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
|
---|---|---|---|---|---|
44856c153098e1010ff77f02bd7b56c9b46c62dd | 339 | package org.isisaddons.module.security.fixture.demoapp.demotenantedmodule.fixturescripts.sub;
public class TenantedEntity_create_it_mil extends AbstractTenantedEntityFixtureScript {
@Override
protected void execute(ExecutionContext executionContext) {
create("Tenanted in /it/mil", "/it/mil", executionContext);
}
}
| 30.818182 | 93 | 0.784661 |
dc35cc020998bb7302dec6ac7dc3f40e6bcd9a7d | 1,538 | package com.company.project.modules.activeMQ;
import com.jeespring.common.utils.SendMailUtil;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 消息消费者.
* @author 黄炳桂 [email protected]
* @version v.0.1
* @date 2016年8月23日
*/
@Component
public class CompanyConsumer {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = CompanyProducer.ActiveMQQueueKey)
public void receiveQueue(String text) {
System.out.println(dateFormat.format(new Date()) + " | " +"ActiveMQ Consumer :"+ CompanyProducer.ActiveMQQueueKey+":收到的报文为:"+text);
}
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = CompanyProducer.ActiveMQQueueKeyA)
public void receiveQueueA(String text) {
System.out.println(dateFormat.format(new Date()) + " | " +"ActiveMQ Consumer :"+ CompanyProducer.ActiveMQQueueKeyA+":收到的报文为:"+text);
}
// 使用JmsListener配置消费者监听的队列,其中text是接收到的消息
@JmsListener(destination = CompanyProducer.ActiveMQQueueKeyB)
@SendTo("company.out.queue")
public String receiveQueueB(String text) {
System.out.println(dateFormat.format(new Date()) + " | " +"ActiveMQ Consumer :"+ CompanyProducer.ActiveMQQueueKeyA+"收到的报文为:"+text);
return "return message:"+text;
}
} | 36.619048 | 140 | 0.742523 |
1dce6fe9087182ed2eb44a0b307e6deb74367f8c | 2,332 | package com.pengsoft.ss.service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.pengsoft.ss.domain.QualityCheck;
import com.pengsoft.support.service.EntityService;
import com.pengsoft.system.domain.Asset;
/**
* The service interface of {@link QualityCheck}.
*
* @author [email protected]
* @since 1.0.0
*/
public interface QualityCheckService extends EntityService<QualityCheck, String> {
/**
* 提交
*
* @param check {@link QualityCheck}
* @param assets A collection of {@link Asset}
*/
void submit(@Valid @NotNull QualityCheck check, @NotEmpty List<Asset> assets);
/**
* 处理
*
* @param check {@link QualityCheck}
* @param result 处理结果
* @param assets A collection of {@link Asset}
*/
void handle(@NotNull QualityCheck check, @NotBlank String result, @NotEmpty List<Asset> assets);
/**
* Returns an {@link Optional} of a {@link QualityCheck}
* with the given
* code.
*
* @param code {@link QualityCheck}'s code
*/
Optional<QualityCheck> findOneByCode(@NotBlank String code);
/**
* 查询指定时间段内的工程项目的安全检查天数
*
* @param projectIds 工程项目ID列表
* @param startTime 开始时间
* @param endTime 结束时间
*/
List<Map<String, Object>> getCheckedDays(@NotEmpty List<String> projectIds, @NotNull LocalDateTime startTime,
@NotNull LocalDateTime endTime);
/**
* 查询指定时间段内的工程项目的安全检查统计数据
*
* @param projectIds 工程项目ID列表
* @param startTime 开始时间
* @param endTime 结束时间
*/
List<Map<String, Object>> statistic(@NotEmpty List<String> projectIds, @NotNull LocalDateTime startTime,
@NotNull LocalDateTime endTime);
/**
* 查询检查人指定时间段内的工程项目的安全检查统计数据
*
* @param projectIds 工程项目ID列表
* @param checkerIds 检查人ID列表
* @param startTime 开始时间
* @param endTime 结束时间
*/
List<Map<String, Object>> statisticByChecker(@NotEmpty List<String> projectIds, @NotEmpty List<String> checkerIds,
@NotNull LocalDateTime startTime, @NotNull LocalDateTime endTime);
}
| 28.096386 | 118 | 0.670669 |
ab0353c8658fd90f9547bca72d6e4f1ea31e98f2 | 2,315 | package multithread;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.concurrent.*;
/**
* Created by sun on 2017/2/7.
*/
public class ThreadPoolTest {
private static Log log = LogFactory.getLog(ThreadPoolTest.class);
public static void main(String[] args){
log.info("---测试ThreadPoolTest类---");
// ExecutorService executor = Executors.newSingleThreadExecutor(); //创建一个单线程的线程池
// ExecutorService executor = Executors.newFixedThreadPool(5); //创建一个固定大小的线程池
// ExecutorService executor = Executors.newCachedThreadPool(); //创建一个可缓存的线程池
for (int i = 0 ; i < 10; i++){
// executor.execute(new MyJob(i));
}
// executor.shutdown();
ScheduledExecutorService executor = Executors.newScheduledThreadPool(5); //创建一个定长线程池,支持定时及周期性执行任务
/*executor.schedule(new Runnable() {
@Override
public void run() {
System.out.println("延迟3秒执行");
}
}, 3000, TimeUnit.MILLISECONDS);*/
/*executor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("延迟1秒后每3秒执行一次");
}
}, 1000, 3000, TimeUnit.MILLISECONDS);*/
testThreadPool();
System.out.println("所有线程执行结束!");
}
public static void testThreadPool(){
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 1000,
TimeUnit.MICROSECONDS, new LinkedBlockingDeque<Runnable>(5));
for (int i = 0; i < 15; i++) {
executor.execute(new MyJob(i));
System.out.println("线程池中当前线程数目:" + executor.getPoolSize() +
"任务缓存队列中等待执行的任务数:" + executor.getQueue().size());
}
executor.shutdown();
}
}
/**
* 自定义一个工作任务类,实现Runnable接口
*/
class MyJob implements Runnable{
private int index;
public MyJob(int i){
index = i;
}
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " 开始执行。index = " + index);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " 执行结束。");
}
} | 32.152778 | 108 | 0.594816 |
ef858993a5d54435d89b9d102ff6f05f89c97e24 | 1,768 | package org.gurpsdomain.domain;
import static org.gurpsdomain.domain.Attribute.*;
import static org.gurpsdomain.domain.DifficultyLevel.*;
public class Spell {
private final String name;
private final int cost;
private final String pageReference;
private final DifficultyLevel difficultyLevel;
private final String colleges;
private final String powerSource;
private final String spellClasses;
private final String maintenanceCost;
private final String castingTime;
private final String duration;
public Spell(String name, int cost, String pageReference, DifficultyLevel difficultyLevel, String colleges, String powerSource, String spellClasses, String maintenanceCost, String castingTime, String duration) {
this.name = name;
this.cost = cost;
this.pageReference = pageReference;
this.difficultyLevel = difficultyLevel;
this.colleges = colleges;
this.powerSource = powerSource;
this.spellClasses = spellClasses;
this.maintenanceCost = maintenanceCost;
this.castingTime = castingTime;
this.duration = duration;
if (!(difficultyLevel.equals(HARD)) && !(difficultyLevel.equals(VERY_HARD))) {
throw new IllegalArgumentException(String.format("Unexpected difficultyLevel %s for spell %s", difficultyLevel, name));
}
}
void payCost(Points points) {
points.addSpell(cost);
}
private int delta() {
return difficultyLevel.determineDelta(cost);
}
public int level(Attributes attributes) {
Attribute controllingAttribute = INTELLIGENCE;
Attribute magery = MAGERY;
return attributes.level(controllingAttribute) + delta() + attributes.level(magery);
}
}
| 36.081633 | 215 | 0.707579 |
39cf7e88a632b6dfab147709073e082e46c4cc8c | 183 | package com.telerikacademy.agency.commands.listing;
import com.telerikacademy.agency.commands.contracts.Command;
public class ListVehiclesCommand implements Command {
// TODO
}
| 22.875 | 60 | 0.814208 |
7483eaae2fb0066cf170c72c188481188eb24402 | 463 | package de.renew.navigator.io;
/**
* @author Konstantin Simon Maria M??llers
* @version 0.1
*/
public interface ProgressListener {
/**
* Each execution informs the GUI about a new progress.
*
* @param progress the current progress.
* @param max the maximum progress.
*/
void progress(float progress, int max);
/**
* Informs the progress whether its worker got cancelled.
*/
boolean isWorkerCancelled();
} | 20.130435 | 61 | 0.643629 |
887828bcf5e0f5efb97fa43637795d17dd4c12c3 | 5,227 | /*
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openehealth.ipf.commons.ihe.xds.core.metadata;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.junit.jupiter.api.Test;
import org.openehealth.ipf.commons.ihe.xds.core.SampleData;
import org.openehealth.ipf.commons.ihe.xds.core.responses.RetrievedDocument;
import org.openehealth.ipf.commons.ihe.xds.core.responses.RetrievedDocumentSet;
import java.io.*;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.openehealth.ipf.commons.ihe.xds.core.metadata.JsonUtils.createObjectMapper;
/**
* Tests that all requests/responses and metadata classes can be serialized.
* @author Jens Riemschneider
*/
public class SerializationTest {
@Test
public void testProvideAndRegisterDocumentSet() throws Exception {
var request = SampleData.createProvideAndRegisterDocumentSet();
checkSerialization(request);
}
@Test
public void testQueryRegistry() throws Exception {
checkSerialization(SampleData.createFindDocumentsQuery());
checkSerialization(SampleData.createFindDocumentsForMultiplePatientsQuery());
checkSerialization(SampleData.createFindFoldersQuery());
checkSerialization(SampleData.createFindFoldersForMultiplePatientsQuery());
checkSerialization(SampleData.createFindSubmissionSetsQuery());
checkSerialization(SampleData.createGetAllQuery());
checkSerialization(SampleData.createGetAssociationsQuery());
checkSerialization(SampleData.createGetDocumentsAndAssociationsQuery());
checkSerialization(SampleData.createGetDocumentsQuery());
checkSerialization(SampleData.createGetFolderAndContentsQuery());
checkSerialization(SampleData.createGetFoldersForDocumentQuery());
checkSerialization(SampleData.createGetFoldersQuery());
checkSerialization(SampleData.createGetRelatedDocumentsQuery());
checkSerialization(SampleData.createGetSubmissionSetAndContentsQuery());
checkSerialization(SampleData.createGetSubmissionSetsQuery());
}
@Test
public void testRegisterDocumentSet() throws Exception {
checkSerialization(SampleData.createRegisterDocumentSet());
}
@Test
public void testRetrieveDocumentSet() throws Exception {
checkSerialization(SampleData.createRetrieveDocumentSet());
}
@Test
public void testQueryResponse() throws Exception {
checkSerialization(SampleData.createQueryResponseWithLeafClass());
checkSerialization(SampleData.createQueryResponseWithObjRef());
}
@Test
public void testRetrievedDocumentSet() throws Exception {
RetrievedDocumentSet response = SampleData.createRetrievedDocumentSet();
for (RetrievedDocument doc : response.getDocuments()) {
doc.setDataHandler(null);
}
checkSerialization(response);
}
private void checkSerialization(Object original) throws Exception {
checkJavaSerialization(original);
checkJacksonSerialization(original);
}
private void checkJavaSerialization(Object original) throws IOException, ClassNotFoundException {
var out = new ByteArrayOutputStream();
try (var oos = new ObjectOutputStream(out)) {
oos.writeObject(original);
}
var in = new ByteArrayInputStream(out.toByteArray());
try (var ois = new ObjectInputStream(in)) {
Object copy = ois.readObject();
assertSame(original.getClass(), copy.getClass());
assertEquals(original, copy);
}
}
private void checkJacksonSerialization(Object original) throws IOException {
var objectMapper = createObjectMapper();
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
var json = objectMapper.writeValueAsString(original);
var unmarshalled = objectMapper.readValue(json, original.getClass());
assertEquals(original, unmarshalled);
}
@Test
public void testNameHandling() throws Exception {
var original = new Person();
original.setName(new XpnName("Krause", "Wilhelm", "Klaus Peter", "Esq.", "Prince", "Dr.-Ing."));
var objectMapper = createObjectMapper();
var json = objectMapper.writeValueAsString(original);
Object unmarshalled = objectMapper.readValue(json, original.getClass());
assertEquals(original, unmarshalled);
}
}
| 41.816 | 105 | 0.715324 |
084b0ad33723b4e783dbee0633d067a7dff0f32c | 1,213 | /*
* Copyright 2020 Siphalor
*
* 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 de.siphalor.nbtcrafting.dollar.part.unary;
import de.siphalor.nbtcrafting.dollar.DollarEvaluationException;
import de.siphalor.nbtcrafting.dollar.part.DollarPart;
import java.util.Map;
public abstract class UnaryDollarOperator implements DollarPart {
DollarPart dollarPart;
public UnaryDollarOperator(DollarPart dollarPart) {
this.dollarPart = dollarPart;
}
@Override
public final Object evaluate(Map<String, Object> reference) throws DollarEvaluationException {
return evaluate(dollarPart.evaluate(reference));
}
public abstract Object evaluate(Object value) throws DollarEvaluationException;
}
| 31.102564 | 95 | 0.781533 |
354385be6e0df2a8fdb54a3111f7577dee2826f9 | 318 | package com.ls.framework.jdbc.annotation;
import java.lang.annotation.*;
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LSColumn {
String value() default "";
/**
* @return 标注非数据库字段
*/
boolean ignore() default false;
}
| 18.705882 | 42 | 0.663522 |
217e4b0802f3b32fe717fc73d924058aa0dd34a3 | 7,872 | package io.github.hooj0.springdata.template.repository.query.complex;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.data.repository.query.ParametersParameterAccessor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import io.github.hooj0.springdata.template.repository.query.TemplateQueryMethod;
import io.github.hooj0.springdata.template.repository.query.complex.ExpressionEvaluatingParameterBinder.BindingContext;
import io.github.hooj0.springdata.template.repository.query.complex.ExpressionEvaluatingParameterBinder.ParameterBinding;
/**
* 将字符串转换为可以查询的语句对象
*
* @createDate 2018年7月14日 下午9:11:05
* @file StringBasedQuery.java
* @package io.github.hooj0.springdata.template.repository.query.complex
* @project spring-data-template
* @blog http://hoojo.cnblogs.com
* @email [email protected]
* @version 1.0
*/
public class StringBasedQuery {
private final String query;
private final ExpressionEvaluatingParameterBinder parameterBinder;
private final List<ParameterBinding> queryParameterBindings = new ArrayList<>();
/**
* Create a new {@link StringBasedQuery} given {@code query}, {@link ExpressionEvaluatingParameterBinder} and
* {@link CodecRegistry}.
* @param query must not be empty.
* @param parameterBinder must not be {@literal null}.
*/
public StringBasedQuery(String query, ExpressionEvaluatingParameterBinder parameterBinder) {
Assert.hasText(query, "Query must not be empty");
Assert.notNull(parameterBinder, "ExpressionEvaluatingParameterBinder must not be null");
this.parameterBinder = parameterBinder;
this.query = ParameterBindingParser.INSTANCE.parseAndCollectParameterBindingsFromQueryIntoBindings(query, this.queryParameterBindings);
}
private ExpressionEvaluatingParameterBinder getParameterBinder() {
return this.parameterBinder;
}
protected String getQuery() {
return this.query;
}
/**
* 将方法和参数、及其参数值,绑定一个Statement对象
* @param parameterAccessor must not be {@literal null}.
* @param queryMethod must not be {@literal null}.
* @return the bound String query containing formatted parameters.
*/
public SimpleStatement bindQuery(ParametersParameterAccessor parameterAccessor, TemplateQueryMethod queryMethod, Object[] values) {
Assert.notNull(parameterAccessor, "ParametersParameterAccessor must not be null");
Assert.notNull(queryMethod, "TemplateQueryMethod must not be null");
List<Object> arguments = getParameterBinder().bind(parameterAccessor, new BindingContext(queryMethod, this.queryParameterBindings), values);
return ParameterBinder.INSTANCE.bind(getQuery(), arguments);
}
/**
* 从给定查询字符串中提取参数绑定的解析器。
* 将 ?_param_? 替换为 ?
*/
public static enum ParameterBinder {
INSTANCE;
private static final String ARGUMENT_PLACEHOLDER = "?_param_?";
private static final Pattern ARGUMENT_PLACEHOLDER_PATTERN = Pattern.compile(Pattern.quote(ARGUMENT_PLACEHOLDER));
public SimpleStatement bind(String input, List<Object> parameters) {
if (parameters.isEmpty()) {
return new SimpleStatement(input);
}
StringBuilder result = new StringBuilder();
int startIndex = 0;
int currentPosition = 0;
int parameterIndex = 0;
Matcher matcher = ARGUMENT_PLACEHOLDER_PATTERN.matcher(input);
while (currentPosition < input.length()) {
if (!matcher.find()) {
break;
}
int exprStart = matcher.start();
result.append(input.subSequence(startIndex, exprStart)).append("?");
parameterIndex++;
currentPosition = matcher.end();
startIndex = currentPosition;
}
String bindableStatement = result.append(input.subSequence(currentPosition, input.length())).toString();
return new SimpleStatement(bindableStatement, parameters.subList(0, parameterIndex).toArray());
}
}
/**
* 从给定查询字符串中提取参数绑定的解析器。
* 将参数或表达式替换成 ?_param_?
*/
public static enum ParameterBindingParser {
INSTANCE;
private static final char CURRLY_BRACE_OPEN = '{';
private static final char CURRLY_BRACE_CLOSE = '}';
private static final Pattern INDEX_PARAMETER_BINDING_PATTERN = Pattern.compile("\\?(\\d+)");
private static final Pattern NAMED_PARAMETER_BINDING_PATTERN = Pattern.compile("\\:(\\w+)");
private static final Pattern INDEX_BASED_EXPRESSION_PATTERN = Pattern.compile("\\?\\#\\{");
private static final Pattern NAME_BASED_EXPRESSION_PATTERN = Pattern.compile("\\:\\#\\{");
private static final String ARGUMENT_PLACEHOLDER = "?_param_?";
/**
* Returns a list of {@link ParameterBinding}s found in the given {@code input}.
* @param input can be {@literal null} or empty.
* @param bindings must not be {@literal null}.
* @return a list of {@link ParameterBinding}s found in the given {@code input}.
*/
public String parseAndCollectParameterBindingsFromQueryIntoBindings(String input, List<ParameterBinding> bindings) {
if (!StringUtils.hasText(input)) {
return input;
}
Assert.notNull(bindings, "Parameter bindings must not be null");
return transformQueryAndCollectExpressionParametersIntoBindings(input, bindings);
}
private static String transformQueryAndCollectExpressionParametersIntoBindings(String input, List<ParameterBinding> bindings) {
StringBuilder result = new StringBuilder();
int startIndex = 0;
int currentPosition = 0;
while (currentPosition < input.length()) {
Matcher matcher = findNextBindingOrExpression(input, currentPosition);
// no expression parameter found
if (matcher == null) {
break;
}
int exprStart = matcher.start();
currentPosition = exprStart;
if (matcher.pattern() == NAME_BASED_EXPRESSION_PATTERN || matcher.pattern() == INDEX_BASED_EXPRESSION_PATTERN) {
// eat parameter expression
int curlyBraceOpenCount = 1;
currentPosition += 3;
while (curlyBraceOpenCount > 0 && currentPosition < input.length()) {
switch (input.charAt(currentPosition++)) {
case CURRLY_BRACE_OPEN:
curlyBraceOpenCount++;
break;
case CURRLY_BRACE_CLOSE:
curlyBraceOpenCount--;
break;
default:
}
}
result.append(input.subSequence(startIndex, exprStart));
} else {
result.append(input.subSequence(startIndex, exprStart));
}
result.append(ARGUMENT_PLACEHOLDER);
if (matcher.pattern() == NAME_BASED_EXPRESSION_PATTERN || matcher.pattern() == INDEX_BASED_EXPRESSION_PATTERN) {
bindings.add(ExpressionEvaluatingParameterBinder.ParameterBinding.expression(input.substring(exprStart + 3, currentPosition - 1), true));
} else {
if (matcher.pattern() == INDEX_PARAMETER_BINDING_PATTERN) {
bindings.add(ExpressionEvaluatingParameterBinder.ParameterBinding.indexed(Integer.parseInt(matcher.group(1))));
} else {
bindings.add(ExpressionEvaluatingParameterBinder.ParameterBinding.named(matcher.group(1)));
}
currentPosition = matcher.end();
}
startIndex = currentPosition;
}
return result.append(input.subSequence(currentPosition, input.length())).toString();
}
@Nullable
private static Matcher findNextBindingOrExpression(String input, int position) {
List<Matcher> matchers = new ArrayList<>();
matchers.add(INDEX_PARAMETER_BINDING_PATTERN.matcher(input));
matchers.add(NAMED_PARAMETER_BINDING_PATTERN.matcher(input));
matchers.add(INDEX_BASED_EXPRESSION_PATTERN.matcher(input));
matchers.add(NAME_BASED_EXPRESSION_PATTERN.matcher(input));
TreeMap<Integer, Matcher> matcherMap = new TreeMap<>();
for (Matcher matcher : matchers) {
if (matcher.find(position)) {
matcherMap.put(matcher.start(), matcher);
}
}
return (matcherMap.isEmpty() ? null : matcherMap.values().iterator().next());
}
}
}
| 34.831858 | 142 | 0.7453 |
998c3c45aa09781fe1c1f4f3630992af83485afe | 110 | package com.kezong.demo.libaar;
public class AarFlavor {
private static final String TAG = "flavor2";
}
| 15.714286 | 48 | 0.727273 |
b050ad9be905fd980067cccaba583a11443aa2d5 | 3,777 | package org.insightcentre.uld.naisc.meas;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelFactory;
import org.apache.jena.riot.adapters.RDFReaderRIOT;
import org.insightcentre.uld.naisc.Dataset;
import org.insightcentre.uld.naisc.DatasetLoader;
import org.insightcentre.uld.naisc.main.DefaultDatasetLoader;
import org.insightcentre.uld.naisc.main.DefaultDatasetLoader.ModelDataset;
import org.insightcentre.uld.naisc.util.Option;
import org.insightcentre.uld.naisc.util.Some;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.GZIPInputStream;
/**
* The Meas loader also creates a SPARQL endpoint for the datasets
*
* @author John McCrae
*/
public class MeasDatasetLoader implements DatasetLoader<MeasDatasetLoader.MeasDataset>, AutoCloseable {
private Set<String> models = new HashSet<>();
private final String requestURL;
public MeasDatasetLoader(String requestURL) {
this.requestURL = requestURL.endsWith("/") ? requestURL : (requestURL + "/");
}
@Override
public Dataset fromFile(File file, String name) throws IOException {
final Model model = ModelFactory.createDefaultModel();
if(file.getName().endsWith(".rdf")) {
model.read(new FileReader(file), file.toURI().toString(), "RDF/XML");
} else if(file.getName().endsWith(".ttl")) {
model.read(new FileReader(file), file.toURI().toString(), "Turtle");
} else if(file.getName().endsWith(".nt")) {
model.read(new FileReader(file), file.toURI().toString(), "N-TRIPLES");
} else if(file.getName().endsWith(".rdf.gz")) {
model.read(new InputStreamReader(new GZIPInputStream(new FileInputStream(file))), file.toURI().toString(), "RDF/XML");
} else if(file.getName().endsWith(".ttl.gz")) {
model.read(new InputStreamReader(new GZIPInputStream(new FileInputStream(file))), file.toURI().toString(), "Turtle");
} else if(file.getName().endsWith(".nt.gz")) {
model.read(new InputStreamReader(new GZIPInputStream(new FileInputStream(file))), file.toURI().toString(), "N-TRIPLES");
} else {
model.read(new FileReader(file), file.toURI().toString(), "RDF/XML");
}
SPARQLEndpointServlet.registerModel(name, model);
models.add(name);
return new MeasDataset(name, model);
}
@Override
public Dataset fromEndpoint(URL endpoint) {
return new DefaultDatasetLoader.EndpointDataset(endpoint, endpoint.toString());
}
@Override
public MeasDataset combine(MeasDataset dataset1, MeasDataset dataset2, String name) {
final Model combined = ModelFactory.createDefaultModel();
final Model leftModel = dataset1.model;
final Model rightModel = dataset2.model;
combined.add(leftModel);
combined.add(rightModel);
SPARQLEndpointServlet.registerModel(name, combined);
models.add(name);
return new MeasDataset(name, combined);
}
@Override
public void close() throws IOException {
for (String model : models) {
SPARQLEndpointServlet.deregisterModel(model);
}
}
public class MeasDataset extends ModelDataset {
private final String name;
public MeasDataset(String name, Model model) {
super(model, name, null);
this.name = name;
}
@Override
public Option<URL> asEndpoint() {
try {
return new Some<>(new URL(requestURL + "sparql/" + name));
} catch (MalformedURLException ex) {
throw new RuntimeException(ex);
}
}
}
}
| 36.669903 | 132 | 0.664813 |
2ed5fb1c05647361719faaa913a465f9fbacacfa | 212 | package org.distributeme.test.blacklisting;
public class BlacklistingTestServiceImpl implements BlacklistingTestService {
@Override
public void doSomeThing(int mod) {
System.out.println("mod " + mod);
}
}
| 21.2 | 77 | 0.783019 |
fc1f918c8db3791c97010ed6bc575efd9b9ec6e3 | 2,167 | package com.ql.util.express.instruction;
import com.ql.util.express.ExpressRunner;
import com.ql.util.express.InstructionSet;
import com.ql.util.express.exception.QLException;
import com.ql.util.express.instruction.detail.InstructionLoadLambda;
import com.ql.util.express.instruction.opdata.OperateDataLocalVar;
import com.ql.util.express.parse.ExpressNode;
import java.util.Stack;
public class LambdaInstructionFactory extends InstructionFactory {
private static final String LAMBDA_NODE_NAME = "LAMBDA";
@Override
public boolean createInstruction(ExpressRunner aCompile, InstructionSet result, Stack<ForRelBreakContinue> forStack,
ExpressNode node, boolean isRoot) throws Exception {
ExpressNode[] children = node.getChildren();
if (children.length != 2) {
throw new QLException("lambda 操作符需要2个操作数");
}
InstructionSet lambdaSet = new InstructionSet(InstructionSet.TYPE_FUNCTION);
// lambda 参数列表
ExpressNode lambdaVarDefine = children[0];
if ("CHILD_EXPRESS".equals(lambdaVarDefine.getNodeType().getName())) {
// 带括号的参数写法
for (ExpressNode varDefine : lambdaVarDefine.getChildren()) {
OperateDataLocalVar tmpVar = new OperateDataLocalVar(varDefine.getValue(), null);
lambdaSet.addParameter(tmpVar);
}
} else {
// 单参数省略括号的写法
lambdaSet.addParameter(new OperateDataLocalVar(lambdaVarDefine.getValue(), null));
}
// lambda 逻辑体
ExpressNode lambdaBodyRoot = new ExpressNode(aCompile.getNodeTypeManager()
.findNodeType("FUNCTION_DEFINE"), LAMBDA_NODE_NAME);
if ("STAT_BLOCK".equals(node.getNodeType().getName())) {
for (ExpressNode tempNode : children[1].getChildren()) {
lambdaBodyRoot.addLeftChild(tempNode);
}
} else {
lambdaBodyRoot.addLeftChild(children[1]);
}
aCompile.createInstructionSet(lambdaBodyRoot, lambdaSet);
result.addInstruction(new InstructionLoadLambda(lambdaSet));
return false;
}
}
| 38.696429 | 120 | 0.672358 |
4357513f6ce6748217cd2915c6e003eedf156cb7 | 226 |
package com.mbach231.diseasecraft.DiseaseEffects;
import org.bukkit.entity.LivingEntity;
abstract public class DiseaseEffect {
DiseaseEffect(){
}
abstract public void applyEffect(LivingEntity entity);
}
| 15.066667 | 58 | 0.747788 |
a3c09ba631130445a3d7716b6a3448761b784aab | 9,254 | /*
* MIT License
*
* Copyright (c) 2010 - 2021 The OSHI Project Contributors: https://github.com/oshi/oshi/graphs/contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package oshi.software.os.unix.freebsd;
import static oshi.software.os.OSService.State.RUNNING;
import static oshi.software.os.OSService.State.STOPPED;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import oshi.annotation.concurrent.ThreadSafe;
import oshi.driver.unix.freebsd.Who;
import oshi.jna.platform.unix.freebsd.FreeBsdLibc;
import oshi.jna.platform.unix.freebsd.FreeBsdLibc.Timeval;
import oshi.software.common.AbstractOperatingSystem;
import oshi.software.os.FileSystem;
import oshi.software.os.InternetProtocolStats;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSProcess;
import oshi.software.os.OSService;
import oshi.software.os.OSSession;
import oshi.util.ExecutingCommand;
import oshi.util.ParseUtil;
import oshi.util.platform.unix.freebsd.BsdSysctlUtil;
import oshi.util.tuples.Pair;
/**
* FreeBSD is a free and open-source Unix-like operating system descended from
* the Berkeley Software Distribution (BSD), which was based on Research Unix.
* The first version of FreeBSD was released in 1993. In 2005, FreeBSD was the
* most popular open-source BSD operating system, accounting for more than
* three-quarters of all installed simply, permissively licensed BSD systems.
*/
@ThreadSafe
public class FreeBsdOperatingSystem extends AbstractOperatingSystem {
private static final Logger LOG = LoggerFactory.getLogger(FreeBsdOperatingSystem.class);
private static final long BOOTTIME = querySystemBootTime();
/*
* Package-private for use by FreeBsdOSProcess
*/
static final List<String> PS_KEYWORDS =
Collections.unmodifiableList(
Arrays.asList(
"state", "pid", "ppid", "user", "uid", "group", "gid", "nlwp", "pri",
"vsz", "rss", "etimes", "systime", "time", "comm", "majflt", "minflt",
"nvcsw", "nivcsw", "args"));
static final String PS_KEYWORD_ARGS = String.join(",", PS_KEYWORDS);
@Override
public String queryManufacturer() {
return "Unix/BSD";
}
@Override
public Pair<String, OSVersionInfo> queryFamilyVersionInfo() {
String family = BsdSysctlUtil.sysctl("kern.ostype", "FreeBSD");
String version = BsdSysctlUtil.sysctl("kern.osrelease", "");
String versionInfo = BsdSysctlUtil.sysctl("kern.version", "");
String buildNumber = versionInfo.split(":")[0].replace(family, "").replace(version, "").trim();
return new Pair<>(family, new OSVersionInfo(version, null, buildNumber));
}
@Override
protected int queryBitness(int jvmBitness) {
if (jvmBitness < 64 && ExecutingCommand.getFirstAnswer("uname -m").indexOf("64") == -1) {
return jvmBitness;
}
return 64;
}
@Override
public FileSystem getFileSystem() {
return new FreeBsdFileSystem();
}
@Override
public InternetProtocolStats getInternetProtocolStats() {
return new FreeBsdInternetProtocolStats();
}
@Override
public List<OSSession> getSessions() {
return USE_WHO_COMMAND ? super.getSessions() : Who.queryUtxent();
}
@Override
public List<OSProcess> queryAllProcesses() {
return getProcessListFromPS(-1);
}
@Override
public List<OSProcess> queryChildProcesses(int parentPid) {
List<OSProcess> allProcs = queryAllProcesses();
Set<Integer> descendantPids = getChildrenOrDescendants(allProcs, parentPid, false);
return allProcs.stream().filter(p -> descendantPids.contains(p.getProcessID())).collect(Collectors.toList());
}
@Override
public List<OSProcess> queryDescendantProcesses(int parentPid) {
List<OSProcess> allProcs = queryAllProcesses();
Set<Integer> descendantPids = getChildrenOrDescendants(allProcs, parentPid, true);
return allProcs.stream().filter(p -> descendantPids.contains(p.getProcessID())).collect(Collectors.toList());
}
@Override
public OSProcess getProcess(int pid) {
List<OSProcess> procs = getProcessListFromPS(pid);
if (procs.isEmpty()) {
return null;
}
return procs.get(0);
}
private static List<OSProcess> getProcessListFromPS(int pid) {
List<OSProcess> procs = new ArrayList<>();
String psCommand = "ps -awwxo " + PS_KEYWORD_ARGS;
if (pid >= 0) {
psCommand += " -p " + pid;
}
List<String> procList = ExecutingCommand.runNative(psCommand);
if (procList.isEmpty() || procList.size() < 2) {
return procs;
}
// remove header row
procList.remove(0);
// Fill list
for (String proc : procList) {
String[] split = ParseUtil.whitespaces.split(proc.trim(), PS_KEYWORDS.size());
// Elements should match ps command order
if (split.length == PS_KEYWORDS.size()) {
procs.add(new FreeBsdOSProcess(pid < 0 ? ParseUtil.parseIntOrDefault(split[1], 0) : pid, split));
}
}
return procs;
}
@Override
public int getProcessId() {
return FreeBsdLibc.INSTANCE.getpid();
}
@Override
public int getProcessCount() {
List<String> procList = ExecutingCommand.runNative("ps -axo pid");
if (!procList.isEmpty()) {
// Subtract 1 for header
return procList.size() - 1;
}
return 0;
}
@Override
public int getThreadCount() {
int threads = 0;
for (String proc : ExecutingCommand.runNative("ps -axo nlwp")) {
threads += ParseUtil.parseIntOrDefault(proc.trim(), 0);
}
return threads;
}
@Override
public long getSystemUptime() {
return System.currentTimeMillis() / 1000 - BOOTTIME;
}
@Override
public long getSystemBootTime() {
return BOOTTIME;
}
private static long querySystemBootTime() {
Timeval tv = new Timeval();
if (!BsdSysctlUtil.sysctl("kern.boottime", tv) || tv.tv_sec == 0) {
// Usually this works. If it doesn't, fall back to text parsing.
// Boot time will be the first consecutive string of digits.
return ParseUtil.parseLongOrDefault(
ExecutingCommand.getFirstAnswer("sysctl -n kern.boottime").split(",")[0].replaceAll("\\D", ""),
System.currentTimeMillis() / 1000);
}
// tv now points to a 128-bit timeval structure for boot time.
// First 8 bytes are seconds, second 8 bytes are microseconds (we ignore)
return tv.tv_sec;
}
@Override
public NetworkParams getNetworkParams() {
return new FreeBsdNetworkParams();
}
@Override
public OSService[] getServices() {
// Get running services
List<OSService> services = new ArrayList<>();
Set<String> running = new HashSet<>();
for (OSProcess p : getChildProcesses(1, ProcessFiltering.ALL_PROCESSES, ProcessSorting.PID_ASC, 0)) {
OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING);
services.add(s);
running.add(p.getName());
}
// Get Directories for stopped services
File dir = new File("/etc/rc.d");
File[] listFiles;
if (dir.exists() && dir.isDirectory() && (listFiles = dir.listFiles()) != null) {
for (File f : listFiles) {
String name = f.getName();
if (!running.contains(name)) {
OSService s = new OSService(name, 0, STOPPED);
services.add(s);
}
}
} else {
LOG.error("Directory: /etc/init does not exist");
}
return services.toArray(new OSService[0]);
}
}
| 36.577075 | 117 | 0.650746 |
bd33bd2affdee742d009b4ab0b2adfd99c355d7f | 9,353 | package org.codenarc.rule;
import org.codehaus.groovy.ast.*;
import org.codehaus.groovy.ast.expr.*;
import org.codehaus.groovy.ast.stmt.*;
import org.codehaus.groovy.classgen.BytecodeExpression;
import java.util.List;
/**
* This is a horrible hack needed because method dispatch is broken in Groovy 1.8.
* When they fix the defect then we can remove this class.
*/
@SuppressWarnings("PMD.UselessOverridingMethod")
public abstract class ClassCodeVisitorSupportHack extends ClassCodeVisitorSupport {
@Override
public void visitClass(ClassNode node) {
super.visitClass(node);
}
@Override
protected void visitObjectInitializerStatements(ClassNode node) {
super.visitObjectInitializerStatements(node);
}
@Override
public void visitPackage(PackageNode node) {
super.visitPackage(node);
}
@Override
public void visitImports(ModuleNode node) {
super.visitImports(node);
}
@Override
public void visitAnnotations(AnnotatedNode node) {
super.visitAnnotations(node);
}
@Override
protected void visitClassCodeContainer(Statement code) {
super.visitClassCodeContainer(code);
}
@Override
public void visitDeclarationExpression(DeclarationExpression expression) {
super.visitDeclarationExpression(expression);
}
@Override
protected void visitConstructorOrMethod(MethodNode node, boolean isConstructor) {
super.visitConstructorOrMethod(node, isConstructor);
}
@Override
public void visitConstructor(ConstructorNode node) {
super.visitConstructor(node);
}
@Override
public void visitMethod(MethodNode node) {
super.visitMethod(node);
}
@Override
public void visitField(FieldNode node) {
super.visitField(node);
}
@Override
public void visitProperty(PropertyNode node) {
super.visitProperty(node);
}
@Override
protected void addError(String msg, ASTNode expr) {
super.addError(msg, expr);
}
@Override
protected void visitStatement(Statement statement) {
super.visitStatement(statement);
}
@Override
public void visitAssertStatement(AssertStatement statement) {
super.visitAssertStatement(statement);
}
@Override
public void visitBlockStatement(BlockStatement block) {
super.visitBlockStatement(block);
}
@Override
public void visitBreakStatement(BreakStatement statement) {
super.visitBreakStatement(statement);
}
@Override
public void visitCaseStatement(CaseStatement statement) {
super.visitCaseStatement(statement);
}
@Override
public void visitCatchStatement(CatchStatement statement) {
super.visitCatchStatement(statement);
}
@Override
public void visitContinueStatement(ContinueStatement statement) {
super.visitContinueStatement(statement);
}
@Override
public void visitDoWhileLoop(DoWhileStatement loop) {
super.visitDoWhileLoop(loop);
}
@Override
public void visitExpressionStatement(ExpressionStatement statement) {
super.visitExpressionStatement(statement);
}
@Override
public void visitForLoop(ForStatement forLoop) {
super.visitForLoop(forLoop);
}
@Override
public void visitIfElse(IfStatement ifElse) {
super.visitIfElse(ifElse);
}
@Override
public void visitReturnStatement(ReturnStatement statement) {
super.visitReturnStatement(statement);
}
@Override
public void visitSwitch(SwitchStatement statement) {
super.visitSwitch(statement);
}
@Override
public void visitSynchronizedStatement(SynchronizedStatement statement) {
super.visitSynchronizedStatement(statement);
}
@Override
public void visitThrowStatement(ThrowStatement statement) {
super.visitThrowStatement(statement);
}
@Override
public void visitTryCatchFinally(TryCatchStatement statement) {
super.visitTryCatchFinally(statement);
}
@Override
public void visitWhileLoop(WhileStatement loop) {
super.visitWhileLoop(loop);
}
@Override
protected void visitEmptyStatement(EmptyStatement statement) {
super.visitEmptyStatement(statement);
}
@Override
public void visitMethodCallExpression(MethodCallExpression call) {
super.visitMethodCallExpression(call);
}
@Override
public void visitStaticMethodCallExpression(StaticMethodCallExpression call) {
super.visitStaticMethodCallExpression(call);
}
@Override
public void visitConstructorCallExpression(ConstructorCallExpression call) {
super.visitConstructorCallExpression(call);
}
@Override
public void visitBinaryExpression(BinaryExpression expression) {
super.visitBinaryExpression(expression);
}
@Override
public void visitTernaryExpression(TernaryExpression expression) {
super.visitTernaryExpression(expression);
}
@Override
public void visitShortTernaryExpression(ElvisOperatorExpression expression) {
super.visitShortTernaryExpression(expression);
}
@Override
public void visitPostfixExpression(PostfixExpression expression) {
super.visitPostfixExpression(expression);
}
@Override
public void visitPrefixExpression(PrefixExpression expression) {
super.visitPrefixExpression(expression);
}
@Override
public void visitBooleanExpression(BooleanExpression expression) {
super.visitBooleanExpression(expression);
}
@Override
public void visitNotExpression(NotExpression expression) {
super.visitNotExpression(expression);
}
@Override
public void visitClosureExpression(ClosureExpression expression) {
super.visitClosureExpression(expression);
}
@Override
public void visitTupleExpression(TupleExpression expression) {
super.visitTupleExpression(expression);
}
@Override
public void visitListExpression(ListExpression expression) {
super.visitListExpression(expression);
}
@Override
public void visitArrayExpression(ArrayExpression expression) {
super.visitArrayExpression(expression);
}
@Override
public void visitMapExpression(MapExpression expression) {
super.visitMapExpression(expression);
}
@Override
public void visitMapEntryExpression(MapEntryExpression expression) {
super.visitMapEntryExpression(expression);
}
@Override
public void visitRangeExpression(RangeExpression expression) {
super.visitRangeExpression(expression);
}
@Override
public void visitSpreadExpression(SpreadExpression expression) {
super.visitSpreadExpression(expression);
}
@Override
public void visitSpreadMapExpression(SpreadMapExpression expression) {
super.visitSpreadMapExpression(expression);
}
@Override
public void visitMethodPointerExpression(MethodPointerExpression expression) {
super.visitMethodPointerExpression(expression);
}
@Override
public void visitUnaryMinusExpression(UnaryMinusExpression expression) {
super.visitUnaryMinusExpression(expression);
}
@Override
public void visitUnaryPlusExpression(UnaryPlusExpression expression) {
super.visitUnaryPlusExpression(expression);
}
@Override
public void visitBitwiseNegationExpression(BitwiseNegationExpression expression) {
super.visitBitwiseNegationExpression(expression);
}
@Override
public void visitCastExpression(CastExpression expression) {
super.visitCastExpression(expression);
}
@Override
public void visitConstantExpression(ConstantExpression expression) {
super.visitConstantExpression(expression);
}
@Override
public void visitClassExpression(ClassExpression expression) {
super.visitClassExpression(expression);
}
@Override
public void visitVariableExpression(VariableExpression expression) {
super.visitVariableExpression(expression);
}
@Override
public void visitPropertyExpression(PropertyExpression expression) {
super.visitPropertyExpression(expression);
}
@Override
public void visitAttributeExpression(AttributeExpression expression) {
super.visitAttributeExpression(expression);
}
@Override
public void visitFieldExpression(FieldExpression expression) {
super.visitFieldExpression(expression);
}
@Override
public void visitGStringExpression(GStringExpression expression) {
super.visitGStringExpression(expression);
}
@Override
protected void visitListOfExpressions(List<? extends Expression> list) {
super.visitListOfExpressions(list);
}
@Override
public void visitArgumentlistExpression(ArgumentListExpression ale) {
super.visitArgumentlistExpression(ale);
}
@Override
public void visitClosureListExpression(ClosureListExpression cle) {
super.visitClosureListExpression(cle);
}
@Override
public void visitBytecodeExpression(BytecodeExpression cle) {
super.visitBytecodeExpression(cle);
}
}
| 26.876437 | 86 | 0.718807 |
34bffc853b7702e8a3c88848b1cf9160c50cb384 | 322 | package cn.dmego.seata.at.business.serivce;
import cn.dmego.seata.common.dto.BusinessDTO;
/**
* @className: BusinessService
*
* @description: BusinessService
* @author: ZengKai<[email protected]>
* @date: 2020/12/8 17:41
**/
public interface BusinessService {
String handleBusiness(BusinessDTO businessDTO);
}
| 20.125 | 51 | 0.73913 |
22358af017da00ae06e9737cda352cf700d3788a | 14,536 |
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;
public class ClientUsers extends javax.swing.JFrame {
private DataOutputStream giden;
private DataInputStream gelen;
private String UserName;
private String UserCode; // Kullanıcıya has olan bir rastgele sayı
private Vector kullanicilar = new Vector(); // Konuşulan pencereleri tutan vektör
ClientMsjBekle nobetci; // Client tarafının mesaj bekleyen nöbetçisi, tellalı, threadi
String[] userCodes = new String[0];
String[] userNames = new String[0];
public ClientUsers(DataOutputStream os, DataInputStream is, String unamesi, String uCodu) { //os=OutputStream, is=InputStream
try {
UserName = unamesi; // oluşturma zamanında kullanıcı adını al
gelen = is; // InputStreami al
giden = os; // Output Streami al
giden.flush();
UserCode = uCodu;
initComponents(); // Komponentleri kur
setVisible(true); // Görünür yap
new Thread(new ClientMsjBekle(this, jList1, userCodes, userNames, is, UserName, UserCode)).start(); //Mesaj bekleyen threadi çalıştır
new Thread(new ClientListeYenileyici(this)).start();
//giden.writeUTF("<KullaniciListesi>"); // Serverden kullanıcı listesini iste
jLabel1.setText(unamesi); // Labele kulanıcı adını yaz
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jScrollPane1 = new javax.swing.JScrollPane();
jList1 = new javax.swing.JList();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Qostebek");
setLocationByPlatform(true);
setResizable(false);
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosed(java.awt.event.WindowEvent evt) {
formWindowClosed(evt);
}
public void windowClosing(java.awt.event.WindowEvent evt) {
formWindowClosing(evt);
}
});
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));
jList1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jList1MouseClicked(evt);
}
});
jList1.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jList1ValueChanged(evt);
}
});
jList1.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
jList1FocusGained(evt);
}
});
jList1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
jList1KeyReleased(evt);
}
});
jScrollPane1.setViewportView(jList1);
jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/connect.png"))); // NOI18N
jLabel2.setToolTipText("Bağlı");
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/qost.png"))); // NOI18N
jLabel1.setText("jLabel1");
jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/user.png"))); // NOI18N
jLabel4.setText("Kullanıcı bağlı");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 248, Short.MAX_VALUE)
.addComponent(jLabel1)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 150, Short.MAX_VALUE)
.addComponent(jLabel2)))
.addContainerGap())
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 235, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
public synchronized void updateUserList() {
boolean kont = true;
String okunan;
try {
//nobetci.wait();
giden.writeUTF("<KullaniciListesi>");
System.out.println("-Liste istendi");
DefaultListModel userList = new DefaultListModel();
while (kont) {
System.out.println("Bişey beklenior..");
okunan = gelen.readUTF();
System.out.println("bişey geldi..");
if (okunan.equals("</KullaniciListesi>")) {
System.out.println("Liste Bitti..");
okunan = "";
jList1.setModel(userList);
kont = false;
break;
} else {
userList.addElement(okunan);
System.out.println("-alındı");
}
}
//nobetci.interrupt();
System.out.println("-Liste Güncellendi.");
} catch (Exception e) {
e.printStackTrace();
}
}
**/
public synchronized int getUserIndex(String uCode) {// Kodu kontrol eden
// Vektörden kullanıcı adına göre indexi getiren metod
int uIndex = -1;
ClientChat uO;
for (int i = 0; i < kullanicilar.size(); i++) {
uO = (ClientChat) kullanicilar.elementAt(i);
if (uO.getUserCode().equals(uCode)) {
uIndex = i;
break;
}
}
return uIndex;
}
public synchronized int konusuyorMu(String uName) {// ismi kontrol eden
// Vektörden kullanıcı adına göre indexi getiren metod
int uIndex = -1;
ClientChat uO;
for (int i = 0; i < kullanicilar.size(); i++) {
uO = (ClientChat) kullanicilar.elementAt(i);
if (uO.getUserName().equals(uName)) {
uIndex = i;
break;
}
}
return uIndex;
}
public synchronized String getUserNameByCode(String uCode) {
System.out.println("KODA GÖRE İSMİ GETİR");
String name = "";
String deneyTupu;
System.out.println("Kulllanıcı sayısı : : : " + userCodes.length);
for (int i = 0; i < userCodes.length; i++) {
System.out.println("DDÖNGÜYE GİRDİİİİİİİİİİİİİ");
deneyTupu = userCodes[i];
System.out.println("deneyTupune alındı : " + deneyTupu);
if (!deneyTupu.equals(null) && deneyTupu.equals(uCode)) {
name = userNames[i];
System.out.println("kullllanaıcı adıııııı bulunduuuuuuuuuu");
return name;
}
System.out.println("BU DEĞİLLLLLLLL : " + name);
}
System.out.println("bittttiiiii bu k araaaadddddrrrd");
return name;
}
public synchronized void mesajYonlendir(String gondCode, String mesaj) {
//Gelen mesajı buradaki (vektörde tutlan) pencereye yönlendiren metod
//System.out.println("YÖNLENDİRİLİYOOOOOOOOOOOOOOORRRRRRRR");
ClientChat cc;
String gondName;
int uID = getUserIndex(gondCode);
System.out.println("Mesaj Yönlendiriliyorrrrrrrrrrrrrrrrrrrrrrrrr...................");
gondName = getUserNameByCode(gondCode);
System.out.println("gonderen Adı : " + gondName);
if (uID == -1) {
cc = new ClientChat(this, UserName, UserCode, gondName, gondCode);// ... ,alici_isim,kod);
kullanicilar.add(cc);
cc.setTitle("Konuşma : " + gondName);
} else {
cc = (ClientChat) kullanicilar.elementAt(uID);
}
cc.mesajAl(mesaj);
}
public void mesajYolla(String msj, String aliciCode) {
// Pencerelerden mesaj yollama isteği geldiğinde akışa bırak.
try {
giden.writeUTF("<msg:" + UserCode + ":" + aliciCode + ">" + msj + "</msg>");
giden.flush();
} catch (Exception e) {
}
}
public void setUserCodeList(String[] uCL) {
userCodes = uCL;
}
public void setUserNameList(String[] uN) {
userNames = uN;
}
public synchronized void konusmaBaslat() {
//<msg:23456781968529685:57689624186933>MESAJ</msg>
if (jList1.getSelectedIndex() > -1) {
ClientChat cc;
String kiminle = (String) jList1.getSelectedValue();
int kontrol = konusuyorMu(kiminle);
//System.out.println("Kontrol : : : : . : : . : .: " + kontrol);
if (kontrol == -1) {
int kimIndex = jList1.getSelectedIndex();
cc = new ClientChat(this, UserName, UserCode, kiminle, userCodes[kimIndex]);
kullanicilar.add(cc);
cc.setTitle("Konuşma :" + kiminle);
} else {
kontrol = konusuyorMu(kiminle);
cc = (ClientChat) kullanicilar.elementAt(kontrol);
}
cc.setVisible(true);
}
}
private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
// TODO add your handling code here:
try {
giden.writeUTF("<Disconnect>");
giden.flush();
} catch (Exception e) {
e.printStackTrace();
}
}//GEN-LAST:event_formWindowClosing
public void refreshListe() {
try {
jList1.removeAll();
giden.writeUTF("<KullaniciListesi>");
giden.flush();
} catch (Exception e) {
}
}
public void kullaniciSay() {
jLabel4.setText((jList1.getLastVisibleIndex() + 2) + " kullanıcı bağlı");
}
private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
// TODO add your handling code here:
try {
giden.writeUTF("<Disconnect>");
giden.flush();
} catch (Exception e) {
}
}//GEN-LAST:event_formWindowClosed
private void jList1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jList1FocusGained
// TODO add your handling code here:
//updateUserList();
}//GEN-LAST:event_jList1FocusGained
long ilkT = 0;
private void jList1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jList1MouseClicked
// TODO add your handling code here:
long sonT;
sonT = System.currentTimeMillis();
if ((sonT - ilkT) < 1000) {
konusmaBaslat();
}
ilkT = sonT;
}//GEN-LAST:event_jList1MouseClicked
private void jList1ValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jList1ValueChanged
// TODO add your handling code here:
}//GEN-LAST:event_jList1ValueChanged
private void jList1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jList1KeyReleased
// TODO add your handling code here:
if (jList1.getSelectedIndex() > -1 && evt.getKeyCode() == 10) {
konusmaBaslat();
}
}//GEN-LAST:event_jList1KeyReleased
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JList jList1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| 40.946479 | 156 | 0.622179 |
20717ac04c61006cf025917a15c16707fc1701cd | 6,823 | package org.aion.avm.core.persistence;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.List;
import i.IObjectDeserializer;
import i.RuntimeAssertionError;
public class ByteBufferObjectDeserializer implements IObjectDeserializer {
private final ByteBuffer buffer;
private final SortedFieldCache cache;
private final IGlobalResolver resolver;
private final IPersistenceNameMapper classNameMapper;
// Note that this will be null if this is our pre-pass where we are merely walking through the buffer to find the instance types.
private final List<Object> instanceList;
public ByteBufferObjectDeserializer(ByteBuffer buffer, List<Object> instanceList, SortedFieldCache cache, IGlobalResolver resolver, IPersistenceNameMapper classNameMapper) {
this.buffer = buffer;
this.cache = cache;
this.resolver = resolver;
this.classNameMapper = classNameMapper;
this.instanceList = instanceList;
}
@Override
public boolean readBoolean() {
return ((byte)0x1 == this.buffer.get());
}
@Override
public byte readByte() {
return this.buffer.get();
}
@Override
public short readShort() {
return this.buffer.getShort();
}
@Override
public char readChar() {
return this.buffer.getChar();
}
@Override
public int readInt() {
return this.buffer.getInt();
}
@Override
public float readFloat() {
return Float.intBitsToFloat(this.buffer.getInt());
}
@Override
public long readLong() {
return this.buffer.getLong();
}
@Override
public double readDouble() {
return Double.longBitsToDouble(this.buffer.getLong());
}
@Override
public void readByteArray(byte[] result) {
this.buffer.get(result);
}
@Override
public Object readObject() {
// NOTE: If the instance list is null, this is a pre-pass, meaning we shouldn't try to create/resolve the objects, since we will do this again.
byte refType = this.buffer.get();
Object result = null;
switch (refType) {
case ReferenceConstants.REF_NULL: {
result = null;
break;
}
case ReferenceConstants.REF_CLASS: {
String internalClassName = internalReadClassName();
result = (null != this.instanceList)
? this.resolver.getClassObjectForInternalName(internalClassName)
: null;
break;
}
case ReferenceConstants.REF_CONSTANT: {
int constantIdentifier = this.buffer.getInt();
result = (null != this.instanceList)
? this.resolver.getConstantForIdentifier(constantIdentifier)
: null;
break;
}
case ReferenceConstants.REF_NORMAL: {
int instanceIndex = this.buffer.getInt();
result = (null != this.instanceList)
? this.instanceList.get(instanceIndex)
: null;
break;
}
default:
throw RuntimeAssertionError.unreachable("Unknown byte");
}
return result;
}
@Override
public String readClassName() {
return internalReadClassName();
}
@Override
public void automaticallyDeserializeFromRoot(Class<?> rootClass, Object instance) {
// This is called after any rootClass instance variables have been deserialized.
// So, we just need to deserialize all the fields defined by other classes, excluding the root class.
// This means, we need to recursively walk to the root.
internalDeserializeFieldsFromRoot(rootClass, instance.getClass(), instance);
}
private void internalDeserializeFieldsFromRoot(Class<?> rootClass, Class<?> thisClass, Object instance) {
if (rootClass != thisClass) {
// We can deserialize this one, but first see if we need to call a superclass.
internalDeserializeFieldsFromRoot(rootClass, thisClass.getSuperclass(), instance);
// Now, serialize the fields in this level.
try {
Field[] fields = this.cache.getInstanceFields(thisClass);
for (Field field : fields) {
// We need to crack the type, here.
Class<?> type = field.getType();
if (boolean.class == type) {
boolean val = this.readBoolean();
field.setBoolean(instance, val);
} else if (byte.class == type) {
byte val = this.readByte();
field.setByte(instance, val);
} else if (short.class == type) {
short val = this.readShort();
field.setShort(instance, val);
} else if (char.class == type) {
char val = this.readChar();
field.setChar(instance, val);
} else if (int.class == type) {
int val = this.readInt();
field.setInt(instance, val);
} else if (float.class == type) {
float val = this.readFloat();
field.setFloat(instance, val);
} else if (long.class == type) {
long val = this.readLong();
field.setLong(instance, val);
} else if (double.class == type) {
double val = this.readDouble();
field.setDouble(instance, val);
} else {
// Object types require further logic.
Object val = this.readObject();
field.set(instance, val);
}
}
} catch (IllegalAccessException e) {
// Reflection errors can't happen since we set this up so we could access it.
throw RuntimeAssertionError.unexpected(e);
}
}
}
private String internalReadClassName() {
// We limit class names to 255 UTF-8 bytes so read the length byte.
int length = (0xff & this.buffer.get());
RuntimeAssertionError.assertTrue(length > 0);
byte[] utf8 = new byte[length];
this.buffer.get(utf8);
String storageClassName = new String(utf8, StandardCharsets.UTF_8);
return this.classNameMapper.getInternalClassName(storageClassName);
}
}
| 37.284153 | 177 | 0.564268 |
1178755dd08d481d836ab638b758859d288d4a9d | 4,708 | package org.robolectric.shadows;
import android.R;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.Transformation;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.TestRunners;
import org.robolectric.util.TestAnimationListener;
import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.Robolectric.shadowOf;
@RunWith(TestRunners.WithDefaults.class)
public class AnimationTest {
private TestAnimation animation;
private ShadowAnimation shadow;
private TestAnimationListener listener;
@Before
public void setUp() throws Exception {
animation = new TestAnimation();
shadow = shadowOf(animation);
listener = new TestAnimationListener();
animation.setAnimationListener(listener);
}
@Test
public void startShouldInvokeStartCallback() throws Exception {
assertThat(listener.wasStartCalled).isFalse();
animation.start();
assertThat(listener.wasStartCalled).isTrue();
assertThat(listener.wasEndCalled).isFalse();
assertThat(listener.wasRepeatCalled).isFalse();
}
@Test
public void cancelShouldInvokeEndCallback() throws Exception {
assertThat(listener.wasEndCalled).isFalse();
animation.cancel();
assertThat(listener.wasStartCalled).isFalse();
assertThat(listener.wasEndCalled).isTrue();
assertThat(listener.wasRepeatCalled).isFalse();
}
@Test
public void invokeRepeatShouldInvokeRepeatCallback() throws Exception {
assertThat(listener.wasRepeatCalled).isFalse();
shadow.invokeRepeat();
assertThat(listener.wasStartCalled).isFalse();
assertThat(listener.wasEndCalled).isFalse();
assertThat(listener.wasRepeatCalled).isTrue();
}
@Test
public void invokeEndShouldInvokeEndCallback() throws Exception {
assertThat(listener.wasEndCalled).isFalse();
shadow.invokeEnd();
assertThat(listener.wasStartCalled).isFalse();
assertThat(listener.wasEndCalled).isTrue();
assertThat(listener.wasRepeatCalled).isFalse();
}
@Test
public void invokeEnd_endsTheAnimation() throws Exception {
shadow.invokeEnd();
assertThat(animation.hasEnded()).isTrue();
}
@Test
public void cancel_endsTheAnimation() throws Exception {
animation.cancel();
assertThat(animation.hasEnded()).isTrue();
}
@Test
public void simulateAnimationEndShouldInvokeApplyTransformationWith1() throws Exception {
assertThat(animation.interpolatedTime).isEqualTo(0f);
shadow.invokeEnd();
assertThat(animation.interpolatedTime).isEqualTo(1f);
}
@Test
public void testHasStarted() throws Exception {
assertThat(animation.hasStarted()).isFalse();
animation.start();
assertThat(animation.hasStarted()).isTrue();
animation.cancel();
assertThat(animation.hasStarted()).isFalse();
}
@Test
public void testDuration() throws Exception {
assertThat(animation.getDuration()).isNotEqualTo(1000l);
animation.setDuration(1000);
assertThat(animation.getDuration()).isEqualTo(1000l);
}
@Test
public void testInterpolation() throws Exception {
assertThat(animation.getInterpolator()).isNull();
LinearInterpolator i = new LinearInterpolator();
animation.setInterpolator(i);
assertThat((LinearInterpolator) animation.getInterpolator()).isSameAs(i);
}
@Test
public void testRepeatCount() throws Exception {
assertThat(animation.getRepeatCount()).isNotEqualTo(5);
animation.setRepeatCount(5);
assertThat(animation.getRepeatCount()).isEqualTo(5);
}
@Test
public void testRepeatMode() throws Exception {
assertThat(animation.getRepeatMode()).isNotEqualTo(Animation.REVERSE);
animation.setRepeatMode(Animation.REVERSE);
assertThat(animation.getRepeatMode()).isEqualTo(Animation.REVERSE);
}
@Test
public void testStartOffset() throws Exception {
assertThat(animation.getStartOffset()).isNotEqualTo(500l);
animation.setStartOffset(500l);
assertThat(animation.getStartOffset()).isEqualTo(500l);
}
@Test(expected=IllegalStateException.class)
public void testNotLoadedFromResourceId() throws Exception {
shadow.getLoadedFromResourceId();
}
@Test
public void testLoadedFromResourceId() throws Exception {
shadow.setLoadedFromResourceId(R.anim.fade_in);
assertThat(shadow.getLoadedFromResourceId()).isEqualTo(R.anim.fade_in);
}
private class TestAnimation extends Animation {
float interpolatedTime;
Transformation t;
@Override protected void applyTransformation(float interpolatedTime, Transformation t) {
this.interpolatedTime = interpolatedTime;
this.t = t;
}
}
}
| 30.973684 | 92 | 0.75446 |
ddd9010d49ac7b679cf100335b2a9d20d5994f58 | 4,543 | package com.asw.alllistapp;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toolbar;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
Button empButton;
private ListView listView;
private TextView headerText;
private Toolbar toolbar;
private PackageManager packageManager;
private ArrayAdapter<ApplicationInfo> adapter;
private ArrayList<ApplicationInfo> applicationInfos;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
packageManager = getPackageManager();
applicationInfos = new ArrayList<>();
//find View by id
listView = (ListView) findViewById(R.id.list_view);
//show progress dialog
progressDialog = ProgressDialog.show(this, "Loading All Apps", "Loading application info...");
//set list view adapter
LayoutInflater inflater = getLayoutInflater();
View header = inflater.inflate(R.layout.layout_lv_header, listView, false);
headerText = (TextView) header.findViewById(R.id.text_header);
listView.addHeaderView(header, null, false);
//initializing and set adapter for listview
adapter = new ApplicationAdapter(this, R.layout.item_listview, applicationInfos);
listView.setAdapter(adapter);
/*empButton = findViewById(R.id.emp);
empButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.asw.webadminapplication");
if (launchIntent != null) {
startActivity(launchIntent);
} else {
Toast.makeText(MainActivity.this, "There is no package available in android", Toast.LENGTH_LONG).show();
}
}
});*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setOnQueryTextListener(onQueryTextListener()); // text changed listener
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
private SearchView.OnQueryTextListener onQueryTextListener() {
return new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
//filter adapter and update ListView
adapter.getFilter().filter(s);
return false;
}
};
}
@Override
protected void onStart() {
super.onStart();
//invoke asynctask
new GetAllAppsTask(this, applicationInfos, packageManager).execute();
}
public void callBackDataFromAsynctask(List<ApplicationInfo> list) {
applicationInfos.clear();
for (int i = 0; i < list.size(); i++) {
applicationInfos.add(list.get(i));
}
headerText.setText("All Apps (" + applicationInfos.size() + ")");
adapter.notifyDataSetChanged();
progressDialog.dismiss();
}
public void updateUILayout(String content) {
headerText.setText(content);
}
}
| 34.157895 | 125 | 0.654634 |
e03e61f52b9e15b66104e66ad11d9dd142e0611c | 1,017 | package cn.savory.esmanage.convertor;
import java.util.List;
import cn.savory.esmanage.contract.request.AliasCreateRequest;
import cn.savory.esmanage.contract.request.AliasUpdateRequest;
import cn.savory.esmanage.contract.vo.AliasBasicVo;
import cn.savory.esmanage.contract.vo.AliasExtendedVo;
import cn.savory.esmanage.repository.entity.AliasEntity;
public interface IAliasConvertor {
/**
* request => entity
*/
AliasEntity toEntity(AliasCreateRequest request);
/**
* request => entity
*/
AliasEntity toEntity(AliasUpdateRequest request);
/**
* entity => basicVo
*/
AliasBasicVo toBasicVo(AliasEntity entity);
/**
* entityList => basicVoList
*/
List<AliasBasicVo> toBasicVoList(List<AliasEntity> entityList);
/**
* entity => extendedVo
*/
AliasExtendedVo toExtendedVo(AliasEntity entity);
/**
* entityList => extendedVoList
*/
List<AliasExtendedVo> toExtendedVoList(List<AliasEntity> entityList);
}
| 23.651163 | 73 | 0.702065 |
4357ac8ba0641928f3586b586a26cfc424e645cc | 489 | package com.hr.framework.repo;
import com.hr.framework.po.business.crm.meeting.Rooms;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import java.util.List;
@RepositoryRestResource(collectionResourceRel = "meetingRoom" , path = "meetingRoom")
public interface CRMMeetingRoomRepository extends PagingAndSortingRepository<Rooms,Long>{
List<Rooms> findById(Long id);
}
| 32.6 | 90 | 0.803681 |
0fe26d369aed2804d6e495e36c11b6c94e3a61a6 | 3,803 | package org.ray.api.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.ray.api.Ray;
import org.ray.api.RayActor;
import org.ray.api.RayObject;
import org.ray.api.RayRemote;
import org.ray.api.UniqueID;
@RunWith(MyRunner.class)
public class ActorTest {
@RayRemote
public static Integer sayWorld(Integer n, RayActor<ActorTest.Adder> adder) {
RayObject<Integer> result = Ray.call(ActorTest.Adder::add, adder, 1);
return result.get() + n;
}
@Test
public void test() {
RayActor<ActorTest.Adder> adder = Ray.create(ActorTest.Adder.class);
Ray.call(Adder::set, adder, 10);
RayObject<Integer> result = Ray.call(Adder::add, adder, 1);
Assert.assertEquals(11, (int) result.get());
RayActor<Adder> secondAdder = Ray.create(Adder.class);
RayObject<Integer> result2 = Ray.call(Adder::add, secondAdder, 1);
Assert.assertEquals(1, (int) result2.get());
RayObject<Integer> result3 = Ray.call(Adder::add2, 1);
Assert.assertEquals(2, (int) result3.get());
RayObject<Integer> result4 = Ray.call(ActorTest::sayWorld, 2, adder);
Assert.assertEquals(14, (int) result4.get());
RayActor<Adder2> adder2 = Ray.create(Adder2.class);
Ray.call(Adder2::setAdder, adder2, adder);
RayObject<Integer> result5 = Ray.call(Adder2::increase, adder2);
Assert.assertEquals(1, (int) result5.get());
List list = new ArrayList<>();
list.add(adder);
Ray.call(Adder2::setAdderList, adder2, list);
RayObject<Integer> result7 = Ray.call(Adder2::testActorList, adder2);
Assert.assertEquals(14, (int) result7.get());
List tempList = new ArrayList<>();
tempList.add(result);
Ray.call(Adder::setObjectList, adder, tempList);
RayObject<Integer> result8 = Ray.call(Adder::testObjectList, adder);
Assert.assertEquals(11, (int) result8.get());
}
@RayRemote
public static class Adder {
private List<RayObject<Integer>> objectList;
private Integer sum = 0;
public static Integer add2(Integer n) {
return n + 1;
}
public Integer set(Integer n) {
sum = n;
return sum;
}
public Integer increase() {
return (++sum);
}
public Integer add(Integer n) {
return (sum += n);
}
public Integer setObjectList(List<RayObject<Integer>> objectList) {
this.objectList = objectList;
return 1;
}
public Integer testObjectList() {
return ((RayObject<Integer>) objectList.get(0)).get();
}
}
@RayRemote
public static class Adder2 {
private RayActor<Adder> adder;
private List<RayActor<Adder>> adderList;
private UniqueID id;
private Integer sum = 0;
public static Integer add2(Adder a, Integer n) {
return n + 1;
}
public Integer set(Integer n) {
sum = n;
return sum;
}
public Integer increase() {
RayObject<Integer> result = Ray.call(Adder::increase, adder);
Assert.assertEquals(13, (int) result.get());
return (++sum);
}
public Integer testActorList() {
RayActor<Adder> temp = adderList.get(0);
RayObject<Integer> result = Ray.call(Adder::increase, temp);
return result.get();
}
public Integer add(Integer n) {
return (sum += n);
}
public RayActor<Adder> getAdder() {
return adder;
}
public Integer setAdder(RayActor<Adder> adder) {
this.adder = adder;
return 0;
}
public UniqueID getId() {
return id;
}
public Integer setId(UniqueID id) {
this.id = id;
adder = new RayActor<>(id);
return 0;
}
public Integer setAdderList(List<RayActor<Adder>> adderList) {
this.adderList = adderList;
return 0;
}
}
}
| 24.856209 | 78 | 0.646069 |
a84f54ef8ddd6609364e9c910f879150cf79783f | 436 | package br.com.salon.carine.lima.repositoriessdp;
import java.util.Calendar;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import br.com.salon.carine.lima.models.Lancamento;
@Repository
public interface LancamentoRepositorySJPA extends JpaRepository<Lancamento, Integer> {
List<Lancamento> findByDataBetween(Calendar from, Calendar to);
}
| 25.647059 | 86 | 0.827982 |
ef5c1ee7503c130fdac0066408a325197b9437b3 | 271 | package no.nav.foreldrepenger.sikkerhet.abac.pdp;
import no.nav.foreldrepenger.sikkerhet.abac.domene.Tilgangsbeslutning;
import no.nav.foreldrepenger.sikkerhet.abac.pep.PdpRequest;
public interface Pdp {
Tilgangsbeslutning forespørTilgang(PdpRequest pdpRequest);
}
| 30.111111 | 70 | 0.833948 |
5367d9f852cb9e2fd93bab0eb70f2416a4f30659 | 2,348 | /*
* Copyright 1999,2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.xmlrpc.serializer;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
/** Abstract base implementation of a type serializer.
*/
public abstract class TypeSerializerImpl implements TypeSerializer {
protected static final Attributes ZERO_ATTRIBUTES = new AttributesImpl();
/** Tag name of a value element.
*/
public static final String VALUE_TAG = "value";
protected void write(ContentHandler pHandler, String pTagName, String pValue) throws SAXException {
write(pHandler, pTagName, pValue.toCharArray());
}
protected void write(ContentHandler pHandler, String pTagName, char[] pValue) throws SAXException {
pHandler.startElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG, ZERO_ATTRIBUTES);
if (pTagName != null) {
pHandler.startElement("", pTagName, pTagName, ZERO_ATTRIBUTES);
}
pHandler.characters(pValue, 0, pValue.length);
if (pTagName != null) {
pHandler.endElement("", pTagName, pTagName);
}
pHandler.endElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG);
}
protected void write(ContentHandler pHandler, String pLocalName, String pQName,
String pValue) throws SAXException {
pHandler.startElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG, ZERO_ATTRIBUTES);
pHandler.startElement(XmlRpcWriter.EXTENSIONS_URI, pLocalName, pQName, ZERO_ATTRIBUTES);
char[] value = pValue.toCharArray();
pHandler.characters(value, 0, value.length);
pHandler.endElement(XmlRpcWriter.EXTENSIONS_URI, pLocalName, pQName);
pHandler.endElement("", TypeSerializerImpl.VALUE_TAG, TypeSerializerImpl.VALUE_TAG);
}
} | 41.192982 | 105 | 0.769165 |
4733f8a7c937f9a92bf1a0c1233e292cc1c23ce2 | 9,130 | // Generated from /home/gusta/googledrive/Github/NeuraLogic/Parsing/src/main/java/cz/cvut/fel/ida/logic/parsing/antlr/grammars/Neuralogic.g4 by ANTLR 4.8
package cz.cvut.fel.ida.logic.parsing.antlr;
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
/**
* This class provides an empty implementation of {@link NeuralogicVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public class NeuralogicBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements NeuralogicVisitor<T> {
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTemplateFile(NeuralogicParser.TemplateFileContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTemplateLine(NeuralogicParser.TemplateLineContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitExamplesFile(NeuralogicParser.ExamplesFileContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLiftedExample(NeuralogicParser.LiftedExampleContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLabel(NeuralogicParser.LabelContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitQueriesFile(NeuralogicParser.QueriesFileContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFact(NeuralogicParser.FactContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitAtom(NeuralogicParser.AtomContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTermList(NeuralogicParser.TermListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTerm(NeuralogicParser.TermContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVariable(NeuralogicParser.VariableContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitConstant(NeuralogicParser.ConstantContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPredicate(NeuralogicParser.PredicateContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitConjunction(NeuralogicParser.ConjunctionContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMetadataVal(NeuralogicParser.MetadataValContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMetadataList(NeuralogicParser.MetadataListContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitLrnnRule(NeuralogicParser.LrnnRuleContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPredicateOffset(NeuralogicParser.PredicateOffsetContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPredicateMetadata(NeuralogicParser.PredicateMetadataContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitWeightMetadata(NeuralogicParser.WeightMetadataContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitTemplateMetadata(NeuralogicParser.TemplateMetadataContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitWeight(NeuralogicParser.WeightContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitFixedValue(NeuralogicParser.FixedValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitOffset(NeuralogicParser.OffsetContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitValue(NeuralogicParser.ValueContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitNumber(NeuralogicParser.NumberContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitVector(NeuralogicParser.VectorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSparseVector(NeuralogicParser.SparseVectorContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMatrix(NeuralogicParser.MatrixContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitSparseMatrix(NeuralogicParser.SparseMatrixContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitDimensions(NeuralogicParser.DimensionsContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitElement(NeuralogicParser.ElementContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitElement2d(NeuralogicParser.Element2dContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitNegation(NeuralogicParser.NegationContext ctx) { return visitChildren(ctx); }
} | 36.230159 | 153 | 0.704491 |
d18bba35a79268906369d7e7df58fd32f135c49d | 203 | package com.dvsnier.cache.base;
/**
* IEvictableManager
* Created by dovsnier on 2019-07-11.
*/
public interface IEvictableManager extends IAbstractEvictableManager, Evictable, MultipleEvictable {
}
| 22.555556 | 100 | 0.788177 |
855503acbd1f9bbe6ab10bbdbdb5a0352c6188f4 | 403 | package com.stanrnd.excel.exception;
public class ExcelBuilderException extends ExcelException {
private static final long serialVersionUID = 1L;
public ExcelBuilderException(String message) {
super(message);
}
public ExcelBuilderException(Throwable throwable) {
super(throwable);
}
public ExcelBuilderException(String message, Throwable throwable) {
super(message, throwable);
}
}
| 20.15 | 68 | 0.779156 |
689397a1164304cab110f52d51f5ddd9fe621c67 | 950 | package com.github.sibmaks.sp.domain;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
/**
* @author sibmaks
* Created at 12-10-2021
*/
@Data
@Entity
@Table(name = "user")
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
@Id
@Column(name = "id", nullable = false)
@SequenceGenerator(name = "user_id_seq", sequenceName = "user_id_seq", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "user_id_seq")
private long id;
@Column(name = "login", nullable = false)
private String login;
@Column(name = "password", nullable = false)
private String password;
@Column(name = "first_name", nullable = false)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
}
| 26.388889 | 94 | 0.718947 |
d597765b3a864e391db735b1198929873d77615f | 3,009 | package edu.utexas.tacc.tapis.apps.dao;
import edu.utexas.tacc.tapis.search.parser.ASTNode;
import edu.utexas.tacc.tapis.shared.exceptions.TapisException;
import edu.utexas.tacc.tapis.shared.threadlocal.OrderBy;
import edu.utexas.tacc.tapis.sharedapi.security.ResourceRequestUser;
import edu.utexas.tacc.tapis.apps.model.PatchApp;
import edu.utexas.tacc.tapis.apps.model.App;
import edu.utexas.tacc.tapis.apps.model.App.AppOperation;
import java.util.List;
import java.util.Set;
public interface AppsDao
{
boolean createApp(ResourceRequestUser rUser, App app, String createJsonStr, String scrubbedText)
throws TapisException, IllegalStateException;
void patchApp(ResourceRequestUser rUser, App patchedApp, PatchApp patchApp, String updateJsonStr, String scrubbedText)
throws TapisException, IllegalStateException;
void putApp(ResourceRequestUser rUser, App putApp, String updateJsonStr, String scrubbedText)
throws TapisException, IllegalStateException;
void updateEnabled(ResourceRequestUser rUser, String tenantId, String id, boolean enabled) throws TapisException;
void updateDeleted(ResourceRequestUser rUser, String tenantId, String id, boolean deleted) throws TapisException;
void updateAppOwner(ResourceRequestUser rUser, String tenantId, String id, String newOwnerName) throws TapisException;
void addUpdateRecord(ResourceRequestUser rUser, String tenant, String id, String version,
AppOperation op, String upd_json, String upd_text) throws TapisException;
int hardDeleteApp(String tenant, String id) throws TapisException;
Exception checkDB();
void migrateDB() throws TapisException;
boolean checkForApp(String tenant, String id, boolean includeDeleted) throws TapisException;
boolean checkForAppVersion(String tenant, String id, String version, boolean includeDeleted) throws TapisException;
boolean checkForApp(String tenant, String id, String version, boolean includeDeleted) throws TapisException;
boolean isEnabled(String tenant, String id) throws TapisException;
App getApp(String tenant, String id) throws TapisException;
App getApp(String tenant, String id, String version) throws TapisException;
App getApp(String tenant, String id, String version, boolean includeDeleted) throws TapisException;
int getAppsCount(String tenant, List<String> searchList, ASTNode searchAST, Set<String> setOfIDs,
List<OrderBy> orderByList, String startAfter, Boolean versionSpecified,
boolean showDeleted) throws TapisException;
List<App> getApps(String tenant, List<String> searchList, ASTNode searchAST, Set<String> appIDs, int limit,
List<OrderBy> orderByList, int skip, String startAfter, Boolean versionSpecified,
boolean showDeleted) throws TapisException;
Set<String> getAppIDs(String tenant, boolean showDeleted) throws TapisException;
String getAppOwner(String tenant, String id) throws TapisException;
}
| 45.590909 | 120 | 0.784646 |
74d8685a7a37bc8d395861afe6938b82e2610801 | 2,286 | package com.direwolf20.logisticslasers.common.items.logiccards;
import com.direwolf20.logisticslasers.common.container.cards.StockerFilterContainer;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.inventory.container.SimpleNamedContainerProvider;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.ActionResultType;
import net.minecraft.util.Hand;
import net.minecraft.util.IIntArray;
import net.minecraft.util.text.StringTextComponent;
import net.minecraft.world.World;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.items.ItemStackHandler;
public class CardStocker extends BaseCard {
public CardStocker() {
super();
CARDTYPE = CardType.STOCK;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, PlayerEntity player, Hand hand) {
ItemStack itemStack = player.getHeldItem(hand);
if (world.isRemote) return new ActionResult<>(ActionResultType.PASS, itemStack);
ItemStackHandler handler = getInventory(itemStack);
IIntArray tempArray = new IIntArray() {
@Override
public int get(int index) {
if (index == 0)
return getPriority(itemStack);
else if (index < 16)
return getInventory(itemStack).getStackInSlot(index - 1).getCount();
else
throw new IllegalArgumentException("Invalid index: " + index);
}
@Override
public void set(int index, int value) {
throw new IllegalStateException("Cannot set values through IIntArray");
}
@Override
public int size() {
return 16;
}
};
NetworkHooks.openGui((ServerPlayerEntity) player, new SimpleNamedContainerProvider(
(windowId, playerInventory, playerEntity) -> new StockerFilterContainer(itemStack, windowId, playerInventory, handler, tempArray), new StringTextComponent("")), (buf -> {
buf.writeItemStack(itemStack);
}));
return new ActionResult<>(ActionResultType.PASS, itemStack);
}
}
| 40.105263 | 186 | 0.675853 |
1a33cbee604eb46b48308cea9995afaa92012226 | 3,537 | package velmm.com.glideandroid;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.*;
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageview);
/*//Normal way
Glide.with(this)
.load("imageUrl")
.into(imageView);
//With PlaceHolder
Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.placeholderOf(R.drawable.no_image))
.into(imageView);*/
//With Placeholder and error placeholder
/*Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.placeholderOf(R.drawable.no_image))
.apply(RequestOptions.errorOf(R.drawable.error))
.into(imageView);
*/
//Resizing image
/*Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.placeholderOf(R.drawable.no_image))
.apply(RequestOptions.overrideOf(300,300))
.into(imageView);*/
/*Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.overrideOf(100,100))
.apply(RequestOptions.centerCropTransform())
.into(imageView);*/
/*Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.overrideOf(100,100))
.apply(RequestOptions.fitCenterTransform())
.into(imageView);*/
//Croping image
//center crop
/*Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.centerCropTransform())
.into(imageView);*/
//Circle crop
Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.circleCropTransform())
.into(imageView);
/*Glide.with(this)
.load("imageUrl")
.apply(RequestOptions.fitCenterTransform())
.into(imageView);*/
Glide.with(this)
.load("imageUrl")
.listener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
return false;
}
@Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
Toast.makeText(getApplicationContext(),"Success",Toast.LENGTH_SHORT).show();
return false;
}
})
.into(imageView);
}
}
| 32.75 | 158 | 0.580153 |
303fe8def4bf5d3e7ee2c26c5aa883a15093e559 | 445 | import java.util.function.Function;
public class FunctionCompose {
private static volatile double r = 0;
public static double executeTask(double i) {
Function<Double,Double> sin_asin = ((Function<Double,Double>)Math::sin).compose(Math::asin);
return sin_asin.apply((double)i);
}
public static void main(String[] args) {
for (double i = 0; i < 1000000000; ++i) {
r = executeTask(i);
}
}
}
| 22.25 | 101 | 0.635955 |
09f8a10c79efb747f849303f26e996d5504a11f8 | 7,878 | // 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.doris.qe;
import org.apache.doris.common.FeConstants;
import org.apache.doris.common.Reference;
import org.apache.doris.common.UserException;
import org.apache.doris.system.Backend;
import org.apache.doris.thrift.TNetworkAddress;
import org.apache.doris.thrift.TScanRangeLocation;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SimpleSchedulerTest {
private static Backend be1;
private static Backend be2;
private static Backend be3;
private static Backend be4;
private static Backend be5;
@BeforeClass
public static void setUp() {
FeConstants.heartbeat_interval_second = 2;
be1 = new Backend(1000L, "192.168.100.0", 9050);
be2 = new Backend(1001L, "192.168.100.1", 9050);
be3 = new Backend(1002L, "192.168.100.2", 9050);
be4 = new Backend(1003L, "192.168.100.3", 9050);
be5 = new Backend(1004L, "192.168.100.4", 9050);
be1.setAlive(true);
be2.setAlive(true);
be3.setAlive(true);
be4.setAlive(true);
be5.setAlive(true);
}
private static Map<Long, Backend> genBackends() {
Map<Long, Backend> map = Maps.newHashMap();
map.put(be1.getId(), be1);
map.put(be2.getId(), be2);
map.put(be3.getId(), be3);
map.put(be4.getId(), be4);
map.put(be5.getId(), be5);
return map;
}
@Test
public void testGetHostNormal() throws UserException, InterruptedException {
Reference<Long> ref = new Reference<Long>();
ImmutableMap<Long, Backend> backends = ImmutableMap.copyOf(genBackends());
List<TScanRangeLocation> locations = Lists.newArrayList();
TScanRangeLocation scanRangeLocation1 = new TScanRangeLocation();
scanRangeLocation1.setBackendId(be1.getId());
locations.add(scanRangeLocation1);
TScanRangeLocation scanRangeLocation2 = new TScanRangeLocation();
scanRangeLocation2.setBackendId(be2.getId());
locations.add(scanRangeLocation2);
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
try {
boolean foundCandidate = false;
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
TNetworkAddress address = SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref);
Assert.assertNotNull(address);
if (!foundCandidate && address.getHostname().equals(be2.getHost())) {
foundCandidate = true;
}
}
System.out.println("cost: " + (System.currentTimeMillis() - start));
Assert.assertTrue(foundCandidate);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
try {
Set<String> resBackends = Sets.newHashSet();
long start = System.currentTimeMillis();
for (int i = 0; i < 1000; i++) {
TNetworkAddress address = SimpleScheduler.getHost(backends, ref);
Assert.assertNotNull(address);
resBackends.add(address.hostname);
}
System.out.println("cost: " + (System.currentTimeMillis() - start));
Assert.assertTrue(resBackends.size() >= 4);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
SimpleScheduler.addToBlacklist(be1.getId(), "test");
}
});
t3.start();
t1.start();
t2.start();
t1.join();
t2.join();
t3.join();
Assert.assertFalse(SimpleScheduler.isAvailable(be1));
Thread.sleep((FeConstants.heartbeat_interval_second + 5) * 1000);
Assert.assertTrue(SimpleScheduler.isAvailable(be1));
}
@Test
public void testGetHostAbnormal() throws UserException, InterruptedException {
Reference<Long> ref = new Reference<Long>();
ImmutableMap<Long, Backend> backends = ImmutableMap.copyOf(genBackends());
// 1. unknown backends
List<TScanRangeLocation> locations = Lists.newArrayList();
TScanRangeLocation scanRangeLocation1 = new TScanRangeLocation();
scanRangeLocation1.setBackendId(2000L);
locations.add(scanRangeLocation1);
TScanRangeLocation scanRangeLocation2 = new TScanRangeLocation();
scanRangeLocation2.setBackendId(2001L);
locations.add(scanRangeLocation2);
try {
SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref);
Assert.fail();
} catch (UserException e) {
System.out.println(e.getMessage());
}
// 2. all backends in black list
locations.clear();
scanRangeLocation1 = new TScanRangeLocation();
scanRangeLocation1.setBackendId(be1.getId());
locations.add(scanRangeLocation1);
scanRangeLocation2 = new TScanRangeLocation();
scanRangeLocation2.setBackendId(be2.getId());
locations.add(scanRangeLocation2);
TScanRangeLocation scanRangeLocation3 = new TScanRangeLocation();
scanRangeLocation3.setBackendId(be3.getId());
locations.add(scanRangeLocation3);
TScanRangeLocation scanRangeLocation4 = new TScanRangeLocation();
scanRangeLocation4.setBackendId(be4.getId());
locations.add(scanRangeLocation4);
TScanRangeLocation scanRangeLocation5 = new TScanRangeLocation();
scanRangeLocation5.setBackendId(be5.getId());
locations.add(scanRangeLocation5);
SimpleScheduler.addToBlacklist(be1.getId(), "test");
SimpleScheduler.addToBlacklist(be2.getId(), "test");
SimpleScheduler.addToBlacklist(be3.getId(), "test");
SimpleScheduler.addToBlacklist(be4.getId(), "test");
SimpleScheduler.addToBlacklist(be5.getId(), "test");
try {
SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref);
Assert.fail();
} catch (UserException e) {
System.out.println(e.getMessage());
}
Thread.sleep((FeConstants.heartbeat_interval_second + 5) * 1000);
Assert.assertNotNull(SimpleScheduler.getHost(locations.get(0).backend_id, locations, backends, ref));
}
}
| 39.19403 | 129 | 0.625413 |
2626618b563783dcc5e2583e0ee8506a3fa03342 | 2,612 | /*
* L2jFrozen Project - www.l2jfrozen.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package com.l2jfrozen.gameserver.network.serverpackets;
import com.l2jfrozen.gameserver.model.L2ShortCut;
import com.l2jfrozen.gameserver.model.actor.instance.L2PcInstance;
/**
* ShortCutInit format d *(1dddd)/(2ddddd)/(3dddd)
* @version $Revision: 1.3.2.1.2.4 $ $Date: 2005/03/27 15:29:39 $
*/
public class ShortCutInit extends L2GameServerPacket
{
private static final String _S__57_SHORTCUTINIT = "[S] 45 ShortCutInit";
private L2ShortCut[] _shortCuts;
private L2PcInstance _activeChar;
public ShortCutInit(final L2PcInstance activeChar)
{
_activeChar = activeChar;
if (_activeChar == null)
return;
_shortCuts = _activeChar.getAllShortCuts();
}
@Override
protected final void writeImpl()
{
writeC(0x45);
writeD(_shortCuts.length);
for (final L2ShortCut sc : _shortCuts)
{
writeD(sc.getType());
writeD(sc.getSlot() + sc.getPage() * 12);
switch (sc.getType())
{
case L2ShortCut.TYPE_ITEM: // 1
writeD(sc.getId());
writeD(0x01);
writeD(-1);
writeD(0x00);
writeD(0x00);
writeH(0x00);
writeH(0x00);
break;
case L2ShortCut.TYPE_SKILL: // 2
writeD(sc.getId());
writeD(sc.getLevel());
writeC(0x00); // C5
writeD(0x01); // C6
break;
case L2ShortCut.TYPE_ACTION: // 3
writeD(sc.getId());
writeD(0x01); // C6
break;
case L2ShortCut.TYPE_MACRO: // 4
writeD(sc.getId());
writeD(0x01); // C6
break;
case L2ShortCut.TYPE_RECIPE: // 5
writeD(sc.getId());
writeD(0x01); // C6
break;
default:
writeD(sc.getId());
writeD(0x01); // C6
}
}
}
/*
* (non-Javadoc)
* @see com.l2jfrozen.gameserver.serverpackets.ServerBasePacket#getType()
*/
@Override
public String getType()
{
return _S__57_SHORTCUTINIT;
}
}
| 25.115385 | 74 | 0.671516 |
0eda731f02ef613c4425751252de072544489a5a | 15,773 | package org.jrd.backend.data;
import java.io.File;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.jrd.backend.data.Cli.*;
/**
* Class for relaying help texts to the user.
*/
public final class Help {
static final String HELP_FORMAT = HELP + ", " + H;
static final String VERBOSE_FORMAT = VERBOSE;
static final String VERSION_FORMAT = VERSION;
static final String BASE64_FORMAT = BASE64 + " <PUC> <CLASS REGEX>...";
static final String BYTES_FORMAT = BYTES + " <PUC> <CLASS REGEX>...";
static final String LIST_JVMS_FORMAT = LIST_JVMS;
static final String LIST_PLUGINS_FORMAT = LIST_PLUGINS;
static final String LIST_CLASSES_FORMAT = LIST_CLASSES + " <PUC> [<CLASS REGEX>...]";
static final String LIST_CLASSESDETAILS_FORMAT = LIST_CLASSESDETAILS + " <PUC> [<CLASS REGEX>...]";
static final String COMPILE_FORMAT = COMPILE + " [" + P + " <PLUGIN>] [" + CP + " <PUC>] [" + R + "] <PATH>...";
static final String DECOMPILE_FORMAT = DECOMPILE + " <PUC> <PLUGIN> <CLASS REGEX>...";
static final String OVERWRITE_FORMAT = OVERWRITE + " <PUC> <FQN> [<CLASS FILE>]";
static final String INIT_FORMAT = INIT + " <PUC> <FQN>";
static final String API_FORMAT = API + " <PUC>";
static final String SAVE_AS_FORMAT = SAVE_AS + " <PATH>";
static final String SAVE_LIKE_FORMAT = SAVE_LIKE + " <SAVE METHOD>";
private static final String HELP_TEXT = "Print this help text.";
private static final String VERBOSE_TEXT = "All exceptions and some debugging strings will be printed to standard error.";
private static final String VERSION_TEXT = "Print version project name, version and build timestamp.";
private static final String BASE64_TEXT = "Print Base64 encoded binary form of requested classes of a process.";
private static final String BYTES_TEXT = "Print binary form of requested classes of a process";
private static final String LIST_JVMS_TEXT = "List all local Java processes and their PIDs.";
private static final String LIST_PLUGINS_TEXT = "List all currently configured decompiler plugins and their statuses.";
private static final String LIST_CLASSES_TEXT = "List all loaded classes of a process, optionally filtering them.\n" +
"Only '" + SAVE_LIKE + " " + Saving.EXACT + "' or '" + SAVE_LIKE + " " + Saving.DEFAULT +
"' are allowed as saving modifiers.";
private static final String LIST_CLASSESDETAILS_TEXT = "Similar to " + LIST_CLASSES + ", only more details are printed about classes.";
private static final String COMPILE_TEXT = "Compile local files against runtime classpath, specified by " + CP + ".\n" +
"Use " + P + " to utilize some plugins' (like jasm or jcoder) bundled compilers.\n" +
"Use " + R + " for recursive search if <PATH> is a directory.\n" +
"If the argument of '" + SAVE_AS + "' is a valid PID or URL, " +
"the compiled code will be attempted to be injected into that process.\n" +
"If multiple PATHs were specified, but no '" + SAVE_AS + "', the process fails.";
private static final String DECOMPILE_TEXT = "Decompile and print classes of a process with the specified decompiler plugin.\n" +
"Javap can be passed options by appending them without spaces: " +
"'javap-v-public ...' executes as 'javap -v -public ...'";
private static final String OVERWRITE_TEXT = "Overwrite class of a process with new bytecode. If <CLASS FILE> is not set, standard input is used.";
private static final String INIT_TEXT = "Try to initialize a class in a running JVM (has no effect in FS VMs). " +
"Because class loading is lazy, the class you need might be missing, eg. java.lang.Override.";
private static final String API_TEXT = "Will print out which can be used to insert fields/methods to running vm";
private static final String SAVE_AS_TEXT = "All outputs will be written to PATH instead of to standard output.";
private static final String SAVE_LIKE_TEXT = "Specify how saving will behave.";
private static final String NOTES_SLASH = "All options can be with either one or two leading slashes ('-').";
private static final String NOTES_REGEX = "When using <CLASS REGEX>, don't forget to escape dollar signs '$' of inner classes to '\\$', as otherwise they are treated as end-of-line by REGEX.";
private static final String NOTES_FQN = "<FQN> is the fully qualified name of a class as per the Java Language Specification §6.7.";
private static final String NOTES_PUC = "<PUC>, short for PidUrlClasspath, can be one of:";
private static final String NOTES_SAVE = "<SAVE METHOD> can be one of:";
private static final String[] NOTES_PUC_ITEMS = new String[]{
"local process PID",
"remote process URL, in the format of 'hostname:port'",
"classpath of JAR on the filesystem (classpath separator is '" + File.pathSeparator + "')"
};
private static final String[] NOTES_SAVE_ITEMS = new String[]{
"'" + Saving.DIR + "' - Result will be saved as '<PATH>/fully/qualified/name.class'. Default for .class binaries.",
"'" + Saving.FQN + "' - Result will be saved as '<PATH>/fully.qualified.name.java'. Default for .java sources.",
"'" + Saving.EXACT + "' - Result will be saved exactly to '<PATH>'. Default for everything else.",
"'" + Saving.DEFAULT + "' - Saving uses the defaults mentioned above."
};
private static final String LAUNCHER_LINUX = "./start.sh";
private static final String LAUNCHER_WINDOWS = "start.bat";
static final Map<String, String> ALL_OPTIONS;
static final Map<String, String> SAVING_OPTIONS;
private static final Map<String, String[]> NOTES;
static {
ALL_OPTIONS = new LinkedHashMap<>();
ALL_OPTIONS.put(HELP_FORMAT, HELP_TEXT);
ALL_OPTIONS.put(VERBOSE_FORMAT, VERBOSE_TEXT);
ALL_OPTIONS.put(VERSION_FORMAT, VERSION_TEXT);
ALL_OPTIONS.put(LIST_JVMS_FORMAT, LIST_JVMS_TEXT);
ALL_OPTIONS.put(LIST_PLUGINS_FORMAT, LIST_PLUGINS_TEXT);
ALL_OPTIONS.put(LIST_CLASSES_FORMAT, LIST_CLASSES_TEXT);
ALL_OPTIONS.put(LIST_CLASSESDETAILS_FORMAT, LIST_CLASSESDETAILS_TEXT);
ALL_OPTIONS.put(BASE64_FORMAT, BASE64_TEXT);
ALL_OPTIONS.put(BYTES_FORMAT, BYTES_TEXT);
ALL_OPTIONS.put(COMPILE_FORMAT, COMPILE_TEXT);
ALL_OPTIONS.put(DECOMPILE_FORMAT, DECOMPILE_TEXT);
ALL_OPTIONS.put(OVERWRITE_FORMAT, OVERWRITE_TEXT);
ALL_OPTIONS.put(INIT_FORMAT, INIT_TEXT);
ALL_OPTIONS.put(API_FORMAT, API_TEXT);
SAVING_OPTIONS = new LinkedHashMap<>();
SAVING_OPTIONS.put(SAVE_AS_FORMAT, SAVE_AS_TEXT);
SAVING_OPTIONS.put(SAVE_LIKE_FORMAT, SAVE_LIKE_TEXT);
NOTES = new LinkedHashMap<>();
NOTES.put(NOTES_SLASH, new String[0]);
NOTES.put(NOTES_REGEX, new String[0]);
NOTES.put(NOTES_FQN, new String[0]);
NOTES.put(NOTES_PUC, NOTES_PUC_ITEMS);
NOTES.put(NOTES_SAVE, NOTES_SAVE_ITEMS);
}
private static final String[] UNSAVABLE_OPTIONS = {HELP, H, OVERWRITE, INIT};
private static final String[] SAVABLE_OPTIONS = {
LIST_CLASSES, LIST_CLASSESDETAILS, BYTES, BASE64, COMPILE, DECOMPILE, API, LIST_JVMS, LIST_PLUGINS};
private static final int LONGEST_FORMAT_LENGTH =
Stream.of(ALL_OPTIONS.keySet(), SAVING_OPTIONS.keySet())
.flatMap(Collection::stream)
.map(String::length)
.max(Integer::compare)
.orElse(30) + 1; // at least one space between format and text
private Help() {
}
protected static void printHelpText() {
printHelpText(new CliHelpFormatter());
}
private static void printHelpText(HelpFormatter formatter) {
formatter.printTitle();
formatter.printName();
formatter.printUsageHeading();
formatter.printUsage();
formatter.printOptionsHeading();
formatter.printOptions();
formatter.printNotesHeading();
formatter.printNotes();
}
public static void main(String[] args) {
printHelpText(new ManPageFormatter());
}
private interface HelpFormatter {
void printTitle();
void printName();
void printUsageHeading();
/**
* Prints each {@link #launchOptions() launch option} prepended with the common {@link #launcher()} String.
* Man page formatting doesn't mind the indentation so this is common for both formatters.
*/
default void printUsage() {
for (String launchOption : launchOptions()) {
System.out.println(indent(1) + launcher() + launchOption);
}
}
void printOptionsHeading();
void printMainOptionsSubheading();
void printSavingOptionsSubheading();
default void printOptions() {
printMainOptionsSubheading();
printOptions(ALL_OPTIONS);
printSavingOptionsSubheading();
printOptions(SAVING_OPTIONS);
}
void printOptions(Map<String, String> map);
/**
* Joins options together with a pipe and surrounds them in parentheses.
*
* @param options String array containing the individual options
* @return String in the format of "(opt1|opt2|...)"
*/
String optionize(String[] options);
default String indent(int depth) { // default because ManPageFormatter doesn't use it
return " ".repeat(depth);
}
default String[] launchOptions() {
return new String[]{
"# launches GUI",
optionize(UNSAVABLE_OPTIONS),
optionize(SAVABLE_OPTIONS) + savingModifiers()
};
}
String launcher();
String savingModifiers();
void printNotesHeading();
void printNotes();
}
private static class CliHelpFormatter implements HelpFormatter {
@Override
public void printTitle() {
}
@Override
public void printName() {
}
@Override
public void printUsageHeading() {
System.out.println("Usage:");
}
@Override
public void printOptionsHeading() {
}
@Override
public void printMainOptionsSubheading() {
System.out.println("Available options:");
}
@Override
public void printSavingOptionsSubheading() {
System.out.println("Saving modifiers:");
}
@Override
public void printOptions(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String format = entry.getKey();
String initialSpacing = " ".repeat(LONGEST_FORMAT_LENGTH - format.length());
String interlineSpacing = "\n" + indent(1) + " ".repeat(LONGEST_FORMAT_LENGTH);
System.out.println(indent(1) + format + initialSpacing +
entry.getValue().replaceAll("\n", interlineSpacing));
}
}
@Override
public String optionize(String[] options) {
return "(" + String.join("|", options) + ")";
}
@Override
public String savingModifiers() {
return " [" + SAVE_AS + " [" + SAVE_LIKE + "]]";
}
@Override
public String launcher() {
return (Directories.isOsWindows() ? LAUNCHER_WINDOWS : LAUNCHER_LINUX) + " [" + VERBOSE + "] ";
}
@Override
public void printNotesHeading() {
System.out.println("Additional information");
}
@Override
public void printNotes() {
for (Map.Entry<String, String[]> entry : NOTES.entrySet()) {
System.out.println(indent(1) + entry.getKey());
for (String item : entry.getValue()) {
System.out.println(indent(2) + "- " + item);
}
}
}
}
private static class ManPageFormatter implements HelpFormatter {
String formatWrap(char formatChar, String string) {
return "\\f" + formatChar + string + "\\fR";
}
String manFormat(String line) {
return line.replace("\\", "\\\\") // escape one more time for man parsing
.replaceAll("<(.*?)>", "<\\\\fI$1\\\\fR>"); // underline <PLACEHOLDERS>
}
@Override
public void printTitle() {
String buildTimestamp;
String centerTitle;
try {
buildTimestamp = MetadataProperties.getInstance().getTimestamp().split(" ")[0];
centerTitle = MetadataProperties.getInstance().getGroup();
} catch (IndexOutOfBoundsException e) {
buildTimestamp = "";
centerTitle = ""; // empty == defaults to "General Commands Manual"
}
System.out.println(".TH JRD 1 \"" + buildTimestamp + "\" \"\" " + centerTitle);
}
@Override
public void printName() {
System.out.println(".SH NAME");
System.out.println("JRD - Java Runtime Decompiler");
}
@Override
public void printUsageHeading() {
System.out.println(".SH SYNOPSIS");
}
@Override
public void printOptionsHeading() {
System.out.println(".SH OPTIONS");
}
@Override
public void printMainOptionsSubheading() {
System.out.println(".SS Standard options");
}
@Override
public void printSavingOptionsSubheading() {
System.out.println(".SS Saving modifiers");
}
@Override
public void printOptions(Map<String, String> map) {
for (Map.Entry<String, String> entry : map.entrySet()) {
String manPageParagraphs = entry.getValue().replaceAll("\n", "\n\n ");
System.out.println(
".HP\n" +
manFormat(entry.getKey()) + "\n " +
manFormat(manPageParagraphs)
);
}
}
@Override
public String optionize(String[] options) {
return "(" +
Stream.of(options)
.map(s -> formatWrap('B', s))
.collect(Collectors.joining("|")) +
")";
}
@Override
public String launcher() {
return "\n" + // paragraph separation
optionize(new String[]{LAUNCHER_LINUX, LAUNCHER_WINDOWS}) +
" [" + formatWrap('I', VERBOSE) + "] "; // trailing space separates from rest of line
}
@Override
public String savingModifiers() {
return " [" + formatWrap('I', SAVE_AS) + " [" + formatWrap('I', SAVE_LIKE) + "]]";
}
@Override
public void printNotesHeading() {
System.out.println(".SH NOTES");
}
@Override
public void printNotes() {
for (Map.Entry<String, String[]> entry : NOTES.entrySet()) {
System.out.println(".HP\n" + manFormat(entry.getKey()) + "\n");
for (String item : entry.getValue()) {
System.out.println("\\[bu] " + manFormat(item) + "\n"); // unordered list
}
}
}
}
}
| 40.340153 | 196 | 0.603753 |
125dddc24fe0cbc7af869a8d1f73340bc931c48e | 11,590 | package print;
import javax.swing.*;
import java.awt.*;
import java.util.*;
public class Printer
{
private String name;
private double tonerLevel = 100;
private int maxCapacity;
private int paperLeft;
private int size = 0;
private Node front, rear;
/**
* Constructs a Printer class
* front and rear nodes are intialized to null because the queue is empty at time of creation
* @param name - name of the Printer object
* @param maxCapacity - number of pieces of paper a printer can hold
*/
public Printer(String name, int maxCapacity)
{
this.name = name;
this.maxCapacity = maxCapacity;
this.paperLeft = maxCapacity;
this.front = null;
this.rear = null;
}
/**
* Starts the printing of the queue of this Printer objecy
* Create new JFrame, and dequeues the first Document in the queue if not null
* Makes sure the Printer has enough paper and toner before printing, if not it will create a warning popup
* Also, will enqueue the dequeued Document
* Calculates time needed to print Document and waits that time
* Creates popup when printing for document is done
*/
public void startPrinting() {
JFrame frame = new JFrame();
boolean ok = true;
while (ok && front != null)
{
Document front = dequeue();
if (isPrinterReadyToPrint(front))
{
double timeNeeded = getTimeRequired(front);
int seconds = (int)timeNeeded;
int milli = (int)((timeNeeded - seconds) * 1000);
try
{
Thread.sleep(milli);
} catch (InterruptedException e)
{
Thread.currentThread().interrupt();
}
JOptionPane.showMessageDialog(frame, front.getDocumentName() + " was printed to " + this.name + " by ID " +
front.getId(),
"Success", JOptionPane.INFORMATION_MESSAGE);
} else {
enqueue(front);
ok = false;
}
}
}
/**
* Works with the isPrinterReadyToPrint(Document doc) method to ensure the printer has enough ink to print
* If the amount used is greater than zero, it will allow the Document to be printed
* If Toner goes beneath 10%, it will create a pop-up warning to warn of low toner
* @param numPages - Number of pages in the document to be printed
* @return boolean
*/
private boolean checkToner(int numPages)
{
JFrame frame = new JFrame();
double tonerUsed = numPages * .25;
if (tonerLevel - tonerUsed > 0)
{
tonerLevel-=tonerUsed;
if (tonerLevel < 10)
{
JOptionPane.showMessageDialog(frame, "Toner Warning",
"Toner Low at " + name, JOptionPane.WARNING_MESSAGE);
}
return true;
}
return false;
}
/**
* Checks if the Document that is to be printed can be printed due to the number of pages it has
* If the Document is listed as double-sided, it will reduce the number of pages by half.
* Calculates the number of pages needed, and checks if there is enough paper in the printer
* If there is it will return true, but if the paper is lower than 30, it will create a "Low on Paper" warning
* If there is not enough paper, it will return false, and not allow the Printer to print the next Document
* @param numPages - Number of pages in the Document
* @param doubleSided - boolean that dentoes if the Document is to be printed on one side or both sides.
* @return boolean - true/ false
*/
private boolean checkPaper(int numPages, boolean doubleSided)
{
JFrame frame = new JFrame();
if (doubleSided)
{
if (numPages%2 == 1)
{
int pages = ((numPages - 1) / 2) + 1;
if (paperLeft - pages > 0)
{
paperLeft-=pages;
if (paperLeft < 30)
{
JOptionPane.showMessageDialog(frame, "Low On Paper Warning",
"Low Paper at " + name, JOptionPane.WARNING_MESSAGE);
}
return true;
} else
{
return false;
}
} else
{
int pages = numPages / 2;
if (paperLeft - pages > 0)
{
paperLeft-=numPages;
if (paperLeft < 30)
{
JOptionPane.showMessageDialog(frame, "Low On Paper Warning",
"Low Paper at " + name, JOptionPane.WARNING_MESSAGE);
}
return true;
} else {
return false;
}
}
} else {
if (paperLeft - numPages > 0)
{
paperLeft-=numPages;
if (paperLeft < 30)
{
JOptionPane.showMessageDialog(frame, "Low On Paper Warning",
"Low Paper at " + name, JOptionPane.WARNING_MESSAGE);
}
return true;
} else
{
return false;
}
}
}
/**
* Refills the Paper Tray to the maximum capacity indicted earlier
*/
public void refillPaper()
{
paperLeft = maxCapacity;
}
/**
* Refills the toner to 100% capacity
*/
public void fillToner()
{
tonerLevel = 100;
}
/**
* Checks if the Document next in the queue has enough paper and toner to print
* If both are good, then will allow the Document to be printed
* If not, it will run an out of paper/ toner and prompt the user to refill the Printer
* @param document - Document object at the front of the queue
* @return boolean
*/
private boolean isPrinterReadyToPrint(Document document)
{
int numPages = document.getNumPages();
boolean doubleSided = document.isDoubleSided();
if (checkPaper(numPages, doubleSided) && checkToner(numPages))
{
return true;
} else
{
JFrame frame = new JFrame();
if (!checkPaper(numPages, doubleSided))
{
JOptionPane.showMessageDialog(frame, "Printer " + name + " Out of Paper",
"ERROR - Paper", JOptionPane.ERROR_MESSAGE);
} else if (!checkToner(numPages))
{
JOptionPane.showMessageDialog(frame, "Printer " + name + " Low on Toner",
"ERROR - Toner", JOptionPane.ERROR_MESSAGE);
}
return false;
}
}
/**
* Builds a string of the contents of the queue of the Printer
* @return String
*/
public String outputQueue()
{
StringBuilder queue = new StringBuilder("");
queue.append("Position").append(" | ").append("Doc Name").append(" | ").append("Employee ID").append("\n");
int count = 1;
Node current = front;
while (current != null)
{
String docID = current.getData().getDocumentName();
int eID = current.getData().getId();
queue.append(count).append(" | ").append(docID).append(" | ").append(eID).append("\n");
current = current.next;
count++;
}
return queue.toString();
}
/**
* Gets the next document in the queue, and reduces size of the queue
* @return Document object representing the object on top
*/
public Document dequeue() {
Document onTop = front.getData();
front = front.next;
if (isEmpty())
{
rear = null;
}
size--;
return onTop;
}
/**
* Adds a new Document object to the queue, and readjusts the rear and .next of the previous rear of the queue
* @param document - Document object to be added
*/
public void enqueue(Document document)
{
Node oldRear = rear;
rear = new Node(document);
rear.data = document;
rear.next = null;
if (isEmpty())
{
front = rear;
} else
{
oldRear.next = rear;
}
size++;
}
/**
* Calculates the time required to print the document based upon the number of pages
* @param document - Document to print
* @return double representing the time needed
*/
private double getTimeRequired(Document document)
{
int numPages = document.getNumPages();
double timeNeeded = (numPages * 0.6);
return timeNeeded;
}
/**
* Gets the Document at the front of the queue
* @return Document object
*/
public Document getFront() {
if (isEmpty())
throw new NoSuchElementException();
else
return front.getData();
}
/**
* Returns the name of the printer
* @return String
*/
public String getName()
{
return name;
}
/**
* Gets the size of the queue of the printer
* @return Int
*/
public int getLength()
{
return size;
}
/**
* Checks if the queue is empty by checking the numerical value of size
* @return
*/
public boolean isEmpty() {
return size == 0;
}
/**
* Class that stores the data and forms the queue of the Printer
*/
public class Node
{
private Document data;
private Node next;
/**
* Constructs a new Node
* @param data - Document object
*/
public Node(Document data)
{
this(data, null);
}
/**
* Constructs a new Node
* @param data Document object
* @param nextEntry Node that references the object behind/ next to it
*/
Node (Document data, Node nextEntry)
{
data = data;
next = nextEntry;
}
/**
* Retuns the Document object inside a Node object
* @return
*/
public Document getData()
{
return data;
}
/**
* Sets a new Document object to a Node
* @param newDocument new Document object
*/
private void setData(Document newDocument)
{
data = newDocument;
}
/**
* Gets the Node behind this node
* @return Node
*/
public Node getNext()
{
return next;
}
/**
* Changes the Node that refernces the next Node in the linked list/ queue
* @param nextEntry Node
*/
private void setNext(Node nextEntry)
{
next = nextEntry;
}
}
} | 31.155914 | 124 | 0.50811 |
b56d96346014743212e2d496be8e74736a19b5a3 | 7,395 | package com.example.myapplication.search;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.room.Room;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.myapplication.R;
import com.example.myapplication.room.AppDatabase;
import com.example.myapplication.room.User;
import java.util.List;
import static android.app.SearchManager.EXTRA_DATA_KEY;
public class SearchActivity extends AppCompatActivity {
SearchView mSearchView;
String query;
List<User> users;
AppDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i("search", "create");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
Toolbar toolbar = findViewById(R.id.searchToolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(true);
}
db = Room.databaseBuilder(getApplicationContext(),
AppDatabase.class, "myDatabase")
.fallbackToDestructiveMigration()
.build();
handleIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
Log.i("search", "newIntent");
super.onNewIntent(intent);
setIntent(intent);
handleIntent(intent);
}
public void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
suggestions.saveRecentQuery(query, null);
doMySearch(query);
} else if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Log.i("search", "actionView");
String dataStr = intent.getDataString();
String extra = intent.getStringExtra(EXTRA_DATA_KEY);
new Thread(new Runnable() {
@Override
public void run() {
try {
assert dataStr != null;
int id = Integer.parseInt(dataStr);
users = db.userDao().getSpecificOneUser_id(id);
TextView textView = findViewById(R.id.searchTextView1);
textView.setVisibility(View.VISIBLE);
if (users.size() != 0) {
User user = users.get(0);
String text = user.getId() + " " + user.getUsername() + " " + user.isIs_login() + " " + extra;
textView.setText(text);
}
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}).start();
}
}
Handler handler = new Handler();
public void doMySearch(String query) {
Log.i("search", query);
new Thread(new Runnable() {
@Override
public void run() {
try {
int id = Integer.parseInt(query);
users = db.userDao().getSpecificOneUser_id(id);
} catch (NumberFormatException e) {
if (query.equals("true") | query.equals("false")) {
boolean isLogin = Boolean.parseBoolean(query);
users = db.userDao().getSpecificOneUser_isLogin(isLogin);
} else {
users = db.userDao().getSpecificOneUser_username_NoLivedata(query);
}
}
handler.post(new Runnable() {
@Override
public void run() {
Log.i("search", "setAdapter");
TextView textView = findViewById(R.id.searchTextView1);
if (users.size() == 0) {
textView.setText("没找到");
textView.setVisibility(View.VISIBLE);
} else {
RecyclerView recyclerView = findViewById(R.id.searchRecycleView);
recyclerView.setLayoutManager(new LinearLayoutManager(SearchActivity.this));
recyclerView.setAdapter(new SearchUserAdapter(users));
textView.setVisibility(View.GONE);
}
}
});
}
}).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i("search", "createMenu");
getMenuInflater().inflate(R.menu.menu_main, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) searchItem.getActionView();
mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
mSearchView.setSubmitButtonEnabled(true);
mSearchView.setQueryRefinementEnabled(true);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuClearHistory:
SearchRecentSuggestions suggestions = new SearchRecentSuggestions(this,
MySuggestionProvider.AUTHORITY, MySuggestionProvider.MODE);
suggestions.clearHistory();
return true;
case R.id.menuAdd:
Log.i("search", "add");
User user1 = new User("a", true);
User user2 = new User("b", true);
User user3 = new User("c", true);
User user4 = new User("d", true);
User user5 = new User("e", false);
User user6 = new User("f", true);
User user7 = new User("g", false);
User[] users1 = {user1, user2, user3, user4, user5, user6, user7};
new Thread(new Runnable() {
@Override
public void run() {
db.userDao().insertAll(users1);
}
}).start();
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onStart() {
super.onStart();
Log.i("search", "start");
}
@Override
protected void onResume() {
super.onResume();
Log.i("search", "resume");
}
@Override
protected void onDestroy() {
super.onDestroy();
db.close();
}
} | 35.382775 | 122 | 0.563083 |
2248a14d8b3734f2b3402ab25cc89f122fc28be8 | 845 | package com.revolsys.beans;
/**
* An exception that wraps an object that caused the exception.
*/
public class ObjectException extends RuntimeException {
/**
*
*/
private static final long serialVersionUID = 1L;
private final Object object;
public ObjectException(final Object object) {
this.object = object;
}
public ObjectException(final Object object, final String message) {
super(message);
this.object = object;
}
public ObjectException(final Object object, final String message, final Throwable cause) {
super(message, cause);
this.object = object;
}
public ObjectException(final Object object, final Throwable cause) {
super(cause.getMessage(), cause);
this.object = object;
}
@SuppressWarnings("unchecked")
public <V> V getObject() {
return (V)this.object;
}
}
| 21.666667 | 92 | 0.697041 |
2a4882b2fbc37a5e19cdb41edd01cf99940c5893 | 875 | package Controlador;
import java.awt.event.*;
import javax.swing.JTextField;
import modelo.Modelo;
import vista.Login_alum;
import vista.Select_user;
public class CtrlLogin {
private Select_user selectUser;
private Login_alum log;
private Modelo model;
public CtrlLogin(Select_user sel, Modelo mod, Login_alum log) {
selectUser = sel;
model = mod;
this.log = log;
}
public void guardaInput(Login_alum obj) {
ActionListener escucha = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
model.setTextUser(obj.Text_login_alum01.getText());
System.out.println("Input: "+model.getTextUser());
}
};
obj.Button_login_alum.addActionListener(escucha);
}
}
| 23.648649 | 67 | 0.608 |
b0c81229fb1f83e4c2e86da9d15684584b8a0398 | 3,340 | package com.romickid.simpbook.fragments.Collection;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.romickid.simpbook.R;
import com.romickid.simpbook.fragments.FragmentExpense;
import com.romickid.simpbook.fragments.FragmentIncome;
import com.romickid.simpbook.fragments.FragmentTransfer;
public class ActivityCollectionAdd extends AppCompatActivity implements
FragmentIncome.OnFragmentInteractionListener,
FragmentExpense.OnFragmentInteractionListener,
FragmentTransfer.OnFragmentInteractionListener,
FragmentCollectionAdd.OnFragmentInteractionListener {
private Toolbar toolbar;
private Fragment fragment;
private FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
// Activity相关
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_collectionadd);
initFindById();
initToolbar();
initFragment();
}
// Fragment相关
@Override
public void onFragmentInteraction(Uri uri) {
}
// 初始化相关
/**
* 初始化Id
*/
private void initFindById() {
toolbar = findViewById(R.id.collectionadd_toolbar);
}
/**
* 初始化Toolbar
*/
private void initToolbar() {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
/**
* 初始化Fragment
*/
private void initFragment() {
fragmentManager = getSupportFragmentManager();
fragmentTransaction = fragmentManager.beginTransaction();
setCurrentFragment();
}
/**
* 设置显示的Fragment页面(支出/收入/转账)
*/
private void setCurrentFragment() {
Intent intent = getIntent();
String currentType = intent.getStringExtra("CollectionAddType");
switch (currentType) {
case "Expense":
fragment = new FragmentExpense();
fragmentTransaction.replace(R.id.collectionadd_framelayout, fragment);
fragmentTransaction.commit();
break;
case "Income":
fragment = new FragmentIncome();
fragmentTransaction.replace(R.id.collectionadd_framelayout, fragment);
fragmentTransaction.commit();
break;
case "Transfer":
fragment = new FragmentTransfer();
fragmentTransaction.replace(R.id.collectionadd_framelayout, fragment);
fragmentTransaction.commit();
break;
case "Default":
fragment = new FragmentCollectionAdd();
fragmentTransaction.replace(R.id.collectionadd_framelayout, fragment);
fragmentTransaction.commit();
break;
}
}
}
| 29.298246 | 86 | 0.652994 |
dd376d7843781853c4b9cc7b8b0a2821c14af95d | 4,382 | /** Manual tests for Text Generator.
* @author: Rafayel Mkrtchyan
**/
import java.util.TreeMap;
import java.io.IOException;
import java.util.ArrayList;
public class testing {
public static void main(String[] args) {
checkForEmpty();
System.out.println();
checkForOne();
System.out.println();
testToMap();
System.out.println();
testingSaveToList();
System.out.println();
noElemSaveToList();
System.out.println();
oneElemSaveToList();
System.out.println();
testTextToData();
System.out.println();
testingGenerator();
System.out.println();
secondTestGenerator();
}
/** Checks saveToMap() for empty file. **/
private static void checkForEmpty() {
TextGenerator current = new TextGenerator("input.txt");
try {
TreeMap<String, ArrayList<WordTuple>> data = current.saveToMap();
if (current.saveToMap() == null) {
System.out.println("Checking Error 001");
}
} catch (IOException ex) {
}
}
/** Checks saveToMap() for file that contains just one word. **/
private static void checkForOne() {
TextGenerator current = new TextGenerator("input1.txt");
try {
TreeMap<String, ArrayList<WordTuple>> data = current.saveToMap();
for (String item : data.keySet()) {
ArrayList<WordTuple> currentList = data.get(item);
for (WordTuple tup : currentList) {
System.out.println(item + " " + tup.getword() + " "
+ tup.getNumber());
}
}
} catch (IOException ex) {
}
}
/** Checks saveToMap() function. **/
private static void testToMap() {
TextGenerator current = new TextGenerator("input2.txt");
try {
TreeMap<String, ArrayList<WordTuple>> data = current.saveToMap();
for (String item : data.keySet()) {
ArrayList<WordTuple> currentList = data.get(item);
for (WordTuple tup : currentList) {
System.out.println(item + " " + tup.getword() + " "
+ tup.getNumber());
}
}
} catch (IOException ex){
}
}
/** Checks saveToList() function. **/
private static void testingSaveToList() {
TextGenerator current = new TextGenerator("input2.txt");
try {
ArrayList<Triple> result = current.saveToList();
for (Triple item : result) {
System.out.println("Pred is: " + item.getPredecessor() + ", " +
"Succ is: " + item.getSuccessor() + ", " +
"# of Occurances: " + item.getNumber());
}
} catch(IOException exp) {
}
}
/** Checks saveToList() for an input file that doesn't
* have any data in it.
**/
private static void noElemSaveToList() {
TextGenerator current = new TextGenerator("input.txt");
try {
ArrayList<Triple> result = current.saveToList();
if (result == null) {
System.out.println("Checking Error 002");
}
} catch (IOException ex) {
}
}
/** Checks saveToList() function for an input file that
* contains only 1 word in it. **/
private static void oneElemSaveToList() {
TextGenerator current = new TextGenerator("input1.txt");
try {
ArrayList<Triple> result = current.saveToList();
for (Triple item : result) {
System.out.println("Pred is: " + item.getPredecessor() + ", " +
"Succ is: " + item.getSuccessor() + ", " +
"% of Occurances: " + item.getNumber());
}
} catch(IOException exp) {
}
}
/** Checks textToData() function. **/
private static void testTextToData() {
TextGenerator current = new TextGenerator("input2.txt");
try {
TreeMap<String, Stats> answer = current.textToData();
for (String item : answer.keySet()) {
Stats currentStats = answer.get(item);
ArrayList<WordTuple> massive = currentStats.getArray();
for (WordTuple tup : massive) {
System.out.println("Word is: " + item + ", Succ is: "
+ tup.getword() + ", Successor's # is: "+ tup.getNumber() +
", sigma is: " + currentStats.getSigma());
}
}
} catch (IOException exp) { }
}
/** Tests generateText() function for Martin Luther King's
* "I Have a Dream Speech" text.
**/
private static void testingGenerator() {
TextGenerator current = new TextGenerator("input2.txt");
try {
current.generateText(2000);
} catch( IOException exp) {
}
}
/** Tests generateText() function for Shakespeare's "Hamlet"
* text.
**/
private static void secondTestGenerator() {
TextGenerator current = new TextGenerator("input3.txt");
try {
current.generateText(40000);
} catch( IOException exp) {
}
}
} | 27.3875 | 68 | 0.644683 |
dd2d7883c8c0757ecbf8d0dbe68c1c2c4d67e2fd | 2,027 | package com.lf.mp.conf;
import com.github.lfopenjavaswagger2word.util.GenerateDocxUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import java.io.IOException;
/**
* 项目初始化后:调用Swagger2 接口获取JSON文档
*/
@Component
@Slf4j
public class SpringInit implements ApplicationRunner {
private static final CloseableHttpClient httpclient = HttpClients.createDefault();
@Value("${server.port}")
private String port;
@Override
public void run(ApplicationArguments args) throws Exception {
String uri = "http://127.0.0.1:" + port + "/v2/api-docs";
log.info("访问:{}", uri);
HttpGet httpget = new HttpGet(uri);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpget);
} catch (IOException e1) {
e1.printStackTrace();
}
String result = null;
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
result = EntityUtils.toString(entity);
log.info("结果:{}", result != null ? "success" : "fail!");
// TextUtil.write("./swagger/file.json", result);
boolean b = GenerateDocxUtils.generateFileByJSON(result,null);
System.err.println(b);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
| 32.693548 | 86 | 0.640355 |
411414ca5703ef9dd9d0d797335d799df8d1045e | 4,495 | /**
* Copyright 2016 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
package com.github.ambry.network;
import com.codahale.metrics.MetricRegistry;
import com.github.ambry.commons.SSLFactory;
import com.github.ambry.commons.TestSSLUtils;
import com.github.ambry.config.SSLConfig;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.util.Random;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class SSLBlockingChannelTest {
private static SSLFactory sslFactory;
private static SSLConfig clientSSLConfig;
private static SSLSocketFactory sslSocketFactory;
private static EchoServer sslEchoServer;
private static String hostName = "localhost";
private static int sslPort = 18284;
/**
* Run only once for all tests
*/
@BeforeClass
public static void initializeTests() throws Exception {
File trustStoreFile = File.createTempFile("truststore", ".jks");
SSLConfig sslConfig =
new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.SERVER, trustStoreFile, "server"));
clientSSLConfig =
new SSLConfig(TestSSLUtils.createSslProps("DC1,DC2,DC3", SSLFactory.Mode.CLIENT, trustStoreFile, "client"));
sslFactory = SSLFactory.getNewInstance(sslConfig);
sslEchoServer = new EchoServer(sslFactory, sslPort);
sslEchoServer.start();
//client
sslFactory = SSLFactory.getNewInstance(clientSSLConfig);
SSLContext sslContext = sslFactory.getSSLContext();
sslSocketFactory = sslContext.getSocketFactory();
}
/**
* Run only once for all tests
*/
@AfterClass
public static void finalizeTests() throws Exception {
int serverExceptionCount = sslEchoServer.getExceptionCount();
assertEquals(serverExceptionCount, 0);
sslEchoServer.close();
}
@Before
public void setup() throws Exception {
}
@After
public void teardown() throws Exception {
}
@Test
public void testSendAndReceive() throws Exception {
BlockingChannel channel =
new SSLBlockingChannel(hostName, sslPort, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory,
clientSSLConfig);
sendAndReceive(channel);
channel.disconnect();
}
@Test
public void testRenegotiation() throws Exception {
BlockingChannel channel =
new SSLBlockingChannel(hostName, sslPort, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory,
clientSSLConfig);
sendAndReceive(channel);
sslEchoServer.renegotiate();
sendAndReceive(channel);
channel.disconnect();
}
@Test
public void testWrongPortConnection() throws Exception {
BlockingChannel channel =
new SSLBlockingChannel(hostName, sslPort + 1, new MetricRegistry(), 10000, 10000, 10000, 2000, sslSocketFactory,
clientSSLConfig);
try {
// send request
channel.connect();
fail("should have thrown!");
} catch (IOException e) {
}
}
private void sendAndReceive(BlockingChannel channel) throws Exception {
long blobSize = 1028;
byte[] bytesToSend = new byte[(int) blobSize];
new Random().nextBytes(bytesToSend);
ByteBuffer byteBufferToSend = ByteBuffer.wrap(bytesToSend);
byteBufferToSend.putLong(0, blobSize);
BoundedByteBufferSend bufferToSend = new BoundedByteBufferSend(byteBufferToSend);
// send request
channel.connect();
channel.send(bufferToSend);
// receive response
InputStream streamResponse = channel.receive().getInputStream();
DataInputStream input = new DataInputStream(streamResponse);
byte[] bytesReceived = new byte[(int) blobSize - 8];
input.readFully(bytesReceived);
for (int i = 0; i < blobSize - 8; i++) {
Assert.assertEquals(bytesToSend[8 + i], bytesReceived[i]);
}
}
}
| 32.572464 | 120 | 0.728365 |
4bb8d8152091a299d0badb9393fd44dbd4622bb9 | 184 | package org.jbehave.examples.core.steps;
import java.util.HashMap;
import java.util.Map;
public class MyContext {
Map<String,Object> variables = new HashMap<String, Object>();
}
| 16.727273 | 62 | 0.75 |
8015476299ef693ba1f43d0e93d05fe6402f0701 | 2,760 | /*
Derby - Class org.apache.derby.client.net.OpenSocketAction
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.derby.client.net;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedExceptionAction;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.SocketFactory;
import javax.net.ssl.SSLSocketFactory;
import org.apache.derby.jdbc.BasicClientDataSource40;
class OpenSocketAction implements PrivilegedExceptionAction<Socket> {
private String server_;
private int port_;
private int clientSSLMode_;
OpenSocketAction(String server, int port, int clientSSLMode) {
server_ = server;
port_ = port;
clientSSLMode_ = clientSSLMode;
}
@Override
public Socket run()
throws UnknownHostException,
IOException,
NoSuchAlgorithmException,
KeyManagementException,
NoSuchProviderException,
KeyStoreException,
UnrecoverableKeyException,
CertificateException
{
SocketFactory sf;
switch (clientSSLMode_) {
case BasicClientDataSource40.SSL_BASIC:
sf = NaiveTrustManager.getSocketFactory();
break;
case BasicClientDataSource40.
SSL_PEER_AUTHENTICATION:
sf = (SocketFactory)SSLSocketFactory.getDefault();
break;
case BasicClientDataSource40.SSL_OFF:
sf = SocketFactory.getDefault();
break;
default:
// Assumes cleartext for undefined values
sf = SocketFactory.getDefault();
break;
}
return sf.createSocket(server_, port_);
}
}
| 33.658537 | 75 | 0.702899 |
9b90caa174a17136e38fa1b653820007c3417ecf | 3,420 | package com.wolper.config;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.BeanNameViewResolver;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import java.io.IOException;
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = { "com.wolper.controller" })
@PropertySource("classpath:config.properties")
@EnableAsync
public class WebConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
//static resource handler
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/public/**").addResourceLocations("/WEB-INF/public/");
registry.addResourceHandler("/private/**").addResourceLocations("/WEB-INF/private/");
}
//beanName resolver
@Bean
public ViewResolver beanNameViewResolver() {
BeanNameViewResolver resolver = new BeanNameViewResolver();
resolver.setOrder(1);
return resolver;
}
//thymeleaf resolver
@Bean
public ViewResolver viewResolver() {
ThymeleafViewResolver resolver = new ThymeleafViewResolver();
resolver.setTemplateEngine(templateEngine());
resolver.setCharacterEncoding("UTF-8");
resolver.setOrder(10);
return resolver;
}
//thymeleaf engine
@Bean
public TemplateEngine templateEngine() {
SpringTemplateEngine engine = new SpringTemplateEngine();
engine.setEnableSpringELCompiler(true);
engine.setTemplateResolver(templateResolver());
return engine;
}
//thymeleaf template resolver
private ITemplateResolver templateResolver() {
SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
resolver.setApplicationContext(applicationContext);
resolver.setPrefix("/WEB-INF/private/");
resolver.setTemplateMode(TemplateMode.HTML);
return resolver;
}
@Bean
public MultipartResolver multipartResolver() throws IOException {
return new StandardServletMultipartResolver();
}
} | 36 | 93 | 0.781871 |
40dfb12527f6e24ad0f6800bcf53fea36e67c126 | 1,530 | package com.aspose.words.examples.programming_documents.bookmarks;
import com.aspose.words.Bookmark;
import com.aspose.words.*;
import com.aspose.words.Row;
import com.aspose.words.SaveFormat.*;
import com.aspose.words.examples.Utils;
public class InsertBookmarksWithWhiteSpaces
{
/**
* The main entry point for the application.
*/
public static void main(String[] args) throws Exception {
//ExStart:InsertBookmarksWithWhiteSpaces
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertBookmarksWithWhiteSpaces.class);
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.startBookmark("My Bookmark");
builder.writeln("Text inside a bookmark.");
builder.startBookmark("Nested Bookmark");
builder.writeln("Text inside a NestedBookmark.");
builder.endBookmark("Nested Bookmark");
builder.writeln("Text after Nested Bookmark.");
builder.endBookmark("My Bookmark");
PdfSaveOptions options = new PdfSaveOptions();
options.getOutlineOptions().getBookmarksOutlineLevels().add("My Bookmark", 1);
options.getOutlineOptions().getBookmarksOutlineLevels().add("Nested Bookmark", 2);
dataDir = dataDir + "Insert.Bookmarks_out_.pdf";
doc.save(dataDir, options);
System.out.println("\nBookmarks with white spaces inserted successfully.\nFile saved at " + dataDir);
//ExEnd:InsertBookmarksWithWhiteSpaces
}
} | 34 | 109 | 0.70719 |
6d26f5e9bea0cc3012b7715611442896c442c5d4 | 629 | package pravin.rv.quizzz.service.accesscontrol;
import org.springframework.stereotype.Service;
import pravin.rv.quizzz.exceptions.UnauthorizedActionException;
import pravin.rv.quizzz.model.AuthenticatedUser;
import pravin.rv.quizzz.model.Quiz;
@Service("AccessControlQuiz")
public class AccessControlServiceQuiz extends AccessControlServiceUserOwned<Quiz> {
/*
* As long as the user is authenticated, it can create a Quiz.
*/
@Override
public void canUserCreateObject(AuthenticatedUser user, Quiz object) throws UnauthorizedActionException {
if (user == null) {
throw new UnauthorizedActionException();
}
}
}
| 27.347826 | 106 | 0.796502 |
9afb2f28203cde4517a318f65a965a5ad5cd5d91 | 892 | /*
* Copyright (c) 2013 EMC Corporation
* All Rights Reserved
*/
package com.emc.storageos.coordinator.client.model;
import com.emc.storageos.svcs.errorhandling.resources.APIException;
/**
* Product name class
*
* Product name is initialized by bean file. It is used
* SoftwareVersion and the whole upgrade machinery depends on this name
* e.g. "vipr"
*/
public class ProductName {
private static String _name;
protected ProductName() {
}
public void setName(String name) {
// This method is only called in test cases and when Spring initialization, safe to suppress
_name = name; // NOSONAR("findbugs:ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD")
}
public static String getName() {
if (_name == null) {
throw APIException.internalServerErrors.targetIsNullOrEmpty("product name");
}
return _name;
}
}
| 26.235294 | 100 | 0.689462 |
311a51371a02905babd1b3eb2daf8d63d998621b | 2,415 | package mage.cards.i;
import mage.abilities.Ability;
import mage.abilities.common.SpellCastAllTriggeredAbility;
import mage.abilities.costs.Cost;
import mage.abilities.effects.OneShotEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.FilterSpell;
import mage.game.Game;
import mage.game.stack.StackObject;
import mage.players.Player;
import mage.util.ManaUtil;
import java.util.UUID;
/**
* @author emerald000
*/
public final class InTheEyeOfChaos extends CardImpl {
private static final FilterSpell filter = new FilterSpell("an instant spell");
static {
filter.add(CardType.INSTANT.getPredicate());
}
public InTheEyeOfChaos(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{2}{U}");
addSuperType(SuperType.WORLD);
// Whenever a player casts an instant spell, counter it unless that player pays {X}, where X is its converted mana cost.
this.addAbility(new SpellCastAllTriggeredAbility(Zone.BATTLEFIELD, new InTheEyeOfChaosEffect(), filter, false, SetTargetPointer.SPELL));
}
public InTheEyeOfChaos(final InTheEyeOfChaos card) {
super(card);
}
@Override
public InTheEyeOfChaos copy() {
return new InTheEyeOfChaos(this);
}
}
class InTheEyeOfChaosEffect extends OneShotEffect {
InTheEyeOfChaosEffect() {
super(Outcome.Detriment);
this.staticText = "counter it unless that player pays {X}, where X is its converted mana cost";
}
InTheEyeOfChaosEffect(final InTheEyeOfChaosEffect effect) {
super(effect);
}
@Override
public InTheEyeOfChaosEffect copy() {
return new InTheEyeOfChaosEffect(this);
}
@Override
public boolean apply(Game game, Ability source) {
StackObject spell = game.getStack().getStackObject(targetPointer.getFirst(game, source));
if (spell != null) {
Player player = game.getPlayer(spell.getControllerId());
if (player != null) {
Cost cost = ManaUtil.createManaCost(spell.getConvertedManaCost(), true);
if (!cost.pay(source, game, source, player.getId(), false)) {
game.getStack().counter(spell.getId(), source, game);
}
return true;
}
}
return false;
}
}
| 30.1875 | 144 | 0.675362 |
881bfc24d12109bd63e08d352506d367bab84e3b | 1,892 | /*
* Copyright 2016-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.lettuce.core.dynamic;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import javax.inject.Inject;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import io.lettuce.core.TestSupport;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;
import io.lettuce.test.LettuceExtension;
/**
* @author Mark Paluch
*/
@ExtendWith(LettuceExtension.class)
class RedisCommandsAsyncIntegrationTests extends TestSupport {
private final RedisCommands<String, String> redis;
@Inject
RedisCommandsAsyncIntegrationTests(StatefulRedisConnection<String, String> connection) {
this.redis = connection.sync();
}
@Test
void async() {
RedisCommandFactory factory = new RedisCommandFactory(redis.getStatefulConnection());
MultipleExecutionModels api = factory.getCommands(MultipleExecutionModels.class);
Future<String> set = api.set(key, value);
assertThat(set).isInstanceOf(CompletableFuture.class);
}
static interface MultipleExecutionModels extends Commands {
Future<String> set(String key, String value);
}
}
| 31.016393 | 93 | 0.7537 |
54688c430ac8840dca9222bc3def8a3661d5d764 | 311 | package com.haulmont.yarg.util.converter;
/**
* Converts parameters from string to object and from object to string
*/
public interface ObjectToStringConverter {
String convertToString(Class parameterClass, Object paramValue);
Object convertFromString(Class parameterClass, String paramValueStr);
}
| 28.272727 | 73 | 0.794212 |
68d70096c159a5dc2011dba4a2aa8d9e473edb18 | 4,910 | /*
* Copyright (c) 2016 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.oauth.as.webauthz;
import java.util.Optional;
import org.apache.logging.log4j.Logger;
import com.nimbusds.oauth2.sdk.AuthorizationErrorResponse;
import com.nimbusds.oauth2.sdk.ErrorObject;
import com.nimbusds.oauth2.sdk.OAuth2Error;
import com.nimbusds.oauth2.sdk.http.HTTPResponse;
import pl.edu.icm.unity.base.utils.Log;
import pl.edu.icm.unity.engine.api.authn.InvocationContext;
import pl.edu.icm.unity.engine.api.authn.LoginSession;
import pl.edu.icm.unity.engine.api.idp.EntityInGroup;
import pl.edu.icm.unity.engine.api.idp.IdPEngine;
import pl.edu.icm.unity.engine.api.translation.ExecutionFailException;
import pl.edu.icm.unity.engine.api.translation.out.TranslationResult;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.exceptions.IllegalGroupValueException;
import pl.edu.icm.unity.oauth.as.OAuthASProperties;
import pl.edu.icm.unity.oauth.as.OAuthAuthzContext;
import pl.edu.icm.unity.oauth.as.OAuthErrorResponseException;
import pl.edu.icm.unity.oauth.as.OAuthSystemAttributesProvider.GrantFlow;
import pl.edu.icm.unity.types.basic.EntityParam;
import pl.edu.icm.unity.types.basic.IdentityParam;
import pl.edu.icm.unity.types.translation.TranslationProfile;
/**
* Wraps {@link IdPEngine} with code used by OAuth AS. In the first place provides standard error handling.
*
* @author K. Benedyczak
*/
public class OAuthIdPEngine
{
private static final Logger log = Log.getLogger(Log.U_SERVER_OAUTH, OAuthIdPEngine.class);
private IdPEngine idpEngine;
public OAuthIdPEngine(IdPEngine idpEngine)
{
this.idpEngine = idpEngine;
}
public TranslationResult getUserInfo(OAuthAuthzContext ctx) throws OAuthErrorResponseException
{
try
{
return getUserInfoUnsafe(ctx);
} catch (ExecutionFailException e)
{
log.debug("Authentication failed due to profile's decision, returning error");
ErrorObject eo = new ErrorObject("access_denied",
e.getMessage(), HTTPResponse.SC_FORBIDDEN);
AuthorizationErrorResponse oauthResponse = new AuthorizationErrorResponse(ctx.getReturnURI(),
eo, ctx.getRequest().getState(), ctx.getRequest().impliedResponseMode());
throw new OAuthErrorResponseException(oauthResponse, true);
} catch (IllegalGroupValueException igve)
{
log.debug("Entity trying to access OAuth resource is not a member of required group");
ErrorObject eo = new ErrorObject("access_denied",
"Not a member of required group " + ctx.getUsersGroup(),
HTTPResponse.SC_FORBIDDEN);
AuthorizationErrorResponse oauthResponse = new AuthorizationErrorResponse(ctx.getReturnURI(),
eo, ctx.getRequest().getState(), ctx.getRequest().impliedResponseMode());
throw new OAuthErrorResponseException(oauthResponse, true);
} catch (Exception e)
{
log.error("Engine problem when handling client request", e);
//we kill the session as the user may want to log as different user if has access to several entities.
AuthorizationErrorResponse oauthResponse = new AuthorizationErrorResponse(ctx.getReturnURI(),
OAuth2Error.SERVER_ERROR, ctx.getRequest().getState(),
ctx.getRequest().impliedResponseMode());
throw new OAuthErrorResponseException(oauthResponse, true);
}
}
public IdentityParam getIdentity(TranslationResult userInfo, String subjectIdentityType)
{
for (IdentityParam id: userInfo.getIdentities())
if (subjectIdentityType.equals(id.getTypeId()))
return id;
throw new IllegalStateException("There is no " + subjectIdentityType + " identity "
+ "for the authenticated user, sub claim can not be created. "
+ "Probably the endpoint is misconfigured.");
}
private TranslationResult getUserInfoUnsafe(OAuthAuthzContext ctx) throws EngineException
{
LoginSession ae = InvocationContext.getCurrent().getLoginSession();
String flow = ctx.getRequest().getResponseType().impliesCodeFlow()
? GrantFlow.authorizationCode.toString()
: GrantFlow.implicit.toString();
EntityInGroup requesterEntity = new EntityInGroup(
ctx.getConfig().getValue(OAuthASProperties.CLIENTS_GROUP),
new EntityParam(ctx.getClientEntityId()));
return getUserInfoUnsafe(ae.getEntityId(), ctx.getRequest().getClientID().getValue(),
Optional.of(requesterEntity), ctx.getUsersGroup(),
ctx.getTranslationProfile() ,
flow, ctx.getConfig());
}
public TranslationResult getUserInfoUnsafe(long entityId, String clientId,
Optional<EntityInGroup> requesterEntity,
String userGroup, TranslationProfile translationProfile, String flow,
OAuthASProperties config) throws EngineException
{
return idpEngine.obtainUserInformationWithEnrichingImport(
new EntityParam(entityId), userGroup, translationProfile,
clientId, requesterEntity,
"OAuth2", flow, true, config);
}
}
| 40.916667 | 107 | 0.7778 |
91e1199af1fa720fa960da48e0424f7a1831ee10 | 689 | import java.io.*;
import java.text.DecimalFormat;
public class Main {
public static void main(String args[]) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader (System.in));
DecimalFormat df = new DecimalFormat("0.00");
double salario, vendas;
String AUX, nome;
nome = input.readLine();
salario = Double.parseDouble(input.readLine());
vendas = Double.parseDouble(input.readLine());
salario = salario + (vendas * 0.15);
AUX = df.format(salario);
AUX = AUX.replaceAll(",", ".");
System.out.println("TOTAL = R$ " + AUX);
}
} | 29.956522 | 85 | 0.584906 |
e9cce54138297e414fea0d583a7cbf4a652d8b95 | 7,096 | package com.optimove.sdk.optimove_sdk.optitrack;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.google.gson.Gson;
import com.optimove.sdk.optimove_sdk.main.LifecycleObserver;
import com.optimove.sdk.optimove_sdk.main.sdk_configs.configs.OptitrackConfigs;
import com.optimove.sdk.optimove_sdk.main.tools.networking.HttpClient;
import com.optimove.sdk.optimove_sdk.main.tools.opti_logger.OptiLoggerStreamsContainer;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import static com.optimove.sdk.optimove_sdk.main.OptistreamEventBuilder.Constants.CATEGORY_OPTIPUSH;
public class OptistreamHandler implements LifecycleObserver.ActivityStopped {
@NonNull
private HttpClient httpClient;
@NonNull
private LifecycleObserver lifecycleObserver;
@NonNull
private OptistreamPersistanceAdapter optistreamPersistanceAdapter;
@NonNull
private OptitrackConfigs optitrackConfigs;
@NonNull
private ScheduledExecutorService singleThreadScheduledExecutor;
@NonNull
private Gson optistreamGson;
@Nullable
private ScheduledFuture timerDispatchFuture;
//accessed ONLY by the single thread of the executor
private boolean dispatchRequestWaitsForResponse = false;
private boolean initialized = false;
public final static class Constants {
public static final int EVENT_BATCH_LIMIT = 100;
public static final int DISPATCH_INTERVAL_IN_SECONDS = 30;
}
public OptistreamHandler(@NonNull HttpClient httpClient,
@NonNull LifecycleObserver lifecycleObserver,
@NonNull OptistreamPersistanceAdapter optistreamPersistanceAdapter,
@NonNull OptitrackConfigs optitrackConfigs) {
this.httpClient = httpClient;
this.lifecycleObserver = lifecycleObserver;
this.optistreamPersistanceAdapter = optistreamPersistanceAdapter;
this.optitrackConfigs = optitrackConfigs;
this.singleThreadScheduledExecutor = Executors.newSingleThreadScheduledExecutor();
this.optistreamGson = new Gson();
}
private synchronized void ensureInit() {
if (!initialized) {
//this will not cause a leak because this component is tied to the app context
this.initialized = true;
this.lifecycleObserver.addActivityStoppedListener(this);
this.scheduleTheNextDispatch();
}
}
public void reportEvents(List<OptistreamEvent> optistreamEvents) {
this.ensureInit();
try {
singleThreadScheduledExecutor.submit(() -> {
boolean immediateEventFound = false;
for (OptistreamEvent optistreamEvent: optistreamEvents) {
optistreamPersistanceAdapter.insertEvent(optistreamGson.toJson(optistreamEvent));
if (optistreamEvent.getMetadata().isRealtime() || optistreamEvent.getCategory().equals(CATEGORY_OPTIPUSH)) {
immediateEventFound = true;
}
}
if (immediateEventFound) {
if (timerDispatchFuture != null) {
timerDispatchFuture.cancel(false);
}
dispatchBulkIfExists();
}
});
} catch (Throwable throwable) {
OptiLoggerStreamsContainer.error("Error while submitting a command - %s", throwable.getMessage());
}
}
private void dispatchBulkIfExists(){
if (dispatchRequestWaitsForResponse) {
return; //protects from sending same events twice
}
OptistreamDbHelper.EventsBulk eventsBulk = optistreamPersistanceAdapter.getFirstEvents(Constants.EVENT_BATCH_LIMIT);
if (eventsBulk == null) {
scheduleTheNextDispatch();
return;
}
List<String> eventJsons = eventsBulk.getEventJsons();
if (eventJsons != null && !eventJsons.isEmpty()) {
try {
JSONArray jsonArrayToDispatch = new JSONArray();
for (String eventJson: eventJsons) {
jsonArrayToDispatch.put(new JSONObject(eventJson));
}
dispatchRequestWaitsForResponse = true;
httpClient.postJsonArray(optitrackConfigs.getOptitrackEndpoint(), jsonArrayToDispatch)
.errorListener(error -> {
OptiLoggerStreamsContainer.error("Events dispatching failed - %s",
error.getMessage());
// some error occurred, try again in the next dispatch
dispatchRequestWaitsForResponse = false;
scheduleTheNextDispatch();
})
.successListener(response -> {
try {
singleThreadScheduledExecutor.submit(() -> {
optistreamPersistanceAdapter.removeEvents(eventsBulk.getLastId());
dispatchRequestWaitsForResponse = false;
dispatchBulkIfExists();
});
} catch (Throwable throwable) {
OptiLoggerStreamsContainer.error("Error while submitting a command - %s", throwable.getMessage());
}
})
.send();
} catch (Throwable e) {
dispatchRequestWaitsForResponse = false;
OptiLoggerStreamsContainer.error("Events dispatching failed - %s",
e.getMessage());
}
} else {
// Schedule another dispatch all if we are done dispatching
dispatchRequestWaitsForResponse = false;
scheduleTheNextDispatch();
}
}
private void scheduleTheNextDispatch(){
try {
this.timerDispatchFuture = this.singleThreadScheduledExecutor.schedule(this::dispatchBulkIfExists,
Constants.DISPATCH_INTERVAL_IN_SECONDS, TimeUnit.SECONDS);
} catch (Throwable e) {
OptiLoggerStreamsContainer.error("Failed to schedule another dispatch - %s",
e.getMessage());
}
}
@Override
public void activityStopped() {
// Stop the scheduled dispatch if exists
if (timerDispatchFuture != null) {
timerDispatchFuture.cancel(false);
}
try {
singleThreadScheduledExecutor.submit(this::dispatchBulkIfExists);
} catch (Throwable throwable) {
OptiLoggerStreamsContainer.error("Error while submitting a dispatch command - %s", throwable.getMessage());
}
}
}
| 42.491018 | 130 | 0.621195 |
5a558607790f88d7336922d8b1c3c056cb69afe2 | 331 | package com.shyam0507.github.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import com.shyam0507.github.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}
| 27.583333 | 67 | 0.8429 |
b7ca6774c6d1e9ba09ffcfed623578ff9313dd33 | 654 | package org.qfox.jestful.core.io;
import org.qfox.jestful.core.Response;
import java.io.IOException;
import java.io.InputStream;
/**
* <p>
* Description:
* </p>
* <p>
* <p>
* Company: 广州市俏狐信息科技有限公司
* </p>
*
* @author Payne [email protected]
* @date 2016年5月10日 下午5:52:27
* @since 1.0.0
*/
public class ResponseLazyInputStream extends LazyInputStream {
private final Response response;
public ResponseLazyInputStream(Response response) {
super();
this.response = response;
}
@Override
protected InputStream getInputStream() throws IOException {
return response.getResponseInputStream();
}
}
| 18.685714 | 63 | 0.678899 |
dbc16ffc3c99dfb7298e71f2ce2ead4a47626234 | 1,634 | package org.danielpacker.restapi.service;
import java.util.DoubleSummaryStatistics;
// This class is a simple POJO for display in the controller.
// It is updated by the Statistics singleton.
public class StatisticsView {
private long count = 0;
private double sum = 0.0;
private double avg = 0.0;
private double min = 0.0;
private double max = 0.0;
public StatisticsView() {
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public double getSum() {
return sum;
}
public void setSum(double sum) {
this.sum = sum;
}
public double getAvg() {
return avg;
}
public void setAvg(double avg) {
this.avg = avg;
}
public double getMin() {
return min;
}
public void setMin(double min) {
this.min = min;
}
public double getMax() {
return max;
}
public void setMax(double max) {
this.max = max;
}
// Convert the stats summary to stats for display.
public void refresh(DoubleSummaryStatistics totalStats) {
setSum(totalStats.getSum());
setCount(totalStats.getCount());
setAvg(totalStats.getAverage());
// When this renders to JSON, Infinity should be represented as 0.
if (totalStats.getMin() == Double.POSITIVE_INFINITY)
setMin(0);
else
setMin(totalStats.getMin());
if (totalStats.getMax() == Double.NEGATIVE_INFINITY)
setMax(0);
else
setMax(totalStats.getMax());
}
}
| 22.081081 | 74 | 0.593023 |
6f420d85e33fb8f27148edf26620c8e9daa07afe | 623 | package com.mobileteknoloji.runners;
import io.cucumber.junit.Cucumber;
import io.cucumber.junit.CucumberOptions;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(
features = "@target/rerun.txt",
glue = "com/mobileteknoloji/step_definitions",
// dryRun = false,
plugin = {
"json:target/json-reports/cucumber.json",
"html:target/FailedScenarios_cucumber/",
//"return:target/rerun.txt"
}
)
public class FailedScenarios {
//in this class,if there are failed scenarios,this class run failed scenarios
}
| 23.961538 | 81 | 0.661316 |
76595193757a91e0e607819676fccd75ef98a1eb | 202 | package authoring.gui.cartography;
/**
* Delta class to help with dragging.
*
* @author Harry Guo, Aditya Srinivasan, Nick Lockett, Arjun Desai
*
*/
public class Delta {
double x;
double y;
}
| 15.538462 | 66 | 0.688119 |
ddd6d50ba52f3b489421e1ff365c7c8c9d880fc8 | 3,121 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.requestitem;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dspace.content.Item;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.I18nUtil;
import org.dspace.eperson.EPerson;
import org.dspace.eperson.service.EPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import java.sql.SQLException;
/**
* RequestItem strategy to allow DSpace support team's helpdesk to receive requestItem request
* With this enabled, then the Item author/submitter doesn't receive the request, but the helpdesk instead does.
*
* Failover to the RequestItemSubmitterStrategy, which means the submitter would get the request if there is no specified helpdesk email.
*
* @author Sam Ottenhoff
* @author Peter Dietz
*/
public class RequestItemHelpdeskStrategy extends RequestItemSubmitterStrategy {
private Logger log = Logger.getLogger(RequestItemHelpdeskStrategy.class);
@Autowired(required = true)
protected EPersonService ePersonService;
public RequestItemHelpdeskStrategy() {}
@Override
public RequestItemAuthor getRequestItemAuthor(Context context, Item item) throws SQLException {
boolean helpdeskOverridesSubmitter = ConfigurationManager.getBooleanProperty("request.item.helpdesk.override", false);
String helpDeskEmail = ConfigurationManager.getProperty("mail.helpdesk");
if (helpdeskOverridesSubmitter && StringUtils.isNotBlank(helpDeskEmail)) {
return getHelpDeskPerson(context, helpDeskEmail);
} else {
//Fallback to default logic (author of Item) if helpdesk isn't fully enabled or setup
return super.getRequestItemAuthor(context, item);
}
}
/**
* Return a RequestItemAuthor object for the specified helpdesk email address.
* It makes an attempt to find if there is a matching eperson for the helpdesk address, to use the name,
* Otherwise it falls back to a helpdeskname key in the Messages.props.
* @param context context
* @param helpDeskEmail email
* @return RequestItemAuthor
* @throws SQLException if database error
*/
public RequestItemAuthor getHelpDeskPerson(Context context, String helpDeskEmail) throws SQLException{
EPerson helpdeskEPerson = null;
context.turnOffAuthorisationSystem();
helpdeskEPerson = ePersonService.findByEmail(context, helpDeskEmail);
context.restoreAuthSystemState();
if(helpdeskEPerson != null) {
return new RequestItemAuthor(helpdeskEPerson);
} else {
String helpdeskName = I18nUtil.getMessage(
"org.dspace.app.requestitem.RequestItemHelpdeskStrategy.helpdeskname",
context);
return new RequestItemAuthor(helpdeskName, helpDeskEmail);
}
}
}
| 39.506329 | 137 | 0.735662 |
cd9c9f6c3a5e2277d445a1a4eed105f5fe8ac29c | 3,951 | // Copyright 2015-2020 SWIM.AI 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 swim.http;
import java.nio.ByteBuffer;
import swim.codec.Binary;
import swim.codec.Debug;
import swim.codec.Encoder;
import swim.codec.Format;
import swim.codec.Output;
import swim.codec.OutputBuffer;
import swim.codec.Utf8;
import swim.util.Murmur3;
public final class HttpChunk implements Debug {
private static int hashSeed;
private static HttpChunk last;
final HttpChunkHeader header;
final Encoder<?, ?> content;
public HttpChunk(HttpChunkHeader header, Encoder<?, ?> content) {
this.header = header;
this.content = content;
}
public static HttpChunk last() {
if (last == null) {
last = new HttpChunk(HttpChunkHeader.sentinel(), Encoder.done());
}
return last;
}
public static HttpChunk from(int length, Encoder<?, ?> content) {
final HttpChunkHeader header = HttpChunkHeader.from(length);
return new HttpChunk(header, content);
}
public static HttpChunk from(ByteBuffer data) {
final HttpChunkHeader header = HttpChunkHeader.from(data.remaining());
return new HttpChunk(header, Binary.byteBufferWriter(data));
}
public static HttpChunk from(String text) {
Output<ByteBuffer> output = Utf8.encodedOutput(Binary.byteBufferOutput(text.length()));
output = output.write(text);
final ByteBuffer data = output.bind();
final HttpChunkHeader header = HttpChunkHeader.from(data.remaining());
return new HttpChunk(header, Binary.byteBufferWriter(data));
}
public boolean isEmpty() {
return this.header.isEmpty();
}
public HttpChunkHeader header() {
return this.header;
}
public Encoder<?, ?> content() {
return this.content;
}
public Encoder<?, ?> httpEncoder(HttpWriter http) {
if (this.header.isEmpty()) {
return Utf8.encodedWriter(this.header.httpWriter(http));
} else {
return new HttpChunkEncoder(http, this.header, this.content);
}
}
public Encoder<?, ?> httpEncoder() {
return httpEncoder(Http.standardWriter());
}
public Encoder<?, ?> encodeHttp(OutputBuffer<?> output, HttpWriter http) {
if (this.header.isEmpty()) {
return Utf8.writeEncoded(this.header.httpWriter(http), output);
} else {
return HttpChunkEncoder.encode(output, http, this.header, this.content);
}
}
public Encoder<?, ?> encodeHttp(OutputBuffer<?> output) {
return encodeHttp(output, Http.standardWriter());
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
} else if (other instanceof HttpChunk) {
final HttpChunk that = (HttpChunk) other;
return this.header.equals(that.header) && this.content.equals(that.content);
}
return false;
}
@Override
public int hashCode() {
if (hashSeed == 0) {
hashSeed = Murmur3.seed(HttpChunk.class);
}
return Murmur3.mash(Murmur3.mix(Murmur3.mix(hashSeed,
this.header.hashCode()), this.content.hashCode()));
}
@Override
public void debug(Output<?> output) {
output = output.write("HttpChunk").write('.');
if (header != HttpChunkHeader.sentinel()) {
output = output.write("from").write('(').debug(this.header).write(", ").debug(this.content).write(')');
} else {
output = output.write("last").write('(').write(')');
}
}
@Override
public String toString() {
return Format.debug(this);
}
}
| 29.051471 | 109 | 0.685396 |
26dacba0b593e94fcb772529c84b5159429e1f32 | 2,756 | /* *******************************************************************
* Copyright (c) 2002, 2010 Contributors
* All rights reserved.
* This program and the accompanying materials are made available
* under the terms of the Eclipse Public License v1.0
* which accompanies this distribution and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* PARC initial implementation
* ******************************************************************/
package org.aspectj.weaver.patterns;
import java.io.IOException;
import java.util.Map;
import org.aspectj.util.FuzzyBoolean;
import org.aspectj.weaver.CompressingDataOutputStream;
import org.aspectj.weaver.ResolvedType;
import org.aspectj.weaver.World;
public class NoTypePattern extends TypePattern {
public NoTypePattern() {
super(false, false, new TypePatternList());
}
/*
* (non-Javadoc)
*
* @see org.aspectj.weaver.patterns.TypePattern#couldEverMatchSameTypesAs(org.aspectj.weaver.patterns.TypePattern)
*/
@Override
protected boolean couldEverMatchSameTypesAs(TypePattern other) {
return false;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesExactly(IType)
*/
@Override
protected boolean matchesExactly(ResolvedType type) {
return false;
}
@Override
protected boolean matchesExactly(ResolvedType type, ResolvedType annotatedType) {
return false;
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesInstanceof(IType)
*/
@Override
public FuzzyBoolean matchesInstanceof(ResolvedType type) {
return FuzzyBoolean.NO;
}
@Override
public void write(CompressingDataOutputStream s) throws IOException {
s.writeByte(NO_KEY);
}
/**
* @see org.aspectj.weaver.patterns.TypePattern#matches(IType, MatchKind)
*/
// public FuzzyBoolean matches(IType type, MatchKind kind) {
// return FuzzyBoolean.YES;
// }
/**
* @see org.aspectj.weaver.patterns.TypePattern#matchesSubtypes(IType)
*/
@Override
protected boolean matchesSubtypes(ResolvedType type) {
return false;
}
@Override
public boolean isStar() {
return false;
}
@Override
public String toString() {
return "<nothing>";
}// FIXME AV - bad! toString() cannot be parsed back (not idempotent)
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
return (obj instanceof NoTypePattern);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
return 17 * 37 * 37;
}
@Override
public Object accept(PatternNodeVisitor visitor, Object data) {
return visitor.visit(this, data);
}
@Override
public TypePattern parameterizeWith(Map arg0, World w) {
return this;
}
}
| 23.355932 | 115 | 0.690131 |
9dd881d1c2d13be024ab68fd7a9378f171d5e752 | 876 | package me.yingrui.simple.crawler.configuration.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.List;
import java.util.stream.Collectors;
@Configuration
@ConfigurationProperties(prefix = "wrappers")
public class Wrappers {
private List<WrapperSettings> websites;
public WrapperSettings getWrapper(String website) {
List<WrapperSettings> collect = websites.stream()
.filter(wrapper -> wrapper.getWebsite().equals(website))
.collect(Collectors.toList());
return collect.size() > 0 ? collect.get(0) : null;
}
public List<WrapperSettings> getWebsites() {
return websites;
}
public void setWebsites(List<WrapperSettings> websites) {
this.websites = websites;
}
}
| 28.258065 | 75 | 0.714612 |
e9be0718fbfe2752727f49788b912c681bf3c2f3 | 475 | package com.qfox.network.downloader;
/**
* <p>
* Description:
* </p>
*
* <p>
* Company: 广州市俏狐信息科技有限公司
* </p>
*
* @author yangchangpei [email protected]
*
* @date 2015年8月13日 下午12:20:16
*
* @version 1.0.0
*/
public interface Callback {
void success(AsynchronousDownloader<?> downloader);
void failure(AsynchronousDownloader<?> downloader, Exception exception);
void complete(AsynchronousDownloader<?> downloader, boolean success, Exception exception);
}
| 17.592593 | 91 | 0.701053 |
7f7a2b1d4b7f43cbe56e197b0740752998b30972 | 6,298 | /*
* Copyright (c) 2010-2016. Axon Framework
*
* 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.axonframework.eventhandling.saga.repository;
import org.axonframework.common.IdentifierFactory;
import org.axonframework.eventhandling.saga.AssociationValue;
import org.axonframework.eventhandling.saga.Saga;
import org.axonframework.eventhandling.saga.repository.inmemory.InMemorySagaStore;
import org.axonframework.messaging.unitofwork.CurrentUnitOfWork;
import org.axonframework.messaging.unitofwork.DefaultUnitOfWork;
import org.axonframework.messaging.unitofwork.UnitOfWork;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InOrder;
import java.util.HashSet;
import java.util.Set;
import static java.util.Collections.singleton;
import static org.axonframework.messaging.unitofwork.DefaultUnitOfWork.startAndGet;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Mockito.*;
@SuppressWarnings("unchecked")
public class AnnotatedSagaRepositoryTest {
private AnnotatedSagaRepository<Object> testSubject;
private SagaStore store;
private UnitOfWork<?> currentUnitOfWork;
@Before
public void setUp() throws Exception {
currentUnitOfWork = startAndGet(null);
this.store = spy(new InMemorySagaStore());
this.testSubject = new AnnotatedSagaRepository<>(Object.class, store);
}
@After
public void tearDown() throws Exception {
if (currentUnitOfWork.isActive()) {
currentUnitOfWork.commit();
}
}
@Test
public void testLoadedFromUnitOfWorkAfterCreate() throws Exception {
Saga<Object> saga =
testSubject.createInstance(IdentifierFactory.getInstance().generateIdentifier(), Object::new);
saga.getAssociationValues().add(new AssociationValue("test", "value"));
Saga<Object> saga2 = testSubject.load(saga.getSagaIdentifier());
assertSame(saga, saga2);
currentUnitOfWork.commit();
verify(store, never()).loadSaga(any(), any());
verify(store, never()).updateSaga(any(), any(), any(), any(), any());
verify(store).insertSaga(eq(Object.class), any(), any(), any(), any());
}
@Test
public void testLoadedFromNestedUnitOfWorkAfterCreate() throws Exception {
Saga<Object> saga =
testSubject.createInstance(IdentifierFactory.getInstance().generateIdentifier(), Object::new);
saga.getAssociationValues().add(new AssociationValue("test", "value"));
Saga<Object> saga2 =
startAndGet(null).executeWithResult(() -> testSubject.load(saga.getSagaIdentifier()));
assertSame(saga, saga2);
currentUnitOfWork.commit();
verify(store, never()).loadSaga(any(), any());
verify(store, never()).updateSaga(any(), any(), any(), any(), any());
verify(store).insertSaga(eq(Object.class), any(), any(), any(), anySet());
}
@Test
public void testLoadedFromNestedUnitOfWorkAfterCreateAndStore() throws Exception {
Saga<Object> saga =
testSubject.createInstance(IdentifierFactory.getInstance().generateIdentifier(), Object::new);
saga.getAssociationValues().add(new AssociationValue("test", "value"));
currentUnitOfWork.onPrepareCommit(u -> {
startAndGet(null).execute(() -> {
Saga<Object> saga1 = testSubject.load(saga.getSagaIdentifier());
saga1.getAssociationValues().add(new AssociationValue("second", "value"));
});
});
currentUnitOfWork.commit();
InOrder inOrder = inOrder(store);
Set<AssociationValue> associationValues = new HashSet<>();
associationValues.add(new AssociationValue("test", "value"));
associationValues.add(new AssociationValue("second", "value"));
inOrder.verify(store).insertSaga(eq(Object.class), any(), any(), any(), eq(associationValues));
inOrder.verify(store).updateSaga(eq(Object.class), any(), any(), any(), any());
inOrder.verifyNoMoreInteractions();
}
@Test
public void testLoadedFromUnitOfWorkAfterPreviousLoad() throws Exception {
Saga<Object> preparedSaga =
testSubject.createInstance(IdentifierFactory.getInstance().generateIdentifier(), Object::new);
currentUnitOfWork.commit();
currentUnitOfWork = startAndGet(null);
reset(store);
Saga<Object> saga = testSubject.load(preparedSaga.getSagaIdentifier());
saga.getAssociationValues().add(new AssociationValue("test", "value"));
Saga<Object> saga2 = testSubject.load(preparedSaga.getSagaIdentifier());
assertSame(saga, saga2);
verify(store).loadSaga(eq(Object.class), any());
verify(store, never()).updateSaga(eq(Object.class), any(), any(), any(), any());
currentUnitOfWork.commit();
verify(store).updateSaga(eq(Object.class), any(), any(), any(), any());
verify(store, never()).insertSaga(eq(Object.class), any(), any(), any(), any());
}
@Test
public void testSagaAssociationsVisibleInOtherThreadsBeforeSagaIsCommitted() throws Exception {
String sagaId = "sagaId";
AssociationValue associationValue = new AssociationValue("test", "value");
Thread otherProcess = new Thread(() -> {
UnitOfWork<?> unitOfWork = DefaultUnitOfWork.startAndGet(null);
testSubject.createInstance(sagaId, Object::new).getAssociationValues().add(associationValue);
CurrentUnitOfWork.clear(unitOfWork);
});
otherProcess.start();
otherProcess.join();
assertEquals(singleton(sagaId), testSubject.find(associationValue));
}
}
| 40.896104 | 110 | 0.688314 |
e9abe3e181f3f3644f6e9376a9ca522d1dbc45f1 | 6,292 | package org.moskito.central.connectors.rest;
import com.sun.jersey.api.core.ResourceConfig;
import com.sun.jersey.core.util.Base64;
import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerRequestFilter;
import com.sun.jersey.test.framework.AppDescriptor;
import com.sun.jersey.test.framework.JerseyTest;
import com.sun.jersey.test.framework.WebAppDescriptor;
import org.junit.Test;
import org.moskito.central.Snapshot;
import org.moskito.central.SnapshotMetaData;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.UriInfo;
import java.security.Principal;
import java.util.HashMap;
/**
* Test class for MoSKito Central REST-connector with HTTP basic authentication enabled.
*
* @author Vladyslav Bezuhlyi
*/
public class RESTConnectorHttpBasicAuthTest extends JerseyTest {
/**
* Exposing send method to test the connector.
*/
public static class ExposedRESTConnector extends RESTConnector {
public ExposedRESTConnector() {
super.setConfigurationName("rest-connector-auth");
}
@Override
public void sendData(Snapshot snapshot) {
super.sendData(snapshot);
}
}
@Override
protected AppDescriptor configure() {
return new WebAppDescriptor.Builder("org.moskito.central.connectors.rest;org.codehaus.jackson.jaxrs")
.initParam(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, HttpBasicAuthFilter.class.getName()).build();
}
@Override
protected int getPort(int defaultPort) {
return super.getPort(9988);
}
@Test
public void testHttpBasicAuth() throws InterruptedException {
ExposedRESTConnector connector = new ExposedRESTConnector();
connector.sendData(prepareSnapshot());
Thread.sleep(1000);
}
public Snapshot prepareSnapshot() {
Snapshot snapshot = new Snapshot();
SnapshotMetaData metaData = new SnapshotMetaData();
metaData.setProducerId("prodId");
metaData.setCategory("catId");
metaData.setSubsystem("subSId");
snapshot.setMetaData(metaData);
HashMap<String, String> data = new HashMap<String, String>();
data.put("firstname", "moskito");
data.put("lastname", "central");
snapshot.addSnapshotData("test", data);
snapshot.addSnapshotData("test2", data);
snapshot.addSnapshotData("test3", data);
return snapshot;
}
/**
* HTTP Basic Authentication request filter for {@link com.sun.jersey.test.framework.spi.container.TestContainer}.
* Simulates enabled HTTP basic authentication on server's side.
*/
public static class HttpBasicAuthFilter implements ContainerRequestFilter {
/**
* User login (and role). Should be the same as in rest-connector-auth.json
*/
private final String user = "testlogin";
/**
* User password. Should be the same as in rest-connector-auth.json
*/
private final String password = "testpassword";
/**
* Injectable URI info.
*/
@Context
UriInfo uriInfo;
@Override
public ContainerRequest filter(ContainerRequest request) {
User user = authenticate(request);
request.setSecurityContext(new HttpBasicAuthContext(user));
return request;
}
private User authenticate(ContainerRequest request) {
// Extract authentication credentials
String authentication = request.getHeaderValue(ContainerRequest.AUTHORIZATION);
if (authentication == null) {
throw new WebApplicationException(401);
// Authentication credentials are required
}
if (!authentication.startsWith("Basic ")) {
throw new WebApplicationException(406);
// Additional checks should be done here
// Only HTTP Basic authentication is supported
}
authentication = authentication.substring("Basic ".length());
String[] values = new String(Base64.base64Decode(authentication)).split(":");
if (values.length < 2) {
throw new WebApplicationException(401);
// Invalid syntax for username and password
}
String username = values[0];
String password = values[1];
if ((username == null) || (password == null)) {
throw new WebApplicationException(401);
// Missing username or password
}
// Validate the extracted credentials
User user = null;
if (username.equals(this.user) && password.equals(this.password)) {
user = new User(this.user, this.user);
} else {
throw new WebApplicationException(406);
// Invalid username or password
}
return user;
}
public class HttpBasicAuthContext implements SecurityContext {
private User user;
private Principal principal;
public HttpBasicAuthContext(final User user) {
this.user = user;
this.principal = new Principal() {
public String getName() {
return user.username;
}
};
}
public Principal getUserPrincipal() {
return this.principal;
}
public boolean isUserInRole(String role) {
return (role.equals(user.role));
}
public boolean isSecure() {
return "https".equals(uriInfo.getRequestUri().getScheme());
}
public String getAuthenticationScheme() {
return SecurityContext.BASIC_AUTH;
}
}
public class User {
public String username;
public String role;
public User(String username, String role) {
this.username = username;
this.role = role;
}
}
}
}
| 31.939086 | 123 | 0.611252 |
800790793024387dd0bdbeb526c19f343b5863da | 6,099 | package cn.m1yellow.mypages.excavation.service.impl;
import cn.m1yellow.mypages.common.util.FileUtil;
import cn.m1yellow.mypages.common.util.ObjectUtil;
import cn.m1yellow.mypages.common.util.RedisUtil;
import cn.m1yellow.mypages.common.util.UUIDGenerateUtil;
import cn.m1yellow.mypages.excavation.bo.UserInfoItem;
import cn.m1yellow.mypages.excavation.constant.PlatformInfo;
import cn.m1yellow.mypages.excavation.dto.UserFollowingDto;
import cn.m1yellow.mypages.excavation.entity.UserFollowing;
import cn.m1yellow.mypages.excavation.mapper.UserFollowingMapper;
import cn.m1yellow.mypages.excavation.service.DataExcavateService;
import cn.m1yellow.mypages.excavation.service.UserFollowingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* <p>
* 用户关注表 服务实现类
* </p>
*
* @author M1Yellow
* @since 2021-04-13
*/
@Slf4j
@Service
public class UserFollowingServiceImpl extends ServiceImpl<UserFollowingMapper, UserFollowing> implements UserFollowingService {
@Value("${user.avatar.savedir}")
private String saveDir;
@Autowired
private RedisUtil redisUtil;
/**
* @Resource、@Autowired、@Qualifier的注解注入及区别 在Java代码中可以使用 @Resource 或者 @Autowired 注解方式来进行注入。
* 虽然 @Resource 和 @Autowried 都可以完成依赖注入,但是他们是有区别的。
* @Resource 默认是按照名称来装配注入的,只有当找不到与名称匹配的bean才会按照类型来注入。
* 它有两个属性是比较重要的:
* ①. name: Spring 将 name 的属性值解析为 bean 的名称, 使用 byName 的自动注入策略
* ②. type: Spring 将 type的属性值解析为 bean 的类型,使用 byType 的自动注入策略
* 注: 如果既不指定 name 属性又不指定 type 属性,Spring这时通过反射机制使用 byName 自动注入策略
* @Resource 的装配顺序
* 1. 如果同时指定了 name 属性和 type 属性,那么 Spring 将从容器中找唯一匹配的 bean 进行装配,找不到则抛出异常
* 2. 如果指定了 name 属性值,则从容器中查找名称匹配的 bean 进行装配,找不到则抛出异常
* 3. 如果指定了 type 属性值,则从容器中查找类型匹配的唯一的 bean 进行装配,找不到或者找到多个都会抛出异常
* 4. 如果都不指定,则会自动按照 byName 方式进行装配, 如果没有匹配,则回退一个原始类型进行匹配,如果匹配则自动装配
* @Autowried 默认是按照类型进行装配注入,默认情况下,它要求依赖对象必须存在,如果允许 null 值,可以设置它 required 为false。
* 如果我们想要按名称进行装配的话,可以添加一个 @Qualifier 注解解决。
*/
@Resource(name = "dataOfBiliExcavateService")
private DataExcavateService dataOfBiliExcavateService;
@Resource(name = "dataOfWeiboExcavateService")
private DataExcavateService dataOfWeiboExcavateService;
@Override
public UserInfoItem doExcavate(UserFollowingDto following) {
if (following == null || !following.getIsUser()) {
return null;
}
// 获取、校验用户所属平台的id
String userId = getUserKeyFromMainPage(following);
if (StringUtils.isBlank(userId)) {
log.error("用户主页不符合要求,following id:" + following.getFollowingId());
return null;
}
// 参数封装
Map<String, Object> params = new HashMap<>();
if (StringUtils.isNotBlank(following.getProfilePhoto())) {
params.put("profileOriginalDir", following.getProfilePhoto());
}
String apiUrl = null; // 请求地址模板
String fromUrl = null; // 调整后的请求地址
UserInfoItem userInfoItem = null;
// 设置保存路径为 classpath 下的目录
String saveDirFullPath = FileUtil.getSaveDirFullPath(UserFollowingServiceImpl.class, saveDir);
switch (PlatformInfo.getPlatformInfoByUrl(following.getMainPage())) {
case BILIBILI:
apiUrl = "https://api.bilibili.com/x/space/acc/info?mid=userId&jsonp=jsonp";
fromUrl = apiUrl.replace("userId", userId);
userInfoItem = dataOfBiliExcavateService.singleImageDownloadFromJson(fromUrl, saveDirFullPath, params);
break;
case WEIBO:
//apiUrl = "https://weibo.com/u/userId";
//apiUrl = "https://m.weibo.cn/api/container/getIndex?type=uid&value=userId&containerid=1005056488142313";
apiUrl = "https://m.weibo.cn/api/container/getIndex?type=uid&value=userId";
fromUrl = apiUrl.replace("userId", userId);
userInfoItem = dataOfWeiboExcavateService.singleImageDownloadFromJson(fromUrl, saveDirFullPath, params);
break;
case DOUBAN:
break;
case ZHIHU:
break;
default:
}
return userInfoItem;
}
@Override
public boolean saveUserInfo(UserInfoItem userInfoItem, UserFollowing following) {
boolean isSuc = false;
following.setName(ObjectUtil.getString(userInfoItem.getUserName()));
following.setSignature(ObjectUtil.getString(userInfoItem.getSignature()));
following.setProfilePhoto(ObjectUtil.getString(userInfoItem.getHeadImgPath()));
// 去字符串字段两边空格
ObjectUtil.stringFiledTrim(following);
isSuc = saveOrUpdate(following);
return isSuc;
}
@Override
public String getUserKeyFromMainPage(UserFollowingDto following) {
String userKey = null;
if (following != null && StringUtils.isNotBlank(following.getMainPage())) {
String[] mainPageArr = following.getMainPage().split("/");
if (mainPageArr.length < 2) {
return null;
}
if (following.getIsUser()) {
switch (PlatformInfo.getPlatformInfoByUrl(following.getMainPage())) {
case BILIBILI:
userKey = mainPageArr[mainPageArr.length - 2];
break;
case WEIBO:
userKey = mainPageArr[mainPageArr.length - 1];
break;
case DOUBAN:
break;
case ZHIHU:
break;
default:
}
} else { // 非用户
userKey = UUIDGenerateUtil.getUUID32();
}
}
return userKey;
}
}
| 35.876471 | 127 | 0.657157 |
975b4df477d026e1d39c46a83588f0a90c1e10cd | 686 | package org.zstack.header.console;
import org.zstack.header.message.APIEvent;
/**
* Created with IntelliJ IDEA.
* User: frank
* Time: 11:27 PM
* To change this template use File | Settings | File Templates.
*/
public class APIRequestConsoleAccessEvent extends APIEvent {
private ConsoleInventory inventory;
public APIRequestConsoleAccessEvent() {
super(null);
}
public APIRequestConsoleAccessEvent(String apiId) {
super(apiId);
}
public ConsoleInventory getInventory() {
return inventory;
}
public void setInventory(ConsoleInventory inventory) {
this.inventory = inventory;
}
}
| 22.866667 | 65 | 0.666181 |
656608e5b4406b2bc4fe704758236f3adc8db636 | 2,229 | package org.protempa.proposition.value;
/*
* #%L
* Protempa Framework
* %%
* Copyright (C) 2012 - 2015 Emory University
* %%
* 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 java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import org.apache.commons.lang3.builder.ToStringBuilder;
/**
*
* @author Andrew Post
*/
public class ValueListBuilder<V extends Value> implements ValueBuilder<ValueList<V>> {
private List<V> elements;
public ValueListBuilder() {
}
public ValueListBuilder(ValueList<V> valueList) {
this.elements = new ArrayList<>(valueList);
}
public ValueBuilder<V>[] getElements() {
return (ValueBuilder<V>[]) elements.toArray();
}
public void setElements(ValueBuilder<V>[] elements) {
this.elements = new ArrayList<>();
for (ValueBuilder<V> elt : elements) {
this.elements.add(elt.build());
}
}
@Override
public ValueList<V> build() {
return new ValueList<>(this.elements);
}
@Override
public int hashCode() {
int hash = 7;
hash = 59 * hash + Objects.hashCode(this.elements);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final ValueListBuilder<?> other = (ValueListBuilder<?>) obj;
if (!Objects.equals(this.elements, other.elements)) {
return false;
}
return true;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
| 25.918605 | 86 | 0.628533 |
c0ccec187088ebef99b27adca6ec9627352033db | 7,360 | package com.salesorderapp.backend.ResourceControllers;
import java.util.List;
import java.util.Map;
import com.salesorderapp.backend.daos.CustomerDao;
import com.salesorderapp.backend.daos.OrderLineDao;
import com.salesorderapp.backend.daos.ProductDao;
import com.salesorderapp.backend.daos.SalesOrderDao;
import com.salesorderapp.backend.models.Customer;
import com.salesorderapp.backend.models.OrderLine;
import com.salesorderapp.backend.models.Product;
import com.salesorderapp.backend.models.SalesOrder;
import com.salesorderapp.backend.entities.SalesOrderList;
import com.salesorderapp.backend.entities.SalesOrderEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Shittu on 30/05/2016.
*/
@Controller
@RequestMapping(value="/salesorder")
public class SalesOrderController {
// CREATE
@RequestMapping(value="/create" , method = RequestMethod.POST)
@ResponseBody
public SalesOrderEntity create(
@RequestBody final SalesOrderEntity salesOrderEntity
) {
try {
SalesOrderEntity salesOrder = mSalesOrderDao.getById(salesOrderEntity.getOrderNumber());
if(salesOrder == null) {
// do sales order checks before creating
boolean creditCheck = validateCreditBalance(salesOrderEntity);
boolean productCheck = validateProductQuantity(salesOrderEntity);
// if valid sales make adjustment to affected balances
if (creditCheck && productCheck) {
mSalesOrderDao.create(new SalesOrder(
salesOrderEntity.getOrderNumber(),
String.format(
"(%s) %s",
salesOrderEntity.getCustomer().get("id"),
salesOrderEntity.getCustomer().get("name")
),
salesOrderEntity.getTotalPrice())
);
for (Map<String, Object> productObject : salesOrderEntity.getProducts()) {
mOrderLineDao.create(new OrderLine(
salesOrderEntity.getOrderNumber(),
Long.parseLong((String) productObject.get("id")),
(Double) productObject.get("price"),
(Double) productObject.get("quantity")
));
}
updateCustomerCreditBalance(salesOrderEntity);
updateProductQuantity(salesOrderEntity);
} else {
return null;
}
} else {
mSalesOrderDao.update(new SalesOrder(
salesOrderEntity.getOrderNumber(),
String.format(
"(%s) %s",
salesOrderEntity.getCustomer().get("id"),
salesOrderEntity.getCustomer().get("name")
),
salesOrderEntity.getTotalPrice())
);
for (Map<String, Object> productObject : salesOrderEntity.getProducts()) {
mOrderLineDao.create(new OrderLine(
salesOrderEntity.getOrderNumber(),
Long.parseLong((String) productObject.get("id")),
(Double) productObject.get("price"),
(Double) productObject.get("quantity")
));
}
setCustomerCreditBalance(salesOrderEntity, salesOrderEntity.getTotalPrice() - salesOrder.getTotalPrice());
updateProductQuantity(salesOrderEntity);
}
}
catch(final Exception ex) {
ex.printStackTrace();
return null;
}
return mSalesOrderDao.getById(salesOrderEntity.getOrderNumber());
}
// READ
@RequestMapping(value="/all" , method = RequestMethod.GET)
@ResponseBody
public SalesOrderList getAll() {
try {
return new SalesOrderList(mSalesOrderDao.getAll());
}
catch(final Exception ex) {
ex.printStackTrace();
return null;
}
}
@RequestMapping(value="/", method = RequestMethod.GET)
@ResponseBody
public SalesOrderEntity getSalesOrder(@RequestParam(name="salescode") final long salesCode) {
try {
return mSalesOrderDao.getById(salesCode);
}
catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
//UPDATE
@RequestMapping(value="/update" , method = RequestMethod.PUT)
@ResponseBody
public Boolean update(
final SalesOrder salesOrder
) {
try {
mSalesOrderDao.update(salesOrder);
}
catch(final Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
// DELETE
@RequestMapping(value="/delete", method = RequestMethod.GET)
@ResponseBody
public Boolean delete(@RequestParam(name="ordernumber")final long orderNumber) {
try {
List<OrderLine> orderLines = mOrderLineDao.getBySalesCode(orderNumber);
orderLines.stream().forEach(orderLine -> mOrderLineDao.delete(orderLine));
SalesOrder salesOrder = new SalesOrder(orderNumber);
mSalesOrderDao.delete(salesOrder);
}
catch(Exception ex) {
ex.printStackTrace();
return false;
}
return true;
}
private boolean validateProductQuantity (final SalesOrderEntity salesOrderEntity){
for(Map<String, Object> productObject : salesOrderEntity.getProducts()){
Double quantityAvailable = mProductDao.getById(Long.parseLong((String)productObject.get("id"))).getQuantity();
Double quantityOrdered = (Double)productObject.get("quantity");
if(quantityAvailable <= quantityOrdered){
return false;
}
}
return true;
}
private boolean validateCreditBalance (final SalesOrderEntity salesOrderEntity) {
Customer customer = mCustomerDao.getById(Long.parseLong((String)salesOrderEntity.getCustomer().get("id")));
return salesOrderEntity.getTotalPrice() <= customer.getCreditLimit() - customer.getCurrentCredit();
}
private void updateCustomerCreditBalance (final SalesOrderEntity salesOrderEntity) {
Customer customer = mCustomerDao.getById(Long.parseLong((String)salesOrderEntity.getCustomer().get("id")));
customer.setCurrentCredit(customer.getCurrentCredit() + salesOrderEntity.getTotalPrice());
mCustomerDao.update(customer);
}
private void updateProductQuantity (final SalesOrderEntity salesOrderEntity) {
for(Map<String, Object> productObject : salesOrderEntity.getProducts()){
Product product = mProductDao.getById(Long.parseLong((String)productObject.get("id")));
product.setQuantity(product.getQuantity() - (Double)productObject.get("quantity"));
mProductDao.update(product);
}
}
private void setCustomerCreditBalance (final SalesOrderEntity salesOrderEntity, final Double additionalCredit) {
Customer customer = mCustomerDao.getById(Long.parseLong((String)salesOrderEntity.getCustomer().get("id")));
customer.setCurrentCredit(customer.getCurrentCredit() + additionalCredit);
mCustomerDao.update(customer);
}
// Private fields
@Autowired
private SalesOrderDao mSalesOrderDao;
@Autowired
private ProductDao mProductDao;
@Autowired
private CustomerDao mCustomerDao;
@Autowired
private OrderLineDao mOrderLineDao;
}
| 34.392523 | 116 | 0.692391 |
6e23e5f6a1bf89c67b1a9ef9fb2114078324da45 | 578 | package com.lin.aop.handler;
import com.lin.aop.aspect.JoinPointInfo;
import com.lin.aop.listener.LogTraceListener;
import java.util.List;
/**
* 切点处理器
*
* @author dadiyang
* @since 2019/3/1
*/
public interface JoinPointHandler {
/**
* 切点处理
*
* @param joinPointInfo 切点相关信息
* @return 处理结果
* @throws Throwable 抛出的异常
*/
Object handle(JoinPointInfo joinPointInfo) throws Throwable;
/**
* 设置日志跟踪监听器
*
* @param logTraceListeners 监听器列表
*/
void setLogTraceListeners(List<LogTraceListener> logTraceListeners);
}
| 18.0625 | 72 | 0.66263 |
00b703923e382908007690a4e06c16b1aada4d94 | 4,143 | /*
* TestResult.java
*
* This source file is part of the FoundationDB open source project
*
* Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.apple.foundationdb.test;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
public class TestResult {
private long id;
private Map<String,Map<String,Object>> kpis;
private List<Throwable> errors;
public TestResult(Random r) {
id = Math.abs(r.nextLong());
kpis = new TreeMap<String,Map<String,Object>>(); // Tree map because we will have to print this out.
errors = new ArrayList<Throwable>();
}
public void addKpi(String name, Number value, String units) {
TreeMap<String,Object> kpi = new TreeMap<String,Object>();
kpi.put("value", value);
kpi.put("units", units);
kpis.put(name, kpi);
}
public void addError(Throwable t) {
errors.add(t);
}
public void save(String directory) {
String file = "javaresult-" + id + ".json";
if(directory.length() > 0) {
file = directory + "/" + file;
}
// TODO: Should we use a really JSON library?
StringBuilder outputBuilder = new StringBuilder();
outputBuilder.append('{');
// Add KPIs:
outputBuilder.append("\"kpis\": {");
boolean firstKpi = true;
for (Map.Entry<String,Map<String,Object>> kpi : kpis.entrySet()) {
if (firstKpi) {
firstKpi = false;
} else {
outputBuilder.append(", ");
}
outputBuilder.append("\"");
outputBuilder.append(kpi.getKey());
outputBuilder.append("\": {");
boolean firstEntry = true;
for (Map.Entry<String,Object> entry : kpi.getValue().entrySet()) {
if (firstEntry) {
firstEntry = false;
} else {
outputBuilder.append(", ");
}
outputBuilder.append("\"");
outputBuilder.append(entry.getKey());
outputBuilder.append("\": ");
Object value = entry.getValue();
if (value instanceof String) {
outputBuilder.append("\"");
outputBuilder.append((String)value);
outputBuilder.append("\"");
} else {
outputBuilder.append(value.toString());
}
}
outputBuilder.append("}");
}
outputBuilder.append("}, ");
// Add errors:
outputBuilder.append("\"errors\":[");
boolean firstError = true;
for (Throwable t : errors) {
if (firstError) {
firstError = false;
} else {
outputBuilder.append(", ");
}
StringBuilder msgBuilder = new StringBuilder();
msgBuilder.append(t.getClass().toString());
msgBuilder.append(": ");
msgBuilder.append(t.getMessage()); // Escaping quotes. Yeah, this won't work in the general case....
StackTraceElement[] stackTraceElements = t.getStackTrace();
for (StackTraceElement element : stackTraceElements) {
msgBuilder.append("\n ");
msgBuilder.append(element.toString());
}
outputBuilder.append('"');
outputBuilder.append(msgBuilder.toString()
.replace("\\", "\\\\")
.replace("\"", "\\\"")
.replace("\t", "\\t")
.replace("\r", "\\r")
.replace("\n", "\\n")
.replace("\f", "\\f")
.replace("\b", "\\b")
);
outputBuilder.append('"');
}
outputBuilder.append("]");
outputBuilder.append('}');
try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
writer.write(outputBuilder.toString());
} catch (IOException e) {
System.out.println("Could not write results to file " + file);
throw new RuntimeException("Could not save results: " + e.getMessage(), e);
}
}
}
| 27.805369 | 103 | 0.658219 |
76db35f2abd1b93b03dc5db7de034c621cca67a7 | 437 | package com.voting.sessao.dto;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class SessaoDTO {
private long id;
private long idPauta;
private String abertura;
private String fechamento;
}
| 21.85 | 61 | 0.805492 |
801c17cfe61a6e517e36044982d8c3c40dbed3f5 | 3,186 | /**
* Copyright (c) 2014 SQUARESPACE, 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.squarespace.template;
import java.util.ArrayList;
import java.util.List;
/**
* Mapping of fixed instruction identifiers. Instructions which have variant
* forms (predicates, variable references) are handled separately.
*/
public class InstructionTable {
private static final int HASHMAP_BUCKETS = 32;
private static final StringViewMap<StringView, InstructionType> table = new StringViewMap<>(HASHMAP_BUCKETS);
private static final List<String> symbolList = new ArrayList<>();
/**
* Adds a mapping from the string identifier to the instruction type.
*/
static void add(String str, InstructionType type) {
add(str, type, true);
}
/**
* Adds a mapping from the string identifier to the instruction type.
*/
static void add(String str, InstructionType type, boolean isSymbol) {
table.put(new StringView(str), type);
if (isSymbol) {
symbolList.add(str);
}
}
static {
add(".alternates", InstructionType.ALTERNATES_WITH, false);
add(".ctx", InstructionType.CTXVAR);
add(".end", InstructionType.END);
add(".eval", InstructionType.EVAL);
add(".if", InstructionType.IF);
add(".include", InstructionType.INCLUDE);
add(".inject", InstructionType.INJECT);
add(".macro", InstructionType.MACRO);
add(".meta-left", InstructionType.META_LEFT);
add(".meta-right", InstructionType.META_RIGHT);
add(".newline", InstructionType.NEWLINE);
add(".or", InstructionType.OR_PREDICATE);
add(".repeated", InstructionType.REPEATED, false);
add(".section", InstructionType.SECTION);
add(".space", InstructionType.SPACE);
add(".tab", InstructionType.TAB);
add(".var", InstructionType.BINDVAR);
// Special-case for instructions containing whitespace (yeah).
symbolList.add(".alternates with");
symbolList.add(".repeated section");
}
/**
* Used for debugging the internal table layout.
*/
public static String dump() {
try {
return table.dump();
} catch (Exception e) {
throw new RuntimeException("Error dumping instruction table", e);
}
}
/**
* Returns the instruction table.
*/
public static StringViewMap<StringView, InstructionType> getTable() {
return table;
}
/**
* Returns the instruction type for the given symbol.
*/
public static InstructionType get(StringView symbol) {
return table.get(symbol);
}
/**
* Returns all symbols registered in the table.
*/
public static String[] getSymbols() {
return symbolList.toArray(Constants.EMPTY_ARRAY_OF_STRING);
}
}
| 29.229358 | 111 | 0.695229 |
6ab280e4c16c45b5fc13c39c703bca3712a4e5ab | 350 | package com.revauniversity.revasdpapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class firstyearsdp extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_firstyearsdp);
}
}
| 25 | 56 | 0.771429 |
e1186d56255ac6385fee999c3c1c43556e61c5b7 | 570 | package com.example.xsy.pocketmusic;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* A simple {@link Fragment} subclass.
*/
public class NetMusicListFragment extends Fragment {
public NetMusicListFragment() {
// Required empty public constructor
}
public static NetMusicListFragment newInstance() {
NetMusicListFragment net = new NetMusicListFragment();
return net;
}
}
| 19.655172 | 62 | 0.731579 |
8f54ec3fef97215cc3d0cc80a7d514a9d32137f9 | 3,190 | package com.codiform.moo.property.source;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import com.codiform.moo.MissingSourcePropertyValueException;
public class ReflectionSourceProperty implements SourceProperty {
private String propertyName;
private String isGetterName;
private String getGetterName;
public ReflectionSourceProperty( String propertyName ) {
this.propertyName = propertyName;
String capped = cap( propertyName );
isGetterName = "is" + capped;
getGetterName = "get" + capped;
}
private String cap( String propertyName ) {
char firstChar = propertyName.charAt( 0 );
if( Character.isLowerCase( firstChar ) ) {
return "" + Character.toUpperCase( firstChar ) + propertyName.substring( 1 );
} else {
return propertyName;
}
}
@Override
public Object getValue( Object source ) {
Class<?> currentClass = source.getClass();
while( currentClass != null ) {
Method getter = getGetter( source, currentClass );
if( getter != null )
return getValue( getter, source );
Field field = getField( source, currentClass );
if( field != null )
return getValue( field, source );
currentClass = currentClass.getSuperclass();
}
throw new MissingSourcePropertyValueException( propertyName, source.getClass() );
}
private Object getValue( Field field, Object source ) {
field.setAccessible( true );
try {
return field.get( source );
} catch ( IllegalArgumentException cause ) {
throw new MissingSourcePropertyValueException( propertyName, source.getClass(), cause );
} catch ( IllegalAccessException cause ) {
throw new MissingSourcePropertyValueException( propertyName, source.getClass(), cause );
}
}
private Field getField( Object source, Class<?> currentClass ) {
for( Field item : currentClass.getDeclaredFields( ) ) {
if( item.getName().equals( propertyName ) )
return item;
}
return null;
}
private Object getValue( Method getter, Object source ) {
getter.setAccessible( true );
try {
return getter.invoke( source );
} catch ( IllegalArgumentException cause ) {
throw new MissingSourcePropertyValueException( propertyName, source.getClass(), cause );
} catch ( IllegalAccessException cause ) {
throw new MissingSourcePropertyValueException( propertyName, source.getClass(), cause );
} catch ( InvocationTargetException cause ) {
throw new MissingSourcePropertyValueException( propertyName, source.getClass(), cause );
}
}
private Method getGetter( Object source, Class<?> currentClass ) {
for( Method item : currentClass.getDeclaredMethods() ) {
if( item.getParameterTypes().length == 0 ) {
String methodName = item.getName();
if( methodName.equals( isGetterName ) || methodName.equals( getGetterName ) )
return item;
}
}
return null;
}
@Override
public Object getValue( Object source, Map<String, Object> variables ) {
return getValue( source );
}
public String getExpression() {
return propertyName;
}
@Override
public String toString() {
return "ReflectionSourceProperty [propertyName=" + propertyName + "]";
}
}
| 30.380952 | 91 | 0.723824 |
b6ccb0dabf91a1761a5da27f7aecd8301905488a | 241 | package com.jpworks.datajdbc.employee.vo;
import lombok.Builder;
import lombok.Data;
import java.time.LocalDate;
@Data
@Builder
public class Salary {
private LocalDate fromDate;
private long salary;
private LocalDate toDate;
}
| 17.214286 | 41 | 0.763485 |
aaff928d1750c254343c4a73ce5d4968e00057eb | 5,765 | /*
* Copyright 2016-2018 shardingsphere.io.
* <p>
* 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.
* </p>
*/
package io.shardingsphere.core.parsing.antlr.extractor.impl;
import com.google.common.base.Optional;
import io.shardingsphere.core.parsing.antlr.extractor.OptionalSQLSegmentExtractor;
import io.shardingsphere.core.parsing.antlr.extractor.util.ExtractorUtils;
import io.shardingsphere.core.parsing.antlr.extractor.util.RuleName;
import io.shardingsphere.core.parsing.antlr.sql.segment.column.ColumnSegment;
import io.shardingsphere.core.parsing.antlr.sql.segment.expr.CommonExpressionSegment;
import io.shardingsphere.core.parsing.antlr.sql.segment.expr.ExpressionSegment;
import io.shardingsphere.core.parsing.antlr.sql.segment.expr.FunctionExpressionSegment;
import io.shardingsphere.core.parsing.antlr.sql.segment.expr.PropertyExpressionSegment;
import io.shardingsphere.core.parsing.antlr.sql.segment.expr.StarExpressionSegment;
import io.shardingsphere.core.parsing.antlr.sql.segment.expr.SubquerySegment;
import io.shardingsphere.core.parsing.lexer.token.Symbol;
import io.shardingsphere.core.util.SQLUtil;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTree;
import org.antlr.v4.runtime.tree.TerminalNode;
import java.util.HashMap;
/**
* Expression extractor.
*
* @author duhongjun
*/
public final class ExpressionExtractor implements OptionalSQLSegmentExtractor {
@Override
public Optional<ExpressionSegment> extract(final ParserRuleContext expressionNode) {
String firstChildText = expressionNode.getText();
if (firstChildText.endsWith(Symbol.STAR.getLiterals())) {
int position = firstChildText.indexOf(Symbol.DOT.getLiterals());
Optional<String> owner = Optional.absent();
if (0 < position) {
owner = Optional.of(SQLUtil.getExactlyValue(firstChildText.substring(0, position)));
}
return Optional.<ExpressionSegment>of(new StarExpressionSegment(expressionNode.getStart().getStartIndex(), owner));
}
Optional<ParserRuleContext> subqueryNode = ExtractorUtils.findFirstChildNode(expressionNode, RuleName.SUBQUERY);
if (subqueryNode.isPresent()) {
Optional<SubquerySegment> subquerySegment = new SubqueryExtractor().extract(subqueryNode.get());
if (subquerySegment.isPresent()) {
return Optional.<ExpressionSegment>of(subquerySegment.get());
}
return Optional.absent();
}
return fillForPropertyOrFunction(expressionNode);
}
private Optional<ExpressionSegment> fillForPropertyOrFunction(final ParserRuleContext node) {
Optional<ParserRuleContext> aliasNode = ExtractorUtils.findFirstChildNode(node, RuleName.ALIAS);
Optional<String> alias = aliasNode.isPresent() ? Optional.of(SQLUtil.getExactlyValue(aliasNode.get().getText())) : Optional.<String>absent();
Optional<ParserRuleContext> functionCall = ExtractorUtils.findFirstChildNode(node, RuleName.FUNCTION_CALL);
if (functionCall.isPresent()) {
String name = functionCall.get().getChild(0).getText();
int startIndex = ((TerminalNode) functionCall.get().getChild(1)).getSymbol().getStartIndex();
boolean hasDistinct = hasDistinct(node);
int distinctColumnNameStartPosition = hasDistinct ? calculateDistinctColumnNamePosition(functionCall.get()) : -1;
FunctionExpressionSegment functionExpressionSegment = new FunctionExpressionSegment(name, functionCall.get().getStart().getStartIndex(),
startIndex, functionCall.get().getStop().getStopIndex(), hasDistinct, distinctColumnNameStartPosition);
functionExpressionSegment.setAlias(alias);
return Optional.<ExpressionSegment>of(functionExpressionSegment);
}
if (RuleName.COLUMN_NAME.getName().equals(node.getChild(0).getClass().getSimpleName())) {
ParserRuleContext columnNode = (ParserRuleContext) node.getChild(0);
Optional<ColumnSegment> columnSegment = new ColumnSegmentExtractor(new HashMap<String, String>()).extract(columnNode);
return Optional.<ExpressionSegment>of(new PropertyExpressionSegment(columnSegment.get().getOwner(), columnSegment.get().getName(),
columnNode.getStart().getStartIndex(), columnNode.getStop().getStopIndex(), alias));
}
return Optional.<ExpressionSegment>of(new CommonExpressionSegment(node.getStart().getStartIndex(), node.getStop().getStopIndex(), alias));
}
private boolean hasDistinct(final ParserRuleContext node) {
return ExtractorUtils.findFirstChildNode(node, RuleName.DISTINCT).isPresent();
}
private int calculateDistinctColumnNamePosition(final ParserRuleContext functionNode) {
ParseTree distinctItemNode = functionNode.getChild(3);
if (distinctItemNode instanceof TerminalNode) {
return ((TerminalNode) distinctItemNode).getSymbol().getStartIndex();
}
if (distinctItemNode instanceof ParserRuleContext) {
return ((ParserRuleContext) distinctItemNode).getStart().getStartIndex();
}
return -1;
}
}
| 54.386792 | 149 | 0.734085 |
2802505e9a8dbd17ad56e8eebae3b8bbe4f96ca5 | 477 | package com.dogigiri.core.concurrency.executiveframework.implementingasynchronousapi;
public class LongOperation {
public static void takeTime() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void takeTime(long delay) {
try {
Thread.sleep(delay);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 25.105263 | 85 | 0.587002 |
5257e093c0e69413325ffc18acd4d4e2ffdc4986 | 14,718 | package codes.writeonce.dispatcher;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static codes.writeonce.dispatcher.Helper.find;
import static java.util.Arrays.asList;
import static java.util.function.Function.identity;
abstract class AbstractDispatcherFactory implements DispatcherFactory {
@Override
@Nonnull
public <T> T wrap(@Nonnull Class<T> dispatcherType, @Nonnull Object... delegates) {
return createStub(dispatcherType, generateMap(dispatcherType, Object::getClass, delegates));
}
@Override
public void test(@Nonnull Class<?> dispatcherType, @Nonnull Class<?>[] delegates, @Nonnull Class<?>... subtypes)
throws DispatcherException {
final var map = generateMap(dispatcherType, identity(), delegates);
for (final var method : dispatcherType.getMethods()) {
for (final var subtype : subtypes) {
find(map.get(method), method, subtype);
}
}
}
@SafeVarargs
@Nonnull
private <T, D> Map<Method, Map<Class<?>, InheritedEntry<InvocationEntry>>> generateMap(
@Nonnull Class<T> dispatcherType,
@Nonnull Function<D, Class<?>> delegateClassFunction,
@Nonnull D... delegates
) {
if (!dispatcherType.isInterface()) {
throw new DispatcherException("First parameter must be interface: " + dispatcherType);
}
final var baseTypeAndParamsToDispatcherMethod =
new HashMap<Class<?>, HashMap<Class<?>, Map<List<Class<?>>, Method>>>();
final var dispatcherMethodAndImplTypeToDelegate =
new HashMap<Method, Map<Class<?>, InheritedEntry<InvocationEntry>>>();
final var dispatcherMethodOptionals = new HashMap<Method, Set<Integer>>();
for (final var method : dispatcherType.getMethods()) {
final var parameterAnnotations = method.getParameterAnnotations();
final var parameterTypes = method.getParameterTypes();
if (parameterTypes.length < 1) {
throw new DispatcherException("Dispatcher method has too few parameters: " + method);
}
if (isAnnotationPresent(parameterAnnotations[0])) {
throw new DispatcherException(
"Dispatcher method's first parameter may not have OptionalArg annotation: " + method);
}
final var optionals = new HashSet<Integer>();
for (int i = 1; i < parameterAnnotations.length; i++) {
if (isAnnotationPresent(parameterAnnotations[i])) {
optionals.add(i);
}
}
if (baseTypeAndParamsToDispatcherMethod
.computeIfAbsent(method.getReturnType(), k -> new HashMap<>())
.computeIfAbsent(parameterTypes[0], k -> new HashMap<>())
.put(getParameters(parameterTypes), method) != null) {
throw new DispatcherException("Duplicate dispatcher method signature: " + method);
}
if (dispatcherMethodAndImplTypeToDelegate.put(method, new HashMap<>()) != null) {
throw new DispatcherException("Duplicate dispatcher method: " + method);
}
dispatcherMethodOptionals.put(method, optionals);
}
for (final var delegate : delegates) {
final var delegateClass = delegateClassFunction.apply(delegate);
final var methods = delegateClass.getMethods();
checkClass(delegateClass, new HashSet<>(asList(methods)));
for (final var method : methods) {
if (method.isAnnotationPresent(Endpoint.class)) {
final var parameterTypes = method.getParameterTypes();
if (parameterTypes.length < 1) {
throw new DispatcherException("Delegate method has too few parameters: " + method);
}
final var type = parameterTypes[0];
if (type.isAnnotation()) {
throw new DispatcherException("First delegate parameter must not be annotation: " + method);
}
final var map = baseTypeAndParamsToDispatcherMethod.get(method.getReturnType());
if (map != null) {
for (final var entry : map.entrySet()) {
if (entry.getKey().isAssignableFrom(type)) {
final var dispatcherMethods =
getDispatcherMethods(entry.getValue(), dispatcherMethodOptionals, method,
parameterTypes);
for (final var entry2 : dispatcherMethods.entrySet()) {
final var dispatcherMethod = entry2.getKey();
final var presentParameters = entry2.getValue();
final var exceptionTypes = dispatcherMethod.getExceptionTypes();
for (final var exceptionType : method.getExceptionTypes()) {
checkException(exceptionType, exceptionTypes, method, dispatcherMethod);
}
final var entryMap = dispatcherMethodAndImplTypeToDelegate.get(dispatcherMethod);
final var inheritedEntry = entryMap.get(type);
if (inheritedEntry != null) {
final var impl = inheritedEntry.impl;
if (extending(presentParameters, impl.presentParameters)) {
entryMap.put(type, new InheritedEntry<>(type,
new InvocationEntry(method, delegate, presentParameters)));
} else if (!extending(impl.presentParameters, presentParameters)) {
throw new DispatcherException(
"Duplicate or ambiguous delegate method signature: " + impl.method +
" on " + impl.target + " and " + method + " on " + delegate);
}
} else {
entryMap.put(type, new InheritedEntry<>(type,
new InvocationEntry(method, delegate, presentParameters)));
}
}
}
}
}
}
}
}
return dispatcherMethodAndImplTypeToDelegate;
}
private boolean isAnnotationPresent(@Nonnull Annotation[] parameterAnnotation) {
for (final var annotation : parameterAnnotation) {
if (annotation.annotationType() == OptionalArg.class) {
return true;
}
}
return false;
}
private boolean extending(@Nonnull Set<Integer> highPresentParameters, @Nonnull Set<Integer> lowPresentParameters) {
final var set = new HashSet<>(highPresentParameters);
for (final var parameter : lowPresentParameters) {
if (!set.remove(parameter)) {
return false;
}
}
return !set.isEmpty();
}
@Nonnull
private Map<Method, Set<Integer>> getDispatcherMethods(
@Nonnull Map<List<Class<?>>, Method> map,
@Nonnull Map<Method, Set<Integer>> dispatcherMethodOptionals,
@Nonnull Method candidateMethod,
@Nonnull Class<?>[] parameterTypes
) {
final var methods = new HashMap<Method, Set<Integer>>();
for (final var method : map.values()) {
final var optionals = dispatcherMethodOptionals.get(method);
final var presentParameters =
getPresentParameters(method, method.getParameterTypes(), optionals, candidateMethod, parameterTypes,
1, 1);
if (presentParameters != null) {
presentParameters.add(0);
methods.put(method, presentParameters);
}
}
return methods;
}
@Nullable
private Set<Integer> getPresentParameters(
@Nonnull Method method,
@Nonnull Class<?>[] methodParameterTypes,
@Nonnull Set<Integer> methodOptionals,
@Nonnull Method candidateMethod,
@Nonnull Class<?>[] parameterTypes,
int i,
int j
) {
Set<Integer> set = null;
while (true) {
if (j == parameterTypes.length) {
while (i < methodParameterTypes.length) {
if (!methodOptionals.contains(i)) {
return null;
}
i++;
}
return set == null ? new HashSet<>() : set;
}
while (true) {
if (parameterTypes.length - j > methodParameterTypes.length - i) {
return null;
}
if (methodParameterTypes[i] == parameterTypes[j]) {
if (methodOptionals.contains(i)) {
final var set2 =
getPresentParameters(method, methodParameterTypes, methodOptionals, candidateMethod,
parameterTypes, i + 1, j);
final var set3 =
getPresentParameters(method, methodParameterTypes, methodOptionals, candidateMethod,
parameterTypes, i + 1, j + 1);
if (set2 == null) {
if (set3 == null) {
return null;
} else {
if (set == null) {
set = new HashSet<>(set3.size() + 1);
}
set.add(i);
set.addAll(set3);
return set;
}
} else {
if (set3 == null) {
if (set == null) {
return set2;
} else {
set.addAll(set2);
return set;
}
} else {
throw new AmbiguousTypeDispatcherException(
"Ambiguous method parameters: " + candidateMethod + " for method: " + method);
}
}
} else {
if (set == null) {
set = new HashSet<>(methodParameterTypes.length - i);
}
set.add(i);
i++;
j++;
break;
}
} else {
if (methodOptionals.contains(i)) {
i++;
} else {
return null;
}
}
}
}
}
private static void checkException(
@Nonnull Class<?> exceptionType,
@Nonnull Class<?>[] exceptionTypes,
@Nonnull Method method,
@Nonnull Method dispatcherMethod
) {
if (RuntimeException.class.isAssignableFrom(exceptionType) || Error.class.isAssignableFrom(exceptionType)) {
return;
}
for (final var type : exceptionTypes) {
if (type.isAssignableFrom(exceptionType)) {
return;
}
}
throw new DispatcherException(
"Endpoint " + method + " throws " + exceptionType + " not declared in " + dispatcherMethod);
}
private static void checkClass(@Nonnull Class<?> aClass, @Nonnull Set<Method> methods) {
while (true) {
checkMethods(aClass, methods);
checkInterfaces(aClass, methods);
aClass = aClass.getSuperclass();
if (aClass == null) {
return;
}
}
}
private static void checkInterfaces(@Nonnull Class<?> aClass, @Nonnull Set<Method> methods) {
for (final var anInterface : aClass.getInterfaces()) {
checkMethods(aClass, methods);
checkInterfaces(anInterface, methods);
}
}
private static void checkMethods(@Nonnull Class<?> aClass, @Nonnull Set<Method> methods) {
for (final var method : aClass.getDeclaredMethods()) {
if (method.isAnnotationPresent(Endpoint.class)) {
if (Modifier.isStatic(method.getModifiers())) {
throw new DispatcherException("Static endpoints not allowed: " + method);
}
if (!methods.contains(method)) {
throw new DispatcherException("Inaccessible endpoint: " + method);
}
}
}
}
@Nonnull
private static List<Class<?>> getParameters(@Nonnull Class<?>[] parameterTypes) {
return asList(parameterTypes).subList(1, parameterTypes.length);
}
@Nonnull
protected abstract <T> T createStub(
@Nonnull Class<T> dispatcherType,
@Nonnull Map<Method, Map<Class<?>, InheritedEntry<InvocationEntry>>> map
);
protected static final class InvocationEntry {
@Nonnull
public final Method method;
@Nonnull
public final Object target;
@Nonnull
public final Set<Integer> presentParameters;
public InvocationEntry(@Nonnull Method method, @Nonnull Object target,
@Nonnull Set<Integer> presentParameters) {
this.method = method;
this.target = target;
this.presentParameters = presentParameters;
}
}
}
| 42.051429 | 120 | 0.506319 |
740be3904584d99b9e150cff8391c6d0e7b627a6 | 394 | package listeners;
import java.util.List;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.widgets.Table;
public abstract class TableListener implements MouseListener
{
protected Table table;
protected List<?> data;
public void setTable(Table table)
{
this.table=table;
}
public void setData(List<?> data)
{
this.data = data;
}
}
| 17.130435 | 61 | 0.692893 |
0ff0078d05ac67fe47734038c8e469f3787782da | 5,933 | package edu.gemini.spModel.gemini.seqcomp;
import edu.gemini.pot.sp.ISPNodeInitializer;
import edu.gemini.pot.sp.ISPSeqComponent;
import edu.gemini.pot.sp.SPComponentType;
import edu.gemini.shared.util.immutable.ImOption;
import edu.gemini.spModel.gemini.calunit.CalUnitConstants;
import edu.gemini.spModel.gemini.calunit.CalUnitParams.*;
import edu.gemini.spModel.gemini.init.ComponentNodeInitializer;
import edu.gemini.spModel.obscomp.InstConstants;
import edu.gemini.spModel.seqcomp.GhostExpSeqComponent;
import edu.gemini.spModel.seqcomp.GhostSeqRepeatExp;
import edu.gemini.spModel.pio.ParamSet;
import edu.gemini.spModel.pio.PioFactory;
import edu.gemini.spModel.pio.Pio;
import edu.gemini.spModel.obsclass.ObsClass;
import java.util.*;
/**
* The GHOST flat iterator, and equivalent of SeqRepeatFlatObs.
* The difference here is that GHOST does not have a single exposure time, but due to having two detectors - a red
* and a blue - exposure times and exposure counts for each. Additionally, GHOST does not have coadds.
*/
final public class GhostSeqRepeatFlatObs extends GhostSeqRepeatExp
implements GhostExpSeqComponent {
private static final long serialVersionUID = 1L;
public static final SPComponentType SP_TYPE = SPComponentType.OBSERVER_GHOST_GEMFLAT;
public static final ISPNodeInitializer<ISPSeqComponent, GhostSeqRepeatFlatObs> NI =
new ComponentNodeInitializer<>(SP_TYPE, GhostSeqRepeatFlatObs::new, GhostSeqRepeatFlatObsCB::new);
public static final String OBSERVE_TYPE = InstConstants.FLAT_OBSERVE_TYPE;
private Set<Lamp> lamps = new TreeSet<>();
private Shutter shutter = Shutter.DEFAULT;
private Filter filter = Filter.DEFAULT;
private Diffuser diffuser = Diffuser.DEFAULT;
public GhostSeqRepeatFlatObs() {
super(SP_TYPE, ObsClass.PARTNER_CAL);
lamps.add(Lamp.DEFAULT);
}
@Override
public Object clone() {
final GhostSeqRepeatFlatObs copy = (GhostSeqRepeatFlatObs)super.clone();
copy.lamps = new TreeSet<>(lamps);
return copy;
}
@Override
public String getTitle() {
return (isArc() ? "Manual Ghost Arc: " : "Manual Ghost Flat: ") + Lamp.show(lamps, Lamp::displayValue)
+ " (" + getStepCount() + "X)";
}
@Override
public String getObserveType() {
return (isArc() ? InstConstants.ARC_OBSERVE_TYPE :
InstConstants.FLAT_OBSERVE_TYPE);
}
public int getLampCount() {
return lamps.size();
}
public TreeSet<Lamp> getLamps() {
return new TreeSet<>(lamps);
}
public void setLamp(Lamp newValue) {
final Set<Lamp> oldValue = lamps;
lamps = new TreeSet<>();
lamps.add(newValue);
if (!lamps.equals(oldValue)) {
firePropertyChange(CalUnitConstants.LAMP_PROP, oldValue, lamps);
}
}
public void setLamps(Collection<Lamp> newValue) {
final Set<Lamp> oldValue = lamps;
if (!newValue.equals(oldValue)) {
lamps = new TreeSet<>(newValue);
firePropertyChange(CalUnitConstants.LAMP_PROP, oldValue, newValue);
}
}
private void setLampsFromFormattedNames(String formattedList) {
setLamps(Lamp.read(formattedList));
}
public boolean isArc() { return Lamp.containsArc(lamps); }
public Shutter getShutter() {
return shutter;
}
public void setShutter(Shutter newValue) {
final Shutter oldValue = getShutter();
if (!newValue.equals(oldValue)) {
shutter = newValue;
firePropertyChange(CalUnitConstants.SHUTTER_PROP, oldValue, newValue);
}
}
public Filter getFilter() {
return filter;
}
public void setFilter(Filter newValue) {
final Filter oldValue = getFilter();
if (!newValue.equals(oldValue)) {
filter = newValue;
firePropertyChange(CalUnitConstants.FILTER_PROP, oldValue, newValue);
}
}
public Diffuser getDiffuser() {
return diffuser;
}
public void setDiffuser(Diffuser newValue) {
final Diffuser oldValue = getDiffuser();
if (!newValue.equals(oldValue)) {
diffuser = newValue;
firePropertyChange(CalUnitConstants.DIFFUSER_PROP, oldValue, newValue);
}
}
public ObsClass getDefaultObsClass() {
if (isArc()) return ObsClass.PROG_CAL;
return ObsClass.PARTNER_CAL;
}
@Override
public ParamSet getParamSet(PioFactory factory) {
ParamSet paramSet = super.getParamSet(factory);
Pio.addParam(factory, paramSet, CalUnitConstants.LAMP_PROP, Lamp.show(getLamps(), Lamp::name));
Pio.addParam(factory, paramSet, CalUnitConstants.SHUTTER_PROP, getShutter().name());
Pio.addParam(factory, paramSet, CalUnitConstants.FILTER_PROP, getFilter().name());
Pio.addParam(factory, paramSet, CalUnitConstants.DIFFUSER_PROP, getDiffuser().name());
return paramSet;
}
@Override
public void setParamSet(ParamSet paramSet) {
super.setParamSet(paramSet);
ImOption.apply(Pio.getValue(paramSet, CalUnitConstants.LAMP_PROP)).
forEach(this::setLampsFromFormattedNames);
ImOption.apply(Pio.getEnumValue(paramSet, CalUnitConstants.SHUTTER_PROP, Shutter.class)).
forEach(this::setShutter);
ImOption.apply(Pio.getEnumValue(paramSet, CalUnitConstants.FILTER_PROP, Filter.class)).
forEach(this::setFilter);
ImOption.apply(Pio.getEnumValue(paramSet, CalUnitConstants.DIFFUSER_PROP, Diffuser.class)).
forEach(this::setDiffuser);
// Only set the obs class if null: otherwise we use the partner obs class.
if (ImOption.apply(Pio.getEnumValue(paramSet, InstConstants.OBS_CLASS_PROP, getDefaultObsClass())).isEmpty())
setObsClass(getDefaultObsClass());
}
}
| 36.623457 | 117 | 0.685151 |
80102a9262ae28a0ccd325e393fb281f9415418f | 2,018 | /*
* 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.httprpc.io;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.StringWriter;
import java.time.DayOfWeek;
import java.util.Date;
import java.util.List;
import java.util.Map;
import static org.httprpc.util.Collections.entry;
import static org.httprpc.util.Collections.listOf;
import static org.httprpc.util.Collections.mapOf;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class CSVEncoderTest {
@Test
public void testWrite() throws IOException {
String expected = "\"a\",\"b\",\"c\",\"d.e\",\"f\",\"g\"\r\n"
+ "\"A,B,\"\"C\"\" \",1,2.0,true,0,3\r\n"
+ "\" D\r\nÉ\r\nF\r\n\",2,4.0,,,\r\n";
List<Map<String, ?>> values = listOf(
mapOf(
entry("a", "A,B,\"C\" "),
entry("b", 1),
entry("c", 2.0),
entry("d", mapOf(
entry("e", true)
)),
entry("f", new Date(0)),
entry("g", DayOfWeek.THURSDAY)
),
mapOf(
entry("a", " D\r\nÉ\r\nF\r\n"),
entry("b", 2),
entry("c", 4.0)
)
);
StringWriter writer = new StringWriter();
CSVEncoder csvEncoder = new CSVEncoder(listOf("a", "b", "c", "d.e", "f", "g"));
csvEncoder.write(values, writer);
assertEquals(expected, writer.toString());
}
}
| 31.046154 | 87 | 0.578791 |
094e3e3e5fed0b561b5cfe311e8607ab22627228 | 6,345 | /*
* Copyright (C) 2017-2019 Dremio Corporation
*
* 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.dremio.exec.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.arrow.vector.types.pojo.Field;
import com.dremio.common.exceptions.UserException;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
/**
* Given 2 field lists will compute a deep difference between them
* and get list of dropped, updated and added columns.
*/
public class BatchSchemaDiffer {
private final Field parent;
public BatchSchemaDiffer(Field parent) {
this.parent = parent;
}
public BatchSchemaDiffer() {
this.parent = null;
}
public static BatchSchemaDiffer withParent(Field parent) {
return new BatchSchemaDiffer(parent);
}
public BatchSchemaDiff diff(List<Field> left, List<Field> right) {
// (left-right) gives fields deleted in right
// for each deleted:
// deleted.stream().map(d -> {return appendParent ? new parent with d as child : d}).forEach(diff::droppedField);
// (right-left) gives field added in right
// for each added:
// added.stream().map(d -> { return appendParent ? new parent with d as child : d}).forEach(diff::addedField);
// for common fields:
// if field is primitive
// move on if type is same else add to diff.modified with or without parent depending on appendParent
// if complex do BatchSchemaDiffer.withParent(complexField.topLevel).diff(leftComplex.getChildren(), right.getChildren())
// and add all fields to diff.modified with parent if appendParent is true
BatchSchemaDiff diff = new BatchSchemaDiff();
Map<String,Field> leftFieldMap = new LinkedHashMap<>();
Map<String,Field> rightFieldMap = new LinkedHashMap<>();
for (Field field : left) {
leftFieldMap.put(field.getName().toLowerCase(), field);
}
for (Field field : right) {
rightFieldMap.put(field.getName().toLowerCase(), field);
}
List<Field> deletedFields = Maps.difference(leftFieldMap, rightFieldMap).entriesOnlyOnLeft().values().stream().collect(Collectors.toList());
deletedFields = deletedFields.stream().flatMap(x -> {
if(parent != null) {
return appendParent(parent, x).stream();
}
if(x.getChildren().size() > 0) {
return appendParents(x, x.getChildren()).stream();
}
return Arrays.asList(x).stream();
}).collect(Collectors.toList());
diff.droppedField(deletedFields);
List<Field> addedFields = Maps.difference(leftFieldMap, rightFieldMap).entriesOnlyOnRight().values().stream().collect(Collectors.toList());
addedFields = addedFields.stream().flatMap(x -> {
if(parent != null) {
return appendParent(parent, x).stream();
}
if(x.getChildren().size() > 0) {
return appendParents(x, x.getChildren()).stream();
}
return Arrays.asList(x).stream();
}).collect(Collectors.toList());
diff.addedField(addedFields);
//any 2 fields with the same name are common fields. Type may have
//changed.
rightFieldMap.keySet().retainAll(leftFieldMap.keySet());
List<Field> commonFields = rightFieldMap.values().stream().collect(Collectors.toList());
for(Field f : commonFields) {
if(f.getType().isComplex() ^ leftFieldMap.get(f.getName().toLowerCase()).getType().isComplex()) {
throw UserException.invalidMetadataError().
message(String.format("Field %s and %s should either both be simple or both be complex", leftFieldMap.get(f.getName().toLowerCase()), f.getType()))
.buildSilently();
}
boolean isSimple = !f.getType().isComplex();
//Simple field with types not same.
if(isSimple) {
if(!leftFieldMap.get(f.getName().toLowerCase()).getType().equals(f.getType())) {
diff.modifiedField(appendParent(parent, f));
}
} else {
//Is a complex field
BatchSchemaDiff batchSchemaDiff = BatchSchemaDiffer.withParent(f).diff(leftFieldMap.get(f.getName().toLowerCase()).getChildren(), f.getChildren());
diff.addedField(batchSchemaDiff.getAddedFields().stream().flatMap(x -> {
if(parent != null) {
return appendParent(parent, x).stream();
}
return Arrays.asList(x).stream();
}).collect(Collectors.toList()));
diff.droppedField(batchSchemaDiff.getDroppedFields().stream().flatMap(x -> {
if(parent != null) {
return appendParent(parent, x).stream();
}
return Arrays.asList(x).stream();
}).collect(Collectors.toList()));
diff.modifiedField(batchSchemaDiff.getModifiedFields().stream().flatMap(x -> {
if(parent != null) {
return appendParent(parent, x).stream();
}
return Arrays.asList(x).stream();
}).collect(Collectors.toList()));
}
}
return diff;
}
private List<Field> appendParent(Field parent, Field child) {
if(!child.getType().isComplex()) {
if(parent == null) {
//return the child if there is not parent
return ImmutableList.of(child);
}
return ImmutableList.of(new Field(parent.getName(), parent.getFieldType(), ImmutableList.of(child)));
} else {
return child.getChildren().stream().map(x -> {
return new Field(parent.getName(), parent.getFieldType(), appendParent(child, x));
}).collect(Collectors.toList());
}
}
private List<Field> appendParents(Field parent, List<Field> child) {
List<Field> children = new ArrayList();
for(Field ele : child) {
children.addAll(appendParent(parent, ele));
}
return children;
}
}
| 36.465517 | 157 | 0.666351 |
4cb5c226c02896b5787511d23ae57268ca381c2f | 3,573 | /*
* Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.lang.invoke;
import java.util.List;
public final
class MethodType implements java.io.Serializable {
public static
MethodType methodType(Class<?> rtype, Class<?>[] ptypes) {
return null;
}
public static
MethodType methodType(Class<?> rtype, List<Class<?>> ptypes) {
return null;
}
public static
MethodType methodType(Class<?> rtype, Class<?> ptype0, Class<?>... ptypes) { return null; }
public static
MethodType methodType(Class<?> rtype) { return null; }
public static
MethodType methodType(Class<?> rtype, Class<?> ptype0) { return null; }
public static
MethodType methodType(Class<?> rtype, MethodType ptypes) { return null; }
public static
MethodType genericMethodType(int objectArgCount, boolean finalArray) { return null; }
public static
MethodType genericMethodType(int objectArgCount) { return null; }
public MethodType changeParameterType(int num, Class<?> nptype) { return null; }
public MethodType insertParameterTypes(int num, Class<?>... ptypesToInsert) { return null; }
public MethodType appendParameterTypes(Class<?>... ptypesToInsert) { return null; }
public MethodType insertParameterTypes(int num, List<Class<?>> ptypesToInsert) { return null; }
public MethodType appendParameterTypes(List<Class<?>> ptypesToInsert) { return null; }
public MethodType dropParameterTypes(int start, int end) { return null; }
public MethodType changeReturnType(Class<?> nrtype) { return null; }
public boolean hasPrimitives() { return false; }
public boolean hasWrappers() { return false; }
public MethodType erase() { return null; }
public MethodType generic() { return null; }
public MethodType wrap() { return null; }
public MethodType unwrap() { return null; }
public Class<?> parameterType(int num) { return null; }
public int parameterCount() { return 0; }
public Class<?> returnType() { return null; }
public List<Class<?>> parameterList() { return null; }
public Class<?>[] parameterArray() { return null; }
public static MethodType fromMethodDescriptorString(String descriptor, ClassLoader loader)
throws IllegalArgumentException, TypeNotPresentException { return null; }
public String toMethodDescriptorString() { return null; }
}
| 34.68932 | 99 | 0.715925 |
bd1af33fa0804abe6ccd4be229e5a27fe8233a1c | 254 | package com.trusona.sdk.resources.exception;
public class ResourceNotProcessable extends TrusonaException {
private static final long serialVersionUID = 979016294537540040L;
public ResourceNotProcessable(String message) {
super(message);
}
} | 25.4 | 67 | 0.80315 |
ad0deb28879125e9156efe8ae2408909665c3956 | 1,439 | package main;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.stage.Stage;
import main.utils.readwrite.ReadWriteFile;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Objects;
public class LoadBookJar extends Application {
public static void main(String[] args) {
launch(args);
}
private static Stage stage;
public static void closeStage() {
stage.close();
}
@Override
public void start(Stage primaryStage) throws Exception {
try {
ReadWriteFile.loadData();
} catch (IOException e) {
FileOutputStream fileOut = new FileOutputStream("userbooks.dat");
fileOut.close();
}
Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("resources/fxml/bookJar.fxml")));
stage = new Stage();
stage.setTitle("BookJar");
stage.setScene(new Scene(root, 900, 600));
stage.getIcons().add(new Image(Objects.requireNonNull(getClass().getResourceAsStream("resources/images/bookJarLogo-200x.png"))));
stage.show();
stage.setOnCloseRequest(e -> {
try {
ReadWriteFile.saveData();
} catch (IOException e1) {
e1.printStackTrace();
}
});
}
}
| 27.150943 | 137 | 0.641418 |
eaed718b28e410ef5fb26e53d0454363fde6d6cd | 374 | package ghissues;
import act.controller.annotation.UrlContext;
import org.osgl.mvc.annotation.GetAction;
@UrlContext("821")
public class Gh821 extends BaseController {
@GetAction("invalid_json")
public String getInvalidJSON() {
return "abc";
}
@GetAction("valid_json")
public String getValidJSON() {
return "{\"foo\": 123}";
}
}
| 18.7 | 44 | 0.668449 |
980e927dc7fed2774d56f0d92cd02f7a7cbc226f | 4,075 | package com.gdg.hanoi.demo;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import com.firebase.client.AuthData;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.gdg.hanoi.demo.databinding.ActivityMainBinding;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
// host: https://codelab2.firebaseio.com/
private static final String FIREBASE_HOST = "https://codelab2.firebaseio.com/";
// credentical to authenticate
private String mEmail = "[email protected]";
private String mPassword = "123456";
// Firebase reference
Firebase myFirebaseRef;
ActivityMainBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The Firebase library must be initialized once with an Android context.
// This must happen before any Firebase app reference is created or used.
Firebase.setAndroidContext(this);
mBinding = DataBindingUtil.setContentView(this,R.layout.activity_main);
mBinding.setEmail(mEmail);
mBinding.setPassword(mPassword);
myFirebaseRef = new Firebase(FIREBASE_HOST);
// Reading data from your Firebase database is accomplished by attaching an event
// listener and handling the resulting events
myFirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
//prints "Do you have data? You'll love Firebase."
System.out.println(snapshot.getValue());
}
@Override
public void onCancelled(FirebaseError error) {
System.out.println(error.getMessage());
}
});
}
public void onLoginClick(final View button) {
// Enable authenticate with password on firebase server first
myFirebaseRef.authWithPassword(mEmail, mPassword,
new Firebase.AuthResultHandler() {
@Override
public void onAuthenticated(AuthData authData) {
String dataToSend = "Do you have data? You'll love Firebase.";
myFirebaseRef.child("message")
.setValue(dataToSend);
Snackbar.make(button, "login success", Snackbar.LENGTH_SHORT).show();
}
@Override
public void onAuthenticationError(FirebaseError firebaseError) {
Snackbar.make(button, firebaseError.getMessage(), Snackbar.LENGTH_SHORT)
.show();
}
});
}
public void onRegisterClick(final View button) {
// Firebase provides full support for authenticating users with Email & Password,
// Facebook, Twitter, GitHub, Google, or your existing authentication system.
myFirebaseRef.createUser(mEmail, mPassword, //
new Firebase.ValueResultHandler<Map<String, Object>>() {
@Override
public void onSuccess(Map<String, Object> result) {
System.out.println("Created account with uid: " + result.get("uid"));
Snackbar.make(button, "Created account with uid: " + result.get("uid"),
Snackbar.LENGTH_SHORT)
.show();
}
@Override
public void onError(FirebaseError firebaseError) {
Snackbar.make(button, firebaseError.getMessage(), Snackbar.LENGTH_SHORT)
.show();
}
});
}
}
| 38.443396 | 96 | 0.60908 |
5bd184fe938493aba87b372c507eb00d8f450b90 | 1,686 | package www.bwsensing.com.common.netty.initializer;
import www.bwsensing.com.common.constant.NettyConstants;
import org.springframework.beans.factory.annotation.Autowired;
import www.bwsensing.com.common.netty.decoder.NettyServerDecoder;
import www.bwsensing.com.common.netty.handler.NettyTcpServerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
/**
* @author macos-zyj
*/
@Component
public class NettyTcpInitializer extends ChannelInitializer<SocketChannel> {
@Autowired
private NettyTcpServerHandler nettyServerHandler;
@Override
protected void initChannel(SocketChannel socketChannel) {
ChannelPipeline pipeline = socketChannel.pipeline();
int localPort = socketChannel.localAddress().getPort();
pipeline.addLast(new IdleStateHandler(
NettyConstants.SERVER_READ_IDEL_TIME_OUT,
NettyConstants.SERVER_WRITE_IDEL_TIME_OUT,
NettyConstants.SERVER_ALL_IDEL_TIME_OUT,
TimeUnit.SECONDS))
.addLast("aggregator", new HttpObjectAggregator(512 * 1024))
.addLast(new StringEncoder())
.addLast(new ByteArrayEncoder())
//根据端口动态的选择解码器
.addLast("decoder",new NettyServerDecoder(localPort))
.addLast("nettyServerHandler", nettyServerHandler);
}
}
| 39.209302 | 76 | 0.763345 |
5c44db8a6556cebf7a5cd1f7a8ece92fe35e984e | 481 | package com.ccrma.faust;
public class Smooth {
private float delay = 0;
private float s = 0;
public void reset(){
delay = 0;
}
// set the smoothing (pole)
public void setSmooth(float smooth){
s = smooth;
}
// compute one sample
public double tick(float input){
float currentSample = input*(1.0f-s);
currentSample = currentSample + delay;
delay = currentSample*s;
return currentSample;
}
}
| 20.041667 | 46 | 0.590437 |
6c26ee0fe3a6da4f6f0baf0a97ce0c4b3f6d6780 | 1,209 | package org.tests.basic.encrypt;
import io.ebean.BaseTestCase;
import io.ebean.DB;
import io.ebean.SqlRow;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.EBasicEncryptBinary;
import java.sql.Timestamp;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestEncryptBinary extends BaseTestCase {
@Test
public void test() {
Timestamp t0 = new Timestamp(System.currentTimeMillis());
EBasicEncryptBinary e = new EBasicEncryptBinary();
e.setName("test1");
e.setDescription("testdesc1");
e.setSomeTime(t0);
e.setData("HelloWorld".getBytes());
DB.save(e);
SqlRow row = DB.sqlQuery("select * from e_basicenc_bin where id = :id")
.setParameter("id", e.getId())
.findOne();
row.getString("name");
row.get("data");
row.get("some_time");
EBasicEncryptBinary e1 = DB.find(EBasicEncryptBinary.class, e.getId());
Timestamp t1 = e1.getSomeTime();
e1.getData();
e1.getDescription();
assertEquals(t0, t1);
e1.setName("testmod");
e1.setDescription("moddesc");
DB.save(e1);
EBasicEncryptBinary e2 = DB.find(EBasicEncryptBinary.class, e.getId());
e2.getDescription();
}
}
| 22.388889 | 75 | 0.686518 |
4a0a33cbcf31327c7fdcb40bc818645be8c037e1 | 7,674 | /*
* Copyright 2013-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.gateway.filter.factory.rewrite;
import java.util.Map;
import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.NettyWriteResponseFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.cloud.gateway.support.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.support.DefaultClientResponse;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
import org.springframework.http.client.reactive.ClientHttpResponse;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.util.MultiValueMap;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ExchangeStrategies;
import org.springframework.web.server.ServerWebExchange;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR;
/**
* This filter is BETA and may be subject to change in a future release.
*/
public class ModifyResponseBodyGatewayFilterFactory extends
AbstractGatewayFilterFactory<ModifyResponseBodyGatewayFilterFactory.Config> {
private final ServerCodecConfigurer codecConfigurer;
public ModifyResponseBodyGatewayFilterFactory(ServerCodecConfigurer codecConfigurer) {
super(Config.class);
this.codecConfigurer = codecConfigurer;
}
@Override
public GatewayFilter apply(Config config) {
return new ModifyResponseGatewayFilter(config);
}
public static class Config {
private Class inClass;
private Class outClass;
private Map<String, Object> inHints;
private Map<String, Object> outHints;
private String newContentType;
private RewriteFunction rewriteFunction;
public Class getInClass() {
return inClass;
}
public Config setInClass(Class inClass) {
this.inClass = inClass;
return this;
}
public Class getOutClass() {
return outClass;
}
public Config setOutClass(Class outClass) {
this.outClass = outClass;
return this;
}
public Map<String, Object> getInHints() {
return inHints;
}
public Config setInHints(Map<String, Object> inHints) {
this.inHints = inHints;
return this;
}
public Map<String, Object> getOutHints() {
return outHints;
}
public Config setOutHints(Map<String, Object> outHints) {
this.outHints = outHints;
return this;
}
public String getNewContentType() {
return newContentType;
}
public Config setNewContentType(String newContentType) {
this.newContentType = newContentType;
return this;
}
public RewriteFunction getRewriteFunction() {
return rewriteFunction;
}
public Config setRewriteFunction(RewriteFunction rewriteFunction) {
this.rewriteFunction = rewriteFunction;
return this;
}
public <T, R> Config setRewriteFunction(Class<T> inClass, Class<R> outClass,
RewriteFunction<T, R> rewriteFunction) {
setInClass(inClass);
setOutClass(outClass);
setRewriteFunction(rewriteFunction);
return this;
}
}
public class ModifyResponseGatewayFilter implements GatewayFilter, Ordered {
private final Config config;
public ModifyResponseGatewayFilter(Config config) {
this.config = config;
}
@Override
@SuppressWarnings("unchecked")
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(
exchange.getResponse()) {
@Override
public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
Class inClass = config.getInClass();
Class outClass = config.getOutClass();
String originalResponseContentType = exchange
.getAttribute(ORIGINAL_RESPONSE_CONTENT_TYPE_ATTR);
HttpHeaders httpHeaders = new HttpHeaders();
// explicitly add it in this way instead of
// 'httpHeaders.setContentType(originalResponseContentType)'
// this will prevent exception in case of using non-standard media
// types like "Content-Type: image"
httpHeaders.add(HttpHeaders.CONTENT_TYPE,
originalResponseContentType);
ResponseAdapter responseAdapter = new ResponseAdapter(body,
httpHeaders);
DefaultClientResponse clientResponse = new DefaultClientResponse(
responseAdapter, ExchangeStrategies.withDefaults());
// TODO: flux or mono
Mono modifiedBody = clientResponse.bodyToMono(inClass)
.flatMap(originalBody -> config.rewriteFunction
.apply(exchange, originalBody));
BodyInserter bodyInserter = BodyInserters.fromPublisher(modifiedBody,
outClass);
CachedBodyOutputMessage outputMessage = new CachedBodyOutputMessage(
exchange, exchange.getResponse().getHeaders());
return bodyInserter.insert(outputMessage, new BodyInserterContext())
.then(Mono.defer(() -> {
Flux<DataBuffer> messageBody = outputMessage.getBody();
HttpHeaders headers = getDelegate().getHeaders();
if (!headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
messageBody = messageBody.doOnNext(data -> headers
.setContentLength(data.readableByteCount()));
}
// TODO: use isStreamingMediaType?
return getDelegate().writeWith(messageBody);
}));
}
@Override
public Mono<Void> writeAndFlushWith(
Publisher<? extends Publisher<? extends DataBuffer>> body) {
return writeWith(Flux.from(body).flatMapSequential(p -> p));
}
};
return chain.filter(exchange.mutate().response(responseDecorator).build());
}
@Override
public int getOrder() {
return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER - 1;
}
}
public class ResponseAdapter implements ClientHttpResponse {
private final Flux<DataBuffer> flux;
private final HttpHeaders headers;
public ResponseAdapter(Publisher<? extends DataBuffer> body,
HttpHeaders headers) {
this.headers = headers;
if (body instanceof Flux) {
flux = (Flux) body;
}
else {
flux = ((Mono) body).flux();
}
}
@Override
public Flux<DataBuffer> getBody() {
return flux;
}
@Override
public HttpHeaders getHeaders() {
return headers;
}
@Override
public HttpStatus getStatusCode() {
return null;
}
@Override
public int getRawStatusCode() {
return 0;
}
@Override
public MultiValueMap<String, ResponseCookie> getCookies() {
return null;
}
}
}
| 29.178707 | 115 | 0.752802 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.