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
|
---|---|---|---|---|---|
e3d58412b871518da4f0cac4b72db7a001d6e992 | 4,465 | package cern.enice.jira.amh.baseruleset;
import static junitparams.JUnitParamsRunner.$;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Contains test cases to test the following fields: Components, Fix Versions, Affected Versions
* @author vvasilye
*
*/
@RunWith(JUnitParamsRunner.class)
public class MultivalueFieldsTest extends BaseRuleSetBaseTest {
@Parameters(method="parametersForComponentsField")
@Test
public void testComponentsAreSet(String tokenValue, String expectedValuesAsString) {
Set<String> expectedValues = new HashSet<String>(Arrays.asList(expectedValuesAsString.split(";")));
tokens.put(Tokens.COMPONENTS, tokenValue);
issueDescriptor.setComponents(ruleSet.validateMultivalueField(tokens, Tokens.COMPONENTS, "NT", "Bug"));
assertThat(issueDescriptor.getComponents(), is(expectedValues));
}
private Object parametersForComponentsField() {
return $(
$("advanced mail handler, component2, jira listeners", "Advanced Mail Handler;Component2;JIRA listeners"),
$("jira listeners, advanced mail handler", "JIRA listeners;Advanced Mail Handler")
);
}
@Parameters(method="parametersForFixAndAffectedVersionsFields")
@Test
public void testAffectedVersionsAreSet(String tokenValue, String expectedValuesAsString) {
Set<String> expectedValues = new HashSet<String>(Arrays.asList(expectedValuesAsString.split(";")));
tokens.put(Tokens.AFFECTED_VERSIONS, tokenValue);
issueDescriptor.setAffectedVersions(ruleSet.validateMultivalueField(tokens, Tokens.AFFECTED_VERSIONS, "NT", "Bug"));
assertThat(issueDescriptor.getAffectedVersions(), is(expectedValues));
}
@Parameters(method="parametersForFixAndAffectedVersionsFields")
@Test
public void testFixVersionsAreSet(String tokenValue, String expectedValuesAsString) {
Set<String> expectedValues = new HashSet<String>(Arrays.asList(expectedValuesAsString.split(";")));
tokens.put(Tokens.FIX_VERSIONS, tokenValue);
issueDescriptor.setFixVersions(ruleSet.validateMultivalueField(tokens, Tokens.FIX_VERSIONS, "NT", "Bug"));
assertThat(issueDescriptor.getFixVersions(), is(expectedValues));
}
private Object parametersForFixAndAffectedVersionsFields() {
return $(
$("5.0, 5.1", "5.0;5.1"),
$("5.1", "5.1")
);
}
@Parameters
@Test
public void testMultivalueFieldIsNotSetDueToUnknownValues(String token, String tokenValue) {
tokens.put(token, tokenValue);
issueDescriptor.setComponents(ruleSet.validateMultivalueField(tokens, Tokens.COMPONENTS, "NT", "Bug"));
issueDescriptor.setAffectedVersions(ruleSet.validateMultivalueField(tokens, Tokens.AFFECTED_VERSIONS, "NT", "Bug"));
issueDescriptor.setFixVersions(ruleSet.validateMultivalueField(tokens, Tokens.FIX_VERSIONS, "NT", "Bug"));
assertNull(issueDescriptor.getComponents());
assertNull(issueDescriptor.getAffectedVersions());
assertNull(issueDescriptor.getFixVersions());
}
private Object parametersForTestMultivalueFieldIsNotSetDueToUnknownValues() {
return $(
$(Tokens.COMPONENTS, "abc, bcd, cde"),
$(Tokens.AFFECTED_VERSIONS, "abc, bcd, cde"),
$(Tokens.FIX_VERSIONS, "abc, bcd, cde")
);
}
@Test
public void testMultivalueFieldIsNotSetDueToMissingToken() {
issueDescriptor.setComponents(ruleSet.validateMultivalueField(tokens, Tokens.COMPONENTS, "NT", "Bug"));
assertNull(issueDescriptor.getComponents());
}
@Parameters
@Test
public void testMultivalueFieldValuesAreSplitByDifferentSeparator(String tokenValue, String expectedValuesAsString, String separator) {
Set<String> expectedValues = new HashSet<String>(Arrays.asList(expectedValuesAsString.split(";")));
tokens.put(Tokens.SEPARATOR, separator);
tokens.put(Tokens.FIX_VERSIONS, tokenValue);
issueDescriptor.setFixVersions(ruleSet.validateMultivalueField(tokens, Tokens.FIX_VERSIONS, "NT", "Bug"));
assertThat(issueDescriptor.getFixVersions(), is(expectedValues));
}
private Object parametersForTestMultivalueFieldValuesAreSplitByDifferentSeparator() {
return $(
$("5.0, 5.1", "5.0;5.1", null),
$("5.0, 5.1", "5.0;5.1", ""),
$("5.0; 5.1", "5.0;5.1", ";"),
$("5.0 5.1", "5.0;5.1", " "),
$("5.1", "5.1", null),
$("5.1::5.0", "5.1;5.0", "::")
);
}
}
| 38.826087 | 136 | 0.759239 |
bb84d30ef6f4fb6265597ad479ed2ef4e05cee01 | 1,565 |
/*
* Autor: Hincho Jove, Angel Eduardo
*
* Descripcion del problema: Implementar el codigo visto en laboratorio
* hallar su complejidad. Un metodo que realice una accion 'statement'
*
* PREGUNTA!
* Cual es la complejidad de este codigo?
* La complejidad es de O(n^2)
*
*/
public class Cuadratic_Time_Sum {
public static void main(String[] args) {
// Repaso de Complejidad en Tiempo
cuadraticTimeSum(5);
cuadraticTimeSum(10);
cuadraticTimeSum(20);
}
public static void cuadraticTimeSum(int n) {
// Q5: Cual es la Complejidad en Tiempo de:
System.out.println("Prueba con un valor n = " + n);
int repeats = 0;
for(int i = 0; i < n; i++) { // Ciclo for de 'n' veces
for(int j = 0; j < i; j++) { // Ciclo for de 'i' veces
// Parte Statement del codigo
repeats++; // Acumular en la variable 'repeats' O(1)
}
}
System.out.println("Repeticiones: " + repeats);
System.out.println();
/*
* Explicacion:
*
* Valor de i | Valor de j | Repeticiones
* --------------------------------------
* 0 0 0
* --------------------------------------
* 1 0 1
* --------------------------------------
* 2 0 , 1 2
* --------------------------------------
* 3 0 , 1 , 2 3
* --------------------------------------
* ...
* --------------------------------------
* n - 1 0 ,..., n - 1 n - 1
*
* Entonces:
*
* O((n - 1) * (n) / 2) = O(n^2 - n) = O(n^2)
*
*/
}
}
| 20.866667 | 71 | 0.444728 |
652fc9c89d76f8f069cdd561e028aef582222134 | 684 | package ca.dantav.game.gfx;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import ca.dantav.game.Game;
public final class GraphicManager {
public final List<GraphicHandler> graphics = new ArrayList<>();
private Game game;
public GraphicManager(Game game) {
this.game = game;
}
public void drawAll(Graphics g) {
graphics.stream().filter(Objects::nonNull).forEach((GraphicHandler h) -> h.draw(game, g));;
}
public void add(GraphicHandler handler) {
graphics.add(handler);
}
public void remove(GraphicHandler handler) {
graphics.remove(handler);
}
public Game getGame() {
return game;
}
}
| 18 | 93 | 0.716374 |
cd1209e194477d8bb0831794a09870bee0816147 | 1,065 | public class Triangle {
private int mSideA;
private int mSideB;
private int mSideC;
public Triangle(int sideA, int sideB, int sideC) {
mSideA = sideA;
mSideB = sideB;
mSideC = sideC;
}
public int getSideA() {
return mSideA;
}
public int getSideB() {
return mSideB;
}
public int getSideC() {
return mSideC;
}
public boolean isTriangle() {
if ((mSideA + mSideB > mSideC) && (mSideB + mSideC > mSideA) && (mSideC + mSideA > mSideB)) {
return true;
} else {
return false;
}
}
public boolean isScalene() {
if ((mSideA != mSideB) && (mSideB != mSideC) && (mSideC != mSideA)) {
return true;
} else {
return false;
}
}
public boolean isIsosceles() {
if ((mSideA == mSideB) || (mSideB == mSideC) || (mSideC == mSideA)) {
return true;
} else {
return false;
}
}
public boolean isEquilateral() {
if ((mSideA == mSideB) && (mSideB == mSideC) && (mSideC == mSideA)) {
return true;
} else {
return false;
}
}
}
| 18.362069 | 97 | 0.553991 |
7c826686b75e37a2596c4ddc7393815e6cee5a1b | 2,435 | /*
* This file is part of ClassGraph.
*
* Author: Luke Hutchison
*
* Hosted at: https://github.com/classgraph/classgraph
*
* --
*
* The MIT License (MIT)
*
* Copyright (c) 2021 Luke Hutchison
*
* 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 io.github.classgraph;
import java.io.Closeable;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* A wrapper for {@link ByteBuffer} that implements the {@link Closeable} interface, releasing the
* {@link ByteBuffer} when it is no longer needed.
*/
public class CloseableByteBuffer implements Closeable {
private ByteBuffer byteBuffer;
private Runnable onClose;
/**
* A wrapper for {@link ByteBuffer} that implements the {@link Closeable} interface, releasing the
* {@link ByteBuffer} when it is no longer needed.
*/
public CloseableByteBuffer(final ByteBuffer byteBuffer, final Runnable onClose) {
this.byteBuffer = byteBuffer;
this.onClose = onClose;
}
/**
* @return The wrapped {@link ByteBuffer}.
*/
public ByteBuffer getByteBuffer() {
return byteBuffer;
}
@Override
public void close() throws IOException {
if (onClose != null) {
try {
onClose.run();
} catch (final Exception e) {
// Ignore
}
onClose = null;
}
byteBuffer = null;
}
}
| 33.819444 | 111 | 0.687474 |
dca7385c2d297c24f51b4e76a401b88e132ecdcb | 1,203 | package org.example.ioc.utils;
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
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 javax.sql.DataSource;
/**
* @Classname SpringConfig
* @Description 配置类
* @Date 2021-04-05 12:24
* @Created by Klein
*/
@Configuration
@ComponentScan(basePackages = "org.example.ioc")
@PropertySource(value = "classpath:jdbc.properties")
public class SpringConfig {
@Value("${jdbc.driver}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String userName;
@Value("${jdbc.password}")
private String passWord;
@Bean("dataSource")
public DataSource getDataSource() {
DruidDataSource dataSource=new DruidDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(userName);
dataSource.setPassword(passWord);
return dataSource;
}
}
| 26.733333 | 61 | 0.731505 |
bede2969f9f7e364bd88758d7a192920eb522c09 | 2,065 | /*
* Copyright © 2018 www.noark.xyz All Rights Reserved.
*
* 感谢您选择Noark框架,希望我们的努力能为您提供一个简单、易用、稳定的服务器端框架 !
* 除非符合Noark许可协议,否则不得使用该文件,您可以下载许可协议文件:
*
* http://www.noark.xyz/LICENSE
*
* 1.未经许可,任何公司及个人不得以任何方式或理由对本框架进行修改、使用和传播;
* 2.禁止在本项目或任何子项目的基础上发展任何派生版本、修改版本或第三方版本;
* 3.无论你对源代码做出任何修改和改进,版权都归Noark研发团队所有,我们保留所有权利;
* 4.凡侵犯Noark版权等知识产权的,必依法追究其法律责任,特此郑重法律声明!
*/
package xyz.noark.core.ioc.definition.field;
import xyz.noark.core.converter.ConvertManager;
import xyz.noark.core.converter.Converter;
import xyz.noark.core.env.EnvConfigHolder;
import xyz.noark.core.exception.ConvertException;
import xyz.noark.core.exception.UnrealizedException;
import xyz.noark.core.ioc.IocMaking;
import xyz.noark.core.util.FieldUtils;
import xyz.noark.core.util.StringUtils;
import java.lang.reflect.Field;
/**
* Value方式注入配置参数.
*
* @author 小流氓[[email protected]]
* @since 3.0
*/
public class ValueFieldDefinition extends DefaultFieldDefinition {
/**
* 对应配置文件中的Key...
*/
private final String key;
public ValueFieldDefinition(Field field, String key) {
super(field, false);
this.key = key;
}
/**
* 配置参数注入,如果没找到则忽略,使用默认值...
*/
@Override
public void injection(Object single, IocMaking making) {
String value = EnvConfigHolder.getString(key);
if (StringUtils.isNotEmpty(value)) {
Converter<?> converter = ConvertManager.getInstance().getConverter(field.getType());
if (converter != null) {
try {
FieldUtils.writeField(single, field, converter.convert(field, value));
} catch (Exception e) {
throw new ConvertException(single.getClass().getName() + " >> " + field.getName() + " >> " + value + "-->" + converter.buildErrorMsg(), e);
}
} else {
throw new UnrealizedException("类:" + single.getClass().getName() + "中的属性:" + field.getName() + "类型未实现此转化器");
}
}
}
} | 32.777778 | 160 | 0.631477 |
55d44b5e8ffe68c0629b0d11967bdb801f2839c4 | 972 | package frc.robot.commands.auto.commandgroups.testergroups;
import edu.wpi.first.wpilibj2.command.SequentialCommandGroup;
/**
* The chassis goes in a diamond command group
* @author Madison J.
* @category AUTON
*/
public class swerveDiamond extends SequentialCommandGroup {
@SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"})
/**
* The chassis goes in a diamond command group
*/
public swerveDiamond() {
addCommands(
/* new driveToPosition(Robot.SwerveDrivetrain, 0, 45, 1),
new driveToPosition(Robot.SwerveDrivetrain, 24, 45, 1),
new driveToPosition(Robot.SwerveDrivetrain, 0, -45, 1),
new driveToPosition(Robot.SwerveDrivetrain, 24, -45, 1),
new driveToPosition(Robot.SwerveDrivetrain, 0, 45, 1),
new driveToPosition(Robot.SwerveDrivetrain, -24, 45, 1),
new driveToPosition(Robot.SwerveDrivetrain, 0, -45, 1),
new driveToPosition(Robot.SwerveDrivetrain, -24, -45, 1)
*/
);
}
}
| 29.454545 | 68 | 0.708848 |
7c001d3644b4be2317a6769d7e4f5c87beb781a4 | 642 | @Inject
private UrlRouting urlRouting;
@Inject
private GroupTable<Customer> customersTable;
@Inject
private Dialogs dialogs;
@Subscribe("getLinkButton")
public void onGetLinkButtonClick(Button.ClickEvent event) {
Customer selectedCustomer = customersTable.getSingleSelected();
if (selectedCustomer != null) {
String routeToSelectedRole = urlRouting.getRouteGenerator()
.getEditorRoute(selectedCustomer);
dialogs.createMessageDialog()
.withCaption("Generated route")
.withMessage(routeToSelectedRole)
.withWidth("710")
.show();
}
} | 27.913043 | 67 | 0.676012 |
53d82e7be7a59ed4c1e907cddb5fe9ee33e880ad | 3,667 | package com.sillykid.app.adapter;
import android.content.Context;
import android.widget.ImageView;
import com.kymjs.common.StringUtils;
import com.sillykid.app.R;
import com.sillykid.app.entity.PackLineBean.ResultBean.DriverBeanX;
import com.sillykid.app.utils.GlideImageLoader;
import cn.bingoogolapple.androidcommon.adapter.BGAAdapterViewAdapter;
import cn.bingoogolapple.androidcommon.adapter.BGAViewHolderHelper;
/**
* 包车定制--司导 适配器
* Created by Admin on 2017/8/15.
*/
public class CompanyGuideViewAdapter extends BGAAdapterViewAdapter<DriverBeanX> {
public CompanyGuideViewAdapter(Context context) {
super(context, R.layout.item_localguide);
}
@Override
public void fillData(BGAViewHolderHelper viewHolderHelper, int position, DriverBeanX listBean) {
/**
* 图片
*/
GlideImageLoader.glideOrdinaryLoader(mContext, listBean.getHead_pic(), (ImageView) viewHolderHelper.getView(R.id.img_companyGuide), R.mipmap.placeholderfigure);
/**
* 姓名
*/
viewHolderHelper.setText(R.id.tv_name, listBean.getNickname());
/**
* 工号
*/
viewHolderHelper.setText(R.id.tv_jobNumber, listBean.getDrv_code());
/**
*城市
*/
viewHolderHelper.setText(R.id.tv_address, listBean.getCountry()+"•" + listBean.getCity());
/**
*城市
*/
if (!StringUtils.isEmpty(listBean.getLine())) {
viewHolderHelper.setText(R.id.tv_title, listBean.getLine());
} else {
viewHolderHelper.setText(R.id.tv_title, "");
}
/**
* 服务星级
*/
switch (StringUtils.toInt(listBean.getPlat_start(), 0)) {
case 0:
viewHolderHelper.setImageDrawable(R.id.img_service, null);
break;
case 1:
viewHolderHelper.setImageResource(R.id.img_service, R.mipmap.star_one);
break;
case 2:
viewHolderHelper.setImageResource(R.id.img_service, R.mipmap.star_two);
break;
case 3:
viewHolderHelper.setImageResource(R.id.img_service, R.mipmap.star_three);
break;
case 4:
viewHolderHelper.setImageResource(R.id.img_service, R.mipmap.star_four);
break;
case 5:
viewHolderHelper.setImageResource(R.id.img_service, R.mipmap.star_full);
break;
default:
viewHolderHelper.setImageDrawable(R.id.img_service, null);
break;
}
/**
* 评价星级
*/
switch (StringUtils.toInt(listBean.getStar(), 0)) {
case 0:
viewHolderHelper.setImageDrawable(R.id.img_evaluation, null);
break;
case 1:
viewHolderHelper.setImageResource(R.id.img_evaluation, R.mipmap.heart_one);
break;
case 2:
viewHolderHelper.setImageResource(R.id.img_evaluation, R.mipmap.heart_two);
break;
case 3:
viewHolderHelper.setImageResource(R.id.img_evaluation, R.mipmap.heart_three);
break;
case 4:
viewHolderHelper.setImageResource(R.id.img_evaluation, R.mipmap.heart_four);
break;
case 5:
viewHolderHelper.setImageResource(R.id.img_evaluation, R.mipmap.heart_full);
break;
default:
viewHolderHelper.setImageDrawable(R.id.img_evaluation, null);
break;
}
}
} | 32.451327 | 168 | 0.588219 |
2690ca017d13446a607ee19ebba75c405b2ab90b | 832 | package org.lnu.is.converter.person.type;
import org.lnu.is.annotations.Converter;
import org.lnu.is.converter.AbstractConverter;
import org.lnu.is.domain.person.type.PersonType;
import org.lnu.is.resource.person.type.PersonTypeResource;
/**
* Person Type PersonType PersonTypeResource converter.
* @author ivanursul
*
*/
@Converter("personTypeConverter")
public class PersonTypeConverter extends AbstractConverter<PersonType, PersonTypeResource> {
@Override
public PersonTypeResource convert(final PersonType source, final PersonTypeResource target) {
target.setId(source.getId());
target.setName(source.getName());
target.setAbbrName(source.getAbbrName());
return target;
}
@Override
public PersonTypeResource convert(final PersonType source) {
return convert(source, new PersonTypeResource());
}
}
| 26 | 94 | 0.784856 |
4fb1c51d117795421d9ffbbc497c80dfe921e8ac | 1,550 | package com.ptrprograms.androidtvmediaplayer.Bonus;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.Transformation;
/**
* Created by PaulTR on 7/10/14.
*/
public class AnimateDrawable extends ProxyDrawable {
private Animation mAnimation;
private Transformation mTransformation = new Transformation();
public AnimateDrawable(Drawable target) {
super(target);
}
public AnimateDrawable(Drawable target, Animation animation) {
super(target);
mAnimation = animation;
}
public Animation getAnimation() {
return mAnimation;
}
public void setAnimation(Animation anim) {
mAnimation = anim;
}
public boolean hasStarted() {
return mAnimation != null && mAnimation.hasStarted();
}
public boolean hasEnded() {
return mAnimation == null || mAnimation.hasEnded();
}
@Override
public void draw(Canvas canvas) {
Drawable dr = getProxy();
if (dr != null) {
int sc = canvas.save();
Animation anim = mAnimation;
if (anim != null) {
anim.getTransformation(
AnimationUtils.currentAnimationTimeMillis(),
mTransformation);
canvas.concat(mTransformation.getMatrix());
}
dr.draw(canvas);
canvas.restoreToCount(sc);
}
}
} | 26.724138 | 68 | 0.625161 |
60c67776ac1426bd7754033e61036a78191f0328 | 1,107 | package com.ecnu.microservice.order.logic;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ecnu.microservice.order.clients.CatalogClient;
import com.ecnu.microservice.order.clients.CustomerClient;
@Service
class OrderService {
private OrderRepository orderRepository;
private CustomerClient customerClient;
private CatalogClient itemClient;
@Autowired
private OrderService(OrderRepository orderRepository,
CustomerClient customerClient, CatalogClient itemClient) {
super();
this.orderRepository = orderRepository;
this.customerClient = customerClient;
this.itemClient = itemClient;
}
public Order order(Order order) {
if (order.getNumberOfLines() == 0) {
throw new IllegalArgumentException("No order lines!");
}
if (!customerClient.isValidCustomerId(order.getCustomerId())) {
throw new IllegalArgumentException("Customer does not exist!");
}
return orderRepository.save(order);
}
public double getPrice(long orderId) {
return orderRepository.findOne(orderId).totalPrice(itemClient);
}
}
| 27.675 | 66 | 0.791328 |
a074b7dcbe84753ac2f1c4b534c4c820c1d575d7 | 3,179 | /*
* 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.bihealth.mi.easysmpc.performanceevaluation;
import java.util.Iterator;
import java.util.List;
import org.bihealth.mi.easysmpc.performanceevaluation.Combinator.Combination;
/**
* A class to combine the different parameters for the performance evaluation
*
* @author Felix Wirth
* @author Fabian Prasser
*/
public abstract class Combinator implements Iterable<Combination>, Iterator<Combination> {
/**
* A combination of possible parameters
*
* @author Felix Wirth
*/
public class Combination {
/** Participant */
private final int participants;
/** Bins */
private final int bins;
/** mailboxCheckInterval */
private final int mailboxCheckInterval;
/**
* Creates a new instance
*
* @param participants
* @param bins
* @param mailboxCheckInterval
*/
public Combination(int participants, int bins, int mailboxCheckInterval) {
this.participants = participants;
this.bins = bins;
this.mailboxCheckInterval = mailboxCheckInterval;
}
/**
* @return the bins
*/
protected int getBins() {
return bins;
}
/**
* @return the mailboxCheckInterval
*/
protected int getMailboxCheckInterval() {
return mailboxCheckInterval;
}
/**
* @return participants
*/
protected int getParticipants() {
return participants;
}
}
/** Possible participants */
private final List<Integer> participants;
/** Possible bins */
private final List<Integer> bins;
/** Possible mailboxCheckInterval */
private final List<Integer> mailboxCheckInterval;
/**
* @param participants
* @param bins
* @param mailboxCheckInterval
*/
public Combinator(List<Integer> participants,
List<Integer> bins,
List<Integer> mailboxCheckInterval) {
// Store
this.participants = participants;
this.bins = bins;
this.mailboxCheckInterval = mailboxCheckInterval;
}
/**
* @return the bins
*/
protected List<Integer> getBins() {
return bins;
}
/**
* @return the mailboxCheckInterval
*/
protected List<Integer> getMailboxCheckInterval() {
return mailboxCheckInterval;
}
/**
* @return the participants
*/
protected List<Integer> getParticipants() {
return participants;
}
}
| 26.491667 | 90 | 0.616232 |
472453e1e85d08d5307179085f0a0a77180536f5 | 1,013 | package fr.openwide.maven.artifact.notifier.core.business.search.service;
import java.io.File;
import java.util.List;
import fr.openwide.core.jpa.exception.ServiceException;
import fr.openwide.maven.artifact.notifier.core.business.search.model.ArtifactBean;
import fr.openwide.maven.artifact.notifier.core.business.search.model.ArtifactVersionBean;
import fr.openwide.maven.artifact.notifier.core.business.search.model.PomBean;
public interface IMavenCentralSearchApiService {
List<ArtifactBean> getArtifacts(String global, String groupId, String artifactId, int offset, int maxRows)
throws ServiceException;
long countArtifacts(String global, String groupId, String artifactId) throws ServiceException;
long countArtifacts(String artifactId) throws ServiceException;
PomBean searchFromPom(String xml) throws ServiceException;
PomBean searchFromPom(File file) throws ServiceException;
List<ArtifactVersionBean> getArtifactVersions(String groupId, String artifactId) throws ServiceException;
}
| 38.961538 | 107 | 0.837117 |
4144746e27cafdefe197e01f8fe9cf898ffb8d37 | 6,330 | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Twineworks GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.twineworks.tweakflow.lang.parse;
import com.twineworks.tweakflow.lang.ast.expressions.BinaryNode;
import com.twineworks.tweakflow.lang.ast.expressions.ExpressionNode;
import com.twineworks.tweakflow.lang.ast.structure.ModuleNode;
import com.twineworks.tweakflow.lang.ast.structure.VarDefNode;
import com.twineworks.tweakflow.lang.load.loadpath.ResourceLocation;
import com.twineworks.tweakflow.lang.parse.units.ResourceParseUnit;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static com.twineworks.tweakflow.lang.ast.NodeStructureAssert.assertThat;
import static org.assertj.core.api.Assertions.assertThat;
public class ParserBinaryLiteralsTest {
private HashMap<String, Map<String, VarDefNode>> moduleCache = new HashMap<>();
private synchronized Map<String, VarDefNode> getVars(String ofModule) {
if (!moduleCache.containsKey(ofModule)) {
Parser p = new Parser(
new ResourceParseUnit(new ResourceLocation.Builder().build(), ofModule)
);
ParseResult result = p.parseUnit();
if (result.isError()) {
result.getException().printDigestMessageAndStackTrace();
}
// parse is successful
assertThat(result.isSuccess()).isTrue();
// get the variable map
Map<String, VarDefNode> varMap = ((ModuleNode) result.getNode()).getLibraries().get(0).getVars().getMap();
moduleCache.put(ofModule, varMap);
}
return moduleCache.get(ofModule);
}
@Test
void parses_0b() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_empty").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[0]);
}
@Test
void parses_0b00() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_00").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {0});
}
@Test
void parses_0b01() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_01").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {1});
}
@Test
void parses_0b0001() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_0001").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {0, 1});
}
@Test
void parses_0b0100() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_0100").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {1, 0});
}
@Test
void parses_0baAbB() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_aAbB").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {(byte) 0xaA, (byte) 0xbB});
}
@Test
void parses_0bfAcE() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_fAcE").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {(byte) 0xfA, (byte) 0xcE});
}
@Test
void parses_0b0123456789abcdef() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_all").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {0x01, 0x23, 0x45, 0x67, (byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef});
}
@Test
void parses_0b____01_23_45_67_89_abcdef___() {
Map<String, VarDefNode> varDefMap = getVars("fixtures/tweakflow/analysis/parsing/literals/binaries.tf");
ExpressionNode expNode = varDefMap.get("bin_all_spacers").getValueExpression();
assertThat(expNode).isInstanceOf(BinaryNode.class);
BinaryNode node = (BinaryNode) expNode;
assertThat(node.getBytes()).isEqualTo(new byte[] {0x01, 0x23, 0x45, 0x67, (byte)0x89, (byte)0xab, (byte)0xcd, (byte)0xef});
}
} | 36.37931 | 127 | 0.735229 |
0758eedf2436d45ae2c45e5c4601d278bdaf4ea8 | 2,104 | package vectorwing.farmersdelight.common.loot.function;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonObject;
import net.minecraft.MethodsReturnNonnullByDefault;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.RecipeType;
import net.minecraft.world.item.crafting.SmokingRecipe;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.functions.LootItemConditionalFunction;
import net.minecraft.world.level.storage.loot.functions.LootItemFunctionType;
import net.minecraft.world.level.storage.loot.predicates.LootItemCondition;
import vectorwing.farmersdelight.FarmersDelight;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.Optional;
@MethodsReturnNonnullByDefault
@ParametersAreNonnullByDefault
public class SmokerCookFunction extends LootItemConditionalFunction
{
public static final ResourceLocation ID = new ResourceLocation(FarmersDelight.MODID, "smoker_cook");
protected SmokerCookFunction(LootItemCondition[] conditionsIn) {
super(conditionsIn);
}
@Override
protected ItemStack run(ItemStack stack, LootContext context) {
if (stack.isEmpty()) {
return stack;
} else {
Optional<SmokingRecipe> recipe = context.getLevel().getRecipeManager().getAllRecipesFor(RecipeType.SMOKING).stream()
.filter(r -> r.getIngredients().get(0).test(stack)).findFirst();
if (recipe.isPresent()) {
ItemStack result = recipe.get().getResultItem().copy();
result.setCount(result.getCount() * stack.getCount());
return result;
} else {
return stack;
}
}
}
@Override
@Nullable
public LootItemFunctionType getType() {
return null;
}
public static class Serializer extends LootItemConditionalFunction.Serializer<SmokerCookFunction>
{
@Override
public SmokerCookFunction deserialize(JsonObject _object, JsonDeserializationContext _context, LootItemCondition[] conditionsIn) {
return new SmokerCookFunction(conditionsIn);
}
}
}
| 34.491803 | 132 | 0.803707 |
516776a710c50b271649cd150807ef903b345fd2 | 460 | package hello.aop.exam.aop;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Slf4j
@Aspect
public class TraceAspect {
@Before("@annotation(hello.aop.exam.annotation.Trace)")
public void doTrace(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();
log.info("[trace] {} args={}", joinPoint.getSignature(), args);
}
}
| 25.555556 | 71 | 0.715217 |
0a4379a34a3cd5f8777b3f90988e2ae6962a3308 | 12,962 | package com.wecoo.qutianxia.view.wheelcity;
import android.app.Dialog;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.NumberPicker.OnValueChangeListener;
import android.widget.TextView;
import com.wecoo.qutianxia.R;
import com.wecoo.qutianxia.utils.LogUtil;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by mwl on 2016/11/23.
* 三级地址选取
*/
public class SelectAdressUtil implements OnClickListener, OnValueChangeListener {
private Context context;
private Dialog dialog;
private ChooseCityInterface cityInterface;
private NumberPicker npProvince, npCity, npCounty;
private TextView tvCancel, tvSure;
private String[] newCityArray = new String[4];
private String cityCode;
private List<ProvinceBean.ProvinceEntity> ProvinceList;
public void createDialog(Context context, String code, ChooseCityInterface cityInterface) {
this.context = context;
this.cityInterface = cityInterface;
this.cityCode = code;
ProvinceList = AsyncAdress.getAdressIntance(context).getCityList();
View view = LayoutInflater.from(context).inflate(R.layout.select_cities_layout, null);
dialog = new Dialog(context, R.style.Dialog_No_Board);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
dialog.addContentView(view, params);
dialog.show();
Window dialogWindow = dialog.getWindow();
dialogWindow.setGravity(Gravity.BOTTOM);
dialogWindow.setWindowAnimations(R.style.PopupAnimation);
dialog.setCanceledOnTouchOutside(true);
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
lp.width = context.getResources().getDisplayMetrics().widthPixels; // 设置宽度
dialog.getWindow().setAttributes(lp);
//初始化控件
tvCancel = (TextView) view.findViewById(R.id.selectCity_txt_cancel);
tvSure = (TextView) view.findViewById(R.id.selectCity_txt_sure);
tvCancel.setOnClickListener(this);
tvSure.setOnClickListener(this);
npProvince = (NumberPicker) view.findViewById(R.id.npProvince);
npCity = (NumberPicker) view.findViewById(R.id.npCity);
npCounty = (NumberPicker) view.findViewById(R.id.npCounty);
setNomal();
//省:设置选择器最小值、最大值、初始值
String[] provinceArray = new String[ProvinceList.size()];//初始化省数组
for (int i = 0; i < provinceArray.length; i++) {//省数组填充数据
provinceArray[i] = ProvinceList.get(i).getName();
}
npProvince.setDisplayedValues(provinceArray);//设置选择器数据、默认值
npProvince.setMinValue(0);
npProvince.setMaxValue(provinceArray.length - 1);
npProvince.setWrapSelectorWheel(false); // 取消循环滚动
if (TextUtils.isEmpty(cityCode) || cityCode.length() < 6) {
newCityArray[0] = ProvinceList.get(0).getName();
newCityArray[1] = "";
newCityArray[2] = "";
newCityArray[3] = ProvinceList.get(0).getCode();
npProvince.setValue(0);
changeCity(0);//联动市数据
} else {
for (int i = 0; i < ProvinceList.size(); i++) {
if (cityCode.substring(0, 2).equals(ProvinceList.get(i).getCode().substring(0, 2))) {
npProvince.setValue(i);
changeCity(i);//联动市数据
}
}
}
}
//根据省,联动市数据
private void changeCity(int provinceTag) {
List<CityEntity> cList = ProvinceList.get(provinceTag).getList();
if (cList == null || cList.size() < 1) {
cList = new ArrayList<CityEntity>();
CityEntity cityEntity = new CityEntity();
cityEntity.setName(" ");
cityEntity.setCode(ProvinceList.get(provinceTag).getCode());
cList.add(cityEntity);
}
String[] cityArray = new String[cList.size()];
for (int i = 0; i < cityArray.length; i++) {
cityArray[i] = cList.get(i).getName();
}
LogUtil.i("adressCity : " + Arrays.toString(cityArray));
try {
npCity.setMinValue(0);
npCity.setMaxValue(cityArray.length - 1);
npCity.setDisplayedValues(cityArray);//设置选择器数据、默认值
} catch (Exception e) {
npCity.setDisplayedValues(cityArray);//设置选择器数据、默认值
npCity.setMinValue(0);
npCity.setMaxValue(cityArray.length - 1);
}
if (TextUtils.isEmpty(cityCode) || cityCode.length() < 6) {
newCityArray[0] = ProvinceList.get(provinceTag).getName();
newCityArray[1] = cList.get(0).getName();
newCityArray[2] = "";
newCityArray[3] = cList.get(0).getCode();
npCity.setValue(0);
changeCounty(provinceTag, 0);//联动县数据
} else {
for (int i = 0; i < cList.size(); i++) {
if (cityCode.substring(0, 4).equals(cList.get(i).getCode().substring(0, 4))) {
npCity.setValue(i);
changeCounty(provinceTag, i);//联动县数据
return;
}
}
}
npCity.setWrapSelectorWheel(false); // 取消循环滚动
}
//根据市,联动县数据
private void changeCounty(int provinceTag, int cityTag) {
List<CountyEntity> xList = ProvinceList.get(provinceTag).getList().get(cityTag).getList();
if (xList == null || xList.size() < 1) {
xList = new ArrayList<CountyEntity>();
CountyEntity countyEntity = new CountyEntity();
countyEntity.setName(" ");
countyEntity.setCode(ProvinceList.get(provinceTag).getList().get(cityTag).getCode());
xList.add(countyEntity);
}
String[] countyArray = new String[xList.size()];
for (int i = 0; i < countyArray.length; i++) {
countyArray[i] = xList.get(i).getName();
}
LogUtil.i("adressCounty : " + Arrays.toString(countyArray));
try {
npCounty.setMinValue(0);
npCounty.setMaxValue(countyArray.length - 1);
npCounty.setDisplayedValues(countyArray);//设置选择器数据、默认值
} catch (Exception e) {
npCounty.setDisplayedValues(countyArray);//设置选择器数据、默认值
npCounty.setMinValue(0);
npCounty.setMaxValue(countyArray.length - 1);
}
if (TextUtils.isEmpty(cityCode) || cityCode.length() < 6) {
newCityArray[0] = ProvinceList.get(provinceTag).getName();
newCityArray[1] = ProvinceList.get(provinceTag).getList().get(cityTag).getName();
newCityArray[2] = xList.get(0).getName();
newCityArray[3] = xList.get(0).getCode();
npCounty.setValue(0);
} else {
for (int i = 0; i < xList.size(); i++) {
if (cityCode.equals(xList.get(i).getCode())) {
npCounty.setValue(i);
newCityArray[0] = ProvinceList.get(provinceTag).getName();
newCityArray[1] = ProvinceList.get(provinceTag).getList().get(cityTag).getName();
newCityArray[2] = xList.get(i).getName();
newCityArray[3] = xList.get(i).getCode();
}
}
}
npCounty.setWrapSelectorWheel(false); //取消循环滚动
}
//设置NumberPicker的分割线透明、字体颜色、设置监听
private void setNomal() {
//设置监听
npProvince.setOnValueChangedListener(this);
npCity.setOnValueChangedListener(this);
npCounty.setOnValueChangedListener(this);
//去除分割线
setNumberPickerDividerColor(npProvince);
setNumberPickerDividerColor(npCity);
setNumberPickerDividerColor(npCounty);
//设置字体颜色
setNumberPickerTextColor(npProvince, context.getResources().getColor(R.color.wecoo_gray5));
setNumberPickerTextColor(npCity, context.getResources().getColor(R.color.wecoo_gray5));
setNumberPickerTextColor(npCounty, context.getResources().getColor(R.color.wecoo_gray5));
}
//设置分割线颜色
private void setNumberPickerDividerColor(NumberPicker numberPicker) {
NumberPicker picker = numberPicker;
Field[] pickerFields = NumberPicker.class.getDeclaredFields();
for (Field pf : pickerFields) {
if (pf.getName().equals("mSelectionDivider")) {
pf.setAccessible(true);
try {
//设置分割线的颜色值
pf.set(picker, new ColorDrawable(context.getResources().getColor(R.color.wecoo_gray2)));// pf.set(picker, new Div)
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (Resources.NotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
break;
}
}
}
//设置选择器字体颜色
public static boolean setNumberPickerTextColor(NumberPicker numberPicker, int color) {
boolean result = false;
final int count = numberPicker.getChildCount();
for (int i = 0; i < count; i++) {
View child = numberPicker.getChildAt(i);
if (child instanceof EditText) {
try {
Field selectorWheelPaintField = numberPicker.getClass()
.getDeclaredField("mSelectorWheelPaint");
selectorWheelPaintField.setAccessible(true);
((Paint) selectorWheelPaintField.get(numberPicker)).setColor(color);
((EditText) child).setTextColor(color);
numberPicker.invalidate();
result = true;
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
return result;
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.selectCity_txt_cancel:
dialog.dismiss();
break;
case R.id.selectCity_txt_sure:
dialog.dismiss();
if ("市辖区".equals(newCityArray[1]) || "县".equals(newCityArray[1])){
newCityArray[1] = "";
}else if (newCityArray[0].equals(newCityArray[1])){
newCityArray[1] = "";
} else if (newCityArray[1].equals(newCityArray[2])){
newCityArray[1] = "";
}
cityInterface.sure(newCityArray);
break;
}
}
@Override
public void onValueChange(NumberPicker numberPicker, int i, int i1) {
switch (numberPicker.getId()) {
case R.id.npProvince:
cityCode = null;
// List<ProvinceBean> dataList = cityList;
// newCityArray[0] = ProvinceList.get(npProvince.getValue()).getName();
changeCity(npProvince.getValue());
// newCityArray[1] = ProvinceList.get(npProvince.getValue()).getList().get(0).getName();
// newCityArray[2] = ProvinceList.get(npProvince.getValue()).getList().get(0).getList().get(0).getName();
// newCityArray[3] = ProvinceList.get(npProvince.getValue()).getList().get(0).getList().get(0).getCode();
break;
case R.id.npCity:
cityCode = null;
// List<ProvinceBean.CityEntity> cList = ProvinceList.get(npProvince.getValue()).getList();
// newCityArray[1] = cList.get(npCity.getValue()).getName();
changeCounty(npProvince.getValue(), npCity.getValue());
// newCityArray[2] = cList.get(npCity.getValue()).getList().get(0).getName();
// newCityArray[3] = cList.get(npCity.getValue()).getList().get(0).getCode();
break;
case R.id.npCounty:
List<CountyEntity> countyList = ProvinceList.get(npProvince.getValue()).getList().get(npCity.getValue()).getList();
newCityArray[2] = countyList.get(npCounty.getValue()).getName();
newCityArray[3] = countyList.get(npCounty.getValue()).getCode();
break;
}
}
}
| 42.638158 | 134 | 0.59551 |
13930a69615871c4add87a36a94bbe0057bb32eb | 1,470 | package com.adelerobots.web.fiopre.listeners;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.treelogic.fawna.presentacion.componentes.event.api.GestorDatosComponentes;
import com.treelogic.fawna.presentacion.componentes.event.api.GestorEstadoComponentes;
import com.treelogic.fawna.presentacion.componentes.event.interfaces.IProcesadorDeAjaxChangeListener;
public class AddValueToList implements IProcesadorDeAjaxChangeListener{
/**
*
*/
private static final long serialVersionUID = -719412645714991747L;
private Integer valorID = null;
@SuppressWarnings("unchecked")
public void procesarAjaxChangeListener(GestorEstadoComponentes gestorEstados,
GestorDatosComponentes gestorDatos) {
/** Recuperar información del valor de la lista a insertar **/
String valorLista = (String) gestorDatos.getValue("valorLista");
if(!valorLista.equals("")){
List<Map<String, String>> items = (List<Map<String, String>>)gestorDatos.getValue("tablaValoresLista");
if(items == null || items.isEmpty()){
items = new ArrayList<Map<String,String>>();
valorID = 0;
}else{
valorID++;
}
Map<String, String> valorRow = new HashMap<String, String>();
valorRow.put("nombre", valorLista);
valorRow.put("valor_id", valorID.toString());
items.add(valorRow);
gestorDatos.setValue("tablaValoresLista", items);
gestorDatos.setValue("valorLista", "");
}
}
}
| 28.823529 | 106 | 0.74898 |
01ae9ebe83ffd3e3cc5169b1083b43a62ca2a528 | 3,174 | /*
* Decompiled with CFR <Could not determine version>.
*/
package org.apache.http.impl;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestFactory;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.RequestLine;
import org.apache.http.annotation.Contract;
import org.apache.http.annotation.ThreadingBehavior;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.util.Args;
@Contract(threading=ThreadingBehavior.IMMUTABLE)
public class DefaultHttpRequestFactory
implements HttpRequestFactory {
public static final DefaultHttpRequestFactory INSTANCE = new DefaultHttpRequestFactory();
private static final String[] RFC2616_COMMON_METHODS = new String[]{"GET"};
private static final String[] RFC2616_ENTITY_ENC_METHODS = new String[]{"POST", "PUT"};
private static final String[] RFC2616_SPECIAL_METHODS = new String[]{"HEAD", "OPTIONS", "DELETE", "TRACE", "CONNECT"};
private static final String[] RFC5789_ENTITY_ENC_METHODS = new String[]{"PATCH"};
private static boolean isOneOf(String[] methods, String method) {
String[] arr$ = methods;
int len$ = arr$.length;
int i$ = 0;
while (i$ < len$) {
String method2 = arr$[i$];
if (method2.equalsIgnoreCase(method)) {
return true;
}
++i$;
}
return false;
}
@Override
public HttpRequest newHttpRequest(RequestLine requestline) throws MethodNotSupportedException {
Args.notNull(requestline, "Request line");
String method = requestline.getMethod();
if (DefaultHttpRequestFactory.isOneOf(RFC2616_COMMON_METHODS, method)) {
return new BasicHttpRequest(requestline);
}
if (DefaultHttpRequestFactory.isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
return new BasicHttpEntityEnclosingRequest(requestline);
}
if (DefaultHttpRequestFactory.isOneOf(RFC2616_SPECIAL_METHODS, method)) {
return new BasicHttpRequest(requestline);
}
if (!DefaultHttpRequestFactory.isOneOf(RFC5789_ENTITY_ENC_METHODS, method)) throw new MethodNotSupportedException(method + " method not supported");
return new BasicHttpEntityEnclosingRequest(requestline);
}
@Override
public HttpRequest newHttpRequest(String method, String uri) throws MethodNotSupportedException {
if (DefaultHttpRequestFactory.isOneOf(RFC2616_COMMON_METHODS, method)) {
return new BasicHttpRequest(method, uri);
}
if (DefaultHttpRequestFactory.isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
return new BasicHttpEntityEnclosingRequest(method, uri);
}
if (DefaultHttpRequestFactory.isOneOf(RFC2616_SPECIAL_METHODS, method)) {
return new BasicHttpRequest(method, uri);
}
if (!DefaultHttpRequestFactory.isOneOf(RFC5789_ENTITY_ENC_METHODS, method)) throw new MethodNotSupportedException(method + " method not supported");
return new BasicHttpEntityEnclosingRequest(method, uri);
}
}
| 44.083333 | 156 | 0.713926 |
f372c41c78efb1da3ac63fb2436cc44b1ffc95d3 | 158 | /**
* This package only exists to avoid using reflection when accessing
* internal variables of Weka's classifier trees.
*/
package weka.classifiers.trees; | 31.6 | 68 | 0.772152 |
8ff685a104f825164711443c5013928a2037c0b0 | 991 | package student_player;
import java.util.ArrayList;
public class Node{
static final int WIN_SCORE = 10;
int level;
int opponent;
private final State state;
private Node parent;
private ArrayList<Node> childArray;
Node(State pState){
state = pState;
parent = null;
childArray = new ArrayList<>();
}
ArrayList<Node> getChildArray(){
return childArray;
}
State getState(){
return state;
}
public void setParent(Node pNode){
parent = pNode;
}
public Node getParent() {
return parent;
}
public Node getRandomChild(){
return childArray.get((int) (Math.random()%childArray.size()));
}
public Node getChildWithMaxScore(){
Node max = this.getRandomChild();
for(Node n: childArray){
if(max.getState().getWinScore() < n.getState().getWinScore()){
max = n;
}
}
return max;
}
}
| 19.82 | 74 | 0.57114 |
a887e52a8847440a4158e718640b1272da1a76fe | 2,777 | package com.webcheckers.ui;
import com.webcheckers.appl.PlayerLobby;
import com.webcheckers.model.Player;
import com.webcheckers.utils.Constants;
import spark.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.logging.Logger;
/**
* The UI Controller to GET the Home page.
*
* @author <a href='mailto:[email protected]'>Bryan Basham</a>
*/
public class GetHomeRoute implements Route {
private static final Logger LOG = Logger.getLogger(GetHomeRoute.class.getName());
public static final String TITLE = "Welcome!";
private final PlayerLobby playerLobby;
private final TemplateEngine templateEngine;
/**
* Create the Spark Route (UI controller) for the
* {@code GET /} HTTP request.
*
* @param templateEngine
* the HTML template rendering engine
*/
public GetHomeRoute(final PlayerLobby playerLobby, final TemplateEngine templateEngine) {
// validation
Objects.requireNonNull(templateEngine, "templateEngine must not be null");
//
this.playerLobby = playerLobby;
this.templateEngine = templateEngine;
//
LOG.config("GetHomeRoute is initialized.");
}
/**
* Render the WebCheckers Home page.
*
* @param request the HTTP request
* @param response the HTTP response
* @return the rendered HTML for the Home page
*/
@Override
public Object handle(Request request, Response response) {
LOG.finer("GetHomeRoute is invoked.");
Map<String, Object> vm = new HashMap<>();
vm.put(Constants.TITLE, TITLE);
vm.put(Constants.NUM_USER, playerLobby.getPlayers().size());
final Session currentSession = request.session();
if (currentSession.attribute(Constants.SIGNED_IN_PLAYER) != null ) {
String myUserName = currentSession.attribute(Constants.PLAYER_NAME);
Player player = playerLobby.getPlayerByUsername(myUserName);
if(player != null && player.isInGame()){
response.redirect(Constants.GAME_URL);
}
}
if (currentSession.attribute(Constants.BUSY_OPPONENT_ERROR) == null){
currentSession.attribute(Constants.BUSY_OPPONENT_ERROR, false);
}
String thisPlayerName = currentSession.attribute(Constants.PLAYER_NAME);
vm.put(Constants.SIGNED_IN_PLAYER, playerLobby.isActiveUser(thisPlayerName));
vm.put(Constants.BUSY_OPPONENT_ERROR, currentSession.attribute(Constants.BUSY_OPPONENT_ERROR));
vm.put(Constants.FREE_PLAYERS, playerLobby.getFreePlayerNames(thisPlayerName));
vm.put(Constants.PLAYER_NAME, thisPlayerName);
return templateEngine.render(new ModelAndView(vm, "home.ftl"));
}
} | 34.7125 | 103 | 0.684192 |
a921d90d541f39e17485e7c760793c3565d9b567 | 1,429 | package org.blacksmith.finlib.datetime.calendar;
import java.time.LocalDate;
import java.util.Set;
import org.blacksmith.finlib.datetime.calendar.extractor.DateExtractor;
import org.blacksmith.finlib.datetime.calendar.policy.DatePartHolidayPolicy;
import org.blacksmith.finlib.datetime.calendar.provider.DatePartInMemoryProvider;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class YearMonthDayPolicyTest {
@Test
public void holidayByYearMonthDay() {
Set<LocalDate> days = Set.of(
LocalDate.of(2019, 5, 15),
LocalDate.of(2019, 6, 10));
HolidayPolicy policy = DatePartHolidayPolicy.of(DateExtractor.getInstance(),
DatePartInMemoryProvider.of(days));
assertFalse(policy.isHoliday(LocalDate.of(2019, 1, 15)));
assertTrue(policy.isHoliday(LocalDate.of(2019, 5, 15)));
assertFalse(policy.isHoliday(LocalDate.of(2019, 5, 20)));
assertTrue(policy.isHoliday(LocalDate.of(2019, 6, 10)));
assertFalse(policy.isHoliday(LocalDate.of(2019, 6, 11)));
assertFalse(policy.isHoliday(LocalDate.of(2020, 1, 15)));
assertFalse(policy.isHoliday(LocalDate.of(2020, 5, 15)));
assertFalse(policy.isHoliday(LocalDate.of(2020, 5, 20)));
assertFalse(policy.isHoliday(LocalDate.of(2020, 6, 10)));
assertFalse(policy.isHoliday(LocalDate.of(2020, 6, 11)));
}
}
| 40.828571 | 81 | 0.751575 |
0b149886db477c60b1a6f9e68f6429ca1c5359c8 | 221 | package com.andersonmarques.bvp.exception;
public class LoginInvalidoException extends RuntimeException{
private static final long serialVersionUID = 1L;
public LoginInvalidoException(String msg) {
super(msg);
}
} | 24.555556 | 61 | 0.80543 |
f33777646c7a0eb7fb80fd68b2b0a41a16ce32d8 | 2,486 | /*
* package tests;
*
* import base.BaseTest; import lombok.extern.slf4j.Slf4j; import
* org.testng.Reporter; import org.testng.annotations.Parameters; import
* org.testng.annotations.Test;
*
* import pages.Dashboard; import pages.LoginPage; import pages.SecureAreaPage;
*
* import static org.testng.Assert.assertTrue;
*
* import static utils.Timers.getDurationInMillisFrom; import static
* utils.Timers.setTimestamp;
*
* @Slf4j public class LoginTests extends BaseTest {
*
* @Test(groups = "end2end")
*
* @Parameters({"email", "password"}) public void testSuccessfulLogin(String
* email, String password){
*
* //Start timer setTimestamp("testSuccessfulLogin");
*
* // LoginPage loginPage = homePage.clickFormAuthentication();
* loginPage.setEmail(email); Reporter.log("Enter email: " + email);
* log.debug("Once before all tests within this class");
* loginPage.setPassword(password); Reporter.log("Enter password: " + password);
* Dashboard dashboardPage = loginPage.clickLoginButton(); //
* dashboardPage.getHeaderText();
*
* assertTrue(dashboardPage.getAlertText()
* .contains("You logged into a secure area!") , "Alert text is incorrect");
*
* //Report duration Reporter.log("Test duration: " +
* getDurationInMillisFrom("testSuccessfulLogin") + " ms");
*
* //Log duration
* log.debug(Long.toString(getDurationInMillisFrom("testSuccessfulLogin")));
* System.out.println(getDurationInMillisFrom("testSuccessfulLogin")); long
* maxDuration = 2000L;
*
* assertTrue(maxDuration >= getDurationInMillisFrom("testSuccessfulLogin")); }
*
* @Test(groups = "end2end") public void testSuccessfulLogin1() throws
* InterruptedException {
*
* loginPage.setEmail("[email protected]");
* loginPage.setPassword("SCCTest@2021"); SecureAreaPage secureAreaPage =
* loginPage.clickSignInButton(); secureAreaPage.getAlertText();
* assertTrue(secureAreaPage.getAlertText()
* .contains("You logged into a secure area!") , "Alert text is incorrect"); }
*
* @Test(groups = "end2end") public void testSuccessfulLogin2() throws
* InterruptedException { LoginPage loginPage =
* homePage.clickFormAuthentication();
* loginPage.setUsername("[email protected]");
* loginPage.setPassword("CCTest@2021"); SecureAreaPage secureAreaPage =
* loginPage.clickLoginButton(); secureAreaPage.getAlertText();
* assertTrue(secureAreaPage.getAlertText()
* .contains("You logged into a secure area!") , "Alert text is incorrect"); } }
*/ | 40.754098 | 80 | 0.736525 |
a2816f90e6528b1ec9151eefddb6eadc6c25c313 | 4,217 | package com.alsash.reciper.mvp.presenter;
import android.support.annotation.UiThread;
import android.support.annotation.WorkerThread;
import com.alsash.reciper.logic.BusinessLogic;
import com.alsash.reciper.logic.StorageLogic;
import com.alsash.reciper.mvp.model.entity.BaseEntity;
import com.alsash.reciper.mvp.model.entity.Recipe;
import com.alsash.reciper.mvp.view.BaseListView;
import com.alsash.reciper.mvp.view.RecipeListView;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* An abstract presenter that represents list of recipes, grouped by any id
*
* @param <G> - Entity, that represents group of recipes
* @param <V> - view, that can be attached to this presenter
*/
public abstract class BaseRecipeGroupPresenter<G extends BaseEntity, V extends BaseListView<G>>
extends BaseListPresenter<G, V> {
private final int recipesLimit;
private final Map<G, List<Recipe>> prefetchedRecipes;
private final Map<G, RecipeGroupInnerPresenter<G>> presenters;
public BaseRecipeGroupPresenter(int groupsLimit, int recipesLimit) {
super(groupsLimit);
this.recipesLimit = recipesLimit;
this.prefetchedRecipes = Collections.synchronizedMap(
new HashMap<G, List<Recipe>>());
this.presenters = Collections.synchronizedMap(
new HashMap<G, RecipeGroupInnerPresenter<G>>());
}
protected abstract StorageLogic getStorageLogic();
protected abstract BusinessLogic getBusinessLogic();
@WorkerThread
protected abstract List<G> loadNextGroups(int offset, int limit);
@WorkerThread
protected abstract List<Recipe> loadNextRecipes(G group, int offset, int limit);
public boolean canOpenGroup(G group) {
return group.getId() == null || presenters.get(group).getModels().size() > 0;
}
@Override
public void refresh(V view) {
prefetchedRecipes.clear();
presenters.clear();
super.refresh(view);
}
@Override
protected void refresh() {
prefetchedRecipes.clear();
presenters.clear();
super.refresh();
}
@Override
protected void clear(WeakReference<V> viewRef) {
prefetchedRecipes.clear();
presenters.clear();
super.clear(viewRef);
}
@WorkerThread
@Override
protected List<G> loadNext(int offset, int limit) {
List<G> groups = loadNextGroups(offset, limit);
// Prefetch Recipes by group
synchronized (prefetchedRecipes) {
for (G group : groups) {
prefetchedRecipes.put(group, loadNextRecipes(group, 0, recipesLimit));
}
}
return groups;
}
@UiThread
public BaseRecipeListPresenter<RecipeListView> getInnerPresenter(G group) {
RecipeGroupInnerPresenter<G> presenter = presenters.get(group);
if (presenter == null) {
presenter = new RecipeGroupInnerPresenter<>(recipesLimit, group, this);
presenters.put(group, presenter);
List<Recipe> recipes = prefetchedRecipes.get(group);
if (recipes != null) presenter.getModels().addAll(recipes);
}
return presenter;
}
/**
* An inner presenter, that helps to represent inner list of Recipes
*
* @param <G> - Entity, that represents group of recipes
*/
private static class RecipeGroupInnerPresenter<G extends BaseEntity>
extends BaseRecipeListPresenter<RecipeListView> {
private final BaseRecipeGroupPresenter<G, ?> outerPresenter;
private final G group;
public RecipeGroupInnerPresenter(int limit,
G group,
BaseRecipeGroupPresenter<G, ?> outerPresenter) {
super(limit, outerPresenter.getStorageLogic(), outerPresenter.getBusinessLogic());
this.group = group;
this.outerPresenter = outerPresenter;
}
@Override
protected List<Recipe> loadNext(int offset, int limit) {
return outerPresenter.loadNextRecipes(group, offset, limit);
}
}
}
| 33.468254 | 95 | 0.664453 |
e6c09e02fecb399856be17982eb290fd74f12d8c | 3,226 | package net.sytes.surfael.api;
import android.content.Context;
import java.io.IOException;
import java.net.SocketException;
import net.sytes.surfael.api.ApiReceiveInterface;
import net.sytes.surfael.api.ApiSendFacade;
import net.sytes.surfael.api.control.sync.ClientStream;
import net.sytes.surfael.api.control.sync.Status;
import net.sytes.surfael.api.model.clients.Client;
import net.sytes.surfael.api.model.exceptions.ServerException;
import net.sytes.surfael.api.model.messages.DisconnectionMessage;
import net.sytes.surfael.api.model.messages.History;
import net.sytes.surfael.api.model.messages.Message;
import net.sytes.surfael.api.model.messages.NormalMessage;
import net.sytes.surfael.api.model.messages.ServerMessage;
import net.sytes.surfael.data.Session;
public class ApiReceiveFromServerThread implements Runnable {
private Client fbClient;
private ClientStream stream = ClientStream.getInstance();
private ApiReceiveInterface api;
private boolean suicide = false;
private String email;
private String password;
private boolean crypt;
private Context context;
public void setContext(Context context) {
this.context = context;
}
@Override
public void run() {
Status.getInstance().setConnected(true);
if (fbClient != null) {
ApiSendFacade.loginFacebook(fbClient);
} else {
ApiSendFacade.login(email, password, crypt);
}
while (!suicide) {
try {
final Object o = stream.receiveMessage();
api.onReceive(o);
if (o instanceof Message) {
if (o instanceof NormalMessage) {
api.onReceiveNormalMessage((NormalMessage) o);
} else if (o instanceof DisconnectionMessage) {
Status.getInstance().setConnected(false);
Status.getInstance().setLoggedIn(false);
api.onReceiveDisconnectionMessage((DisconnectionMessage) o);
break;
} else if (o instanceof ServerMessage) {
api.onReceiveServerMessage((ServerMessage) o);
}
} else if (o instanceof Client) {
Status.getInstance().setLoggedIn(true);
api.onReceiveClient((Client) o);
} else if (o instanceof ServerException) {
Status.getInstance().setConnected(false);
Status.getInstance().setLoggedIn(false);
suicide = true;
api.onConnectionError(new Exception(((ServerException) o).getMessage()));
} else if (o instanceof History) {
api.onReceiveServerHistory((History) o);
}
} catch (ClassNotFoundException | IOException e) {
Status.getInstance().setConnected(false);
// Status.getInstance().setLoggedIn(false);
e.printStackTrace();
suicide = true;
api.onConnectionError(e);
}
}
suicide = !Status.getInstance().isConnected();
}
public ApiReceiveFromServerThread(ApiReceiveInterface apiBridge) {
this.api = apiBridge;
}
public ApiReceiveFromServerThread() {
}
public void overwriteListener(ApiReceiveInterface apiBridge) {
this.api = apiBridge;
}
public void killThread() {
suicide = true;
}
public void setFacebookClient(Client client) {
this.fbClient = client;
}
public void setEmail(String email) {
this.email = email;
}
public void setPassword(String password) {
this.password = password;
}
public void setCrypt(boolean crypt) {
this.crypt = crypt;
}
}
| 28.298246 | 78 | 0.736206 |
b64257d2a72e3d382d3de23132af6db512137109 | 2,449 | /*
* (C) Copyright 2018 VILMAA.
*
* 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 vilmaa.genome.analysis.mr;
import vilmaa.genome.analysis.models.avro.GeneSummary;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicReference;
/**
* Created by mh719 on 27/02/2017.
*/
public class GeneSummaryCombiner extends Reducer<Text, ImmutableBytesWritable, Text, ImmutableBytesWritable> {
private GeneSummaryReadWrite readWrite;
@Override
protected void setup(Context context) throws IOException, InterruptedException {
super.setup(context);
init();
}
void init() {
readWrite = new GeneSummaryReadWrite();
}
@Override
protected void reduce(Text key, Iterable<ImmutableBytesWritable> values, Context context) throws IOException, InterruptedException {
context.getCounter("vilmaa", "combine").increment(1);
GeneSummary geneSummary = combine(values);
context.write(key, new ImmutableBytesWritable(readWrite.write(geneSummary)));
}
public GeneSummary combine(Iterable<ImmutableBytesWritable> values) {
Set<Integer> cases = new HashSet<>();
Set<Integer> ctl = new HashSet<>();
AtomicReference<GeneSummary> tmp = new AtomicReference<>();
values.forEach(gs -> {
GeneSummary read = readWrite.read(gs.get(), tmp.get());
cases.addAll(read.getCases());
ctl.addAll(read.getControls());
tmp.set(read);
});
// reuse
GeneSummary summary = tmp.get();
summary.getCases().clear();
summary.getCases().addAll(cases);
summary.getControls().clear();
summary.getControls().addAll(ctl);
return summary;
}
}
| 33.547945 | 136 | 0.690486 |
9d9d0042423c0c68654e9fd785053cb0dc3780e0 | 604 | package com.umg.ventas.core.ies.bo;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Set;
@Data
@Table(name = "proveedores")
@Entity
public class Proveedor implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "codigo_proveedor")
private Long codigoProveedor;
@Column(name = "nit")
private String nit;
@Column(name = "razon_social")
private String razonSocial;
@Column(name = "paginaWeb")
private String paginaWeb;
@Column(name = "contacto_principal")
private String contactoPrincipal;
}
| 22.37037 | 53 | 0.746689 |
52bf83a49ca930196a6b77cf2eaadc849272fe49 | 2,110 | package com.testing.pageObjects.pages;
import org.openqa.selenium.By;
import net.thucydides.core.annotations.DefaultUrl;
@DefaultUrl("/")
public class HomePage extends BasePage {
// Locators ----------------------------------------------------------------------------------------------------------
public static By BODY = css("body");
public static By TOP_LOGO = css("a[href*='demoqa.com']");
public static By BANNER = css("img[alt='New Live Session']");
public static By ELEMENTS = text("Elements");
public static By FORMS = text("Forms");
public static By ALERTS_FRAME_AND_WINDOWS = text("Alerts, Frame & Windows");
public static By WIDGETS = text("Widgets");
public static By INTERACTIONS = text("Interactions");
public static By BOOK_STORE_APPLICATION = text("Book Store Application");
// Common elements ---------------------------------------------------------------------------------------------------
// These elements are found in multiple pages, therefore we are defining them in a parent HomePage (parent class)
public static By FIRST_NAME_FIELD = css("input[id='firstName']");
public static By LAST_NAME_FIELD = css("input[id='lastName']");
public static By EMAIL_FIELD = css("input[id=userEmail]");
public static By SUBMIT_BUTTON = id("submit");
public static By CURRENT_ADDRESS_FIELD = css("textarea[id='currentAddress']");
public static By YEAR_PICKER = css("[class*='react-datepicker__year']");
public static By MONTH_PICKER = css("select.react-datepicker__month-select");
public static By CURRENT_MONTH_DATES = xpath("//div[(contains(@class, 'react-datepicker__day--')) and not(contains(@class, 'outside'))]");
// Public methods ----------------------------------------------------------------------------------------------------
public void waitForPageToLoad() {
getElement(BANNER).waitUntilPresent();
logWeAreOnPage();
}
public void click(String elementName){
if(elementName.contains("_OPTION")) scrollIntoView(elementName);
super.click(elementName);
if(elementName.contains("_OPTION")) scrollIntoView(TOP_LOGO);
}
}
| 51.463415 | 140 | 0.624171 |
593f7f5eb50224108196c380b5248f3212c8ccc8 | 482 | package com.java.offer;
//左旋转字符串
/*
* 我的思路就是:先将字符串转成字符数组,然后先将从n到最后的字符加入字符串中,
* 然后再将前n个字符加入字符串中
* 运行时间33ms
* 占用内存629k
*/
public class Solution14 {
public String LeftRotateString(String str, int n){
if(str == null || n > str.length()){
return "";
}
StringBuffer sb = new StringBuffer();
char [] ch = str.toCharArray();
for(int i = n; i < ch.length; i++){
sb.append(ch[i]);
}
for(int i = 0; i < n; i++){
sb.append(ch[i]);
}
return sb.toString();
}
}
| 18.538462 | 51 | 0.609959 |
41105b935e11c588c73440eed147c2683267cff2 | 240 | package org.metasyntactic.automata.compiler.python.scanner;
public class WhitespaceToken extends PythonToken {
public WhitespaceToken(String text) {
super(text);
}
public Type getTokenType() {
return Type.Whitespace;
}
}
| 20 | 59 | 0.741667 |
3d1cdf17e40464796aab1f19d19d03a46e6e9253 | 1,416 | package com.google.common.collect;
import java.util.Comparator;
import java.util.Map.Entry;
public final class ImmutableListMultimap$Builder<K, V> extends ImmutableMultimap$Builder<K, V> {
public ImmutableListMultimap$Builder<K, V> put(K key, V value) {
super.put(key, value);
return this;
}
public ImmutableListMultimap$Builder<K, V> put(Entry<? extends K, ? extends V> entry) {
super.put(entry);
return this;
}
public ImmutableListMultimap$Builder<K, V> putAll(K key, Iterable<? extends V> values) {
super.putAll((Object) key, (Iterable) values);
return this;
}
public ImmutableListMultimap$Builder<K, V> putAll(K key, V... values) {
super.putAll((Object) key, (Object[]) values);
return this;
}
public ImmutableListMultimap$Builder<K, V> putAll(Multimap<? extends K, ? extends V> multimap) {
super.putAll(multimap);
return this;
}
public ImmutableListMultimap$Builder<K, V> orderKeysBy(Comparator<? super K> keyComparator) {
super.orderKeysBy(keyComparator);
return this;
}
public ImmutableListMultimap$Builder<K, V> orderValuesBy(Comparator<? super V> valueComparator) {
super.orderValuesBy(valueComparator);
return this;
}
public ImmutableListMultimap<K, V> build() {
return (ImmutableListMultimap) super.build();
}
}
| 30.782609 | 101 | 0.661017 |
4d3991a061b3625337da2574a3147e6c393021cc | 2,681 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 行业代理收单接口
*
* @author auto create
* @since 1.0, 2017-05-10 11:09:03
*/
public class AlipayCommerceTradeApplyModel extends AlipayObject {
private static final long serialVersionUID = 3857256826476669949L;
/**
* 订单费用详情,用于在订单确认页面展示
*/
@ApiField("amount_detail")
private String amountDetail;
/**
* 接口请求渠道编码,由支付宝提供
*/
@ApiField("channel")
private String channel;
/**
* 接口版本号
*/
@ApiField("interface_version")
private String interfaceVersion;
/**
* 用于标识操作模型,由支付宝配置提供
*/
@ApiField("op_code")
private String opCode;
/**
* 场景的数据表示. json 数组格式,根据场景不同的模型传入不同参数,由支付宝负责提供参数集合
*/
@ApiField("order_detail")
private String orderDetail;
/**
* 用于标识数据模型,由支付宝配置提供
*/
@ApiField("scene_code")
private String sceneCode;
/**
* 场景覆盖的目标人群标识,支持支付宝userId、身份证号、支付宝登录号、支付宝绑定手机号;
*/
@ApiField("target_id")
private String targetId;
/**
* 场景覆盖人群id类型
*/
@ApiField("target_id_type")
private String targetIdType;
/**
* 交易请求参数
*/
@ApiField("trade_apply_params")
private TradeApplyParams tradeApplyParams;
public String getAmountDetail() {
return this.amountDetail;
}
public void setAmountDetail(String amountDetail) {
this.amountDetail = amountDetail;
}
public String getChannel() {
return this.channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
public String getInterfaceVersion() {
return this.interfaceVersion;
}
public void setInterfaceVersion(String interfaceVersion) {
this.interfaceVersion = interfaceVersion;
}
public String getOpCode() {
return this.opCode;
}
public void setOpCode(String opCode) {
this.opCode = opCode;
}
public String getOrderDetail() {
return this.orderDetail;
}
public void setOrderDetail(String orderDetail) {
this.orderDetail = orderDetail;
}
public String getSceneCode() {
return this.sceneCode;
}
public void setSceneCode(String sceneCode) {
this.sceneCode = sceneCode;
}
public String getTargetId() {
return this.targetId;
}
public void setTargetId(String targetId) {
this.targetId = targetId;
}
public String getTargetIdType() {
return this.targetIdType;
}
public void setTargetIdType(String targetIdType) {
this.targetIdType = targetIdType;
}
public TradeApplyParams getTradeApplyParams() {
return this.tradeApplyParams;
}
public void setTradeApplyParams(TradeApplyParams tradeApplyParams) {
this.tradeApplyParams = tradeApplyParams;
}
}
| 20.007463 | 70 | 0.694144 |
b8e2a8ddec66328503a889afa7a367eca6d5cd6a | 1,378 | package com.example.application.calendar;
import com.example.application.calendar.EventsJSONConverter;
import org.junit.BeforeClass;
import org.junit.Test;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class EventsJSONConverterTest {
public static EventsJSONConverter eventsJSONConverter;
private final DateFormat JSONFormat = new SimpleDateFormat("yyyy-MM-dd");
@BeforeClass
public static void beforeClass(){
eventsJSONConverter = new EventsJSONConverter();
}
@Test
public void AddDaysToDateTest() throws NoSuchMethodException,
InvocationTargetException, IllegalAccessException, ParseException {
Date date = JSONFormat.parse("1999-08-20");
Method method = EventsJSONConverter.class.getDeclaredMethod("addDaysToDate",Date.class,Integer.class);
method.setAccessible(true);
Date output = (Date) method.invoke(eventsJSONConverter,date,1);
assertEquals(output.toString(),"Sat Aug 21 00:00:00 CEST 1999");
}
} | 32.046512 | 110 | 0.748186 |
2ce0449b7058a609e98f6a7bdba45ed987fc3f10 | 751 | package com.blogspot.toomuchcoding.book.chapter3._6_MockingFinalClassesPowerMock;
import com.blogspot.toomuchcoding.person.Person;
public final class TaxService {
public static final double POLAND_TAX_FACTOR = 0.3;
public static final double DEFAULT_TAX_FACTOR = 0.5;
public static final String POLAND = "Poland";
public double calculateTaxFactorFor(Person person) {
if (POLAND.equalsIgnoreCase(person.getCountryName())) {
return POLAND_TAX_FACTOR;
}
return DEFAULT_TAX_FACTOR;
}
public void updateTaxData(double taxFactor, Person person) {
System.out.printf("Calling web service with tax factor [%s]to update person [%s] tax data%n", taxFactor, person.getName());
}
}
| 27.814815 | 131 | 0.71771 |
8f0d3e5abc6cfe75e1ff489154327ba09f7cb2d0 | 641 | package org.osmdroid.tileprovider.modules;
/**
* @author Fabrice Fontaine
* Used to be embedded in MapTileModuleProviderBase
* <p>
* Thrown by a tile provider module in TileLoader.loadTile() to signal that it can no longer
* function properly. This will typically clear the pending queue.
* @since 6.0.2
*/
public class CantContinueException extends Exception {
private static final long serialVersionUID = 146526524087765133L;
public CantContinueException(final String pDetailMessage) {
super(pDetailMessage);
}
public CantContinueException(final Throwable pThrowable) {
super(pThrowable);
}
}
| 29.136364 | 92 | 0.74415 |
26d625532286dc74d57801f8f069da6fd4f56832 | 1,958 | /*******************************************************************************
* Copyright 2020 Pinterest, 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.pinterest.orion.core.automation.operator;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.pinterest.orion.core.Cluster;
public class OperatorContainer {
private static Logger logger = Logger.getLogger(OperatorContainer.class.getName());
private Operator operator;
private volatile boolean previousSuccess = true;
private volatile String previousOutput = "";
private volatile Exception previousError;
public OperatorContainer(Operator operator) {
this.operator = operator;
}
public void operate(Cluster cluster) {
try {
operator.setMessage("");
operator.operate(cluster);
previousSuccess = true;
previousError = null;
} catch (Exception e) {
previousSuccess = false;
previousError = e;
logger.log(Level.SEVERE, "Operator " + operator.getName() + " failed", e);
}
previousOutput = operator.getMessage();
}
public Operator getOperator() {
return operator;
}
public boolean isPreviousSuccess() {
return previousSuccess;
}
public String getPreviousOutput() {
return previousOutput;
}
public Exception getPreviousError() {
return previousError;
}
}
| 30.59375 | 85 | 0.6619 |
ec737e98ed5ded3eed5417c2d581953746f19a8d | 546 | package optifine;
import net.minecraft.util.BlockPos;
import net.minecraft.world.ColorizerFoliage;
import net.minecraft.world.IBlockAccess;
final class CustomColors$3 implements CustomColors.IColorizer {
public int getColor(IBlockAccess p_getColor_1_, BlockPos p_getColor_2_) {
return CustomColors.access$200() != null ? CustomColors.access$200().getColor(p_getColor_1_, p_getColor_2_) : ColorizerFoliage.getFoliageColorPine();
}
public boolean isColorConstant() {
return CustomColors.access$200() == null;
}
}
| 34.125 | 157 | 0.763736 |
54e89b5365607acc15c1d50e5d05ef2059aba90c | 1,985 | package org.xbib.netty.http.server.api;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpMethod;
import org.xbib.net.URL;
import org.xbib.netty.http.common.HttpParameters;
import javax.net.ssl.SSLSession;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
public interface ServerRequest {
Builder getBuilder();
InetSocketAddress getLocalAddress();
InetSocketAddress getRemoteAddress();
URL getURL();
List<String> getContext();
Map<String, String> getPathParameters();
String getRequestURI();
HttpMethod getMethod();
HttpHeaders getHeaders();
String getHeader(String name);
HttpParameters getParameters();
String getContextPath();
String getEffectiveRequestPath();
Integer getSequenceId();
Integer getStreamId();
Long getRequestId();
ByteBuf getContent();
String getContent(Charset charset);
ByteBufInputStream getInputStream();
SSLSession getSession();
URL getBaseURL();
URL getContextURL();
Domain<? extends EndpointResolver<? extends Endpoint<?>>> getDomain();
EndpointResolver<? extends Endpoint<?>> getEndpointResolver();
Endpoint<?> getEndpoint();
interface Builder {
String getRequestURI();
HttpMethod getMethod();
HttpHeaders getHeaders();
String getEffectiveRequestPath();
Builder setBaseURL(URL baseURL);
Builder setDomain(Domain<? extends EndpointResolver<? extends Endpoint<?>>> domain);
Builder setEndpointResolver(EndpointResolver<? extends Endpoint<?>> endpointResolver);
Builder setEndpoint(Endpoint<?> endpoint);
Builder setContext(List<String> context);
Builder addPathParameter(String key, String value);
ServerRequest build();
void release();
}
}
| 21.117021 | 94 | 0.704786 |
424af9fd5b34c57958b2744fbff4388eac7c5831 | 100 | package org.ttrzcinski.dictionaries;
public enum Binding {
NONE,
DASHES,
UNDERSCORES
}
| 12.5 | 36 | 0.7 |
f4a1c5053dc5db3a3390ae812e5dc50f80a1f1a8 | 199 | package work.lollipops.循环依赖;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class B {
@Autowired
private A a;
}
| 18.090909 | 62 | 0.809045 |
2b7d5da8d11a460bf1e5d4d0255e562f84d68700 | 2,209 | package robtest.stateinterfw.examples.openStack;
import robtest.stateinterfw.*;
import robtest.stateinterfw.data.TestStateVerdictItem;
import robtest.stateinterfw.examples.openStack.content.OpenStackUserContent;
import robtest.stateinterfw.openStack.cli.waiters.PowerOnWaiter;
public class OpenStackTestStateCommand extends TestStateCommand implements IOpenStackTestStateCommand {
private OpenStackTestExecutionContextWrapper contextWrapper;
public OpenStackTestStateCommand() {
this.configure();
}
@Override
public ITestStateVerdict command(ITestExecutionContext testExecutionContext, ITestInput testInput) {
this.contextWrapper = new OpenStackTestExecutionContextWrapper(testExecutionContext);
return super.command(testExecutionContext, testInput);
}
OpenStackUserContent getUserContent() {
return contextWrapper.getUserContent();
}
private void configure() {
add("compute.flavor.created", this::flavorCreated);
add("image.created", this::imageCreated);
add("compute.server.created", this::serverCreated);
add("compute.server.poweron", this::serverPowerOn);
}
protected ITestStateVerdictItem flavorCreated(ITestState state, ITestInputArgs args) {
return TestStateVerdictItem.createPassOk(state);
}
protected ITestStateVerdictItem imageCreated(ITestState state, ITestInputArgs args) {
return TestStateVerdictItem.createPassOk(state);
}
protected ITestStateVerdictItem serverCreated(ITestState state, ITestInputArgs args) {
return TestStateVerdictItem.createPassOk(state);
}
protected ITestStateVerdictItem serverPowerOn(ITestState state, ITestInputArgs args) {
var userContent = getUserContent();
var name = args.get("name").getDataValue();
var result = new PowerOnWaiter(userContent.getId(), name, state.getState().getTimeout()).waitCondition();
if (result.get()) {
return TestStateVerdictItem.createPassOk(state, result.getTimeSpent());
} else {
return TestStateVerdictItem.createInvalidStateError(state, result.getTimeSpent(), "Server could not power on");
}
}
}
| 40.163636 | 123 | 0.742417 |
1b4e77380cc2fd101a33e4c1820ded95c9e9313e | 1,510 | package org.openbaton.tosca.templates.TopologyTemplate.Nodes.CP;
import java.util.Map;
/**
* Created by rvl on 17.08.16.
*/
public class CPProperties {
private String type = null;
private boolean anti_spoof_protection = false;
private String floatingIP = null;
public CPProperties(Object properties) {
Map<String, Object> propertiesMap = (Map<String, Object>) properties;
if (propertiesMap.containsKey("type")) {
this.type = (String) propertiesMap.get("type");
}
if (propertiesMap.containsKey("anti_spoof_protection")) {
this.anti_spoof_protection = (Boolean) propertiesMap.get("anti_spoof_protection");
}
if (propertiesMap.containsKey("floatingIP")) {
this.floatingIP = (String) propertiesMap.get("floatingIP");
}
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean getAnti_spoof_protection() {
return anti_spoof_protection;
}
public void setAnti_spoof_protection(boolean anti_spoof_protection) {
this.anti_spoof_protection = anti_spoof_protection;
}
public String getFloatingIP() {
return floatingIP;
}
public void setFloatingIP(String floatingIP) {
this.floatingIP = floatingIP;
}
@Override
public String toString() {
return "CP Properties: \n"
+ "Type: "
+ type
+ "\n"
+ "FloatingIp: "
+ floatingIP
+ "\n"
+ "AntiSpoof: "
+ anti_spoof_protection;
}
}
| 22.537313 | 88 | 0.664901 |
3455dc2c4f2f22206c9297c495bb91b33ce2a62e | 7,735 | package edu.uwpr.protinfer.idpicker;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import edu.uwpr.protinfer.infer.InferredProtein;
import edu.uwpr.protinfer.infer.Peptide;
import edu.uwpr.protinfer.infer.PeptideHit;
import edu.uwpr.protinfer.infer.Protein;
import edu.uwpr.protinfer.infer.SearchSource;
import junit.framework.TestCase;
public class IDPickerExecutorTest3 extends TestCase {
protected void setUp() throws Exception {
super.setUp();
}
protected void tearDown() throws Exception {
super.tearDown();
}
public final void testInferProteins() {
IDPickerParams params = new IDPickerParams();
params.setMaxFdr(0.05f);
List<PeptideSpectrumMatchIDP> searchHits = makeSearchHits();
IDPickerExecutor executor = new IDPickerExecutor();
executor.doNotCalculateCoverage(); // don't calculate coverage; we don't want to
// to look in nrseq database
List<InferredProtein<SpectrumMatchIDP>> proteins = null;
try {
proteins = executor.inferProteins(searchHits, params);
}
catch (Exception e) {
e.printStackTrace();
fail("failed");
}
assertEquals(4, proteins.size());
int parsimonious = 0;
for(InferredProtein<SpectrumMatchIDP> prot: proteins) {
if(prot.getIsAccepted()) parsimonious++;
}
assertEquals(3, parsimonious);
Collections.sort(proteins, new Comparator<InferredProtein<SpectrumMatchIDP>>() {
public int compare(InferredProtein<SpectrumMatchIDP> o1,
InferredProtein<SpectrumMatchIDP> o2) {
return Integer.valueOf(o1.getProtein().getId()).compareTo(o2.getProtein().getId());
}});
int minCluster = Integer.MAX_VALUE;
int maxCluster = 0;
for (InferredProtein<SpectrumMatchIDP> prot: proteins) {
minCluster = Math.min(minCluster, prot.getProteinClusterLabel());
maxCluster = Math.max(maxCluster, prot.getProteinClusterLabel());
System.out.println(prot.getAccession()+"; cluster: "+prot.getProteinClusterLabel()+"; group: "+prot.getProteinGroupLabel());
}
// create a map for the proteins
Map<String, InferredProtein<SpectrumMatchIDP>> map = new HashMap<String, InferredProtein<SpectrumMatchIDP>>();
for (InferredProtein<SpectrumMatchIDP> prot: proteins) {
map.put(prot.getAccession(), prot);
}
// CHECK THE CLUSTERS
// proteins 1, 2, 3 and 4 should be in the same cluster
int clusterId1 = map.get("protein_1").getProteinClusterLabel();
assertTrue(clusterId1 > 0);
assertEquals(clusterId1, map.get("protein_2").getProteinClusterLabel());
assertEquals(clusterId1, map.get("protein_3").getProteinClusterLabel());
assertEquals(clusterId1, map.get("protein_4").getProteinClusterLabel());
// CHECK THE PROTEIN GROUPS
// protein_1
int groupId1 = map.get("protein_1").getProteinGroupLabel();
assertTrue(groupId1 > 0);
// protein_2
int groupId2 = map.get("protein_2").getProteinGroupLabel();
assertTrue(groupId2 > 0);
assertNotSame(groupId2, groupId1);
// protein_3
int groupId3 = map.get("protein_3").getProteinGroupLabel();
assertTrue(groupId3 > 0);
assertNotSame(groupId3, groupId1);
assertNotSame(groupId3, groupId2);
// protein_4
int groupId4 = map.get("protein_4").getProteinGroupLabel();
assertTrue(groupId4 > 0);
assertNotSame(groupId4, groupId1);
assertNotSame(groupId4, groupId2);
assertNotSame(groupId4, groupId3);
InferredProtein<SpectrumMatchIDP> prot = map.get("protein_1");
assertEquals(1, prot.getProtein().getId());
assertEquals("protein_1", prot.getAccession());
assertEquals(2, prot.getPeptides().size());
assertTrue(prot.getIsAccepted());
prot = map.get("protein_2");
assertEquals(2, prot.getProtein().getId());
assertEquals("protein_2", prot.getAccession());
assertEquals(2, prot.getPeptides().size());
assertTrue(prot.getIsAccepted());
prot = map.get("protein_3");
assertEquals(3, prot.getProtein().getId());
assertEquals("protein_3", prot.getAccession());
assertEquals(3, prot.getPeptides().size());
assertFalse(prot.getIsAccepted());
prot = map.get("protein_4");
assertEquals(4, prot.getProtein().getId());
assertEquals("protein_4", prot.getAccession());
assertEquals(2, prot.getPeptides().size());
assertTrue(prot.getIsAccepted());
assertEquals(1, minCluster);
assertEquals(1, maxCluster);
}
private List<PeptideSpectrumMatchIDP> makeSearchHits() {
List<PeptideSpectrumMatchIDP> hits = new ArrayList<PeptideSpectrumMatchIDP>();
SearchSource source = new SearchSource("test");
Protein[] proteins = new Protein[5]; // 4 proteins
for (int i = 1; i < proteins.length; i++) {
proteins[i] = new Protein("protein_"+i, i);
}
int proteinId = 1;
int scanId = 1;
// peptide_1: matches protein 1
addSearchHits(proteinId++, hits, source, scanId, new Protein[]{proteins[1]});
// peptide_2: matches protein 2
addSearchHits(proteinId++, hits, source, scanId+=2, new Protein[]{proteins[2]});
// peptide_3: matches protein 1, 3
addSearchHits(proteinId++, hits, source, scanId+=2, new Protein[]{proteins[1], proteins[3]});
// peptide_4: matches protein 2, 3
addSearchHits(proteinId++, hits, source, scanId+=2, new Protein[]{proteins[2], proteins[3]});
// peptide_5: matches protein 3, 4
addSearchHits(proteinId++, hits, source, scanId+=2, new Protein[]{proteins[3], proteins[4]});
// peptide_6: matches protein 4
addSearchHits(proteinId++, hits, source, scanId+=2, new Protein[]{proteins[4]});
return hits;
}
private void addSearchHits(int peptideId, List<PeptideSpectrumMatchIDP> hits, SearchSource source, int scanId, Protein[] proteins) {
Peptide p = new Peptide("peptide_"+peptideId, "peptide_"+peptideId, peptideId);
PeptideHit peptHit = new PeptideHit(p);
for(Protein prot: proteins) {
peptHit.addProtein(prot);
}
PeptideSpectrumMatchIDPImpl h1 = new PeptideSpectrumMatchIDPImpl(); //(source, scanId++, 2, peptHit);
SpectrumMatchIDPImpl sm = new SpectrumMatchIDPImpl();
sm.setScanId(scanId++);
sm.setCharge(2);
sm.setSourceId(source.getId());
h1.setPeptide(peptHit);
h1.setSpectrumMatch(sm);
hits.add(h1);
peptHit = new PeptideHit(p);
for(Protein prot: proteins) {
peptHit.addProtein(prot);
}
// SequestHit h2 = new SequestHit(source, scanId, 3, peptHit);
PeptideSpectrumMatchIDPImpl h2 = new PeptideSpectrumMatchIDPImpl(); //(source, scanId++, 2, peptHit);
sm = new SpectrumMatchIDPImpl();
sm.setScanId(scanId++);
sm.setCharge(2);
sm.setSourceId(source.getId());
h2.setPeptide(peptHit);
h2.setSpectrumMatch(sm);
hits.add(h2);
}
}
| 38.869347 | 136 | 0.61797 |
45fdd8b756b250df8e91434e4cb053c3ce400ccd | 122 | package epitech.epioid.API.Items;
/**
* Created by michelantoine on 16/01/15.
*/
public abstract class EpitechItem {
}
| 15.25 | 40 | 0.721311 |
31048d230fe927c09f4f3e55e9cb9305d6c53244 | 2,069 | package com.ty.product.api.domain.productPb.service.impl;
import com.ty.april.common.tool.page.PageParam;
import com.ty.april.core.mybatis.AbstractService;
import com.ty.product.api.domain.productPb.repository.dao.ProductMapper;
import com.ty.product.api.domain.productPb.repository.model.Product;
import com.ty.product.api.domain.productPb.service.IProductService;
import com.ty.product.feign.base.ProductVo;
import com.ty.product.feign.base.ProductDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;
/**
* @author: wenqing
* @date: 2020/04/09 16:57:50
* @description: Product服务实现
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class ProductServiceImpl extends AbstractService<Product> implements IProductService {
@Autowired
private ProductMapper tblProductMapper;
@Override
public ProductVo queryById(ProductDto productDto) {
Condition condition = new Condition(Product.class);
Example.Criteria criteria = condition.createCriteria();
// criteria.andEqualTo("id",productDto.getId());
Product products = tblProductMapper.selectByCondition(condition).get(0);
// MyPageInfo<Product> myPageInfo = pageList(condition, PageParam.buildWithDefaultSort(productDto.getCurrentPage(), productDto.getPageSize()));
Product product = new Product();
BeanUtils.copyProperties(productDto,product);
product.setGoodsNo(productDto.getGoodsNo());
if(!productDto.getGoodsName().equalsIgnoreCase("")){
product.setGoodsName(productDto.getGoodsName());
}
// Product products = tblProductMapper.select(product).get(0);
ProductVo productVo = ProductVo.builder().goodsName(products.getGoodsName()).goodsNo(products.getGoodsNo()).id(products.getId()).build();
return productVo;
}
}
| 40.568627 | 150 | 0.761237 |
1db7143c7a873bfa66c3be81723853f6e01f6ff9 | 706 | package com.xwx.myblog.utils;
import com.xwx.myblog.dao.CategoryDao;
import com.xwx.myblog.dao.UserDao;
import com.xwx.myblog.service.CategoryService;
import com.xwx.myblog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by 73667 on 2017/11/6.
*/
public class OtherUtils {
private static CategoryDao categoryDao = SpringContextHolder.getBean(CategoryDao.class);
private static UserDao userDao = SpringContextHolder.getBean(UserDao.class);
public static String getCategoryById(int cid) {
return categoryDao.getCategoryById(cid);
}
public static String getUserName(int uid) {
return userDao.getUserName(uid);
}
}
| 29.416667 | 91 | 0.760623 |
4cd8b5abf702a5e7583435d2b0d0ae9aed1b7bc8 | 1,252 | /*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.api;
/**
* Interface that defines several status handler callback functions. A status handler
* allows the application developer to use function showStatus in JavaScript, passing
* in a string argument. The actual implementation of the showStatus function is provided
* by the application developer.
* <p>
* If a status handler is defined, engine may use it to write status information.
*/
public interface IStatusHandler {
/**
* initialize the status handler.
*/
public void initialize();
/**
* showa the status string
*
* @param s the status string
*/
public void showStatus(String s);
/**
* does cleanup work
*/
public void finish();
}
| 30.536585 | 89 | 0.634984 |
4115a6f2cb8b0fcf31c708a4c91ca586bd7a7baa | 5,804 | package top.easyblog.util;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
/**
* AES加解密工具
* AES-128: key和iv都是16个字节,16*8=128bit,java似乎只支持AES-128
* @author HuangXin
* @since 2020/1/19 15:26
*/
public class AESCryptUtils {
/**
* AES CBC 加密
* @param message 需要加密的字符串
* @param key 密匙
* @param iv IV,需要和key长度相同
* @return 返回加密后密文,编码为base64
*/
public static String encryptCBC(String message, String key, String iv) {
final String cipherMode = "AES/CBC/PKCS5Padding";
final String charsetName = "UTF-8";
try {
byte[] content = new byte[0];
content = message.getBytes(charsetName);
//
byte[] keyByte = key.getBytes(charsetName);
SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
//
byte[] ivByte = iv.getBytes(charsetName);
IvParameterSpec ivSpec = new IvParameterSpec(ivByte);
Cipher cipher = Cipher.getInstance(cipherMode);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
byte[] data = cipher.doFinal(content);
final Base64.Encoder encoder = Base64.getEncoder();
return encoder.encodeToString(data);
} catch (UnsupportedEncodingException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* AES CBC 解密
* @param messageBase64 密文,base64编码
* @param key 密匙,和加密时相同
* @param iv IV,需要和key长度相同
* @return 解密后数据
*/
public static String decryptCBC(String messageBase64, String key, String iv) {
final String cipherMode = "AES/CBC/PKCS5Padding";
final String charsetName = "UTF-8";
try {
final Base64.Decoder decoder = Base64.getDecoder();
byte[] messageByte = decoder.decode(messageBase64);
//
byte[] keyByte = key.getBytes(charsetName);
SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
//
byte[] ivByte = iv.getBytes(charsetName);
IvParameterSpec ivSpec = new IvParameterSpec(ivByte);
Cipher cipher = Cipher.getInstance(cipherMode);
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
byte[] content = cipher.doFinal(messageByte);
String result = new String(content, charsetName);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* AES ECB 加密
* @param message 需要加密的字符串
* @param key 密匙
* @return 返回加密后密文,编码为base64
*/
public static String encryptECB(String message, String key) {
final String cipherMode = "AES/ECB/PKCS5Padding";
final String charsetName = "UTF-8";
try {
byte[] content = new byte[0];
content = message.getBytes(charsetName);
//
byte[] keyByte = key.getBytes(charsetName);
SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
Cipher cipher = Cipher.getInstance(cipherMode);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] data = cipher.doFinal(content);
final Base64.Encoder encoder = Base64.getEncoder();
final String result = encoder.encodeToString(data);
return result;
} catch (UnsupportedEncodingException | NoSuchPaddingException | InvalidKeyException | NoSuchAlgorithmException | IllegalBlockSizeException | BadPaddingException e) {
e.printStackTrace();
}
return null;
}
/**
* AES ECB 解密
* @param messageBase64 密文,base64编码
* @param key 密匙,和加密时相同
* @return 解密后数据
*/
public static String decryptECB(String messageBase64, String key) {
final String cipherMode = "AES/ECB/PKCS5Padding";
final String charsetName = "UTF-8";
try {
final Base64.Decoder decoder = Base64.getDecoder();
byte[] messageByte = decoder.decode(messageBase64);
//
byte[] keyByte = key.getBytes(charsetName);
SecretKeySpec keySpec = new SecretKeySpec(keyByte, "AES");
Cipher cipher = Cipher.getInstance(cipherMode);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] content = cipher.doFinal(messageByte);
String result = new String(content, charsetName);
return result;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 测试
*/
public static void Test()
{
String key = "1a2b3c4d5e6f7g8h";
String iv = "1234567890000000";
String msg = "Spring";
{
String encrypt = AESCryptUtils.encryptCBC(msg, key, iv);
System.out.println(encrypt);
String decryptStr = AESCryptUtils.decryptCBC(encrypt, key, iv);
System.out.println(decryptStr);
}
{
String encrypt = AESCryptUtils.encryptECB(msg, key);
System.out.println(encrypt);
String decryptStr = AESCryptUtils.decryptECB(encrypt, key);
System.out.println(decryptStr);
}
}
}
| 35.175758 | 211 | 0.615955 |
0f54c00fe665e26f3eacde3e99a88aa2f3d230a3 | 5,022 | package catrobat.calculator.uitest;
import android.widget.TextView;
import catrobat.calculator.R;
/**
* Created by chrl on 01/06/16.
* <p/>
* Basic Testcase
*/
public class CalculatorTest extends CalculatorUITestTemplate {
public void testButtons() throws Exception {
for (int i = 0; i < 10; i++) {
solo.clickOnText(Integer.toString(i));
}
solo.clickOnText("+");
solo.clickOnText("-");
solo.clickOnText("*");
solo.clickOnText("/");
solo.clickOnText("AC");
solo.clickOnText("DEL");
}
public void testWriteFormula() throws Exception {
for (int i = 0; i < 10; i++) {
solo.clickOnText(Integer.toString(i));
}
solo.clickOnText("+");
solo.clickOnText("0");
solo.clickOnText("0");
for (int i = 0; i < 10; i++) {
solo.clickOnText(Integer.toString(i));
}
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(300);
assertEquals("Formula not correctly represented", "123456789+123456789", textView.getText().toString());
}
public void testWriteFormula2() throws Exception {
for (int i = 0; i < 3; i++) {
solo.clickOnText(Integer.toString(i));
}
solo.clickOnText("+");
solo.clickOnText("*");
solo.clickOnText("+");
for (int i = 0; i < 3; i++) {
solo.clickOnText(Integer.toString(i));
}
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(300);
assertEquals("Formula not correctly represented", "12+12", textView.getText().toString());
}
public void testWriteFormula3() throws Exception {
typeNumbers();
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(500);
assertEquals("Formula not correctly represented", "12*-12", textView.getText().toString());
}
private void typeNumbers() {
for (int i = 0; i < 3; i++) {
solo.clickOnText(Integer.toString(i));
}
solo.clickOnText("+");
solo.clickOnText("*");
solo.clickOnText("-");
for (int i = 0; i < 3; i++) {
solo.clickOnText(Integer.toString(i));
}
}
public void testWriteFormula4() throws Exception {
solo.clickOnText("-");
typeNumbers();
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(500);
assertEquals("Formula not correctly represented", "-12*-12", textView.getText().toString());
}
public void testWriteFormula5() throws Exception {
solo.clickOnText("*");
typeNumbers();
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(500);
assertEquals("Formula not correctly represented", "12*-12", textView.getText().toString());
}
public void testWriteFormula6() throws Exception {
solo.clickOnText("+");
typeNumbers();
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(500);
assertEquals("Formula not correctly represented", "12*-12", textView.getText().toString());
}
public void testWriteFormula7() throws Exception {
solo.clickOnText("/");
typeNumbers();
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(500);
assertEquals("Formula not correctly represented", "12*-12", textView.getText().toString());
}
public void testWriteFormula8() throws Exception {
typeNumbers();
solo.clickOnText("*");
solo.clickOnText("-");
solo.clickOnText("/");
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.calculation);
solo.sleep(500);
assertEquals("Formula not correctly represented", "12*-12/", textView.getText().toString());
}
public void testCalculateAdd() throws Exception {
for (int i = 0; i < 3; i++) {
solo.clickOnText(Integer.toString(i));
}
solo.clickOnText("+");
for (int i = 0; i < 3; i++) {
solo.clickOnText(Integer.toString(i));
}
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.res);
solo.sleep(500);
assertEquals("Formula not correctly represented", "24", textView.getText().toString());
}
public void testDel() throws Exception {
typeNumbers();
solo.clickOnText("DEL");
solo.clickOnText("DEL");
solo.clickOnText("DEL");
TextView textView = (TextView) solo.getCurrentActivity().findViewById(R.id.res);
solo.sleep(500);
assertEquals("DEL does not work", "12", textView.getText().toString());
}
}
| 31 | 112 | 0.599761 |
d98d31698b5f014067e4495deb0f01a998b4f41c | 5,391 | /*******************************************************************************
* Copyright 2019 Mountain Fog, 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 ai.idylnlp.nlp.recognizer;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ai.idylnlp.model.entity.Entity;
import ai.idylnlp.model.exceptions.EntityFinderException;
import ai.idylnlp.model.nlp.ner.EntityExtractionRequest;
import ai.idylnlp.model.nlp.ner.EntityExtractionResponse;
import ai.idylnlp.model.nlp.ner.EntityRecognizer;
import com.neovisionaries.i18n.LanguageCode;
import opennlp.tools.namefind.RegexNameFinder;
import opennlp.tools.tokenize.Tokenizer;
import opennlp.tools.tokenize.WhitespaceTokenizer;
import opennlp.tools.util.Span;
/**
* An {@link EntityRecognizer} that identifies entities based
* on regular expressions.
*
* @author Mountain Fog, Inc.
*
*/
public class RegularExpressionEntityRecognizer implements EntityRecognizer {
private static final Logger LOGGER = LogManager.getLogger(RegularExpressionEntityRecognizer.class);
private Pattern pattern;
private String type;
/**
* Creates a regular expression entity recognizer.
* @param pattern The regular expression {@link Pattern pattern}.
* @param type The {@link String class} of the entities to identify.
*/
public RegularExpressionEntityRecognizer(Pattern pattern, String type) {
this.pattern = pattern;
this.type = type;
}
/**
* {@inheritDoc}
*/
@Override
public EntityExtractionResponse extractEntities(EntityExtractionRequest request) throws EntityFinderException {
long startTime = System.currentTimeMillis();
Set<Entity> entities = new LinkedHashSet<>();
try {
// TODO: Surround all patterns with spaces.
final String text = StringUtils.join(request.getText(), " ").replaceAll(pattern.pattern(), " $1 ");
Pattern[] patterns = {pattern};
// TODO: This recognizer must use the WhitespaceTokenizer.
Tokenizer tokenizer = WhitespaceTokenizer.INSTANCE;
// tokenize the text into the required OpenNLP format
String[] tokens = tokenizer.tokenize(text);
//the values used in these Spans are string character offsets of each token from the sentence beginning
Span[] tokenPositionsWithinSentence = tokenizer.tokenizePos(text);
// find the location names in the tokenized text
// the values used in these Spans are NOT string character offsets, they are indices into the 'tokens' array
RegexNameFinder regexNameFinder = new RegexNameFinder(patterns);
Span names[] = regexNameFinder.find(tokens);
//for each name that got found, create our corresponding occurrence
for (Span name : names) {
//find offsets relative to the start of the sentence
int beginningOfFirstWord = tokenPositionsWithinSentence[name.getStart()].getStart();
// -1 because the high end of a Span is noninclusive
int endOfLastWord = tokenPositionsWithinSentence[name.getEnd() - 1].getEnd();
//to get offsets relative to the document as a whole, just add the offset for the sentence itself
//int startOffsetInDoc = sentenceSpan.getStart() + beginningOfFirstWord;
//int endOffsetInDoc = sentenceSpan.getStart() + endOfLastWord;
//look back into the original input string to figure out what the text is that I got a hit on
String nameInDocument = text.substring(beginningOfFirstWord, endOfLastWord);
// Create a new entity object.
Entity entity = new Entity(nameInDocument, 100.0, type, LanguageCode.undefined.getAlpha3().toString(),
request.getContext(), request.getDocumentId());
entity.setSpan(new ai.idylnlp.model.entity.Span(name.getStart(), name.getEnd()));
entity.setContext(request.getContext());
entity.setExtractionDate(System.currentTimeMillis());
LOGGER.debug("Found entity with text: {}", nameInDocument);
// Add the entity to the list.
entities.add(entity);
LOGGER.trace("Found entity [{}] as a {} with span {}.", nameInDocument, type, name.toString());
}
long extractionTime = (System.currentTimeMillis() - startTime);
EntityExtractionResponse response = new EntityExtractionResponse(entities, extractionTime, true);
return response;
} catch (Exception ex) {
LOGGER.error("Unable to find entities with the RegularExpressionEntityRecognizer.", ex);
throw new EntityFinderException("Unable to find entities with the RegularExpressionEntityRecognizer.", ex);
}
}
}
| 36.924658 | 114 | 0.700983 |
4d41c0041c280a47e6ab2d273fb088dde624c11e | 8,324 | import java.io.*;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
public class ServerThread extends Thread {
protected Socket socket;
protected UserList UList;
protected PostList PList;
protected ArrayList<String> headers, values;
public ServerThread(Socket clientSocket,UserList UList,PostList PList) {
this.socket = clientSocket;
this.UList=UList;
this.PList=PList;
}
/*
ERROR
TITLE
END
TEXT
END
END
END
ERROR
TITLE
END
TEXT
END
QUIT
QUIT
*/
private String sanitize(String a){
return a.replaceAll("FOLLOWS","follows").replaceAll("END","END");
}
private synchronized UserList accessUserList(){
return this.UList;
}
private synchronized PostList accessPostList(){
return this.PList;
}
public String valueByHeader(String header) throws HeaderNotFoundException {
for(int i=0;i<headers.size();i++){
if(headers.get(i).equals(header)){
return values.get(i);
}
}
throw new HeaderNotFoundException();
}
public void run() {
InputStream inp = null;
BufferedReader in = null;
DataOutputStream out = null;
try {
inp = socket.getInputStream();
in = new BufferedReader(new InputStreamReader(inp));
out = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
return;
}
String line,action=null,name="USER";
headers= new ArrayList<String>();
values= new ArrayList<String>();
while (true) {
try {
line = in.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
socket.close();
return;
} else {
if(line.startsWith("ACTION")) {
headers.clear();
values.clear();
action=line.split(" ", 2)[1];
while(!line.equals("END")){
if(line.startsWith("FOLLOWS")){
headers.add(line.split(" ", 2)[1]);
}
else{
if(!line.startsWith("ACTION")) {
values.add(line);
}
}
line=in.readLine();
}
}
if(line.equals("END")){
if(action.equals("signIn")){
UserList u=accessUserList();
boolean access= u.signIn(new User(valueByHeader("username"),valueByHeader("password")));
out.writeBytes("OK\n");
out.writeBytes("FOLLOWS status\n");
if(access){
out.writeBytes("OK\n");
out.writeBytes("END\n");
name=valueByHeader("username");
}
else{
out.writeBytes("NO\n");
out.writeBytes("END\n");
}
}
else if(action.equals("signUp")){
UserList u=accessUserList();
boolean access= u.signUp(new User(valueByHeader("username"),valueByHeader("password")));
out.writeBytes("OK\n");
out.writeBytes("FOLLOWS status\n");
if(access){
out.writeBytes("OK\n");
out.writeBytes("END\n");
name=valueByHeader("username");
}
else{
out.writeBytes("NO\n");
out.writeBytes("END\n");
}
}
else if(name.equals("DEFAULT")){
out.writeBytes("ERROR\n" +
"Authentication Error\n" +
"END\n" +
"You must log in" +
"END\n" +
"QUIT\n" +
"QUIT\n");
}
else if(action.equals("listPosts")){
PostList p= accessPostList();
out.writeBytes("OK\n");
for(int i=0;i<p.size();i++){
//Post c= p.get(i);
out.writeBytes("FOLLOWS POST-Id-"+String.valueOf(i) +"\n"+
sanitize(String.valueOf(p.get(i).getId()))+"\n" +
"FOLLOWS POST-Title-"+String.valueOf(i) +"\n"+
sanitize(p.get(i).getTitle())+"\n" +
"FOLLOWS POST-Author-"+String.valueOf(i) +"\n"+
sanitize(p.get(i).getAuthor())+"\n" +
"FOLLOWS POST-Date-"+String.valueOf(i) +"\n"+
sanitize(p.get(i).getDate())+"\n");
}
out.writeBytes("END\n");
}
else if(action.equals("getPostBody")){
PostList p= accessPostList();
Post a= new Post("Error","Post not found","Server","01/01/1970",-1);
for(int i=0;i<p.size();i++){
if(p.get(i).getId()==Integer.parseInt(this.valueByHeader("POST-Id"))){
a=p.get(i);
out.writeBytes("OK\n");
out.writeBytes("FOLLOWS body\n");
out.writeBytes(a.getBody()+"\n");
out.writeBytes("END\n");
break;
}
}
}
else if(action.equals("sendPost")){
int ID=this.accessPostList().getNewId();
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date date = new Date();
Post p= new Post(this.valueByHeader("POST-Title"),this.valueByHeader("POST-Body"),name,dateFormat.format(date),ID);
PostList pl= accessPostList();
pl.add(p);
out.writeBytes("OK\n");
out.writeBytes("FOLLOWS status\n");
out.writeBytes("OK\n");
out.writeBytes("END\n");
}
}
//out.writeBytes(line + "\n\r");
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
} catch (HeaderNotFoundException e) {
e.printStackTrace();
try {
out.writeBytes("ERROR\n" +
"Request Error\n" +
"END\n" +
"The server received a malformed request\n" +
"END\n" +
"END\n" +
"END\n");
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
} | 41.412935 | 143 | 0.373378 |
65dc400de152fc506a025b603e514b1abb510bfd | 13,917 | /*
* Copyright (C) 2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.syndesis.server.api.generator.openapi.v3;
import java.net.URI;
import java.util.ArrayList;
import java.util.Optional;
import io.apicurio.datamodels.core.models.Extension;
import io.apicurio.datamodels.core.models.common.Server;
import io.apicurio.datamodels.core.models.common.ServerVariable;
import io.apicurio.datamodels.openapi.v3.models.Oas30Document;
import io.apicurio.datamodels.openapi.v3.models.Oas30SecurityScheme;
import io.syndesis.common.model.connection.ConfigurationProperty;
import io.syndesis.common.model.connection.ConfigurationProperty.PropertyValue;
import io.syndesis.common.model.connection.ConnectorSettings;
import io.syndesis.server.api.generator.openapi.OpenApiModelInfo;
import io.syndesis.server.api.generator.openapi.OpenApiSecurityScheme;
import io.syndesis.server.api.generator.openapi.util.OasModelHelper;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class Oas30PropertyGeneratorsTest {
private static final Oas30PropertyGenerators GENERATOR = new Oas30PropertyGenerators();
@Test
public void shouldConsiderOnlyAuthorizationCodeOAuthFlows() {
final Oas30Document openApiDoc = new Oas30Document();
openApiDoc.components = openApiDoc.createComponents();
openApiDoc.components.addSecurityScheme("oauth-username-password", oauth2SecurityScheme("oauth-username-password", "password", "https://api.example.com/token", null));
openApiDoc.components.addSecurityScheme("oauth-implicit", oauth2SecurityScheme("oauth-implicit", "implicit", null, "https://api.example.com/authz"));
openApiDoc.components.addSecurityScheme("oauth-authorization-code", oauth2SecurityScheme("oauth-authorization-code", "authorizationCode","https://api.example.com/token", "https://api.example.com/authz"));
openApiDoc.components.addSecurityScheme("basic-auth", basicAuthSecurityScheme("basic-auth"));
openApiDoc.components.addSecurityScheme("api-key", apiKeySecurityScheme("api-key"));
final ConfigurationProperty template = new ConfigurationProperty.Builder().build();
final ConnectorSettings settings = new ConnectorSettings.Builder().build();
final Optional<ConfigurationProperty> authenticationTypes = GENERATOR.forProperty("authenticationType")
.generate(new OpenApiModelInfo.Builder().model(openApiDoc).build(), template, settings);
assertThat(authenticationTypes)
.contains(new ConfigurationProperty.Builder()
.addEnum(PropertyValue.Builder.of("oauth2:oauth-authorization-code", "OAuth 2.0 - oauth-authorization-code"))
.addEnum(PropertyValue.Builder.of("basic:basic-auth", "HTTP Basic Authentication - basic-auth"))
.addEnum(PropertyValue.Builder.of("apiKey:api-key", "API Key - api-key"))
.build());
}
@Test
public void shouldDefaultToNoSecurityIfNoSupportedSecurityDefinitionsFound() {
final Oas30Document openApiDoc = new Oas30Document();
openApiDoc.components = openApiDoc.createComponents();
openApiDoc.components.addSecurityScheme("oauth-username-password", oauth2SecurityScheme("oauth-username-password", "password", "https://api.example.com/token", null));
openApiDoc.components.addSecurityScheme("oauth-implicit", oauth2SecurityScheme("oauth-implicit", "implicit", null, "https://api.example.com/authz"));
final ConfigurationProperty template = new ConfigurationProperty.Builder().build();
final ConnectorSettings settings = new ConnectorSettings.Builder().build();
final Optional<ConfigurationProperty> authenticationTypes = GENERATOR.forProperty("authenticationType")
.generate(new OpenApiModelInfo.Builder().model(openApiDoc).build(), template, settings);
assertThat(authenticationTypes)
.contains(new ConfigurationProperty.Builder()
.defaultValue("none")
.addEnum(PropertyValue.Builder.of("none", "No Security"))
.build());
}
@Test
public void shouldDetermineFromHostsContainingPorts() {
Oas30Document openApiDoc = new Oas30Document();
openApiDoc.addServer("https://54.152.43.92:8080", "TestServer");
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("https://54.152.43.92");
}
@Test
public void shouldDetermineHostFromSpecification() {
Oas30Document openApiDoc = new Oas30Document();
Server server = openApiDoc.addServer("{scheme}://api.example.com", "TestServer");
ServerVariable schemes = server.createServerVariable("scheme");
schemes.default_ = "https";
schemes.enum_ = new ArrayList<>();
schemes.enum_.add("https");
server.addServerVariable("scheme", schemes);
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("https://api.example.com");
schemes.enum_.add("http");
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("https://api.example.com");
schemes.default_ = "http";
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("http://api.example.com");
}
@Test
public void shouldDetermineHostFromSpecificationUrl() {
final URI specificationUrl = URI.create("https://api.example.com/swagger.json");
Oas30Document openApiDoc = new Oas30Document();
Extension extension = new Extension();
extension.name = OasModelHelper.URL_EXTENSION;
extension.value = specificationUrl;
openApiDoc.addExtension(OasModelHelper.URL_EXTENSION, extension);
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("https://api.example.com");
Server server = openApiDoc.addServer("{scheme}://api.example.com", "TestServer");
ServerVariable schemes = server.createServerVariable("scheme");
schemes.default_ = "http";
schemes.enum_ = new ArrayList<>();
schemes.enum_.add("http");
server.addServerVariable("scheme", schemes);
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("http://api.example.com");
server.url = "{scheme}://api2.example.com";
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isEqualTo("http://api2.example.com");
}
@Test
public void shouldDetermineSecurityDefinitionToUseFromTheConfiguredAuthenticationType() {
final Oas30SecurityScheme securityScheme = basicAuthSecurityScheme("username-password");
final Oas30Document openApiDoc = new Oas30Document();
openApiDoc.components = openApiDoc.createComponents();
openApiDoc.components.addSecurityScheme("username-password", securityScheme);
final ConnectorSettings settings = new ConnectorSettings.Builder()
.putConfiguredProperty("authenticationType", "basic:username-password")
.build();
final Optional<Oas30SecurityScheme> got = GENERATOR.securityDefinition(
new OpenApiModelInfo.Builder().model(openApiDoc).build(), settings, OpenApiSecurityScheme.BASIC);
assertThat(got).containsSame(securityScheme);
}
@Test
public void shouldDetermineSecurityDefinitionToUseFromTheConfiguredAuthenticationTypeWithName() {
final Oas30SecurityScheme securityScheme = basicAuthSecurityScheme("username-password");
final Oas30Document openApiDoc = new Oas30Document();
openApiDoc.components = openApiDoc.createComponents();
openApiDoc.components.addSecurityScheme("username-password", securityScheme);
final ConnectorSettings settings = new ConnectorSettings.Builder()
.putConfiguredProperty("authenticationType", "basic:username-password")
.build();
final Optional<Oas30SecurityScheme> got = GENERATOR.securityDefinition(
new OpenApiModelInfo.Builder().model(openApiDoc).build(), settings, OpenApiSecurityScheme.BASIC);
assertThat(got).containsSame(securityScheme);
}
@Test
public void shouldReturnNullIfNoHostGivenAnywhere() {
Oas30Document openApiDoc = new Oas30Document();
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isNull();
openApiDoc.addServer("/v1", "TestServer");
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isNull();
}
@Test
public void shouldReturnNullIfNoHttpSchemesFound() {
Oas30Document openApiDoc = new Oas30Document();
Server server = openApiDoc.addServer("{scheme}://api.example.com", "TestServer");
ServerVariable schemes = server.createServerVariable("scheme");
schemes.default_ = "ws";
schemes.enum_ = new ArrayList<>();
schemes.enum_.add("ws");
schemes.enum_.add("wss");
server.addServerVariable("scheme", schemes);
assertThat(GENERATOR.determineHost(new OpenApiModelInfo.Builder().model(openApiDoc).build())).isNull();
}
@Test
public void shouldTakeOnlyAuthorizationCodeOAuthFlowUrls() {
final Oas30Document openApiDoc = new Oas30Document();
openApiDoc.components = openApiDoc.createComponents();
openApiDoc.components.addSecurityScheme("oauth-username-password",
oauth2SecurityScheme("oauth-username-password", "password", "https://wrong.example.com/token", null));
openApiDoc.components.addSecurityScheme("oauth-implicit",
oauth2SecurityScheme("oauth-implicit", "implicit", null, "https://wrong.example.com/authz"));
openApiDoc.components.addSecurityScheme("oauth-authorization-code",
oauth2SecurityScheme("oauth-authorization-code", "authorizationCode","https://api.example.com/token", "https://api.example.com/authz"));
final ConfigurationProperty template = new ConfigurationProperty.Builder().build();
final ConnectorSettings settings = new ConnectorSettings.Builder()
.putConfiguredProperty("authenticationType", "oauth2:oauth-authorization-code")
.build();
final Optional<ConfigurationProperty> authorizationEndpoint = GENERATOR.forProperty("authorizationEndpoint")
.generate(new OpenApiModelInfo.Builder().model(openApiDoc).build(), template, settings);
assertThat(authorizationEndpoint)
.contains(new ConfigurationProperty.Builder()
.defaultValue("https://api.example.com/authz")
.build());
final Optional<ConfigurationProperty> tokenEndpoint = GENERATOR.forProperty("tokenEndpoint")
.generate(new OpenApiModelInfo.Builder().model(openApiDoc).build(), template, settings);
assertThat(tokenEndpoint)
.contains(new ConfigurationProperty.Builder()
.defaultValue("https://api.example.com/token")
.build());
}
private static Oas30SecurityScheme oauth2SecurityScheme(String name, String flow, String tokenUrl, String authorizationUrl) {
Oas30SecurityScheme securityScheme = new Oas30SecurityScheme(name);
securityScheme.type = OpenApiSecurityScheme.OAUTH2.getName();
securityScheme.flows = securityScheme.createOAuthFlows();
if ("authorizationCode".equals(flow)) {
securityScheme.flows.authorizationCode = securityScheme.flows.createAuthorizationCodeOAuthFlow();
securityScheme.flows.authorizationCode.tokenUrl = tokenUrl;
securityScheme.flows.authorizationCode.authorizationUrl = authorizationUrl;
}
if ("clientCredentials".equals(flow)) {
securityScheme.flows.clientCredentials = securityScheme.flows.createClientCredentialsOAuthFlow();
securityScheme.flows.clientCredentials.tokenUrl = tokenUrl;
securityScheme.flows.clientCredentials.authorizationUrl = authorizationUrl;
}
if ("password".equals(flow)) {
securityScheme.flows.password = securityScheme.flows.createPasswordOAuthFlow();
securityScheme.flows.password.tokenUrl = tokenUrl;
securityScheme.flows.password.authorizationUrl = authorizationUrl;
}
if ("implicit".equals(flow)) {
securityScheme.flows.implicit = securityScheme.flows.createImplicitOAuthFlow();
securityScheme.flows.implicit.tokenUrl = tokenUrl;
securityScheme.flows.implicit.authorizationUrl = authorizationUrl;
}
return securityScheme;
}
private static Oas30SecurityScheme basicAuthSecurityScheme(String name) {
Oas30SecurityScheme securityScheme = new Oas30SecurityScheme(name);
securityScheme.type = OpenApiSecurityScheme.BASIC.getName();
return securityScheme;
}
private static Oas30SecurityScheme apiKeySecurityScheme(String name) {
Oas30SecurityScheme securityScheme = new Oas30SecurityScheme(name);
securityScheme.type = OpenApiSecurityScheme.API_KEY.getName();
return securityScheme;
}
}
| 52.91635 | 212 | 0.720198 |
c770d2d72a25423656884a1e8bf491045e119eb7 | 1,596 | package cn.aethli.lock.aspect;
import cn.aethli.lock.annotation.DistributedLock;
import cn.aethli.lock.common.emnus.ResponseStatus;
import cn.aethli.lock.model.ResponseModel;
import cn.aethli.lock.utils.LockUtil;
import java.lang.reflect.Method;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Aspect
@Component
@Slf4j
public class LockMethodAspect {
private final LockUtil lockUtil;
@Autowired
public LockMethodAspect(LockUtil lockUtil) {
this.lockUtil = lockUtil;
}
@Around("@annotation(cn.aethli.lock.annotation.DistributedLock)")
public Object aroundDistributedLock(ProceedingJoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
DistributedLock lock = method.getAnnotation(DistributedLock.class);
String key = lock.key();
int expire = lock.expire();
int waitTime = lock.waitTime();
int polling = lock.polling();
String value = UUID.randomUUID().toString();
if (!lockUtil.lock(key, expire, waitTime, polling, value)) {
return new ResponseModel(ResponseStatus.ERROR, "业务超时");
}
Object proceed = joinPoint.proceed();
if (!lockUtil.unlock(key, value)) {
log.info("业务:{},解锁错误", key);
}
return proceed;
}
}
| 32.571429 | 87 | 0.753759 |
76ab793024a98de59cd2c15a437fafbff56293b9 | 2,645 | package com.bitdubai.reference_wallet.crypto_broker_wallet.preference_settings;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.PreferenceWalletSettings;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantGetDefaultLanguageException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantGetDefaultSkinException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantLoadWalletSettings;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantSaveWalletSettings;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantSetDefaultLanguageException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.exceptions.CantSetDefaultSkinException;
import com.bitdubai.fermat_wpd_api.layer.wpd_middleware.wallet_settings.interfaces.WalletSettings;
import java.util.UUID;
/**
* Created by mati on 2015.08.24..
*/
public class CryptoBrokerWalletPreferenceSettings implements WalletSettings {
/**
* This method let us know the default language of a wallet
*
* @return the identifier of the default language of the wallet
* @throws CantGetDefaultLanguageException
*/
@Override
public UUID getDefaultLanguage() throws CantGetDefaultLanguageException {
return null;
}
/**
* This method let us know the default skin of a wallet
*
* @return the identifier of the default skin of the wallet
* @throws CantGetDefaultSkinException
*/
@Override
public UUID getDefaultSkin() throws CantGetDefaultSkinException {
return null;
}
/**
* This method let us set the default language for a wallet
*
* @param languageId the identifier of the language to set as default
* @throws CantSetDefaultLanguageException
*/
@Override
public void setDefaultLanguage(UUID languageId) throws CantSetDefaultLanguageException {
}
/**
* This method let us set the default skin for a wallet
*
* @param skinId the identifier of the skin to set as default
* @throws CantSetDefaultSkinException
*/
@Override
public void setDefaultSkin(UUID skinId) throws CantSetDefaultSkinException {
}
@Override
public void setPreferenceSettings(PreferenceWalletSettings preferenceWalletSettings) throws CantSaveWalletSettings {
}
@Override
public String getPreferenceSettings(PreferenceWalletSettings preferenceWalletSettings) throws CantLoadWalletSettings {
return null;
}
}
| 36.736111 | 122 | 0.774669 |
4a8182f55179a3f34e3a2fe035556c46ae848e86 | 45 | test warning keyword param bar foo invoke foo | 45 | 45 | 0.844444 |
72cadcfcd12fbb20bc3d62945c600234aa9f1cbc | 432 | package hotciv.framework.Strategies;
import hotciv.framework.Position;
import hotciv.framework.Unit;
import hotciv.framework.World;
public interface BattleStrategy {
/** returns the victor of a battle
*
* @param attacker the unit that attacks
* @param defender the unit that defends
* @return the unit that succeeds in battle
*/
Unit getVictor(Position attacker, Position defender, World world);
}
| 28.8 | 70 | 0.731481 |
4ea7d2aef3a0274047f6efa09257f3e01404e6db | 5,687 | /*
* Copyright 2017 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.stunner.core.graph.command.impl;
import java.util.Optional;
import java.util.function.Consumer;
import org.jboss.errai.common.client.api.annotations.MapsTo;
import org.jboss.errai.common.client.api.annotations.Portable;
import org.kie.soup.commons.validation.PortablePreconditions;
import org.kie.workbench.common.stunner.core.command.CommandResult;
import org.kie.workbench.common.stunner.core.command.util.CommandUtils;
import org.kie.workbench.common.stunner.core.definition.clone.ClonePolicy;
import org.kie.workbench.common.stunner.core.graph.Edge;
import org.kie.workbench.common.stunner.core.graph.Node;
import org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext;
import org.kie.workbench.common.stunner.core.graph.content.view.Connection;
import org.kie.workbench.common.stunner.core.graph.content.view.View;
import org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector;
import org.kie.workbench.common.stunner.core.rule.RuleViolation;
import org.kie.workbench.common.stunner.core.util.UUID;
/**
* A Command which adds an candidate into a graph and sets its target sourceNode.
*/
@Portable
public final class CloneConnectorCommand extends AbstractGraphCompositeCommand {
private final Edge candidate;
private transient Edge clone;
private transient Connection sourceConnection;
private transient Connection targetConnection;
private transient Node<? extends View<?>, Edge> sourceNode;
private transient Node<? extends View<?>, Edge> targetNode;
private final String sourceNodeUUID;
private final String targetNodeUUID;
private final Optional<Consumer<Edge>> callback;
public CloneConnectorCommand() {
this(null, null, null);
}
public CloneConnectorCommand(final @MapsTo("candidate") Edge candidate, final @MapsTo("sourceNodeUUID") String sourceNodeUUID, final @MapsTo("targetNodeUUID") String targetNodeUUID) {
this(candidate, sourceNodeUUID, targetNodeUUID, null);
}
public CloneConnectorCommand(Edge candidate, String sourceNodeUUID, String targetNodeUUID, Consumer<Edge> callback) {
this.candidate = PortablePreconditions.checkNotNull("candidate",
candidate);
this.sourceNodeUUID = PortablePreconditions.checkNotNull("sourceNodeUUID", sourceNodeUUID);
this.targetNodeUUID = PortablePreconditions.checkNotNull("targetNodeUUID", targetNodeUUID);
this.callback = Optional.ofNullable(callback);
}
@Override
@SuppressWarnings("unchecked")
protected CloneConnectorCommand initialize(final GraphCommandExecutionContext context) {
super.initialize(context);
this.sourceNode = (Node<? extends View<?>, Edge>) getNode(context, sourceNodeUUID);
this.targetNode = (Node<? extends View<?>, Edge>) getNode(context, targetNodeUUID);
if (!(candidate.getContent() instanceof ViewConnector)) {
throw new IllegalArgumentException("Candidate: " + candidate.getTargetNode() + " content should be a ViewConnector");
}
//clone candidate
ViewConnector edgeContent = (ViewConnector) candidate.getContent();
final Object bean = edgeContent.getDefinition();
clone = context.getFactoryManager().newElement(UUID.uuid(), bean.getClass()).asEdge();
//Cloning the candidate content with properties
Object clonedDefinition = context.getDefinitionManager().cloneManager().clone(edgeContent.getDefinition(), ClonePolicy.ALL);
ViewConnector clonedContent = (ViewConnector) clone.getContent();
clonedContent.setDefinition(clonedDefinition);
// Magnet being moved on node
ViewConnector connectionContent = (ViewConnector) candidate.getContent();
this.sourceConnection = (Connection) connectionContent.getSourceConnection().orElse(null);
this.targetConnection = (Connection) connectionContent.getTargetConnection().orElse(null);
commands.add(new AddConnectorCommand(sourceNode, clone, sourceConnection));
commands.add(new SetConnectionTargetNodeCommand(targetNode, clone, targetConnection));
// Add the candidate into index, so child commands can find it.
getMutableIndex(context).addEdge(clone);
return this;
}
@Override
public CommandResult<RuleViolation> execute(GraphCommandExecutionContext context) {
CommandResult<RuleViolation> commandResult = super.execute(context);
if (!CommandUtils.isError(commandResult)) {
callback.ifPresent(c -> c.accept(clone));
}
return commandResult;
}
@Override
@SuppressWarnings("unchecked")
public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context) {
return new DeleteConnectorCommand(clone).execute(context);
}
@Override
protected boolean delegateRulesContextToChildren() {
return true;
}
protected Edge getCandidate() {
return candidate;
}
} | 45.134921 | 187 | 0.737999 |
311fa0be31cfc90b71f77dff0b571176dd95971e | 426 | package ai.eve;
import java.util.Properties;
public abstract class AbstractTrackerClient {
private Properties properties;
public AbstractTrackerClient(Properties props) {
this.properties = props;
}
public Properties getProperties() {
return this.properties;
}
abstract public void trackEvent(UserSession session, AbstractTrackerEvent event);
abstract public void trackEvent(AbstractTrackerEvent event);
}
| 21.3 | 82 | 0.79108 |
71b22f498532f1ba710e3fc3c96644fa3b747fed | 1,462 | package com.jstechnologies.usermanagement;
import android.os.Bundle;
import android.widget.Toast;
import androidx.annotation.IdRes;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
/*Base fragment for authentication and auth protection. Implements some basic Viewmodel creation*/
abstract public class BaseAuthFragment<VM extends ViewModel> extends Fragment {
protected VM viewmodel;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewmodel=createViewModel();
observe();
}
abstract protected VM createViewModel();
abstract protected void observe();
protected void showToast(String message){
Toast.makeText(this.getContext(),message,Toast.LENGTH_SHORT).show();
}
protected void navigateTo(@IdRes int fragmaentContainerID, Fragment fragment){
this.getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(fragmaentContainerID,fragment)
.commit();
}
protected void navigateToWithBackStack(@IdRes int fragmaentContainerID, Fragment fragment){
this.getActivity().getSupportFragmentManager()
.beginTransaction()
.addToBackStack(fragment.getClass().getName())
.replace(fragmaentContainerID,fragment)
.commit();
}
}
| 32.488889 | 98 | 0.70383 |
c434913376750aad058bac5b675454c45a736366 | 674 | package ai.residences;
import l2f.gameserver.model.instances.NpcInstance;
public class SiegeGuardRanger extends SiegeGuard
{
public SiegeGuardRanger(NpcInstance actor)
{
super(actor);
}
@Override
protected boolean createNewTask()
{
return defaultFightTask();
}
@Override
public int getRatePHYS()
{
return 25;
}
@Override
public int getRateDOT()
{
return 50;
}
@Override
public int getRateDEBUFF()
{
return 25;
}
@Override
public int getRateDAM()
{
return 75;
}
@Override
public int getRateSTUN()
{
return 75;
}
@Override
public int getRateBUFF()
{
return 5;
}
@Override
public int getRateHEAL()
{
return 50;
}
} | 11.423729 | 50 | 0.689911 |
54797416bb2732b05fe78c2309ec4712dfc2ffec | 36 | ./dependencies/D/src/android/D.java
| 18 | 35 | 0.777778 |
cb3c4ada38a36f1be4fbd7735c59b840bf7ef372 | 260 | package ayp2.clase15.patrones;
public class File implements AbstractFile{
private String m_name;
public File(String name){
m_name = name;
}
public void ls(){
System.out.println(AbstractFile.g_indent + m_name);
}
}
| 14.444444 | 60 | 0.638462 |
4b087ef40d366b2be5b40a21ee2535c87a3fbd75 | 4,560 | /*
* Copyright 2017 Lime - HighTech Solutions s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.getlime.security.powerauth.lib.nextstep.model.response;
import io.getlime.security.powerauth.lib.nextstep.model.entity.AuthStep;
import io.getlime.security.powerauth.lib.nextstep.model.enumeration.AuthResult;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Response object used for updating an operation.
*
* @author Petr Dvorak, [email protected]
*/
public class UpdateOperationResponse {
private String operationId;
private String operationName;
private String userId;
private AuthResult result;
private String resultDescription;
private Date timestampCreated;
private Date timestampExpires;
private List<AuthStep> steps;
/**
* Default constructor.
*/
public UpdateOperationResponse() {
steps = new ArrayList<>();
}
/**
* Get operation ID.
* @return Operation ID.
*/
public String getOperationId() {
return operationId;
}
/**
* Set operation ID.
* @param operationId Operation ID.
*/
public void setOperationId(String operationId) {
this.operationId = operationId;
}
/**
* Get operation name.
* @return Operation name.
*/
public String getOperationName() {
return operationName;
}
/**
* Set operation name.
* @param operationName Operation name.
*/
public void setOperationName(String operationName) {
this.operationName = operationName;
}
/**
* Get user ID of the user who is associated with the operation.
* @return User ID.
*/
public String getUserId() {
return userId;
}
/**
* Set user ID of the user who is associated with the operation.
* @param userId User ID.
*/
public void setUserId(String userId) {
this.userId = userId;
}
/**
* Get the authentication step result.
* @return Authentication step result.
*/
public AuthResult getResult() {
return result;
}
/**
* Set the authentication step result.
* @param result Authentication step result.
*/
public void setResult(AuthResult result) {
this.result = result;
}
/**
* Get the authentication result description.
*
* @return Result description.
*/
public String getResultDescription() {
return resultDescription;
}
/**
* Set the authentication result description.
*
* @param resultDescription Result description.
*/
public void setResultDescription(String resultDescription) {
this.resultDescription = resultDescription;
}
/**
* Get the timestamp of when the operation was created.
* @return Timestamp when operation was created.
*/
public Date getTimestampCreated() {
return timestampCreated;
}
/**
* Set the timestamp of when the operation was created.
* @param timestampCreated Timestamp when operation was created.
*/
public void setTimestampCreated(Date timestampCreated) {
this.timestampCreated = timestampCreated;
}
/**
* Get the timestamp of when the operation expires.
* @return Timestamp when operation expires.
*/
public Date getTimestampExpires() {
return timestampExpires;
}
/**
* Set the timestamp of when the operation expires.
* @param timestampExpires Timestamp when operation expires.
*/
public void setTimestampExpires(Date timestampExpires) {
this.timestampExpires = timestampExpires;
}
/**
* Is the operation expired?
*
* @return true if expired
*/
public boolean isExpired() {
return new Date().after(timestampExpires);
}
/**
* Get the list with optional extra parameters.
* @return Extra parameters.
*/
public List<AuthStep> getSteps() {
return steps;
}
}
| 25.333333 | 79 | 0.65 |
661827afcf4037be07df778438e243faf3841d9d | 218 | package com.jun.jpa.domain;
import com.jun.jpa.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 数据持久层操作接口
*
*/
public interface RoleRepository extends JpaRepository<Role, Long> {
}
| 16.769231 | 67 | 0.761468 |
5e6951b7dead032c25c00cc607c9d572c82628f1 | 90 | /**
* Classes for storing constant values.
*/
package com.epam.brest.courses.constants;
| 18 | 41 | 0.733333 |
8dbf7ddb6e6928bff423ce6daf5dcfd6644c1c33 | 5,564 | package com.sung.hee.shcrowd.model;
/**
* Created by SungHere on 2017-05-24.
*/
public class SHCrowd {
private String rnn="";
private int seq;
private int pnum;
private String title = "";
public String getTitleTemp() {
titleTemp = title;
titleTemp = titleTemp.replace("&", "&");
titleTemp = titleTemp.replace("<", "<");
titleTemp = titleTemp.replace(">", ">");
return titleTemp;
}
public void setTitleTemp(String titleTemp) {
this.titleTemp = titleTemp;
}
private String titleTemp = "";
private String titleSub = "";
private String content;
private String id;
private int goalMoney;
private int likenum;
private int curMoney;
private String tag;
private String sdate;
private String edate;
private String category;
private String address;
public String getTitleSub() {
titleSub = title;
if (titleSub.length() > 15) {
titleSub = titleSub.substring(0, 15) + "..";
}
titleSub = titleSub.replace("&", "&");
titleSub = titleSub.replace("<", "<");
titleSub = titleSub.replace(">", ">");
return titleSub;
}
public void setTitleSub(String titleSub) {
this.titleSub = title;
}
private int type = 2;/*기본형 = 2,보상형=3 등등..*/
private int req = 0;
private int del = 0;
private String wdate;
private String search_type = "search";
private String search = "";
private int cnt;
public int getCnt() {
return cnt;
}
public void setCnt(int cnt) {
this.cnt = cnt;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
private String endflag = "0";
private String reward = "0";
private String latlng = "";
@Override
public String toString() {
return "SHCrowd [rnn=" + rnn + ", seq=" + seq + ", pnum=" + pnum + ", title=" + title + ", titleTemp="
+ titleTemp + ", titleSub=" + titleSub + ", content=" + content + ", id=" + id + ", goalmoney="
+ goalMoney + ", likenum=" + likenum + ", curmoney=" + curMoney + ", tag=" + tag + ", sdate=" + sdate
+ ", edate=" + edate + ", category=" + category + ", address=" + address + ", type=" + type + ", req="
+ req + ", del=" + del + ", wdate=" + wdate + ", search_type=" + search_type + ", search=" + search
+ ", cnt=" + cnt + ", endflag=" + endflag + ", reward=" + reward + ", latlng=" + latlng + "]";
}
public int getPnum() {
return pnum;
}
public void setPnum(int pnum) {
this.pnum = pnum;
}
public String getLatlng() {
return latlng;
}
public void setLatlng(String latlng) {
this.latlng = latlng;
}
public String getRnn() {
return rnn;
}
public void setRnn(String rnn) {
this.rnn = rnn;
}
public int getSeq() {
return seq;
}
public void setSeq(int seq) {
this.seq = seq;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getGoalMoney() {
return goalMoney;
}
public void setGoalMoney(int goalMoney) {
this.goalMoney = goalMoney;
}
public int getLikenum() {
return likenum;
}
public void setLikenum(int likenum) {
this.likenum = likenum;
}
public int getCurMoney() {
return curMoney;
}
public void setCurMoney(int curMoney) {
this.curMoney = curMoney;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
public String getSdate() {
return sdate;
}
public void setSdate(String sdate) {
this.sdate = sdate;
}
public String getEdate() {
return edate;
}
public void setEdate(String edate) {
this.edate = edate;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getReq() {
return req;
}
public void setReq(int req) {
this.req = req;
}
public int getDel() {
return del;
}
public void setDel(int del) {
this.del = del;
}
public String getWdate() {
return wdate;
}
public void setWdate(String wdate) {
this.wdate = wdate;
}
public String getSearch_type() {
return search_type;
}
public void setSearch_type(String search_type) {
this.search_type = search_type;
}
public String getEndflag() {
return endflag;
}
public void setEndflag(String endflag) {
this.endflag = endflag;
}
public String getReward() {
return reward;
}
public void setReward(String reward) {
this.reward = reward;
}
}
| 20.014388 | 106 | 0.554996 |
e8ef8545b41cd7037da3f6e5c900c94bc2c832a6 | 3,297 | package org.bzewdu.graph;
import org.bzewdu.stats.DataSet;
import org.bzewdu.util.Subresults;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class GraphRW {
private static void usage() {
System.out.println("Usage: java GraphRW [JDK identifier string] [subresults directory] ...");
System.out.println("Graphs multiple benchmarks' subresults from multiple JDKs.");
System.out.println("JDKs are displayed in graphs in the order they are specified");
System.out.println("on the command line.");
System.out.println("Example invocation: ");
System.out.println("java GraphRW \"JDK 1.4.2\" .../results-142/results \\");
System.out.println(" \"JDK 5\" .../results-15/results \\");
System.out.println(" \"JDK 6\" .../results-16/results \\");
System.out.println("Once window is visible, left-click on a particular benchmark");
System.out.println("to zoom in, and right-click to zoom back out.");
System.exit(1);
}
private static List<GraphDataModel> buildDataModel(final String[] experimentNames,
final Subresults[] subresults) {
List<GraphDataModel> data = new ArrayList<GraphDataModel>();
Subresults base = subresults[0];
for (final String benchmarkName : base.benchmarkNames()) {
// Find benchmark in all JDKs
data.add(new GraphDataModel() {
public String getTitle() {
return benchmarkName;
}
public int getNumDataPoints() {
return experimentNames.length;
}
public double getDataPoint(int i) {
DataSet datum = subresults[i].get(benchmarkName);
if (datum == null) return 0;
return datum.mean();
}
public String getDataPointTitle(int i) {
return experimentNames[i];
}
});
}
return data;
}
public static void main(String[] args) throws IOException {
if ((args.length == 0) || ((args.length % 2) != 0))
usage();
String[] experimentNames = new String[args.length / 2];
Subresults[] subresults = new Subresults[args.length / 2];
int i = 0;
int j = 0;
while (i < args.length) {
experimentNames[j] = args[i++];
subresults[j] = new Subresults(new File(args[i++]));
j++;
}
Toolkit.getDefaultToolkit().setDynamicLayout(true);
final JFrame frame = new JFrame("Benchmark results");
frame.getContentPane().setBackground(Color.BLACK);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphMulti multi = new GraphMulti(frame.getContentPane(), buildDataModel(experimentNames, subresults));
frame.setSize(640, 480);
frame.setVisible(true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frame.invalidate();
frame.validate();
}
});
}
}
| 38.337209 | 111 | 0.569912 |
8b2591693c5ab342b09995f36d9d71a2794a5d3f | 2,811 | /*********************************************************************************
* TotalCross Software Development Kit *
* Copyright (C) 1998, 1999 Wabasoft <www.wabasoft.com> *
* Copyright (C) 2000-2012 SuperWaba Ltda. *
* All Rights Reserved *
* *
* This library and virtual machine 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. *
* *
* This file is covered by the GNU LESSER GENERAL PUBLIC LICENSE VERSION 3.0 *
* A copy of this license is located in file license.txt at the root of this *
* SDK or can be downloaded here: *
* http://www.gnu.org/licenses/lgpl-3.0.txt *
* *
*********************************************************************************/
package totalcross.ui.event;
import totalcross.ui.Control;
/**
* MultiTouchEvent works on devices that support more than one finger at a time.
*
* It can be emulated in JavaSE by using the right mouse button:
* <ol>
* <li> Right-click and go up: the scale is increased. release the button.
* <li> Right-click and go down: the scale is decreased. release the button.
* </ol>
*/
public class MultiTouchEvent extends Event<MultiTouchListener> {
/** The event type for a pen or mouse down. */
public static final int SCALE = 250;
protected static final String[] EVENT_NAME = { "SCALE" };
/** The current scale value. */
public double scale;
/** Updates this event setting also the timestamp, consumed and target.
* @since TotalCross 1.0
*/
public MultiTouchEvent update(Control c, double scale) {
this.type = SCALE;
timeStamp = totalcross.sys.Vm.getTimeStamp(); // guich@200b4: removed this from the other subclasses and putted here.
consumed = false;
target = c;
this.scale = scale;
return this;
}
/** Returns the event name. Used to debugging. */
public static String getEventName(int type) {
return SCALE <= type && type <= SCALE ? EVENT_NAME[type - 250] : "Not a MultiTouchEvent";
}
@Override
public String toString() {
return EVENT_NAME[type - 250] + " scale: " + scale + " " + super.toString();
}
@Override
public void dispatch(MultiTouchListener listener) {
listener.scale(this);
}
}
| 41.338235 | 121 | 0.521878 |
d47ecc656606853ff8adb5b2fde7fa03967274bf | 3,260 | package activity;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.database.core.view.View;
import helper.ConfiguracaoFirebase;
import helper.UsuarioFirebase;
import isuper.com.br.R;
import model.Empresa;
import model.Usuario;
public class ConfiguracoesUsuarioActivity extends AppCompatActivity {
private EditText editUsuarioNome;
private EditText editUsuarioEndereco;
private String idUsuario;
private DatabaseReference firebaseRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuracoes_usuario);
inicializarComponentes();
idUsuario = UsuarioFirebase.getIdUsuario();
firebaseRef = ConfiguracaoFirebase.getFirebase();
//Configurações Toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Configurações usuário");
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recuperarDadosUsuario();
}
private void recuperarDadosUsuario(){
DatabaseReference usuarioRef = firebaseRef
.child("usuarios")
.child(idUsuario);
usuarioRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
Usuario usuario = dataSnapshot.getValue(Usuario.class);
editUsuarioNome.setText(usuario.getNome());
editUsuarioEndereco.setText(usuario.getEndereco());
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public void validarDadosUsuario(View view) {
String nome = editUsuarioNome.getText().toString();
String endereco = editUsuarioEndereco.getText().toString();
if( !nome.isEmpty()){
if( !endereco.isEmpty()){
Usuario usuario = new Usuario();
usuario.setIdUsuario(idUsuario);
usuario.setNome(nome);
usuario.setEndereco(endereco);
usuario.salvar();
exibirMensagem("Dados Atualizados com sucesso");
finish();
}else{
exibirMensagem("Digite seu endereço");
}
}else{
exibirMensagem("Digite seu nome");
}
}
private void inicializarComponentes(){
editUsuarioNome = findViewById(R.id.editUsuarioNome);
editUsuarioEndereco = findViewById(R.id.editUsuarioEndereco);
}
private void exibirMensagem(String texto){
Toast.makeText(this, texto, Toast.LENGTH_SHORT)
.show();
}
}
| 33.265306 | 76 | 0.662883 |
04817e26424f0bbb39712f0abbc5318c19216b51 | 836 | package br.com.fjsistemas.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import br.com.fjsistemas.backend.Almoxarifado;
import br.com.fjsistemas.repository.AlmoxarifadoRepository;
@Service
public class AlmoxarifadoService {
// CRUD
@Autowired
private AlmoxarifadoRepository almoxarifadoRepository;
public void create(Almoxarifado almoxarifado) {
almoxarifadoRepository.save(almoxarifado);
}
public List<Almoxarifado> read() {
List<Almoxarifado> almoxarifados = almoxarifadoRepository.findAll();
return almoxarifados;
}
public void update(Almoxarifado almoxarifado) {
almoxarifadoRepository.save(almoxarifado);
}
public void delete(Almoxarifado almoxarifado) {
almoxarifadoRepository.delete(almoxarifado);
}
} | 22.594595 | 70 | 0.808612 |
dbd77665e11aa06fc9894672491514e2fd8f5b59 | 1,862 | package com.couchbase.perftest;
import android.content.Context;
import android.util.Log;
import com.couchbase.lite.CouchbaseLiteException;
import com.couchbase.lite.DatabaseConfiguration;
import com.couchbase.lite.MutableDocument;
public class DocPerfTest extends PerfTest {
public DocPerfTest(Context context, DatabaseConfiguration dbConfig) {
super(context, dbConfig);
}
@Override
protected void test() {
final int revs = 10000;
Log.i(TAG, String.format("--- Creating %d revisions ---", revs));
measure(revs, "revision", new Runnable() {
@Override
public void run() {
addRevisions(revs);
}
});
}
void addRevisions(final int revisions) {
try {
db.inBatch(new Runnable() {
@Override
public void run() {
try {
MutableDocument mDoc = new MutableDocument("doc");
updateDoc(mDoc, revisions);
//updateDocWithGetDocument(mDoc, revisions);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
});
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
}
void updateDoc(MutableDocument doc, final int revisions) throws CouchbaseLiteException {
for (int i = 0; i < revisions; i++) {
doc.setValue("count", i);
db.save(doc);
}
}
void updateDocWithGetDocument(MutableDocument doc, final int revisions) throws CouchbaseLiteException {
for (int i = 0; i < revisions; i++) {
doc.setValue("count", i);
db.save(doc);
doc = db.getDocument("doc").toMutable();
}
}
}
| 29.555556 | 107 | 0.546187 |
90e0834d05c5111187e75e60843e0ea0cb4ed099 | 1,659 | package com.goodjob.crm.security;
import java.util.Collection;
import java.util.stream.Collectors;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import com.auth0.jwt.interfaces.DecodedJWT;
/**
*
* @author ahmedeid
*
*/
public class JWTAuthenticationToken implements Authentication{
/**
*
*/
private static final long serialVersionUID = 7988744725111588175L;
private String jwt;
private DecodedJWT decodedJWT;
private Boolean isAuthenticated;
public JWTAuthenticationToken(String rawJWT) {
this.jwt = rawJWT;
this.isAuthenticated = false;
}
public void setDecodedJWT(DecodedJWT decJWT) {
this.decodedJWT = decJWT;
}
public String getJWT() {
return this.jwt;
}
@Override
public String getName() {
return decodedJWT.getSubject();
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return decodedJWT.getClaim("roles").asList(String.class)
.stream().map(r -> new SimpleGrantedAuthority(r))
.collect(Collectors.toList());
}
@Override
public Object getCredentials() {
return decodedJWT;
}
@Override
public Object getDetails() {
return decodedJWT;
}
@Override
public Object getPrincipal() {
return decodedJWT.getSubject();
}
@Override
public boolean isAuthenticated() {
return this.isAuthenticated;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
this.isAuthenticated = isAuthenticated;
}
}
| 20.7375 | 88 | 0.729355 |
b7cd2c52488fa7afecd974442ef515e639882d37 | 596 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.muzza.ws;
import java.util.Date;
import javax.jws.WebService;
/**
*
* @author M Mozammil
*/
@WebService(endpointInterface = "org.muzza.ws.TimeServer")
public class TimeServerImpl implements TimeServer{
@Override
public String getServerTime() {
return new Date().toString();
}
@Override
public long getElapsedTime() {
return new Date().getTime();
}
}
| 19.866667 | 79 | 0.686242 |
42c520438fe9a4e80587f5809dcb571a32ff674f | 4,783 | package io.vertx.ext.web.openapi;
import io.vertx.codegen.annotations.VertxGen;
import io.vertx.core.json.JsonObject;
import io.vertx.core.json.pointer.JsonPointer;
/**
* Main class for router factory exceptions
*
* @author Francesco Guardiani @slinkydeveloper
*/
public class RouterFactoryException extends RuntimeException {
@VertxGen
public enum ErrorType {
/**
* You are trying to mount an operation with operation_id not defined in specification
*/
OPERATION_ID_NOT_FOUND,
/**
* Error while loading contract. The path is wrong or the spec is an invalid json/yaml file
*/
INVALID_FILE,
/**
* Provided file is not a valid OpenAPI contract
*/
INVALID_SPEC,
/**
* Missing security handler during construction of router
*/
MISSING_SECURITY_HANDLER,
/**
* You are trying to use a spec feature not supported by this package.
* Most likely you you have defined in you contract
* two or more path parameters with a combination of parameters/name/styles/explode not supported
*/
UNSUPPORTED_SPEC,
/**
* You specified an interface not annotated with {@link io.vertx.ext.web.api.service.WebApiServiceGen} while calling {@link RouterFactory#mountServiceInterface(Class, String)}
*/
WRONG_INTERFACE,
/**
* You specified a wrong service extension
*/
WRONG_SERVICE_EXTENSION,
/**
* Error while generating the {@link io.vertx.ext.web.validation.ValidationHandler}
*/
CANNOT_GENERATE_VALIDATION_HANDLER
}
private ErrorType type;
public RouterFactoryException(String message, ErrorType type, Throwable cause) {
super(message, cause);
this.type = type;
}
public ErrorType type() {
return type;
}
// public static RouterFactoryException createPathNotFoundException(String pathName) {
// return new RouterFactoryException(pathName + " not found inside specification", ErrorType.PATH_NOT_FOUND);
// }
//
// public static RouterFactoryException createOperationIdNotFoundException(String operationId) {
// return new RouterFactoryException(operationId + " not found inside specification", ErrorType
// .OPERATION_ID_NOT_FOUND);
// }
public static RouterFactoryException cannotFindParameterProcessorGenerator(JsonPointer pointer, JsonObject parameter) {
return new RouterFactoryException(
String.format("Cannot find a ParameterProcessorGenerator for %s: %s", pointer.toString(), parameter.encode()),
ErrorType.UNSUPPORTED_SPEC,
null
);
}
public static RouterFactoryException createBodyNotSupported(JsonPointer pointer) {
return new RouterFactoryException(
String.format("Cannot find a BodyProcessorGenerator for %s", pointer.toString()),
ErrorType.UNSUPPORTED_SPEC,
null
);
}
public static RouterFactoryException createInvalidSpecException(Throwable cause) {
return new RouterFactoryException("Spec is invalid", ErrorType.INVALID_SPEC, cause);
}
public static RouterFactoryException createInvalidFileSpec(String path, Throwable cause) {
return new RouterFactoryException("Cannot load the spec in path " + path, ErrorType.INVALID_FILE, cause);
}
public static RouterFactoryException createMissingSecurityHandler(String securitySchema) {
return new RouterFactoryException("Missing handler for security requirement: " + securitySchema, ErrorType
.MISSING_SECURITY_HANDLER, null);
}
public static RouterFactoryException createMissingSecurityHandler(String securitySchema, String securityScope) {
return new RouterFactoryException("Missing handler for security requirement: " + securitySchema + ":" +
securityScope, ErrorType.MISSING_SECURITY_HANDLER, null);
}
// public static RouterFactoryException createWrongInterface(Class i) {
// return new RouterFactoryException("Interface " + i.getName() + " is not annotated with @WebApiServiceProxy", ErrorType.WRONG_INTERFACE);
// }
public static RouterFactoryException createUnsupportedSpecFeature(String message) {
return new RouterFactoryException(message, ErrorType.UNSUPPORTED_SPEC, null);
}
public static RouterFactoryException createWrongExtension(String message) {
return new RouterFactoryException(message, ErrorType.WRONG_SERVICE_EXTENSION, null);
}
public static RouterFactoryException createRouterFactoryInstantiationError(Throwable e, String url) {
return new RouterFactoryException("Cannot instantiate Router Factory for openapi " + url, ErrorType.UNSUPPORTED_SPEC, e);
}
public static RouterFactoryException createErrorWhileGeneratingValidationHandler(String message, Throwable cause) {
return new RouterFactoryException(message, ErrorType.CANNOT_GENERATE_VALIDATION_HANDLER, cause);
}
}
| 37.661417 | 179 | 0.755384 |
1a3f516fb2698dd4c2f11d0729e89563b609f4fd | 1,443 | package mkTails.invariants;
import java.util.List;
import mkTails.model.event.EventType;
import mkTails.model.interfaces.INode;
/**
* An implicit invariant for totally ordered Synoptic models that encodes the
* constraint that (1) every trace must start with an Initial event, (2) end
* with a Terminal event, and (3) have no intermediate Terminal events.
*/
public class TOInitialTerminalInvariant extends BinaryInvariant {
public TOInitialTerminalInvariant(EventType typeFirst,
EventType typeSecond, String relation) {
super(typeFirst, typeSecond, relation);
}
/**
* This invariant is not used during refinement or coarsening, so LTL has
* been left undefined
*/
@Override
public String getLTLString() {
throw new UnsupportedOperationException();
}
@Override
public <T extends INode<T>> List<T> shorten(List<T> path) {
return path;
}
@Override
public String toString() {
return "Initial event: " + first.toString() + ", Terminal event: "
+ second.toString();
}
@Override
public String getShortName() {
return "^Initial[^(Initial|Terminal)]*Terminal$";
}
@Override
public String getLongName() {
return getShortName();
}
@Override
public String getRegex(char firstC, char secondC) {
return firstC + "[^" + firstC + secondC + "]*" + secondC;
}
}
| 25.767857 | 77 | 0.652807 |
05418cf1009424a26be698ad1f6c14f24e2a217c | 1,375 | /**
* AET
*
* Copyright (C) 2013 Cognifide Limited
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.cognifide.aet.communication.api.wrappers;
import com.cognifide.aet.communication.api.metadata.RunType;
import com.cognifide.aet.communication.api.metadata.Suite;
import java.io.Serializable;
public interface Run<T> extends Serializable {
RunType getType();
T getObjectToRun();
void setObjectToRun(T object);
default void setRealSuite(Suite suite) {}
default Suite getRealSuite() {
return null;
}
default String getCorrelationId() {
return null;
}
default String getProject() {
return null;
}
default String getCompany() {
return null;
}
default String getName() {
return null;
}
default String getSuiteIdentifier() {
return null;
}
default String getTestName() {
return null;
}
}
| 22.916667 | 100 | 0.72 |
b46cf89ac3d790584eba0a38031b0ab875f193f7 | 3,158 | package polsl.tab.skiresort.api.employee;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import polsl.tab.skiresort.api.employee.request.AgeDiscountsRequest;
import polsl.tab.skiresort.api.employee.request.PriceListRequest;
import polsl.tab.skiresort.api.employee.request.QuantityPassRequest;
import polsl.tab.skiresort.api.employee.request.TimePassRequest;
import polsl.tab.skiresort.api.employee.response.PriceListResponse;
import polsl.tab.skiresort.api.employee.service.PriceListService;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("/api/priceList")
public class PriceListApi {
private final PriceListService priceListService;
public PriceListApi(PriceListService priceListService) {
this.priceListService = priceListService;
}
@GetMapping("/current")
public ResponseEntity<PriceListResponse> getActivePriceList() {
return ResponseEntity.ok(priceListService.getActivePriceList());
}
@GetMapping("/edit/all")
public ResponseEntity<List<PriceListResponse>> getAllPriceLists() {
return ResponseEntity.ok(priceListService.getAll());
}
@PutMapping("/edit/current")
public ResponseEntity<PriceListResponse> editStartDateAndEndDateOfActivePriceList(
@RequestParam("startDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
@RequestParam("endDate") @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate
) {
return ResponseEntity.ok(priceListService.modifyActivePriceListStartDateEndDate(
new java.sql.Date(startDate.getTime()),
new java.sql.Date(endDate.getTime())
));
}
@PostMapping("/edit/new")
public ResponseEntity<PriceListResponse> addNewPriceList(@RequestBody PriceListRequest priceListRequest) {
return ResponseEntity.ok(priceListService.addNewCurrentPriceList(priceListRequest));
}
@PutMapping("/edit/ageDiscounts")
public ResponseEntity<PriceListResponse> modifyActivePriceListAgeDiscounts(
@RequestBody AgeDiscountsRequest request
) {
return ResponseEntity.ok(priceListService.modifyAgeDiscountsForActivePriceList(request));
}
@PutMapping("/edit/quantityPasses")
public ResponseEntity<PriceListResponse> modifyActivePriceListQuantityPasses(
@RequestBody QuantityPassRequest request
) {
return ResponseEntity.ok(priceListService.modifyQuantityPassForActivePriceList(request));
}
@PutMapping("/edit/timePasses")
public ResponseEntity<PriceListResponse> modifyActivePriceListTimePasses(
@RequestBody TimePassRequest request
) {
return ResponseEntity.ok(priceListService.modifyTimePassForActivePriceList(request));
}
@PostMapping("/edit/priceList")
public ResponseEntity<PriceListResponse> modifyCurrentPriceListAndDeactivateOldOne(
@RequestBody PriceListRequest request
) {
return ResponseEntity.ok(priceListService.modifyCurrentPriceListAndDeactivateOldOne(request));
}
}
| 38.987654 | 110 | 0.758075 |
cefc9decac89693b79a134e3ae81214dff29abde | 436 | package com.github.mirs.banxiaoxiao.framework.core.log;
public interface BizLogger {
void debug(String bizType, Object... propertys);
void info(String bizType, Object... propertys);
void warn(String bizType, Object... propertys);
void warn(String bizType, Throwable e, Object... propertys);
void error(String bizType, Throwable e, Object... propertys);
void error(String bizType, Object... propertys);
}
| 24.222222 | 65 | 0.711009 |
657ea396399eacdf80c5d1a29590780547929498 | 407 | package com.thenetwork.app.android.thenetwork.HelperClasses;
import android.support.annotation.NonNull;
import com.google.firebase.firestore.Exclude;
/**
* Created by Kashish on 14-03-2018.
*/
public class BlogPostId {
@Exclude
public String BlogPostId;
public <T extends BlogPostId> T withId(@NonNull final String id){
this.BlogPostId = id;
return (T) this;
}
}
| 17.695652 | 71 | 0.695332 |
f8660d7925368a03349f7b32aeeb212762a8a537 | 2,740 | package com.lightbend.futures;
import java.io.*;
import java.nio.file.Path;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
interface ObjectStore {
Optional<Object> read(UUID id);
boolean write(UUID id, Object obj);
}
/**
* The ObjectStore is a file based storage mechanism for Objects. It is
* intended to provide blocking operations that simulate operations that would
* traditionally use a database, an external HTTP endpoint, etc.
*/
class FileBasedObjectStore implements ObjectStore {
private File storeFolder;
// This would be more efficient if written with a lock per file.
// However for simplicity we are going with a single lock instead.
private ReadWriteLock lock = new ReentrantReadWriteLock();
/**
* Construct an ObjectStore Store
* @param storeFolder This folder will be used to store the object data.
*/
FileBasedObjectStore(Path storeFolder) {
this.storeFolder = storeFolder.toFile();
assert(this.storeFolder.exists());
assert(this.storeFolder.isDirectory());
}
/**
* Reads an object from the file store.
* @param id - The ID of the object
* @return The object if it exists or empty if it does not.
*/
@Override
public Optional<Object> read(UUID id) {
lock.readLock().lock();
File file = new File(storeFolder, id.toString());
Optional<Object> result;
try (
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn)
) {
result = Optional.ofNullable(in.readObject());
} catch ( IOException | ClassNotFoundException ex) {
result = Optional.empty();
} finally {
lock.readLock().unlock();
}
return result;
}
/**
* Writes an object to a file in the file store.
* @param id - The id of the object being written.
* @param obj - The object to be written.
* @return true if the write was successful, false if it failed.
*/
@Override
public boolean write(UUID id, Object obj) {
lock.writeLock().lock();
File file = new File(storeFolder, id.toString());
boolean result;
try (
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut)
) {
out.writeObject(obj);
result = true;
} catch (IOException ex) {
result = false;
} finally {
lock.writeLock().unlock();
}
return result;
}
}
| 29.148936 | 78 | 0.633212 |
884d73ebd6f85b44594780c14f62665fd8d6d263 | 4,988 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.util.bloom;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.BitSet;
import org.roaringbitmap.RoaringBitmap;
/**
* It is the extendable class to hadoop bloomfilter, it is extendable to implement compressed bloom
* and fast serialize and deserialize of bloom.
*/
public class CarbonBloomFilter extends BloomFilter {
private RoaringBitmap bitmap;
private boolean compress;
private int blockletNo;
// used for building blocklet when query
private String shardName;
public CarbonBloomFilter() {
}
public CarbonBloomFilter(int vectorSize, int nbHash, int hashType, boolean compress) {
super(vectorSize, nbHash, hashType);
this.compress = compress;
}
@Override
public boolean membershipTest(Key key) {
if (compress) {
// If it is compressed check in roaring bitmap
if (key == null) {
throw new NullPointerException("key cannot be null");
}
int[] h = hash.hash(key);
hash.clear();
for (int i = 0; i < nbHash; i++) {
if (!bitmap.contains(h[i])) {
return false;
}
}
return true;
} else {
// call super method to avoid IllegalAccessError for `bits` field
return super.membershipTest(key);
}
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(blockletNo);
out.writeInt(this.nbHash);
out.writeByte(this.hashType);
out.writeInt(this.vectorSize);
out.writeBoolean(compress);
BitSet bits = getBitSet();
if (!compress) {
byte[] bytes = bits.toByteArray();
out.writeInt(bytes.length);
out.write(bytes);
} else {
RoaringBitmap bitmap = new RoaringBitmap();
int length = bits.cardinality();
int nextSetBit = bits.nextSetBit(0);
for (int i = 0; i < length; ++i) {
bitmap.add(nextSetBit);
nextSetBit = bits.nextSetBit(nextSetBit + 1);
}
bitmap.serialize(out);
}
}
@Override
public void readFields(DataInput in) throws IOException {
this.blockletNo = in.readInt();
this.nbHash = in.readInt();
this.hashType = in.readByte();
this.vectorSize = in.readInt();
this.compress = in.readBoolean();
if (!compress) {
int len = in.readInt();
byte[] bytes = new byte[len];
in.readFully(bytes);
setBitSet(BitSet.valueOf(bytes));
} else {
this.bitmap = new RoaringBitmap();
bitmap.deserialize(in);
}
this.hash = new HashFunction(this.vectorSize, this.nbHash, this.hashType);
}
public int getSize() {
int size = 14; // size of nbHash,hashType, vectorSize, compress
if (compress) {
size += bitmap.getSizeInBytes();
} else {
try {
size += getBitSet().toLongArray().length * 8;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return size;
}
/**
* Get bitset from super class using reflection, in some cases java cannot access the fields if
* jars are loaded in separte class loaders.
*
* @return
* @throws IOException
*/
private BitSet getBitSet() throws IOException {
try {
Field field = BloomFilter.class.getDeclaredField("bits");
field.setAccessible(true);
return (BitSet)field.get(this);
} catch (Exception e) {
throw new IOException(e);
}
}
/**
* Set bitset from super class using reflection, in some cases java cannot access the fields if
* jars are loaded in separte class loaders.
* @param bitSet
* @throws IOException
*/
private void setBitSet(BitSet bitSet) throws IOException {
try {
Field field = BloomFilter.class.getDeclaredField("bits");
field.setAccessible(true);
field.set(this, bitSet);
} catch (Exception e) {
throw new IOException(e);
}
}
public void setBlockletNo(int blockletNo) {
this.blockletNo = blockletNo;
}
public int getBlockletNo() {
return blockletNo;
}
public String getShardName() {
return shardName;
}
public void setShardName(String shardName) {
this.shardName = shardName;
}
}
| 27.865922 | 99 | 0.663392 |
2e85d36fb4fe8e40d3f85c1ecab429d1bb503aea | 1,683 | package mkl.testarea.pdfbox2.content;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* @author mkl
*/
public class ShowSpecialGlyph {
final static File RESULT_FOLDER = new File("target/test-outputs", "content");
@BeforeClass
public static void setUpBeforeClass() throws Exception {
RESULT_FOLDER.mkdirs();
}
/**
* <a href="https://stackoverflow.com/questions/49426018/%e2%82%b9-indian-rupee-symbol-symbol-is-printing-as-question-mark-in-pdf-using-apa">
* ₹ (Indian Rupee Symbol) symbol is printing as ? (question mark) in pdf using Apache PDFBOX
* </a>
* <p>
* This test shows how to successfully show the Indian Rupee symbol
* based on the OP's source frame and Tilman's proposed font.
* </p>
*/
@Test
public void testIndianRupeeForVandanaSharma() throws IOException {
PDDocument doc = new PDDocument();
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream cos= new PDPageContentStream(doc, page);
cos.beginText();
String text = "Deposited Cash of ₹10,00,000/- or more in a Saving Bank Account";
cos.newLineAtOffset(25, 700);
cos.setFont(PDType0Font.load(doc, new File("c:/windows/fonts/arial.ttf")), 12);
cos.showText(text);
cos.endText();
cos.close();
doc.save(new File(RESULT_FOLDER, "IndianRupee.pdf"));
doc.close();
}
}
| 33 | 145 | 0.673797 |
34ef390de5c68ced3eed9fc03506fa8f428522b6 | 4,531 | /*
* AT&T - PROPRIETARY
* THIS FILE CONTAINS PROPRIETARY INFORMATION OF
* AT&T AND IS NOT TO BE DISCLOSED OR USED EXCEPT IN
* ACCORDANCE WITH APPLICABLE AGREEMENTS.
*
* Copyright (c) 2013 AT&T Knowledge Ventures
* Unpublished and Not for Publication
* All Rights Reserved
*/
package com.att.research.xacml.std;
import com.att.research.xacml.api.Identifier;
import com.att.research.xacml.api.StatusCode;
import com.att.research.xacml.api.XACML1;
/**
* Immutable implementation of the {@link com.att.research.xacml.api.StatusCode} interface to store the major
* and minor {@link com.att.research.xacml.common.StatusCodeValues} objects associated with a XACML StatusCode element.
*
* @author car
* @version $Revision: 1.1 $
*/
public class StdStatusCode implements StatusCode {
private Identifier statusCodeValue;
private StatusCode child;
public static final StatusCode STATUS_CODE_OK = new StdStatusCode(XACML1.ID_STATUS_OK);
public static final StatusCode STATUS_CODE_MISSING_ATTRIBUTE = new StdStatusCode(XACML1.ID_STATUS_MISSING_ATTRIBUTE);
public static final StatusCode STATUS_CODE_SYNTAX_ERROR = new StdStatusCode(XACML1.ID_STATUS_SYNTAX_ERROR);
public static final StatusCode STATUS_CODE_PROCESSING_ERROR = new StdStatusCode(XACML1.ID_STATUS_PROCESSING_ERROR);
/**
* Creates a new <code>StdStatusCode</code> with the given {@link com.att.research.xacml.api.Identifier} representing the XACML StatusCode value,
* and the given {@link com.att.research.xacml.api.StatusCode} representing the sub-StatusCode.
*
* @param statusCodeValueIn the <code>Identifier</code> representing the XACML StatusCode value
* @param childIn the <code>StatusCode</code> representing the XACML sub-StatusCode value
*/
public StdStatusCode(Identifier statusCodeValueIn, StatusCode childIn) {
this.statusCodeValue = statusCodeValueIn;
this.child = childIn;
}
/**
* Creates a new <code>StdStatusCode</code> with the given {@link com.att.research.xacml.api.Identifier} representing the XACML StatusCode value
*
* @param statusCodeValueIn the <code>Identifier</code> representing the XACML StatusCode value
*/
public StdStatusCode(Identifier majorStatusCodeValueIn) {
this(majorStatusCodeValueIn, null);
}
/**
* Creates a new <code>StdStatusCode</code> that is a copy of the given {@link com.att.research.xacml.api.StatusCode}.
*
* @param statusCode the <code>StatusCode</code> to copy
* @return a new <code>StdStatusCode</code> that is a copy of the given <code>StatusCode</code>.
*/
public static StdStatusCode copy(StatusCode statusCode) {
return new StdStatusCode(statusCode.getStatusCodeValue(), statusCode.getChild());
}
@Override
public Identifier getStatusCodeValue() {
return this.statusCodeValue;
}
@Override
public StatusCode getChild() {
return this.child;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder("{");
boolean needsComma = false;
Object objectToDump;
if ((objectToDump = this.getStatusCodeValue()) != null) {
stringBuilder.append("statusCodeValue=");
stringBuilder.append(objectToDump.toString());
needsComma = true;
}
if ((objectToDump = this.getChild()) != null) {
if (needsComma) {
stringBuilder.append(',');
}
stringBuilder.append("child=");
stringBuilder.append(objectToDump.toString());
needsComma = true;
}
stringBuilder.append('}');
return stringBuilder.toString();
}
@Override
public int hashCode() {
Identifier identifierStatusCodeValue = this.getStatusCodeValue();
StatusCode statusCodeChild = this.getChild();
int hc = (identifierStatusCodeValue == null ? 0 : identifierStatusCodeValue.hashCode());
if (statusCodeChild != null) {
hc += statusCodeChild.hashCode();
}
return hc;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
} else if (obj == this) {
return true;
} else if (!(obj instanceof StatusCode)) {
return false;
}
StatusCode statusCodeObj = (StatusCode)obj;
if (!(statusCodeObj.getStatusCodeValue().equals(this.getStatusCodeValue()))) {
return false;
}
StatusCode statusCodeChildThis = this.getChild();
StatusCode statusCodeChildObj = statusCodeObj.getChild();
if (statusCodeChildThis == null) {
return (statusCodeChildObj == null);
} else {
return (statusCodeChildThis.equals(statusCodeChildObj));
}
}
}
| 34.325758 | 146 | 0.723681 |
f8bef78c913659a3a16c8a053bd83e6d763bb51a | 1,246 | package org.bougainvillea.java.basejava.codequality.chapter09;
/**
* 119.启动线程前stop方法是不可靠的
*/
public class Eo {
/**
* 此段代码中,设置了一个极端条件:
* 所有的线程在启动前都执行stop方法,虽然它是一个已过时(Deprecated)的方法,但它的运行逻辑还是正常的,
* 况且stop方法在此处的目的并不是停止一个线程,而是设置线程为不可启用状态。
* 想来这应该是没有问题的,但是运行结果却出现了奇怪的现象:
* 部分线程还是启动了,也就是在某些线程(没有规律)中的start方法正常执行了。
* 在不符合判断规则的情况下,不可启用状态的线程还是启用了
* 为什么?
* 这是线程启动(start方法)的一个缺陷。
* Thread类的stop方法会根据线程状态来判断是终结线程还是设置线程为不可运行状态,
* 对于未启动的线程(线程状态为NEW)来说,会设置其标志位为不可启动,
* 而其他的状态则是直接停止
*
* 根据stop源码,start源码分析得出
* stop设置了一个不可启动布尔值,
* start启动时,会先启动一个线程,然后判断上述布尔值,再stop0结束这个线程
* 解决方案
*不再使用stop方法进行状态的设置,
* 直接通过判断条件来决定线程是否可启用。
* 对于start方法的该缺陷,一般不会引起太大的问题,只是增加了线程启动和停止的精度而已
*/
public static void main(String[] args) {
//不分昼夜地制造垃圾邮件
while (true){
//多线程多个垃圾邮件制造机
SpamMachine spamMachine = new SpamMachine();
//条件判断,不符合条件就设置该线程不可执行
if(!false){
spamMachine.stop();
}
//如果线程是stop状态,则不会启动
spamMachine.start();
}
}
}
class SpamMachine extends Thread{
@Override
public void run() {
System.err.println("制造大量垃圾邮件");
}
}
| 25.428571 | 64 | 0.624398 |
2f2976382f4c08e5e7aaa9a34d46443f62b8e55b | 10,114 | /*
* 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.lucene.facet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.lucene.facet.FacetsCollector.MatchingDocs;
import org.apache.lucene.facet.taxonomy.FacetLabel;
import org.apache.lucene.facet.taxonomy.FastTaxonomyFacetCounts;
import org.apache.lucene.facet.taxonomy.TaxonomyFacetLabels;
import org.apache.lucene.facet.taxonomy.TaxonomyFacetLabels.FacetLabelReader;
import org.apache.lucene.facet.taxonomy.TaxonomyReader;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util.TestUtil;
public abstract class FacetTestCase extends LuceneTestCase {
public Facets getTaxonomyFacetCounts(
TaxonomyReader taxoReader, FacetsConfig config, FacetsCollector c) throws IOException {
return getTaxonomyFacetCounts(taxoReader, config, c, FacetsConfig.DEFAULT_INDEX_FIELD_NAME);
}
public Facets getTaxonomyFacetCounts(
TaxonomyReader taxoReader, FacetsConfig config, FacetsCollector c, String indexFieldName)
throws IOException {
return new FastTaxonomyFacetCounts(indexFieldName, taxoReader, config, c);
}
/**
* Utility method that uses {@link FacetLabelReader} to get facet labels for each hit in {@link
* MatchingDocs}. The method returns {@code List<List<FacetLabel>>} where outer list has one entry
* per document and inner list has all {@link FacetLabel} entries that belong to a document. The
* inner list may be empty if no {@link FacetLabel} are found for a hit.
*
* @param taxoReader {@link TaxonomyReader} used to read taxonomy during search. This instance is
* expected to be open for reading.
* @param fc {@link FacetsCollector} A collector with matching hits.
* @param dimension facet dimension for which labels are requested. A null value fetches labels
* for all dimensions.
* @return {@code List<List<FacetLabel>} where outer list has one non-null entry per document. and
* inner list contain all {@link FacetLabel} entries that belong to a document.
* @throws IOException when a low-level IO issue occurs.
*/
public List<List<FacetLabel>> getAllTaxonomyFacetLabels(
String dimension, TaxonomyReader taxoReader, FacetsCollector fc) throws IOException {
List<List<FacetLabel>> actualLabels = new ArrayList<>();
TaxonomyFacetLabels taxoLabels =
new TaxonomyFacetLabels(taxoReader, FacetsConfig.DEFAULT_INDEX_FIELD_NAME);
for (MatchingDocs m : fc.getMatchingDocs()) {
FacetLabelReader facetLabelReader = taxoLabels.getFacetLabelReader(m.context);
DocIdSetIterator disi = m.bits.iterator();
while (disi.nextDoc() != DocIdSetIterator.NO_MORE_DOCS) {
actualLabels.add(allFacetLabels(disi.docID(), dimension, facetLabelReader));
}
}
return actualLabels;
}
/**
* Utility method to get all facet labels for an input docId and dimension using the supplied
* {@link FacetLabelReader}.
*
* @param docId docId for which facet labels are needed.
* @param dimension Retain facet labels for supplied dimension only. A null value fetches all
* facet labels.
* @param facetLabelReader {@FacetLabelReader} instance use to get facet labels for input docId.
* @return {@code List<FacetLabel>} containing matching facet labels.
* @throws IOException when a low-level IO issue occurs while reading facet labels.
*/
List<FacetLabel> allFacetLabels(int docId, String dimension, FacetLabelReader facetLabelReader)
throws IOException {
List<FacetLabel> facetLabels = new ArrayList<>();
FacetLabel facetLabel;
if (dimension != null) {
for (facetLabel = facetLabelReader.nextFacetLabel(docId, dimension); facetLabel != null; ) {
facetLabels.add(facetLabel);
facetLabel = facetLabelReader.nextFacetLabel(docId, dimension);
}
} else {
for (facetLabel = facetLabelReader.nextFacetLabel(docId); facetLabel != null; ) {
facetLabels.add(facetLabel);
facetLabel = facetLabelReader.nextFacetLabel(docId);
}
}
return facetLabels;
}
protected String[] getRandomTokens(int count) {
String[] tokens = new String[count];
for (int i = 0; i < tokens.length; i++) {
tokens[i] = TestUtil.randomRealisticUnicodeString(random(), 1, 10);
// tokens[i] = _TestUtil.randomSimpleString(random(), 1, 10);
}
return tokens;
}
protected String pickToken(String[] tokens) {
for (int i = 0; i < tokens.length; i++) {
if (random().nextBoolean()) {
return tokens[i];
}
}
// Move long tail onto first token:
return tokens[0];
}
protected static class TestDoc {
public String content;
public String[] dims;
public float value;
}
protected List<TestDoc> getRandomDocs(String[] tokens, int count, int numDims) {
List<TestDoc> docs = new ArrayList<>();
for (int i = 0; i < count; i++) {
TestDoc doc = new TestDoc();
docs.add(doc);
doc.content = pickToken(tokens);
doc.dims = new String[numDims];
for (int j = 0; j < numDims; j++) {
doc.dims[j] = pickToken(tokens);
if (random().nextInt(10) < 3) {
break;
}
}
if (VERBOSE) {
System.out.println(" doc " + i + ": content=" + doc.content);
for (int j = 0; j < numDims; j++) {
if (doc.dims[j] != null) {
System.out.println(" dim[" + j + "]=" + doc.dims[j]);
}
}
}
}
return docs;
}
protected void sortTies(List<FacetResult> results) {
for (FacetResult result : results) {
sortTies(result.labelValues);
}
}
protected void sortTies(LabelAndValue[] labelValues) {
double lastValue = -1;
int numInRow = 0;
int i = 0;
while (i <= labelValues.length) {
if (i < labelValues.length && labelValues[i].value.doubleValue() == lastValue) {
numInRow++;
} else {
if (numInRow > 1) {
Arrays.sort(
labelValues,
i - numInRow,
i,
new Comparator<LabelAndValue>() {
@Override
public int compare(LabelAndValue a, LabelAndValue b) {
assert a.value.doubleValue() == b.value.doubleValue();
return new BytesRef(a.label).compareTo(new BytesRef(b.label));
}
});
}
numInRow = 1;
if (i < labelValues.length) {
lastValue = labelValues[i].value.doubleValue();
}
}
i++;
}
}
protected void sortLabelValues(List<LabelAndValue> labelValues) {
Collections.sort(
labelValues,
new Comparator<LabelAndValue>() {
@Override
public int compare(LabelAndValue a, LabelAndValue b) {
if (a.value.doubleValue() > b.value.doubleValue()) {
return -1;
} else if (a.value.doubleValue() < b.value.doubleValue()) {
return 1;
} else {
return new BytesRef(a.label).compareTo(new BytesRef(b.label));
}
}
});
}
protected void sortFacetResults(List<FacetResult> results) {
Collections.sort(
results,
new Comparator<FacetResult>() {
@Override
public int compare(FacetResult a, FacetResult b) {
if (a.value.doubleValue() > b.value.doubleValue()) {
return -1;
} else if (b.value.doubleValue() > a.value.doubleValue()) {
return 1;
} else {
return 0;
}
}
});
}
protected void assertFloatValuesEquals(List<FacetResult> a, List<FacetResult> b) {
assertEquals(a.size(), b.size());
float lastValue = Float.POSITIVE_INFINITY;
Map<String, FacetResult> aByDim = new HashMap<>();
for (int i = 0; i < a.size(); i++) {
assertTrue(a.get(i).value.floatValue() <= lastValue);
lastValue = a.get(i).value.floatValue();
aByDim.put(a.get(i).dim, a.get(i));
}
lastValue = Float.POSITIVE_INFINITY;
Map<String, FacetResult> bByDim = new HashMap<>();
for (int i = 0; i < b.size(); i++) {
bByDim.put(b.get(i).dim, b.get(i));
assertTrue(b.get(i).value.floatValue() <= lastValue);
lastValue = b.get(i).value.floatValue();
}
for (String dim : aByDim.keySet()) {
assertFloatValuesEquals(aByDim.get(dim), bByDim.get(dim));
}
}
protected void assertFloatValuesEquals(FacetResult a, FacetResult b) {
assertEquals(a.dim, b.dim);
assertTrue(Arrays.equals(a.path, b.path));
assertEquals(a.childCount, b.childCount);
assertEquals(a.value.floatValue(), b.value.floatValue(), a.value.floatValue() / 1e5);
assertEquals(a.labelValues.length, b.labelValues.length);
for (int i = 0; i < a.labelValues.length; i++) {
assertEquals(a.labelValues[i].label, b.labelValues[i].label);
assertEquals(
a.labelValues[i].value.floatValue(),
b.labelValues[i].value.floatValue(),
a.labelValues[i].value.floatValue() / 1e5);
}
}
}
| 37.738806 | 100 | 0.654439 |
327038eb5dd6b60a047da759ff3119c6119789ff | 182 | package frc.robot.subsystems.dummy;
import frc.robot.subsystems.Climber;
public class DummyClimber implements Climber {
@Override
public void setOutput(double output) {
}
}
| 16.545455 | 46 | 0.769231 |
acddb065e8b6599d00f869213cd343e02bd7e6b5 | 448 | package uk.co.gmescouts.stmarys.beddingplants.data;
import org.springframework.data.jpa.repository.JpaRepository;
import uk.co.gmescouts.stmarys.beddingplants.data.model.Plant;
import javax.persistence.OrderBy;
import java.util.Set;
public interface PlantRepository extends JpaRepository<Plant, Long> {
Plant findByNumAndSaleSaleYear(Integer num, Integer saleSaleYear);
@OrderBy("num")
Set<Plant> findBySaleSaleYear(Integer saleSaleYear);
}
| 29.866667 | 69 | 0.823661 |
37d0df0777f9c2df3faa0df2406244b36fe13cda | 3,866 | /*
* Copyright (C) 2020 Beijing Yishu Technology Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.growingio.android.sdk;
import android.text.TextUtils;
public class CoreConfiguration implements Configurable {
private String mProjectId;
private String mUrlScheme;
private String mChannel;
private boolean mDebugEnabled = false;
private int mCellularDataLimit = 10;
private int mDataUploadInterval = 15;
private int mSessionInterval = 30;
private boolean mDataCollectionEnabled = true;
private boolean mUploadExceptionEnabled = true;
private String mDataCollectionServerHost = "http://api.growingio.com";
private boolean mOaidEnabled = false;
public CoreConfiguration(String projectId, String urlScheme) {
mProjectId = projectId;
mUrlScheme = urlScheme;
}
public CoreConfiguration setProject(String projectId, String urlScheme) {
mProjectId = projectId;
mUrlScheme = urlScheme;
return this;
}
public String getProjectId() {
return mProjectId;
}
public boolean isDataCollectionEnabled() {
return mDataCollectionEnabled;
}
public CoreConfiguration setDataCollectionEnabled(boolean dataCollectionEnabled) {
mDataCollectionEnabled = dataCollectionEnabled;
return this;
}
public String getUrlScheme() {
return mUrlScheme;
}
public String getChannel() {
return mChannel;
}
public CoreConfiguration setChannel(String channel) {
this.mChannel = channel;
return this;
}
public boolean isUploadExceptionEnabled() {
return mUploadExceptionEnabled;
}
public CoreConfiguration setUploadExceptionEnabled(boolean uploadExceptionEnabled) {
this.mUploadExceptionEnabled = uploadExceptionEnabled;
return this;
}
public boolean isDebugEnabled() {
return mDebugEnabled;
}
public CoreConfiguration setDebugEnabled(boolean enabled) {
this.mDebugEnabled = enabled;
return this;
}
public int getCellularDataLimit() {
return mCellularDataLimit;
}
public CoreConfiguration setCellularDataLimit(int cellularDataLimit) {
this.mCellularDataLimit = cellularDataLimit;
return this;
}
public int getDataUploadInterval() {
return mDataUploadInterval;
}
public CoreConfiguration setDataUploadInterval(int dataUploadInterval) {
this.mDataUploadInterval = dataUploadInterval;
return this;
}
public int getSessionInterval() {
return mSessionInterval;
}
public CoreConfiguration setSessionInterval(int sessionInterval) {
this.mSessionInterval = sessionInterval;
return this;
}
public String getDataCollectionServerHost() {
return mDataCollectionServerHost;
}
public CoreConfiguration setDataCollectionServerHost(String dataCollectionServerHost) {
if (!TextUtils.isEmpty(dataCollectionServerHost)) {
mDataCollectionServerHost = dataCollectionServerHost;
}
return this;
}
public boolean isOaidEnabled() {
return mOaidEnabled;
}
public CoreConfiguration setOaidEnabled(boolean enabled) {
this.mOaidEnabled = enabled;
return this;
}
}
| 28.218978 | 91 | 0.699948 |
e1aeacc8407eaad31575e5125e68360921de017b | 1,128 | package hash;
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;
public class LinguisticHash {
public static int hash(String key) {
//Google Translate Set up
Translate translate = TranslateOptions.getDefaultInstance().getService();
//Translate Key to German
//TODO: Set this up so that the language the key is translated to is selected as different based on characteristics of the key. Need to think more on this.
Translation translation = translate.translate(
key,
Translate.TranslateOption.sourceLanguage("en"),
Translate.TranslateOption.targetLanguage("gr")
);
//the rest is a fairly basic hash
int index = 1;
String translatedKey = translation.toString();
char[] array = translatedKey.toCharArray();
for (int i = 0; i < array.length; i++) {
int c = array[i];
c *= i;
index *= c;
}
index *= 599;
return index;
}
}
| 26.232558 | 163 | 0.617908 |
a392705e16716b567a1e7785371d923d909a064c | 3,946 | package edu.anadolu.qpp;
import edu.anadolu.datasets.DataSet;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.TermQuery;
import org.clueweb09.InfoNeed;
import java.io.IOException;
import java.nio.file.Path;
import java.util.LinkedHashSet;
import static edu.anadolu.analysis.Analyzers.getAnalyzedToken;
import static edu.anadolu.analysis.Analyzers.getAnalyzedTokens;
import static org.apache.lucene.search.similarities.ModelBase.log2;
/**
* The PMI of a pair of outcomes x and y belonging to discrete random variables X and Y quantifies the discrepancy between
* the probability of their coincidence given their joint distribution and their individual distributions, assuming independence.
*/
public class PMI extends Base {
private final QueryParser queryParser;
public PMI(Path indexPath, String field) throws IOException {
super(indexPath, field);
queryParser = new QueryParser(field, analyzer);
queryParser.setDefaultOperator(QueryParser.Operator.AND);
}
public PMI(DataSet dataset, String tag, String field) throws IOException {
this(dataset.indexesPath().resolve(tag), field);
}
/**
* the number of documents containing at both of the terms
*/
private int term1ANDterm2(String term1, String term2) throws IOException, ParseException {
int temp = t1ANDt2(term1, term2);
int actual = searcher.count(queryParser.parse(term1 + " " + term2)) + 1;
if (temp != actual) throw new RuntimeException("previous implementation returns different result from new one");
return actual;
}
/**
* the number of documents containing at both of the terms
*/
private int t1ANDt2(String term1, String term2) throws IOException {
TermQuery t1 = new TermQuery(new Term(field, getAnalyzedToken(term1, analyzer)));
TermQuery t2 = new TermQuery(new Term(field, getAnalyzedToken(term2, analyzer)));
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.add(t1, BooleanClause.Occur.MUST).add(t2, BooleanClause.Occur.MUST);
return searcher.count(builder.build()) + 1;
}
@Override
public double value(String word) {
throw new UnsupportedOperationException();
}
public long analyzedDF(String field, String word) throws IOException {
return df(field, getAnalyzedToken(word, analyzer)) + 1;
}
public double pmi(String m1, String m2) throws IOException, ParseException {
return log2((docCount + 1) * (double) term1ANDterm2(m1, m2) / (double) (analyzedDF(field, m1) * analyzedDF(field, m2)));
}
public double value(InfoNeed need) throws IOException, ParseException {
double pmi = 0.0;
int counter = 0;
// hip-hop contains more than one tokens : [hip, hop]
String[] distinctTerms = (new LinkedHashSet<>(getAnalyzedTokens(need.query(), analyzer))).toArray(new String[0]);
if (distinctTerms.length == 1) {
// TODO what is the value of average PMI for one term query?
return 0.0;
}
for (int i = 0; i < distinctTerms.length; i++) {
final String m1 = distinctTerms[i];
for (int j = i + 1; j < distinctTerms.length; j++) {
final String m2 = distinctTerms[j];
int intersect = term1ANDterm2(m1, m2);
if (intersect == 0) {
//TODO do something when there is no intersection since logarithm of zero is not defined.
// at the time of being use +1 trick
}
pmi += pmi(m1, m2);
counter++;
}
}
return pmi / counter;
}
}
| 34.614035 | 129 | 0.667765 |
a378740f0485815130a396812f8fc0650d7dbc6d | 1,072 | /**
*
*/
package de.unileipzig.ws2tm.ws.soap.impl;
import de.unileipzig.ws2tm.ws.soap.Authentication;
/**
* <b>Class AuthenticationImpl</b> implements class {@link Authentication}
*
* @author Torsten Grigull
* @version 0.1 (2011/01/31)
*
*/
public class AuthenticationImpl implements Authentication {
private String pw;
private String userName;
public AuthenticationImpl(String user, String pw) {
this.setUserName(user);
this.setUserPassword(pw);
}
@Override
public boolean securityRequired() {
if (this.pw != null && this.userName != null) {
return true;
}
return false;
}
@Override
public String getUserPassword() {
return this.pw;
}
@Override
public String getUserName() {
return this.userName;
}
@Override
public void setUserPassword(String pw) {
if (pw == null || pw.length() == 0) {
throw new NullPointerException();
}
this.pw = pw;
}
@Override
public void setUserName(String name) {
if (name == null || name.length() == 0) {
throw new NullPointerException();
}
this.userName = name;
}}
| 17.866667 | 74 | 0.67444 |
bae05dc3c765ed8f95799961888855c922f387ae | 2,369 | // --------------------------------------------------------------------------------
// Copyright 2002-2022 Echo Three, LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.echothree.ui.web.cms.action;
import com.echothree.ui.web.cms.framework.ParameterConstants;
import com.google.common.base.Splitter;
import javax.servlet.http.HttpServletRequest;
public class ItemDescriptionNames {
public String itemDescriptionTypeName;
public String itemName;
public String[] itemNames;
public String languageIsoName;
public ItemDescriptionNames(HttpServletRequest request) {
String itemNamesParameter = request.getParameter(ParameterConstants.ITEM_NAMES);
itemDescriptionTypeName = request.getParameter(ParameterConstants.ITEM_DESCRIPTION_TYPE_NAME);
itemName = request.getParameter(ParameterConstants.ITEM_NAME);
languageIsoName = request.getParameter(ParameterConstants.LANGUAGE_ISO_NAME);
// If ItemName exists as a parameter, try to split it using a :. If there was only
// one result, then clear itemNames, otherwise clear itemname. Onely one of the two
// should be not null in the end.
if(itemNamesParameter != null) {
itemNames = Splitter.on(':').trimResults().omitEmptyStrings().splitToList(itemNamesParameter).toArray(new String[0]);
if(itemNames.length == 0) {
itemNames = null;
}
}
}
public boolean hasAllNames() {
// You must have either itemName or itemNames, but never both.
return itemDescriptionTypeName != null
&& ((itemName != null && itemNames == null) || (itemName == null && itemNames != null))
&& languageIsoName != null;
}
}
| 41.561404 | 129 | 0.649219 |
ed239c80491d3d350176a11956dc785745e13923 | 5,452 | package openblocks.client.renderer.item;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.RenderItem;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.Icon;
import net.minecraftforge.client.IItemRenderer;
import openblocks.common.item.ItemDevNull.Icons;
import openmods.GenericInventory;
import openmods.ItemInventory;
import openmods.renderer.DisplayListWrapper;
import openmods.utils.ItemUtils;
import openmods.utils.TextureUtils;
import openmods.utils.render.RenderUtils;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL12;
public class ItemRendererDevNull implements IItemRenderer {
protected static RenderItem itemRenderer = new RenderItem();
private GenericInventory inventory = new GenericInventory("", false, 1);
private DisplayListWrapper cube = new DisplayListWrapper() {
@Override
public void compile() {
Icon backgroundIcon = Icons.iconFull;
final float minU = backgroundIcon.getMinU();
final float minV = backgroundIcon.getMinV();
final float maxV = backgroundIcon.getMaxV();
final float maxU = backgroundIcon.getMaxU();
final Tessellator tes = new Tessellator();
tes.startDrawingQuads();
tes.addVertexWithUV(0, 0, 0, minU, minV);
tes.addVertexWithUV(0, 1, 0, minU, maxV);
tes.addVertexWithUV(1, 1, 0, maxU, maxV);
tes.addVertexWithUV(1, 0, 0, maxU, minV);
tes.addVertexWithUV(0, 0, 1, minU, minV);
tes.addVertexWithUV(1, 0, 1, minU, maxV);
tes.addVertexWithUV(1, 1, 1, maxU, maxV);
tes.addVertexWithUV(0, 1, 1, maxU, minV);
tes.addVertexWithUV(0, 0, 0, minU, minV);
tes.addVertexWithUV(0, 0, 1, minU, maxV);
tes.addVertexWithUV(0, 1, 1, maxU, maxV);
tes.addVertexWithUV(0, 1, 0, maxU, minV);
tes.addVertexWithUV(1, 0, 0, minU, minV);
tes.addVertexWithUV(1, 1, 0, minU, maxV);
tes.addVertexWithUV(1, 1, 1, maxU, maxV);
tes.addVertexWithUV(1, 0, 1, maxU, minV);
tes.addVertexWithUV(0, 0, 0, minU, minV);
tes.addVertexWithUV(1, 0, 0, minU, maxV);
tes.addVertexWithUV(1, 0, 1, maxU, maxV);
tes.addVertexWithUV(0, 0, 1, maxU, minV);
tes.addVertexWithUV(0, 1, 0, minU, minV);
tes.addVertexWithUV(0, 1, 1, minU, maxV);
tes.addVertexWithUV(1, 1, 1, maxU, maxV);
tes.addVertexWithUV(1, 1, 0, maxU, minV);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glFrontFace(GL11.GL_CW);
GL11.glDisable(GL11.GL_LIGHTING);
RenderUtils.disableLightmap();
tes.draw();
RenderUtils.enableLightmap();
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glFrontFace(GL11.GL_CCW);
GL11.glDisable(GL11.GL_CULL_FACE);
}
};
@Override
public boolean handleRenderType(ItemStack item, ItemRenderType type) {
return true;
}
@Override
public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack stack, ItemRendererHelper helper) {
return type != ItemRenderType.INVENTORY;
}
@Override
public void renderItem(ItemRenderType type, ItemStack containerStack, Object... data) {
if (data.length == 0 || !(data[0] instanceof RenderBlocks)) { return; }
NBTTagCompound tag = ItemUtils.getItemTag(containerStack);
NBTTagCompound inventoryTag = ItemInventory.getInventoryTag(tag);
inventory.readFromNBT(inventoryTag);
ItemStack containedStack = inventory.getStackInSlot(0);
if (type == ItemRenderType.INVENTORY) renderInventoryStack(containerStack, containedStack);
else renderInHandStack(type, containerStack, containedStack);
}
protected void renderInHandStack(ItemRenderType type, ItemStack containerStack, ItemStack containedStack) {
GL11.glPushMatrix();
if (type == ItemRenderType.ENTITY) GL11.glTranslated(-0.5, -0.5, -0.5);
// GL11.glLineWidth(1.0f);
TextureUtils.bindDefaultItemsTexture();
cube.render();
if (containedStack != null) {
GL11.glTranslated(0.5, 0.5, 0.5);
GL11.glScalef(0.8f, 0.8f, 0.8f);
Minecraft mc = Minecraft.getMinecraft();
RenderManager.instance.itemRenderer.renderItem(mc.thePlayer, containedStack, 0, type);
}
GL11.glPopMatrix();
}
private static void renderInventoryStack(ItemStack containerStack, ItemStack containedStack) {
Minecraft mc = Minecraft.getMinecraft();
TextureManager textureManager = mc.getTextureManager();
FontRenderer fontRenderer = RenderManager.instance.getFontRenderer();
GL11.glPushMatrix();
RenderUtils.disableLightmap();
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
GL11.glEnable(GL12.GL_RESCALE_NORMAL);
Icon backgroundIcon = Icons.iconTransparent;
TextureUtils.bindDefaultItemsTexture();
itemRenderer.renderIcon(0, 0, backgroundIcon, 16, 16);
if (fontRenderer != null && containedStack != null) {
GL11.glPushMatrix();
RenderHelper.enableGUIStandardItemLighting();
GL11.glScalef(14.0f / 16.0f, 14.0f / 16.0f, 1);
itemRenderer.renderItemAndEffectIntoGUI(fontRenderer, textureManager, containedStack, 1, 1);
GL11.glPopMatrix();
final String sizeToRender = (containedStack.stackSize > 1)? Integer.toString(containedStack.stackSize) : "";
itemRenderer.renderItemOverlayIntoGUI(fontRenderer, textureManager, containedStack, 0, 0, sizeToRender);
}
GL11.glPopMatrix();
}
}
| 34.506329 | 111 | 0.747982 |
b651f1cdaf0c0163f05729bbfbc75b34c8f09d6b | 2,512 | package gov.vha.isaac.ochre.model.logic.node;
import gov.vha.isaac.ochre.api.DataTarget;
import gov.vha.isaac.ochre.model.logic.LogicalExpressionOchreImpl;
import gov.vha.isaac.ochre.api.logic.LogicNode;
import gov.vha.isaac.ochre.api.logic.NodeSemantic;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.IOException;
import java.util.UUID;
import gov.vha.isaac.ochre.api.util.UuidT5Generator;
/**
* Created by kec on 12/10/14.
*/
public class LiteralNodeBoolean extends LiteralNode {
boolean literalValue;
public LiteralNodeBoolean(LogicalExpressionOchreImpl logicGraphVersion, DataInputStream dataInputStream) throws IOException {
super(logicGraphVersion, dataInputStream);
literalValue = dataInputStream.readBoolean();
}
public LiteralNodeBoolean(LogicalExpressionOchreImpl logicGraphVersion, boolean literalValue) {
super(logicGraphVersion);
this.literalValue = literalValue;
}
public boolean getLiteralValue() {
return literalValue;
}
@Override
protected void writeNodeData(DataOutput dataOutput, DataTarget dataTarget) throws IOException {
super.writeData(dataOutput, dataTarget);
dataOutput.writeBoolean(literalValue);
}
@Override
public NodeSemantic getNodeSemantic() {
return NodeSemantic.LITERAL_BOOLEAN;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
LiteralNodeBoolean that = (LiteralNodeBoolean) o;
return literalValue == that.literalValue;
}
@Override
protected UUID initNodeUuid() {
return UuidT5Generator.get(getNodeSemantic().getSemanticUuid(),
Boolean.toString(literalValue));
}
@Override
protected int compareFields(LogicNode o) {
LiteralNodeBoolean that = (LiteralNodeBoolean) o;
return Boolean.compare(this.literalValue, that.literalValue);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (literalValue ? 1 : 0);
return result;
}
@Override
public String toString() {
return toString("");
}
@Override
public String toString(String nodeIdSuffix) {
return "Boolean literal[" + getNodeIndex() + nodeIdSuffix + "]" + literalValue + super.toString(nodeIdSuffix);
}
} | 28.545455 | 129 | 0.6875 |
b09badcba504879281aaac9d086ada58a461cd26 | 147 | class Test {
{
Object o = null;
Comparable<String> c = <error descr="Variable 'o' is already defined in the scope">o</error> -> 42;
}
} | 24.5 | 103 | 0.612245 |
9a2422dbece9bf559b83e841202b8845eaa6cc9a | 1,610 | package com.alibaba.arthas.tunnel.server.app.security;
import com.alibaba.arthas.tunnel.server.app.entity.SysRole;
import com.alibaba.arthas.tunnel.server.app.entity.SysUser;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Set;
public class SecurityUser extends SysUser implements UserDetails {
private static final long serialVersionUID = 1L;
public SecurityUser(SysUser suser) {
if(suser != null)
{
this.setUserName(suser.getUserName());
this.setPassword(suser.getPassword());
this.setSysRoles(suser.getSysRoles());
}
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
Set<SysRole> userRoles = this.getSysRoles();
if(userRoles != null)
{
for (SysRole role : userRoles) {
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(role.getRoleName());
authorities.add(authority);
}
}
return authorities;
}
@Override
public String getPassword() {
return super.getPassword();
}
@Override
public String getUsername() {
return super.getUserName();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| 22.676056 | 86 | 0.752174 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.