hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
9232891c7771b63354efb76f30cdcdccbf01ae1e
1,717
java
Java
SkidCore/src/org/objectweb/asm/optimizer/FieldConstantsCollector.java
FireMasterK/SkidSuite2-Latest
9a5d50286f8a893d8797d67e81defb2e5d02adac
[ "Apache-2.0" ]
33
2018-02-18T15:51:05.000Z
2021-09-16T11:26:39.000Z
SkidCore/src/org/objectweb/asm/optimizer/FieldConstantsCollector.java
FireMasterK/SkidSuite2-Latest
9a5d50286f8a893d8797d67e81defb2e5d02adac
[ "Apache-2.0" ]
null
null
null
SkidCore/src/org/objectweb/asm/optimizer/FieldConstantsCollector.java
FireMasterK/SkidSuite2-Latest
9a5d50286f8a893d8797d67e81defb2e5d02adac
[ "Apache-2.0" ]
8
2018-04-02T21:39:24.000Z
2022-01-15T06:07:32.000Z
28.147541
83
0.626092
996,252
package org.objectweb.asm.optimizer; import org.objectweb.asm.AnnotationVisitor; import org.objectweb.asm.Attribute; import org.objectweb.asm.FieldVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.TypePath; /** * A {@link FieldVisitor} that collects the {@link Constant}s of the fields it * visits. * * @author Eric Bruneton */ public class FieldConstantsCollector extends FieldVisitor { private final ConstantPool cp; public FieldConstantsCollector(final FieldVisitor fv, final ConstantPool cp) { super(Opcodes.ASM5, fv); this.cp = cp; } @Override public AnnotationVisitor visitAnnotation(final String desc, final boolean visible) { cp.newUTF8(desc); if (visible) { cp.newUTF8("RuntimeVisibleAnnotations"); } else { cp.newUTF8("RuntimeInvisibleAnnotations"); } return new AnnotationConstantsCollector(fv.visitAnnotation(desc, visible), cp); } @Override public AnnotationVisitor visitTypeAnnotation(int typeRef, TypePath typePath, String desc, boolean visible) { cp.newUTF8(desc); if (visible) { cp.newUTF8("RuntimeVisibleTypeAnnotations"); } else { cp.newUTF8("RuntimeInvisibleTypeAnnotations"); } return new AnnotationConstantsCollector(fv.visitAnnotation(desc, visible), cp); } @Override public void visitAttribute(final Attribute attr) { // can do nothing fv.visitAttribute(attr); } @Override public void visitEnd() { fv.visitEnd(); } }
923289c69ba5166114cabe1935c4a0878e216d6e
11,779
java
Java
EclipsePlugin/com.aspose.ecplugin/src/com/aspose/ecplugin/CustomProjectSupport.java
asposemarketplace/Aspose_for_Eclipse
c4b6c17dc8fc83de5201a8c5877adcc5f9768314
[ "MIT" ]
1
2021-04-01T10:58:47.000Z
2021-04-01T10:58:47.000Z
EclipsePlugin/com.aspose.ecplugin/src/com/aspose/ecplugin/CustomProjectSupport.java
asposemarketplace/Aspose_for_Eclipse
c4b6c17dc8fc83de5201a8c5877adcc5f9768314
[ "MIT" ]
null
null
null
EclipsePlugin/com.aspose.ecplugin/src/com/aspose/ecplugin/CustomProjectSupport.java
asposemarketplace/Aspose_for_Eclipse
c4b6c17dc8fc83de5201a8c5877adcc5f9768314
[ "MIT" ]
5
2015-06-05T09:51:17.000Z
2015-12-03T10:38:42.000Z
28.520581
149
0.71186
996,253
/* * Copyright (c) 2001-2013 Aspose Pty Ltd. All Rights Reserved. * Author: Mohsan.Raza */ package com.aspose.ecplugin; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URL; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.eclipse.core.resources.ICommand; import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IProjectDescription; import org.eclipse.core.resources.IResource; import org.eclipse.core.resources.ResourcesPlugin; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IPath; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClasspathEntry; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.JavaModelException; import com.aspose.ecplugin.AsposeComponentsManager; public class CustomProjectSupport { /** * For this marvelous project we need to: * - create the default Eclipse project * - add the custom project nature * - create the folder structure * * @param projectName * @param location * @param natureId * @return */ public static IProject createProject(String projectName, URI location) { Assert.isNotNull(projectName); Assert.isTrue(projectName.trim().length() > 0); IProject project = createBaseProject(projectName, location); //project. try { addNature(project,AsposeConstants.NATURE_ID); addNature(project,AsposeConstants.NATURE_ID_JDT); addBuildCommand(project); String[] paths = { AsposeConstants.SRC_FOLDER, AsposeConstants.BIN_FOLDER,AsposeConstants.LIB_FOLDER }; addToProjectStructure(project, paths); addClassPath(project); project.refreshLocal(0, null); } catch (CoreException e) { e.printStackTrace(); project = null; } return project; } /** * * @param project * @param libName * @param URL */ public static void downloadLibrary(IProject project, String libName, String URL) { URL website; try { IJavaProject javaProject = JavaCore.create(project); IFolder libFolder = project.getFolder(AsposeConstants.LIB_FOLDER); IPackageFragmentRoot libRoot = javaProject.getPackageFragmentRoot(libFolder); IPath libFolderPath = libRoot.getPath(); IPath workspacePath = ResourcesPlugin.getWorkspace().getRoot().getLocation(); IPath absoluteLibFolderPath=workspacePath.append(libFolderPath); @SuppressWarnings("unused") String libraryPath = absoluteLibFolderPath.toString(); String combPath = "lib" + "/" + libName; IFile iFile= project.getFile(combPath); website = new URL(URL + libName); ReadableByteChannel rbc; rbc = Channels.newChannel(website.openStream()); FileOutputStream fos; java.io.File file = iFile.getLocation().toFile(); fos = new FileOutputStream(file); fos.getChannel().transferFrom(rbc, 0, 1 << 24); fos.close(); try { iFile.refreshLocal(0, null); } catch (CoreException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } /** * * @param project * @throws JavaModelException */ public static void addClassPath(IProject project) throws JavaModelException { IJavaProject javaProject = JavaCore.create(project); IClasspathEntry[] newEntries = new IClasspathEntry[2]; // add a new entry using the path to the container Path junitPath = new Path(AsposeConstants.ORG_ECLIPSE_JDT_LAUNCHING_CONTAINER); IClasspathEntry junitEntry = JavaCore.newContainerEntry(junitPath); newEntries[0] = JavaCore.newContainerEntry(junitEntry.getPath()); //add src folder IFolder sourceFolder = project.getFolder(AsposeConstants.SRC_FOLDER); IPackageFragmentRoot srcRoot = javaProject.getPackageFragmentRoot(sourceFolder); IClasspathEntry srcPathEntry = JavaCore.newSourceEntry(srcRoot.getPath()); newEntries[1] = srcPathEntry; for(AsposeJavaComponent component:AsposeJavaComponents.list.values()) { if(component.is_selected() && component.is_downloaded()) { IFolder libFolder = project.getFolder(AsposeConstants.LIB_FOLDER + File.separator + component.get_name()); if(!libFolder.exists()) { try { libFolder.create(IResource.NONE,true,null); } catch (CoreException e) { e.printStackTrace(); } } IPackageFragmentRoot libRoot = javaProject.getPackageFragmentRoot(libFolder); File dir = new File(AsposeComponentsManager.getLibaryDownloadPath() + AsposeComponentsManager.removeExtention(component.get_downloadFileName())); copyLibsAsResouces(dir.getAbsolutePath(),project, component); try { IResource[] libFiles = libFolder.members(); boolean entriesAdded = false; for(int i=0; i< libFiles.length;i++) { String libName = libFiles[i].getName(); IClasspathEntry libPathEntry = JavaCore.newLibraryEntry(libRoot.getPath().append(libName),libRoot.getPath().append(libName),null); newEntries = incrementCapacity(newEntries); newEntries[newEntries.length -1] = libPathEntry; entriesAdded = true; } if(entriesAdded) javaProject.setRawClasspath(newEntries, null); } catch (CoreException e) { e.printStackTrace(); } } } } /** * * @param path * @param project */ private static void copyLibsAsResouces( String path, IProject project,AsposeJavaComponent component ) { File root = new File( path ); File[] list = root.listFiles(); for ( File f : list ) { if ( f.isDirectory() ) { copyLibsAsResouces( f.getAbsolutePath(), project, component ); } else { File file = new File(f.getAbsolutePath()); copyAsResource(project,file.getAbsolutePath(), "lib" + File.separator + component.get_name() + File.separator + file.getName()/*projectLib*/); } } } /** * * @param list * @return */ public static IClasspathEntry[] incrementCapacity(IClasspathEntry[] list){ IClasspathEntry[] newList = new IClasspathEntry[list.length+1]; for (int j = 0; j < list.length; j++ ){ newList[j] = list[j];} return newList; } /** * * @param project * @param srcPath * @param destPath * @return */ private static boolean copyAsResource(IProject project, String srcPath, String destPath) { try { InputStream is = new BufferedInputStream(new FileInputStream(srcPath)); IFile file = project.getFile(destPath); file.create(is, false, null); return true; } catch (CoreException e) { e.printStackTrace(); return false; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } } /** * Just do the basics: create a basic project. * * @param location * @param projectName */ private static IProject createBaseProject(String projectName, URI location) { // it is acceptable to use the ResourcesPlugin class IProject newProject = ResourcesPlugin.getWorkspace().getRoot().getProject(projectName); if (!newProject.exists()) { URI projectLocation = location; IProjectDescription desc = newProject.getWorkspace().newProjectDescription(newProject.getName()); if (location != null && ResourcesPlugin.getWorkspace().getRoot().getLocationURI().equals(location)) { projectLocation = null; } desc.setLocationURI(projectLocation); try { newProject.create(desc, null); if (!newProject.isOpen()) { newProject.open(null); } } catch (CoreException e) { e.printStackTrace(); } } return newProject; } /** * * @param folder * @throws CoreException */ private static void createFolder(IFolder folder) throws CoreException { IContainer parent = folder.getParent(); if (parent instanceof IFolder) { createFolder((IFolder) parent); } if (!folder.exists()) { folder.create(false, true, null); } } /** * Create a folder structure with a parent root, overlay, and a few child * folders. * * @param newProject * @param paths * @throws CoreException */ private static void addToProjectStructure(IProject newProject, String[] paths) throws CoreException { for (String path : paths) { IFolder etcFolders = newProject.getFolder(path); createFolder(etcFolders); } } /** * * @param project * @param natureId * @throws CoreException */ private static void addNature(IProject project, String natureId) throws CoreException { if (!project.hasNature(natureId)) { IProjectDescription description = project.getDescription(); String[] prevNatures = description.getNatureIds(); String[] newNatures = new String[prevNatures.length + 1]; System.arraycopy(prevNatures, 0, newNatures, 0, prevNatures.length); newNatures[prevNatures.length] = natureId; description.setNatureIds(newNatures); IProgressMonitor monitor = null; project.setDescription(description, monitor); } } /** * * @param project * @throws CoreException */ private static void addBuildCommand(IProject project) throws CoreException { IProjectDescription description = project.getDescription(); ICommand[] buildCommands = description.getBuildSpec(); ICommand command = description.newCommand(); command.setBuilderName(AsposeConstants.ORG_ECLIPSE_JDT_CORE_JAVA_BUILDER); ICommand[] newBuildCommands; if ( contains( buildCommands, AsposeConstants.ORG_ECLIPSE_JDT_CORE_JAVA_BUILDER ) ) { newBuildCommands = swap( buildCommands, AsposeConstants.ORG_ECLIPSE_JDT_CORE_JAVA_BUILDER, command ); } else { newBuildCommands = insert( buildCommands, command ); } description.setBuildSpec(newBuildCommands); project.setDescription(description, null); } /** * * @param sourceCommands * @param command * @return */ private static ICommand[] insert( ICommand[] sourceCommands, ICommand command ) { ICommand[] newCommands = new ICommand[ sourceCommands.length + 1 ]; newCommands[0] = command; for (int i = 0; i < sourceCommands.length; i++ ) { newCommands[i+1] = sourceCommands[i]; } return newCommands; } /** * * @param sourceCommands * @param builderId * @return */ @SuppressWarnings("unused") private static ICommand[] remove( ICommand[] sourceCommands, String builderId ) { ICommand[] newCommands = new ICommand[ sourceCommands.length - 1 ]; int newCommandIndex = 0; for (int i = 0; i < sourceCommands.length; i++ ) { if ( !sourceCommands[i].getBuilderName( ).equals( builderId ) ) { newCommands[newCommandIndex++] = sourceCommands[i]; } } return newCommands; } /** * * @param commands * @param builderId * @return */ private static boolean contains(ICommand[] commands, String builderId) { boolean found = false; for (int i = 0; i < commands.length; i++) { if (commands[i].getBuilderName().equals(builderId)) { found = true; break; } } return found; } /** * * @param sourceCommands * @param oldBuilderId * @param newCommand * @return */ private static ICommand[] swap( ICommand[] sourceCommands, String oldBuilderId, ICommand newCommand) { ICommand[] newCommands = new ICommand[sourceCommands.length]; for ( int i = 0; i < sourceCommands.length; i++ ) { if ( sourceCommands[i].getBuilderName( ).equals( oldBuilderId ) ) { newCommands[i] = newCommand; } else { newCommands[i] = sourceCommands[i]; } } return newCommands; } }
923289cab4e397f9717635fc41787c791176189f
2,077
java
Java
oulipo-communications/src/main/java/net/sf/appia/protocols/total/sequencer/TotalSequencerHeader.java
sisbell/appia
c49b96f82a48460f63b190eeac30499dd64ae343
[ "Apache-2.0" ]
2
2016-11-25T15:30:33.000Z
2019-04-04T09:40:52.000Z
oulipo-communications/src/main/java/net/sf/appia/protocols/total/sequencer/TotalSequencerHeader.java
sisbell/appia
c49b96f82a48460f63b190eeac30499dd64ae343
[ "Apache-2.0" ]
null
null
null
oulipo-communications/src/main/java/net/sf/appia/protocols/total/sequencer/TotalSequencerHeader.java
sisbell/appia
c49b96f82a48460f63b190eeac30499dd64ae343
[ "Apache-2.0" ]
null
null
null
25.641975
86
0.675494
996,254
/** * Appia: Group communication and protocol composition framework library * Copyright 2006 University of Lisbon * * 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. * * Initial developer(s): Alexandre Pinto and Hugo Miranda. * Contributor(s): See Appia web page for a list of contributors. */ package net.sf.appia.protocols.total.sequencer; import java.io.*; /** * Header added to the events to be sent in total order. */ public class TotalSequencerHeader implements Externalizable { private static final long serialVersionUID = 7750742443002978989L; private int ordem; private int emissor; private int nSeqInd; public TotalSequencerHeader() {} /** * Constructor. * @param o total order * @param e sender * @param nSeq individual sequence number */ public TotalSequencerHeader(int o,int e,int nSeq) { ordem=o; emissor=e; nSeqInd=nSeq; } /** * @return total order */ public int getOrder() { return ordem; } /** * @return The event */ public int getSender() { return emissor; } /** * @return the individual sequence number */ public int getnSeqInd() { return nSeqInd; } public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(ordem); out.writeInt(emissor); out.writeInt(nSeqInd); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { ordem = in.readInt(); emissor = in.readInt(); nSeqInd = in.readInt(); } }
92328ab1d13a22af79ffe2410816a13c5332f41b
3,659
java
Java
service/core-activity/activity-controller/src/main/java/org/torpay/service/core/activity/controller/ActivityLoaderImpl.java
irmann/torpay-
b78988665572a2090cb7e57b5f04ce3a3b61fde3
[ "Apache-2.0" ]
null
null
null
service/core-activity/activity-controller/src/main/java/org/torpay/service/core/activity/controller/ActivityLoaderImpl.java
irmann/torpay-
b78988665572a2090cb7e57b5f04ce3a3b61fde3
[ "Apache-2.0" ]
null
null
null
service/core-activity/activity-controller/src/main/java/org/torpay/service/core/activity/controller/ActivityLoaderImpl.java
irmann/torpay-
b78988665572a2090cb7e57b5f04ce3a3b61fde3
[ "Apache-2.0" ]
null
null
null
31.273504
94
0.749112
996,255
package org.torpay.service.core.activity.controller; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import org.springframework.util.ClassUtils; import org.springframework.util.SystemPropertyUtils; import org.torpay.common.util.ErrorCodes; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ActivityLoaderImpl implements ActivityLoader { private List<String> path; private static List<CoreActivity> activities; static final Logger LOG = LoggerFactory.getLogger(ActivityLoaderImpl.class); public List<CoreActivity> loadActivities() throws ActivityControllException { if (activities != null) return activities; activities = new ArrayList<CoreActivity>(); if (path == null) throw new ActivityControllException( ErrorCodes.TECHNICAL_ERROR, "internal error during loading activities: path of activities is null", "ActivityLoader"); else if (path.size() == 0) LOG.warn("path is empty"); ; List<Class> classes = new ArrayList<Class>(); try { for (String p : path) { LOG.debug(" loading from path " + p); classes = findMyTypes(p); for (Class c : classes) { Object object = c.getConstructor().newInstance(); if (object instanceof CoreActivity) { LOG.debug("object activity " + c.getName() + " is created"); activities.add((CoreActivity) object); } } } } catch (Exception e) { throw new ActivityControllException(ErrorCodes.TECHNICAL_ERROR, "internal error during loading activities", "ActivityLoader", e); } return activities; } public List<String> getPath() { return path; } public void setPath(List<String> path) { this.path = path; } private List<Class> findMyTypes(String basePackage) throws IOException, ClassNotFoundException { ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory( resourcePatternResolver); List<Class> candidates = new ArrayList<Class>(); String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage) + "/" + "**/*.class"; Resource[] resources = resourcePatternResolver .getResources(packageSearchPath); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader = metadataReaderFactory .getMetadataReader(resource); if (isCandidate(metadataReader)) { candidates.add(Class.forName(metadataReader .getClassMetadata().getClassName())); } } } return candidates; } private String resolveBasePackage(String basePackage) { return ClassUtils.convertClassNameToResourcePath(SystemPropertyUtils .resolvePlaceholders(basePackage)); } private boolean isCandidate(MetadataReader metadataReader) throws ClassNotFoundException { try { Class c = Class.forName(metadataReader.getClassMetadata() .getClassName()); // if (c.getAnnotation(XmlRootElement.class) != null) { return true; // } } catch (Throwable e) { e.printStackTrace(); } return false; } }
92328abe51c9f93f88a3b8400adb429fe5a5f813
2,354
java
Java
src/test/java/nextstep/subway/acceptance/PathAcceptanceTest.java
00hongjun/atdd-subway-path
29201361b526453dbeda83cc60e1feecdac43fdd
[ "MIT" ]
null
null
null
src/test/java/nextstep/subway/acceptance/PathAcceptanceTest.java
00hongjun/atdd-subway-path
29201361b526453dbeda83cc60e1feecdac43fdd
[ "MIT" ]
null
null
null
src/test/java/nextstep/subway/acceptance/PathAcceptanceTest.java
00hongjun/atdd-subway-path
29201361b526453dbeda83cc60e1feecdac43fdd
[ "MIT" ]
null
null
null
28.361446
92
0.680544
996,256
package nextstep.subway.acceptance; import io.restassured.response.ExtractableResponse; import io.restassured.response.Response; import nextstep.subway.acceptance.step_feature.StationStepFeature; import nextstep.subway.applicaion.dto.PathResponse; import nextstep.subway.applicaion.dto.StationResponse; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.http.HttpStatus; import java.util.Arrays; import static nextstep.subway.acceptance.step_feature.LineStepFeature.*; import static nextstep.subway.acceptance.step_feature.PathServiceStepFeature.*; @DisplayName("지하철 노선 관리 기능") class PathAcceptanceTest extends AcceptanceTest { private StationResponse 강남역; private StationResponse 판교역; private StationResponse 교대역; @BeforeEach void setUpStation() { 강남역 = StationStepFeature.지하철역_생성_조회_요청("강남역"); 판교역 = StationStepFeature.지하철역_생성_조회_요청("판교역"); 교대역 = StationStepFeature.지하철역_생성_조회_요청("교대역"); 지하철_노선_생성_조회_요청(노선_생성_Param_생성("신분당선", 신분당선_색, 강남역.getId(), 판교역.getId(), 30)); 지하철_노선_생성_조회_요청(노선_생성_Param_생성("2호선", "green", 교대역.getId(), 강남역.getId(), 40)); } /** * When 가장 짧은 경로를 요청하면 * Then 짧은 경로의 역들을 순서대로 응답 받는다 */ @DisplayName("짧은 경로 조회") @Test void findShortestPath() { // when PathResponse response = 최단경로_조회_요청_응답(판교역.getId(), 교대역.getId()); // then 최단경로_조회_응답_검증(response, Arrays.asList(판교역.getName(), 강남역.getName(), 교대역.getName())); } /** * When 없는 역을 기준으로 가장 짧은 경로를 요청하면 * Then 400 status code를 응답한다. */ @DisplayName("없는 역을 조회하면 400응답을 받는다") @Test void findShortestPath_notFoundStation() { // given long 없는역Id = 1000; // when ExtractableResponse<Response> response = 최단경로_조회_요청(판교역.getId(), 없는역Id); // then 최단경로_조회_응답상태_검증(response, HttpStatus.BAD_REQUEST); } /** * When 출발역과 도착역이 같은 경로를 조회 하면 * Then 400 status code를 응답한다. */ @DisplayName("출발역과 도착역이 같으면 400응답을 받는다") @Test void findShortestPath_sameStation() { // when ExtractableResponse<Response> response = 최단경로_조회_요청(판교역.getId(), 판교역.getId()); // then 최단경로_조회_응답상태_검증(response, HttpStatus.BAD_REQUEST); } }
92328b06540d3169723fa768c6bec91a520c875c
515
java
Java
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/ScheduledHardwareUpgradeInfoHardwareUpgradeStatus.java
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
504cbeec6fce27a4b6b23887b28d6a4e85393f4b
[ "Apache-2.0" ]
null
null
null
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/ScheduledHardwareUpgradeInfoHardwareUpgradeStatus.java
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
504cbeec6fce27a4b6b23887b28d6a4e85393f4b
[ "Apache-2.0" ]
null
null
null
HTML5/dev/simplivity-citrixplugin-service/src/main/java/com/vmware/vim25/ScheduledHardwareUpgradeInfoHardwareUpgradeStatus.java
HewlettPackard/SimpliVity-Citrix-VCenter-Plugin
504cbeec6fce27a4b6b23887b28d6a4e85393f4b
[ "Apache-2.0" ]
1
2018-10-03T16:53:11.000Z
2018-10-03T16:53:11.000Z
21.458333
110
0.667961
996,257
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.06.12 at 09:16:35 AM EDT // package com.vmware.vim25; /** * */ public enum ScheduledHardwareUpgradeInfoHardwareUpgradeStatus { none, pending, success, failed; }
92328bdac1d979d9d3c24ebfad972b22451d6600
3,938
java
Java
BaristaMatic/src/main/java/cis365week2/baristamatic/Recipe.java
MattGuzowski/MattGuzowski_Assignment2
245498fdf96b907189d0f61e2c6d3e2a0e1cf83d
[ "MIT" ]
null
null
null
BaristaMatic/src/main/java/cis365week2/baristamatic/Recipe.java
MattGuzowski/MattGuzowski_Assignment2
245498fdf96b907189d0f61e2c6d3e2a0e1cf83d
[ "MIT" ]
null
null
null
BaristaMatic/src/main/java/cis365week2/baristamatic/Recipe.java
MattGuzowski/MattGuzowski_Assignment2
245498fdf96b907189d0f61e2c6d3e2a0e1cf83d
[ "MIT" ]
null
null
null
23.02924
82
0.589639
996,258
/* * code modified from https://github.com/stuff-and-exercises/barista-matic * modified to practice unit tests */ package cis365week2.baristamatic; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; public abstract class Recipe { public Map<String, Integer> recipe; public final String name; public double cost; protected Inventory inventory; public Recipe(String nameIn, Inventory inventoryIn) { inventory = inventoryIn; name = nameIn; recipe = new HashMap<String, Integer>(); setRecipe(); cost = (double) cost() / 100; } public double getCost() { return cost; } public void addIngredient(String ingredientIn, int qtyIn) { recipe.put(ingredientIn, qtyIn); } // Every new recipe has to specify the ingredients that will be using public abstract void setRecipe(); public void dispenseCoffee() { System.out.println("Dispensing: " + name); } public void outOfStock() { System.out.println("Out of Stock: " + name); } public Drink makeDrink() { Drink drink; if (isInStock()) { drink = new Drink(name); for (Entry<String, Integer> ingredient : recipe.entrySet()) { for (int i = 0; i < ingredient.getValue(); i++) { drink = inventory.get(ingredient.getKey()).addTo(drink); } } dispenseCoffee(); return drink; } else { outOfStock(); return null; } } public boolean isInStock() { for (Entry<String, Integer> ingredient : recipe.entrySet()) { if (!inventory.enoughOf(ingredient.getKey(), ingredient.getValue())) { return false; } } return true; } public int cost() { int cost = 0; for (Entry<String, Integer> ingredient : recipe.entrySet()) { for (int i = 0; i < ingredient.getValue(); i++) { cost += inventory.getCost(ingredient.getKey()); } } return cost; } } class CoffeeRecipe extends Recipe { public CoffeeRecipe(Inventory inventory) { super("Coffee", inventory); } @Override public void setRecipe() { addIngredient("Coffee", 3); addIngredient("Sugar", 1); addIngredient("Cream", 1); } } class DecafCoffeeRecipe extends Recipe { public DecafCoffeeRecipe(Inventory inventory) { super("Decaf Coffee", inventory); } @Override public void setRecipe() { addIngredient("Decaf Coffee", 3); addIngredient("Sugar", 1); addIngredient("Cream", 1); } } class CaffeLatteRecipe extends Recipe { public CaffeLatteRecipe(Inventory inventory) { super("Caffe Latte", inventory); } @Override public void setRecipe() { addIngredient("Espresso", 2); addIngredient("Steamed Milk", 1); } } class CaffeAmericanoRecipe extends Recipe { public CaffeAmericanoRecipe(Inventory inventory) { super("Caffe Americano", inventory); } @Override public void setRecipe() { addIngredient("Espresso", 3); } } class CaffeMochaRecipe extends Recipe { public CaffeMochaRecipe(Inventory inventory) { super("Caffe Mocha", inventory); } @Override public void setRecipe() { addIngredient("Espresso", 1); addIngredient("Cocoa", 1); addIngredient("Steamed Milk", 1); addIngredient("Whipped Cream", 1); } } class CappuccinoRecipe extends Recipe { public CappuccinoRecipe(Inventory inventory) { super("Cappuccino", inventory); } @Override public void setRecipe() { addIngredient("Espresso", 2); addIngredient("Steamed Milk", 1); addIngredient("Foamed Milk", 1); } }
92328c5e4814aa9d8bb74dc8e6cbe10999b42b9e
613
java
Java
app/models/Filme.java
PedroSilvano/Pop-Films
ab01c765a2a68212ad5f9c1e227273d0087f8016
[ "CC0-1.0" ]
null
null
null
app/models/Filme.java
PedroSilvano/Pop-Films
ab01c765a2a68212ad5f9c1e227273d0087f8016
[ "CC0-1.0" ]
null
null
null
app/models/Filme.java
PedroSilvano/Pop-Films
ab01c765a2a68212ad5f9c1e227273d0087f8016
[ "CC0-1.0" ]
null
null
null
22.703704
104
0.690049
996,259
package models; import play.data.*; import javax.persistence.*; import io.ebean.*; import java.util.Date; import java.text.SimpleDateFormat; @Entity public class Filme extends Model { @Id public long id; public String nome, genero; public Date data_lancamento; public static final Finder<Long, Filme> find = new Finder<>(Filme.class); public String dataLancamentoFormat(Date dataLancamento){ SimpleDateFormat fmt = new SimpleDateFormat("dd/MM/yyyy"); // fmt.parse("17/12/2007 19:30:20"); String dataf = fmt.format(dataLancamento); return dataf; } }
92328cb19f21a91277b36350f736d989f486fd1f
5,212
java
Java
org/openxmlformats/schemas/wordprocessingml/x2006/main/SettingsDocument.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
null
null
null
org/openxmlformats/schemas/wordprocessingml/x2006/main/SettingsDocument.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
null
null
null
org/openxmlformats/schemas/wordprocessingml/x2006/main/SettingsDocument.java
AlhonGelios/AO
3e78fefe875ab102016e1259874886970e3c5c2a
[ "Apache-2.0" ]
null
null
null
44.931034
215
0.76746
996,260
package org.openxmlformats.schemas.wordprocessingml.x2006.main; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.net.URL; import javax.xml.stream.XMLStreamReader; import org.apache.poi.POIXMLTypeLoader; import org.apache.xmlbeans.SchemaType; import org.apache.xmlbeans.XmlBeans; import org.apache.xmlbeans.XmlException; import org.apache.xmlbeans.XmlObject; import org.apache.xmlbeans.XmlOptions; import org.apache.xmlbeans.xml.stream.XMLInputStream; import org.apache.xmlbeans.xml.stream.XMLStreamException; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSettings; import org.w3c.dom.Node; public interface SettingsDocument extends XmlObject { SchemaType type = (SchemaType)XmlBeans.typeSystemForClassLoader(SettingsDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.sF1327CCA741569E70F9CA8C9AF9B44B2").resolveHandle("settings9dd1doctype"); CTSettings getSettings(); void setSettings(CTSettings var1); CTSettings addNewSettings(); public static final class Factory { public static SettingsDocument newInstance() { return (SettingsDocument)POIXMLTypeLoader.newInstance(SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument newInstance(XmlOptions var0) { return (SettingsDocument)POIXMLTypeLoader.newInstance(SettingsDocument.type, var0); } public static SettingsDocument parse(String var0) throws XmlException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(String var0, XmlOptions var1) throws XmlException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(File var0) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(File var0, XmlOptions var1) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(URL var0) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(URL var0, XmlOptions var1) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(InputStream var0) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(InputStream var0, XmlOptions var1) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(Reader var0) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(Reader var0, XmlOptions var1) throws XmlException, IOException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(XMLStreamReader var0) throws XmlException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(XMLStreamReader var0, XmlOptions var1) throws XmlException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(Node var0) throws XmlException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(Node var0, XmlOptions var1) throws XmlException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static SettingsDocument parse(XMLInputStream var0) throws XmlException, XMLStreamException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, (XmlOptions)null); } public static SettingsDocument parse(XMLInputStream var0, XmlOptions var1) throws XmlException, XMLStreamException { return (SettingsDocument)POIXMLTypeLoader.parse(var0, SettingsDocument.type, var1); } public static XMLInputStream newValidatingXMLInputStream(XMLInputStream var0) throws XmlException, XMLStreamException { return POIXMLTypeLoader.newValidatingXMLInputStream(var0, SettingsDocument.type, (XmlOptions)null); } public static XMLInputStream newValidatingXMLInputStream(XMLInputStream var0, XmlOptions var1) throws XmlException, XMLStreamException { return POIXMLTypeLoader.newValidatingXMLInputStream(var0, SettingsDocument.type, var1); } } }
92328d6686b5978385f7a17ef41d0821fa349e64
771
java
Java
src/test/java/com/conveyal/datatools/UnitTest.java
mvanlaar/datatools-server
87350ca686d7d6743168c5a34f9c18eef4861c4d
[ "MIT" ]
26
2019-06-20T21:46:40.000Z
2022-03-11T12:32:39.000Z
src/test/java/com/conveyal/datatools/UnitTest.java
mvanlaar/datatools-server
87350ca686d7d6743168c5a34f9c18eef4861c4d
[ "MIT" ]
255
2019-05-22T16:19:43.000Z
2022-03-25T18:58:22.000Z
src/test/java/com/conveyal/datatools/UnitTest.java
mvanlaar/datatools-server
87350ca686d7d6743168c5a34f9c18eef4861c4d
[ "MIT" ]
22
2019-06-20T18:47:58.000Z
2022-03-04T16:29:43.000Z
38.55
119
0.736706
996,261
package com.conveyal.datatools; import org.junit.jupiter.api.BeforeAll; import static org.junit.jupiter.api.Assumptions.assumeFalse; /** * This class is used by all unit tests to indicate that all test cases are not part of the end-to-end tests. This way, * if the e2e tests should be ran, all the unit tests can be skipped in order to save time and generate appropriate * code coverage reports. */ public abstract class UnitTest { @BeforeAll public static void beforeAll () { // make sure the RUN_E2E environment variable is set to true. Otherwise, this test suite should be skipped and // the overall build should not depend on inheriting test suites passing in order to save time. assumeFalse(TestUtils.isRunningE2E()); } }
92328db55ed76d6039daa25887ca7cbf4ca46291
3,259
java
Java
Programming/Lab6/client/src/main/java/commands/ExecuteScriptCommand.java
spynad/ITMO_Study
f9f7753ef4af24648fce1cbef6564ce6e757f14d
[ "MIT" ]
1
2021-04-26T02:22:17.000Z
2021-04-26T02:22:17.000Z
Programming/Lab6/client/src/main/java/commands/ExecuteScriptCommand.java
spynad/ITMO_Study
f9f7753ef4af24648fce1cbef6564ce6e757f14d
[ "MIT" ]
null
null
null
Programming/Lab6/client/src/main/java/commands/ExecuteScriptCommand.java
spynad/ITMO_Study
f9f7753ef4af24648fce1cbef6564ce6e757f14d
[ "MIT" ]
null
null
null
41.782051
132
0.617981
996,262
package commands; import client.Application; import exception.*; import io.ScriptRouteParser; import io.UserIO; import locale.ClientLocale; import route.Response; import java.io.*; public class ExecuteScriptCommand extends AbstractCommand { CommandInvoker commandInvoker; Application application; UserIO userIO; String[] args; String fileName; public ExecuteScriptCommand(Application application, CommandInvoker commandInvoker, UserIO userIO) { this.application = application; this.commandInvoker = commandInvoker; this.userIO = userIO; } @Override public void setArgs(String[] args) { this.args = args.clone(); } @Override public void execute() throws CommandExecutionException { try { if (args.length == 1) { fileName = args[0]; } else { throw new InvalidArgumentException(String.format(ClientLocale.getString("exception.expected_got"), 1, args.length)); } } catch (InvalidArgumentException iae) { throw new CommandExecutionException(iae.getMessage()); } try (BufferedReader reader = new BufferedReader(new FileReader(fileName))){ if (commandInvoker.getScripts().contains(fileName)) { throw new IllegalStateException(ClientLocale.getString("exception.recursive_script_call")+": " + fileName); } commandInvoker.addScript(fileName); while (reader.ready()) { String commands = reader.readLine(); try { commandInvoker.execute(commands, null); } catch (CommandNotFoundException e) { try { Response response = application.communicateWithServer(commands, new ScriptRouteParser(reader, userIO)); userIO.printLine(response.getMessage()); } catch (EOFException eofe) { userIO.printErrorMessage(ClientLocale.getString("exception.too_many_bytes")); } catch (IOException | ClassNotFoundException ioe) { userIO.printErrorMessage(ClientLocale.getString("exception.general_network")+": " + ioe.getMessage()); } catch (RouteReadException | RouteBuildException | IllegalStateException ex) { userIO.printErrorMessage(e.getMessage()); } } catch (CommandExecutionException executionException) { userIO.printErrorMessage(ClientLocale.getString("exception.command_exec_error") + ": " + executionException.getMessage()); } } commandInvoker.removeScript(fileName); } catch (IllegalStateException ise) { userIO.printErrorMessage(ClientLocale.getString("exception.script_exec_error")); } catch (FileNotFoundException fnfe) { userIO.printErrorMessage(ClientLocale.getString("exception.script_not_found")+": " + fileName); } catch (IOException e) { userIO.printErrorMessage(ClientLocale.getString("exception.script_read_error")+": " + e.getMessage()); } } }
92328dfbed520df5e3d40d592fc3ae88e63adb34
17,227
java
Java
library/src/main/java/com/sababado/circularview/CircularViewObject.java
sababado/CircularView
c9ab818d063bcc0796183616f8a82166a9b80aac
[ "Apache-2.0" ]
66
2015-01-04T01:18:52.000Z
2020-12-03T09:55:48.000Z
library/src/main/java/com/sababado/circularview/CircularViewObject.java
sababado/CircularView
c9ab818d063bcc0796183616f8a82166a9b80aac
[ "Apache-2.0" ]
9
2015-04-24T21:20:53.000Z
2018-10-28T21:56:36.000Z
library/src/main/java/com/sababado/circularview/CircularViewObject.java
sababado/CircularView
c9ab818d063bcc0796183616f8a82166a9b80aac
[ "Apache-2.0" ]
26
2015-01-13T06:02:20.000Z
2020-02-17T07:23:58.000Z
34.112871
231
0.601904
996,263
package com.sababado.circularview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.StateSet; import android.view.MotionEvent; import android.view.View; import java.util.concurrent.atomic.AtomicInteger; /** * TODO Document * don't forget refs */ public class CircularViewObject { /* * View states are largely copied from View.java. * Not all states are required at the moment so there are some gaps. */ private static final int[][] VIEW_STATE_SETS; static final int VIEW_STATE_SELECTED = 1 << 1; static final int VIEW_STATE_FOCUSED = 1 << 2; static final int VIEW_STATE_PRESSED = 1 << 4; static final int[] VIEW_STATE_IDS = new int[]{ 0, 0, android.R.attr.state_selected, VIEW_STATE_SELECTED, android.R.attr.state_focused, VIEW_STATE_FOCUSED, 0, 0, android.R.attr.state_pressed, VIEW_STATE_PRESSED }; static { final int NUM_BITS = VIEW_STATE_IDS.length / 2; VIEW_STATE_SETS = new int[1 << NUM_BITS][]; VIEW_STATE_SETS[0] = StateSet.NOTHING; VIEW_STATE_SETS[VIEW_STATE_SELECTED] = new int[]{android.R.attr.state_selected}; VIEW_STATE_SETS[VIEW_STATE_FOCUSED] = new int[]{android.R.attr.state_focused}; VIEW_STATE_SETS[VIEW_STATE_PRESSED] = new int[]{android.R.attr.state_pressed}; VIEW_STATE_SETS[VIEW_STATE_SELECTED | VIEW_STATE_FOCUSED] = new int[]{android.R.attr.state_selected, android.R.attr.state_focused}; VIEW_STATE_SETS[VIEW_STATE_SELECTED | VIEW_STATE_PRESSED] = new int[]{android.R.attr.state_selected, android.R.attr.state_pressed}; VIEW_STATE_SETS[VIEW_STATE_PRESSED | VIEW_STATE_FOCUSED] = new int[]{android.R.attr.state_pressed, android.R.attr.state_focused}; VIEW_STATE_SETS[VIEW_STATE_SELECTED | VIEW_STATE_PRESSED | VIEW_STATE_FOCUSED] = new int[]{android.R.attr.state_selected, android.R.attr.state_pressed, android.R.attr.state_focused}; } private int mCombinedState; private static final AtomicInteger sAtomicIdCounter = new AtomicInteger(0); private final int id; protected float radius; protected float radiusPadding; protected float x; protected float y; private final Paint paint; private final Context context; private Drawable drawable; private CircularView.AdapterDataSetObserver mAdapterDataSetObserver; private boolean fitToCircle; private int visibility; /** * Use this value to make sure that no color shows. */ public static final int NO_COLOR = -1; /** * Create a new CircularViewObject with the current context. * * @param context Current context. */ public CircularViewObject(final Context context) { this.context = context; id = sAtomicIdCounter.getAndAdd(1); paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setStyle(Paint.Style.FILL); paint.setColor(NO_COLOR); setRadiusPadding(5f); fitToCircle = false; visibility = View.VISIBLE; } CircularViewObject(final Context context, final float radiusPadding, final int centerBackgroundColor) { this(context); setRadiusPadding(radiusPadding); paint.setColor(centerBackgroundColor); } protected void init(final float x, final float y, final float radius, final CircularView.AdapterDataSetObserver adapterDataSetObserver) { this.x = x; this.y = y; setRadius(radius); this.mAdapterDataSetObserver = adapterDataSetObserver; } protected void draw(final Canvas canvas) { if (visibility == View.VISIBLE) { if (paint.getColor() != NO_COLOR) { canvas.drawCircle(x, y, radius, paint); } if (drawable != null) { float leftOffset = -radius + radiusPadding; float topOffset = -radius + radiusPadding; float rightOffset = radius - radiusPadding; float bottomOffset = radius - radiusPadding; if (fitToCircle) { final double extraOffset = distanceFromCenter(x + leftOffset, y + topOffset) - radius; leftOffset += extraOffset; topOffset += extraOffset; rightOffset -= extraOffset; bottomOffset -= extraOffset; } drawable.setBounds( (int) (x + leftOffset), (int) (y + topOffset), (int) (x + rightOffset), (int) (y + bottomOffset) ); drawable.draw(canvas); } } } /** * Check to see if a point is in the center circle or not. * This simply uses the distance formula to get the distance from the center of the circle * to the given point and then compares that to the circle's radius. * * @param x X coordinate. * @param y Y coordinate. * @return True if the point is within the circle, false if not. */ public boolean isInCenterCircle(final float x, final float y) { final double c = distanceFromCenter(x, y); return c <= radius; } /** * Get the distance from the given point to the center of this object. * * @param x X coordinate. * @param y Y coordinate. * @return Distance from the given point to the center of this object. */ public double distanceFromCenter(final float x, final float y) { return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2)); } /** * Get this Object's unique ID. The ID is generated atomically on initialization. * * @return Atomically generated ID. */ public int getId() { return id; } /** * Set the object's visual as a bitmap. * * @param bitmap Bitmap to display. */ public void setSrc(Bitmap bitmap) { setSrc(new BitmapDrawable(context.getResources(), bitmap)); } /** * Set the object's visual by using a resource id. * * @param resId Resource id of the drawable to display. */ public void setSrc(final int resId) { // setSrc(BitmapFactory.decodeResource(context.getResources(), resId)); setSrc(context.getResources().getDrawable(resId)); } /** * Set the object's visual as a drawable. * * @param drawable Drawable to display. */ public void setSrc(final Drawable drawable) { this.drawable = drawable; invalidate(); } void setCallback(final View view) { if (drawable != null) { drawable.setCallback(view); } } /** * Specify a set of states for the drawable. These are use-case specific, so see the relevant documentation. As an example, the background for widgets like Button understand the following states: [state_focused, state_pressed]. * * * If the new state you are supplying causes the appearance of the Drawable to change, then it is responsible for calling invalidateSelf() in order to have itself redrawn, and true will be returned from this function. * * * Note: The Drawable holds a reference on to stateSet until a new state array is given to it, so you must not modify this array during that time. * * @param stateSet The new set of states to be displayed. * @return Returns true if this change in state has caused the appearance of the Drawable to change (hence requiring an invalidate), otherwise returns false. */ public boolean setState(final int[] stateSet) { boolean appearanceChange = false; if (drawable != null) { appearanceChange = drawable.setState(stateSet); if (appearanceChange) { invalidate(); } } return appearanceChange; } /** * Either remove or add a state to the combined state. * * @param state State to add or remove. * @param flag True to add, false to remove. */ public void updateDrawableState(int state, boolean flag) { final int oldState = mCombinedState; // Update the combined state flag if (flag) mCombinedState |= state; else mCombinedState &= ~state; // Set the combined state if (oldState != mCombinedState) { setState(VIEW_STATE_SETS[mCombinedState]); } } /** * Get the object's drawable. * * @return The drawable. */ public Drawable getDrawable() { return drawable; } /** * Get the y position. * * @return The y position. */ public float getY() { return y; } /** * Set the y position. * * @param y The new y position. */ public void setY(float y) { this.y = y; invalidate(); } /** * Get the x position. * * @return The x position. */ public float getX() { return x; } /** * Set the x position. * * @param x The new x position. */ public void setX(float x) { this.x = x; invalidate(); } /** * Get the radius of the object. * * @return The radius. */ public float getRadius() { return radius; } /** * Set the radius of the object. * * @param radius The new radius. */ public void setRadius(float radius) { this.radius = radius; invalidate(); } /** * Get the object's visual padding from the radius. * * @return The object's visual padding from the radius. */ public float getRadiusPadding() { return radiusPadding; } /** * Set the object's visual padding from the radius. * * @param radiusPadding The object's visual padding from the radius. */ public void setRadiusPadding(float radiusPadding) { this.radiusPadding = radiusPadding; invalidate(); } /** * Gets the center background color attribute value. * * @return The center background color attribute value. */ public int getCenterBackgroundColor() { return paint.getColor(); } /** * Sets the view's center background color attribute value. * * @param centerBackgroundColor The color attribute value to use. */ public void setCenterBackgroundColor(int centerBackgroundColor) { paint.setColor(centerBackgroundColor); invalidate(); } CircularView.AdapterDataSetObserver getAdapterDataSetObserver() { return mAdapterDataSetObserver; } void setAdapterDataSetObserver(CircularView.AdapterDataSetObserver adapterDataSetObserver) { this.mAdapterDataSetObserver = adapterDataSetObserver; } /** * True if the object's drawable should fit inside the center circle. False if it will not. * * @return True if the object's drawable should fit inside the center circle. False if it will not. */ public boolean isFitToCircle() { return fitToCircle; } /** * Set to true if this object's drawable should fit inside of the center circle and false if not. * * @param fitToCircle Flag to determine if this drawable should fit inside the center circle. */ public void setFitToCircle(boolean fitToCircle) { this.fitToCircle = fitToCircle; invalidate(); } /** * Returns the visibility status for this view. * * @return One of {@link View#VISIBLE}, {@link View#INVISIBLE}, or {@link View#GONE}. */ public int getVisibility() { return visibility; } /** * Set the enabled state of this view. * * @param visibility One of {@link View#VISIBLE}, {@link View#INVISIBLE}, or {@link View#GONE}. */ public void setVisibility(int visibility) { if (this.visibility != visibility) { final boolean hasSpace = this.visibility == View.VISIBLE || this.visibility == View.INVISIBLE; final boolean removingSpace = visibility == View.GONE; final boolean change = hasSpace && removingSpace; this.visibility = visibility; // Only change the dataset if it is absolutely necessary if (change && mAdapterDataSetObserver != null) { mAdapterDataSetObserver.onChanged(); } else { invalidate(); } } } /** * Act on a touch event. Returns a status based on what action was taken. * * @param event The motion event that was just received. * @return Return a negative number if the event wasn't handled. Return a MotionEvent action code if it was handled. */ public int onTouchEvent(final MotionEvent event) { int status = -2; if (visibility != View.GONE) { final int action = event.getAction(); final boolean isEventInCenterCircle = isInCenterCircle(event.getX(), event.getY()); if (action == MotionEvent.ACTION_DOWN) { // check if center if (isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, true); status = MotionEvent.ACTION_DOWN; } } else if (action == MotionEvent.ACTION_UP) { final boolean isPressed = (mCombinedState & VIEW_STATE_PRESSED) != 0; if (isPressed && isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, false); status = MotionEvent.ACTION_UP; } } else if (action == MotionEvent.ACTION_MOVE) { if (!isEventInCenterCircle) { updateDrawableState(VIEW_STATE_PRESSED, false); } } } return status; } /** * Schedule the object's parent to redraw again. */ protected void invalidate() { if (mAdapterDataSetObserver != null) { mAdapterDataSetObserver.onInvalidated(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CircularViewObject object = (CircularViewObject) o; if (fitToCircle != object.fitToCircle) return false; if (id != object.id) return false; if (mCombinedState != object.mCombinedState) return false; if (Float.compare(object.radius, radius) != 0) return false; if (Float.compare(object.radiusPadding, radiusPadding) != 0) return false; if (visibility != object.visibility) return false; if (Float.compare(object.x, x) != 0) return false; if (Float.compare(object.y, y) != 0) return false; if (context != null ? !context.equals(object.context) : object.context != null) return false; if (drawable != null ? !drawable.equals(object.drawable) : object.drawable != null) return false; if (mAdapterDataSetObserver != null ? !mAdapterDataSetObserver.equals(object.mAdapterDataSetObserver) : object.mAdapterDataSetObserver != null) return false; if (paint != null ? !paint.equals(object.paint) : object.paint != null) return false; return true; } @Override public int hashCode() { int result = mCombinedState; result = 31 * result + id; result = 31 * result + (radius != +0.0f ? Float.floatToIntBits(radius) : 0); result = 31 * result + (radiusPadding != +0.0f ? Float.floatToIntBits(radiusPadding) : 0); result = 31 * result + (x != +0.0f ? Float.floatToIntBits(x) : 0); result = 31 * result + (y != +0.0f ? Float.floatToIntBits(y) : 0); result = 31 * result + (paint != null ? paint.hashCode() : 0); result = 31 * result + (context != null ? context.hashCode() : 0); result = 31 * result + (drawable != null ? drawable.hashCode() : 0); result = 31 * result + (mAdapterDataSetObserver != null ? mAdapterDataSetObserver.hashCode() : 0); result = 31 * result + (fitToCircle ? 1 : 0); result = 31 * result + visibility; return result; } @Override public String toString() { return "CircularViewObject{" + "mCombinedState=" + mCombinedState + ", id=" + id + ", radius=" + radius + ", radiusPadding=" + radiusPadding + ", x=" + x + ", y=" + y + ", paint=" + paint + ", context=" + context + ", drawable=" + drawable + ", mAdapterDataSetObserver=" + mAdapterDataSetObserver + ", fitToCircle=" + fitToCircle + ", visibility=" + visibility + '}'; } }
92328e7e1216c5d1bd3db2478b7d7da03a550272
1,263
java
Java
oxygen-core/src/test/java/vip/justlive/oxygen/core/util/concurrent/ResidentPoolTest.java
justlive1/oxygen
647d164e753ec5a0769e1e43aa47ea6d1eb44b88
[ "Apache-2.0" ]
163
2019-01-07T00:00:53.000Z
2021-07-26T03:29:27.000Z
oxygen-core/src/test/java/vip/justlive/oxygen/core/util/concurrent/ResidentPoolTest.java
justlive1/oxygen
647d164e753ec5a0769e1e43aa47ea6d1eb44b88
[ "Apache-2.0" ]
5
2021-02-03T10:48:30.000Z
2022-01-21T23:12:32.000Z
oxygen-core/src/test/java/vip/justlive/oxygen/core/util/concurrent/ResidentPoolTest.java
justlive1/oxygen
647d164e753ec5a0769e1e43aa47ea6d1eb44b88
[ "Apache-2.0" ]
14
2019-01-14T02:47:18.000Z
2020-08-18T14:25:23.000Z
28.704545
101
0.69517
996,264
/* * Copyright (C) 2021 the original author or 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 vip.justlive.oxygen.core.util.concurrent; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.concurrent.atomic.AtomicInteger; import org.junit.jupiter.api.Test; class ResidentPoolTest { @Test void test() { AtomicInteger count = new AtomicInteger(); ResidentPool pool = new ResidentPool(3); pool.add(new RepeatRunnable(() -> { count.incrementAndGet(); ThreadUtils.sleep(1000); })); ThreadUtils.sleep(3000); assertEquals(3, count.get()); pool.shutdown(); ThreadUtils.sleep(3000); assertEquals(3, count.get()); } }
92328ec1d5ec812ce18b6869e5175f1d15e3cad8
1,832
java
Java
src/api/java/io/core9/rules/AbstractRulesEngine.java
core9/module-rules
1c230f7979ca209ad223dbdefe1ed75987b0cc88
[ "MIT" ]
null
null
null
src/api/java/io/core9/rules/AbstractRulesEngine.java
core9/module-rules
1c230f7979ca209ad223dbdefe1ed75987b0cc88
[ "MIT" ]
null
null
null
src/api/java/io/core9/rules/AbstractRulesEngine.java
core9/module-rules
1c230f7979ca209ad223dbdefe1ed75987b0cc88
[ "MIT" ]
null
null
null
26.171429
102
0.731987
996,265
package io.core9.rules; import io.core9.plugin.server.VirtualHost; import io.core9.rules.handlers.RuleHandler; import java.util.HashMap; import java.util.List; import java.util.Map; public abstract class AbstractRulesEngine<T, K> implements RulesEngine<T, K> { private final Map<String, RuleHandler<T, K>> handlers = new HashMap<String, RuleHandler<T, K>>(); private final RulesRegistry registry = new RulesRegistry(); protected RulesRegistry getRulesRegistry() { return registry; } @Override public K handleRuleset(RuleSet ruleSet, T context, K result) throws RuleException { for(Rule rule : ruleSet.getRules()) { result = handlers.get(rule.getType()).handle(rule, context, result); switch (handleRuleResult(result)) { case STOP: return result; case EXCEPTION: throw new RuleException(); default: continue; } } return result; } public abstract Result handleRuleResult(K result); @Override public RulesEngine<T,K> addRuleHandler(String ruleType, RuleHandler<T, K> handler) { handlers.put(ruleType, handler); return this; } @Override public RuleHandler<T, K> getHandler(String ruleType) { return handlers.get(ruleType); } @Override public RulesEngine<T, K> addRuleSet(VirtualHost vhost, RuleSet ruleSet) { registry.addRuleSet(vhost, ruleSet); return this; } @Override public K handle(VirtualHost vhost, String ruleSet, T context, K result) throws RuleException { RuleSet set = registry.getRuleSet(vhost, ruleSet); return handleRuleset(set, context, result); } @Override public K handle(VirtualHost vhost, List<String> ruleSets, T context, K result) throws RuleException { for(String ruleSet : ruleSets) { RuleSet set = registry.getRuleSet(vhost, ruleSet); result = handleRuleset(set, context, result); } return result; } }
923290923a2118ed1dedc1616a6855d38aad727d
1,087
java
Java
src/org/fedoraproject/mbi/ci/model/MacroBuilder.java
mizdebsk/mbici-workflow
5f9d137376ce0c6a1fecb9275837c5f9178f39b4
[ "Apache-2.0" ]
null
null
null
src/org/fedoraproject/mbi/ci/model/MacroBuilder.java
mizdebsk/mbici-workflow
5f9d137376ce0c6a1fecb9275837c5f9178f39b4
[ "Apache-2.0" ]
7
2021-11-25T15:36:03.000Z
2022-02-16T06:43:31.000Z
src/org/fedoraproject/mbi/ci/model/MacroBuilder.java
mizdebsk/mbici-workflow
5f9d137376ce0c6a1fecb9275837c5f9178f39b4
[ "Apache-2.0" ]
null
null
null
23.630435
75
0.678013
996,266
/*- * Copyright (c) 2021 Red Hat, Inc. * * 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.fedoraproject.mbi.ci.model; import org.fedoraproject.mbi.xml.Builder; /** * @author Mikolaj Izdebski */ public class MacroBuilder implements Builder<Macro> { private String name; private String value; public void setName( String name ) { this.name = name; } public void setValue( String value ) { this.value = value; } @Override public Macro build() { return new Macro( name, value ); } }
923291243701f7d711b39e150d46bbf443c6eb5c
490
java
Java
prueba.java
CptRenko/LejosJAVA
b9f6fb9f9574f4db372983478f9e0e6333d8191d
[ "MIT" ]
null
null
null
prueba.java
CptRenko/LejosJAVA
b9f6fb9f9574f4db372983478f9e0e6333d8191d
[ "MIT" ]
null
null
null
prueba.java
CptRenko/LejosJAVA
b9f6fb9f9574f4db372983478f9e0e6333d8191d
[ "MIT" ]
null
null
null
23.333333
97
0.681633
996,267
package manipulacion; import lejos.nxt.SensorPort; public class prueba { public static void main(String[] args) { SensorPort[] sensor=new SensorPort[] {SensorPort.S1,SensorPort.S2,SensorPort.S3,SensorPort.S4}; Manipulacion prueba = new Manipulacion (sensor); Manipulacion.velocidad(100); for (int i = 0; i < 5; i++) { do { Manipulacion.mover('F'); Manipulacion.moverIndividual('A', 'B'); } while(prueba.getSensorUltrasonido().getDistance() > 35); } } }
923292c077f4282e3ce46c38bda5e658f443432b
5,459
java
Java
plugins/bluenimble-plugin-converter.pdf/src/main/java/com/bluenimble/platform/converter/pdf/services/SplitApiServiceSpi.java
bluenimble/serverless
909d8ec243e055f74c6bceaee475fdcb4a2db3de
[ "Apache-2.0" ]
38
2018-03-08T14:46:02.000Z
2019-05-04T00:28:56.000Z
plugins/bluenimble-plugin-converter.pdf/src/main/java/com/bluenimble/platform/converter/pdf/services/SplitApiServiceSpi.java
bluenimble/serverless
909d8ec243e055f74c6bceaee475fdcb4a2db3de
[ "Apache-2.0" ]
13
2020-03-04T21:53:20.000Z
2022-03-30T04:04:25.000Z
plugins/bluenimble-plugin-converter.pdf/src/main/java/com/bluenimble/platform/converter/pdf/services/SplitApiServiceSpi.java
bluenimble/serverless
909d8ec243e055f74c6bceaee475fdcb4a2db3de
[ "Apache-2.0" ]
4
2018-06-14T02:52:10.000Z
2018-09-10T17:43:34.000Z
35.219355
165
0.721927
996,268
/* * 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 com.bluenimble.platform.converter.pdf.services; import java.awt.image.BufferedImage; import java.util.Iterator; import javax.imageio.ImageIO; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.rendering.PDFRenderer; import com.bluenimble.platform.Json; import com.bluenimble.platform.Lang; import com.bluenimble.platform.api.Api; import com.bluenimble.platform.api.ApiOutput; import com.bluenimble.platform.api.ApiRequest; import com.bluenimble.platform.api.ApiResponse; import com.bluenimble.platform.api.ApiServiceExecutionException; import com.bluenimble.platform.api.ApiVerb; import com.bluenimble.platform.api.ApiRequest.Scope; import com.bluenimble.platform.api.ApiSpace.Endpoint; import com.bluenimble.platform.api.impls.JsonApiOutput; import com.bluenimble.platform.api.impls.spis.AbstractApiServiceSpi; import com.bluenimble.platform.api.security.ApiConsumer; import com.bluenimble.platform.json.JsonArray; import com.bluenimble.platform.json.JsonObject; import com.bluenimble.platform.storage.Folder; import com.bluenimble.platform.storage.Storage; import com.bluenimble.platform.storage.StorageObject; public class SplitApiServiceSpi extends AbstractApiServiceSpi { private static final long serialVersionUID = -6640536437255542851L; interface Spec { String File = "file"; String OutputDirectory = "out"; String OnFinish = "onFinish"; } @Override public ApiOutput execute (Api api, ApiConsumer consumer, ApiRequest request, ApiResponse response) throws ApiServiceExecutionException { String file = (String)request.getService ().getSpiDef ().get (Spec.File); JsonObject result = new JsonObject (); JsonArray files = new JsonArray (); result.set (ApiOutput.Defaults.Id, file); result.set (ApiOutput.Defaults.Items, files); String out = (String)request.getService ().getSpiDef ().get (Spec.OutputDirectory); try { Folder folder = feature (api, Storage.class, null, request).root (); Folder outFolder = (Folder)folder.get (out); PDDocument doc = PDDocument.load (folder.get (file).reader (request)); PDFRenderer renderer = new PDFRenderer(doc); for (int i = 0; i < doc.getNumberOfPages(); i++) { String oid = Lang.oid (); StorageObject outFile = outFolder.add (null, oid, false); BufferedImage image = renderer.renderImageWithDPI (i, 200); ImageIO.write (image, "JPEG", outFile.writer (request)); files.add (oid); } } catch (Exception ex) { throw new ApiServiceExecutionException (ex.getMessage (), ex); } if (request.getService ().getSpiDef ().containsKey (Spec.OnFinish)) { call ( api, consumer, request, Json.template (Json.getObject (request.getService ().getSpiDef (), Spec.OnFinish), result, true) ); } return new JsonApiOutput (result); } public static ApiOutput call (final Api api, final ApiConsumer consumer, final ApiRequest pRequest, final JsonObject oRequest) throws ApiServiceExecutionException { ApiRequest request = api.space ().request (pRequest, consumer, new Endpoint () { @Override public String space () { return Json.getString (oRequest, ApiRequest.Fields.Space, api.space ().getNamespace ()); } @Override public String api () { return Json.getString (oRequest, ApiRequest.Fields.Api, api.getNamespace ()); } @Override public String [] resource () { String resource = Json.getString (oRequest, ApiRequest.Fields.Resource); if (resource.startsWith (Lang.SLASH)) { resource = resource.substring (1); } if (resource.endsWith (Lang.SLASH)) { resource = resource.substring (0, resource.length () - 1); } if (Lang.isNullOrEmpty (resource)) { return null; } return Lang.split (resource, Lang.SLASH); } @Override public ApiVerb verb () { try { return ApiVerb.valueOf ( Json.getString (oRequest, ApiRequest.Fields.Verb, ApiVerb.POST.name ()).toUpperCase () ); } catch (Exception ex) { return ApiVerb.POST; } } }); JsonObject parameters = Json.getObject (oRequest, ApiRequest.Fields.Data.Parameters); if (!Json.isNullOrEmpty (parameters)) { Iterator<String> keys = parameters.keys (); while (keys.hasNext ()) { String key = keys.next (); request.set (key, parameters.get (key)); } } JsonObject headers = Json.getObject (oRequest, ApiRequest.Fields.Data.Headers); if (!Json.isNullOrEmpty (headers)) { Iterator<String> keys = headers.keys (); while (keys.hasNext ()) { String key = keys.next (); request.set (key, headers.get (key), Scope.Header); } } return api.call (request); } }
923295aa171c5415be17eb8a1fbd1ec3878fa933
3,574
java
Java
src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java
mismatch/JBake
38283d985982a035b2c03d5553f02e3d2f071caf
[ "MIT" ]
1
2017-03-17T23:01:24.000Z
2017-03-17T23:01:24.000Z
src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java
mismatch/JBake
38283d985982a035b2c03d5553f02e3d2f071caf
[ "MIT" ]
null
null
null
src/test/java/org/jbake/app/template/GroovyMarkupTemplateEngineRenderingTest.java
mismatch/JBake
38283d985982a035b2c03d5553f02e3d2f071caf
[ "MIT" ]
null
null
null
42.547619
144
0.618914
996,269
package org.jbake.app.template; import org.apache.commons.io.FileUtils; import org.jbake.app.Crawler; import org.jbake.app.DBUtil; import org.jbake.app.Parser; import org.jbake.app.Renderer; import org.jbake.model.DocumentTypes; import org.junit.Assert; import org.junit.Test; import java.io.File; import java.util.Arrays; import java.util.Map; import static org.assertj.core.api.Assertions.assertThat; public class GroovyMarkupTemplateEngineRenderingTest extends AbstractTemplateEngineRenderingTest { public GroovyMarkupTemplateEngineRenderingTest() { super("groovyMarkupTemplates", "tpl"); outputStrings.put("post", Arrays.asList("<h2>Second Post</h2>", "<p class=\"post-date\">28", "2013</p>", "Lorem ipsum dolor sit amet", "<h5>Published Posts</h5>", "blog/2012/first-post.html")); outputStrings.put("page", Arrays.asList("<h4>About</h4>", "All about stuff!", "<h5>Published Pages</h5>", "/projects.html")); outputStrings.put("index", Arrays.asList("<h4><a href=\"blog/2012/first-post.html\">First Post</a></h4>", "<h4><a href=\"blog/2013/second-post.html\">Second Post</a></h4>")); outputStrings.put("feed", Arrays.asList("<description>My corner of the Internet</description>", "<title>Second Post</title>", "<title>First Post</title>")); outputStrings.put("archive", Arrays.asList("<a href=\"blog/2013/second-post.html\">Second Post</a></h4>", "<a href=\"blog/2012/first-post.html\">First Post</a></h4>")); outputStrings.put("tags", Arrays.asList("<a href=\"blog/2013/second-post.html\">Second Post</a></h4>", "<a href=\"blog/2012/first-post.html\">First Post</a></h4>")); outputStrings.put("sitemap", Arrays.asList("blog/2013/second-post.html", "blog/2012/first-post.html", "papers/published-paper.html")); outputStrings.put("paper", Arrays.asList("<h2>Published Paper</h2>", "<p class=\"post-date\">24", "2014</p>", "Lorem ipsum dolor sit amet", "<h5>Published Posts</h5>", "<li>Published Paper published</li>")); } @Test public void renderCustomTypePaper() throws Exception { // setup config.setProperty("template.paper.file", "paper." + templateExtension); DocumentTypes.addDocumentType("paper"); DBUtil.updateSchema(db); Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Parser parser = new Parser(config, sourceFolder.getPath()); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); String filename = "published-paper.html"; File sampleFile = new File(sourceFolder.getPath() + File.separator + "content" + File.separator + "papers" + File.separator + filename); Map<String, Object> content = parser.processFile(sampleFile); content.put(Crawler.Attributes.URI, "/" + filename); renderer.render(content); File outputFile = new File(destinationFolder, filename); Assert.assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile); for (String string : getOutputStrings("paper")) { assertThat(output).contains(string); } } }
9232977d53463be56fc4913390e40fa859f702ae
793
java
Java
ailab.ontology.viewer.server/src/ru/ifmo/ailab/ontology/viewer/base/utils/ItemWithId.java
ailabitmo/AilabOntologyViewer
677461a15e5cbe323316caa4c9dc2d010286d26c
[ "Apache-2.0" ]
1
2020-06-03T23:27:56.000Z
2020-06-03T23:27:56.000Z
ailab.ontology.viewer.server/src/ru/ifmo/ailab/ontology/viewer/base/utils/ItemWithId.java
ailabitmo/AilabOntologyViewer
677461a15e5cbe323316caa4c9dc2d010286d26c
[ "Apache-2.0" ]
null
null
null
ailab.ontology.viewer.server/src/ru/ifmo/ailab/ontology/viewer/base/utils/ItemWithId.java
ailabitmo/AilabOntologyViewer
677461a15e5cbe323316caa4c9dc2d010286d26c
[ "Apache-2.0" ]
null
null
null
20.868421
80
0.615385
996,270
package ru.ifmo.ailab.ontology.viewer.base.utils; /** * Created with IntelliJ IDEA. * User: Kivan * Date: 15.03.13 * Time: 4:05 * To change this template use File | Settings | File Templates. * * %%% Нечто с абстрактным идентификатором */ public abstract class ItemWithId { /** * У наследника обязательно должен присутствовать конструктор без параметров */ public ItemWithId() { } public abstract String getId(); public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ItemWithId that = (ItemWithId) o; if (getId().equals(that.getId())) return false; return true; } public int hashCode() { return getId().hashCode(); } }
92329793eda86d629acb9bfb499e105a673d5198
11,509
java
Java
src/main/java/com/sun/jna/platform/win32/IPHlpAPI.java
supertsp/oshiOneLib
4ca05e6e3c795f1916533da88e02a9d75a047fca
[ "MIT" ]
1
2022-01-06T22:30:43.000Z
2022-01-06T22:30:43.000Z
src/main/java/com/sun/jna/platform/win32/IPHlpAPI.java
supertsp/oshiOneLib
4ca05e6e3c795f1916533da88e02a9d75a047fca
[ "MIT" ]
null
null
null
src/main/java/com/sun/jna/platform/win32/IPHlpAPI.java
supertsp/oshiOneLib
4ca05e6e3c795f1916533da88e02a9d75a047fca
[ "MIT" ]
null
null
null
41.250896
125
0.664437
996,271
/* Copyright (c) 2018 Daniel Widdis, All Rights Reserved * * The contents of this file is dual-licensed under 2 * alternative Open Source/Free licenses: LGPL 2.1 or later and * Apache License 2.0. (starting with JNA version 4.0.0). * * You can freely decide which license you want to apply to * the project. * * You may obtain a copy of the LGPL License at: * * http://www.gnu.org/licenses/licenses.html * * A copy is also included in the downloadable source code package * containing JNA, in file "LGPL2.1". * * You may obtain a copy of the Apache License at: * * http://www.apache.org/licenses/ * * A copy is also included in the downloadable source code package * containing JNA, in file "AL2.0". */ package com.sun.jna.platform.win32; import com.sun.jna.Library; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.Structure; import com.sun.jna.Structure.FieldOrder; import com.sun.jna.platform.win32.Guid.GUID; import com.sun.jna.ptr.IntByReference; import com.sun.jna.win32.W32APIOptions; /** * Windows IP Helper API * * @see <A HREF= * "https://msdn.microsoft.com/en-us/library/windows/desktop/aa373083(v=vs.85).aspx">IP * Helper Reference</A> */ public interface IPHlpAPI extends Library { IPHlpAPI INSTANCE = Native.load("IPHlpAPI", IPHlpAPI.class, W32APIOptions.DEFAULT_OPTIONS); int IF_MAX_STRING_SIZE = 256; int IF_MAX_PHYS_ADDRESS_LENGTH = 32; int MAX_INTERFACE_NAME_LEN = 256; int MAXLEN_IFDESCR = 256; int MAXLEN_PHYSADDR = 8; int MAX_HOSTNAME_LEN = 128; int MAX_DOMAIN_NAME_LEN = 128; int MAX_SCOPE_ID_LEN = 256; /** * The MIB_IFROW structure stores information about a particular interface. * * @see <A HREF= * "https://docs.microsoft.com/en-us/previous-versions/windows/desktop/api/ifmib/ns-ifmib-_mib_ifrow">MIB_IFROW</A> */ @FieldOrder({ "wszName", "dwIndex", "dwType", "dwMtu", "dwSpeed", "dwPhysAddrLen", "bPhysAddr", "dwAdminStatus", "dwOperStatus", "dwLastChange", "dwInOctets", "dwInUcastPkts", "dwInNUcastPkts", "dwInDiscards", "dwInErrors", "dwInUnknownProtos", "dwOutOctets", "dwOutUcastPkts", "dwOutNUcastPkts", "dwOutDiscards", "dwOutErrors", "dwOutQLen", "dwDescrLen", "bDescr" }) class MIB_IFROW extends Structure { public char[] wszName = new char[MAX_INTERFACE_NAME_LEN]; public int dwIndex; public int dwType; public int dwMtu; public int dwSpeed; public int dwPhysAddrLen; public byte[] bPhysAddr = new byte[MAXLEN_PHYSADDR]; public int dwAdminStatus; public int dwOperStatus; public int dwLastChange; public int dwInOctets; public int dwInUcastPkts; public int dwInNUcastPkts; public int dwInDiscards; public int dwInErrors; public int dwInUnknownProtos; public int dwOutOctets; public int dwOutUcastPkts; public int dwOutNUcastPkts; public int dwOutDiscards; public int dwOutErrors; public int dwOutQLen; public int dwDescrLen; public byte[] bDescr = new byte[MAXLEN_IFDESCR]; } /** * The MIB_IF_ROW2 structure stores information about a particular * interface. * * @see <A HREF= * "https://msdn.microsoft.com/library/windows/hardware/ff559214">MIB_IF_ROW2</A> */ @FieldOrder({ "InterfaceLuid", "InterfaceIndex", "InterfaceGuid", "Alias", "Description", "PhysicalAddressLength", "PhysicalAddress", "PermanentPhysicalAddress", "Mtu", "Type", "TunnelType", "MediaType", "PhysicalMediumType", "AccessType", "DirectionType", "InterfaceAndOperStatusFlags", "OperStatus", "AdminStatus", "MediaConnectState", "NetworkGuid", "ConnectionType", "TransmitLinkSpeed", "ReceiveLinkSpeed", "InOctets", "InUcastPkts", "InNUcastPkts", "InDiscards", "InErrors", "InUnknownProtos", "InUcastOctets", "InMulticastOctets", "InBroadcastOctets", "OutOctets", "OutUcastPkts", "OutNUcastPkts", "OutDiscards", "OutErrors", "OutUcastOctets", "OutMulticastOctets", "OutBroadcastOctets", "OutQLen" }) class MIB_IF_ROW2 extends Structure { public long InterfaceLuid; // 64-bit union NET_LUID public int InterfaceIndex; public GUID InterfaceGuid; public char[] Alias = new char[IF_MAX_STRING_SIZE + 1]; public char[] Description = new char[IF_MAX_STRING_SIZE + 1]; public int PhysicalAddressLength; public byte[] PhysicalAddress = new byte[IF_MAX_PHYS_ADDRESS_LENGTH]; public byte[] PermanentPhysicalAddress = new byte[IF_MAX_PHYS_ADDRESS_LENGTH]; public int Mtu; public int Type; // enums public int TunnelType; public int MediaType; public int PhysicalMediumType; public int AccessType; public int DirectionType; // 8-bit structure public byte InterfaceAndOperStatusFlags; // enums public int OperStatus; public int AdminStatus; public int MediaConnectState; public GUID NetworkGuid; public int ConnectionType; public long TransmitLinkSpeed; public long ReceiveLinkSpeed; public long InOctets; public long InUcastPkts; public long InNUcastPkts; public long InDiscards; public long InErrors; public long InUnknownProtos; public long InUcastOctets; public long InMulticastOctets; public long InBroadcastOctets; public long OutOctets; public long OutUcastPkts; public long OutNUcastPkts; public long OutDiscards; public long OutErrors; public long OutUcastOctets; public long OutMulticastOctets; public long OutBroadcastOctets; public long OutQLen; } /** * The IP_ADDRESS_STRING structure stores an IPv4 address in dotted decimal * notation. The IP_ADDRESS_STRING structure definition is also the type * definition for the IP_MASK_STRING structure. * * @see <A HREF= * "https://docs.microsoft.com/en-us/windows/desktop/api/iptypes/ns-iptypes-ip_address_string">IP_ADDRESS_STRING</A> */ @FieldOrder({ "String" }) class IP_ADDRESS_STRING extends Structure { // Null terminated string // up to 3 chars (decimal 0-255) and dot // ending with null public byte[] String = new byte[16]; } /** * The IP_ADDR_STRING structure represents a node in a linked-list of IPv4 * addresses. * * @see <A HREF= * "https://docs.microsoft.com/en-us/windows/desktop/api/iptypes/ns-iptypes-_ip_addr_string">IP_ADDR_STRING</A> */ @FieldOrder({ "Next", "IpAddress", "IpMask", "Context" }) class IP_ADDR_STRING extends Structure { public IP_ADDR_STRING.ByReference Next; public IP_ADDRESS_STRING IpAddress; public IP_ADDRESS_STRING IpMask; public int Context; public static class ByReference extends IP_ADDR_STRING implements Structure.ByReference { } } /** * The FIXED_INFO structure contains information that is the same across all * the interfaces on a computer. * * @see <A HREF= * "https://docs.microsoft.com/en-us/windows/desktop/api/iptypes/ns-iptypes-fixed_info_w2ksp1">FIXED_INFO</A> */ @FieldOrder({ "HostName", "DomainName", "CurrentDnsServer", "DnsServerList", "NodeType", "ScopeId", "EnableRouting", "EnableProxy", "EnableDns" }) class FIXED_INFO extends Structure { public byte[] HostName = new byte[MAX_HOSTNAME_LEN + 4]; public byte[] DomainName = new byte[MAX_DOMAIN_NAME_LEN + 4]; public IP_ADDR_STRING.ByReference CurrentDnsServer; public IP_ADDR_STRING DnsServerList; public int NodeType; public byte[] ScopeId = new byte[MAX_SCOPE_ID_LEN + 4]; public int EnableRouting; public int EnableProxy; public int EnableDns; public FIXED_INFO(Pointer p) { super(p); read(); } public FIXED_INFO() { super(); } } /** * The GetIfEntry function retrieves information for the specified interface * on the local computer. * * The dwIndex member in the MIB_IFROW structure pointed to by the pIfRow * parameter must be initialized to a valid network interface index * retrieved by a previous call to the GetIfTable, GetIfTable2, or * GetIfTable2Ex function. The GetIfEntry function will fail if the dwIndex * member of the MIB_IFROW pointed to by the pIfRow parameter does not match * an existing interface index on the local computer. * * @param pIfRow * A pointer to a MIB_IFROW structure that, on successful return, * receives information for an interface on the local computer. * On input, set the dwIndex member of MIB_IFROW to the index of * the interface for which to retrieve information. * @return If the function succeeds, the return value is NO_ERROR. */ int GetIfEntry(MIB_IFROW pIfRow); /** * The GetIfEntry2 function retrieves information for the specified * interface on the local computer. * * On input, at least one of the following members in the MIB_IF_ROW2 * structure passed in the Row parameter must be initialized: InterfaceLuid * or InterfaceIndex. The fields are used in the order listed above. So if * the InterfaceLuid is specified, then this member is used to determine the * interface. If no value was set for the InterfaceLuid member (the value of * this member was set to zero), then the InterfaceIndex member is next used * to determine the interface. On output, the remaining fields of the * MIB_IF_ROW2 structure pointed to by the Row parameter are filled in. * * @param pIfRow2 * A pointer to a MIB_IF_ROW2 structure that, on successful * return, receives information for an interface on the local * computer. On input, the InterfaceLuid or the InterfaceIndex * member of the MIB_IF_ROW2 must be set to the interface for * which to retrieve information. * @return If the function succeeds, the return value is NO_ERROR. */ int GetIfEntry2(MIB_IF_ROW2 pIfRow2); /** * The GetNetworkParams function retrieves network parameters for the local * computer. * * @param pFixedInfo * A pointer to a buffer that contains a FIXED_INFO structure * that receives the network parameters for the local computer, * if the function was successful. This buffer must be allocated * by the caller prior to calling the GetNetworkParams function. * @param pOutBufLen * A pointer to a ULONG variable that specifies the size of the * FIXED_INFO structure. If this size is insufficient to hold the * information, GetNetworkParams fills in this variable with the * required size, and returns an error code of * ERROR_BUFFER_OVERFLOW. * @return If the function succeeds, the return value is ERROR_SUCCESS. */ int GetNetworkParams(Pointer pFixedInfo, IntByReference pOutBufLen); }
923297987c7515a007f8bfc25d27e0888d85b026
2,927
java
Java
src/main/java/chapter1/topic2/LeetCode_73.java
DonaldY/LeetCode-Practice
7bc79ba4444f7507c601c0f2a61165d751f781bf
[ "MIT" ]
2
2019-08-15T12:04:50.000Z
2021-08-16T00:40:00.000Z
src/main/java/chapter1/topic2/LeetCode_73.java
DonaldY/LeetCode-Practice
7bc79ba4444f7507c601c0f2a61165d751f781bf
[ "MIT" ]
null
null
null
src/main/java/chapter1/topic2/LeetCode_73.java
DonaldY/LeetCode-Practice
7bc79ba4444f7507c601c0f2a61165d751f781bf
[ "MIT" ]
null
null
null
23.416
61
0.373762
996,272
package chapter1.topic2; /** * 73. Set Matrix Zeroes * * Input: * [ * [1,1,1], * [1,0,1], * [1,1,1] * ] * Output: * [ * [1,0,1], * [0,0,0], * [1,0,1] * ] * * Input: * [ * [0,1,2,0], * [3,4,5,2], * [1,3,1,5] * ] * Output: * [ * [0,0,0,0], * [0,4,5,0], * [0,3,1,0] * ] * * 题意:将矩阵中为0的行与列都置为0 * * 思路: * 1. 两层for循环查询,并用两层for循环置 * 2. 用另一个数组来报存是否置零,然后查询 * 3. 使用一个标记变量: 对方法二进一步优化,只使用一个标记变量记录第一列是否原本存在 00。 * 这样,第一列的第一个元素即可以标记第一行是否出现 00。 * 但为了防止第一列的第一个元素被提前更新,我们需要从最后一行开始,倒序地处理矩阵元素。 * */ public class LeetCode_73 { public void setZeroes(int[][] matrix) { } // Time: o(m * n), Space: o(m + n), Faster: 100.00% public void setZeroInMatrix(int [][] a) { int m = a.length, n = a[0].length; boolean[] rows = new boolean[m]; boolean[] cols = new boolean[n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (a[i][j] == 0) rows[i] = cols[j] = true; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (rows[i] || cols[j]) a[i][j] = 0; } // Time: o(m * n), Space: o(1), Faster: 100.00% public void setZeroInMatrixO1(int [][] matrix) { int m = matrix.length, n = matrix[0].length; boolean row0 = false, col0 = false; for (int i = 0; i < m; ++i) if (matrix[i][0] == 0) col0 = true; for (int j = 0; j < n; ++j) if (matrix[0][j] == 0) row0 = true; for (int i = 1; i < m; ++i) { for (int j = 1; j < n; ++j) { if (matrix[i][j] == 0) { matrix[i][0] = matrix[0][j] = 0; } } } for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; if (row0) for (int j = 0; j < n; ++j) matrix[0][j] = 0; if (col0) for (int i = 0; i < m; ++i) matrix[i][0] = 0; } // Time: O(m * n), Space: O(1), Faster: 99.91% public void setZeroesMatrix02(int[][] matrix) { int m = matrix.length, n = matrix[0].length; boolean flagCol0 = false; for (int i = 0; i < m; i++) { if (matrix[i][0] == 0) { flagCol0 = true; } for (int j = 1; j < n; j++) { if (matrix[i][j] == 0) { matrix[i][0] = matrix[0][j] = 0; } } } for (int i = m - 1; i >= 0; i--) { for (int j = 1; j < n; j++) { if (matrix[i][0] == 0 || matrix[0][j] == 0) { matrix[i][j] = 0; } } if (flagCol0) { matrix[i][0] = 0; } } } }
923297a1f2a27e4ca87ba3f0fcb15e8aff78c733
5,235
java
Java
src/main/java/com/supervisor/domain/impl/DmMembership.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
3
2022-01-31T20:40:22.000Z
2022-02-11T04:15:44.000Z
src/main/java/com/supervisor/domain/impl/DmMembership.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
33
2022-01-31T20:40:16.000Z
2022-02-21T01:57:51.000Z
src/main/java/com/supervisor/domain/impl/DmMembership.java
my-supervisor/my-supervisor
ba6ecc4a3373cd439586a72a8e9fc035b09a3f2b
[ "CC-BY-3.0" ]
null
null
null
26.846154
79
0.786819
996,273
package com.supervisor.domain.impl; import com.supervisor.billing.AllPaymentReceipts; import com.supervisor.billing.Invoice; import com.supervisor.billing.Invoices; import com.supervisor.billing.PaymentMethod; import com.supervisor.billing.PaymentMethods; import com.supervisor.billing.ProductCatalog; import com.supervisor.billing.PurchaseOrder; import com.supervisor.billing.PurchaseOrders; import com.supervisor.billing.Tax; import com.supervisor.billing.Taxes; import com.supervisor.billing.UserPaymentReceipts; import com.supervisor.billing.UserPaymentRequests; import com.supervisor.billing.impl.PgAllPaymentReceipts; import com.supervisor.billing.impl.PgUserPaymentReceipts; import com.supervisor.billing.impl.PgUserPaymentRequests; import com.supervisor.billing.impl.PxInvoices; import com.supervisor.billing.impl.PxPaymentMethods; import com.supervisor.billing.impl.PxPurchaseOrders; import com.supervisor.billing.impl.PxTaxes; import com.supervisor.domain.Access; import com.supervisor.domain.Accesses; import com.supervisor.domain.Countries; import com.supervisor.domain.Country; import com.supervisor.domain.Currencies; import com.supervisor.domain.Currency; import com.supervisor.domain.Language; import com.supervisor.domain.Languages; import com.supervisor.domain.Membership; import com.supervisor.domain.Person; import com.supervisor.domain.Persons; import com.supervisor.domain.Plans; import com.supervisor.domain.Profiles; import com.supervisor.domain.RegistrationRequest; import com.supervisor.domain.RegistrationRequests; import com.supervisor.domain.Sequence; import com.supervisor.domain.Sequences; import com.supervisor.domain.User; import com.supervisor.domain.Users; import com.supervisor.takes.RqUser; import com.supervisor.sdk.datasource.Base; import com.supervisor.sdk.datasource.RecordSet; import org.takes.Request; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.TimeZone; import java.util.UUID; public final class DmMembership implements Membership { private final RecordSet<User> source; private final User user; private final Base base; public DmMembership(final Base base) throws IOException { this( base, new DmUser(base, User.ANONYMOUS_ID) ); } public DmMembership(final Base base, final Request req) throws IOException { this(base, new RqUser(base, req)); } public DmMembership(final Base base, final User user) throws IOException { this.base = base; this.base.changeUser(user.id()); this.source = this.base.select(User.class); this.user = user; } @Override public Persons contacts() throws IOException { return new DmPersons( source.of(Person.class) ); } @Override public Users members() throws IOException { return new PgUsers(user); } @Override public Accesses accesses() throws IOException { return new PxAccesses(source.of(Access.class)); } @Override public RegistrationRequests registrationRequests() throws IOException { return new PxRegistrationRequests( source.of(RegistrationRequest.class) ); } @Override public Users users() throws IOException { return new PgUsers(user); } @Override public Countries countries() throws IOException { return new PxCountries(source.of(Country.class)); } @Override public Languages languages() throws IOException { return new PxLanguages(source.of(Language.class)); } @Override public PaymentMethods paymentMethods() throws IOException { return new PxPaymentMethods(source.of(PaymentMethod.class)); } @Override public Plans plans() throws IOException { return new PgPlans(planCatalog()); } @Override public Currencies currencies() throws IOException { return new PxCurrencies(source.of(Currency.class)); } @Override public Sequences sequences() throws IOException { return new PxSequences(source.of(Sequence.class)); } @Override public Taxes taxes() throws IOException { return new PxTaxes(source.of(Tax.class)); } @Override public List<TimeZone> timeZones() throws IOException { List<TimeZone> timeZones = new ArrayList<>(); for (String id : TimeZone.getAvailableIDs()) { timeZones.add(TimeZone.getTimeZone(id)); } return timeZones; } @Override public ProductCatalog planCatalog() throws IOException { return new PxPlanCatalog(user); } @Override public PurchaseOrders purchaseOrders() throws IOException { return new PxPurchaseOrders(source.of(PurchaseOrder.class)); } @Override public Invoices invoices() throws IOException { return new PxInvoices(source.of(Invoice.class)); } @Override public User user() { return user; } @Override public ProductCatalog softwareEngineeringServiceCatalog() throws IOException { return new PxSoftwareEngineeringCatalog(user); } @Override public UserPaymentRequests paymentRequests() throws IOException { return new PgUserPaymentRequests(user); } @Override public UserPaymentReceipts paymentReceipts() throws IOException { return new PgUserPaymentReceipts(user); } @Override public AllPaymentReceipts allPaymentReceipts() throws IOException { return new PgAllPaymentReceipts(user); } @Override public Profiles profiles() throws IOException { return new PxProfiles(base); } }
923297f1fdfd48ab7463803f6301098453157226
1,562
java
Java
src/string_handle/Boj9933.java
minuk8932/Algorithm_BaekJoon
9ba6e6669d7cdde622c7d527fef77c2035bf2528
[ "Apache-2.0" ]
3
2019-05-10T08:23:46.000Z
2020-08-20T10:35:30.000Z
src/string_handle/Boj9933.java
minuk8932/Algorithm_BaekJoon
9ba6e6669d7cdde622c7d527fef77c2035bf2528
[ "Apache-2.0" ]
null
null
null
src/string_handle/Boj9933.java
minuk8932/Algorithm_BaekJoon
9ba6e6669d7cdde622c7d527fef77c2035bf2528
[ "Apache-2.0" ]
3
2019-05-15T13:06:50.000Z
2021-04-19T08:40:40.000Z
23.313433
76
0.526889
996,274
package string_handle; import java.io.BufferedReader; import java.io.InputStreamReader; public class Boj9933 { public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int N = Integer.parseInt(br.readLine()); String[] words = new String[N]; for(int i = 0; i < N; i++){ words[i] = br.readLine(); } br.close(); StringBuilder sb = new StringBuilder(); MAIN_LOOP: for(int i = 0; i < N; i++){ int len = words[i].length(); int half = words[i].length() / 2; boolean isFel = true; for(int j = 0; j < half; j++){ if(words[i].charAt(j) != words[i].charAt(len -1 -j)){ isFel = false; break; } } if(isFel){ sb.append(len).append(" ").append(words[i].charAt(half)); break; } for(int k = i+1; k < N; k++){ if(len == words[k].length()){ // StringBuilder sb2 = new StringBuilder(words[k]); // // if(words[i].equals(sb2.reverse().toString())){ // sb.append(len).append(" ").append(words[i].charAt(half)); // break MAIN_LOOP; // } way 1 boolean isRev = true; for(int l = 0; l < half; l++){ if(words[i].charAt(l) != words[k].charAt(len - 1 - l)){ isRev = false; break; } } if(isRev){ sb.append(len).append(" ").append(words[i].charAt(half)); break MAIN_LOOP; } // way 2 } } } System.out.println(sb.toString()); } }
9232988876686344a8551e618d8acd62a71dbd86
357
java
Java
src/main/java/gui/customcomponents/ColorPalette.java
Argor1992/companyportal
a247670e47d8c8b92ad705d4de035656e94216e4
[ "Unlicense" ]
null
null
null
src/main/java/gui/customcomponents/ColorPalette.java
Argor1992/companyportal
a247670e47d8c8b92ad705d4de035656e94216e4
[ "Unlicense" ]
null
null
null
src/main/java/gui/customcomponents/ColorPalette.java
Argor1992/companyportal
a247670e47d8c8b92ad705d4de035656e94216e4
[ "Unlicense" ]
null
null
null
23.8
51
0.661064
996,275
package gui.customcomponents; import java.awt.*; /** * @author Thorsten Zieres, 1297197 */ public interface ColorPalette { Color BASE = new Color(231, 235, 239); Color PRIMARY = new Color(22, 118, 243); Color PRIMARY_LIGHT = new Color(214, 226, 238); Color ERROR = new Color(255, 66, 56); Color TEXT_BLACK = new Color(37, 51, 59); }
923298c2f3284db8fe82d76d60c5c8e69b0d5d9f
525
java
Java
dmd-mall/src/main/java/com/dmd/mall/model/vo/UmsWalletLogVo.java
qhl0505/dmd
e9b3ca850d3f53cc56f0efba30ff3dde5c65138a
[ "Apache-2.0" ]
2
2019-11-18T10:16:45.000Z
2019-11-18T10:16:47.000Z
dmd-mall/src/main/java/com/dmd/mall/model/vo/UmsWalletLogVo.java
qhl0505/dmd
e9b3ca850d3f53cc56f0efba30ff3dde5c65138a
[ "Apache-2.0" ]
1
2020-12-09T22:15:16.000Z
2020-12-09T22:15:16.000Z
dmd-mall/src/main/java/com/dmd/mall/model/vo/UmsWalletLogVo.java
qhl0505/dmd
e9b3ca850d3f53cc56f0efba30ff3dde5c65138a
[ "Apache-2.0" ]
null
null
null
14.583333
39
0.582857
996,276
package com.dmd.mall.model.vo; import lombok.Data; import java.math.BigDecimal; import java.util.Date; /** * @author YangAnsheng * @version 1.0 * @createDate 2019/9/25 14:18 * @Description 钱包记录 vo */ @Data public class UmsWalletLogVo { /** * 操作金额 */ private BigDecimal money; /** * 操作类型(1:增加 2:减少) */ private Integer type; /** * 来源去向(1:微信 2:支付宝 3:银联 4:邀请 5:消费) */ private Integer sourceDestination; /** * 创建日期 */ private Date createdTime; }
9232990eb82f3403aef21aca78093bd3082d2496
1,757
java
Java
src/interpreter/ForceInterpreter.java
mason668/combat
dfc9456e9c6a7cf6ffe027b1a7bd34d8610b3669
[ "MIT" ]
null
null
null
src/interpreter/ForceInterpreter.java
mason668/combat
dfc9456e9c6a7cf6ffe027b1a7bd34d8610b3669
[ "MIT" ]
null
null
null
src/interpreter/ForceInterpreter.java
mason668/combat
dfc9456e9c6a7cf6ffe027b1a7bd34d8610b3669
[ "MIT" ]
null
null
null
29.283333
88
0.688674
996,277
package interpreter; import java.util.Vector; import sim.Constants; import sim.forces.Force; import utils.Logger; import utils.Tracer; public class ForceInterpreter extends Interpreter{ private Force myForce; public void doCommand(Force force, String command, Vector<String> vector){ if (force == null) return; myForce = force; doCommand(command, vector); myForce = null; } protected void doCommand (String command, Vector<String> vector){ if (trace){ Tracer.write(this.getClass().getName() + ": interpreting " + command + ":" + vector); } if (myForce == null) return; if (command.compareToIgnoreCase("") == 0){ } else if (command.compareToIgnoreCase("hostility") == 0){ if (vector.size()<2) return; String otherForce = vector.remove(0); String hostility = vector.remove(0); int hostilityValue = Constants.HOSTILITY_FRIEND; if (hostility.compareToIgnoreCase("enemy")== 0){ hostilityValue = Constants.HOSTILITY_ENEMY; } else if (hostility.compareToIgnoreCase("neutral")== 0) { hostilityValue = Constants.HOSTILITY_NEUTRAL; } myForce.setHostility(otherForce, hostilityValue); } else if (command.compareToIgnoreCase("scan_cycle") == 0){ String arg = vector.remove(0); try{ double clock = Double.parseDouble(arg); myForce.setScanTime(clock); } catch (Exception e){ Logger.err(this,0, "invalid scan_cycle"); } } else if (command.compareToIgnoreCase("speed") == 0){ if (vector.isEmpty()) return; String arg = vector.remove(0); try{ double d = Double.parseDouble(arg); myForce.setSpeed(d); } catch (Exception e){ Logger.err(this,0, "invalid force speed"); } } else { Logger.err(this,Logger.WARNING, "invalid command " + command); } } }
923299cf84fd66f3adb264902181d1994d4be042
3,493
java
Java
store-service/src/main/java/com/justpickup/storeservice/domain/category/service/CategoryService.java
Development-team-1/just-pickup
8fd4561f5bd0065c19b690db618c5c46c112e059
[ "MIT" ]
12
2022-01-21T05:25:15.000Z
2022-02-18T10:57:46.000Z
store-service/src/main/java/com/justpickup/storeservice/domain/category/service/CategoryService.java
Development-team-1/just-pickup
8fd4561f5bd0065c19b690db618c5c46c112e059
[ "MIT" ]
40
2022-01-26T05:27:37.000Z
2022-03-31T07:22:39.000Z
store-service/src/main/java/com/justpickup/storeservice/domain/category/service/CategoryService.java
Development-team-1/just-pickup
8fd4561f5bd0065c19b690db618c5c46c112e059
[ "MIT" ]
null
null
null
42.084337
122
0.656456
996,278
package com.justpickup.storeservice.domain.category.service; import com.justpickup.storeservice.domain.category.dto.CategoryDto; import com.justpickup.storeservice.domain.category.entity.Category; import com.justpickup.storeservice.domain.category.exception.NotFoundStoreException; import com.justpickup.storeservice.domain.category.repository.CategoryRepository; import com.justpickup.storeservice.domain.category.repository.CategoryRepositoryCustom; import com.justpickup.storeservice.domain.store.entity.Store; import com.justpickup.storeservice.domain.store.repository.StoreRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.stream.Collectors; @Service @Slf4j @RequiredArgsConstructor @Transactional(readOnly = true) public class CategoryService { private final CategoryRepository categoryRepository; private final CategoryRepositoryCustom categoryRepositoryCustom; private final StoreRepository storeRepository; public List<CategoryDto> getCategoriesWithItemByUserId(Long userId){ return categoryRepositoryCustom.getCategoryListByUserId(userId) .stream() .map(CategoryDto::new) .collect(Collectors.toList()); } public List<CategoryDto> getCategoriesWithItemById(Long storeId){ return categoryRepositoryCustom.getCategoryListById(storeId) .stream() .map(CategoryDto::new) .collect(Collectors.toList()); } @Transactional public void putCategoryList(Long storeId , List<CategoryDto> categoryDtoList , List<CategoryDto> deletedCategoryDtoList ){ Store store = storeRepository.findById(storeId) .orElseThrow(() -> new NotFoundStoreException(HttpStatus.BAD_REQUEST,"존재하지않는 Store")); List<Category> categoryList =categoryDtoList.stream() .map(categoryDto -> new Category(categoryDto.getId(), categoryDto.getName(), categoryDto.getOrder(), store)) .collect(Collectors.toList()); List<Category> deletedCategoryList =deletedCategoryDtoList.stream() .map(categoryDto -> new Category(categoryDto.getId(), categoryDto.getName(), categoryDto.getOrder(), store)) .collect(Collectors.toList()); categoryList.forEach( category -> { if (category.getId() ==null) categoryRepository.save(category); else { categoryRepository.findById(category.getId()) .orElseThrow(() -> new NotFoundStoreException(HttpStatus.BAD_REQUEST,"존재하지않는 Category")) .changeNameAndOrder(category.getName(),category.getOrder()); } } ); deletedCategoryList.forEach( category -> { if (category.getId() !=null) categoryRepository.delete(categoryRepository.findById(category.getId()) .orElseThrow(() -> new NotFoundStoreException(HttpStatus.BAD_REQUEST,"존재하지않는 Category"))); } ); } }
92329c4e7aba5cd3113349739b115ca17c77203b
3,540
java
Java
Alisha Aakanksha/src/main/java/com/nith/appteam/nimbus/Utils/SharedPref.java
Vishal17599/Nimbus-1st-Year
e5790525c5537ac8d135e4fc4c977bad5ee36069
[ "Apache-2.0" ]
null
null
null
Alisha Aakanksha/src/main/java/com/nith/appteam/nimbus/Utils/SharedPref.java
Vishal17599/Nimbus-1st-Year
e5790525c5537ac8d135e4fc4c977bad5ee36069
[ "Apache-2.0" ]
null
null
null
Alisha Aakanksha/src/main/java/com/nith/appteam/nimbus/Utils/SharedPref.java
Vishal17599/Nimbus-1st-Year
e5790525c5537ac8d135e4fc4c977bad5ee36069
[ "Apache-2.0" ]
7
2018-03-21T17:06:02.000Z
2018-03-25T19:21:17.000Z
29.016393
89
0.69322
996,279
package com.nith.appteam.nimbus.Utils; import android.content.Context; import android.content.SharedPreferences; public class SharedPref { private SharedPreferences sharedPreferences; private SharedPreferences.Editor editor; private static final String PREF_NAME="UserInfo"; private static final String LOGIN_STATUS="loginstatus"; private static final String SKIP_STATUS="skipstatus"; private static final String USER_ID="apikey"; private static final String IS_FIRST_TIME="isfirstTime"; private static final String USER_NAME="name"; private static final String USER_EMAIL="email"; private static final String USER_ROLLNO="rollno"; private static final String USER_PIC_URL="picUrl"; private static final String NITIAN_STATUS="nitian"; private static final String FIRST_ROLL_REGISTER="rollRegister"; public SharedPref(){ this(MyApplication.getAppContext()); } public SharedPref(Context context){ sharedPreferences = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE); editor = sharedPreferences.edit(); } public void setLoginStatus(boolean isLogIn){ editor.putBoolean(LOGIN_STATUS,isLogIn); editor.commit(); } public boolean getInstructionsReadStatus(){ return sharedPreferences.getBoolean("quizinstruct",false); } public boolean getLoginStatus(){ return sharedPreferences.getBoolean(LOGIN_STATUS,false); } public void setSkipStatus(boolean isSkip){ editor.putBoolean(SKIP_STATUS,isSkip); editor.commit(); } public boolean getSkipStatus(){ return sharedPreferences.getBoolean(SKIP_STATUS,false); } public void setUserId(String userId){ editor.putString(USER_ID,userId); editor.commit(); } public String getUserId(){ return sharedPreferences.getString(USER_ID,""); } public void setIsFirstTime(){ editor.putBoolean(IS_FIRST_TIME,true); editor.commit(); } public boolean showIsFirstTime(){ return sharedPreferences.getBoolean(IS_FIRST_TIME,false); } public void setUserName(String name){ editor.putString(USER_NAME,name); editor.commit(); } public String getUserName(){ return sharedPreferences.getString(USER_NAME,""); } public void setUserRollno(String rollno){ editor.putString(USER_ROLLNO,rollno); editor.commit(); } public String getUserRollno(){ return sharedPreferences.getString(USER_ROLLNO,""); } public void setUserEmail(String email){ editor.putString(USER_EMAIL,email); editor.commit(); } public String getUserEmail(){ return sharedPreferences.getString(USER_EMAIL,""); } public void setUserPicUrl(String picUrl){ editor.putString(USER_PIC_URL,picUrl); editor.commit(); } public String getUserPicUrl(){ return sharedPreferences.getString(USER_PIC_URL,""); } public void setNitianStatus(boolean status){ editor.putBoolean(NITIAN_STATUS,status); editor.commit(); } public boolean getNitianStatus(){ return sharedPreferences.getBoolean(NITIAN_STATUS,false); } public void setFirstRollRegister(boolean status){ editor.putBoolean(FIRST_ROLL_REGISTER,status); editor.commit(); } public boolean getFirstTimeRollregister(){ return sharedPreferences.getBoolean(FIRST_ROLL_REGISTER,true); } }
92329c6d13550f14d11ea54a8ed0084fe081896b
1,239
java
Java
src/main/java/fi/riista/feature/permit/application/HarvestPermitApplicationRepository.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
14
2017-01-11T23:22:36.000Z
2022-02-09T06:49:46.000Z
src/main/java/fi/riista/feature/permit/application/HarvestPermitApplicationRepository.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
4
2018-04-16T13:00:49.000Z
2021-02-15T11:56:06.000Z
src/main/java/fi/riista/feature/permit/application/HarvestPermitApplicationRepository.java
suomenriistakeskus/oma-riista-web
4b641df6b80384ed36bc3e284f104b98f8a84afd
[ "MIT" ]
4
2017-01-20T10:34:24.000Z
2021-02-09T14:41:46.000Z
41.3
107
0.807103
996,280
package fi.riista.feature.permit.application; import fi.riista.feature.common.repository.BaseRepository; import fi.riista.feature.common.repository.NativeQueries; import fi.riista.feature.permit.area.HarvestPermitArea; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Optional; import java.util.UUID; public interface HarvestPermitApplicationRepository extends BaseRepository<HarvestPermitApplication, Long>, HarvestPermitApplicationRepositoryCustom { HarvestPermitApplication findByUuid(UUID uuid); @Query("SELECT a FROM HarvestPermitApplication a WHERE a.area = ?1") List<HarvestPermitApplication> findByPermitArea(final HarvestPermitArea area); @Query("SELECT a FROM HarvestPermitApplication a WHERE a.applicationNumber = ?1") Optional<HarvestPermitApplication> findByApplicationNumber(int applicationNumber); @Query(nativeQuery = true, value = NativeQueries.LIST_HARVEST_PERMIT_APPLICATION_CONFLICTS) List<HarvestPermitApplication> findIntersecting( @Param("harvestPermitApplicationId") long harvestPermitApplicationId, @Param("applicationYear") int huntingYear); }
92329c8e4a5c3bcd9c3163d4e1bc0fbcf6d97f68
958
java
Java
bungee-rebel-plugin/src/main/java/ninja/smirking/rebel/StatefulPlugin.java
csh/minecraft-rebel-plugin
5c9152ebfa0f6d89e638942f3a52030b0f820518
[ "Apache-2.0" ]
17
2017-01-31T03:39:53.000Z
2022-03-27T17:42:28.000Z
bungee-rebel-plugin/src/main/java/ninja/smirking/rebel/StatefulPlugin.java
Fireflies/minecraft-rebel-plugin
5c9152ebfa0f6d89e638942f3a52030b0f820518
[ "Apache-2.0" ]
4
2016-06-24T17:26:06.000Z
2017-10-29T16:33:41.000Z
bungee-rebel-plugin/src/main/java/ninja/smirking/rebel/StatefulPlugin.java
Fireflies/minecraft-rebel-plugin
5c9152ebfa0f6d89e638942f3a52030b0f820518
[ "Apache-2.0" ]
null
null
null
30.903226
109
0.741127
996,281
/* * Copyright 2016 Connor Spencer Harries * * 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 ninja.smirking.rebel; /** * It's highly unlikely that a plugin implements methods with the names below, hence picking them over {@code * isEnabled()}. * * @author Connor Spencer Harries */ @SuppressWarnings("WeakerAccess") public interface StatefulPlugin { void _rebel_setEnabled(boolean enabled); boolean _rebel_isEnabled(); }
92329cbea6671c4d0df97d694f4e72ed11fb002a
15,243
java
Java
erp_desktop_all/src_cartera/com/bydan/erp/cartera/presentation/web/jsf/sessionbean/ContactoClienteSessionBean.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
1
2018-01-05T17:50:03.000Z
2018-01-05T17:50:03.000Z
erp_desktop_all/src_cartera/com/bydan/erp/cartera/presentation/web/jsf/sessionbean/ContactoClienteSessionBean.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
null
null
null
erp_desktop_all/src_cartera/com/bydan/erp/cartera/presentation/web/jsf/sessionbean/ContactoClienteSessionBean.java
jarocho105/pre2
f032fc63741b6deecdfee490e23dfa9ef1f42b4f
[ "Apache-2.0" ]
null
null
null
30.42515
156
0.781473
996,282
/* *AVISO LEGAL © Copyright *Este programa esta protegido por la ley de derechos de autor. *La reproduccion o distribucion ilicita de este programa o de cualquiera de *sus partes esta penado por la ley con severas sanciones civiles y penales, *y seran objeto de todas las sanciones legales que correspondan. *Su contenido no puede copiarse para fines comerciales o de otras, *ni puede mostrarse, incluso en una version modificada, en otros sitios Web. Solo esta permitido colocar hipervinculos al sitio web. */ package com.bydan.erp.cartera.presentation.web.jsf.sessionbean; import java.util.Set; import java.util.HashSet; import java.util.ArrayList; import java.util.Date; import java.io.Serializable; import com.bydan.framework.erp.util.Constantes; import com.bydan.erp.cartera.business.entity.*; @SuppressWarnings("unused") public class ContactoClienteSessionBean extends ContactoClienteSessionBeanAdditional { private static final long serialVersionUID = 1L; protected Boolean isPermiteNavegacionHaciaForeignKeyDesdeContactoCliente; protected Boolean isPermiteRecargarInformacion; protected String sNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente; protected Boolean isBusquedaDesdeForeignKeySesionForeignKeyContactoCliente; protected Long lIdContactoClienteActualForeignKey; protected Long lIdContactoClienteActualForeignKeyParaPosibleAtras; protected Boolean isBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras; protected String sUltimaBusquedaContactoCliente; protected String sServletGenerarHtmlReporte; protected Integer iNumeroPaginacion; protected Integer iNumeroPaginacionPagina; protected String sPathNavegacionActual=""; protected Boolean isPaginaPopup=false; protected String sStyleDivArbol=""; protected String sStyleDivContent=""; protected String sStyleDivOpcionesBanner=""; protected String sStyleDivExpandirColapsar=""; protected String sFuncionBusquedaRapida=""; Boolean isBusquedaDesdeForeignKeySesionEmpresa; Long lidEmpresaActual; Boolean isBusquedaDesdeForeignKeySesionSucursal; Long lidSucursalActual; Boolean isBusquedaDesdeForeignKeySesionCliente; Long lidClienteActual; private Long id; private Long id_empresa; private Long id_sucursal; private Long id_cliente; protected Boolean conGuardarRelaciones=false; protected Boolean estaModoGuardarRelaciones=false; protected Boolean esGuardarRelacionado=false; protected Boolean estaModoBusqueda=false; protected Boolean noMantenimiento=false; protected ContactoClienteSessionBeanAdditional contactoclienteSessionBeanAdditional=null; public ContactoClienteSessionBeanAdditional getContactoClienteSessionBeanAdditional() { return this.contactoclienteSessionBeanAdditional; } public void setContactoClienteSessionBeanAdditional(ContactoClienteSessionBeanAdditional contactoclienteSessionBeanAdditional) { try { this.contactoclienteSessionBeanAdditional=contactoclienteSessionBeanAdditional; } catch(Exception e) { ; } } public ContactoClienteSessionBean () { this.inicializarContactoClienteSessionBean(); } public void inicializarContactoClienteSessionBean () { this.isPermiteNavegacionHaciaForeignKeyDesdeContactoCliente=false; this.isPermiteRecargarInformacion=false; this.sNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente=""; this.isBusquedaDesdeForeignKeySesionForeignKeyContactoCliente=false; this.lIdContactoClienteActualForeignKey=0L; this.lIdContactoClienteActualForeignKeyParaPosibleAtras=0L; this.isBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras=false; this.sUltimaBusquedaContactoCliente =""; this.sServletGenerarHtmlReporte=""; this.iNumeroPaginacion=10; this.iNumeroPaginacionPagina=0; this.sPathNavegacionActual=""; this.sFuncionBusquedaRapida=""; this.sStyleDivArbol="display:table-row;width:20%;height:800px;visibility:visible"; this.sStyleDivContent="height:600px;width:80%"; this.sStyleDivOpcionesBanner="display:table-row"; this.sStyleDivExpandirColapsar="display:table-row"; this.isPaginaPopup=false; this.estaModoGuardarRelaciones=true; this.conGuardarRelaciones=false; this.esGuardarRelacionado=false; this.estaModoBusqueda=false; this.noMantenimiento=false; isBusquedaDesdeForeignKeySesionEmpresa=false; lidEmpresaActual=0L; isBusquedaDesdeForeignKeySesionSucursal=false; lidSucursalActual=0L; isBusquedaDesdeForeignKeySesionCliente=false; lidClienteActual=0L; this.id_empresa=-1L; this.id_sucursal=-1L; this.id_cliente=-1L; } public void setPaginaPopupVariables(Boolean isPopupVariables) { if(isPopupVariables) { if(!this.isPaginaPopup) { this.sStyleDivArbol="display:none;width:0px;height:0px;visibility:hidden"; this.sStyleDivContent="height:800px;width:100%";; this.sStyleDivOpcionesBanner="display:none"; this.sStyleDivExpandirColapsar="display:none"; this.isPaginaPopup=true; } } else { if(this.isPaginaPopup) { this.sStyleDivArbol="display:table-row;width:15%;height:600px;visibility:visible;overflow:auto;"; this.sStyleDivContent="height:600px;width:80%"; this.sStyleDivOpcionesBanner="display:table-row"; this.sStyleDivExpandirColapsar="display:table-row"; this.isPaginaPopup=false; } } } public Boolean getisPermiteNavegacionHaciaForeignKeyDesdeContactoCliente() { return this.isPermiteNavegacionHaciaForeignKeyDesdeContactoCliente; } public void setisPermiteNavegacionHaciaForeignKeyDesdeContactoCliente( Boolean isPermiteNavegacionHaciaForeignKeyDesdeContactoCliente) { this.isPermiteNavegacionHaciaForeignKeyDesdeContactoCliente= isPermiteNavegacionHaciaForeignKeyDesdeContactoCliente; } public Boolean getisPermiteRecargarInformacion() { return this.isPermiteRecargarInformacion; } public void setisPermiteRecargarInformacion( Boolean isPermiteRecargarInformacion) { this.isPermiteRecargarInformacion=isPermiteRecargarInformacion; } public String getsNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente() { return this.sNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente; } public void setsNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente(String sNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente) { this.sNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente = sNombrePaginaNavegacionHaciaForeignKeyDesdeContactoCliente; } public Boolean getisBusquedaDesdeForeignKeySesionForeignKeyContactoCliente() { return isBusquedaDesdeForeignKeySesionForeignKeyContactoCliente; } public void setisBusquedaDesdeForeignKeySesionForeignKeyContactoCliente( Boolean isBusquedaDesdeForeignKeySesionForeignKeyContactoCliente) { this.isBusquedaDesdeForeignKeySesionForeignKeyContactoCliente= isBusquedaDesdeForeignKeySesionForeignKeyContactoCliente; } public Long getlIdContactoClienteActualForeignKey() { return lIdContactoClienteActualForeignKey; } public void setlIdContactoClienteActualForeignKey( Long lIdContactoClienteActualForeignKey) { this.lIdContactoClienteActualForeignKey = lIdContactoClienteActualForeignKey; } public Long getlIdContactoClienteActualForeignKeyParaPosibleAtras() { return lIdContactoClienteActualForeignKeyParaPosibleAtras; } public void setlIdContactoClienteActualForeignKeyParaPosibleAtras( Long lIdContactoClienteActualForeignKeyParaPosibleAtras) { this.lIdContactoClienteActualForeignKeyParaPosibleAtras = lIdContactoClienteActualForeignKeyParaPosibleAtras; } public Boolean getisBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras() { return isBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras; } public void setisBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras( Boolean isBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras) { this.isBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras = isBusquedaDesdeForeignKeySesionForeignKeyContactoClienteParaPosibleAtras; } public String getsUltimaBusquedaContactoCliente() { return sUltimaBusquedaContactoCliente; } public void setsUltimaBusquedaContactoCliente(String sUltimaBusquedaContactoCliente) { this.sUltimaBusquedaContactoCliente = sUltimaBusquedaContactoCliente; } public String getsServletGenerarHtmlReporte() { return sServletGenerarHtmlReporte; } public void setsServletGenerarHtmlReporte(String sServletGenerarHtmlReporte) { this.sServletGenerarHtmlReporte = sServletGenerarHtmlReporte; } public Integer getiNumeroPaginacion() { return iNumeroPaginacion; } public void setiNumeroPaginacion(Integer iNumeroPaginacion) { this.iNumeroPaginacion= iNumeroPaginacion; } public Integer getiNumeroPaginacionPagina() { return iNumeroPaginacionPagina; } public void setiNumeroPaginacionPagina(Integer iNumeroPaginacionPagina) { this.iNumeroPaginacionPagina= iNumeroPaginacionPagina; } public String getsPathNavegacionActual() { return this.sPathNavegacionActual; } public void setsPathNavegacionActual(String sPathNavegacionActual) { this.sPathNavegacionActual = sPathNavegacionActual; } public Boolean getisPaginaPopup() { return this.isPaginaPopup; } public void setisPaginaPopup(Boolean isPaginaPopup) { this.isPaginaPopup = isPaginaPopup; } public String getsStyleDivArbol() { return this.sStyleDivArbol; } public void setsStyleDivArbol(String sStyleDivArbol) { this.sStyleDivArbol = sStyleDivArbol; } public String getsStyleDivContent() { return this.sStyleDivContent; } public void setsStyleDivContent(String sStyleDivContent) { this.sStyleDivContent = sStyleDivContent; } public String getsStyleDivOpcionesBanner() { return this.sStyleDivOpcionesBanner; } public void setsStyleDivOpcionesBanner(String sStyleDivOpcionesBanner) { this.sStyleDivOpcionesBanner = sStyleDivOpcionesBanner; } public String getsStyleDivExpandirColapsar() { return this.sStyleDivExpandirColapsar; } public void setsStyleDivExpandirColapsar(String sStyleDivExpandirColapsar) { this.sStyleDivExpandirColapsar = sStyleDivExpandirColapsar; } public String getsFuncionBusquedaRapida() { return this.sFuncionBusquedaRapida; } public void setsFuncionBusquedaRapida(String sFuncionBusquedaRapida) { this.sFuncionBusquedaRapida = sFuncionBusquedaRapida; } public Boolean getConGuardarRelaciones() { return this.conGuardarRelaciones; } public void setConGuardarRelaciones(Boolean conGuardarRelaciones) { this.conGuardarRelaciones = conGuardarRelaciones; } public Boolean getEstaModoGuardarRelaciones() { return this.estaModoGuardarRelaciones; } public void setEstaModoGuardarRelaciones(Boolean estaModoGuardarRelaciones) { this.estaModoGuardarRelaciones = estaModoGuardarRelaciones; } public Boolean getEsGuardarRelacionado() { return this.esGuardarRelacionado; } public void setEsGuardarRelacionado(Boolean esGuardarRelacionado) { this.esGuardarRelacionado = esGuardarRelacionado; } public Boolean getEstaModoBusqueda() { return this.estaModoBusqueda; } public void setEstaModoBusqueda(Boolean estaModoBusqueda) { this.estaModoBusqueda = estaModoBusqueda; } public Boolean getNoMantenimiento() { return this.noMantenimiento; } public void setNoMantenimiento(Boolean noMantenimiento) { this.noMantenimiento = noMantenimiento; } public Long getid() { return this.id; } public Long getid_empresa() { return this.id_empresa; } public Long getid_sucursal() { return this.id_sucursal; } public Long getid_cliente() { return this.id_cliente; } public void setid(Long newid)throws Exception { try { if(this.id!=newid) { if(newid==null) { //newid=0L; if(Constantes.ISDEVELOPING) { System.out.println("ContactoCliente:Valor nulo no permitido en columna id"); } } this.id=newid; } } catch(Exception e) { throw e; } } public void setid_empresa(Long newid_empresa)throws Exception { try { if(this.id_empresa!=newid_empresa) { if(newid_empresa==null) { //newid_empresa=-1L; if(Constantes.ISDEVELOPING) { System.out.println("ContactoCliente:Valor nulo no permitido en columna id_empresa"); } } this.id_empresa=newid_empresa; } } catch(Exception e) { throw e; } } public void setid_sucursal(Long newid_sucursal)throws Exception { try { if(this.id_sucursal!=newid_sucursal) { if(newid_sucursal==null) { //newid_sucursal=-1L; if(Constantes.ISDEVELOPING) { System.out.println("ContactoCliente:Valor nulo no permitido en columna id_sucursal"); } } this.id_sucursal=newid_sucursal; } } catch(Exception e) { throw e; } } public void setid_cliente(Long newid_cliente)throws Exception { try { if(this.id_cliente!=newid_cliente) { if(newid_cliente==null) { //newid_cliente=-1L; if(Constantes.ISDEVELOPING) { System.out.println("ContactoCliente:Valor nulo no permitido en columna id_cliente"); } } this.id_cliente=newid_cliente; } } catch(Exception e) { throw e; } } public Boolean getisBusquedaDesdeForeignKeySesionEmpresa() { return isBusquedaDesdeForeignKeySesionEmpresa; } public void setisBusquedaDesdeForeignKeySesionEmpresa( Boolean isBusquedaDesdeForeignKeySesionEmpresa) { this.isBusquedaDesdeForeignKeySesionEmpresa = isBusquedaDesdeForeignKeySesionEmpresa; } public Long getlidEmpresaActual() { return lidEmpresaActual; } public void setlidEmpresaActual(Long lidEmpresaActual) { this.lidEmpresaActual = lidEmpresaActual; } public Boolean getisBusquedaDesdeForeignKeySesionSucursal() { return isBusquedaDesdeForeignKeySesionSucursal; } public void setisBusquedaDesdeForeignKeySesionSucursal( Boolean isBusquedaDesdeForeignKeySesionSucursal) { this.isBusquedaDesdeForeignKeySesionSucursal = isBusquedaDesdeForeignKeySesionSucursal; } public Long getlidSucursalActual() { return lidSucursalActual; } public void setlidSucursalActual(Long lidSucursalActual) { this.lidSucursalActual = lidSucursalActual; } public Boolean getisBusquedaDesdeForeignKeySesionCliente() { return isBusquedaDesdeForeignKeySesionCliente; } public void setisBusquedaDesdeForeignKeySesionCliente( Boolean isBusquedaDesdeForeignKeySesionCliente) { this.isBusquedaDesdeForeignKeySesionCliente = isBusquedaDesdeForeignKeySesionCliente; } public Long getlidClienteActual() { return lidClienteActual; } public void setlidClienteActual(Long lidClienteActual) { this.lidClienteActual = lidClienteActual; } }
92329d3525eeb436f75d643e9030c1d696b0aab0
298
java
Java
src/test/java/com/rbkmoney/adapter/businessru/TestData.java
rbkmoney/cashreg-adapter-businessru
58c71f9cf05958a061ce998e57204a3aab75a479
[ "Apache-2.0" ]
1
2020-06-17T11:44:02.000Z
2020-06-17T11:44:02.000Z
src/test/java/com/rbkmoney/adapter/businessru/TestData.java
rbkmoney/cashreg-adapter-businessru
58c71f9cf05958a061ce998e57204a3aab75a479
[ "Apache-2.0" ]
null
null
null
src/test/java/com/rbkmoney/adapter/businessru/TestData.java
rbkmoney/cashreg-adapter-businessru
58c71f9cf05958a061ce998e57204a3aab75a479
[ "Apache-2.0" ]
1
2021-12-07T09:20:01.000Z
2021-12-07T09:20:01.000Z
26.636364
59
0.733788
996,283
package com.rbkmoney.adapter.businessru; public class TestData { public static final String CASHREG_ID = "CashregId"; public static final String PARTY_ID = "party_id"; public static final String SHOP_ID = "shop_id"; public static final String TEST_EMAIL = "ychag@example.com"; }
92329d367efefb724cda01424e32e0adc825f3f9
517
java
Java
comp401/sushi/TunaPortion.java
adamalston/SushiGame
b1ecee157c0868c58efc03960a00539795830e18
[ "MIT" ]
1
2020-06-02T10:20:07.000Z
2020-06-02T10:20:07.000Z
comp401/sushi/TunaPortion.java
adamalston/SushiGame
b1ecee157c0868c58efc03960a00539795830e18
[ "MIT" ]
null
null
null
comp401/sushi/TunaPortion.java
adamalston/SushiGame
b1ecee157c0868c58efc03960a00539795830e18
[ "MIT" ]
1
2022-02-04T03:13:28.000Z
2022-02-04T03:13:28.000Z
22.478261
83
0.729207
996,284
package comp401.sushi; public class TunaPortion extends IngredientPortionImpl { private static final Ingredient TUNA = new Tuna(); public TunaPortion(double amount) { super(amount, TUNA); } @Override public IngredientPortion combine(IngredientPortion other) { if (other == null) { return this; } if (!other.getIngredient().equals(TUNA)) { throw new RuntimeException("Can not combine portions of different ingredients"); } return new TunaPortion(other.getAmount()+this.getAmount()); } }
92329dcc2a570da607b09790c88052622f8d304b
5,659
java
Java
oscm-dataservice-unittests/javasrc-it/org/oscm/domobjects/TechnicalProductOperationIT.java
srinathjiinfotach/billingdevelopment
564e66593c9d272b8e04804410b633bc089aa203
[ "Apache-2.0" ]
56
2015-10-06T15:09:39.000Z
2021-08-09T01:18:03.000Z
oscm-dataservice-unittests/javasrc-it/org/oscm/domobjects/TechnicalProductOperationIT.java
srinathjiinfotach/billingdevelopment
564e66593c9d272b8e04804410b633bc089aa203
[ "Apache-2.0" ]
845
2016-02-10T14:06:17.000Z
2020-10-20T07:44:09.000Z
oscm-dataservice-unittests/javasrc-it/org/oscm/domobjects/TechnicalProductOperationIT.java
srinathjiinfotach/billingdevelopment
564e66593c9d272b8e04804410b633bc089aa203
[ "Apache-2.0" ]
41
2015-10-22T14:22:23.000Z
2022-03-18T07:55:15.000Z
35.36875
96
0.599399
996,285
/******************************************************************************* * * Copyright FUJITSU LIMITED 2017 * * Creation Date: 16.08.2010 * *******************************************************************************/ package org.oscm.domobjects; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.oscm.types.enumtypes.OperationParameterType.INPUT_STRING; import static org.oscm.types.enumtypes.OperationParameterType.REQUEST_SELECT; import java.util.concurrent.Callable; import org.junit.Assert; import org.junit.Test; import org.oscm.internal.types.enumtypes.OrganizationRoleType; import org.oscm.internal.types.enumtypes.ServiceAccessType; import org.oscm.test.data.Organizations; import org.oscm.test.data.TechnicalProducts; import org.oscm.types.enumtypes.OperationParameterType; /** * @author weiser * */ public class TechnicalProductOperationIT extends DomainObjectTestBase { private Organization organization; private TechnicalProduct technicalProduct; @Override protected void dataSetup() throws Exception { createOrganizationRoles(mgr); organization = Organizations.createOrganization(mgr, OrganizationRoleType.TECHNOLOGY_PROVIDER); technicalProduct = TechnicalProducts.createTechnicalProduct(mgr, organization, "TP", false, ServiceAccessType.DIRECT); } @Test public void testAdd() throws Exception { doAdd(); } @Test public void testModify() throws Exception { doModify(doAdd()); } @Test public void testDelete() throws Exception { final TechnicalProductOperation read = doModify(doAdd()); runTX(new Callable<Void>() { @Override public Void call() throws Exception { TechnicalProductOperation operation = mgr.getReference( TechnicalProductOperation.class, read.getKey()); mgr.remove(operation); return null; } }); } @Test public void testDeleteTP() throws Exception { doAdd(); runTX(new Callable<Void>() { @Override public Void call() throws Exception { TechnicalProduct tp = mgr.getReference(TechnicalProduct.class, technicalProduct.getKey()); mgr.remove(tp); return null; } }); } @Test public void isRequestParameterValuesRequired_Positive() { TechnicalProductOperation tpo = prepareTPO(new OperationParameterType[] { INPUT_STRING, INPUT_STRING, REQUEST_SELECT, INPUT_STRING }); assertTrue(tpo.isRequestParameterValuesRequired()); } @Test public void isRequestParameterValuesRequired_Negative() { TechnicalProductOperation tpo = prepareTPO(new OperationParameterType[] { INPUT_STRING, INPUT_STRING, INPUT_STRING }); assertFalse(tpo.isRequestParameterValuesRequired()); } @Test public void isRequestParameterValuesRequired_Empty() { TechnicalProductOperation tpo = prepareTPO(new OperationParameterType[] {}); assertFalse(tpo.isRequestParameterValuesRequired()); } private TechnicalProductOperation prepareTPO(OperationParameterType[] types) { TechnicalProductOperation tpo = new TechnicalProductOperation(); for (OperationParameterType type : types) { OperationParameter op = new OperationParameter(); op.setType(type); tpo.getParameters().add(op); } return tpo; } private TechnicalProductOperation doAdd() throws Exception { final TechnicalProductOperation op = new TechnicalProductOperation(); op.setOperationId("ID"); op.setActionUrl("actionUrl"); final TechnicalProductOperation read = runTX(new Callable<TechnicalProductOperation>() { @Override public TechnicalProductOperation call() throws Exception { TechnicalProduct tp = mgr.getReference(TechnicalProduct.class, technicalProduct.getKey()); op.setTechnicalProduct(tp); mgr.persist(op); return mgr.getReference(TechnicalProductOperation.class, op.getKey()); } }); Assert.assertEquals("ID", read.getOperationId()); Assert.assertEquals("actionUrl", read.getActionUrl()); return read; } private TechnicalProductOperation doModify( final TechnicalProductOperation op) throws Exception { final TechnicalProductOperation read = runTX(new Callable<TechnicalProductOperation>() { @Override public TechnicalProductOperation call() throws Exception { TechnicalProductOperation tpo = mgr.getReference( TechnicalProductOperation.class, op.getKey()); tpo.setActionUrl("someOtherUlr"); return mgr.getReference(TechnicalProductOperation.class, tpo.getKey()); } }); Assert.assertEquals("ID", read.getOperationId()); Assert.assertEquals("someOtherUlr", read.getActionUrl()); return read; } }
92329e3a7f26d31e818481e5b5ed4d78eb7726ba
432
java
Java
IHMCAvatarInterfaces/src/us/ihmc/avatar/ros/messages/Float64Message.java
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
170
2016-02-01T18:58:50.000Z
2022-03-17T05:28:01.000Z
IHMCAvatarInterfaces/src/us/ihmc/avatar/ros/messages/Float64Message.java
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
162
2016-01-29T17:04:29.000Z
2022-02-10T16:25:37.000Z
IHMCAvatarInterfaces/src/us/ihmc/avatar/ros/messages/Float64Message.java
wxmerkt/ihmc-open-robotics-software
2c47c9a9bd999e7811038e99c3888683f9973a2a
[ "Apache-2.0" ]
83
2016-01-28T22:49:01.000Z
2022-03-28T03:11:24.000Z
16
86
0.62963
996,286
package us.ihmc.avatar.ros.messages; public class Float64Message { /** * General Float64 message wrapper, as defined in the std_msgs/Float64 rosmsg type. */ private double value; public void setValue(double value) { this.value = value; } public double getValue() { return value; } @Override public String toString() { return "[Float64Message] Value: " + value; } }
92329ec15b78baa1046fa99fc78e0e77c0f1936d
3,014
java
Java
web/src/main/java/com/jeesite/modules/departs/entity/DepartsTeacher.java
ZWT-99/jwglxt
9590f36f8c3380e14c60f6b7ccf61268d16c608b
[ "Apache-2.0" ]
1
2021-01-04T12:56:36.000Z
2021-01-04T12:56:36.000Z
web/src/main/java/com/jeesite/modules/departs/entity/DepartsTeacher.java
ZWT-99/jwglxt
9590f36f8c3380e14c60f6b7ccf61268d16c608b
[ "Apache-2.0" ]
null
null
null
web/src/main/java/com/jeesite/modules/departs/entity/DepartsTeacher.java
ZWT-99/jwglxt
9590f36f8c3380e14c60f6b7ccf61268d16c608b
[ "Apache-2.0" ]
null
null
null
24.306452
70
0.711015
996,287
/** * Copyright (c) 2013-Now http://jeesite.com All rights reserved. */ package com.jeesite.modules.departs.entity; import org.hibernate.validator.constraints.Length; import java.util.Date; import com.jeesite.common.mybatis.annotation.JoinTable; import com.jeesite.common.mybatis.annotation.JoinTable.Type; import com.fasterxml.jackson.annotation.JsonFormat; import com.jeesite.common.entity.DataEntity; import com.jeesite.common.mybatis.annotation.Column; import com.jeesite.common.mybatis.annotation.Table; import com.jeesite.common.mybatis.mapper.query.QueryType; /** * departsEntity * @author sdy * @version 2021-01-08 */ @Table(name="teacher", alias="a", columns={ @Column(name="tno", attrName="tno", label="教师编号", isPK=true), @Column(name="tname", attrName="tname", label="姓名"), @Column(name="sex", attrName="sex", label="性别"), @Column(name="department", attrName="department.dname", label="学院"), @Column(name="nationality", attrName="nationality", label="民族"), @Column(name="nativeplace", attrName="nativeplace", label="籍贯"), @Column(name="telephone", attrName="telephone", label="电话"), @Column(name="tbirth", attrName="tbirth", label="生日"), }, orderBy="a.tno ASC" ) public class DepartsTeacher extends DataEntity<DepartsTeacher> { private static final long serialVersionUID = 1L; private String tno; // 教师编号 private String tname; // 姓名 private Long sex; // 性别 private Departs department; // 学院 父类 private String nationality; // 民族 private String nativeplace; // 籍贯 private String telephone; // 电话 private Date tbirth; // 生日 public DepartsTeacher() { this(null); } public DepartsTeacher(Departs department){ this.department = department; } public String getTno() { return tno; } public void setTno(String tno) { this.tno = tno; } @Length(min=0, max=20, message="姓名长度不能超过 20 个字符") public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } public Long getSex() { return sex; } public void setSex(Long sex) { this.sex = sex; } @Length(min=0, max=20, message="学院长度不能超过 20 个字符") public Departs getDepartment() { return department; } public void setDepartment(Departs department) { this.department = department; } @Length(min=0, max=20, message="民族长度不能超过 20 个字符") public String getNationality() { return nationality; } public void setNationality(String nationality) { this.nationality = nationality; } @Length(min=0, max=40, message="籍贯长度不能超过 40 个字符") public String getNativeplace() { return nativeplace; } public void setNativeplace(String nativeplace) { this.nativeplace = nativeplace; } @Length(min=0, max=20, message="电话长度不能超过 20 个字符") public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") public Date getTbirth() { return tbirth; } public void setTbirth(Date tbirth) { this.tbirth = tbirth; } }
92329ff93a6e8d907a9abdc2cc1b4d6cd3098af7
22,333
java
Java
src/com/fuhj/itower/model/ITBill.java
fhj7627406/itowerElec
830b8c578a304863c748fb15793d55f86ca07852
[ "MIT" ]
null
null
null
src/com/fuhj/itower/model/ITBill.java
fhj7627406/itowerElec
830b8c578a304863c748fb15793d55f86ca07852
[ "MIT" ]
null
null
null
src/com/fuhj/itower/model/ITBill.java
fhj7627406/itowerElec
830b8c578a304863c748fb15793d55f86ca07852
[ "MIT" ]
null
null
null
26.05951
100
0.650428
996,288
package com.fuhj.itower.model; import java.util.Date; public class ITBill extends BaseModel { private int itBillId; public static final String IT_BILL_ID = "it_bill_id"; private String billCode; public static final String BILL_CODE = "bill_code"; private String billStatus; public static final String BILL_STATUS = "bill_status"; private Date acceptTime; public static final String ACCEPT_TIME = "accept_time"; private Date dispatchTime; public static final String DISPATCH_TIME = "dispatch_time"; private Date receiveTime; public static final String RECEIVE_TIME = "receive_time"; private Date alarmTime; public static final String ALARM_TIME = "alarm_time"; private String timeLimit; public static final String TIME_LIMIT = "time_limit"; private Date receiptTime; public static final String RECEIPT_TIME = "receipt_time"; private Date filedTime; public static final String FILED_TIME = "filed_time"; private String faultSource; public static final String FAULT_SOURCE = "fault_source"; private String alarmName; public static final String ALARM_NAME = "alarm_name"; private String alarmStatus; public static final String ALARM_STATUS = "alarm_status"; private String alarmDetail; public static final String ALARM_DETAIL = "alarm_detail"; private String alarmLevel; public static final String ALARM_LEVEL = "alarm_level"; private String stationCode; public static final String STATION_CODE = "station_code"; private String stationName; public static final String STATION_NAME = "station_name"; private String province; public static final String PROVINCE = "province"; private String city; public static final String CITY = "city"; private String district; public static final String DISTRICT = "district"; private String itProvinceId; public static final String IT_PROVINCE_ID = "it_province_id"; private String itCityId; public static final String IT_CITY_ID = "it_city_id"; private String itDistrictId; public static final String IT_DISTRICT_ID = "it_district_id"; private String goStation; public static final String GO_STATION = "go_station"; private String faultReason; public static final String FAULT_REASON = "fault_reason"; private String immunity; public static final String IMMUNITY = "immunity"; private String disclaimer; public static final String DISCLAIMER = "disclaimer"; private String immunityReason; public static final String IMMUNITY_REASON = "immunity_reason"; private Date alarmClearTime; public static final String ALARM_CLEAR_TIME = "alarm_clear_time"; private String alarmReplyContent; public static final String ALARM_REPLY_CONTENT = "alarm_reply_content"; private String faultDeviceType; public static final String FAULT_DEVICE_TYPE = "fault_device_type"; private String hasPressed; public static final String HAS_PRESSED = "has_pressed"; private String isReceiptTimeout; public static final String IS_RECEIPT_TIMEOUT = "is_receipt_timeout"; private String receiptPerson; public static final String RECEIPT_PERSON = "receipt_person"; private String agentsCorp; public static final String AGENTS_CORP = "agents_corp"; private String billProcess; public static final String BILL_PROCESS = "bill_process"; private String machineRoomType; public static final String MACHINE_ROOM_TYPE = "machine_room_type"; private String powerSupplyMode; public static final String POWER_SUPPLY_MODE = "power_supply_mode"; private String fsuNetworkCardType; public static final String FSU_NETWORK_CARD_TYPE = "fsu_network_card_type"; private String fsuManufactor; public static final String FSU_MANUFACTOR = "fsu_manufactor"; private String acManufactor; public static final String AC_MANUFACTOR = "ac_manufactor"; private String batteryManufactor; public static final String BATTERY_MANUFACTOR = "battery_manufactor"; private String switchManufactor; public static final String SWITCH_MANUFACTOR = "switch_manufactor"; private String elecConditions; public static final String ELEC_CONDITIONS = "elec_conditions"; private String batteryCount; public static final String BATTERY_COUNT = "battery_count"; private String batteryCapacity; public static final String BATTERY_CAPACITY = "battery_capacity"; private String totalCurrent; public static final String TOTAL_CURRENT = "total_current"; private String batteryGuarantee; public static final String BATTERY_GUARANTEE = "battery_guarantee"; private String alarmDuration; public static final String ALARM_DURATION = "alarm_duration"; private String billDuration; public static final String BILL_DURATION = "bill_duration"; private String billHandler; public static final String BILL_HANDLER = "bill_handler"; private String receiptTerminal; public static final String RECEIPT_TERMINAL = "receipt_terminal"; private String receiveDuration; public static final String RECEIVE_DURATION = "receive_duration"; private Date firstReplyTime; public static final String FIRST_REPLY_TIME = "first_reply_time"; private String isReceiveTimeout; public static final String IS_RECEIVE_TIMEOUT = "is_receive_timeout"; private String operator; public static final String OPERATOR = "operator"; private String faultConfirmContent; public static final String FAULT_CONFIRM_CONTENT = "fault_confirm_content"; private String areaManager; public static final String AREA_MANAGER = "area_manager"; private String dataOrigin; public static final String DATA_ORIGIN = "data_origin"; private String receiveTerminal; public static final String RECEIVE_TERMINAL = "receive_terminal"; private Date signTime; public static final String SIGN_TIME = "sign_time"; private String signLng; public static final String SIGN_LNG = "sign_lng"; private String signLat; public static final String SIGN_LAT = "sign_lat"; private String stationLng; public static final String STATION_LNG = "station_lng"; private String stationLat; public static final String STATION_LAT = "station_lat"; private String isElecGenerBill; public static final String IS_ELEC_GENER_BILL = "is_elec_gener_bill"; private String faultType; public static final String FAULT_TYPE = "fault_type"; private String remark; public static final String REMARK = "remark"; private Date updateTime; public static final String UPDATE_TIME = "update_time"; private Date createTime; public static final String CREATE_TIME = "create_time"; private int status; public static final String STATUS = "status"; public int getItBillId() { return itBillId; } public void setItBillId(int itBillId) { this.itBillId = itBillId; } public String getBillCode() { return billCode; } public void setBillCode(String billCode) { this.billCode = billCode == null ? null : billCode.trim(); } public String getBillStatus() { return billStatus; } public void setBillStatus(String billStatus) { this.billStatus = billStatus == null ? null : billStatus.trim(); } public Date getAcceptTime() { return acceptTime; } public void setAcceptTime(Date acceptTime) { this.acceptTime = acceptTime; } public Date getDispatchTime() { return dispatchTime; } public void setDispatchTime(Date dispatchTime) { this.dispatchTime = dispatchTime; } public Date getReceiveTime() { return receiveTime; } public void setReceiveTime(Date receiveTime) { this.receiveTime = receiveTime; } public Date getAlarmTime() { return alarmTime; } public void setAlarmTime(Date alarmTime) { this.alarmTime = alarmTime; } public String getTimeLimit() { return timeLimit; } public void setTimeLimit(String timeLimit) { this.timeLimit = timeLimit == null ? null : timeLimit.trim(); } public Date getReceiptTime() { return receiptTime; } public void setReceiptTime(Date receiptTime) { this.receiptTime = receiptTime; } public Date getFiledTime() { return filedTime; } public void setFiledTime(Date filedTime) { this.filedTime = filedTime; } public String getFaultSource() { return faultSource; } public void setFaultSource(String faultSource) { this.faultSource = faultSource == null ? null : faultSource.trim(); } public String getAlarmName() { return alarmName; } public void setAlarmName(String alarmName) { this.alarmName = alarmName == null ? null : alarmName.trim(); } public String getAlarmStatus() { return alarmStatus; } public void setAlarmStatus(String alarmStatus) { this.alarmStatus = alarmStatus == null ? null : alarmStatus.trim(); } public String getAlarmDetail() { return alarmDetail; } public void setAlarmDetail(String alarmDetail) { this.alarmDetail = alarmDetail == null ? null : alarmDetail.trim(); } public String getAlarmLevel() { return alarmLevel; } public void setAlarmLevel(String alarmLevel) { this.alarmLevel = alarmLevel == null ? null : alarmLevel.trim(); } public String getStationCode() { return stationCode; } public void setStationCode(String stationCode) { this.stationCode = stationCode == null ? null : stationCode.trim(); } public String getStationName() { return stationName; } public void setStationName(String stationName) { this.stationName = stationName == null ? null : stationName.trim(); } public String getProvince() { return province; } public void setProvince(String province) { this.province = province == null ? null : province.trim(); } public String getCity() { return city; } public void setCity(String city) { this.city = city == null ? null : city.trim(); } public String getDistrict() { return district; } public void setDistrict(String district) { this.district = district == null ? null : district.trim(); } public String getItProvinceId() { return itProvinceId; } public void setItProvinceId(String itProvinceId) { this.itProvinceId = itProvinceId == null ? null : itProvinceId.trim(); } public String getItCityId() { return itCityId; } public void setItCityId(String itCityId) { this.itCityId = itCityId == null ? null : itCityId.trim(); } public String getItDistrictId() { return itDistrictId; } public void setItDistrictId(String itDistrictId) { this.itDistrictId = itDistrictId == null ? null : itDistrictId.trim(); } public String getGoStation() { return goStation; } public void setGoStation(String goStation) { this.goStation = goStation == null ? null : goStation.trim(); } public String getFaultReason() { return faultReason; } public void setFaultReason(String faultReason) { this.faultReason = faultReason == null ? null : faultReason.trim(); } public String getImmunity() { return immunity; } public void setImmunity(String immunity) { this.immunity = immunity == null ? null : immunity.trim(); } public String getDisclaimer() { return disclaimer; } public void setDisclaimer(String disclaimer) { this.disclaimer = disclaimer == null ? null : disclaimer.trim(); } public String getImmunityReason() { return immunityReason; } public void setImmunityReason(String immunityReason) { this.immunityReason = immunityReason == null ? null : immunityReason.trim(); } public Date getAlarmClearTime() { return alarmClearTime; } public void setAlarmClearTime(Date alarmClearTime) { this.alarmClearTime = alarmClearTime; } public String getAlarmReplyContent() { return alarmReplyContent; } public void setAlarmReplyContent(String alarmReplyContent) { this.alarmReplyContent = alarmReplyContent == null ? null : alarmReplyContent.trim(); } public String getFaultDeviceType() { return faultDeviceType; } public void setFaultDeviceType(String faultDeviceType) { this.faultDeviceType = faultDeviceType == null ? null : faultDeviceType.trim(); } public String getHasPressed() { return hasPressed; } public void setHasPressed(String hasPressed) { this.hasPressed = hasPressed == null ? null : hasPressed.trim(); } public String getIsReceiptTimeout() { return isReceiptTimeout; } public void setIsReceiptTimeout(String isReceiptTimeout) { this.isReceiptTimeout = isReceiptTimeout == null ? null : isReceiptTimeout.trim(); } public String getReceiptPerson() { return receiptPerson; } public void setReceiptPerson(String receiptPerson) { this.receiptPerson = receiptPerson == null ? null : receiptPerson.trim(); } public String getAgentsCorp() { return agentsCorp; } public void setAgentsCorp(String agentsCorp) { this.agentsCorp = agentsCorp == null ? null : agentsCorp.trim(); } public String getBillProcess() { return billProcess; } public void setBillProcess(String billProcess) { this.billProcess = billProcess == null ? null : billProcess.trim(); } public String getMachineRoomType() { return machineRoomType; } public void setMachineRoomType(String machineRoomType) { this.machineRoomType = machineRoomType == null ? null : machineRoomType.trim(); } public String getPowerSupplyMode() { return powerSupplyMode; } public void setPowerSupplyMode(String powerSupplyMode) { this.powerSupplyMode = powerSupplyMode == null ? null : powerSupplyMode.trim(); } public String getFsuNetworkCardType() { return fsuNetworkCardType; } public void setFsuNetworkCardType(String fsuNetworkCardType) { this.fsuNetworkCardType = fsuNetworkCardType == null ? null : fsuNetworkCardType.trim(); } public String getFsuManufactor() { return fsuManufactor; } public void setFsuManufactor(String fsuManufactor) { this.fsuManufactor = fsuManufactor == null ? null : fsuManufactor.trim(); } public String getAcManufactor() { return acManufactor; } public void setAcManufactor(String acManufactor) { this.acManufactor = acManufactor == null ? null : acManufactor.trim(); } public String getBatteryManufactor() { return batteryManufactor; } public void setBatteryManufactor(String batteryManufactor) { this.batteryManufactor = batteryManufactor == null ? null : batteryManufactor.trim(); } public String getSwitchManufactor() { return switchManufactor; } public void setSwitchManufactor(String switchManufactor) { this.switchManufactor = switchManufactor == null ? null : switchManufactor.trim(); } public String getElecConditions() { return elecConditions; } public void setElecConditions(String elecConditions) { this.elecConditions = elecConditions == null ? null : elecConditions.trim(); } public String getBatteryCount() { return batteryCount; } public void setBatteryCount(String batteryCount) { this.batteryCount = batteryCount == null ? null : batteryCount.trim(); } public String getBatteryCapacity() { return batteryCapacity; } public void setBatteryCapacity(String batteryCapacity) { this.batteryCapacity = batteryCapacity == null ? null : batteryCapacity.trim(); } public String getTotalCurrent() { return totalCurrent; } public void setTotalCurrent(String totalCurrent) { this.totalCurrent = totalCurrent == null ? null : totalCurrent.trim(); } public String getBatteryGuarantee() { return batteryGuarantee; } public void setBatteryGuarantee(String batteryGuarantee) { this.batteryGuarantee = batteryGuarantee == null ? null : batteryGuarantee.trim(); } public String getAlarmDuration() { return alarmDuration; } public void setAlarmDuration(String alarmDuration) { this.alarmDuration = alarmDuration == null ? null : alarmDuration.trim(); } public String getBillDuration() { return billDuration; } public void setBillDuration(String billDuration) { this.billDuration = billDuration == null ? null : billDuration.trim(); } public String getBillHandler() { return billHandler; } public void setBillHandler(String billHandler) { this.billHandler = billHandler == null ? null : billHandler.trim(); } public String getReceiptTerminal() { return receiptTerminal; } public void setReceiptTerminal(String receiptTerminal) { this.receiptTerminal = receiptTerminal == null ? null : receiptTerminal.trim(); } public String getReceiveDuration() { return receiveDuration; } public void setReceiveDuration(String receiveDuration) { this.receiveDuration = receiveDuration == null ? null : receiveDuration.trim(); } public Date getFirstReplyTime() { return firstReplyTime; } public void setFirstReplyTime(Date firstReplyTime) { this.firstReplyTime = firstReplyTime; } public String getIsReceiveTimeout() { return isReceiveTimeout; } public void setIsReceiveTimeout(String isReceiveTimeout) { this.isReceiveTimeout = isReceiveTimeout == null ? null : isReceiveTimeout.trim(); } public String getOperator() { return operator; } public void setOperator(String operator) { this.operator = operator == null ? null : operator.trim(); } public String getFaultConfirmContent() { return faultConfirmContent; } public void setFaultConfirmContent(String faultConfirmContent) { this.faultConfirmContent = faultConfirmContent == null ? null : faultConfirmContent.trim(); } public String getAreaManager() { return areaManager; } public void setAreaManager(String areaManager) { this.areaManager = areaManager == null ? null : areaManager.trim(); } public String getDataOrigin() { return dataOrigin; } public void setDataOrigin(String dataOrigin) { this.dataOrigin = dataOrigin == null ? null : dataOrigin.trim(); } public String getReceiveTerminal() { return receiveTerminal; } public void setReceiveTerminal(String receiveTerminal) { this.receiveTerminal = receiveTerminal == null ? null : receiveTerminal.trim(); } public Date getSignTime() { return signTime; } public void setSignTime(Date signTime) { this.signTime = signTime; } public String getSignLng() { return signLng; } public void setSignLng(String signLng) { this.signLng = signLng == null ? null : signLng.trim(); } public String getSignLat() { return signLat; } public void setSignLat(String signLat) { this.signLat = signLat == null ? null : signLat.trim(); } public String getStationLng() { return stationLng; } public void setStationLng(String stationLng) { this.stationLng = stationLng == null ? null : stationLng.trim(); } public String getStationLat() { return stationLat; } public void setStationLat(String stationLat) { this.stationLat = stationLat == null ? null : stationLat.trim(); } public String getIsElecGenerBill() { return isElecGenerBill; } public void setIsElecGenerBill(String isElecGenerBill) { this.isElecGenerBill = isElecGenerBill == null ? null : isElecGenerBill.trim(); } public String getFaultType() { return faultType; } public void setFaultType(String faultType) { this.faultType = faultType == null ? null : faultType.trim(); } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } }
9232a0f9935cbd4a08f87f6619b61f691809948e
174
java
Java
framework/src/play/src/main/java/play/mvc/package-info.java
bjfletcher/playframework
5533ced6154c87c22bf3a800f9babd9040a2895f
[ "Apache-2.0" ]
null
null
null
framework/src/play/src/main/java/play/mvc/package-info.java
bjfletcher/playframework
5533ced6154c87c22bf3a800f9babd9040a2895f
[ "Apache-2.0" ]
null
null
null
framework/src/play/src/main/java/play/mvc/package-info.java
bjfletcher/playframework
5533ced6154c87c22bf3a800f9babd9040a2895f
[ "Apache-2.0" ]
null
null
null
19.333333
72
0.689655
996,289
/* * Copyright (C) 2009-2016 Typesafe Inc. <http://www.typesafe.com> */ /** * Provides the Controller/Action/Result API for handling HTTP requests. */ package play.mvc;
9232a1557a9f8454d2ac0ecd186fb9fbb93a5a02
87
java
Java
shop-manage/src/main/java/quick/pager/shop/manage/param/goods/ClassificationSaveParam.java
lidongjie007/spring-cloud-shop
2d3163cfa6af1dba1bdd029ba0728403fbb558ef
[ "MIT" ]
1
2021-04-07T06:13:36.000Z
2021-04-07T06:13:36.000Z
shop-manage/src/main/java/quick/pager/shop/manage/param/goods/ClassificationSaveParam.java
fallSoul/spring-cloud-shop
1d4139e19b44a023eace15b7e3f9508fc1d73086
[ "MIT" ]
null
null
null
shop-manage/src/main/java/quick/pager/shop/manage/param/goods/ClassificationSaveParam.java
fallSoul/spring-cloud-shop
1d4139e19b44a023eace15b7e3f9508fc1d73086
[ "MIT" ]
null
null
null
17.4
44
0.816092
996,290
package quick.pager.shop.manage.param.goods; public class ClassificationSaveParam { }
9232a197f8d4d5b24fd962f1a406a0f0b973defe
2,889
java
Java
src/main/java/com/boohee/one/ui/InviteFriendsActivity.java
JackChan1999/boohee_v5.6
221f7ea237f491e2153039a42941a515493ba52c
[ "Apache-2.0" ]
7
2017-05-30T12:01:38.000Z
2021-04-22T12:22:39.000Z
src/main/java/com/boohee/one/ui/InviteFriendsActivity.java
JackChan1999/boohee_v5.6
221f7ea237f491e2153039a42941a515493ba52c
[ "Apache-2.0" ]
null
null
null
src/main/java/com/boohee/one/ui/InviteFriendsActivity.java
JackChan1999/boohee_v5.6
221f7ea237f491e2153039a42941a515493ba52c
[ "Apache-2.0" ]
6
2017-07-28T03:47:08.000Z
2019-06-28T17:57:50.000Z
37.038462
98
0.613707
996,291
package com.boohee.one.ui; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import boohee.lib.share.ShareManager; import com.boohee.main.GestureActivity; import com.boohee.one.R; import java.io.File; public class InviteFriendsActivity extends GestureActivity implements OnClickListener { private final String shareDesc = "薄荷已经帮助近600万用户成功减去32,000,000斤!加入薄荷,和我一起减肥吧!"; private final String shareMsg = "薄荷已经帮助近600万用户成功减去32,000,000斤!加入薄荷,和我一起减肥吧!http://a.app.qq" + ".com/o/simple.jsp?pkgname=com.boohee.one&g_f=991653"; private final String shareUrl = "http://a.app.qq.com/o/simple.jsp?pkgname=com.boohee" + ".one&g_f=991653"; public void onCreate(Bundle outState) { super.onCreate(outState); setContentView(R.layout.hd); setTitle("邀请伙伴"); addListener(); init(); } private void addListener() { findViewById(R.id.txtMsg).setOnClickListener(this); findViewById(R.id.sinaWeibo).setOnClickListener(this); findViewById(R.id.weichatFriends).setOnClickListener(this); findViewById(R.id.circle).setOnClickListener(this); } private void init() { } public void onClick(View v) { switch (v.getId()) { case R.id.txtMsg: Intent intent = new Intent("android.intent.action.SENDTO", Uri.parse("smsto:")); intent.putExtra("sms_body", "薄荷已经帮助近600万用户成功减去32,000,000斤!加入薄荷,和我一起减肥吧!http://a" + ".app.qq.com/o/simple.jsp?pkgname=com.boohee.one&g_f=991653"); startActivity(intent); return; case R.id.sinaWeibo: case R.id.weichatFriends: case R.id.circle: ShareManager.share(this, "邀请伙伴", "薄荷已经帮助近600万用户成功减去32,000," + "000斤!加入薄荷,和我一起减肥吧!http://a.app.qq.com/o/simple.jsp?pkgname=com.boohee" + ".one&g_f=991653"); return; default: return; } } public void shareMsg(String activityTitle, String msgTitle, String msgText, String imgPath) { Intent intent = new Intent("android.intent.action.SEND"); if (imgPath == null || imgPath.equals("")) { intent.setType("text/plain"); } else { File f = new File(imgPath); if (f != null && f.exists() && f.isFile()) { intent.setType("image/jpg"); intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(f)); } } intent.putExtra("android.intent.extra.SUBJECT", msgTitle); intent.putExtra("android.intent.extra.TEXT", msgText); intent.setFlags(268435456); startActivity(Intent.createChooser(intent, activityTitle)); } }
9232a1cb7d9061e7737ede64013edaa267b4a98f
1,669
java
Java
components/proxy/src/main/java/com/hotels/styx/infrastructure/configuration/json/mixins/OriginsSnapshotMixin.java
kenluluuuluuuuu/styx
dc74250d5b92e247d3db8c6be702df1bd1f453d9
[ "Apache-2.0" ]
239
2017-10-13T16:13:59.000Z
2021-04-28T17:24:57.000Z
components/proxy/src/main/java/com/hotels/styx/infrastructure/configuration/json/mixins/OriginsSnapshotMixin.java
kenluluuuluuuuu/styx
dc74250d5b92e247d3db8c6be702df1bd1f453d9
[ "Apache-2.0" ]
238
2017-10-19T10:49:26.000Z
2021-06-09T12:23:12.000Z
components/proxy/src/main/java/com/hotels/styx/infrastructure/configuration/json/mixins/OriginsSnapshotMixin.java
kenluluuuluuuuu/styx
dc74250d5b92e247d3db8c6be702df1bd1f453d9
[ "Apache-2.0" ]
79
2017-10-16T10:55:25.000Z
2021-06-05T01:16:27.000Z
33.38
82
0.746555
996,292
/* Copyright (C) 2013-2021 Expedia Inc. 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.hotels.styx.infrastructure.configuration.json.mixins; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.hotels.styx.api.extension.Origin; import java.util.Collection; import java.util.Set; /** * Jackson annotations for {@link com.hotels.styx.api.extension.OriginsSnapshot}. */ public abstract class OriginsSnapshotMixin { @JsonCreator OriginsSnapshotMixin( @JsonProperty("appId") String appId, @JsonProperty("activeOrigins") Collection<Origin> activeOrigins, @JsonProperty("inactiveOrigins") Collection<Origin> inactiveOrigins, @JsonProperty("disabledOrigins") Collection<Origin> disabledOrigins) { } @JsonProperty("appId") public abstract String appIdAsString(); @JsonProperty("activeOrigins") public abstract Set<Origin> activeOrigins(); @JsonProperty("inactiveOrigins") public abstract Set<Origin> inactiveOrigins(); @JsonProperty("disabledOrigins") public abstract Set<Origin> disabledOrigins(); }
9232a3b0c4e089350e31f04ebd8a58ed52e41221
2,067
java
Java
src/main/java/xyz/xuminghai/cache/decorator/ScheduledDecorator.java
xuMingHai1/aliyundrive-client-spring-boot-starter
25435dfb8d497feb2ce9ddf32901f6ed3fa37f39
[ "MulanPSL-1.0" ]
6
2021-11-15T14:12:12.000Z
2022-03-26T03:18:42.000Z
src/main/java/xyz/xuminghai/cache/decorator/ScheduledDecorator.java
xuMingHai1/aliyundrive-client-spring-boot-starter
25435dfb8d497feb2ce9ddf32901f6ed3fa37f39
[ "MulanPSL-1.0" ]
1
2021-11-19T08:11:43.000Z
2021-11-27T23:54:56.000Z
src/main/java/xyz/xuminghai/cache/decorator/ScheduledDecorator.java
xuMingHai1/aliyundrive-client-spring-boot-starter
25435dfb8d497feb2ce9ddf32901f6ed3fa37f39
[ "MulanPSL-1.0" ]
null
null
null
24.034884
87
0.649734
996,293
/* * Copyright (c) [2021] [xuMingHai] * [aliyundrive-client-spring-boot-starter] is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * http://license.coscl.org.cn/MulanPSL2 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ package xyz.xuminghai.cache.decorator; import lombok.extern.slf4j.Slf4j; import xyz.xuminghai.cache.Cache; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * 2021/10/21 18:33 星期四<br/> * 给定多少秒,定时清空缓存 * * @author xuMingHai */ @Slf4j public class ScheduledDecorator implements Cache { /** * 被装饰的对象 */ private final Cache cache; @SuppressWarnings("AlibabaThreadPoolCreation") public ScheduledDecorator(Cache cache, int fixedDelay) { this.cache = cache; Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(() -> { log.info("【{}】定时{}秒:执行了定时清空缓存", getName(), fixedDelay); clear(); }, fixedDelay, fixedDelay, TimeUnit.SECONDS); } @Override public String getName() { return cache.getName(); } @Override public void put(Object key, Object value) { cache.put(key, value); } @Override public void put(Object key, Object value, long timestampSeconds) { cache.put(key, value, timestampSeconds); } @Override public Object get(Object key) { return cache.get(key); } @Override public void remove(Object key) { cache.remove(key); } @Override public void clear() { cache.clear(); } @Override public long size() { return cache.size(); } @Override public Set<Object> keySet() { return cache.keySet(); } }
9232a59366688bcf08f08f023fa2e493b6bc7997
1,476
java
Java
common/src/main/java/ua/lviv/navpil/collections/TestCollections.java
navpil/java-examples
b218ac1cd79edcc9cc6087ca952a5a57b1b6f82a
[ "MIT" ]
null
null
null
common/src/main/java/ua/lviv/navpil/collections/TestCollections.java
navpil/java-examples
b218ac1cd79edcc9cc6087ca952a5a57b1b6f82a
[ "MIT" ]
null
null
null
common/src/main/java/ua/lviv/navpil/collections/TestCollections.java
navpil/java-examples
b218ac1cd79edcc9cc6087ca952a5a57b1b6f82a
[ "MIT" ]
null
null
null
27.333333
113
0.598916
996,294
package ua.lviv.navpil.collections; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.ListIterator; import java.util.Map; import java.util.stream.Collectors; public class TestCollections { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add("" + i); } ArrayList<Person> people = new ArrayList<>(); for (int i = 0; i < 10; i++) { people.add(new Person("Name" + i, i)); } Map<String, Integer> map = people.stream().collect(Collectors.toMap(Person::getName, Person::getAge)); System.out.println(map); Collections.fill(list.subList(3, 9), "6"); System.out.println(list.stream().collect(Collectors.toMap(val -> val, val -> val, (v1, v2) -> v1 + v2))); System.out.println(list); // ListIterator<String> it = list.listIterator(list.size()); // // while (it.hasPrevious()) { // System.out.println(it.previous()); // } // // int a = 1; // int b = -a; // // int i = -Integer.MIN_VALUE; // int minValue = Integer.MIN_VALUE; // System.out.println(i == minValue); // // System.out.println(0b10000000_00000000_00000000_00000000); // System.out.println(0b11111111_11111111_11111111_11111111); } }
9232a5b85d90f3cdc495d964389a6b63585ece1c
3,481
java
Java
src/main/java/com/redhat/fuse/boosters/rest/routers/lab02/RestRouter.java
leviatas/fuse-workshop
596846b8eaeb66d1d925b95dc58d3859a37b8972
[ "Apache-2.0" ]
null
null
null
src/main/java/com/redhat/fuse/boosters/rest/routers/lab02/RestRouter.java
leviatas/fuse-workshop
596846b8eaeb66d1d925b95dc58d3859a37b8972
[ "Apache-2.0" ]
null
null
null
src/main/java/com/redhat/fuse/boosters/rest/routers/lab02/RestRouter.java
leviatas/fuse-workshop
596846b8eaeb66d1d925b95dc58d3859a37b8972
[ "Apache-2.0" ]
null
null
null
40.476744
123
0.540075
996,295
package com.redhat.fuse.boosters.rest.routers.lab02; import org.apache.camel.builder.RouteBuilder; import org.springframework.stereotype.Component; import com.redhat.fuse.boosters.rest.model.Order; import com.redhat.fuse.boosters.rest.model.TwitterSearchRequest;; @Component public class RestRouter extends RouteBuilder { @Override public void configure() throws Exception { // insert your rest code here rest("/telegram") .put("/toggle").description("Toggle Start/Stop Telegram Bot") .route().routeId("telegram-toggle") .process(new ToggleRouteProcessor("telegram_bot")) .log("${body}") .endRest(); rest("/twitter") .put("/toggle").type(TwitterSearchRequest.class).description("Toggle Start/Stop Twitter searcher") .route().routeId("twitter-toggle") //.log("${body}") .wireTap("direct:twitter-search") .setBody().simple("Se comenzo pedido de datos a Twitter") .endRest(); rest("/ordergenerator") .put("/toggle").description("Toggle Start/Stop ordergenerator searcher") .route().routeId("ordergenerator-toggle") .process(new ToggleRouteProcessor("order_generator")) .log("${body}") .endRest(); rest("/orders") .get("/").description("Get all orders") .route().routeId("all-orders") .log("geting all orders entries from database") .to(this.selectAll) .endRest() .get("/{id}").description("Get orders by id") .route().routeId("find-by-id") .log("geting order with id ${header.id} entry from database") .to(this.selectById) .endRest() .post("/").type(Order.class).description("Create a new order") .route().routeId("create order") .log("Order received") .to(this.insertOrder) .endRest() .post("/async").type(Order.class).description("Create a new order") .route().routeId("create order async") .log("Order received") .wireTap("direct:create-order") .setBody().simple("We received your request, as soon we process your request we will notify you by email.") .endRest(); from("direct:create-order") .log("sending ${body.item} to JMS queue") .to("activemq:queue:orders"); // Consume from the message broker queue from("activemq:queue:orders") .routeId("queue_consumer") .noAutoStartup() .log("received ${body.item} from JMS queue") .to(this.insertOrder) .to("mock:notify-by-email"); } // Query support private String ds = "?dataSource=dataSource"; private String selectAll = "sql:select * from orders" + ds; private String selectById = "sql:select * from orders where id = :#${header.id}" + ds; private String insertOrder = "sql:insert into orders (item, amount, description, processed) values " + "(:#${body.item}, :#${body.amount}, :#${body.description}, false)"+ ds; }
9232a6412afbb06f93bf1616ac1f3d243325855d
6,144
java
Java
src/me/rv/game/Game.java
amazingrv/2D-Multiplayer-Engine
02b8212326bb843aae4aa3ee675d639e56dbb495
[ "MIT" ]
null
null
null
src/me/rv/game/Game.java
amazingrv/2D-Multiplayer-Engine
02b8212326bb843aae4aa3ee675d639e56dbb495
[ "MIT" ]
null
null
null
src/me/rv/game/Game.java
amazingrv/2D-Multiplayer-Engine
02b8212326bb843aae4aa3ee675d639e56dbb495
[ "MIT" ]
null
null
null
28.183486
115
0.528971
996,296
package me.rv.game; import java.awt.Canvas; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferStrategy; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import javax.swing.JFrame; import javax.swing.JOptionPane; import me.rv.game.entities.Player; import me.rv.game.entities.PlayerMP; import me.rv.game.gfx.Screen; import me.rv.game.gfx.SpriteSheet; import me.rv.game.level.Level; import me.rv.game.net.GameClient; import me.rv.game.net.GameServer; import me.rv.game.net.packets.Packet00Login; public class Game extends Canvas implements Runnable { private static final long serialVersionUID = 1L; public static final int WIDTH = 160; public static final int HEIGHT = WIDTH / 12 * 9; public static final int SCALE = 3; public static final String NAME = "Game"; public static final Dimension DIMENSIONS = new Dimension(WIDTH * SCALE, HEIGHT * SCALE); public static Game game; public JFrame frame; private Thread thread; public boolean running = false; public int tickCount = 0; private BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); private int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); private int[] colours = new int[6 * 6 * 6]; private Screen screen; public InputHandler input; public WindowHandler windowHandler; public Level level; public Player player; public GameClient socketClient; public GameServer socketServer; public boolean debug = true; public boolean isApplet = false; public void init() { game = this; int index = 0; for (int r = 0; r < 6; r++) { for (int g = 0; g < 6; g++) { for (int b = 0; b < 6; b++) { int rr = (r * 255 / 5); int gg = (g * 255 / 5); int bb = (b * 255 / 5); colours[index++] = rr << 16 | gg << 8 | bb; } } } screen = new Screen(WIDTH, HEIGHT, new SpriteSheet("/sprite_sheet.png")); input = new InputHandler(this); level = new Level("/levels/water_test_level.png"); player = new PlayerMP(level, 100, 100, input, JOptionPane.showInputDialog(this, "Please enter a username"), null, -1); level.addEntity(player); if (!isApplet) { Packet00Login loginPacket = new Packet00Login(player.getUsername(), player.x, player.y); if (socketServer != null) { socketServer.addConnection((PlayerMP) player, loginPacket); } loginPacket.writeData(socketClient); } } public synchronized void start() { running = true; thread = new Thread(this, NAME + "_main"); thread.start(); if (!isApplet) { if (JOptionPane.showConfirmDialog(this, "Do you want to run the server") == 0) { socketServer = new GameServer(this); socketServer.start(); } socketClient = new GameClient(this, "localhost"); socketClient.start(); } } public synchronized void stop() { running = false; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void run() { long lastTime = System.nanoTime(); double nsPerTick = 1000000000D / 60D; int ticks = 0; int frames = 0; long lastTimer = System.currentTimeMillis(); double delta = 0; init(); while (running) { long now = System.nanoTime(); delta += (now - lastTime) / nsPerTick; lastTime = now; boolean shouldRender = true; while (delta >= 1) { ticks++; tick(); delta -= 1; shouldRender = true; } try { Thread.sleep(2); } catch (InterruptedException e) { e.printStackTrace(); } if (shouldRender) { frames++; render(); } if (System.currentTimeMillis() - lastTimer >= 1000) { lastTimer += 1000; debug(DebugLevel.INFO, ticks + " ticks, " + frames + " frames"); frames = 0; ticks = 0; } } } public void tick() { tickCount++; level.tick(); } public void render() { BufferStrategy bs = getBufferStrategy(); if (bs == null) { createBufferStrategy(3); return; } int xOffset = player.x - (screen.width / 2); int yOffset = player.y - (screen.height / 2); level.renderTiles(screen, xOffset, yOffset); level.renderEntities(screen); for (int y = 0; y < screen.height; y++) { for (int x = 0; x < screen.width; x++) { int colourCode = screen.pixels[x + y * screen.width]; if (colourCode < 255) pixels[x + y * WIDTH] = colours[colourCode]; } } Graphics g = bs.getDrawGraphics(); g.drawImage(image, 0, 0, getWidth(), getHeight(), null); g.dispose(); bs.show(); } public static long fact(int n) { if (n <= 1) { return 1; } else { return n * fact(n - 1); } } public void debug(DebugLevel level, String msg) { switch (level) { default: case INFO: if (debug) { System.out.println("[" + NAME + "] " + msg); } break; case WARNING: System.out.println("[" + NAME + "] [WARNING] " + msg); break; case SEVERE: System.out.println("[" + NAME + "] [SEVERE]" + msg); this.stop(); break; } } public static enum DebugLevel { INFO, WARNING, SEVERE; } }
9232a847c8e8f07ba68e29325e861e74381e6a20
5,466
java
Java
TimingFramework-Fundamentals/BasicRace/src/TrackView.java
romainguy/filthy-rich-clients
29e0c2011bb41870540301b8df21385d264baadd
[ "BSD-3-Clause" ]
162
2015-07-01T19:30:01.000Z
2022-03-15T02:36:56.000Z
TimingFramework-Advanced/SetterRace/src/TrackView.java
romainguy/filthy-rich-clients
29e0c2011bb41870540301b8df21385d264baadd
[ "BSD-3-Clause" ]
null
null
null
TimingFramework-Advanced/SetterRace/src/TrackView.java
romainguy/filthy-rich-clients
29e0c2011bb41870540301b8df21385d264baadd
[ "BSD-3-Clause" ]
47
2015-07-02T00:38:30.000Z
2021-08-23T11:09:31.000Z
40.191176
86
0.664654
996,297
/** * Copyright (c) 2007, Sun Microsystems, Inc * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted 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 the TimingFramework project nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * 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. */ import java.awt.AlphaComposite; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.Point; import javax.swing.JComponent; import javax.imageio.ImageIO; import javax.swing.JFrame; /** * This class does the work of rendering the current view of the * racetrack. It holds the car position and rotation and displays * the car accordingly. The track itself is merely a background image * that is copied the same on every repaint. * Note that carPosition and carRotation are both JavaBean properties, which * is exploited in the SetterRace and MultiStepRace variations. * * @author Chet */ public class TrackView extends JComponent { BufferedImage car; BufferedImage track; Point carPosition; double carRotation = 0; int trackW, trackH; int carW, carH, carWHalf, carHHalf; /** Hard-coded positions of interest on the track */ static final Point START_POS = new Point(450, 70); static final Point FIRST_TURN_START = new Point(130, 70); static final Point FIRST_TURN_END = new Point(76, 127); static final Point SECOND_TURN_START = new Point(76, 404); static final Point SECOND_TURN_END = new Point(130, 461); static final Point THIRD_TURN_START = new Point(450, 461); static final Point THIRD_TURN_END = new Point(504, 404); static final Point FOURTH_TURN_START = new Point(504, 127); /** Creates a new instance of TrackView */ public TrackView() { try { car = ImageIO.read(TrackView.class.getResource("images/beetle_red.gif")); track = ImageIO.read(TrackView.class.getResource("images/track.jpg")); } catch (Exception e) { System.out.println("Problem loading track/car images: " + e); } carPosition = new Point(START_POS.x, START_POS.y); carW = car.getWidth(); carH = car.getHeight(); carWHalf = carW / 2; carHHalf = carH / 2; trackW = track.getWidth(); trackH = track.getHeight(); } public Dimension getPreferredSize() { return new Dimension(trackW, trackH); } /** * Render the track and car */ public void paintComponent(Graphics g) { // First draw the race track g.drawImage(track, 0, 0, null); // Now draw the car. The translate/rotate/translate settings account // for any nonzero carRotation values Graphics2D g2d = (Graphics2D)g.create(); g2d.translate(carPosition.x, carPosition.y); g2d.rotate(Math.toRadians(carRotation)); g2d.translate(-(carPosition.x), -(carPosition.y)); // Now the graphics has been set up appropriately; draw the // car in position g2d.drawImage(car, carPosition.x - carWHalf, carPosition.y - carHHalf, null); } /** * Set the new position and schedule a repaint */ public void setCarPosition(Point newPosition) { repaint(0, carPosition.x - carWHalf, carPosition.y - carHHalf, carW, carH); carPosition.x = newPosition.x; carPosition.y = newPosition.y; repaint(0, carPosition.x - carWHalf, carPosition.y - carHHalf, carW, carH); } /** * Set the new rotation and schedule a repaint */ public void setCarRotation(double newDegrees) { carRotation = newDegrees; // repaint area accounts for larger rectangular are because rotate // car will exceed normal rectangular bounds repaint(0, carPosition.x - carW, carPosition.y - carH, 2 * carW, 2 * carH); } }
9232a8533fd08eb749d1c78237488d60546dc6ff
2,396
java
Java
dubbo-cache-core/src/main/java/com/github/bohrqiu/dubbo/cache/factory/AbstractCacheFactory.java
bohrqiu/dubbo-cache
43314b32653272b25cac01fd55b7ebcb8ffaed41
[ "Apache-2.0" ]
12
2018-07-27T03:03:11.000Z
2021-04-29T02:34:55.000Z
dubbo-cache-core/src/main/java/com/github/bohrqiu/dubbo/cache/factory/AbstractCacheFactory.java
bohrqiu/dubbo-cache
43314b32653272b25cac01fd55b7ebcb8ffaed41
[ "Apache-2.0" ]
1
2021-09-01T06:53:19.000Z
2021-09-01T06:53:19.000Z
dubbo-cache-core/src/main/java/com/github/bohrqiu/dubbo/cache/factory/AbstractCacheFactory.java
bohrqiu/dubbo-cache
43314b32653272b25cac01fd55b7ebcb8ffaed41
[ "Apache-2.0" ]
3
2020-09-05T07:40:15.000Z
2021-09-01T06:51:47.000Z
39.933333
109
0.713689
996,298
/* * 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 com.github.bohrqiu.dubbo.cache.factory; import com.alibaba.dubbo.common.logger.Logger; import com.alibaba.dubbo.common.logger.LoggerFactory; import com.alibaba.dubbo.rpc.Invocation; import com.alibaba.dubbo.rpc.Invoker; import com.github.bohrqiu.dubbo.cache.Cache; import com.github.bohrqiu.dubbo.cache.CacheFactory; import com.github.bohrqiu.dubbo.cache.CacheMeta; import com.github.bohrqiu.dubbo.cache.el.SpelKeyGenerator; import com.github.bohrqiu.dubbo.cache.impl.NullCache; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * @date 2018-07-24 01:48 */ public abstract class AbstractCacheFactory implements CacheFactory { private static final Logger logger = LoggerFactory.getLogger(SpelKeyGenerator.class); private static ConcurrentMap<CacheMeta, Cache> concurrentMap = new ConcurrentHashMap<CacheMeta, Cache>(); public Cache getCache(Invoker<?> invoker, Invocation inv, CacheMeta cacheMeta) { Cache cache; try { cache = concurrentMap.get(cacheMeta); if (cache == null) { cache = doGetCache(invoker, inv, cacheMeta); if (cache == null) { cache = NullCache.INSTANCE; } concurrentMap.putIfAbsent(cacheMeta, cache); } } catch (Exception e) { logger.warn("create CacheFactory FAILURE", e); cache = NullCache.INSTANCE; } return cache; } public abstract Cache doGetCache(Invoker<?> invoker, Invocation inv, CacheMeta cacheMeta); }
9232a8577b4b30170f7cda0e27fa287458310d12
1,538
java
Java
libs/craftbukkit/src/main/java/net/minecraft/server/ItemFlintAndSteel.java
123099/QuestJobs
fe5e83e399ef9e151e2ac1cd56491c2a126dc8e9
[ "MIT" ]
null
null
null
libs/craftbukkit/src/main/java/net/minecraft/server/ItemFlintAndSteel.java
123099/QuestJobs
fe5e83e399ef9e151e2ac1cd56491c2a126dc8e9
[ "MIT" ]
null
null
null
libs/craftbukkit/src/main/java/net/minecraft/server/ItemFlintAndSteel.java
123099/QuestJobs
fe5e83e399ef9e151e2ac1cd56491c2a126dc8e9
[ "MIT" ]
null
null
null
48.0625
259
0.661248
996,299
package net.minecraft.server; public class ItemFlintAndSteel extends Item { public ItemFlintAndSteel() { this.maxStackSize = 1; this.setMaxDurability(64); this.a(CreativeModeTab.i); } public EnumInteractionResult a(ItemStack itemstack, EntityHuman entityhuman, World world, BlockPosition blockposition, EnumHand enumhand, EnumDirection enumdirection, float f, float f1, float f2) { blockposition = blockposition.shift(enumdirection); if (!entityhuman.a(blockposition, enumdirection, itemstack)) { return EnumInteractionResult.FAIL; } else { if (world.getType(blockposition).getMaterial() == Material.AIR) { // CraftBukkit start - Store the clicked block if (org.bukkit.craftbukkit.event.CraftEventFactory.callBlockIgniteEvent(world, blockposition.getX(), blockposition.getY(), blockposition.getZ(), org.bukkit.event.block.BlockIgniteEvent.IgniteCause.FLINT_AND_STEEL, entityhuman).isCancelled()) { itemstack.damage(1, entityhuman); return EnumInteractionResult.PASS; } // CraftBukkit end world.a(entityhuman, blockposition, SoundEffects.by, SoundCategory.BLOCKS, 1.0F, ItemFlintAndSteel.j.nextFloat() * 0.4F + 0.8F); world.setTypeAndData(blockposition, Blocks.FIRE.getBlockData(), 11); } itemstack.damage(1, entityhuman); return EnumInteractionResult.SUCCESS; } } }
9232a88e0fa987498b8769da91a82edb73e4de3c
265
java
Java
crud/spring/src/main/java/ru/ibs/dpr/crud/spring/services/interceptors/DefaultPreCreateInterceptorImpl.java
KHValenting/ibs-components
b95a9f036430555a6870feb221789ef415344207
[ "Apache-2.0" ]
null
null
null
crud/spring/src/main/java/ru/ibs/dpr/crud/spring/services/interceptors/DefaultPreCreateInterceptorImpl.java
KHValenting/ibs-components
b95a9f036430555a6870feb221789ef415344207
[ "Apache-2.0" ]
null
null
null
crud/spring/src/main/java/ru/ibs/dpr/crud/spring/services/interceptors/DefaultPreCreateInterceptorImpl.java
KHValenting/ibs-components
b95a9f036430555a6870feb221789ef415344207
[ "Apache-2.0" ]
null
null
null
29.444444
104
0.754717
996,300
package ru.ibs.dpr.crud.spring.services.interceptors; public class DefaultPreCreateInterceptorImpl<DTO, ENTITY> implements InterceptorPreCreate<DTO, ENTITY> { @Override public ENTITY preCreate(ENTITY newEntity, DTO dto) { return newEntity; } }
9232a8ec9ab5951c403b714687c4a63589e6117b
1,643
java
Java
xbean-server/src/main/java/org/apache/xbean/server/loader/Loader.java
codehaus/xbean
8df3bc28bfe8f4b7064c9de14310753416be4021
[ "Apache-2.0" ]
null
null
null
xbean-server/src/main/java/org/apache/xbean/server/loader/Loader.java
codehaus/xbean
8df3bc28bfe8f4b7064c9de14310753416be4021
[ "Apache-2.0" ]
null
null
null
xbean-server/src/main/java/org/apache/xbean/server/loader/Loader.java
codehaus/xbean
8df3bc28bfe8f4b7064c9de14310753416be4021
[ "Apache-2.0" ]
null
null
null
35.717391
113
0.722459
996,301
/** * * Copyright 2005-2006 The Apache Software Foundation or its licensors, as applicable. * * 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.apache.xbean.server.loader; import org.apache.xbean.kernel.ServiceName; import org.apache.xbean.kernel.Kernel; /** * Loaders load configurations into a Kernel. * @author Dain Sundstrom * @version $Id$ * @since 2.0 */ public interface Loader { /** * Gets the kernel in which configuraitons are loaded. * @return the kernel in which configurations are loaded */ Kernel getKernel(); /** * Loads the specified configuration into the kernel. The location passed to this method is specific loader * implementation. It is important to remember that a loader only loads the configuration into the kernel and * does not start the configuration. * * @param location the location of the configuration * @return the service name of the configuration added to the kernel * @throws Exception if a problem occurs while loading the configuration */ ServiceName load(String location) throws Exception; }
9232a9eb354401731ff754ae5d513d46a9570528
2,652
java
Java
coffee-chats/src/main/java/com/google/step/coffee/servlets/GroupMembersServlet.java
googleinterns/step250-2020
055b00a2596d084564f9fd48a12946075b6d273a
[ "Apache-2.0" ]
3
2020-07-13T09:19:43.000Z
2020-08-10T12:01:55.000Z
coffee-chats/src/main/java/com/google/step/coffee/servlets/GroupMembersServlet.java
googleinterns/step250-2020
055b00a2596d084564f9fd48a12946075b6d273a
[ "Apache-2.0" ]
6
2020-08-11T16:03:58.000Z
2022-02-13T19:33:38.000Z
coffee-chats/src/main/java/com/google/step/coffee/servlets/GroupMembersServlet.java
googleinterns/step250-2020
055b00a2596d084564f9fd48a12946075b6d273a
[ "Apache-2.0" ]
null
null
null
35.837838
108
0.751508
996,302
package com.google.step.coffee.servlets; import com.google.step.coffee.HttpError; import com.google.step.coffee.JsonServlet; import com.google.step.coffee.JsonServletRequest; import com.google.step.coffee.PermissionChecker; import com.google.step.coffee.data.CalendarUtils; import com.google.step.coffee.data.EventStore; import com.google.step.coffee.data.GroupStore; import com.google.step.coffee.entity.Event; import com.google.step.coffee.entity.Group; import com.google.step.coffee.entity.GroupMembership; import com.google.step.coffee.entity.User; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.stream.Collectors; @WebServlet("/api/groupMembers") public class GroupMembersServlet extends JsonServlet { private GroupStore groupStore = new GroupStore(); private EventStore eventStore = new EventStore(); private static class GroupMember { public final User user; public final GroupMembership.Status status; public GroupMember(User user, GroupMembership.Status status) { this.user = user; this.status = status; } } @Override public Object get(JsonServletRequest request) throws IOException, HttpError { PermissionChecker.ensureLoggedIn(); Group group = Group.fromEntity(request.getEntityFromParameter("id", "group")); return groupStore.getMembers(group).stream() .map(x -> new GroupMember(x.user(), x.status())).collect(Collectors.toList()); } @Override public Object post(JsonServletRequest request) throws IOException, HttpError { Group group = Group.fromEntity(request.getEntityFromParameter("id", "group")); User user = User.builder() .setId(request.getRequiredParameter("user")) .build(); GroupMembership.Status status, oldStatus; try { status = GroupMembership.Status.valueOf(request.getRequiredParameter("status")); } catch (IllegalArgumentException exception) { throw new HttpError(HttpServletResponse.SC_BAD_REQUEST, "Invalid value for parameter 'status'"); } oldStatus = groupStore.getMembershipStatus(group, user); PermissionChecker.ensureCanUpdateMembershipStatus(group, user, status); groupStore.updateMembershipStatus(group, user, status); if (oldStatus == GroupMembership.Status.NOT_A_MEMBER || status == GroupMembership.Status.NOT_A_MEMBER) { // somebody joined or left the group // let's invite/exclude them from upcoming events for (Event event : eventStore.getUpcomingEventsForGroup(group)) { CalendarUtils.updateGroupEvent(event); } } return null; } }
9232abb24057dab02864b5cf1159134923ef5820
1,433
java
Java
modules/base/vcs-api/src/main/java/com/intellij/openapi/vcs/vfs/VcsVirtualFolder.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
634
2015-01-01T19:14:25.000Z
2022-03-22T11:42:50.000Z
modules/base/vcs-api/src/main/java/com/intellij/openapi/vcs/vfs/VcsVirtualFolder.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
410
2015-01-19T09:57:51.000Z
2022-03-22T16:24:59.000Z
modules/base/vcs-api/src/main/java/com/intellij/openapi/vcs/vfs/VcsVirtualFolder.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
50
2015-03-10T04:14:49.000Z
2022-03-22T07:08:45.000Z
31.844444
111
0.750872
996,303
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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.intellij.openapi.vcs.vfs; import com.intellij.openapi.vcs.VcsBundle; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.VirtualFileSystem; import javax.annotation.Nonnull; import java.io.IOException; public class VcsVirtualFolder extends AbstractVcsVirtualFile { private final VirtualFile myChild; public VcsVirtualFolder(String name, VirtualFile child, VirtualFileSystem fileSystem) { super(name == null ? "" : name, fileSystem); myChild = child; } public VirtualFile[] getChildren() { return new VirtualFile[]{myChild}; } public boolean isDirectory() { return true; } @Nonnull public byte[] contentsToByteArray() throws IOException { throw new RuntimeException(VcsBundle.message("exception.text.internal.error.method.should.not.be.called")); } }
9232abb95aa1c32353193c1f553cc3f117c8f9f4
2,791
java
Java
src/datastructure/queue/blockqueue/SimpleArrayBlockQueue.java
shiwei-Ren/algorithm
c1c22d2d587060d650fd7591a7728c1e79a20f45
[ "Apache-2.0" ]
5
2021-09-10T01:12:27.000Z
2021-12-17T07:07:35.000Z
src/datastructure/queue/blockqueue/SimpleArrayBlockQueue.java
shiwei-Ren/algorithm
c1c22d2d587060d650fd7591a7728c1e79a20f45
[ "Apache-2.0" ]
null
null
null
src/datastructure/queue/blockqueue/SimpleArrayBlockQueue.java
shiwei-Ren/algorithm
c1c22d2d587060d650fd7591a7728c1e79a20f45
[ "Apache-2.0" ]
1
2021-09-25T11:57:57.000Z
2021-09-25T11:57:57.000Z
23.453782
94
0.473307
996,304
package datastructure.queue.blockqueue; /** * description:数组来实现简单的阻塞队列 * <p> * 使用 synchronized + wait() + notifyAll() * * @author RenShiWei * Date: 2021/8/6 16:34 **/ public class SimpleArrayBlockQueue<T> { /** 实际的元素个数 */ private int count; /** 队首指针 */ private int head; /** 队尾指针 */ private int tail; /** 存放元素的数组 */ private T[] data; @SuppressWarnings("unchecked") public SimpleArrayBlockQueue(int arrLen) { this.count = 0; this.head = 0; this.tail = 0; data = (T[]) new Object[arrLen]; } /** * 阻塞队列入队 * * @param data 入队元素 */ public synchronized void put(T data) { while (count >= this.data.length) { try { System.out.println(Thread.currentThread().getName() + "队列已满,put操作阻塞线程"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } this.data[tail] = data; this.tail = (tail + 1) % this.data.length; count++; notifyAll(); } /** * 阻塞队列出队 * * @return 出队元素 */ public synchronized T take() { while (count <= 0) { try { System.out.println(Thread.currentThread().getName() + "队列已空,take操作阻塞线程"); wait(); } catch (InterruptedException e) { e.printStackTrace(); } } T t = data[head]; this.head = (head + 1) % data.length; count--; notifyAll(); return t; } /** * @return 阻塞队列的长度 */ public synchronized int size() { return data.length; } /** * 测试 */ @SuppressWarnings("all") public static void main(String[] args) { SimpleArrayBlockQueue<Integer> blockingQueue = new SimpleArrayBlockQueue<Integer>(10); Thread thread = new Thread(() -> { for (int i = 0; i < 9; i++) { blockingQueue.put(i); System.out.println("put-num:" + i); } }); try { thread.start(); //等待thread执行完毕后再进行操作 thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { for (int i = 0; i < 5; i++) { Integer num = blockingQueue.take(); System.out.println(Thread.currentThread().getName() + "-take-num:" + num); } }).start(); new Thread(() -> { for (int i = 0; i < 15; i++) { Integer num = blockingQueue.take(); System.out.println(Thread.currentThread().getName() + "-take-num:" + num); } }).start(); } }
9232aeb88acde71aaf501d3cddb17b061471dcf8
658
java
Java
src/com/sun/corba/se/spi/activation/ORBPortInfo.java
pengisgood/jdk-source-code
c799af9f668303aa045df3152d984388e151954d
[ "MIT" ]
1
2020-05-11T07:44:10.000Z
2020-05-11T07:44:10.000Z
jdk/src/main/java/com/sun/corba/se/spi/activation/ORBPortInfo.java
dibt/spring-framework
ce2dfa68e2331a07d36bdcf7aa92597c91a391ee
[ "Apache-2.0" ]
null
null
null
jdk/src/main/java/com/sun/corba/se/spi/activation/ORBPortInfo.java
dibt/spring-framework
ce2dfa68e2331a07d36bdcf7aa92597c91a391ee
[ "Apache-2.0" ]
null
null
null
24.37037
141
0.712766
996,305
package com.sun.corba.se.spi.activation; /** * com/sun/corba/se/spi/activation/ORBPortInfo.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from /Users/java_re/workspace/8-2-build-macosx-x86_64/jdk8u191/11896/corba/src/share/classes/com/sun/corba/se/spi/activation/activation.idl * Saturday, October 6, 2018 8:38:57 AM PDT */ public final class ORBPortInfo implements org.omg.CORBA.portable.IDLEntity { public String orbId = null; public int port = (int)0; public ORBPortInfo () { } // ctor public ORBPortInfo (String _orbId, int _port) { orbId = _orbId; port = _port; } // ctor } // class ORBPortInfo
9232b08bf2435deb64fc5051c1f95b3e009cc59e
320
java
Java
src/main/java/com/ketnoiso/media/grabber/repository/SingerRepository.java
lephuongbac/grabberv2
8a8463b6d8014315820ee5167f20e07b929673cb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ketnoiso/media/grabber/repository/SingerRepository.java
lephuongbac/grabberv2
8a8463b6d8014315820ee5167f20e07b929673cb
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ketnoiso/media/grabber/repository/SingerRepository.java
lephuongbac/grabberv2
8a8463b6d8014315820ee5167f20e07b929673cb
[ "Apache-2.0" ]
null
null
null
26.666667
71
0.79375
996,307
package com.ketnoiso.media.grabber.repository; import com.ketnoiso.media.grabber.core.model.Singer; import org.springframework.data.repository.CrudRepository; /** * Created by IT on 3/30/2015. */ public interface SingerRepository extends CrudRepository<Singer,Long> { Singer findByNameIgnoreCase(String name); }
9232b0d0f59e7b9a8b16e5c4c464d5858efe6694
4,094
java
Java
src/main/javaopen/com/jediterm/terminal/TextStyle.java
HaleyWang/SpringRemote
62e442731a4eda8e54dafb1dfb36064cd8dfa597
[ "MIT" ]
39
2019-02-26T02:02:38.000Z
2022-03-28T02:09:23.000Z
src/main/javaopen/com/jediterm/terminal/TextStyle.java
HaleyWang/SpringRemote
62e442731a4eda8e54dafb1dfb36064cd8dfa597
[ "MIT" ]
2
2020-04-19T04:05:01.000Z
2022-03-27T02:10:18.000Z
src/main/javaopen/com/jediterm/terminal/TextStyle.java
HaleyWang/SpringRemote
62e442731a4eda8e54dafb1dfb36064cd8dfa597
[ "MIT" ]
4
2020-03-17T07:23:33.000Z
2021-11-21T11:00:25.000Z
25.271605
126
0.695652
996,308
package com.jediterm.terminal; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.ref.WeakReference; import java.util.EnumSet; import java.util.Objects; import java.util.WeakHashMap; public class TextStyle { private static final EnumSet<Option> NO_OPTIONS = EnumSet.noneOf(Option.class); public static final TextStyle EMPTY = new TextStyle(); private static final WeakHashMap<TextStyle, WeakReference<TextStyle>> styles = new WeakHashMap<>(); private final TerminalColor myForeground; private final TerminalColor myBackground; private final EnumSet<Option> myOptions; public TextStyle() { this(null, null, NO_OPTIONS); } public TextStyle(@Nullable TerminalColor foreground, @Nullable TerminalColor background) { this(foreground, background, NO_OPTIONS); } public TextStyle(@Nullable TerminalColor foreground, @Nullable TerminalColor background, @NotNull EnumSet<Option> options) { myForeground = foreground; myBackground = background; myOptions = options.clone(); } @NotNull public static TextStyle getCanonicalStyle(TextStyle currentStyle) { if (currentStyle instanceof HyperlinkStyle) { return currentStyle; } final WeakReference<TextStyle> canonRef = styles.get(currentStyle); if (canonRef != null) { final TextStyle canonStyle = canonRef.get(); if (canonStyle != null) { return canonStyle; } } styles.put(currentStyle, new WeakReference<>(currentStyle)); return currentStyle; } @Nullable public TerminalColor getForeground() { return myForeground; } @Nullable public TerminalColor getBackground() { return myBackground; } public TextStyle createEmptyWithColors() { return new TextStyle(myForeground, myBackground); } public int getId() { return hashCode(); } public boolean hasOption(final Option option) { return myOptions.contains(option); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TextStyle textStyle = (TextStyle) o; return Objects.equals(myForeground, textStyle.myForeground) && Objects.equals(myBackground, textStyle.myBackground) && myOptions.equals(textStyle.myOptions); } @Override public int hashCode() { return Objects.hash(myForeground, myBackground, myOptions); } public TerminalColor getBackgroundForRun() { return myOptions.contains(Option.INVERSE) ? myForeground : myBackground; } public TerminalColor getForegroundForRun() { return myOptions.contains(Option.INVERSE) ? myBackground : myForeground; } @NotNull public Builder toBuilder() { return new Builder(this); } public enum Option { BOLD, ITALIC, BLINK, DIM, INVERSE, UNDERLINED, HIDDEN; private void set(@NotNull EnumSet<Option> options, boolean val) { if (val) { options.add(this); } else { options.remove(this); } } } public static class Builder { private TerminalColor myForeground; private TerminalColor myBackground; private EnumSet<Option> myOptions; public Builder(@NotNull TextStyle textStyle) { myForeground = textStyle.myForeground; myBackground = textStyle.myBackground; myOptions = textStyle.myOptions.clone(); } public Builder() { myForeground = null; myBackground = null; myOptions = EnumSet.noneOf(Option.class); } @NotNull public Builder setForeground(@Nullable TerminalColor foreground) { myForeground = foreground; return this; } @NotNull public Builder setBackground(@Nullable TerminalColor background) { myBackground = background; return this; } @NotNull public Builder setOption(@NotNull Option option, boolean val) { option.set(myOptions, val); return this; } @NotNull public TextStyle build() { return new TextStyle(myForeground, myBackground, myOptions); } } }
9232b17296b01b052d71402cd150e259960881c0
2,346
java
Java
src/main/java/com/shimizukenta/hokuyoopticalparallel/dme/DMEInputData.java
kenta-shimizu/hokuyo-optical-parallel-io-java8
992e328acd1d323181d309c7897354e22ec296bd
[ "Apache-2.0" ]
1
2020-06-15T10:46:25.000Z
2020-06-15T10:46:25.000Z
src/main/java/com/shimizukenta/hokuyoopticalparallel/dme/DMEInputData.java
kenta-shimizu/hokuyo-optical-parallel-io-java8
992e328acd1d323181d309c7897354e22ec296bd
[ "Apache-2.0" ]
null
null
null
src/main/java/com/shimizukenta/hokuyoopticalparallel/dme/DMEInputData.java
kenta-shimizu/hokuyo-optical-parallel-io-java8
992e328acd1d323181d309c7897354e22ec296bd
[ "Apache-2.0" ]
null
null
null
16.757143
69
0.548167
996,309
package com.shimizukenta.hokuyoopticalparallel.dme; import java.io.Serializable; /** * This class is DME InputData. * * @author kenta-shimizu * */ public final class DMEInputData implements Serializable { private static final long serialVersionUID = -4009350247279673915L; private byte input; private DMEInputData(byte input) { this.input = input; } private DMEInputData() { this((byte)0x0); } /** * Returns Input byte * * @return Input byte */ public byte get() { synchronized ( this ) { return this.input; } } private boolean isHigh(int shift) { synchronized ( this ) { byte b = (byte)0x1; b <<= shift; return (this.input & b) != 0x0; } } /** * Returns input is high. * * @param input * @return {@code true} is high */ public boolean isInput(DMEInput input) { synchronized ( this ) { return isHigh(input.shift()) == input.high(); } } @Override public String toString() { synchronized ( this ) { StringBuilder sb = new StringBuilder(); for ( int i = 8; i > 0; ) { --i; sb.append(isHigh(i) ? "1" : "0"); } return sb.toString(); } } /** * byte setter. * * @param input */ public void set(byte input) { synchronized ( this ) { this.input = input; } } /** * inputs Setter. * * @param inputs */ public void set(DMEInput... inputs) { synchronized ( this ) { byte ref = get(); for ( DMEInput i : inputs ) { byte b = (byte)0x1; b <<= i.shift(); if ( i.high() ) { ref |= b; } else { ref &= ~b; } } set(ref); } } /** * Returns new instance. * * @return DMEInputData instance */ public static DMEInputData initial() { return new DMEInputData(); } /** * Returns new instance from byte. * * @param input * @return DMEInputData instance */ public static DMEInputData from(byte input) { return new DMEInputData(input); } /** * Returns DMEInputData from inputs. * * @param inputs * @return DMEInputData instance */ public static DMEInputData from(DMEInput... inputs) { DMEInputData i = initial(); i.set(inputs); return i; } }
9232b1c849e284a0e50b561f0943da5f368c25a6
14,372
java
Java
aai-els-onap-logging/src/main/java/org/onap/aai/util/AAIApplicationConfig.java
onap/aai-aai-common
a49ef9fe705e5b076436f0a0fc1a6ea0a099fb51
[ "Apache-2.0" ]
3
2019-02-19T02:21:30.000Z
2020-05-18T23:08:48.000Z
aai-els-onap-logging/src/main/java/org/onap/aai/util/AAIApplicationConfig.java
onap/aai-aai-common
a49ef9fe705e5b076436f0a0fc1a6ea0a099fb51
[ "Apache-2.0" ]
null
null
null
aai-els-onap-logging/src/main/java/org/onap/aai/util/AAIApplicationConfig.java
onap/aai-aai-common
a49ef9fe705e5b076436f0a0fc1a6ea0a099fb51
[ "Apache-2.0" ]
1
2020-05-18T23:08:52.000Z
2020-05-18T23:08:52.000Z
34.631325
128
0.606944
996,310
/** * ============LICENSE_START======================================================= * org.onap.aai * ================================================================================ * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved. * ================================================================================ * 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. * ============LICENSE_END========================================================= */ package org.onap.aai.util; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.util.security.Password; import org.onap.aai.exceptions.AAIException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AAIApplicationConfig { private static final Logger LOGGER = LoggerFactory.getLogger(AAIApplicationConfig.class); private static String GLOBAL_PROP_FILE_NAME = "application.properties"; private static final String SERVER_CERTS_LOCATION_PROP_NAME = "server.certs.location"; private static final String PASSPHRASSES_FILENAME = ".passphrases"; private static final String PASSWORD_FILENAME = ".password"; private static final String TRUSTSTORE_PASSWORD_PROP_NAME = "cadi_truststore_password"; public static final String SERVER_SSL_KEYSTORE_PROP_NAME = "server.ssl.key-store"; public static final String SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME = "server.ssl.key-store.pkcs12"; public static final String SERVER_SSL_TRUSTSTORE_PROP_NAME = "server.ssl.trust-store"; public static final String TRUSTSTORE_PASSWORD_NAME = "server.ssl.trust-store-password"; public static final String KEYSTORE_PASSWORD_NAME = "server.ssl.key-store-password"; private static Properties serverProps; private static boolean propsInitialized = false; private static String TRUSTSTORE_PASSWORD = null; private static String KEYSTORE_PASSWORD = null; private static final String PROPERTY_REGEX = "\\$\\{([^\\$\\{\\}]+)\\}"; /** * Instantiates a new AAI config. */ // Don't instantiate private AAIApplicationConfig() { } /** * Inits the. * * @throws AAIException the AAI exception */ public synchronized static void init() { LOGGER.info("Initializing AAIApplicationConfig"); AAIApplicationConfig.reloadConfig(); } /** * Reload config. */ public synchronized static void reloadConfig() { Properties newServerProps = new Properties(); LOGGER.debug("Reloading config from " + GLOBAL_PROP_FILE_NAME); try { InputStream is = AAIApplicationConfig.class.getClassLoader().getResourceAsStream(GLOBAL_PROP_FILE_NAME); newServerProps.load(is); propsInitialized = true; serverProps = newServerProps; TRUSTSTORE_PASSWORD = retrieveTruststorePassword(); KEYSTORE_PASSWORD = retrieveKeystorePassword(); } catch (Exception fnfe) { final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("application.properties"); LOGGER.info("Unable to find the application.properties from filesystem so using file in jar"); if (is != null) { try { newServerProps.load(is); serverProps = newServerProps; TRUSTSTORE_PASSWORD = retrieveTruststorePassword(); KEYSTORE_PASSWORD = retrieveKeystorePassword(); } catch (IOException e) { LOGGER.warn("Encountered IO Exception during loading of props from inputstream", e); } } else { LOGGER.error("Expected to find the properties file in the jar but unable to find it"); } } } /** * Gets the key value * * @param key the key * @param defaultValue the default value * @return the string */ public static String get(String key, String defaultValue) { String result = defaultValue; try { result = get(key); } catch (AAIException a) { } if (result == null || result.isEmpty()) { result = defaultValue; } return (result); } /** * Gets the key value * * @param key the key * @return the string * @throws AAIException the AAI exception */ public static String get(String key) throws AAIException { String response = null; if (!propsInitialized || (serverProps == null)) { reloadConfig(); } if ((key.endsWith("password") || key.endsWith("passwd") || key.endsWith("apisecret")) && serverProps.containsKey(key + ".x")) { String valx = serverProps.getProperty(key + ".x"); return Password.deobfuscate(valx); } if (!serverProps.containsKey(key)) { throw new AAIException("AAI_4005", "Property key " + key + " cannot be found"); } else { response = serverProps.getProperty(key); if (response == null || response.isEmpty()) { throw new AAIException("AAI_4005", "Property key " + key + " is null or empty"); } response = replaceProperties(response); } return response; } /** * Gets the keystore path * * @return the string * @throws AAIException the AAI exception */ public static String getKeystore() throws AAIException { return (get(SERVER_SSL_KEYSTORE_PROP_NAME)); } /** * Gets the PKCS12 keystore path * * @return the string * @throws AAIException the AAI exception */ public static String getKeystorePkcs12() throws AAIException { return (get(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME)); } /** * Gets the keystore path * * @return the string * @throws AAIException the AAI exception */ public static String getTruststore() throws AAIException { return (get(SERVER_SSL_TRUSTSTORE_PROP_NAME)); } /** * Retrieve the keystore password * * @return the password */ private static String retrieveKeystorePassword() { String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME); if (certPath == null) { return null; } try { certPath = replaceProperties(certPath); } catch (AAIException e) { return null; } return (retrieveKeystorePasswordWithCertPath(certPath)); } /** * Retrieve the keystore password * * @return the password */ private static String retrieveKeystorePasswordWithCertPath(String certPath) { File passwordFile = null; InputStream passwordStream = null; String keystorePassword = null; // Override the passwords from application.properties if we find AAF certman files try { passwordFile = new File(certPath + PASSWORD_FILENAME); passwordStream = new FileInputStream(passwordFile); keystorePassword = IOUtils.toString(passwordStream, Charset.defaultCharset()); if (keystorePassword != null) { keystorePassword = keystorePassword.trim(); } } catch (IOException e) { LOGGER.warn("Not using AAF Certman password file, e=" + e.getMessage()); } catch (NullPointerException n) { LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage()); } finally { if (passwordStream != null) { try { passwordStream.close(); } catch (Exception e) { } } } return keystorePassword; } /** * Get the keystore password * * @return the password */ public static String getKeystorePassword() { return (KEYSTORE_PASSWORD); } /** * Gets the truststore password * * @return the password */ private static String retrieveTruststorePasswordWithCertPath(String certPath) { File passphrasesFile = null; InputStream passphrasesStream = null; String truststorePassword = null; try { passphrasesFile = new File(certPath + PASSPHRASSES_FILENAME); passphrasesStream = new FileInputStream(passphrasesFile); Properties passphrasesProps = new Properties(); passphrasesProps.load(passphrasesStream); truststorePassword = passphrasesProps.getProperty(TRUSTSTORE_PASSWORD_PROP_NAME); if (truststorePassword != null) { truststorePassword = truststorePassword.trim(); } } catch (IOException e) { LOGGER.warn("Not using AAF Certman passphrases file, e=" + e.getMessage()); } catch (NullPointerException n) { LOGGER.warn("Not using AAF Certman passphrases file, e=" + n.getMessage()); } finally { if (passphrasesStream != null) { try { passphrasesStream.close(); } catch (Exception e) { } } } return truststorePassword; } /** * Gets the truststore password * * @return the password */ private static String retrieveTruststorePassword() { String certPath = serverProps.getProperty(SERVER_CERTS_LOCATION_PROP_NAME); if (certPath == null) { return null; } try { certPath = replaceProperties(certPath); } catch (AAIException e) { return null; } return (retrieveTruststorePasswordWithCertPath(certPath)); } /** * Get the trustore password * * @return the password */ public static String getTruststorePassword() { return (TRUSTSTORE_PASSWORD); } /** * Gets the int value for the key. * * @param key the key * @return the int * @throws AAIException the AAI exception */ public static int getInt(String key) throws AAIException { return Integer.parseInt(AAIApplicationConfig.get(key)); } /** * Gets the int. * * @param key the key * @return the int */ public static int getInt(String key, String value) { return Integer.parseInt(AAIApplicationConfig.get(key, value)); } /** * Gets the server props. * * @return the server props */ public static Properties getServerProps() { return serverProps; } /** * Check if a null or an Empty string is passed in. * * @param s the s * @return boolean */ public static boolean isEmpty(String s) { return (s == null || s.length() == 0); } private static String replaceProperties(String originalValue) throws AAIException { final Pattern p = Pattern.compile(PROPERTY_REGEX); Matcher m = p.matcher(originalValue); /*if (!m.matches()) { return originalValue; }*/ StringBuffer sb = new StringBuffer(); while(m.find()) { String text = m.group(1); String replacement = get(text); m.appendReplacement(sb, replacement); } m.appendTail(sb); return(sb.toString()); } public static Properties retrieveKeystoreProps() throws AAIException { Properties props = new Properties(); String truststorePath = System.getProperty(SERVER_SSL_TRUSTSTORE_PROP_NAME); String truststorePassword = System.getProperty(TRUSTSTORE_PASSWORD_NAME); String keystorePath = System.getProperty(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME); String keystorePassword = System.getProperty(KEYSTORE_PASSWORD_NAME); String certLocation = System.getProperty(SERVER_CERTS_LOCATION_PROP_NAME); if (truststorePath == null || truststorePath.isEmpty()){ truststorePath = AAIApplicationConfig.getTruststore(); } if (truststorePath != null) { props.setProperty(SERVER_SSL_TRUSTSTORE_PROP_NAME, truststorePath); } if (truststorePassword == null || truststorePassword.isEmpty()) { if (certLocation != null && (!certLocation.isEmpty())) { truststorePassword = AAIApplicationConfig.retrieveTruststorePasswordWithCertPath(certLocation); } else { truststorePassword = AAIApplicationConfig.getTruststorePassword(); } } if (truststorePassword != null) { props.setProperty(TRUSTSTORE_PASSWORD_NAME, truststorePassword); } if (keystorePath == null || keystorePath.isEmpty()){ keystorePath = AAIApplicationConfig.getKeystorePkcs12(); } if (keystorePath != null) { props.setProperty(SERVER_SSL_KEYSTORE_PKCS12_PROP_NAME, keystorePath); } if (keystorePassword == null || keystorePassword.isEmpty()){ if (certLocation != null && (!certLocation.isEmpty())) { keystorePassword = AAIApplicationConfig.retrieveKeystorePasswordWithCertPath(certLocation); } else { keystorePassword = AAIApplicationConfig.getKeystorePassword(); } } if (keystorePassword != null) { props.setProperty(KEYSTORE_PASSWORD_NAME, keystorePassword); } return(props); } }
9232b21befcb618486359ad30bf8d6647bc605b9
10,261
java
Java
google-cloud-aiplatform/src/test/java/com/google/cloud/aiplatform/v1/MockModelServiceImpl.java
aditidatta/java-aiplatform
a37df55116ab1118b45e69a1d6af7c12eeb822fc
[ "Apache-2.0" ]
7
2021-02-21T10:39:41.000Z
2021-12-07T07:31:28.000Z
google-cloud-aiplatform/src/test/java/com/google/cloud/aiplatform/v1/MockModelServiceImpl.java
aditidatta/java-aiplatform
a37df55116ab1118b45e69a1d6af7c12eeb822fc
[ "Apache-2.0" ]
407
2020-09-23T21:46:09.000Z
2022-03-29T23:42:09.000Z
google-cloud-aiplatform/src/test/java/com/google/cloud/aiplatform/v1/MockModelServiceImpl.java
aditidatta/java-aiplatform
a37df55116ab1118b45e69a1d6af7c12eeb822fc
[ "Apache-2.0" ]
17
2020-09-23T21:44:55.000Z
2022-03-21T17:23:46.000Z
38.003704
106
0.661729
996,311
/* * Copyright 2021 Google LLC * * 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 * * https://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.google.cloud.aiplatform.v1; import com.google.api.core.BetaApi; import com.google.cloud.aiplatform.v1.ModelServiceGrpc.ModelServiceImplBase; import com.google.longrunning.Operation; import com.google.protobuf.AbstractMessage; import io.grpc.stub.StreamObserver; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import javax.annotation.Generated; @BetaApi @Generated("by gapic-generator-java") public class MockModelServiceImpl extends ModelServiceImplBase { private List<AbstractMessage> requests; private Queue<Object> responses; public MockModelServiceImpl() { requests = new ArrayList<>(); responses = new LinkedList<>(); } public List<AbstractMessage> getRequests() { return requests; } public void addResponse(AbstractMessage response) { responses.add(response); } public void setResponses(List<AbstractMessage> responses) { this.responses = new LinkedList<Object>(responses); } public void addException(Exception exception) { responses.add(exception); } public void reset() { requests = new ArrayList<>(); responses = new LinkedList<>(); } @Override public void uploadModel(UploadModelRequest request, StreamObserver<Operation> responseObserver) { Object response = responses.poll(); if (response instanceof Operation) { requests.add(request); responseObserver.onNext(((Operation) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method UploadModel, expected %s or %s", response == null ? "null" : response.getClass().getName(), Operation.class.getName(), Exception.class.getName()))); } } @Override public void getModel(GetModelRequest request, StreamObserver<Model> responseObserver) { Object response = responses.poll(); if (response instanceof Model) { requests.add(request); responseObserver.onNext(((Model) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method GetModel, expected %s or %s", response == null ? "null" : response.getClass().getName(), Model.class.getName(), Exception.class.getName()))); } } @Override public void listModels( ListModelsRequest request, StreamObserver<ListModelsResponse> responseObserver) { Object response = responses.poll(); if (response instanceof ListModelsResponse) { requests.add(request); responseObserver.onNext(((ListModelsResponse) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method ListModels, expected %s or %s", response == null ? "null" : response.getClass().getName(), ListModelsResponse.class.getName(), Exception.class.getName()))); } } @Override public void updateModel(UpdateModelRequest request, StreamObserver<Model> responseObserver) { Object response = responses.poll(); if (response instanceof Model) { requests.add(request); responseObserver.onNext(((Model) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method UpdateModel, expected %s or %s", response == null ? "null" : response.getClass().getName(), Model.class.getName(), Exception.class.getName()))); } } @Override public void deleteModel(DeleteModelRequest request, StreamObserver<Operation> responseObserver) { Object response = responses.poll(); if (response instanceof Operation) { requests.add(request); responseObserver.onNext(((Operation) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method DeleteModel, expected %s or %s", response == null ? "null" : response.getClass().getName(), Operation.class.getName(), Exception.class.getName()))); } } @Override public void exportModel(ExportModelRequest request, StreamObserver<Operation> responseObserver) { Object response = responses.poll(); if (response instanceof Operation) { requests.add(request); responseObserver.onNext(((Operation) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method ExportModel, expected %s or %s", response == null ? "null" : response.getClass().getName(), Operation.class.getName(), Exception.class.getName()))); } } @Override public void getModelEvaluation( GetModelEvaluationRequest request, StreamObserver<ModelEvaluation> responseObserver) { Object response = responses.poll(); if (response instanceof ModelEvaluation) { requests.add(request); responseObserver.onNext(((ModelEvaluation) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method GetModelEvaluation, expected %s or %s", response == null ? "null" : response.getClass().getName(), ModelEvaluation.class.getName(), Exception.class.getName()))); } } @Override public void listModelEvaluations( ListModelEvaluationsRequest request, StreamObserver<ListModelEvaluationsResponse> responseObserver) { Object response = responses.poll(); if (response instanceof ListModelEvaluationsResponse) { requests.add(request); responseObserver.onNext(((ListModelEvaluationsResponse) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method ListModelEvaluations, expected %s or %s", response == null ? "null" : response.getClass().getName(), ListModelEvaluationsResponse.class.getName(), Exception.class.getName()))); } } @Override public void getModelEvaluationSlice( GetModelEvaluationSliceRequest request, StreamObserver<ModelEvaluationSlice> responseObserver) { Object response = responses.poll(); if (response instanceof ModelEvaluationSlice) { requests.add(request); responseObserver.onNext(((ModelEvaluationSlice) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method GetModelEvaluationSlice, expected %s or %s", response == null ? "null" : response.getClass().getName(), ModelEvaluationSlice.class.getName(), Exception.class.getName()))); } } @Override public void listModelEvaluationSlices( ListModelEvaluationSlicesRequest request, StreamObserver<ListModelEvaluationSlicesResponse> responseObserver) { Object response = responses.poll(); if (response instanceof ListModelEvaluationSlicesResponse) { requests.add(request); responseObserver.onNext(((ListModelEvaluationSlicesResponse) response)); responseObserver.onCompleted(); } else if (response instanceof Exception) { responseObserver.onError(((Exception) response)); } else { responseObserver.onError( new IllegalArgumentException( String.format( "Unrecognized response type %s for method ListModelEvaluationSlices, expected %s or %s", response == null ? "null" : response.getClass().getName(), ListModelEvaluationSlicesResponse.class.getName(), Exception.class.getName()))); } } }
9232b21f61a737273517e49866ff580ddebf4f5b
2,154
java
Java
indri-utils/src/main/java/edu/isi/nlp/indri/DefaultIndriQueryer.java
berquist/nlp-util
cb65117b9a61bef2f4fffad9ee9a3c8ba5372650
[ "MIT" ]
1
2020-02-24T16:03:22.000Z
2020-02-24T16:03:22.000Z
indri-utils/src/main/java/edu/isi/nlp/indri/DefaultIndriQueryer.java
usc-isi-i2/nlp-util
cb65117b9a61bef2f4fffad9ee9a3c8ba5372650
[ "MIT" ]
8
2018-12-12T22:09:33.000Z
2021-12-09T20:08:14.000Z
indri-utils/src/main/java/edu/isi/nlp/indri/DefaultIndriQueryer.java
usc-isi-i2/nlp-util
cb65117b9a61bef2f4fffad9ee9a3c8ba5372650
[ "MIT" ]
4
2019-04-28T09:55:17.000Z
2020-08-05T15:44:07.000Z
34.190476
96
0.739554
996,312
package edu.isi.nlp.indri; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.ImmutableList; import edu.isi.nlp.scoring.Scored; import java.util.List; import lemurproject.indri.QueryEnvironment; import lemurproject.indri.ScoredExtentResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** Wraps Indri index in convenience methods. Create instances using {@link Indri}. */ /* package-private */ final class DefaultIndriQueryer implements IndriQueryer { private final QueryEnvironment indriIndex; private final String docIDField; private static final int UNLIMITED = Integer.MAX_VALUE; private static Logger log = LoggerFactory.getLogger(DefaultIndriQueryer.class); public DefaultIndriQueryer(QueryEnvironment indriIndex, String docIDField) { this.indriIndex = checkNotNull(indriIndex); this.docIDField = checkNotNull(docIDField); checkArgument(!docIDField.isEmpty(), "May not have a null doc ID field for Indri queryer."); } @Override public List<Scored<String>> docIDsMatchingQuery(String query) { return docIDsMatchingQuery(query, UNLIMITED); } @Override public List<Scored<String>> docIDsMatchingQuery(String query, int limit) { final ImmutableList.Builder<Scored<String>> ret = ImmutableList.builder(); try { final ScoredExtentResult[] indriResults = indriIndex.runQuery(query, limit); final String[] docIDs = indriIndex.documentMetadata(indriResults, docIDField); for (int i = 0; i < indriResults.length; ++i) { ret.add(Scored.from(docIDs[i], indriResults[i].score)); } return ret.build(); } catch (Exception e) { throw new IndriException("Exception while processing query: " + query, e); } } @Override public int countResults(String query) { // it can sometimes be significantly faster not to lookup the doc IDs try { return indriIndex.runQuery(query, UNLIMITED).length; } catch (Exception e) { throw new IndriException("Exception while processing query: " + query, e); } } }
9232b34b722f8607a7a600331c1ac8931e27ffec
32,703
java
Java
src/net/java/sip/communicator/plugin/update/UpdateServiceImpl.java
dyoh777/jitsi
c81e58f1a9c63b60f6ebbccfca113906472b186b
[ "Apache-2.0" ]
3,442
2015-01-08T09:51:28.000Z
2022-03-31T02:48:33.000Z
src/net/java/sip/communicator/plugin/update/UpdateServiceImpl.java
fleapapa/jitsi
805d76dad2d2218614de395f6a9c0cb3b582e664
[ "Apache-2.0" ]
577
2015-01-27T20:50:12.000Z
2022-03-11T13:08:45.000Z
src/net/java/sip/communicator/plugin/update/UpdateServiceImpl.java
fleapapa/jitsi
805d76dad2d2218614de395f6a9c0cb3b582e664
[ "Apache-2.0" ]
953
2015-01-04T05:20:14.000Z
2022-03-31T14:04:14.000Z
34.496835
86
0.477112
996,313
/* * Jitsi, the OpenSource Java VoIP and Instant Messaging client. * * Copyright @ 2015 Atlassian Pty Ltd * * 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 net.java.sip.communicator.plugin.update; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.text.*; import net.java.sip.communicator.plugin.desktoputil.*; import net.java.sip.communicator.plugin.desktoputil.FileUtils; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.httputil.*; import net.java.sip.communicator.service.update.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.util.Logger; import org.jitsi.service.resources.*; import org.jitsi.utils.version.*; import org.jitsi.util.*; /** * Implements checking for software updates, downloading and applying them i.e. * the very logic of the update plug-in. * * @author Damian Minkov * @author Lyubomir Marinov */ public class UpdateServiceImpl implements UpdateService { /** * The link pointing to the ChangeLog of the update. */ private static String changesLink; /** * The <tt>JDialog</tt>, if any, which is associated with the currently * executing "Check for Updates". While the "Check for Updates" * functionality cannot be entered, clicking the "Check for Updates" menu * item will bring it to the front. */ private static JDialog checkForUpdatesDialog; /** * The link pointing at the download of the update. */ private static String downloadLink; /** * The indicator/counter which determines how many methods are currently * executing the "Check for Updates" functionality so that it is known * whether it can be entered. */ private static int inCheckForUpdates = 0; /** * The latest version of the software found at the configured update * location. */ private static String latestVersion; /** * The <tt>Logger</tt> used by the <tt>UpdateServiceImpl</tt> class and its * instances for logging output. */ private static final Logger logger = Logger.getLogger(UpdateServiceImpl.class); /** * The name of the property which specifies the update link in the * configuration file. */ private static final String PROP_UPDATE_LINK = "net.java.sip.communicator.UPDATE_LINK"; /** * Initializes a new Web browser <tt>Component</tt> instance and navigates * it to a specific URL. * * @param url the URL to navigate the new Web browser <tt>Component</tt> * instance * @return the new Web browser <tt>Component</tt> instance which has been * navigated to the specified <tt>url</tt> */ private static Component createBrowser(String url) { // Initialize the user interface. JEditorPane editorPane = new JEditorPane(); editorPane.setContentType("text/html"); editorPane.setEditable(false); JScrollPane scrollPane = new JScrollPane(); scrollPane.setViewportView(editorPane); // Navigate the user interface to the specified URL. try { Document document = editorPane.getDocument(); if (document instanceof AbstractDocument) ((AbstractDocument) document).setAsynchronousLoadPriority(0); editorPane.setPage(new URL(url)); } catch (Throwable t) { if (t instanceof ThreadDeath) throw (ThreadDeath) t; else { logger.error( "Failed to navigate the Web browser to: " + url, t); } } return scrollPane; } /** * Notifies this <tt>UpdateCheckActivator</tt> that a method is entering the * "Check for Updates" functionality and it is thus not allowed to enter it * again. * * @param checkForUpdatesDialog the <tt>JDialog</tt> associated with the * entry in the "Check for Updates" functionality if any. While "Check for * Updates" cannot be entered again, clicking the "Check for Updates" menu * item will bring the <tt>checkForUpdatesDialog</tt> to the front. */ private static synchronized void enterCheckForUpdates( JDialog checkForUpdatesDialog) { inCheckForUpdates++; if (checkForUpdatesDialog != null) UpdateServiceImpl.checkForUpdatesDialog = checkForUpdatesDialog; } /** * Notifies this <tt>UpdateCheckActivator</tt> that a method is exiting the * "Check for Updates" functionality and it may thus be allowed to enter it * again. * * @param checkForUpdatesDialog the <tt>JDialog</tt> which was associated * with the matching call to {@link #enterCheckForUpdates(JDialog)} if any */ private static synchronized void exitCheckForUpdates( JDialog checkForUpdatesDialog) { if (inCheckForUpdates == 0) throw new IllegalStateException("inCheckForUpdates"); else { inCheckForUpdates--; if ((checkForUpdatesDialog != null) && (UpdateServiceImpl.checkForUpdatesDialog == checkForUpdatesDialog)) UpdateServiceImpl.checkForUpdatesDialog = null; } } /** * Gets the current (software) version. * * @return the current (software) version */ private static Version getCurrentVersion() { return getVersionService().getCurrentVersion(); } /** * Returns the currently registered instance of version service. * @return the current version service. */ private static VersionService getVersionService() { return ServiceUtils.getService( UpdateActivator.bundleContext, VersionService.class); } /** * Determines whether we are currently running the latest version. * * @return <tt>true</tt> if we are currently running the latest version; * otherwise, <tt>false</tt> */ private static boolean isLatestVersion() { try { String updateLink = UpdateActivator.getConfiguration().getString( PROP_UPDATE_LINK); if(updateLink == null) { updateLink = Resources.getUpdateConfigurationString("update_link"); } if(updateLink == null) { if (logger.isDebugEnabled()) logger.debug( "Updates are disabled, faking latest version."); } else { HttpUtils.HTTPResponseResult res = HttpUtils.openURLConnection(updateLink); if (res != null) { InputStream in = null; Properties props = new Properties(); try { in = res.getContent(); props.load(in); } finally { in.close(); } latestVersion = props.getProperty("last_version"); downloadLink = props.getProperty("download_link"); /* * Make sure that download_link points to the architecture * of the running application. */ if (downloadLink != null) { if (OSUtils.IS_LINUX32) { downloadLink = downloadLink.replace("amd64", "i386"); } else if (OSUtils.IS_LINUX64) { downloadLink = downloadLink.replace("i386", "amd64"); } else if (OSUtils.IS_WINDOWS32) { downloadLink = downloadLink.replace("x64", "x86"); } else if (OSUtils.IS_WINDOWS64) { downloadLink = downloadLink.replace("x86", "x64"); } } changesLink = updateLink.substring( 0, updateLink.lastIndexOf("/") + 1) + props.getProperty("changes_html"); try { VersionService versionService = getVersionService(); Version latestVersionObj = versionService.parseVersionString(latestVersion); if(latestVersionObj != null) return latestVersionObj.compareTo( getCurrentVersion()) <= 0; else logger.error("Version obj not parsed(" + latestVersion + ")"); } catch(Throwable t) { logger.error("Error parsing version string", t); } // fallback to lexicographically compare // of version strings in case of an error return latestVersion.compareTo( getCurrentVersion().toString()) <= 0; } } } catch (Exception e) { logger.warn( "Could not retrieve latest version or compare it to current" + " version", e); /* * If we get an exception, then we will return that the current * version is the newest one in order to prevent opening the dialog * notifying about the availability of a new version. */ } return true; } /** * Runs in a daemon/background <tt>Thread</tt> dedicated to checking whether * a new version of the application is available and notifying the user * about the result of the check. * * @param notifyAboutNewestVersion <tt>true</tt> to notify the user in case * she is running the newest/latest version available already; otherwise, * <tt>false</tt> */ private static void runInCheckForUpdatesThread( boolean notifyAboutNewestVersion) { if(isLatestVersion()) { if(notifyAboutNewestVersion) { SwingUtilities.invokeLater( new Runnable() { public void run() { UIService ui = UpdateActivator.getUIService(); ResourceManagementService r = Resources.getResources(); ui.getPopupDialog().showMessagePopupDialog( r.getI18NString( "plugin.updatechecker.DIALOG_NOUPDATE"), r.getI18NString( "plugin.updatechecker.DIALOG_NOUPDATE_TITLE"), PopupDialog.INFORMATION_MESSAGE); } }); } } else { SwingUtilities.invokeLater( new Runnable() { public void run() { if (OSUtils.IS_WINDOWS) showWindowsNewVersionAvailableDialog(); else showGenericNewVersionAvailableDialog(); } }); } } /** * Shows dialog informing about the availability of a new version with a * Download button which launches the system Web browser. */ private static void showGenericNewVersionAvailableDialog() { /* * Before showing the dialog, we'll enterCheckForUpdates() in order to * notify that it is not safe to enter "Check for Updates" again. If we * don't manage to show the dialog, we'll have to exitCheckForUpdates(). * If we manage though, we'll have to exitCheckForUpdates() but only * once depending on its modality. */ final boolean[] exitCheckForUpdates = new boolean[] { false }; final JDialog dialog = new SIPCommDialog() { private static final long serialVersionUID = 0L; @Override protected void close(boolean escaped) { synchronized (exitCheckForUpdates) { if (exitCheckForUpdates[0]) exitCheckForUpdates(this); } } }; ResourceManagementService resources = Resources.getResources(); dialog.setTitle( resources.getI18NString("plugin.updatechecker.DIALOG_TITLE")); JEditorPane contentMessage = new JEditorPane(); contentMessage.setContentType("text/html"); contentMessage.setOpaque(false); contentMessage.setEditable(false); String dialogMsg = resources.getI18NString( "plugin.updatechecker.DIALOG_MESSAGE", new String[] { resources.getSettingsString( "service.gui.APPLICATION_NAME") }); if(latestVersion != null) dialogMsg += resources.getI18NString( "plugin.updatechecker.DIALOG_MESSAGE_2", new String[] { resources.getSettingsString( "service.gui.APPLICATION_NAME"), latestVersion }); contentMessage.setText(dialogMsg); JPanel contentPane = new TransparentPanel(new BorderLayout(5,5)); contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); contentPane.add(contentMessage, BorderLayout.CENTER); JPanel buttonPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); final JButton closeButton = new JButton( resources.getI18NString( "plugin.updatechecker.BUTTON_CLOSE")); closeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); if (exitCheckForUpdates[0]) exitCheckForUpdates(dialog); } }); if(downloadLink != null) { JButton downloadButton = new JButton( resources.getI18NString( "plugin.updatechecker.BUTTON_DOWNLOAD")); downloadButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { UpdateActivator.getBrowserLauncher().openURL(downloadLink); /* * Do the same as the Close button in order to not duplicate * the code. */ closeButton.doClick(); } }); buttonPanel.add(downloadButton); } buttonPanel.add(closeButton); contentPane.add(buttonPanel, BorderLayout.SOUTH); dialog.setContentPane(contentPane); dialog.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); dialog.setLocation( screenSize.width/2 - dialog.getWidth()/2, screenSize.height/2 - dialog.getHeight()/2); synchronized (exitCheckForUpdates) { enterCheckForUpdates(dialog); exitCheckForUpdates[0] = true; } try { dialog.setVisible(true); } finally { synchronized (exitCheckForUpdates) { if (exitCheckForUpdates[0] && dialog.isModal()) exitCheckForUpdates(dialog); } } } /** * Shows dialog informing about new version with button Install * which triggers the update process. */ private static void showWindowsNewVersionAvailableDialog() { /* * Before showing the dialog, we'll enterCheckForUpdates() in order to * notify that it is not safe to enter "Check for Updates" again. If we * don't manage to show the dialog, we'll have to exitCheckForUpdates(). * If we manage though, we'll have to exitCheckForUpdates() but only * once depending on its modality. */ final boolean[] exitCheckForUpdates = new boolean[] { false }; @SuppressWarnings("serial") final JDialog dialog = new SIPCommDialog() { @Override protected void close(boolean escaped) { synchronized (exitCheckForUpdates) { if (exitCheckForUpdates[0]) exitCheckForUpdates(this); } } }; ResourceManagementService r = Resources.getResources(); dialog.setTitle(r.getI18NString("plugin.updatechecker.DIALOG_TITLE")); JEditorPane contentMessage = new JEditorPane(); contentMessage.setContentType("text/html"); contentMessage.setOpaque(false); contentMessage.setEditable(false); /* * Use the font of the dialog because contentMessage is just like a * label. */ contentMessage.putClientProperty( JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); String dialogMsg = r.getI18NString( "plugin.updatechecker.DIALOG_MESSAGE", new String[] { r.getSettingsString( "service.gui.APPLICATION_NAME") }); if(latestVersion != null) { dialogMsg += r.getI18NString( "plugin.updatechecker.DIALOG_MESSAGE_2", new String[] { r.getSettingsString( "service.gui.APPLICATION_NAME"), latestVersion }); } contentMessage.setText(dialogMsg); JPanel contentPane = new SIPCommFrame.MainContentPane(); contentMessage.setBorder(BorderFactory.createEmptyBorder(10, 0, 20, 0)); contentPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 10)); contentPane.add(contentMessage, BorderLayout.NORTH); Component browser = createBrowser(changesLink); if (browser != null) { browser.setPreferredSize(new Dimension(550, 200)); contentPane.add(browser, BorderLayout.CENTER); } JPanel buttonPanel = new TransparentPanel(new FlowLayout(FlowLayout.CENTER, 10, 10)); final JButton closeButton = new JButton( r.getI18NString( "plugin.updatechecker.BUTTON_CLOSE")); closeButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { dialog.dispose(); if (exitCheckForUpdates[0]) exitCheckForUpdates(dialog); } }); if(downloadLink != null) { JButton installButton = new JButton( r.getI18NString("plugin.updatechecker.BUTTON_INSTALL")); installButton.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { enterCheckForUpdates(null); try { /* * Do the same as the Close button in order to * not duplicate the code. */ closeButton.doClick(); } finally { boolean windowsUpdateThreadHasStarted = false; try { new Thread() { @Override public void run() { try { windowsUpdate(); } finally { exitCheckForUpdates(null); } } }.start(); windowsUpdateThreadHasStarted = true; } finally { if (!windowsUpdateThreadHasStarted) exitCheckForUpdates(null); } } } }); buttonPanel.add(installButton); } buttonPanel.add(closeButton); contentPane.add(buttonPanel, BorderLayout.SOUTH); dialog.setContentPane(contentPane); dialog.pack(); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); dialog.setLocation( screenSize.width/2 - dialog.getWidth()/2, screenSize.height/2 - dialog.getHeight()/2); synchronized (exitCheckForUpdates) { enterCheckForUpdates(dialog); exitCheckForUpdates[0] = true; } try { dialog.setVisible(true); } finally { synchronized (exitCheckForUpdates) { if (exitCheckForUpdates[0] && dialog.isModal()) exitCheckForUpdates(dialog); } } } /** * Implements the very update procedure on Windows which includes without * being limited to: * <ol> * <li>Downloads the setup in a temporary directory.</li> * <li>Warns that the update procedure will shut down the application.</li> * <li>Executes the setup in a separate process and shuts down the * application.</li> * </ol> */ private static void windowsUpdate() { /* * Firstly, try a delta update which contains a bspatch file to be used * to reconstruct the latest MSI from the locally-cached one. If it * fails, fall back to a full update. */ File delta = null; boolean deleteDelta = true; File msi = null; try { String deltaTarget = null; Version ver = getCurrentVersion(); if(ver.isNightly()) deltaTarget = ver.getNightlyBuildID(); else deltaTarget = ver.toString(); String deltaLink = downloadLink.replace( latestVersion, latestVersion + "-delta-" + deltaTarget); if (!deltaLink.equalsIgnoreCase(downloadLink)) delta = FileUtils.download(deltaLink, "setup", ".exe"); if (delta != null) { File[] deltaMsi = new File[1]; FileUtils.createTempFileOutputStream( delta.toURI().toURL(), ".msi", /* * Do not actually create a FileOutputStream, we just * want the File (name). */ true, deltaMsi, "setup", ".exe" ); Process process = new ProcessBuilder( delta.getCanonicalPath(), "--quiet", deltaMsi[0].getCanonicalPath()) .start(); int exitCode = 1; while (true) { try { exitCode = process.waitFor(); break; } catch (InterruptedException ie) { /* * Ignore it, we're interested in the exit code of the * process. */ } } if (0 == exitCode) { deleteDelta = false; msi = deltaMsi[0]; } } } catch (Exception e) { /* Ignore it, we'll try the full update. */ } finally { if (deleteDelta && (delta != null)) { delta.delete(); delta = null; } } /* * Secondly, either apply the delta update or download and apply a full * update. */ boolean deleteMsi = true; deleteDelta = true; try { if (msi == null) msi = FileUtils.download(downloadLink, "setup", ".exe"); if (msi != null) { ResourceManagementService resources = Resources.getResources(); if(UpdateActivator.getUIService() .getPopupDialog().showConfirmPopupDialog( resources.getI18NString( "plugin.updatechecker.DIALOG_WARN", new String[]{ resources.getSettingsString( "service.gui.APPLICATION_NAME") }), resources.getI18NString( "plugin.updatechecker.DIALOG_TITLE"), PopupDialog.YES_NO_OPTION, PopupDialog.QUESTION_MESSAGE) == PopupDialog.YES_OPTION) { List<String> command = new ArrayList<String>(); /* * If a delta update is in effect, the delta will execute * the latest MSI it has previously recreated from the * locally-cached MSI. Otherwise, a full update is in effect * and it will just execute itself. */ command.add( ((delta == null) ? msi : delta).getCanonicalPath()); command.add("--wait-parent"); if (delta != null) { command.add("--msiexec"); command.add(msi.getCanonicalPath()); } command.add( "SIP_COMMUNICATOR_AUTOUPDATE_INSTALLDIR=\"" + System.getProperty("user.dir") + "\""); deleteMsi = false; deleteDelta = false; /* * The setup has been downloaded. Now start it and shut * down. */ new ProcessBuilder(command).start(); UpdateActivator.getShutdownService().beginShutdown(); } } } catch(FileNotFoundException fnfe) { ResourceManagementService resources = Resources.getResources(); UpdateActivator.getUIService() .getPopupDialog().showMessagePopupDialog( resources.getI18NString( "plugin.updatechecker.DIALOG_MISSING_UPDATE"), resources.getI18NString( "plugin.updatechecker.DIALOG_NOUPDATE_TITLE"), PopupDialog.INFORMATION_MESSAGE); } catch (Exception e) { if (logger.isInfoEnabled()) logger.info("Could not update", e); } finally { /* * If we've failed, delete the temporary file into which the setup * was supposed to be or has already been downloaded. */ if (deleteMsi && (msi != null)) { msi.delete(); msi = null; } if (deleteDelta && (delta != null)) { delta.delete(); delta = null; } } } /** * Invokes "Check for Updates". * * @param notifyAboutNewestVersion <tt>true</tt> if the user is to be * notified if they have the newest version already; otherwise, * <tt>false</tt> */ public synchronized void checkForUpdates( final boolean notifyAboutNewestVersion) { if (inCheckForUpdates > 0) { if (checkForUpdatesDialog != null) checkForUpdatesDialog.toFront(); return; } Thread checkForUpdatesThread = new Thread() { @Override public void run() { try { runInCheckForUpdatesThread(notifyAboutNewestVersion); } finally { exitCheckForUpdates(null); } } }; checkForUpdatesThread.setDaemon(true); checkForUpdatesThread.setName( getClass().getName() + ".checkForUpdates"); enterCheckForUpdates(null); try { checkForUpdatesThread.start(); checkForUpdatesThread = null; } finally { if (checkForUpdatesThread != null) exitCheckForUpdates(null); } } }
9232b372b97aa7c5f048ea40f7d04752a5d9445d
343
java
Java
app/src/main/java/me/stupideme/embeddedtool/view/custom/OnBindViewIdChangedListener.java
StupidL/EmbeddedTool
57a16b634649bb71995bdf58007cf43cb2b80948
[ "Apache-2.0" ]
1
2016-12-15T07:29:54.000Z
2016-12-15T07:29:54.000Z
app/src/main/java/me/stupideme/embeddedtool/view/custom/OnBindViewIdChangedListener.java
StupidL/EmbeddedTool
57a16b634649bb71995bdf58007cf43cb2b80948
[ "Apache-2.0" ]
null
null
null
app/src/main/java/me/stupideme/embeddedtool/view/custom/OnBindViewIdChangedListener.java
StupidL/EmbeddedTool
57a16b634649bb71995bdf58007cf43cb2b80948
[ "Apache-2.0" ]
null
null
null
22.866667
50
0.673469
996,314
package me.stupideme.embeddedtool.view.custom; /** * Created by stupidl on 16-10-12. */ public interface OnBindViewIdChangedListener { /** * listen if a view's bind view changed or not * @param other id of the view to bind * @param self id of the view itself */ void onBindViewIdChanged(int other, int self); }
9232b4a1d687d1084d33536a5f557e7fc2fa4d0e
283
java
Java
aliyun-sdk-managed-credentials-providers/aliyun-sdk-common-managed-credentials-provider/src/main/java/com/aliyun/kms/secretsmanager/plugin/common/auth/CloudCredentials.java
aliyun/aliyun-sdk-managed-credentials-providers
181670f16c926c4c8de01a884d6828fe7fad0328
[ "Apache-2.0" ]
2
2021-08-13T04:00:42.000Z
2021-08-13T14:00:53.000Z
aliyun-sdk-managed-credentials-providers/aliyun-sdk-common-managed-credentials-provider/src/main/java/com/aliyun/kms/secretsmanager/plugin/common/auth/CloudCredentials.java
aliyun/aliyun-sdk-managed-credentials-providers
181670f16c926c4c8de01a884d6828fe7fad0328
[ "Apache-2.0" ]
null
null
null
aliyun-sdk-managed-credentials-providers/aliyun-sdk-common-managed-credentials-provider/src/main/java/com/aliyun/kms/secretsmanager/plugin/common/auth/CloudCredentials.java
aliyun/aliyun-sdk-managed-credentials-providers
181670f16c926c4c8de01a884d6828fe7fad0328
[ "Apache-2.0" ]
null
null
null
16.647059
57
0.614841
996,315
package com.aliyun.kms.secretsmanager.plugin.common.auth; public interface CloudCredentials { /** * obtain access key id * @return */ String getAccessKeyId(); /** * obtain access key secret * @return */ String getAccessKeySecret(); }
9232b6229957f212cee302f970ed3ddbac0f5652
2,869
java
Java
sdks/java/extensions/sorter/src/test/java/org/apache/beam/sdk/extensions/sorter/ExternalSorterTest.java
reuvenlax/incubator-beam
5864a38ba595cdf90d2d5559e4312ef6144f60c7
[ "Apache-2.0" ]
null
null
null
sdks/java/extensions/sorter/src/test/java/org/apache/beam/sdk/extensions/sorter/ExternalSorterTest.java
reuvenlax/incubator-beam
5864a38ba595cdf90d2d5559e4312ef6144f60c7
[ "Apache-2.0" ]
3
2016-12-10T03:57:24.000Z
2017-03-30T05:44:50.000Z
sdks/java/extensions/sorter/src/test/java/org/apache/beam/sdk/extensions/sorter/ExternalSorterTest.java
reuvenlax/incubator-beam
5864a38ba595cdf90d2d5559e4312ef6144f60c7
[ "Apache-2.0" ]
null
null
null
32.602273
98
0.742768
996,316
/* * 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.beam.sdk.extensions.sorter; import static org.junit.Assert.fail; import org.apache.beam.sdk.extensions.sorter.SorterTestUtils.SorterGenerator; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /** Tests for Sorter. */ @RunWith(JUnit4.class) public class ExternalSorterTest { @Rule public ExpectedException thrown = ExpectedException.none(); @Test public void testEmpty() throws Exception { SorterTestUtils.testEmpty(ExternalSorter.create(new ExternalSorter.Options())); } @Test public void testSingleElement() throws Exception { SorterTestUtils.testSingleElement(ExternalSorter.create(new ExternalSorter.Options())); } @Test public void testEmptyKeyValueElement() throws Exception { SorterTestUtils.testEmptyKeyValueElement(ExternalSorter.create(new ExternalSorter.Options())); } @Test public void testMultipleIterations() throws Exception { SorterTestUtils.testMultipleIterations(ExternalSorter.create(new ExternalSorter.Options())); } @Test public void testRandom() throws Exception { SorterTestUtils.testRandom( new SorterGenerator() { @Override public Sorter generateSorter() throws Exception { return ExternalSorter.create(new ExternalSorter.Options()); } }, 1, 1000000); } @Test public void testAddAfterSort() throws Exception { SorterTestUtils.testAddAfterSort(ExternalSorter.create(new ExternalSorter.Options()), thrown); fail(); } @Test public void testSortTwice() throws Exception { SorterTestUtils.testSortTwice(ExternalSorter.create(new ExternalSorter.Options()), thrown); fail(); } @Test public void testNegativeMemory() throws Exception { thrown.expect(IllegalArgumentException.class); thrown.expectMessage("memoryMB must be greater than zero"); ExternalSorter.Options options = new ExternalSorter.Options(); options.setMemoryMB(-1); } }
9232b7d103968fd844b85938b5e84318e6ef1e9f
6,515
java
Java
exonum-java-binding-qa-service/src/test/java/com/exonum/binding/qaservice/transactions/IncrementCounterTxIntegrationTest.java
KateNegrienko/exonum-java-binding
7e078e1cd5fd3f21a2c0aece6bbd80eb9a1412fd
[ "Apache-2.0" ]
1
2018-12-14T14:07:36.000Z
2018-12-14T14:07:36.000Z
exonum-java-binding-qa-service/src/test/java/com/exonum/binding/qaservice/transactions/IncrementCounterTxIntegrationTest.java
KateNegrienko/exonum-java-binding
7e078e1cd5fd3f21a2c0aece6bbd80eb9a1412fd
[ "Apache-2.0" ]
null
null
null
exonum-java-binding-qa-service/src/test/java/com/exonum/binding/qaservice/transactions/IncrementCounterTxIntegrationTest.java
KateNegrienko/exonum-java-binding
7e078e1cd5fd3f21a2c0aece6bbd80eb9a1412fd
[ "Apache-2.0" ]
null
null
null
36.194444
101
0.738603
996,317
/* * Copyright 2018 The Exonum Team * * 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.exonum.binding.qaservice.transactions; import static com.exonum.binding.common.serialization.json.JsonSerializer.json; import static com.exonum.binding.qaservice.transactions.CreateCounterTxIntegrationTest.createCounter; import static com.exonum.binding.qaservice.transactions.IncrementCounterTx.serializeBody; import static com.exonum.binding.qaservice.transactions.QaTransaction.INCREMENT_COUNTER; import static java.nio.charset.StandardCharsets.UTF_8; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import com.exonum.binding.common.hash.HashCode; import com.exonum.binding.common.hash.Hashing; import com.exonum.binding.common.message.BinaryMessage; import com.exonum.binding.common.message.Message; import com.exonum.binding.proxy.Cleaner; import com.exonum.binding.proxy.CloseFailuresException; import com.exonum.binding.qaservice.QaSchema; import com.exonum.binding.qaservice.QaService; import com.exonum.binding.storage.database.Database; import com.exonum.binding.storage.database.Fork; import com.exonum.binding.storage.database.MemoryDb; import com.exonum.binding.storage.indices.MapIndex; import com.exonum.binding.storage.indices.ProofMapIndexProxy; import com.exonum.binding.test.RequiresNativeLibrary; import com.exonum.binding.util.LibraryLoader; import com.google.gson.reflect.TypeToken; import nl.jqno.equalsverifier.EqualsVerifier; import org.junit.jupiter.api.Test; class IncrementCounterTxIntegrationTest { static { LibraryLoader.load(); } static Message MESSAGE_TEMPLATE = new Message.Builder() .mergeFrom(Transactions.QA_TX_MESSAGE_TEMPLATE) .setMessageType(INCREMENT_COUNTER.id()) .setBody(serializeBody(new IncrementCounterTx(1, Hashing.sha256().hashInt(1)))) .buildPartial(); @Test void converterFromMessageRejectsWrongServiceId() { BinaryMessage message = messageBuilder() .setServiceId((short) (QaService.ID + 1)) .buildRaw(); assertThrows(IllegalArgumentException.class, () -> IncrementCounterTx.converter().fromMessage(message)); } @Test void converterFromMessageRejectsWrongTxId() { BinaryMessage message = messageBuilder() .setMessageType((short) (INCREMENT_COUNTER.id() + 1)) .buildRaw(); assertThrows(IllegalArgumentException.class, () -> IncrementCounterTx.converter().fromMessage(message)); } @Test void converterRoundtrip() { long seed = 0; HashCode counterId = Hashing.sha256().hashInt(0); IncrementCounterTx tx = new IncrementCounterTx(seed, counterId); BinaryMessage message = tx.getMessage(); IncrementCounterTx txFromMessage = IncrementCounterTx.converter().fromMessage(message); assertThat(txFromMessage, equalTo(tx)); } @Test void isValid() { long seed = 0; HashCode counterId = Hashing.sha256().hashInt(0); IncrementCounterTx tx = new IncrementCounterTx(seed, counterId); assertTrue(tx.isValid()); } @Test @RequiresNativeLibrary void executeIncrementsCounter() throws CloseFailuresException { try (Database db = MemoryDb.newInstance(); Cleaner cleaner = new Cleaner()) { Fork view = db.createFork(cleaner); // Add a new counter with the given name and initial value String name = "counter"; long initialValue = 0; createCounter(view, name, initialValue); // Create and execute the transaction long seed = 0L; HashCode nameHash = Hashing.defaultHashFunction().hashString(name, UTF_8); IncrementCounterTx tx = new IncrementCounterTx(seed, nameHash); tx.execute(view); // Check the counter has an incremented value QaSchema schema = new QaSchema(view); ProofMapIndexProxy<HashCode, Long> counters = schema.counters(); long expectedValue = initialValue + 1; assertThat(counters.get(nameHash), equalTo(expectedValue)); } } @Test @RequiresNativeLibrary void executeNoSuchCounter() throws CloseFailuresException { try (Database db = MemoryDb.newInstance(); Cleaner cleaner = new Cleaner()) { Fork view = db.createFork(cleaner); // Create and execute the transaction that attempts to update an unknown counter long seed = 0L; String name = "unknown-counter"; HashCode nameHash = Hashing.defaultHashFunction().hashString(name, UTF_8); IncrementCounterTx tx = new IncrementCounterTx(seed, nameHash); tx.execute(view); // Check there isn’t such a counter after tx execution QaSchema schema = new QaSchema(view); MapIndex<HashCode, Long> counters = schema.counters(); MapIndex<HashCode, String> counterNames = schema.counterNames(); assertFalse(counters.containsKey(nameHash)); assertFalse(counterNames.containsKey(nameHash)); } } @Test void info() { // Create a transaction with the given parameters. long seed = Long.MAX_VALUE - 1; String name = "new_counter"; HashCode nameHash = Hashing.defaultHashFunction() .hashString(name, UTF_8); IncrementCounterTx tx = new IncrementCounterTx(seed, nameHash); String info = tx.info(); // Check the transaction parameters in JSON AnyTransaction<IncrementCounterTx> txParameters = json().fromJson(info, new TypeToken<AnyTransaction<IncrementCounterTx>>(){}.getType()); assertThat(txParameters.body, equalTo(tx)); } @Test void equals() { EqualsVerifier.forClass(IncrementCounterTx.class) .withPrefabValues(HashCode.class, HashCode.fromInt(1), HashCode.fromInt(2)) .verify(); } private static Message.Builder messageBuilder() { return new Message.Builder() .mergeFrom(MESSAGE_TEMPLATE); } }
9232b89b3e804901dc1ee949b0d3b01434e60b92
576
java
Java
src/main/java/pradeep/abstractfactory/mixeddrinksabstract/RedSangaria.java
pradeepcse504/MixedDrinks
416323e86ebfd2998125e0c7f379d1d5fbf21a5b
[ "Apache-2.0" ]
null
null
null
src/main/java/pradeep/abstractfactory/mixeddrinksabstract/RedSangaria.java
pradeepcse504/MixedDrinks
416323e86ebfd2998125e0c7f379d1d5fbf21a5b
[ "Apache-2.0" ]
null
null
null
src/main/java/pradeep/abstractfactory/mixeddrinksabstract/RedSangaria.java
pradeepcse504/MixedDrinks
416323e86ebfd2998125e0c7f379d1d5fbf21a5b
[ "Apache-2.0" ]
null
null
null
28.8
70
0.697917
996,318
package pradeep.abstractfactory.mixeddrinksabstract; public class RedSangaria extends MixedDrink{ MixedDrinkIngredientFactory ingredientFactory; public RedSangaria(MixedDrinkIngredientFactory ingredientFactory){ this.ingredientFactory = ingredientFactory; } void prepare(){ System.out.println("Preparing " + name); sugar = ingredientFactory.createSugar(); juice = ingredientFactory.createJuice(); water = ingredientFactory.createWater(); cubes = ingredientFactory.createCubes(); } }
9232b8dbe065cce5991ffce718e751e2ca04e3c4
798
java
Java
tlbimp/src/main/java/com4j/tlbimp/def/VarType.java
protogenes/com4j
1e690b805fb0e4e9ef61560e20a56335aecb0b24
[ "BSD-2-Clause" ]
98
2015-01-08T15:10:42.000Z
2022-03-16T01:22:31.000Z
tlbimp/src/main/java/com4j/tlbimp/def/VarType.java
protogenes/com4j
1e690b805fb0e4e9ef61560e20a56335aecb0b24
[ "BSD-2-Clause" ]
38
2015-01-12T07:16:52.000Z
2020-11-17T21:36:00.000Z
tlbimp/src/main/java/com4j/tlbimp/def/VarType.java
protogenes/com4j
1e690b805fb0e4e9ef61560e20a56335aecb0b24
[ "BSD-2-Clause" ]
66
2015-01-11T22:32:44.000Z
2022-02-04T07:25:56.000Z
16.22449
45
0.572327
996,319
package com4j.tlbimp.def; import com4j.ComEnum; /** * @author Kohsuke Kawaguchi (anpch@example.com) */ public enum VarType implements ComEnum { VT_I2(2), VT_I4(3), VT_R4(4), VT_R8(5), VT_CY(6), VT_DATE(7), VT_BSTR(8), VT_DISPATCH(9), VT_ERROR(10), VT_BOOL(11), VT_VARIANT(12), VT_UNKNOWN(13), VT_DECIMAL(14), VT_I1(16), VT_UI1(17), VT_UI2(18), VT_UI4(19), VT_I8(20), VT_UI8(21), VT_INT(22), VT_UINT(23), VT_VOID(24), VT_HRESULT(25), VT_PTR(26), VT_SAFEARRAY(27), VT_CARRAY(28), VT_USERDEFINED(29), VT_LPSTR(30), VT_LPWSTR(31); private final int value; VarType(int value) { this.value=value; } public int comEnumValue() { return value; } }
9232b9304c22409ae3ffe5c5796d20968c5179d6
5,265
java
Java
src/main/java/com/gmail/willramanand/RamSkills/commands/SkillCommand.java
willramanand/RamSkills
7be26abb481cb19c2c688dffa4fb55ac60d1192a
[ "MIT" ]
null
null
null
src/main/java/com/gmail/willramanand/RamSkills/commands/SkillCommand.java
willramanand/RamSkills
7be26abb481cb19c2c688dffa4fb55ac60d1192a
[ "MIT" ]
null
null
null
src/main/java/com/gmail/willramanand/RamSkills/commands/SkillCommand.java
willramanand/RamSkills
7be26abb481cb19c2c688dffa4fb55ac60d1192a
[ "MIT" ]
null
null
null
32.90625
153
0.641406
996,320
package com.gmail.willramanand.RamSkills.commands; import com.gmail.willramanand.RamSkills.RamSkills; import com.gmail.willramanand.RamSkills.skills.Skill; import com.gmail.willramanand.RamSkills.skills.Skills; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.command.TabExecutor; import org.bukkit.entity.Player; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public abstract class SkillCommand implements TabExecutor { protected final RamSkills plugin; public List<String> aliases; private final String permission; public int requiredArgsSize; public int totalArgs; private final boolean enabled; private final boolean playerOnly; public String helpText; public List<SkillCommand> subCommands; public SkillCommand(RamSkills plugin, boolean enabled, boolean playerOnly, int requiredArgsSize, int totalArgs) { this.plugin = plugin; this.enabled = enabled; this.playerOnly = playerOnly; this.permission = null; this.requiredArgsSize = requiredArgsSize; this.totalArgs = totalArgs; this.aliases = new ArrayList<>(); this.subCommands = new ArrayList<>(); } public SkillCommand(RamSkills plugin, boolean enabled, boolean playerOnly, String permission, int requiredArgsSize, int totalArgs) { this.plugin = plugin; this.enabled = enabled; this.playerOnly = playerOnly; this.permission = permission; this.requiredArgsSize = requiredArgsSize; this.totalArgs = totalArgs; this.aliases = new ArrayList<>(); this.subCommands = new ArrayList<>(); } public abstract void perform(CommandContext context); public abstract List<String> tabCompletes(CommandSender sender, String[] args); public void execute(CommandContext context) { // Is there a matching sub command? if (context.args.size() > 0) { for (SkillCommand subCommand : this.subCommands) { if (subCommand.aliases.contains(context.args.get(0).toLowerCase())) { context.args.remove(0); context.commandChain.add(this); subCommand.execute(context); return; } } } if (!validCall(context)) { return; } if (!this.isEnabled()) { context.msg("{w}This command is not enabled!"); return; } perform(context); } public boolean validCall(CommandContext context) { if (requiredArgsSize != 0 && requiredArgsSize > context.args.size()) { context.msg("{w}Usage: " + context.command.getUsage().replace("<command>", context.command.getName())); return false; } if (totalArgs != -1 && totalArgs < context.args.size()) { context.msg("{w}Too many args! Usage: " + context.command.getUsage().replace("<command>", context.command.getName())); return false; } if (!(context.sender instanceof Player) && playerOnly) { context.msg("{w}Only a player can execute this command!"); return false; } // Check our perms if (permission != null && !(context.sender.hasPermission(permission))) { context.msg("{w}You do not have permission for this command!"); return false; } // Check spigot perms if (context.command.getPermission() != null && !(context.sender.hasPermission(context.command.getPermission()))) { context.msg("{w}You do not have permission for this command!"); return false; } return true; } public boolean isEnabled() { return enabled; } @Override public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command, @NotNull String label, @NotNull String[] args) { this.execute(new CommandContext(sender, command, new ArrayList<>(Arrays.asList(args)), label)); return true; } @Override public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { return tabCompletes(sender, args); } public List<String> tabCompletePlayers() { List<String> playerNames = new ArrayList<>(); for (Player player : Bukkit.getOnlinePlayers()) playerNames.add(player.getName()); return playerNames; } public List<String> tabCompleteWorlds() { List<String> worldNames = new ArrayList<>(); for (World world : Bukkit.getWorlds()) worldNames.add(world.getName()); return worldNames; } public List<String> tabCompleteSkills() { List<String> skillNames = new ArrayList<>(); for (Skill skill : Skills.values()) skillNames.add(skill.name().toLowerCase()); return skillNames; } public String getHelpText() { return helpText; } public String getPermission() { return permission; } }
9232baa692dd7aa45fdf7012036e7e2851be83b5
56
java
Java
algorithms/named/Quickselect.java
thundergolfer/uni
e604d1edd8e5085f0ae1c0211015db38c07fc926
[ "MIT" ]
1
2022-01-06T04:50:09.000Z
2022-01-06T04:50:09.000Z
algorithms/named/Quickselect.java
thundergolfer/uni
e604d1edd8e5085f0ae1c0211015db38c07fc926
[ "MIT" ]
1
2022-01-23T06:09:21.000Z
2022-01-23T06:14:17.000Z
algorithms/named/Quickselect.java
thundergolfer/uni
e604d1edd8e5085f0ae1c0211015db38c07fc926
[ "MIT" ]
null
null
null
11.2
26
0.785714
996,321
package algorithms.named; public class Quickselect { }
9232bb3967d2ad19bd99c360666c98ab60e6f433
2,547
java
Java
src/main/java/ai/digamma/rules/weekend/WeekEnd.java
digamma-ai/timeextractor
8a47b60413795af30c97d99ad144a9dc9eeac213
[ "Apache-2.0" ]
21
2018-01-02T19:06:46.000Z
2021-12-29T12:46:07.000Z
src/main/java/ai/digamma/rules/weekend/WeekEnd.java
digamma-ai/timeextractor
8a47b60413795af30c97d99ad144a9dc9eeac213
[ "Apache-2.0" ]
8
2017-10-12T16:49:36.000Z
2022-01-25T08:43:56.000Z
src/main/java/ai/digamma/rules/weekend/WeekEnd.java
digamma-ai/timeextractor
8a47b60413795af30c97d99ad144a9dc9eeac213
[ "Apache-2.0" ]
9
2017-10-24T21:49:20.000Z
2021-02-05T17:30:33.000Z
24.257143
106
0.629761
996,322
package ai.digamma.rules.weekend; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.UUID; import ai.digamma.entities.ExtractionRule; import ai.digamma.temporal.entities.Temporal; import ai.digamma.temporal.entities.TimeDate; import ai.digamma.temporal.entities.Type; import ai.digamma.utils.TemporalObjectGenerator; import ai.digamma.temporal.entities.Date; import ai.digamma.temporal.entities.DayOfWeek; public class WeekEnd extends ExtractionRule { private double confidence = 0.9; private String rule = "\\b(weekend|weekends|week-end|week-ends)\\b"; protected int priority = 1; protected String example = "weekend, week-end, etc."; protected UUID id = UUID.fromString("7bf02d24-c82b-47db-99b8-9344f9bbed20"); public WeekEnd() { } @Override public Type getType() { return Type.DAY_OF_WEEK_INTERVAL; } @Override public List<Temporal> getTemporal(String text) { TimeDate start = new TimeDate(); TimeDate end = new TimeDate(); Date startDate = new Date(); Date endDate = new Date(); startDate.setDayOfWeek(DayOfWeek.SA); endDate.setDayOfWeek(DayOfWeek.SU); start.setDate(startDate); end.setDate(endDate); Temporal temporal = TemporalObjectGenerator.generateTemporalTime(Type.DATE_INTERVAL, start, end); List<Temporal> temporalList = new ArrayList<Temporal>(); temporalList.add(temporal); return temporalList; } @Override public Locale getLocale() { return locale; } public void setLocale(Locale locale) { this.locale = locale; } @Override public double getConfidence() { return confidence; } public void setConfidence(double confidence) { this.confidence = confidence; } @Override public int compareTo(ExtractionRule o) { return super.compare(this, o); } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; } public String getExample() { return example; } public void setExample(String example) { this.example = example; } public UUID getId() { return id; } }
9232bb4d62d5437b64cea991a0c9a02e9523f20f
130
java
Java
biz.aQute.bndlib.tests/test/test/cdi/beans_b/AppScopedBean.java
johnoliver/bnd
82822deee69453df66bd68f67f9cbf431e33e76f
[ "Apache-2.0" ]
1
2022-03-23T14:00:11.000Z
2022-03-23T14:00:11.000Z
biz.aQute.bndlib.tests/test/test/cdi/beans_b/AppScopedBean.java
johnoliver/bnd
82822deee69453df66bd68f67f9cbf431e33e76f
[ "Apache-2.0" ]
1
2018-07-31T09:47:46.000Z
2020-10-10T18:55:13.000Z
biz.aQute.bndlib.tests/test/test/cdi/beans_b/AppScopedBean.java
ScienceCityJena/bnd
7ed389319e22a41fd1d07f77b68e995c3ba12104
[ "Apache-2.0" ]
1
2018-11-29T13:40:39.000Z
2018-11-29T13:40:39.000Z
14.444444
50
0.823077
996,323
package test.cdi.beans_b; import javax.enterprise.context.ApplicationScoped; @ApplicationScoped public class AppScopedBean { }
9232bc0882c3631706070d407a0fa5fed5e2ecc3
1,454
java
Java
src/main/java/org/ipso/lbc/common/db/DbUtilsExcel.java
reeselaye/org.ipso.lbc.common
a38b8231d413dd78a79f1664ccd067b57d53b9d8
[ "Apache-2.0" ]
1
2016-04-20T05:35:29.000Z
2016-04-20T05:35:29.000Z
src/main/java/org/ipso/lbc/common/db/DbUtilsExcel.java
reeselaye/org.ipso.lbc.common
a38b8231d413dd78a79f1664ccd067b57d53b9d8
[ "Apache-2.0" ]
2
2016-03-19T15:00:25.000Z
2016-06-28T08:07:19.000Z
src/main/java/org/ipso/lbc/common/db/DbUtilsExcel.java
reeselaye/org.ipso.lbc.common
a38b8231d413dd78a79f1664ccd067b57d53b9d8
[ "Apache-2.0" ]
2
2016-03-19T04:38:28.000Z
2016-04-21T05:58:31.000Z
29.673469
142
0.676066
996,324
/* * 版权所有 (c) 2015 。 李倍存 (iPso)。 * 所有者对该文件所包含的代码的正确性、执行效率等任何方面不作任何保证。 * 所有个人和组织均可不受约束地将该文件所包含的代码用于非商业用途。若需要将其用于商业软件的开发,请首先联系所有者以取得许可。 */ package org.ipso.lbc.common.db; import org.apache.commons.dbutils.DbUtils; import org.ipso.lbc.common.exception.DatabaseAccessException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; /** * Created by LBC on 2015/1/22. */ public class DbUtilsExcel implements IDbUtils { public DbUtilsExcel() { } public static final String DB_URL = "jdbc:Excel:/D:\\系统文档\\Documents\\IdeaProjects\\TestStruts2\\src\\main.java.db\\basic\\20141014.xlsx"; public static final String DRIVER = "com.hxtt.sql.excel.ExcelDriver"; public static final String USERNAME = "SCOTT"; public static final String PASSWORD = "123456"; public Connection getConnection(String url, String drv, String username, String password) { DbUtils.loadDriver(drv); try { return DriverManager.getConnection(url, username, password); } catch (SQLException e) { throw new DatabaseAccessException(e); } } public Connection getDefaultConnection() throws Exception { try { Class.forName(DRIVER); //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); } catch (Exception e) { System.out.println("Error"); } return getConnection(DB_URL, DRIVER, "", ""); } }
9232bc4dcad683f7c6e4a7108f02561615459467
2,967
java
Java
src/test/java/com/baidu/beidou/navi/pbrpc/client/BlockingIOPooledPbrpcClientMainTest.java
nihaojava/navi-pbrpc
e7452d89773f28f1832ce07a449bb06814a25fd6
[ "Apache-2.0" ]
181
2015-07-05T03:43:08.000Z
2022-02-24T14:18:02.000Z
src/test/java/com/baidu/beidou/navi/pbrpc/client/BlockingIOPooledPbrpcClientMainTest.java
nihaojava/navi-pbrpc
e7452d89773f28f1832ce07a449bb06814a25fd6
[ "Apache-2.0" ]
1
2019-08-10T04:23:03.000Z
2019-08-10T04:37:36.000Z
src/test/java/com/baidu/beidou/navi/pbrpc/client/BlockingIOPooledPbrpcClientMainTest.java
nihaojava/navi-pbrpc
e7452d89773f28f1832ce07a449bb06814a25fd6
[ "Apache-2.0" ]
72
2015-07-10T08:22:47.000Z
2021-07-28T11:28:00.000Z
32.966667
104
0.657904
996,325
package com.baidu.beidou.navi.pbrpc.client; import java.util.Random; import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.baidu.beidou.navi.pbrpc.demo.proto.Demo; import com.baidu.beidou.navi.pbrpc.demo.proto.Demo.DemoRequest; import com.baidu.beidou.navi.pbrpc.demo.proto.Demo.DemoResponse; import com.baidu.beidou.navi.pbrpc.transport.PbrpcMsg; public class BlockingIOPooledPbrpcClientMainTest { private static final Logger LOG = LoggerFactory.getLogger(PooledPbrpcClientMainTest.class); public static void main(String[] args) throws Exception { BlockingIOPooledPbrpcClientMainTest test = new BlockingIOPooledPbrpcClientMainTest(); test.testPool(); // test.testPoolBatch(); } public void testPool() throws Exception { PbrpcClient client = PbrpcClientFactory.buildPooledConnection(new PooledConfiguration(), "127.0.0.1", 8088, 4000); PbrpcMsg msg; msg = new PbrpcMsg(); msg.setServiceId(100); msg.setProvider("beidou"); msg.setData(getData(1)); DemoResponse res = client.asyncTransport(DemoResponse.class, msg).get(); System.out.println(res); int multiSize = 12; int totalRequestSize = 100000; ExecutorService pool = Executors.newFixedThreadPool(multiSize); CompletionService<DemoResponse> completionService = new ExecutorCompletionService<DemoResponse>( pool); Invoker invoker = new Invoker(client); long time = System.currentTimeMillis(); for (int i = 0; i < totalRequestSize; i++) { completionService.submit(invoker); } for (int i = 0; i < totalRequestSize; i++) { completionService.take().get(); } long timetook = System.currentTimeMillis() - time; LOG.info("Total using " + timetook + "ms"); LOG.info("QPS:" + 1000f / ((timetook) / (1.0f * totalRequestSize))); } private static byte[] getData(int userId) { DemoRequest.Builder req = DemoRequest.newBuilder(); req.setUserId(userId); byte[] data = req.build().toByteArray(); return data; } private class Invoker implements Callable<DemoResponse> { private PbrpcClient client; public Invoker(PbrpcClient client) { this.client = client; } @Override public DemoResponse call() throws Exception { PbrpcMsg msg; msg = new PbrpcMsg(); msg.setServiceId(100); msg.setProvider("beidou"); msg.setData(getData(1)); DemoResponse res = client.asyncTransport(DemoResponse.class, msg).get(); return res; } } }
9232bd03883589d967f85992ad3cf3e5845fab1c
3,646
java
Java
common/src/main/java/xyz/jpenilla/minimotd/common/util/UpdateChecker.java
bloctown/MiniMOTD
3bf3796ce2262d8556c481190ceb33b465adbced
[ "MIT" ]
118
2021-01-22T13:11:30.000Z
2022-03-23T16:53:02.000Z
common/src/main/java/xyz/jpenilla/minimotd/common/util/UpdateChecker.java
bloctown/MiniMOTD
3bf3796ce2262d8556c481190ceb33b465adbced
[ "MIT" ]
43
2021-01-21T09:32:59.000Z
2022-03-16T16:55:33.000Z
common/src/main/java/xyz/jpenilla/minimotd/common/util/UpdateChecker.java
bloctown/MiniMOTD
3bf3796ce2262d8556c481190ceb33b465adbced
[ "MIT" ]
12
2021-02-18T02:02:37.000Z
2022-01-02T17:40:37.000Z
48.613333
160
0.736972
996,326
/* * This file is part of MiniMOTD, licensed under the MIT License. * * Copyright (c) 2021 Jason Penilla * * 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 xyz.jpenilla.minimotd.common.util; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.gson.JsonArray; import com.google.gson.JsonParser; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.checkerframework.checker.nullness.qual.NonNull; import xyz.jpenilla.minimotd.common.Constants; public final class UpdateChecker { private final JsonParser parser = new JsonParser(); public @NonNull List<String> checkVersion() { final JsonArray result; final String url = String.format("https://api.github.com/repos/%s/%s/releases", Constants.PluginMetadata.GITHUB_USER, Constants.PluginMetadata.GITHUB_REPO); try (final InputStream is = new URL(url).openStream(); InputStreamReader reader = new InputStreamReader(is, Charsets.UTF_8)) { result = this.parser.parse(reader).getAsJsonArray(); } catch (final IOException ex) { return Collections.singletonList("Cannot look for updates: " + ex.getMessage()); } final Map<String, String> versionMap = new LinkedHashMap<>(); result.forEach(element -> versionMap.put(element.getAsJsonObject().get("tag_name").getAsString(), element.getAsJsonObject().get("html_url").getAsString())); final List<String> versionList = new LinkedList<>(versionMap.keySet()); final String currentVersion = "v" + Constants.PluginMetadata.VERSION; if (versionList.get(0).equals(currentVersion)) { return Collections.emptyList(); // Up to date, do nothing } if (currentVersion.contains("SNAPSHOT")) { return ImmutableList.of( "This server is running a development build of " + Constants.PluginMetadata.NAME + "! (" + currentVersion + ")", "The latest official release is " + versionList.get(0) ); } final int versionsBehind = versionList.indexOf(currentVersion); return ImmutableList.of( "There is an update available for " + Constants.PluginMetadata.NAME + "!", "This server is running version " + currentVersion + ", which is " + (versionsBehind == -1 ? "UNKNOWN" : versionsBehind) + " versions outdated.", "Download the latest version, " + versionList.get(0) + " from GitHub at the link below:", versionMap.get(versionList.get(0)) ); } }
9232bd3a7efbc415f11ff8b3a12a281c6075290e
288
java
Java
src/main/java/com/github/drbookings/DateEntry.java
DrBookings/drbookings-core
16eaa31dcf02980f555ab8b49f9ff4e70d16af81
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/drbookings/DateEntry.java
DrBookings/drbookings-core
16eaa31dcf02980f555ab8b49f9ff4e70d16af81
[ "Apache-2.0" ]
null
null
null
src/main/java/com/github/drbookings/DateEntry.java
DrBookings/drbookings-core
16eaa31dcf02980f555ab8b49f9ff4e70d16af81
[ "Apache-2.0" ]
null
null
null
18
64
0.697917
996,327
package com.github.drbookings; import java.time.LocalDate; public interface DateEntry<E> extends Comparable<DateEntry<E>> { @Override default int compareTo(final DateEntry<E> o) { return getDate().compareTo(o.getDate()); } LocalDate getDate(); E getElement(); }
9232bd81859f2458607870568a4edd60182dc875
1,752
java
Java
spring-boot-actuator-simple/src/test/java/com/github/diegopacheco/springcloud/actuator/test/DateTimeAppTest.java
diegopacheco/spring-cloud-playground
511f3b1f443f7d714141ba453a1ef17769c4d4c0
[ "Unlicense" ]
null
null
null
spring-boot-actuator-simple/src/test/java/com/github/diegopacheco/springcloud/actuator/test/DateTimeAppTest.java
diegopacheco/spring-cloud-playground
511f3b1f443f7d714141ba453a1ef17769c4d4c0
[ "Unlicense" ]
null
null
null
spring-boot-actuator-simple/src/test/java/com/github/diegopacheco/springcloud/actuator/test/DateTimeAppTest.java
diegopacheco/spring-cloud-playground
511f3b1f443f7d714141ba453a1ef17769c4d4c0
[ "Unlicense" ]
null
null
null
35.04
126
0.811644
996,328
package com.github.diegopacheco.springcloud.actuator.test; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.LocalServerPort; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringRunner; import static org.assertj.core.api.BDDAssertions.then; import com.github.diegopacheco.springcloud.actuator.DateTimeApp; @RunWith(SpringRunner.class) @SpringBootTest(classes = DateTimeApp.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestPropertySource(properties = { "management.port=0" }) public class DateTimeAppTest { @LocalServerPort private int port; @Value("${local.management.port}") private int mgt; @Autowired private TestRestTemplate testRestTemplate; @Test public void shouldReturn200WhenSendingRequestToController() throws Exception { ResponseEntity<String> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.port + "/date", String.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void shouldReturn200WhenSendingRequestToManagementEndpoint() throws Exception { @SuppressWarnings("rawtypes") ResponseEntity<Map> entity = this.testRestTemplate.getForEntity("http://localhost:" + this.mgt + "/info", Map.class); then(entity.getStatusCode()).isEqualTo(HttpStatus.OK); } }
9232bda9847f3a17dcbe875c5f10230886497feb
5,275
java
Java
src/jokrey/utilities/encoder/type_transformer/TransformerTest.java
jokrey/utility-algorithms-java
efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f
[ "MIT" ]
null
null
null
src/jokrey/utilities/encoder/type_transformer/TransformerTest.java
jokrey/utility-algorithms-java
efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f
[ "MIT" ]
null
null
null
src/jokrey/utilities/encoder/type_transformer/TransformerTest.java
jokrey/utility-algorithms-java
efc66376bac33ff3ac1ee25c5d3afeeda42d7e0f
[ "MIT" ]
null
null
null
59.943182
138
0.689479
996,329
package jokrey.utilities.encoder.type_transformer; import jokrey.utilities.encoder.tag_based.implementation.paired.length_indicator.type.transformer.LITypeToBytesTransformer; import jokrey.utilities.encoder.tag_based.implementation.paired.length_indicator.type.transformer.LITypeToStringTransformer; import org.junit.Test; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Tests for both string and byte[] transformers * @author jokrey */ public class TransformerTest { @Test public void test_bytes_transformer() { test_transformer(new LITypeToBytesTransformer()); } @Test public void test_string_transformer() { test_transformer(new LITypeToStringTransformer()); } private <SF> void test_transformer(TypeToFromRawTransformer<SF> transformer) { boolean[] o1 = new boolean[] {true, false, false, true, false, true, true, true, true}; assertArrayEquals(o1, transformer.detransform(transformer.transform(o1), o1.getClass())); byte[] o2 = new byte[] {1,2,3,4,5,6,7}; assertArrayEquals(o2, transformer.detransform(transformer.transform(o2), o2.getClass())); short[] o3 = new short[] {1,2,3,4,5,6,7}; assertArrayEquals(o3, transformer.detransform(transformer.transform(o3), o3.getClass())); int[] o4 = new int[] {1,2,3,4,5,6,7}; assertArrayEquals(o4, transformer.detransform(transformer.transform(o4), o4.getClass())); long[] o5 = new long[] {1,2,3,4,5,6,7}; assertArrayEquals(o5, transformer.detransform(transformer.transform(o5), o5.getClass())); float[] o6 = new float[] {1,2,3,4,5,6,7}; assertArrayEquals(o6, transformer.detransform(transformer.transform(o6), o6.getClass()), 0f); double[] o7 = new double[] {1,2,3,4,5,6,7}; assertArrayEquals(o7, transformer.detransform(transformer.transform(o7), o7.getClass()), 0d); char[] o8 = new char[] {'a', 'x', '?', 'ä', 'í', '1'}; assertArrayEquals(o8, transformer.detransform(transformer.transform(o8), o8.getClass())); boolean p1 = true; assertEquals(p1, transformer.detransform(transformer.transform(p1), boolean.class)); assertEquals(p1, transformer.detransform(transformer.transform(p1), Boolean.class)); byte p2 = 13; assertEquals(new Byte(p2), transformer.detransform(transformer.transform(p2), byte.class)); assertEquals(new Byte(p2), transformer.detransform(transformer.transform(p2), Byte.class)); short p3 = 13000; assertEquals(new Short(p3), transformer.detransform(transformer.transform(p3), short.class)); assertEquals(new Short(p3), transformer.detransform(transformer.transform(p3), Short.class)); int p4 = 356234513; assertEquals(new Integer(p4), transformer.detransform(transformer.transform(p4), int.class)); assertEquals(new Integer(p4), transformer.detransform(transformer.transform(p4), Integer.class)); long p5 = 9924382344534513L; assertEquals(new Long(p5), transformer.detransform(transformer.transform(p5), long.class)); assertEquals(new Long(p5), transformer.detransform(transformer.transform(p5), Long.class)); float p6 = 133242534675657.123123123f; assertEquals(new Float(p6), transformer.detransform(transformer.transform(p6), float.class)); assertEquals(new Float(p6), transformer.detransform(transformer.transform(p6), Float.class)); double p7 = 9865756756756756756753713.213123523234d; assertEquals(new Double(p7), transformer.detransform(transformer.transform(p7), double.class)); assertEquals(new Double(p7), transformer.detransform(transformer.transform(p7), Double.class)); char p8 = 'ó'; assertEquals(new Character(p8), transformer.detransform(transformer.transform(p8), char.class)); assertEquals(new Character(p8), transformer.detransform(transformer.transform(p8), Character.class)); String p9 = "asfd lakzrn34vz3vzg874zvgae4b 7bzg8osez g74zgeagh847hse i hgseuhv784hv"; assertEquals(p9, transformer.detransform(transformer.transform(p9), p9.getClass())); //recursively supported arrays String[] a1 = {p9, "213123", "ä+sdäf+sdäf#+däsf+äsdvf", "test", ""}; assertArrayEquals(a1, transformer.detransform(transformer.transform(a1), a1.getClass())); String[][] a2 = {{p9, "213123", "ä+sdäf+sdäf#+däsf+äsdvf", "test"}, {p9, p9, p9, p9, "1"}, {"9","1","4","1","1","6"}}; assertArrayEquals(a2, transformer.detransform(transformer.transform(a2), a2.getClass())); String[][][] a3 = {{}, a2, {{p9, "213123", "ä+sdäf+sdäf#+däsf+äsdvf", "test"}, {p9, p9, p9, p9, "1"}, {"9","1","4","1","1","6"}}}; assertArrayEquals(a3, transformer.detransform(transformer.transform(a3), a3.getClass())); int[][] a4 = {{}, o4, {1,2,3,4,5,6,7,8,9,0,2323234}, o4, o4, {1,9865333}, o4}; assertArrayEquals(a4, transformer.detransform(transformer.transform(a4), a4.getClass())); assertTrue(transformer.canTransform(byte.class)); assertTrue(transformer.canTransform(byte[].class)); assertTrue(transformer.canTransform(String[][].class)); } }
9232bf92f23a26af5e6d6d99a95c16544ce22759
834
java
Java
src/com/twu/biblioteca/repositories/SampleBookLibraryRepository.java
dalzymendoza/twu-biblioteca-dalzy
643927cced357dfbf388b109d1f79ba0d6939c2e
[ "Apache-2.0" ]
null
null
null
src/com/twu/biblioteca/repositories/SampleBookLibraryRepository.java
dalzymendoza/twu-biblioteca-dalzy
643927cced357dfbf388b109d1f79ba0d6939c2e
[ "Apache-2.0" ]
5
2019-04-08T10:02:35.000Z
2019-04-15T02:09:07.000Z
src/com/twu/biblioteca/repositories/SampleBookLibraryRepository.java
dalzymendoza/twu-biblioteca-dalzy
643927cced357dfbf388b109d1f79ba0d6939c2e
[ "Apache-2.0" ]
null
null
null
33.36
103
0.703837
996,330
package com.twu.biblioteca.repositories; import com.twu.biblioteca.representations.Book; import com.twu.biblioteca.representations.LibraryItem; import java.time.Year; import java.util.*; public class SampleBookLibraryRepository extends LibraryRepository { public SampleBookLibraryRepository() { super.setLibraryItemMap(generateSampleMapOf3Books()); } private Map<Integer, LibraryItem> generateSampleMapOf3Books() { Map <Integer, LibraryItem> books = new HashMap<>(); books.put(1, new Book(1, "A Brief History of Time", "Stephen Hawking", Year.of(1988))); books.put(2, new Book(2, "The Lion, the Witch and the Wardrobe", "C.S. Lewis", Year.of(1950))); books.put(3, new Book(3, "Your Dream Life Starts Here", "Kristina Karlsson", Year.of(2018))); return books; } }
9232c035ac024ad76ac5757ab4a9eb3111dc6fc2
1,075
java
Java
TestSoftuni/src/Task2.java
marmotka/Java-Exercises-Basics
077ca84d5adb51f184fe35a46be8734e37afd03e
[ "MIT" ]
null
null
null
TestSoftuni/src/Task2.java
marmotka/Java-Exercises-Basics
077ca84d5adb51f184fe35a46be8734e37afd03e
[ "MIT" ]
null
null
null
TestSoftuni/src/Task2.java
marmotka/Java-Exercises-Basics
077ca84d5adb51f184fe35a46be8734e37afd03e
[ "MIT" ]
null
null
null
21.078431
57
0.55907
996,331
import java.util.Scanner; import java.util.ArrayList; public class Task2 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); String txt = sc.nextLine(); String[] numss = txt.split(" "); ArrayList<Integer> num = new ArrayList<Integer>(); int i = 0; int sum = 0; while (i < numss.length) { int myInt = Integer.parseInt(numss[i]); num.add(myInt); i++; } int idx = -1; do { idx = Integer.parseInt(sc.nextLine()); int numb = -1; if (idx < 0) { numb = num.get(0); num.set(0, Integer.valueOf(num.get(num.size() - 1))); } else if (idx >= num.size()) { numb = num.get(num.size() - 1); num.set(num.size() - 1, Integer.valueOf(num.get(0))); } else { numb = num.get(idx); num.remove(idx); } sum += numb; for (i = 0; i < num.size(); i++) { if (num.get(i) <= numb) { num.set(i, Integer.valueOf(num.get(i) + numb)); } else { num.set(i, Integer.valueOf(num.get(i) - numb)); } } } while (!num.isEmpty()); System.out.println(sum); sc.close(); } }
9232c08fbf31d4c3423dd07dba1921cbd60ca923
382
java
Java
spring-boot-crudrepository/src/main/java/com/iamcarrot/samples/springbootcrudrepository/models/UserCountResponseDto.java
ImCarrot/SpringBootSamples
3afa8e72813847eed5b5db76dc8217a73ac99b3e
[ "MIT" ]
1
2021-11-16T04:39:08.000Z
2021-11-16T04:39:08.000Z
spring-boot-crudrepository/src/main/java/com/iamcarrot/samples/springbootcrudrepository/models/UserCountResponseDto.java
ImCarrot/SpringBootSamples
3afa8e72813847eed5b5db76dc8217a73ac99b3e
[ "MIT" ]
null
null
null
spring-boot-crudrepository/src/main/java/com/iamcarrot/samples/springbootcrudrepository/models/UserCountResponseDto.java
ImCarrot/SpringBootSamples
3afa8e72813847eed5b5db76dc8217a73ac99b3e
[ "MIT" ]
1
2020-07-01T11:21:24.000Z
2020-07-01T11:21:24.000Z
21.222222
62
0.727749
996,332
package com.iamcarrot.samples.springbootcrudrepository.models; import com.fasterxml.jackson.annotation.JsonProperty; public class UserCountResponseDto { @JsonProperty("NoOfUsers") private final long userCount; public UserCountResponseDto(long userCount) { this.userCount = userCount; } public long getUserCount() { return userCount; } }
9232c13c516ecba0ae0f16da83732e99646361d5
1,718
java
Java
javamesh-samples/javamesh-route/route-server/src/main/java/com/huawei/route/server/rules/notifier/PathDataUpdater.java
scyiwei/JavaMesh
ab72caceb00022021110ad58a902f5ce9cea98b4
[ "Apache-2.0" ]
null
null
null
javamesh-samples/javamesh-route/route-server/src/main/java/com/huawei/route/server/rules/notifier/PathDataUpdater.java
scyiwei/JavaMesh
ab72caceb00022021110ad58a902f5ce9cea98b4
[ "Apache-2.0" ]
null
null
null
javamesh-samples/javamesh-route/route-server/src/main/java/com/huawei/route/server/rules/notifier/PathDataUpdater.java
scyiwei/JavaMesh
ab72caceb00022021110ad58a902f5ce9cea98b4
[ "Apache-2.0" ]
null
null
null
30.678571
99
0.663562
996,333
/* * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved. */ package com.huawei.route.server.rules.notifier; import com.huawei.route.server.conditions.ZookeeperConfigCenterCondition; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.data.Stat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Conditional; import org.springframework.stereotype.Component; import java.nio.charset.StandardCharsets; /** * 路径数据更新器 * * @author zhouss * @since 2021-10-28 */ @Component @Conditional(ZookeeperConfigCenterCondition.class) public class PathDataUpdater { private static final Logger LOGGER = LoggerFactory.getLogger(PathDataUpdater.class); @Autowired private CuratorFramework zkClient; /** * 更新ZK路径的数据 * * @param path zk路劲 * @param data 数据 */ public void updatePathData(String path, byte[] data) { try { final Stat stat = zkClient.checkExists().forPath(path); if (data == null) { data = String.valueOf(System.currentTimeMillis()).getBytes(StandardCharsets.UTF_8); } if (stat == null) { // 节点为空 zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.PERSISTENT) .forPath(path, data); } else { zkClient.setData().forPath(path, data); } } catch (Exception e) { LOGGER.warn("update path data failed for notification, reason: {}", e.getMessage()); } } }
9232c1a996d2489e68023a22d4fbfa5225a61890
5,969
java
Java
week_7/src/main/java/Energies.java
ericghara/princeton-algs4-pt1
44df903ea2642677a190f29fdde43311a9696ed8
[ "MIT" ]
null
null
null
week_7/src/main/java/Energies.java
ericghara/princeton-algs4-pt1
44df903ea2642677a190f29fdde43311a9696ed8
[ "MIT" ]
null
null
null
week_7/src/main/java/Energies.java
ericghara/princeton-algs4-pt1
44df903ea2642677a190f29fdde43311a9696ed8
[ "MIT" ]
null
null
null
33.914773
111
0.512649
996,334
import edu.princeton.cs.algs4.Picture; import java.util.Arrays; public class Energies { private final VertexWeightedSP.MatrixInterface eInterface; private int[][] pixMap; private int W, H; private double[][] energies; private enum Direction {V,H}; public Energies(Picture pic) { W = pic.width(); H = pic.height(); pixMap = createPixMap(pic); createEnergies(); eInterface = new Normal(); } public void removeHorizontalSeam(int[] seam) { // seam is y vals // (mostly) in place eager delete, extra space = H H--; for (int x = 0; x < W; x++) { int y = seam[x]; // pixMap int[] auxP = new int[H]; System.arraycopy(pixMap[x], 0, auxP, 0, y); System.arraycopy(pixMap[x], y+1, auxP, y, H-y); pixMap[x] = auxP; // energies double[] auxE = new double[H]; System.arraycopy(energies[x], 0, auxE, 0, y); System.arraycopy(energies[x], y+1, auxE, y, H-y); energies[x] = auxE; } calcEnergy(seam, Direction.H); } public void removeVerticalSeam(int[] seam) { // seam is x vals // (mostly) in place eager delete, extra space = W for (int y = 0; y < H; y++) { int x = seam[y]; pixMap[x][y] = 0; // mark for deletion (valid pixels are negative ints) } /* Fills in holes of pixels marked for deletion by moving pixels directly to the right into holes. * After a move, pixel to the right now becomes a hole. Process repeats until entire rightmost column * is holes (and can be deleted) */ for (int x = 0; x < W-1; x++) { for (int y = 0; y < H; y++) { if (pixMap[x][y] == 0) { pixMap[x][y] = pixMap[x+1][y]; // move pixel left energies[x][y] = energies[x+1][y]; // move weight left pixMap[x+1][y] = 0; // mark hole to be filled } } } pixMap = Arrays.copyOfRange(pixMap,0, --W); // decreases width of matrix by 1 energies = Arrays.copyOfRange(energies,0, W); calcEnergy(seam, Direction.V); } // Note overloaded, this should be used when recalculating energies around a removed seam private void calcEnergy(int[] seam, Direction dir ) { if (dir == Direction.V) { for (int y = 0; y < H; y++) { int x = seam[y]; if ( validX(x) ) { calcEnergy(x,y); } if ( validX(--x) ) { calcEnergy(x,y); } } } else { for (int x = 0; x < W; x++) { int y = seam[x]; if ( validY(y) ) { calcEnergy(x, y); } if ( validY(--y) ) { calcEnergy(x, y); } } } } // energy of pixel at column x and row y // output range: 0 - 441.7, with 1000 being reserved for boarder pixels private void calcEnergy(int x, int y) { // Cannot use this energy function for boarder pixels so arbitrarily set to 1000, // precluding any path from going through the boarder if (x == 0 || x == W-1 || y == 0 || y == H-1) { energies[x][y] = 1000d; return; } // sqrt( Δ(East,West) + Δ(North,South) ) double deltaSqSums = deltaSqSum(x-1,y,x+1,y); deltaSqSums += deltaSqSum(x,y-1,x,y+1); energies[x][y] = Math.sqrt(deltaSqSums); } // for pixels p1 and p2 returns (r1-r2)^2 + (g1-g2)^2 + (b1-b2)^2 private double deltaSqSum(int x1, int y1, int x2, int y2) { int p1 = pixMap[x1][y1]; int p2 = pixMap[x2][y2]; int sum = 0; for (int i = 0; i < 3; i++) { int delta = (p1 & 0xFF) - (p2 & 0xFF); sum += delta*delta; p1 >>= 8; p2 >>= 8; } // avoids multiple conversions, working with ints until the very end return (double) sum; } private void createEnergies() { energies = new double[W][H]; for (int x = 0; x < W; x++ ) { for (int y = 0; y < H; y++) { calcEnergy(x,y); } } } private int [][] createPixMap(Picture pic) { int[][] map = new int[W][H]; for (int x = 0; x < W; x++ ) { for (int y = 0; y < H; y++) { map[x][y] = pic.getRGB(x,y); } } return map; } public Picture redraw() { Picture pic = new Picture(W,H); for (int x = 0; x < W; x++) { for (int y = 0; y < H; y++) { pic.setRGB( x,y, pixMap[x][y] ); } } return pic; } private boolean validX(int x) { return 0 <= x && x < W; } private boolean validY(int y) { return 0 <= y && y < H; } public int[] getVerticalSP() { VertexWeightedSP SP = new VertexWeightedSP( new Transposed() ); return SP.shortestPath(); } public int[] getHorizontalSP() { VertexWeightedSP SP = new VertexWeightedSP( eInterface ); return SP.shortestPath(); } public VertexWeightedSP.MatrixInterface getEnergyInterface() { return eInterface; } // use for horizontal shortest paths public class Normal implements VertexWeightedSP.MatrixInterface { public double get(int x, int y) { return energies[x][y]; } public int height() { return H; } public int width() { return W; } } // use for vertical shortest paths; provides client access to energies // as a transposed matrix public class Transposed implements VertexWeightedSP.MatrixInterface { public double get(int x, int y) { return energies[y][x]; } // notice transposed public int height() { return W; } // ...transposed public int width() { return H; } // ...and transposed } }
9232c2bf1403626a1f2e0e194c5e34ec0ec75eac
124
java
Java
src/main/java/ro/training/java/c06/_04_lambda/SomeStringFunction.java
lzrmihnea/training-java
a3d0eacbadfaac0973e67164a13729041593614d
[ "MIT" ]
null
null
null
src/main/java/ro/training/java/c06/_04_lambda/SomeStringFunction.java
lzrmihnea/training-java
a3d0eacbadfaac0973e67164a13729041593614d
[ "MIT" ]
null
null
null
src/main/java/ro/training/java/c06/_04_lambda/SomeStringFunction.java
lzrmihnea/training-java
a3d0eacbadfaac0973e67164a13729041593614d
[ "MIT" ]
2
2021-02-14T14:56:48.000Z
2021-05-07T21:56:49.000Z
20.666667
41
0.798387
996,335
package ro.training.java.c06._04_lambda; public interface SomeStringFunction { String operateOnString(String input); }
9232c37ffa290835c9ccf34fefdc4df725cd4137
6,168
java
Java
isaac-drools/src/main/java/gov/va/isaac/drools/evaluators/IsParentMemberOfEvaluatorDefinition.java
Apelon-VA/ISAAC
070f241bb0cfbdae449806a876ea08ef3c100bf1
[ "Apache-2.0" ]
2
2015-02-01T20:32:47.000Z
2016-03-31T18:34:02.000Z
isaac-drools/src/main/java/gov/va/isaac/drools/evaluators/IsParentMemberOfEvaluatorDefinition.java
Apelon-VA/ISAAC
070f241bb0cfbdae449806a876ea08ef3c100bf1
[ "Apache-2.0" ]
null
null
null
isaac-drools/src/main/java/gov/va/isaac/drools/evaluators/IsParentMemberOfEvaluatorDefinition.java
Apelon-VA/ISAAC
070f241bb0cfbdae449806a876ea08ef3c100bf1
[ "Apache-2.0" ]
null
null
null
31.469388
146
0.731518
996,336
/** * Copyright (c) 2009 International Health Terminology Standards Development * Organisation * * 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 gov.va.isaac.drools.evaluators; import gov.va.isaac.AppContext; import gov.va.isaac.drools.evaluators.facts.ConceptFact; import java.io.IOException; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; import org.drools.core.base.BaseEvaluator; import org.drools.core.base.ValueType; import org.drools.core.base.evaluators.Operator; import org.ihtsdo.otf.tcc.api.concept.ConceptVersionBI; import org.ihtsdo.otf.tcc.api.contradiction.ContradictionException; import org.ihtsdo.otf.tcc.api.coordinate.ViewCoordinate; import org.ihtsdo.otf.tcc.api.spec.ConceptSpec; import org.ihtsdo.otf.tcc.api.spec.ValidationException; import org.ihtsdo.otf.tcc.api.store.TerminologyStoreDI; import org.kie.api.runtime.rule.EvaluatorDefinition; public class IsParentMemberOfEvaluatorDefinition extends IsaacBaseEvaluatorDefinition implements EvaluatorDefinition { public static Operator IS_PARENT_MEMBER_OF = Operator.addOperatorToRegistry("isParentMemberOf", false); public static Operator NOT_IS_PARENT_MEMBER_OF = Operator.addOperatorToRegistry(IS_PARENT_MEMBER_OF.getOperatorString(), true); public static class IsParentMemberOfEvaluator extends IsaacBaseEvaluator { public IsParentMemberOfEvaluator() { super(); // No arg constructor for serialization. } public IsParentMemberOfEvaluator(final ValueType type, final boolean isNegated) { super(type, isNegated ? IsParentMemberOfEvaluatorDefinition.NOT_IS_PARENT_MEMBER_OF : IsParentMemberOfEvaluatorDefinition.IS_PARENT_MEMBER_OF); } @Override protected boolean test(final Object value1, final Object value2) { try { //value1 (concept): this could be concept VersionBI or conceptFact //value2 (refset): this will be put in Refset.java (tk-arena-rules) as a ConceptSpec ConceptSpec refexConcept = (ConceptSpec) value2; try { if (!AppContext.getService(TerminologyStoreDI.class).hasUuid(refexConcept.getLenient().getPrimordialUuid())) { return false; } } catch (ValidationException ex) { //do nothing } catch (IOException ex) { //do nothing } ConceptVersionBI possibleMember = null; if (ConceptVersionBI.class.isAssignableFrom(value1.getClass())) { possibleMember = (ConceptVersionBI) value1; } else if (ConceptFact.class.isAssignableFrom(value1.getClass())) { possibleMember = ((ConceptFact) value1).getConcept(); } else { throw new UnsupportedOperationException("Can't convert: " + value1); } ViewCoordinate vc = possibleMember.getViewCoordinate(); ConceptVersionBI possibleRefsetCV = null; ConceptSpec possibleRefset = null; Collection<? extends ConceptVersionBI> parents = possibleMember.getRelationshipsOutgoingDestinationsActiveIsa(); int evalRefsetNid = 0; if (ConceptVersionBI.class.isAssignableFrom(value2.getClass())) { possibleRefsetCV = (ConceptVersionBI) value2; evalRefsetNid = possibleRefsetCV.getNid(); } else if (ConceptSpec.class.isAssignableFrom(value2.getClass())) { possibleRefset = (ConceptSpec) value2; try { evalRefsetNid = possibleRefset.getStrict(vc).getNid(); } catch (ValidationException ve) { return false; } } else if (ConceptFact.class.isAssignableFrom(value2.getClass())) { ConceptFact fact = (ConceptFact) value2; possibleRefsetCV = (ConceptVersionBI) fact.getConcept(); evalRefsetNid = possibleRefsetCV.getNid(); } return this.getOperator().isNegated() ^ (testParentOf(evalRefsetNid, parents, possibleMember)); } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e); return this.getOperator().isNegated() ^ (false); } catch (ContradictionException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, e); return this.getOperator().isNegated() ^ (false); } } private boolean testParentOf(int evalRefsetNid, Collection<? extends ConceptVersionBI> parents, ConceptVersionBI possibleMember) { boolean parentMember = false; try { for (ConceptVersionBI parent : parents) { parentMember = parent.isMember(evalRefsetNid); if (parentMember) { break; } else if (!parentMember && !parent.getRelationshipsOutgoingDestinationsActiveIsa().isEmpty()) { parentMember = testParentOf(evalRefsetNid, parent.getRelationshipsOutgoingDestinationsActiveIsa(), possibleMember); } } } catch (IOException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "refset concept not found", e); return parentMember; } catch (ContradictionException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "refset concept not found", e); return parentMember; } return parentMember; } @Override public String toString() { return "IsMemberOf isMemberOf"; } } /** * @see gov.va.isaac.drools.evaluators.IsaacBaseEvaluatorDefinition#getId() */ @Override protected String getId() { return IS_PARENT_MEMBER_OF.getOperatorString(); } /** * @see gov.va.isaac.drools.evaluators.IsaacBaseEvaluatorDefinition#buildEvaluator(org.drools.core.base.ValueType, boolean, String) */ @Override protected BaseEvaluator buildEvaluator(ValueType type, boolean isNegated, String parameterText) { return new IsParentMemberOfEvaluator(type, isNegated); } }
9232c3b21f8f4a5944a78a568090dd29f7e733e0
11,826
java
Java
common/src/main/java/com/kumuluz/ee/fault/tolerance/config/MicroprofileConfigUtil.java
kumuluz/kumuluzee-circuit-breaker
96124e2dd486ca424345d368420ef8ac9329a4e7
[ "MIT" ]
null
null
null
common/src/main/java/com/kumuluz/ee/fault/tolerance/config/MicroprofileConfigUtil.java
kumuluz/kumuluzee-circuit-breaker
96124e2dd486ca424345d368420ef8ac9329a4e7
[ "MIT" ]
1
2018-07-12T14:08:42.000Z
2020-04-08T11:20:44.000Z
common/src/main/java/com/kumuluz/ee/fault/tolerance/config/MicroprofileConfigUtil.java
kumuluz/kumuluzee-fault-tolerance
bb6a5dbf97b04ac096d6c1be6be97e9f6e301ea4
[ "MIT" ]
null
null
null
37.66242
177
0.628446
996,337
/* * Copyright (c) 2014-2017 Kumuluz and/or its affiliates * and other contributors as indicated by the @author tags and * the contributor list. * * Licensed under the MIT License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://opensource.org/licenses/MIT * * 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. See the License for the specific language governing permissions and * limitations under the License. */ package com.kumuluz.ee.fault.tolerance.config; import com.kumuluz.ee.fault.tolerance.interfaces.ConfigWrapper; import org.eclipse.microprofile.faulttolerance.*; import javax.enterprise.context.ApplicationScoped; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.time.temporal.ChronoUnit; import java.util.Optional; /** * Utility for Fault Tolerance configuration with Microprofile config. * * @author Urban Malc * @since 1.1.0 */ @ApplicationScoped public class MicroprofileConfigUtil { private ConfigWrapper config; private boolean nonFallbackEnabled; public MicroprofileConfigUtil() { try { Class.forName("org.eclipse.microprofile.config.Config"); config = new MicroprofileConfig(); } catch (ClassNotFoundException e) { // mp config not found, using no-op config config = new NoopConfig(); } nonFallbackEnabled = config.getOptionalValue("MP_Fault_Tolerance_NonFallback_Enabled", Boolean.class) .orElse(true); } public ConfigWrapper getConfig() { return config; } public Bulkhead configOverriddenBulkhead(Class clazz, Method method, Bulkhead annotation) { if (annotation == null || !isAnnotationEnabled(clazz, method, Bulkhead.class)) { return null; } int value = getConfigProperty(clazz, method, Bulkhead.class, "value", Integer.class).orElse(annotation.value()); int waitingTaskQueue = getConfigProperty(clazz, method, Bulkhead.class, "waitingTaskQueue", Integer.class).orElse(annotation.waitingTaskQueue()); return new Bulkhead() { @Override public Class<? extends Annotation> annotationType() { return Bulkhead.class; } @Override public int value() { return value; } @Override public int waitingTaskQueue() { return waitingTaskQueue; } }; } public CircuitBreaker configOverriddenCircuitBreaker(Class clazz, Method method, CircuitBreaker annotation) { if (annotation == null || !isAnnotationEnabled(clazz, method, CircuitBreaker.class)) { return null; } Class<? extends Throwable>[] failOn = getConfigProperty(clazz, method, CircuitBreaker.class, "failOn", Class[].class).orElse(annotation.failOn()); long delay = getConfigProperty(clazz, method, CircuitBreaker.class, "delay", Long.class).orElse(annotation.delay()); ChronoUnit delayUnit = getConfigProperty(clazz, method, CircuitBreaker.class, "delayUnit", ChronoUnit.class).orElse(annotation.delayUnit()); int requestVolumeThreshold = getConfigProperty(clazz, method, CircuitBreaker.class, "requestVolumeThreshold", Integer.class).orElse(annotation.requestVolumeThreshold()); double failureRatio = getConfigProperty(clazz, method, CircuitBreaker.class, "failureRatio", Double.class).orElse(annotation.failureRatio()); int successThreshold = getConfigProperty(clazz, method, CircuitBreaker.class, "successThreshold", Integer.class).orElse(annotation.successThreshold()); return new CircuitBreaker() { @Override public Class<? extends Annotation> annotationType() { return CircuitBreaker.class; } @Override public Class<? extends Throwable>[] failOn() { return failOn; } @Override public long delay() { return delay; } @Override public ChronoUnit delayUnit() { return delayUnit; } @Override public int requestVolumeThreshold() { return requestVolumeThreshold; } @Override public double failureRatio() { return failureRatio; } @Override public int successThreshold() { return successThreshold; } }; } public Fallback configOverriddenFallback(Class clazz, Method method, Fallback annotation) { if (annotation == null || !isAnnotationEnabled(clazz, method, Fallback.class)) { return null; } Class<? extends FallbackHandler<?>> value = getConfigProperty(clazz, method, Fallback.class, "value", Class.class).orElse(annotation.value()); String fallbackMethod = getConfigProperty(clazz, method, Fallback.class, "fallbackMethod", String.class).orElse(annotation.fallbackMethod()); return new Fallback() { @Override public Class<? extends Annotation> annotationType() { return Fallback.class; } @Override public Class<? extends FallbackHandler<?>> value() { return value; } @Override public String fallbackMethod() { return fallbackMethod; } }; } public Retry configOverriddenRetry(Class clazz, Method method, Retry annotation) { if (annotation == null || !isAnnotationEnabled(clazz, method, Retry.class)) { return null; } int maxRetries = getConfigProperty(clazz, method, Retry.class, "maxRetries", Integer.class).orElse(annotation.maxRetries()); long delay = getConfigProperty(clazz, method, Retry.class, "delay", Long.class).orElse(annotation.delay()); ChronoUnit delayUnit = getConfigProperty(clazz, method, Retry.class, "delayUnit", ChronoUnit.class).orElse(annotation.delayUnit()); long maxDuration = getConfigProperty(clazz, method, Retry.class, "maxDuration", Long.class).orElse(annotation.maxDuration()); ChronoUnit durationUnit = getConfigProperty(clazz, method, Retry.class, "durationUnit", ChronoUnit.class).orElse(annotation.durationUnit()); long jitter = getConfigProperty(clazz, method, Retry.class, "jitter", Long.class).orElse(annotation.jitter()); ChronoUnit jitterDelayUnit = getConfigProperty(clazz, method, Retry.class, "jitterDelayUnit", ChronoUnit.class).orElse(annotation.jitterDelayUnit()); Class<? extends Throwable>[] retryOn = getConfigProperty(clazz, method, Retry.class, "retryOn", Class[].class).orElse(annotation.retryOn()); Class<? extends Throwable>[] abortOn = getConfigProperty(clazz, method, Retry.class, "abortOn", Class[].class).orElse(annotation.abortOn()); return new Retry() { @Override public Class<? extends Annotation> annotationType() { return Retry.class; } @Override public int maxRetries() { return maxRetries; } @Override public long delay() { return delay; } @Override public ChronoUnit delayUnit() { return delayUnit; } @Override public long maxDuration() { return maxDuration; } @Override public ChronoUnit durationUnit() { return durationUnit; } @Override public long jitter() { return jitter; } @Override public ChronoUnit jitterDelayUnit() { return jitterDelayUnit; } @Override public Class<? extends Throwable>[] retryOn() { return retryOn; } @Override public Class<? extends Throwable>[] abortOn() { return abortOn; } }; } public Timeout configOverriddenTimeout(Class clazz, Method method, Timeout annotation) { if (annotation == null || !isAnnotationEnabled(clazz, method, Timeout.class)) { return null; } long value = getConfigProperty(clazz, method, Timeout.class, "value", Long.class).orElse(annotation.value()); ChronoUnit unit = getConfigProperty(clazz, method, Timeout.class, "unit", ChronoUnit.class).orElse(annotation.unit()); return new Timeout() { @Override public Class<? extends Annotation> annotationType() { return Timeout.class; } @Override public long value() { return value; } @Override public ChronoUnit unit() { return unit; } }; } public boolean isAnnotationEnabled(Class clazz, Method method, Class<? extends Annotation> annotation) { Optional<Boolean> value = getConfigPropertyForEnabled(clazz, method, annotation); return value.orElse((annotation.equals(Fallback.class)) || this.nonFallbackEnabled); } private Optional<Boolean> getConfigPropertyForEnabled(Class clazz, Method method, Class<? extends Annotation> annotation) { Optional<Boolean> value = Optional.empty(); if (method != null) { value = config.getOptionalValue(getClassMethodKeyPrefix(clazz, method, annotation, "enabled"), Boolean.class); } if (!value.isPresent()) { value = config.getOptionalValue(getClassKeyPrefix(clazz, annotation, "enabled"), Boolean.class); } if (!value.isPresent()) { value = config.getOptionalValue(getKeyPrefix(annotation, "enabled"), Boolean.class); } return value; } private <T> Optional<T> getConfigProperty(Class clazz, Method method, Class<? extends Annotation> annotation, String propertyName, Class<T> tClass) { Optional<T> value; if (method != null) { value = config.getOptionalValue(getClassMethodKeyPrefix(clazz, method, annotation, propertyName), tClass); } else { value = config.getOptionalValue(getClassKeyPrefix(clazz, annotation, propertyName), tClass); } if (!value.isPresent()) { value = config.getOptionalValue(getKeyPrefix(annotation, propertyName), tClass); } return value; } private String getClassMethodKeyPrefix(Class clazz, Method method, Class<? extends Annotation> annotation, String propertyName) { return clazz.getName() + "/" + method.getName() + "/" + getKeyPrefix(annotation, propertyName); } private String getClassKeyPrefix(Class clazz, Class<? extends Annotation> annotation, String propertyName) { return clazz.getName() + "/" + getKeyPrefix(annotation, propertyName); } private String getKeyPrefix(Class<? extends Annotation> annotation, String propertyName) { return annotation.getSimpleName() + "/" + propertyName; } }
9232c3fbcd8aa4c7f7b800e116a659c5449eed1d
4,473
java
Java
src/main/java/com/chrisrm/idea/ui/MTTextBorder.java
amwill04/material-theme-jetbrains
53767c7965eabab8282578526eeb2445c3c6159a
[ "MIT" ]
null
null
null
src/main/java/com/chrisrm/idea/ui/MTTextBorder.java
amwill04/material-theme-jetbrains
53767c7965eabab8282578526eeb2445c3c6159a
[ "MIT" ]
null
null
null
src/main/java/com/chrisrm/idea/ui/MTTextBorder.java
amwill04/material-theme-jetbrains
53767c7965eabab8282578526eeb2445c3c6159a
[ "MIT" ]
null
null
null
40.663636
125
0.711379
996,338
/* * The MIT License (MIT) * * Copyright (c) 2018 Chris Magnussen and Elior Boukhobza * * 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.chrisrm.idea.ui; import com.intellij.ide.ui.laf.darcula.ui.DarculaTextBorder; import com.intellij.ide.ui.laf.darcula.ui.TextFieldWithPopupHandlerUI; import com.intellij.ui.ColorPanel; import com.intellij.util.ui.JBInsets; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.MacUIUtil; import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.*; import javax.swing.text.*; import java.awt.*; import java.awt.geom.*; /** * @author Konstantin Bulenkov */ public final class MTTextBorder extends DarculaTextBorder implements Border, UIResource { private static Color getBorderColor(final boolean enabled) { return enabled ? UIManager.getColor("TextField.separatorColor") : UIManager.getColor("TextField.separatorColorDisabled"); } @Override public Insets getBorderInsets(final Component c) { final int vOffset = TextFieldWithPopupHandlerUI.isSearchField(c) ? 6 : 8; if (TextFieldWithPopupHandlerUI.isSearchFieldWithHistoryPopup(c)) { return JBUI.insets(vOffset, 4, vOffset, 4).asUIResource(); } else if (TextFieldWithPopupHandlerUI.isSearchField(c)) { return JBUI.insets(vOffset, 4, vOffset, 4).asUIResource(); } else if (c instanceof JTextField && c.getParent() instanceof ColorPanel) { return JBUI.insets(3, 3, 2, 2).asUIResource(); } else { final JBInsets.JBInsetsUIResource insets = JBUI.insets(vOffset, 4).asUIResource(); try { TextFieldWithPopupHandlerUI.updateBorderInsets(c, insets); return insets; } catch (final NoSuchMethodError e) { return insets; } } } @Override public boolean isBorderOpaque() { return false; } @Override public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) { if (((JComponent) c).getClientProperty("JTextField.Search.noBorderRing") == Boolean.TRUE) { return; } final Rectangle r = new Rectangle(x, y, width, height); final Graphics2D g2 = (Graphics2D) g.create(); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, MacUIUtil.USE_QUARTZ ? RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE); try { g2.translate(x, y); if (c.hasFocus()) { g2.setColor(getSelectedBorderColor()); g2.fillRect(JBUI.scale(1), height - JBUI.scale(2), width - JBUI.scale(2), JBUI.scale(2)); } else if (!c.isEnabled()) { g.setColor(getBorderColor(c.isEnabled())); g2.setStroke(new BasicStroke(1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 0, new float[] {1, 2}, 0)); g2.draw(new Rectangle2D.Double(JBUI.scale(1), height - JBUI.scale(1), width - JBUI.scale(2), JBUI.scale(2))); } else { final boolean editable = !(c instanceof JTextComponent) || ((JTextComponent) c).isEditable(); g2.setColor(getBorderColor(editable)); g2.fillRect(JBUI.scale(1), height - JBUI.scale(1), width - JBUI.scale(2), JBUI.scale(2)); } } finally { g2.dispose(); } } private Color getSelectedBorderColor() { return UIManager.getColor("TextField.selectedSeparatorColor"); } }
9232c49c311f0343fbc6507e878af72ac07200f3
1,454
java
Java
app/src/main/java/com/example/simpletodo/EditActivity.java
NickJHoffmann/codepath_simple_todo
3fe62b4a4b9824e7f55dd8aa86258928f6fe2970
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/simpletodo/EditActivity.java
NickJHoffmann/codepath_simple_todo
3fe62b4a4b9824e7f55dd8aa86258928f6fe2970
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/simpletodo/EditActivity.java
NickJHoffmann/codepath_simple_todo
3fe62b4a4b9824e7f55dd8aa86258928f6fe2970
[ "Apache-2.0" ]
null
null
null
34.619048
128
0.660935
996,339
package com.example.simpletodo; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; public class EditActivity extends AppCompatActivity { EditText etExistingItem; Button btnSave; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edit); etExistingItem = findViewById(R.id.etExistingItem); btnSave = findViewById(R.id.btnSave); getSupportActionBar().setTitle("Edit Item"); etExistingItem.setText(getIntent().getStringExtra(MainActivity.KEY_ITEM_TEXT)); btnSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Create intent which will contain results Intent intent = new Intent(); // Pass results of edit intent.putExtra(MainActivity.KEY_ITEM_TEXT, etExistingItem.getText().toString()); intent.putExtra(MainActivity.KEY_ITEM_POSITION, getIntent().getExtras().getInt(MainActivity.KEY_ITEM_POSITION)); // Set result of intent setResult(RESULT_OK, intent); // Finish activity, close screen and go back finish(); } }); } }
9232c4ce98a9b8043df050e48ec0e5a0c4f9ab61
1,451
java
Java
src/main/java/org/onap/aai/validation/config/PropertiesConfig.java
onap/aai-validation
7874fc8780d18aa7c8856c31a55c044ec15f1696
[ "Apache-2.0" ]
null
null
null
src/main/java/org/onap/aai/validation/config/PropertiesConfig.java
onap/aai-validation
7874fc8780d18aa7c8856c31a55c044ec15f1696
[ "Apache-2.0" ]
null
null
null
src/main/java/org/onap/aai/validation/config/PropertiesConfig.java
onap/aai-validation
7874fc8780d18aa7c8856c31a55c044ec15f1696
[ "Apache-2.0" ]
null
null
null
34.547619
79
0.587181
996,340
/* * ============LICENSE_START=================================================== * Copyright (c) 2018 Amdocs * ============================================================================ * 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. * ============LICENSE_END===================================================== */ package org.onap.aai.validation.config; import java.text.MessageFormat; /** * Base properties configuration class. */ public class PropertiesConfig { /** * Replaces place-holders in property values. * * @param s * a string with place-holders in the form {n} * @param args * values for place-holders * @return a formated String with replaced place-holders. */ public String formatter(String s, Object... args) { MessageFormat formatter = new MessageFormat(""); formatter.applyPattern(s); return formatter.format(args); } }
9232c5938a8533dd7449cce8d1ae0ea3edaf59a2
1,557
java
Java
Java/337.house-robber-iii/Solution1.java
pengzhendong/LeetCode
e17a4b01aa4536da13551eb89421a10c88d5c374
[ "MIT" ]
5
2019-04-22T06:38:21.000Z
2021-06-18T07:03:19.000Z
Java/337.house-robber-iii/Solution1.java
pengzhendong/LeetCode
e17a4b01aa4536da13551eb89421a10c88d5c374
[ "MIT" ]
null
null
null
Java/337.house-robber-iii/Solution1.java
pengzhendong/LeetCode
e17a4b01aa4536da13551eb89421a10c88d5c374
[ "MIT" ]
null
null
null
22.242857
89
0.512524
996,341
/* * @lc app=leetcode.cn id=337 lang=java * * [337] 打家劫舍 III * * https://leetcode-cn.com/problems/house-robber-iii/description/ * * algorithms * Medium (53.03%) * Total Accepted: 2.9K * Total Submissions: 5.4K * Testcase Example: '[3,2,3,null,3,null,1]' * * 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 * 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 * 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。 * * 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。 * * 示例 1: * * 输入: [3,2,3,null,3,null,1] * * ⁠ 3 * ⁠ / \ * ⁠ 2 3 * ⁠ \ \ * ⁠ 3 1 * * 输出: 7 * 解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7. * * 示例 2: * * 输入: [3,4,5,1,3,null,1] * * 3 * ⁠ / \ * ⁠ 4 5 * ⁠ / \ \ * ⁠1 3 1 * * 输出: 9 * 解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9. */ /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { private Map<TreeNode, Integer> memo = new HashMap<>(); public int rob(TreeNode root) { if (root == null) return 0; if (!memo.containsKey(root)) { int sum = root.val; if (root.left != null) sum += rob(root.left.left) + rob(root.left.right); if (root.right != null) sum += rob(root.right.left) + rob(root.right.right); memo.put(root, Math.max(sum, rob(root.left) + rob(root.right))); } return memo.get(root); } }
9232c62b077c3b94cddf74c415521488fd8a0998
4,211
java
Java
graphsdk/src/main/java/com/microsoft/graph/generated/BaseConversation.java
SailReal/msgraph-sdk-android
68bf5bf437e8688142493de5faf88154c388d7c8
[ "MIT" ]
61
2016-06-11T20:14:35.000Z
2021-06-09T03:47:07.000Z
graphsdk/src/main/java/com/microsoft/graph/generated/BaseConversation.java
SailReal/msgraph-sdk-android
68bf5bf437e8688142493de5faf88154c388d7c8
[ "MIT" ]
95
2016-03-30T22:16:20.000Z
2020-09-03T18:37:43.000Z
graphsdk/src/main/java/com/microsoft/graph/generated/BaseConversation.java
SailReal/msgraph-sdk-android
68bf5bf437e8688142493de5faf88154c388d7c8
[ "MIT" ]
49
2016-03-30T19:52:31.000Z
2022-02-25T11:04:50.000Z
31.736842
197
0.646766
996,342
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.generated; import com.microsoft.graph.concurrency.*; import com.microsoft.graph.core.*; import com.microsoft.graph.extensions.*; import com.microsoft.graph.http.*; import com.microsoft.graph.generated.*; import com.microsoft.graph.options.*; import com.microsoft.graph.serializer.*; import java.util.Arrays; import java.util.EnumSet; import com.google.gson.JsonObject; import com.google.gson.JsonElement; import com.google.gson.annotations.*; import java.util.HashMap; import java.util.Map; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Base Conversation. */ public class BaseConversation extends Entity implements IJsonBackedObject { /** * The Topic. * The topic of the conversation. This property can be set when the conversation is created, but it cannot be updated. */ @SerializedName("topic") @Expose public String topic; /** * The Has Attachments. * Indicates whether any of the posts within this Conversation has at least one attachment. */ @SerializedName("hasAttachments") @Expose public Boolean hasAttachments; /** * The Last Delivered Date Time. * The Timestamp type represents date and time information using ISO 8601 format and is always in UTC time. For example, midnight UTC on Jan 1, 2014 would look like this: '2014-01-01T00:00:00Z' */ @SerializedName("lastDeliveredDateTime") @Expose public java.util.Calendar lastDeliveredDateTime; /** * The Unique Senders. * All the users that sent a message to this Conversation. */ @SerializedName("uniqueSenders") @Expose public java.util.List<String> uniqueSenders; /** * The Preview. * A short summary from the body of the latest post in this converstaion. */ @SerializedName("preview") @Expose public String preview; /** * The Threads. * A collection of all the conversation threads in the conversation. A navigation property. Read-only. Nullable. */ public transient ConversationThreadCollectionPage threads; /** * The raw representation of this class */ private transient JsonObject mRawObject; /** * The serializer */ private transient ISerializer mSerializer; /** * Gets the raw representation of this class * @return the raw representation of this class */ public JsonObject getRawObject() { return mRawObject; } /** * Gets serializer * @return the serializer */ protected ISerializer getSerializer() { return mSerializer; } /** * Sets the raw json object * * @param serializer The serializer * @param json The json object to set this object to */ public void setRawObject(final ISerializer serializer, final JsonObject json) { mSerializer = serializer; mRawObject = json; if (json.has("threads")) { final BaseConversationThreadCollectionResponse response = new BaseConversationThreadCollectionResponse(); if (json.has("hzdkv@example.com")) { response.nextLink = json.get("hzdkv@example.com").getAsString(); } final JsonObject[] sourceArray = serializer.deserializeObject(json.get("threads").toString(), JsonObject[].class); final ConversationThread[] array = new ConversationThread[sourceArray.length]; for (int i = 0; i < sourceArray.length; i++) { array[i] = serializer.deserializeObject(sourceArray[i].toString(), ConversationThread.class); array[i].setRawObject(serializer, sourceArray[i]); } response.value = Arrays.asList(array); threads = new ConversationThreadCollectionPage(response, null); } } }
9232c67b42b0224919923652688d362a2df7363b
2,606
java
Java
aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/PredictRequestMarshaller.java
pgoranss/aws-sdk-java
041ffc4197309c98c4be534b43ca2bda146e4f7c
[ "Apache-2.0" ]
1
2019-04-21T21:56:44.000Z
2019-04-21T21:56:44.000Z
aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/PredictRequestMarshaller.java
pgoranss/aws-sdk-java
041ffc4197309c98c4be534b43ca2bda146e4f7c
[ "Apache-2.0" ]
110
2019-11-11T19:37:58.000Z
2021-07-16T18:23:58.000Z
aws-java-sdk-machinelearning/src/main/java/com/amazonaws/services/machinelearning/model/transform/PredictRequestMarshaller.java
pgoranss/aws-sdk-java
041ffc4197309c98c4be534b43ca2bda146e4f7c
[ "Apache-2.0" ]
1
2019-07-22T16:24:05.000Z
2019-07-22T16:24:05.000Z
40.71875
159
0.74482
996,343
/* * Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.machinelearning.model.transform; import java.util.Map; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.machinelearning.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * PredictRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class PredictRequestMarshaller { private static final MarshallingInfo<String> MLMODELID_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("MLModelId").build(); private static final MarshallingInfo<Map> RECORD_BINDING = MarshallingInfo.builder(MarshallingType.MAP).marshallLocation(MarshallLocation.PAYLOAD) .marshallLocationName("Record").build(); private static final MarshallingInfo<String> PREDICTENDPOINT_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("PredictEndpoint").build(); private static final PredictRequestMarshaller instance = new PredictRequestMarshaller(); public static PredictRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(PredictRequest predictRequest, ProtocolMarshaller protocolMarshaller) { if (predictRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(predictRequest.getMLModelId(), MLMODELID_BINDING); protocolMarshaller.marshall(predictRequest.getRecord(), RECORD_BINDING); protocolMarshaller.marshall(predictRequest.getPredictEndpoint(), PREDICTENDPOINT_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
9232c6927d3dc1d4558838c144f104c75800d5a8
765
java
Java
T09regularExpressions/lab/P03MatchDates.java
1vaPetkova/programmingFundamentalsJava
ada7ac4eaee2eb2b6e85cdbb37377506e1347fac
[ "MIT" ]
null
null
null
T09regularExpressions/lab/P03MatchDates.java
1vaPetkova/programmingFundamentalsJava
ada7ac4eaee2eb2b6e85cdbb37377506e1347fac
[ "MIT" ]
null
null
null
T09regularExpressions/lab/P03MatchDates.java
1vaPetkova/programmingFundamentalsJava
ada7ac4eaee2eb2b6e85cdbb37377506e1347fac
[ "MIT" ]
null
null
null
34.772727
100
0.585621
996,344
package T09regularExpressions.lab; import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class P03MatchDates { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String regex = "\\b(?<day>\\d{2})([\\.\\-\\/])(?<month>[A-Z][a-z]{2})\\2(?<year>\\d{4})\\b"; Pattern pattern = Pattern.compile(regex); String input = scan.nextLine(); Matcher matcher = pattern.matcher(input); while(matcher.find()){ String day = matcher.group("day"); String month = matcher.group("month"); String year = matcher.group("year"); System.out.printf("Day: %s, Month: %s, Year: %s\n",day,month,year); } } }
9232c69f8d0b7601846968896782e8bc471c9066
12,496
java
Java
src/main/java/com/webcheckers/model/gamelogic/Lobby.java
Oztaco/Checker-Bois
9b101c5e89cb41ad4e56b6fa43c9c29a20079d67
[ "MIT" ]
null
null
null
src/main/java/com/webcheckers/model/gamelogic/Lobby.java
Oztaco/Checker-Bois
9b101c5e89cb41ad4e56b6fa43c9c29a20079d67
[ "MIT" ]
null
null
null
src/main/java/com/webcheckers/model/gamelogic/Lobby.java
Oztaco/Checker-Bois
9b101c5e89cb41ad4e56b6fa43c9c29a20079d67
[ "MIT" ]
2
2019-03-28T22:18:56.000Z
2020-02-28T01:37:15.000Z
41.339934
119
0.430704
996,345
package com.webcheckers.model.gamelogic; import com.webcheckers.Exceptions.GameNotAddedException; import com.webcheckers.Exceptions.InvalidMoveException; import com.webcheckers.Exceptions.PlayerNotAddedException; import java.util.HashMap; import java.util.logging.Logger; public class Lobby { private static final Logger LOG = Logger.getLogger(Lobby.class.getName()); private final String validChars = "se2xy1bknelxn4y8xzxu3trosptip3q5"; private HashMap<String,Player> players; //Maps Session ID's to Player Objects private HashMap<String,Game> games; //Maps IDs to Game Objects /* ####################################################################################################### Private Methods #######################################################################################################*/ public Lobby(){ this.games = new HashMap<>(); this.players = new HashMap<>(); } /* ####################################################################################################### Getter Methods #######################################################################################################*/ public Game getGame(String id){ return this.games.get(id); } public Player getPlayerBySessionID(String sessionID) { return players.get(sessionID); } private Player getPlayer(String username){ try{ return this.players.get(username); } catch(Exception e){ return null; } } public int getPlayer1Pieces(String gameID){ return this.getGame(gameID).getPlayer1Pieces(); } public int getPlayer2Pieces(String gameID){ return this.getGame(gameID).getPlayer2Pieces(); } /* ####################################################################################################### Lobby Management Methods #######################################################################################################*/ /** * ---------------------------------------------------------------------------------------------------- * addPlayer(Player player) * * adds a player specified to the lobby. * @param username * @throws PlayerNotAddedException * ---------------------------------------------------------------------------------------------------- */ public void addPlayer(String sessionID, String username) { Player newPlayer = new Player(sessionID, username); this.players.put(sessionID, newPlayer); } /** * ---------------------------------------------------------------------------------------------------- * removePlayer * * Removes a player from the lobby based on a sessionID * @param sessionID * ---------------------------------------------------------------------------------------------------- */ public void removePlayer(String sessionID){ this.players.remove(sessionID); } /** * ---------------------------------------------------------------------------------------------------- * addGame(CheckersBoard game) * * Adds game to list of games, given it's players are in the lobby. * @param sessionID1 * @param sessionID2 * @throws GameNotAddedException * ---------------------------------------------------------------------------------------------------- */ public String addNewGame(String sessionID1, String sessionID2){ LOG.severe("Lobby -> addNewGame invoked"); LOG.severe("SessionID1: " + sessionID1); LOG.severe("SessionID2: " + sessionID2); String newId = generateID(); Game game = new Game(this.players.get(sessionID1),this.players.get(sessionID2),newId); this.games.put(newId,game); this.players.get(sessionID1).addToGame(newId); this.players.get(sessionID2).addToGame(newId); return newId; } /* ####################################################################################################### Private Methods #######################################################################################################*/ /** * ---------------------------------------------------------------------------------------------------- * generateID() * * Generates a Random ID to assign to every game. * @return randID * ---------------------------------------------------------------------------------------------------- */ private String generateID(){ int range = this.validChars.length()-1; String randId = ""; for(int i = 0; i <= 6; i++){ int index = (int)(Math.random()*range); randId = randId + validChars.charAt(index); } if(games.containsKey(randId)){ randId = generateID(); //Make a new ID if the ID generated is already in use } return randId; } /* ####################################################################################################### Public Methods #######################################################################################################*/ public void makeMove(String gameID, int x0, int x1, int y0, int y1, MoveType m) throws InvalidMoveException{ Player currPlayer = this.games.get(gameID).getPlayerTurn(); this.games.get(gameID).playTurn(currPlayer, x0,y0,x1,y1,m); } public void playerResigned(String gameID, String playerSessionID) { LOG.severe("Player ID {" + playerSessionID + "} resigned in game {" + gameID + "}"); Player p = this.players.get(playerSessionID); LOG.severe("Name= " + p.getName()); this.games.get(gameID).playerResigned(p); } /* ####################################################################################################### Testing Methods #######################################################################################################*/ /** * ---------------------------------------------------------------------------------------------------- * printLobby() * * Prints lobby for testing purposes * ---------------------------------------------------------------------------------------------------- */ public void printLobby(){ System.out.println("Lobby:"); String players = ""; for(int i = 0;i < this.players.size();i++){ players += (this.players.get(i).getName() + ", " ); } System.out.println("\tUnique players: " + players); System.out.println("\tNumber of unique games: " + this.games.keySet().size()); } /* ####################################################################################################### Communication Methods #######################################################################################################*/ /** * ---------------------------------------------------------------------------------------------------- * getPlayersAsString() * * Formats the players in the lobby for use in JSON files * TODO: METHOD STUBBED * @return * ---------------------------------------------------------------------------------------------------- */ public String getPlayersAsString(){ String playersAsString = ""; for(String current : this.players.keySet()){ playersAsString += (this.players.get(current).getPlayerAsString() + ", "); } if(playersAsString.length() > 1){ playersAsString = playersAsString.substring(0,playersAsString.length()-2); } return playersAsString; } public String getGameAsString(String gameID, String sessionID){ if (!this.games.containsKey(gameID)) { String errorMsg = "Game {" + gameID + "} not found in the lobby. Can not complete getGameAsString request."; LOG.severe(errorMsg); return errorMsg; } return this.games.get(gameID).getGameAsString(this.players.get(sessionID)); } /** * ---------------------------------------------------------------------------------------------------- * getGamesAsString() * * Formats all games in a Lobby excluding a player for use in JSON files * TODO : METHOD STUBBED * @return ArrayList<CheckersBoard> * ---------------------------------------------------------------------------------------------------- */ public String getGamesAsString(String playerID){ String notPlayerGames = ""; if(this.games.size() > 1) { for (String game : this.games.keySet()) { if (!this.players.get(playerID).getIds().contains(game)) { notPlayerGames += (this.games.get(game).getSimpleGameAsString() + ", "); } } } if(notPlayerGames.length() >= 1){ notPlayerGames = notPlayerGames.substring(0,notPlayerGames.length()-2); } return notPlayerGames; } /** * ---------------------------------------------------------------------------------------------------- * getGamesAsStringForPlayer * * Formats all games for a specific player as a string for use in a JSON file * @param player * @return playerGames * ---------------------------------------------------------------------------------------------------- */ public String getGamesAsStringForPlayer(String player){ if (!this.players.containsKey(player)) { String errorMsg = "Player {" + player + "} not found in the lobby. Can not complete getGamesAsStringForPlayer request."; LOG.severe(errorMsg); return errorMsg; } String playerGames = ""; if(this.players.get(player).getIds().size() > 0){ for(String id : this.players.get(player).getIds()){ //For each game the player is currently enrolled in playerGames += (this.getGame(id).getSimpleGameAsString() + ", "); } if(playerGames.length() > 1){ playerGames = playerGames.substring(0,playerGames.length()-2); } } return playerGames; } public String getGameBoardAsString(String id, String playerSessionID){ Player theOneWhoKnocks = this.players.get(playerSessionID); return this.games.get(id).getGameBoardAsString(theOneWhoKnocks); } /** * ---------------------------------------------------------------------------------------------------- * getNumOfPlayers * * Gets the number of Players currently signed in * @return numPlayers * ---------------------------------------------------------------------------------------------------- */ public int getNumOfPlayers() { return this.players.size(); } /* ####################################################################################################### Main Testing #######################################################################################################*/ public static void main(String args[]){ Lobby l = new Lobby(); l.addPlayer("1","peepee"); l.addPlayer("2", "Gerard"); l.addPlayer("3", "Nerd"); l.addNewGame("1","2"); //peepee has one game with his good friend gerard System.out.println("All Players\n\t" + l.getPlayersAsString()); System.out.println("Games for \"peepee\"\n\t" + l.getGamesAsStringForPlayer("1")); System.out.println("Games \"peepee\" was not invited to\n\t" + l.getGamesAsString("1")); l.addNewGame("1","3"); //peepee gets a second game with his sworn enemy nerd System.out.println("All Players\n\t" + l.getPlayersAsString()); System.out.println("Games for \"peepee\"\n\t" + l.getGamesAsStringForPlayer("1")); System.out.println("Games \"peepee\" was not invited to\n\t" + l.getGamesAsString("1")); l.addNewGame("2", "3"); //Woe is me! Gerard and nerd are now in cahoots and playing a game WITHOUT PEEPEE System.out.println("All Players\n\t" + l.getPlayersAsString()); System.out.println("Games for \"peepee\"\n\t" + l.getGamesAsStringForPlayer("1")); System.out.println("Games \"peepee\" was not invited to\n\t" + l.getGamesAsString("1")); } }
9232c6ec5c1a0f6bc8498c4ad570c67ff08bb510
214
java
Java
container/src/test/org/picocontainer/doc/tutorial/simple/Boy.java
ebourg/PicoContainer1
51abe9f604c37daad9b21bdaa61eae8cc9d75ab9
[ "BSD-3-Clause" ]
null
null
null
container/src/test/org/picocontainer/doc/tutorial/simple/Boy.java
ebourg/PicoContainer1
51abe9f604c37daad9b21bdaa61eae8cc9d75ab9
[ "BSD-3-Clause" ]
1
2019-09-19T08:43:00.000Z
2019-09-22T23:18:23.000Z
container/src/test/org/picocontainer/doc/tutorial/simple/Boy.java
ebourg/PicoContainer1
51abe9f604c37daad9b21bdaa61eae8cc9d75ab9
[ "BSD-3-Clause" ]
2
2019-09-19T08:44:33.000Z
2020-03-04T16:27:48.000Z
17.833333
56
0.663551
996,346
package org.picocontainer.doc.tutorial.simple; // START SNIPPET: boy public class Boy { public void kiss(Object kisser) { System.out.println("I was kissed by " + kisser); } } // END SNIPPET: boy
9232c8264421d515fc350720a6a6ed19b6c42b6e
1,379
java
Java
java110-bean/src/main/java/com/java110/dto/tempCarFeeConfigAttr/TempCarFeeConfigAttrDto.java
osxhu/MicroCommunity
7b23ab0add380557d8778fb3e665682d0af8b196
[ "Apache-2.0" ]
711
2017-04-09T15:59:16.000Z
2022-03-27T07:19:02.000Z
java110-bean/src/main/java/com/java110/dto/tempCarFeeConfigAttr/TempCarFeeConfigAttrDto.java
yasudarui/MicroCommunity
1026aa5eaa86446aedfdefd092a3d6fcf0dfe470
[ "Apache-2.0" ]
16
2017-04-09T16:13:09.000Z
2022-01-04T16:36:13.000Z
java110-bean/src/main/java/com/java110/dto/tempCarFeeConfigAttr/TempCarFeeConfigAttrDto.java
yasudarui/MicroCommunity
1026aa5eaa86446aedfdefd092a3d6fcf0dfe470
[ "Apache-2.0" ]
334
2017-04-16T05:01:12.000Z
2022-03-30T00:49:37.000Z
19.7
78
0.657723
996,347
package com.java110.dto.tempCarFeeConfigAttr; import com.java110.dto.PageDto; import java.io.Serializable; import java.util.Date; /** * @ClassName FloorDto * @Description 临时车收费标准属性数据层封装 * @Author wuxw * @Date 2019/4/24 8:52 * @Version 1.0 * add by wuxw 2019/4/24 **/ public class TempCarFeeConfigAttrDto extends PageDto implements Serializable { private String attrId; private String configId; private String specCd; private String value; private Date createTime; private String statusCd = "0"; public String getAttrId() { return attrId; } public void setAttrId(String attrId) { this.attrId = attrId; } public String getConfigId() { return configId; } public void setConfigId(String configId) { this.configId = configId; } public String getSpecCd() { return specCd; } public void setSpecCd(String specCd) { this.specCd = specCd; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public String getStatusCd() { return statusCd; } public void setStatusCd(String statusCd) { this.statusCd = statusCd; } }
9232c857aae2d0b75548117fb8b96ca351164e26
430
java
Java
src/main/java/org/segrada/service/repository/orientdb/querybuilder/QueryPartWorker.java
mkalus/segrada
fa9a9c3c67f9872cb0415c9a8cfebfa55a98488d
[ "Apache-2.0" ]
67
2015-09-14T08:45:42.000Z
2022-03-30T10:15:47.000Z
src/main/java/org/segrada/service/repository/orientdb/querybuilder/QueryPartWorker.java
mkalus/segrada
fa9a9c3c67f9872cb0415c9a8cfebfa55a98488d
[ "Apache-2.0" ]
59
2015-12-07T15:58:12.000Z
2022-02-27T20:53:45.000Z
src/main/java/org/segrada/service/repository/orientdb/querybuilder/QueryPartWorker.java
mkalus/segrada
fa9a9c3c67f9872cb0415c9a8cfebfa55a98488d
[ "Apache-2.0" ]
18
2015-11-28T03:58:02.000Z
2020-08-14T23:28:49.000Z
26.875
61
0.734884
996,348
package org.segrada.service.repository.orientdb.querybuilder; import org.codehaus.jettison.json.JSONObject; public interface QueryPartWorker { /** * create Orient DB query part from input data * @param data input data * @return query string */ String createQuery(JSONObject data); // pass the query builder reference to the worker void setQueryBuilderReference(QueryBuilder queryBuilder); }
9232c8f05282480325ecacf787dab4ed0da86cfa
556
java
Java
src/main/java/com/senderman/telecrafter/telegram/api/entity/User.java
Kozoobmennik/telecrafter
f687232dc10131973ac2872206b608b4c0ad8d7c
[ "MIT" ]
3
2020-08-11T17:03:02.000Z
2020-12-26T18:09:54.000Z
src/main/java/com/senderman/telecrafter/telegram/api/entity/User.java
Kozoobmennik/telecrafter
f687232dc10131973ac2872206b608b4c0ad8d7c
[ "MIT" ]
1
2021-12-16T18:26:52.000Z
2021-12-16T18:26:52.000Z
src/main/java/com/senderman/telecrafter/telegram/api/entity/User.java
Kozoobmennik/telecrafter
f687232dc10131973ac2872206b608b4c0ad8d7c
[ "MIT" ]
2
2021-12-16T18:20:59.000Z
2022-01-01T17:02:06.000Z
20.592593
61
0.694245
996,349
package com.senderman.telecrafter.telegram.api.entity; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class User { private long id; @JsonProperty("is_bot") private boolean isBot; @JsonProperty("first_name") private String firstName; public long getId() { return id; } public boolean isBot() { return isBot; } public String getFirstName() { return firstName; } }
9232c9d849aaf4df915abb064e51ab63898f3736
922
java
Java
wot_api_lib/src/main/java/de/sambalmueslie/wot_api_lib/tankopedia_api/request/EncyclopediaVehiclesRequest.java
sambalmueslie/WOT-API-LIB
f9f33967f4eca0c699f3e665e0795ee444d261f2
[ "Apache-2.0" ]
1
2015-11-02T10:44:29.000Z
2015-11-02T10:44:29.000Z
wot_api_lib/src/main/java/de/sambalmueslie/wot_api_lib/tankopedia_api/request/EncyclopediaVehiclesRequest.java
chipsi007/WOT-API-LIB
f9f33967f4eca0c699f3e665e0795ee444d261f2
[ "Apache-2.0" ]
1
2015-08-21T19:52:22.000Z
2015-08-21T19:52:22.000Z
wot_api_lib/src/main/java/de/sambalmueslie/wot_api_lib/tankopedia_api/request/EncyclopediaVehiclesRequest.java
chipsi007/WOT-API-LIB
f9f33967f4eca0c699f3e665e0795ee444d261f2
[ "Apache-2.0" ]
null
null
null
17.730769
66
0.698482
996,350
package de.sambalmueslie.wot_api_lib.tankopedia_api.request; import de.sambalmueslie.wot_api_lib.common.BaseWotRequest; import java.lang.String; import java.util.Map; import java.lang.Object; public class EncyclopediaVehiclesRequest extends BaseWotRequest { public EncyclopediaVehiclesRequest() { } @Override public String getMethod( ) { return "wot/encyclopedia/tanks/"; } @Override public void getParameter( Map<String, Object> params ) { if (nation != null ) { params.put("nation",nation); } if (tank_id > 0) { params.put("tank_id",tank_id); } if (tier > 0) { params.put("tier",tier); } } public void setNation( String nation ) { this.nation = nation; } public void setTank_id( long tank_id ) { this.tank_id = tank_id; } public void setTier( long tier ) { this.tier = tier; } private java.lang.String nation; private long tank_id; private long tier; }
9232c9df3ec4a0c5f582813712a039a792579b8f
42,900
java
Java
mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/RealImapConnectionTest.java
arissystem/k-9
c0c0e05a291182ac6515b2f5bcaac22ffb6dc333
[ "Apache-2.0" ]
5,896
2015-01-01T09:18:04.000Z
2022-03-31T21:31:43.000Z
mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/RealImapConnectionTest.java
arissystem/k-9
c0c0e05a291182ac6515b2f5bcaac22ffb6dc333
[ "Apache-2.0" ]
4,489
2015-01-02T18:47:21.000Z
2022-03-31T20:19:08.000Z
mail/protocols/imap/src/test/java/com/fsck/k9/mail/store/imap/RealImapConnectionTest.java
arissystem/k-9
c0c0e05a291182ac6515b2f5bcaac22ffb6dc333
[ "Apache-2.0" ]
2,061
2015-01-03T10:52:42.000Z
2022-03-30T13:37:10.000Z
39.483456
127
0.680874
996,351
package com.fsck.k9.mail.store.imap; import java.io.IOException; import java.net.UnknownHostException; import java.util.List; import android.app.Activity; import android.net.ConnectivityManager; import com.fsck.k9.mail.AuthType; import com.fsck.k9.mail.AuthenticationFailedException; import com.fsck.k9.mail.CertificateValidationException; import com.fsck.k9.mail.CertificateValidationException.Reason; import com.fsck.k9.mail.ConnectionSecurity; import com.fsck.k9.mail.K9LibRobolectricTestRunner; import com.fsck.k9.mail.K9MailLib; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mail.XOAuth2ChallengeParserTest; import com.fsck.k9.mail.helpers.TestTrustedSocketFactory; import com.fsck.k9.mail.oauth.OAuth2TokenProvider; import com.fsck.k9.mail.ssl.TrustedSocketFactory; import com.fsck.k9.mail.store.imap.mockserver.MockImapServer; import okio.ByteString; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.shadows.ShadowLog; import static org.hamcrest.core.StringContains.containsString; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; @RunWith(K9LibRobolectricTestRunner.class) public class RealImapConnectionTest { private static final boolean DEBUGGING = false; private static final String USERNAME = "user"; private static final String PASSWORD = "123456"; private static final int SOCKET_CONNECT_TIMEOUT = 10000; private static final int SOCKET_READ_TIMEOUT = 10000; private static final String XOAUTH_TOKEN = "token"; private static final String XOAUTH_ANOTHER_TOKEN = "token2"; private static final String XOAUTH_STRING = ByteString.encodeUtf8( "user=" + USERNAME + "\001auth=Bearer " + XOAUTH_TOKEN + "\001\001").base64(); private static final String XOAUTH_STRING_RETRY = ByteString.encodeUtf8( "user=" + USERNAME + "\001auth=Bearer " + XOAUTH_ANOTHER_TOKEN + "\001\001").base64(); private TrustedSocketFactory socketFactory; private ConnectivityManager connectivityManager; private OAuth2TokenProvider oAuth2TokenProvider; private SimpleImapSettings settings; @Before public void setUp() throws Exception { connectivityManager = mock(ConnectivityManager.class); oAuth2TokenProvider = createOAuth2TokenProvider(); socketFactory = TestTrustedSocketFactory.newInstance(); settings = new SimpleImapSettings(); settings.setUsername(USERNAME); settings.setPassword(PASSWORD); if (DEBUGGING) { ShadowLog.stream = System.out; K9MailLib.setDebug(true); K9MailLib.setDebugSensitive(true); } } @Test public void open_withNoCapabilitiesInInitialResponse_shouldIssuePreAuthCapabilitiesCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); server.output("* OK example.org server"); server.expect("1 CAPABILITY"); server.output("* CAPABILITY IMAP4 IMAP4REV1 AUTH=PLAIN"); server.output("1 OK CAPABILITY Completed"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 OK Success"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withCapabilitiesInInitialResponse_shouldNotIssuePreAuthCapabilitiesCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); server.output("* OK [CAPABILITY IMAP4 IMAP4REV1 AUTH=PLAIN]"); server.expect("1 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("1 OK Success"); postAuthenticationDialogRequestingCapabilities(server, 2); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authPlain() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 OK Success"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_afterCloseWasCalled_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server); server.expect("2 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("2 OK LOGIN completed"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); imapConnection.close(); try { imapConnection.open(); fail("Expected exception"); } catch (IllegalStateException e) { assertEquals("open() called after close(). Check wrapped exception to see where close() was called.", e.getMessage()); } } @Test public void open_authPlainWithLoginDisabled_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "LOGINDISABLED"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Server doesn't support unencrypted passwords using AUTH=PLAIN and LOGIN is disabled.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authPlainWithAuthenticationFailure_shouldFallbackToLogin() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 NO Login Failure"); server.expect("3 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("3 OK LOGIN completed"); postAuthenticationDialogRequestingCapabilities(server, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authPlainAndLoginFallbackWithAuthenticationFailure_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 NO Login Failure"); server.expect("3 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("3 NO Go away"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (AuthenticationFailedException e) { //FIXME: improve exception message assertThat(e.getMessage(), containsString("Go away")); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authPlainFailureAndDisconnect_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 NO [UNAVAILABLE] Maximum number of connections from user+IP exceeded"); server.closeConnection(); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (NegativeImapResponseException e) { assertThat(e.getMessage(), containsString("Maximum number of connections from user+IP exceeded")); } assertFalse(imapConnection.isConnected()); server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authPlainWithByeResponseAndConnectionClose_shouldThrowAuthenticationFailedException() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("* BYE Go away"); server.output("2 NO Login Failure"); server.closeConnection(); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (AuthenticationFailedException e) { //FIXME: improve exception message assertThat(e.getMessage(), containsString("Login Failure")); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authPlainWithoutAuthPlainCapability_shouldUseLoginMethod() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server); server.expect("2 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("2 OK LOGIN completed"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authCramMd5() throws Exception { settings.setAuthType(AuthType.CRAM_MD5); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=CRAM-MD5"); server.expect("2 AUTHENTICATE CRAM-MD5"); server.output("+ " + ByteString.encodeUtf8("<upchh@example.com>").base64()); server.expect("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"); server.output("2 OK Success"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authCramMd5WithAuthenticationFailure_shouldThrow() throws Exception { settings.setAuthType(AuthType.CRAM_MD5); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=CRAM-MD5"); server.expect("2 AUTHENTICATE CRAM-MD5"); server.output("+ " + ByteString.encodeUtf8("<upchh@example.com>").base64()); server.expect("ax5kh6jaqkcd2tiexxs8v6xjo8yv8a6b"); server.output("2 NO Who are you?"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (AuthenticationFailedException e) { //FIXME: improve exception message assertThat(e.getMessage(), containsString("Who are you?")); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authCramMd5WithoutAuthCramMd5Capability_shouldThrow() throws Exception { settings.setAuthType(AuthType.CRAM_MD5); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Server doesn't support encrypted passwords using CRAM-MD5.", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authXoauthWithSaslIr() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("2 OK Success"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authXoauthWithSaslIrThrowsExeptionOn401Response() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("+ " + XOAuth2ChallengeParserTest.STATUS_401_RESPONSE); server.expect(""); server.output("2 NO SASL authentication failed"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail(); } catch (AuthenticationFailedException e) { assertEquals("Command: AUTHENTICATE XOAUTH2; response: #2# [NO, SASL authentication failed]", e.getMessage()); } } @Test public void open_authXoauthWithSaslIrInvalidatesAndRetriesNewTokenOn400Response() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("+ " + XOAuth2ChallengeParserTest.STATUS_400_RESPONSE); server.expect(""); server.output("2 NO SASL authentication failed"); server.expect("3 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING_RETRY); server.output("3 OK Success"); postAuthenticationDialogRequestingCapabilities(server, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authXoauthWithSaslIrInvalidatesAndRetriesNewTokenOnInvalidJsonResponse() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("+ " + XOAuth2ChallengeParserTest.INVALID_RESPONSE); server.expect(""); server.output("2 NO SASL authentication failed"); server.expect("3 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING_RETRY); server.output("3 OK Success"); requestCapabilities(server, 4); simplePostAuthenticationDialog(server, 5); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authXoauthWithSaslIrInvalidatesAndRetriesNewTokenOnMissingStatusJsonResponse() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("+ " + XOAuth2ChallengeParserTest.MISSING_STATUS_RESPONSE); server.expect(""); server.output("2 NO SASL authentication failed"); server.expect("3 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING_RETRY); server.output("3 OK Success"); requestCapabilities(server, 4); simplePostAuthenticationDialog(server, 5); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authXoauthWithSaslIrWithOldTokenThrowsExceptionIfRetryFails() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("+ r3j3krj3irj3oir3ojo"); server.expect(""); server.output("2 NO SASL authentication failed"); server.expect("3 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING_RETRY); server.output("+ 433ba3a3a"); server.expect(""); server.output("3 NO SASL authentication failed"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail(); } catch (AuthenticationFailedException e) { assertEquals("Command: AUTHENTICATE XOAUTH2; response: #3# [NO, SASL authentication failed]", e.getMessage()); } } @Test public void open_authXoauthWithSaslIrParsesCapabilities() throws Exception { settings.setAuthType(AuthType.XOAUTH2); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "SASL-IR AUTH=XOAUTH AUTH=XOAUTH2"); server.expect("2 AUTHENTICATE XOAUTH2 " + XOAUTH_STRING); server.output("2 OK [CAPABILITY IMAP4REV1 IDLE XM-GM-EXT-1]"); simplePostAuthenticationDialog(server, 3); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); assertTrue(imapConnection.hasCapability("XM-GM-EXT-1")); } @Test public void open_authExternal() throws Exception { settings.setAuthType(AuthType.EXTERNAL); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=EXTERNAL"); server.expect("2 AUTHENTICATE EXTERNAL " + ByteString.encodeUtf8(USERNAME).base64()); server.output("2 OK Success"); postAuthenticationDialogRequestingCapabilities(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_authExternalWithAuthenticationFailure_shouldThrow() throws Exception { settings.setAuthType(AuthType.EXTERNAL); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=EXTERNAL"); server.expect("2 AUTHENTICATE EXTERNAL " + ByteString.encodeUtf8(USERNAME).base64()); server.output("2 NO Bad certificate"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (CertificateValidationException e) { //FIXME: improve exception message assertThat(e.getMessage(), containsString("Bad certificate")); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_authExternalWithoutAuthExternalCapability_shouldThrow() throws Exception { settings.setAuthType(AuthType.EXTERNAL); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (CertificateValidationException e) { assertEquals(Reason.MissingCapability, e.getReason()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_withNoPostAuthCapabilityResponse_shouldIssueCapabilityCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 OK Success"); server.expect("3 CAPABILITY"); server.output("* CAPABILITY IDLE"); server.output("3 OK CAPABILITY Completed"); simplePostAuthenticationDialog(server, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); assertTrue(imapConnection.isIdleCapable()); } @Test public void open_withUntaggedPostAuthCapabilityResponse_shouldNotIssueCapabilityCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("* CAPABILITY IMAP4rev1 UNSELECT IDLE QUOTA ID XLIST CHILDREN X-GM-EXT-1 UIDPLUS " + "ENABLE MOVE CONDSTORE ESEARCH UTF8=ACCEPT LIST-EXTENDED LIST-STATUS LITERAL- SPECIAL-USE " + "APPENDLIMIT=35651584"); server.output("2 OK"); simplePostAuthenticationDialog(server, 3); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); assertTrue(imapConnection.isIdleCapable()); } @Test public void open_withPostAuthCapabilityResponse_shouldNotIssueCapabilityCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "AUTH=PLAIN"); server.expect("2 AUTHENTICATE PLAIN"); server.output("+"); server.expect(ByteString.encodeUtf8("\000" + USERNAME + "\000" + PASSWORD).base64()); server.output("2 OK [CAPABILITY IDLE]"); simplePostAuthenticationDialog(server, 3); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); assertTrue(imapConnection.isIdleCapable()); } @Test public void open_withNamespaceCapability_shouldIssueNamespaceCommand() throws Exception { MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, "NAMESPACE"); server.expect("3 NAMESPACE"); server.output("* NAMESPACE ((\"\" \"/\")) NIL NIL"); server.output("3 OK command completed"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withConnectionError_shouldThrow() throws Exception { settings.setHost("127.1.2.3"); settings.setPort(143); ImapConnection imapConnection = createImapConnection( settings, socketFactory, connectivityManager, oAuth2TokenProvider); try { imapConnection.open(); fail("Expected exception"); } catch (MessagingException e) { assertEquals("Cannot connect to host", e.getMessage()); assertTrue(e.getCause() instanceof IOException); } } @Test public void open_withInvalidHostname_shouldThrow() throws Exception { settings.setHost("host name"); settings.setPort(143); ImapConnection imapConnection = createImapConnection( settings, socketFactory, connectivityManager, oAuth2TokenProvider); try { imapConnection.open(); fail("Expected exception"); } catch (UnknownHostException ignored) { } assertFalse(imapConnection.isConnected()); } @Test public void open_withStartTlsCapability_shouldIssueStartTlsCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); settings.setConnectionSecurity(ConnectionSecurity.STARTTLS_REQUIRED); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "STARTTLS LOGINDISABLED"); server.expect("2 STARTTLS"); server.output("2 OK [CAPABILITY IMAP4REV1 NAMESPACE]"); server.startTls(); server.expect("3 CAPABILITY"); server.output("* CAPABILITY IMAP4 IMAP4REV1"); server.output("3 OK"); server.expect("4 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("4 OK [CAPABILITY NAMESPACE] LOGIN completed"); server.expect("5 NAMESPACE"); server.output("* NAMESPACE ((\"\" \"/\")) NIL NIL"); server.output("5 OK command completed"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withStartTlsButWithoutStartTlsCapability_shouldThrow() throws Exception { settings.setConnectionSecurity(ConnectionSecurity.STARTTLS_REQUIRED); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (CertificateValidationException e) { //FIXME: CertificateValidationException seems wrong assertEquals("STARTTLS connection security not available", e.getMessage()); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_withUntaggedCapabilityAfterStartTls_shouldNotThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); settings.setConnectionSecurity(ConnectionSecurity.STARTTLS_REQUIRED); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "STARTTLS LOGINDISABLED"); server.expect("2 STARTTLS"); server.output("2 OK Begin TLS negotiation now"); server.startTls(); server.output("* CAPABILITY IMAP4REV1 IMAP4"); server.expect("3 CAPABILITY"); server.output("* CAPABILITY IMAP4 IMAP4REV1"); server.output("3 OK"); server.expect("4 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("4 OK [CAPABILITY IMAP4REV1] LOGIN completed"); simplePostAuthenticationDialog(server, 5); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withNegativeResponseToStartTlsCommand_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); settings.setConnectionSecurity(ConnectionSecurity.STARTTLS_REQUIRED); MockImapServer server = new MockImapServer(); preAuthenticationDialog(server, "STARTTLS"); server.expect("2 STARTTLS"); server.output("2 NO"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Expected exception"); } catch (NegativeImapResponseException e) { assertEquals(e.getMessage(), "Command: STARTTLS; response: #2# [NO]"); } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_withCompressDeflateCapability_shouldEnableCompression() throws Exception { settings.setUseCompression(true); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, "COMPRESS=DEFLATE"); server.expect("3 COMPRESS DEFLATE"); server.output("3 OK"); server.enableCompression(); simplePostAuthenticationDialog(server, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withNegativeResponseToCompressionCommand_shouldContinue() throws Exception { settings.setAuthType(AuthType.PLAIN); settings.setUseCompression(true); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, "COMPRESS=DEFLATE"); server.expect("3 COMPRESS DEFLATE"); server.output("3 NO"); simplePostAuthenticationDialog(server, 4); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void open_withIoExceptionDuringCompressionCommand_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); settings.setUseCompression(true); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, "COMPRESS=DEFLATE"); server.expect("3 COMPRESS DEFLATE"); server.closeConnection(); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Exception expected"); } catch (IOException ignored) { } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_withIoExceptionDuringListCommand_shouldThrow() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, ""); server.expect("3 LIST \"\" \"\""); server.output("* Now what?"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.open(); fail("Exception expected"); } catch (IOException ignored) { } server.verifyConnectionClosed(); server.verifyInteractionCompleted(); } @Test public void open_withNegativeResponseToListCommand() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); simplePreAuthAndLoginDialog(server, ""); server.expect("3 LIST \"\" \"\""); server.output("3 NO"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void isConnected_withoutPreviousOpen_shouldReturnFalse() throws Exception { ImapConnection imapConnection = createImapConnection( settings, socketFactory, connectivityManager, oAuth2TokenProvider); boolean result = imapConnection.isConnected(); assertFalse(result); } @Test public void isConnected_afterOpen_shouldReturnTrue() throws Exception { MockImapServer server = new MockImapServer(); ImapConnection imapConnection = simpleOpen(server); boolean result = imapConnection.isConnected(); assertTrue(result); server.verifyConnectionStillOpen(); server.shutdown(); } @Test public void isConnected_afterOpenAndClose_shouldReturnFalse() throws Exception { MockImapServer server = new MockImapServer(); ImapConnection imapConnection = simpleOpen(server); imapConnection.close(); boolean result = imapConnection.isConnected(); assertFalse(result); server.verifyConnectionClosed(); server.shutdown(); } @Test public void close_withoutOpen_shouldNotThrow() throws Exception { ImapConnection imapConnection = createImapConnection( settings, socketFactory, connectivityManager, oAuth2TokenProvider); imapConnection.close(); } @Test public void close_afterOpen_shouldCloseConnection() throws Exception { MockImapServer server = new MockImapServer(); ImapConnection imapConnection = simpleOpen(server); imapConnection.close(); server.verifyConnectionClosed(); server.shutdown(); } @Test public void isIdleCapable_withoutIdleCapability() throws Exception { MockImapServer server = new MockImapServer(); ImapConnection imapConnection = simpleOpen(server); boolean result = imapConnection.isIdleCapable(); assertFalse(result); server.shutdown(); } @Test public void isIdleCapable_withIdleCapability() throws Exception { MockImapServer server = new MockImapServer(); ImapConnection imapConnection = simpleOpenWithCapabilities(server, "IDLE"); boolean result = imapConnection.isIdleCapable(); assertTrue(result); server.shutdown(); } @Test public void sendContinuation() throws Exception { settings.setAuthType(AuthType.PLAIN); MockImapServer server = new MockImapServer(); simpleOpenDialog(server, "IDLE"); server.expect("4 IDLE"); server.output("+ idling"); server.expect("DONE"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); imapConnection.sendCommand("IDLE", false); imapConnection.readResponse(); imapConnection.sendContinuation("DONE"); server.waitForInteractionToComplete(); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void executeSingleCommand_withOkResponse_shouldReturnResult() throws Exception { MockImapServer server = new MockImapServer(); simpleOpenDialog(server, ""); server.expect("4 CREATE Folder"); server.output("4 OK Folder created"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); List<ImapResponse> result = imapConnection.executeSimpleCommand("CREATE Folder"); assertEquals(result.size(), 1); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void executeSingleCommand_withNoResponse_shouldThrowNegativeImapResponseException() throws Exception { MockImapServer server = new MockImapServer(); simpleOpenDialog(server, ""); server.expect("4 CREATE Folder"); server.output("4 NO Folder exists"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); try { imapConnection.executeSimpleCommand("CREATE Folder"); fail("Expected exception"); } catch (NegativeImapResponseException e) { assertEquals("Folder exists", e.getLastResponse().getString(1)); } server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } @Test public void hasCapability_withNotYetOpenedConnection_shouldConnectAndFetchCapabilities() throws Exception { MockImapServer server = new MockImapServer(); simpleOpenDialog(server, "X-SOMETHING"); ImapConnection imapConnection = startServerAndCreateImapConnection(server); boolean capabilityPresent = imapConnection.hasCapability("X-SOMETHING"); assertTrue(capabilityPresent); server.verifyConnectionStillOpen(); server.verifyInteractionCompleted(); } private ImapConnection createImapConnection(ImapSettings settings, TrustedSocketFactory socketFactory, ConnectivityManager connectivityManager, OAuth2TokenProvider oAuth2TokenProvider) { return new RealImapConnection(settings, socketFactory, connectivityManager, oAuth2TokenProvider, SOCKET_CONNECT_TIMEOUT, SOCKET_READ_TIMEOUT, 1); } private ImapConnection startServerAndCreateImapConnection(MockImapServer server) throws IOException { server.start(); settings.setHost(server.getHost()); settings.setPort(server.getPort()); return createImapConnection(settings, socketFactory, connectivityManager, oAuth2TokenProvider); } private ImapConnection simpleOpen(MockImapServer server) throws Exception { return simpleOpenWithCapabilities(server, ""); } private ImapConnection simpleOpenWithCapabilities(MockImapServer server, String postAuthCapabilities) throws Exception { simpleOpenDialog(server, postAuthCapabilities); ImapConnection imapConnection = startServerAndCreateImapConnection(server); imapConnection.open(); return imapConnection; } private void preAuthenticationDialog(MockImapServer server) { preAuthenticationDialog(server, ""); } private void preAuthenticationDialog(MockImapServer server, String capabilities) { server.output("* OK IMAP4rev1 Service Ready"); server.expect("1 CAPABILITY"); server.output("* CAPABILITY IMAP4 IMAP4REV1 " + capabilities); server.output("1 OK CAPABILITY"); } private void postAuthenticationDialogRequestingCapabilities(MockImapServer server) { postAuthenticationDialogRequestingCapabilities(server, 3); } private void postAuthenticationDialogRequestingCapabilities(MockImapServer server, int tag) { requestCapabilities(server, tag); simplePostAuthenticationDialog(server, tag + 1); } private void requestCapabilities(MockImapServer server, int tag) { server.expect(tag + " CAPABILITY"); server.output("* CAPABILITY IMAP4 IMAP4REV1 "); server.output(tag + " OK CAPABILITY"); } private void simplePostAuthenticationDialog(MockImapServer server, int tag) { server.expect(tag + " LIST \"\" \"\""); server.output("* LIST () \"/\" foo/bar"); server.output(tag + " OK"); } private void simpleOpenDialog(MockImapServer server, String postAuthCapabilities) { simplePreAuthAndLoginDialog(server, postAuthCapabilities); simplePostAuthenticationDialog(server, 3); } private void simplePreAuthAndLoginDialog(MockImapServer server, String postAuthCapabilities) { settings.setAuthType(AuthType.PLAIN); preAuthenticationDialog(server); server.expect("2 LOGIN \"" + USERNAME + "\" \"" + PASSWORD + "\""); server.output("2 OK [CAPABILITY " + postAuthCapabilities + "] LOGIN completed"); } private OAuth2TokenProvider createOAuth2TokenProvider() { return new OAuth2TokenProvider() { private int invalidationCount = 0; @Override public String getToken(String username, long timeoutMillis) throws AuthenticationFailedException { assertEquals(USERNAME, username); assertEquals(OAUTH2_TIMEOUT, timeoutMillis); switch (invalidationCount) { case 0: { return XOAUTH_TOKEN; } case 1: { return XOAUTH_ANOTHER_TOKEN; } default: { throw new AuthenticationFailedException("Ran out of auth tokens. invalidateToken() called too often?"); } } } @Override public void invalidateToken(String username) { assertEquals(USERNAME, username); invalidationCount++; } @Override public List<String> getAccounts() { throw new UnsupportedOperationException(); } @Override public void authorizeApi(String username, Activity activity, OAuth2TokenProviderAuthCallback callback) { throw new UnsupportedOperationException(); } }; } }
9232ca4af82284034ae9ad91eb80fe98aa12dce8
7,244
java
Java
AndroidLibrary/src/main/java/com/mysaasa/ui/ActivityMain.java
ahammer/MySaasaClient
7f20ba78fdf283c404ca6b7efaf6cf1127785cd6
[ "Apache-2.0" ]
null
null
null
AndroidLibrary/src/main/java/com/mysaasa/ui/ActivityMain.java
ahammer/MySaasaClient
7f20ba78fdf283c404ca6b7efaf6cf1127785cd6
[ "Apache-2.0" ]
null
null
null
AndroidLibrary/src/main/java/com/mysaasa/ui/ActivityMain.java
ahammer/MySaasaClient
7f20ba78fdf283c404ca6b7efaf6cf1127785cd6
[ "Apache-2.0" ]
null
null
null
32.778281
155
0.629625
996,352
package com.mysaasa.ui; import android.app.AlertDialog; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.FrameLayout; import android.widget.ListView; import com.mysaasa.MySaasaApplication; import com.mysaasa.ApplicationSectionsManager; import com.mysaasa.R; import com.mysaasa.api.model.BlogPost; import com.mysaasa.api.model.Category; import com.mysaasa.ui.adapters.BlogAdapter; import com.mysaasa.ui.fragments.EmptyListAdapter; import java.util.List; import de.keyboardsurfer.android.widget.crouton.Crouton; import de.keyboardsurfer.android.widget.crouton.Style; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * This is the launch point for the applicatoin, the root activity. * * There is a sidebar and fragment support in the main panel. Other specialized activities * might be launched from it. It supports top level browsing of the app. * * Created by adam on 2014-10-31. */ public class ActivityMain extends SideNavigationCompatibleActivity { private ListView newsList; private MenuItem post; private FrameLayout fragmentFrame; private MenuItem cart; private Subscription subscription; private List<BlogPost> posts; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isConnected()) { return; } setContentView(R.layout.activity_main); initializeSideNav(); if (getIntent().getSerializableExtra("category") != null) { selectedCategory = (Category) getIntent().getSerializableExtra("category"); } if (savedInstanceState != null && savedInstanceState.get("category") != null) { selectedCategory = (Category) savedInstanceState.getSerializable("category"); } fragmentFrame = (FrameLayout) findViewById(R.id.fragment_frame); newsList = (ListView) findViewById(R.id.content_frame); newsList.setOnItemClickListener((adapterView, view, i, l) -> { Object o = adapterView.getAdapter().getItem(i); if (o instanceof BlogPost) { ActivityBlogPost.startActivity(ActivityMain.this, (BlogPost) o, selectedCategory); } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("category", selectedCategory); } @Override protected void onPause() { if (subscription != null) subscription.unsubscribe(); super.onPause(); } @Override protected void categoryChanged(Category c) { super.selectedCategory = c; updateBlogList(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.standard,menu); post = menu.findItem(R.id.action_post); if (post != null) { post.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { ActivityPostToBlog.postComment(ActivityMain.this, selectedCategory); return true; } }); } updateBlogList(); return super.onCreateOptionsMenu(menu); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (RESULT_OK == resultCode) { updateBlogPostSubscription(); } } @Override public void onBackPressed() { if (isSidenavOpen()){ new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Closing Activity") .setMessage("Are you sure you want to close this activity?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); } }) .setNegativeButton("No", null) .show(); } else { mDrawerLayout.openDrawer(sidenav); } } private void updateBlogPostSubscription() { if (subscription != null) subscription.unsubscribe(); ApplicationSectionsManager.CategoryDef categoryDef = MySaasaApplication.getInstance().getAndroidCategoryManager().getCategoryDef(selectedCategory); subscription = MySaasaApplication.getService() .getBlogManager() .getBlogPostsObservable(getSelectedCategory()) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .toSortedList((blogPost, blogPost2) -> { return Integer.valueOf((int) (blogPost2.id - blogPost.id)); }).subscribe(this::setPosts, this::handleError); } private void handleError(Throwable throwable) { throwable.printStackTrace(); Crouton.makeText(this, throwable.getMessage(), Style.ALERT).show(); } public void setPosts(List<BlogPost> posts) { this.posts = posts; newsList.setAdapter(new BlogAdapter(posts)); } protected void updateBlogList() { if (!isConnected()) return; ApplicationSectionsManager.CategoryDef def = MySaasaApplication.getInstance().getAndroidCategoryManager().getCategoryDef(selectedCategory); setTitle(def.title); if (TextUtils.isEmpty(def.fragment)) { newsList.setVisibility(View.VISIBLE); fragmentFrame.setVisibility(View.GONE); updateBlogPostSubscription(); if (post != null) { post.setVisible(def.postsAllowed); } } else { post.setVisible(false); newsList.setAdapter(new EmptyListAdapter() { @Override protected void Clicked() { } @Override protected String getText() { return "--- No News ---"; } }); fragmentFrame.setVisibility(View.VISIBLE); newsList.setVisibility(View.GONE); try { Fragment f = (Fragment) Class.forName(def.fragment).newInstance(); getFragmentManager().beginTransaction().replace(R.id.fragment_frame, f).commit(); } catch (Exception e) {} } } public static void startFreshTop(Context ctx, Category c) { Intent i = new Intent(ctx,ActivityMain.class); i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.putExtra("category", c); ctx.startActivity(i); } public List<BlogPost> getPosts() { return posts; } }