hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
f0ccd79e3db4918b74503a10fb2db3f146119a8f
1,886
package com.anthonycaliendo.instagramphotoviewer.model.dao; import android.os.Looper; import android.test.AndroidTestCase; import com.anthonycaliendo.instagramphotoviewer.model.Photo; import com.loopj.android.http.AsyncHttpClient; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; public class InstagramClientIntegrationTest extends AndroidTestCase { public void testFetchPopularPhotos_LoadsDataFromInstagram() throws Exception { final InstagramClient client = new InstagramClient(new AsyncHttpClient()); final RecordingResponseHandler responseHandler = new RecordingResponseHandler(); final ExecutorService executor = Executors.newFixedThreadPool(2); final Future<List<Photo>> instagramCallFuture = executor.submit(new Callable<List<Photo>>() { @Override public List<Photo> call() throws Exception { Looper.prepare(); client.fetchPopularPhotos(responseHandler); while (responseHandler.photos == null) { // block until we get photos } return responseHandler.photos; } }); // give the test 10 seconds to load the data final List<Photo> photos = instagramCallFuture.get(10, TimeUnit.SECONDS); assertFalse("should have photos", photos.isEmpty()); // all photos should have at least a username and posting timestamp. everything else is non-deterministic should we shouldn't assert against assertNotNull("should have a poster username", photos.get(0).getPosterUsername()); assertNotNull("should have a posted at", photos.get(0).getPostedAt()); } }
43.860465
148
0.697773
0ac0354fbba65b31b888ccedc8b7f719a9668b49
6,085
package com.spacetimecat.build.java; import org.apache.maven.model.*; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Properties; import java.util.function.Consumer; import java.util.stream.Collectors; public final class Project implements HasGav { private final List<HasGav> dependencies = new ArrayList<>(); private final List<Gav> plugins = new ArrayList<>(); private final List<Project> children = new ArrayList<>(); private final String path; private final Project parent; private String groupId = "groupId"; private String artifactId = "artifactId"; private String version = "0.0.0-SNAPSHOT"; private String packaging = "jar"; private String minMavenVersion; /** * @param path * path relative to the path of the parent project * (not necessarily the root project) */ public Project (String path) { this(null, path); } private Project (Project parent, String path) { this.parent = parent; this.path = path; } public Project with (Consumer<Project> conf) { conf.accept(this); return this; } private Gav gav () { return new Gav(groupId, artifactId, version); } public String packaging () { return packaging; } public Project packaging (String s) { packaging = s; return this; } public String path () { return path; } private boolean pathIs (String s) { return Paths.get(path).equals(Paths.get(s)); } public String group () { return groupId; } public Project group (String s) { groupId = s; return this; } @Override public String getGroupId () { return groupId; } public String artifact () { return artifactId; } public Project artifact (String s) { artifactId = s; return this; } @Override public String getArtifactId () { return artifactId; } public String version () { return version; } public Project version (String s) { version = s; return this; } @Override public String getVersion () { return version; } public Project dependOn (Gav gav) { dependencies.add(gav); return this; } public Project dependOn (String gav) { return dependOn(Gav.parse(gav)); } public Project dependOn (Project p) { dependencies.add(p); return this; } public Project plugin (Gav gav) { plugins.add(gav); return this; } public Project plugin (String gav) { return plugin(Gav.parse(gav)); } public Project minMavenVersion (String v) { minMavenVersion = v; return this; } public Project getChild (String path) { return ensureChild(path); } public Project child (String path) { return child(path, c -> {}); } public Project child (String path, Consumer<Project> configure) { final Project child = ensureChild(path); configure.accept(child); return this; } private Project ensureChild (String path) { return children.stream() .filter(p -> p.pathIs(path)) .findAny() .orElseGet(() -> createChild(path)); } private Project createChild (String path) { final Path name = Paths.get(path).getFileName(); if (name == null) { throw new IllegalArgumentException(path); } final Project child = new Project(this, path) .group(groupId) .artifact(name.toString()) .version(version) ; children.add(child); return child; } List<Project> children () { return children; } Model mavenModel () { final Model m = new Model(); m.setModelVersion("4.0.0"); final Properties properties = new Properties(); final String javaVersion = "1.8"; properties.put("maven.compiler.source", javaVersion); properties.put("maven.compiler.target", javaVersion); m.setProperties(properties); final List<Plugin> mavenPlugins = plugins.stream().map(Project::createPlugin).collect(Collectors.toList()); if (!mavenPlugins.isEmpty()) { final Build build = new Build(); PluginManagement pluginManagement = new PluginManagement(); pluginManagement.setPlugins(mavenPlugins); build.setPluginManagement(pluginManagement); m.setBuild(build); } if (parent != null) { final Parent p = new Parent(); p.setGroupId(parent.group()); p.setArtifactId(parent.artifact()); p.setVersion(parent.version()); m.setParent(p); } if (minMavenVersion != null) { final Prerequisites p = new Prerequisites(); p.setMaven(minMavenVersion); m.setPrerequisites(p); } final String effectivePackaging = children.isEmpty() ? packaging : "pom"; final List<Project> children = new ArrayList<>(this.children); children.sort(Comparator.comparing(Project::path)); children.forEach(c -> m.addModule(c.path())); m.setPackaging(effectivePackaging); m.setGroupId(groupId); m.setArtifactId(artifactId); m.setVersion(version); for (HasGav gav : dependencies) { m.addDependency(dependency(gav)); } return m; } private static Plugin createPlugin (Gav gav) { final Plugin p = new Plugin(); p.setGroupId(gav.getGroupId()); p.setArtifactId(gav.getArtifactId()); p.setVersion(gav.getVersion()); return p; } private static Dependency dependency (HasGav gav) { final Dependency d = new Dependency(); d.setGroupId(gav.getGroupId()); d.setArtifactId(gav.getArtifactId()); d.setVersion(gav.getVersion()); return d; } private static Dependency dependency (String strGav) { return dependency(Gav.parse(strGav)); } }
28.97619
115
0.61479
41d4b1e2e03cbdd4d81c80398e211589d774d8b0
1,447
// This file is auto-generated, don't edit it. Thanks. package com.antgroup.antchain.openapi.deps.models; import com.aliyun.tea.*; public class QueryCellRequest extends TeaModel { @NameInMap("auth_token") public String authToken; @NameInMap("tenant") public String tenant; // 目标工作空间名称 @NameInMap("workspace") public String workspace; // 目标环境名称 @NameInMap("workspace_group") public String workspaceGroup; public static QueryCellRequest build(java.util.Map<String, ?> map) throws Exception { QueryCellRequest self = new QueryCellRequest(); return TeaModel.build(map, self); } public QueryCellRequest setAuthToken(String authToken) { this.authToken = authToken; return this; } public String getAuthToken() { return this.authToken; } public QueryCellRequest setTenant(String tenant) { this.tenant = tenant; return this; } public String getTenant() { return this.tenant; } public QueryCellRequest setWorkspace(String workspace) { this.workspace = workspace; return this; } public String getWorkspace() { return this.workspace; } public QueryCellRequest setWorkspaceGroup(String workspaceGroup) { this.workspaceGroup = workspaceGroup; return this; } public String getWorkspaceGroup() { return this.workspaceGroup; } }
24.525424
89
0.662751
87a9d6398edd490844b25ca418008155f7e65a0e
576
package juice.exceptions; /** * @author Ricky Fung */ public class SerializationException extends NestedRuntimeException { /** * Constructs a new {@link SerializationException} instance. * * @param msg */ public SerializationException(String msg) { super(msg); } /** * Constructs a new {@link SerializationException} instance. * * @param msg the detail message. * @param cause the nested exception. */ public SerializationException(String msg, Throwable cause) { super(msg, cause); } }
21.333333
68
0.631944
318825c531db991822b0cac1efaf32ecb3a058ea
16,054
/* * Copyright 2018-2021, ranke (213539@qq.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package top.klw8.alita.ftp; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.net.ftp.*; import org.springframework.util.Assert; /** * FTP客户端工具 * 2020/6/4 16:00 */ @Slf4j public class FtpClient { /**(213539 @ qq.com) * 字符集编码 */ private String charSet = "UTF-8"; /**(213539 @ qq.com) * 远端文件编码 */ private String remoteCharSet = "iso-8859-1"; /**(213539 @ qq.com) * 字节数组长度 */ private int byteSize = 1024; /**(213539 @ qq.com) * 缓冲区大小 */ public static final int IO_BUFFERED = 1024; /**(213539 @ qq.com) * 路径中的分隔符 / */ private String separated = "/"; /**(213539 @ qq.com) * FTP服务端IP */ private String host; /**(213539 @ qq.com) * FTP服务端端口 */ private int port; /**(213539 @ qq.com) * FTP服务端用户名 */ private String username; /**(213539 @ qq.com) * FTP服务端用户密码 */ private String password; /**(213539 @ qq.com) * 连接FTP服务端时使用的代理IP */ private String proxyHost; /**(213539 @ qq.com) * 连接FTP服务端时使用的代理端口 */ private int porxyPort; /** * @return void * 设置客户端字符编码 * 2020/6/5 16:15 * @param: charSet */ public void setCharSet(String charSet) { this.charSet = charSet; } /** * @return java.lang.String * 获取客户端字符编码 * 2020/6/5 16:15 * @param: */ public String getCharSet() { return charSet; } /** * @return void * 设置FTP服务端字符编码 * 2020/6/5 16:15 * @param: serverCharSet */ public void setServerCharSet(String serverCharSet) { this.remoteCharSet = serverCharSet; } /** * @return java.lang.String * 获取FTP服务端字符编码 * 2020/6/5 16:16 * @param: */ public String getServerCharSet() { return this.remoteCharSet; } /** * @return top.klw8.alita.ftp.FtpClient * 连接并获得一个ftp客户端 * 2020/6/5 9:15 * @param: host * @param: port * @param: username * @param: password */ public static FtpClient creatClient(String host, String port, String username, String password) { Assert.hasText(host, "host不能为空"); Assert.hasText(port, "port不能为空"); Assert.hasText(username, "username不能为空"); Assert.hasText(password, "password不能为空"); return new FtpClient(host, port, username, password); } /** * @param host 主机名 * @param port 端口 * @param username 用户名 * @param password 密码 * 无参构造 * 2020/6/5 9:20 */ private FtpClient(String host, String port, String username, String password) { this.host = host; this.port = Integer.valueOf(port); this.username = username; this.password = password; } /** * @return void * 设置代理 * 2020/6/5 16:12 * @param: proxyHost * @param: porxyPort */ public void useProxy(String proxyHost, String porxyPort) { this.proxyHost = proxyHost; this.porxyPort = Integer.valueOf(porxyPort); } /** * @return org.apache.commons.net.ftp.FTPClient * 初始化一个Apache FtpClient 并创建连接 * 2020/6/5 16:16 * @param: */ private FTPClient initApacheFtpClient() { FTPClient client; try { // 判断是否有代理数据 实例化FTP客户端 if (!StringUtils.isEmpty(proxyHost) && porxyPort > 0) { // 实例化有代理的FTP客户端 client = new FTPHTTPClient(proxyHost, porxyPort); } else { // 实例化FTP客户端 client = new FTPClient(); } client.connect(host, port); client.setControlEncoding(this.charSet); if (FTPReply.isPositiveCompletion(client.getReplyCode()) && client.login(username, password)) { // 设置被动模式 client.enterLocalPassiveMode(); return client; } disconnect(client); return null; } catch (IOException e) { log.error("FTPClient初始化错误!", e); return null; } } /** * @return void * 断开与远程服务器的连接 * 2020/6/5 9:53 * @param: */ private void disconnect(FTPClient client) throws IOException { if (client.isConnected()) { client.disconnect(); } } /**(213539 @ qq.com) * 上传文件到FTP服务器,支持断点续传 * 2020/6/5 9:53 * @param: local 本地文件名称/绝对路径 * @param: remote 远程文件路径 * @return 上传是否成功 */ public boolean upload(String local, String remote) throws IOException { FTPClient ftpClient = this.initApacheFtpClient(); // 设置以二进制流的方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); ftpClient.setControlEncoding(this.charSet); // 对远程目录的处理 String remoteFileName = remote; if (remote.contains(this.separated)) { remoteFileName = remote.substring(remote.lastIndexOf(this.separated) + 1); // 服务器中创建目录,创建失败直接返回 if (!this.createDirecroty(remote, ftpClient)) { this.log.info("服务器中创建目录失败"); return false; } } // 返回状态 boolean result; // 检查远程是否存在文件 FTPFile[] files = ftpClient .listFiles(new String(remoteFileName.getBytes(this.charSet), this.remoteCharSet)); if (files.length == 1) { long remoteSize = files[0].getSize(); File f = new File(local); long localSize = f.length(); if (remoteSize >= localSize) { this.log.info("远端文件大于等于本地文件大小,无需上传,终止上传"); result = true; } else { // 尝试移动文件内读取指针,实现断点续传 result = uploadFile(remoteFileName, f, ftpClient, remoteSize); if(!result) { // 如果断点续传没有成功,则删除服务器上文件,重新上传 result = this.reUploadFile(ftpClient, remoteFileName, f); } } } else { result = uploadFile(remoteFileName, new File(local), ftpClient, 0); } this.disconnect(ftpClient); return result; } /** * @return java.lang.String * 如果断点续传没有成功,则删除服务器上文件,重新上传 * 2020/6/5 9:56 * @param: result * @param: remoteFileName * @param: f */ private boolean reUploadFile(FTPClient ftpClient, String remoteFileName, File f) throws IOException { boolean rs = false; if (!ftpClient.deleteFile(remoteFileName)) { this.log.info("删除远端文件失败"); return rs; } rs = uploadFile(remoteFileName, f, ftpClient, 0); return rs; } /** * @param remote 远程文件路径 * @param local 本地文件路径 * @return 下载是否成功 * 从FTP服务器上下载文件, 支持断点续传,下载百分比汇报 * 2020/6/5 9:56 */ public boolean download(String remote, String local) throws IOException { FTPClient ftpClient = this.initApacheFtpClient(); // 设置以二进制方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 返回状态 boolean result; // 检查远程文件是否存在 FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes(this.charSet), this.remoteCharSet)); if (files.length != 1) { this.log.info("远程文件不存在"); result = false; } else { result = this.download(ftpClient, files, local, remote); } this.disconnect(ftpClient); return result; } /** * @param files 文件列表 * @param local 本地路径 * @param remote 远程路径 * @return 结果 * 下载文件 * 2020/6/5 9:56 */ private boolean download(FTPClient ftpClient, FTPFile[] files, String local, String remote) throws IOException { boolean result; // 获得远程文件的大小 long lRemoteSize = files[0].getSize(); // 获得本地文件对象(不存在,则创建) File f = new File(local); // 本地存在文件,进行断点下载 if (f.exists()) { // 获得本地文件的长度 long localSize = f.length(); // 判断本地文件大小是否大于远程文件大小 if (localSize >= lRemoteSize) { this.log.info("本地文件大于等于远程文件,无需下载,下载中止"); result = false; } else { result = this.downloaddd(ftpClient, localSize, f, remote, lRemoteSize); } } else { result = this.downloadCreate(ftpClient, f, remote, lRemoteSize); } return result; } /** * @param localSize 文件尺寸 * @param f 文件 * @param remote 远程目录 * @param lRemoteSize 远程文件尺寸 * @return 结果 * 下载 * 2020/6/5 9:57 */ private boolean downloaddd(FTPClient ftpClient, long localSize, File f, String remote, long lRemoteSize) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { // 设置开始点 ftpClient.setRestartOffset(localSize); // 获得流(进行断点续传,并记录状态) bos = new BufferedOutputStream(new FileOutputStream(f, true)); bis = new BufferedInputStream( ftpClient.retrieveFileStream(new String(remote.getBytes(this.charSet), this.remoteCharSet))); // 字节流 byte[] bytes; bytes = new byte[this.byteSize]; // 开始下载 int c; while ((c = bis.read(bytes)) != -1) { bos.write(bytes, 0, c); } } catch (Exception ex){ log.error("FTP文件下载出现错误", ex); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.flush(); bos.close(); } ftpClient.completePendingCommand(); } return true; } /** * @param f 文件 * @param remote 远程路径 * @param lRemoteSize 远程文件尺寸 * @return 结果 * 下载 * 2020/6/5 9:57 */ private boolean downloadCreate(FTPClient ftpClient, File f, String remote, long lRemoteSize) throws IOException { BufferedInputStream bis = null; BufferedOutputStream bos = null; try { // 获得流 bos = new BufferedOutputStream(new FileOutputStream(f)); bis = new BufferedInputStream( ftpClient.retrieveFileStream(new String(remote.getBytes(this.charSet), this.remoteCharSet))); // 开始下载 int c; byte[] bytes; bytes = new byte[this.byteSize]; while ((c = bis.read(bytes)) != -1) { bos.write(bytes, 0, c); } } catch (Exception ex){ log.error("FTP文件下载出现错误", ex); } finally { if (bis != null) { bis.close(); } if (bos != null) { bos.flush(); bos.close(); } ftpClient.completePendingCommand(); } return true; } /** * @return org.apache.commons.net.ftp.FTPFile[] * 返回远程文件列表 * 2020/6/5 9:58 * @param: remotePath */ public FTPFile[] getremoteFiles(String remotePath) throws IOException { FTPClient ftpClient = this.initApacheFtpClient(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // 设置以二进制方式传输 FTPFile[] result = ftpClient.listFiles(remotePath); this.disconnect(ftpClient); return result; } /** * @return boolean * 删除ftp上的文件 * 2020/6/5 9:58 * @param: remotePath */ public boolean removeFile(String remotePath) throws IOException { boolean flag = false; FTPClient ftpClient = this.initApacheFtpClient(); if (ftpClient != null) { // 设置以二进制方式传输 ftpClient.setFileType(FTP.BINARY_FILE_TYPE); flag = ftpClient.deleteFile(new String(remotePath.getBytes(this.charSet), this.remoteCharSet)); } this.disconnect(ftpClient); return flag; } /** * @param remoteFile 远程文件名,在上传之前已经将服务器工作目录做了改变 * @param localFile 本地文件File句柄,绝对路径 * @param fc FTPClient引用 * @return 上传是否成功 * 上传文件到服务器, 新上传和断点续传 * 2020/6/5 9:59 */ private boolean uploadFile(String remoteFile, File localFile, FTPClient fc, long remoteSize) throws IOException { RandomAccessFile raf = null; BufferedOutputStream bos = null; try { raf = new RandomAccessFile(localFile, "r"); bos = new BufferedOutputStream( fc.appendFileStream(new String(remoteFile.getBytes(this.charSet), this.remoteCharSet)), IO_BUFFERED); // 断点续传 if (remoteSize > 0) { fc.setRestartOffset(remoteSize); raf.seek(remoteSize); } // 开始上传 byte[] bytes; bytes = new byte[this.byteSize]; int c; while (-1 != (c = raf.read(bytes))) { bos.write(bytes, 0, c); } } catch (Exception ex){ log.error("FTP文件上传时发生错误: ", ex); return false; } finally { if (bos != null) { bos.flush(); bos.close(); } if (raf != null) { raf.close(); } fc.completePendingCommand(); } return true; } /** * @param remote 远程服务器文件绝对路径 * @param fc FTPClient对象 * @return 目录创建是否成功 * 递归创建远程服务器目录 * 2020/6/5 9:59 */ private boolean createDirecroty(String remote, FTPClient fc) throws IOException { boolean status = true; String directory = remote.substring(0, remote.lastIndexOf(this.separated) + 1); if (!this.separated.equalsIgnoreCase(directory) && !fc.changeWorkingDirectory(new String(directory.getBytes(this.charSet), this.remoteCharSet))) { // 如果远程目录不存在,则递归创建远程服务器目录 status = this.createDirecroty(directory, fc, remote); } return status; } /** * @return java.lang.String * 创建目录 * 2020/6/5 10:00 * @param: directory * @param: fc * @param: remote */ private boolean createDirecroty(String directory, FTPClient fc, String remote) throws IOException { int start = 0; int end; if (directory.startsWith(this.separated)) { start = 1; } end = directory.indexOf(this.separated, start); while (true) { String subDirectory = new String(remote.substring(start, end).getBytes(this.charSet), this.remoteCharSet); if (!fc.changeWorkingDirectory(subDirectory)) { if (fc.makeDirectory(subDirectory)) { fc.changeWorkingDirectory(subDirectory); } else { this.log.info("创建目录失败"); return false; } } start = end + 1; end = directory.indexOf(this.separated, start); // 检查所有目录是否创建完毕 if (end <= start) { break; } } return true; } }
27.584192
129
0.544537
3eb480aa2efd737b9df2a5ae0391705e2bc5856e
151
package custom; public class AClass { public AClass returnA() {} public void paramA(AClass a) {} @AAnnotation public void annoA() {} }
18.875
35
0.649007
1f41f6d7406f6a556f686f30b4c54d3d7a19335c
4,427
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sis.storage.netcdf; import java.io.IOException; import org.opengis.metadata.Metadata; import org.apache.sis.util.Debug; import org.apache.sis.util.ArgumentChecks; import org.apache.sis.storage.DataStore; import org.apache.sis.storage.DataStoreException; import org.apache.sis.storage.StorageConnector; import org.apache.sis.internal.netcdf.Decoder; import org.apache.sis.metadata.ModifiableMetadata; /** * A data store backed by NetCDF files. * Instances of this data store are created by {@link NetcdfStoreProvider#open(StorageConnector)}. * * @author Martin Desruisseaux (Geomatys) * @since 0.3 * @version 0.3 * @module * * @see NetcdfStoreProvider */ public class NetcdfStore extends DataStore { /** * The object to use for decoding the NetCDF file content. There is two different implementations, * depending on whether we are using the embedded SIS decoder or a wrapper around the UCAR library. */ private final Decoder decoder; /** * The object returned by {@link #getMetadata()}, created when first needed and cached. */ private Metadata metadata; /** * Creates a new NetCDF store from the given file, URL, stream or {@link ucar.nc2.NetcdfFile} object. * This constructor invokes {@link StorageConnector#closeAllExcept(Object)}, keeping open only the * needed resource. * * @param storage Information about the storage (URL, stream, {@link ucar.nc2.NetcdfFile} instance, <i>etc</i>). * @throws DataStoreException If an error occurred while opening the NetCDF file. */ public NetcdfStore(final StorageConnector storage) throws DataStoreException { ArgumentChecks.ensureNonNull("storage", storage); try { decoder = NetcdfStoreProvider.decoder(listeners, storage); } catch (IOException e) { throw new DataStoreException(e); } } /** * Returns information about the dataset as a whole. The returned metadata object can contain information * such as the spatiotemporal extent of the dataset, contact information about the creator or distributor, * data quality, usage constraints and more. * * @return Information about the dataset. * @throws DataStoreException If an error occurred while reading the data. */ @Override public Metadata getMetadata() throws DataStoreException { if (metadata == null) try { final MetadataReader reader = new MetadataReader(decoder); metadata = reader.read(); if (metadata instanceof ModifiableMetadata) { ((ModifiableMetadata) metadata).freeze(); } } catch (IOException e) { throw new DataStoreException(e); } return metadata; } /** * Closes this NetCDF store and releases any underlying resources. * * @throws DataStoreException If an error occurred while closing the NetCDF file. */ @Override public void close() throws DataStoreException { metadata = null; try { decoder.close(); } catch (IOException e) { throw new DataStoreException(e); } } /** * Returns a string representation of this NetCDF store for debugging purpose. * The content of the string returned by this method may change in any future SIS version. * * @return A string representation of this datastore for debugging purpose. */ @Debug @Override public String toString() { return getClass().getSimpleName() + '[' + decoder + ']'; } }
37.201681
117
0.687825
f112f507f9045334205d5b18657629f0a233dbe5
2,746
package ghost.framework.web.socket.plugin.server; import ghost.framework.context.module.IModule; import ghost.framework.web.context.servlet.ServletContextHeader; import javax.servlet.http.HttpSession; import javax.websocket.Extension; import javax.websocket.HandshakeResponse; import javax.websocket.server.HandshakeRequest; import javax.websocket.server.ServerEndpointConfig; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * package: ghost.framework.web.socket.plugin.server * * @Author: 郭树灿{guo-w541} * @link: 手机:13715848993, QQ 27048384 * @Description:默认ServerEndpoint配置类 * @Date: 2020/5/2:18:23 */ public final class DefaultServerEndpointConfigurator extends ServerEndpointConfig.Configurator { private IModule module; @Override public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) { //获取web所在模块 this.module = (IModule) ServletContextHeader.getServletContext().getAttribute(IModule.class.getName()); if (request.getHttpSession() != null) { // HttpSession httpSession = (HttpSession) request.getHttpSession(); config.getUserProperties().put(HttpSession.class.getName(), request.getHttpSession()); } } /** * 获取构建类型实例 * @param clazz * @param <T> * @return * @throws InstantiationException */ @Override public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException { try { //使用模块Bean构建类型对象 return module.addBean(clazz); } catch (Exception e) { throw new InstantiationException(e.getMessage()); } } @Override public String getNegotiatedSubprotocol(List<String> supported, List<String> requested) { for (String request : requested) { if (supported.contains(request)) { return request; } } return ""; } @Override public List<Extension> getNegotiatedExtensions(List<Extension> installed, List<Extension> requested) { Set<String> installedNames = new HashSet<>(); for (Extension e : installed) { installedNames.add(e.getName()); } List<Extension> result = new ArrayList<>(); for (Extension request : requested) { if (installedNames.contains(request.getName())) { result.add(request); } } return result; } @Override public boolean checkOrigin(String originHeaderValue) { return true; } }
31.930233
111
0.633285
df7a3b1b91bf751cdbb8895d5fbb458ae9a83f89
2,602
package epi.graph; import java.util.*; //Clone a connected directed cyclic graph public class CloneDirectedGraph { private static class GNode{ char value; List<GNode> adj = new LinkedList<GNode>(); public GNode(char value){ this.value = value; } } static Set<GNode> visited = new HashSet<GNode>(); public static void main(String[] args){ /* Graph 1: a <-d | \ > > > | b -> c -> e */ GNode a = new GNode('a'); GNode b = new GNode('b'); GNode c = new GNode('c'); GNode d = new GNode('d'); GNode e = new GNode('e'); a.adj.add(b); a.adj.add(c); b.adj.add(c); c.adj.add(d); d.adj.add(a); c.adj.add(e); printBFS(a); GNode clone = cloneGraph(a); printBFS(clone); /* Output: a @ 1627674070 b @ 1360875712 c @ 1625635731 d @ 1580066828 e @ 491044090 a @ 644117698 b @ 1872034366 c @ 1581781576 d @ 1725154839 e @ 1670675563 */ } static GNode cloneGraph(GNode src){ Queue<GNode> bfs = new LinkedList<>(); Map<GNode, GNode> gToClone = new HashMap<>(); GNode clnSrc = new GNode (src.value); bfs.add(src); gToClone.put(src, clnSrc); while (! bfs.isEmpty()){ GNode cur = bfs.remove(); if(visited.contains(cur)){ continue; } visited.add(cur); for(GNode adj: cur.adj){ GNode clonedCur = gToClone.get(cur); GNode cloneAdj = null; if(gToClone.containsKey(adj)){ cloneAdj = gToClone.get(adj); }else{ cloneAdj = new GNode(adj.value); gToClone.put(adj, cloneAdj); } clonedCur.adj.add(cloneAdj);//added a cloned adj to the cloned graph bfs.add(adj); } } return clnSrc; } static void printBFS(GNode node){ Set<GNode> visited = new HashSet<GNode>(); Queue<GNode> bfs = new LinkedList<>(); bfs.add(node); visited.add(node); while (!bfs.isEmpty()){ GNode cur = bfs.remove(); System.out.print(cur.value +" @ "+cur.hashCode()+" "); for(GNode adj: cur.adj){ if(! visited.contains(adj)){ bfs.add(adj); visited.add(adj); } } } System.out.println(); } }
23.87156
84
0.476556
1c76f14be98df2ba2b450b7beaf8ad185cebd736
1,830
package mcjty.immcraft.blocks.furnace; import mcjty.immcraft.api.handles.DefaultInterfaceHandle; import net.minecraft.entity.item.EntityXPOrb; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.FurnaceRecipes; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.math.MathHelper; import net.minecraftforge.fml.common.FMLCommonHandler; public class FurnaceOutputInteractionHandler extends DefaultInterfaceHandle { public FurnaceOutputInteractionHandler(String selectorID) { super(selectorID); } @Override public ItemStack extractOutput(TileEntity genericTE, EntityPlayer player, int amount) { ItemStack stack = super.extractOutput(genericTE, player, amount); spawnExperience(player, stack); FMLCommonHandler.instance().firePlayerSmeltedEvent(player, stack); return stack; } public void spawnExperience(EntityPlayer player, ItemStack stack) { if (!player.world.isRemote) { int i = stack.getCount(); float f = FurnaceRecipes.instance().getSmeltingExperience(stack); if (f == 0.0F) { i = 0; } else if (f < 1.0F) { int j = MathHelper.floor((float) i * f); if (j < MathHelper.ceil((float) i * f) && Math.random() < (double) ((float) i * f - (float) j)) { ++j; } i = j; } while (i > 0) { int k = EntityXPOrb.getXPSplit(i); i -= k; player.world.spawnEntity(new EntityXPOrb(player.world, player.posX, player.posY + 0.5D, player.posZ + 0.5D, k)); } } } @Override public boolean isOutput() { return true; } }
33.272727
128
0.621311
26a1f1addb32dff7413ad5c01753ea0f5bf58032
2,399
package com.udacity.jdnd.course3.critter.controller; import com.udacity.jdnd.course3.critter.dto.PetDTO; import com.udacity.jdnd.course3.critter.entity.Customer; import com.udacity.jdnd.course3.critter.entity.Pet; import com.udacity.jdnd.course3.critter.service.PetService; import com.udacity.jdnd.course3.critter.service.UserService; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * Handles web requests related to Pets. */ @RestController @RequestMapping("/pet") public class PetController { private PetService petService; private UserService userService; @Autowired public PetController(PetService petService, UserService userService){ this.petService = petService; this.userService = userService; } @PostMapping public PetDTO savePet(@RequestBody PetDTO petDTO) { Customer customer = userService.getCustomerById(petDTO.getOwnerId()); Pet pet = convertDTO2Pet(petDTO); return convertPet2DTO(petService.savePet(pet, customer)); } @GetMapping("/{petId}") public PetDTO getPet(@PathVariable long petId) { return convertPet2DTO(petService.getPet(petId)); } @GetMapping public List<PetDTO> getPets(){ List<PetDTO> petsDTO = new ArrayList<>(); List<Pet> pets = petService.getAllPets(); for(Pet pet : pets){ PetDTO petDTO = convertPet2DTO(pet); petsDTO.add(petDTO); } return petsDTO; } @GetMapping("/owner/{ownerId}") public List<PetDTO> getPetsByOwner(@PathVariable long ownerId) { List<PetDTO> petsDTO = new ArrayList<>(); List<Pet> pets = petService.getAllPetsByOwner(ownerId); for(Pet pet : pets){ PetDTO petDTO = convertPet2DTO(pet); petsDTO.add(petDTO); } return petsDTO; } private Pet convertDTO2Pet(PetDTO petDTO) { Pet pet = new Pet(); BeanUtils.copyProperties(petDTO, pet); return pet; } private PetDTO convertPet2DTO(Pet pet) { PetDTO petDTO = new PetDTO(); BeanUtils.copyProperties(pet, petDTO); petDTO.setOwnerId(pet.getOwner().getId()); return petDTO; } }
29.256098
77
0.680283
5565537535bf3945eef41c562387011c8bcb43a7
12,700
/* * This file is part of Latch, licensed under the MIT License. * * Copyright (c) 2016-2018 IchorPowered <https://github.com/IchorPowered> * Copyright (c) Contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.meronat.latch; import com.google.common.collect.ImmutableSet; import com.google.common.reflect.TypeToken; import com.meronat.latch.enums.LockType; import ninja.leaping.configurate.commented.CommentedConfigurationNode; import ninja.leaping.configurate.loader.ConfigurationLoader; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.block.BlockTypes; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Configuration { private CommentedConfigurationNode rootNode; private final ConfigurationLoader<CommentedConfigurationNode> configManager; public Configuration(ConfigurationLoader<CommentedConfigurationNode> configManager) { this.configManager = configManager; try { this.rootNode = configManager.load(); } catch (IOException e) { Latch.getLogger().error("Unable to load configuration, starting with a default one."); this.rootNode = configManager.createEmptyNode(); } loadDefaults(); saveConfig(); } private void loadDefaults() { //Should we add latch.normal to default permissions? if (this.rootNode.getNode("add_default_permissions").isVirtual()) { this.rootNode.getNode("add_default_permissions").setValue(false); } //Blocks we're able to lock if (this.rootNode.getNode("lockable_blocks").isVirtual()) { final List<String> lockableBlocks = new ArrayList<>(); lockableBlocks.add(BlockTypes.CHEST.getId()); lockableBlocks.add(BlockTypes.TRAPPED_CHEST.getId()); lockableBlocks.add(BlockTypes.BLACK_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.BLUE_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.BROWN_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.CYAN_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.GRAY_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.GREEN_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.LIGHT_BLUE_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.LIME_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.MAGENTA_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.ORANGE_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.PINK_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.PURPLE_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.RED_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.SILVER_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.WHITE_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.YELLOW_SHULKER_BOX.getId()); lockableBlocks.add(BlockTypes.BREWING_STAND.getId()); lockableBlocks.add(BlockTypes.JUKEBOX.getId()); lockableBlocks.add(BlockTypes.FURNACE.getId()); lockableBlocks.add(BlockTypes.LIT_FURNACE.getId()); lockableBlocks.add(BlockTypes.HOPPER.getId()); lockableBlocks.add(BlockTypes.DISPENSER.getId()); lockableBlocks.add(BlockTypes.DROPPER.getId()); // Fix issue with doors, possibly from MalisisDoors, look into it more later and revisit in 1.13 Sponge.getRegistry().getType(BlockType.class, "minecraft:fence_gate").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:spruce_fence_gate").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:birch_fence_gate").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:jungle_fence_gate").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:dark_oak_fence_gate").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:acacia_fence_gate").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:wooden_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:spruce_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:birch_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:jungle_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:acacia_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:dark_oak_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:iron_door").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:trapdoor").ifPresent(t -> lockableBlocks.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:iron_trapdoor").ifPresent(t -> lockableBlocks.add(t.getId())); this.rootNode.getNode("lockable_blocks").setValue(lockableBlocks); } //Should we protect locks from explosions? if (this.rootNode.getNode("protect_from_explosives").isVirtual()) { this.rootNode.getNode("protect_from_explosives").setValue(true); } //Blocks we should prevent being placed next to locks the player doesn't own if (this.rootNode.getNode("prevent_adjacent_to_locks").isVirtual()) { final List<String> preventAdjacent = new ArrayList<>(); preventAdjacent.add(BlockTypes.HOPPER.getId()); this.rootNode.getNode("prevent_adjacent_to_locks").setValue(preventAdjacent); } //Blocks that rely on a block under them to stay intact if (this.rootNode.getNode("protect_below_block").isVirtual()) { final List<String> protectBelowBlock = new ArrayList<>(); Sponge.getRegistry().getType(BlockType.class, "minecraft:wooden_door").ifPresent(t -> protectBelowBlock.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:spruce_door").ifPresent(t -> protectBelowBlock.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:birch_door").ifPresent(t -> protectBelowBlock.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:jungle_door").ifPresent(t -> protectBelowBlock.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:acacia_door").ifPresent(t -> protectBelowBlock.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:dark_oak_door").ifPresent(t -> protectBelowBlock.add(t.getId())); Sponge.getRegistry().getType(BlockType.class, "minecraft:iron_door").ifPresent(t -> protectBelowBlock.add(t.getId())); this.rootNode.getNode("protect_below_block").setValue(protectBelowBlock); } //Lock limit per enum if (this.rootNode.getNode("lock_limit").isVirtual()) { final HashMap<String, Integer> limits = new HashMap<>(); limits.put("total", 64); for (LockType type : LockType.values()) { limits.put(type.toString().toLowerCase(), 12); } limits.put(LockType.PRIVATE.toString().toLowerCase(), 24); try { this.rootNode.getNode("lock_limit").setValue(new TypeToken<Map<String, Integer>>() {}, limits); } catch (ObjectMappingException e) { this.rootNode.getNode("lock_limit").setValue(limits); e.printStackTrace(); } } //Do we allow redstone protection? if (this.rootNode.getNode("protect_from_redstone").isVirtual()) { this.rootNode.getNode("protect_from_redstone").setValue(false); } if (this.rootNode.getNode("auto_lock_on_placement").isVirtual()) { this.rootNode.getNode("auto_lock_on_placement").setValue(false); } if (this.rootNode.getNode("remove_bypass_on_logout").isVirtual()) { this.rootNode.getNode("remove_bypass_on_logout").setValue(true); } if (this.rootNode.getNode("clean_old_locks").isVirtual()) { this.rootNode.getNode("clean_old_locks").setValue(false); } if (this.rootNode.getNode("clean_old_locks_interval").isVirtual()) { this.rootNode.getNode("clean_old_locks_interval").setValue(4); } if (this.rootNode.getNode("clean_locks_older_than").isVirtual()) { this.rootNode.getNode("clean_locks_older_than").setValue(40); } if (this.rootNode.getNode("allow_opening_locked_iron").isVirtual()) { this.rootNode.getNode("allow_opening_locked_iron").setComment("Allows opening locked iron doors and trapdoors by right clicking."); this.rootNode.getNode("allow_opening_locked_iron").setValue(true); } } public boolean allowOpeningLockedIron() { return this.rootNode.getNode("allow_opening_locked_iron").getBoolean(false); } /* public boolean addLockableBlock(BlockType blockType) { final CommentedConfigurationNode node = this.rootNode.getNode("lockable_blocks"); try { node.setValue(node.getList(TypeToken.of(String.class)).add(blockType.getId())); saveConfig(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } public boolean removeLockableBlock(BlockType blockType) { final CommentedConfigurationNode node = this.rootNode.getNode("lockable_blocks"); try { node.setValue(node.getList(TypeToken.of(String.class)).remove(blockType.getId())); saveConfig(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } */ private void saveConfig() { try { this.configManager.save(this.rootNode); } catch (IOException e) { Latch.getLogger().error("There were issues saving the configuration."); } } public void reloadConfig() { try { this.rootNode = configManager.load(); } catch (IOException e) { Latch.getLogger().error("Unable to load configuration, starting with a default one."); this.rootNode = configManager.createEmptyNode(); } this.loadDefaults(); this.saveConfig(); } public CommentedConfigurationNode getRootNode() { return this.rootNode; } public boolean setLockableBlocks(ImmutableSet<String> blockTypes) { final CommentedConfigurationNode node = this.rootNode.getNode("lockable_blocks"); try { node.setValue(blockTypes); saveConfig(); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
48.288973
143
0.674646
14d327de661b1264d82158a15975f10745c06bac
3,369
package flyway.oskari; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import fi.nls.oskari.util.IOHelper; public class V1_46_9__replace_externalids_in_mapful_bglayerselection_plugin_config_test { private static final String RESOURCE_FILE_NAME = "mapfull_sample_config.json"; private static final String SELECTED_LAYERS_SAMPLE = "{\"selectedLayers\":[{\"id\":\"base_35\",\"opacity\":100},{\"id\":99,\"opacity\":100},{\"id\":90,\"opacity\":100},{\"id\":\"myplaces_7509\",\"opacity\":100}],\"zoom\":10,\"east\":659796,\"north\":7025206}"; @Test public void testUpdateConfig() throws JSONException, IOException { JSONObject config = new JSONObject(getConfig()); JSONObject bgPlugin = V1_46_9__replace_externalids_in_mapful_bglayerselection_plugin_config.findBGPlugin(config.getJSONArray("plugins")); JSONArray baseLayers = bgPlugin.getJSONObject("config").getJSONArray("baseLayers"); assertEquals("base_2", baseLayers.getString(0)); assertEquals("24", baseLayers.getString(1)); assertEquals("base_35", baseLayers.getString(2)); Map<String, Integer> externalIdToLayerId = new HashMap<>(); externalIdToLayerId.put("base_2", 13); externalIdToLayerId.put("base_35", 101); boolean updated = V1_46_9__replace_externalids_in_mapful_bglayerselection_plugin_config.updateConfig(config, externalIdToLayerId); assertEquals(true, updated); assertEquals("13", baseLayers.getString(0)); assertEquals("24", baseLayers.getString(1)); assertEquals("101", baseLayers.getString(2)); } private String getConfig() throws IOException { try (InputStream in = V1_46_9__replace_externalids_in_mapful_bglayerselection_plugin_config_test.class.getClassLoader().getResourceAsStream(RESOURCE_FILE_NAME)) { return new String(IOHelper.readBytes(in), StandardCharsets.UTF_8); } } @Test public void testUpdateState() throws JSONException, IOException { JSONObject state = new JSONObject(SELECTED_LAYERS_SAMPLE); JSONArray selectedLayers = state.getJSONArray("selectedLayers"); assertEquals("base_35", selectedLayers.getJSONObject(0).getString("id")); assertEquals(99, selectedLayers.getJSONObject(1).getInt("id")); assertEquals(90, selectedLayers.getJSONObject(2).getInt("id")); assertEquals("myplaces_7509", selectedLayers.getJSONObject(3).getString("id")); Map<String, Integer> externalIdToLayerId = Collections.singletonMap("base_35", 1000); boolean updated = V1_46_9__replace_externalids_in_mapful_bglayerselection_plugin_config.updateState(state, externalIdToLayerId); assertEquals(true, updated); assertEquals(1000, selectedLayers.getJSONObject(0).getInt("id")); assertEquals(99, selectedLayers.getJSONObject(1).getInt("id")); assertEquals(90, selectedLayers.getJSONObject(2).getInt("id")); assertEquals("myplaces_7509", selectedLayers.getJSONObject(3).getString("id")); } }
45.527027
264
0.72336
0927ad30eaa966b08fc9be4e0a1a7abebc7b2e33
1,785
package xyz.neopan.example.graphql; import graphql.execution.instrumentation.Instrumentation; import graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentation; import graphql.execution.instrumentation.dataloader.DataLoaderDispatcherInstrumentationOptions; import lombok.extern.slf4j.Slf4j; import lombok.val; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Import; import xyz.neopan.api.gql.XyzDataLoaderRegistryBuilder; import xyz.neopan.api.gql.XyzGqlContextBuilder; import xyz.neopan.api.iam.XyzIamScalars; import xyz.neopan.api.iam.XyzSubjectStore; /** * @author neo.pan * @since 2020/1/30 */ @Slf4j @Import({XyzIamScalars.class}) public class AppKickstartConfig { @Bean XyzSubjectStore xyzSubjectStore() { log.info("[APP] xyzSubjectStore"); return new XyzSubjectStore.InMemory(); } @Bean XyzDataLoaderRegistryBuilder xyzDataLoaderRegistryBuilder() { log.info("[APP] xyzDataLoaderRegistryBuilder"); return XyzDataLoaderRegistryBuilder.newBuilder(); } @Bean XyzGqlContextBuilder xyzGqlContextBuilder( XyzSubjectStore subjectStore, XyzDataLoaderRegistryBuilder registryBuilder) { log.info("[APP] xyzGqlContextBuilder"); return new XyzGqlContextBuilder(subjectStore, registryBuilder); } @ConditionalOnProperty("xyz.gql.instrumentation") @Bean public Instrumentation instrumentation() { log.info("[APP] instrumentation"); val options = DataLoaderDispatcherInstrumentationOptions .newOptions().includeStatistics(true); return new DataLoaderDispatcherInstrumentation(options); } }
33.679245
95
0.770308
b1edf901574ea1b6b8c8f05d12c16c3166241aed
549
package leetcode.p860; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class Solution860Test { @Test void lemonadeChange() { Solution860 underTest = new Solution860(); Assertions.assertTrue(underTest.lemonadeChange(new int[]{5, 5, 5, 10, 20})); Assertions.assertTrue(underTest.lemonadeChange(new int[]{5, 5, 10})); Assertions.assertFalse(underTest.lemonadeChange(new int[]{10, 10})); Assertions.assertFalse(underTest.lemonadeChange(new int[]{5, 5, 10, 10, 20})); } }
34.3125
86
0.688525
292ebb8094e122ccc467f74d156f997a13ca0c0b
1,639
/* * Copyright © 2017 CHANGLEI. All rights reserved. */ package com.baidaojuhe.library.baidaolibrary.adapter.viewholder; import androidx.annotation.NonNull; import androidx.appcompat.widget.AppCompatTextView; import android.view.ViewGroup; import android.widget.CompoundButton; import com.baidaojuhe.library.baidaolibrary.R; import com.baidaojuhe.library.baidaolibrary.adapter.AnswerAdapter; import com.baidaojuhe.library.baidaolibrary.compat.IViewCompat; import com.baidaojuhe.library.baidaolibrary.entity.Answer; import net.box.app.library.adapter.IArrayAdapter; /** * Created by box on 2018/5/2. * <p> * 到访问卷答案选择 */ public class AnswerViewHolder extends BaseViewHolder { private CompoundButton mRadioButton; private AppCompatTextView mTvName; public AnswerViewHolder(@NonNull ViewGroup parent, boolean isSingleSelection) { super(isSingleSelection ? R.layout.bd_item_radio : R.layout.bd_item_checkbox, parent); mRadioButton = IViewCompat.findById(itemView, R.id.bd_radio_button); mTvName = IViewCompat.findById(itemView, R.id.bd_tv_name); } @Override public void onBindDatas(@NonNull IArrayAdapter adapter, int position) { super.onBindDatas(adapter, position); Answer answer = (Answer) adapter.getItem(position); mTvName.setText(answer.getContent()); if (!(adapter instanceof AnswerAdapter)) { return; } AnswerAdapter answerAdapter = (AnswerAdapter) adapter; mRadioButton.setChecked(answerAdapter.isSelected(answer)); itemView.setOnClickListener(view -> answerAdapter.setSelected(answer)); } }
33.44898
94
0.748017
e38ce6b4cf6a4b487c33b5084e7d19d817b3252e
3,356
/* * (C) Copyright IBM Corp. 2019,2020 * * SPDX-License-Identifier: Apache-2.0 */ package com.ibm.ta.sdk.core.report; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.*; public class IssueReport { private JsonObject issueJO; private String severity = null; private String cost; private String issueOverhead; private String id; private String title; private String occurrencesCount; private String occurrencesCost; private List<String> solutionTextList = new ArrayList<>(); private List<Map<String, String>> occurances = new ArrayList<>(); private Map<String, String> occurrencesFields = new HashMap<>(); private int occurancesCount = 0; // do not need to display, should be used to determine # of rows of occurrences table public IssueReport(JsonObject issueJO){ this.issueJO = issueJO; this.severity = issueJO.get("severity").getAsString(); this.cost = issueJO.get("cost").getAsString(); this.issueOverhead = issueJO.get("issueOverhead").getAsString(); this.id = issueJO.get("id").getAsString(); this.title = issueJO.get("title").getAsString(); this.occurrencesCount = issueJO.get("occurrencesCount").getAsString(); this.occurrencesCost = issueJO.get("occurrencesCost").getAsString(); JsonArray solutionTextJA = issueJO.getAsJsonArray("solutionText"); for (JsonElement solutionTextObj : solutionTextJA){ String solutionText = solutionTextObj.getAsString(); this.solutionTextList.add(solutionText); } JsonObject occurrencesFields = (JsonObject) issueJO.get("occurrencesFields"); Set<String> occurrencesFieldsKeySet = occurrencesFields.keySet(); for (String occurrencesFieldsKey : occurrencesFieldsKeySet){ this.occurrencesFields.put(occurrencesFieldsKey, occurrencesFields.get(occurrencesFieldsKey).getAsString()); } JsonArray occurancesJA = (JsonArray)issueJO.get("occurrences"); for (Object occurancesObj : occurancesJA) { JsonObject occurancesJO = (JsonObject) occurancesObj; Set<String> occurancesJOKeySet = occurancesJO.keySet(); Map occurance = new HashMap(); for (String occurancesJOKey : occurancesJOKeySet){ occurance.put(occurancesJOKey, occurancesJO.get(occurancesJOKey)); } this.occurances.add(occurance); } } public JsonObject getIssueJO() { return issueJO; } public String getSeverity() { return severity; } public String getCost() { return cost; } public String getIssueOverhead() { return issueOverhead; } public String getId() { return id; } public String getTitle() { return title; } public String getOccurrencesCount() { return occurrencesCount; } public List<String> getSolutionTextList() { return solutionTextList; } public List<Map<String, String>> getOccurances() { return occurances; } public Map<String, String> getOccurrencesFields() { return occurrencesFields; } public String getOccurancesCost() { return occurrencesCost; } }
30.234234
124
0.662992
69182f03098013491f849c70a265fb0e30d89ed8
14,180
/* * Copyright 2014 Tedroid developers * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mx.udlap.is522.tedroid.view; import android.graphics.Canvas; import android.graphics.Paint; import java.util.Arrays; /** * Define el comportamiento de cualquier tetromino o pieza de tetris. * * @author Daniel Pedraza-Arcega, Andrés Peña-Peralta * @since 1.0 */ public class Tetromino { private final GameBoardView gameBoardView; private final Paint foreground; private final Paint border; private final Position position; private final boolean hasRotation; private int[][] shapeMatrix; /** * Construye un nuevo tetromino. * * @param gameBoardView el GameBoardView donde será dibujado. * @param shapeMatrix la forma que tendrá. * @param hasRotation si rota o no. */ Tetromino(GameBoardView gameBoardView, int[][] shapeMatrix, boolean hasRotation) { this.gameBoardView = gameBoardView; this.shapeMatrix = shapeMatrix; this.hasRotation = hasRotation; this.position = new Position(); this.foreground = new Paint(); this.foreground.setStyle(Paint.Style.FILL); // El color se toma de la matriz this.border = new Paint(); this.border.setStyle(Paint.Style.STROKE); this.border.setColor(gameBoardView.getContext().getResources().getColor(Shape.BORDER_COLOR)); } /** * Dibuja este tetromino en un canvas con las dimensiones de su tablero de juego asosiado. * * @param canvas el objeto donde dibujar. */ void drawOn(Canvas canvas) { for (int row = 0; row < shapeMatrix.length; row++) { for (int column = 0; column < shapeMatrix[0].length; column++) { if (shapeMatrix[row][column] != android.R.color.transparent) { foreground.setColor(gameBoardView.getContext().getResources().getColor(shapeMatrix[row][column])); float x0 = (column + position.boardMatrixColumn) * gameBoardView.getBoardColumnWidth(); float y0 = (row + position.boardMatrixRow) * gameBoardView.getBoardRowHeight(); float x1 = (column + 1 + position.boardMatrixColumn) * gameBoardView.getBoardColumnWidth(); float y1 = (row + 1 + position.boardMatrixRow) * gameBoardView.getBoardRowHeight(); canvas.drawRect(x0, y0, x1, y1, foreground); canvas.drawRect(x0, y0, x1, y1, border); } } } } /** * Mueve este tetromino un lugar tablero usado {@link Direction}. * * @param direction {@link Direction#LEFT}, {@link Direction#RIGHT} o {@link Direction#DOWN}. * @return si se pudo mover o no. */ boolean moveTo(Direction direction) { switch (direction) { case LEFT: return moveLeft(); case RIGHT: return moveRight(); case DOWN: return moveDown(); default: return false; } } /** * Centra este tetromino en el tablero padre. * * @return si se traslapa con otras piezas o no. */ boolean centerOnGameBoardView() { int[][] boardMatrix = gameBoardView.getBoardMatrix(); int boardCenterX = boardMatrix[0].length / 2; int shapeCenterX = shapeMatrix[0].length / 2; int xMoves = boardCenterX - shapeCenterX; position.boardMatrixColumn = xMoves; return canFit(getShapeMatrix()); } /** * Rota este tetromino 90° en sentido de las agujas del reloj en el tablero. * * @return si se pudo mover o no. */ boolean rotate() { if (hasRotation) { int[][] originalShapeMatrix = shapeMatrix; int[][] newShapeMatrix = new int[originalShapeMatrix[0].length][originalShapeMatrix.length]; for (int row = 0; row < originalShapeMatrix.length; row++) { for (int column = 0; column < originalShapeMatrix[0].length; column++) { newShapeMatrix[column][originalShapeMatrix.length - 1 - row] = originalShapeMatrix[row][column]; } } if (canFit(newShapeMatrix)) { shapeMatrix = newShapeMatrix; return true; } } return false; } /** @return una matriz de 0s y 1s con la forma de este tetromino. */ int[][] getShapeMatrix() { return shapeMatrix; } /** @return si la figura tiene o no rotación este tetromino. */ boolean hasRotation() { return hasRotation; } /** * @return la posición en el tablero donde se encuentra la esquina superior izquierda de la * matriz de este tetromino */ Position getPosition() { return position; } /** @return el GameBoardView donde se encuentra. */ GameBoardView getGameBoardView() { return gameBoardView; } /** @return el Paint con el que se pinta la superficie. */ Paint getForeground() { return foreground; } /** @return el Paint con el que se pinta el borde. */ Paint getBorder() { return border; } /** * Mueve este tetromino un lugar hacia la derecha en el tablero. * * @return si se pudo mover o no. */ private boolean moveRight() { if (canFit(Direction.RIGHT)) { position.boardMatrixColumn++; return true; } return false; } /** * Mueve este tetromino un lugar hacia la izquierda en el tablero. * * @return si se pudo mover o no. */ private boolean moveLeft() { if (canFit(Direction.LEFT)) { position.boardMatrixColumn--; return true; } return false; } /** * Mueve este tetromino un lugar hacia abajo en el tablero. * * @return si se pudo mover o no. */ private boolean moveDown() { if (canFit(Direction.DOWN)) { position.boardMatrixRow++; return true; } return false; } /** * Genera una predicción poniendo el tetromino en el lugar en el que quedaria después de * rotarse. * * @param rotatedShape la matriz rotada. * @return si cupo o no después de moverse. */ private boolean canFit(int[][] rotatedShape) { int[][] boardMatrix = gameBoardView.getBoardMatrix(); for (int row = 0; row < rotatedShape.length; row++) { for (int column = 0; column < rotatedShape[0].length; column++) { int boardMatrixRow = position.boardMatrixRow + row; int boardMatrixColumn = position.boardMatrixColumn + column; if (isRowOutOfBoundsOfBoard(boardMatrixRow) || isColumnOutOfBoundsOfBoard(boardMatrixColumn) || (boardMatrix[boardMatrixRow][boardMatrixColumn] != android.R.color.transparent && rotatedShape[row][column] != android.R.color.transparent)) { return false; } } } return true; } /** * Genera una predicción poniendo el tetromino en el lugar en el que quedaria después de * moverse. * * @param direction {@link Direction#LEFT}, {@link Direction#RIGHT} o {@link Direction#DOWN}. * @return si cupo o no después de moverse. */ private boolean canFit(Direction direction) { int[][] shape = getShapeMatrix(); int[][] boardMatrix = gameBoardView.getBoardMatrix(); for (int row = 0; row < shape.length; row++) { for (int column = 0; column < shape[0].length; column++) { int boardMatrixRow = position.boardMatrixRow + row; int boardMatrixColumn = position.boardMatrixColumn + column; switch (direction) { case DOWN: boardMatrixRow++; break; case LEFT: boardMatrixColumn--; break; case RIGHT: boardMatrixColumn++; break; default: break; } if (isRowOutOfBoundsOfBoard(boardMatrixRow) || isColumnOutOfBoundsOfBoard(boardMatrixColumn) || (boardMatrix[boardMatrixRow][boardMatrixColumn] != android.R.color.transparent && shape[row][column] != android.R.color.transparent)) { return false; } } } return true; } /** * @param row la fila. * @return si la fila esta fuera o no de los indices del tablero. */ private boolean isRowOutOfBoundsOfBoard(int row) { int[][] boardMatrix = gameBoardView.getBoardMatrix(); return row < 0 || row >= boardMatrix.length; } /** * @param column la columna. * @return si la columna esta fuera o no de los indices del tablero. */ private boolean isColumnOutOfBoundsOfBoard(int column) { int[][] boardMatrix = gameBoardView.getBoardMatrix(); return column < 0 || column >= boardMatrix[0].length; } /** {@inheritDoc} */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (hasRotation ? 1231 : 1237); result = prime * result + Arrays.deepHashCode(shapeMatrix); return result; } /** {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Tetromino other = (Tetromino) obj; if (hasRotation != other.hasRotation) return false; if (!Arrays.deepEquals(shapeMatrix, other.shapeMatrix)) return false; return true; } /** * Contiene las coordenadas de un tetromino en su tablero. * * @author Daniel Pedraza-Arcega * @since 1.0 */ static class Position { private int boardMatrixColumn; private int boardMatrixRow; /** * @return la columna donde se encuentra la esquina superior izquierda de la matriz de este * tetromino. */ int getBoardMatrixColumn() { return boardMatrixColumn; } /** * @return la fila donde se encuentra la esquina superior izquierda de la matriz de este * tetromino. */ int getBoardMatrixRow() { return boardMatrixRow; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + boardMatrixColumn; result = prime * result + boardMatrixRow; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Position other = (Position) obj; if (boardMatrixColumn != other.boardMatrixColumn) return false; if (boardMatrixRow != other.boardMatrixRow) return false; return true; } } /** * Constructor de tetrominos. * * @author Daniel Pedraza-Arcega * @since 1.0 */ static final class Builder { static final Shape DEFAULT_SHAPE = TetrominoShape.O; private int[][] shapeMatrix; private boolean hasRotation; private GameBoardView gameBoardView; /** * Constructor que inicializa valores por default. * * @param gameBoardView el tablero donde crear el nuevo tetromino. */ Builder(GameBoardView gameBoardView) { hasRotation = DEFAULT_SHAPE.hasRotation(); shapeMatrix = new int[DEFAULT_SHAPE.getShapeMatrix().length][]; System.arraycopy(DEFAULT_SHAPE.getShapeMatrix(), 0, shapeMatrix, 0, DEFAULT_SHAPE.getShapeMatrix().length); this.gameBoardView = gameBoardView; } /** * Construira un nuevo tetromino usando una de las figuras predefinadas. * * @param shape un {@link TetrominoShape}. * @return este Builder. */ Builder use(TetrominoShape shape) { shapeMatrix = new int[shape.getShapeMatrix().length][]; System.arraycopy(shape.getShapeMatrix(), 0, shapeMatrix, 0, shape.getShapeMatrix().length); hasRotation = shape.hasRotation(); return this; } /** * Construira un nuevo tetromino con la forma de una matriz de 1s y 0s. * * @param shapeMatrix una matriz de 1s y 0s. * @return este Builder. */ Builder setShape(int[][] shapeMatrix) { this.shapeMatrix = new int[shapeMatrix.length][]; System.arraycopy(shapeMatrix, 0, this.shapeMatrix, 0, shapeMatrix.length); return this; } /** * Construira un nuevo tetromino que podrá rotar. * * @return este Builder. */ Builder hasRotation() { this.hasRotation = true; return this; } /** * @return un nuevo tetromino. */ Tetromino build() { return new Tetromino(gameBoardView, shapeMatrix, hasRotation); } } /** * Constantes de dirección * * @author Daniel Pedraza-Arcega * @since 1.0 */ static enum Direction { RIGHT, LEFT, DOWN } }
32.900232
119
0.581453
f91346a00fbe512c00f664879cb1de4c54624b26
2,868
//package us.codecraft.jobhunter.pipeline; // //import java.io.ByteArrayOutputStream; //import java.io.File; //import java.io.FileOutputStream; //import java.io.IOException; //import java.io.InputStream; //import java.net.MalformedURLException; //import java.net.URL; //import java.net.URLConnection; // //import javax.annotation.Resource; // //import org.springframework.stereotype.Component; // //import us.codecraft.jobhunter.dao.MkzhanDAO; //import us.codecraft.jobhunter.model.MkzhanJobInfo; //import us.codecraft.webmagic.Task; //import us.codecraft.webmagic.pipeline.PageModelPipeline; // ///** // * @author code4crafer@gmail.com // * Date: 13-6-23 // * Time: 下午8:56 // */ //@Component("mkzhanDaoPipeline") //public class MkzhanDaoPipeline implements PageModelPipeline<MkzhanJobInfo> { // // @Resource // private MkzhanDAO mkzhanDAO; // // // public static InputStream inStream = null; // public static String rootPath = "/Users/Oliver/mkzhan"; // // // // public void process(MkzhanJobInfo mkzhanJobInfo, Task task) { // // // String coursePath = rootPath + "/" + mkzhanJobInfo.getId(); // File file = new File(coursePath); // if(!file.exists()) // { // file.mkdirs(); // } // // String chapterPath = coursePath + "/" + mkzhanJobInfo.getChapterId(); // file = new File(chapterPath); // if(!file.exists()) // { // file.mkdirs(); // } // // // // for(int i = 0; i < mkzhanJobInfo.getImgs().size(); i++){ // String link = mkzhanJobInfo.getImgs().get(i); // try { // URL url = new URL(link); // URLConnection con = url.openConnection(); // inStream = con.getInputStream(); // ByteArrayOutputStream outStream = new ByteArrayOutputStream(); // byte[] buf = new byte[1024]; // int len = 0; // while((len = inStream.read(buf)) != -1){ // outStream.write(buf,0,len); // } // inStream.close(); // outStream.close(); // file = new File(chapterPath+"/"+i+".jpg"); //图片下载地址 // FileOutputStream op = new FileOutputStream(file); // op.write(outStream.toByteArray()); // op.close(); // } catch (MalformedURLException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (IOException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // // mkzhanJobInfo.setImgSize(mkzhanJobInfo.getImgs().size()); // mkzhanDAO.add(mkzhanJobInfo); // } //}
32.590909
80
0.542538
f00f1c22ec1950f00769efad1469eb92c66c7fd8
1,949
package dev.blufantasyonline.embercore.physics; import com.fasterxml.jackson.annotation.JsonIgnore; import dev.blufantasyonline.embercore.config.serialization.SerializationInfo; import dev.blufantasyonline.embercore.reflection.annotations.OnEnable; import org.bukkit.Location; import java.util.HashMap; import java.util.LinkedHashSet; @OnEnable public final class ProjectileRegistry { private static int maxProjectiles = 1000; @SerializationInfo(filename = "projectile-presets.yml") private static HashMap<String, ProjectilePreset> projectilePresets = new HashMap<>(); @JsonIgnore private static LinkedHashSet<VectorProjectile> projectiles = new LinkedHashSet<>(); public static VectorProjectile fromPreset(String presetName, Location origin) { ProjectilePreset preset = projectilePresets.get(presetName); if (preset != null) return new VectorProjectile(origin) { @Override protected void init() { setLifetime(preset.lifetime); setRange(preset.range); setSize(preset.size); super.init(); } }; return null; } public static ProjectilePreset fromPresetName(String presetName) { return projectilePresets.get(presetName); } public static void registerProjectile(VectorProjectile proj) { projectiles.add(proj); if (projectiles.size() >= maxProjectiles) { VectorProjectile oldest = projectiles.iterator().next(); oldest.destroy(); } } public static boolean removeProjectile(VectorProjectile proj) { return projectiles.remove(proj); } public static void destroyAll() { VectorProjectile[] arr = new VectorProjectile[projectiles.size()]; projectiles.toArray(arr); for (VectorProjectile v : arr) v.destroy(); } }
32.483333
89
0.664956
6f1429af7d423cf828dfacb729814899051bc35a
623
package tterrag.stoneLamp.common.block; public class BlockInfo { public static final String LAMP_UNLOC_NAME = "stoneLamp"; public static final String EMPTYLAMP_UNLOC_NAME = "emptyLamp"; public static final String COLOREDLAMP_UNLOC_NAME = "coloredLamp"; public static final String EMPTYCOLOREDLAMP_UNLOC_NAME = "emptyColoredLamp"; public static final String LAMP_LOC_NAME = "Stone Lamp"; public static final String EMPTYLAMP_LOC_NAME = "Empty Stone Lamp"; public static final String COLOREDLAMP_LOC_NAME = "Colored Stone Lamp"; public static final String EMPTYCOLOREDLAMP_LOC_NAME = "Empty Colored Stone Lamp"; }
38.9375
83
0.807384
a793d68f56fb2df7380a2db6e08400510337640a
1,673
package com.lanshiqin.algorithm.leetcode.a167; /** * 167. 两数之和 II - 输入有序数组 * <p> * 给你一个下标从 1 开始的整数数组 numbers ,该数组已按 非递减顺序排列 ,请你从数组中找出满足相加之和等于目标数 target 的两个数。如果设这两个数分别是 numbers[index1] 和 numbers[index2] ,则 1 <= index1 < index2 <= numbers.length 。 * <p> * 以长度为 2 的整数数组 [index1, index2] 的形式返回这两个整数的下标 index1 和 index2。 * <p> * 你可以假设每个输入 只对应唯一的答案 ,而且你 不可以 重复使用相同的元素。 * <p> * 你所设计的解决方案必须只使用常量级的额外空间。 * <p> * 示例 1: * <p> * 输入:numbers = [2,7,11,15], target = 9 * 输出:[1,2] * 解释:2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。 * <p> * <p> * 示例 2: * <p> * 输入:numbers = [2,3,4], target = 6 * 输出:[1,3] * 解释:2 与 4 之和等于目标数 6 。因此 index1 = 1, index2 = 3 。返回 [1, 3] 。 * <p> * <p> * 示例 3: * <p> * 输入:numbers = [-1,0], target = -1 * 输出:[1,2] * 解释:-1 与 0 之和等于目标数 -1 。因此 index1 = 1, index2 = 2 。返回 [1, 2] 。 * <p> * 提示: * <p> * 2 <= numbers.length <= 3 * 104 * -1000 <= numbers[i] <= 1000 * numbers 按 非递减顺序 排列 * -1000 <= target <= 1000 * 仅存在一个有效答案 * <p> * <p> * 来源:力扣(LeetCode) * 链接:<a href="https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted">https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted</a> * 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ public class Solution { public int[] twoSum(int[] numbers, int target) { int left = 0, right = numbers.length - 1; while (left < right) { int value = numbers[left] + numbers[right]; if (value == target) { return new int[]{left + 1, right + 1}; } else if (value > target) { right--; } else { left++; } } return new int[0]; } }
26.140625
165
0.545129
8b21233c8c4e99b8d47622fd9966130d571aefb3
397
package com.vmanolache.httpserver.api; import java.nio.file.Path; import java.nio.file.Paths; /** * Created by Vlad Manolache on 2018-09-22. */ public class PathResolver { private final Path documentRoot; public PathResolver(String documentRoot) { this.documentRoot = Paths.get(documentRoot); } public Path resolve(String uri) { return documentRoot.resolve(uri.substring(1)); } }
18.045455
48
0.743073
d0faa6b931843c0d7c694457c93bc3e9d0721d34
1,988
package me.gca.talismancreator.gui; import com.cryptomorin.xseries.XMaterial; import me.gca.talismancreator.TalismanCreator; import me.gca.talismancreator.events.Listeners; import me.gca.talismancreator.gui.util.SpigotGUIComponents; import me.gca.talismancreator.managers.Talisman; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffectType; public class TalismanEditEffectIntensityGUI extends SpigotGUIComponents { public TalismanEditEffectIntensityGUI(Player p, Talisman talisman, PotionEffectType effectType, int intensity){ if (p == null || talisman == null){ return; } if (intensity <= 0){ p.sendMessage(TalismanCreator.colorFormat(TalismanCreator.getPluginPrefix() + " &6Error: You can't set an intensity lower than 1.")); return; } // Params int size = 9*2; Listeners.getInstance().addTalismanEditing(p, talisman); // Create Inventory. Inventory inv = Bukkit.createInventory(null, size, TalismanCreator.colorFormat("&6Talisman Edit Intensity")); ItemStack decreaseButton = createButton(XMaterial.REDSTONE_BLOCK.parseItem(), createLore("&8Click to decrease"), "&c" + effectType.getName() + " " + intensity + " - " + "1"); ItemStack increaseButton = createButton(XMaterial.EMERALD_BLOCK.parseItem(), createLore("&8Click to increase"), "&a" + effectType.getName() + " " + intensity + " + " + "1"); ItemStack confirmButton = createButton(XMaterial.POTION.parseItem(), createLore("&8Click to confirm"), "&6" + effectType.getName() + " " + intensity); // Add Buttons to Inventory. inv.setItem(0, decreaseButton); inv.setItem(4, confirmButton); inv.setItem(8, increaseButton); inv.setItem(size - 1, getCloseGUIButton()); // Open Inventory. openGUI(inv, p); } }
40.571429
182
0.690644
5489a75dc5faca69c2ac15f8b79897cdda41adb1
6,119
package org.jaya.android; import android.app.Activity; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.AssetManager; import android.support.v4.content.ContextCompat; import android.util.Log; import android.util.Pair; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; public class AssetsManager { private Context context; private String resFolderPath; private final ArrayList<Pair<String,String>> mFilesToCopy = new ArrayList<Pair<String,String>>(); public AssetsManager(Context c){ context = c; //resFolderPath = context.getFilesDir() + "/" + JayaApp.VERSION + "/"; resFolderPath = JayaApp.getDocumentsFolder(); } public String getResFolderPath(){ return resFolderPath; } private boolean listAssetFiles(AssetManager assets, String path, List<String> recursiveFilePaths) { String [] list; try { list = assets.list(path); if (list.length > 0) { // This is a folder for (String file : list) { if (!listAssetFiles(assets, path + "/" + file, recursiveFilePaths)) return false; } } else { recursiveFilePaths.add(path); } } catch (IOException e) { return false; } return true; } public void copyResourcesToCacheIfRequired(Activity activity){ if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) return; String sigFilePath = JayaApp.getSearchIndexFolder() + "/segments.gen"; File sigFile = new File(sigFilePath); if(!sigFile.exists()) { InputStream stream = null; OutputStream output = null; try { ArrayList<String> assetFiles = new ArrayList<>(); //listAssetFiles(JayaApp.getAppContext().getAssets(), "to_be_indexed", assetFiles); listAssetFiles(JayaApp.getAppContext().getAssets(), "index", assetFiles); for (String fileName : assetFiles) { String dstPath = JayaApp.getAppExtStorageFolder() + "/" + fileName; File dstFile = new File(dstPath); boolean bDirsCreated = dstFile.getParentFile().mkdirs(); stream = JayaApp.getAppContext().getAssets().open(fileName); output = new BufferedOutputStream(new FileOutputStream(dstPath)); byte data[] = new byte[16*1024]; int count; while ((count = stream.read(data)) != -1) { output.write(data, 0, count); } output.flush(); output.close(); stream.close(); stream = null; output = null; } }catch (IOException ex){ ex.printStackTrace(); } } } public void copyResourcesToCacheIfRequired1(Activity activity){ if( ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) return; String sigFilePath = resFolderPath + "/sarvamoola/aitareya.txt"; File sigFile = new File(sigFilePath); if(!sigFile.exists()) { for (Pair<String, String> item : mFilesToCopy) { String fileName ; if(item.first.indexOf('/')!= -1) fileName = item.first.substring(item.first.lastIndexOf("/")+1); else fileName = item.first; String destUrl = resFolderPath; if(!item.second.isEmpty()) { // if(new File(item.second).isAbsolute()){ if(File.separator.equals(item.second.substring(0,1))){ // Shortcut to check isAbsolute() // Its an absolute url. set the destUrl to empty so that item.second is taken as is destUrl = ""; } destUrl = destUrl + item.second + '/'; } destUrl = destUrl + fileName; copyFile(item.first, destUrl); } } } private void copyFile(String srcPath, String dstPath){ InputStream srcStream = null; FileOutputStream dstStream = null; try { try { srcStream = context.getAssets().open(srcPath); File dstFile = new File(dstPath); boolean bDirsCreated = dstFile.getParentFile().mkdirs(); dstStream = new FileOutputStream(dstPath, false); if (srcStream != null && dstStream != null) { byte[] buffer = new byte[1024 * 64]; // Adjust if you want int bytesRead; while ((bytesRead = srcStream.read(buffer)) != -1) { dstStream.write(buffer, 0, bytesRead); } } else { Log.d(JayaApp.APP_NAME, "JayaApp.copyFile(): Error reading one of the files. src:" + srcPath + ", dst:" + dstPath); } } catch (IOException ex) { Log.e(JayaApp.APP_NAME, "JayaApp.copyFile() exception : " + ex.toString()); } finally { if (srcStream != null) srcStream.close(); if (dstStream != null) dstStream.close(); } }catch (IOException ex){ Log.e(JayaApp.APP_NAME, "JayaApp.copyFile() Stream close failed : " + ex.toString()); } } }
35.783626
108
0.539958
2220b67ee7f80017e2bdf8a3bcb44e0160f4f938
7,053
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.management.internal.cli.commands; import static org.apache.geode.distributed.ConfigurationProperties.ENABLE_CLUSTER_CONFIGURATION; import static org.apache.geode.distributed.ConfigurationProperties.HTTP_SERVICE_PORT; import static org.apache.geode.distributed.ConfigurationProperties.LOG_LEVEL; import static org.apache.geode.distributed.ConfigurationProperties.MCAST_PORT; import static org.apache.geode.distributed.ConfigurationProperties.USE_CLUSTER_CONFIGURATION; import static org.assertj.core.api.Assertions.assertThat; import java.util.Properties; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.distributed.Locator; import org.apache.geode.distributed.internal.InternalConfigurationPersistenceService; import org.apache.geode.distributed.internal.InternalDistributedSystem; import org.apache.geode.distributed.internal.InternalLocator; import org.apache.geode.internal.AvailablePortHelper; import org.apache.geode.internal.cache.InternalCache; import org.apache.geode.test.dunit.IgnoredException; import org.apache.geode.test.dunit.rules.ClusterStartupRule; import org.apache.geode.test.dunit.rules.MemberVM; import org.apache.geode.test.junit.categories.RegionsTest; import org.apache.geode.test.junit.rules.GfshCommandRule; @Category(RegionsTest.class) // GEODE-973 GEODE-2009 @SuppressWarnings("serial") public class RegionChangesPersistThroughClusterConfigurationDUnitTest { @Rule public GfshCommandRule gfsh = new GfshCommandRule(); @Rule public ClusterStartupRule lsRule = new ClusterStartupRule(); private MemberVM locator, server1, server2; private static final String REGION_NAME = "testRegionSharedConfigRegion"; private static final String REGION_PATH = "/" + REGION_NAME; private static final String GROUP_NAME = "cluster"; @Before public void setup() throws Exception { int[] randomPorts = AvailablePortHelper.getRandomAvailableTCPPorts(2); int jmxPort = randomPorts[0]; int httpPort = randomPorts[1]; Properties props = new Properties(); props.setProperty(MCAST_PORT, "0"); props.setProperty(LOG_LEVEL, "fine"); props.setProperty(ENABLE_CLUSTER_CONFIGURATION, "true"); props.setProperty(ConfigurationProperties.JMX_MANAGER_HOSTNAME_FOR_CLIENTS, "localhost"); props.setProperty(ConfigurationProperties.JMX_MANAGER_PORT, "" + jmxPort); props.setProperty(ConfigurationProperties.MAX_WAIT_TIME_RECONNECT, "5000"); props.setProperty(HTTP_SERVICE_PORT, "" + httpPort); locator = lsRule.startLocatorVM(0, props); IgnoredException .addIgnoredException("Possible loss of quorum due to the loss of 1 cache processes"); gfsh.connectAndVerify(locator); Properties serverProps = new Properties(); serverProps.setProperty(MCAST_PORT, "0"); serverProps.setProperty(USE_CLUSTER_CONFIGURATION, "true"); server1 = lsRule.startServerVM(1, serverProps, locator.getPort()); server2 = lsRule.startServerVM(2, serverProps, locator.getPort()); gfsh.executeAndAssertThat( "create region --type=REPLICATE --enable-statistics=true --name=" + REGION_PATH) .statusIsSuccess(); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(REGION_PATH, 2); } @Test public void createdRegionPersistsThroughCacheConfig() { locator.invoke(() -> { InternalConfigurationPersistenceService sharedConfig = ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService(); assertThat(sharedConfig.getConfiguration(GROUP_NAME).getCacheXmlContent()) .contains(REGION_NAME); }); server2.forceDisconnect(); server2.waitTilFullyReconnected(); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(REGION_PATH, 2); server2.invoke(() -> { InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance(); InternalCache cache = system.getCache(); assertThat(cache.getInternalRegionByPath(REGION_PATH)).isNotNull(); }); } @Test public void regionUpdatePersistsThroughClusterConfig() { server2.invoke(() -> { InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance(); InternalCache cache = system.getCache(); assertThat(cache.getInternalRegionByPath(REGION_PATH).isEntryExpiryPossible()).isFalse(); }); gfsh.executeAndAssertThat( "alter region --name=" + REGION_PATH + " --entry-time-to-live-expiration=45635 " + "--entry-time-to-live-expiration-action=destroy") .statusIsSuccess(); locator.invoke(() -> { InternalConfigurationPersistenceService sharedConfig = ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService(); assertThat(sharedConfig.getConfiguration(GROUP_NAME).getCacheXmlContent()).contains("45635"); }); server2.forceDisconnect(); server2.waitTilFullyReconnected(); locator.waitUntilRegionIsReadyOnExactlyThisManyServers(REGION_PATH, 2); server2.invoke(() -> { InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance(); InternalCache cache = system.getCache(); assertThat(cache.getInternalRegionByPath(REGION_PATH)).isNotNull(); assertThat(cache.getInternalRegionByPath(REGION_PATH).isEntryExpiryPossible()).isTrue(); }); } @Test public void destroyRegionPersistsThroughClusterConfig() { gfsh.executeAndAssertThat("destroy region --name=" + REGION_PATH).statusIsSuccess(); locator.invoke(() -> { InternalConfigurationPersistenceService sharedConfig = ((InternalLocator) Locator.getLocator()).getConfigurationPersistenceService(); assertThat(sharedConfig.getConfiguration(GROUP_NAME).getCacheXmlContent()) .doesNotContain(REGION_NAME); }); server2.forceDisconnect(); server2.waitTilFullyReconnected(); server2.invoke(() -> { InternalDistributedSystem system = InternalDistributedSystem.getConnectedInstance(); InternalCache cache = system.getCache(); assertThat(cache.getInternalRegionByPath(REGION_PATH)).isNull(); }); } }
41.005814
100
0.766908
58d74d1846baf8ee912888e43f57bb4b68cfd0b2
1,254
package com.google.android.gms.internal.ads; import android.os.RemoteException; import android.view.View; import com.google.android.gms.dynamic.ObjectWrapper; import java.util.HashMap; /* compiled from: com.google.android.gms:play-services-ads-lite@@19.4.0 */ final class zzwl extends zzwn<zzael> { private final /* synthetic */ zzvx zzcij; private final /* synthetic */ View zzciu; private final /* synthetic */ HashMap zzciv; private final /* synthetic */ HashMap zzciw; zzwl(zzvx zzvx, View view, HashMap hashMap, HashMap hashMap2) { this.zzcij = zzvx; this.zzciu = view; this.zzciv = hashMap; this.zzciw = hashMap2; } /* access modifiers changed from: protected */ public final /* synthetic */ Object zzpp() { zzvx.zza(this.zzciu.getContext(), "native_ad_view_holder_delegate"); return new zzzv(); } public final /* synthetic */ Object zzpq() throws RemoteException { return this.zzcij.zzcir.zzb(this.zzciu, this.zzciv, this.zzciw); } public final /* synthetic */ Object zza(zzxp zzxp) throws RemoteException { return zzxp.zza(ObjectWrapper.wrap(this.zzciu), ObjectWrapper.wrap(this.zzciv), ObjectWrapper.wrap(this.zzciw)); } }
34.833333
120
0.682616
f5c8968c4b086396c4f9bdca7f242d43ed6ae0c9
4,561
package ilyag.ah81; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.HashMap; public class MainActivity extends ActionBarActivity { HashMap<String, Integer> map; TextView tv; SharedPreferences sp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button bAdd = (Button) findViewById(R.id.bAdd); Button bShow = (Button) findViewById(R.id.bShow); Button bReset = (Button) findViewById(R.id.bReset); tv = (TextView) findViewById(R.id.tvOutput); bAdd.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplication(), AddActivity.class); startActivityForResult(intent, 0); } }); bShow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplication(), ShowActivity.class); intent.putExtra("list", map); startActivity(intent); } }); bReset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { map = new HashMap<String, Integer>(); tv.setText("0"); } }); } @Override protected void onResume() { super.onResume(); if (map != null) { tv.setText("" + map.size()); } else { FileInputStream fis; ObjectInputStream ois = null; try { fis = openFileInput("ah81.ser"); ois = new ObjectInputStream(fis); Object o = ois.readObject(); if (o == null) { Toast.makeText(getApplication(), "got null object", Toast.LENGTH_LONG).show(); map = new HashMap<>(); tv.setText("0"); } else { map = (HashMap<String, Integer>) o; int size = map.size(); tv.setText("" + size); } ois.close(); } catch (FileNotFoundException e) { Log.e("ilyag1", e.getMessage()); } catch (IOException e) { Log.e("ilyag1", e.getMessage()); } catch (ClassNotFoundException e) { Log.e("ilyag1", e.getMessage()); } } } @Override protected void onPause() { super.onPause(); FileOutputStream fos; ObjectOutputStream oos = null; try { fos = openFileOutput("ah81.ser", MODE_PRIVATE); oos = new ObjectOutputStream(fos); oos.writeObject(map); } catch (FileNotFoundException e) { Log.e("ilyag1", e.getMessage()); } catch (IOException e) { Log.e("ilyag1", e.getMessage()); } finally { if (oos != null) { try { oos.close(); } catch (IOException e) { Log.e("ilyag1", e.getMessage()); } } } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0 && resultCode >= 0) { if (data == null) { Toast.makeText(getApplicationContext(), "nothing has been returned", Toast.LENGTH_LONG).show(); } else { String itemName = data.getStringExtra("product name"); int count = data.getIntExtra("count", -1); if (itemName == null || count == -1) { Toast.makeText(getApplicationContext(), "incorrect product or count", Toast.LENGTH_LONG).show(); } else { map.put(itemName, count); } } } super.onActivityResult(requestCode, resultCode, data); } }
33.050725
116
0.539794
e4d65a8f5259b0825f95118f77ae29b5c13ae815
2,744
package com.ihgoo.allinone.support; import org.json.JSONObject; import java.util.HashSet; import java.util.Set; /** * Created by ihgoo on 2015/6/16. */ public class StringUtil { public static String quoteString(Object object, String left, String right) { return left.concat(object.toString()).concat(right); } public static String concat(Object... objects) { String str = new String(); if (objects != null) { for (Object object : objects) { if (object != null) { try { str = str.concat(object.toString()); } catch (Exception e) { } } } } return str; } public static <T> String join(Set<T> list) { return join(list.toArray(), ","); } public static String join(Object[] objects) { return join(objects, ","); } public static String join(Object[] objects, String glue) { int k = objects.length; if (k == 0) return ""; StringBuilder out = new StringBuilder(); out.append(objects[0]); for (int x = 1; x < k; ++x) out.append(glue).append(objects[x]); return out.toString(); } public static String toString(Object object) { String result = "错误:null"; if (object != null) { result = object.toString(); } return result; } /** * @param string string以逗号分隔返回string的hashset * @return */ public static HashSet<String> parseKeys(String string) { HashSet<String> keywords = new HashSet<String>(); if (string != null) { for (String key : string.split(",")) { keywords.add(key); } } return keywords; } /** * @param objects * @param glue * @param left * @param right * @return */ public static String joinWithQuote(Object[] objects, String glue, String left, String right) { int k = objects.length; if (k == 0) return null; StringBuilder out = new StringBuilder(); out.append(quoteString(objects[0], left, right)); for (int x = 1; x < k; ++x) out.append(glue).append(quoteString(objects[x], left, right)); return out.toString(); } public static String getStr(JSONObject jsonObject, String name) { String result = ""; try { if (jsonObject != null && jsonObject.has(name)) { result = jsonObject.getString(name); } } catch (Exception e) { e.printStackTrace(); } return result; } }
26.901961
98
0.52223
08958346b90b733a95c73d29e3b38f64095c37fe
2,749
package com.codeborne.selenide.impl; import com.codeborne.selenide.Driver; import org.apache.commons.io.IOUtils; import org.openqa.selenium.By; import org.openqa.selenium.By.ByCssSelector; import org.openqa.selenium.SearchContext; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.List; import static com.codeborne.selenide.SelectorMode.CSS; import static java.lang.Thread.currentThread; /** * Thanks to http://selenium.polteq.com/en/injecting-the-sizzle-css-selector-library/ */ public class WebElementSelector { public static WebElementSelector instance = new WebElementSelector(); protected String sizzleSource; public WebElement findElement(Driver driver, SearchContext context, By selector) { if (driver.config().selectorMode() == CSS || !(selector instanceof ByCssSelector)) { return context.findElement(selector); } List<WebElement> webElements = evaluateSizzleSelector(driver, context, (ByCssSelector) selector); return webElements.isEmpty() ? null : webElements.get(0); } public List<WebElement> findElements(Driver driver, SearchContext context, By selector) { if (driver.config().selectorMode() == CSS || !(selector instanceof ByCssSelector)) { return context.findElements(selector); } return evaluateSizzleSelector(driver, context, (ByCssSelector) selector); } protected List<WebElement> evaluateSizzleSelector(Driver driver, SearchContext context, ByCssSelector sizzleCssSelector) { injectSizzleIfNeeded(driver); String sizzleSelector = sizzleCssSelector.toString() .replace("By.selector: ", "") .replace("By.cssSelector: ", ""); if (context instanceof WebElement) return driver.executeJavaScript("return Sizzle(arguments[0], arguments[1])", sizzleSelector, context); else return driver.executeJavaScript("return Sizzle(arguments[0])", sizzleSelector); } protected void injectSizzleIfNeeded(Driver driver) { if (!sizzleLoaded(driver)) { injectSizzle(driver); } } protected Boolean sizzleLoaded(Driver driver) { try { return driver.executeJavaScript("return typeof Sizzle != 'undefined'"); } catch (WebDriverException e) { return false; } } protected synchronized void injectSizzle(Driver driver) { if (sizzleSource == null) { try { sizzleSource = IOUtils.toString(currentThread().getContextClassLoader().getResource("sizzle.js"), StandardCharsets.UTF_8); } catch (IOException e) { throw new RuntimeException("Cannot load sizzle.js from classpath", e); } } driver.executeJavaScript(sizzleSource); } }
33.938272
130
0.733721
c33353a61e8af656558d755b1cb31637892abad1
567
package com.alexanderhirschfeld.singleton; import static org.junit.Assert.assertTrue; import org.junit.jupiter.api.Test; public class EnumSingletonTest { @Test public void testSingleton() { EnumSingleton instance1 = EnumSingleton.Instance.getInstance(); assertTrue(instance1 instanceof EnumSingleton); EnumSingleton instance2 = EnumSingleton.Instance.getInstance(); assertTrue(instance2 instanceof EnumSingleton); instance1.setInfo(false); assertTrue(instance1.getInfo().equals(false)); assertTrue(instance2.getInfo().equals(false)); } }
25.772727
65
0.783069
c23513d100e5120bc72cacb24b86300764721943
665
package com.mrbysco.liquidblocks.handler; import net.minecraft.world.World; import net.minecraftforge.event.TickEvent; import net.minecraftforge.event.TickEvent.Phase; import net.minecraftforge.event.TickEvent.WorldTickEvent; import net.minecraftforge.eventbus.api.EventPriority; import net.minecraftforge.eventbus.api.SubscribeEvent; public class FluidEvents { @SubscribeEvent(priority = EventPriority.HIGHEST) public void worldTick(WorldTickEvent event) { if(event.phase == TickEvent.Phase.START && event.phase == Phase.START) return; World world = event.world; if (world.getGameTime() % 20 == 0) { } // System.out.println(event.getState()); } }
28.913043
80
0.778947
a77e9ab0c593ef160a764b283f8c673592855967
5,155
package tencent2018; import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class Main3 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); sc.nextLine(); char[][] picture = new char[n][m]; for (int i=0;i<n;i++) { String str = sc.nextLine(); picture[i] = str.toCharArray(); } if (n == 1){ boolean yellowflag = false; boolean blueflag = false; int res = 0; for (int i=0;i<m;i++){ if (yellowflag){ if (picture[0][i] == 'X' || picture[0][i] == 'B'){ yellowflag = false; res++; } } if (picture[0][i] == 'Y' || picture[0][i] == 'G'){ yellowflag = true; } } for (int i=0;i<m;i++){ if (blueflag){ if (picture[0][i] == 'X' || picture[0][i] == 'Y'){ blueflag = false; res++; } } if (picture[0][i] == 'B' || picture[0][i] == 'G'){ blueflag = true; } } if (yellowflag) res++; if (blueflag) res++; System.out.println(res); return; } if (m == 1){ boolean yellowflag = false; boolean blueflag = false; int res = 0; for (int i=0;i<n;i++){ if (yellowflag){ if (picture[i][0] == 'X' || picture[i][0] == 'B'){ yellowflag = false; res++; } } if (picture[i][0] == 'Y' || picture[i][0] == 'G'){ yellowflag = true; } } for (int i=0;i<n;i++){ if (blueflag){ if (picture[i][0] == 'X' || picture[i][0] == 'Y'){ blueflag = false; res++; } } if (picture[i][0] == 'B' || picture[i][0] == 'G'){ blueflag = true; } } if (yellowflag) res++; if (blueflag) res++; System.out.println(res); return; } int times = n+m-1; int res = 0; for (int time = 0;time<times;time++){ boolean yellowflag = false; boolean blueflag = false; if (time >= times/2){ int len = times - time; int start = time - times/2; for (int i = 0;i<len;i++){ // is interrupted if (yellowflag){ if (picture[i][start+i] == 'X' || picture[i][start+i] == 'B'){ yellowflag = false; res++; } } if (picture[i][start+i] == 'Y' || picture[i][start+i] == 'G'){ yellowflag = true; } } for (int i = 0;i<len;i++){ if (blueflag){ if (picture[i][m-start-i-1] == 'X' || picture[i][m-start-i-1] == 'Y'){ blueflag = false; res++; } } if (picture[i][m-start-i-1] == 'B' || picture[i][m-start-i-1] == 'G'){ blueflag = true; } } if (yellowflag) res++; if (blueflag) res++; } else{ int len = time+1; int start = time; for (int i = 0;i<len;i++){ if (yellowflag){ if (picture[n-start-1+i][i] == 'X' || picture[n-start-1+i][i] == 'B'){ yellowflag = false; res++; } } if (picture[n-start-1+i][i] == 'Y' || picture[n-start-1+i][i] == 'G'){ yellowflag = true; } } for (int i = 0;i<len;i++){ if (blueflag){ if (picture[n-start-1+i][m-i-1] == 'X' || picture[n-start-1+i][m-i-1] == 'Y'){ blueflag = false; res++; } } if (picture[n-start-1+i][m-i-1] == 'B' || picture[n-start-1+i][m-i-1] == 'G'){ blueflag = true; } } if (yellowflag) res++; if (blueflag) res++; } } System.out.println(res); } }
34.139073
102
0.321242
2b2aac5226230fb9e2a974e514f39ff638154464
3,371
package main.me.thedome.aesencryptor.utils; import main.me.thedome.aesencryptor.classes.DEBUG_MODE; import main.me.thedome.aesencryptor.classes.OPERATION_MODE; import main.me.thedome.aesencryptor.main.AESEncryptor; import java.io.File; import java.util.ArrayList; import java.util.Collections; /** * AES_Encryptor/PACKAGE_NAME * Created on 11/2016. */ public class ArgumentParser { private final ArrayList<String> args; private int index = 0; private AESEncryptor aec; private IOUtils utils = IOUtils.getInstance(); public ArgumentParser(String[] args, AESEncryptor encclass) { this.args = new ArrayList<>(); Collections.addAll(this.args, args); aec = encclass; pepareArguments(); } /** * Print the Help and exit then */ public static void printHelp() { System.out.println("Usage: [name] inputfile for an only encryption"); System.out.println("Usage: [name] -i inputfile -k key for an encryption with a key"); System.out.println("Usage: [name] -i inputfile -k key -d for a decryption with a key"); System.out.println("\nOther parameters to pass:"); System.out.println("\t-i input file"); System.out.println("\t-o output file"); System.out.println("\t-e encryption mode"); System.out.println("\t-d decyption mode"); System.out.println("\t-k keyfile"); System.out.println("\t-h display this help"); System.out.println("\t-p Enable the percentage display mode (may not be enabled due the debug mode)"); System.out.println("\t[optional] -v [optional] level (0,1,2) Enable verbose mode with level (default:1)"); System.exit(1); } /** * Watch through the Arguments and draw first conclusions */ private void pepareArguments() { if (args.contains("-h")) { printHelp(); } if (args.size() < 1) { printHelp(); } } public void pushBack() { this.index--; } /** * Parse the Arguments given to the Object */ public void parseArgs() { checkForSingleArgs(); // Check arguments while (hasNextArgument()) { switch (nextArgument()) { case "-v": int level; try { level = Integer.parseInt(nextArgument()); } catch (Exception e) { pushBack(); level = DEBUG_MODE.MODE_NORMAL.level; } aec.debMode = DEBUG_MODE.MODE_NORMAL.getByLevel(level); break; case "-k": utils.keyfile = new File(nextArgument()); break; case "-e": aec.mode = OPERATION_MODE.MODE_ENCRYPT; break; case "-d": aec.mode = OPERATION_MODE.MODE_DECRYPT; break; case "-i": utils.inputfile = new File(nextArgument()); break; case "-o": utils.outputfile = new File(nextArgument()); break; case "-h": printHelp(); break; case "-p": aec.percentage_mode = true; break; case "--version": Logger.getInstance().print("Current Version:"); Logger.getInstance().print("\t" + aec.VERSION); System.exit(1); break; default: break; } } } private void checkForSingleArgs() { if (args.size() == 1) { utils.inputfile = new File(args.get(0)); } } /** * Get the next argument * * @return The next argument */ public String nextArgument() { return args.get(index++); } /** * Returnst, if we have Arguments left * * @return If we have an Argument left */ public boolean hasNextArgument() { return index < args.size(); } }
23.248276
108
0.650845
81a28e8ef3f240ff4b72544118e9bbd62cdd0a35
398
package cz.krtinec.telka; public class CannotLoadProgrammeException extends RuntimeException { public CannotLoadProgrammeException(String detailMessage, Throwable throwable) { super(detailMessage, throwable); // TODO Auto-generated constructor stub } public CannotLoadProgrammeException(String detailMessage) { super(detailMessage); // TODO Auto-generated constructor stub } }
22.111111
68
0.79397
50f7f5948ee4eeef14f4604f221c6ba2f340abd5
275
package com.jiaxingrong.requstov.wx; import lombok.Data; /** * @Author:luchang * @Date: 2019/12/28 15:54 * @Version 1.0 */ @Data public class GoodsBean { private Integer number; private String picUrl; private Integer id; private String goodsName; }
13.095238
36
0.676364
786a522c754d95ddb045da21c302968ae7a516e3
1,956
package com.github.maxopoly.WurstCivTools.effect; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.SkullMeta; public class HeadHunterEffect extends AbstractEnchantmentEffect { public void handleKillNPCForHeldItem(Player attacker, Entity victim, EntityDeathEvent event) { ItemStack headDrop = null; int level = getEnchantLevel(attacker.getInventory().getItemInMainHand()); if (!chanceConfig.roll(level)) { return; } switch (victim.getType()) { case SKELETON: headDrop = new ItemStack(Material.SKULL_ITEM, 1, (short) 0); break; case ZOMBIE: headDrop = new ItemStack(Material.SKULL_ITEM, 1, (short) 2); break; case CREEPER: headDrop = new ItemStack(Material.SKULL_ITEM, 1, (short) 4); break; default: break; } if (headDrop != null) { event.getDrops().add(headDrop); } } @Override public void handleKillPlayerForHeldItem(Player attacker, Player victim, PlayerDeathEvent e) { int level = getEnchantLevel(attacker.getInventory().getItemInMainHand()); if (!chanceConfig.roll(level)) { return; } ItemStack drop = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); // Make head appear to be killed's head SkullMeta skullMeta = (SkullMeta) drop.getItemMeta(); skullMeta.setOwningPlayer(victim); skullMeta.setDisplayName(ChatColor.RED + victim.getName() + "s head"); drop.setItemMeta(skullMeta); // The above method might be buggy // People online were having a hard time aswell, it seems e.getDrops().add(drop); } @Override public boolean parseParameters(ConfigurationSection config) { return true; } @Override public String getIdentifier() { return "HEADDROP"; } }
27.942857
95
0.745399
07f5a2720ac077058ba7af8328d2ac887948b208
1,670
/** * Copyright 2018-2019 The Jaeger Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package io.jaegertracing.tests.model; import java.util.List; import org.junit.runner.Result; import org.junit.runner.notification.Failure; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Builder @AllArgsConstructor @NoArgsConstructor @Data public class TestSuiteStatus { private String name; private Boolean wasSuccessful; private Integer failureCount; private Integer runCount; private Integer ignoreCount; private Long runTime; private List<Failure> failures; public static TestSuiteStatus get(String name, Result testResult) { return TestSuiteStatus.builder() .name(name) .wasSuccessful(testResult.wasSuccessful()) .runCount(testResult.getRunCount()) .failureCount(testResult.getFailureCount()) .ignoreCount(testResult.getIgnoreCount()) .runTime(testResult.getRunTime()) .failures(testResult.getFailures()) .build(); } }
32.745098
100
0.707186
b61fb55fc05b09666f2a79522adb8f766502e4ba
2,512
package yanagishima.module; import com.google.inject.servlet.ServletModule; import yanagishima.servlet.*; public class PrestoServletModule extends ServletModule { @Override protected void configureServlets() { bind(PrestoServlet.class); bind(PrestoAsyncServlet.class); bind(QueryServlet.class); bind(KillServlet.class); bind(FormatSqlServlet.class); bind(HistoryServlet.class); bind(HistoryStatusServlet.class); bind(ShareHistoryServlet.class); bind(PublishServlet.class); bind(QueryDetailServlet.class); bind(DownloadServlet.class); bind(ShareDownloadServlet.class); bind(CsvDownloadServlet.class); bind(ShareCsvDownloadServlet.class); bind(QueryHistoryServlet.class); bind(QueryHistoryUserServlet.class); bind(DatasourceAuthServlet.class); bind(QueryStatusServlet.class); bind(BookmarkServlet.class); bind(BookmarkUserServlet.class); bind(ToValuesQueryServlet.class); bind(TableListServlet.class); bind(PrestoPartitionServlet.class); bind(CommentServlet.class); bind(ConvertPrestoServlet.class); bind(LabelServlet.class); serve("/presto").with(PrestoServlet.class); serve("/prestoAsync").with(PrestoAsyncServlet.class); serve("/query").with(QueryServlet.class); serve("/kill").with(KillServlet.class); serve("/format").with(FormatSqlServlet.class); serve("/history").with(HistoryServlet.class); serve("/historyStatus").with(HistoryStatusServlet.class); serve("/share/shareHistory").with(ShareHistoryServlet.class); serve("/publish").with(PublishServlet.class); serve("/queryDetail").with(QueryDetailServlet.class); serve("/download").with(DownloadServlet.class); serve("/share/download").with(ShareDownloadServlet.class); serve("/csvdownload").with(CsvDownloadServlet.class); serve("/share/csvdownload").with(ShareCsvDownloadServlet.class); serve("/queryHistory").with(QueryHistoryServlet.class); serve("/queryHistoryUser").with(QueryHistoryUserServlet.class); serve("/datasourceAuth").with(DatasourceAuthServlet.class); serve("/queryStatus").with(QueryStatusServlet.class); serve("/bookmark").with(BookmarkServlet.class); serve("/bookmarkUser").with(BookmarkUserServlet.class); serve("/toValuesQuery").with(ToValuesQueryServlet.class); serve("/tableList").with(TableListServlet.class); serve("/prestoPartition").with(PrestoPartitionServlet.class); serve("/comment").with(CommentServlet.class); serve("/convertPresto").with(ConvertPrestoServlet.class); serve("/label").with(LabelServlet.class); } }
38.646154
66
0.774283
8e22801626cdbf4df087afbae96ad88af11856fe
1,005
package music.service; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import music.model.Vinyl; import music.repository.VinylRepository; @Service public class VinylService { @Autowired VinylRepository vinylRepository; public Vinyl createVinyl(Vinyl vinyl) { return vinylRepository.save(vinyl); } public List<Vinyl> getVinyls() { return vinylRepository.findAll(); } public Vinyl updateVinyl(Vinyl vinyl, Integer id) { vinyl.setId(id); return vinylRepository.save(vinyl); } public void deleteVinylById(Integer id) { vinylRepository.deleteById(id); } public void deleteVinylByEntity(Vinyl vinyl) { vinylRepository.delete(vinyl); } public Vinyl getVinylById(Integer id) { Optional<Vinyl> vinylOpt = vinylRepository.findById(id); if(vinylOpt.isPresent()) { return vinylOpt.get(); } else { return null; } } }
20.9375
62
0.728358
3a2f93875bf6efe2fd85b083e33d1c39c2de2a37
369
package com.lemon.web.request; import com.lemon.web.base.request.BaseRequest; import lombok.Data; import lombok.EqualsAndHashCode; import javax.validation.constraints.NotBlank; /** * PayRequest * * @author sjp * @date 2019/5/23 */ @Data @EqualsAndHashCode(callSuper = false) public class PayRequest extends BaseRequest { @NotBlank private String orderIdEn; }
17.571429
46
0.766938
14461cf354f308cfa730f7e04b3c2bf3d4e63064
1,158
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.iothub.v2018_04_01.implementation; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * The JSON-serialized array of Certificate objects. */ public class CertificateListDescriptionInner { /** * The array of Certificate objects. */ @JsonProperty(value = "value") private List<CertificateDescriptionInner> value; /** * Get the array of Certificate objects. * * @return the value value */ public List<CertificateDescriptionInner> value() { return this.value; } /** * Set the array of Certificate objects. * * @param value the value value to set * @return the CertificateListDescriptionInner object itself. */ public CertificateListDescriptionInner withValue(List<CertificateDescriptionInner> value) { this.value = value; return this; } }
25.733333
95
0.690846
57682166c9922fd02244a6df733250b41ca49df2
2,764
/******************************************************************************* * Copyright (c)2014 Prometheus Consulting * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package nz.co.senanque.rules; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * * The class reference stores a map of field references. * * @author Roger Parkinson * @version $Revision: 1.3 $ */ public class ClassReference implements Serializable { private static final long serialVersionUID = 1L; private final transient Map<String,FieldReference> m_fieldReferenceMap = new HashMap<String,FieldReference>(); private final transient Class<?> m_class; private final transient List<ClassReference> m_children = new ArrayList<ClassReference>(); public ClassReference(final Class<?> clazz) { m_class = clazz; } public String getClassName() { return m_class.getSimpleName(); } public FieldReference getFieldReference(final String fieldName) { FieldReference fieldReference = m_fieldReferenceMap.get(fieldName); if (fieldReference == null) { fieldReference = new FieldReference(getClassName(), fieldName); m_fieldReferenceMap.put(fieldName,fieldReference); } return fieldReference; } public String getSuperClass() { return m_class.getSuperclass().getSimpleName(); } public void figureChildren(Map<String, ClassReference> classReferenceMap) { for (ClassReference cr: classReferenceMap.values()) { String superClass = cr.getSuperClass(); if (superClass.equals(getClassName())) { m_children.add(cr); } } } public List<ClassReference> getChildren() { List<ClassReference> ret = new ArrayList<ClassReference>(); ret.add(this); for (ClassReference cr: m_children) { ret.addAll(cr.getChildren()); } return ret; } public Class<?> getClazz() { return m_class; } }
29.094737
111
0.624457
9f089541a10c90da2f5d5a41a9a4634975ff2765
1,984
package com.mz.jarboot; import com.mz.jarboot.api.AgentService; import com.mz.jarboot.api.JarbootFactory; import com.mz.jarboot.api.cmd.spi.CommandProcessor; import com.mz.jarboot.api.service.ServiceManager; import com.mz.jarboot.api.service.SettingService; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.core.env.Environment; /** * @author majianzheng */ @ConditionalOnProperty(name = "spring.jarboot.enabled", matchIfMissing = true) @EnableConfigurationProperties({ JarbootConfigProperties.class }) public class JarbootAutoConfiguration { @Bean @ConditionalOnClass(name = Constants.AGENT_CLASS) public AgentService agentService() { return JarbootFactory.createAgentService(); } @Bean @ConditionalOnProperty(havingValue = "serverAddr") public ServiceManager serviceManager(JarbootConfigProperties properties) { return JarbootFactory .createServerManager(properties.getServerAddr(), properties.getUsername(), properties.getPassword()); } @Bean @ConditionalOnProperty(havingValue = "serverAddr") public SettingService setting(JarbootConfigProperties properties) { return JarbootFactory .createSettingService(properties.getServerAddr(), properties.getUsername(), properties.getPassword()); } @Bean("spring.env") public CommandProcessor springEnv(Environment environment) { return new com.mz.jarboot.command.SpringEnvCommandProcessor(environment); } @Bean("spring.bean") public CommandProcessor springBean(ApplicationContext context) { return new com.mz.jarboot.command.SpringBeanCommandProcessor(context); } }
38.901961
118
0.775706
1423eb13681081e15be599d396411f7c1a433e02
40,885
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.largeFilesEditor.editor; import com.google.common.collect.EvictingQueue; import com.intellij.CommonBundle; import com.intellij.codeInsight.highlighting.HighlightManager; import com.intellij.largeFilesEditor.file.ReadingPageResultHandler; import com.intellij.largeFilesEditor.search.SearchResult; import com.intellij.openapi.actionSystem.IdeActions; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.editor.*; import com.intellij.openapi.editor.colors.EditorColors; import com.intellij.openapi.editor.event.*; import com.intellij.openapi.editor.ex.EditorEx; import com.intellij.openapi.editor.markup.RangeHighlighter; import com.intellij.openapi.fileEditor.ex.IdeDocumentHistory; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.wm.impl.status.PositionPanel; import com.intellij.ui.components.JBLayeredPane; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.ui.JBUI; import org.jetbrains.annotations.CalledInAwt; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; public class EditorModel { private static final Logger LOG = Logger.getInstance(EditorModel.class); private static final int EDITOR_LINE_BEGINNING_INDENT = 5; private static final int PAGES_CASH_CAPACITY = 10; private static final int MAX_AVAILABLE_LINE_LENGTH = 1000; private final DataProvider dataProvider; private final Editor editor; private final DocumentOfPagesModel documentOfPagesModel; private final Collection<RangeHighlighter> pageRangeHighlighters; private final EvictingQueue<Page> pagesCash = EvictingQueue.create(PAGES_CASH_CAPACITY); private final List<Long> numbersOfRequestedForReadingPages = new LinkedList<>(); private final AtomicBoolean isUpdateRequested = new AtomicBoolean(false); private boolean isBrokenMode = false; private final AbsoluteEditorPosition targetVisiblePosition = new AbsoluteEditorPosition(0, 0); private boolean isLocalScrollBarStabilized = false; private final AbsoluteSymbolPosition targetCaretPosition = new AbsoluteSymbolPosition(0, 0); private boolean isRealCaretAndSelectionCanAffectOnTarget = true; private boolean isNeedToShowCaret = false; private final SelectionState targetSelectionState = new SelectionState(); private boolean wasViewPortInTheEndOfFileLastTime = false; private boolean isAllowedToFollowTheEndOfFile = false; private boolean isNeedToHighlightCloseSearchResults = false; private boolean isHighlightedSearchResultsAreStabilized = false; private JComponent myRootComponent; private final ExecutorService myPageReaderExecutor = AppExecutorUtil.createBoundedApplicationPoolExecutor("Large File Editor Page Reader Executor", 1); private final GlobalScrollBar myGlobalScrollBar; private final LocalInvisibleScrollBar myLocalInvisibleScrollBar; EditorModel(Document document, Project project, DataProvider dataProvider) { this.dataProvider = dataProvider; pageRangeHighlighters = new ArrayList<>(); documentOfPagesModel = new DocumentOfPagesModel(document); documentOfPagesModel.addDocumentListener(new DocumentListener() { @Override public void documentChanged(@NotNull DocumentEvent event) { fireHighlightedSearchResultsAreOutdated(); } }); editor = createSpecialEditor(document, project); editor.getCaretModel().addCaretListener(new CaretListener() { @Override public void caretPositionChanged(@NotNull CaretEvent event) { fireRealCaretPositionChanged(event); } }); editor.getSelectionModel().addSelectionListener(new SelectionListener() { @Override public void selectionChanged(@NotNull SelectionEvent e) { fireRealSelectionChanged(e); } }); myGlobalScrollBar = new GlobalScrollBar(this); myLocalInvisibleScrollBar = new LocalInvisibleScrollBar(this); JScrollPane scrollPaneInEditor = ((EditorEx)editor).getScrollPane(); scrollPaneInEditor.setVerticalScrollBar(myLocalInvisibleScrollBar); scrollPaneInEditor.getVerticalScrollBar().setOpaque(true); myRootComponent = editor.getComponent(); insertGlobalScrollBarIntoEditorComponent(); } private void insertGlobalScrollBarIntoEditorComponent() { JComponent mainPanelInEditor = editor.getComponent(); LayoutManager layout = mainPanelInEditor.getLayout(); if (layout instanceof BorderLayout) { BorderLayout borderLayout = (BorderLayout)layout; Component originalCentralComponent = borderLayout.getLayoutComponent(BorderLayout.CENTER); JBLayeredPane intermediatePane = new JBLayeredPane() { @Override public void doLayout() { final Component[] components = getComponents(); final Rectangle bounds = getBounds(); for (Component component : components) { if (component == myGlobalScrollBar) { int scrollBarWidth = myGlobalScrollBar.getPreferredSize().width; component.setBounds(bounds.width - scrollBarWidth, 0, scrollBarWidth, bounds.height); } else { component.setBounds(0, 0, bounds.width, bounds.height); } } } @Override public Dimension getPreferredSize() { return originalCentralComponent.getPreferredSize(); } }; intermediatePane.add(originalCentralComponent, JLayeredPane.DEFAULT_LAYER); intermediatePane.add(myGlobalScrollBar, JLayeredPane.PALETTE_LAYER); mainPanelInEditor.add(intermediatePane, BorderLayout.CENTER); } else { // layout instanceof BorderLayout == false LOG.info("[Large File Editor Subsystem] EditorModel.insertGlobalScrollBarIntoEditorComponent():" + " can't insert GlobalScrollBar in normal way."); myRootComponent = new JPanel(); myRootComponent.setLayout(new BorderLayout()); myRootComponent.add(editor.getComponent(), BorderLayout.CENTER); myRootComponent.add(myGlobalScrollBar, BorderLayout.EAST); } } long getCaretPageNumber() { return targetCaretPosition.pageNumber; } int getCaretPageOffset() { return targetCaretPosition.symbolOffsetInPage; } Editor getEditor() { return editor; } JComponent getComponent() { return myRootComponent; } void setBrokenMode() { isBrokenMode = true; requestUpdate(); } void addCaretListener(CaretListener caretListener) { editor.getCaretModel().addCaretListener(caretListener); } <T> void putUserDataToEditor(@NotNull Key<T> key, T value) { editor.putUserData(key, value); } private void fireRealCaretPositionChanged(@NotNull CaretEvent event) { if (isRealCaretAndSelectionCanAffectOnTarget) { reflectRealToTargetCaretPosition(); isNeedToShowCaret = true; if (editor.getSelectionModel().getSelectionEnd() == editor.getSelectionModel().getSelectionStart()) { targetSelectionState.isExists = false; } if (event.getOldPosition().line != event.getNewPosition().line) { IdeDocumentHistory docHistory = IdeDocumentHistory.getInstance(dataProvider.getProject()); if (docHistory != null) { docHistory.includeCurrentCommandAsNavigation(); docHistory.setCurrentCommandHasMoves(); } } requestUpdate(); } } private void reflectRealToTargetCaretPosition() { int caretOffset = editor.getCaretModel().getPrimaryCaret().getOffset(); AbsoluteSymbolPosition absoluteSymbolPosition = documentOfPagesModel.offsetToAbsoluteSymbolPosition(caretOffset); targetCaretPosition.set(absoluteSymbolPosition); } private void fireRealSelectionChanged(SelectionEvent selectionEvent) { if (isRealCaretAndSelectionCanAffectOnTarget) { reflectRealToTargetSelection(selectionEvent); } } private void reflectRealToTargetSelection(SelectionEvent selectionEvent) { TextRange newSelectionRange = selectionEvent.getNewRange(); if (newSelectionRange == null || newSelectionRange.isEmpty()) { targetSelectionState.isExists = false; } else { int startOffset = newSelectionRange.getStartOffset(); int endOffset = newSelectionRange.getEndOffset(); AbsoluteSymbolPosition startAbsolutePosition = documentOfPagesModel.offsetToAbsoluteSymbolPosition(startOffset); AbsoluteSymbolPosition endAbsolutePosition = documentOfPagesModel.offsetToAbsoluteSymbolPosition(endOffset); targetSelectionState.set(startAbsolutePosition, endAbsolutePosition); targetSelectionState.isExists = true; } } private void fireHighlightedSearchResultsAreOutdated() { isHighlightedSearchResultsAreStabilized = false; requestUpdate(); } public void fireGlobalScrollBarValueChangedFromOutside(long pageNumber) { long pagesAmount; try { pagesAmount = dataProvider.getPagesAmount(); } catch (IOException e) { LOG.info(e); return; } if (pageNumber < 0 || pageNumber > pagesAmount) { LOG.warn("[Large File Editor Subsystem] EditorModel.fireGlobalScrollBarValueChangedFromOutside(pageNumber):" + " Illegal argument pageNumber. Expected: 0 < pageNumber <= pagesAmount." + " Actual: pageNumber=" + pageNumber + " pagesAmount=" + pagesAmount); return; } targetVisiblePosition.set(pageNumber, 0); update(); } private void requestUpdate() { // elimination of duplicates of update() tasks in EDT queue if (isUpdateRequested.compareAndSet(false, true)) { ApplicationManager.getApplication().invokeLater(() -> { isUpdateRequested.set(false); update(); }); } } @CalledInAwt private void update() { if (isBrokenMode) { documentOfPagesModel.removeAllPages(dataProvider.getProject()); return; } long pagesAmountInFile; try { pagesAmountInFile = dataProvider.getPagesAmount(); } catch (IOException e) { LOG.info(e); Messages.showErrorDialog(EditorBundle.message("large.file.editor.message.error.while.working.with.file.try.to.reopen.it"), CommonBundle.getErrorTitle()); return; } if (isNeedToShowCaret) { ensureTargetCaretPositionIsInFileBounds(pagesAmountInFile); targetVisiblePosition.set(targetCaretPosition.pageNumber, targetVisiblePosition.verticalScrollOffset); // we can't count the necessary offset at this stage } normalizePagesInDocumentListBeginning(); if (pagesAmountInFile == 0) { return; } if (documentOfPagesModel.getPagesAmount() == 0) { long pageNumber = targetVisiblePosition.pageNumber == 0 ? 0 : targetVisiblePosition.pageNumber == pagesAmountInFile // to avoid redundant document rebuilding ? targetVisiblePosition.pageNumber - 2 : targetVisiblePosition.pageNumber - 1; Page page = tryGetPageFromCash(pageNumber); if (page != null) { setNextPageIntoDocument(page); } else { requestReadPage(pageNumber); return; } } if (isNeedToTurnOnSoftWrapping()) { // TODO: 2019-05-21 need to notify user someway editor.getSettings().setUseSoftWraps(true); } normalizePagesInDocumentListEnding(); ensureDocumentLastPageIsValid(pagesAmountInFile); if (wasViewPortInTheEndOfFileLastTime && isAllowedToFollowTheEndOfFile) { targetVisiblePosition.set(Long.MAX_VALUE, 0); isNeedToShowCaret = false; isAllowedToFollowTheEndOfFile = false; } tryReflectTargetCaretPositionToReal(); tryReflectTargetSelectionToReal(); tryNormalizeTargetVisiblePosition(); if (!isLocalScrollBarStabilized) { tryScrollToTargetVisiblePosition(); } updateGlobalStrollBarView(); long nextPageNumberToAdd = tryGetNextPageNumberToAdd(pagesAmountInFile); if (nextPageNumberToAdd != -1) { Page nextPageToAdd = tryGetPageFromCash(nextPageNumberToAdd); if (nextPageToAdd != null) { setNextPageIntoDocument(nextPageToAdd); requestUpdate(); } else { requestReadPage(nextPageNumberToAdd); } return; } pagesCash.clear(); if (isNeedToShowCaret) { if (isLocalScrollBarStabilized) { showCaretThatIsNeededToShow(); } else { requestUpdate(); return; } } else { if (!isRealCaretMatchesTarget()) { setCaretToConvenientPosition(); } } wasViewPortInTheEndOfFileLastTime = false; if (documentOfPagesModel.getLastPage().getPageNumber() == pagesAmountInFile - 1 && myLocalInvisibleScrollBar.getValue() + myLocalInvisibleScrollBar.getHeight() == myLocalInvisibleScrollBar.getMaximum()) { wasViewPortInTheEndOfFileLastTime = true; } tryHighlightSearchResultsIfNeed(); } // IDEA-232158 private void ensureDocumentLastPageIsValid(long pagesAmountInFile) { Page lastPageInDocument = documentOfPagesModel.getLastPage(); if (lastPageInDocument.isLastInFile() != (lastPageInDocument.getPageNumber() == pagesAmountInFile - 1)) { removeLastPageFromDocument(); pagesCash.removeIf(page -> lastPageInDocument.getPageNumber() == page.getPageNumber()); } } private boolean isNeedToTurnOnSoftWrapping() { return !editor.getSettings().isUseSoftWraps() && isExistLineWithTooLargeLength(); } // TODO: 2019-05-13 can be optimized by checking lines only for last added page private boolean isExistLineWithTooLargeLength() { Document document = documentOfPagesModel.getDocument(); int lineCount = document.getLineCount(); for (int i = 0; i < lineCount; i++) { int lineWidth = document.getLineEndOffset(i) - document.getLineStartOffset(i); if (lineWidth > MAX_AVAILABLE_LINE_LENGTH) { return true; } } return false; } private void tryHighlightSearchResultsIfNeed() { if (isNeedToHighlightCloseSearchResults) { if (!isHighlightedSearchResultsAreStabilized) { updateSearchResultsHighlighting(); isHighlightedSearchResultsAreStabilized = true; } } else { clearHighlightedSearchResults(); } } private void updateSearchResultsHighlighting() { clearHighlightedSearchResults(); List<TextRange> highlightRanges = getAllSearchResultsRangesInDocument(); if (!highlightRanges.isEmpty()) { HighlightManager highlightManager = HighlightManager.getInstance(dataProvider.getProject()); for (TextRange range : highlightRanges) { highlightManager.addRangeHighlight( editor, range.getStartOffset(), range.getEndOffset(), EditorColors.TEXT_SEARCH_RESULT_ATTRIBUTES, true, pageRangeHighlighters); } } } private List<TextRange> getAllSearchResultsRangesInDocument() { List<TextRange> searchResultsRanges = new ArrayList<>(); for (int i = 0; i < documentOfPagesModel.getPagesList().size(); i++) { Page page = documentOfPagesModel.getPagesList().get(i); List<SearchResult> searchResults = dataProvider.getSearchResultsInPage(page); if (searchResults != null) { for (SearchResult result : searchResults) { int from = documentOfPagesModel.getSymbolOffsetToStartOfPage( documentOfPagesModel.getIndexOfPageByPageNumber(result.startPosition.pageNumber)) + result.startPosition.symbolOffsetInPage; int to = documentOfPagesModel.getSymbolOffsetToStartOfPage( documentOfPagesModel.getIndexOfPageByPageNumber(result.endPostion.pageNumber)) + result.endPostion.symbolOffsetInPage; if (from < 0) from = 0; if (to > documentOfPagesModel.getDocument().getTextLength()) to = documentOfPagesModel.getDocument().getTextLength(); if (from < to) { searchResultsRanges.add(new TextRange(from, to)); } } } } return searchResultsRanges; } private void clearHighlightedSearchResults() { final HighlightManager highlightManager = HighlightManager.getInstance(dataProvider.getProject()); for (RangeHighlighter pageRangeHighlighter : pageRangeHighlighters) { highlightManager.removeSegmentHighlighter(editor, pageRangeHighlighter); } pageRangeHighlighters.clear(); } private void showCaretThatIsNeededToShow() { int targetCaretOffsetInDocument = tryGetTargetCaretOffsetInDocumentWithMargin(); if (targetCaretOffsetInDocument != -1) { if (!isRealCaretInsideTargetVisibleArea()) { editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE); } } else { LOG.warn("[Large File Editor Subsystem] EditorMode.update(): can't show caret. " + " targetCaretPosition.pageNumber=" + targetCaretPosition.pageNumber + " targetCaretPosition.symbolOffsetInPage=" + targetCaretPosition.symbolOffsetInPage + " targetVisiblePosition.pageNumber=" + targetVisiblePosition.pageNumber + " targetVisiblePosition.verticalScrollOffset=" + targetVisiblePosition.verticalScrollOffset); } isNeedToShowCaret = false; } private boolean isRealCaretInsideTargetVisibleArea() { Point pointOfCaret = editor.offsetToXY(editor.getCaretModel().getOffset()); Rectangle area = editor.getScrollingModel().getVisibleAreaOnScrollingFinished(); return area.contains(pointOfCaret); } private void setCaretToConvenientPosition() { int offset = tryGetConvenientOffsetForCaret(); if (offset != -1) { runCaretAndSelectionListeningTransparentCommand( () -> editor.getCaretModel().moveToOffset(offset)); reflectRealToTargetCaretPosition(); } else { LOG.info("[Large File Editor Subsystem] EditorModel.setCaretToConvenientPosition(): " + "Can't set caret to convenient position."); } } private boolean isRealCaretMatchesTarget() { int targetCaretOffsetInDocument = tryGetTargetCaretOffsetInDocumentWithMargin(); return targetCaretOffsetInDocument == editor.getCaretModel().getOffset(); } private void tryReflectTargetCaretPositionToReal() { int targetCaretOffsetInDocument = tryGetTargetCaretOffsetInDocumentWithMargin(); if (targetCaretOffsetInDocument != -1) { runCaretAndSelectionListeningTransparentCommand( () -> editor.getCaretModel().moveToOffset(targetCaretOffsetInDocument)); } } private void tryReflectTargetSelectionToReal() { if (targetSelectionState.isExists && documentOfPagesModel.getPagesAmount() != 0) { int docLength = documentOfPagesModel.getDocument().getTextLength(); int startOffset = Math.min(documentOfPagesModel.absoluteSymbolPositionToOffset(targetSelectionState.start), docLength); int endOffset = Math.min(documentOfPagesModel.absoluteSymbolPositionToOffset(targetSelectionState.end), docLength); runCaretAndSelectionListeningTransparentCommand(() -> { if (startOffset == endOffset) { editor.getSelectionModel().removeSelection(); } else { editor.getSelectionModel().setSelection(startOffset, endOffset); } }); } } private int tryGetConvenientOffsetForCaret() { Rectangle visibleArea = editor.getScrollingModel().getVisibleAreaOnScrollingFinished(); return editor.logicalPositionToOffset(editor.xyToLogicalPosition(new Point( 0, visibleArea.y + editor.getLineHeight()))); } private int tryGetTargetCaretOffsetInDocumentWithMargin() { if (documentOfPagesModel.getPagesAmount() == 0) { return 0; } int offset = tryGetTargetCaretOffsetInDocument(); if (offset == -1) return -1; int startOfAllowedRange = tryGetStartMarginForTargetCaretInDocument(); int endOfAllowedRange = getSymbolOffsetToStartOfPage(documentOfPagesModel.getPagesAmount()); try { if (documentOfPagesModel.getLastPage().getPageNumber() != dataProvider.getPagesAmount() - 1) { endOfAllowedRange -= documentOfPagesModel.getLastPage().getText().length() / 2; } } catch (IOException e) { LOG.warn(e); } if (offset >= startOfAllowedRange && offset <= endOfAllowedRange) { return offset; } else { return -1; } } private int tryGetStartMarginForTargetCaretInDocument() { if (documentOfPagesModel.getPagesAmount() > 0) { if (documentOfPagesModel.getFirstPage().getPageNumber() == 0) { return 0; } else { return documentOfPagesModel.getFirstPage().getText().length() / 2; } } else { return 0; } } private int tryGetTargetCaretOffsetInDocument() { int indexOfPage = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetCaretPosition.pageNumber); int targetCaretOffsetInDocument; if (indexOfPage != -1) { targetCaretOffsetInDocument = getSymbolOffsetToStartOfPage(indexOfPage) + targetCaretPosition.symbolOffsetInPage; } else if (targetCaretPosition.symbolOffsetInPage == 0 && targetCaretPosition.pageNumber == documentOfPagesModel.getLastPage().getPageNumber() + 1) { targetCaretOffsetInDocument = getSymbolOffsetToStartOfPage(documentOfPagesModel.getPagesAmount()); } else { return -1; } int docLength = documentOfPagesModel.getDocument().getTextLength(); if (targetCaretOffsetInDocument >= 0) { return Math.min(targetCaretOffsetInDocument, docLength); } else { LOG.warn("[Large File Editor Subsystem] EditorModel.tryGetTargetCaretOffsetInDocument():" + " Invalid targetCaretPosition state." + " targetCaretPosition.pageNumber=" + targetCaretPosition.pageNumber + " targetCaretPosition.symbolOffsetInPage=" + targetCaretPosition.symbolOffsetInPage + " targetCaretOffsetInDocument=" + targetCaretOffsetInDocument + " document.getTextLength()=" + docLength); } return -1; } // TODO: 2019-04-10 need to handle possible 'long' values private void updateGlobalStrollBarView() { long pagesAmount; try { pagesAmount = dataProvider.getPagesAmount(); } catch (IOException e) { LOG.warn(e); return; } if (pagesAmount >= Integer.MAX_VALUE) { LOG.warn("[Large File Editor Subsystem] EditorModel.updateGlobalStrollBarView():" + "pagesAmount > Integer.MAX_VALUE. pagesAmount=" + pagesAmount); } int extent = 1; // to make thumb of minimum size myGlobalScrollBar.setValues((int)targetVisiblePosition.pageNumber, extent, 0, (int)pagesAmount + 1); } private long tryGetNextPageNumberToAdd(long pagesAmountInFile) { if (documentOfPagesModel.getPagesAmount() == 0) { return targetVisiblePosition.pageNumber == 0 ? targetVisiblePosition.pageNumber : targetVisiblePosition.pageNumber - 1; } int visibleTargetPageIndex = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetVisiblePosition.pageNumber); if (visibleTargetPageIndex == -1) { // some pages before visible one exist and are located in list => just need to get next to last in list return tryGetNumberOfNextToDocumentPage(pagesAmountInFile); } // check if we really need some extra pages or already not int offsetToFirstVisibleSymbolOfTargetVisiblePage = getSymbolOffsetToStartOfPage(visibleTargetPageIndex); int topOfTargetVisiblePage = offsetToY(offsetToFirstVisibleSymbolOfTargetVisiblePage); int topOfTargetVisibleArea = topOfTargetVisiblePage + targetVisiblePosition.verticalScrollOffset; Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); int bottomOfTargetVisibleArea = topOfTargetVisibleArea + visibleArea.height; int lastVisiblePageIndex = visibleTargetPageIndex; int offsetToEndOfLastVisiblePage = getSymbolOffsetToStartOfPage(lastVisiblePageIndex + 1); while (lastVisiblePageIndex + 1 < documentOfPagesModel.getPagesAmount() && offsetToY(offsetToEndOfLastVisiblePage) <= bottomOfTargetVisibleArea) { lastVisiblePageIndex++; offsetToEndOfLastVisiblePage = getSymbolOffsetToStartOfPage(lastVisiblePageIndex + 1); } if (documentOfPagesModel.getPagesAmount() - 1 == lastVisiblePageIndex) { // we need at least 1 invisible page after visible ones, if it's not the end return tryGetNumberOfNextToDocumentPage(pagesAmountInFile); } return -1; } private long tryGetNumberOfNextToDocumentPage(long pagesAmountInFile) { if (documentOfPagesModel.getPagesAmount() > 0) { long nextPageNumber = documentOfPagesModel.getLastPage().getPageNumber() + 1; return nextPageNumber < pagesAmountInFile ? nextPageNumber : -1; } else { return -1; } } private void tryNormalizeTargetVisiblePosition() { boolean needToRepeat; try { do { needToRepeat = tryNormalizeTargetEditorViewPosition_iteration(); } while (needToRepeat); } catch (IOException e) { LOG.info(e); } } private boolean tryNormalizeTargetEditorViewPosition_iteration() throws IOException { long pagesAmountInFile = dataProvider.getPagesAmount(); if (pagesAmountInFile == 0) { targetVisiblePosition.set(0, 0); return false; } if (targetVisiblePosition.pageNumber >= pagesAmountInFile) { targetVisiblePosition.set(pagesAmountInFile, -1); } if (targetVisiblePosition.verticalScrollOffset < 0) { if (targetVisiblePosition.pageNumber == 0) { targetVisiblePosition.set(0, 0); return false; } int prevPageIndex = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetVisiblePosition.pageNumber - 1); if (prevPageIndex == -1) { return false; } int symbolOffsetToBeginningOfPrevPage = getSymbolOffsetToStartOfPage(prevPageIndex); int symbolOffsetToBeginningOfTargetPage = getSymbolOffsetToStartOfPage(prevPageIndex + 1); int verticalOffsetToBeginningOfPrevPage = offsetToY(symbolOffsetToBeginningOfPrevPage); int verticalOffsetToBeginningOfTargetPage = offsetToY(symbolOffsetToBeginningOfTargetPage); targetVisiblePosition.set(targetVisiblePosition.pageNumber - 1, targetVisiblePosition.verticalScrollOffset + verticalOffsetToBeginningOfTargetPage - verticalOffsetToBeginningOfPrevPage); return true; } // here targetVisiblePosition.pageNumber < pagesAmountInFile // && targetVisiblePosition.verticalScrollOffset >= 0 int visibleTargetPageIndex = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetVisiblePosition.pageNumber); if (visibleTargetPageIndex == -1) { return false; } int symbolOffsetToBeginningOfTargetVisiblePage = getSymbolOffsetToStartOfPage(visibleTargetPageIndex); int symbolOffsetToEndOfTargetVisiblePage = getSymbolOffsetToStartOfPage(visibleTargetPageIndex + 1); int topOfTargetVisiblePage = offsetToY(symbolOffsetToBeginningOfTargetVisiblePage); int bottomOfExpectedVisibleArea = topOfTargetVisiblePage + targetVisiblePosition.verticalScrollOffset + editor.getScrollingModel().getVisibleArea().height; if (bottomOfExpectedVisibleArea > editor.getContentComponent().getHeight()) { int indexOfLastLastPage = documentOfPagesModel.tryGetIndexOfNeededPageInList(pagesAmountInFile - 1); if (indexOfLastLastPage == -1) { return false; } int extraDifference = bottomOfExpectedVisibleArea - editor.getContentComponent().getHeight(); targetVisiblePosition.set(targetVisiblePosition.pageNumber, targetVisiblePosition.verticalScrollOffset - extraDifference); return true; } // here targetVisiblePosition.pageNumber < pagesAmountInFile // && targetVisiblePosition.verticalScrollOffset >= 0 // && bottomOfExpectedVisibleArea <= editor.getContentComponent().getHeight() int bottomOfTargetVisiblePage = offsetToY(symbolOffsetToEndOfTargetVisiblePage); if (topOfTargetVisiblePage + targetVisiblePosition.verticalScrollOffset >= bottomOfTargetVisiblePage) { targetVisiblePosition.set(targetVisiblePosition.pageNumber + 1, targetVisiblePosition.verticalScrollOffset - bottomOfTargetVisiblePage + topOfTargetVisiblePage); return true; } return false; } private void ensureTargetCaretPositionIsInFileBounds(long pagesAmount) { if (targetCaretPosition.pageNumber < 0) { targetCaretPosition.set(0, 0); } else if (targetCaretPosition.pageNumber >= pagesAmount) { targetCaretPosition.set(pagesAmount, 0); } } private void normalizePagesInDocumentListEnding() { int visibleTargetPageIndex = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetVisiblePosition.pageNumber); if (visibleTargetPageIndex == -1) { return; } int offsetToFirstVisibleSymbolOfTargetVisiblePage = getSymbolOffsetToStartOfPage(visibleTargetPageIndex); int topOfTargetVisiblePage = offsetToY(offsetToFirstVisibleSymbolOfTargetVisiblePage); int topOfTargetVisibleArea = topOfTargetVisiblePage + targetVisiblePosition.verticalScrollOffset; Rectangle visibleArea = editor.getScrollingModel().getVisibleArea(); int bottomOfTargetVisibleArea = topOfTargetVisibleArea + visibleArea.height; int lastVisiblePageIndex = visibleTargetPageIndex; int offsetToEndOfLastVisiblePage = getSymbolOffsetToStartOfPage(lastVisiblePageIndex + 1); while (lastVisiblePageIndex + 1 < documentOfPagesModel.getPagesAmount() && offsetToY(offsetToEndOfLastVisiblePage) <= bottomOfTargetVisibleArea) { lastVisiblePageIndex++; offsetToEndOfLastVisiblePage = getSymbolOffsetToStartOfPage(lastVisiblePageIndex + 1); } int maxAllowedAmountOfPagesInDocumentHere = lastVisiblePageIndex + 2 + 1; // max 2 invisible pages in the end while (documentOfPagesModel.getPagesAmount() > maxAllowedAmountOfPagesInDocumentHere) { removeLastPageFromDocument(); } } private void tryScrollToTargetVisiblePosition() { int visibleTargetPageIndex = documentOfPagesModel.tryGetIndexOfNeededPageInList(targetVisiblePosition.pageNumber); if (visibleTargetPageIndex == -1) { return; } int symbolOffsetToBeginningOfTargetVisiblePage = getSymbolOffsetToStartOfPage(visibleTargetPageIndex); int topOfTargetVisiblePage = offsetToY(symbolOffsetToBeginningOfTargetVisiblePage); int targetTopOfVisibleArea = topOfTargetVisiblePage + targetVisiblePosition.verticalScrollOffset; if (editor.getScrollingModel().getVisibleAreaOnScrollingFinished().y != targetTopOfVisibleArea) { editor.getScrollingModel().disableAnimation(); editor.getScrollingModel().scrollVertically(targetTopOfVisibleArea); editor.getScrollingModel().enableAnimation(); } if (editor.getScrollingModel().getVisibleAreaOnScrollingFinished().y == targetTopOfVisibleArea) { isLocalScrollBarStabilized = true; } } public void setCaretToFileEndAndShow() { long pagesAmount; try { pagesAmount = dataProvider.getPagesAmount(); } catch (IOException e) { LOG.info(e); return; } setCaretAndShow(pagesAmount, 0); } public void setCaretToFileStartAndShow() { setCaretAndShow(0, 0); } public void setCaretAndShow(long pageNumber, int symbolOffsetInPage) { targetCaretPosition.set(pageNumber, symbolOffsetInPage); isNeedToShowCaret = true; requestUpdate(); } private int offsetToY(int offset) { return editor.offsetToXY(offset).y; } private int getSymbolOffsetToStartOfPage(int indexOfPage) { return documentOfPagesModel.getSymbolOffsetToStartOfPage(indexOfPage); } private void requestReadPage(long pageNumber) { if (!numbersOfRequestedForReadingPages.contains(pageNumber)) { dataProvider.requestReadPage(pageNumber, page -> tellPageWasRead(pageNumber, page)); numbersOfRequestedForReadingPages.add(pageNumber); } } private void tellPageWasRead(long pageNumber, Page page) { ApplicationManager.getApplication().invokeLater(() -> { if (page == null) { LOG.warn("page with number " + pageNumber + " is null."); return; } pagesCash.add(page); numbersOfRequestedForReadingPages.remove(pageNumber); requestUpdate(); }); } private void setNextPageIntoDocument(Page page) { runCaretAndSelectionListeningTransparentCommand( () -> documentOfPagesModel.addPageIntoEnd(page, dataProvider.getProject())); } private void removeLastPageFromDocument() { if (documentOfPagesModel.getPagesAmount() > 0) { pagesCash.add(documentOfPagesModel.getLastPage()); runCaretAndSelectionListeningTransparentCommand( () -> documentOfPagesModel.removeLastPage(dataProvider.getProject())); } } private void deleteAllPagesFromDocument() { pagesCash.addAll(documentOfPagesModel.getPagesList()); runCaretAndSelectionListeningTransparentCommand( () -> documentOfPagesModel.removeAllPages(dataProvider.getProject())); } private void runCaretAndSelectionListeningTransparentCommand(Runnable command) { isRealCaretAndSelectionCanAffectOnTarget = false; command.run(); isRealCaretAndSelectionCanAffectOnTarget = true; } private Page tryGetPageFromCash(long pageNumber) { for (Page page : pagesCash) { if (page.getPageNumber() == pageNumber) { return page; } } return null; } private void normalizePagesInDocumentListBeginning() { if (!isOkBeginningOfPagesInDocumentList()) { isLocalScrollBarStabilized = false; deleteAllPagesFromDocument(); } } private boolean isOkBeginningOfPagesInDocumentList() { int listSize = documentOfPagesModel.getPagesAmount(); if (listSize < 1) { return true; } long numberOfPage0 = documentOfPagesModel.getPageByIndex(0).getPageNumber(); if (numberOfPage0 != targetVisiblePosition.pageNumber - 2 && numberOfPage0 != targetVisiblePosition.pageNumber - 1) { // we can have no any extra pages before visible one only in case, when target visible page is in the beginning of the file return numberOfPage0 == targetVisiblePosition.pageNumber && targetVisiblePosition.pageNumber == 0; } if (listSize < 2) { return true; } long numberOfPage1 = documentOfPagesModel.getPageByIndex(1).getPageNumber(); if (numberOfPage1 == targetVisiblePosition.pageNumber) { return true; } if (numberOfPage1 != targetVisiblePosition.pageNumber - 1) { return false; } if (listSize < 3) { return true; } long numberOfPage2 = documentOfPagesModel.getPageByIndex(2).getPageNumber(); return numberOfPage2 == targetVisiblePosition.pageNumber; } void dispose() { if (editor != null) { EditorFactory.getInstance().releaseEditor(editor); } myPageReaderExecutor.shutdown(); } private static Editor createSpecialEditor(Document document, Project project) { // TODO: 2019-05-21 use line below to activate editor, when editing opportunity will be available //Editor editor = EditorFactory.getInstance().createEditor(document, project, EditorKind.MAIN_EDITOR); Editor editor = EditorFactory.getInstance().createViewer(document, project, EditorKind.MAIN_EDITOR); editor.getSettings().setLineMarkerAreaShown(false); editor.getSettings().setLineNumbersShown(false); editor.getSettings().setFoldingOutlineShown(false); editor.getContentComponent().setBorder(JBUI.Borders.emptyLeft(EDITOR_LINE_BEGINNING_INDENT)); if (editor instanceof EditorEx) { ((EditorEx)editor).setContextMenuGroupId(IdeActions.GROUP_EDITOR_POPUP); } else { LOG.warn("[Large File Editor Subsystem] com.intellij.largeFilesEditor.editor.EditorModel.createSpecialEditor:" + " 'editor' is not instance of EditorEx. Can't set proper context menu group id."); } // don't show PositionPanel for this editor, because it still can't work properly with the editor editor.putUserData(PositionPanel.DISABLE_FOR_EDITOR, new Object()); return editor; } public void fireLocalScrollBarValueChanged() { if (editor.isDisposed()) return; // to avoid DisposalException: Editor is already disposed if (isLocalScrollBarStabilized) { reflectLocalScrollBarStateToTargetPosition(); } requestUpdate(); } private void reflectLocalScrollBarStateToTargetPosition() { if (documentOfPagesModel.getPagesAmount() == 0) return; int localScrollBarValue = myLocalInvisibleScrollBar.getValue(); int indexOfPage = 0; int topOfPage = 0; int bottomOfPage = 0; while (indexOfPage < documentOfPagesModel.getPagesAmount()) { topOfPage = bottomOfPage; bottomOfPage = offsetToY(getSymbolOffsetToStartOfPage(indexOfPage + 1)); if (localScrollBarValue < bottomOfPage) { targetVisiblePosition.set(documentOfPagesModel.getPageByIndex(indexOfPage).getPageNumber(), localScrollBarValue - topOfPage); return; } indexOfPage++; } if (indexOfPage >= 1 && localScrollBarValue == bottomOfPage) { targetVisiblePosition.set(documentOfPagesModel.getPageByIndex(indexOfPage - 1).getPageNumber(), localScrollBarValue - topOfPage); return; } LOG.warn("[Large File Editor Subsystem] EditorModel.reflectLocalScrollBarStateToTargetPosition():" + " can't reflect state." + " indexOfPage=" + indexOfPage + " localScrollBarValue=" + localScrollBarValue + " topOfPage=" + topOfPage + " bottomOfPage=" + bottomOfPage + " pagesInDocument.size()=" + documentOfPagesModel.getPagesAmount()); } @CalledInAwt public void showSearchResult(SearchResult searchResult) { targetSelectionState.set(searchResult.startPosition.pageNumber, searchResult.startPosition.symbolOffsetInPage, searchResult.endPostion.pageNumber, searchResult.endPostion.symbolOffsetInPage); targetSelectionState.isExists = true; targetCaretPosition.pageNumber = searchResult.endPostion.pageNumber; targetCaretPosition.symbolOffsetInPage = searchResult.endPostion.symbolOffsetInPage; isNeedToShowCaret = true; requestUpdate(); } @CalledInAwt public void setHighlightingCloseSearchResultsEnabled(boolean enabled) { if (isNeedToHighlightCloseSearchResults != enabled) { isNeedToHighlightCloseSearchResults = enabled; fireHighlightedSearchResultsAreOutdated(); requestUpdate(); } } @CalledInAwt public void onFileChanged(Page lastPage, boolean isLengthIncreased) { isLocalScrollBarStabilized = false; pagesCash.clear(); if (isLengthIncreased) { runCaretAndSelectionListeningTransparentCommand(() -> { documentOfPagesModel.removeLastPage(dataProvider.getProject()); }); isAllowedToFollowTheEndOfFile = true; } else { runCaretAndSelectionListeningTransparentCommand(() -> { documentOfPagesModel.removeAllPages(dataProvider.getProject()); }); } if (lastPage != null) { pagesCash.add(lastPage); } update(); } @CalledInAwt public void onEncodingChanged() { isLocalScrollBarStabilized = false; pagesCash.clear(); runCaretAndSelectionListeningTransparentCommand(() -> { documentOfPagesModel.removeAllPages(dataProvider.getProject()); }); requestUpdate(); } interface DataProvider { Page getPage(long pageNumber) throws IOException; long getPagesAmount() throws IOException; Project getProject(); void requestReadPage(long pageNumber, ReadingPageResultHandler readingPageResultHandler); List<SearchResult> getSearchResultsInPage(Page page); } }
37.168182
140
0.721194
3109bfe8352585f92077be6a25c1876df3e04f3c
1,528
package xyz.mieszko.speed; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.java.JavaPlugin; /** * @author Mieszko Kycermann */ public class Speed extends JavaPlugin { @Override public void onEnable() { this.getCommand("speed").setExecutor(this); } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!(sender.isOp() || sender.hasPermission("speed.use"))) { sender.sendMessage("§4You cannot use this command."); return true; } if(!(sender instanceof Player)) { sender.sendMessage("§4You cannot use this command from the console."); return true; } float speed = 0; try { speed = Float.parseFloat(args[0]); } catch(NumberFormatException ex) { return false; } if(speed < 1 || speed > 10) { sender.sendMessage("Speed must be between 0 and 10."); return true; } Player p = (Player) sender; if(p.isFlying()) { p.setFlySpeed(0.1f + ((speed - 1f) / 9f) * 0.9f); p.sendMessage("Set fly speed to " + speed); } else { p.setWalkSpeed(0.2f + ((speed - 1f) / 9f) * 0.8f); p.sendMessage("Set walk speed to " + speed); } return true; } }
27.285714
98
0.543194
0f2f3c129a465d29035f74bc91e7e93956276f51
603
package com.javapatterns.observerawt.mouse4; import java.awt.Frame; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class ConcreteSubject extends Frame { public ConcreteSubject() { } public static void main(String[] argv) { ConcreteSubject s = new ConcreteSubject(); s.setBounds(100, 100, 100 , 100); s.addMouseListener( new MouseAdapter() { public void mouseClicked(MouseEvent e) { System.out.println(e.getWhen()); } } ); s.show(); } /** @link dependency */ /*#MouseAdapter lnkMouseAdapter;*/ }
18.84375
44
0.655058
2a547b633cbfdad9e01cd9db4ad7d6997e1f5292
606
package io.cattle.platform.configitem.context.data.metadata.version2; import io.cattle.platform.configitem.context.data.metadata.common.ServiceMetaData; import io.cattle.platform.configitem.context.data.metadata.common.StackMetaData; import java.util.List; public class StackMetaDataVersion2 extends StackMetaData { public StackMetaDataVersion2(StackMetaData stackData) { super(stackData); } public List<ServiceMetaData> getServices() { return super.services; } public void setServices(List<ServiceMetaData> services) { super.services = services; } }
26.347826
82
0.757426
492b66c596e1a6208573e7b917e7eeacd899ea96
729
package io.lpgph.ddd.book.converter; import io.lpgph.ddd.common.BaseEnum; import lombok.extern.slf4j.Slf4j; import org.springframework.core.convert.converter.Converter; import org.springframework.data.convert.WritingConverter; /** * TODO 妥协 spring data jdbc 枚举默认使用枚举名称 即 枚举转换字符串 如果需要自定义枚举值 枚举值类型必须为字符串 * * <p>https://github.com/spring-projects/spring-data-jdbc/issues/629 * * @see org.springframework.core.convert.support.EnumToStringConverter * @see org.springframework.data.jdbc.core.convert.JdbcColumnTypes */ @Slf4j @WritingConverter public class EnumToValueConverter implements Converter<BaseEnum, String> { @Override public String convert(BaseEnum source) { return String.valueOf(source.getValue()); } }
30.375
74
0.791495
9830097075f3af2ec6e0822d66e5d5198ba8784a
46
package com.loc.framework.autoconfigure.lock;
23
45
0.847826
a500deab5f938d306d2e0acdc536727dee9af986
1,912
package br.edu.fumep.entity; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; /** * Created by arabasso on 09/05/2017. */ public class GrupoEstudoTests { private GrupoEstudo grupoEstudo; private Aluno aluno; private Usuario usuario; @Before public void inicializacao() { grupoEstudo = new GrupoEstudo(); grupoEstudo.setNome("Amigos"); grupoEstudo.setCurso("Ciência da Computação"); grupoEstudo.setMateria("Engenharia de Software II"); grupoEstudo.setProfessor("José da Silva"); grupoEstudo.setCoordenador("João dos Santos"); List<GrupoEstudoAluno> gruposEstudoAlunos = new ArrayList<>(); usuario = new Usuario(); aluno = new Aluno("Paulo", usuario); gruposEstudoAlunos.add(new GrupoEstudoAluno(grupoEstudo, aluno)); grupoEstudo.setGruposEstudoAluno(gruposEstudoAlunos); } @Test public void alunoEstaInseridoGrupo() { assertThat(grupoEstudo.alunoEstaInserido(aluno), is(true)); } @Test public void alunoNuloEstaInseridoGrupo() { assertThat(grupoEstudo.alunoEstaInserido(null), is(false)); } @Test public void temTags(){ assertThat(grupoEstudo.temTags(), is(false)); } @Test public void tagsVazia() { assertThat(grupoEstudo.getTags(), is("")); } @Test public void variasTags() { Tag tag1 = new Tag("Álgebra"); Tag tag2 = new Tag("Cálculo"); grupoEstudo.setGruposEstudoTag(new ArrayList<>()); grupoEstudo.getGruposEstudoTag().add(new GrupoEstudoTag(grupoEstudo, tag1)); grupoEstudo.getGruposEstudoTag().add(new GrupoEstudoTag(grupoEstudo, tag2)); assertThat(grupoEstudo.getTags(), is("Álgebra, Cálculo")); } }
26.191781
84
0.669456
3a43b341d6a5037f57ff443251617571371a4cae
1,472
package view; import java.util.*; import javafx.scene.control.*; import javafx.scene.layout.*; import parsing.Interpreter; public class ViewHistory extends ViewInterpretable implements Observer{ private VBox vb = new VBox(); private final ResourceBundle cssResources = ResourceBundle.getBundle("CSSClasses"); public ViewHistory(ViewType ID, Preferences savedPreferences){ super(ID, savedPreferences); init(); } @Override public void update(Observable o, Object arg) { if(arg=="NEWHISTORY"){ vb.getChildren().add(((HistoryElem) o).getTextBox()); } if(arg=="ERROR"){ Interpreter ip = (Interpreter) o; ErrorElem errorText = new ErrorElem(ip.getErrorMessage()); vb.getChildren().add(errorText.getTextBox()); } if(arg=="CLICKED"){ getInterpreter().run(((HistoryElem) o).getString()); } if (arg=="RESULT") { Interpreter ip = (Interpreter) o; ResultElem resultText = new ResultElem(ip.getReturnResult()); vb.getChildren().add(resultText.getTextBox()); } } @Override public void setInterpreter(Interpreter ip) { super.setInterpreter(ip); ip.addObserver(this); } private void init() { vb.setPrefSize(View.NARROW_WIDTH,View.WIDE_WIDTH); vb.getStyleClass().addAll(cssResources.getString("VBOX"),cssResources.getString("DISPLAYVIEW")); ScrollPane sp = new ScrollPane(vb); setPane(sp); } @Override public int getX() { return COORD02[0]; } @Override public int getY() { return COORD02[1]; } }
23.741935
98
0.70856
d6815b215369c98cdb5c5f31d9424ac17c9c67c1
199
package edu.miu.eshop.product.dto; import jdk.jfr.Timespan; import lombok.*; @Getter @Setter @ToString @NoArgsConstructor @AllArgsConstructor public class BooleanDto { private boolean bool; }
14.214286
34
0.773869
eac3abfc1552d4e52da89ccff0ec1e113ae89eea
335
package mainpackage; public class ConcreteBlockedFactory extends ContactFactory { @Override public Contact createContact(Name name, Address address, String email, Number number) { return new BlockContact(name, address, email, number); //To change body of generated methods, choose Tools | Templates. } }
33.5
128
0.728358
54a06e75f282025c2fa179b64a4d501ee08291b2
1,594
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nl.uva.cs.lobcder.auth; import lombok.Data; import javax.xml.bind.annotation.XmlRootElement; import java.util.HashSet; import java.util.Set; import javax.xml.bind.annotation.XmlRootElement; import lombok.Data; /** * * @author dvasunin */ @Data @XmlRootElement public class Permissions { private Set<String> read = new HashSet<>(); private Set<String> write = new HashSet<>(); private String owner = ""; public Permissions() { } // public Permissions(MyPrincipal mp) { // owner = mp.getUserId(); // read.addAll(mp.getRoles()); // } public Permissions(MyPrincipal mp, Permissions rootPermissions) { owner = mp.getUserId(); read.addAll(rootPermissions.getRead()); read.retainAll(mp.getRoles()); } public String getReadStr() { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : read) { if (first) { sb.append(s); first = false; } else { sb.append(',').append(s); } } return sb.toString(); } public String getWriteStr() { StringBuilder sb = new StringBuilder(); boolean first = true; for (String s : write) { if (first) { sb.append(s); first = false; } else { sb.append(',').append(s); } } return sb.toString(); } }
23.101449
69
0.552698
bfb3a629fdb526a550a10c5683fa0d0178082258
1,130
package simulator.cs.anycast.events; import simulator.cs.anycast.core.Configuration; import simulator.cs.anycast.core.Simulator; import simulator.cs.anycast.components.Connection; import simulator.cs.anycast.utils.SimulatorThread; /** * Class defines the methods any class that want to process events * need to extend. * @author carlosnatalino */ public abstract class ActiveProcess { private double time; protected Configuration configuration; public ActiveProcess() { configuration = ((SimulatorThread) Thread.currentThread()).getConfiguration(); } /** * Method called by the simulator event processor when processing this event. * @param event is the event object for the current event */ public abstract void activity(Event<Connection> event); public double getTime() { return time; } public void setTime(double time) { this.time = time; } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } public Simulator getSimulator() { return configuration.getSimulator(); } }
25.111111
86
0.715929
97a87faae1a5290e4ebb0dcbc30269a867da93fb
1,712
package nl.guuslieben.circle.components; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.Tag; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.html.H3; import com.vaadin.flow.component.html.Paragraph; import com.vaadin.flow.component.littemplate.LitTemplate; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.template.Id; import java.util.Optional; import java.util.function.Consumer; import nl.guuslieben.circle.ClientService; import nl.guuslieben.circle.common.Topic; @Tag("topic-component") @JsModule("./elements/topic.ts") public class TopicComponent extends LitTemplate { private final ClientService service; private final Topic topic; private final Consumer<Topic> onSelect; @Id private H3 name; @Id private Paragraph author; public TopicComponent(ClientService service, Topic topic, Consumer<Topic> onSelect) { this.service = service; this.topic = topic; this.onSelect = onSelect; this.name.setText(topic.getName()); this.author.setText("By: " + topic.getAuthor().getName()); this.name.addClickListener(this::onSelect); } private void onSelect(ClickEvent<H3> event) { final long id = this.topic.getId(); final Optional<Topic> topic = this.service.get("topic/" + id, Topic.class); if (topic.isPresent()) { Notification.show("Got topic '" + topic.get().getId() + "' with " + topic.get().getResponses().size() + " responses"); this.onSelect.accept(topic.get()); } else { Notification.show("Failed to get topic"); } } }
32.301887
130
0.695678
fe2f26f29bfdb2e1354b82f400777d3d6813a7d5
5,154
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.deployer; import com.android.tools.deployer.model.Apk; import com.android.tools.deployer.model.ApkEntry; import com.android.tools.deployer.model.FileDiff; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; public class ApkDiffer { public List<FileDiff> specDiff(DeploymentCacheDatabase.Entry cacheEntry, List<Apk> newApks) throws DeployerException { if (cacheEntry == null) { // TODO: We could just fall back to non-optimistic swap. throw DeployerException.remoteApkNotFound(); } // This function performs a standard diff, but additionally ensures that any resource not // currently present in the overlay is added to the list of file diffs. DiffFunction compare = (oldFile, newFile) -> { Optional<FileDiff> normalDiff = standardDiff(oldFile, newFile); // If there's a real diff, prefer to return that. if (normalDiff.isPresent()) { return normalDiff; } // If newFile == null, standardDiff would have returned a diff. We can assume // newFile is not null from this point forward. boolean inOverlay = cacheEntry .getOverlayContents() .containsFile(newFile.getQualifiedPath()); boolean isResource = newFile.getName().startsWith("res"); if (!inOverlay && isResource) { return Optional.of( new FileDiff( null, newFile, FileDiff.Status.RESOURCE_NOT_IN_OVERLAY)); } return Optional.empty(); }; return diff(cacheEntry.getApks(), newApks, compare); } public List<FileDiff> diff(List<Apk> oldApks, List<Apk> newApks) throws DeployerException { return diff(oldApks, newApks, ApkDiffer::standardDiff); } public List<FileDiff> diff(List<Apk> oldApks, List<Apk> newApks, DiffFunction compare) throws DeployerException { List<ApkEntry> oldFiles = new ArrayList<>(); Map<String, Map<String, ApkEntry>> oldMap = new HashMap<>(); groupFiles(oldApks, oldFiles, oldMap); List<ApkEntry> newFiles = new ArrayList<>(); Map<String, Map<String, ApkEntry>> newMap = new HashMap<>(); groupFiles(newApks, newFiles, newMap); if (newMap.size() != oldMap.size()) { throw DeployerException.apkCountMismatch(); } if (!newMap.keySet().equals(oldMap.keySet())) { throw DeployerException.apkNameMismatch(); } // Traverse local and remote list of crcs in order to detect what has changed in a local apk. List<FileDiff> diffs = new ArrayList<>(); for (ApkEntry newFile : newFiles) { ApkEntry oldFile = oldMap.get(newFile.getApk().name).get(newFile.getName()); compare.diff(oldFile, newFile).ifPresent(diffs::add); } for (ApkEntry oldFile : oldFiles) { ApkEntry newFile = newMap.get(oldFile.getApk().name).get(oldFile.getName()); if (newFile == null) { compare.diff(oldFile, null).ifPresent(diffs::add); } } return diffs; } private static void groupFiles( List<Apk> apks, List<ApkEntry> entries, Map<String, Map<String, ApkEntry>> map) { for (Apk apk : apks) { map.putIfAbsent(apk.name, apk.apkEntries); entries.addAll(apk.apkEntries.values()); } } private static Optional<FileDiff> standardDiff(ApkEntry oldFile, ApkEntry newFile) { FileDiff.Status status = null; if (oldFile == null) { status = FileDiff.Status.CREATED; } else if (newFile == null) { status = FileDiff.Status.DELETED; } else if (oldFile.getChecksum() != newFile.getChecksum()) { status = FileDiff.Status.MODIFIED; } if (status != null) { return Optional.of(new FileDiff(oldFile, newFile, status)); } return Optional.empty(); } @FunctionalInterface private interface DiffFunction { Optional<FileDiff> diff(ApkEntry oldFile, ApkEntry newFile); } }
38.177778
101
0.600893
69d519a783fc84b298f52e2e823160bf8fa2ea41
6,953
package jsortie.quicksort.governor.expansionist; import jsortie.RangeSorter; import jsortie.earlyexitdetector.RangeSortEarlyExitDetector; import jsortie.earlyexitdetector.TwoWayInsertionEarlyExitDetector; import jsortie.heapsort.topdown.TwoAtATimeHeapsort; import jsortie.janitors.exchanging.BranchAvoidingAlternatingCombsort; import jsortie.quicksort.collector.NullSampleCollector; import jsortie.quicksort.collector.SampleCollector; import jsortie.quicksort.expander.PartitionExpander; import jsortie.quicksort.expander.branchavoiding.LeftSkippyExpander; import jsortie.quicksort.expander.branchavoiding.RightSkippyExpander; import jsortie.quicksort.partitioner.kthstatistic.algorithm489.Afterthought489Partitioner; import jsortie.quicksort.samplesizer.SampleSizer; import jsortie.quicksort.samplesizer.SquareRootSampleSizer; import jsortie.quicksort.selector.SinglePivotSelector; import jsortie.quicksort.selector.simple.MiddleElementSelector; public class ExpansionistQuicksort implements RangeSorter { static protected RangeSortEarlyExitDetector defaultEED = new TwoWayInsertionEarlyExitDetector(); static protected SampleSizer defaultSampleSizer = new SquareRootSampleSizer(); static protected SinglePivotSelector defaultSelector = new MiddleElementSelector(); static protected SampleCollector defaultCollector = new NullSampleCollector(); static protected SamplePartitioner defaultPartitioner = new MedianPartitioner ( new Afterthought489Partitioner() ); static protected PartitionExpander defaultLeftExpander = new LeftSkippyExpander(); static protected PartitionExpander defaultRightExpander = new RightSkippyExpander(); static protected RangeSorter defaultJanitor = new BranchAvoidingAlternatingCombsort(1.4, 256); static protected int defaultJanitorThreshold = 512; static protected RangeSorter defaultLastResort = new TwoAtATimeHeapsort(); protected RangeSortEarlyExitDetector eed; protected SampleSizer sizer; protected SinglePivotSelector selector; protected SampleCollector collector; protected SamplePartitioner partitioner; protected PartitionExpander leftExpander; protected PartitionExpander rightExpander; protected int janitorThreshold; protected RangeSorter janitor; protected RangeSorter lastResort; public ExpansionistQuicksort() { eed = defaultEED; sizer = defaultSampleSizer; collector = defaultCollector; selector = defaultSelector; partitioner = defaultPartitioner; leftExpander = defaultLeftExpander; rightExpander = defaultRightExpander; janitorThreshold = defaultJanitorThreshold; janitor = defaultJanitor; lastResort = defaultLastResort; } public ExpansionistQuicksort ( RangeSortEarlyExitDetector detector , SampleCollector collectorToUse , SamplePartitioner samplePartitionerToUse , PartitionExpander leftExpanderToUse , PartitionExpander rightExpanderToUse , int janitorThresholdToUse , RangeSorter janitorToUse , RangeSorter sortOfLastResort) { eed = detector; sizer = defaultSampleSizer; collector = collectorToUse; selector = defaultSelector; partitioner = samplePartitionerToUse; leftExpander = leftExpanderToUse; rightExpander = rightExpanderToUse; janitorThreshold = janitorThresholdToUse; janitor = janitorToUse; lastResort = sortOfLastResort; } public String toString() { return this.getClass().getSimpleName() + "( " + eed.toString() + ", " + sizer.toString() + ", " + collector.toString() + ", " + selector.toString() + ", " + partitioner.toString() + ", " + leftExpander.toString() + ", " + rightExpander.toString() + ", " + janitorThreshold + ", " + janitor.toString() + ", " + lastResort.toString() + ")"; } public void setSamplePartitioner (SamplePartitioner sp) { if (sp==null) { throw new IllegalArgumentException ( "Cannot pass null to setSamplePartitioner"); } partitioner = sp; } @Override public void sortRange ( int[] vArray, int start, int stop) { int maxDepth = getMaxPartitioningDepth(stop-start); sortRangeWith ( vArray, start, start , stop, stop, leftExpander, maxDepth); } protected int getMaxPartitioningDepth ( int m) { return (int) Math.floor ( (Math.log(m+1) * 4.0) ); } public void sortRangeWith ( int[] vArray, int originalStart , int start, int stop, int originalStop , PartitionExpander expander, int maxDepth) { for ( int m=stop-start ; janitorThreshold < m ; m=stop-start) { if ( originalStart < start && stop < originalStop ) { if ( vArray[start-1] == vArray[stop] ) { return; } } if ( eed.exitEarlyIfSorted ( vArray, start, stop ) ) { return; } if (maxDepth<0) { lastResort.sortRange(vArray, start, stop); return; } int c = sizer.getSampleSize(m, 2); int pivotIndex, sampleStart, sampleStop; if ( c < 2 || m <= c ) { pivotIndex = selector.selectPivotIndex ( vArray, start, stop ); sampleStart = pivotIndex; sampleStop = sampleStart + 1; } else { int targetIndex = start + (m>>1); sampleStart = targetIndex - (c>>1); sampleStop = sampleStart + c; if (stop<sampleStop) { sampleStop = stop; } collector.moveSampleToPosition ( vArray, start, stop , sampleStart, sampleStop ); pivotIndex = partitioner.partitionSampleRange ( vArray, start, stop, targetIndex , sampleStart, sampleStop); } int split = expander.expandPartition ( vArray, start, sampleStart , pivotIndex, sampleStop, stop); --maxDepth; if (split-start < stop-split) { sortRangeWith ( vArray, originalStart, start , split, originalStop , leftExpander, maxDepth); start = split + 1; expander = rightExpander; } else { sortRangeWith ( vArray, originalStart, split+1 , stop, originalStop , rightExpander, maxDepth); stop = split; expander = leftExpander; } } if ( originalStart < start && stop < originalStop) { if (vArray[start-1] == vArray[stop]) { return; } } if ( eed.exitEarlyIfSorted ( vArray, start, stop ) ) { return; } janitor.sortRange(vArray, start, stop); } }
34.939698
90
0.653243
6ee7d355293bdabbf2f4c631b14865dea65498fe
2,219
package org.jesperancinha.jtd.jee.app1.domain; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.SystemException; import javax.transaction.UserTransaction; public class ManagedSessionBeanAlbumDao implements AlbumSessionDao { @Inject private EntityManager entityManager; @Inject private UserTransaction utx; @Inject private FacesContext facesContext; @Override public Album realUpdateAlbum(Album album) { try { utx.begin(); final Album persistedAlbum = entityManager.merge(album); utx.commit(); return persistedAlbum; } catch (NotSupportedException e) { e.printStackTrace(); } catch (SystemException e) { e.printStackTrace(); } catch (HeuristicMixedException e) { e.printStackTrace(); } catch (HeuristicRollbackException e) { e.printStackTrace(); } catch (RollbackException e) { } catch (Exception e) { String errorMessage = e.getMessage(); FacesMessage m = new FacesMessage(FacesMessage.SEVERITY_ERROR, errorMessage, "Registration unsuccessful, you cannot update an id"); facesContext.addMessage(null, m); } return album; } @Override public Album getAlbum(Long id) { Album album = null; try { utx.begin(); album = entityManager.find(Album.class, id); utx.commit(); } catch (NotSupportedException e) { e.printStackTrace(); } catch (SystemException e) { e.printStackTrace(); } catch (HeuristicMixedException e) { e.printStackTrace(); } catch (HeuristicRollbackException e) { e.printStackTrace(); } catch (RollbackException e) { e.printStackTrace(); } return album; } }
31.253521
143
0.644885
d91684cfed3ad357e609f75268f13e8bea2b5f21
2,930
/* Annot8 (annot8.io) - Licensed under Apache-2.0. */ package io.annot8.components.text.processors; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.junit.jupiter.api.Test; import io.annot8.common.data.bounds.ContentBounds; import io.annot8.common.data.content.Text; import io.annot8.conventions.AnnotationTypes; import io.annot8.conventions.PropertyKeys; import io.annot8.core.annotations.Annotation; import io.annot8.core.components.Processor; import io.annot8.core.context.Context; import io.annot8.core.data.Item; import io.annot8.core.exceptions.Annot8Exception; import io.annot8.core.stores.AnnotationStore; import io.annot8.testing.testimpl.TestContext; import io.annot8.testing.testimpl.TestItem; import io.annot8.testing.testimpl.content.TestStringContent; public class DetectLanguageTest { @Test public void testDetectLanguageEnglish() throws Annot8Exception { // Taken from Pride and Prejudice doTest( "It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife.\n" + "However little known the feelings or views of such a man may be on his first entering a neighbourhood, this truth is so " + "well fixed in the minds of the surrounding families, that he is considered the rightful property of some one or other of their daughters.", "en"); } @Test public void testDetectLanguageGerman() throws Annot8Exception { // Taken from Der Mord an der Jungfrau doTest( "Immerzu traurig, Amaryllis! sollten dich die jungen Herrn im Stich\n" + "gelassen haben, deine Blüten welk, deine Wohlgerüche ausgehaucht sein? Ließ\n" + "Atys, das göttliche Kind, von dir mit seinen eitlen Liebkosungen?", "de"); } private void doTest(String sourceText, String expectedLanguage) throws Annot8Exception { try (Processor p = new DetectLanguage()) { Item item = new TestItem(); Context context = new TestContext(); p.configure(context); Text content = item.create(TestStringContent.class).withName("test").withData(sourceText).save(); p.process(item); AnnotationStore store = content.getAnnotations(); List<Annotation> annotations = store.getAll().collect(Collectors.toList()); assertEquals(1, annotations.size()); Annotation a = annotations.get(0); assertEquals(ContentBounds.getInstance(), a.getBounds()); assertEquals(AnnotationTypes.ANNOTATION_TYPE_LANGUAGE, a.getType()); assertEquals(1, a.getProperties().getAll().size()); Optional<Object> o = a.getProperties().get(PropertyKeys.PROPERTY_KEY_LANGUAGE); assertTrue(o.isPresent()); assertEquals(expectedLanguage, o.get()); } } }
38.051948
154
0.730375
a520a522927ac83b6cb481dd77ff4d19ebab45e9
626
package com.wedian.site.modules.weixin.web; import com.wedian.site.common.web.BaseController; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by wanliang_mvp on 2015/7/25. */ @Controller @RequestMapping("/weixin") public class WxMessageContorller extends BaseController { @RequestMapping(value = "/message/index", method = RequestMethod.GET) public String index(ModelMap model) { return "weixin/message/index.ftl"; } }
28.454545
73
0.776358
28c1efc49a89242313ad55552bf247ac86c8ded7
1,379
/* * Copyright 2018-2020 The Code Department. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.tcdng.unify.core.database; import com.tcdng.unify.core.constant.ForceConstraints; import com.tcdng.unify.core.constant.PrintFormat; /** * Data source manager options. * * @author Lateef Ojulari * @since 1.0 */ public class DataSourceManagerOptions { private PrintFormat printFormat; private ForceConstraints forceConstraints; public DataSourceManagerOptions(PrintFormat printFormat, ForceConstraints forceConstraints) { this.printFormat = printFormat; this.forceConstraints = forceConstraints; } public PrintFormat getPrintFormat() { return printFormat; } public ForceConstraints getForceConstraints() { return forceConstraints; } }
28.729167
98
0.711385
6431376252b02816ea3771e2bb5e926e57478307
394
package com.cjy.mall.ware.dao; import com.cjy.mall.ware.entity.WareOrderTaskDetailEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 库存工作单 * * @author chenjy01 * @email chenjunyu102@126.com * @date 2020-08-20 15:30:40 */ @Mapper public interface WareOrderTaskDetailDao extends BaseMapper<WareOrderTaskDetailEntity> { }
21.888889
87
0.77665
6d6272ddcb2e7c7a1967328ebdf50d46496b37bb
1,545
/******************************************************************************* * Copyright (c) 2004 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.model.api; import org.eclipse.birt.report.model.api.metadata.DimensionValue; /** * Provides the absolute dimension value for absolute font size constant. */ public interface IAbsoluteFontSizeValueProvider { /** * Returns the dimension value of absolute font size constant. These * constants are defined in <code>DesignChoiceConstants</code>. And the * absolute value of the following should be provided: * <ul> * <li><code>FONT_SIZE_XX_SMALL</code> * <li><code>FONT_SIZE_X_SMALL</code> * <li><code>FONT_SIZE_SMALL</code> * <li><code>FONT_SIZE_MEDIUM</code> * <li><code>FONT_SIZE_LARGE</code> * <li><code>FONT_SIZE_X_LARGE</code> * <li><code>FONT_SIZE_XX_LARGE</code> * </ul> * * @param fontSizeConstant * the absolute font size constant * @return the absolute dimension value. The unit of the returned value * should be one of px, in, cm, mm, and pt. */ public DimensionValue getValueOf( String fontSizeConstant ); }
34.333333
81
0.649191
eb238ac80d9a0026777bb75877c7c102ab6af0cf
2,844
package com.compuware.ispw.restapi; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; /** * A Java bean that holds any possible context path related parameters * Note: this method is using reflection to set object properties, so if you need some transformation * you need do it in get() method instead of set() method. * * @author Sam Zhou * */ public class IspwContextPathBean { private String application; private String srid; private String assignmentId; private String releaseId; private String requestId; private String setId; private String level; private String taskId; private String mname; private String mtype; private String action; private String approver; private String checkout = Constants.FALSE; @Override public String toString() { return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); } public String getSrid() { return srid; } public void setSrid(String srid) { this.srid = srid; } public String getAssignmentId() { return assignmentId; } public void setAssignmentId(String assignmentId) { this.assignmentId = assignmentId; } public String getReleaseId() { return releaseId; } public void setReleaseId(String releaseId) { this.releaseId = releaseId; } public String getRequestId() { return requestId; } public void setRequestId(String requestId) { this.requestId = requestId; } public String getSetId() { return setId; } public void setSetId(String setId) { this.setId = StringUtils.trimToEmpty(setId).toUpperCase(); } public String getLevel() { return level; } public void setLevel(String level) { this.level = level; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getMname() { return mname; } public void setMname(String mname) { this.mname = mname; } public String getMtype() { return mtype; } public void setMtype(String mtype) { this.mtype = mtype; } public String getCheckout() { return checkout; } public void setCheckout(String checkout) { this.checkout = checkout; } public String getAction() { return action; } public void setAction(String action) { this.action = StringUtils.trimToEmpty(action).toLowerCase(); } public String getApprover() { return approver; } public void setApprover(String approver) { this.approver = StringUtils.trimToEmpty(approver).toUpperCase(); } public String getApplication() { return this.application; } public void setApplication(String application) { this.application = application; } }
21.709924
102
0.701125
cd287c6752dccd18e71c0d468b5ed63c7e5129bc
1,955
import java.util.HashMap; import java.util.Map; /** * Given a string, find the length of the longest substring without repeating characters. * * Example 1: * * Input: "abcabcbb" * Output: 3 * Explanation: The answer is "abc", with the length of 3. * Example 2: * * Input: "bbbbb" * Output: 1 * Explanation: The answer is "b", with the length of 1. * Example 3: * * Input: "pwwkew" * Output: 3 * Explanation: The answer is "wke", with the length of 3. * Note that the answer must be a substring, "pwke" is a subsequence and not a substring. */ public class Problem3 { /** * Method to get length of longest substring without any repeating character * Algo: * We use a sliding window approach. * 1. Keep two variables i & j -> i is used to keep track of the index where the repeated character occurs and j * is used to traverse the string array * 2. The longest substring without any repeating character is => j - i * where, * j = current index of char in string * i = previous index of the current char if it is repeated * * 3. Traverse the array only once, and get the max of all non-repeated substrings * * @param s */ private static int lengthOfLongestSubstring(String s) { int maxLength = -1; Map<Character, Integer> charIndexMap = new HashMap<>(); for (int i = 0, j = 0; j < s.length(); j++) { char ch = s.charAt(j); if (charIndexMap.containsKey(ch)) { i = Math.max(i, charIndexMap.get(ch)); } maxLength = Math.max(maxLength, j - i + 1); charIndexMap.put(ch, j + 1); } return maxLength; } /** * Main method to test cases * * @param args */ public static void main(String[] args) { String s = "abcabcabc"; System.out.println(lengthOfLongestSubstring(s)); } }
29.621212
116
0.595908
716fb381f208d0f51da3480d9159e64248fdb16a
562
package com.bug1312.cloudyporkchops.common.item; import com.bug1312.cloudyporkchops.util.enums.RenderDimension; public interface IItem3D { public default RenderDimension handRendering() { return RenderDimension.THREE; } public default RenderDimension inventoryRendering() { return RenderDimension.TWO; } public default RenderDimension hatRendering() { return RenderDimension.THREE; } public default RenderDimension itemEntityRendering() { return RenderDimension.TWO; } public default RenderDimension itemFrameRendering() { return RenderDimension.TWO; } }
46.833333
85
0.823843
d5577285021e5d51d5a235673926f654fa4ffd5e
375
package jp.ac.ems.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; @Controller public class LoginController { @GetMapping(path="login") String login() { return "login"; } @GetMapping(path="top") String top() { return "top"; } }
18.75
59
0.754667
6b51f9e394bea59bf02d0d5a1b5862eaebdeb337
1,174
package me.retrodaredevil.solarthing.graphql.packets; import me.retrodaredevil.solarthing.packets.Packet; import me.retrodaredevil.solarthing.packets.collection.FragmentedPacketGroup; import java.util.ArrayList; import java.util.List; public final class PacketUtil { private PacketUtil(){ throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") public static <T> List<PacketNode<T>> convertPackets(List<? extends FragmentedPacketGroup> packetGroups, Class<T> acceptClass, PacketFilter filter){ List<PacketNode<T>> r = new ArrayList<>(); for(FragmentedPacketGroup packetGroup : packetGroups) { for(Packet packet : packetGroup.getPackets()) { if (!acceptClass.isInstance(packet)) { continue; } int fragmentId = packetGroup.getFragmentId(packet); String sourceId = packetGroup.getSourceId(packet); Long dateMillis = packetGroup.getDateMillis(packet); if(dateMillis == null) { dateMillis = packetGroup.getDateMillis(); } PacketNode<T> packetNode = new PacketNode<>((T) packet, dateMillis, sourceId, fragmentId); if(filter.keep(packetNode)) { r.add(packetNode); } } } return r; } }
33.542857
149
0.739353
4f97b8e657d184c12f02b645c289fe23d1d1b7ff
6,683
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.jooby.mongodb; import static java.util.Objects.requireNonNull; import java.util.function.BiConsumer; import java.util.function.Consumer; import org.jooby.Env; import org.jooby.Env.ServiceKey; import org.jooby.internal.mongodb.AutoIncID; import org.jooby.internal.mongodb.GuiceObjectFactory; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.EntityInterceptor; import org.mongodb.morphia.Morphia; import org.mongodb.morphia.annotations.PrePersist; import org.mongodb.morphia.mapping.Mapper; import com.google.inject.Binder; import com.typesafe.config.Config; /** * Extends {@link Mongodb} with object-document mapping via {@link Morphia}. * * Exposes {@link Morphia} and {@link Datastore} services. * * <h1>usage</h1> * * <p> * application.conf: * </p> * * <pre> * db = "mongodb://localhost/mydb" * </pre> * * <pre> * { * use(new Monphia()); * * get("/", req {@literal ->} { * Datastore ds = req.require(Datastore.class); * // work with mydb datastore * }); * } * </pre> * * <h1>options</h1> * <h2>morphia callback</h2> * <p> * The {@link Morphia} callback let you map classes and/or set mapper options. * </p> * * <pre> * { * use(new Monphia() * .doWith((morphia, config) {@literal ->} { * // work with morphia * morphia.map(MyObject.class); * }); * ); * } * </pre> * * For more detailed information, check * <a href="https://github.com/mongodb/morphia/wiki/MappingObjects">here</a> * * <h2>datastore callback</h2> * <p> * This {@link Datastore} callback is executed only once, it's perfect for checking indexes: * </p> * * <pre> * { * use(new Monphia() * .doWith(datastore {@literal ->} { * // work with datastore * datastore.ensureIndexes(); * datastore.ensureCap(); * }); * ); * } * </pre> * * For more detailed information, check * <a href="https://github.com/mongodb/morphia/wiki/Datastore#ensure-indexes-and-caps">here</a> * * <h2>auto-incremental ID</h2> * <p> * This modules comes with auto-incremental ID generation. * </p> * <p> * usage: * </p> * <pre> * { * use(new Monphia().with(IdGen.GLOBAL); // or IdGen.LOCAL * } * </pre> * <p> * ID must be of type: {@link Long} and annotated with {@link GeneratedValue}: * </p> * <pre> * &#64;Entity * public class MyEntity { * &#64;Id &#64;GeneratedValue Long id; * } * </pre> * * <p> * There two ID gen: * </p> * <ul> * <li>GLOBAL: generates a global and unique ID regardless of entity type.</li> * <li>LOCAL: generates an unique ID per entity type.</li> * </ul> * * <h1>entity listeners</h1> * * <p> * Guice will create and inject entity listeners (when need it). * </p> * * <pre> * public class MyListener { * * private Service service; * * &#64;Inject * public MyListener(Service service) { * this.service = service; * } * * &#64;PreLoad void preLoad(MyObject object) { * service.doSomething(object); * } * * } * </pre> * * <p> * NOTE: ONLY Constructor injection is supported. * </p> * * @author edgar * @since 0.5.0 */ public class Monphia extends Mongodb { private BiConsumer<Morphia, Config> morphiaCbck; private Consumer<Datastore> callback; private IdGen gen = null; /** * Creates a new {@link Monphia} module. * * @param db Name of the property with the connection URI. */ public Monphia(final String db) { super(db); } /** * Creates a new {@link Monphia} using the default property: <code>db</code>. */ public Monphia() { } /** * Morphia startup callback, from here you can map classes, set mapper options, etc.. * * @param callback Morphia callback. * @return This module. */ public Monphia doWith(final BiConsumer<Morphia, Config> callback) { this.morphiaCbck = requireNonNull(callback, "Mapper callback is required."); return this; } /** * {@link Datastore} startup callback, from here you can call {@link Datastore#ensureIndexes()}. * * @param callback Datastore callback. * @return This module. */ public Monphia doWith(final Consumer<Datastore> callback) { this.callback = requireNonNull(callback, "Datastore callback is required."); return this; } /** * <p> * Setup up an {@link EntityInterceptor} on {@link PrePersist} events that generates an * incremental ID. * </p> * * Usage: * <pre> * { * use(new Monphia().with(IdGen.GLOBAL); * } * </pre> * * <p> * ID must be of type: {@link Long} and annotated with {@link GeneratedValue}: * </p> * <pre> * &#64;Entity * public class MyEntity { * &#64;Id &#64;GeneratedValue Long id; * } * </pre> * * @param gen an {@link IdGen} strategy * @return This module. */ public Monphia with(final IdGen gen) { this.gen = requireNonNull(gen, "ID Gen is required."); return this; } @Override public void configure(final Env env, final Config conf, final Binder binder) { configure(env, conf, binder, (uri, client) -> { String db = uri.getDatabase(); Mapper mapper = new Mapper(); Morphia morphia = new Morphia(mapper); if (this.morphiaCbck != null) { this.morphiaCbck.accept(morphia, conf); } Datastore datastore = morphia.createDatastore(client, mapper, db); if (gen != null) { mapper.addInterceptor(new AutoIncID(datastore, gen)); } if (callback != null) { callback.accept(datastore); } ServiceKey serviceKey = env.serviceKey(); serviceKey.generate(Morphia.class, db, k -> binder.bind(k).toInstance(morphia)); serviceKey.generate(Datastore.class, db, k -> binder.bind(k).toInstance(datastore)); env.onStart(registry -> new GuiceObjectFactory(registry, morphia)); }); } }
24.479853
98
0.637438
f35044b27c49a922f939c0df15c663c3025727bc
165
package de.adito.irradiate; /** * @author j.boesl, 29.12.2015 */ public interface IDetector<T> { void hit(T pValue); void failure(Throwable pThrowable); }
11.785714
37
0.678788
21d22c5fe8ca6561752d5a43cf91bc76c6b0e036
711
package leetCode; import static org.testng.Assert.assertEquals; import org.testng.annotations.Test; public class LeetCode628Test { @Test public void maximumProduct() { LeetCode628 l = new LeetCode628(); assertEquals(l.maximumProduct(new int[]{1, 2, 3}), 6); assertEquals(l.maximumProduct(new int[]{1, 2, 3, 4, 5, 6}), 120); assertEquals(l.maximumProduct(new int[]{1, 2, 3, -4, -5, 6}), 120); assertEquals(l.maximumProduct(new int[]{1, 2, -3, 4, -5, 6}), 90); assertEquals(l.maximumProduct(new int[]{-1, 2, 3, 4, 5, -6}), 60); assertEquals(l.maximumProduct(new int[]{-1, -2, -3, -4, -5, -6}), -6); assertEquals(l.maximumProduct(new int[]{-1, -2, -3, 0, 5, 6}), 36); } }
33.857143
74
0.630098
5a0c2e1fa8a3607d5937125d283dc10d6a158db6
299
package Game; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; public class WinningScreen { public void paint(Graphics g, int Winner) { g.setColor(Color.WHITE); g.setFont(new Font("TimesRoman", Font.BOLD, 20)); g.drawString("Player "+ Winner + " Wins",110,120); } }
19.933333
52
0.705686
2051826e66d7ce94a43d9938f778499b55d91846
580
package au.com.origin.snapshots.docs; import au.com.origin.snapshots.Expect; import au.com.origin.snapshots.annotations.UseSnapshotConfig; import au.com.origin.snapshots.junit5.SnapshotExtension; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(SnapshotExtension.class) // apply your custom snapshot configuration to this test class @UseSnapshotConfig(LowercaseToStringSnapshotConfig.class) public class CustomSnapshotConfigExample { @Test public void myTest(Expect expect) { expect.toMatchSnapshot("hello world"); } }
32.222222
62
0.817241
5bc32ad7742dd79e2186f7e6dc270f33ce88c99c
724
import java.util.ArrayList; import java.util.Arrays; import java.util.Locale; import java.util.Scanner; public class Index_of_Letters { public static void main(String[] args) { Locale.setDefault(Locale.ROOT); Scanner scanner = new Scanner(System.in); ArrayList<Character> letterArray = new ArrayList<>(); char letter = 'a'; for (int i = 0; i < 26; i++) { letterArray.add(letter); letter++; } String word = scanner.nextLine(); for(int i = 0; i < word.length(); i++){ char c = word.charAt(i); int index = letterArray.indexOf(c); System.out.printf("%s -> %d%n", c, index); } } }
23.354839
61
0.553867
6459c9f81bfaaa04aceabd579d9f64280484c5b1
450
package com.ronja.crm.ronjaserver.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.List; public class StatusValidator implements ConstraintValidator<Status, String> { private final List<String> statuses = List.of("ACTIVE", "INACTIVE"); @Override public boolean isValid(String value, ConstraintValidatorContext context) { return statuses.contains(value); } }
28.125
77
0.797778
f11b675a33a8cce0516adeec6c27dfcb5408ed61
5,572
package org.xmlet.xsdparser; import org.junit.Assert; import org.junit.Test; import org.xmlet.xsdparser.core.XsdParser; import org.xmlet.xsdparser.xsdelements.*; import java.net.URL; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class IssuesTest { private static final List<XsdElement> elements; private static final List<XsdSchema> schemas; private static final XsdParser parser; static { parser = new XsdParser(getFilePath()); schemas = parser.getResultXsdSchemas().collect(Collectors.toList()); elements = parser.getResultXsdElements().collect(Collectors.toList()); } @Test public void testSubstitutionGroup(){ List<XsdElement> elements = parser.getResultXsdElements().collect(Collectors.toList()); Optional<XsdElement> navnOptional = elements.stream().filter(element -> element.getName().equals("navn")).findFirst(); Optional<XsdElement> kundeOptional = elements.stream().filter(element -> element.getName().equals("kunde")).findFirst(); Assert.assertTrue(navnOptional.isPresent()); Assert.assertTrue(kundeOptional.isPresent()); XsdElement navnElement = navnOptional.get().getXsdSubstitutionGroup(); XsdElement kundeElement = kundeOptional.get().getXsdSubstitutionGroup(); Assert.assertEquals("xsd:string", navnElement.getType()); XsdComplexType kundeComplexType = kundeElement.getXsdComplexType(); Assert.assertNotNull(kundeComplexType); Assert.assertEquals("custinfo", kundeComplexType.getName()); XsdSequence custinfoSequence = kundeComplexType.getChildAsSequence(); Assert.assertNotNull(custinfoSequence); List<XsdElement> sequenceElements = custinfoSequence.getChildrenElements().collect(Collectors.toList()); Assert.assertNotNull(sequenceElements); Assert.assertEquals(1, sequenceElements.size()); XsdElement nameElement = sequenceElements.get(0); Assert.assertEquals(navnElement.getName(), nameElement.getName()); Assert.assertEquals(navnElement.getType(), nameElement.getType()); } @Test public void testDocumentationWithCDATA(){ Optional<XsdElement> someElementOpt = elements.stream().filter(e -> e.getName().equals("someElement")).findFirst(); Assert.assertTrue(someElementOpt.isPresent()); XsdElement someElement = someElementOpt.get(); XsdAnnotation annotation = someElement.getAnnotation(); List<XsdDocumentation> documentations = annotation.getDocumentations(); XsdDocumentation xsdDocumentation = documentations.get(0); Assert.assertEquals("<![CDATA[\r\n" + "\t\t\tCDATA line 1\r\n" + "\t\t\tCDATA line 2\r\n" + "\t\t\t]]>",xsdDocumentation.getContent()); } @Test public void testIssue20(){ Optional<XsdSchema> issuesSchemaOpt = schemas.stream().findFirst(); Assert.assertTrue(issuesSchemaOpt.isPresent()); XsdSchema issuesSchema = issuesSchemaOpt.get(); Optional<XsdComplexType> fooTypeComplexTypeOpt = issuesSchema.getChildrenComplexTypes().filter(xsdComplexType -> xsdComplexType.getName().equals("fooType")).findFirst(); Assert.assertTrue(fooTypeComplexTypeOpt.isPresent()); XsdSequence fooTypeSequence = fooTypeComplexTypeOpt.get().getChildAsSequence(); Assert.assertNotNull(fooTypeSequence); Optional<XsdElement> sequenceElementOpt = fooTypeSequence.getChildrenElements().filter(elem -> elem.getName().equals("id")).findFirst(); Assert.assertTrue(sequenceElementOpt.isPresent()); XsdElement sequenceElement = sequenceElementOpt.get(); XsdComplexType complexType = sequenceElement.getXsdComplexType(); Assert.assertNull(complexType); XsdSimpleType simpleType = sequenceElement.getXsdSimpleType(); Assert.assertNotNull(simpleType); } @Test public void testIssue21(){ Optional<XsdElement> hoursPerWeekOpt = elements.stream().filter(e -> e.getName().equals("hoursPerWeek")).findFirst(); Assert.assertTrue(hoursPerWeekOpt.isPresent()); XsdElement hoursPerWeek = hoursPerWeekOpt.get(); String type = hoursPerWeek.getAttributesMap().get(XsdAbstractElement.TYPE_TAG); String typeOfMethod = hoursPerWeek.getType(); Assert.assertEquals("xsd:double", type); Assert.assertEquals("xsd:double", typeOfMethod); XsdNamedElements xsdType = hoursPerWeek.getTypeAsXsd(); XsdComplexType xsdComplexType = hoursPerWeek.getTypeAsComplexType(); XsdSimpleType xsdSimpleType = hoursPerWeek.getTypeAsSimpleType(); XsdBuiltInDataType xsdBuiltInDataType = hoursPerWeek.getTypeAsBuiltInDataType(); Assert.assertEquals("xsd:double", xsdType.getRawName()); Assert.assertEquals("xsd:double", xsdBuiltInDataType.getRawName()); Assert.assertNull(xsdComplexType); Assert.assertNull(xsdSimpleType); Assert.assertEquals(hoursPerWeek, xsdBuiltInDataType.getParent()); } /** * @return Obtains the filePath of the file associated with this test class. */ private static String getFilePath(){ URL resource = HtmlParseTest.class.getClassLoader().getResource("issues.xsd"); if (resource != null){ return resource.getPath(); } else { throw new RuntimeException("The issues.xsd file is missing from the XsdParser resource folder."); } } }
38.965035
177
0.703877
260ec8bf8c6af5a7b00c04fe003f8267fd669101
306
package it.mcella.jcr.oak.upgrade.repository.firstversion.node.root; import it.mcella.jcr.oak.upgrade.repository.JcrNode; public class OakRootNodeFactory implements JcrRootNodeFactory { @Override public JcrRootNode createFrom(JcrNode jcrNode) { return new OakRootNode(jcrNode); } }
23.538462
68
0.767974
de5017b87f0c4d553179a170c3e8c9706638e383
462
package pulse.util; /** * A listener used by {@code PropertyHolder}s to track changes with the * associated {@code Propert}ies. */ public interface PropertyHolderListener { /** * This event is triggered by any {@code PropertyHolder}, the properties of * which have been changed. * * @param event the event associated with actions taken on a * {@code Property}. */ public void onPropertyChanged(PropertyEvent event); }
24.315789
79
0.679654
ddd3f877fc2799b894de5f48fa6dc85fbc69aa34
4,558
package com.cda.jee.crypto.dao.impl; import com.cda.jee.crypto.dao.CryptoCurrencyDao; import com.cda.jee.crypto.dao.DaoConnection; import com.cda.jee.crypto.dao.exception.DaoException; import com.cda.jee.crypto.model.CryptoCurrency; import java.sql.*; import java.util.ArrayList; import java.util.List; import java.util.Optional; public class CryptoCurrencyImpl implements CryptoCurrencyDao { Connection conn = DaoConnection.getInstance().getConnection(); PreparedStatement ps; ResultSet rs; @Override public Optional<CryptoCurrency> get(int id) throws DaoException { CryptoCurrency cryptoCurrency = null; try { ps = conn.prepareStatement("select * from cryptoCurrency where idCrypto = ?"); ps.setInt(1, id); rs = ps.executeQuery(); if (rs.next()) { cryptoCurrency = new CryptoCurrency( rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getInt(5), rs.getString(6), rs.getTimestamp(7).toLocalDateTime() ); } } catch (SQLException throwables) { throwables.printStackTrace(); } return Optional.ofNullable(cryptoCurrency); } @Override public List<CryptoCurrency> getAll() throws DaoException { List<CryptoCurrency> cryptoCurrencies = new ArrayList<>(); try { ps = conn.prepareStatement( "select * from cryptoCurrency" ); rs = ps.executeQuery(); while (rs.next()) { CryptoCurrency cc = new CryptoCurrency( rs.getInt(1), rs.getString(2), rs.getString(3), rs.getInt(4), rs.getDouble(5), rs.getString(6), rs.getTimestamp(7).toLocalDateTime() ); cryptoCurrencies.add(cc); } } catch (SQLException throwables) { throwables.printStackTrace(); } return cryptoCurrencies; } @Override public void save(CryptoCurrency cc) throws DaoException { try { ps = conn.prepareStatement("insert into cryptoCurrency (name, symbol,delta, currentPrice, imageUrl, lastUpdated) values(?,?,?,?,?,?)", PreparedStatement.RETURN_GENERATED_KEYS); rs.getInt(1); rs.getString(2); rs.getString(3); rs.getInt(4); rs.getInt(5); rs.getString(6); rs.getTimestamp(7).toLocalDateTime(); ps.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } } @Override public void update(CryptoCurrency cryptoCurrency, int id) throws DaoException { try { ps = conn.prepareStatement("update cryptoCurrency set name = ?, symbol = ?, currentPrice = ?, imageUrl = ?, lastUpdated = ? where idCrypto = ?"); ps.setString(1, cryptoCurrency.getName()); ps.setString(2, cryptoCurrency.getSymbol()); ps.setDouble(3, cryptoCurrency.getCurrentPrice()); ps.setString(4, cryptoCurrency.getImageUrl()); ps.setTimestamp(5, Timestamp.valueOf(cryptoCurrency.getLastUpdated())); ps.setInt(6, id); ps.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } } public void updateDelta(int idCrypto, double newDelta) { try { ps = conn.prepareStatement("update cryptoCurrency set delta = ? where idCrypto = ?"); ps.setDouble(1, newDelta); ps.setInt(2, idCrypto); ps.executeUpdate(); } catch (SQLException throwables) { throwables.printStackTrace(); } } @Override public boolean delete(int id) throws DaoException { boolean res = false; try { ps = conn.prepareStatement("delete from cryptoCurrency where idCrypto = ?"); ps.setInt(1, id); ps.executeUpdate(); res = true; } catch (SQLException throwables) { throwables.printStackTrace(); } return res; } @Override public ArrayList<Integer> delta() { return null; } }
32.791367
188
0.550461
ee2ea5108bcd222fad2a7c34af47ebcb5dc11a86
165
package ug.or.nda.dao; import ug.or.nda.entities.PaymentNotification; public interface PaymentNotificationDAOI extends GenericDAOI<PaymentNotification, Long> { }
20.625
89
0.824242
3f1bb93ca5b35be1a88780e235ea7fb33b5c35c9
22,801
/* * ButtonInternalImplTest.java * * Copyright (c) 2018 Button, Inc. (https://usebutton.com) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.usebutton.merchant; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import com.usebutton.merchant.exception.ApplicationIdNotFoundException; import com.usebutton.merchant.exception.ButtonNetworkException; import com.usebutton.merchant.module.Features; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import java.util.concurrent.Executor; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ButtonInternalImplTest { private ButtonInternalImpl buttonInternal; private Executor executor; @Before public void setUp() { executor = new TestMainThreadExecutor(); buttonInternal = new ButtonInternalImpl(executor); } @Test public void configure_saveApplicationIdInMemory() { ButtonRepository buttonRepository = mock(ButtonRepository.class); buttonInternal.configure(buttonRepository, "app-abcdef1234567890"); verify(buttonRepository).setApplicationId("app-abcdef1234567890"); } @Test public void getApplicationId_retrieveFromRepository() { ButtonRepository buttonRepository = mock(ButtonRepository.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); String applicationId = buttonInternal.getApplicationId(buttonRepository); assertEquals("valid_application_id", applicationId); } @Test public void trackIncomingIntent_withValidData_persistUrl() { ButtonRepository buttonRepository = mock(ButtonRepository.class); Intent intent = mock(Intent.class); Uri uri = mock(Uri.class); Uri.Builder builder = mock(Uri.Builder.class); when(intent.getData()).thenReturn(uri); when(uri.buildUpon()).thenReturn(builder); when(uri.buildUpon().clearQuery()).thenReturn(builder); when(builder.build()).thenReturn(uri); when(uri.getQueryParameter("btn_ref")).thenReturn("valid_source_token"); buttonInternal.trackIncomingIntent(mock(TestManager.class), buttonRepository, mock(DeviceManager.class), mock(Features.class), intent); verify(buttonRepository).setSourceToken("valid_source_token"); } @Test public void trackIncomingIntent_withNullIntentData_doNotPersist() { ButtonRepository buttonRepository = mock(ButtonRepository.class); Intent intent = mock(Intent.class); when(intent.getData()).thenReturn(null); buttonInternal.trackIncomingIntent(mock(TestManager.class), buttonRepository, mock(DeviceManager.class), mock(Features.class), intent); verify(buttonRepository, never()).setSourceToken(anyString()); } @Test public void trackIncomingIntent_shouldPassIntentToTestManager() { TestManager testManager = mock(TestManager.class); Intent intent = mock(Intent.class); Uri uri = mock(Uri.class); Uri.Builder builder = mock(Uri.Builder.class); when(intent.getData()).thenReturn(uri); when(uri.buildUpon()).thenReturn(builder); when(uri.buildUpon().clearQuery()).thenReturn(builder); when(builder.build()).thenReturn(uri); when(uri.getQueryParameter("btn_ref")).thenReturn("valid_source_token"); buttonInternal.trackIncomingIntent(testManager, mock(ButtonRepository.class), mock(DeviceManager.class), mock(Features.class), intent); verify(testManager).parseIntent(intent); } @Test public void setAttributionToken_ShouldNotifyListenersWithToken() { String validToken = "valid_source_token"; ButtonRepository buttonRepository = mock(ButtonRepository.class); Intent intent = mock(Intent.class); Uri uri = mock(Uri.class); Uri.Builder builder = mock(Uri.Builder.class); when(intent.getData()).thenReturn(uri); when(uri.buildUpon()).thenReturn(builder); when(uri.buildUpon().clearQuery()).thenReturn(builder); when(builder.build()).thenReturn(uri); when(uri.getQueryParameter("btn_ref")).thenReturn(validToken); // Add Listener ButtonMerchant.AttributionTokenListener listener = mock(ButtonMerchant.AttributionTokenListener.class); buttonInternal.addAttributionTokenListener(buttonRepository, listener); buttonInternal.trackIncomingIntent(mock(TestManager.class), buttonRepository, mock(DeviceManager.class), mock(Features.class), intent); verify(buttonRepository).setSourceToken(validToken); verify(listener).onAttributionTokenChanged(validToken); } @Test public void setAttributionToken_shouldNotNotifyListenersOrSetTokenWithNull() { ButtonRepository buttonRepository = mock(ButtonRepository.class); Intent intent = mock(Intent.class); Uri uri = mock(Uri.class); Uri.Builder builder = mock(Uri.Builder.class); when(intent.getData()).thenReturn(uri); when(uri.buildUpon()).thenReturn(builder); when(uri.buildUpon().clearQuery()).thenReturn(builder); when(builder.build()).thenReturn(uri); when(uri.getQueryParameter("btn_ref")).thenReturn(null); // Add Listener ButtonMerchant.AttributionTokenListener listener = mock(ButtonMerchant.AttributionTokenListener.class); buttonInternal.addAttributionTokenListener(buttonRepository, listener); buttonInternal.trackIncomingIntent(mock(TestManager.class), buttonRepository, mock(DeviceManager.class), mock(Features.class), intent); verify(buttonRepository, never()).setSourceToken(null); verify(listener, never()).onAttributionTokenChanged(null); } @Test public void setAttributionToken_shouldNotNotifyListenersOrSetTokenWithEmptyString() { ButtonRepository buttonRepository = mock(ButtonRepository.class); Intent intent = mock(Intent.class); Uri uri = mock(Uri.class); Uri.Builder builder = mock(Uri.Builder.class); when(intent.getData()).thenReturn(uri); when(uri.buildUpon()).thenReturn(builder); when(uri.buildUpon().clearQuery()).thenReturn(builder); when(builder.build()).thenReturn(uri); when(uri.getQueryParameter("btn_ref")).thenReturn(""); // Add Listener ButtonMerchant.AttributionTokenListener listener = mock(ButtonMerchant.AttributionTokenListener.class); buttonInternal.addAttributionTokenListener(buttonRepository, listener); buttonInternal.trackIncomingIntent(mock(TestManager.class), buttonRepository, mock(DeviceManager.class), mock(Features.class), intent); verify(buttonRepository, never()).setSourceToken(""); verify(listener, never()).onAttributionTokenChanged(""); } @Test public void addAndRemoveAttributionToken_verifyInternalList() { ButtonRepository buttonRepository = mock(ButtonRepository.class); ButtonMerchant.AttributionTokenListener listener = mock(ButtonMerchant.AttributionTokenListener.class); buttonInternal.addAttributionTokenListener(buttonRepository, listener); assertTrue(buttonInternal.attributionTokenListeners.contains(listener)); buttonInternal.removeAttributionTokenListener(buttonRepository, listener); assertFalse(buttonInternal.attributionTokenListeners.contains(listener)); } @Test public void getAttributionToken_returnPersistedToken() { ButtonRepository buttonRepository = mock(ButtonRepository.class); when(buttonRepository.getSourceToken()).thenReturn("valid_source_token"); String attributionToken = buttonInternal.getAttributionToken(buttonRepository); assertEquals("valid_source_token", attributionToken); } @Test public void clearAllData_clearPersistenceManager() { ButtonRepository buttonRepository = mock(ButtonRepository.class); buttonInternal.clearAllData(buttonRepository); verify(buttonRepository).clear(); } @Test public void handlePostInstallIntent_returnValidPostInstallLink_setSourceToken() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features,"com.usebutton.merchant", postInstallIntentListener); ArgumentCaptor<GetPendingLinkTask.Listener> listenerArgumentCaptor = ArgumentCaptor.forClass(GetPendingLinkTask.Listener.class); verify(buttonRepository).getPendingLink(eq(deviceManager), eq(features), listenerArgumentCaptor.capture()); PostInstallLink.Attribution attribution = new PostInstallLink.Attribution("valid_source_token", "SMS"); PostInstallLink postInstallLink = new PostInstallLink(true, "ddl-6faffd3451edefd3", "uber://asdfasfasf", attribution); listenerArgumentCaptor.getValue().onTaskComplete(postInstallLink); verify(postInstallIntentListener).onResult(any(Intent.class), (Throwable) isNull()); verify(buttonRepository).setSourceToken("valid_source_token"); } @Test public void handlePostInstallIntent_returnInvalidPostInstallLink_doNotSetSourceToken() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); ArgumentCaptor<GetPendingLinkTask.Listener> listenerArgumentCaptor = ArgumentCaptor.forClass(GetPendingLinkTask.Listener.class); verify(buttonRepository).getPendingLink(eq(deviceManager), eq(features), listenerArgumentCaptor.capture()); PostInstallLink postInstallLink = new PostInstallLink(false, "ddl-6faffd3451edefd3", null, null); listenerArgumentCaptor.getValue().onTaskComplete(postInstallLink); verify(postInstallIntentListener).onResult(null, null); verify(buttonRepository, never()).setSourceToken(anyString()); } @Test public void handlePostInstallIntent_nullApplicationId_throwException() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn(null); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); verify(buttonRepository, never()).getPendingLink(any(DeviceManager.class), any(Features.class), any(Task.Listener.class)); verify(buttonRepository, never()).setSourceToken(anyString()); verify(postInstallIntentListener).onResult((Intent) isNull(), any(ApplicationIdNotFoundException.class)); } @Test public void handlePostInstallIntent_throwButtonNetworkException() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); ArgumentCaptor<GetPendingLinkTask.Listener> listenerArgumentCaptor = ArgumentCaptor.forClass(GetPendingLinkTask.Listener.class); verify(buttonRepository).getPendingLink(eq(deviceManager), eq(features), listenerArgumentCaptor.capture()); listenerArgumentCaptor.getValue().onTaskError(new ButtonNetworkException("")); verify(postInstallIntentListener).onResult((Intent) isNull(), any(ButtonNetworkException.class)); } @Test public void handlePostInstallIntent_newInstallationAndDidNotCheckDeferredDeepLink_updateCheckDeferredDeepLink() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); when(deviceManager.isOldInstallation()).thenReturn(false); when(buttonRepository.checkedDeferredDeepLink()).thenReturn(false); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); verify(buttonRepository).updateCheckDeferredDeepLink(true); verify(buttonRepository).getPendingLink(any(DeviceManager.class), any(Features.class), any(Task.Listener.class)); } @Test public void handlePostInstallIntent_oldInstallation_doNotUpdateCheckDeferredDeepLink_verifyCallback() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); when(deviceManager.isOldInstallation()).thenReturn(true); when(buttonRepository.checkedDeferredDeepLink()).thenReturn(false); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); verify(postInstallIntentListener).onResult(null, null); verify(buttonRepository, never()).updateCheckDeferredDeepLink(anyBoolean()); } @Test public void handlePostInstallIntent_checkedDeferredDeepLink_doNotUpdateCheckDeferredDeepLink_verifyCallback() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); when(deviceManager.isOldInstallation()).thenReturn(false); when(buttonRepository.checkedDeferredDeepLink()).thenReturn(true); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); verify(postInstallIntentListener).onResult((Intent) isNull(), (Throwable) isNull()); verify(buttonRepository, never()).updateCheckDeferredDeepLink(anyBoolean()); } @Test public void handlePostInstallIntent_previouslySetTokenFromDirectDeeplink_shouldNotPersistTokenNorProvideDeferredDeeplink() { ButtonRepository buttonRepository = mock(ButtonRepository.class); PostInstallIntentListener postInstallIntentListener = mock(PostInstallIntentListener.class); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); Intent intent = mock(Intent.class); Uri link = mock(Uri.class); Uri.Builder builder = mock(Uri.Builder.class); when(link.buildUpon()).thenReturn(builder); when(link.buildUpon().clearQuery()).thenReturn(builder); when(builder.build()).thenReturn(link); when(link.getQueryParameter("btn_ref")).thenReturn("valid_token"); when(intent.getData()).thenReturn(link); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); ArgumentCaptor<GetPendingLinkTask.Listener<PostInstallLink>> listenerArgumentCaptor = ArgumentCaptor.forClass(GetPendingLinkTask.Listener.class); PostInstallLink.Attribution attribution = new PostInstallLink.Attribution("valid_source_token", "SMS"); PostInstallLink postInstallLink = new PostInstallLink(true, "ddl-6faffd3451edefd3", "uber://asdfasfasf", attribution); buttonInternal.trackIncomingIntent(mock(TestManager.class), buttonRepository, deviceManager, features, intent); buttonInternal.handlePostInstallIntent(buttonRepository, deviceManager, features, "com.usebutton.merchant", postInstallIntentListener); verify(buttonRepository).getPendingLink(eq(deviceManager), eq(features), listenerArgumentCaptor.capture()); listenerArgumentCaptor.getValue().onTaskComplete(postInstallLink); verify(postInstallIntentListener).onResult((Intent) isNull(), (Throwable) isNull()); verify(buttonRepository, never()).setSourceToken("valid_source_token"); } @Test public void reportOrder_nullApplicationId_verifyException() { ButtonRepository buttonRepository = mock(ButtonRepository.class); when(buttonRepository.getApplicationId()).thenReturn(null); OrderListener orderListener = mock(OrderListener.class); buttonInternal.reportOrder(buttonRepository, mock(DeviceManager.class), mock(Features.class), mock(Order.class), orderListener); verify(orderListener).onResult(any(ApplicationIdNotFoundException.class)); } @Test public void reportOrder_hasApplicationId_verifyPostOrder() { ButtonRepository buttonRepository = mock(ButtonRepository.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); DeviceManager deviceManager = mock(DeviceManager.class); Features features = mock(Features.class); Order order = mock(Order.class); OrderListener orderListener = mock(OrderListener.class); buttonInternal.reportOrder(buttonRepository, deviceManager, features, order, orderListener); verify(buttonRepository).postOrder(eq(order), eq(deviceManager), eq(features), any(Task.Listener.class)); } @Test public void reportOrder_onTaskComplete_verifyCallback() { ButtonRepository buttonRepository = mock(ButtonRepository.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); OrderListener orderListener = mock(OrderListener.class); buttonInternal.reportOrder(buttonRepository, mock(DeviceManager.class), mock(Features.class), mock(Order.class), orderListener); ArgumentCaptor<Task.Listener> argumentCaptor = ArgumentCaptor.forClass(Task.Listener.class); verify(buttonRepository).postOrder(any(Order.class), any(DeviceManager.class), any(Features.class), argumentCaptor.capture()); argumentCaptor.getValue().onTaskComplete(null); verify(orderListener).onResult((Throwable) isNull()); } @Test public void reportOrder_onTaskError_verifyCallback() { ButtonRepository buttonRepository = mock(ButtonRepository.class); when(buttonRepository.getApplicationId()).thenReturn("valid_application_id"); OrderListener orderListener = mock(OrderListener.class); buttonInternal.reportOrder(buttonRepository, mock(DeviceManager.class), mock(Features.class), mock(Order.class), orderListener); ArgumentCaptor<Task.Listener> argumentCaptor = ArgumentCaptor.forClass(Task.Listener.class); verify(buttonRepository).postOrder(any(Order.class), any(DeviceManager.class), any(Features.class), argumentCaptor.capture()); Exception exception = mock(Exception.class); argumentCaptor.getValue().onTaskError(exception); verify(orderListener).onResult(exception); } private class TestMainThreadExecutor implements Executor { @Override public void execute(@NonNull Runnable command) { command.run(); } } }
46.723361
128
0.727687
4a0e3b02626c762153c048af1e93e275307d058e
280
package org.zhuonima.exchange.accounts.requests; import lombok.Data; import org.zhuonima.exchange.common.models.Currency; import java.math.BigDecimal; @Data public class DepositRequest { private Long userId; private Currency currency; private BigDecimal balance; }
20
52
0.785714
33d20c9e01b24086311eb8718329cc1ed9dd817c
1,680
package com.riaancornelius.flux.ui.issue; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.TextView; import com.riaancornelius.flux.jira.domain.author.Author; import com.riaancornelius.flux.jira.domain.issue.Comments; import java.util.ArrayList; import java.util.List; /** * Created by Elsabe on 2014/02/08. */ public class UsersAdapter extends BaseAdapter { private List<Author> authors; private LayoutInflater inflater; public UsersAdapter(LayoutInflater i, List<Author> authorList) { this.inflater = i; setAuthors(authorList); } public void setAuthors(List<Author> authorList) { if (authorList == null) { authors = new ArrayList<Author>(); } else { authors = authorList; } notifyDataSetChanged(); } @Override public int getCount() { return authors.size(); } @Override public Object getItem(int i) { return authors.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { Author author = authors.get(i); View v = view; if (v == null) { v = inflater.inflate(android.R.layout.simple_list_item_2, null); } ((TextView) v.findViewById(android.R.id.text1)).setText(author.getDisplayName()); ((TextView) v.findViewById(android.R.id.text2)).setText(author.getEmailAddress()); return v; } }
25.074627
90
0.656548
74da04fcfc0a67bc8f284c3b2c998a408e926c2b
6,179
package cz.metacentrum.perun.wui.consolidator.pages; import com.google.gwt.core.client.*; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.Widget; import cz.metacentrum.perun.wui.client.resources.PerunConfiguration; import cz.metacentrum.perun.wui.client.resources.PerunSession; import cz.metacentrum.perun.wui.client.utils.Utils; import cz.metacentrum.perun.wui.consolidator.client.resources.PerunConsolidatorTranslation; import cz.metacentrum.perun.wui.consolidator.widgets.Wayf; import cz.metacentrum.perun.wui.json.JsonEvents; import cz.metacentrum.perun.wui.json.managers.RegistrarManager; import cz.metacentrum.perun.wui.model.BasicOverlayObject; import cz.metacentrum.perun.wui.model.PerunException; import cz.metacentrum.perun.wui.model.beans.ExtSource; import cz.metacentrum.perun.wui.widgets.*; import org.gwtbootstrap3.client.ui.*; import org.gwtbootstrap3.client.ui.constants.AlertType; import java.util.Objects; /** * Single page used by consolidator to display it's state * * @author Pavel Zlámal <zlamal@cesnet.cz> */ public class SelectPage { private String token; private String redirect = Window.Location.getParameter("target_url"); private Widget rootElement; interface ConsolidatorPageUiBinder extends UiBinder<Widget, SelectPage> { } private static ConsolidatorPageUiBinder ourUiBinder = GWT.create(ConsolidatorPageUiBinder.class); private PerunConsolidatorTranslation translation = GWT.create(PerunConsolidatorTranslation.class); @UiField(provided = true) Wayf wayf; @UiField PerunLoader loader; @UiField Heading heading; @UiField Heading joinHeading; @UiField Heading identity; @UiField Heading login; @UiField Alert alert; @UiField Alert counter; public SelectPage() { } public Widget draw() { wayf = new Wayf(redirect); if (rootElement == null) { rootElement = ourUiBinder.createAndBindUi(this); } heading.setText(translation.currentIdentityIs()); String text = PerunConfiguration.getWayfLinkAnAccountText(); if (text == null || text.isEmpty()) { joinHeading.setText(translation.joinWith()); } else { joinHeading.setText(text); } // fixme on error loader.onError(error, null); if (token == null || token.isEmpty()) { RegistrarManager.getConsolidatorToken(new JsonEvents() { @Override public void onFinished(JavaScriptObject jso) { token = ((BasicOverlayObject) jso).getString(); // we do have a valid token String extSourceType = PerunSession.getInstance().getPerunPrincipal().getExtSourceType(); String translatedExtSourceName = PerunSession.getInstance().getPerunPrincipal().getExtSource(); String translatedActor = PerunSession.getInstance().getPerunPrincipal().getActor(); if (extSourceType.equals(ExtSource.ExtSourceType.IDP.getType())) { translatedExtSourceName = translatedActor.split("@")[1];// Utils.translateIdp(translatedExtSourceName); // social identity if (translatedActor.endsWith("extidp.cesnet.cz") || translatedActor.endsWith("elixir-europe.org") || Objects.equals(translatedExtSourceName, "https://login.elixir-czech.org/idp/")) { translatedExtSourceName = Utils.translateIdp("@"+translatedActor.split("@")[1]); translatedActor = translatedActor.split("@")[0]; } translatedActor = translatedActor.split("@")[0]; // get actor from attributes if present String displayName = PerunSession.getInstance().getPerunPrincipal().getAdditionInformation("displayName"); String commonName = PerunSession.getInstance().getPerunPrincipal().getAdditionInformation("cn"); if (displayName != null && !displayName.isEmpty()) { translatedActor = displayName; } else { if (commonName != null && !commonName.isEmpty()) { translatedActor = commonName; } } } else if (extSourceType.equals(ExtSource.ExtSourceType.X509.getType())) { translatedActor = Utils.convertCertCN(translatedActor); translatedExtSourceName = Utils.convertCertCN(translatedExtSourceName); } else if (extSourceType.equals(ExtSource.ExtSourceType.KERBEROS.getType())) { translatedExtSourceName = Utils.translateKerberos(translatedExtSourceName); } heading.setVisible(true); if (PerunSession.getInstance().getUser() != null) { login.setText(PerunSession.getInstance().getUser().getFullName()); login.setSubText("( " + PerunSession.getInstance().getPerunPrincipal().getActor() + " )"); } else { login.setText(translatedActor); } login.setVisible(!PerunConfiguration.isWayfLinkAnAccountDisabled()); identity.setText(translatedExtSourceName); identity.setVisible(true); joinHeading.setVisible(!PerunConfiguration.isWayfLinkAnAccountDisabled()); identity.setTitle(translatedActor); if (PerunSession.getInstance().getUser() == null) { alert.setVisible(true); alert.setText(translation.notRegistered()); } wayf.setToken(token); wayf.buildWayfGroups(); loader.onFinished(); loader.setVisible(false); wayf.setVisible(true); setTimer(); } @Override public void onError(PerunException error) { loader.onError(error, null); } @Override public void onLoadingStart() { loader.onLoading(); loader.setVisible(true); } }); } else { wayf.buildWayfGroups(); loader.onFinished(); loader.setVisible(false); wayf.setVisible(true); setTimer(); } return rootElement; } private void setTimer() { //counter.setText(translation.authorizationTokenWillExpire(300)); //counter.setVisible(true); Timer t = new Timer() { int count = 60 * 5; public void run() { counter.setText(translation.authorizationTokenWillExpire(count)); count--; if (count < 0) { counter.setType(AlertType.DANGER); counter.setVisible(true); counter.setText(translation.authorizationTokenHasExpired()); this.cancel(); } } }; t.scheduleRepeating(1000); t.run(); } }
31.687179
188
0.725198
a1666b6529095c892cf10de5ec58c5e9e1da03b2
2,715
package com.brickgit.motoracergdx.actors; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.utils.Timer; import com.brickgit.motoracergdx.utils.Assets; import java.util.Iterator; /** * Created by Daniel Lin on 24/04/2018. */ public class Racer extends BaseActor { public enum State { NORMAL, SKIDDING, HIT } private Sprite imgRacer = Assets.getRacer(); private float speed = 5; private Road road; private State state = State.NORMAL; public Racer(int x, int y, Road road) { setSize(imgRacer.getWidth(), imgRacer.getHeight()); setPosition(x - getWidth() / 2, y - getHeight() / 2); updateBounds(); this.road = road; } public State getState() { return state; } public void move(float newX) { newX = newX - getWidth() / 2; float oldX = getX(); if (Math.abs(newX - oldX) < speed) return; if (newX > oldX) moveRight(); else moveLeft(); } public void moveRight() { if (state != State.NORMAL) return; float newX = getX() + speed; if (newX < road.getX() + road.getWidth() - getWidth()) { setX(newX); bounds.x = newX; updateBounds(); } } public void moveLeft() { if (state != State.NORMAL) return; float newX = getX() - speed; if (newX > road.getX()) { setX(newX); bounds.x = newX; updateBounds(); } } @Override public void act(float delta) { super.act(delta); Iterator<Oil> oils = road.getOils().iterator(); while (oils.hasNext()) { Oil oil = oils.next(); if (hit(oil)) { state = State.SKIDDING; Timer.schedule(new Timer.Task() { @Override public void run() { state = State.NORMAL; } }, 1); break; } } Iterator<Car> cars = road.getCars().iterator(); while (cars.hasNext()) { Car car = cars.next(); if (hit(car)) { state = State.HIT; Timer.instance().clear(); } } } @Override public void draw(Batch batch, float parentAlpha) { super.draw(batch, parentAlpha); float rotation = (state == State.NORMAL) ? getRotation() : 30; batch.draw( imgRacer, getX(), getY(), getOriginX(), getOriginY(), getWidth(), getHeight(), 1, 1, rotation); } }
25.138889
70
0.507182
9f94b29c4693dc03c0bd1c963c3f3be208682f63
674
package com.lyhace.sfnotice.service; import feign.hystrix.FallbackFactory; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; @Slf4j @Component public class DoingCommHystrixFactory implements FallbackFactory<DoingCommOpenfeignService> { @Override public DoingCommOpenfeignService create(Throwable throwable) { return new DoingCommOpenfeignService(){ @Override public String doing() { String message = "访问comm doing service 异常,已降级!"; log.info(message); log.error("ERROR:", throwable); return message; } }; } }
25.923077
92
0.652819
80f37630ae96f96afe996d2c61185d7114a871ee
88
package com.question.answer.misc; public enum AREA { AREA1, AREA2, AREA3 }
11
33
0.647727
1bb388ba63932fc7db0316b3209e5bf38614ff22
642
package net.kemitix.slushy.app.trello.webhook; import org.apache.camel.builder.RouteBuilder; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; @ApplicationScoped public class RegisterWebhookRoute extends RouteBuilder { private final RegisterWebhook registerWebhook; @Inject public RegisterWebhookRoute(RegisterWebhook registerWebhook) { this.registerWebhook = registerWebhook; } @Override public void configure() { from("timer:trello-webhook?repeatCount=1") .routeId("trello-webhook") .bean(registerWebhook) ; } }
22.928571
66
0.702492
49d02b00c5acef58f71eca8b2fb6f8d9269df044
801
package com.communote.server.core.exception.mapper; import com.communote.server.core.exception.ExceptionMapper; import com.communote.server.core.exception.Status; import com.communote.server.core.tag.TagNotFoundException; /** * Mapper to create a useful error message when a tag does not exist * * @author Communote GmbH - <a href="http://www.communote.com/">http://www.communote.com/</a> * */ public class TagNotFoundExceptionMapper implements ExceptionMapper<TagNotFoundException> { @Override public Class<TagNotFoundException> getExceptionClass() { return TagNotFoundException.class; } @Override public Status mapException(TagNotFoundException exception) { return new Status("common.error.tag.not.found", NOT_FOUND); } }
30.807692
94
0.726592
85ee735ca4f7e0d6a8da1bcfde39e1ddb0dc07eb
666
package de.fraunhofer.iem.swan.features.code.type; import de.fraunhofer.iem.swan.data.Method; /** * Implicit methods (e.g. methods from bytecode for access of private fields) * * @author Lisa Nguyen Quang Do * */ public class IsImplicitMethod extends WeightedFeature implements IFeature { @Override public Type applies(Method method) { return (method.getMethodName().contains("$") ? Type.TRUE : Type.FALSE); } @Override public String toString() { return "<Implicit method>"; } @Override public void setWeight(int weight) { super.setWeight(weight); } @Override public int getWeight() { return super.getWeight(); } }
20.181818
77
0.696697
e1a2ad3e5d150e5e197b1d54c77d19e1d8a224b9
3,921
/* * Copyright (c) 2018 David Sargent * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of David Sargent nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior * written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.onbotjava.handlers.file; import org.firstinspires.ftc.onbotjava.OnBotJavaFileSystemUtils; import org.firstinspires.ftc.onbotjava.OnBotJavaProgrammingMode; import org.firstinspires.ftc.onbotjava.RegisterWebHandler; import org.firstinspires.ftc.onbotjava.RequestConditions; import org.firstinspires.ftc.onbotjava.OnBotJavaManager; import org.firstinspires.ftc.robotcore.internal.system.AppUtil; import org.firstinspires.ftc.robotcore.internal.webserver.WebHandler; import org.threeten.bp.LocalDateTime; import fi.iki.elonen.NanoHTTPD; @RegisterWebHandler(uri = OnBotJavaProgrammingMode.URI_FILE_DOWNLOAD) public class DownloadFile implements WebHandler { @Override public NanoHTTPD.Response getResponse(NanoHTTPD.IHTTPSession session) { final NanoHTTPD.Response file = OnBotJavaFileSystemUtils.getFile(session.getParameters(), true, OnBotJavaFileSystemUtils.LineEndings.WINDOWS.lineEnding); if (file.getStatus() != NanoHTTPD.Response.Status.OK) { return file; } String fileName = RequestConditions.dataForParameter(session, RequestConditions.REQUEST_KEY_FILE); if (fileName.equals(OnBotJavaFileSystemUtils.PATH_SEPARATOR + OnBotJavaManager.srcDir.getName() + OnBotJavaFileSystemUtils.PATH_SEPARATOR)) { fileName = "OnBotJava-" + AppUtil.getInstance().getIso8601DateTimeFormatter().format(LocalDateTime.now()) + OnBotJavaFileSystemUtils.EXT_ZIP_FILE; } else if (fileName.endsWith(OnBotJavaFileSystemUtils.PATH_SEPARATOR)) { // Check to see if this is a folder, if so add a ".zip" extension fileName = fileName.substring(0, fileName.length() - 1); fileName = fileName.substring(fileName.lastIndexOf(OnBotJavaFileSystemUtils.PATH_SEPARATOR) + 1); fileName += OnBotJavaFileSystemUtils.EXT_ZIP_FILE; } else if (fileName.contains(OnBotJavaFileSystemUtils.PATH_SEPARATOR)) { fileName = fileName.substring(fileName.lastIndexOf(OnBotJavaFileSystemUtils.PATH_SEPARATOR) + 1); } file.addHeader("Content-Disposition", "attachment; filename=" + fileName); file.addHeader("Pragma", "no-cache"); return file; } }
51.592105
161
0.765876
4c41688daad3a826bc172f3ba94d34e9e30ebfe5
4,618
package com.gaochunjiang.tools; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; public class BizUtil { /** * 判断是否为 null、""、"null" */ public static boolean isNull(Object obj){ boolean result = false; try{ if(obj instanceof String){ String str = (String)obj; if(str==null || str.length()==0 || "null".equalsIgnoreCase(str)){ result = true; } } else { if(obj == null){ result = true; } } } catch (Exception e) { } return result; } /** * 是否不为空 */ public static boolean isNotNull(Object obj){ return !isNull(obj); } /** * null 替换为 "" * @return */ public static String replaceNullStr(Object obj){ return nullToStr(obj, ""); } /** * null 替换为 "" * @return */ public static Object replaceNull(Object obj){ return nullToObj(obj, ""); } /** * obj 为 null 替换为 str * @param obj * @param str * @return */ public static Object nullToObj(Object obj, Object str){ return isNull(obj) ? str : obj; } /** * obj 为 null 替换为 str * @param obj * @param str * @return */ public static String nullToStr(Object obj, String str){ Object rst = nullToObj(obj, str); return rst == null ? null : (rst instanceof String ? (String)rst : rst.toString()); } /** * 是否为数字(整数) * @param str * @return */ public static boolean isNumber(String str){ boolean result = false; // try{ if(isNotNull(str)){ String regex = "^([1-9]\\d*)|(0)$"; result = str.matches(regex); } } catch (Exception e) { } // return result; } /** * 字符串转整形 * @return */ public static Integer stringToInteger(String str, Integer def){ try{ return Integer.valueOf(str); } catch(Exception e){ return def; } } /** * 字符串转浮点型 * @return */ public static Double stringToDouble(String str, Double def){ try{ return Double.valueOf(str); } catch(Exception e){ return def; } } /** * 获得当前文字的长度,中文为2个字符 */ public static int chineseLen(String fromStr) { if(isNull(fromStr)){ return 0; } int fromLen = fromStr.length(); int chineseLen = 0; for(int i = 0;i<fromLen;i++){ if(gbValue(fromStr.charAt(i))>0){ chineseLen = chineseLen + 2; }else{ chineseLen ++; } } return chineseLen; } /** * 返回GBK值 */ public static int gbValue(char ch) { String str = new String(); str += ch; try { byte[] bytes = str.getBytes("GBK"); if (bytes.length < 2) return 0; return (bytes[0] << 8 & 0xff00) + (bytes[1] & 0xff); } catch (Exception e) { return 0; } } /** * 集合转数组 * @param list * @return */ public static String[] listToArray(List<String> list){ String[] result = null; if(list != null && list.size() > 0){ result = new String[list.size()]; for(int i=0; i<list.size(); i++){ result[i] = list.get(i); } } return result; } /** * 集合转字符串(英文逗号分隔) * @param list * @return */ public static String listToString(List<String> list){ StringBuffer result = new StringBuffer(); if(list != null && list.size() > 0){ for(int i=0; i<list.size(); i++){ if(i > 0){ result.append(","); } result.append(list.get(i)); } } return result.toString(); } /** * 数组转集合 * @param list * @return */ public static List<String> arrayToList(String[] ary){ List<String> result = null; if(ary != null && ary.length > 0){ result = new ArrayList<String>(); for(int i=0; i<ary.length; i++){ result.add(ary[i]); } } return result; } /** * 保留 num 位小数 * @param val * @param num * @return */ public static String formatDouble(double val, int num){ StringBuffer formatStr = new StringBuffer(); formatStr.append("#"); if(num > 0){ formatStr.append("."); } for(int i=0; i<num; i++){ formatStr.append("#"); } DecimalFormat df = new DecimalFormat(formatStr.toString()); String rst = df.format(val); return rst; } /** * id 去重,去异常 * @param ids * @return */ public static String getValidIds(String ids){ String rst = null; if(isNotNull(ids)){ String[] idAry = ids.split(","); List<String> idList = new ArrayList<String>(); for(String id : idAry){ int idInt = stringToInteger(id, 0); if(idInt > 0 && idList.contains(""+idInt) == false){ idList.add(""+idInt); } } // rst = listToString(idList); } return rst; } }
19.403361
86
0.555652
e7bbbc4d9f3270a8c1c038bb02861d42343c864f
931
package com.mygdx.game.Dungeon.DungeonTiles; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.math.GridPoint2; import com.mygdx.game.Dungeon.Dungeon; import com.mygdx.game.Dungeon.DungeonTile; public class EmptyDungeonTile extends DungeonTile { public EmptyDungeonTile(GridPoint2 pos, Dungeon dungeon) { super(pos, dungeon); } @Override public float getCorridorPlacingCost() { return 50; } @Override public boolean isVisionObstructing() { return true; } @Override public boolean isPassable() { return false; } @Override public TextureRegion getTileTexture() { return null; } @Override public boolean isEmpty(){ return true; } @Override public boolean isVisible(){ return false; } @Override public float getVisibilityLevel(){ return 0; } }
19.395833
62
0.653061
9011ebd7e20caaf0baf1bf893d64cd93cdb905ca
4,168
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.camel.spring; import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.camunda.bpm.engine.RuntimeService; import org.camunda.bpm.engine.TaskService; import org.camunda.bpm.engine.task.Task; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.Collections; import java.util.HashMap; import java.util.Map; import static org.fest.assertions.api.Assertions.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:spring-camel-activiti-context.xml") public class SimpleSpringProcessTest { MockEndpoint service1; MockEndpoint service2; @Autowired(required = true) ApplicationContext applicationContext; @Autowired(required = true) CamelContext camelContext; @Autowired(required = true) RuntimeService runtimeService; @Autowired(required = true) @Rule public ProcessEngineRule processEngineRule; @Before public void setUp() { service1 = (MockEndpoint) camelContext.getEndpoint("mock:service1"); service1.reset(); service2 = (MockEndpoint) camelContext.getEndpoint("mock:service2"); service2.reset(); } @Test @Deployment(resources = {"process/example.bpmn20.xml"}) public void testRunProcess() throws Exception { ProducerTemplate tpl = camelContext.createProducerTemplate(); service1.expectedBodiesReceived("ala"); Map<String, Object> processVariables = new HashMap<String, Object>(); processVariables.put("var1", "ala"); runtimeService.startProcessInstanceByKey("camelProcess", processVariables); assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(1); //String instanceId = (String) tpl.requestBody("direct:start", Collections.singletonMap("var1", "ala")); //tpl.sendBodyAndProperty("direct:receive", null, CamundaBpmProducer.PROCESS_ID_PROPERTY, instanceId); //assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(0); //service1.assertIsSatisfied(); //Map m = service2.getExchanges().get(0).getIn().getBody(Map.class); //assertThat(m.get("var1")).isEqualTo("ala"); //assertThat(m.get("var2")).isEqualTo("var2"); } //@Test // @Deployment(resources = {"process/example.bpmn20.xml"}) // public void testRunProcessByKey() throws Exception { // //CamelContext camelContext = applicationContext.getBean(CamelContext.class); // ProducerTemplate tpl = camelContext.createProducerTemplate(); // MockEndpoint me = (MockEndpoint) camelContext.getEndpoint("mock:service1"); // me.expectedBodiesReceived("ala"); // // // tpl.sendBodyAndProperty("direct:start", Collections.singletonMap("var1", "ala"), CamundaBpmProducer.PROCESS_KEY_PROPERTY, "key1"); // // String instanceId = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey("key1") // .singleResult().getProcessInstanceId(); // tpl.sendBodyAndProperty("direct:receive", null, CamundaBpmProducer.PROCESS_KEY_PROPERTY, "key1"); // // //assertProcessEnded(instanceId); // assertThat(runtimeService.createProcessInstanceQuery().count()).isEqualTo(0); // me.assertIsSatisfied(); // } }
37.214286
136
0.760797
ffb8a0ae671d8f4d41682d49d304ff4224495648
1,903
/* * Copyright 2017 Redsaz <redsaz@gmail.com>. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.redsaz.lognition.convert; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Converts a JTL Row into a different JTL Row with potentially different columns. * * @author Redsaz <redsaz@gmail.com> */ class JtlRowToJtlRow { private final List<Integer> cols = new ArrayList<>(); private final List<JtlType> jtlTypes = new ArrayList<>(); public JtlRowToJtlRow(String[] headers, JtlType... columns) { Set<JtlType> colSet = new HashSet<>(Arrays.asList(columns)); for (int i = 0; i < headers.length; ++i) { String header = headers[i]; JtlType jtlType = JtlType.fromHeader(header); if (jtlType != null && colSet.contains(jtlType)) { cols.add(i); jtlTypes.add(jtlType); } } } public String[] getHeaders() { String[] outputRow = new String[cols.size()]; for (int i = 0; i < cols.size(); ++i) { outputRow[i] = jtlTypes.get(i).csvName(); } return outputRow; } public String[] convert(String[] row) { String[] outputRow = new String[cols.size()]; for (int i = 0; i < cols.size(); ++i) { int col = cols.get(i); String value = row[col]; outputRow[i] = value; } return outputRow; } }
29.734375
82
0.662112
afbe1ed9a000b61815a851a6e51eac51cbddfedb
1,037
package com.github.dormesica.mapcontroller; import android.os.Parcel; import androidx.test.ext.junit.runners.AndroidJUnit4; import com.github.dormesica.mapcontroller.graphics.Color; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class ColorAndroidTest { @Test public void writeToParcel() { final int RED = 125; final int GREEN = 23; final int BLUE = 89; final double ALPHA = 0.44; Parcel parcel = Parcel.obtain(); Color color = new Color(RED, GREEN, BLUE, ALPHA); color.writeToParcel(parcel, color.describeContents()); parcel.setDataPosition(0); Color fromParcel = Color.CREATOR.createFromParcel(parcel); Assert.assertNotNull(fromParcel); Assert.assertEquals(RED, fromParcel.red()); Assert.assertEquals(GREEN, fromParcel.green()); Assert.assertEquals(BLUE, fromParcel.blue()); Assert.assertEquals(ALPHA, fromParcel.alpha(), 0.001); } }
30.5
66
0.689489
864895362bdc3a5c2b016dd96afebe4c0d4f55c9
2,582
package com.example.demo.defaultapp.security.jwt; import com.example.demo.defaultapp.exceptions.JwtAuthenticationException; import com.example.demo.defaultapp.properties.JwtProperties; import io.jsonwebtoken.*; import org.springframework.http.HttpStatus; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import java.util.Date; @Component public class JwtTokenProvider { private final UserDetailsService userDetailsService; private final JwtProperties jwtProperties; public JwtTokenProvider(UserDetailsService userDetailsService, JwtProperties jwtProperties) { this.userDetailsService = userDetailsService; this.jwtProperties = jwtProperties; } public String createToken(String username){ Claims claims = Jwts.claims().setSubject(username); Date now = new Date(); Date expiration = new Date(now.getTime() + jwtProperties.getExpirationSeconds() * 1_000); return Jwts.builder() .setClaims(claims) .setIssuedAt(now) .setExpiration(expiration) .signWith(SignatureAlgorithm.HS256, jwtProperties.getSecret()) .compact(); } public boolean validateToken(String token) { try { Jws<Claims> claimsJws = Jwts.parser().setSigningKey(jwtProperties.getSecret()).parseClaimsJws(token); return !claimsJws.getBody().getExpiration().before(new Date()); } catch (JwtException | IllegalArgumentException e) { throw new JwtAuthenticationException("JWT token is expired of invalid", HttpStatus.UNAUTHORIZED); } } public Authentication getAuthentication(String token) { UserDetails userDetails = this.userDetailsService.loadUserByUsername(getUsername(token)); return new UsernamePasswordAuthenticationToken(userDetails, "", userDetails.getAuthorities()); } public String resolveToken(HttpServletRequest request) { return request.getHeader(jwtProperties.getHeader()); } public String getUsername(String token) { return Jwts.parser() .setSigningKey(jwtProperties.getSecret()) .parseClaimsJws(token) .getBody() .getSubject(); } }
39.723077
113
0.717661
1cec7be424e8ae368701621591c98a2c43708337
1,136
package io.wttech.markuply.engine.component.method.resolver.context; import io.wttech.markuply.engine.component.MarkuplyComponentContext; import io.wttech.markuply.engine.component.method.resolver.MethodArgumentResolver; import io.wttech.markuply.engine.component.method.resolver.MethodArgumentResolverFactory; import io.wttech.markuply.engine.pipeline.context.PageContext; import lombok.AllArgsConstructor; import org.springframework.stereotype.Component; import java.lang.reflect.Parameter; import java.util.Optional; @Component public class PageContextResolverFactory implements MethodArgumentResolverFactory { @Override public Optional<MethodArgumentResolver> createResolver(Parameter parameter) { if (parameter.getType().equals(PageContext.class)) { return Optional.of(PageContextResolver.instance()); } else { return Optional.empty(); } } @AllArgsConstructor(staticName = "instance") private static class PageContextResolver implements MethodArgumentResolver { @Override public Object resolve(MarkuplyComponentContext context) { return context.getPageContext(); } } }
31.555556
89
0.800176