hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
415b0e2c5a9b7fa0be1459c0cf9fc7a56d411267
5,204
/* * Copyright 2014 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 org.springframework.social.twitter.api.impl; import java.util.List; import org.springframework.social.twitter.api.GeoOperations; import org.springframework.social.twitter.api.Place; import org.springframework.social.twitter.api.PlacePrototype; import org.springframework.social.twitter.api.PlaceType; import org.springframework.social.twitter.api.SimilarPlaces; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.client.RestTemplate; public class GeoTemplate extends AbstractTwitterOperations implements GeoOperations { private final RestTemplate restTemplate; public GeoTemplate(RestTemplate restTemplate, boolean isAuthorizedForUser, boolean isAuthorizedForApp) { super(isAuthorizedForUser, isAuthorizedForApp); this.restTemplate = restTemplate; } public Place getPlace(String placeId) { requireUserAuthorization(); return restTemplate.getForObject(buildUri("geo/id/" + placeId + ".json"), Place.class); } public List<Place> reverseGeoCode(double latitude, double longitude) { return reverseGeoCode(latitude, longitude, null, null); } public List<Place> reverseGeoCode(double latitude, double longitude, PlaceType granularity, String accuracy) { requireUserAuthorization(); MultiValueMap<String, String> parameters = buildGeoParameters(latitude, longitude, granularity, accuracy, null); return restTemplate.getForObject(buildUri("geo/reverse_geocode.json", parameters), PlacesList.class).getList(); } public List<Place> search(double latitude, double longitude) { return search(latitude, longitude, null, null, null); } public List<Place> search(double latitude, double longitude, PlaceType granularity, String accuracy, String query) { requireUserAuthorization(); MultiValueMap<String, String> parameters = buildGeoParameters(latitude, longitude, granularity, accuracy, query); return restTemplate.getForObject(buildUri("geo/search.json", parameters), PlacesList.class).getList(); } public SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name) { return findSimilarPlaces(latitude, longitude, name, null, null); } public SimilarPlaces findSimilarPlaces(double latitude, double longitude, String name, String streetAddress, String containedWithin) { requireUserAuthorization(); MultiValueMap<String, String> parameters = buildPlaceParameters(latitude, longitude, name, streetAddress, containedWithin); SimilarPlacesResponse response = restTemplate.getForObject(buildUri("geo/similar_places.json", parameters), SimilarPlacesResponse.class); PlacePrototype placePrototype = new PlacePrototype(response.getToken(), latitude, longitude, name, streetAddress, containedWithin); return new SimilarPlaces(response.getPlaces(), placePrototype); } public Place createPlace(PlacePrototype placePrototype) { requireUserAuthorization(); MultiValueMap<String, String> request = buildPlaceParameters(placePrototype.getLatitude(), placePrototype.getLongitude(), placePrototype.getName(), placePrototype.getStreetAddress(), placePrototype.getContainedWithin()); request.set("token", placePrototype.getCreateToken()); return restTemplate.postForObject("https://api.twitter.com/1.1/geo/place.json", request, Place.class); } // private helpers private MultiValueMap<String, String> buildGeoParameters(double latitude, double longitude, PlaceType granularity, String accuracy, String query) { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); parameters.set("lat", String.valueOf(latitude)); parameters.set("long", String.valueOf(longitude)); if(granularity != null) { parameters.set("granularity", granularity.equals(PlaceType.POINT_OF_INTEREST) ? "poi" : granularity.toString().toLowerCase()); } if(accuracy != null) { parameters.set("accuracy", accuracy); } if(query != null ) { parameters.set("query", query); } return parameters; } private MultiValueMap<String, String> buildPlaceParameters(double latitude, double longitude, String name, String streetAddress, String containedWithin) { MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>(); parameters.set("lat", String.valueOf(latitude)); parameters.set("long", String.valueOf(longitude)); parameters.set("name", name); if(streetAddress != null) { parameters.set("attribute:street_address", streetAddress); } if(containedWithin != null) { parameters.set("contained_within", containedWithin); } return parameters; } }
45.252174
222
0.780938
4795e85cec510d8a421336a6d9a1f1a03f0aeac0
1,227
package two_pointer; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 2230번: 수 고르기 * * @see https://www.acmicpc.net/problem/2230 * */ public class Boj2230 { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int N = Integer.parseInt(st.nextToken()); int M = Integer.parseInt(st.nextToken()); int[] arr = new int[N]; for(int i = 0; i < N; i++) { arr[i] = Integer.parseInt(br.readLine()); } System.out.println(twoPointer(M, arr)); } private static int twoPointer(int limit, int[] arr) { int min = 2_000_000_001; Arrays.sort(arr); int start = 0, end = 0; while(end < arr.length && start <= end) { int diff = Math.abs(arr[end] - arr[start]); if(diff < limit) { end++; continue; } min = Math.min(min, diff); start++; } return min; } }
23.596154
81
0.559087
58dbc5a177d6fb1f33b86b723871d42d228e9639
1,350
package uk.ac.soton.ecs.comp6237.utils; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.util.List; import jline.TerminalFactory; import org.codehaus.groovy.tools.shell.AnsiDetector; import org.fusesource.jansi.Ansi; import org.fusesource.jansi.AnsiConsole; import org.python.util.InteractiveConsole; public class JythonInterpreter implements Runnable { public InteractiveConsole shell; private PipedInputStream is; private PipedOutputStream os; private PipedInputStream pis; private PipedOutputStream pos; public JythonInterpreter() throws IOException { is = new PipedInputStream(); os = new PipedOutputStream(); pis = new PipedInputStream(os); pos = new PipedOutputStream(is); System.setProperty(TerminalFactory.JLINE_TERMINAL, "none"); AnsiConsole.systemInstall(); Ansi.setDetector(new AnsiDetector()); shell = new InteractiveConsole(); shell.setIn(pis); shell.setOut(pos); shell.setErr(pos); } public PipedInputStream getInputStream() { return is; } public PipedOutputStream getOutputStream() { return os; } @Override public void run() { // shell.r shell.interact(); } public void execute(String script) { shell.exec(script); } public void execute(List<String> script) { for (final String s : script) shell.exec(s); } }
21.774194
61
0.756296
9ff30222af397d429be7d9190522de7fc541c29d
2,266
package datasource; import java.sql.Connection; import java.sql.SQLException; import cache.DataSourceProxy; import cache.Scanner; import db.Database; import db.element.Row; import db.element.Table; import db.exception.MissingPKsException; import db.instance.DatabaseInstance; import db.instance.generic.wrapper.TableWrapper; /** * @author Daniel J. Rivers * 2014 * * Created: Jan 3, 2014, 11:56:04 PM */ public class DBSource implements DataSource { private DatabaseInstance db; private Scanner scan; public DBSource() { scan = new Scanner( DataSourceProxy.getInstance() ); } @Override public void insert( Table t, Row r ) { try { TableWrapper.insertRow( t, r, getConnection() ); } catch ( ClassNotFoundException | SQLException e ) { System.err.println( r.toString() ); e.printStackTrace(); } } @Override public void update( Table t, Row r ) { try { TableWrapper.updateRow( t, r, getConnection() ); } catch ( ClassNotFoundException | SQLException | MissingPKsException e ) { System.err.println( r.toString() ); e.printStackTrace(); } } @Override public void delete( Table t, Row r ) { try { TableWrapper.deleteRow( t, r, getConnection() ); } catch ( ClassNotFoundException | SQLException | MissingPKsException e ) { System.err.println( r.toString() ); e.printStackTrace(); } } @Override public Row get( Table t, Row r ) { Row ret = null; try { ret = TableWrapper.getRow( t, r, getConnection() ); } catch ( ClassNotFoundException | SQLException | MissingPKsException e ) { System.err.println( r.toString() ); e.printStackTrace(); } return ret; } public DatabaseInstance getDatabase() { return db; } public void createDatabase( DatabaseInstance type ) { db = Database.create( type ); } public Connection getConnection() throws ClassNotFoundException, SQLException { return db.getDatabaseWrapper().getConnection(); } public Scanner getScanner() { return scan; } public void startScanner( boolean scanData ) { scan.scanStructure(); if ( scanData ) { scan.scanData(); } } public void stopScanner() { scan.stop(); } }
22.888889
81
0.659312
089f03dfca7fac0d9a45725001434e3fa7ff907f
1,841
package com.chenjie.financial.manager.error; import org.springframework.boot.autoconfigure.web.BasicErrorController; import org.springframework.boot.autoconfigure.web.ErrorAttributes; import org.springframework.boot.autoconfigure.web.ErrorProperties; import org.springframework.boot.autoconfigure.web.ErrorViewResolver; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; /** * @Author chenjie * @Date 2018/9/14 16:59 * @Description: */ public class MyErrorController extends BasicErrorController { public MyErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) { super(errorAttributes, errorProperties, errorViewResolvers); } /*{ x "timestamp": "2018-09-14 17:23:30", x "status": 500, x "error": "Internal Server Error", x "exception": "java.lang.IllegalArgumentException", "message": "编号不可为空", x "path": "/financial/manager/products" +code }*/ @Override protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { Map<String, Object> errorAttributes = super.getErrorAttributes(request, includeStackTrace); errorAttributes.remove("timestamp"); errorAttributes.remove("status"); errorAttributes.remove("error"); errorAttributes.remove("exception"); errorAttributes.remove("path"); String errorCode = (String) errorAttributes.get("message"); ErrorEnum errorEnum = ErrorEnum.getByCode(errorCode); errorAttributes.put("message", errorEnum.getMessage()); errorAttributes.put("code", errorEnum.getCode()); errorAttributes.put("canRetry",errorEnum.isCanRetry()); return errorAttributes; } }
36.82
140
0.719718
8db82103aa38ab5f478bcace148a82d14ca52072
186
/** * */ package com.ctrip.hermes.core.selector; /** * @author marsqing * * Jun 24, 2016 4:51:05 PM */ public interface ExpireTimeHolder { long currentExpireTime(); }
11.625
39
0.61828
f42ac8fc55b9be6f126a06ebff8f8f2de3a125e3
1,361
package ru.szhernovoy.mod;/** * Created by szhernovoy on 15.12.2016. */ import com.mchange.v2.c3p0.ComboPooledDataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.beans.PropertyVetoException; import java.io.FileInputStream; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; public class PoolConnectors { private static Logger log = LoggerFactory.getLogger(PoolConnectors.class); private static ComboPooledDataSource pool; private PoolConnectors(){ } static { Properties prop = new Properties(); pool = new ComboPooledDataSource(); try { prop.load(new FileInputStream(PoolConnectors.class.getClassLoader().getResource("db.properties").getPath())); } catch (IOException e) { e.printStackTrace(); } try { pool.setDriverClass(prop.getProperty("driverClass")); } catch (PropertyVetoException e) { e.printStackTrace(); } pool.setJdbcUrl(prop.getProperty("jdbcUrl")); pool.setUser(prop.getProperty("user")); pool.setPassword(prop.getProperty("password")); pool.setMaxPoolSize(5); } public static Connection getConnection() throws SQLException { return pool.getConnection(); } }
26.686275
121
0.676708
ac8023e1dc61017e8d1bf89ce375b83a7e610761
8,801
package sh.ajo.linkeye.linkeye.services.mysql; import org.springframework.core.env.Environment; import org.springframework.data.domain.*; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import sh.ajo.linkeye.linkeye.dto.AccountUpdateDTO; import sh.ajo.linkeye.linkeye.dto.UserDTO; import sh.ajo.linkeye.linkeye.exception.DuplicateUsernameException; import sh.ajo.linkeye.linkeye.exception.InvalidPasswordException; import sh.ajo.linkeye.linkeye.exception.MismatchedPasswordException; import sh.ajo.linkeye.linkeye.model.AuthorityLevel; import sh.ajo.linkeye.linkeye.model.User; import sh.ajo.linkeye.linkeye.repositories.UserRepository; import sh.ajo.linkeye.linkeye.services.AuthorityService; import sh.ajo.linkeye.linkeye.services.UserService; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.function.Predicate; @Service public class UserServiceImpl implements UserService { private final UserRepository userRepository; private final AuthorityService authorityService; private final Environment environment; private final PasswordEncoder passwordEncoder; public UserServiceImpl(UserRepository userRepository, AuthorityService authorityService, Environment environment, PasswordEncoder passwordEncoder) { this.userRepository = userRepository; this.authorityService = authorityService; this.environment = environment; this.passwordEncoder = passwordEncoder; } @Override public List<User> findPaginated(int pageNo, int pageSize) { Pageable paging = PageRequest.of(pageNo, pageSize); Page<User> pagedResult = userRepository.findAll(paging); return pagedResult.toList(); } @Override public User getOneByUsername(String username) { return userRepository.getOneByUsername(username); } @Override public User getOneById(long userId) { return userRepository.getOneById(userId); } @Override public Optional<User> findOneByUsername(String username) { return userRepository.findOneByUsername(username); } @Override public User updateUser(User user, UserDTO userDTO) throws DuplicateUsernameException { // Do not change the linkeye demo admin account if running in demo mode if (!(user.getUsername().equalsIgnoreCase("linkeye") && Arrays.stream(environment.getActiveProfiles()).anyMatch(Predicate.isEqual("demo")))) { // Do not update to taken usernames if ((!userDTO.getUsername().equals(user.getUsername()) && userRepository.findOneByUsername(userDTO.getUsername()).isPresent())) { throw new DuplicateUsernameException(); } else { user.setUsername(userDTO.getUsername()); } // Do not change the password if blank if (!userDTO.getPassword().isBlank()) { user.setPassword(passwordEncoder.encode(userDTO.getPassword())); } user.setEnabled(userDTO.isEnabled()); if (userDTO.isAdmin()) { userDTO.getAuthorities().add(authorityService.getByAuthority(AuthorityLevel.ADMIN.getAuthorityLevel())); } else { userDTO.getAuthorities().add(authorityService.getByAuthority(AuthorityLevel.USER.getAuthorityLevel())); } user.setAuthorities(new ArrayList<>(userDTO.getAuthorities())); return userRepository.saveAndFlush(user); } // Dont touch the database at all if it's the demo admin is the target return user; } @Override public User createUser(UserDTO userDTO) throws DuplicateUsernameException, InvalidPasswordException { // Do not create users with taken usernames if (userRepository.findOneByUsername(userDTO.getUsername()).isPresent()) { throw new DuplicateUsernameException(); } if (userDTO.isAdmin()) { userDTO.getAuthorities().add(authorityService.getByAuthority(AuthorityLevel.ADMIN.getAuthorityLevel())); } else { userDTO.getAuthorities().add(authorityService.getByAuthority(AuthorityLevel.USER.getAuthorityLevel())); } // Dont allow blank passwords, encrypt valid ones. if (!userDTO.getPassword().isBlank()) { userDTO.setPassword(passwordEncoder.encode(userDTO.getPassword())); } else { throw new InvalidPasswordException(); } return userRepository.saveAndFlush(new User(userDTO)); } @Override // This method is intended to be used in self-serve by users. updateUser should be sued by admin/system. public void changePassword(User user, AccountUpdateDTO accountUpdateDTO) throws InvalidPasswordException, MismatchedPasswordException { // Check if provided current password does not match the actual current password if (!passwordEncoder.matches(accountUpdateDTO.getCurrentPassword(), user.getPassword())){ throw new InvalidPasswordException(); } // Check if either password is blank else if (accountUpdateDTO.getConfirmNewPassword().isBlank() || accountUpdateDTO.getNewPassword().isBlank()) { throw new InvalidPasswordException(); } // Check if provided passwords match else if (!accountUpdateDTO.getNewPassword().equals(accountUpdateDTO.getConfirmNewPassword())){ throw new MismatchedPasswordException(); } else { user.setPassword(passwordEncoder.encode(accountUpdateDTO.getNewPassword())); userRepository.saveAndFlush(user); } } @Override public List<User> findAll() { return userRepository.findAll(); } @Override public List<User> findAll(Sort sort) { return userRepository.findAll(sort); } @Override public Page<User> findAll(Pageable pageable) { return userRepository.findAll(pageable); } @Override public List<User> findAllById(Iterable<Long> iterable) { return userRepository.findAllById(iterable); } @Override public long count() { return userRepository.count(); } @Override public void deleteById(Long aLong) { delete(userRepository.getOneById(aLong)); } @Override public void delete(User user) { // Do not change the linkeye demo admin account if running in demo mode if (!(user.getUsername().equalsIgnoreCase("linkeye") && Arrays.stream(environment.getActiveProfiles()).anyMatch(Predicate.isEqual("demo")))) { userRepository.delete(user); } } @Override public void deleteAll(Iterable<? extends User> iterable) { userRepository.deleteAll(iterable); } @Override public void deleteAll() { userRepository.deleteAll(); } @Override public <S extends User> S save(S s) { return userRepository.save(s); } @Override public <S extends User> List<S> saveAll(Iterable<S> iterable) { return userRepository.saveAll(iterable); } @Override public Optional<User> findById(Long aLong) { return userRepository.findById(aLong); } @Override public boolean existsById(Long aLong) { return userRepository.existsById(aLong); } @Override public void flush() { userRepository.flush(); } @Override public <S extends User> S saveAndFlush(S s) { return userRepository.saveAndFlush(s); } @Override public void deleteInBatch(Iterable<User> iterable) { userRepository.deleteInBatch(iterable); } @Override public void deleteAllInBatch() { userRepository.deleteAllInBatch(); } @Override public User getOne(Long aLong) { return userRepository.getOne(aLong); } @Override public <S extends User> Optional<S> findOne(Example<S> example) { return userRepository.findOne(example); } @Override public <S extends User> List<S> findAll(Example<S> example) { return userRepository.findAll(example); } @Override public <S extends User> List<S> findAll(Example<S> example, Sort sort) { return userRepository.findAll(example, sort); } @Override public <S extends User> Page<S> findAll(Example<S> example, Pageable pageable) { return userRepository.findAll(example, pageable); } @Override public <S extends User> long count(Example<S> example) { return userRepository.count(); } @Override public <S extends User> boolean exists(Example<S> example) { return userRepository.exists(example); } }
32.596296
152
0.681968
5565851d69c9b3d146bf7df166433adbb4f8b54c
598
package io.renren.modules.hotel.dto; import java.math.BigDecimal; import java.util.Date; import lombok.Data; /** * 商家会员 * * @author taoz * */ @Data public class HotelSellerMemberDto { private Long userId; private Long id; private String img; private String nick; private String tel; private String name; private String cardNo; private String levelName; private String certificateNo; private int gender; private String level; private BigDecimal score; private BigDecimal balance; private String salesman; private Date joinTime; private Date createDate; }
11.96
36
0.737458
3de4e9cd62a8acb4e0a743a94268fbd515b4e49c
1,519
package com.spj.demo.pojo; public class PTest { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column p.id * * @mbggenerated */ private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column p.name * * @mbggenerated */ private String name; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column p.id * * @return the value of p.id * * @mbggenerated */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column p.id * * @param id the value for p.id * * @mbggenerated */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column p.name * * @return the value of p.name * * @mbggenerated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column p.name * * @param name the value for p.name * * @mbggenerated */ public void setName(String name) { this.name = name == null ? null : name.trim(); } }
22.671642
66
0.579329
0c5d96a516fefb32c2ba19dc4aaab0d9307a3f26
14,778
/* * Copyright 2020-2021 ADEAL Systems GmbH * * 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.adealsystems.platform.spark.main; import org.adealsystems.platform.id.DataIdentifier; import org.adealsystems.platform.spark.SparkDataProcessingJob; import org.adealsystems.platform.time.TimeHandling; import org.apache.spark.sql.SparkSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.PropertySource; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.TreeMap; import java.util.TreeSet; import java.util.stream.Collectors; import static org.adealsystems.platform.spark.main.SystemProperties.loadPropertiesFrom; import static org.adealsystems.platform.spark.main.SystemProperties.replaceProperty; @SuppressWarnings("PMD.UseUtilityClass") @ComponentScan({"org.adealsystems.platform.spark.config", "org.adealsystems.platform.spark.main"}) @PropertySource("classpath:adeal-platform-git.properties") @PropertySource("classpath:application.properties") @PropertySource(value = "file:application.properties", ignoreResourceNotFound = true) public class Application { private static final Logger LOGGER = LoggerFactory.getLogger(Application.class); private static final String JOB_PREFIX = "--job="; private static final String INVOCATION_DATE_PREFIX = "--invocation-date="; private static final String REMOTE = "--remote"; private static final String DEBUG = "--debug"; private static final String SPRING_PROFILES_ACTIVE_PROPERTY_NAME = "spring.profiles.active"; private static final String PROFILE_REPLACEMENT_PROPERTIES_PATH = "profile-replacement.properties"; public static void main(String[] args) throws IOException { poorMansBootBanner(); poorMansSpringProfileInclude(); ParsedArgs parsedArgs = processArgs(args); if (parsedArgs.isDebug()) { debugProperties(); debugResource("log4j.xml"); debugResource("application.properties"); debugResource("adeal-platform-git.properties"); } //String[] remainingArgs = parsedArgs.getRemaining().toArray(new String[]{}); DataIdentifier job = parsedArgs.getJob(); try (ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext(Application.class)) { Map<String, SparkDataProcessingJob> beans = applicationContext.getBeansOfType(SparkDataProcessingJob.class); Map<DataIdentifier, SparkDataProcessingJob> jobs = processJobs(beans); if (jobs.isEmpty()) { LOGGER.warn("Could not find any jobs of type SparkDataProcessingJob!"); return; } if (jobs.size() == 1 && job == null) { job = jobs.keySet().stream().findFirst().get(); } boolean unrecognized = false; if (job == null) { LOGGER.warn("No job specified with --job=output_identifier!"); unrecognized = true; } else { if (!jobs.containsKey(job)) { LOGGER.warn("Unrecognized job: {}", job); unrecognized = true; } } if (unrecognized) { Set<DataIdentifier> validJobs = new TreeSet<>(jobs.keySet()); StringBuilder builder = new StringBuilder(); for (DataIdentifier currentJob : validJobs) { if (builder.length() != 0) { builder.append('\n'); } builder.append("--job=").append(currentJob); } LOGGER.warn("\nValid jobs:\n{}", builder); return; } SparkSession.Builder sparkSessionBuilder = applicationContext.getBean(SparkSession.Builder.class) .appName("ADEAL-Systems-Batch"); SparkDataProcessingJob currentJob = null; // NOPMD try (SparkSession sparkSession = sparkSessionBuilder.getOrCreate()) { try (SparkDataProcessingJob sparkJob = jobs.get(job)) { currentJob = sparkJob; processJob(sparkJob, sparkSession); } catch (Exception ex) { LOGGER.warn("Exception while processing {}!", job, ex); } } // finalizing the job if (currentJob != null) { currentJob.finalizeJob(); } } } @SuppressWarnings({"PMD.AvoidInstantiatingObjectsInLoops", "PMD.SystemPrintln"}) private static void debugProperties() { Properties props = System.getProperties(); Map<String, String> foo = new TreeMap<>(); String pathSeparator = props.getProperty("path.separator"); for (Map.Entry<Object, Object> current : props.entrySet()) { foo.put(String.valueOf(current.getKey()), String.valueOf(current.getValue())); } StringBuilder builder = new StringBuilder("System.getProperties():"); Set<String> paths = new HashSet<>(); paths.add("java.class.path"); paths.add("java.endorsed.dirs"); paths.add("java.ext.dirs"); paths.add("java.library.path"); paths.add("sun.boot.class.path"); paths.add("sun.boot.library.path"); paths.add("spark.driver.extraClassPath"); paths.add("spark.executor.extraClassPath"); for (Map.Entry<String, String> current : foo.entrySet()) { String key = current.getKey(); String value = current.getValue(); if ("line.separator".equals(key)) { value = value.replace("\r", "\\r"); value = value.replace("\n", "\\n"); } else if (paths.contains(key)) { StringTokenizer tok = new StringTokenizer(value, pathSeparator); Set<String> entries = new TreeSet<>(); while (tok.hasMoreTokens()) { entries.add(tok.nextToken()); } StringBuilder cpBuilder = new StringBuilder(); for (String entry : entries) { if (cpBuilder.length() != 0) { cpBuilder.append("\n\t"); } cpBuilder.append("- ").append(entry); } value = cpBuilder.toString(); } builder.append("\n- ").append(key).append(":\n\t").append(value); } System.err.println(builder); } @SuppressWarnings({"PMD.SystemPrintln", "PMD.AvoidPrintStackTrace"}) private static void debugResource(String path) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); try { Set<String> found = new TreeSet<>(); Enumeration<URL> resources = classLoader.getResources(path); while (resources.hasMoreElements()) { found.add(String.valueOf(resources.nextElement())); } StringBuilder builder = new StringBuilder(200); int count = found.size(); builder.append("\nFound ").append(count).append(" resource"); if (count > 1) { builder.append('s'); } builder.append(" for \"").append(path).append('"'); if (count == 0) { builder.append('.'); } else { builder.append(':'); for (String current : found) { builder.append("\n- ").append(current); } } System.err.println(builder); } catch (IOException e) { e.printStackTrace(); } } private static void processJob(SparkDataProcessingJob sparkJob, SparkSession sparkSession) { if (LOGGER.isInfoEnabled()) LOGGER.info("\n\n## Starting batch job {}...\n#### Class : {}", sparkJob.getOutputIdentifiers(), sparkJob.getClass()); sparkJob.init(sparkSession); // no, sparkSession.newSession() does not help. m( if (LOGGER.isInfoEnabled()) { StringBuilder builder = new StringBuilder(); builder.append("\n###### Inputs:"); sparkJob.getInputInstances().keySet().stream() .map(DataIdentifier::toString) .sorted() .forEach(it -> builder.append("\n###### - ").append(it)); LOGGER.info(builder.toString()); } sparkJob.execute(); if (LOGGER.isInfoEnabled()) LOGGER.info("\n## Finished batch job {}", sparkJob.getOutputIdentifiers()); } private static ParsedArgs processArgs(String[] args) { // TODO: use something else to parse arguments // the problem is that most tooling expects arguments to // be parsed from start to finish. // We, on the other hand, would like to parse *some* arguments // right here while propagating the remaining "unused" arguments // to spring-boot... List<String> remaining = new ArrayList<>(); DataIdentifier job = null; boolean debug = false; for (String current : args) { if (REMOTE.equals(current)) { System.setProperty("spring.profiles.active", "remote"); continue; } if (DEBUG.equals(current)) { debug = true; continue; } if (current.startsWith(JOB_PREFIX)) { String jobString = current.substring(JOB_PREFIX.length()); job = DataIdentifier.fromString(jobString); continue; } if (current.startsWith(INVOCATION_DATE_PREFIX)) { String dateString = current.substring(INVOCATION_DATE_PREFIX.length()); LocalDate parsed = LocalDate.parse(dateString, TimeHandling.YYYY_DASH_MM_DASH_DD_DATE_FORMATTER); System.setProperty("invocation.date", parsed.toString()); continue; } LOGGER.warn("Remaining: {}", current); remaining.add(current); } return new ParsedArgs(job, debug, remaining); } @SuppressWarnings("PMD.CloseResource") private static Map<DataIdentifier, SparkDataProcessingJob> processJobs(Map<String, SparkDataProcessingJob> jobs) { Objects.requireNonNull(jobs, "jobs must not be null!"); Map<DataIdentifier, SparkDataProcessingJob> result = new HashMap<>(); for (Map.Entry<String, SparkDataProcessingJob> entry : jobs.entrySet()) { SparkDataProcessingJob value = entry.getValue(); Set<DataIdentifier> outputIdentifiers = value.getOutputIdentifiers(); if (outputIdentifiers == null || outputIdentifiers.isEmpty()) { LOGGER.warn("Found a processing job {} without any output data identifier configured!", value); continue; } for (DataIdentifier outputIdentifier : outputIdentifiers) { SparkDataProcessingJob previous = result.put(outputIdentifier, value); if (previous != null) { throw new IllegalStateException("Duplicate entries for " + outputIdentifier + "! previous: " + previous.getClass() + ", current: " + value.getClass()); } } } return result; } private static void poorMansSpringProfileInclude() { replaceProperty(SPRING_PROFILES_ACTIVE_PROPERTY_NAME, PROFILE_REPLACEMENT_PROPERTIES_PATH); } @SuppressWarnings("PMD.SystemPrintln") private static void poorMansBootBanner() throws IOException { ClassLoader cl = Thread.currentThread().getContextClassLoader(); String text; try (InputStream is = cl.getResourceAsStream("banner.txt")) { if (is == null) { throw new IllegalStateException("Failed to load banner.txt!"); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) { text = reader.lines().collect(Collectors.joining("\n")); } } Properties bannerProperties = createBannerProperties(); for (String key : bannerProperties.stringPropertyNames()) { String value = bannerProperties.getProperty(key); if (value == null) { continue; } text = text.replace("${" + key + "}", value); } System.out.println(text); } private static Properties createBannerProperties() throws IOException { Properties props = new Properties(); loadPropertiesFrom(props, "adeal-platform-git.properties"); boolean dirty = Boolean.parseBoolean(props.getProperty("git.dirty")); props.setProperty("git.dirty.text", dirty ? " (dirty)" : ""); LOGGER.debug("Default-Properties: {}", props); return props; } private static class ParsedArgs { private final DataIdentifier job; private final List<String> remaining; private final boolean debug; ParsedArgs(DataIdentifier job, boolean debug, List<String> remaining) { this.job = job; this.remaining = remaining; this.debug = debug; } public DataIdentifier getJob() { return job; } public List<String> getRemaining() { return remaining; } public boolean isDebug() { return debug; } } }
40.487671
172
0.608743
3a4deab6d538e1296b1aacd78c59ab8a98e05c3d
695
package remote.ct.process; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import remote.ct.ssh.SshConnection; public class ProcessGitCommand implements Process { private static final Logger logger = LoggerFactory.getLogger(ProcessGitCommand.class); @Override public void execute(SshConnection sshConnection) { String execLine2 = "git --version\n"; try { sshConnection.open(); String result2 = sshConnection.executeCommand(execLine2); logger.debug(result2); logger.debug("[" + result2.length() + " bytes]"); } catch (Exception e) { e.printStackTrace(); } } @Override public String getLog() { // TODO Auto-generated method stub return null; } }
21.060606
87
0.726619
309ce34dc87a6df3ad72385c56c5a289ed639bd6
40,775
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.frameworkperf; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.lang.String; import java.util.HashMap; import java.util.Random; import android.util.ArrayMap; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.TypedArray; import android.content.res.XmlResourceParser; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.os.Bundle; import android.os.FileUtils; import android.os.Handler; import android.os.IBinder; import android.os.Looper; import android.os.Message; import android.os.Messenger; import android.os.Process; import android.os.RemoteException; import android.os.SystemClock; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.util.Log; import android.util.Xml; import android.view.LayoutInflater; public class TestService extends Service { static final String TAG = "Perf"; final static Op[] mOpPairs = new Op[] { new MethodCallOp(), new NoOp(), new MethodCallOp(), new CpuOp(), new MethodCallOp(), new SchedulerOp(), new MethodCallOp(), new GcOp(), new MethodCallOp(), new CreateFileOp(), new MethodCallOp(), new CreateWriteFileOp(), new MethodCallOp(), new CreateWriteSyncFileOp(), new MethodCallOp(), new WriteFileOp(), new MethodCallOp(), new ReadFileOp(), new SchedulerOp(), new SchedulerOp(), new GcOp(), new NoOp(), new ObjectGcOp(), new NoOp(), new FinalizingGcOp(), new NoOp(), new PaintGcOp(), new NoOp(), new IpcOp(), new NoOp(), new IpcOp(), new CpuOp(), new IpcOp(), new SchedulerOp(), new IpcOp(), new GcOp(), new IpcOp(), new CreateFileOp(), new IpcOp(), new CreateWriteFileOp(), new IpcOp(), new CreateWriteSyncFileOp(), new IpcOp(), new WriteFileOp(), new IpcOp(), new ReadFileOp(), new CreateFileOp(), new NoOp(), new CreateWriteFileOp(), new NoOp(), new CreateWriteSyncFileOp(), new NoOp(), new WriteFileOp(), new NoOp(), new ReadFileOp(), new NoOp(), new WriteFileOp(), new CreateWriteFileOp(), new ReadFileOp(), new CreateWriteFileOp(), new WriteFileOp(), new CreateWriteSyncFileOp(), new ReadFileOp(), new CreateWriteSyncFileOp(), new WriteFileOp(), new WriteFileOp(), new WriteFileOp(), new ReadFileOp(), new ReadFileOp(), new WriteFileOp(), new ReadFileOp(), new ReadFileOp(), new OpenXmlResOp(), new NoOp(), new ReadXmlAttrsOp(), new NoOp(), new ParseXmlResOp(), new NoOp(), new ParseLargeXmlResOp(), new NoOp(), new LayoutInflaterOp(), new NoOp(), new LayoutInflaterLargeOp(), new NoOp(), new LayoutInflaterViewOp(), new NoOp(), new LayoutInflaterButtonOp(), new NoOp(), new LayoutInflaterImageButtonOp(), new NoOp(), new CreateBitmapOp(), new NoOp(), new CreateRecycleBitmapOp(), new NoOp(), new LoadSmallBitmapOp(), new NoOp(), new LoadRecycleSmallBitmapOp(), new NoOp(), new LoadLargeBitmapOp(), new NoOp(), new LoadRecycleLargeBitmapOp(), new NoOp(), new LoadSmallScaledBitmapOp(), new NoOp(), new LoadLargeScaledBitmapOp(), new NoOp(), }; final static Op[] mAvailOps = new Op[] { null, new NoOp(), new CpuOp(), new SchedulerOp(), new MethodCallOp(), new GcOp(), new ObjectGcOp(), new FinalizingGcOp(), new PaintGcOp(), new IpcOp(), new CreateFileOp(), new CreateWriteFileOp(), new CreateWriteSyncFileOp(), new WriteFileOp(), new ReadFileOp(), new OpenXmlResOp(), new ReadXmlAttrsOp(), new ParseXmlResOp(), new ParseLargeXmlResOp(), new LayoutInflaterOp(), new LayoutInflaterLargeOp(), new LayoutInflaterViewOp(), new LayoutInflaterButtonOp(), new LayoutInflaterImageButtonOp(), new CreateBitmapOp(), new CreateRecycleBitmapOp(), new LoadSmallBitmapOp(), new LoadRecycleSmallBitmapOp(), new LoadLargeBitmapOp(), new LoadRecycleLargeBitmapOp(), new LoadSmallScaledBitmapOp(), new LoadLargeScaledBitmapOp(), new GrowTinyHashMapOp(), new GrowTinyArrayMapOp(), new GrowSmallHashMapOp(), new GrowSmallArrayMapOp(), new GrowLargeHashMapOp(), new GrowLargeArrayMapOp(), new LookupTinyHashMapOp(), new LookupTinyArrayMapOp(), new LookupSmallHashMapOp(), new LookupSmallArrayMapOp(), new LookupLargeHashMapOp(), new LookupLargeArrayMapOp(), }; static final int CMD_START_TEST = 1; static final int CMD_TERMINATE = 2; static final int MSG_REALLY_START = 1000; static final int MSG_REALLY_TERMINATE = 1001; static final int RES_TEST_FINISHED = 1; static final int RES_TERMINATED = 2; final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case CMD_START_TEST: { // Give a little time for things to settle down. Message newMsg = Message.obtain(null, MSG_REALLY_START); newMsg.obj = msg.obj; newMsg.replyTo = msg.replyTo; sendMessageDelayed(newMsg, 500); } break; case MSG_REALLY_START: { Bundle bundle = (Bundle)msg.obj; bundle.setClassLoader(getClassLoader()); final TestArgs args = (TestArgs)bundle.getParcelable("args"); final Messenger replyTo = msg.replyTo; mRunner.run(this, args, new Runnable() { @Override public void run() { if (replyTo != null) { Message msg = Message.obtain(null, RES_TEST_FINISHED); Bundle bundle = new Bundle(); bundle.putParcelable("res", new RunResult(mRunner)); msg.obj = bundle; try { replyTo.send(msg); } catch (RemoteException e) { } } } }); } break; case CMD_TERMINATE: { // Give a little time for things to settle down. Message newMsg = Message.obtain(null, MSG_REALLY_TERMINATE); newMsg.obj = msg.obj; newMsg.replyTo = msg.replyTo; sendMessageDelayed(newMsg, 50); } break; case MSG_REALLY_TERMINATE: { if (msg.replyTo != null) { Message reply = Message.obtain(null, RES_TERMINATED); try { msg.replyTo.send(reply); } catch (RemoteException e) { } } terminate(); } break; } } }; final TestRunner mRunner = new TestRunner(); @Override public IBinder onBind(Intent intent) { return (new Messenger(mHandler)).getBinder(); } void terminate() { Runtime.getRuntime().exit(0); } enum BackgroundMode { NOTHING, CPU, SCHEDULER }; public class TestRunner { Handler mHandler; long mMaxRunTime; long mMaxOps; Op mForegroundOp; Op mBackgroundOp; Runnable mDoneCallback; RunnerThread mBackgroundThread; RunnerThread mForegroundThread; long mStartTime; boolean mBackgroundRunning; boolean mForegroundRunning; long mBackgroundEndTime; long mBackgroundOps; long mForegroundEndTime; long mForegroundOps; public TestRunner() { } public String getForegroundName() { return mForegroundOp.getName(); } public String getBackgroundName() { return mBackgroundOp.getName(); } public String getName() { String fgName = mForegroundOp.getName(); String bgName = mBackgroundOp.getName(); StringBuilder res = new StringBuilder(); if (fgName != null) { res.append(fgName); res.append("Fg"); } if (bgName != null) { res.append(bgName); res.append("Bg"); } return res.toString(); } public String getForegroundLongName() { return mForegroundOp.getLongName(); } public String getBackgroundLongName() { return mBackgroundOp.getLongName(); } public void run(Handler handler, TestArgs args, Runnable doneCallback) { mHandler = handler; mMaxRunTime = args.maxTime; mMaxOps = args.maxOps; if (args.combOp >= 0) { mForegroundOp = mOpPairs[args.combOp]; mBackgroundOp = mOpPairs[args.combOp+1]; } else { mForegroundOp = mAvailOps[args.fgOp]; mBackgroundOp = mAvailOps[args.bgOp]; } mDoneCallback = doneCallback; mBackgroundThread = new RunnerThread("background", new Runnable() { @Override public void run() { boolean running; int ops = 0; do { running = mBackgroundOp.onRun(); ops++; } while (evalRepeat(running, true) && running); mBackgroundEndTime = SystemClock.uptimeMillis(); mBackgroundOps = ops * mBackgroundOp.getOpsPerRun(); threadFinished(false); } }, Process.THREAD_PRIORITY_BACKGROUND); mForegroundThread = new RunnerThread("foreground", new Runnable() { @Override public void run() { boolean running; int ops = 0; do { running = mForegroundOp.onRun(); ops++; } while (evalRepeat(true, running) && running); mForegroundEndTime = SystemClock.uptimeMillis(); mForegroundOps = ops * mForegroundOp.getOpsPerRun(); threadFinished(true); } }, Process.THREAD_PRIORITY_FOREGROUND); mForegroundOp.onInit(TestService.this, true); mBackgroundOp.onInit(TestService.this, false); synchronized (this) { mStartTime = SystemClock.uptimeMillis(); mBackgroundRunning = true; mForegroundRunning = true; } mBackgroundThread.start(); mForegroundThread.start(); } public long getForegroundTime() { return mForegroundEndTime-mStartTime; } public long getForegroundOps() { return mForegroundOps; } public long getBackgroundTime() { return mBackgroundEndTime-mStartTime; } public long getBackgroundOps() { return mBackgroundOps; } private boolean evalRepeat(boolean bgRunning, boolean fgRunning) { synchronized (this) { if (!bgRunning) { mBackgroundRunning = false; } if (!fgRunning) { mForegroundRunning = false; } if (!mBackgroundRunning && !mForegroundRunning) { return false; } if (mMaxOps > 0) { // iteration-limited case if (mForegroundOps >= mMaxOps) { return false; } mForegroundOps++; } else { // time-limited case long now = SystemClock.uptimeMillis(); if (now > (mStartTime+mMaxRunTime)) { return false; } } return true; } } private void threadFinished(boolean foreground) { synchronized (this) { if (foreground) { mForegroundRunning = false; } else { mBackgroundRunning = false; } if (!mBackgroundRunning && !mForegroundRunning) { mHandler.post(new Runnable() { @Override public void run() { mForegroundOp.onTerm(TestService.this); mBackgroundOp.onTerm(TestService.this); if (mDoneCallback != null) { mDoneCallback.run(); } } }); } } } } class RunnerThread extends Thread { private final Runnable mOp; private final int mPriority; RunnerThread(String name, Runnable op, int priority) { super(name); mOp = op; mPriority = priority; } public void run() { Process.setThreadPriority(mPriority); mOp.run(); } } static public abstract class Op { final String mName; final String mLongName; public Op(String name, String longName) { mName = name; mLongName = longName; } public String getName() { return mName; } public String getLongName() { return mLongName; } void onInit(Context context, boolean foreground) { } abstract boolean onRun(); void onTerm(Context context) { } int getOpsPerRun() { return 1; } } static class NoOp extends Op { NoOp() { super(null, "Nothing"); } boolean onRun() { return false; } int getOpsPerRun() { return 0; } } static class CpuOp extends Op { CpuOp() { super("CPU", "Consume CPU"); } boolean onRun() { return true; } } static class SchedulerOp extends Op { SchedulerOp() { super("Sched", "Change scheduler group"); } boolean onRun() { Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND); Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); return true; } } static class GcOp extends Op { GcOp() { super("Gc", "Run garbage collector"); } boolean onRun() { byte[] stuff = new byte[1024*1024]; return true; } } static class ObjectGcOp extends Op { ObjectGcOp() { super("ObjectGc", "Run garbage collector with simple objects"); } boolean onRun() { Object obj = new Object(); return true; } } static class FinalizingGcOp extends Op { class Finalizable { Finalizable() {} @Override protected void finalize() throws Throwable { super.finalize(); } } FinalizingGcOp() { super("FinalizingGc", "Run garbage collector with finalizable objects"); } boolean onRun() { Finalizable obj = new Finalizable(); return true; } } static class PaintGcOp extends Op { PaintGcOp() { super("PaintGc", "Run garbage collector with Paint objects"); } boolean onRun() { Paint p = new Paint(); return true; } } static class MethodCallOp extends Op { MethodCallOp() { super("MethodCall", "Method call"); } boolean onRun() { final int N = getOpsPerRun(); for (int i=0; i<N; i++) { someFunc(i); } return true; } int someFunc(int foo) { return 0; } int getOpsPerRun() { return 500; } } static class IpcOp extends Op { PackageManager mPm; String mProcessName; IpcOp() { super("Ipc", "IPC to system process"); } void onInit(Context context, boolean foreground) { mPm = context.getPackageManager(); mProcessName = context.getApplicationInfo().processName; } boolean onRun() { final int N = getOpsPerRun(); for (int i=0; i<N; i++) { mPm.queryContentProviders(mProcessName, Process.myUid(), 0); } return true; } int getOpsPerRun() { return 100; } } static class OpenXmlResOp extends Op { Context mContext; OpenXmlResOp() { super("OpenXmlRes", "Open (and close) an XML resource"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { XmlResourceParser parser = mContext.getResources().getLayout(R.xml.simple); parser.close(); return true; } } static class ReadXmlAttrsOp extends Op { Context mContext; XmlResourceParser mParser; AttributeSet mAttrs; ReadXmlAttrsOp() { super("ReadXmlAttrs", "Read attributes from an XML tag"); } void onInit(Context context, boolean foreground) { mContext = context; mParser = mContext.getResources().getLayout(R.xml.simple); mAttrs = Xml.asAttributeSet(mParser); int eventType; try { // Find the first <item> tag. eventType = mParser.getEventType(); String tagName; do { if (eventType == XmlPullParser.START_TAG) { tagName = mParser.getName(); if (tagName.equals("item")) { break; } } eventType = mParser.next(); } while (eventType != XmlPullParser.END_DOCUMENT); } catch (XmlPullParserException e) { throw new RuntimeException("I died", e); } catch (IOException e) { throw new RuntimeException("I died", e); } } void onTerm(Context context) { mParser.close(); } boolean onRun() { TypedArray a = mContext.obtainStyledAttributes(mAttrs, com.android.internal.R.styleable.MenuItem); a.recycle(); return true; } } static class ParseXmlResOp extends Op { Context mContext; ParseXmlResOp() { super("ParseXmlRes", "Parse compiled XML resource"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { SimpleInflater inf = new SimpleInflater(mContext); inf.inflate(R.xml.simple); return true; } } static class ParseLargeXmlResOp extends Op { Context mContext; ParseLargeXmlResOp() { super("ParseLargeXmlRes", "Parse large XML resource"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { SimpleInflater inf = new SimpleInflater(mContext); inf.inflate(R.xml.simple_large); return true; } } static class LayoutInflaterOp extends Op { Context mContext; LayoutInflaterOp() { super("LayoutInflater", "Inflate layout resource"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { if (Looper.myLooper() == null) { Looper.prepare(); } LayoutInflater inf = (LayoutInflater)mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inf.inflate(R.layout.small_layout, null); return true; } } static class LayoutInflaterLargeOp extends Op { Context mContext; LayoutInflaterLargeOp() { super("LayoutInflaterLarge", "Inflate large layout resource"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { if (Looper.myLooper() == null) { Looper.prepare(); } LayoutInflater inf = (LayoutInflater)mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inf.inflate(R.layout.large_layout, null); return true; } } static class LayoutInflaterViewOp extends Op { Context mContext; LayoutInflaterViewOp() { super("LayoutInflaterView", "Inflate layout with 50 View objects"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { if (Looper.myLooper() == null) { Looper.prepare(); } LayoutInflater inf = (LayoutInflater)mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inf.inflate(R.layout.view_layout, null); return true; } } static class LayoutInflaterButtonOp extends Op { Context mContext; LayoutInflaterButtonOp() { super("LayoutInflaterButton", "Inflate layout with 50 Button objects"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { if (Looper.myLooper() == null) { Looper.prepare(); } LayoutInflater inf = (LayoutInflater)mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inf.inflate(R.layout.button_layout, null); return true; } } static class LayoutInflaterImageButtonOp extends Op { Context mContext; LayoutInflaterImageButtonOp() { super("LayoutInflaterImageButton", "Inflate layout with 50 ImageButton objects"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { if (Looper.myLooper() == null) { Looper.prepare(); } LayoutInflater inf = (LayoutInflater)mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE); inf.inflate(R.layout.image_button_layout, null); return true; } } static class CreateBitmapOp extends Op { Context mContext; CreateBitmapOp() { super("CreateBitmap", "Create a Bitmap"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888); return true; } } static class CreateRecycleBitmapOp extends Op { Context mContext; CreateRecycleBitmapOp() { super("CreateRecycleBitmap", "Create and recycle a Bitmap"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = Bitmap.createBitmap(16, 16, Bitmap.Config.ARGB_8888); bm.recycle(); return true; } } static class LoadSmallBitmapOp extends Op { Context mContext; LoadSmallBitmapOp() { super("LoadSmallBitmap", "Load small raw bitmap"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.stat_sample, opts); return true; } } static class LoadRecycleSmallBitmapOp extends Op { Context mContext; LoadRecycleSmallBitmapOp() { super("LoadRecycleSmallBitmap", "Load and recycle small raw bitmap"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.stat_sample, opts); bm.recycle(); return true; } } static class LoadLargeBitmapOp extends Op { Context mContext; LoadLargeBitmapOp() { super("LoadLargeBitmap", "Load large raw bitmap"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wallpaper_goldengate, opts); return true; } } static class LoadRecycleLargeBitmapOp extends Op { Context mContext; LoadRecycleLargeBitmapOp() { super("LoadRecycleLargeBitmap", "Load and recycle large raw bitmap"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wallpaper_goldengate, opts); bm.recycle(); return true; } } static class LoadSmallScaledBitmapOp extends Op { Context mContext; LoadSmallScaledBitmapOp() { super("LoadSmallScaledBitmap", "Load small raw bitmap that is scaled for density"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.stat_sample_scale, opts); return true; } } static class LoadLargeScaledBitmapOp extends Op { Context mContext; LoadLargeScaledBitmapOp() { super("LoadLargeScaledBitmap", "Load large raw bitmap that is scaled for density"); } void onInit(Context context, boolean foreground) { mContext = context; } boolean onRun() { BitmapFactory.Options opts = new BitmapFactory.Options(); opts.inScreenDensity = DisplayMetrics.DENSITY_DEVICE; Bitmap bm = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.wallpaper_goldengate_scale, opts); return true; } } static class CreateFileOp extends Op { File mFile; CreateFileOp() { super("CreateFile", "Create and delete a file"); } void onInit(Context context, boolean foreground) { mFile = context.getFileStreamPath(foreground ? "test-fg.file" : "test-bg.file"); mFile.delete(); } boolean onRun() { try { mFile.createNewFile(); } catch (IOException e) { Log.w(TAG, "Failure creating " + mFile, e); } mFile.delete(); return true; } } static class CreateWriteFileOp extends Op { File mFile; CreateWriteFileOp() { super("CreateWriteFile", "Create, write, and delete a file"); } void onInit(Context context, boolean foreground) { mFile = context.getFileStreamPath(foreground ? "test-fg.file" : "test-bg.file"); mFile.delete(); } boolean onRun() { try { FileOutputStream fos = new FileOutputStream(mFile); fos.write(1); fos.close(); } catch (IOException e) { Log.w(TAG, "Failure creating " + mFile, e); } mFile.delete(); return true; } } static class CreateWriteSyncFileOp extends Op { File mFile; CreateWriteSyncFileOp() { super("CreateWriteSyncFile", "Create, write, sync, and delete a file"); } void onInit(Context context, boolean foreground) { mFile = context.getFileStreamPath(foreground ? "test-fg.file" : "test-bg.file"); mFile.delete(); } boolean onRun() { try { FileOutputStream fos = new FileOutputStream(mFile); fos.write(1); fos.flush(); FileUtils.sync(fos); fos.close(); } catch (IOException e) { Log.w(TAG, "Failure creating " + mFile, e); } mFile.delete(); return true; } } static class WriteFileOp extends Op { File mFile; RandomAccessFile mRAF; byte[] mBuffer; WriteFileOp() { super("WriteFile", "Truncate and write a 64k file"); } void onInit(Context context, boolean foreground) { mBuffer = new byte[1024*64]; for (int i=0; i<mBuffer.length; i++) { mBuffer[i] = (byte)i; } mFile = context.getFileStreamPath(foreground ? "test-fg.file" : "test-bg.file"); mFile.delete(); try { mRAF = new RandomAccessFile(mFile, "rw"); } catch (FileNotFoundException e) { Log.w(TAG, "Failure creating " + mFile, e); } } boolean onRun() { try { mRAF.seek(0); mRAF.setLength(0); mRAF.write(mBuffer); } catch (IOException e) { Log.w(TAG, "Failure writing " + mFile, e); } return true; } void onTerm(Context context) { try { mRAF.close(); } catch (IOException e) { Log.w(TAG, "Failure closing " + mFile, e); } mFile.delete(); } } static class ReadFileOp extends Op { File mFile; RandomAccessFile mRAF; byte[] mBuffer; ReadFileOp() { super("ReadFile", "Seek and read a 64k file"); } void onInit(Context context, boolean foreground) { mBuffer = new byte[1024*64]; for (int i=0; i<mBuffer.length; i++) { mBuffer[i] = (byte)i; } mFile = context.getFileStreamPath(foreground ? "test-fg.file" : "test-bg.file"); mFile.delete(); try { mRAF = new RandomAccessFile(mFile, "rw"); mRAF.seek(0); mRAF.setLength(0); mRAF.write(mBuffer); } catch (IOException e) { Log.w(TAG, "Failure creating " + mFile, e); } } boolean onRun() { try { mRAF.seek(0); mRAF.read(mBuffer); } catch (IOException e) { Log.w(TAG, "Failure reading " + mFile, e); } return true; } void onTerm(Context context) { try { mRAF.close(); } catch (IOException e) { Log.w(TAG, "Failure closing " + mFile, e); } mFile.delete(); } } static abstract class GenericMapOp extends Op { final int mSize; String[] mKeys; String[] mValues; GenericMapOp(String name, String longName, int size) { super(name, longName); mSize = size; } void onInit(Context context, boolean foreground) { mKeys = new String[mSize]; mValues = new String[mSize]; Random random = new Random(0); for (int i=0; i<mSize; i++) { int chars = random.nextInt(10); StringBuilder builder = new StringBuilder(chars); for (int j=0; j<chars; j++) { builder.append('a' + random.nextInt(100)); } mKeys[i] = builder.toString(); mValues[i] = Integer.toString(i); } } int getOpsPerRun() { return mSize; } } static class GrowTinyHashMapOp extends GenericMapOp { GrowTinyHashMapOp() { super("GrowTinyHashMap", "Add 5 items to a HashMap", 5); } boolean onRun() { HashMap<String, String> map = new HashMap<String, String>(); for (int i=0; i<mSize; i++) { map.put(mKeys[i], mValues[i]); } return true; } } static class GrowTinyArrayMapOp extends GenericMapOp { GrowTinyArrayMapOp() { super("GrowTinyArrayMap", "Add 5 items to a ArrayMap", 5); } boolean onRun() { ArrayMap<String, String> map = new ArrayMap<String, String>(); for (int i=0; i<mSize; i++) { map.put(mKeys[i], mValues[i]); } return true; } } static class GrowSmallHashMapOp extends GenericMapOp { GrowSmallHashMapOp() { super("GrowSmallHashMap", "Add 100 items to a HashMap", 100); } boolean onRun() { HashMap<String, String> map = new HashMap<String, String>(); for (int i=0; i<mSize; i++) { map.put(mKeys[i], mValues[i]); } return true; } } static class GrowSmallArrayMapOp extends GenericMapOp { GrowSmallArrayMapOp() { super("GrowSmallArrayMap", "Add 100 items to a ArrayMap", 100); } boolean onRun() { ArrayMap<String, String> map = new ArrayMap<String, String>(); for (int i=0; i<mSize; i++) { map.put(mKeys[i], mValues[i]); } return true; } } static class GrowLargeHashMapOp extends GenericMapOp { GrowLargeHashMapOp() { super("GrowLargeHashMap", "Add 10000 items to a HashMap", 10000); } boolean onRun() { HashMap<String, String> map = new HashMap<String, String>(); for (int i=0; i<mSize; i++) { map.put(mKeys[i], mValues[i]); } return true; } } static class GrowLargeArrayMapOp extends GenericMapOp { GrowLargeArrayMapOp() { super("GrowLargeArrayMap", "Add 10000 items to a ArrayMap", 10000); } boolean onRun() { ArrayMap<String, String> map = new ArrayMap<String, String>(); for (int i=0; i<mSize; i++) { map.put(mKeys[i], mValues[i]); } return true; } } static class LookupTinyHashMapOp extends LookupSmallHashMapOp { LookupTinyHashMapOp() { super("LookupTinyHashMap", "Lookup items in 5 entry HashMap", 5); } } static class LookupTinyArrayMapOp extends LookupSmallArrayMapOp { LookupTinyArrayMapOp() { super("LookupTinyArrayMap", "Lookup items in 5 entry ArrayMap", 5); } } static class LookupSmallHashMapOp extends GenericMapOp { HashMap<String, String> mHashMap; LookupSmallHashMapOp() { super("LookupSmallHashMap", "Lookup items in 100 entry HashMap", 100); } LookupSmallHashMapOp(String name, String longname, int size) { super(name, longname, size); } void onInit(Context context, boolean foreground) { super.onInit(context, foreground); mHashMap = new HashMap<String, String>(); for (int i=0; i<mSize; i++) { mHashMap.put(mKeys[i], mValues[i]); } } boolean onRun() { for (int i=0; i<mSize; i++) { mHashMap.get(mKeys[i]); } return true; } } static class LookupSmallArrayMapOp extends GenericMapOp { ArrayMap<String, String> mArrayMap; LookupSmallArrayMapOp() { super("LookupSmallArrayMap", "Lookup items in 100 entry ArrayMap", 100); } LookupSmallArrayMapOp(String name, String longname, int size) { super(name, longname, size); } void onInit(Context context, boolean foreground) { super.onInit(context, foreground); mArrayMap = new ArrayMap<String, String>(); for (int i=0; i<mSize; i++) { mArrayMap.put(mKeys[i], mValues[i]); } } boolean onRun() { for (int i=0; i<mSize; i++) { mArrayMap.get(mKeys[i]); } return true; } } static class LookupLargeHashMapOp extends LookupSmallHashMapOp { LookupLargeHashMapOp() { super("LookupLargeHashMap", "Lookup items in 10000 entry HashMap", 10000); } } static class LookupLargeArrayMapOp extends LookupSmallArrayMapOp { LookupLargeArrayMapOp() { super("LookupLargeArrayMap", "Lookup items in 10000 entry ArrayMap", 10000); } } }
30.820106
95
0.525788
b25f7e02858567c082bf4a99ae8fe5d15821eb43
970
package org.liangjies.zhihu.service; import org.liangjies.zhihu.entity.Zhihu; import java.util.List; /** * (Zhihu)表服务接口 * * @author liangjies * @since 2020-03-30 00:30:54 */ public interface ZhihuService { /** * 通过ID查询单条数据 * * @param id 主键 * @return 实例对象 */ Zhihu queryById(Integer id); /** * 通过answer ID查询单条数据 * * @param answer 主键 * @return 实例对象 */ Zhihu queryByAnswer(Integer answer); /** * 查询多条数据 * * @param offset 查询起始位置 * @param limit 查询条数 * @return 对象列表 */ List<Zhihu> queryAllByLimit(int offset, int limit); /** * 新增数据 * * @param zhihu 实例对象 * @return 实例对象 */ Zhihu insert(Zhihu zhihu); /** * 修改数据 * * @param zhihu 实例对象 * @return 实例对象 */ Zhihu update(Zhihu zhihu); /** * 通过主键删除数据 * * @param id 主键 * @return 是否成功 */ boolean deleteById(Integer id); }
15.645161
55
0.530928
54f8c6afbdd12971594953e39aaafad81e132350
3,138
package uiTest; import com.app.flight.Main; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.RadioButton; import javafx.stage.Stage; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.testfx.api.FxRobot; import org.testfx.assertions.api.Assertions; import org.testfx.framework.junit5.ApplicationExtension; import org.testfx.framework.junit5.Start; import java.io.IOException; /** * @author JiaBoran * @version 2.0 * Test class for SelectFoodType */ @ExtendWith(ApplicationExtension.class) public class SelectFoodTypeTest { /** * Before all tests initiation of uploading fxml pages * * @param stage stage * @throws IOException IOException */ @Start private void start(Stage stage) throws IOException { FXMLLoader fxmlLoader = new FXMLLoader(Main.class.getResource("fxml/SelectFoodType.fxml")); Scene scene = new Scene(fxmlLoader.load(), 1200, 800); stage.setTitle("Smart flight check-in kiosk"); stage.setScene(scene); stage.show(); } /** * test for containing elements in the page * * @param robot robot */ @Test void containText(FxRobot robot) { Assertions.assertThat(robot.lookup("#r1").queryAs(RadioButton.class)).isVisible(); Assertions.assertThat(robot.lookup("#r2").queryAs(RadioButton.class)).isVisible(); Assertions.assertThat(robot.lookup("#r3").queryAs(RadioButton.class)).isVisible(); Assertions.assertThat(robot.lookup("#help").queryAs(Button.class)).hasText("Help"); Assertions.assertThat(robot.lookup("#next").queryAs(Button.class)).hasText("Next"); } /** * test for clicking help button * * @param robot robot */ @Test void onClickHelpButton(FxRobot robot) { robot.clickOn("#help"); Assertions.assertThat(robot.lookup("#call").queryAs(Button.class)).hasText("Yes"); } /** * test for clicking on first radiobutton * * @param robot robot */ @Test void onClickFirstRadioButton(FxRobot robot) { robot.clickOn("#r1"); Assertions.assertThat(robot.lookup("#r1").queryAs(RadioButton.class)).isFocused(); Assertions.assertThat(robot.lookup("#next").queryAs(Button.class)).isEnabled(); } /** * test for clicking on second radiobutton * * @param robot robot */ @Test void onClickSecondRadioButton(FxRobot robot) { robot.clickOn("#r2"); Assertions.assertThat(robot.lookup("#r2").queryAs(RadioButton.class)).isFocused(); Assertions.assertThat(robot.lookup("#next").queryAs(Button.class)).isEnabled(); } /** * test for clicking on third radiobutton * * @param robot robot */ @Test void onClickThirdRadioButton(FxRobot robot) { robot.clickOn("#r3"); Assertions.assertThat(robot.lookup("#r3").queryAs(RadioButton.class)).isFocused(); Assertions.assertThat(robot.lookup("#next").queryAs(Button.class)).isEnabled(); } }
30.764706
99
0.667304
40eec3deff9469cb5c1e75caf978a114918e3ace
433
package com.kelvem.crawler.test; import com.kelvem.common.CrawlerUtil; /** * TestHttpGet * * @ClassName TestHttpGet * @author kelvem * @version 1.0 */ public class TestHttpGet { /** * main * * @param args * @return void * @throws */ public static void main(String[] args) { String content = CrawlerUtil.get("https://www.cuponomia.com.br/cupom/alimentos-e-bebidas"); System.out.println(content); } }
15.464286
93
0.660508
416ddc2e110130daeef5d9d2446eec946cb90520
599
package com.mikufans.blog.infrastructure.repository.log; import com.mikufans.blog.domain.aggregate.log.LogEntity; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Service; import java.util.List; @Mapper public interface LogRepository { /** * 添加日志 * @param logDomain * @return */ int addLog(LogPo logDomain); /** * 删除日志 * @param id * @return */ int deleteLogById(@Param("id") Integer id); /** * 获取日志 * @return */ List<LogPo> getLogs(); }
18.71875
56
0.646077
3e0fc51de32174a8336ea5122b8ff5d129768d6e
2,418
/* * 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 studio.raptor.ddal.common.sql; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import org.junit.Assert; import org.junit.Test; import studio.raptor.ddal.common.sql.SQLHintParser.SQLHint; /** * @author Sam * @since 3.0.0 */ public class SQLHintSpecTest { @Test public void testSqlHintSpec_1() { String sql = "/*!hint page(offset=0, count=10); shard(id=10000);*/ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); Assert .assertEquals("/*!hint page(offset=0, count=10); shard(id=10000); */", sqlHint.toString()); assertThat(sqlHint.toSpec(), is("DDALHintSpec;page;shard+id")); } @Test public void testSqlHintSpec_2() { String sql = "/*!hint page(offset=0, count=5); */ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); assertThat(sqlHint.toSpec(), is("DDALHintSpec;page")); } @Test public void testSqlHintSpec_3() { String sql = "/*!hint shard(user_id=10000);*/ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); Assert.assertEquals("/*!hint shard(user_id=10000); */", sqlHint.toString()); assertThat(sqlHint.toSpec(), is("DDALHintSpec;shard+user_id")); } @Test public void testSqlHintSpec_4() { String sql = "/*!hint page(offset=0, count=5); readonly; */ select * from t_user"; SQLHint sqlHint = SQLHintParser.parse(sql); Assert.assertNotNull(sqlHint); assertThat(sqlHint.toSpec(), is("DDALHintSpec;page;readonly")); } }
35.043478
99
0.710918
4e2aa4033b6802c21046c0b8c6edbf6b8ff0a97e
679
package model.statement; public class ForkStatement extends Statement { private Statement program; public ForkStatement(Statement program) { this.program = program; } /** * Getter for property 'program'. * * @return Value for property 'program'. */ public Statement getProgram() { return program; } /** * {@inheritDoc} */ @Override public String toString() { return String.format("fork(%s)", program.toString()); } /** * {@inheritDoc} */ @Override public Statement cloneDeep() { return new ForkStatement(program.cloneDeep()); } }
16.975
61
0.565538
a575eb53704d696bc8cad0523ae586748173c66c
10,793
/* * NativeCapableFactory.java * * Created on 23 de mayo de 2005, 17:31 * * To change this template, choose Tools | Options and locate the template under * the Source Creation and Management node. Right-click the template and choose * Open. You can then make changes to the template in the Source Editor. */ package com.innowhere.jnieasy.core.util; import com.innowhere.jnieasy.core.data.CanBeNativeCapable; import com.innowhere.jnieasy.core.data.NativeBoolean; import com.innowhere.jnieasy.core.data.NativeByte; import com.innowhere.jnieasy.core.data.NativeCharacter; import com.innowhere.jnieasy.core.data.NativeDouble; import com.innowhere.jnieasy.core.data.NativeFloat; import com.innowhere.jnieasy.core.data.NativeInteger; import com.innowhere.jnieasy.core.data.NativeLong; import com.innowhere.jnieasy.core.data.NativeString; import com.innowhere.jnieasy.core.data.NativeStringBuffer; import com.innowhere.jnieasy.core.data.NativePointer; import com.innowhere.jnieasy.core.data.NativeShort; import com.innowhere.jnieasy.core.data.NativeStringAnsi; import com.innowhere.jnieasy.core.data.NativeStringBufferAnsi; import com.innowhere.jnieasy.core.data.NativeStringBufferUnicode; import com.innowhere.jnieasy.core.data.NativeStringUnicode; import com.innowhere.jnieasy.core.typedec.NativeTypeManager; /** * The <code>NativeCapableFactory</code> is the interface used as a shortcut * to create native capable objects wrapping other native capable, * or "can be native" objects, or primitive values. * * @see com.innowhere.jnieasy.core.JNIEasy#getNativeCapableFactory() */ public interface NativeCapableFactory { /** * Returns the utility object to declare native types. * * * * @return the <code>NativeTypeManager</code> object. */ public NativeTypeManager getTypeManager(); /** * Wraps the specified "can be native" value inside a native * capable object. * <p> * The native type used is the default native type of the specified * value. * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * TypeCanBeNativeCapable typeDec = (TypeCanBeNativeCapable)getTypeManager().getDefaultType(value); * return (CanBeNativeCapable)typeDec.wrapValue(value); * </code></blockquote> * For instance: * <blockquote><code> * NativeCapableFactory factory = JNIEasy.get().getObjectFactory(); * NativeString obj = (NativeString)factory.wrapValue("Hello"); * </code></blockquote> * * * @param value the object to wrap. * @return the native capable object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#getDefaultType(Object) * @see com.innowhere.jnieasy.core.typedec.TypeCanBeNativeCapable#wrapValue(Object) */ public CanBeNativeCapable wrapValue(Object value); /** * Creates a native capable NativePointer object containing the * specified reference as the contained pointer. * <p> * Current implementation uses the default native type of * the parameter to construct the type of the container pointer. * * @param addressed the reference to be addressed. Can not be null. * @return the new NativePointer object containing the specified reference. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#getDefaultType(Object) * @see com.innowhere.jnieasy.core.typedec.TypeNative#decVarType() * @see com.innowhere.jnieasy.core.typedec.VarTypeNative#decPointer() * @see com.innowhere.jnieasy.core.typedec.TypeNativeObject#newValue() * @see com.innowhere.jnieasy.core.data.NativeSingleFieldContainer#setValue(Object) */ public NativePointer newPointer(Object addressed); /** * Wraps (makes native capable) a String object with a NativeString * wrapper object. * <p> * This method is a shortcut of * {@link com.innowhere.jnieasy.core.typedec.TypeNativeString#newString(String)} * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * return getTypeManager().decString().newString(value); * </code></blockquote> * * * * * @param value the String value to wrap. * @return the native capable wrapper object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#decString() */ public NativeString newString(String value); /** * Wraps (makes native capable) a String object with a NativeStringAnsi * wrapper object. * <p> * This method is a shortcut of * {@link com.innowhere.jnieasy.core.typedec.TypeNativeStringAnsi#newStringAnsi(String)} * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * return getTypeManager().decStringAnsi().newStringAnsi(value); * </code></blockquote> * * * @param value the String value to wrap. * @return the native capable wrapper object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#decStringAnsi() */ public NativeStringAnsi newStringAnsi(String value); /** * Wraps (makes native capable) a String object with a NativeStringUnicode * wrapper object. * <p> * This method is a shortcut of * {@link com.innowhere.jnieasy.core.typedec.TypeNativeStringUnicode#newStringUnicode(String)} * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * return getTypeManager().decStringUnicode().newStringUnicode(value); * </code></blockquote> * * * * * * @param value the String value to wrap. * @return the native capable wrapper object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#decStringUnicode() */ public NativeStringUnicode newStringUnicode(String value); /** * Wraps (makes native capable) a StringBuffer object with a NativeStringBuffer * wrapper object. * <p> * This method is a shortcut of * {@link com.innowhere.jnieasy.core.typedec.TypeNativeStringBuffer#newStringBuffer(StringBuffer)} * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * return getTypeManager().decStringBuffer().newStringBuffer(value); * </code></blockquote> * * * * * @param value the StringBuffer value to wrap. * @return the native capable wrapper object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#decStringBuffer() */ public NativeStringBuffer newStringBuffer(StringBuffer value); /** * Wraps (makes native capable) a StringBuffer object with a NativeStringBufferAnsi * wrapper object. * <p> * This method is a shortcut of * {@link com.innowhere.jnieasy.core.typedec.TypeNativeStringBufferAnsi#newStringBufferAnsi(StringBuffer)} * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * return getTypeManager().decStringBufferAnsi().newStringBufferAnsi(value); * </code></blockquote> * * * * * * @param value the StringBuffer value to wrap. * @return the native capable wrapper object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#decStringBufferAnsi() */ public NativeStringBufferAnsi newStringBufferAnsi(StringBuffer value); /** * Wraps (makes native capable) a StringBuffer object with a NativeStringBufferUnicode * wrapper object. * <p> * This method is a shortcut of * {@link com.innowhere.jnieasy.core.typedec.TypeNativeStringBufferUnicode#newStringBufferUnicode(StringBuffer)} * <p> * Current implementation is: * <blockquote><code> * if (value == null) return null; * return getTypeManager().decStringBufferUnicode().newStringBufferUnicode(value); * </code></blockquote> * * @param value the StringBuffer value to wrap. * @return the native capable wrapper object. * @see com.innowhere.jnieasy.core.typedec.NativeTypeManager#decStringBufferUnicode() */ public NativeStringBufferUnicode newStringBufferUnicode(StringBuffer value); /** * Creates a new native capable boolean object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeBoolean newNativeBoolean(boolean value); /** * Creates a new native capable byte object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeByte newNativeByte(byte value); /** * Creates a new native capable character object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeCharacter newNativeCharacter(char value); /** * Creates a new native capable short object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeShort newNativeShort(short value); /** * Creates a new native capable integer object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeInteger newNativeInteger(int value); /** * Creates a new native capable long object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeLong newNativeLong(long value); /** * Creates a new native capable float object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeFloat newNativeFloat(float value); /** * Creates a new native capable double object with the specified value. * * @param value the value to set the new object. * @return the new native capable object. */ public NativeDouble newNativeDouble(double value); }
37.346021
117
0.658946
3ab26382fe88b9b57444cc571e282e0e93d2287c
441
package rx.internal.util.unsafe; /* compiled from: SpmcArrayQueue */ abstract class SpmcArrayQueueL1Pad<E> extends ConcurrentCircularArrayQueue<E> { long p10; long p11; long p12; long p13; long p14; long p15; long p16; long p30; long p31; long p32; long p33; long p34; long p35; long p36; long p37; public SpmcArrayQueueL1Pad(int capacity) { super(capacity); } }
17.64
79
0.62585
8ebc18573996310de50bb03a65190634a6f071e1
3,685
package com.ruoyi.alipay.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.ruoyi.common.annotation.Excel; import com.ruoyi.common.core.domain.BaseEntity; /** * 商户信息对象 t_merchant_info * * @author ruoyi * @date 2020-03-18 */ public class MerchantInfoEntity extends BaseEntity { private static final long serialVersionUID = 1L; /** 数据ID */ private Long id; /** 商户ID */ @Excel(name = "商户ID") private String merchantId; /** 商户名称 */ @Excel(name = "商户名称") private String merchantName; /** 商家私钥 */ @Excel(name = "商家私钥") private String privateKey; /** 商家公钥 */ @Excel(name = "商家公钥") private String publicKey; /** 交易密钥 */ @Excel(name = "交易密钥") private String dealKey; /** 提现密码 */ @Excel(name = "提现密码") private String withdrawalPwd; /** 提现盐值 */ @Excel(name = "提现盐值") private String withdrawalSalt; /** 商户状态 */ @Excel(name = "商户状态") private Integer switches; /** 删除标志 */ private Integer delFlag; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setMerchantId(String merchantId) { this.merchantId = merchantId; } public String getMerchantId() { return merchantId; } public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public String getMerchantName() { return merchantName; } public void setPrivateKey(String privateKey) { this.privateKey = privateKey; } public String getPrivateKey() { return privateKey; } public void setPublicKey(String publicKey) { this.publicKey = publicKey; } public String getPublicKey() { return publicKey; } public void setDealKey(String dealKey) { this.dealKey = dealKey; } public String getDealKey() { return dealKey; } public void setWithdrawalPwd(String withdrawalPwd) { this.withdrawalPwd = withdrawalPwd; } public String getWithdrawalPwd() { return withdrawalPwd; } public void setWithdrawalSalt(String withdrawalSalt) { this.withdrawalSalt = withdrawalSalt; } public String getWithdrawalSalt() { return withdrawalSalt; } public void setSwitches(Integer switches) { this.switches = switches; } public Integer getSwitches() { return switches; } public void setDelFlag(Integer delFlag) { this.delFlag = delFlag; } public Integer getDelFlag() { return delFlag; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("merchantId", getMerchantId()) .append("merchantName", getMerchantName()) .append("privateKey", getPrivateKey()) .append("publicKey", getPublicKey()) .append("dealKey", getDealKey()) .append("withdrawalPwd", getWithdrawalPwd()) .append("withdrawalSalt", getWithdrawalSalt()) .append("createBy", getCreateBy()) .append("createTime", getCreateTime()) .append("updateBy", getUpdateBy()) .append("updateTime", getUpdateTime()) .append("switches", getSwitches()) .append("delFlag", getDelFlag()) .append("remark", getRemark()) .toString(); } }
21.934524
71
0.59213
c7d01fee66783be107f1447f51980cb85540acda
1,877
package cn.ibestcode.easiness.exception.handler; import cn.ibestcode.easiness.exception.properties.EasinessExceptionTipsProperties; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.ObjectError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @RestControllerAdvice public class MethodArgumentNotValidExceptionHandler extends AbstractEasinessExceptionHandler { @Autowired private EasinessExceptionTipsProperties properties; @Setter @Getter @ToString private class Error { private String defaultMessage; private String objectName; private String field; private Object rejectedValue; } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) { Map<String, Object> result = new HashMap<>(); List<Error> errors = new ArrayList<>(); List<ObjectError> objectErrors = exception.getBindingResult().getAllErrors(); for (ObjectError objectError : objectErrors) { Error error = new Error(); BeanUtils.copyProperties(objectError, error); errors.add(error); } result.put(properties.getErrorName(), errors); result.put(properties.getCodeName(), "MethodArgumentNotValid"); result.put(properties.getMsgName(), "参数校验失败"); return new ResponseEntity<>(result, HttpStatus.OK); } }
36.096154
115
0.797549
f38e6626345628f9e32ca593b4bb6a867085f06d
759
package com.cb.project.gracefulmovies.view.adapter; import android.support.v7.widget.RecyclerView; import android.util.SparseArray; import android.view.View; /** * BaseRecyclerViewHolder * <p/> * Created by woxignxiao on 2017-01-25. */ public class BaseRecyclerViewHolder extends RecyclerView.ViewHolder { private SparseArray<View> mViews; public BaseRecyclerViewHolder(View itemView) { super(itemView); mViews = new SparseArray<>(); } public <V extends View> V findView(int id) { View view = mViews.get(id); if (view == null) { view = itemView.findViewById(id); if (view != null) { mViews.put(id, view); } } return (V) view; } }
23.71875
69
0.620553
ffb858131e86341a17d48cf41b862d63d858140b
1,950
package io.objects.tl.api; import io.objects.tl.TLObjectUtils; import io.objects.tl.api.request.TLRequestChannelsCreateChannel; import io.objects.tl.core.TLObject; import org.junit.Ignore; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.security.SecureRandom; import static org.assertj.core.api.Java6Assertions.assertThat; class TLReqResLogTest { private static final String ALPHA_NUMERIC_STRING = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; public static String randomAlphaNumeric(int count) { StringBuilder builder = new StringBuilder(); while (count-- != 0) { int character = (int) (Math.random() * ALPHA_NUMERIC_STRING.length()); builder.append(ALPHA_NUMERIC_STRING.charAt(character)); } return builder.toString(); } @Test void testTLReqResLogSerializationDeSerialization() throws IOException { TLReqResLog log = new TLReqResLog(); SecureRandom random = new SecureRandom(); log.setAuthKeyId(Math.abs(random.nextLong()) + 1); log.setUserId(random.nextInt()); log.setRequestTime(random.nextInt()); log.setResponseTime(random.nextInt()); TLRequestChannelsCreateChannel request = new TLRequestChannelsCreateChannel(); request.setTitle(randomAlphaNumeric(10)); request.setAbout(randomAlphaNumeric(200)); request.setBroadcast(true); request.setMegagroup(true); log.setRequest(request); log.setResponse(new TLUpdateChannel()); byte[] bytes = log.serialize(); TLReqResLog deserialize = TLObjectUtils.deserialize(bytes); assertThat(log.authKeyId).isEqualTo(deserialize.authKeyId); assertThat(log.userId).isEqualTo(deserialize.userId); assertThat(log.requestTime).isEqualTo(deserialize.requestTime); } }
35.454545
94
0.714359
f7451c596b277a60d0b1cc1e343558246cbd89c3
2,465
package demo.block; import net.minestorm.server.instance.block.BlockHandler; import net.minestorm.server.item.ItemStack; import net.minestorm.server.item.Material; import net.minestorm.server.tag.Tag; import net.minestorm.server.tag.TagReadable; import net.minestorm.server.tag.TagSerializer; import net.minestorm.server.tag.TagWritable; import net.minestorm.server.utils.NamespaceID; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jglrxavpok.hephaistos.nbt.NBTCompound; import org.jglrxavpok.hephaistos.nbt.NBTList; import org.jglrxavpok.hephaistos.nbt.NBTTypes; import java.util.ArrayList; import java.util.Collection; import java.util.List; public class CampfireHandler implements BlockHandler { public static final Tag<List<ItemStack>> ITEMS = Tag.View(new TagSerializer<>() { private final Tag<NBTList<NBTCompound>> internal = Tag.NBT("Items"); @Override public @Nullable List<ItemStack> read(@NotNull TagReadable reader) { NBTList<NBTCompound> item = reader.getTag(internal); if (item == null) return null; List<ItemStack> result = new ArrayList<>(); item.forEach(nbtCompound -> { int amount = nbtCompound.getAsByte("Count"); String id = nbtCompound.getString("id"); Material material = Material.fromNamespaceId(id); result.add(ItemStack.of(material, amount)); }); return result; } @Override public void write(@NotNull TagWritable writer, @Nullable List<ItemStack> value) { if (value == null) { writer.removeTag(internal); return; } NBTList<NBTCompound> items = new NBTList<>(NBTTypes.TAG_Compound); for (var item : value) { NBTCompound compound = new NBTCompound() .setByte("Count", (byte) item.getAmount()) .setByte("Slot", (byte) 1) .setString("id", item.getMaterial().name()); items.add(compound); } writer.setTag(internal, items); } }); @Override public @NotNull Collection<Tag<?>> getBlockEntityTags() { return List.of(ITEMS); } @Override public @NotNull NamespaceID getNamespaceId() { return NamespaceID.from("minestom:test"); } }
35.724638
89
0.629615
ac7aa20fab3663c74d06f6ab020165895b4fff94
5,526
/* * Copyright 2019-2020 Zheng Jie * * 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 me.zhengjie.modules.quartz.config; import cn.hutool.core.util.ObjectUtil; import org.quartz.Scheduler; import org.quartz.spi.TriggerFiredBundle; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.config.AutowireCapableBeanFactory; import org.springframework.beans.factory.config.PropertiesFactoryBean; import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.core.io.ClassPathResource; import org.springframework.scheduling.quartz.AdaptableJobFactory; import org.springframework.scheduling.quartz.SchedulerFactoryBean; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.Properties; /** * 定时任务配置 * @author / * @date 2019-01-07 */ @Configuration public class QuartzConfig { @Autowired private Environment environment; private final String DB_HOST ="DB_HOST"; private final String DB_PORT ="DB_PORT"; private final String DB_NAME ="DB_NAME"; /** * 解决Job中注入Spring Bean为null的问题 */ @Component("quartzJobFactory") public static class QuartzJobFactory extends AdaptableJobFactory { private final AutowireCapableBeanFactory capableBeanFactory; public QuartzJobFactory(AutowireCapableBeanFactory capableBeanFactory) { this.capableBeanFactory = capableBeanFactory; } @Override protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception { //调用父类的方法 Object jobInstance = super.createJobInstance(bundle); capableBeanFactory.autowireBean(jobInstance); return jobInstance; } } @Bean public SchedulerFactoryBean schedulerFactoryBean(QuartzJobFactory quartzJobFactory) throws IOException { //获取配置属性 PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean(); propertiesFactoryBean.setLocation(new ClassPathResource("config/quartz.properties")); //在quartz.properties中的属性被读取并注入后再初始化对象 propertiesFactoryBean.afterPropertiesSet(); // DB_HOST DB_PORT DB_NAME Properties properties = propertiesFactoryBean.getObject(); String url =properties.getProperty("org.quartz.dataSource.qzDS.URL"); String dbPwd =properties.getProperty("org.quartz.dataSource.qzDS.password"); String dbHost = environment.getProperty(DB_HOST); String dbPort = environment.getProperty(DB_PORT); String dbName = environment.getProperty(DB_NAME); String realUrl = this.resolveUrl(url,dbHost,dbPort,dbName); properties.setProperty("org.quartz.dataSource.qzDS.URL",realUrl); if(ObjectUtil.isNotNull(dbPwd)){ properties.setProperty("org.quartz.dataSource.qzDS.password",dbPwd); } //创建SchedulerFactoryBean SchedulerFactoryBean factory = new SchedulerFactoryBean(); factory.setQuartzProperties(properties); factory.setJobFactory(quartzJobFactory);//支持在JOB实例中注入其他的业务对象 factory.setApplicationContextSchedulerContextKey("applicationContextKey"); factory.setWaitForJobsToCompleteOnShutdown(true);//这样当spring关闭时,会等待所有已经启动的quartz job结束后spring才能完全shutdown。 factory.setOverwriteExistingJobs(false);//是否覆盖己存在的Job factory.setStartupDelay(10);//QuartzScheduler 延时启动,应用启动完后 QuartzScheduler 再启动 return factory; } /** * 注入scheduler到spring * @param quartzJobFactory / * @return Scheduler * @throws Exception / */ @Bean(name = "scheduler") public Scheduler scheduler(QuartzJobFactory quartzJobFactory) throws Exception { Scheduler scheduler=schedulerFactoryBean(quartzJobFactory).getScheduler(); return scheduler; } private String replaceDBInfo(String url){ return null; } private String resolveUrl(String url,String DB_HOST,String DB_PORT,String DB_NAME){ String[] arr = url.split("\\/"); String[] hostAndPort = arr[2].split("\\$"); String dbHost = "$" + hostAndPort[1].substring(0,hostAndPort[1].length()-1); String dbPort = "$" + hostAndPort[2]; String[] db = arr[3].split("\\?"); String dbName = db[0]; String host = handleHost(dbHost,DB_HOST); url = url.replace(dbHost,host); String port = handlePort(dbPort,DB_PORT); url = url.replace(dbPort,port); String name = handleName(dbName,DB_NAME); url = url.replace(dbName,name); return url; } private String handleHost(String dbHost,String envHost){ if(ObjectUtil.isNull(envHost)){ String[] hostArr = dbHost.split("\\:"); String ee = hostArr[1].replace("}",""); return ee; }else{ return envHost; } } private String handlePort(String dbPort,String envPort){ if(ObjectUtil.isNull(envPort)){ String[] hostArr = dbPort.split("\\:"); return hostArr[1].replace("}",""); }else{ return envPort; } } private String handleName(String dbName,String envName){ if(ObjectUtil.isNull(envName)){ String[] hostArr = dbName.split("\\:"); return hostArr[1].replace("}",""); }else{ return envName; } } }
34.5375
108
0.767644
a2fb3854a214fd2dc3c447e6a7705d2ea317995e
8,459
/* * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* test %W% %E% @bug 4874070 @summary Tests basic DnD functionality @author Your Name: Alexey Utkin area=dnd @run applet ImageDecoratedDnDInOut.html */ import java.applet.Applet; import java.awt.*; import java.awt.Robot; import java.awt.event.InputEvent; import java.awt.dnd.DragSource; public class ImageDecoratedDnDInOut extends Applet { //Declare things used in the test, like buttons and labels here public void init() { //Create instructions for the user here, as well as set up // the environment -- set the layout manager, add buttons, // etc. this.setLayout(new BorderLayout()); String[] instructions = { "Automatic test.", "A Frame, which contains a yellow button labeled \"Drag ME!\" and ", "a red panel, will appear below. ", "1. The button would be clicked and dragged to the red panel. ", "2. When the mouse enters the red panel during the drag, the panel ", "should turn yellow. On the systems that supports pictured drag, ", "the image under the drag-cursor should appear (ancor is shifted ", "from top-left corner of the picture inside the picture to 10pt in both dimensions ). ", "In WIN32 systems the image under cursor would be visible ONLY over ", "the drop targets with activated extended OLE D\'n\'D support (that are ", "the desktop and IE ).", "3. The mouse would be released.", "The panel should turn red again and a yellow button labeled ", "\"Drag ME!\" should appear inside the panel. " }; Sysout.createDialogWithInstructions(instructions); }//End init() public void start() { Frame f = new Frame("Use keyboard for DnD change"); Panel mainPanel; Component dragSource, dropTarget; f.setBounds(0, 400, 200, 200); f.setLayout(new BorderLayout()); mainPanel = new Panel(); mainPanel.setLayout(new BorderLayout()); mainPanel.setBackground(Color.blue); dropTarget = new DnDTarget(Color.red, Color.yellow); dragSource = new DnDSource("Drag ME! (" + (DragSource.isDragImageSupported()?"with ":"without") + " image)" ); mainPanel.add(dragSource, "North"); mainPanel.add(dropTarget, "Center"); f.add(mainPanel, BorderLayout.CENTER); f.setVisible(true); try { Point sourcePoint = dragSource.getLocationOnScreen(); Dimension d = dragSource.getSize(); sourcePoint.translate(d.width / 2, d.height / 2); Robot robot = new Robot(); robot.mouseMove(sourcePoint.x, sourcePoint.y); robot.mousePress(InputEvent.BUTTON1_MASK); Thread.sleep(2000); for(int i = 0; i <100; ++i) { robot.mouseMove( sourcePoint.x + d.width / 2 + 10, sourcePoint.y + d.height); Thread.sleep(100); robot.mouseMove(sourcePoint.x, sourcePoint.y); Thread.sleep(100); robot.mouseMove( sourcePoint.x, sourcePoint.y + d.height); Thread.sleep(100); } sourcePoint.y += d.height; robot.mouseMove(sourcePoint.x, sourcePoint.y); Thread.sleep(100); robot.mouseRelease(InputEvent.BUTTON1_MASK); Thread.sleep(4000); } catch( Exception e){ e.printStackTrace(); throw new RuntimeException("test failed: drop was not successful with exception " + e); } }// start() }// class DnDAcceptanceTest /** * ************************************************* * Standard Test Machinery * DO NOT modify anything below -- it's a standard * chunk of code whose purpose is to make user * interaction uniform, and thereby make it simpler * to read and understand someone else's test. * ************************************************** */ class Sysout { private static TestDialog dialog; public static void createDialogWithInstructions(String[] instructions) { dialog = new TestDialog(new Frame(), "Instructions"); dialog.printInstructions(instructions); dialog.show(); println("Any messages for the tester will display here."); } public static void createDialog() { dialog = new TestDialog(new Frame(), "Instructions"); String[] defInstr = {"Instructions will appear here. ", ""}; dialog.printInstructions(defInstr); dialog.show(); println("Any messages for the tester will display here."); } public static void printInstructions(String[] instructions) { dialog.printInstructions(instructions); } public static void println(String messageIn) { dialog.displayMessage(messageIn); } }// Sysout class class TestDialog extends Dialog { TextArea instructionsText; TextArea messageText; int maxStringLength = 80; //DO NOT call this directly, go through Sysout public TestDialog(Frame frame, String name) { super(frame, name); int scrollBoth = TextArea.SCROLLBARS_BOTH; instructionsText = new TextArea("", 15, maxStringLength, scrollBoth); add("North", instructionsText); messageText = new TextArea("", 5, maxStringLength, scrollBoth); add("South", messageText); pack(); show(); }// TestDialog() //DO NOT call this directly, go through Sysout public void printInstructions(String[] instructions) { //Clear out any current instructions instructionsText.setText(""); //Go down array of instruction strings String printStr, remainingStr; for (int i = 0; i < instructions.length; i++) { //chop up each into pieces maxSringLength long remainingStr = instructions[i]; while (remainingStr.length() > 0) { //if longer than max then chop off first max chars to print if (remainingStr.length() >= maxStringLength) { //Try to chop on a word boundary int posOfSpace = remainingStr. lastIndexOf(' ', maxStringLength - 1); if (posOfSpace <= 0) posOfSpace = maxStringLength - 1; printStr = remainingStr.substring(0, posOfSpace + 1); remainingStr = remainingStr.substring(posOfSpace + 1); } //else just print else { printStr = remainingStr; remainingStr = ""; } instructionsText.append(printStr + "\n"); }// while }// for }//printInstructions() //DO NOT call this directly, go through Sysout public void displayMessage(String messageIn) { messageText.append(messageIn + "\n"); } }// TestDialog class
35.995745
118
0.597707
89dda0431490c37ae3b82063338dd70dcf317895
2,835
package dev.alnat.moneykeeper.conf; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.StringHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter; import java.nio.charset.StandardCharsets; import java.util.List; /** * Created by @author AlNat on 27.07.2020. * Licensed by Apache License, Version 2.0 */ @Configuration public class MessageConverterConfiguration { // Указываем список конверторов для строки конвертации через строку @Bean public StringHttpMessageConverter stringHttpMessageConverter() { StringHttpMessageConverter converter = new StringHttpMessageConverter(); converter.setDefaultCharset(StandardCharsets.UTF_8); List<MediaType> supportedMediaTypesList = List.of( MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_PLAIN, MediaType.TEXT_HTML, MediaType.MULTIPART_FORM_DATA ); converter.setSupportedMediaTypes(supportedMediaTypesList); return converter; } // Переопределяем стандартные конверторы XML и JSON у Jackson для поддержки полей c Lazy @Bean public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() { MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(new HibernateAwareObjectMapper()); return converter; } @Bean public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter() { MappingJackson2XmlHttpMessageConverter converter = new MappingJackson2XmlHttpMessageConverter(); converter.setObjectMapper(new HibernateAwareXmlMapper()); return converter; } /** * Данный класс реализует корректную обработку ошибки LazyInitializationException при преобразовании в JSON */ public static class HibernateAwareObjectMapper extends ObjectMapper { public HibernateAwareObjectMapper() { registerModule(new Hibernate5Module()); } } /** * Данный класс реализует корректную обработку ошибки LazyInitializationException при преобразовании в XML */ public static class HibernateAwareXmlMapper extends XmlMapper { public HibernateAwareXmlMapper() { registerModule(new Hibernate5Module()); } } }
33.75
111
0.752028
29e9098822f907ee4d668ac4a1aebb44c384a112
391
package application.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import application.model.Authentication; @Repository public interface AuthenticationRepository extends JpaRepository<Authentication, Long> { public Authentication findByIdUser(Long idUser); public Authentication findByToken(String token); }
27.928571
87
0.851662
7414de36d577c2407cf7bd9ad423e71674b83499
2,495
/* * Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Eike Stepper - initial API and implementation */ package org.eclipse.emf.cdo.server.internal.net4j.protocol; import org.eclipse.emf.cdo.common.branch.CDOBranchVersion; import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.common.protocol.CDODataInput; import org.eclipse.emf.cdo.common.protocol.CDODataOutput; import org.eclipse.emf.cdo.common.protocol.CDOProtocolConstants; import org.eclipse.emf.cdo.server.internal.net4j.bundle.OM; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevision; import org.eclipse.emf.cdo.spi.common.revision.InternalCDORevisionManager; import org.eclipse.emf.cdo.spi.common.revision.RevisionInfo; import org.eclipse.net4j.util.om.trace.ContextTracer; import java.io.IOException; /** * @author Eike Stepper */ public class LoadRevisionByVersionIndication extends CDOServerReadIndication { private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG_PROTOCOL, LoadRevisionByVersionIndication.class); private CDOID id; private CDOBranchVersion branchVersion; private int referenceChunk; public LoadRevisionByVersionIndication(CDOServerProtocol protocol) { super(protocol, CDOProtocolConstants.SIGNAL_LOAD_REVISION_BY_VERSION); } @Override protected void indicating(CDODataInput in) throws IOException { id = in.readCDOID(); if (TRACER.isEnabled()) { TRACER.format("Read id: {0}", id); //$NON-NLS-1$ } branchVersion = in.readCDOBranchVersion(); if (TRACER.isEnabled()) { TRACER.format("Read branchVersion: {0}", branchVersion); //$NON-NLS-1$ } referenceChunk = in.readInt(); if (TRACER.isEnabled()) { TRACER.format("Read referenceChunk: {0}", referenceChunk); //$NON-NLS-1$ } } @Override protected void responding(CDODataOutput out) throws IOException { InternalCDORevisionManager revisionManager = getRepository().getRevisionManager(); InternalCDORevision revision = revisionManager.getRevisionByVersion(id, branchVersion, referenceChunk, true); RevisionInfo.writeResult(out, revision, referenceChunk, null); // Exposes revision to client side } }
32.828947
113
0.757515
48a9034a08d99b46f1a60dda03b225ab8e1ea55d
510
class Solution { public int countBalls(int lowLimit, int highLimit) { Map<Integer,Integer> hashmap = new HashMap<>(); for(int i=lowLimit;i<=highLimit;i++){ int sum=0; int n=i; while(n>0){ sum += n%10; n=n/10; } hashmap.put(sum,hashmap.getOrDefault(sum,0)+1); } int ans=0; for(int i: hashmap.values()){ ans = Math.max(ans,i); } return ans; } }
26.842105
59
0.452941
3b9fbc3504099be8d4250da8827d6525d4933a69
4,440
package com.jn.agileway.ssh.client.impl.synergy; import com.jn.agileway.ssh.client.SshException; import com.jn.agileway.ssh.client.channel.AbstarctSessionedChannel; import com.jn.agileway.ssh.client.utils.PTYMode; import com.jn.agileway.ssh.client.utils.Signal; import com.jn.langx.util.collection.Collects; import com.jn.langx.util.function.Consumer2; import com.sshtools.client.PseudoTerminalModes; import com.sshtools.client.SessionChannelNG; import com.sshtools.common.ssh.RequestFuture; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Map; class SynergySessionedChannel extends AbstarctSessionedChannel { private SessionChannelNG channel; SynergySessionedChannel(SessionChannelNG channel) { this.channel = channel; } @Override public void pty(String term) throws SshException { this.channel.allocatePseudoTerminal(term); } @Override public void pty(String term, int termWidthCharacters, int termHeightCharacters, int termWidthPixels, int termHeightPixels, Map<PTYMode, Integer> terminalModes) throws SshException { final PseudoTerminalModes modes = new PseudoTerminalModes(); if (terminalModes != null) { Collects.forEach(terminalModes, new Consumer2<PTYMode, Integer>() { @Override public void accept(PTYMode ptyMode, Integer value) { try { modes.setTerminalMode(ptyMode.getOpcodeInt(), value); } catch (Throwable ex) { // ignore it } } }); } this.channel.allocatePseudoTerminal(term, termWidthCharacters, termHeightCharacters, termWidthPixels, termHeightPixels, modes); } @Override protected void internalX11Forwarding(String hostname, int port, boolean singleConnection, String x11AuthenticationProtocol, String x11AuthenticationCookie, int x11ScreenNumber) throws SshException { // } @Override public void env(String variableName, String variableValue) throws SshException { try { RequestFuture future = channel.setEnvironmentVariable(variableName, variableValue); future.waitForever(); } catch (Throwable ex) { throw new SshException(ex); } } @Override protected void internalExec(String command) throws SshException { try { RequestFuture future = channel.executeCommand(command); future.waitForever(); } catch (Throwable ex) { throw new SshException(ex); } } @Override protected void internalSubsystem(String subsystem) throws SshException { try { RequestFuture future = channel.startSubsystem(subsystem); future.waitForever(); } catch (Throwable ex) { throw new SshException(ex); } } @Override protected void internalShell() throws SshException { try { RequestFuture future = channel.startShell(); future.waitForever(); } catch (Throwable ex) { throw new SshException(ex); } } @Override public void signal(Signal signal) throws SshException { } @Override public int getExitStatus() { int exitCode = channel.getExitCode(); long deadline = System.currentTimeMillis() + 30 * 1000; while (exitCode == -2147483648) { synchronized (this) { if (System.currentTimeMillis() <= deadline) { try { this.wait(50); } catch (InterruptedException ex) { // ignore it } } exitCode = channel.getExitCode(); } } return exitCode; } @Override public InputStream getErrorInputStream() throws SshException { return channel.getStderrStream(); } @Override public InputStream getInputStream() throws SshException { return channel.getInputStream(); } @Override public OutputStream getOutputStream() throws SshException { return channel.getOutputStream(); } @Override public void close() throws IOException { channel.close(); } @Override protected void beforeAction() { } }
31.048951
202
0.630405
072a92192adb04ba2fda5488376c7d5c23d4e507
575
package fi.kapsi.janner.fmireader.query; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.*; /** * Created by janne on 17/05/17. */ public class SimpleQueryBuilderTest { @Test public void testGeoId() throws Exception { SimpleQuery query = new SimpleQueryBuilder() .geoid(1234).finish(); assertThat(query.getGeoid(), is(1234)); } @Test(expected = IllegalArgumentException.class) public void testFinish() { SimpleQueryBuilder builder = new SimpleQueryBuilder(); builder.finish(); } }
21.296296
58
0.711304
fca549544703b5e2e22304dd0f07403722afcdf6
2,006
package view; import java.io.File; import java.util.ArrayList; import javafx.collections.FXCollections; import javafx.fxml.FXML; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.TextField; import javafx.stage.DirectoryChooser; import model.Dadosfile; public class PrincipalController { @FXML TextField txtPath; @FXML TableView<Dadosfile> tbl; @FXML TableColumn<Dadosfile, String> colNome; @FXML TableColumn<Dadosfile, String> colTamanho; private ArrayList<Dadosfile> lista = new ArrayList<Dadosfile>(); @FXML public void initialize() { inicializaTabela(); } @FXML public void apagaLinhaSelecionada() { Dadosfile df = tbl.getSelectionModel().getSelectedItem(); if (df != null) { File f = new File(df.getPath()); f.delete(); lista.remove(df); tbl.setItems(FXCollections.observableArrayList(lista)); } } @FXML public void listar() { if (!txtPath.getText().equals("")) { File diretorio = new File(txtPath.getText()); if (diretorio.isDirectory()) { File[] v = diretorio.listFiles(); for (File f : v) { Dadosfile dados = new Dadosfile(); dados.setNome(f.getName()); dados.setTamanho(f.length() + ""); dados.setPath(f.getAbsolutePath()); lista.add(dados); } tbl.setItems(FXCollections.observableArrayList(lista)); } } } @FXML private void apagaTodos() { for (Dadosfile df : tbl.getItems()) { File f = new File(df.getPath()); f.delete(); } lista.clear(); tbl.setItems(FXCollections.observableArrayList(lista)); } @FXML public void abreDiretorio() { DirectoryChooser dc = new DirectoryChooser(); File selecionado = dc.showDialog(null); if (selecionado != null) { txtPath.setText(selecionado.getAbsolutePath()); } } private void inicializaTabela() { colNome.setCellValueFactory(cellData -> cellData.getValue().nomeProperty()); colTamanho.setCellValueFactory(cellData -> cellData.getValue().tamanhoProperty()); } }
23.057471
84
0.704387
a384d638f97a16d6b537e61ec007f5b9b8bb149f
3,858
package de.metas.impexp.config; import java.util.Collection; import java.util.Optional; import org.adempiere.ad.dao.IQueryBL; import org.adempiere.exceptions.AdempiereException; import org.compiere.model.I_C_DataImport; import org.springframework.stereotype.Repository; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import de.metas.cache.CCache; import de.metas.impexp.format.ImpFormatId; import de.metas.util.Check; import de.metas.util.GuavaCollectors; import de.metas.util.Services; import de.metas.util.StringUtils; import lombok.NonNull; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2019 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ @Repository public class DataImportConfigRepository { private final CCache<Integer, DataImportConfigsCollection> cache = CCache.<Integer, DataImportConfigRepository.DataImportConfigsCollection> builder() .tableName(I_C_DataImport.Table_Name) .build(); public DataImportConfig getById(@NonNull final DataImportConfigId id) { return getCollection().getById(id); } public Optional<DataImportConfig> getByInternalName(@NonNull final String internalName) { return getCollection().getByInternalName(internalName); } private DataImportConfigsCollection getCollection() { return cache.getOrLoad(0, this::retrieveCollection); } private DataImportConfigsCollection retrieveCollection() { final ImmutableList<DataImportConfig> configs = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_DataImport.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(record -> toDataImportConfig(record)) .collect(ImmutableList.toImmutableList()); return new DataImportConfigsCollection(configs); } private static DataImportConfig toDataImportConfig(@NonNull final I_C_DataImport record) { return DataImportConfig.builder() .id(DataImportConfigId.ofRepoId(record.getC_DataImport_ID())) .internalName(StringUtils.trimBlankToNull(record.getInternalName())) .impFormatId(ImpFormatId.ofRepoId(record.getAD_ImpFormat_ID())) .build(); } private static class DataImportConfigsCollection { private final ImmutableMap<DataImportConfigId, DataImportConfig> configsById; private final ImmutableMap<String, DataImportConfig> configsByInternalName; public DataImportConfigsCollection(final Collection<DataImportConfig> configs) { configsById = Maps.uniqueIndex(configs, DataImportConfig::getId); configsByInternalName = configs.stream() .filter(config -> config.getInternalName() != null) .collect(GuavaCollectors.toImmutableMapByKey(DataImportConfig::getInternalName)); } public DataImportConfig getById(@NonNull final DataImportConfigId id) { final DataImportConfig config = configsById.get(id); if (config == null) { throw new AdempiereException("@NotFound@ @C_DataConfig_ID@: " + id); } return config; } public Optional<DataImportConfig> getByInternalName(final String internalName) { Check.assumeNotEmpty(internalName, "internalName is not empty"); return Optional.ofNullable(configsByInternalName.get(internalName)); } } }
32.420168
150
0.776568
dd013b677ff11716a7b10632b35b8e895221faaf
2,550
/* * Copyright 2013 Luciano Resende * * 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 ioc.tuscany; import static org.fest.assertions.Assertions.assertThat; import org.apache.log4j.Level; import org.apache.log4j.LogManager; import org.apache.tuscany.sca.node.Contribution; import org.apache.tuscany.sca.node.ContributionLocationHelper; import org.apache.tuscany.sca.node.Node; import org.apache.tuscany.sca.node.NodeFactory; import org.junit.BeforeClass; import org.junit.Test; import com.meterware.httpunit.GetMethodWebRequest; import com.meterware.httpunit.PostMethodWebRequest; import com.meterware.httpunit.WebConversation; import com.meterware.httpunit.WebRequest; import com.meterware.httpunit.WebResponse; public class ResourceTest { private static String SERVICE_ENDPOINT = "http://localhost:8080/services/tuscany"; private static Node node; @BeforeClass public static void init() throws Exception { try { String contribution = ContributionLocationHelper.getContributionLocation("application.composite"); node = NodeFactory.newInstance().createNode("application.composite", new Contribution("ioc-application", contribution)); node.start(); } catch (Exception e) { e.printStackTrace(); } } @Test public void TestFoo() throws Exception { WebConversation wc = new WebConversation(); WebRequest request = new GetMethodWebRequest(SERVICE_ENDPOINT + "/foo"); WebResponse response = wc.getResource(request); assertThat(response.getResponseCode()).isEqualTo(200); } @Test public void TestCreateFoo() throws Exception { WebConversation wc = new WebConversation(); WebRequest request = new PostMethodWebRequest(SERVICE_ENDPOINT + "/foo"); WebResponse response = wc.getResource(request); System.out.println(response.getHeaderField("location")); assertThat(response.getResponseCode()).isEqualTo(201); } }
34.459459
110
0.723137
6288d262476ef3210bd9e520c38fc5a14ef43d34
175
package org.zstack.header.network.service; public class VirtualRouterHaCallbackStruct { public String type; public VirtualRouterHaCallbackInterface callback; }
25
54
0.788571
ffcff78b58f627957d994885d2cd7bf537236e6b
309
package kg.nurtelecom.cashbackapi.repository; import kg.nurtelecom.cashbackapi.entity.ClientEvent; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ClientEventRepository extends JpaRepository<ClientEvent, Long> { }
30.9
81
0.857605
1f980964f8aa55bca43e0604c1d58502ee5273c7
1,604
package org.czw.flight.model; import java.util.Date; public class Admin { private String username; private Integer loginId; private String name; private String password; private Date lastLoginTime; private Integer type; private Byte status; private String photo; public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public Integer getLoginId() { return loginId; } public void setLoginId(Integer loginId) { this.loginId = loginId; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public Date getLastLoginTime() { return lastLoginTime; } public void setLastLoginTime(Date lastLoginTime) { this.lastLoginTime = lastLoginTime; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public Byte getStatus() { return status; } public void setStatus(Byte status) { this.status = status; } public String getPhoto() { return photo; } public void setPhoto(String photo) { this.photo = photo == null ? null : photo.trim(); } }
18.870588
66
0.602244
7a061a5ccbc8b8b83e5f82be969d6cc844ec50ad
1,371
package models.view.main; import models.utils.infrastructurePackages.Paging; import play.data.Form; import java.util.ArrayList; import java.util.List; public class BasePagedFilterModel<T, F> { public BasePagedFilterModel(List<T> list, int count, Paging paging, Form<F> form) { this.list = list; this.count = count; this.paging = paging; this.form = form; } public List<T> list; public int count; public Paging paging; public Form<F> form; public Integer getTotalPages() { int totalPages = (int) Math.ceil((double) this.count / this.paging.itemsPerPage); return totalPages; } public List<Integer> getPageNumbers() { List<Integer> pageNumbers = new ArrayList<Integer>(); int totalPages = this.getTotalPages(); if (totalPages > 10) { int minPage = (this.paging.page - 5) <= 0 ? 1 : (this.paging.page - 5); int maxPage = minPage + 10; if (minPage > 1) { pageNumbers.add(1); } for (int i = minPage; i <= minPage + 10; i++) { pageNumbers.add(i); } } else { for (int i = 1; i <= totalPages; i++) { pageNumbers.add(i); } } return pageNumbers; } }
29.170213
90
0.539023
adbb3b84835305d5e7f7389e6eb0c74b170e5fda
1,479
/* * Copyright 2007 skynamics AG * * 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.openbp.common.application; /** * The product profile contains all information about a product. * * @author Andreas Putz */ public interface ProductProfile { /** * Gets the short name of a company for internal use. * @nowarn */ public String getShortCompanyName(); /** * Gets the full company name for display in the user interface. * @nowarn */ public String getFullCompanyName(); /** * Gets the short name of a product for internal use. * @nowarn */ public String getShortProductName(); /** * Gets the full name of a product. * @nowarn */ public String getFullProductName(); /** * Gets the product version. * @nowarn */ public String getVersion(); /** * Gets the product build number. * @nowarn */ public String getBuildNumber(); }
24.245902
78
0.661258
0ee8865d47d5ba81060f39ca007ffd9b2b7f30a8
1,044
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package adg.red.controllers; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Hyperlink; /** * FXML Controller class * <p/> * @author harsimran.maan */ public class AboutController implements Initializable { @FXML private void linkGithub(ActionEvent event) { try { java.awt.Desktop.getDesktop().browse(new URI(((Hyperlink) event.getSource()).getId())); } catch (Exception ex) { Logger.getLogger(AboutController.class.getName()).log(Level.SEVERE, null, ex); } } /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { } }
22.212766
99
0.670498
85640640a24a70b68278c2d598998b063d866990
134
package io.lunes.lunesJava; public interface Account { static byte MAINNET = (byte) '1'; static byte TESTNET = (byte) '0'; }
19.142857
37
0.664179
34fe46fef89827298398376b5042086a93db41e1
3,424
package org.jenkinsci.plugins.sqlplus.script.runner.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.util.Map; import org.jenkinsci.plugins.sqlplus.script.runner.ScriptType; public class ExternalProgramUtil { private static final String EOL = "\n"; private static final String LIB_DIR = "lib"; private static final String BIN_DIR = "bin"; private static final String NET_DIR = "network" + File.separator + "admin"; private static final String ENV_LD_LIBRARY_PATH = "LD_LIBRARY_PATH"; private static final String ENV_ORACLE_HOME = "ORACLE_HOME"; private static final String ENV_TNS_ADMIN = "TNS_ADMIN"; private static final String SQLPLUS = "sqlplus"; private static final String SQLPLUS_EXIT = EOL + "exit;" + EOL + "exit;"; private static final String SQLPLUS_TRY_LOGIN_JUST_ONCE = "-L"; private static final String SQLPLUS_VERSION = "-v"; private static final String AT = "@"; private static final String SLASH = "/"; public static String run(String user,String password,String instance,String script,String sqlPath,String oracleHome,String scriptType) throws IOException,InterruptedException { String sqlplusOutput = ""; String arg1 = user + SLASH + password; if (instance != null) { arg1 = arg1 + AT + instance; } String arg2 = script; if (ScriptType.userDefined.name().equals(scriptType)) { addExitOnFile(arg2); } else { addExitOnFile(sqlPath + File.separator + arg2); } System.out.println(arg2); String line; ProcessBuilder pb = new ProcessBuilder(oracleHome + File.separator + BIN_DIR + File.separator + SQLPLUS,SQLPLUS_TRY_LOGIN_JUST_ONCE,arg1,AT + arg2); Map<String,String> env = pb.environment(); env.put(ENV_ORACLE_HOME,oracleHome); env.put(ENV_LD_LIBRARY_PATH,oracleHome + File.separator + LIB_DIR); env.put(ENV_TNS_ADMIN,oracleHome + File.separator + NET_DIR); pb.directory(new File(sqlPath)); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); while ( (line = bri.readLine()) != null) { sqlplusOutput += line + EOL; } return sqlplusOutput; } public static String getVersion(String sqlPath,String oracleHome) throws IOException,InterruptedException { String sqlplusOutput = ""; String line; ProcessBuilder pb = new ProcessBuilder(oracleHome + File.separator + BIN_DIR + File.separator + SQLPLUS,SQLPLUS_VERSION); Map<String,String> env = pb.environment(); env.put(ENV_ORACLE_HOME,oracleHome); env.put(ENV_LD_LIBRARY_PATH,oracleHome + File.separator + LIB_DIR); pb.directory(new File(sqlPath)); pb.redirectErrorStream(true); Process p = pb.start(); p.waitFor(); BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream())); while ( (line = bri.readLine()) != null) { sqlplusOutput += line + EOL; } return sqlplusOutput; } private static void addExitOnFile(String filePath) { Writer output = null; try { output = new BufferedWriter(new FileWriter(filePath,true)); output.append(SQLPLUS_EXIT); output.close(); } catch (Exception e) { e.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { } } } } }
29.264957
177
0.72722
d9914583c559a8bafccf8ab54c0517ad13be3f53
4,289
package example.util; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.highlight.*; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.RAMDirectory; import java.io.IOException; import java.nio.file.Paths; public class LuceneUtil { /** * 获取索引文件存放的文件夹对象 * * @param path * @return */ public static Directory getDirectory(String path) { Directory directory = null; try { directory = FSDirectory.open(Paths.get(path)); } catch (IOException e) { e.printStackTrace(); } return directory; } /** * 索引文件存放在内存 * * @return */ public static Directory getRAMDirectory() { Directory directory = new RAMDirectory(); return directory; } /** * 文件夹读取对象 * * @param directory * @return */ public static DirectoryReader getDirectoryReader(Directory directory) { DirectoryReader reader = null; try { reader = DirectoryReader.open(directory); } catch (IOException e) { e.printStackTrace(); } return reader; } /** * 文件索引对象 * * @param reader * @return */ public static IndexSearcher getIndexSearcher(DirectoryReader reader) { IndexSearcher indexSearcher = new IndexSearcher(reader); return indexSearcher; } /** * 写入索引对象 * * @param directory * @param analyzer * @return */ public static IndexWriter getIndexWriter(Directory directory, Analyzer analyzer) { IndexWriter iwriter = null; try { IndexWriterConfig config = new IndexWriterConfig(analyzer); config.setOpenMode(OpenMode.CREATE_OR_APPEND); // Sort sort=new Sort(new SortField("content", Type.STRING)); // config.setIndexSort(sort);//排序 config.setCommitOnClose(true); // 自动提交 // config.setMergeScheduler(new ConcurrentMergeScheduler()); // config.setIndexDeletionPolicy(new // SnapshotDeletionPolicy(NoDeletionPolicy.INSTANCE)); iwriter = new IndexWriter(directory, config); } catch (IOException e) { e.printStackTrace(); } return iwriter; } /** * 关闭索引文件生成对象以及文件夹对象 * * @param indexWriter * @param directory */ public static void close(IndexWriter indexWriter, Directory directory) { if (indexWriter != null) { try { indexWriter.close(); } catch (IOException e) { indexWriter = null; } } if (directory != null) { try { directory.close(); } catch (IOException e) { directory = null; } } } /** * 关闭索引文件读取对象以及文件夹对象 * * @param reader * @param directory */ public static void close(DirectoryReader reader, Directory directory) { if (reader != null) { try { reader.close(); } catch (IOException e) { reader = null; } } if (directory != null) { try { directory.close(); } catch (IOException e) { directory = null; } } } /** * 高亮标签 * * @param query * @param fieldName * @return */ public static Highlighter getHighlighter(Query query, String fieldName) { Formatter formatter = new SimpleHTMLFormatter("<span style='color:red'>", "</span>"); Scorer fragmentScorer = new QueryTermScorer(query, fieldName); Highlighter highlighter = new Highlighter(formatter, fragmentScorer); highlighter.setTextFragmenter(new SimpleFragmenter(200)); return highlighter; } }
25.837349
93
0.574493
8807268bee342d6035ccd191dfa1eb8ed8e5b1e6
932
package org.aidework.rpc.client.exception; import org.aidework.rpc.core.helper.SystemLogger; import java.util.ArrayList; import java.util.List; public class ExceptionDispatcher { private List<ExceptionHandler> handlerList; private static ExceptionDispatcher instance; private ExceptionDispatcher(){ handlerList=new ArrayList<>(); } public static ExceptionDispatcher build(){ instance=ExceptionDispatcherHolder.instance; return instance; } private static class ExceptionDispatcherHolder{ private static ExceptionDispatcher instance=new ExceptionDispatcher(); } public static void dispatch(String code){ for(ExceptionHandler h:instance.handlerList){ h.handle(code); } } public void registerHandler(ExceptionHandler handler){ if(handler==null){ return; } handlerList.add(handler); } }
25.888889
78
0.690987
90f4d382a25d7b79e67ca89f29b3f8fd2fcd4680
3,506
package tfar.lostandfound; import net.minecraft.item.ItemStack; import net.minecraft.nbt.CompoundNBT; import net.minecraft.nbt.INBT; import net.minecraft.nbt.ListNBT; import net.minecraft.world.World; import net.minecraft.world.server.ServerWorld; import net.minecraft.world.storage.WorldSavedData; import net.minecraftforge.common.util.Constants; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.ItemHandlerHelper; import javax.annotation.Nonnull; import java.util.ArrayList; import java.util.List; public class LostAndFoundData extends WorldSavedData implements IItemHandlerModifiable { public final LazyOptional<IItemHandler> optional = LazyOptional.of(() -> this); public LostAndFoundData(String name) { super(name); } protected final List<ItemStack> stacks = new ArrayList<>(); public static LostAndFoundData getDefaultInstance(ServerWorld world) { return world.getServer().getWorld(World.OVERWORLD).getSavedData().getOrCreate(() -> new LostAndFoundData(LostAndFound.s), LostAndFound.s);//overworld storage } public void addItem(ItemStack stack) { stacks.add(stack); markDirty(); } public void removeItem(int index) { stacks.remove(index); } @Override public void read(CompoundNBT nbt) { ListNBT listNBT = nbt.getList("items", Constants.NBT.TAG_COMPOUND); for (INBT inbt : listNBT) { stacks.add(ItemStack.read((CompoundNBT) inbt)); } } @Override public CompoundNBT write(CompoundNBT compound) { ListNBT listNBT = new ListNBT(); for (ItemStack stack : stacks) { if (!stack.isEmpty()) { listNBT.add(stack.serializeNBT()); } } compound.put("items",listNBT); return compound; } @Override public int getSlots() { return stacks.size(); } @Nonnull @Override public ItemStack getStackInSlot(int slot) { if (slot >= stacks.size()) return ItemStack.EMPTY; else return stacks.get(slot); } @Nonnull @Override //can't add items, only remove public ItemStack insertItem(int slot, @Nonnull ItemStack stack, boolean simulate) { return stack; } @Nonnull @Override public ItemStack extractItem(int slot, int amount, boolean simulate) { if (slot >= stacks.size()) return ItemStack.EMPTY; ItemStack stackInSlot = getStackInSlot(slot); int toExtract = Math.min(amount,stackInSlot.getCount()); ItemStack extracted = ItemHandlerHelper.copyStackWithSize(stackInSlot,toExtract); if (!simulate) { if (toExtract >= stackInSlot.getCount()) { removeItem(slot); } else { stackInSlot.shrink(toExtract); } markDirty(); } return extracted; } @Override public int getSlotLimit(int slot) { return 64; } @Override public boolean isItemValid(int slot, @Nonnull ItemStack stack) { return false; } @Override public void setStackInSlot(int slot, @Nonnull ItemStack stack) { if (slot < stacks.size()) { if (stack.isEmpty()) { stacks.remove(slot); } else { stacks.set(slot, stack); } } } }
28.274194
165
0.642898
c5cbaae6e91d86b5b3944f03f8e7c41fd0275505
133
package org.poem.heart; /** * @author Administrator */ public class Heartbeat { public static final Long TIME = 3 * 1000L; }
13.3
46
0.669173
3883f440d7dea449e34eed12274d14a4e8a4638d
2,836
package com.example.module.resource.model; import lombok.Data; import org.apache.commons.lang3.StringUtils; import java.util.Date; import java.util.HashSet; import java.util.Set; @Data public class ArchiveManageNew { private String number = StringUtils.EMPTY; // 业绩编码 > 合同编号 private String sysNumber = StringUtils.EMPTY;// 业绩编号 private String archiveId = StringUtils.EMPTY;// 业绩id private String archiveType = StringUtils.EMPTY;// 档案类型 private String projectId = StringUtils.EMPTY;// 项目Id private String projectName = StringUtils.EMPTY;// 项目名 private String name = StringUtils.EMPTY;// 合同名 private String contractId = StringUtils.EMPTY;// 合同Id private String createBy = StringUtils.EMPTY;// 创建人 private Date createTime;// 创建时间 private String updateBy = StringUtils.EMPTY;// 修改人 private Date updateTime ;// 修改时间 private String delFlag = StringUtils.EMPTY;// 删除标识 private String type = StringUtils.EMPTY;// 业绩类别 > 项目类别 private String typeId = StringUtils.EMPTY;// 业绩类别Id > 项目类别Id private Date startWorkDate;// 开工日期 private Date checkWorkDate;// 验收日期 private String useStatus = StringUtils.EMPTY;// 使用状态 private String validityStatus = StringUtils.EMPTY;// 有效期状态 private String useNum = StringUtils.EMPTY;// 使用次数 private String aheadTimeRemindDate = StringUtils.EMPTY;// 即将到期提醒时间 private String partnerName = StringUtils.EMPTY;// 合伙人 private String partnerId = StringUtils.EMPTY;// 合伙人Id private String safekeepUser = StringUtils.EMPTY;// 保管人 private String safekeepUserId = StringUtils.EMPTY;// 保管人Id private String parentType = StringUtils.EMPTY;// 证件类型父类 private String parentTypeId = StringUtils.EMPTY;// 证件类型父类Id private String safekeepUserRealName = StringUtils.EMPTY;// 保管人真实姓名 private String completionDate = StringUtils.EMPTY;// 竣工日期 private double actualContractAmount ;// 合同金额 private Date publicityDate ;// 中标时间 private double winBidAmount;// 中标金额 private String isEnabled = StringUtils.EMPTY;// 是否可用 private String remarks = StringUtils.EMPTY;// 备注 private String acceptanceCriteriaId = StringUtils.EMPTY;// 验收标准Id private String acceptanceCriteria = StringUtils.EMPTY;// 验收标准 private String constructionArea = StringUtils.EMPTY;// 建设面积 private String builder = StringUtils.EMPTY;// 项目经理 private String brand = StringUtils.EMPTY;// 品牌 private Date endDat;// 失效日期 private Date startDate;// 生效日期 private double projectContractTotalAmount;// 项目合同总金额 private String contractType = StringUtils.EMPTY;// 合同类别 private String contractTypeId = StringUtils.EMPTY;// 合同类别Id private String projectCode = StringUtils.EMPTY;// 项目编号 private String dataSource = "EPMS"; }
48.067797
72
0.721791
601f5f1e42f17b538d9c60b7d7e11011c2770bb3
2,091
package gerador.de.memes.meme.util; import java.io.File; import java.io.FileOutputStream; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Random; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Bitmap.CompressFormat; import android.net.Uri; import android.os.Environment; import android.widget.RelativeLayout; public class Generator { private Context mContext; private final String FOLDER = "Memes"; private String LAST_IMAGE_SAVED_NAME; public Generator(Context c) { mContext = c; } public String getLastImage() { return Environment.getExternalStorageDirectory().getPath()+"/"+FOLDER+"/"+LAST_IMAGE_SAVED_NAME; } public String generateFileName() { Random generator = new Random(); SimpleDateFormat sdf = new SimpleDateFormat("MM_dd_yyyy_HH_mm_ss"); String currentDateandTime = sdf.format(new Date()); return "Meme_"+ currentDateandTime + "_" + generator.nextInt(1000000000) +".jpg"; } public boolean generateImage(RelativeLayout layout, final String name) { File arquivo = new File(Environment.getExternalStorageDirectory().getPath()+"/"+FOLDER+"/"); if(!arquivo.exists()) arquivo.mkdirs(); try { File file = new File (arquivo, name); layout.setDrawingCacheEnabled(true); Bitmap screenshot; screenshot = Bitmap.createBitmap(layout.getDrawingCache()); Canvas canvas = new Canvas(screenshot); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); canvas.drawBitmap(screenshot, 0, 0, null); screenshot.compress(CompressFormat.JPEG, 100, out); out.flush(); out.close(); layout.setDrawingCacheEnabled(false); LAST_IMAGE_SAVED_NAME = name; return true; } catch (Exception e) { e.printStackTrace(); return false; } finally { mContext.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+Environment.getExternalStorageDirectory().getPath()+"/"+FOLDER+"/"+name))); } } }
29.041667
100
0.730751
b2cda008916a2974e818b19ae4120ebfb7d3c937
312
package com.zup.academy.cartao.domain; public enum StatusBloqueioCartao { BLOQUEADO("BLOQUEADO"), NAO_BLOQUEADO("NAO_BLOQUEADO"); private String value; private StatusBloqueioCartao(String value){ this.value = value; } public String getValue() { return value; } }
17.333333
47
0.663462
6be33f36e68934ce8373b250482a6c5b2bc5d250
4,697
/** * 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.pinot.pql.parsers.pql2.ast; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.TreeSet; import org.apache.pinot.common.request.FilterOperator; import org.apache.pinot.common.utils.StringUtil; import org.apache.pinot.common.utils.request.FilterQueryTree; import org.apache.pinot.common.utils.request.HavingQueryTree; import org.apache.pinot.pql.parsers.Pql2CompilationException; /** * AST node for IN predicates. */ public class InPredicateAstNode extends PredicateAstNode { private final boolean _isNotInClause; public InPredicateAstNode(boolean isNotInClause) { _isNotInClause = isNotInClause; } public ArrayList<String> getValues() { ArrayList<String> values = new ArrayList<>(); for (AstNode astNode : getChildren()) { if (astNode instanceof LiteralAstNode) { LiteralAstNode node = (LiteralAstNode) astNode; values.add(node.getValueAsString()); } } return values; } @Override public void addChild(AstNode childNode) { if (childNode instanceof IdentifierAstNode) { if (_identifier == null && _function == null) { IdentifierAstNode node = (IdentifierAstNode) childNode; _identifier = node.getName(); } else if (_identifier != null) { throw new Pql2CompilationException("IN predicate has more than one identifier."); } else { throw new Pql2CompilationException("IN predicate has both identifier and function."); } } else if (childNode instanceof FunctionCallAstNode) { if (_function == null && _identifier == null) { _function = (FunctionCallAstNode) childNode; } else if (_function != null) { throw new Pql2CompilationException("IN predicate has more than one function."); } else { throw new Pql2CompilationException("IN predicate has both identifier and function."); } } else { super.addChild(childNode); } } @Override public String toString() { if (_identifier != null) { return "InPredicateAstNode{" + "_identifier='" + _identifier + '\'' + '}'; } else if (_function != null) { return "InPredicateAstNode{" + "_function='" + _function.toString() + '\'' + '}'; } else { return "InPredicateAstNode{_identifier/_function= null"; } } @Override public FilterQueryTree buildFilterQueryTree() { if (_identifier == null) { throw new Pql2CompilationException("IN predicate has no identifier"); } Set<String> values = new HashSet<>(); for (AstNode astNode : getChildren()) { if (astNode instanceof LiteralAstNode) { LiteralAstNode node = (LiteralAstNode) astNode; values.add(node.getValueAsString()); } } FilterOperator filterOperator; if (_isNotInClause) { filterOperator = FilterOperator.NOT_IN; } else { filterOperator = FilterOperator.IN; } return new FilterQueryTree(_identifier, new ArrayList<>(values), filterOperator, null); } @Override public HavingQueryTree buildHavingQueryTree() { if (_function == null) { throw new Pql2CompilationException("IN predicate has no function"); } TreeSet<String> values = new TreeSet<>(); for (AstNode astNode : getChildren()) { if (astNode instanceof LiteralAstNode) { LiteralAstNode node = (LiteralAstNode) astNode; values.add(node.getValueAsString()); } } String[] valueArray = values.toArray(new String[values.size()]); FilterOperator filterOperator; if (_isNotInClause) { filterOperator = FilterOperator.NOT_IN; } else { filterOperator = FilterOperator.IN; } return new HavingQueryTree(_function.buildAggregationInfo(), Collections.singletonList(StringUtil.join("\t\t", valueArray)), filterOperator, null); } }
33.077465
94
0.692357
63cfa1055be9fdb55915ba7c7c607b382197bccc
4,604
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.fileEditor.impl.text; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileEditorState; import com.intellij.openapi.fileEditor.FileEditorStateLevel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Arrays; import java.util.Objects; import java.util.function.Supplier; /** * @author Vladimir Kondratyev */ public final class TextEditorState implements FileEditorState { @NotNull CaretState @NotNull [] CARETS = new CaretState[0]; int RELATIVE_CARET_POSITION; // distance from primary caret to the top of editor's viewable area in pixels /** * State which describes how editor is folded. * This field can be {@code null}. */ private CodeFoldingState myFoldingState; private Supplier<? extends CodeFoldingState> myDelayedFoldInfoProducer; private static final int MIN_CHANGE_DISTANCE = 4; /** * Folding state is more complex than, say, line/column number, that's why it's deserialization can be performed only when * necessary pre-requisites are met (e.g. corresponding {@link Document} is created). * <p/> * However, we can't be sure that those conditions are met on IDE startup (when editor states are read). Current method allows * to register a closure within the current state object which returns folding info if possible. * * @param producer delayed folding info producer */ void setDelayedFoldState(@NotNull Supplier<? extends CodeFoldingState> producer) { myDelayedFoldInfoProducer = producer; } @Nullable Supplier<? extends CodeFoldingState> getDelayedFoldState() { return myDelayedFoldInfoProducer; } @Nullable CodeFoldingState getFoldingState() { // Assuming single-thread access here. if (myFoldingState == null && myDelayedFoldInfoProducer != null) { myFoldingState = myDelayedFoldInfoProducer.get(); if (myFoldingState != null) { myDelayedFoldInfoProducer = null; } } return myFoldingState; } void setFoldingState(@Nullable CodeFoldingState foldingState) { myFoldingState = foldingState; myDelayedFoldInfoProducer = null; } @Override public boolean equals(Object o) { if (!(o instanceof TextEditorState)) { return false; } final TextEditorState textEditorState = (TextEditorState)o; if (!Arrays.equals(CARETS, textEditorState.CARETS)) return false; if (RELATIVE_CARET_POSITION != textEditorState.RELATIVE_CARET_POSITION) return false; CodeFoldingState localFoldingState = getFoldingState(); CodeFoldingState theirFoldingState = textEditorState.getFoldingState(); return Objects.equals(localFoldingState, theirFoldingState); } @Override public int hashCode() { return Arrays.hashCode(CARETS); } @Override public boolean canBeMergedWith(@NotNull FileEditorState otherState, @NotNull FileEditorStateLevel level) { if (!(otherState instanceof TextEditorState)) return false; TextEditorState other = (TextEditorState)otherState; return level == FileEditorStateLevel.NAVIGATION && CARETS.length == 1 && other.CARETS.length == 1 && Math.abs(CARETS[0].LINE - other.CARETS[0].LINE) < MIN_CHANGE_DISTANCE; } @Override public String toString() { return Arrays.toString(CARETS); } static class CaretState { int LINE; int COLUMN; boolean LEAN_FORWARD; int VISUAL_COLUMN_ADJUSTMENT; int SELECTION_START_LINE; int SELECTION_START_COLUMN; int SELECTION_END_LINE; int SELECTION_END_COLUMN; @Override public boolean equals(Object o) { if (!(o instanceof CaretState)) { return false; } final CaretState caretState = (CaretState)o; if (COLUMN != caretState.COLUMN) return false; if (LINE != caretState.LINE) return false; if (VISUAL_COLUMN_ADJUSTMENT != caretState.VISUAL_COLUMN_ADJUSTMENT) return false; if (SELECTION_START_LINE != caretState.SELECTION_START_LINE) return false; if (SELECTION_START_COLUMN != caretState.SELECTION_START_COLUMN) return false; if (SELECTION_END_LINE != caretState.SELECTION_END_LINE) return false; return SELECTION_END_COLUMN == caretState.SELECTION_END_COLUMN; } @Override public int hashCode() { return LINE + COLUMN; } @Override public String toString() { return "[" + LINE + "," + COLUMN + "]"; } } }
33.122302
140
0.72437
7c3adda170d23c2d0b9d9aaef53d3c741e93d333
8,449
/*- * #%L * LmdbJavaNative * %% * Copyright (C) 2016 - 2021 The LmdbJava Open Source Project * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.lmdbjava; import static java.util.Objects.requireNonNull; import static org.lmdbjava.KeyRangeType.BACKWARD_ALL; import static org.lmdbjava.KeyRangeType.FORWARD_ALL; /** * Limits the range and direction of keys to iterate. * * <p> * Immutable once created (although the buffers themselves may not be). * * @param <T> buffer type */ public final class KeyRange<T> { private static final KeyRange<?> BK = new KeyRange<>(BACKWARD_ALL, null, null); private static final KeyRange<?> FW = new KeyRange<>(FORWARD_ALL, null, null); private final T start; private final T stop; private final KeyRangeType type; /** * Construct a key range. * * <p> * End user code may find it more expressive to use one of the static methods * provided on this class. * * @param type key type * @param start start key (required if applicable for the passed range type) * @param stop stop key (required if applicable for the passed range type) */ public KeyRange(final KeyRangeType type, final T start, final T stop) { requireNonNull(type, "Key range type is required"); if (type.isStartKeyRequired()) { requireNonNull(start, "Start key is required for this key range type"); } if (type.isStopKeyRequired()) { requireNonNull(stop, "Stop key is required for this key range type"); } this.start = start; this.stop = stop; this.type = type; } /** * Create a {@link KeyRangeType#FORWARD_ALL} range. * * @param <T> buffer type * @return a key range (never null) */ public static <T> KeyRange<T> all() { return (KeyRange<T>) FW; } /** * Create a {@link KeyRangeType#BACKWARD_ALL} range. * * @param <T> buffer type * @return a key range (never null) */ public static <T> KeyRange<T> allBackward() { return (KeyRange<T>) BK; } /** * Create a {@link KeyRangeType#FORWARD_AT_LEAST} range. * * @param <T> buffer type * @param start start key (required) * @return a key range (never null) */ public static <T> KeyRange<T> atLeast(final T start) { return new KeyRange<>(KeyRangeType.FORWARD_AT_LEAST, start, null); } /** * Create a {@link KeyRangeType#BACKWARD_AT_LEAST} range. * * @param <T> buffer type * @param start start key (required) * @return a key range (never null) */ public static <T> KeyRange<T> atLeastBackward(final T start) { return new KeyRange<>(KeyRangeType.BACKWARD_AT_LEAST, start, null); } /** * Create a {@link KeyRangeType#FORWARD_AT_MOST} range. * * @param <T> buffer type * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> atMost(final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_AT_MOST, null, stop); } /** * Create a {@link KeyRangeType#BACKWARD_AT_MOST} range. * * @param <T> buffer type * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> atMostBackward(final T stop) { return new KeyRange<>(KeyRangeType.BACKWARD_AT_MOST, null, stop); } /** * Create a {@link KeyRangeType#FORWARD_CLOSED} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> closed(final T start, final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_CLOSED, start, stop); } /** * Create a {@link KeyRangeType#BACKWARD_CLOSED} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> closedBackward(final T start, final T stop) { return new KeyRange<>(KeyRangeType.BACKWARD_CLOSED, start, stop); } /** * Create a {@link KeyRangeType#FORWARD_CLOSED_OPEN} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> closedOpen(final T start, final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_CLOSED_OPEN, start, stop); } /** * Create a {@link KeyRangeType#BACKWARD_CLOSED_OPEN} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> closedOpenBackward(final T start, final T stop) { return new KeyRange<>(KeyRangeType.BACKWARD_CLOSED_OPEN, start, stop); } /** * Create a {@link KeyRangeType#FORWARD_GREATER_THAN} range. * * @param <T> buffer type * @param start start key (required) * @return a key range (never null) */ public static <T> KeyRange<T> greaterThan(final T start) { return new KeyRange<>(KeyRangeType.FORWARD_GREATER_THAN, start, null); } /** * Create a {@link KeyRangeType#BACKWARD_GREATER_THAN} range. * * @param <T> buffer type * @param start start key (required) * @return a key range (never null) */ public static <T> KeyRange<T> greaterThanBackward(final T start) { return new KeyRange<>(KeyRangeType.BACKWARD_GREATER_THAN, start, null); } /** * Create a {@link KeyRangeType#FORWARD_LESS_THAN} range. * * @param <T> buffer type * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> lessThan(final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_LESS_THAN, null, stop); } /** * Create a {@link KeyRangeType#BACKWARD_LESS_THAN} range. * * @param <T> buffer type * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> lessThanBackward(final T stop) { return new KeyRange<>(KeyRangeType.BACKWARD_LESS_THAN, null, stop); } /** * Create a {@link KeyRangeType#FORWARD_OPEN} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> open(final T start, final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_OPEN, start, stop); } /** * Create a {@link KeyRangeType#BACKWARD_OPEN} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> openBackward(final T start, final T stop) { return new KeyRange<>(KeyRangeType.BACKWARD_OPEN, start, stop); } /** * Create a {@link KeyRangeType#FORWARD_OPEN_CLOSED} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> openClosed(final T start, final T stop) { return new KeyRange<>(KeyRangeType.FORWARD_OPEN_CLOSED, start, stop); } /** * Create a {@link KeyRangeType#BACKWARD_OPEN_CLOSED} range. * * @param <T> buffer type * @param start start key (required) * @param stop stop key (required) * @return a key range (never null) */ public static <T> KeyRange<T> openClosedBackward(final T start, final T stop) { return new KeyRange<>(KeyRangeType.BACKWARD_OPEN_CLOSED, start, stop); } /** * Start key. * * @return start key (may be null) */ public T getStart() { return start; } /** * Stop key. * * @return stop key (may be null) */ public T getStop() { return stop; } /** * Key range type. * * @return type (never null) */ public KeyRangeType getType() { return type; } }
28.257525
81
0.653924
9c8824588bf9994fa8f040c14ee37e4003a83589
4,037
/* * Copyright (c) 2018 Informatics Matters 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 org.squonk.api; import org.squonk.io.SquonkDataSource; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; /** Interfaces for a class that wants to define how it will be persisted using the Notebook/Variable API. * To conform the class must: * <ol> * <li>Implement this interface</li> * <li>Have a constructor with a single parameter of {@link ReadContext} or, for handling generic types, two parameters * of types {java.lang.Class} and {@link ReadContext}</li> * </ol> * This allows the implementation to define exactly how it is persisted, using text and stream values. * For an example see {@link org.squonk.dataset.Dataset} which needs to persist 2 values separately, one for the metadata * and one for the actual (potentially very large) stream of data. * * Created by timbo on 13/03/16. */ public interface VariableHandler<T> extends Handler<T> { /** Write the variable using the Notebook/Variable API * * @param value The value to be writen * @param context The WriteContext to write the variable to */ void writeVariable(T value, WriteContext context) throws Exception; /** Read the variable using the Notebook/Variable API * * @param context * @return * @throws IOException */ T readVariable(ReadContext context) throws Exception; List<SquonkDataSource> readDataSources(ReadContext context) throws Exception; /** Create the variable handled by this handler * * @param input An SquonkDataSource from which the value must be composed * @return The assembled value */ T create(SquonkDataSource input) throws Exception; /** Create an instance from one or more SquonkDataSources. The name of the dataSource identifies the * type of input. Where there is only a single input the name is ignored and the * {@link #create(SquonkDataSource)} method is called with that one input. * * @param inputs multiple datasources defining the variable. * @return * @throws Exception */ T create(List<SquonkDataSource> inputs) throws Exception; T create(String mediaType, Class genericType, Map<String, InputStream> inputs) throws Exception; /** Context that allows a value to be read. * */ interface ReadContext { String readTextValue(String mediaType, String role, String key) throws Exception; default String readTextValue(String mediaType, String role) throws Exception { return readTextValue(mediaType, role, null); } SquonkDataSource readStreamValue(String mediaType, String role, String key) throws Exception; default SquonkDataSource readStreamValue(String mediaType, String role) throws Exception { return readStreamValue(mediaType, role, null); } } /** Context that allows a value to be written. * */ interface WriteContext { void writeTextValue(String value, String mediaType, String role, String key) throws Exception; void writeStreamValue(InputStream value, String mediaType, String role, String key, boolean gzip) throws Exception; default void writeTextValue(String value, String mediaType, String role) throws Exception { writeTextValue(value, mediaType, role, null); } void deleteVariable() throws Exception; } }
36.369369
123
0.708447
613d7953b2c1a3a812a37bb19779727c249a0990
926
package com.thoughtworks.twist.core.execution; import com.thoughtworks.gauge.datastore.DataStoreFactory; /** * TwistSuiteDataStore is a wrapper for using suite level DataStore of Gauge. */ public class TwistSuiteDataStore{ public Object put(Object key, Object value) { if (key == null) { throw new NullPointerException("Key is null"); } if (value == null) { throw new NullPointerException("value is null"); } DataStoreFactory.getSuiteDataStore().put(key, value); return null; } public Object get(Object key) { return DataStoreFactory.getSuiteDataStore().get(key); } public Object remove(Object key) { return DataStoreFactory.getSuiteDataStore().remove(key); } public java.util.Set<java.util.Map.Entry<Object, Object>> entrySet() { return DataStoreFactory.getSuiteDataStore().entrySet(); } }
28.9375
77
0.661987
f443400826e758f292551e3a3631f0d3bee6c44b
1,878
/* * Copyright 2014 MOSPA(Ministry of Security and Public Administration). * * 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 egovframework.sample.emp.service; import egovframework.sample.cmmn.SearchVO; /** * 사원정보를 저장하기 위한 VO클래스 * * @author Daniela Kwon * @since 2014.01.24 * @version 3.0 * @see <pre> * == 개정이력(Modification Information) == * * 수정일 수정자 수정내용 * --------------------------------------------------------------------------------- * 2014.04.07 Daniela Kwon 최초생성 * * </pre> */ public class EmpVO extends SearchVO { private static final long serialVersionUID = 1L; private String empNo; private String empNm; private String birthdate; private String telephone; private String address; public String getEmpNo() { return empNo; } public void setEmpNo(String empNo) { this.empNo = empNo; } public String getEmpNm() { return empNm; } public void setEmpNm(String empNm) { this.empNm = empNm; } public String getBirthdate() { return birthdate; } public void setBirthdate(String birthdate) { this.birthdate = birthdate; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
22.357143
85
0.677849
1b8fec9eb6db38aad31c40d333e18cc468559469
4,375
/** * Copyright (c) 2018 Gluon * 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 Gluon, any associated website, 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 GLUON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.gluonhq.sample.inappbilling; import com.gluonhq.charm.down.Platform; import com.gluonhq.charm.down.Services; import com.gluonhq.charm.down.plugins.InAppBillingService; import com.gluonhq.charm.down.plugins.inappbilling.InAppBillingQueryResult; import com.gluonhq.charm.down.plugins.inappbilling.InAppBillingQueryResultListener; import com.gluonhq.charm.down.plugins.inappbilling.Product; import com.gluonhq.charm.down.plugins.inappbilling.ProductDetails; import com.gluonhq.charm.down.plugins.inappbilling.ProductOrder; import javafx.concurrent.Worker; import java.util.Optional; public class PlayerService implements InAppBillingQueryResultListener { private static final String BASE_64_ANDROID_PUBLIC_KEY = "*** ADD YOUR BASE 64 ENCODED RSA PUBLIC KEY ***"; private static final PlayerService INSTANCE = new PlayerService(); public static PlayerService getInstance() { return INSTANCE; } public Optional<InAppBillingService> getService() { return Optional.ofNullable(service); } private final Player player = new Player(); private final InAppBillingService service; private PlayerService() { Optional<InAppBillingService> service = Services.get(InAppBillingService.class); if (service.isPresent()) { this.service = service.get(); this.service.setQueryResultListener(this); this.service.initialize(BASE_64_ANDROID_PUBLIC_KEY, InAppProduct.getRegisteredProducts()); } else if (! Platform.isDesktop()) { throw new RuntimeException("Charm Down In-App Billing service not discovered."); } else { this.service = null; } } public Player getPlayer() { return player; } @Override public void onQueryResultReceived(InAppBillingQueryResult result) { for (ProductOrder productOrder : result.getProductOrders()) { if (productOrder.getProduct().getType() == Product.Type.CONSUMABLE && productOrder.getProduct().getDetails().getState() == ProductDetails.State.APPROVED) { Worker<Product> finish = service.finish(productOrder); finish.stateProperty().addListener((obs, ov, nv) -> { if (nv == Worker.State.SUCCEEDED) { if (productOrder.getProduct().equals(InAppProduct.HEALTH_POTION.getProduct())) { player.boughtHealthPotion(); } } else if (nv == Worker.State.FAILED) { finish.getException().printStackTrace(); } }); } else if (productOrder.getProduct().equals(InAppProduct.WOODEN_SHIELD.getProduct())) { player.setWoodenShieldOwned(true); } } } }
45.572917
111
0.699657
3a175b37fddcfc09c7c661b57bd279d2e7fb68ae
1,139
package com.lxm.chapter_2.provider; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by lxm on 17/2/8. */ public class DbOpenHelper extends SQLiteOpenHelper{ private static final String DB_NAME = "book_provider.db"; public static final String BOOK_TABLE_NAME = "book"; public static final String USER_TABLE_NAME = "user"; public static final int DB_VERSION = 2; private String CREATE_BOOK_TABLE = "CREATE TABLE IF NOT EXISTS " + BOOK_TABLE_NAME + "(_id INTEGER PRIMARY KEY," + "name TEXT)"; private String CREATE_USER_TABLE = "CREATE TABLE IF NOT EXISTS " + USER_TABLE_NAME + "(_id INTEGER PRIMARY KEY," + "name TEXT," + "sex INT)"; public DbOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_BOOK_TABLE); db.execSQL(CREATE_USER_TABLE); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
27.780488
75
0.689201
acaabb0102db4b479ba354125933bc4f2e968c5c
2,639
/* * 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.openjpa.azure; import java.util.List; import org.apache.openjpa.azure.beans.PObject; import org.apache.openjpa.datacache.ConcurrentQueryCache; import org.apache.openjpa.persistence.OpenJPAEntityManager; import org.apache.openjpa.persistence.test.SQLListenerTestCase; public class TestQueryCache extends SQLListenerTestCase { private static final String CACHE_NAME = "QueryCacheName"; @Override public void setUp() { super.setUp( "openjpa.QueryCache", "true(name=" + CACHE_NAME + ")", "openjpa.RemoteCommitProvider", "sjvm", PObject.class); final OpenJPAEntityManager em = emf.createEntityManager(); em.getTransaction().begin(); em.persist(new PObject()); em.getTransaction().commit(); em.clear(); em.close(); } @Override protected String getPersistenceUnitName() { return System.getProperty("unit", "azure-test"); } public void testCache() { final OpenJPAEntityManager em = emf.createEntityManager(); List<PObject> objs = em.createQuery("SELECT o FROM PObject o").getResultList(); int count = objs.size(); assertTrue(count > 0); resetSQL(); objs = em.createQuery("SELECT o FROM PObject o").getResultList(); assertEquals(count, objs.size()); objs = em.createQuery("SELECT o FROM PObject o").getResultList(); assertEquals(count, objs.size()); assertEquals(0, getSQLCount()); em.close(); } public void testName() { ConcurrentQueryCache qCache = (ConcurrentQueryCache) emf.getConfiguration().getDataCacheManagerInstance().getSystemQueryCache(); assertNotNull(qCache); assertEquals(CACHE_NAME, qCache.getName()); } }
32.9875
114
0.681319
343cb24491db89013779e4020bbfa2278d9016ff
1,302
package com.redescooter.ses.service.mobile.b.service.base.impl; import java.util.List; import org.springframework.stereotype.Service; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.redescooter.ses.service.mobile.b.dao.base.CorExpressOrderTraceMapper; import com.redescooter.ses.service.mobile.b.dm.base.CorExpressOrderTrace; import com.redescooter.ses.service.mobile.b.service.base.CorExpressOrderTraceService; @Service public class CorExpressOrderTraceServiceImpl extends ServiceImpl<CorExpressOrderTraceMapper, CorExpressOrderTrace> implements CorExpressOrderTraceService { @Override public int updateBatch(List<CorExpressOrderTrace> list) { return baseMapper.updateBatch(list); } @Override public int updateBatchSelective(List<CorExpressOrderTrace> list) { return baseMapper.updateBatchSelective(list); } @Override public int batchInsert(List<CorExpressOrderTrace> list) { return baseMapper.batchInsert(list); } @Override public int insertOrUpdate(CorExpressOrderTrace record) { return baseMapper.insertOrUpdate(record); } @Override public int insertOrUpdateSelective(CorExpressOrderTrace record) { return baseMapper.insertOrUpdateSelective(record); } }
29.590909
155
0.777266
5aa1fd317479dabc0a7b31910e2bcf93b8f0462a
1,775
package com.github.raonigabriel.imdb.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpMethod; import org.springframework.security.authentication.ReactiveAuthenticationManager; import org.springframework.security.authentication.UserDetailsRepositoryReactiveAuthenticationManager; import org.springframework.security.config.annotation.method.configuration.EnableReactiveMethodSecurity; import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity; import org.springframework.security.config.web.server.ServerHttpSecurity; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.web.server.SecurityWebFilterChain; import com.github.raonigabriel.imdb.service.RepositoryUserDetailsService; @EnableWebFluxSecurity @EnableReactiveMethodSecurity public class ReactiveWebSecurityConfig { @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public ReactiveAuthenticationManager authenticationManager(@Autowired RepositoryUserDetailsService userService) { return new UserDetailsRepositoryReactiveAuthenticationManager(userService); } @Bean public SecurityWebFilterChain securitygWebFilterChain(ServerHttpSecurity http) { return http.authorizeExchange() .pathMatchers(HttpMethod.GET, "/", "/favicon.ico", "/index.html", "/app.js", "/app.css", "/webjars/**").permitAll() .pathMatchers(HttpMethod.GET, "/actors").permitAll() .pathMatchers(HttpMethod.GET, "/movies").permitAll() .anyExchange().authenticated() .and().httpBasic().and().build(); } }
43.292683
119
0.830423
3045f9ddf4373de3075fb35a515fb86422a8e753
481
package top.plgxs.common.core.api.menu; import lombok.Data; import java.io.Serializable; import java.util.List; /** * @author Stranger。 * @version 1.0 * @since 2021/6/9 11:31 */ @Data public class MenuInit implements Serializable { private static final long serialVersionUID = 1L; /** * 首页信息 */ private HomeInfo homeInfo; /** * logo信息 */ private LogoInfo logoInfo; /** * 菜单信息 */ private List<MenuInfo> menuInfo; }
15.516129
52
0.623701
a797e0b5712fc59c4987f0d4ccb19d05e5f4d399
643
package com.ning.hfind.primary; import com.ning.hfind.Find; import com.ning.hfind.util.PushbackIterator; import org.apache.commons.cli.Option; public class OperandFactory { public static Operand operandFromOption(PushbackIterator<Option> iterator) { Option o = iterator.next(); if (o.getOpt().equals(Find.OR)) { return new OrOperand(); } else if (o.getOpt().equals(Find.AND)) { return new AndOperand(); } else { // Implied AND (two primaries next to each other iterator.pushBack(); return new AndOperand(); } } }
25.72
78
0.601866
d31a1a0c6572f0deb46d3555a00eac8fa406b9e8
2,194
package com.ambrosoft.exercises; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author Jacek R. Ambroziak */ final class FunctionalCounting { // single regex to take care of separation by whitespace and not including leading/trailing punctuation // punctuation can start a token at beginning of line or end a token at end of line private final static Pattern WS_PUNCT_SPLITTER = Pattern.compile("^\\p{Punct}+|\\p{Punct}*\\s+\\p{Punct}*|\\p{Punct}+$"); static Stream<String> tokensInPath(final Path path) throws IOException { return Files.lines(path) .flatMap(WS_PUNCT_SPLITTER::splitAsStream) .filter(token -> !token.isEmpty()); } static Map<String, Long> countTokensInPath(final Path path) { try (final Stream<String> tokens = tokensInPath(path)) { return tokens .map(String::toLowerCase) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } catch (IOException e) { return Collections.emptyMap(); } } // https://stackoverflow.com/questions/23038673/merging-two-mapstring-integer-with-java-8-stream-api static Map<String, Long> countTokensInPathStream(final Stream<Path> pathStream) { return pathStream .map(FunctionalCounting::countTokensInPath) .map(Map::entrySet) // converts each map into an entry set .flatMap(Collection::stream) // converts each set into an entry stream, then .collect( Collectors.toMap( // collects into a map Map.Entry::getKey, // where each entry is based Map.Entry::getValue, // on the entries in the stream Long::sum // merge function )); } }
41.396226
125
0.617593
4c293b0a7d53221799c8fb70bb1494bca72b01e7
1,847
/* * 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.nifi.toolkit.cli.impl.session; import java.util.ArrayList; import java.util.List; /** * Possible variables that can be set in the session. */ public enum SessionVariable { NIFI_CLIENT_PROPS("nifi.props"), NIFI_REGISTRY_CLIENT_PROPS("nifi.reg.props"); private final String variableName; SessionVariable(final String variableName) { this.variableName = variableName; } public String getVariableName() { return this.variableName; } public static SessionVariable fromVariableName(final String variableName) { for (final SessionVariable variable : values()) { if (variable.getVariableName().equals(variableName)) { return variable; } } return null; } public static List<String> getAllVariableNames() { final List<String> names = new ArrayList<>(); for (SessionVariable variable : values()) { names.add(variable.getVariableName()); } return names; } }
31.305085
79
0.693557
943201df98d5aca890b2561432e07f437670002e
360
package com.github.mustahsen.broadcastersample.dto; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; /** * The type Inner object dto. */ @Data @Builder @ToString @NoArgsConstructor @AllArgsConstructor public class InnerObjectDto { private String innerObjectString; }
18
51
0.802778
1df8e83d1b2a0ba70ececa119eb6b106805483d7
1,799
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package co.edu.uniandes.csw.gastronomia.entities; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToOne; import uk.co.jemos.podam.common.PodamExclude; /** * * @author af.benitez */ @Entity public class TipoComidaEntity extends BaseEntity { /** * Nombre del tipo comida. */ private String nombre; @PodamExclude @ManyToOne(cascade = CascadeType.PERSIST) private ClienteEntity cliente; /** * Constructor de la clase TipoComidaEntity. */ public TipoComidaEntity() { //Constructor vacio para evitar falla. } /** * @return the nombre */ public String getNombre() { return nombre; } /** * @param nombre the nombre to set */ public void setNombre(String nombre) { this.nombre = nombre; } /** * @return the cliente */ public ClienteEntity getCliente() { return cliente; } /** * @param cliente the cliente to set */ public void setCliente(ClienteEntity cliente) { this.cliente = cliente; } @Override public boolean equals(Object obj) { if (! super.equals(obj)) { return false; } TipoComidaEntity reservaObj = (TipoComidaEntity) obj; return this.getId().equals(reservaObj.getId()); } @Override public int hashCode() { if (this.getId() != null) { return this.getId().hashCode(); } return super.hashCode(); } }
19.769231
79
0.590884
b0a85d1af32bf89b9cc1085123d327959336b056
1,103
package edu.gatech.gtri.trustmark.v1_0.impl.io.json; import edu.gatech.gtri.trustmark.v1_0.impl.AbstractTest; import edu.gatech.gtri.trustmark.v1_0.model.TrustmarkDefinition; import org.apache.commons.io.FileUtils; import org.junit.Test; import java.io.File; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; /** * Created by brad on 12/9/15. */ public class TestTrustmarkDefinitionJsonDeserializer extends AbstractTest { public static final String TD_FULL_FILE = "./src/test/resources/TDs/td-full.json"; @Test public void testParseFullTrustmarkDefinitionFile() throws Exception { logger.info("Testing that we can read a maximal trustmark definition XML file..."); File xmlFile = new File(TD_FULL_FILE); String json = FileUtils.readFileToString(xmlFile); TrustmarkDefinition td = new TrustmarkDefinitionJsonDeserializer().deserialize(json); assertThat(td, notNullValue()); assertTdFull(td); }//end testParseFullTrustmarkDefinitionFile() }//end testParseFullTrustmarkFile()
31.514286
93
0.75884
b24de4d2915a6d84ec53fd30a0c55832d0fada3a
1,048
package com.huayue.role.controller; import com.huayue.role.services.RoleService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** * @author 西安华越 */ @RestController @Api(tags = "角色") @AllArgsConstructor @RequestMapping("/role") public class RoleController { private RoleService roleService; @ApiOperation(value = "获角色信息", notes = "根据url的id来获取角色详细信息") @ApiImplicitParam(name = "roleId", value = "roleId", required = true, dataType = "Long", paramType = "path") @RequestMapping(value = "/{roleId}", method = RequestMethod.GET) public String getRoleInfo(@PathVariable String roleId){ String s = roleService.getRoleInfo(roleId); return s; } }
34.933333
112
0.764313
07a087e88e04b31c28c69d411512d942b8763da3
2,261
package de.unidue.ltl.escrito.core.tc.stacking; import java.io.File; import java.util.Collections; import java.util.List; import java.util.Properties; import org.dkpro.lab.storage.StorageService.AccessMode; import org.dkpro.lab.storage.impl.PropertiesAdapter; import org.dkpro.tc.core.Constants; import org.dkpro.tc.ml.weka.report.WekaOutcomeIDReport; import org.dkpro.tc.ml.weka.util.MultilabelResult; import weka.core.Instances; public class WekaStackingOutcomeIDReport extends WekaOutcomeIDReport{ // // private File mlResults; // // @Override // public void execute() // throws Exception // { // File arff = WekaUtils.getFile(getContext(), "", // AdapterNameEntries.predictionsFile, AccessMode.READONLY); // mlResults = WekaUtils.getFile(getContext(), "", // WekaStackingTask.evaluationBin, AccessMode.READONLY); // // boolean multiLabel = getDiscriminators() // .get(WekaStackingTask.class.getName() + "|" + Constants.DIM_LEARNING_MODE) // .equals(Constants.LM_MULTI_LABEL); // boolean regression = getDiscriminators() // .get(WekaStackingTask.class.getName() + "|" + Constants.DIM_LEARNING_MODE) // .equals(Constants.LM_REGRESSION); // // Instances predictions = WekaUtils.getInstances(arff, multiLabel); // // List<String> labels = getLabels(predictions, multiLabel, regression); // // Properties props; // // if(multiLabel){ // MultilabelResult r = WekaUtils.readMlResultFromFile(mlResults); // props = generateMlProperties(predictions, labels, r); // } // else{ // props = generateSlProperties(predictions, regression, labels); // } // // // // getContext().storeBinary(Constants.ID_OUTCOME_KEY, // new PropertiesAdapter(props, generateHeader(labels))); // } // // // private List<String> getLabels(Instances predictions, boolean multiLabel, boolean regression) // { // if (regression) { // return Collections.emptyList(); // } // // return WekaUtils.getClassLabels(predictions, multiLabel); // } }
33.25
98
0.634675
fcd53c23b65cf355eb250f6a751666d7e0f4f635
9,749
/* * Copyright 2010-2020 Australian Signals Directorate * * 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 au.gov.asd.tac.constellation.graph.utilities.planes; import au.gov.asd.tac.constellation.graph.GraphReadMethods; /** * * @author algol */ public class PlanePositionPanel extends javax.swing.JPanel { public PlanePositionPanel() { initComponents(); } public float[] getPosition(final GraphReadMethods rg, final float x, final float y, final float z, final float radius, final float width, final float height) { float xx; float yy; float rr = includeRadiusCheck.isSelected() ? radius : 0; if (topLeftRb.isSelected()) { xx = x + rr; yy = y - height - rr; } else if (topRb.isSelected()) { xx = x - width / 2f; yy = y - height - rr; } else if (topRightRb.isSelected()) { xx = x - width - rr; yy = y - height - rr; } else if (rightRb.isSelected()) { xx = x - width - rr; yy = y - height / 2f; } else if (bottomRightRb.isSelected()) { xx = x - width - rr; yy = y + rr; } else if (bottomRb.isSelected()) { xx = x - width / 2f; yy = y + rr; } else if (bottomLeftRb.isSelected()) { xx = x + rr; yy = y + rr; } else if (leftRb.isSelected()) { xx = x + rr; yy = y - height / 2f; } else if (centreRb.isSelected()) { xx = x - width / 2f; yy = y - height / 2f; } else { throw new IllegalStateException(); } return new float[]{xx, yy, z}; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { positionGroup = new javax.swing.ButtonGroup(); jPanel1 = new javax.swing.JPanel(); topLeftRb = new javax.swing.JRadioButton(); topRb = new javax.swing.JRadioButton(); topRightRb = new javax.swing.JRadioButton(); rightRb = new javax.swing.JRadioButton(); bottomRightRb = new javax.swing.JRadioButton(); bottomRb = new javax.swing.JRadioButton(); bottomLeftRb = new javax.swing.JRadioButton(); leftRb = new javax.swing.JRadioButton(); centreRb = new javax.swing.JRadioButton(); includeRadiusCheck = new javax.swing.JCheckBox(); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.jPanel1.border.title"))); // NOI18N positionGroup.add(topLeftRb); topLeftRb.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(topLeftRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.topLeftRb.text")); // NOI18N positionGroup.add(topRb); org.openide.awt.Mnemonics.setLocalizedText(topRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.topRb.text")); // NOI18N positionGroup.add(topRightRb); org.openide.awt.Mnemonics.setLocalizedText(topRightRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.topRightRb.text")); // NOI18N positionGroup.add(rightRb); org.openide.awt.Mnemonics.setLocalizedText(rightRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.rightRb.text")); // NOI18N positionGroup.add(bottomRightRb); org.openide.awt.Mnemonics.setLocalizedText(bottomRightRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.bottomRightRb.text")); // NOI18N positionGroup.add(bottomRb); org.openide.awt.Mnemonics.setLocalizedText(bottomRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.bottomRb.text")); // NOI18N positionGroup.add(bottomLeftRb); org.openide.awt.Mnemonics.setLocalizedText(bottomLeftRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.bottomLeftRb.text")); // NOI18N positionGroup.add(leftRb); org.openide.awt.Mnemonics.setLocalizedText(leftRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.leftRb.text")); // NOI18N positionGroup.add(centreRb); org.openide.awt.Mnemonics.setLocalizedText(centreRb, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.centreRb.text")); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(topLeftRb) .addComponent(topRb) .addComponent(topRightRb) .addComponent(rightRb) .addComponent(bottomRightRb) .addComponent(bottomRb) .addComponent(bottomLeftRb) .addComponent(leftRb) .addComponent(centreRb)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(topLeftRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(topRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(topRightRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(rightRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bottomRightRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bottomRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(bottomLeftRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(leftRb) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(centreRb) .addContainerGap()) ); includeRadiusCheck.setSelected(true); org.openide.awt.Mnemonics.setLocalizedText(includeRadiusCheck, org.openide.util.NbBundle.getMessage(PlanePositionPanel.class, "PlanePositionPanel.includeRadiusCheck.text")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(includeRadiusCheck)) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(includeRadiusCheck) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JRadioButton bottomLeftRb; private javax.swing.JRadioButton bottomRb; private javax.swing.JRadioButton bottomRightRb; private javax.swing.JRadioButton centreRb; private javax.swing.JCheckBox includeRadiusCheck; private javax.swing.JPanel jPanel1; private javax.swing.JRadioButton leftRb; private javax.swing.ButtonGroup positionGroup; private javax.swing.JRadioButton rightRb; private javax.swing.JRadioButton topLeftRb; private javax.swing.JRadioButton topRb; private javax.swing.JRadioButton topRightRb; // End of variables declaration//GEN-END:variables }
48.98995
191
0.671556
4cd8ff0641a1948163a2d8b7f1ec83ae39f31450
4,582
package com.gentics.mesh.core.rest.job; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyDescription; import com.gentics.mesh.core.rest.admin.migration.MigrationStatus; import com.gentics.mesh.core.rest.admin.migration.MigrationType; import com.gentics.mesh.core.rest.common.AbstractResponse; import com.gentics.mesh.core.rest.user.UserReference; /** * POJO for job information. */ public class JobResponse extends AbstractResponse { @JsonProperty(required = true) @JsonPropertyDescription("User reference of the creator of the element.") private UserReference creator; @JsonProperty(required = true) @JsonPropertyDescription("ISO8601 formatted created date string.") private String created; @JsonProperty(required = false) @JsonPropertyDescription("The error message of the job.") private String errorMessage; @JsonProperty(required = false) @JsonPropertyDescription("The detailed error information of the job.") private String errorDetail; @JsonProperty(required = true) @JsonPropertyDescription("The type of the job.") private MigrationType type; @JsonProperty(required = true) @JsonPropertyDescription("Migration status.") private MigrationStatus status; @JsonProperty(required = true) @JsonPropertyDescription("Properties of the job.") private Map<String, String> properties = new HashMap<>(); @JsonProperty(required = true) @JsonPropertyDescription("The stop date of the job.") private String stopDate; @JsonProperty(required = true) @JsonPropertyDescription("The start date of the job.") private String startDate; @JsonProperty(required = true) @JsonPropertyDescription("The completion count of the job. This indicates how many items the job has processed.") private long completionCount; @JsonProperty(required = false) @JsonPropertyDescription("Name of the Gentics Mesh instance on which the job was executed.") private String nodeName; public void setErrorMessage(String errorMessage) { this.errorMessage = errorMessage; } public String getErrorMessage() { return errorMessage; } public String getErrorDetail() { return errorDetail; } public void setErrorDetail(String errorDetail) { this.errorDetail = errorDetail; } public MigrationType getType() { return type; } public void setType(MigrationType type) { this.type = type; } public Map<String, String> getProperties() { return properties; } /** * Return the date on which the job was queued/created. * * @return */ public String getCreated() { return created; } /** * Set the date on which the job was queued/created. * * @param created */ public void setCreated(String created) { this.created = created; } /** * Return the creator of the job. * * @return */ public UserReference getCreator() { return creator; } /** * Set the creator of the job. * * @param creator */ public void setCreator(UserReference creator) { this.creator = creator; } /** * Return the current status of the job. * * @return */ public MigrationStatus getStatus() { return status; } /** * Set the current status of the job. * * @param status */ public void setStatus(MigrationStatus status) { this.status = status; } /** * Return the date on which the job was started. * * @return */ public String getStartDate() { return startDate; } /** * Set the date on which the job was started. * * @param startDate */ public void setStartDate(String startDate) { this.startDate = startDate; } /** * Return the date on which the job finished. * * @return */ public String getStopDate() { return stopDate; } /** * Set the job stop date. * * @param stopDate */ public void setStopDate(String stopDate) { this.stopDate = stopDate; } /** * Return the amount of elements which were processed by the job. * * @return */ public long getCompletionCount() { return completionCount; } /** * Set the amount of elements which were processed by the job. * * @param completionCount */ public void setCompletionCount(long completionCount) { this.completionCount = completionCount; } /** * Return the name of the Gentics Mesh node on which the job was executed. * * @return */ public String getNodeName() { return nodeName; } /** * Set the name on which the job was executed. * * @param nodeName */ public void setNodeName(String nodeName) { this.nodeName = nodeName; } }
21.018349
114
0.713226
26fa8108ca0f84ce842463b5063eb6661b1c49f9
1,541
/********************************************************************* * * Copyright (C) 2007 Andrew Khan * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ***************************************************************************/ package jxl.biff; import jxl.common.Logger; import jxl.read.biff.Record; /** * The conditional format conditions */ public class ConditionalFormatRecord extends WritableRecordData { // the logger private static Logger logger = Logger.getLogger(ConditionalFormatRecord.class); /** * The data */ private byte[] data; /** * Constructor */ public ConditionalFormatRecord(Record t) { super(t); data = getRecord().getData(); } /** * Retrieves the data for output to binary file * * @return the data to be written */ public byte[] getData() { return data; } }
25.262295
76
0.641142
7e14737825d6ed583bee66a4ff886b8de7b2355d
865
package org.shipstone.demo.cache.commons.web.validation; import org.shipstone.demo.cache.commons.domain.IdentifiedObject; import org.springframework.validation.BindingResult; /** * Projet commons Spring * * @author François Robert * LICENCE Apache 2.0 */ public interface ConsistencyUpdateProcessor extends BindingResultProcessor { default <D extends IdentifiedObject> void validateConsistecy(String ResourceId, D data, BindingResult bindingResult) throws ParamsValidationException, ConsistencyEndpointException { validateUniqueIdentifier(ResourceId, data); validateParams(bindingResult); } default <D extends IdentifiedObject> void validateUniqueIdentifier(String ResourceId, D data) throws ConsistencyEndpointException { if (!ResourceId.equals(data.getUniqueIdentifier())) { throw new ConsistencyEndpointException(); } } }
33.269231
183
0.797688
a69528bd68c0cee6e89d62512d756c733586e09e
385
package org.torpay.engine.workflow; import org.torpay.engine.workflow.ErrorHandler; import org.torpay.engine.workflow.WorkflowContext; import org.torpay.engine.workflow.WorkflowException; public interface Activity { public void execute(WorkflowContext context) throws WorkflowException; public ErrorHandler getErrorHandler(); public String getName(); }
20.263158
72
0.774026
9e38b057080a1c633f5ef93b6c420dc5ba979144
2,926
/* * Copyright 2018 NAVER Corp. * * 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.navercorp.pinpoint.plugin.hystrix; import com.navercorp.pinpoint.bootstrap.plugin.test.ExpectedAnnotation; import com.navercorp.pinpoint.bootstrap.plugin.test.PluginTestVerifier; import com.netflix.hystrix.Hystrix; import java.util.concurrent.TimeUnit; import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.annotation; import static com.navercorp.pinpoint.bootstrap.plugin.test.Expectations.event; /** * @author HyunGil Jeong */ public class HystrixTestHelper { public static RuntimeException INTERRUPTED_EXCEPTION_DUE_TO_TIMEOUT = new RuntimeException("expected interrupt"); public static RuntimeException SHORT_CIRCUIT_EXCEPTION = new RuntimeException("Hystrix circuit short-circuited and is OPEN"); public static void reset() { Hystrix.reset(60, TimeUnit.MILLISECONDS); } public static void waitForSpanDataFlush() throws InterruptedException { waitForSpanDataFlush(0); } public static void waitForSpanDataFlush(long additionalDelayMs) throws InterruptedException { Thread.sleep(100L + additionalDelayMs); } public static String sayHello(String name) { return String.format("Hello %s!", name); } public static String fallbackHello(String name) { return String.format("Fallback to %s", name); } public enum ExecutionOption { NORMAL, EXCEPTION, TIMEOUT, SHORT_CIRCUIT; } public static void verifyHystrixMetricsInitialization(PluginTestVerifier verifier, String command, String commandGroup) { ExpectedAnnotation commandKeyAnnotation = annotation("hystrix.command.key", command); ExpectedAnnotation commandGroupKeyAnnotation = annotation("hystrix.command.group.key", commandGroup); ExpectedAnnotation threadPoolKeyAnnotation = annotation("hystrix.thread.pool.key", commandGroup); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "Hystrix Command Metrics Initialization", commandKeyAnnotation, commandGroupKeyAnnotation)); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "Hystrix Circuit Breaker Initialization", commandKeyAnnotation, commandGroupKeyAnnotation)); verifier.verifyTrace(event("HYSTRIX_COMMAND_INTERNAL", "Hystrix ThreadPool Metrics Initialization", threadPoolKeyAnnotation)); } }
40.638889
155
0.760424
b24dae6f97625d8b20fe864d7723016525514933
3,859
package com.smartbit8.laravelstorm.ui; import com.intellij.ide.browsers.BrowserSelector; import com.intellij.ide.browsers.WebBrowser; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.options.SettingsEditor; import com.intellij.openapi.project.Project; import com.jetbrains.php.config.interpreters.PhpInterpreter; import com.jetbrains.php.config.interpreters.PhpInterpreterComboBox; import com.jetbrains.php.config.interpreters.PhpInterpretersManager; import com.jetbrains.php.config.interpreters.PhpInterpretersManagerImpl; import com.smartbit8.laravelstorm.run.LaravelRunConf; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ActionListener; import java.util.*; import java.util.List; public class LaravelRunConfSettingsEditor extends SettingsEditor<LaravelRunConf> { private JPanel mainPanel; private JTextField hostInput; private JSpinner portInput; private JTextField routeInput; private JButton hostSetDefault; private JButton portSetDefault; private JButton routeSetDefault; private JPanel browserInputContainer; private JPanel phpInputContainer; private BrowserSelector browserInput; private PhpInterpreterComboBox phpInput; private Project project; @Override protected void resetEditorFrom(@NotNull LaravelRunConf laravelRunConf) { hostInput.setText(laravelRunConf.getHost()); portInput.setValue(laravelRunConf.getPort()); routeInput.setText(laravelRunConf.getRoute()); browserInput.setSelected(laravelRunConf.getBrowser()); if (laravelRunConf.getInterpreter() != null) phpInput.reset(laravelRunConf.getInterpreter().getName()); else phpInput.reset(); } @Override protected void applyEditorTo(@NotNull LaravelRunConf laravelRunConf) throws ConfigurationException { laravelRunConf.setHost(hostInput.getText()); laravelRunConf.setPort((int) portInput.getValue()); laravelRunConf.setRoute(routeInput.getText()); laravelRunConf.setBrowser(browserInput.getSelected()); laravelRunConf.setInterpreter(PhpInterpretersManagerImpl.getInstance(project) .findInterpreter(phpInput.getSelectedItemName())); } @NotNull @Override protected JComponent createEditor() { return mainPanel; } private void createUIComponents() { portInput = new JSpinner(new SpinnerNumberModel(8000, 1024, 65535, 1)); JSpinner.NumberEditor editor; portInput.setEditor(editor = new JSpinner.NumberEditor(portInput, "#")); editor.getTextField().setHorizontalAlignment(JTextField.LEFT); browserInput = new BrowserSelector(); browserInputContainer = new JPanel(new GridLayout(0, 1)); browserInputContainer.add(browserInput.getMainComponent()); phpInput = new PhpInterpreterComboBox(project, null, true); phpInput.setModel(PhpInterpretersManagerImpl.getInstance(project).getInterpreters(), null); phpInput.setNoItemText("Default (/bin/php)"); phpInputContainer = new JPanel(new GridLayout(0, 1)); phpInputContainer.add(phpInput); } public LaravelRunConfSettingsEditor(Project project) { this.project = project; ActionListener listener = actionEvent -> { if (actionEvent.getSource() == hostSetDefault) hostInput.setText("localhost"); if (actionEvent.getSource() == portSetDefault) portInput.setValue(8000); if (actionEvent.getSource() == routeSetDefault) routeInput.setText("/"); }; hostSetDefault.addActionListener(listener); portSetDefault.addActionListener(listener); routeSetDefault.addActionListener(listener); } }
40.197917
104
0.728945
a49eb263ea2fcac07ee7b58642913da935128146
401
package solvas.authentication.exceptions; import solvas.authentication.jwt.token.RawAccessJwtToken; /** * This exception is thrown when a user attempts to pass an invalid (for example: self-signed) JWT */ public class InvalidJwt extends Exception { /** * @param token The invalid CAS token */ public InvalidJwt(RawAccessJwtToken token) { super(token.getToken()); } }
25.0625
98
0.710723
dd8643daca953739d4e708cb228b9df1d5b26f6b
15,483
package com.tinkerpop.gremlin.structure; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.tinkerpop.gremlin.AbstractGremlinTest; import com.tinkerpop.gremlin.LoadGraphWith; import com.tinkerpop.gremlin.process.Path; import com.tinkerpop.gremlin.structure.io.graphson.GraphSONTokens; import com.tinkerpop.gremlin.structure.io.kryo.KryoMapper; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import java.io.ByteArrayOutputStream; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.*; /** * Serialization tests that occur at a lower level than IO. Note that there is no need to test GraphML here as * it is not a format that can be used for generalized serialization (i.e. it only serializes an entire graph). * * @author Stephen Mallette (http://stephen.genoprime.com) */ @RunWith(Enclosed.class) public class SerializationTest { public static class KryoTest extends AbstractGremlinTest { @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeVertexAsDetached() throws Exception { final KryoMapper kryoMapper = g.io().kryoMapper().create(); final Kryo kryo = kryoMapper.createMapper(); final Vertex v = g.V(convertToVertexId("marko")).next(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final Output output = new Output(stream); kryo.writeObject(output, v); output.close(); final Input input = new Input(stream.toByteArray()); final Vertex detached = kryo.readObject(input, Vertex.class); input.close(); assertNotNull(detached); assertEquals(v.label(), detached.label()); assertEquals(v.id(), detached.id()); assertEquals(v.value("name").toString(), detached.value("name")); assertEquals((Integer) v.value("age"), detached.value("age")); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeEdgeAsDetached() throws Exception { final KryoMapper kryoMapper = g.io().kryoMapper().create(); final Kryo kryo = kryoMapper.createMapper(); final Edge e = g.E(convertToEdgeId("marko", "knows", "vadas")).next(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final Output output = new Output(stream); kryo.writeObject(output, e); output.close(); final Input input = new Input(stream.toByteArray()); final Edge detached = kryo.readObject(input, Edge.class); assertNotNull(detached); assertEquals(e.label(), detached.label()); assertEquals(e.id(), detached.id()); assertEquals((Double) e.value("weight"), detached.value("weight")); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializePropertyAsDetached() throws Exception { final KryoMapper kryoMapper = g.io().kryoMapper().create(); final Kryo kryo = kryoMapper.createMapper(); final Property p = g.E(convertToEdgeId("marko", "knows", "vadas")).next().property("weight"); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final Output output = new Output(stream); kryo.writeObject(output, p); output.close(); final Input input = new Input(stream.toByteArray()); final Property detached = kryo.readObject(input, Property.class); assertNotNull(detached); assertEquals(p.key(), detached.key()); assertEquals(p.value(), detached.value()); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeVertexPropertyAsDetached() throws Exception { final KryoMapper kryoMapper = g.io().kryoMapper().create(); final Kryo kryo = kryoMapper.createMapper(); final VertexProperty vp = g.V(convertToVertexId("marko")).next().property("name"); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final Output output = new Output(stream); kryo.writeObject(output, vp); output.close(); final Input input = new Input(stream.toByteArray()); final VertexProperty detached = kryo.readObject(input, VertexProperty.class); input.close(); assertNotNull(detached); assertEquals(vp.label(), detached.label()); assertEquals(vp.id(), detached.id()); assertEquals(vp.value(), detached.value()); } @Test @LoadGraphWith(LoadGraphWith.GraphData.CREW) public void shouldSerializeVertexPropertyWithPropertiesAsDetached() throws Exception { final KryoMapper kryoMapper = g.io().kryoMapper().create(); final Kryo kryo = kryoMapper.createMapper(); final VertexProperty vp = g.V(convertToVertexId("marko")).next().iterators().propertyIterator("location").next(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final Output output = new Output(stream); kryo.writeObject(output, vp); output.close(); final Input input = new Input(stream.toByteArray()); final VertexProperty detached = kryo.readObject(input, VertexProperty.class); input.close(); assertNotNull(detached); assertEquals(vp.label(), detached.label()); assertEquals(vp.id(), detached.id()); assertEquals(vp.value(), detached.value()); assertEquals(vp.iterators().propertyIterator("startTime").next().value(), detached.iterators().propertyIterator("startTime").next().value()); assertEquals(vp.iterators().propertyIterator("startTime").next().key(), detached.iterators().propertyIterator("startTime").next().key()); assertEquals(vp.iterators().propertyIterator("endTime").next().value(), detached.iterators().propertyIterator("endTime").next().value()); assertEquals(vp.iterators().propertyIterator("endTime").next().key(), detached.iterators().propertyIterator("endTime").next().key()); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializePathAsDetached() throws Exception { final KryoMapper kryoMapper = g.io().kryoMapper().create(); final Kryo kryo = kryoMapper.createMapper(); final Path p = g.V(convertToVertexId("marko")).as("a").outE().as("b").inV().as("c").path().next(); final ByteArrayOutputStream stream = new ByteArrayOutputStream(); final Output output = new Output(stream); kryo.writeObject(output, p); output.close(); final Input input = new Input(stream.toByteArray()); final Path detached = kryo.readObject(input, Path.class); input.close(); assertNotNull(detached); assertEquals(p.labels().size(), detached.labels().size()); assertEquals(p.labels().get(0).size(), detached.labels().get(0).size()); assertEquals(p.labels().get(1).size(), detached.labels().get(1).size()); assertEquals(p.labels().get(2).size(), detached.labels().get(2).size()); assertTrue(p.labels().stream().flatMap(Collection::stream).allMatch(detached::hasLabel)); final Vertex vOut = p.get("a"); final Vertex detachedVOut = detached.get("a"); assertEquals(vOut.label(), detachedVOut.label()); assertEquals(vOut.id(), detachedVOut.id()); // this is a SimpleTraverser so no properties are present in detachment assertFalse(detachedVOut.iterators().propertyIterator().hasNext()); final Edge e = p.get("b"); final Edge detachedE = detached.get("b"); assertEquals(e.label(), detachedE.label()); assertEquals(e.id(), detachedE.id()); // this is a SimpleTraverser so no properties are present in detachment assertFalse(detachedE.iterators().propertyIterator().hasNext()); final Vertex vIn = p.get("c"); final Vertex detachedVIn = detached.get("c"); assertEquals(vIn.label(), detachedVIn.label()); assertEquals(vIn.id(), detachedVIn.id()); // this is a SimpleTraverser so no properties are present in detachment assertFalse(detachedVIn.iterators().propertyIterator().hasNext()); } } public static class GraphSONTest extends AbstractGremlinTest { private final TypeReference<HashMap<String, Object>> mapTypeReference = new TypeReference<HashMap<String, Object>>() { }; @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeVertex() throws Exception { final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper(); final Vertex v = g.V(convertToVertexId("marko")).next(); final String json = mapper.writeValueAsString(v); final Map<String, Object> m = mapper.readValue(json, mapTypeReference); assertEquals(GraphSONTokens.VERTEX, m.get(GraphSONTokens.TYPE)); assertEquals(v.label(), m.get(GraphSONTokens.LABEL)); assertNotNull(m.get(GraphSONTokens.ID)); assertEquals(v.value("name").toString(), ((Map) ((List) ((Map) m.get(GraphSONTokens.PROPERTIES)).get("name")).get(0)).get(GraphSONTokens.VALUE)); assertEquals((Integer) v.value("age"), ((Map) ((List) ((Map) m.get(GraphSONTokens.PROPERTIES)).get("age")).get(0)).get(GraphSONTokens.VALUE)); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeEdge() throws Exception { final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper(); final Edge e = g.E(convertToEdgeId("marko", "knows", "vadas")).next(); final String json = mapper.writeValueAsString(e); final Map<String, Object> m = mapper.readValue(json, mapTypeReference); assertEquals(GraphSONTokens.EDGE, m.get(GraphSONTokens.TYPE)); assertEquals(e.label(), m.get(GraphSONTokens.LABEL)); assertNotNull(m.get(GraphSONTokens.ID)); assertEquals((Double) e.value("weight"), ((Map) m.get(GraphSONTokens.PROPERTIES)).get("weight")); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeProperty() throws Exception { final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper(); final Property p = g.E(convertToEdgeId("marko", "knows", "vadas")).next().property("weight"); final String json = mapper.writeValueAsString(p); final Map<String, Object> m = mapper.readValue(json, mapTypeReference); // todo: decide if this should really include "key" and "type" since Property is a first class citizen assertEquals(p.value(), m.get(GraphSONTokens.VALUE)); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializeVertexProperty() throws Exception { final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper(); final VertexProperty vp = g.V(convertToVertexId("marko")).next().property("name"); final String json = mapper.writeValueAsString(vp); final Map<String, Object> m = mapper.readValue(json, mapTypeReference); // todo: should we have "type" here too? assertEquals(vp.label(), m.get(GraphSONTokens.LABEL)); assertNotNull(m.get(GraphSONTokens.ID)); assertEquals(vp.value(), m.get(GraphSONTokens.VALUE)); } @Test @LoadGraphWith(LoadGraphWith.GraphData.CREW) public void shouldSerializeVertexPropertyWithProperties() throws Exception { final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper(); final VertexProperty vp = g.V(convertToVertexId("marko")).next().iterators().propertyIterator("location").next(); final String json = mapper.writeValueAsString(vp); final Map<String, Object> m = mapper.readValue(json, mapTypeReference); // todo: should we have "type" here too? assertEquals(vp.label(), m.get(GraphSONTokens.LABEL)); assertNotNull(m.get(GraphSONTokens.ID)); assertEquals(vp.value(), m.get(GraphSONTokens.VALUE)); assertEquals(vp.iterators().propertyIterator("startTime").next().value(), ((Map) m.get(GraphSONTokens.PROPERTIES)).get("startTime")); assertEquals(vp.iterators().propertyIterator("endTime").next().value(), ((Map) m.get(GraphSONTokens.PROPERTIES)).get("endTime")); } @Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldSerializePath() throws Exception { final ObjectMapper mapper = g.io().graphSONMapper().create().createMapper(); final Path p = g.V(convertToVertexId("marko")).as("a").outE().as("b").inV().as("c").path().next(); final String json = mapper.writeValueAsString(p); final Map<String, Object> m = mapper.readValue(json, mapTypeReference); // todo: path is not asserted yet... /* assertEquals(p.labels().size(), detached.labels().size()); assertEquals(p.labels().get(0).size(), detached.labels().get(0).size()); assertEquals(p.labels().get(1).size(), detached.labels().get(1).size()); assertEquals(p.labels().get(2).size(), detached.labels().get(2).size()); assertTrue(p.labels().stream().flatMap(Collection::stream).allMatch(detached::hasLabel)); final Vertex vOut = p.get("a"); final Vertex detachedVOut = detached.get("a"); assertEquals(vOut.label(), detachedVOut.label()); assertEquals(vOut.id(), detachedVOut.id()); // this is a SimpleTraverser so no properties are present in detachment assertFalse(detachedVOut.iterators().propertyIterator().hasNext()); final Edge e = p.get("b"); final Edge detachedE = detached.get("b"); assertEquals(e.label(), detachedE.label()); assertEquals(e.id(), detachedE.id()); // this is a SimpleTraverser so no properties are present in detachment assertFalse(detachedE.iterators().propertyIterator().hasNext()); final Vertex vIn = p.get("c"); final Vertex detachedVIn = detached.get("c"); assertEquals(vIn.label(), detachedVIn.label()); assertEquals(vIn.id(), detachedVIn.id()); // this is a SimpleTraverser so no properties are present in detachment assertFalse(detachedVIn.iterators().propertyIterator().hasNext()); */ } } }
51.268212
157
0.636375
4b69058f34f732da10ee20a7862eb1e8482e1a24
239
//Francine de Paula Nogueira Santos public class Triangulo { public static void main (String[] args) { System.out.println("*"); System.out.println("**"); System.out.println("***"); System.out.println("****"); } }
18.384615
43
0.598326
1a0c19719590eb6b73f2d4e4134cf8c38f792c78
1,873
package com.vaadin.tests.elements.twincolselect; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import java.util.List; import org.junit.Before; import org.junit.Test; import com.vaadin.testbench.elements.LabelElement; import com.vaadin.testbench.elements.TwinColSelectElement; import com.vaadin.tests.tb3.MultiBrowserTest; public class TwinColSelectUITest extends MultiBrowserTest { TwinColSelectElement multiSelect; LabelElement multiCounterLbl; @Before public void init() { openTestURL(); multiSelect = $(TwinColSelectElement.class).first(); multiCounterLbl = $(LabelElement.class).id("multiCounterLbl"); } @Test public void testSelectDeselectByText() { multiSelect.selectByText("item2"); assertEquals("1: [item1, item2]", multiCounterLbl.getText()); multiSelect.selectByText("item3"); assertEquals("2: [item1, item2, item3]", multiCounterLbl.getText()); multiSelect.deselectByText("item2"); assertEquals("3: [item1, item3]", multiCounterLbl.getText()); } @Test public void testDeselectSelectByText() { multiSelect.deselectByText("item1"); assertEquals("1: []", multiCounterLbl.getText()); multiSelect.selectByText("item1"); assertEquals("2: [item1]", multiCounterLbl.getText()); } @Test public void testGetAvailableOptions() { assertAvailableOptions("item2", "item3"); multiSelect.selectByText("item2"); assertAvailableOptions("item3"); multiSelect.deselectByText("item1"); assertAvailableOptions("item1", "item3"); } private void assertAvailableOptions(String... items) { List<String> optionTexts = multiSelect.getAvailableOptions(); assertArrayEquals(items, optionTexts.toArray()); } }
32.293103
76
0.695141
fdc1802c27130aa6e6e4226a10d56fd10c3864f5
727
package org.mybatis.spring.cache; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * redis dao cache * @author lindezhi * 2015年12月4日 下午5:11:23 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface RedisCache { /** * 操作类型 * @return */ OperateType operate(); /** * * @return */ String key() default ""; /** * cache前缀 * @return */ String prefix() default ""; /** * 关联cache * @return */ String refPrefix() default ""; /** * 关联key * @return */ String refKey() default ""; int ttl() default RedisCacheService.EXPIRE_DAY; }
14.254902
48
0.65337
30962d937942e545e8605ec1c87cf5ef5fba5a32
4,288
/** * Copyright 2020 Alibaba Group Holding Limited. * * 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.alibaba.maxgraph.v2.frontend.server.loader; import com.alibaba.maxgraph.v2.common.config.Configs; import com.alibaba.maxgraph.v2.common.frontend.api.graph.GraphPartitionManager; import com.alibaba.maxgraph.v2.common.rpc.RoleClients; import com.alibaba.maxgraph.v2.common.frontend.api.schema.SchemaFetcher; import com.alibaba.maxgraph.v2.frontend.compiler.client.QueryExecuteRpcClient; import com.alibaba.maxgraph.v2.frontend.compiler.client.QueryManageRpcClient; import com.alibaba.maxgraph.v2.frontend.compiler.client.QueryStoreRpcClient; import com.alibaba.maxgraph.v2.frontend.context.GraphWriterContext; import com.alibaba.maxgraph.v2.frontend.server.gremlin.loader.MaxGraphOpLoader; import com.alibaba.maxgraph.v2.frontend.server.gremlin.processor.MaxGraphProcessor; import com.alibaba.maxgraph.v2.frontend.server.gremlin.processor.MaxGraphTraversalProcessor; import org.apache.tinkerpop.gremlin.server.Settings; import org.apache.tinkerpop.gremlin.server.op.OpLoader; /** * Load maxgraph processor instead of tinkerpop processor */ public class MaxGraphProcessorLoader implements ProcessorLoader { private Configs configs; private SchemaFetcher schemaFetcher; private GraphPartitionManager partitionManager; private RoleClients<QueryExecuteRpcClient> queryExecuteClients; private RoleClients<QueryStoreRpcClient> queryStoreClients; private RoleClients<QueryManageRpcClient> queryManageClients; private int executorCount; private GraphWriterContext graphWriterContext; public MaxGraphProcessorLoader(Configs configs, SchemaFetcher schemaFetcher, GraphPartitionManager partitionManager, RoleClients<QueryExecuteRpcClient> queryExecuteClients, RoleClients<QueryStoreRpcClient> queryStoreClients, RoleClients<QueryManageRpcClient> queryManageClients, int executorCount, GraphWriterContext graphWriterContext) { this.configs = configs; this.schemaFetcher = schemaFetcher; this.partitionManager = partitionManager; this.queryExecuteClients = queryExecuteClients; this.queryStoreClients = queryStoreClients; this.queryManageClients = queryManageClients; this.executorCount = executorCount; this.graphWriterContext = graphWriterContext; } @Override public void loadProcessor(Settings settings) { OpLoader.init(settings); MaxGraphProcessor maxGraphProcessor = new MaxGraphProcessor(configs, schemaFetcher, this.partitionManager, this.queryStoreClients, this.queryExecuteClients, this.queryManageClients, this.executorCount, this.graphWriterContext); maxGraphProcessor.init(settings); // replace StandardOpProcessor MaxGraphOpLoader.addOpProcessor(maxGraphProcessor.getName(), maxGraphProcessor); MaxGraphTraversalProcessor traversalProcessor = new MaxGraphTraversalProcessor(configs, schemaFetcher, this.partitionManager, this.queryStoreClients, this.queryExecuteClients, this.queryManageClients, this.executorCount, this.graphWriterContext); traversalProcessor.init(settings); // replace traversal processor MaxGraphOpLoader.addOpProcessor(traversalProcessor.getName(), traversalProcessor); } }
46.608696
95
0.713386
88491da0fc6b473ad92a6dfa3ef0f3d3076a5370
10,440
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce.customer; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Visits resource to manage all visits a customer makes to a tenant's sites and measure the level of transactions a customer performs during a unique visit for customer account analytics. Clients can track customer visits by site (including online and in-person interactions), the transactions a customer performs during the visit, and the device type associated with the visit, if any. * </summary> */ public class VisitClient { /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.VisitCollection> mozuClient=GetVisitsClient(); * client.setBaseAddress(url); * client.executeRequest(); * VisitCollection visitCollection = client.Result(); * </code></pre></p> * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.VisitCollection> * @see com.mozu.api.contracts.customer.VisitCollection */ public static MozuClient<com.mozu.api.contracts.customer.VisitCollection> getVisitsClient() throws Exception { return getVisitsClient( null, null, null, null, null); } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.VisitCollection> mozuClient=GetVisitsClient( startIndex, pageSize, sortBy, filter, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * VisitCollection visitCollection = client.Result(); * </code></pre></p> * @param filter A set of filter expressions representing the search parameters for a query. This parameter is optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for a list of supported filters. * @param pageSize When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with this parameter set to 25, to get the 51st through the 75th items, set startIndex to 50. * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param sortBy The element to sort the results by and the channel in which the results appear. Either ascending (a-z) or descending (z-a) channel. Optional. Refer to [Sorting and Filtering](../../../../Developer/api-guides/sorting-filtering.htm) for more information. * @param startIndex When creating paged results from a query, this value indicates the zero-based offset in the complete result set where the returned entities begin. For example, with pageSize set to 25, to get the 51st through the 75th items, set this parameter to 50. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.VisitCollection> * @see com.mozu.api.contracts.customer.VisitCollection */ public static MozuClient<com.mozu.api.contracts.customer.VisitCollection> getVisitsClient(Integer startIndex, Integer pageSize, String sortBy, String filter, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.VisitUrl.getVisitsUrl(filter, pageSize, responseFields, sortBy, startIndex); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.customer.VisitCollection.class; MozuClient<com.mozu.api.contracts.customer.VisitCollection> mozuClient = (MozuClient<com.mozu.api.contracts.customer.VisitCollection>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient=GetVisitClient( visitId); * client.setBaseAddress(url); * client.executeRequest(); * Visit visit = client.Result(); * </code></pre></p> * @param visitId Unique identifier of the customer visit to update. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.Visit> * @see com.mozu.api.contracts.customer.Visit */ public static MozuClient<com.mozu.api.contracts.customer.Visit> getVisitClient(String visitId) throws Exception { return getVisitClient( visitId, null); } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient=GetVisitClient( visitId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Visit visit = client.Result(); * </code></pre></p> * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param visitId Unique identifier of the customer visit to update. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.Visit> * @see com.mozu.api.contracts.customer.Visit */ public static MozuClient<com.mozu.api.contracts.customer.Visit> getVisitClient(String visitId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.VisitUrl.getVisitUrl(responseFields, visitId); String verb = "GET"; Class<?> clz = com.mozu.api.contracts.customer.Visit.class; MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient = (MozuClient<com.mozu.api.contracts.customer.Visit>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); return mozuClient; } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient=AddVisitClient( visit); * client.setBaseAddress(url); * client.executeRequest(); * Visit visit = client.Result(); * </code></pre></p> * @param visit Properties of a customer visit to one of a company's sites. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.Visit> * @see com.mozu.api.contracts.customer.Visit * @see com.mozu.api.contracts.customer.Visit */ public static MozuClient<com.mozu.api.contracts.customer.Visit> addVisitClient(com.mozu.api.contracts.customer.Visit visit) throws Exception { return addVisitClient( visit, null); } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient=AddVisitClient( visit, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Visit visit = client.Result(); * </code></pre></p> * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param visit Properties of a customer visit to one of a company's sites. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.Visit> * @see com.mozu.api.contracts.customer.Visit * @see com.mozu.api.contracts.customer.Visit */ public static MozuClient<com.mozu.api.contracts.customer.Visit> addVisitClient(com.mozu.api.contracts.customer.Visit visit, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.VisitUrl.addVisitUrl(responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.customer.Visit.class; MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient = (MozuClient<com.mozu.api.contracts.customer.Visit>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(visit); return mozuClient; } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient=UpdateVisitClient( visit, visitId); * client.setBaseAddress(url); * client.executeRequest(); * Visit visit = client.Result(); * </code></pre></p> * @param visitId Unique identifier of the customer visit to update. * @param visit Properties of a customer visit to one of a company's sites. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.Visit> * @see com.mozu.api.contracts.customer.Visit * @see com.mozu.api.contracts.customer.Visit */ public static MozuClient<com.mozu.api.contracts.customer.Visit> updateVisitClient(com.mozu.api.contracts.customer.Visit visit, String visitId) throws Exception { return updateVisitClient( visit, visitId, null); } /** * * <p><pre><code> * MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient=UpdateVisitClient( visit, visitId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Visit visit = client.Result(); * </code></pre></p> * @param responseFields Filtering syntax appended to an API call to increase or decrease the amount of data returned inside a JSON object. This parameter should only be used to retrieve data. Attempting to update data using this parameter may cause data loss. * @param visitId Unique identifier of the customer visit to update. * @param visit Properties of a customer visit to one of a company's sites. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.customer.Visit> * @see com.mozu.api.contracts.customer.Visit * @see com.mozu.api.contracts.customer.Visit */ public static MozuClient<com.mozu.api.contracts.customer.Visit> updateVisitClient(com.mozu.api.contracts.customer.Visit visit, String visitId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.customer.VisitUrl.updateVisitUrl(responseFields, visitId); String verb = "PUT"; Class<?> clz = com.mozu.api.contracts.customer.Visit.class; MozuClient<com.mozu.api.contracts.customer.Visit> mozuClient = (MozuClient<com.mozu.api.contracts.customer.Visit>) MozuClientFactory.getInstance(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(visit); return mozuClient; } }
50.434783
396
0.738602
78b31c48d01f79da5b19d45fdce4a707216771fd
6,819
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.constraintlayout.widget; import android.annotation.SuppressLint; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.view.View; /** * Utility class representing a Guideline helper object for * {@link ConstraintLayout}. * Helper objects are not displayed on device * (they are marked as {@code View.GONE}) and are only used * for layout purposes. They only work within a * {@link ConstraintLayout}. *<p> * A Guideline can be either horizontal or vertical: * <ul> * <li>Vertical Guidelines have a width of zero and the height of their * {@link ConstraintLayout} parent</li> * <li>Horizontal Guidelines have a height of zero and the width of their * {@link ConstraintLayout} parent</li> * </ul> *<p> * Positioning a Guideline is possible in three different ways: * <ul> * <li>specifying a fixed distance from the left or the top of a layout * ({@code layout_constraintGuide_begin})</li> * <li>specifying a fixed distance from the right or the bottom of a layout * ({@code layout_constraintGuide_end})</li> * <li>specifying a percentage of the width or the height of a layout * ({@code layout_constraintGuide_percent})</li> * </ul> * <p> * Widgets can then be constrained to a Guideline, * allowing multiple widgets to be positioned easily from * one Guideline, or allowing reactive layout behavior by using percent positioning. * <p> * See the list of attributes in * {@link androidx.constraintlayout.widget.ConstraintLayout.LayoutParams} to set a Guideline * in XML, as well as the corresponding {@link ConstraintSet#setGuidelineBegin}, * {@link ConstraintSet#setGuidelineEnd} * and {@link ConstraintSet#setGuidelinePercent} functions in {@link ConstraintSet}. * <p> * Example of a {@code Button} constrained to a vertical {@code Guideline}: * <pre> * <androidx.constraintlayout.widget.ConstraintLayout * xmlns:android="http://schemas.android.com/apk/res/android" * xmlns:app="http://schemas.android.com/apk/res-auto" * xmlns:tools="http://schemas.android.com/tools" * android:layout_width="match_parent" * android:layout_height="match_parent"> * * <androidx.constraintlayout.widget.Guideline * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:id="@+id/guideline" * app:layout_constraintGuide_begin="100dp" * android:orientation="vertical"/> * <Button * android:text="Button" * android:layout_width="wrap_content" * android:layout_height="wrap_content" * android:id="@+id/button" * app:layout_constraintLeft_toLeftOf="@+id/guideline" * android:layout_marginTop="16dp" * app:layout_constraintTop_toTopOf="parent" /> * </androidx.constraintlayout.widget.ConstraintLayout> * </pre> * <p/> */ public class Guideline extends View { private boolean mFilterRedundantCalls = true; public Guideline(Context context) { super(context); super.setVisibility(View.GONE); } public Guideline(Context context, AttributeSet attrs) { super(context, attrs); super.setVisibility(View.GONE); } public Guideline(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); super.setVisibility(View.GONE); } public Guideline(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr); super.setVisibility(View.GONE); } /** * @DoNotShow */ @Override public void setVisibility(int visibility) { } /** * We are overriding draw and not calling super.draw() here because * Helper objects are not displayed on device. * * @DoNotShow */ @SuppressLint("MissingSuperCall") @Override public void draw(Canvas canvas) { } /** * @DoNotShow */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(0, 0); } /** * Set the guideline's distance from the top or left edge. * * @param margin the distance to the top or left edge */ public void setGuidelineBegin(int margin) { ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) getLayoutParams(); if (mFilterRedundantCalls && params.guideBegin == margin) { return; } params.guideBegin = margin; setLayoutParams(params); } /** * Set a guideline's distance to end. * * @param margin the margin to the right or bottom side of container */ public void setGuidelineEnd(int margin) { ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) getLayoutParams(); if (mFilterRedundantCalls && params.guideEnd == margin) { return; } params.guideEnd = margin; setLayoutParams(params); } /** * Set a Guideline's percent. * @param ratio the ratio between the gap on the left and right 0.0 is top/left 0.5 is middle */ public void setGuidelinePercent(float ratio) { ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) getLayoutParams(); if (mFilterRedundantCalls && params.guidePercent == ratio) { return; } params.guidePercent = ratio; setLayoutParams(params); } /** * filter redundant calls to setGuidelineBegin, setGuidelineEnd & setGuidelinePercent. * * By default calling setGuidelineStart,setGuideLineEnd and setGuidelinePercent will do nothing * if the value is the same as the current value. This can disable that behaviour and call * setLayoutParams(..) while will call requestLayout * * @param filter default true set false to always generate a setLayoutParams */ public void setFilterRedundantCalls(boolean filter) { this.mFilterRedundantCalls = filter; } }
35.701571
99
0.673119
35cf0f73976f03e20b69fd550a35d1837f000837
553
package org.quickstart.example.algorithm.seek; /** * @author youngzil@163.com * @description TODO * @createTime 2019/12/5 22:31 */ public class OrderSearch { /** * 顺序查找平均时间复杂度 O(n) * * @param searchKey 要查找的值 * @param array 数组(从这个数组中查找) * @return 查找结果(数组的下标位置) */ public static int orderSearch(int searchKey, int[] array) { if (array == null || array.length < 1) { return -1; } for (int i = 0; i < array.length; i++) { if (array[i] == searchKey) { return i; } } return -1; } }
18.433333
61
0.56962
bb0e2f8d7a779a881547e4613f00af8ea60193c7
4,039
package com.xbw.spring.boot.cache; import com.xbw.spring.boot.project.controller.CacheController; import com.xbw.spring.boot.project.model.Person; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.cache.CacheManager; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import java.util.concurrent.TimeUnit; @SpringBootTest class RedisTests { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Autowired CacheManager cacheManager; @Autowired private StringRedisTemplate stringRedisTemplate; @Autowired private RedisTemplate redisTemplate; @Autowired private CacheController cacheController; private MockMvc mockMvc; @BeforeEach public void setup() { mockMvc = MockMvcBuilders.standaloneSetup(cacheController).build(); } @Test void cache() { logger.info("CacheManager -> {}", cacheManager.getClass()); cacheManager.getCacheNames() .forEach(cacheName -> logger.info("CacheName -> {}, \nCache -> {}, \nNativeCache -> {}", cacheName, cacheManager.getCache(cacheName).getClass(), cacheManager.getCache(cacheName).getNativeCache().getClass())); } @Test void testMvc() throws Exception { MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/cache/1")) .andExpect(MockMvcResultMatchers.status().isOk()) .andDo(MockMvcResultHandlers.print()) .andReturn(); Assertions.assertEquals("{\"id\":1,\"userName\":\"name1\",\"nickName\":\"n1\",\"birthday\":\"1970-01-01\"}", mvcResult.getResponse().getContentAsString()); } @Test void testStr() throws Exception { stringRedisTemplate.opsForValue().set("test", "test"); Assertions.assertEquals("test", stringRedisTemplate.opsForValue().get("test")); } @Test void testObj() throws Exception { Person person = new Person("aa", "a", "1970-01-01"); ValueOperations<String, Person> operations = redisTemplate.opsForValue(); String basePackage = "com.xbw.spring.boot.project.model"; operations.set(basePackage, person); //redisTemplate.delete(basePackage); // Assertions.assertEquals(true, redisTemplate.hasKey(basePackage)); Assertions.assertTrue(redisTemplate.hasKey(basePackage)); Assertions.assertEquals("aa", operations.get(basePackage).getUserName()); } @Test void testObjTime() throws Exception { Person person = new Person("bb", "b", "1970-01-01"); ValueOperations<String, Person> operations = redisTemplate.opsForValue(); String basePackage = "com.xbw.spring.boot.project.model"; operations.set(basePackage, person, 2, TimeUnit.SECONDS); //redisTemplate.delete(basePackage); // Assertions.assertEquals(true, redisTemplate.hasKey(basePackage)); Assertions.assertTrue(redisTemplate.hasKey(basePackage)); Assertions.assertEquals("bb", operations.get(basePackage).getUserName()); Thread.sleep(2000); // Assertions.assertEquals(false, redisTemplate.hasKey(basePackage)); Assertions.assertFalse(redisTemplate.hasKey(basePackage)); } }
42.968085
163
0.714038
582dce28bcfa78b5b3bfe994c35396d44f75a0ae
169
open module dev.dominion.ecs.engine.benchmarks { requires dev.dominion.ecs.api; requires dev.dominion.ecs.engine; requires jmh.core; requires jol.core; }
28.166667
48
0.727811
43f4a602cead7745eace8d75beb0d439cab2b88b
1,768
/** * 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.atlas.repository.ogm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; import javax.inject.Inject; import java.util.HashMap; import java.util.Map; import java.util.Set; @Component public class DTORegistry { private static final Logger LOG = LoggerFactory.getLogger(DTORegistry.class); private final Map<Class, DataTransferObject> typeDTOMap = new HashMap<>(); @Inject public DTORegistry(Set<DataTransferObject> availableDTOs) { for (DataTransferObject availableDTO : availableDTOs) { LOG.info("Registering DTO: {}", availableDTO.getClass().getSimpleName()); registerDTO(availableDTO); } } public <T extends DataTransferObject> DataTransferObject get(Class t) { return typeDTOMap.get(t); } private void registerDTO(DataTransferObject dto) { typeDTOMap.put(dto.getObjectType(), dto); } }
34.666667
85
0.733597
d1914111789c50051671f57869ed8f0709878794
458
package io.maphey.lock.zk.lock.annotation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:spring-context.xml" }) public class ZkLockTest { @Test public void test() { testLock(); } @ZkLock("test11") public void testLock() { } }
20.818182
71
0.777293
e10153eaf29c1c1caab90a87e7118c403d36fc17
4,503
/* * Copyright 2015 Open Networking Laboratory * * 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.onosproject.bgpio.types; import org.jboss.netty.buffer.ChannelBuffer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides BGP Message Header which is common for all the Messages. */ public class BgpHeader { /* 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | + + | | + + | Marker | + + | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Length | Type | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ protected static final Logger log = LoggerFactory.getLogger(BgpHeader.class); public static final int MARKER_LENGTH = 16; public static final short DEFAULT_HEADER_LENGTH = 19; private byte[] marker; private byte type; private short length; /** * Reset fields. */ public BgpHeader() { this.marker = null; this.length = 0; this.type = 0; } /** * Constructors to initialize parameters. * * @param marker field in BGP header * @param length message length * @param type message type */ public BgpHeader(byte[] marker, short length, byte type) { this.marker = marker; this.length = length; this.type = type; } /** * Sets marker field. * * @param value marker field */ public void setMarker(byte[] value) { this.marker = value; } /** * Sets message type. * * @param value message type */ public void setType(byte value) { this.type = value; } /** * Sets message length. * * @param value message length */ public void setLength(short value) { this.length = value; } /** * Returns message length. * * @return message length */ public short getLength() { return this.length; } /** * Returns message marker. * * @return message marker */ public byte[] getMarker() { return this.marker; } /** * Returns message type. * * @return message type */ public byte getType() { return this.type; } /** * Writes Byte stream of BGP header to channel buffer. * * @param cb ChannelBuffer * @return length index of message header */ public int write(ChannelBuffer cb) { cb.writeBytes(getMarker(), 0, MARKER_LENGTH); int headerLenIndex = cb.writerIndex(); cb.writeShort((short) 0); cb.writeByte(type); return headerLenIndex; } /** * Read from channel buffer and Returns BGP header. * * @param cb ChannelBuffer * @return object of BGPHeader */ public static BgpHeader read(ChannelBuffer cb) { byte[] marker = new byte[MARKER_LENGTH]; byte type; short length; cb.readBytes(marker, 0, MARKER_LENGTH); length = cb.readShort(); type = cb.readByte(); return new BgpHeader(marker, length, type); } }
27.968944
82
0.467466
0c0dc08f0ca8634bdcd8ccf11e405290233e723e
1,562
package com.trkj.framework.mybatisplus.service; import com.baomidou.mybatisplus.core.metadata.IPage; import com.trkj.framework.entity.mybatisplus.Card; import com.trkj.framework.entity.mybatisplus.Leave; import com.trkj.framework.vo.*; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; /** * <p> * 请假表 服务类 * </p> * * @author 里予 * @since 2022-1-2 */ public interface LeaveService { /** * 根据审批类型的加班/审批人查询待处理的审批 * * @param * @return */ IPage<Auditflowone> selectLeaveAll(Auditflowone auditflowone); /** * 根据审批类型的加班/审批人查询已处理的审批 * * @param * @return */ IPage<Auditflowone> selectEndLeaveAll(Auditflowone auditflowone); /** * 根据审批类型的加班/审批人查询已处理的详情信息 * * @param * @return */ List<LeaveDetailsVo> selectDetailsLeaves(LeaveDetailsVo leaveDetailsVo); /** * 根据员工名称是否有补打卡记录 * * @param leaveDetailsVo * @return */ @PostMapping("/selectLeaveExamine") List<LeaveDetailsVo> selectLeaveExamine(LeaveDetailsVo leaveDetailsVo); /** * 添加请假 添加三个审批人 * * @param leaveVo * @return */ int submitToAskForLeave3(LeaveVo leaveVo) throws ArithmeticException; /** * 添加请假 添加两个审批人 * * @param leaveVo * @return */ int submitToAskForLeave2(LeaveVo leaveVo) throws ArithmeticException; /** * 添加请假 添加一个审批人 * * @param leaveVo * @return */ Integer submitToAskForLeave1(LeaveVo leaveVo) throws ArithmeticException; }
20.285714
77
0.642125
60d2da7e3aa517b017fef48c4a90eaf86be4c2a2
2,283
package com.example.android.miwok; import android.content.Context; import android.support.v4.content.ContextCompat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.ArrayList; public class WordAdapter extends ArrayAdapter<Word> { private int mColorResourceId; public WordAdapter(Context context, ArrayList<Word> words, int colorResourceId) { super(context, 0, words); mColorResourceId = colorResourceId; } @Override public View getView(int position, View convertView, ViewGroup parent) { View listItemView = convertView; if (listItemView == null) { listItemView = LayoutInflater.from(getContext()).inflate( R.layout.list_item, parent, false); } Word currentWord = getItem(position); TextView miwokTextView = (TextView) listItemView.findViewById(R.id.miwok_text_view); miwokTextView.setText(currentWord.getMiwokTranslation()); TextView defaultTextView = (TextView) listItemView.findViewById(R.id.default_text_view); defaultTextView.setText(currentWord.getDefaultTranslation()); ImageView imageView = (ImageView) listItemView.findViewById(R.id.image); // Check if an image is provided for this word or not if (currentWord.hasImage()) { // If an image is available, display the provided image based on the resource ID imageView.setImageResource(currentWord.getImageResourceId()); // Make sure the view is visible imageView.setVisibility(View.VISIBLE); } else { // Otherwise hide the ImageView (set visibility to GONE) imageView.setVisibility(View.GONE); } // Set the theme color for the list item View textContainer = listItemView.findViewById(R.id.text_container); // Find the color that the resource ID maps to int color = ContextCompat.getColor(getContext(), mColorResourceId); // Set the background color of the text container View textContainer.setBackgroundColor(color); return listItemView; } }
34.074627
96
0.693824
fa09673f27c13fb0a1a17eb4bc865d394a44c791
486
package pl.cwanix.opensun.authserver.packet.c2s.auth; import pl.cwanix.opensun.authserver.packet.AuthServerPacketOPCode; import pl.cwanix.opensun.commonserver.packets.Packet; import pl.cwanix.opensun.commonserver.packets.annotations.IncomingPacket; @IncomingPacket(category = AuthServerPacketOPCode.Auth.CATEGORY, operation = AuthServerPacketOPCode.Auth.Ask.SRV_LIST) public class C2SAskSrvListPacket implements Packet { public C2SAskSrvListPacket(final byte[] value) { } }
34.714286
118
0.82716
3ac8468afb5ad72614b16a4fd63d5d9c9bec051a
820
package catsrabbits; import java.util.*;import javax.media.opengl.GL2;import javax.media.opengl.glu.GLU; public class CatGroup implements CritterGroup{ private List<Cat>cats=new ArrayList<Cat>(); public CatGroup(GL2 gl,GLU glu){ // format: init x, init y, init z, init angle, speed, tRate, gl, glu cats.add(new Cat(213.25f,3.49f,492.73f,23.62f,.25f,.04f,gl,glu)); cats.add(new Cat(117.39f,2.88f,549.33f,114.69f,.15f,.02f,gl,glu)); cats.add(new Cat(35.14f,4.71f,287.56f,234.01f,.2f,.025f,gl,glu)); cats.add(new Cat(458.2f,4.05f,112.93f,81.09f,.2f,.025f,gl,glu)); cats.add(new Cat(306.18f,3.04f,6.85f,349.4f,.25f,.04f,gl,glu)); cats.add(new Cat(544.86f,5.13f,460.12f,181.27f,.15f,.02f,gl,glu)); } public void draw(GL2 gl,GLU glu){ for(Cat cat:cats) cat.draw(gl, glu); } }
37.272727
84
0.668293
d6c3c9e39f2354b7619adb45dd1a2e2347271417
2,313
package com.diguage.algorithm.leetcode; /** * = 378. Kth Smallest Element in a Sorted Matrix * * https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/[Kth Smallest Element in a Sorted Matrix - LeetCode] * * Given a n x n matrix where each of the rows and columns are sorted in ascending order, find the kth smallest element in the matrix. * * Note that it is the kth smallest element in the sorted order, not the kth distinct element. * * .Example: * [source] * ---- * matrix = [ * [ 1, 5, 9], * [10, 11, 13], * [12, 13, 15] * ], * k = 8, * * return 13. * ---- * * *Note:* * * You may assume k is always valid, 1 ≤ k ≤ n2. * * * @author D瓜哥, https://www.diguage.com/ * @since 2020-01-23 18:08 */ public class _0378_KthSmallestElementInASortedMatrix { /** * Runtime: 0 ms, faster than 100.00% of Java online submissions for Kth Smallest Element in a Sorted Matrix. * * Memory Usage: 56.2 MB, less than 5.41% of Java online submissions for Kth Smallest Element in a Sorted Matrix. * * Copy from: https://leetcode.com/problems/kth-smallest-element-in-a-sorted-matrix/discuss/85173/Share-my-thoughts-and-Clean-Java-Code[Share my thoughts and Clean Java Code - LeetCode Discuss] */ public int kthSmallest(int[][] matrix, int k) { int low = matrix[0][0]; int length = matrix.length; int high = matrix[length - 1][length - 1]; while (low < high) { int mid = low + (high - low) / 2; int count = 0; int j = length - 1; for (int i = 0; i < length; i++) { while (j >= 0 && mid < matrix[i][j]) { j--; } count += (j + 1); } if (count < k) { low = mid + 1; } else { high = mid; } } return low; } public static void main(String[] args) { _0378_KthSmallestElementInASortedMatrix solution = new _0378_KthSmallestElementInASortedMatrix(); int[][] matrix = { {1, 5, 9}, {10, 11, 13}, {12, 13, 15} }; int r1 = solution.kthSmallest(matrix, 8); System.out.println((r1 == 13) + " : " + r1); } }
30.84
197
0.543882
75146305c9a4de66a2fb7ccd283782ea72ba8b01
2,012
package com.tazine.algorithm.playground; import java.util.Arrays; /** * QuickSort Practice * * @author frank * @since 1.0.0 */ public class QuickSort { public static void main(String[] args) { int[] arr = {69, 62, 89, 37, 97, 17, 28, 49}; //quickSort(arr, 0, arr.length - 1); sort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); } private static void sort(int[] arr, int low, int high){ if (low < high){ int mid = getMiddle(arr, low, high); sort(arr, 0, mid-1); sort(arr, mid+1, high); } } private static int getMiddle(int[] arr, int low, int high) { int temp; int base = arr[low]; int i = low; int j = high; while (i != j){ while ((i < j) && (arr[j]) >= base){ j--; } while ((i < j) && (arr[i] <= base)){ i++; } if (i < j){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } arr[low] = arr[i]; arr[i] = base; return i; } public static void quickSort(int[] arr, int low, int high) { int i, j, base, tmp; if (low >= high) { return; } base = arr[low]; i = low; j = high; while (i != j) { while ((arr[j] >= base) && (i < j)) { j--; } while ((arr[i] <= base) && (i < j)) { i++; } if (i < j) { tmp = arr[j]; arr[j] = arr[i]; arr[i] = tmp; } System.out.println("i = " + i + " -- j = " + j); System.out.println(Arrays.toString(arr)); System.out.println(); } arr[low] = arr[i]; arr[i] = base; quickSort(arr, low, i - 1); quickSort(arr, i + 1, high); } }
24.839506
64
0.390656
19fc4b1237a5b2178ccccc67fdff7ab55c0c08d3
519
package pr0x79.instrumentation.exception; import pr0x79.instrumentation.accessor.IAccessor; /** * This exception is thrown when something goes wrong with * an {@link IAccessor} during the registration or instrumentation */ public class InstrumentorException extends RuntimeException { /** * */ private static final long serialVersionUID = 5129156768385369898L; public InstrumentorException(String msg) { super(msg); } public InstrumentorException(String msg, Exception exc) { super(msg, exc); } }
22.565217
67
0.764933