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
6d032411422869418908e5827f7ad15f245d4ea0
2,492
package io.funbet.security; import io.funbet.model.entity.UserEntity; import io.funbet.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.Cacheable; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.stereotype.Component; import org.thymeleaf.util.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.Optional; @Component public class JdbcAuthenticationProvider implements AuthenticationProvider { @Autowired UserRepository userRepository; @Override /*@Cacheable(value = "funbet", key = "'user#' + #authentication.getName().hashCode() + '#' + #authentication.getCredentials().toString().hashCode()", condition = "#authentication.getCredentials() != null")*/ public Authentication authenticate(Authentication authentication) throws AuthenticationException { String email = authentication.getName(); String password = authentication.getCredentials().toString(); UsernamePasswordAuthenticationToken token = Optional.ofNullable(userRepository.findByEmail(email.toLowerCase())) .filter(u -> u.getPassword().equals(password)) .map(u -> { List<GrantedAuthority> list = new ArrayList<>(); if(u.getRole() == UserEntity.Role.ADMIN) list.add(new SimpleGrantedAuthority(UserEntity.Role.ADMIN.name())); else list.add(new SimpleGrantedAuthority(UserEntity.Role.USER.name())); return new UsernamePasswordAuthenticationToken(u, password, list); }) .orElseThrow(() -> new BadCredentialsException("Authentication failed for user = " + email)); return token; } @Override public boolean supports(Class<?> authentication) { return authentication.equals( UsernamePasswordAuthenticationToken.class); } }
43.719298
130
0.715891
6c82da9ec087f8fdd116823f50c7a15ad03790e6
158
package ch.hslu.pcp.sw8; public interface GeneralInterface { default public void doIt() { System.out.println("Do it the GENERAL way."); } }
17.555556
53
0.658228
ff304757c2c5e0a35e291ba915bb3c22f09311e4
9,040
/******************************************************************************* * Copyright 2015 - CNRS (Centre National de Recherche Scientifique) * * 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 fr.univnantes.lina; import java.io.PrintStream; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import org.apache.commons.lang3.mutable.MutableInt; import com.google.common.collect.LinkedListMultimap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; /** * The access point-class of all uima-profiler functionalities. * * @author Damien Cram * */ public class UIMAProfiler implements ITaskProfiler { private static boolean activated = false; private static boolean latexFormat = false; // private static int skipExamples = 0; private static int exampleLimit = 5; private static int overSizeRatio = 5; private static float addToExampleProba = 0.02f; public static void setActivated(boolean activated) { UIMAProfiler.activated = activated; } // public static void setSkipExamples(int skipExamples) { // TaskProfiler.skipExamples = skipExamples; // } public static void setExampleLimit(int exampleLimit) { UIMAProfiler.exampleLimit = exampleLimit; } public static void setLatexFormat(boolean latexFormat) { UIMAProfiler.latexFormat = latexFormat; } private static final Map<String, ITaskProfiler> profilers = Maps.newLinkedHashMap(); public static final ITaskProfiler getProfiler(String name) { if(activated) { ITaskProfiler profiler = profilers.get(name); if(profiler != null) return profiler; else { profiler = new UIMAProfiler(name); profilers.put(name, profiler); return profiler; } } else { return DoNothingProfiler.getInstance(); } } private String name; private Map<String, Object> pointStatus = Maps.newLinkedHashMap(); private Map<String, MutableInt> counters = Maps.newLinkedHashMap(); private Map<String, Set<Object>> examples = Maps.newHashMap(); private Multimap<String, ProfilingTask> tasks = LinkedListMultimap.create(); private Map<String, ProfilingTask> tasksById = Maps.newHashMap(); private UIMAProfiler(String name) { this.name = name; } /* (non-Javadoc) * @see fr.cnrs.uima.profiler.ITaskProfiler#hit(java.lang.String) */ @Override public void hit(String hitName) { if(counters.get(hitName) == null) counters.put(hitName, new MutableInt(1)); else counters.get(hitName).increment(); } @Override public void initHit(String hitName) { if(counters.get(hitName) == null) counters.put(hitName, new MutableInt(0)); } /* (non-Javadoc) * @see fr.cnrs.uima.profiler.ITaskProfiler#hit(java.lang.String, java.lang.Object) */ @Override public void hit(String hitName, Object example) { this.hit(hitName); if(this.examples.get(hitName) == null) this.examples.put(hitName, new HashSet<Object>()); Set<Object> exBuffer = this.examples.get(hitName); if(!exBuffer.contains(example)) { if(exBuffer.size() <= overSizeRatio*exampleLimit) exBuffer.add(example); else { if(new Random().nextFloat() < addToExampleProba) { removeRandomElement(exBuffer); exBuffer.add(example); } } } } private void removeRandomElement(Set<Object> set) { int atIndex = new Random().nextInt(set.size()); int k = 0; Iterator<Object> it = set.iterator(); it.next(); while(k < atIndex) { k++; it.next(); } it.remove(); } /* (non-Javadoc) * @see fr.cnrs.uima.profiler.ITaskProfiler#pointStatus(java.lang.String, java.lang.Object) */ @Override public void pointStatus(String point, Object message) { pointStatus.put(point, message); } /* (non-Javadoc) * @see fr.cnrs.uima.profiler.ITaskProfiler#start(java.lang.Object, java.lang.String) */ @Override public void start(Object o, String taskName) { String classTaskId = getClassTaskId(o, taskName); ProfilingTask task = new ProfilingTask(); tasksById.put(classTaskId, task); task.start(); } private String getClassTaskId(Object o, String taskName) { return System.identityHashCode(o) + ":" + taskName; } private String getClassTaskName(Object o, String taskName) { return o.getClass().getSimpleName() + ":" + taskName; } /* (non-Javadoc) * @see fr.cnrs.uima.profiler.ITaskProfiler#stop(java.lang.Object, java.lang.String) */ @Override public long stop(Object o, String taskName) { String classTaskName = getClassTaskName(o, taskName); ProfilingTask task = tasksById.get(getClassTaskId(o, taskName)); tasks.put(classTaskName, task); return task.stop(); } /* (non-Javadoc) * @see fr.cnrs.uima.profiler.ITaskProfiler#display(java.io.PrintStream) */ @Override public void display(PrintStream stream) { if(isEmpty()) return; stream.println("###########################################################################################"); stream.println("#################################### " + this.name + " ####################################"); stream.println("###########################################################################################"); String formatString = "%30s %10sms\n"; if(!tasks.isEmpty()) { stream.println("--------------- Tasks --------------"); for(String taskName:tasks.keySet()) { long t = 0; for(ProfilingTask task:tasks.get(taskName)) t += task.getTotal(); stream.format( formatString, taskName, t ); } stream.format( formatString, "TOTAL", getTotal()); } if(!counters.isEmpty()) { stream.println("--------------- Hits ------------------"); formatString = "%30s %10s\n"; long total = 0; Comparator<String> comp = new Comparator<String>() { @Override public int compare(String o1, String o2) { return Integer.compare(counters.get(o2).intValue(), counters.get(o1).intValue()); } }; List<String> sortedkeys = new LinkedList<String>(); sortedkeys.addAll(counters.keySet()); Collections.sort(sortedkeys, comp); for(String hitName:sortedkeys) { int h = counters.get(hitName).intValue(); total += h; stream.format( formatString, hitName, h ); } stream.format( formatString, "TOTAL", total); if(latexFormat) { stream.println("--------------- Hits (Latex) ----------"); total = 0; sortedkeys = new LinkedList<String>(); sortedkeys.addAll(counters.keySet()); Collections.sort(sortedkeys, comp); for(String hitName:sortedkeys) { int h = counters.get(hitName).intValue(); total += h; stream.println(hitName + " & " + counters.get(hitName).intValue() + " \\\\"); } stream.println("TOTAL & " + total + " \\\\"); } } if(!examples.isEmpty()) { stream.println("-------------- Examples ---------------"); List<String> keySet = Lists.newArrayList(examples.keySet()); Collections.shuffle(keySet); for(String hitName:keySet) { int i = 0; stream.println("* " + hitName); for(Object o:examples.get(hitName)) { i++; if(i>exampleLimit) break; String str = o == null ? "null" : o.toString().replaceAll("\n", " ").replaceAll("\r", " ").toLowerCase(); stream.println("\t" + str); } } } if(!pointStatus.isEmpty()) { stream.println("-------------- Point status -----------"); for(String point:pointStatus.keySet()) { stream.println(point + ": " + pointStatus.get(point)); } } stream.flush(); } private boolean isEmpty() { return tasks.isEmpty() && counters.isEmpty() && pointStatus.isEmpty(); } private long getTotal() { long t = 0; for(String taskName:tasks.keySet()) { for(ProfilingTask task:tasks.get(taskName)) t += task.getTotal(); } return t; } public static void displayAll(PrintStream ps) { for(String name:profilers.keySet()) profilers.get(name).display(ps); } public static void resetAll() { profilers.clear(); } public static boolean isActivated() { return activated; } }
29.16129
112
0.644248
74867f4e959e14eada58b4cae0370a2efb470f2a
1,032
package com.pedromateus.zupacadey.MercadoLivre.config; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter; import org.springframework.security.oauth2.provider.token.store.JwtTokenStore; import java.util.logging.Filter; @Configuration public class BeansConfig { @Bean public BCryptPasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public JwtAccessTokenConverter accessTokenConverter() { JwtAccessTokenConverter tokenConverter = new JwtAccessTokenConverter(); tokenConverter.setSigningKey("MY-JWT-SECRET"); return tokenConverter; } @Bean public JwtTokenStore tokenStore() { return new JwtTokenStore(accessTokenConverter()); } }
29.485714
88
0.781977
a6bbb57c7dc85c3c5fa93c4677fb95d9be65ff47
2,610
package dev.bstk.gameokkjogoforca.domain.service.factory; import com.fasterxml.jackson.databind.ObjectMapper; import dev.bstk.gameokkjogoforca.domain.model.Dica; import dev.bstk.gameokkjogoforca.domain.model.PalavraSecreta; import org.springframework.core.io.ClassPathResource; import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class PalavraSecretaFactory { private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); private static final SecureRandom SECURE_RANDOM = new SecureRandom(); private static final String RESOURCES_FORCA_PALAVRAS_SECRETAS = "/forca/palavra-secreta.json"; private PalavraSecretaFactory() { } public static PalavraSecreta palavra() { final var palavraSecretas = carregarArquivoJsonComBancoDePalavrasSecretas(); final var totalPalavras = palavraSecretas.size(); final var palavraSecretaIndex = SECURE_RANDOM.nextInt(totalPalavras); final var palavraSecreta = palavraSecretas.get(palavraSecretaIndex); return PalavraSecretaBuilder .builder() .palavra(palavraSecreta.getPalavra()) .dicas(palavraSecreta.getDicas()) .build(); } private static List<PalavraSecreta> carregarArquivoJsonComBancoDePalavrasSecretas() { try { final var json = new ClassPathResource(RESOURCES_FORCA_PALAVRAS_SECRETAS).getFile(); final var palavrasSecretas = JSON_MAPPER.readValue(json, PalavraSecreta[].class); return Arrays.asList(palavrasSecretas); } catch (IOException ex) { throw new ArquivoNaoEncontradoException("Não foi possivél localizar o json!", ex); } } private static final class PalavraSecretaBuilder { private final PalavraSecreta palavra; public PalavraSecretaBuilder() { this.palavra = new PalavraSecreta(); this.palavra.setPalavra(new ArrayList<>()); this.palavra.setDicas(new ArrayList<>()); } public static PalavraSecretaBuilder builder() { return new PalavraSecretaBuilder(); } public PalavraSecretaBuilder palavra(final List<String> palavraSercreta) { this.palavra.setPalavra(palavraSercreta); return this; } public PalavraSecretaBuilder dicas(final List<Dica> dicas) { this.palavra.setDicas(dicas); return this; } public PalavraSecreta build() { return this.palavra; } } }
34.342105
98
0.691188
cfc1075a483953e765df612d7369f164d0f07486
1,191
package com.dv.student.api.controller; import com.dv.student.api.exception.BadRequestException; import com.dv.student.api.model.Student; import com.dv.student.api.service.StudentService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import javax.validation.constraints.NotBlank; import java.util.List; @RestController public class StudentRestApiController { private static final Logger logger = LoggerFactory.getLogger(StudentRestApiController.class); @Autowired private StudentService studentService; @RequestMapping(method = RequestMethod.GET, value = "/students/{searchParam}") public List<Student> autoSuggest(@PathVariable("searchParam") @NotBlank String searchParam){ if(searchParam.length() > 0){ logger.debug("Starting search by using parameter :{}", searchParam); return studentService.getAutoComplete(searchParam); } else { logger.debug("Null search parameter :{}", searchParam); throw new BadRequestException("Search parameter is invalid"); } } }
36.090909
97
0.739715
874f603dacd308cb926585d00bb203831d5c92b0
488
package com.lufax.jijin.ylx.request.domain; import com.lufax.jijin.ylx.batch.dto.YLXBatchDTO; import com.lufax.jijin.ylx.batch.dto.YLXBatchFileDTO; import java.io.File; import java.math.BigDecimal; public interface IYLXRequestWriter { public static final int ROWNUM = 500; // batchSize public BigDecimal writeRequestContent(File newFile, YLXBatchFileDTO batchFile, long start, long end, long total, YLXBatchDTO batch, int fileSize); public long getTotalRecords(long batchId); }
28.705882
147
0.79918
5ab40cd11ebb9555b10d84ae8b87454856d34229
4,225
package com.vbyte.decisionengine.fields; import com.alibaba.fastjson.JSON; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Objects; @TableName("fields_msg") public class ExpandField implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 * */ @TableId(value = "id", type = IdType.AUTO) protected String id; /** * 字段名 * */ @TableField("name") protected String name; /** * 字段类型 * */ @TableField(exist = false) protected Class<?> type; /** * 字段类型的名称 * */ @TableField("type_name") protected String typeName; /** * 表名 * */ @TableField("table_name") protected String tableName; /** * 该字段信息所属于该表的第table_id条字段 * */ @TableField("table_id") protected String tableId; /** * 字段值 * */ @TableField(exist = false) public Object value; /** * 字段值经过json序列化之后的值 * */ @TableField("json_value") protected String jsonValue; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public void setTypeName (String typeName) { this.typeName = typeName; try { this.type = Class.forName(this.typeName); } catch (ClassNotFoundException e) { e.printStackTrace(); } if (this.jsonValue != null) { this.value = JSON.parseObject(this.jsonValue,type); } } public void setTableId(String tableId) { this.tableId = tableId; } public Class<?> getType() { return type; } public String getTypeName() { return typeName; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getTableId() { return tableId; } public Object getValue() { return value; } public String getJsonValue() { return jsonValue; } public void setJsonValue(String jsonValue) { this.jsonValue = jsonValue; if (this.type != null) { this.value = JSON.parseObject(this.jsonValue,type); } } @Override public String toString() { return "BaseField{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", type=" + type + ", typeName='" + typeName + '\'' + ", tableName='" + tableName + '\'' + ", tableId='" + tableId + '\'' + ", value=" + value + ", jsonValue='" + jsonValue + '\'' + '}'; } public boolean isEqual(Object o) { if (this == o) return true; if (!(o instanceof ExpandField)) return false; ExpandField that = (ExpandField) o; return getId().equals(that.getId()) && getName().equals(that.getName()) && getType().equals(that.getType()) && getTypeName().equals(that.getTypeName()) && getTableName().equals(that.getTableName()) && getTableId().equals(that.getTableId()) && getValue().equals(that.getValue()) && getJsonValue().equals(that.getJsonValue()); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ExpandField)) return false; ExpandField expandField = (ExpandField) o; return Objects.equals(getName(), expandField.getName()) && Objects.equals(getTableName(), expandField.getTableName()) && Objects.equals(getTableId(), expandField.getTableId()); } @Override public int hashCode() { return Objects.hash(getName(), getTableName(), getTableId()); } }
24.005682
77
0.551716
795696a8a29f5561b07a72a09c705c6585adabc0
1,817
package com.github.zeroone3010.openinghoursparser; import java.time.DayOfWeek; import java.time.format.DateTimeFormatter; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import java.util.Optional; final class LocalizedTokens { private final Map<String, TokenType> tokens = new LinkedHashMap<>(); /** * Creates a LocalizedTokens instance for English names of the days of the week. */ public LocalizedTokens() { this(Locale.ENGLISH); } /** * Creates a LocalizedTokens instance for the names of the days of the week in the given locale. * * @param locale A Locale that specifies the language that the names of the days of the week should use. */ public LocalizedTokens(final Locale locale) { final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE", locale); tokens.put(formatter.format(DayOfWeek.MONDAY), TokenType.MONDAY); tokens.put(formatter.format(DayOfWeek.TUESDAY), TokenType.TUESDAY); tokens.put(formatter.format(DayOfWeek.WEDNESDAY), TokenType.WEDNESDAY); tokens.put(formatter.format(DayOfWeek.THURSDAY), TokenType.THURSDAY); tokens.put(formatter.format(DayOfWeek.FRIDAY), TokenType.FRIDAY); tokens.put(formatter.format(DayOfWeek.SATURDAY), TokenType.SATURDAY); tokens.put(formatter.format(DayOfWeek.SUNDAY), TokenType.SUNDAY); tokens.put("-", TokenType.RANGE_INDICATOR); tokens.put("\\d\\d:\\d\\d", TokenType.TIME); tokens.put("\\s", TokenType.WHITE_SPACE); tokens.put(",", TokenType.SCHEDULE_SEPARATOR); tokens.put(".+\\s", TokenType.UNKNOWN); } Optional<Token> match(final String candidate) { return tokens.keySet().stream() .filter(candidate::matches) .map(tokens::get) .findAny() .map(type -> new Token(type, candidate)); } }
34.942308
106
0.719318
833847db15d6434f749980757f8c565e9968753f
3,211
package com.zoctan.api.controller; import com.zoctan.api.core.response.Result; import com.zoctan.api.core.response.ResultGenerator; import com.zoctan.api.entity.Dbvariables; import com.zoctan.api.entity.Enviroment; import com.zoctan.api.entity.Project; import com.zoctan.api.service.ProjectService; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.springframework.web.bind.annotation.*; import tk.mybatis.mapper.entity.Condition; import javax.annotation.Resource; import java.util.List; import java.util.Map; /** * @author SeasonFan * @date 2022/03/27 */ @RestController @RequestMapping("/project") public class ProjectController { @Resource private ProjectService projectService; @PostMapping public Result add(@RequestBody Project project) { Condition con=new Condition(Project.class); con.createCriteria().andCondition("projectname = '" + project.getProjectname().replace("'","''") + "'"); if(projectService.ifexist(con)>0) { return ResultGenerator.genFailedResult("项目,迭代名已经存在"); } else { projectService.save(project); return ResultGenerator.genOkResult(); } } @DeleteMapping("/{id}") public Result delete(@PathVariable Long id) { projectService.deleteById(id); return ResultGenerator.genOkResult(); } @PatchMapping public Result update(@RequestBody Project project) { projectService.update(project); return ResultGenerator.genOkResult(); } @GetMapping("/{id}") public Result detail(@PathVariable Long id) { Project project = projectService.getById(id); return ResultGenerator.genOkResult(project); } @GetMapping public Result list(@RequestParam(defaultValue = "0") Integer page, @RequestParam(defaultValue = "0") Integer size) { PageHelper.startPage(page, size); List<Project> list = projectService.listAll(); PageInfo<Project> pageInfo = PageInfo.of(list); return ResultGenerator.genOkResult(pageInfo); } @PutMapping("/detail") public Result updateDeploy(@RequestBody final Project dic) { Condition con=new Condition(Project.class); con.createCriteria().andCondition("projectname = '" + dic.getProjectname().replace("'","''") + "'").andCondition("id <> " + dic.getId()); if(projectService.ifexist(con)>0) { return ResultGenerator.genFailedResult("项目,迭代名已经存在"); } else { this.projectService.updateProject(dic); return ResultGenerator.genOkResult(); } } /** * 输入框查询 */ @PostMapping("/search") public Result search(@RequestBody final Map<String, Object> param) { Integer page= Integer.parseInt(param.get("page").toString()); Integer size= Integer.parseInt(param.get("size").toString()); PageHelper.startPage(page, size); final List<Project> list = this.projectService.findProjectWithName(param); final PageInfo<Project> pageInfo = new PageInfo<>(list); return ResultGenerator.genOkResult(pageInfo); } }
32.434343
145
0.66459
ffe10ed0be5c368d2e1296bb68484bce80e98257
7,866
/* * Copyright 2003-2020 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.mps.openapi.persistence; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.mps.openapi.model.SModel; import org.jetbrains.mps.openapi.model.SModelName; import org.jetbrains.mps.openapi.persistence.datasource.DataSourceType; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.List; import static org.jetbrains.mps.openapi.persistence.MFProblem.NO_PROBLEM; /** * Represents a data source loading/saving/upgrading strategy. * * The location resides rather on the {@link DataSource} * side than here while the storage parameters belong here. * NB: The <code>ModelFactory</code> knows about <code>DataSource</code> but * not vice versa. * * creates/saves/loads models (instances of SModel) from data sources. * * @author apyshkin, others */ public interface ModelFactory { /** * Determines whether the provided data source is maintained by this model factory instance. * Consider calling it before load/create/upgrade methods in order to avoid {@link UnsupportedDataSourceException}. * * @return true iff the given data source can be managed by this factory */ boolean supports(@NotNull DataSource dataSource); /** * Some issues can arise when one tries to create a model onto some data source. * For instance, data source might be read-only or such model name already exists and data source does not support two different * models with the same names. * * Call it before #create invocation. * * @param dataSource target of you model write * @param modelName the new model's name * @param options the additional options you will pass to {@link #create} * @return the problem from which you can extract some text presentation * or {@link MFProblem#NO_PROBLEM} if there is no problem */ @NotNull default MFProblem canCreate(@NotNull DataSource dataSource, @NotNull SModelName modelName, @NotNull ModelLoadingOption... options) { if (!supports(dataSource)) { return new DataSourceNotSupportedProblem(dataSource); } return NO_PROBLEM; } /** * Creates a new model with the supplied <code>modelName</code> on the given <code>DataSource</code>. * Might consider additional options provided in the <code>options</code> varargs. * [General rule: options.contain(SomeOption) => SomeOption is on] * * @param dataSource -- location to create the model in * @param modelName -- a new model name (note that it might be constructed easily from full-qualified <code>String</code>) * @param options -- custom options * @see ModelLoadingOption * @return newly created model * * @throws UnsupportedDataSourceException iff {@link #supports(DataSource)} returns false * @throws ModelCreationException iff there was an irrecoverable problem during creation (for instance model file already exists) * or {@link #canCreate} returns false */ @NotNull SModel create(@NotNull DataSource dataSource, @NotNull SModelName modelName, @NotNull ModelLoadingOption... options) throws UnsupportedDataSourceException, ModelCreationException; /** * Loads an existing model from the given <code>DataSource</code>. * Might consider additional options provided in the <code>options</code> varargs. * [General rule: options.contain(SomeOption) => SomeOption is on] * * @param dataSource -- location to load model from * @param options -- custom options * @see ModelLoadingOption * @return loaded model * * @throws UnsupportedDataSourceException iff {@link #supports(DataSource)} returns false * @throws ModelLoadException iff there was an irrecoverable load problem (for instance format was broken or unrecognized) */ @NotNull SModel load(@NotNull DataSource dataSource, @NotNull ModelLoadingOption... options) throws UnsupportedDataSourceException, ModelLoadException; /** * Saves the model to the provided data source in the factory-specific format (including conversion when needed). */ void save(@NotNull SModel model, @NotNull DataSource dataSource) throws ModelSaveException, IOException; /** * Serialize the model to the provided data source in the factory-specific format with respect to options, if any * @throws ModelSaveException in case serialization fails */ default void save(@NotNull SModel model, @NotNull DataSource dataSource, @Nullable ModelSaveOption ... options) throws ModelSaveException { final ModelSaveOption mandatoryOption = options != null ? Arrays.stream(options).filter(ModelSaveOption::mandatory).findFirst().orElse(null) : null; if (mandatoryOption != null) { final String m = String.format("Could not handle mandatory save option %s", mandatoryOption); throw new ModelSaveException(m, Collections.emptySet()); } try { save(model, dataSource); } catch (IOException ex) { throw new ModelSaveException(ex.getMessage(), Collections.emptySet(), ex); } } /** * Returns an id which is used to get model factory by id in the * {@code ModelFactoryService}. * * @return model factory unique identification entity */ @NotNull ModelFactoryType getType(); /** * As for 193 we have multiple versions for the model persistence. * Essentially the different versions of the same persistence could be represented by {@link ModelFactory}. * This method returns true when the version of the particular persistence is not the latest and could be updated. * * In that case the resaving the model will probably fix the problem. */ default boolean needsUpgrade(@NotNull DataSource dataSource) throws IOException { return false; } /** * Declares a list of preferred data source formats, * sorted from the most preferred to the less preferred data source type. * * fixme [AP] I will move it from here since it does not relate to the API of the model factory itself, * it is just a plugin for DefaultModelRoot to enable automatic 'data source' <-> 'model factory' * relation. * It was a mistake to put this method here in the first place. * * @return a list of data source kinds which might be considered when MPS * meets a data source location and needs to choose a model factory * which is likely to support the content of the data source. * For instance if we have data source types associated with file names (e.g. prefix or suffix) * we are able to establish a file name pattern association with a specific model factory. * For example each model file which ends with '.mps_binary' suffix would be associated with the * corresponding data source type which in turn would be associated with 'MyBinaryModelFactory'. */ @Deprecated(since = "193", forRemoval = true) @NotNull List<DataSourceType> getPreferredDataSourceTypes(); }
44.948571
152
0.705187
a3574c21188d495ebd4b948a555b2bef9329d4f4
1,414
package com.bai.ding.common.exception.handler; import com.bai.ding.common.Result; import com.bai.ding.common.exception.JwtException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; /** * @author BaiDing * @date 2020/3/22 21:04 */ @RestControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 处理JWT自定义异常 */ @ExceptionHandler(JwtException.class) public Result handleJwtException(JwtException e) { logger.error("Token验证异常信息:{}", e.getMessage(), e); return new Result.Builder().error().setCode(e.getCode()).setMessage(e.getMessage()).build(); } /** * 处理所有不可知的异常 */ @ExceptionHandler(Exception.class) public Result handleOtherException(Exception e) { // 打印异常信息 logger.error("服务器发生未知错误:{}", e.getMessage(), e); return new Result.Builder().error().setMessage("系统繁忙,请稍后重试").build(); } @ExceptionHandler(Throwable.class) public Result handleThrowable(Throwable throwable) { // 打印异常信息 logger.error("服务器发生严重错误: {}", throwable.getMessage(), throwable); return new Result.Builder().error().setCode(20006).setMessage("系统出问题了,请联系管理员哦").build(); } }
31.422222
100
0.700141
72bda4bfcaa5994e17976cc7e1380cd2d77b400f
1,434
package org.fitting.dnsproxy.server; import static org.apache.commons.lang.StringUtils.startsWith; /** Session utils. */ public final class SessionUtils { public static String GET = "GET"; public static String HEAD = "HEAD"; public static String POST = "POST"; public static String PUT = "PUT"; public static String CONNECT = "CONNECT"; public static String OPTIONS = "OPTIONS"; public static String CONTENT_LENGTH = "CONTENT-LENGTH"; public static String PROXY_CONNECTION = "Proxy-Connection:"; public static String COOKIE = "Cookie:"; public static String REFERER = "Referer:"; public static String USER_AGENT = "User-Agent"; /** * Tests what method is used with the reqest * @return -1 if the server doesn't support the method */ public static int httpMethodId(final String httpMethod) { if (startsWith(httpMethod, GET) || startsWith(httpMethod, HEAD)) { return 0; } else if (startsWith(httpMethod, POST) || startsWith(httpMethod, PUT)) { return 1; } else if (startsWith(httpMethod, CONNECT)) { return 2; } else if (startsWith(httpMethod, OPTIONS)) { return 3; } else { return -1; /** * No match... * Following methods are not implemented: || * startsWith(httpMethod,"TRACE") */ } } }
34.142857
81
0.610181
81ed3f1daa5c5d0d7a2e67da6c65c0cc0e98319d
14,032
/* * Copyright (C) Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.games.bridge; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; import android.util.Log; import android.view.View; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInStatusCodes; import com.google.android.gms.common.GooglePlayServicesUtil; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.common.api.CommonStatusCodes; import com.google.android.gms.common.api.PendingResult; import com.google.android.gms.common.api.Scope; import com.google.android.gms.common.api.Status; import com.google.android.gms.games.Games; import com.google.android.gms.games.GamesActivityResultCodes; import com.google.android.gms.games.multiplayer.Invitation; import com.google.android.gms.games.multiplayer.realtime.Room; import com.google.android.gms.tasks.Task; /** * Activity fragment with no UI added to the parent activity in order to manage * requests with required onActivityResult handling. */ public class HelperFragment extends Fragment { private static final String TAG = "HelperFragment"; private static final String FRAGMENT_TAG = "gpg.HelperFragment"; static final int RC_SIGN_IN = 9002; static final int RC_SIMPLE_UI = 9003; static final int RC_SELECT_SNAPSHOT_UI = 9004; static final int RC_CAPTURE_OVERLAY_UI = 9005; static final int RC_SELECT_OPPONENTS_UI = 9006; static final int RC_INBOX_UI = 9007; static final int RC_SHOW_WAITING_ROOM_UI = 9008; static final int RC_SHOW_INVITATION_INBOX_UI = 9009; // Pending token request. There can be only one outstanding request at a // time. private static final Object lock = new Object(); private static Request pendingRequest, runningRequest; private static HelperFragment helperFragment; private static boolean mStartUpSignInCheckPerformed = false; /** * External entry point for getting tokens and email address. This * creates the fragment if needed and queues up the request. The fragment, once * active processes the list of requests. * * @param parentActivity - the parent activity to attach the fragment to. * @param requestAuthCode - request a server auth code to exchange on the * server for an OAuth token. * @param requestEmail - request the email address of the user. This * requires the consent of the user. * @param requestIdToken - request an OAuth ID token for the user. This * requires the consent of the user. * @param webClientId - the client id of the associated web application. * This is required when requesting auth code or id * token. The client id must be associated with the same * client as this application. * @param forceRefreshToken - force refreshing the token when requesting * a server auth code. This causes the consent * screen to be presented to the user, so it * should be used only when necessary (if at all). * @param additionalScopes - Additional scopes to request. These will most * likely require the consent of the user. * @param hidePopups - Hides the popups during authentication and game * services events. This done by calling * GamesOptions.setShowConnectingPopup. This is usful for * VR apps. * @param accountName - if non-null, the account name to use when * authenticating. * * @return PendingResult for retrieving the results when ready. */ public static PendingResult fetchToken(Activity parentActivity, boolean silent, boolean requestAuthCode, boolean requestEmail, boolean requestIdToken, String webClientId, boolean forceRefreshToken, String[] additionalScopes, boolean hidePopups, String accountName) { SignInRequest request = new SignInRequest(silent, requestAuthCode, requestEmail, requestIdToken, webClientId, forceRefreshToken, additionalScopes, hidePopups, accountName); if(!HelperFragment.startRequest(parentActivity, request)) { request.setFailure(CommonStatusCodes.DEVELOPER_ERROR); } return request.getPendingResponse(); } public static Task<Integer> showAchievementUi(Activity parentActivity) { AchievementUiRequest request = new AchievementUiRequest(); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static void showCaptureOverlayUi(Activity parentActivity) { CaptureOverlayUiRequest request = new CaptureOverlayUiRequest(); HelperFragment.startRequest(parentActivity, request); } public static Task<Integer> showAllLeaderboardsUi(Activity parentActivity) { AllLeaderboardsUiRequest request = new AllLeaderboardsUiRequest(); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static Task<Integer> showLeaderboardUi(Activity parentActivity, String leaderboardId, int timeSpan) { LeaderboardUiRequest request = new LeaderboardUiRequest(leaderboardId, timeSpan); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static Task<SelectSnapshotUiRequest.Result> showSelectSnapshotUi( Activity parentActivity, /* @NonNull */ String title, boolean allowAddButton, boolean allowDelete, int maxSnapshots) { SelectSnapshotUiRequest request = new SelectSnapshotUiRequest(title, allowAddButton, allowDelete, maxSnapshots); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(SelectSnapshotUiRequest.SELECT_UI_STATUS_UI_BUSY); } return request.getTask(); } public static Task<BaseSelectOpponentsUiRequest.Result> showRtmpSelectOpponentsUi(Activity parentActivity, int minOpponents, int maxOpponents) { RtmpSelectOpponentsUiRequest request = new RtmpSelectOpponentsUiRequest(minOpponents, maxOpponents); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static Task<BaseSelectOpponentsUiRequest.Result> showTbmpSelectOpponentsUi(Activity parentActivity, int minOpponents, int maxOpponents) { TbmpSelectOpponentsUiRequest request = new TbmpSelectOpponentsUiRequest(minOpponents, maxOpponents); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static Task<ShowWaitingRoomUiRequest.Result> showWaitingRoomUI(Activity parentActivity, Room room, int minParticipantsToStart) { ShowWaitingRoomUiRequest request = new ShowWaitingRoomUiRequest(room, minParticipantsToStart); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(ShowWaitingRoomUiRequest.UI_STATUS_BUSY, null); } return request.getTask(); } public static Task<ShowInvitationInboxUIRequest.Result> showInvitationInboxUI(Activity parentActivity) { ShowInvitationInboxUIRequest request = new ShowInvitationInboxUIRequest(); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static Task<InboxUiRequest.Result> showInboxUi(Activity parentActivity){ InboxUiRequest request = new InboxUiRequest(); if(!HelperFragment.startRequest(parentActivity, request)) { request.setResult(CommonUIStatus.UI_BUSY); } return request.getTask(); } public static void signOut(Activity activity) { GoogleSignInClient signInClient = GoogleSignIn.getClient(activity, GoogleSignInOptions.DEFAULT_GAMES_SIGN_IN); signInClient.signOut(); synchronized (lock) { pendingRequest = null; runningRequest = null; } } private static boolean startRequest(Activity parentActivity, Request request) { boolean ok = false; synchronized (lock) { if (pendingRequest == null && runningRequest == null) { pendingRequest = request; ok = true; } } if (ok) { HelperFragment helperFragment = HelperFragment.getHelperFragment(parentActivity); if (helperFragment.isResumed()) { helperFragment.processRequest(); } } return ok; } private static HelperFragment getHelperFragment(Activity parentActivity) { HelperFragment fragment = (HelperFragment) parentActivity.getFragmentManager().findFragmentByTag(FRAGMENT_TAG); if (fragment == null) { try { Log.d(TAG, "Creating fragment"); fragment = new HelperFragment(); FragmentTransaction trans = parentActivity.getFragmentManager().beginTransaction(); trans.add(fragment, FRAGMENT_TAG); trans.commit(); } catch (Throwable th) { Log.e(TAG, "Cannot launch token fragment:" + th.getMessage(), th); return null; } } return fragment; } /** * Processes the token requests that are queued up. */ private void processRequest() { Request request; synchronized (lock) { if (runningRequest != null) { return; } request = pendingRequest; pendingRequest = null; runningRequest = request; } // no request, no need to continue. if (request == null) { return; } request.process(this); } /** * Receive the result from a previous call to * {@link #startActivityForResult(Intent, int)}. This follows the * related Activity API as described there in * {@link Activity#onActivityResult(int, int, Intent)}. * * @param requestCode The integer request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode The integer result code returned by the child activity * through its setResult(). * @param data An Intent, which can return result data to the caller */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Request request; synchronized (lock) { request = runningRequest; } // no request, no need to continue. if (request == null) { return; } request.onActivityResult(requestCode, resultCode, data); } /** * Called when the fragment is visible to the user and actively running. * This is generally * tied to {@link Activity#onResume() Activity.onResume} of the containing * Activity's lifecycle. */ @Override public void onResume() { Log.d(TAG, "onResume called"); super.onResume(); if (helperFragment == null) { helperFragment = this; } processRequest(); } static void finishRequest(Request request) { synchronized (lock) { if(runningRequest == request) { runningRequest = null; } } } interface Request { void process(HelperFragment helperFragment); void onActivityResult(int requestCode, int resultCode, Intent data); }; public static GoogleSignInAccount getAccount(Activity activity) { return GoogleSignIn.getLastSignedInAccount(activity); } public static View createInvisibleView(Activity parentActivity) { View view = new View(parentActivity); view.setVisibility(View.INVISIBLE); view.setClickable(false); return view; } public static View getDecorView(Activity activity) { return activity.getWindow().getDecorView(); } }
39.750708
148
0.652223
15c0292e7445afb9057374a2267db9ad23e4bde2
3,266
package es.nimio.nimiogcs.maven.subtareas.proyecto; import es.nimio.nimiogcs.errores.ErrorInesperadoOperacion; import es.nimio.nimiogcs.jpa.entidades.operaciones.ProcesoAsincrono; import es.nimio.nimiogcs.jpa.entidades.proyectos.ElementoBaseProyecto; import es.nimio.nimiogcs.jpa.entidades.proyectos.EtiquetaProyecto; import es.nimio.nimiogcs.jpa.entidades.proyectos.Proyecto; import es.nimio.nimiogcs.jpa.entidades.proyectos.usos.ProyeccionMavenDeProyecto; import es.nimio.nimiogcs.jpa.entidades.proyectos.usos.UsoYProyeccionProyecto; import es.nimio.nimiogcs.jpa.entidades.sistema.RepositorioCodigo; import es.nimio.nimiogcs.operaciones.ProcesoAsincronoModulo; import es.nimio.nimiogcs.servicios.IContextoEjecucion; import es.nimio.nimiogcs.servicios.externos.Subversion; public class EliminarEstructuraBaseProyeccion extends ProcesoAsincronoModulo<ElementoBaseProyecto> { public EliminarEstructuraBaseProyeccion(IContextoEjecucion contextoEjecucion) { super(contextoEjecucion); } // -- @Override protected String nombreUnicoOperacion(ElementoBaseProyecto elementoProyecto, ProcesoAsincrono op) { return "ELIMINAR ESTRUCTURA MAVEN EN REPOSITORIO PARA '" + elementoProyecto.getNombre() + "'"; } @Override protected void relacionarOperacionConEntidades(ElementoBaseProyecto elementoProyecto, ProcesoAsincrono op) { // relacionamos con el elemento y, si es una etiqueta, con el proyecto registraRelacionConOperacion(op, elementoProyecto); if(elementoProyecto instanceof EtiquetaProyecto) registraRelacionConOperacion(op, ((EtiquetaProyecto)elementoProyecto).getProyecto()); } @Override protected void hazlo(ElementoBaseProyecto datos, ProcesoAsincrono op) throws ErrorInesperadoOperacion { // se trata de coger el uso Maven que tenga y eliminar del repositorio la estructura, // eliminando también el susodicho uso escribeMensaje("Buscar la proyección Maven dentro de los usos registrados."); ProyeccionMavenDeProyecto pmv = null; for(UsoYProyeccionProyecto upp: datos.getUsosYProyecciones()) { if(!(upp instanceof ProyeccionMavenDeProyecto)) continue; pmv = (ProyeccionMavenDeProyecto)upp; break; } if(pmv!=null) { escribeMensaje("Proyección Maven encontrada. URL de repositorio: " + pmv.getUrlRepositorio()); // el registro de repositorio lo sacamos del proyecto final Proyecto p = datos instanceof Proyecto ? (Proyecto)datos : ((EtiquetaProyecto)datos).getProyecto(); final RepositorioCodigo rc = p.getEnRepositorio(); // creamos la conexión a subversion final Subversion svn = new Subversion(rc); // tanto confirmar existencia como la eliminación trabajan con subrutas final String subruta = pmv.getUrlRepositorio().replace(rc.getUriRaizRepositorio() + "/", ""); // si existe la estructura, simplemente la eliminamos if(svn.existeElementoRemoto(subruta)) { escribeMensaje("Eliminar la estructura de repositorio."); svn.eliminarCarpeta(subruta); } else { escribeMensaje(">> No existe la estructura de repositorio."); } // terminamos eliminándola escribeMensaje("Eliminar registro de la proyección."); ce.usosProyecto().delete(pmv); } } }
41.341772
110
0.766993
d2a2e2f9c93120b3e2610fd0a6acbea2bda15a5f
110
package com.petstore.whale.client; public interface Cache<K, V> { void put(K k, V v); V get(K k); }
13.75
34
0.618182
9bc3cac215c14613cf0a083ac97eace94eb225a7
3,629
package edu.fiuba.algo3.controlador; import edu.fiuba.algo3.modelo.Partida; import edu.fiuba.algo3.modelo.ciudad.Ciudad; import edu.fiuba.algo3.modelo.jugador.Jugador; import edu.fiuba.algo3.vista.ContenedorJuego; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.SubScene; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.MenuButton; import javafx.scene.control.MenuItem; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.scene.paint.Paint; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.stage.Popup; import javafx.stage.Stage; import java.util.ArrayList; public class BotonViajar implements EventHandler<ActionEvent> { private Button botonJugar; private Stage stage; private Jugador jugador; private ContenedorJuego stackPane; private Partida partida; public BotonViajar(Button botonJugar, Stage stage, Jugador jugador, ContenedorJuego stackPane, Partida partida) { this.botonJugar = botonJugar; this.stage = stage; this.jugador = jugador; this.stackPane = stackPane; this.partida = partida; botonJugar.setText("Viajar"); botonJugar.setFont(Font.font("FreeSerif", FontWeight.EXTRA_BOLD, 40)); botonJugar.setTextFill(Color.rgb(255, 150, 69)); botonJugar.setBackground(new Background(new BackgroundFill(Color.BLACK, CornerRadii.EMPTY, Insets.EMPTY))); } @Override public void handle(ActionEvent eventoNuevo) { String textoClickeado = "Me han clickeado"; System.out.println(textoClickeado); VBox contenedorCiudades = new VBox(); ArrayList<Ciudad> ciudadesDisponibles = jugador.getCiudadActual().getCiudadesDisponiblesParaViajar(); if (jugador.getCiudadActual().getCiudadesDisponiblesParaViajar().size() == 3){ Button boton1 = new Button(); BotonViajeACiudad botonCiudad1 = new BotonViajeACiudad(boton1, stage, ciudadesDisponibles.get(0), jugador, partida); boton1.setOnAction(botonCiudad1); Button boton2 = new Button(); BotonViajeACiudad botonCiudad2 = new BotonViajeACiudad(boton2, stage, ciudadesDisponibles.get(1), jugador, partida); boton2.setOnAction(botonCiudad2); Button boton3 = new Button(ciudadesDisponibles.get(2).getNombre().getCaracteristica()); BotonViajeACiudad botonCiudad3 = new BotonViajeACiudad(boton3, stage, ciudadesDisponibles.get(2), jugador, partida); boton3.setOnAction(botonCiudad3); contenedorCiudades.getChildren().addAll(boton1,boton2,boton3); } else{ Button boton1 = new Button(); BotonViajeACiudad botonCiudad1 = new BotonViajeACiudad(boton1, stage, ciudadesDisponibles.get(0), jugador, partida); boton1.setOnAction(botonCiudad1); contenedorCiudades.getChildren().add(boton1); } Button boton = new Button(); BotonRetroceder botonRetroceder = new BotonRetroceder(boton, stage, stage.getScene()); boton.setOnAction(botonRetroceder); contenedorCiudades.getChildren().add(boton); StackPane nuevoStackPane = new StackPane(contenedorCiudades); contenedorCiudades.setAlignment(Pos.CENTER); contenedorCiudades.setSpacing(30); Scene nuevaEscena = new Scene(nuevoStackPane,1280,720); stage.setScene(nuevaEscena); stage.show(); } }
40.775281
128
0.718104
6a7aad620ad25cefce268cc0ceff24e23cf777e6
834
package com.example.pengyuanfan.fablix.util; import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.Button; /** * Created by pengyuanfan on 6/9/2016. */ public class DontPressWithParentButton extends Button { public DontPressWithParentButton(Context context) { super(context); } public DontPressWithParentButton(Context context, AttributeSet attrs) { super(context, attrs); } public DontPressWithParentButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setPressed(boolean pressed) { if (pressed && getParent() instanceof View && ((View) getParent()).isPressed()) { return; } super.setPressed(pressed); } }
26.0625
89
0.689448
a59d5d12c3128e00a12c4c73a59135464142f82b
726
package <%= basePackage %>.model.dto.<%= snakeResourceName %>; import java.io.Serializable; import java.util.List; import org.seasar.doma.Entity; import org.seasar.doma.Transient; import org.seasar.doma.jdbc.entity.NamingType; import <%= basePackage %>.model.entity.<%= resourceName %>; import lombok.Data; /** * <%= resourceNameKana %>検索APIのレスポンスDTO * * @author yeoman * */ @Entity(naming = NamingType.SNAKE_LOWER_CASE) @Data public class <%= resourceName %>SearchResponse implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = 1L; /** * 総件数 */ private long count; /** * 検索結果 */ @Transient private List<<%= resourceName %>> <%=camelResourceName %>s; }
18.615385
72
0.695592
9b3ee5cb8b99fb586aed33f43b2bc8cfb3464dc8
233
package io.cattle.platform.api.requesthandler; import io.github.ibuildthecloud.gdapi.request.ApiRequest; import java.io.IOException; public interface ScriptsHandler { boolean handle(ApiRequest request) throws IOException; }
19.416667
58
0.811159
eb088df7f68ef4ef5ca67819586e95d97b57bc5f
709
package com.hamusuke.battlebgmplayer.network.packet.c2s; import io.netty.buffer.ByteBuf; import net.minecraft.entity.EntityLiving; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; public final class ContactServerMobC2SPacket implements IMessage { private int mobId; public ContactServerMobC2SPacket() { } public ContactServerMobC2SPacket(EntityLiving clientMob) { this.mobId = clientMob.getEntityId(); } @Override public void fromBytes(ByteBuf buf) { this.mobId = buf.readInt(); } @Override public void toBytes(ByteBuf buf) { buf.writeInt(this.mobId); } public int getMobId() { return this.mobId; } }
22.870968
66
0.700987
3697babbfc129d469fe1c007081cb3310f4c17ee
8,870
package md2html; import java.io.*; import java.util.ArrayList; import java.util.List; public class Md2Html { private static final String encoding = "UTF-8"; public static void main(String[] args) { if (args.length != 2) { System.err.println("usage: java Md2Html <file.in> <file.out>"); return; } convert(args[0], args[1]); } private static void convert(final String fileIn, final String fileOut) { StringBuilder input = new StringBuilder(); try { try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileIn), encoding))) { int ch = reader.read(); while (ch != -1) { input.append((char) ch); ch = reader.read(); } } } catch (UnsupportedEncodingException e) { System.err.println("Unsupported encoding: " + encoding); } catch (FileNotFoundException e) { System.err.println("Cannot find input file: " + fileIn); } catch (IOException e) { System.err.println("Error while reading from: " + fileIn); } try { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileOut), encoding))) { StringBuilder string = new StringBuilder(); int inputPos = 0; input.append(" "); while (inputPos < input.length()) { int last = input.charAt(inputPos++); int curr = input.charAt(inputPos++); while (inputPos < input.length() && (last == '\r' || last == '\n')) { last = curr; curr = input.charAt(inputPos++); } while (inputPos < input.length() && (last != '\n' || curr != '\r') && (last != '\n' || curr != '\n')) { string.append((char) last); last = curr; curr = input.charAt(inputPos++); } while (string.charAt(string.length() - 1) == '\r' || string.charAt(string.length() - 1) == '\n') { string.delete(string.length() - 1, string.length()); } List<Integer> isPairTag = checkPairs(string); int pos = 0; int ch = string.charAt(pos++); int size = string.length(); int headerCounter = 0; while (pos < size && ch == '#') { headerCounter++; ch = string.charAt(pos++); } if ((char) ch == ' ' && headerCounter > 0) { writer.write("<h" + headerCounter + ">"); convertInput(string, pos, writer, isPairTag); writer.write("</h" + headerCounter + ">"); } else { writer.write("<p>"); for (int i = 0; i < headerCounter; i++) { writer.write("#"); } convertInput(string, pos - 1, writer, isPairTag); writer.write("</p>"); } writer.newLine(); string.delete(0, string.length()); } } } catch (UnsupportedEncodingException e) { System.err.println("Unsupported encoding: " + encoding); } catch (FileNotFoundException e) { System.err.println("Cannot create or change: " + fileOut); } catch (IOException e) { System.err.println("Failed to write to the output file: " + fileOut); } } private static List<Integer> checkPairs(StringBuilder string) { List<Integer> pairs = new ArrayList<>(); List<Integer> tags = new ArrayList<>(); int last; int curr; string.append(" "); for (int pos = 0; pos < string.length() - 1; pos++) { last = string.charAt(pos); curr = string.charAt(pos + 1); if (last == '\\') { pos++; continue; } int key = keyOf(last, curr); if (key != 0) { tags.add(key); pairs.add(0); if (key < 0) { pos++; } } } for (int l = 0; l < tags.size() - 1; l++) { while (l < tags.size() - 1 && tags.get(l) == 0) { l++; } if (l == tags.size() - 1) { break; } int r = l + 1; while (r < tags.size() && !tags.get(r).equals(tags.get(l))) { r++; } if (r == tags.size()) { pairs.set(l, 0); } else { pairs.set(l, 1); pairs.set(r, -1); tags.set(r, 0); } tags.set(l, 0); } return pairs; } private static void convertInput(final StringBuilder string, int pos, final BufferedWriter writer, final List<Integer> isPairTag) throws IOException{ int last; int curr; last = string.charAt(pos++); curr = string.charAt(pos++); int tagNum = 0; while (pos < string.length()) { if (last == '\\') { writer.write(curr); last = string.charAt(pos++); if (pos < string.length()) { curr = string.charAt(pos++); } continue; } int key = keyOf(last, curr); if (key != 0) { switch (isPairTag.get(tagNum)) { case 1: { writer.write(valueOfKeyBegin(key)); break; } case 0: { writer.write(last); break; } case -1: { writer.write(valueOfKeyEnd(key)); break; } } if (key < 0) { last = string.charAt(pos++); } else { last = curr; } curr = string.charAt(pos++); tagNum++; continue; } if (isTagSymbol(last)) { writer.write(textOf(last)); } else { writer.write((char) last); } last = curr; curr = string.charAt(pos++); } } private static int keyOf(final int x, final int y) { switch ((char) x + "" + (char) y) { case "**": return -1; case "__": return -2; case "--": return -3; case "++": return -4; } switch (x) { case '`': return 1; case '*': return 2; case '_': return 3; case '~': return 4; default: return 0; } } private static String valueOfKeyBegin(final int key) { switch (key) { case -1: case -2: return "<strong>"; case -3: return "<s>"; case -4: return "<u>"; case 1: return "<code>"; case 2: case 3: return "<em>"; case 4: return "<mark>"; default: return ""; } } private static String valueOfKeyEnd(final int key) { switch (key) { case -1: case -2: return "</strong>"; case -3: return "</s>"; case -4: return "</u>"; case 1: return "</code>"; case 2: case 3: return "</em>"; case 4: return "</mark>"; default: return ""; } } private static boolean isTagSymbol(final int x) { return x == '<' || x == '>' || x == '&'; } private static String textOf(int x) { switch (x) { case '<': return "&lt;"; case '>': return "&gt;"; case '&': return "&amp;"; default: return ""; } } }
31.122807
153
0.387599
9f0b4951988531e3b36213f3798a03f064a9cfdc
88
package com.example.casadocodigo.validacaoCpfCnpj; public interface DocumentoCnpj { }
14.666667
50
0.829545
9ec381b50f74fbb5c23b9753d9440b64407717d5
397
/* Copyright (C) 2001, 2008 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. All Rights Reserved. */ package gov.nasa.worldwind.applications.gio.csw; /** * @author dcollins * @version $Id: RequestId.java 5466 2008-06-24 02:17:32Z dcollins $ */ public interface RequestId { String getURI(); void setURI(String uri); }
20.894737
71
0.738035
c80726c0289b779e88d2638ceecea2d1ac330c3f
786
//,temp,ShowCompactionsOperation.java,43,66,temp,ShowTransactionsOperation.java,43,64 //,3 public class xxx { @Override public int execute() throws HiveException { SessionState sessionState = SessionState.get(); // Call the metastore to get the currently queued and running compactions. GetOpenTxnsInfoResponse rsp = context.getDb().showTransactions(); // Write the results into the file try (DataOutputStream os = ShowUtils.getOutputStream(new Path(desc.getResFile()), context)) { if (!sessionState.isHiveServerQuery()) { writeHeader(os); } for (TxnInfo txn : rsp.getOpen_txns()) { writeRow(os, txn); } } catch (IOException e) { LOG.warn("show transactions: ", e); return 1; } return 0; } };
29.111111
97
0.665394
3fa276be620c74c3447f7ec50196fed11e19956c
2,871
package com.mylove.module_hotel_launcher; import android.content.Intent; import android.graphics.Bitmap; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.widget.ImageView; import android.widget.TextView; import com.alibaba.android.arouter.facade.annotation.Route; import com.google.zxing.WriterException; import com.jess.arms.base.BaseActivity; import com.jess.arms.di.component.AppComponent; import com.mylove.module_hotel_launcher.app.utils.EncodingHandler; import org.simple.eventbus.Subscriber; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import me.jessyan.armscomponent.commonres.service.CoreService; import me.jessyan.armscomponent.commonsdk.core.RouterHub; import me.jessyan.armscomponent.commonservice.dao.DaoHelper; import me.jessyan.armscomponent.commonservice.dao.HotelEntity; /** * Skeleton of an Android Things activity. * */ @Route(path = RouterHub.HOTEL_HOMEACTIVITY) public class MainActivity extends BaseActivity { private static final String TAG = "MainActivity"; @BindView(R2.id.qrcode) ImageView qrcode; @BindView(R2.id.web_url) TextView webUrl; @Override public void setupActivityComponent(@NonNull AppComponent appComponent) { } @Override public int initView(@Nullable Bundle savedInstanceState) { return R.layout.hotel_activity_main; } @Override public void initData(@Nullable Bundle savedInstanceState) { initConfig(); Intent intent = new Intent(); intent.setClass(this,CoreService.class); startService(intent); } private void initConfig() { for (int i=1; i<20; i++){ HotelEntity hotelEntity = new HotelEntity(); if(i/10 < 1){ hotelEntity.setId("10"+i); }else{ hotelEntity.setId("1"+i); } hotelEntity.setUrl(""); hotelEntity.setPath(""); hotelEntity.setPkg(""); hotelEntity.setAction(""); hotelEntity.setIsAct(""); hotelEntity.setIsNet(""); hotelEntity.setCreateTime(""); DaoHelper.insert(hotelEntity); } } @Override protected void onDestroy() { super.onDestroy(); Intent intent = new Intent(); intent.setClass(this,CoreService.class); stopService(intent); } @Subscriber(tag = "serverStart") private void serverStart(String ip) { try { String mRootUrl = String.format("http://%s:%d/",ip,CoreService.PORT); webUrl.setText(mRootUrl); Bitmap bitmap = EncodingHandler.createQRCode(mRootUrl,300); qrcode.setImageBitmap(bitmap); } catch (WriterException e) { e.printStackTrace(); } } }
29.597938
81
0.668757
fff1f0dc1a6511f5b89c4f3ac1f9fe109da9d1fa
2,788
/* * 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 eu.fasten.core.data; /** * Builder for {@link ExtendedRevisionCallGraph}. */ public abstract class ExtendedBuilder<A> { protected String forge; protected String product; protected String version; protected String cgGenerator; protected long timestamp; protected A classHierarchy; protected Graph graph; protected int nodeCount; public ExtendedBuilder() { } public String getForge() { return forge; } public String getProduct() { return product; } public String getVersion() { return version; } public String getCgGenerator() { return cgGenerator; } public long getTimeStamp() { return timestamp; } public A getClassHierarchy() { return classHierarchy; } public Graph getGraph() { return graph; } public int getNodeCount() { return nodeCount; } public ExtendedBuilder<A> nodeCount(final int nodeCount) { this.nodeCount = nodeCount; return this; } public ExtendedBuilder<A> forge(final String forge) { this.forge = forge; return this; } public ExtendedBuilder<A> product(final String product) { this.product = product; return this; } public ExtendedBuilder<A> version(final String version) { this.version = version; return this; } public ExtendedBuilder<A> cgGenerator(final String cgGenerator) { this.cgGenerator = cgGenerator; return this; } public ExtendedBuilder<A> timestamp(final long timestamp) { this.timestamp = timestamp; return this; } public ExtendedBuilder<A> graph(final Graph graph) { this.graph = graph; return this; } public ExtendedBuilder<A> classHierarchy(final A cha) { this.classHierarchy = cha; return this; } public abstract ExtendedRevisionCallGraph<A> build(); }
24.892857
75
0.662841
be723c2d2f0186b87a5dee3a908b3cb124032e9c
2,356
package org.atlasapi.system.bootstrap.workers; import java.util.Set; import org.atlasapi.entity.ResourceRef; import org.atlasapi.media.entity.Publisher; import org.atlasapi.messaging.EquivalenceAssertionMessage; import org.atlasapi.messaging.v3.ContentEquivalenceAssertionMessage; import org.atlasapi.messaging.v3.ContentEquivalenceAssertionMessage.AdjacentRef; import com.metabroadcast.common.time.DateTimeZones; import com.metabroadcast.common.time.Timestamp; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import org.joda.time.DateTime; public class ContentEquivalenceAssertionLegacyMessageSerializer extends LegacyMessageSerializer<ContentEquivalenceAssertionMessage, EquivalenceAssertionMessage> { public ContentEquivalenceAssertionLegacyMessageSerializer() { super(ContentEquivalenceAssertionMessage.class); } @Override protected EquivalenceAssertionMessage transform(ContentEquivalenceAssertionMessage leg) { String mid = leg.getMessageId(); Timestamp ts = leg.getTimestamp(); ResourceRef subj = resourceRef( leg.getEntityId(), leg.getEntitySource(), leg.getEntityType(), leg.getTimestamp() ); Set<ResourceRef> adjacents = toResourceRef(leg); Set<Publisher> srcs = ImmutableSet.copyOf(Iterables.transform( leg.getSources(), Publisher.FROM_KEY )); return new EquivalenceAssertionMessage(mid, ts, subj, adjacents, srcs); } protected Set<ResourceRef> toResourceRef(ContentEquivalenceAssertionMessage leg) { if (leg.getAdjacent() == null || leg.getAdjacent().isEmpty()) { return ImmutableSet.of(); } DateTime madeUpUpdatedTime = new DateTime(leg.getTimestamp().millis(), DateTimeZones.UTC); ImmutableSet.Builder<ResourceRef> resourceRefs = ImmutableSet.builder(); for (AdjacentRef adjacentRef : leg.getAdjacent()) { resourceRefs.add(toResourceRef( idCodec.decode(adjacentRef.getId()).longValue(), Publisher.fromKey(adjacentRef.getSource()).requireValue(), adjacentRef.getType(), madeUpUpdatedTime )); } return resourceRefs.build(); } }
38.622951
98
0.697368
9ad3701d4f2edd477efb39bd96aa7b08e7e6a6cf
4,048
/* * Copyright 2017 StreamSets Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.streamsets.datacollector.lineage; import com.streamsets.datacollector.config.LineagePublisherDefinition; import com.streamsets.datacollector.config.StageLibraryDefinition; import com.streamsets.datacollector.stagelibrary.StageLibraryTask; import com.streamsets.datacollector.util.Configuration; import com.streamsets.pipeline.api.lineage.LineageEvent; import com.streamsets.pipeline.api.lineage.LineagePublisher; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Collections; import java.util.List; import static org.awaitility.Awaitility.await; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyString; import static org.powermock.api.mockito.PowerMockito.mock; import static org.powermock.api.mockito.PowerMockito.when; public class TestLineagePublisherTaskImpl { /** * Test publisher class that can validate what is the task implementation doing. */ public static class TestLineagePublisher implements LineagePublisher { boolean initCalled = false; boolean destroyCalled = false; List<LineageEvent> events = new ArrayList<>(); @Override public List<ConfigIssue> init(Context context) { initCalled = true; return Collections.emptyList(); } @Override public boolean publishEvents(List<LineageEvent> events) { this.events.addAll(events); return true; } @Override public void destroy() { destroyCalled = true; } } private LineagePublisherTaskImpl lineagePublisherTask; @Before public void setUp() { Configuration configuration = new Configuration(); configuration.set(LineagePublisherConstants.CONFIG_LINEAGE_PUBLISHERS, "test"); configuration.set(LineagePublisherConstants.configDef("test"), "test_library::test_publisher"); StageLibraryDefinition libraryDefinition = mock(StageLibraryDefinition.class); when(libraryDefinition.getName()).thenReturn("Test library"); LineagePublisherDefinition def = new LineagePublisherDefinition( libraryDefinition, Thread.currentThread().getContextClassLoader(), TestLineagePublisher.class, "test", "test", "test" ); StageLibraryTask stageLibraryTask = mock(StageLibraryTask.class); when(stageLibraryTask.getLineagePublisherDefinition(anyString(), anyString())).thenReturn(def); lineagePublisherTask = new LineagePublisherTaskImpl(configuration, stageLibraryTask); } @Test public void testRuntimeLifecycle() { lineagePublisherTask.initTask(); assertTrue(((TestLineagePublisher)lineagePublisherTask.publisherRuntime.publisher).initCalled); assertFalse(((TestLineagePublisher)lineagePublisherTask.publisherRuntime.publisher).destroyCalled); lineagePublisherTask.stopTask(); assertTrue(((TestLineagePublisher)lineagePublisherTask.publisherRuntime.publisher).destroyCalled); } @Test public void testConsumeEvents() { lineagePublisherTask.initTask(); lineagePublisherTask.runTask(); // Publish 10 events for(int i = 0; i < 10; i++) { LineageEvent event = mock(LineageEvent.class); lineagePublisherTask.publishEvent(event); } TestLineagePublisher publisher = (TestLineagePublisher)lineagePublisherTask.publisherRuntime.publisher; await().until(() -> publisher.events.size() == 10); lineagePublisherTask.stopTask(); } }
33.733333
107
0.760623
633d5332d59fff0775d0eafb0d2f826b67dd92d1
1,381
package ro.pub.cs.systems.eim.practicaltest01.practicaltest01; import android.content.Context; import android.content.Intent; import android.provider.SyncStateContract; import java.util.Date; /** * Created by mada on 30.03.2016. */ public class MyThread extends Thread { private boolean isRunning = true; private Integer firstValue, secondValue; private double arithmeticMean; private double geometricMean; private Context context; public MyThread(Context context, Integer firstValue, Integer secondValue) { this.firstValue = firstValue; this.secondValue = secondValue; arithmeticMean = (firstValue + secondValue) /2; geometricMean = Math.sqrt(firstValue + secondValue); this.context = context; } @Override public void run() { while (isRunning) { sendMessage(); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } private void sendMessage () { Intent intent = new Intent(); intent.setAction(Constants.MY_ACTION); intent.putExtra("message", new Date(System.currentTimeMillis()) + " " + arithmeticMean + " " + geometricMean); context.sendBroadcast(intent); } public void stopThread(){ isRunning = false; } }
25.109091
118
0.635047
05db131d29457bb51946d6b1bb1d964b4a6982d5
813
package com.shy.ssm.controller; import com.shy.ssm.bean.User; import com.shy.ssm.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author 石皓岩 * @create 2020-03-01 19:42 * 描述: */ @Controller public class UserController { /** * 用户服务接口 */ @Autowired private UserService userService; @RequestMapping("/list") @ResponseBody public User list() { List<User> list = userService.list(); Map<String,Object> map = new HashMap<>(); map.put("user",new User(1,"aaa","2222")); return new User(1,"aaa","2222"); } }
21.972973
62
0.735547
5252dd16f2f927d616df727db7ee1a8f2d4079f5
621
package ru.r2cloud.jradio.blocks; import org.junit.Test; import ru.r2cloud.jradio.FloatInput; import ru.r2cloud.jradio.TestUtil; import ru.r2cloud.jradio.source.WavFileSource; public class FrequencyXlatingFIRFilterTest { @Test public void test() throws Exception { float[] taps = Firdes.lowPass(1.0, 222222.0f, 222222.0f / 2, 1000, Window.WIN_HAMMING, 6.76); try (FloatInput source = new FrequencyXlatingFIRFilter(new WavFileSource(FrequencyXlatingFIRFilterTest.class.getClassLoader().getResourceAsStream("meteor_small.wav")), taps, 10, -10000)) { TestUtil.assertFloatInput("xlating.bin", source); } } }
31.05
190
0.772947
bba427f94f0dd2a9cc6727592acd81848895a794
2,520
public static void beginParsingByLine(String filename){ try { Scanner sc = new Scanner(new File(filename)); Scanner scancmd;//Declare two scanners one to read the file and one to read the text pulled from the file while(sc.hasNextLine()){//While we have text to read String line = sc.nextLine();//Get our next line scancmd = new Scanner(line);//Create a scanner from this line String cmd = scancmd.next();//Get the first word (the command) on each line String type; switch(cmd){ case "insert"://In the case of insert change our delimiter from white space to <SEP> scancmd.useDelimiter("<SEP>"); String artist = scancmd.next();//Get the artist since it is before <SEP> String song = scancmd.next();//Get the song title that follows <SEP> System.out.println("Insert "+artist+" \\ "+song); break; case "remove": type = scancmd.next();//Get the mode of deletion artist/song String token = scancmd.nextLine(); //Since both artist titles and song titles have spaces //get the rest of the line for the song/artist name switch(type){ case "artist": System.out.println("Artist Delete: "+token); break; case "song": System.out.println("Song Delete: "+token); break; default ://Error bad token System.out.println("Error bad remove type " + type); break; } break; case "print"://Print command type = scancmd.next();//get the type of print command switch(type){ case "artist": System.out.println("Print artist mode"); break; case "song": System.out.println("Print song mode"); break; case "blocks": System.out.println("Print block mode"); break; default: System.out.println("Error bad print type" + type); break; } break; default : System.out.println("Unrecognized input"); break; } } } catch (Exception e) { e.printStackTrace(); } }
42
111
0.498413
e3473be7ca4efad8599c494aeecaa5dd3d8caacd
2,692
/* * Copyright 2018 Crown Copyright * * 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 uk.gov.gchq.palisade.service; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.As; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import uk.gov.gchq.palisade.ToStringBuilder; import static java.util.Objects.requireNonNull; /** * A simple implementation of the {@link ConnectionDetail} that holds an instance * of {@link Service} */ public class SimpleConnectionDetail implements ConnectionDetail { @JsonTypeInfo( use = JsonTypeInfo.Id.CLASS, include = As.PROPERTY, property = "class" ) private Service service; public SimpleConnectionDetail() { } public SimpleConnectionDetail service(final Service service) { requireNonNull(service, "The service can not be set to null"); this.service = service; return this; } public Service getService() { requireNonNull(service, "The service has not been set."); return service; } public void setService(final Service service) { service(service); } @SuppressWarnings("unchecked") @Override public <S extends Service> S createService() { return (S) service; } @Override public String _getClass() { return null; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final SimpleConnectionDetail that = (SimpleConnectionDetail) o; return new EqualsBuilder() .append(service, that.service) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 41) .append(service) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("service", service) .toString(); } }
26.653465
81
0.645617
33db1b5ea6bcbb3f41ecda9c872817c1f82ee77b
807
package daily; import java.util.List; /** * @author ber * @version 1.0 * @date 21/9/14 15:58 */ public class T524 { class Solution { public String findLongestWord(String s, List<String> dictionary) { String res = ""; for (String t : dictionary) { int i = 0, j = 0; while (i < t.length() && j < s.length()) { if (t.charAt(i) == s.charAt(j)) { ++i; } ++j; } if (i == t.length()) { if (t.length() > res.length() || (t.length() == res.length() && t.compareTo(res) < 0)) { res = t; } } } return res; } } }
25.21875
108
0.360595
7808195730986a83e2940e6c604ba99de2b33491
2,115
package com.today.roc.springboot.base.common; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.web.server.ConfigurableWebServerFactory; import org.springframework.boot.web.server.ErrorPage; import org.springframework.boot.web.server.WebServerFactoryCustomizer; import org.springframework.context.annotation.Bean; import org.springframework.http.HttpStatus; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; /** * @author zou.cp * @version 1.0 * @Description * @createTime 2021年03月01日 11:01* * log.info() */ //@ControllerAdvice //@ResponseBody @Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 * * @param binder */ @InitBinder public void initBinder(WebDataBinder binder) { } @ExceptionHandler(RuntimeException.class) @ResponseBody public Object defaultErrorHandler(HttpServletRequest req, Exception e) { e.printStackTrace(); log.error("错误信息:",e); return "默认异常处理"; } /** * 拦截404 */ @Bean public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() { log.info("进入拦截"); return (factory -> { ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"); factory.addErrorPages(errorPage); }); // WebServerFactoryCustomizer<ConfigurableWebServerFactory> result = new WebServerFactoryCustomizer<ConfigurableWebServerFactory>() { // @Override // public void customize(ConfigurableWebServerFactory factory) { // ErrorPage errorPage = new ErrorPage(HttpStatus.NOT_FOUND, "/404.do"); // factory.addErrorPages(errorPage); // } // }; // return result; } }
30.652174
140
0.711584
b30ae80e83b440a760f88c69f7eb48901e46512d
910
package com.domo4pi.gsm; import com.domo4pi.utils.Timer; import com.domo4pi.utils.inject.Inject; import java.util.LinkedList; import java.util.concurrent.TimeUnit; public class SMSSenderTimer extends Timer { @Inject private GSMManager gsmManager; public SMSSenderTimer() { super("GSM.SMSSender"); } private final LinkedList<SMSRequest> pendingSMS = new LinkedList<>(); @Override public int getIntervalValue() { return 2; } @Override public TimeUnit getIntervalUnits() { return TimeUnit.SECONDS; } void addSMS(SMSRequest smsRequest) { pendingSMS.add(smsRequest); } @Override public void tick() { if (gsmManager.isGSMBoardReady()) { SMSRequest request; while ((request = pendingSMS.poll()) != null) { gsmManager.sendSMS(request); } } } }
20.681818
73
0.625275
4662207f25dccf1ac4ba01a7c5381a208e36dfe2
1,016
package com.xe.alipay.service.imp; import com.google.common.cache.Cache; import com.xe.alipay.config.CacheConfig; import com.xe.alipay.model.Customer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.stereotype.Service; import javax.annotation.PostConstruct; @Service public class TokenService { private Cache<String, Customer> customerContextCache; @Autowired private CacheManager cacheManager; @SuppressWarnings("unchecked") @PostConstruct public void init() { customerContextCache = (Cache<String, Customer>) cacheManager.getCache(CacheConfig.CUSTOMER_CONTEXT_CACHE).getNativeCache(); } public Customer getCustomer(String token) { return customerContextCache.getIfPresent(token); } public void refreshCustomer(String token,Customer customerEntity) { customerContextCache.invalidate(token); customerContextCache.put(token,customerEntity); } }
29.882353
132
0.769685
70cd8528a9c30a9b2ea0d151de54f2a00bb1c31f
1,655
package edu.ntvu.jsp.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class MainServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.getSession().getAttribute("CurrentUserName") == null) { resp.sendRedirect("login"); return; } String username = (String)req.getSession().getAttribute("CurrentUserName"); //输出 resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html;charset=UTF-8"); PrintWriter out = resp.getWriter(); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">"); out.println("<title>管理员后台</title>"); out.println("</head>"); out.println("<body>"); out.println("<form id=\"form1\" name=\"form1\" action=\"/student\" method=\"get\">"); out.println("欢迎:" + username + "<a href='/doLogout'>注销</a> <br>"); out.println("</form>"); out.println("</body>"); out.println("</html>"); out.close(); } }
35.212766
123
0.607855
03d80aa76234956841a18a2ed1c98cbc2393d616
4,468
package frc.team1138.robot.commands; import edu.wpi.first.wpilibj.PIDController; import edu.wpi.first.wpilibj.command.PIDCommand; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; import frc.team1138.robot.Robot; public class DriveWithEncoders extends PIDCommand { double distance, speed; // parameter to set in the command group for the PID distance travel by // rotations * tick per rotation and the speed of the output range private static double P = 0.0002, I = 0.0, D = 0.0001; // sets the PID private PIDController driveController; double DistanceToTarget = 0; // resets the PID public static final double KTicksPerRotation = 4096; // ticks public DriveWithEncoders(double distance, double speed) { super("Drive Distance", P, I, D); SmartDashboard.putNumber("setEncoder", 0); requires(Robot.DRIVE_BASE); this.distance = distance; // defines parameter this.speed = speed; // defines parameter driveController = this.getPIDController(); driveController.setInputRange(-20000000, 20000000); // sets the max input range driveController.setOutputRange(-speed, speed); // sets the max output range driveController.setAbsoluteTolerance(100); // Error allowed driveController.setContinuous(true); // sets the value to be continuous throughout the command Robot.DRIVE_BASE.resetEncoders(); // resets the encoders } // Called just before this Command runs the first time @Override protected void initialize() { Robot.DRIVE_BASE.resetEncoders();// resets the encoder setTarget(distance * KTicksPerRotation); // set the rotation needed for the distance * the ticksperRotation to // go that distance } @Override protected double returnPIDInput() { return (Robot.DRIVE_BASE.getLeftEncoderValue()); // returns left encoder value to the code } public void setTarget(double ticks) { this.driveController.setSetpoint(ticks); // sets the target of the PID } @Override protected void usePIDOutput(double output) { // The side with the GEAR IS THE FRONT! if (!driveController.onTarget()) { if (this.returnPIDInput() - this.getSetpoint() < 0) { // need to move forward System.out.println("Move Forward"); System.out.println("Left Motor: " + (output) + "Right Motor: " + (output)); SmartDashboard.putNumber("Distance From Target", this.returnPIDInput() - this.getSetpoint()); Robot.DRIVE_BASE.tankDrive(-output, -output); } else if (this.returnPIDInput() - this.getSetpoint() > 0) { // need to move backward System.out.println("Move Backward"); System.out.println("Left Motor: " + (-output) + "Right Motor: " + (-output)); Robot.DRIVE_BASE.tankDrive(-output, -output); } System.out.println("set point: " + this.getSetpoint()); System.out.println("Current Encoder Value: " + Robot.DRIVE_BASE.getLeftEncoderValue()); System.out.println("Error: " + (Robot.DRIVE_BASE.getLeftEncoderValue() - this.getSetpoint())); System.out.println("Input: " + this.returnPIDInput()); System.out.println("On Target: " + driveController.onTarget()); } else { Robot.DRIVE_BASE.tankDrive(0, 0); System.out.println("On Target: " + driveController.onTarget()); } } // Called repeatedly when this Command is scheduled to run @Override protected void execute() { // final double setEncoder = SmartDashboard.getNumber("setEncoder", 0); // setTarget(setEncoder); setTarget(distance * KTicksPerRotation); // set the rotation needed for the distance * the ticksperRotation to // go that distance SmartDashboard.putBoolean("tracking", true); SmartDashboard.putNumber("Left", Robot.DRIVE_BASE.getLeftEncoderValue()); SmartDashboard.putNumber("Right", Robot.DRIVE_BASE.getRightEncoderValue()); } // Make this return true when this Command no longer needs to run execute() @Override protected boolean isFinished() { System.out.println("On Target: " + driveController.onTarget()); SmartDashboard.putNumber("Error", this.returnPIDInput() - this.getSetpoint()); return driveController.onTarget(); } // Called once after isFinished returns true @Override protected void end() { Robot.DRIVE_BASE.tankDrive(0, 0); Robot.DRIVE_BASE.resetEncoders(); SmartDashboard.putNumber("setEncoder", 0); SmartDashboard.putBoolean("tracking", false); } // Called when another command which requires one or more of the same // subsystems is scheduled to run @Override protected void interrupted() { } }
35.460317
112
0.7265
67a0038b19c4e59556abd8dd3376c96dfb5eee7c
3,163
package ru.bibarsov.telegram.bots.like.repository.storage; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.bibarsov.telegram.bots.common.util.Action; import ru.bibarsov.telegram.bots.like.repository.dao.InlineMessageDao; import javax.annotation.ParametersAreNonnullByDefault; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.*; @ParametersAreNonnullByDefault public class InlineMessageStorage { private static final Logger LOGGER = LoggerFactory.getLogger(InlineMessageStorage.class); private static final int RETRY_COUNT = 3; //<PublicationId, Set<InlineMessageId>> private final Map<String, Set<String>> data = new ConcurrentHashMap<>(); private final ExecutorService singleThreadPool = Executors.newSingleThreadExecutor(); private final BlockingQueue<Pair<String, String>> dataToPersist = new LinkedBlockingQueue<>(); private final InlineMessageDao inlineMessageDao; public InlineMessageStorage(InlineMessageDao inlineMessageDao) { this.inlineMessageDao = inlineMessageDao; } public void onStart() { loadInlineMessages(); singleThreadPool.submit( () -> { while (!Thread.currentThread().isInterrupted()) { Action.executeQuietly(this::doPersist); } } ); } public void addInlineMessage( String publicationId, String inlineMessageId ) { data.computeIfAbsent(publicationId, (ignored) -> new CopyOnWriteArraySet<>()).add(inlineMessageId); dataToPersist.offer(Pair.of(publicationId, inlineMessageId)); } public Set<String> getInlineMessageIds(String publicationId) { return data.getOrDefault(publicationId, Set.of()); } private void doPersist() throws InterruptedException { Pair<String, String> inlineMsg = dataToPersist.take(); int retryCount = RETRY_COUNT; while (--retryCount >= 0) { try { inlineMessageDao.upsertInlineMessage( inlineMsg.getLeft(), //publicationId inlineMsg.getRight() //inlineMessageId ); return; } catch (Throwable t) { if (retryCount > 0) { LOGGER.warn("Couldn't persist data, remaining retries: " + retryCount, t); TimeUnit.SECONDS.sleep(1L); } else { LOGGER.error("Failed to persist data.", t); } } } } private void loadInlineMessages() { Map<String, String> inlineMessages = inlineMessageDao.getInlineMessages(); Map<String, Set<String>> tempData = new HashMap<>(); for (var entry : inlineMessages.entrySet()) { tempData.computeIfAbsent(entry.getKey(), (ignore) -> new HashSet<>()).add(entry.getValue()); } for (var entry : tempData.entrySet()) { data.put(entry.getKey(), new CopyOnWriteArraySet<>(entry.getValue())); } } }
35.144444
107
0.641163
31b5cef28693ac4751e354026a8c986b0ef60579
1,874
package com.tugab.adspartners.domain.entities; import lombok.Data; import org.hibernate.validator.constraints.Length; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.List; @Data @Entity @Table(name = "ad") public class Ad { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(name = "title", nullable = false) private String title; @Column(name = "description") private String description; @Column(name = "reward", nullable = false) private Double reward; @Column(name = "creation_date", nullable = false) private Date creationDate; @Column(name = "valid_to", nullable = false) private Date validTo; @Column(name = "min_videos") private Long minVideos; @Column(name = "min_subscribers") private Long minSubscribers; @Column(name = "min_views") private Long minViews; @Column(name = "is_blocked", nullable = false) private Boolean isBlocked; @ManyToOne(targetEntity = Company.class) @JoinColumn(name = "creator_id", referencedColumnName = "id") private Company company; @ManyToOne(targetEntity = CloudinaryResource.class, cascade = CascadeType.REMOVE) @JoinColumn(name = "picture_id", referencedColumnName = "id") private CloudinaryResource picture; @OneToMany(mappedBy = "ad", targetEntity = Characteristic.class, cascade = CascadeType.ALL, orphanRemoval = true) private List<Characteristic> characteristics; @OneToMany(mappedBy = "id.ad", targetEntity = AdRating.class, cascade = CascadeType.ALL) private List<AdRating> ratingList; @OneToMany(mappedBy = "id.ad", targetEntity = AdApplication.class, cascade = CascadeType.ALL) private List<AdApplication> applicationList; @Transient private Double averageRating = 0.0; }
27.970149
117
0.714514
6076422932e95b3f086574ec668ac9512e22f265
1,398
package com.dataiku.dctc.display; import java.util.List; import com.dataiku.dctc.copy.CopyTaskRunnable; class SimpleDisplay extends AbstractThreadedDisplay { @Override protected final boolean display(CopyTaskRunnable task) { if (task.isDone()) { if (task.getException() != null) { ++failed; } done += task.getInSize(); return true; } else { transfer += task.read(); return false; } } @Override protected void resetLoop() { String msg = "done: " + Size.getReadableSize(done + transfer) + "/" + prettyFilesSize; if (failed != 0) { msg += " with " + failed + " fail(s)."; } else { msg += "."; } print(msg); transfer = 0; } @Override protected final void init(List<CopyTaskRunnable> taskList) { wholeFilesSize = 0; for (CopyTaskRunnable task: taskList) { wholeFilesSize += task.getInSize(); } prettyFilesSize = Size.getReadableSize(wholeFilesSize); } @Override protected final void end() { System.out.println(); } // Attributes private long wholeFilesSize; private String prettyFilesSize; private long done; private long transfer; private int failed; }
24.964286
64
0.54721
ca6bec273b71b2eac516133287f7560e3f1e184e
1,631
package com.prvyx.model.domain; import java.util.Date; /** * @program: java-bilibili * @description: 用户观看视频历史记录的domain * @author: Prvyx * @created: 2022/04/10 17:19 */ public class UserWatchVideoHistory { private String video_id; private String video_title; private String video_img_path; private String user_name; private String watch_datetime; public UserWatchVideoHistory() { } public UserWatchVideoHistory(String video_id, String video_title, String video_img_path, String user_name, String watch_datetime) { this.video_id = video_id; this.video_title = video_title; this.video_img_path = video_img_path; this.user_name = user_name; this.watch_datetime = watch_datetime; } public String getVideo_id() { return video_id; } public void setVideo_id(String video_id) { this.video_id = video_id; } public String getVideo_title() { return video_title; } public void setVideo_title(String video_title) { this.video_title = video_title; } public String getVideo_img_path() { return video_img_path; } public void setVideo_img_path(String video_img_path) { this.video_img_path = video_img_path; } public String getWatch_datetime() { return watch_datetime; } public void setWatch_datetime(String watch_datetime) { this.watch_datetime = watch_datetime; } public String getUser_name() { return user_name; } public void setUser_name(String user_name) { this.user_name = user_name; } }
23.3
135
0.675659
42d4f698b654148dfeebfd81cb6f53a68c79e5c9
371
package com.marshalchen.ultimaterecyclerview.expanx.Util; import com.marshalchen.ultimaterecyclerview.expanx.ExpandableItemData; /** * Author Zheng Haibo * PersonalWebsite http://www.mobctrl.net * Description */ public interface ItemDataClickListener<T extends ExpandableItemData> { void onExpandChildren(T itemData); void onHideChildren(T itemData); }
20.611111
70
0.787062
c3f629f22c24b083f33266a5eed55e5cf85604df
7,043
/* * Copyright (c) 2017, WSO2 Inc. All Rights Reserved. */ package org.wso2.carbon.cloud.complimentary.users; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.cloud.complimentary.users.exception.CustomerException; import org.wso2.carbon.cloud.complimentary.users.exception.SalesforceException; import org.wso2.carbon.cloud.complimentary.users.model.config.SalesforceConfiguration; import org.wso2.carbon.cloud.complimentary.users.utils.SalesforceConnector; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * This class is where the business logic of the Customer service is implemented. * * @since 1.0.0 */ public class CustomerManager { private static Log log = LogFactory.getLog(CustomerManager.class); private static SalesforceConfiguration config; public CustomerManager() { } public static void loadConfig(String username, String password, String token) throws IOException { config = new SalesforceConfiguration(); config.setUsername(username); config.setPassword(password); config.setToken(token); } /** * This method is used to retrieve the list of products for which the customer has production support from * Salesforce. * * @param opportunities List of Jira keys * @return List of products which have production support for the given jira * @throws CustomerException Thrown if the backend resources produce errors */ public static List<String> getProdProductsforOpportunities(List<String> opportunities) throws CustomerException { if (opportunities.size() <= 0) { return new ArrayList<>(); } try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); @SuppressWarnings("unchecked") List<String> salesforceProducts = salesforceConnector.getProductsByOpportunitiesIds(opportunities); salesforceConnector.logout(); return salesforceProducts; } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } /** * Method to check if given customer has production support for given product * * @param opportunities List of production opportunities for customer * @param productName Product name * @return Whether the customer has production support for product * @throws CustomerException */ public static boolean hasProductionSupportForProduct(List<String> opportunities, String productName) throws CustomerException { List<String> products = getProdProductsforOpportunities(opportunities); for (int i = 0; i < products.size(); i++) { String product = products.get(i); if (product.contains(productName)) { return true; } } return false; } public static boolean hasClaimedComplimentarySubscription(List<String> opportunities) throws CustomerException { try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); @SuppressWarnings("unchecked") boolean hasClaimedComplimentarySubscripton = salesforceConnector. hasClaimedComplimentarySubscription(opportunities); salesforceConnector.logout(); return hasClaimedComplimentarySubscripton; } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } public static String getContactWhoClaimedSubscription(List<String> opportunities) throws CustomerException { try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); @SuppressWarnings("unchecked") String contact = salesforceConnector.getContactWhoClaimedSubscription(opportunities); salesforceConnector.logout(); return contact; } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } public static List<String> getOpportunitiesByJira(String[] customerProdJiraKeys) throws CustomerException { try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); List<String> opportunities = salesforceConnector.getOpportunitiesByJira( Arrays.asList(customerProdJiraKeys)); salesforceConnector.logout(); return opportunities; } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } public static void updateSalesforceAccountObject(List<String> opportunities, boolean update) throws CustomerException { try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); String accountId = salesforceConnector.getAccountId(opportunities); salesforceConnector.updateSObject("Account", accountId, update); salesforceConnector.logout(); } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } public static void updateSalesforceContactObject(String contactId, boolean update) throws CustomerException { try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); salesforceConnector.updateSObject("Contact", contactId, update); salesforceConnector.logout(); } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } public static String getContactId(List<String> opportunities, String email) throws CustomerException { try { SalesforceConnector salesforceConnector = new SalesforceConnector(); salesforceConnector.login(config.getUsername(), config.getPassword(), config.getToken()); String contactId = salesforceConnector.getContactId(opportunities, email); salesforceConnector.logout(); return contactId; } catch (SalesforceException e) { log.error(e.getMessage()); throw new CustomerException(e); } } }
42.684848
117
0.677694
15c795eff0bbc62f5137e31548be1c0d9cb71903
663
package com.api.adapter; import com.api.result.GlobalErrorInfoException; import com.api.result.messageenum.GlobalErrorInfoEnum; import java.util.HashMap; import java.util.Map; /** * 适配器容器 */ public class HISTransAdapterContainer { static Map<String,Object> adapterMap = new HashMap<String,Object>(); public static AHISTransAdapter getAdapter(String key) throws GlobalErrorInfoException { try { return (AHISTransAdapter) adapterMap.get(key); } catch (Exception e) { throw new GlobalErrorInfoException(GlobalErrorInfoEnum.ADAPTER_ERROR); } } public static void putAdapter(String key, Object adapter){ adapterMap.put(key, adapter); } }
23.678571
88
0.767722
5fd540f29f05c029d69c209f90ffcc4f28003d4f
2,463
package org.usfirst.frc.team6094.robot.commands; import org.usfirst.frc.team6094.robot.Robot; import edu.wpi.first.wpilibj.command.Command; public class PiToAngle extends Command { private Integer GAngle; private boolean autonRunning; private boolean Inverted; public PiToAngle(Integer Angle, boolean Reversed) { Inverted = Reversed; GAngle = -Angle; requires(Robot.drivetrain); } protected void initialize() { Robot.drivetrain.init(); } protected void execute() { // This fixs the problems with double prints, // not properly closing auton programs // and make sure we dont move while reseting yaw autonRunning = true; /* if (autonRunning == true && Robot.ahrs.isCalibrating() == false) { System.out.printf("Angle, " + Robot.ahrs.getYaw()); if (Robot.ahrs.getYaw() > GAngle + 2) { Robot.drivetrain.tCounterClockwise(); System.out.println("Counterclosewise"); } else if (Robot.ahrs.getYaw() < GAngle - 2 || Robot.ahrs.getYaw() > 1) { Robot.drivetrain.tClockwise(); System.out.println("Clockwise"); } else { System.out.println("Stop"); Robot.drivetrain.driveTrainStop(); } */ // Its something with PiToAngle in this turn correction if (autonRunning == true && Robot.ahrs.isCalibrating() == false) { if (Inverted == false) { System.out.printf("Angle, " + Robot.ahrs.getYaw()); if (Robot.ahrs.getYaw() > GAngle + 2) { Robot.drivetrain.tCounterClockwise(); System.out.println("Counterclosewise"); } else if (Robot.ahrs.getYaw() < GAngle - 2 || Robot.ahrs.getYaw() > 1) { Robot.drivetrain.tClockwise(); System.out.println("Clockwise"); } else { System.out.println("Stop"); Robot.drivetrain.driveTrainStop(); } } else { System.out.printf("Angle, " + Robot.ahrs.getYaw()); if (Robot.ahrs.getYaw() < -GAngle - 2) { Robot.drivetrain.tClockwise(); System.out.println("Closewise"); } else if (Robot.ahrs.getYaw() > GAngle + 2 || Robot.ahrs.getYaw() < -1) { Robot.drivetrain.tCounterClockwise(); System.out.println("CounterClockwise"); } else { System.out.println("Stop"); Robot.drivetrain.driveTrainStop(); } } } } @Override protected boolean isFinished() { return false; } protected void end() { autonRunning = false; Robot.encoderBR.reset(); Robot.encoderFR.reset(); Robot.encoderBL.reset(); Robot.encoderFL.reset(); } protected void interrupted() { end(); } }
27.065934
78
0.664231
59739a3eebd1b83a7b710fd217ba46867817a597
2,283
package org.joverseer.engine.orders; import org.joverseer.domain.Army; import org.joverseer.domain.ArmyElement; import org.joverseer.domain.ArmyElementType; import org.joverseer.domain.Order; import org.joverseer.engine.ErrorException; import org.joverseer.engine.ExecutingOrder; import org.joverseer.engine.ExecutingOrderUtils; import org.joverseer.game.Game; import org.joverseer.game.Turn; import org.joverseer.game.TurnElementsEnum; import org.joverseer.support.infoSources.XmlTurnInfoSource; public class AnchorShipsOrder extends ExecutingOrder { public AnchorShipsOrder(Order order) { super(order); } @Override public void doExecute(Game game, Turn turn) throws ErrorException { addMessage("{char} was ordered to anchor some ships."); if (!loadArmyByMember(turn)) { addMessage("{gp} was not able to anchor ships because {gp} was not with an army."); return; } if (!game.getMetadata().getHex(getHex()).getTerrain().isLand()) { addMessage("{gp} was not able to anchor ships because the army was not on land."); return; } int warships = getParameterInt(0); int transports = getParameterInt(1); warships = Math.min(warships, getArmy().getNumber(ArmyElementType.Warships)); transports = Math.min(transports, getArmy().getNumber(ArmyElementType.Transports)); if (warships + transports == 0) { addMessage("No ships were anchored."); return; } Army a = ExecutingOrderUtils.createArmy("[Anchored Ships]", getCharacter().getNationNo(), getCharacter().getNation().getAllegiance(), getHex(), new XmlTurnInfoSource(turn.getTurnNo(), getCharacter().getNationNo())); a.setElement(new ArmyElement(ArmyElementType.Warships, warships)); a.setElement(new ArmyElement(ArmyElementType.Transports, transports)); a.setNavy(true); a.setCavalry(false); a.setFed(false); turn.getContainer(TurnElementsEnum.Army).addItem(a); ExecutingOrderUtils.cleanupArmy(turn, a); ExecutingOrderUtils.removeElementTroops(getArmy(), ArmyElementType.Warships, warships); ExecutingOrderUtils.removeElementTroops(getArmy(), ArmyElementType.Transports, transports); addMessage(warships + " warships and "+ transports + " transports were anchored."); } }
35.123077
218
0.734998
c675999fc957fd922bde6708322750f6a9f867b0
5,516
/* * The MIT License * * Copyright 2020 Raymond Buckley. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.ray3k.stripe; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.Json; import com.badlogic.gdx.utils.JsonValue; /** * A sublass of {@link Skin} that includes a serializer for FreeType fonts from JSON. These JSON's are typically exported by * Skin Composer. See the * <a href="https://github.com/raeleus/skin-composer/wiki/Creating-FreeType-Fonts#using-a-custom-serializer">Skin Composer documentation</a>. * If you are using Asset Manager, use {@link FreeTypeSkinLoader} */ public class FreeTypeSkin extends Skin { /** Creates an empty skin. */ public FreeTypeSkin() { } /** Creates a skin containing the resources in the specified skin JSON file. If a file in the same directory with a ".atlas" * extension exists, it is loaded as a {@link TextureAtlas} and the texture regions added to the skin. The atlas is * automatically disposed when the skin is disposed. * @param skinFile The JSON file to be read. */ public FreeTypeSkin(FileHandle skinFile) { super(skinFile); } /** Creates a skin containing the resources in the specified skin JSON file and the texture regions from the specified atlas. * The atlas is automatically disposed when the skin is disposed. * @param skinFile The JSON file to be read. * @param atlas The texture atlas to be associated with the {@link Skin}. */ public FreeTypeSkin(FileHandle skinFile, TextureAtlas atlas) { super(skinFile, atlas); } /** Creates a skin containing the texture regions from the specified atlas. The atlas is automatically disposed when the skin * is disposed. * @param atlas The texture atlas to be associated with the {@link Skin}. */ public FreeTypeSkin(TextureAtlas atlas) { super(atlas); } /** * Overrides the default JSON loader to process FreeType fonts from a Skin JSON. * @param skinFile The JSON file to be processed. * @return The {@link Json} used to read the file. */ @Override protected Json getJsonLoader(final FileHandle skinFile) { Json json = super.getJsonLoader(skinFile); final Skin skin = this; json.setSerializer(FreeTypeFontGenerator.class, new Json.ReadOnlySerializer<FreeTypeFontGenerator>() { @Override public FreeTypeFontGenerator read(Json json, JsonValue jsonData, Class type) { String path = json.readValue("font", String.class, jsonData); jsonData.remove("font"); FreeTypeFontGenerator.Hinting hinting = FreeTypeFontGenerator.Hinting.valueOf(json.readValue("hinting", String.class, "AutoMedium", jsonData)); jsonData.remove("hinting"); Texture.TextureFilter minFilter = Texture.TextureFilter.valueOf( json.readValue("minFilter", String.class, "Nearest", jsonData)); jsonData.remove("minFilter"); Texture.TextureFilter magFilter = Texture.TextureFilter.valueOf( json.readValue("magFilter", String.class, "Nearest", jsonData)); jsonData.remove("magFilter"); FreeTypeFontGenerator.FreeTypeFontParameter parameter = json.readValue(FreeTypeFontGenerator.FreeTypeFontParameter.class, jsonData); parameter.hinting = hinting; parameter.minFilter = minFilter; parameter.magFilter = magFilter; FreeTypeFontGenerator generator = new FreeTypeFontGenerator(skinFile.parent().child(path)); generator.setMaxTextureSize(FreeTypeFontGenerator.NO_MAXIMUM); BitmapFont font = generator.generateFont(parameter); skin.add(jsonData.name, font); if (parameter.incremental) { generator.dispose(); return null; } else { return generator; } } }); return json; } }
45.213115
148
0.673133
bb6c628e4873288f478239ebec055eaa84d573b5
1,245
package fastdex.build.lib.snapshoot.file; import fastdex.build.lib.snapshoot.api.Status; import java.util.HashSet; import java.util.Set; /** * Created by tong on 17/3/30. */ public class Options { private final Set<String> suffixList = new HashSet<>(); private Status[] focusStatus = null; public static class Builder { private final Options options = new Options(); public Builder addSuffix(String suffix) { options.suffixList.add(suffix); return this; } public Builder focusStatus(Status ...focusStatus) { if (focusStatus != null) { Set set = new HashSet(); for (Status status : focusStatus) { set.add(status); } if (set.size() < focusStatus.length) { throw new IllegalStateException("Content can not be repeated !"); } } if (focusStatus.length == 0) { options.focusStatus = null; } else { options.focusStatus = focusStatus; } return this; } public Options build() { return options; } } }
25.9375
85
0.526104
c5529af91d54006736414fe694e21c6e6581b75e
5,779
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.ast; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.mozilla.javascript.Token; /** * AST node for an Array literal. The elements list will always be * non-{@code null}, although the list will have no elements if the Array literal * is empty. * * <p>Node type is {@link Token#ARRAYLIT}. * * <pre><i>ArrayLiteral</i> : * <b>[</b> Elisionopt <b>]</b> * <b>[</b> ElementList <b>]</b> * <b>[</b> ElementList , Elisionopt <b>]</b> * <i>ElementList</i> : * Elisionopt AssignmentExpression * ElementList , Elisionopt AssignmentExpression * <i>Elision</i> : * <b>,</b> * Elision <b>,</b></pre> */ public class ArrayLiteral extends AstNode implements DestructuringForm { private static final List<AstNode> NO_ELEMS = Collections.unmodifiableList(new ArrayList<AstNode>()); private List<AstNode> elements; private int destructuringLength; private int skipCount; private boolean isDestructuring; { type = Token.ARRAYLIT; } public ArrayLiteral() { } public ArrayLiteral(int pos) { super(pos); } public ArrayLiteral(int pos, int len) { super(pos, len); } /** * Returns the element list * * @return the element list. If there are no elements, returns an immutable * empty list. Elisions are represented as {@link EmptyExpression} * nodes. */ public List<AstNode> getElements() { return elements != null ? elements : NO_ELEMS; } /** * Sets the element list, and sets each element's parent to this node. * * @param elements the element list. Can be {@code null}. */ public void setElements(List<AstNode> elements) { if (elements == null) { this.elements = null; } else { if (this.elements != null) this.elements.clear(); for (AstNode e : elements) addElement(e); } } /** * Adds an element to the list, and sets its parent to this node. * * @param element the element to add * @throws IllegalArgumentException if element is {@code null}. To indicate * an empty element, use an {@link EmptyExpression} node. */ public void addElement(AstNode element) { assertNotNull(element); if (elements == null) elements = new ArrayList<AstNode>(); elements.add(element); element.setParent(this); } /** * Returns the number of elements in this {@code Array} literal, * including empty elements. */ public int getSize() { return elements == null ? 0 : elements.size(); } /** * Returns element at specified index. * * @param index the index of the element to retrieve * @return the element * @throws IndexOutOfBoundsException if the index is invalid */ public AstNode getElement(int index) { if (elements == null) throw new IndexOutOfBoundsException("no elements"); return elements.get(index); } /** * Returns destructuring length */ public int getDestructuringLength() { return destructuringLength; } /** * Sets destructuring length. This is set by the parser and used * by the code generator. {@code for ([a,] in obj)} is legal, * but {@code for ([a] in obj)} is not since we have both key and * value supplied. The difference is only meaningful in array literals * used in destructuring-assignment contexts. */ public void setDestructuringLength(int destructuringLength) { this.destructuringLength = destructuringLength; } /** * Used by code generator. * * @return the number of empty elements */ public int getSkipCount() { return skipCount; } /** * Used by code generator. * * @param count the count of empty elements */ public void setSkipCount(int count) { skipCount = count; } /** * Marks this node as being a destructuring form - that is, appearing * in a context such as {@code for ([a, b] in ...)} where it's the * target of a destructuring assignment. */ @Override public void setIsDestructuring(boolean destructuring) { isDestructuring = destructuring; } /** * Returns true if this node is in a destructuring position: * a function parameter, the target of a variable initializer, the * iterator of a for..in loop, etc. */ @Override public boolean isDestructuring() { return isDestructuring; } @Override public String toSource(int depth) { StringBuilder sb = new StringBuilder(); sb.append(makeIndent(depth)); sb.append("["); if (elements != null) { printList(elements, sb); } sb.append("]"); return sb.toString(); } /** * Visits this node, then visits its element expressions in order. * Any empty elements are represented by {@link EmptyExpression} * objects, so the callback will never be passed {@code null}. */ @Override public void visit(NodeVisitor v) { if (v.visit(this)) { for (AstNode e : getElements()) { e.visit(v); } } } }
28.46798
94
0.597335
d25dc468ab13aded844759858b6b2f4168f93d02
2,319
package com.koch.ambeth.persistence.xml; /*- * #%L * jambeth-test * %% * Copyright (C) 2017 Koch Softwaredevelopment * %% * 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% */ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.List; import org.junit.Test; import com.koch.ambeth.informationbus.persistence.setup.SQLData; import com.koch.ambeth.informationbus.persistence.setup.SQLStructure; import com.koch.ambeth.persistence.xml.model.Employee; import com.koch.ambeth.persistence.xml.model.IEmployeeService; import com.koch.ambeth.service.config.ServiceConfigurationConstants; import com.koch.ambeth.testutil.AbstractInformationBusWithPersistenceTest; import com.koch.ambeth.testutil.TestModule; import com.koch.ambeth.testutil.TestProperties; import com.koch.ambeth.util.ParamChecker; @SQLData("Relations_data.sql") @SQLStructure("Relations_structure.sql") @TestProperties(name = ServiceConfigurationConstants.mappingFile, value = "com/koch/ambeth/persistence/xml/orm.xml") @TestModule(TestServicesModule.class) public class SelectWhereTest extends AbstractInformationBusWithPersistenceTest { protected IEmployeeService employeeService; @Override public void afterPropertiesSet() throws Throwable { super.afterPropertiesSet(); ParamChecker.assertNotNull(employeeService, "employeeService"); } public void setEmployeeService(IEmployeeService employeeService) { this.employeeService = employeeService; } @Test public void testSelectWhere() throws Throwable { List<Employee> sList = employeeService.retrieveOrderedByName(false); List<Employee> rList = employeeService.retrieveOrderedByName(true); assertFalse(sList.isEmpty()); for (int i = sList.size(); i-- > 0;) { assertEquals(sList.get(i), rList.get(rList.size() - 1 - i)); } } }
32.661972
80
0.790427
0c456da9621ba73db31b323c4123d032d7889087
6,326
package com.cloud.ratelimit.integration; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import com.cloud.api.response.ApiLimitResponse; import com.cloud.api.response.SuccessResponse; import com.cloud.legacymodel.exceptions.CloudRuntimeException; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.junit.Before; import org.junit.Test; /** * Test fixture to do integration rate limit test. * Currently we commented out this test suite since it requires a real MS and Db running. */ public class RateLimitIT extends APITest { private static final int apiMax = 25; // assuming ApiRateLimitService set api.throttling.max = 25 @Before public void setup() { // always reset count for each testcase login("admin", "password"); // issue reset api limit calls final HashMap<String, String> params = new HashMap<>(); params.put("response", "json"); params.put("sessionkey", sessionKey); final String resetResult = sendRequest("resetApiLimit", params); assertNotNull("Reset count failed!", fromSerializedString(resetResult, SuccessResponse.class)); } @Test public void testNoApiLimitOnRootAdmin() throws Exception { // issue list Accounts calls final HashMap<String, String> params = new HashMap<>(); params.put("response", "json"); params.put("listAll", "true"); params.put("sessionkey", sessionKey); // assuming ApiRateLimitService set api.throttling.max = 25 final int clientCount = 26; final Runnable[] clients = new Runnable[clientCount]; final boolean[] isUsable = new boolean[clientCount]; final CountDownLatch startGate = new CountDownLatch(1); final CountDownLatch endGate = new CountDownLatch(clientCount); for (int i = 0; i < isUsable.length; ++i) { final int j = i; clients[j] = new Runnable() { /** * {@inheritDoc} */ @Override public void run() { try { startGate.await(); sendRequest("listAccounts", params); isUsable[j] = true; } catch (final CloudRuntimeException e) { isUsable[j] = false; e.printStackTrace(); } catch (final InterruptedException e) { e.printStackTrace(); } finally { endGate.countDown(); } } }; } final ExecutorService executor = Executors.newFixedThreadPool(clientCount); for (final Runnable runnable : clients) { executor.execute(runnable); } startGate.countDown(); endGate.await(); int rejectCount = 0; for (int i = 0; i < isUsable.length; ++i) { if (!isUsable[i]) { rejectCount++; } } assertEquals("No request should be rejected!", 0, rejectCount); } @Test public void testApiLimitOnUser() throws Exception { // log in using normal user login("demo", "password"); // issue list Accounts calls final HashMap<String, String> params = new HashMap<>(); params.put("response", "json"); params.put("listAll", "true"); params.put("sessionkey", sessionKey); final int clientCount = apiMax + 1; final Runnable[] clients = new Runnable[clientCount]; final boolean[] isUsable = new boolean[clientCount]; final CountDownLatch startGate = new CountDownLatch(1); final CountDownLatch endGate = new CountDownLatch(clientCount); for (int i = 0; i < isUsable.length; ++i) { final int j = i; clients[j] = new Runnable() { /** * {@inheritDoc} */ @Override public void run() { try { startGate.await(); sendRequest("listAccounts", params); isUsable[j] = true; } catch (final CloudRuntimeException e) { isUsable[j] = false; e.printStackTrace(); } catch (final InterruptedException e) { e.printStackTrace(); } finally { endGate.countDown(); } } }; } final ExecutorService executor = Executors.newFixedThreadPool(clientCount); for (final Runnable runnable : clients) { executor.execute(runnable); } startGate.countDown(); endGate.await(); int rejectCount = 0; for (int i = 0; i < isUsable.length; ++i) { if (!isUsable[i]) { rejectCount++; } } assertEquals("Only one request should be rejected!", 1, rejectCount); } @Test public void testGetApiLimitOnUser() throws Exception { // log in using normal user login("demo", "password"); // issue an api call final HashMap<String, String> params = new HashMap<>(); params.put("response", "json"); params.put("listAll", "true"); params.put("sessionkey", sessionKey); sendRequest("listAccounts", params); // issue get api limit calls final HashMap<String, String> params2 = new HashMap<>(); params2.put("response", "json"); params2.put("sessionkey", sessionKey); final String getResult = sendRequest("getApiLimit", params2); final ApiLimitResponse getLimitResp = (ApiLimitResponse) fromSerializedString(getResult, ApiLimitResponse.class); assertEquals("Issued api count is incorrect!", 2, getLimitResp.getApiIssued()); // should be 2 apis issues plus this getlimit api assertEquals("Allowed api count is incorrect!", apiMax - 2, getLimitResp.getApiAllowed()); } }
33.470899
137
0.563547
5ae9d011d80fb93c9e53e18a1ba4a83e1e660883
1,458
package no.ssb.vtl.script.error; /*- * ========================LICENSE_START================================= * Java VTL * %% * Copyright (C) 2016 - 2017 Hadrien Kohl * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * =========================LICENSE_END================================== */ import javax.script.ScriptException; /** * The validation exception is thrown when a validation fails in the * VTL script. */ @Deprecated public class ValidationException extends ScriptException { public ValidationException(String s) { super(s); } public ValidationException(Exception e) { super(e); } public ValidationException(String message, String fileName, int lineNumber) { super(message, fileName, lineNumber); } public ValidationException(String message, String fileName, int lineNumber, int columnNumber) { super(message, fileName, lineNumber, columnNumber); } }
31.021277
99
0.655693
9ce999646088c585c18352385fb885fd73d02103
1,988
// // MessagePack for Java // // Copyright (C) 2009 - 2013 FURUHASHI Sadayuki // // 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.msgpack.io; import java.util.LinkedList; public final class LinkedBufferOutput extends BufferedOutput { private static final class Link { final byte[] buffer; final int offset; final int size; Link(byte[] buffer, int offset, int size) { this.buffer = buffer; this.offset = offset; this.size = size; } } private LinkedList<Link> link; private int size; public LinkedBufferOutput(int bufferSize) { super(bufferSize); link = new LinkedList<Link>(); } public byte[] toByteArray() { byte[] bytes = new byte[size + filled]; int off = 0; for (Link l : link) { System.arraycopy(l.buffer, l.offset, bytes, off, l.size); off += l.size; } if (filled > 0) { System.arraycopy(buffer, 0, bytes, off, filled); } return bytes; } public int getSize() { return size + filled; } @Override protected boolean flushBuffer(byte[] b, int off, int len) { link.add(new Link(b, off, len)); size += len; return false; } public void clear() { link.clear(); size = 0; filled = 0; } @Override public void close() { } }
25.818182
78
0.591046
491c3d21677b2fc4d52c034f8f9fbff2e8b91f81
15,147
package com.quorum.tessera.data; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import javax.persistence.*; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(Parameterized.class) public class EncryptedRawTransactionDAOTest { private EntityManagerFactory entityManagerFactory; private EncryptedRawTransactionDAO encryptedRawTransactionDAO; private TestConfig testConfig; public EncryptedRawTransactionDAOTest(TestConfig testConfig) { this.testConfig = testConfig; } @Before public void onSetUp() { Map properties = new HashMap(); properties.put("javax.persistence.jdbc.url", testConfig.getUrl()); properties.put("javax.persistence.jdbc.user", "junit"); properties.put("javax.persistence.jdbc.password", ""); properties.put("eclipselink.logging.logger", "org.eclipse.persistence.logging.slf4j.SLF4JLogger"); properties.put("eclipselink.logging.level", "FINE"); properties.put("eclipselink.logging.parameters", "true"); properties.put("eclipselink.logging.level.sql", "FINE"); properties.put("javax.persistence.schema-generation.database.action", "drop-and-create"); entityManagerFactory = Persistence.createEntityManagerFactory("tessera", properties); encryptedRawTransactionDAO = new EncryptedRawTransactionDAOImpl(entityManagerFactory); } @After public void onTearDown() { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.createQuery("delete from EncryptedRawTransaction").executeUpdate(); entityManager.getTransaction().commit(); } @Test public void saveDoesntAllowNullEncyptedPayload() { EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setHash(new MessageHash(new byte[] {5})); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); try { encryptedRawTransactionDAO.save(encryptedRawTransaction); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (PersistenceException ex) { String expectedMessage = String.format(testConfig.getRequiredFieldColumTemplate(), "ENCRYPTED_PAYLOAD"); assertThat(ex).hasMessageContaining(expectedMessage).hasMessageContaining("ENCRYPTED_PAYLOAD"); } } @Test public void saveDoesntAllowNullHash() { EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); try { encryptedRawTransactionDAO.save(encryptedRawTransaction); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (PersistenceException ex) { String expectedMessage = String.format(testConfig.getRequiredFieldColumTemplate(), "HASH"); assertThat(ex).hasMessageContaining(expectedMessage).hasMessageContaining("HASH"); } } @Test public void saveDoesntAllowNullNonce() { EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setHash(new MessageHash(new byte[] {5})); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); try { encryptedRawTransactionDAO.save(encryptedRawTransaction); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (PersistenceException ex) { String expectedMessage = String.format(testConfig.getRequiredFieldColumTemplate(), "NONCE"); assertThat(ex).hasMessageContaining(expectedMessage).hasMessageContaining("NONCE"); } } @Test public void saveDoesntAllowNullEncryptedKey() { EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setHash(new MessageHash(new byte[] {5})); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); try { encryptedRawTransactionDAO.save(encryptedRawTransaction); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (PersistenceException ex) { String expectedMessage = String.format(testConfig.getRequiredFieldColumTemplate(), "ENCRYPTED_KEY"); assertThat(ex).hasMessageContaining(expectedMessage).hasMessageContaining("ENCRYPTED_KEY"); } } @Test public void saveDoesntAllowNullSender() { EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setHash(new MessageHash(new byte[] {5})); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setEncryptedKey("key".getBytes()); try { encryptedRawTransactionDAO.save(encryptedRawTransaction); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (PersistenceException ex) { String expectedMessage = String.format(testConfig.getRequiredFieldColumTemplate(), "SENDER"); assertThat(ex).hasMessageContaining(expectedMessage).hasMessageContaining("SENDER"); } } @Test public void cannotPersistMultipleOfSameHash() { final EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setHash(new MessageHash(new byte[] {1})); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); encryptedRawTransactionDAO.save(encryptedRawTransaction); final EncryptedRawTransaction duplicateTransaction = new EncryptedRawTransaction(); duplicateTransaction.setEncryptedPayload(new byte[] {6}); duplicateTransaction.setHash(new MessageHash(new byte[] {1})); duplicateTransaction.setEncryptedKey("key".getBytes()); duplicateTransaction.setNonce("nonce".getBytes()); duplicateTransaction.setSender("from".getBytes()); try { encryptedRawTransactionDAO.save(duplicateTransaction); failBecauseExceptionWasNotThrown(PersistenceException.class); } catch (PersistenceException ex) { assertThat(ex).hasMessageContaining(testConfig.getUniqueContraintViolationMessage()); } } @Test public void validEncryptedRawTransactionCanBePersisted() { MessageHash messageHash = new MessageHash(UUID.randomUUID().toString().getBytes()); final EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setHash(messageHash); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); encryptedRawTransactionDAO.save(encryptedRawTransaction); EntityManager entityManager = entityManagerFactory.createEntityManager(); final EncryptedRawTransaction retrieved = entityManager.find(EncryptedRawTransaction.class, messageHash); assertThat(retrieved).isNotNull().isEqualToComparingFieldByField(encryptedRawTransaction); } @Test public void deleteTransactionRemovesFromDatabaseAndReturnsTrue() { // put a transaction in the database MessageHash messageHash = new MessageHash(UUID.randomUUID().toString().getBytes()); final EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setHash(messageHash); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(encryptedRawTransaction); entityManager.getTransaction().commit(); Query countQuery = entityManager.createQuery("select count(t) from EncryptedRawTransaction t where t.hash = :hash"); Long result = (Long) countQuery.setParameter("hash", messageHash).getSingleResult(); assertThat(result).isEqualTo(1L); // delete the transaction encryptedRawTransactionDAO.delete(messageHash); Long result2 = (Long) countQuery.setParameter("hash", messageHash).getSingleResult(); assertThat(result2).isZero(); } @Test(expected = EntityNotFoundException.class) public void deleteThrowsEntityNotFoundExceptionForNonExistentHash() { // delete the transaction encryptedRawTransactionDAO.delete(new MessageHash(UUID.randomUUID().toString().getBytes())); } @Test public void fetchingAllTransactionsReturnsAll() { EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); final List<EncryptedRawTransaction> payloads = IntStream.range(0, 50) .mapToObj(i -> UUID.randomUUID().toString().getBytes()) .map(MessageHash::new) .map( hash -> new EncryptedRawTransaction( hash, "payload".getBytes(), "key".getBytes(), "nonce".getBytes(), "sender".getBytes())) .peek(entityManager::persist) .collect(Collectors.toList()); entityManager.getTransaction().commit(); final List<EncryptedRawTransaction> retrievedList = encryptedRawTransactionDAO.retrieveTransactions(0, Integer.MAX_VALUE); assertThat(encryptedRawTransactionDAO.transactionCount()).isEqualTo(payloads.size()); assertThat(retrievedList).hasSameSizeAs(payloads); assertThat(retrievedList).hasSameElementsAs(payloads); } @Test public void retrieveByHashFindsTransactionThatIsPresent() { // put a transaction in the database MessageHash messageHash = new MessageHash(UUID.randomUUID().toString().getBytes()); final EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setHash(messageHash); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); EntityManager entityManager = entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); entityManager.persist(encryptedRawTransaction); entityManager.getTransaction().commit(); final Optional<EncryptedRawTransaction> retrieved = encryptedRawTransactionDAO.retrieveByHash(messageHash); assertThat(retrieved).isPresent(); assertThat(retrieved.get()).isEqualToComparingFieldByField(encryptedRawTransaction); } @Test public void retrieveByHashReturnsEmptyOptionalWhenNotPresent() { final MessageHash searchHash = new MessageHash(UUID.randomUUID().toString().getBytes()); final Optional<EncryptedRawTransaction> retrieved = encryptedRawTransactionDAO.retrieveByHash(searchHash); assertThat(retrieved.isPresent()).isFalse(); } @Test public void persistAddsTimestampToEntity() { final MessageHash messageHash = new MessageHash(UUID.randomUUID().toString().getBytes()); final EncryptedRawTransaction encryptedRawTransaction = new EncryptedRawTransaction(); encryptedRawTransaction.setEncryptedPayload(new byte[] {5}); encryptedRawTransaction.setHash(messageHash); encryptedRawTransaction.setEncryptedKey("key".getBytes()); encryptedRawTransaction.setNonce("nonce".getBytes()); encryptedRawTransaction.setSender("from".getBytes()); encryptedRawTransactionDAO.save(encryptedRawTransaction); EntityManager entityManager = entityManagerFactory.createEntityManager(); final EncryptedRawTransaction retrieved = entityManager.find(EncryptedRawTransaction.class, messageHash); assertThat(retrieved).isNotNull(); assertThat(retrieved.getTimestamp()).isNotZero(); } @Parameterized.Parameters(name = "DB {0}") public static Collection<TestConfig> connectionDetails() { return List.of(TestConfig.values()); } @Test public void upcheckReturnsTrue() { assertThat(encryptedRawTransactionDAO.upcheck()); } @Test public void upcheckFailDueToDB() { EntityManagerFactory mockEntityManagerFactory = mock(EntityManagerFactory.class); EntityManager mockEntityManager = mock(EntityManager.class); EntityTransaction mockEntityTransaction = mock(EntityTransaction.class); EntityManagerCallback mockEntityManagerCallback = mock(EntityManagerCallback.class); when(mockEntityManagerFactory.createEntityManager()).thenReturn(mockEntityManager); when(mockEntityManager.getTransaction()).thenReturn(mockEntityTransaction); when(mockEntityManagerCallback.execute(mockEntityManager)).thenThrow(RuntimeException.class); EncryptedRawTransactionDAO encryptedRawTransactionDAO = new EncryptedRawTransactionDAOImpl(mockEntityManagerFactory); assertThat(encryptedRawTransactionDAO.upcheck()).isFalse(); } }
44.031977
116
0.707665
7addb6c5fc59b5f2f54879d37d15ecbab17e30d9
268
package org.commandftc.tests; import org.commandftc.Trigger; public class MyTrigger extends Trigger { private boolean value = false; @Override public boolean get() { return value; } public void set(boolean v) { value = v; } }
17.866667
40
0.63806
ebff70a13b241697dd11c17d205283506fe23f4d
141
package tk.dczippl.lasercraft.fabric.util; public enum LaserColor { WHITE, RED, BLUE, CYAN, GREEN, PURPLE, YELLOW, BLACK, ORANGE }
10.071429
42
0.70922
03455085881e158ba9c1c3c3d96968da2ca04645
2,563
package snackBarApp;; public class Main { public static void workWithData() { //customers Customer c1 = new Customer("Jane", 45.25); Customer c2 = new Customer("Bob", 33.14); //vending machines VendingMachine food = new VendingMachine("food"); VendingMachine drink = new VendingMachine("drink"); VendingMachine office = new VendingMachine("office"); //snacks food Snack chips = new Snack("chips", 36, 1.75, food.getId()); Snack chocolateBar = new Snack("chocolateBar", 36, 1.00, food.getId()); Snack pretzel = new Snack("pretzel", 30, 2.00, food.getId()); //snacks drink Snack soda = new Snack("soda", 24, 2.50, drink.getId()); Snack water = new Snack("water", 20, 2.75, drink.getId()); //1 System.out.println(c1.getName().toString() + " buys 3 sodas and has " + (c1.buySnack(c1.getCash(), 3, soda.cost))); System.out.println(c1.getCash()); System.out.println("There are now " + soda.removeSnack(3) + " sodas"); //2 System.out.println(c1.getName().toString() + " buys 1 soda and has " + (c1.buySnack(c1.getCash(), 1, pretzel.cost))); System.out.println(c1.getCash()); System.out.println("There are now " + pretzel.removeSnack(1) + " pretzels left"); //3 System.out.println(c2.getName().toString() + " buys 2 sodas and has " + (c2.buySnack(c2.getCash(), 2, soda.cost))); System.out.println(c2.getCash()); System.out.println("There are now " + soda.removeSnack(2) + " sodas left"); //4 System.out.println(c1.getName().toString() + " finds " + c1.setCash(10) + " dollars"); System.out.println(c1.getCash()); //5 System.out.println(c1.getName().toString() + " buys 1 bag of chips and has " + (c1.buySnack(c1.getCash(), 1, chips.cost))); System.out.println(c1.getCash()); System.out.println("There are now " + chips.removeSnack(1) + " chips left"); //6 System.out.println("There are now " + pretzel.addSnack(12) + " pretzels left"); System.out.println(pretzel.quantity); //7 System.out.println(c1.getName().toString() + " buys 3 pretzels and has " + (c1.buySnack(c1.getCash(), 3, pretzel.cost))); System.out.println(c1.getCash()); System.out.println("There are now " + pretzel.removeSnack(3) + " pretzels left"); //stretch } public static void main(String[] args) { workWithData(); } }
39.430769
131
0.587593
5af704126008de6e161c1d8ff28ea932e350d7a7
317
import android.app.Activity; import com.squareup.leakcanary.LeakCanary; import javax.annotation.Generated; class TestActivity extends Activity { String mayReturnNull(int i) { return "Hello, Infer!"; } int cantCauseNPE() { String s = mayReturnNull(0); return s.length(); } }
19.8125
42
0.665615
c9ce202583612ec9b8f0c0d80f7feb01bdcf1ca7
3,711
/* * Copyright 2009-2019 University of Hildesheim, Software Systems Engineering * * 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 eu.qualimaster.common.signal; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.apache.log4j.LogManager; import org.apache.log4j.Logger; /** * Implements a generic plug-in parameter signal handler in case that code generation shall be simplified or * cannot be applied due to pre-defined class hierarchies. * * @author Holger Eichelberger */ public class ParameterSignalHandler implements Serializable, IParameterChangeListener { /** * Defines the interface for a plug-in parameter change handler. * * @author Holger Eichelberger */ public interface IParameterChangeHandler extends Serializable { /** * The name of the parameter this handler reacts on. * * @return the name of the parameter */ public String getName(); /** * Handles the parameter change. * * @param change the change information */ public void handle(ParameterChange change); } /** * Provides an abstract default implementation of {@link IParameterChangeHandler}. * * @author Holger Eichelberger */ public abstract static class AbstractParameterChangeHandler implements IParameterChangeHandler { private static final long serialVersionUID = 7123152990533146617L; private String name; /** * Creates the handler for a specific parameter name. * * @param name the parameter name */ protected AbstractParameterChangeHandler(String name) { this.name = name; } @Override public String getName() { return name; } } private static final long serialVersionUID = 8879442982814250422L; private Map<String, IParameterChangeHandler> handlers = new HashMap<String, IParameterChangeHandler>(); /** * Adds a parameter handler. Existing handlers will be overwritten. * * @param handler the handler */ public void addHandler(IParameterChangeHandler handler) { handlers.put(handler.getName(), handler); } @Override public void notifyParameterChange(ParameterChangeSignal signal) { for (int s = 0, n = signal.getChangeCount(); s < n; s++) { ParameterChange change = signal.getChange(s); String name = change.getName(); IParameterChangeHandler handler = handlers.get(name); if (null != handler) { handler.handle(change); } else { getLogger().warn("Unknown parameter change handler for parameter: " + name); } } } /** * Returns the logger. * * @return the logger */ private static Logger getLogger() { return LogManager.getLogger(ParameterSignalHandler.class); } }
31.184874
109
0.622474
7a079a8bed9bcf830525cd1fdbf08b4e0750423d
1,981
package com.ziponia.google; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import com.ziponia.google.maps.GoogleMapsClientInterceptor; import com.ziponia.google.maps.GoogleMapsRepository; import com.ziponia.google.youtube.YoutubeRepository; import okhttp3.OkHttpClient; import retrofit2.Call; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import java.io.IOException; import java.util.Map; public abstract class GoogleBaseClient { public static final String BASE_URL_MAPS = "https://maps.googleapis.com"; public static final String BASE_URL_YOUTUBE = "https://www.googleapis.com"; public static String API_KEY; public GoogleMapsRepository googleMapsClient; public YoutubeRepository youtubeClient; public GoogleBaseClient(final String apiKey) { API_KEY = apiKey; OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(new GoogleMapsClientInterceptor(apiKey)); Retrofit.Builder clientBuilder = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .client(httpClient.build()); googleMapsClient = clientBuilder.baseUrl(BASE_URL_MAPS) .build().create(GoogleMapsRepository.class); youtubeClient = clientBuilder.baseUrl(BASE_URL_YOUTUBE) .build().create(YoutubeRepository.class); } protected Map<String, String> object2Map(Object request) { String js = new Gson().toJson(request); TypeToken<Map<String, Object>> typeToken = new TypeToken<Map<String, Object>>() { }; return new Gson().fromJson(js, typeToken.getType()); } public <T> T exec(Call<T> call) { Response<T> res; try { res = call.execute(); return res.body(); } catch (IOException e) { throw new RuntimeException(e); } } }
34.155172
89
0.697123
e4af988b191f3973f3e5e96c6fdbca3023ddd68e
421
package com.vip001.bubblebar.view; import android.app.Application; /** * Created by vip001 on 2017/11/1. */ public class BrothersApplication extends Application { private static BrothersApplication mApplication; @Override public void onCreate() { super.onCreate(); mApplication = this; } public static Application getApplicationInstance() { return mApplication; } }
19.136364
56
0.688836
09c9052e2915d0104308270ab93b151e6f317283
1,962
package lingogo.testutil; import static lingogo.logic.parser.CliSyntax.PREFIX_ENGLISH_PHRASE; import static lingogo.logic.parser.CliSyntax.PREFIX_FOREIGN_PHRASE; import static lingogo.logic.parser.CliSyntax.PREFIX_LANGUAGE_TYPE; import lingogo.logic.commands.AddCommand; import lingogo.logic.commands.EditCommand.EditFlashcardDescriptor; import lingogo.model.flashcard.Flashcard; /** * A utility class for Flashcard. */ public class FlashcardUtil { /** * Returns an add command string for adding the {@code flashcard}. */ public static String getAddCommand(Flashcard flashcard) { return AddCommand.COMMAND_WORD + " " + getFlashcardDetails(flashcard); } /** * Returns the part of command string for the given {@code flashcard}'s details. */ public static String getFlashcardDetails(Flashcard flashcard) { StringBuilder sb = new StringBuilder(); sb.append(PREFIX_LANGUAGE_TYPE + flashcard.getLanguageType().value + " "); sb.append(PREFIX_ENGLISH_PHRASE + flashcard.getEnglishPhrase().value + " "); sb.append(PREFIX_FOREIGN_PHRASE + flashcard.getForeignPhrase().value + " "); return sb.toString(); } /** * Returns the part of command string for the given {@code EditFlashcardDescriptor}'s details. */ public static String getEditFlashcardDescriptorDetails(EditFlashcardDescriptor descriptor) { StringBuilder sb = new StringBuilder(); descriptor.getLanguageType().ifPresent(languageType -> sb.append(PREFIX_LANGUAGE_TYPE) .append(languageType.value).append(" ")); descriptor.getEnglishPhrase().ifPresent(englishPhrase -> sb.append(PREFIX_ENGLISH_PHRASE) .append(englishPhrase.value).append(" ")); descriptor.getForeignPhrase().ifPresent(foreignPhrase -> sb.append(PREFIX_FOREIGN_PHRASE) .append(foreignPhrase.value).append(" ")); return sb.toString(); } }
40.875
98
0.712538
c0981a0b431f5fa9eb4ac5c032bc80bd2f998a47
6,317
package org.firstinspires.ftc.teamcode.utils; import android.os.Environment; import android.util.Log; import com.sun.tools.doclint.Env; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.Locale; import java.util.Objects; import java.util.TimeZone; public class Logger { private static final String LOG_PATH = "/" + "FIRST" + "/" + "logs" + "/"; private static final String DEFAULT_ROBOT_LOG = "*robotLog.txt"; private static final String DEFAULT_MATCH_LOG = "defaultRobotLog.txt"; private static String matchLogFileName = DEFAULT_MATCH_LOG; private static final boolean deleteOldLogs = true; public static void createMatchLogFile( String className ) { SimpleDateFormat matchFormatter = new SimpleDateFormat( "MM-dd_HH-mm_", Locale.getDefault( ) ); matchFormatter.setTimeZone( TimeZone.getDefault( ) ); String time = matchFormatter.format( new Date( ) ); // ("MM-dd_HH'h'mm'm'_") looks like: 04-05_15h11m_TeleOpTechnicolor.txt // ("MM-dd_HH-mm_") looks like: 04-05_15-11_TeleOpTechnicolor.txt matchLogFileName = time + className + ".txt"; writeAFile( matchLogFileName, matchLogFileName + ": created", false, true ); } /** * writes to the default match file * * @param writeText what the method will write to the fill (plus the timeStamp if includeTimeStamp is true) * @param includeTimeStamp will include the timeStamp for when the method is called */ public static void writeToMatchFile( String writeText, boolean includeTimeStamp ) { Log.v( "MatchFile", writeText ); writeAFile( matchLogFileName, writeText, true, includeTimeStamp ); } /** * writes to the default file *robotLog.txt * * @param writeText what the method will write to the fill (plus the timeStamp if includeTimeStamp is true) * @param isAppending true: will append to the file if it exists, false: will create a new file * @param includeTimeStamp will include the timeStamp for when the method is called */ public static void writeToDefaultFile( String writeText, boolean isAppending, boolean includeTimeStamp ) { Log.v( "DefaultFile", writeText ); writeAFile( DEFAULT_ROBOT_LOG, writeText, isAppending, includeTimeStamp ); } /** * @param fileName the name of the file to write to * @param writeText what the method will write to the fill (plus the timeStamp if includeTimeStamp is true) * @param isAppending true: will append to the file if it exists, false: will create a new file * @param includeTimeStamp will include the timeStamp for when the method is called */ public static void writeAFile( String fileName, String writeText, boolean isAppending, boolean includeTimeStamp ) { // "\n" = System.lineSeparator() new Thread( ( ) -> { String time = ""; Date date; if( includeTimeStamp || deleteOldLogs ) date = new Date( ); if( includeTimeStamp ) time = new SimpleDateFormat( "MM-dd HH:mm:ss", Locale.getDefault( ) ).format( date ) + " :: "; //".../Internal Storage"; String path = Environment.getExternalStorageDirectory( ).getPath( ) + LOG_PATH; try { FileWriter writer = new FileWriter( path + fileName, isAppending ); writer.write( time + writeText + System.lineSeparator( ) ); writer.close( ); } catch( IOException e ) { e.printStackTrace( ); } if( deleteOldLogs ) deleteOldLogsDay( new SimpleDateFormat( "MM-dd", Locale.getDefault( ) ).format( date ) ); } ).start( ); } private static boolean deleteLog( String oldFileName ) { //".../Internal Storage"; String path = Environment.getExternalStorageDirectory( ).getPath( ) + LOG_PATH; return new File( path, oldFileName ).delete( ); } /** * deletes all files in the /FIRST/LOG/ directory without the date provided * * @param date the date to not delete - formatted like this: "08-31" */ public static void deleteOldLogsDay( String date ) { // File dir = Environment.getExternalStorageDirectory( ); File dir = Environment.getRootDirectory( ); // File dir = Environment.getDataDirectory( ); // for( File file : Objects.requireNonNull( dir.listFiles( ) ) ) // if( !file.getName( ).startsWith( date ) ) // Log.e( "LOG", "" + file.getName( ) + System.lineSeparator( ) + " :: " + file.getPath( ) + System.lineSeparator( ) + " :: " + file.getAbsolutePath( ) ); // new File( dir.getPath( ) + LOG_PATH, file.getName( ) ); // deleteLog( f.getName( ) ); } /** * deletes all files in the /FIRST/LOG/ directory without the date(s) provided * * @param dates the date(s) to not delete - formatted like this: "08-31" * @return an array with which files were deleted (true = success) */ public static boolean[] deleteOldLogsDay( String[] dates ) { return deleteOldLogsDay( (ArrayList<String>) Arrays.asList( dates ) ); // File dir = Environment.getExternalStorageDirectory( ); // // boolean[] successfulOperations = new boolean[dates.length]; // int index = 0; // // for( File file : Objects.requireNonNull( dir.listFiles( ) ) ) { // boolean startsWithDate = false; // for( String date : dates ) // if( file.getName( ).startsWith( date ) ) // startsWithDate = true; // if( !startsWithDate ) // successfulOperations[index++] = new File( dir.getPath( ) + LOG_PATH, file.getName( ) ).delete( ); // } // // return successfulOperations; } /** * deletes all files in the /FIRST/LOG/ directory without the date(s) provided * * @param dates the date(s) to not delete - formatted like this: "08-31" * @return an array with which files were deleted (true = success) */ public static boolean[] deleteOldLogsDay( ArrayList<String> dates ) { File dir = Environment.getExternalStorageDirectory( ); boolean[] successfulOperations = new boolean[dates.size( )]; int index = 0; for( File file : Objects.requireNonNull( dir.listFiles( ) ) ) { boolean startsWithDate = false; for( int i = 0; i < dates.size( ); i++ ) if( file.getName( ).startsWith( dates.get( i ) ) ) startsWithDate = true; if( !startsWithDate ) successfulOperations[index++] = new File( dir.getPath( ) + LOG_PATH, file.getName( ) ).delete( ); } return successfulOperations; } }
34.708791
157
0.692259
32bfb44b2fa0d7b85b934ea277251407e3c00c41
1,077
package io.cucumber.java; import org.apiguardian.api.API; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Register a data table type. * <p> * The signature of the method is used to determine which data table type is registered: * * <ul> * <li>{@code String -> Author} will register a {@link io.cucumber.datatable.TableCellTransformer}</li> * <li>{@code Map<String, String> -> Author} will register a {@link io.cucumber.datatable.TableEntryTransformer}</li> * <li>{@code List<String> -> Author} will register a {@link io.cucumber.datatable.TableRowTransformer}</li> * <li>{@code DataTable -> Author} will register a {@link io.cucumber.datatable.TableTransformer}</li> * </ul> * NOTE: {@code Author} is an example of the class you want to convert the table to. * * @see io.cucumber.datatable.DataTableType */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @API(status = API.Status.STABLE) public @interface DataTableType { }
34.741935
117
0.741876
17f48b41595feb836051e4b672f54eec60e3e494
298
package ro.msg.learning.shop.Repositories; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import ro.msg.learning.shop.Entities.Customer; @Repository public interface CustomerRepository extends JpaRepository<Customer, Integer> { }
27.090909
78
0.842282
010e895f3f8306fcdcc3c9cf4ee7b61f62e84147
2,675
package org.bozdogan; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.bozdogan.util.Hashing.sha1FromFile; import static org.bozdogan.util.Hashing.bytes2hex; public class DuplicateDetector{ public static void main(String[] args){ Map<String, List<Path>> visitList = new HashMap<>(); // gonna cause OoM exception at some point. // Starting directory Path start = Paths.get("D:\\bora\\belge\\__GECICI__"); FileVisitor<Path> visitor = new SimpleFileVisitor<Path>(){ @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException{ try{ // System.out.println("Processing "+file.toString()); System.out.print(". "); String sum = bytes2hex(sha1FromFile(file)); if(! visitList.containsKey(sum)) visitList.put(sum, new LinkedList<>()); visitList.get(sum).add(file); } catch(FileSystemException e){ // happens when two processes try to reach a file at the same time. return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc)/* throws IOException*/{ // Handling exceptions properly. if(exc instanceof AccessDeniedException) System.out.println("Access Denied: "+exc.getMessage()); else if(exc instanceof FileSystemException) System.out.println("File System Issue: "+exc.getMessage()); else System.out.println("Some IO Error: "+exc.getMessage()); return FileVisitResult.SKIP_SUBTREE; } }; try{ System.out.println("Processing..."); Files.walkFileTree(start, visitor); } catch(IOException e){ e.printStackTrace(); } System.out.println("\n\n -- Duplicate files: \n" + "-----------------------------------------"); for(Map.Entry<String, List<Path>> e: visitList.entrySet()){ if(e.getValue().size()>1){ System.out.println(e.getKey()+":"); for(Path path : e.getValue()) System.out.println(" "+path.toString()); } } } } //bzdgn
35.197368
104
0.557757
38bd381c1a42f5cb133471591c0119e93aa199ff
1,095
package com.venky.swf.db.annotations.column.validations.processors; import java.text.ParseException; import java.text.SimpleDateFormat; import com.venky.core.util.MultiException; import com.venky.core.util.ObjectUtil; import com.venky.swf.db.annotations.column.COLUMN_DEF; import com.venky.swf.db.annotations.column.defaulting.StandardDefault; public class DateFormatValidator extends FieldValidator<COLUMN_DEF> { public DateFormatValidator(String pool) { super(pool); } @Override public boolean validate(COLUMN_DEF annotation, String humanizedFieldName, String value, MultiException ex){ if (ObjectUtil.isVoid(value)){ return true; } if (annotation.value() == StandardDefault.CURRENT_DATE || annotation.value() == StandardDefault.CURRENT_TIMESTAMP){ String format = annotation.args(); if (!ObjectUtil.isVoid(format)){ try { new SimpleDateFormat(format).parse(value); } catch (ParseException e) { ex.add(new FieldValidationException(humanizedFieldName + " must be in " + format + " format.")); return false; } } } return true; } }
28.815789
117
0.747945
e2939dc90e71807dd6eedf26ef78542f8266f518
351
package Tools; import org.apache.commons.io.IOUtils; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; public class IOUtilsTools { public String inputStreamToString(InputStream inputStream) throws IOException { return IOUtils.toString(inputStream, StandardCharsets.UTF_8.name()); } }
25.071429
83
0.783476
1f5e3e70689a4c510de9ee704dfa367b5e49378a
673
package org.baeldung.springevents.synchronous; import org.springframework.context.ApplicationListener; import org.springframework.lang.NonNull; import org.springframework.stereotype.Component; @Component public class GenericSpringEventListener implements ApplicationListener<GenericSpringAppEvent<String>> { // for testing private boolean hitEventHandler = false; @Override public void onApplicationEvent(@NonNull final GenericSpringAppEvent<String> event) { System.out.println("Received spring generic event - " + event.getWhat()); hitEventHandler = true; } boolean isHitEventHandler() { return hitEventHandler; } }
30.590909
103
0.762259
68677ae97e737135c555c2fcd6a778bfcee4bc2d
2,145
package com.commercetools.history.models.change; import java.time.*; import java.util.*; import java.util.function.Function; import javax.validation.Valid; import javax.validation.constraints.NotNull; import com.commercetools.history.models.common.LocalizedString; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.annotation.*; import io.vrap.rmf.base.client.utils.Generated; @Generated(value = "io.vrap.rmf.codegen.rendring.CoreCodeGenerator", comments = "https://github.com/vrapio/rmf-codegen") @JsonDeserialize(as = SetMetaTitleChangeImpl.class) public interface SetMetaTitleChange extends Change { String SET_META_TITLE_CHANGE = "SetMetaTitleChange"; @NotNull @JsonProperty("type") public String getType(); /** * <p>Shape of the action for <code>setMetaTitle</code></p> */ @NotNull @JsonProperty("change") public String getChange(); @NotNull @Valid @JsonProperty("previousValue") public LocalizedString getPreviousValue(); @NotNull @Valid @JsonProperty("nextValue") public LocalizedString getNextValue(); public void setChange(final String change); public void setPreviousValue(final LocalizedString previousValue); public void setNextValue(final LocalizedString nextValue); public static SetMetaTitleChange of() { return new SetMetaTitleChangeImpl(); } public static SetMetaTitleChange of(final SetMetaTitleChange template) { SetMetaTitleChangeImpl instance = new SetMetaTitleChangeImpl(); instance.setChange(template.getChange()); instance.setPreviousValue(template.getPreviousValue()); instance.setNextValue(template.getNextValue()); return instance; } public static SetMetaTitleChangeBuilder builder() { return SetMetaTitleChangeBuilder.of(); } public static SetMetaTitleChangeBuilder builder(final SetMetaTitleChange template) { return SetMetaTitleChangeBuilder.of(template); } default <T> T withSetMetaTitleChange(Function<SetMetaTitleChange, T> helper) { return helper.apply(this); } }
28.986486
120
0.734732
3c89a7197a4beefcd1e8441bb9642720bddb8f6c
14,733
/* * Copyright (c) 2010-2019 Evolveum and contributors * * This work is dual-licensed under the Apache License 2.0 * and European Union Public License. See LICENSE file for details. */ package com.evolveum.midpoint.model.impl.scripting; import com.evolveum.midpoint.common.StaticExpressionUtil; import com.evolveum.midpoint.model.impl.expr.ModelExpressionThreadLocalHolder; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.CloneUtil; import com.evolveum.midpoint.prism.xml.XsdTypeMapper; import com.evolveum.midpoint.repo.common.ObjectResolver; import com.evolveum.midpoint.repo.common.expression.*; import com.evolveum.midpoint.schema.SchemaConstantsGenerated; import com.evolveum.midpoint.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.expression.ExpressionProfile; import com.evolveum.midpoint.schema.expression.TypedValue; import com.evolveum.midpoint.schema.expression.VariablesMap; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingVariableDefinitionType; import com.evolveum.midpoint.xml.ns._public.model.scripting_3.ScriptingVariablesDefinitionType; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.xml.bind.JAXBElement; import javax.xml.namespace.QName; import java.util.*; /** * @author mederly */ public class VariablesUtil { private static final Trace LOGGER = TraceManager.getTrace(VariablesUtil.class); static class VariableResolutionContext { @NotNull final ExpressionFactory expressionFactory; @NotNull final ObjectResolver objectResolver; @NotNull final PrismContext prismContext; final ExpressionProfile expressionProfile; @NotNull final Task task; VariableResolutionContext(@NotNull ExpressionFactory expressionFactory, @NotNull ObjectResolver objectResolver, @NotNull PrismContext prismContext, ExpressionProfile expressionProfile, @NotNull Task task) { this.expressionFactory = expressionFactory; this.objectResolver = objectResolver; this.prismContext = prismContext; this.expressionProfile = expressionProfile; this.task = task; } } // We create immutable versions of prism variables to avoid unnecessary downstream cloning @NotNull static VariablesMap initialPreparation(VariablesMap initialVariables, ScriptingVariablesDefinitionType derivedVariables, ExpressionFactory expressionFactory, ObjectResolver objectResolver, PrismContext prismContext, ExpressionProfile expressionProfile, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { VariablesMap rv = new VariablesMap(); addProvidedVariables(rv, initialVariables, task); addDerivedVariables(rv, derivedVariables, new VariableResolutionContext(expressionFactory, objectResolver, prismContext, expressionProfile, task), result); return rv; } private static void addProvidedVariables(VariablesMap resultingVariables, VariablesMap initialVariables, Task task) { TypedValue<TaskType> taskValAndDef = new TypedValue<>(task.getUpdatedOrClonedTaskObject().asObjectable(), task.getUpdatedOrClonedTaskObject().getDefinition()); putImmutableValue(resultingVariables, ExpressionConstants.VAR_TASK, taskValAndDef); if (initialVariables != null) { initialVariables.forEach((key, value) -> putImmutableValue(resultingVariables, key, value)); } } private static void addDerivedVariables(VariablesMap resultingVariables, ScriptingVariablesDefinitionType definitions, VariableResolutionContext ctx, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { if (definitions == null) { return; } for (ScriptingVariableDefinitionType definition : definitions.getVariable()) { if (definition.getExpression() == null) { continue; // todo or throw an exception? } String shortDesc = "scripting variable " + definition.getName(); TypedValue valueAndDef; if (definition.getExpression().getExpressionEvaluator().size() == 1 && QNameUtil.match(SchemaConstantsGenerated.C_PATH, definition.getExpression().getExpressionEvaluator().get(0).getName())) { valueAndDef = variableFromPathExpression(resultingVariables, definition.getExpression().getExpressionEvaluator().get(0), ctx, shortDesc, result); } else { valueAndDef = variableFromOtherExpression(resultingVariables, definition, ctx, shortDesc, result); } putImmutableValue(resultingVariables, definition.getName(), valueAndDef); } } private static TypedValue variableFromPathExpression(VariablesMap resultingVariables, JAXBElement<?> expressionEvaluator, VariableResolutionContext ctx, String shortDesc, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (!(expressionEvaluator.getValue() instanceof ItemPathType)) { throw new IllegalArgumentException("Path expression: expected ItemPathType but got " + expressionEvaluator.getValue()); } ItemPath itemPath = ctx.prismContext.toPath((ItemPathType) expressionEvaluator.getValue()); return ExpressionUtil.resolvePathGetTypedValue(itemPath, createVariables(resultingVariables), false, null, ctx.objectResolver, ctx.prismContext, shortDesc, ctx.task, result); } private static ExpressionVariables createVariables(VariablesMap variableMap) { ExpressionVariables rv = new ExpressionVariables(); VariablesMap clonedVariableMap = cloneIfNecessary(variableMap); clonedVariableMap.forEach((name, value) -> rv.put(name, value)); return rv; } private static TypedValue variableFromOtherExpression(VariablesMap resultingVariables, ScriptingVariableDefinitionType definition, VariableResolutionContext ctx, String shortDesc, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException { ItemDefinition<?> outputDefinition = determineOutputDefinition(definition, ctx, shortDesc); Expression<PrismValue, ItemDefinition<?>> expression = ctx.expressionFactory .makeExpression(definition.getExpression(), outputDefinition, ctx.expressionProfile, shortDesc, ctx.task, result); ExpressionEvaluationContext context = new ExpressionEvaluationContext(null, createVariables(resultingVariables), shortDesc, ctx.task); PrismValueDeltaSetTriple<?> triple = ModelExpressionThreadLocalHolder .evaluateAnyExpressionInContext(expression, context, ctx.task, result); Collection<?> resultingValues = triple.getNonNegativeValues(); Object value; if (definition.getMaxOccurs() != null && outputDefinition.isSingleValue() // cardinality of outputDefinition is derived solely from definition.maxOccurs (if specified) || definition.getMaxOccurs() == null || resultingValues.size() <= 1) { value = MiscUtil.getSingleValue(resultingValues, null, shortDesc); // unwrapping will occur when the value is used } else { value = unwrapPrismValues(resultingValues); } return new TypedValue(value, outputDefinition); } // TODO shouldn't we unwrap collections of prism values in the same way as in ExpressionUtil.convertVariableValue ? private static Collection<?> unwrapPrismValues(Collection<?> prismValues) { Collection<Object> rv = new ArrayList<>(prismValues.size()); for (Object value : prismValues) { if (value instanceof PrismValue) { rv.add(((PrismValue) value).getRealValue()); } else { rv.add(value); } } return rv; } private static ItemDefinition<?> determineOutputDefinition(ScriptingVariableDefinitionType variableDefinition, VariableResolutionContext ctx, String shortDesc) throws SchemaException { List<JAXBElement<?>> evaluators = variableDefinition.getExpression().getExpressionEvaluator(); boolean isValue = !evaluators.isEmpty() && QNameUtil.match(evaluators.get(0).getName(), SchemaConstants.C_VALUE); QName elementName = new QName(variableDefinition.getName()); if (variableDefinition.getType() != null) { Integer maxOccurs; if (variableDefinition.getMaxOccurs() != null) { maxOccurs = XsdTypeMapper.multiplicityToInteger(variableDefinition.getMaxOccurs()); } else if (isValue) { // if we have constant values we can try to guess maxOccurs = evaluators.size() > 1 ? -1 : 1; } else { maxOccurs = null; // no idea } if (maxOccurs == null) { maxOccurs = -1; // to be safe } return ctx.prismContext.getSchemaRegistry().createAdHocDefinition(elementName, variableDefinition.getType(), 0, maxOccurs); } if (isValue) { return StaticExpressionUtil.deriveOutputDefinitionFromValueElements(elementName, evaluators, shortDesc, ctx.prismContext); } else { throw new SchemaException("The type of scripting variable " + variableDefinition.getName() + " is not defined"); } } private static void putImmutableValue(VariablesMap map, String name, TypedValue valueAndDef) { map.put(name, makeImmutable(valueAndDef)); } @NotNull public static VariablesMap cloneIfNecessary(@NotNull VariablesMap variables) { VariablesMap rv = new VariablesMap(); variables.forEach((key, value) -> rv.put(key, cloneIfNecessary(key, value))); return rv; } @Nullable public static <T> TypedValue<T> cloneIfNecessary(String name, TypedValue<T> valueAndDef) { T valueClone = (T) cloneIfNecessary(name, valueAndDef.getValue()); if (valueClone == valueAndDef.getValue()) { return valueAndDef; } else { return valueAndDef.createTransformed(valueClone); } } @Nullable public static <T> T cloneIfNecessary(String name, T value) { if (value == null) { return null; } T immutableOrNull = tryMakingImmutable(value); if (immutableOrNull != null) { return immutableOrNull; } else { try { return CloneUtil.clone(value); } catch (Throwable t) { LOGGER.warn("Scripting variable value {} of type {} couldn't be cloned. Using original.", name, value.getClass()); return value; } } } public static <T> TypedValue<T> makeImmutable(TypedValue<T> valueAndDef) { T immutableValue = (T) makeImmutableValue(valueAndDef.getValue()); if (immutableValue == valueAndDef.getValue()) { return valueAndDef; } else { valueAndDef.setValue(immutableValue); } return valueAndDef; } public static <T> T makeImmutableValue(T value) { T rv = tryMakingImmutable(value); return rv != null ? rv : value; } @SuppressWarnings("unchecked") @Nullable public static <T> T tryMakingImmutable(T value) { if (value instanceof Containerable) { PrismContainerValue<?> pcv = ((Containerable) value).asPrismContainerValue(); if (!pcv.isImmutable()) { PrismContainerValue clone = pcv.clone(); Containerable containerableClone = clone.asContainerable(); clone.setImmutable(true); // must be called after first asContainerable on clone return (T) containerableClone; } else { return value; } } else if (value instanceof Referencable) { PrismReferenceValue prv = ((Referencable) value).asReferenceValue(); if (!prv.isImmutable()) { PrismReferenceValue clone = prv.clone(); Referencable referencableClone = clone.asReferencable(); clone.setImmutable(true); // must be called after first asReferencable on clone return (T) referencableClone; } else { return value; } } else if (value instanceof PrismValue) { PrismValue pval = (PrismValue) value; if (!pval.isImmutable()) { PrismValue clone = pval.clone(); clone.setImmutable(true); return (T) clone; } else { return (T) pval; } } else if (value instanceof Item) { Item item = (Item) value; if (!item.isImmutable()) { Item clone = item.clone(); clone.setImmutable(true); return (T) clone; } else { return (T) item; } } else { return null; } } }
50.455479
192
0.689744
2b56f69f3a5ab0badc411ff5c833d80d0c51c1e8
1,807
package evilcraft.api.config; import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import evilcraft.proxies.ClientProxy; /** * Config for entities. * For mobs, there is the {@link MobConfig}. * For entities with custom models there is {@link ModelEntityConfig}. * @author rubensworks * @see ExtendedConfig */ public abstract class EntityConfig extends ExtendedConfig<EntityConfig>{ /** * Make a new instance. * @param enabled If this should is enabled. * @param namedId The unique name ID for the configurable. * @param comment The comment to add in the config file for this configurable. * @param element The class of this configurable. */ public EntityConfig(boolean enabled, String namedId, String comment, Class<? extends Entity> element) { super(enabled, namedId, comment, element); } @Override @SideOnly(Side.CLIENT) public void onRegistered() { @SuppressWarnings("unchecked") Class<? extends Entity> clazz = (Class<? extends Entity>) this.ELEMENT; ClientProxy.ENTITY_RENDERERS.put(clazz, getRender()); } /** * The range at which MC will send tracking updates. * @return The tracking range. */ public int getTrackingRange() { return 160; } /** * The frequency of tracking updates. * @return The update frequency. */ public int getUpdateFrequency() { return 10; } /** * Whether to send velocity information packets as well. * @return Send velocity updates? */ public boolean sendVelocityUpdates() { return false; } protected abstract Render getRender(); }
28.68254
107
0.665744
383d9eb62eb7bd03e1808541c26b936018e7cbef
5,081
package net.encode.wurmesp.feature; import com.wurmonline.client.game.PlayerPosition; import com.wurmonline.mesh.Tiles; import java.awt.Color; import java.util.logging.Level; import java.util.logging.Logger; import net.encode.wurmesp.WurmEspMod; import net.encode.wurmesp.util.RenderUtils; import net.encode.wurmesp.util.XrayColors; public class FeatureXRay extends Feature { @Override public void refresh() { if (!this.world.isOwnBodyAdded()) { return; } WurmEspMod._terrain.clear(); WurmEspMod._caveBuffer = this.world.getCaveBuffer(); PlayerPosition pos = this.world.getPlayer().getPos(); int px = pos.getTileX(); int py = pos.getTileY(); int size = WurmEspMod.xraydiameter; int sx = px - size / 2; int sy = py - size / 2; float ox = this.world.getRenderOriginX(); float oy = this.world.getRenderOriginY(); for (int x = 0; x < size; ++x) { for (int y = size - 1; y >= 0; --y) { try { int tileX = x + sx; int tileY = y + sy; Tiles.Tile tile = WurmEspMod._caveBuffer.getTileType(tileX, tileY); if (tile == null || !tile.isOreCave()) continue; Color color = XrayColors.getColorFor(tile); float[] colorF = new float[]{(float)color.getRed() / 255.0f, (float)color.getGreen() / 255.0f, (float)color.getBlue() / 255.0f}; float curX = (float)(tileX * 4) - ox; float curY = (float)(tileY * 4) - oy; float nextX = (float)((tileX + 1) * 4) - ox; float nextY = (float)((tileY + 1) * 4) - oy; float x0 = curX + 0.2f; float y0 = curY + 0.2f; float x1 = nextX - 0.2f; float y1 = nextY - 0.2f; WurmEspMod._terrain.add(new float[]{x0, y0, x1, y1, colorF[0], colorF[1], colorF[2]}); continue; } catch (IllegalArgumentException | SecurityException ex) { Logger.getLogger(FeatureXRay.class.getName()).log(Level.SEVERE, null, ex); } } } } @Override public void queue() { if (WurmEspMod._terrain == null) { return; } WurmEspMod._terrain.stream().forEach(t -> { float x0 = t[0]; float y0 = t[1]; float x1 = t[2]; float y1 = t[3]; float[] color = new float[]{t[4],t[5],t[6], 1.0F}; PlayerPosition pos = this.world.getPlayer().getPos(); float z0 = pos.getH(); float z1 = z0 + 3; float[] vertexdata = new float[] { x1, z0, y0, x1, z1, y0, x0, z1, y0, x0, z0, y0, x1, z0, y1, x1, z1, y1, x0, z1, y1, x0, z0, y1 }; int[] indexdata = new int[] { 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 }; RenderUtils.renderPrimitiveLines(8, vertexdata, indexdata, this.queuePick, color); }); /* if (!this.world.isOwnBodyAdded()) { return; } WurmEspMod._terrain.clear(); WurmEspMod._caveBuffer = this.world.getCaveBuffer(); PlayerPosition pos = this.world.getPlayer().getPos(); int px = pos.getTileX(); int py = pos.getTileY(); int size = WurmEspMod.xraydiameter; int sx = px - size / 2; int sy = py - size / 2; WorldRender worldRenderer = (WorldRender)ReUtils.getField(this.world, "worldRenderer"); CaveRender caveRenderer = (CaveRender)ReUtils.getField(worldRenderer, "caveRenderer"); for (int x = 0; x < size; ++x) { for (int y = size - 1; y >= 0; --y) { try { int tileX = x + sx; int tileY = y + sy; for (int side = 0; side < 7; ++side) { IntBuffer intBuffer = IntBuffer.allocate(3); intBuffer.put(tileX); intBuffer.put(tileY); intBuffer.put(side); Class<HitNamesData> cls = HitNamesData.class; Constructor<HitNamesData> constructor = cls.getDeclaredConstructor(IntBuffer.class, Integer.TYPE); constructor.setAccessible(true); HitNamesData hitNames = (HitNamesData)constructor.newInstance(intBuffer, 3); caveRenderer.getPickedWall(hitNames).renderPicked(this.queuePick, RenderState.RENDERSTATE_DEFAULT, com.wurmonline.client.renderer.Color.GREEN); } continue; } catch (IllegalAccessException | IllegalArgumentException | InstantiationException | NoSuchMethodException | SecurityException | InvocationTargetException ex) { Logger.getLogger(FeatureXRay.class.getName()).log(Level.SEVERE, null, ex); } } }*/ } }
40.325397
175
0.525684
55290fcdbec1a5c91adf7d52fff7b0c686434038
447
package net.mrsistemas.healthy.data.business.repository; import net.mrsistemas.healthy.data.business.model.DataSensor; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import java.util.List; public interface DataSensorRepository extends MongoRepository<DataSensor, Long> { @Query("{ 'patient.id' : ?0 }") List<DataSensor> findDataSensorByPatient(Long id); }
31.928571
81
0.803132
3d89eca40ff16dd9dd5faabb6b8e41921f6e4c79
2,872
package net.swordie.ms.life.mob.boss.demian.sword; import net.swordie.ms.connection.OutPacket; import net.swordie.ms.util.Position; /** * Created on 17-8-2019. * * @author Asura */ public class DemianFlyingSwordNode { private DemianFlyingSwordNodeType nodeType; private DemianFlyingSwordPathIdx pathIdx; private short nodeIdx; private short velocity; private int startDelay; private int endDelay; private int duration; private boolean hide; private byte collisionType; private Position position; public DemianFlyingSwordNode(DemianFlyingSwordNodeType nodeType, Position position) { this.nodeType = nodeType; this.velocity = 35; this.position = position; } public DemianFlyingSwordNodeType getNodeType() { return nodeType; } public void setNodeType(DemianFlyingSwordNodeType nodeType) { this.nodeType = nodeType; } public DemianFlyingSwordPathIdx getPathIdx() { return pathIdx; } public void setPathIdx(DemianFlyingSwordPathIdx pathIdx) { this.pathIdx = pathIdx; } public short getNodeIdx() { return nodeIdx; } public void setNodeIdx(short nodeIdx) { this.nodeIdx = nodeIdx; } public short getVelocity() { return velocity; } public void setVelocity(short velocity) { this.velocity = velocity; } public int getStartDelay() { return startDelay; } public void setStartDelay(int startDelay) { this.startDelay = startDelay; } public int getEndDelay() { return endDelay; } public void setEndDelay(int endDelay) { this.endDelay = endDelay; } public int getDuration() { return duration; } public void setDuration(int duration) { this.duration = duration; } public boolean isHide() { return hide; } public void setHide(boolean hide) { this.hide = hide; } public byte getCollisionType() { return collisionType; } public void setCollisionType(byte collisionType) { this.collisionType = collisionType; } public Position getPosition() { return position; } public void setPosition(Position position) { this.position = position; } public void encodeNodeData(OutPacket outPacket) { outPacket.encodeByte(getNodeType().getVal()); outPacket.encodeShort(getPathIdx().getVal()); outPacket.encodeShort(getNodeIdx()); outPacket.encodeShort(getVelocity()); outPacket.encodeInt(getStartDelay()); outPacket.encodeInt(getEndDelay()); outPacket.encodeInt(getDuration()); outPacket.encodeByte(isHide()); outPacket.encodeByte(getCollisionType()); outPacket.encodePositionInt(getPosition()); } }
23.540984
89
0.652855
fad17a7be747601c38a28d7b3a0a643ec26940cb
1,445
package com.migo.portal.controller; import com.migo.pojo.TbItem; import com.migo.portal.service.ItemService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Author 知秋 * Created by kauw on 2016/10/25. */ @Controller public class ItemController { @Autowired private ItemService itemService; @RequestMapping("/item/{itemId}") public String getItemInfo(@PathVariable Long itemId, Model model){ TbItem item = itemService.getItemById(itemId); model.addAttribute("item",item); return "item"; } @RequestMapping(value = "/item/desc/{itemId}",produces = MediaType.TEXT_HTML_VALUE+";charset=utf-8") @ResponseBody public String getItemDescinfo(@PathVariable Long itemId){ String itemDesc = itemService.getItemDescById(itemId); return itemDesc; } @RequestMapping(value = "/item/param/{itemId}",produces = MediaType.TEXT_HTML_VALUE+";charset=utf-8") @ResponseBody public String getItemParam(@PathVariable Long itemId){ String itemParamHtml = itemService.getItemParamById(itemId); return itemParamHtml; } }
33.604651
105
0.745329
f40812fafeb7ddb42425e88de55de7cc8df810f6
3,927
package com.github.cc3002.finalreality.controller.phases.subphases; import com.github.cc3002.finalreality.controller.GameController; import com.github.cc3002.finalreality.controller.phases.InvalidMethodCalledException; import com.github.cc3002.finalreality.controller.phases.InvalidTransitionException; import com.github.cc3002.finalreality.controller.phases.PhaseTest; import com.github.cc3002.finalreality.model.character.ICharacter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.LinkedList; import static org.junit.jupiter.api.Assertions.*; public class EnemyBeginTurnPhaseTest extends PhaseTest { @BeforeEach void setUp(){ testController = new GameController(); originalPhase = new EnemyBeginTurnPhase("EnemyBeginTurnPhase"); testPhase = new EnemyBeginTurnPhase("EnemyBeginTurnPhase"); testController.setPhase(testPhase); entitySetUp(); } @Override public void checkToEnemyBeginTurnPhase() { try { testPhase.toEnemyBeginTurnPhase(); } catch (InvalidTransitionException e) { assertEquals(new EnemyBeginTurnPhase("EnemyBeginTurnPhase"),testController.getPhase()); } } @Override public void checkToEndTurnPhase() { try { testPhase.toEndTurnPhase(); } catch (InvalidTransitionException e) { e.printStackTrace(); } assertEquals(new EndTurnPhase("EndTurnPhase"),testController.getPhase()); } @Override public void checkToEndGamePhase() { try { testPhase.toEndGamePhase(); } catch (InvalidTransitionException e) { e.printStackTrace(); } assertEquals(new EndGamePhase("EndGamePhase"),testController.getPhase()); } @Override public void checkActionAttackRandomPlayerCharacter() { try { ICharacter cast = (ICharacter) testCharacter3; int prevHp = cast.getCurrentHealthPoints(); System.out.println(prevHp); LinkedList info = testPhase.actionAttackRandomPlayerCharacter(testCharacter1); assertEquals(cast.getName(),info.get(1)); assertEquals(cast.getCurrentHealthPoints(),prevHp - (int) info.get(0)); } catch (InvalidMethodCalledException e) { e.printStackTrace(); } } @Test public void constructionTest(){ StartGamePhase differentPhase = new StartGamePhase("StartGamePhase"); EnemyBeginTurnPhase expectedPhase = new EnemyBeginTurnPhase("EnemyBeginTurnPhase"); assertEquals(testPhase,testPhase); assertFalse(testPhase.equals(differentPhase)); assertEquals(expectedPhase,testPhase); assertEquals(expectedPhase.hashCode(),testPhase.hashCode()); } @Test public void methodsTest() throws InterruptedException { checkToPlayerBeginTurnPhase(); testController.setPhase(new EnemyBeginTurnPhase("EnemyBeginTurnPhase")); checkToEnemyBeginTurnPhase(); testController.setPhase(new EnemyBeginTurnPhase("EnemyBeginTurnPhase")); checkToEquipWeaponPhase(); testController.setPhase(new EnemyBeginTurnPhase("EnemyBeginTurnPhase")); checkToSelectAttackTargetPhase(); testController.setPhase(new EnemyBeginTurnPhase("EnemyBeginTurnPhase")); checkToEndTurnPhase(); testController.setPhase(new EnemyBeginTurnPhase("EnemyBeginTurnPhase")); checkToEndGamePhase(); testController.setPhase(new EnemyBeginTurnPhase("EnemyBeginTurnPhase")); checkStartTurns(); checkActionAttackCharacter(); checkActionAttackRandomPlayerCharacter(); checkEquipWeapon(); checkEndTurn(); checkPlayerWins(); checkPlayerLost(); } }
38.126214
100
0.679654
c0b63045d1fb932497e62816f5b57a7f25ef9615
159
package com.example.weather; public class City { public String cityname; public String stateDetailed; public String tem1; public String tem2; }
15.9
30
0.72956
5431329d7338bdbfcdcc626f9921e6143c92dae8
500
package pw.mihou.rosedb.manager; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class ResponseManager { public static final Map<String, String> responses = new ConcurrentHashMap<>(); public static String get(String key){ String t = responses.get(key); responses.remove(key); RequestManager.requests.remove(key); return t; } public static boolean isNull(String key){ return responses.get(key) == null; } }
22.727273
82
0.678
0cdd829cd9dcfc4409fafeb65d96119e76acd435
3,685
/* * Copyright 2011-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.databasemigrationservice.model.transform; import java.util.Map; import java.util.List; import com.amazonaws.SdkClientException; import com.amazonaws.services.databasemigrationservice.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.BinaryUtils; import com.amazonaws.util.StringUtils; import com.amazonaws.util.IdempotentUtils; import com.amazonaws.util.StringInputStream; import com.amazonaws.protocol.json.*; /** * OrderableReplicationInstanceMarshaller */ public class OrderableReplicationInstanceJsonMarshaller { /** * Marshall the given parameter object, and output to a SdkJsonGenerator */ public void marshall(OrderableReplicationInstance orderableReplicationInstance, StructuredJsonGenerator jsonGenerator) { if (orderableReplicationInstance == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { jsonGenerator.writeStartObject(); if (orderableReplicationInstance.getEngineVersion() != null) { jsonGenerator.writeFieldName("EngineVersion").writeValue(orderableReplicationInstance.getEngineVersion()); } if (orderableReplicationInstance.getReplicationInstanceClass() != null) { jsonGenerator.writeFieldName("ReplicationInstanceClass").writeValue(orderableReplicationInstance.getReplicationInstanceClass()); } if (orderableReplicationInstance.getStorageType() != null) { jsonGenerator.writeFieldName("StorageType").writeValue(orderableReplicationInstance.getStorageType()); } if (orderableReplicationInstance.getMinAllocatedStorage() != null) { jsonGenerator.writeFieldName("MinAllocatedStorage").writeValue(orderableReplicationInstance.getMinAllocatedStorage()); } if (orderableReplicationInstance.getMaxAllocatedStorage() != null) { jsonGenerator.writeFieldName("MaxAllocatedStorage").writeValue(orderableReplicationInstance.getMaxAllocatedStorage()); } if (orderableReplicationInstance.getDefaultAllocatedStorage() != null) { jsonGenerator.writeFieldName("DefaultAllocatedStorage").writeValue(orderableReplicationInstance.getDefaultAllocatedStorage()); } if (orderableReplicationInstance.getIncludedAllocatedStorage() != null) { jsonGenerator.writeFieldName("IncludedAllocatedStorage").writeValue(orderableReplicationInstance.getIncludedAllocatedStorage()); } jsonGenerator.writeEndObject(); } catch (Throwable t) { throw new SdkClientException("Unable to marshall request to JSON: " + t.getMessage(), t); } } private static OrderableReplicationInstanceJsonMarshaller instance; public static OrderableReplicationInstanceJsonMarshaller getInstance() { if (instance == null) instance = new OrderableReplicationInstanceJsonMarshaller(); return instance; } }
45.493827
144
0.722931
8d20cdfd3b5a101a89ad7435c77bf7bddc28196c
1,121
package eu.applabs.allplaylibrary.event; import eu.applabs.allplaylibrary.services.ServiceType; public class ServiceConnectionEvent extends Event { public enum ServiceConnectionEventType { CONNECTED, DISCONNECTED, ERROR } private ServiceConnectionEventType mServiceConnectionEventType; private ServiceType mServiceType; public ServiceConnectionEvent(ServiceConnectionEventType serviceConnectionEventType, ServiceType serviceType) { super(EventType.SERVICE_CONNECTION_EVENT); mServiceConnectionEventType = serviceConnectionEventType; mServiceType = serviceType; } public ServiceConnectionEventType getServiceConnectionEventType() { return mServiceConnectionEventType; } public void setServiceConnectionEventType(ServiceConnectionEventType serviceConnectionEventType) { mServiceConnectionEventType = serviceConnectionEventType; } public ServiceType getServiceType() { return mServiceType; } public void setServiceType(ServiceType serviceType) { mServiceType = serviceType; } }
28.74359
115
0.760036
ef134644184f1fe495d786892bfda82a64508987
3,086
package com.amazonaws.services.iot.client.shadow; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.Mockito.lenient; import java.util.concurrent.atomic.AtomicLong; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import com.amazonaws.services.iot.client.AWSIotDeviceErrorCode; import com.amazonaws.services.iot.client.AWSIotQos; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(MockitoJUnitRunner.class) public class AwsIotDeviceSyncMessageTest { private static final String TEST_TOPIC = "test/topic"; private static final AWSIotQos TEST_QOS = AWSIotQos.QOS0; @Mock private AbstractAwsIotDevice device; private ObjectMapper objectMapper; @Before public void setup() { objectMapper = new ObjectMapper(); when(device.getJsonObjectMapper()).thenReturn(objectMapper); } @Test public void testOnSuccessInvalidPayload() { AwsIotDeviceSyncMessage message = new AwsIotDeviceSyncMessage(TEST_TOPIC, TEST_QOS, device); message.setStringPayload("123"); message.onSuccess(); verify(device, never()).getLocalVersion(); } @Test public void testOnSuccessVersionAlreadyUpdated() { AtomicLong localVersion = new AtomicLong(2); when(device.getLocalVersion()).thenReturn(localVersion); AwsIotDeviceSyncMessage message = new AwsIotDeviceSyncMessage(TEST_TOPIC, TEST_QOS, device); message.setStringPayload("{\"version\":1}"); message.onSuccess(); assertEquals(2, localVersion.get()); } @Test public void testOnSuccessVersionNotUpdated() { AtomicLong localVersion = new AtomicLong(-1); when(device.getLocalVersion()).thenReturn(localVersion); AwsIotDeviceSyncMessage message = new AwsIotDeviceSyncMessage(TEST_TOPIC, TEST_QOS, device); message.setStringPayload("{\"version\":1}"); message.onSuccess(); assertEquals(1, localVersion.get()); } @Test public void testOnFailureDeviceNotFound() { AtomicLong localVersion = new AtomicLong(-1); when(device.getLocalVersion()).thenReturn(localVersion); AwsIotDeviceSyncMessage message = new AwsIotDeviceSyncMessage(TEST_TOPIC, TEST_QOS, device); message.setErrorCode(AWSIotDeviceErrorCode.NOT_FOUND); message.onFailure(); assertEquals(0, localVersion.get()); } @Test public void testOnFailureOtherError() { AtomicLong localVersion = new AtomicLong(-1); lenient().when(device.getLocalVersion()).thenReturn(localVersion); AwsIotDeviceSyncMessage message = new AwsIotDeviceSyncMessage(TEST_TOPIC, TEST_QOS, device); message.setErrorCode(AWSIotDeviceErrorCode.INTERNAL_SERVICE_FAILURE); message.onFailure(); assertEquals(-1, localVersion.get()); } }
30.554455
100
0.722618
e11bf3c06cc856d2b38aca38c686746c72780b3c
2,584
/* * STFNReferenceHandler.java * * 03.05.2013 * * (c) by ollie * */ package archimedes.legacy.scheme.stf.handler; import archimedes.legacy.scheme.stf.*; /** * A class with the basic data for STF access of NReference objects. * * @author ollie * * @changed OLI 03.05.2013 - Added. */ public class STFNReferenceHandler extends AbstractSTFHandler { public static final String ALTERABLE = "Alterable"; public static final String CODEGENERATOR = "Codegenerator"; public static final String COLUMN = "Spalte"; public static final String COUNT = "Anzahl"; public static final String DELETE_CONFIRMATION_REQUIRED = "DeleteConfirmationRequired"; public static final String EXTENSIBLE = "Extensible"; public static final String ID = "Id"; public static final String NREFERENCE = "NReferenz"; public static final String NREFERENCES = "NReferenzen"; public static final String PANEL = "Panel"; public static final String PANEL_TYPE = "PanelType"; public static final String PERMIT_CREATE = "PermitCreate"; public static final String TABLE = "Tabelle"; public static final String TABLES = "Tabellen"; /** * Creates an array with the strings to identify a field of table i and the nReferences. * * @param additionalIds The additional id's which are following the id header for list * elements. * * @changed OLI 03.05.2013 - Added. */ @Override public String[] createPath(int i, String... additionalIds) { return super.createPath(i, concat(new String[] {CODEGENERATOR, NREFERENCES}, additionalIds)); } /** * Creates an array with the strings to identify a field of table i and nReference j. * * @param i The index of the table whose path create. * @param j The index of the nReference whose path create. * @param additionalIds The additional id's which are following the id header for list * elements. * * @changed OLI 03.05.2013 - Added. */ public String[] createPathForNReference(int i, int j, String... additionalIds) { return this.createPath(i, concat(new String[] {NREFERENCE + j}, additionalIds)); } /** * @changed OLI 03.05.2013 - Added. */ @Override public String getSingleListElementTagId() { return TABLE; } /** * @changed OLI 03.05.2013 - Added. */ @Override public String getWholeBlockTagId() { return TABLES; } }
31.512195
93
0.642415
f131a15b1f94030a22b0773917c569f6f42398c5
2,300
/* * Copyright (c) 2015 EMC Corporation * All Rights Reserved */ package com.emc.storageos.model.vpool; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "file_protection") public class FileVirtualPoolProtectionUpdateParam extends VirtualPoolProtectionParam { private Boolean scheduleSnapshots; private Boolean replicationSupported; private Boolean allowFilePolicyAtProjectLevel; private Boolean allowFilePolicyAtFSLevel; private Long minRpoValue; private String minRpoType; public FileVirtualPoolProtectionUpdateParam() { } /** * The snapshot protection settings for a virtual pool. * */ @XmlElement(name = "schedule_snapshots") public Boolean getScheduleSnapshots() { return scheduleSnapshots; } public void setScheduleSnapshots(Boolean scheduleSnapshots) { this.scheduleSnapshots = scheduleSnapshots; } @XmlElement(name = "replication_supported") public Boolean getReplicationSupported() { return replicationSupported; } public void setReplicationSupported(Boolean replicationSupported) { this.replicationSupported = replicationSupported; } @XmlElement(name = "allow_policy_at_project_level") public Boolean getAllowFilePolicyAtProjectLevel() { return allowFilePolicyAtProjectLevel; } public void setAllowFilePolicyAtProjectLevel(Boolean allowFilePolicyAtProjectLevel) { this.allowFilePolicyAtProjectLevel = allowFilePolicyAtProjectLevel; } @XmlElement(name = "allow_policy_at_fs_level") public Boolean getAllowFilePolicyAtFSLevel() { return allowFilePolicyAtFSLevel; } public void setAllowFilePolicyAtFSLevel(Boolean allowFilePolicyAtFSLevel) { this.allowFilePolicyAtFSLevel = allowFilePolicyAtFSLevel; } @XmlElement(name = "min_rpo_value") public Long getMinRpoValue() { return minRpoValue; } public void setMinRpoValue(Long minRpoValue) { this.minRpoValue = minRpoValue; } @XmlElement(name = "rpo_type") public String getMinRpoType() { return minRpoType; } public void setMinRpoType(String minRpoType) { this.minRpoType = minRpoType; } }
27.710843
89
0.729565
05e8dab8c82362837b656a61c251a818af75df0f
2,854
/** * 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. * * Copyright 2012-2015 the original author or authors. */ package org.assertj.core.error; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.error.ShouldHaveEqualContent.shouldHaveEqualContent; import static org.assertj.core.util.Lists.newArrayList; import static org.assertj.core.util.SystemProperties.LINE_SEPARATOR; import java.io.ByteArrayInputStream; import java.util.List; import org.assertj.core.description.TextDescription; import org.assertj.core.presentation.StandardRepresentation; import org.junit.Before; import org.junit.Test; /** * Tests for * <code>{@link ShouldHaveEqualContent#create(org.assertj.core.description.Description, org.assertj.core.presentation.Representation)}</code> * . * * @author Yvonne Wang * @author Matthieu Baechler */ public class ShouldHaveEqualContent_create_Test { private List<String> diffs; @Before public void setUp() { diffs = newArrayList("line:<0>, \nExpecting:\n<line0> but was:<line_0>", "line:<1>, \nExpecting:\n<line1> but was:<line_1>", "line:<2>, \nExpecting:\n<line2> but was:<line_%s>"); } @Test public void should_create_error_message_file_even_if_content_contains_format_specifier() { ErrorMessageFactory factory = shouldHaveEqualContent(new FakeFile("abc"), new FakeFile("xyz"), diffs); StringBuilder b = new StringBuilder("[Test] \nFile:\n <abc>\nand file:\n <xyz>\ndo not have equal content:"); for (String diff : diffs) b.append(LINE_SEPARATOR).append(diff); assertThat(factory.create(new TextDescription("Test"), new StandardRepresentation())).isEqualTo(b.toString()); } @Test public void should_create_error_message_inputstream_even_if_content_contains_format_specifier() { ErrorMessageFactory factory = shouldHaveEqualContent(new ByteArrayInputStream(new byte[] { 'a' }), new ByteArrayInputStream(new byte[] { 'b' }), diffs); StringBuilder b = new StringBuilder("[Test] \nInputStreams do not have equal content:"); for (String diff : diffs) b.append(LINE_SEPARATOR).append(diff); assertThat(factory.create(new TextDescription("Test"), new StandardRepresentation())).isEqualTo(b.toString()); } }
41.970588
141
0.724597
b476739614792fadb3d8c0ddf08980e084625d0d
1,379
package uni.UNI4950687.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import androidx.annotation.Nullable; import uni.UNI4950687.db.SupplierContract.SupplierEntry; public class DBHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "Supplier.db"; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + SupplierEntry.TABLE_NAME + " (" + SupplierEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + SupplierEntry.COLUMN_NAME_NAME + " TEXT," + SupplierEntry.COLUMN_NAME_AREA + " VARCHAR(255)," + SupplierEntry.COLUMN_NAME_ADDRESS + " TEXT," + SupplierEntry.COLUMN_NAME_TEL + " VARCHAR(255)," + SupplierEntry.COLUMN_NAME_DELIVERY + " VARCHAR(255))"; public DBHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) { super(context, name, factory, version); } @Override public void onCreate(SQLiteDatabase sqLiteDatabase) { sqLiteDatabase.execSQL(SQL_CREATE_ENTRIES); } @Override public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) { } }
35.358974
132
0.684554
2fb278797bd982d8f8ed7d61efe3b56ceb64169d
2,110
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/gaming/v1alpha/allocation_policies.proto package com.google.cloud.gaming.v1alpha; public interface CreateAllocationPolicyRequestOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.gaming.v1alpha.CreateAllocationPolicyRequest) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Required. The parent resource name, using the form: * `projects/{project_id}/locations/{location}`. * </pre> * * <code>string parent = 1;</code> */ java.lang.String getParent(); /** * * * <pre> * Required. The parent resource name, using the form: * `projects/{project_id}/locations/{location}`. * </pre> * * <code>string parent = 1;</code> */ com.google.protobuf.ByteString getParentBytes(); /** * * * <pre> * Required. The ID of the allocation policy resource to be created. * </pre> * * <code>string allocation_policy_id = 2;</code> */ java.lang.String getAllocationPolicyId(); /** * * * <pre> * Required. The ID of the allocation policy resource to be created. * </pre> * * <code>string allocation_policy_id = 2;</code> */ com.google.protobuf.ByteString getAllocationPolicyIdBytes(); /** * * * <pre> * Required. The allocation policy resource to be created. * </pre> * * <code>.google.cloud.gaming.v1alpha.AllocationPolicy allocation_policy = 3;</code> */ boolean hasAllocationPolicy(); /** * * * <pre> * Required. The allocation policy resource to be created. * </pre> * * <code>.google.cloud.gaming.v1alpha.AllocationPolicy allocation_policy = 3;</code> */ com.google.cloud.gaming.v1alpha.AllocationPolicy getAllocationPolicy(); /** * * * <pre> * Required. The allocation policy resource to be created. * </pre> * * <code>.google.cloud.gaming.v1alpha.AllocationPolicy allocation_policy = 3;</code> */ com.google.cloud.gaming.v1alpha.AllocationPolicyOrBuilder getAllocationPolicyOrBuilder(); }
24.534884
108
0.656872
e77114940497d3ee65958ef189bcf7731b0eef55
2,980
package org.firstinspires.ftc.teamcode.util; public class RateController { private double m_rate; // factor for rate control private double m_maximumOutput = 1.0; // |maximum output| private double m_minimumOutput = -1.0; // |minimum output| private boolean m_enabled = false; //is the pid controller enabled private double m_result = 0.0; private long m_prevNanos; //time of previous calculate() in nanoseconds from the current epoch private double m_deltaTime; // time between calls to calculate() in fractional seconds private long m_currentNanos; /** * Allocate a RateController with the given RatePerSecond * Implementation assumes the emit() method will be colled * somewhat regularly whenever enabled * @param RatePerSecond */ public RateController(double RatePerSecond) { m_rate = RatePerSecond; m_prevNanos = System.nanoTime(); } //simplified call to set the RatePerSecond and enable in the same call to get() //can make the usage more readable public double get(double RatePerSecond){ setRate(RatePerSecond); enable(); return get(); } /** * Emit the rate since the last call to get() */ public double get() { // If enabled then proceed into controller calculations if (m_enabled) { //time since last iteration m_currentNanos = System.nanoTime(); m_deltaTime=(m_currentNanos - m_prevNanos)/1E9; m_prevNanos = m_currentNanos; //factor the rate for deltaTime m_result = m_rate * m_deltaTime; // Make sure the final result is within bounds // if (m_result > m_maximumOutput) { // m_result = m_maximumOutput; // } else if (m_result < m_minimumOutput) { // m_result = m_minimumOutput; // } } else m_result = 0; return m_result; } public void setRate(double ratePerSecond) { m_rate = ratePerSecond; } public synchronized double getRate() { return m_rate; } /** * Sets the minimum and maximum values to write. * * @param minimumOutput the minimum value to write to the output * @param maximumOutput the maximum value to write to the output */ public void setOutputRange(double minimumOutput, double maximumOutput) { m_minimumOutput = minimumOutput; m_maximumOutput = maximumOutput; } public synchronized double getDeltaTime() { return m_deltaTime; } public void enable() { if (!m_enabled) m_prevNanos = System.nanoTime(); //if it's been disabled the previous time is likely very stale m_enabled = true; } /** * Stop running the Rate Controller, this forces the output to zero. */ public void disable() { m_enabled = false; } }
30.408163
119
0.62349
574b83345d6bc8d66506c443974ad08c22bc7cfc
249
package nerddinner.model; import lombok.Data; import java.util.List; @Data public class ValidationResult<T> { private Boolean isValid; private List<ValidationError> validationErrors; private T model; private String successUrl; }
16.6
51
0.751004
26279f3e5eda0dba507caec789402ca3954a41d2
2,095
package ir.shayandaneshvar.model.Assets; import ir.shayandaneshvar.model.Assets.BoardAssets; import ir.shayandaneshvar.model.Assets.Cell; import ir.shayandaneshvar.model.Assets.Piece; import ir.shayandaneshvar.model.Position; import javafx.scene.paint.Color; import org.jgrapht.Graph; import org.jgrapht.graph.DefaultEdge; import org.jgrapht.graph.SimpleGraph; import java.util.ArrayList; import java.util.List; public class Board { private Graph<Cell, DefaultEdge> gameBoard; private List<Cell> cells; private BoardAssets assets; public Board() { assets = new BoardAssets(new Piece(new Position(4, 0), Color.GREENYELLOW), new Piece(new Position(4, 8), Color.CRIMSON)); this.gameBoard = new SimpleGraph<>(DefaultEdge.class); cells = new ArrayList<>(); for (int j = 0; j < 9; j++) { for (int i = 0; i < 9; i++) { Cell cell = new Cell(new Position(i, j)); cells.add(cell); gameBoard.addVertex(cell); } } for (int k = 0; k < 9; k++) { int l = k; for (int i = 0; i < 9; i++) { int j = i; Cell main = cells.stream().filter(x -> x.getPosition().getX() == j && x.getPosition().getY() == l).findAny().get(); if (k != 8) { gameBoard.addEdge(main, cells.stream().filter(x -> x.getPosition(). getX() == j && x.getPosition().getY() == l + 1).findAny().get()); } if (i != 8) { gameBoard.addEdge(main, cells.stream().filter(x -> x. getPosition().getX() == j + 1 && x.getPosition().getY() == l).findAny().get()); } } } } public Graph<Cell, DefaultEdge> getGameBoard() { return gameBoard; } public ArrayList<Cell> getCells() { return (ArrayList<Cell>) ((ArrayList<Cell>) cells).clone(); } public BoardAssets getAssets() { return assets; } }
34.344262
107
0.536038
a947fc44014c63fb6074f3966546006fa709d4ad
3,671
/* SPDX-License-Identifier: Apache-2.0 */ /* Copyright Contributors to the ODPi Egeria project. */ package org.odpi.egeria.connectors.ibm.igc.repositoryconnector.stores; import org.odpi.egeria.connectors.ibm.igc.repositoryconnector.IGCOMRSRepositoryConnector; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.TypeDef; import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.properties.typedefs.TypeDefPatch; import org.odpi.openmetadata.repositoryservices.ffdc.exception.InvalidParameterException; import org.odpi.openmetadata.repositoryservices.ffdc.exception.PatchErrorException; import java.util.*; /** * Store of implemented mappings for the repository. */ public abstract class MappingStore { protected IGCOMRSRepositoryConnector igcomrsRepositoryConnector; private Map<String, TypeDef> typeDefs; private Map<String, String> omrsNameToGuid; protected MappingStore(IGCOMRSRepositoryConnector igcomrsRepositoryConnector) { typeDefs = new TreeMap<>(); omrsNameToGuid = new HashMap<>(); this.igcomrsRepositoryConnector = igcomrsRepositoryConnector; } /** * Adds the provided TypeDef as one that has been mapped. * * @param typeDef to add */ public void addTypeDef(TypeDef typeDef) { if (typeDef != null) { String guid = typeDef.getGUID(); typeDefs.put(guid, typeDef); addNameToGuidMapping(typeDef.getName(), guid); } } /** * Adds a mapping between an OMRS type name and its GUID. * * @param name of the OMRS type * @param guid of the OMRS type */ private void addNameToGuidMapping(String name, String guid) { if (name != null && guid != null) { omrsNameToGuid.put(name, guid); } } /** * Retrieve the GUID of an OMRS type given its name. * * @param name of the OMRS type * @return String giving its GUID, or null if it is not a mapped type */ public String getGuidForName(String name) { return omrsNameToGuid.getOrDefault(name, null); } /** * Updates a mapping using the provided TypeDefPatch, where the mapping for the type being patched must already * exist. * * @param typeDefPatch the patch to apply * @return boolean false when unable to find the existing mapping to patch * @throws InvalidParameterException if the typeDefPatch is null * @throws PatchErrorException if the patch is either badly formatted or does not apply to the defined type */ public boolean updateMapping(TypeDefPatch typeDefPatch) throws InvalidParameterException, PatchErrorException { String omrsTypeGUID = typeDefPatch.getTypeDefGUID(); TypeDef existing = typeDefs.getOrDefault(omrsTypeGUID, null); if (existing != null) { TypeDef updated = igcomrsRepositoryConnector.getRepositoryHelper().applyPatch(igcomrsRepositoryConnector.getServerName(), existing, typeDefPatch); typeDefs.put(omrsTypeGUID, updated); } return (existing != null); } /** * Retrieves the listing of all TypeDefs for which classification mappings are implemented. * * @return {@code List<TypeDef>} */ public List<TypeDef> getTypeDefs() { return new ArrayList<>(this.typeDefs.values()); } /** * Retrieve the OMRS TypeDef by its guid. * * @param guid of the OMRS TypeDef * @return TypeDef */ public TypeDef getTypeDefByGUID(String guid) { return typeDefs.getOrDefault(guid, null); } }
35.640777
158
0.694906
f081a7a11533f6f1e218ea534bc4baaaba8839f2
2,055
/** * 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.hadoop.hdfs.server.namenode; import java.io.InputStream; import org.apache.hadoop.io.MD5Hash; /** * Wrapper class used for loading images to the namesystem. It contains * information about the md5 digest, size and the string representation of the * underlying image location. */ public class ImageInputStream { final long txid; final InputStream inputStream; MD5Hash digest; final String name; final long size; public ImageInputStream(long txid, InputStream inputStream, MD5Hash digest, String name, long size) { this.txid = txid; this.inputStream = inputStream; this.digest = digest; this.name = name; this.size = size; } /** * Get size of the image stored in the underlying location. */ public long getSize() { return size; } @Override public String toString() { return name; } /** * Get input stream for reading. */ public InputStream getInputStream() { return inputStream; } /** * Update image digest for this image. */ public void setImageDigest(MD5Hash digest) { this.digest = digest; } /** * Return digest associated with this image location. */ public MD5Hash getDigest() { return digest; } }
26.012658
78
0.707543
7e0e54fd783331499f06588c87fc6b28bae9e88a
2,488
package cn.originx.infix.mysql5.cv; /** * MySql关键字 */ public interface MySqlWord { interface Foreign { /* 设置NULL **/ String SET_NULL = "SET NULL"; /* 设置NO ACTION **/ String NO_ACTION = "NO ACTION"; /* 设置CASCADE */ String CASCADE = "CASCADE"; } interface Type { /* 0.TINYINT */ String TINYINT = "TINYINT"; /* 1.SMALLINT */ String SMALLINT = "SMALLINT"; /* 2.INT */ String INT = "INT"; /* 3.BIGINT */ String BIGINT = "BIGINT"; /* 4.DECIMAL */ String DECIAML = "DECIMAL"; /* 5.NUMBERIC */ String NUMERIC = "NUMERIC"; /* 6.FLOAT */ String FLOAT = "FLOAT"; /* 7.CHAR */ String CHAR = "CHAR"; /* 8.VARCHAR */ String VARCHAR = "VARCHAR"; /* 9.TEXT */ String TEXT = "TEXT"; /* 10.BIT */ String BIT = "BIT"; /* 11.BINARY */ String BINARY = "BINARY"; /* 12.VARBINARY */ String VARBINARY = "VARBINARY"; /* 13.DATE */ String DATE = "DATE"; /* 14.DATETIME */ String DATETIME = "DATETIME"; /* 15.TIME */ String TIME = "TIME"; /* 16.TIMESTAMP */ String TIMESTAMP = "TIMESTAMP"; /* 17.JSON */ String JSON = "JSON"; } interface Pattern { /* P_S */ String P_S = "({0},{1})"; /* P_N */ String P_N = "({0})"; /* 自增长 */ String P_IDENTIFY = "AUTO_INCREMENT"; /* Decimal */ String P_DECIMAL = Type.DECIAML + P_S; /* Numeric */ String P_NUMERIC = Type.NUMERIC + P_S; /* CHAR,VARCHAR */ String P_CHAR = Type.CHAR + P_N; String P_VARCHAR = Type.VARCHAR + P_N; /* BINARY,VARBINARY */ String P_BINARY = Type.BINARY + P_N; String P_VARBINARY = Type.VARBINARY + P_N; } interface Metadata { /* 数据库名 */ String DATABASE = "TABLE_CATALOG"; /* 表名 */ String TABLE = "TABLE_NAME"; /* 列名 */ String COLUMN = "COLUMN_NAME"; /* 约束名 */ String CONSTRAINT_NAME = "CONSTRAINT_NAME"; /* 约束类型 */ String CONSTRAINT_TYPE = "CONSTRAINT_TYPE"; String DATA_TYPE = "DATA_TYPE"; String CHARACTER_LENGTH = "CHARACTER_MAXIMUM_LENGTH"; String NUMERIC_PRECISION = "NUMERIC_PRECISION"; String NUMERIC_SCALE = "NUMERIC_SCALE"; } }
26.468085
61
0.495177
c17d9d8afb7b81004a6399d9cff97b2ec147205b
2,627
package it.davidenastri.clouddrive.services; import it.davidenastri.clouddrive.mapper.CredentialMapper; import it.davidenastri.clouddrive.mapper.UserMapper; import it.davidenastri.clouddrive.model.Credential; import org.apache.commons.lang3.RandomStringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; import java.util.List; @Service public class CredentialService { private final EncryptionService encryptionService; private final UserMapper userMapper; private final CredentialMapper credentialMapper; Logger logger = LoggerFactory.getLogger(CredentialService.class); public CredentialService(UserMapper userMapper, CredentialMapper credentialMapper, EncryptionService encryptionService) { this.userMapper = userMapper; this.credentialMapper = credentialMapper; this.encryptionService = encryptionService; } public int create(Credential credential, String username) { credential = encryptPassword(credential); return credentialMapper.create( new Credential(null, credential.getUrl(), credential.getUsername(), credential.getKey(), credential.getPassword(), userMapper.getUser(username).getUserId())); } public int update(Credential credential, String username) { credential = encryptPassword(credential); return credentialMapper.update( new Credential(credential.getCredentialid(), credential.getUrl(), credential.getUsername(), credential.getKey(), credential.getPassword(), userMapper.getUser(username).getUserId())); } public Credential get(int credentialid, String username) { return credentialMapper.get(credentialid, userMapper.getUser(username).getUserId()); } public List<Credential> getAll(String username) { return credentialMapper.getAll(userMapper.getUser(username).getUserId()); } public int delete(int credentialid) { return credentialMapper.delete(credentialid); } private Credential encryptPassword(Credential credential) { String key = RandomStringUtils.random(16, true, true); credential.setKey(key); credential.setPassword(encryptionService.encryptValue(credential.getPassword(), key)); return credential; } public Credential decryptPassword(Credential credential) { credential.setPassword(encryptionService.decryptValue(credential.getPassword(), credential.getKey())); return credential; } }
37.528571
125
0.721355
377d14d2d499bdc24f8641adf8548d699177a417
858
package com.tenable.io.api.scans.models; import java.util.List; /** * Copyright (c) 2017 Tenable Network Security, Inc. */ public class ScanListResult { private List<Scan> scans; private int timestamp; /** * Get the list of scans. * * @return the list of scans */ public List<Scan> getScans() { return scans; } /** * Sets the list of scans * * @param scans the list of scans */ public void setScans( List<Scan> scans ) { this.scans = scans; } /** * Gets timestamp. * * @return the timestamp */ public int getTimestamp() { return timestamp; } /** * Sets timestamp. * * @param timestamp the timestamp */ public void setTimestamp( int timestamp ) { this.timestamp = timestamp; } }
16.5
52
0.551282
7a936347ec2db50e4d0a1ab1fd8534aff33996c7
1,602
/* * 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 com.worldpay.innovation.wpwithin.types; import java.util.HashMap; /** * * @author worldpay */ public class WWDevice { // 1: string uid // 2: string name // 3: string description // 4: map<i32, Service> services // 5: string ipv4Address // 6: string currencyCode String uid; String name; String description; HashMap<Integer, WWService> services; String ipv4Address; String currencyCode; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public HashMap<Integer, WWService> getServices() { return services; } public void setServices(HashMap<Integer, WWService> services) { this.services = services; } public String getIpv4Address() { return ipv4Address; } public void setIpv4Address(String ipv4Address) { this.ipv4Address = ipv4Address; } public String getCurrencyCode() { return currencyCode; } public void setCurrencyCode(String currencyCode) { this.currencyCode = currencyCode; } }
20.025
79
0.639201
a8a48444a5fb796707e4b553a392b31d92922a5d
1,294
package com.test.springBoot.readWriteFile; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Arrays; import java.util.List; /** * @Description: 读写文件 * @Author: wangyinjia * @Date: 2020/1/6 * @Version: 1.0 */ @Slf4j @Controller @RequestMapping("rw") public class readWriteFileController { /** * 读写文件service */ @Autowired private ReadWriteFileService readWriteFileService; @GetMapping(value = "/file") public void readAndWriteFile() { String fileName = "d:\\test.txt"; List<Integer> list = Arrays.asList(1,2,3,4,5,6,7,8,9,10); String lock = "lock"; list.parallelStream().forEach(a -> { //读写原子操作 synchronized (lock){ String content = readWriteFileService.readFile(fileName); System.out.println("read:" + content); content = Integer.valueOf(content) + 1 + ""; readWriteFileService.writeFile(fileName, content); System.out.println("write:" + content); } }); } }
27.531915
73
0.644513