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
|
---|---|---|---|---|---|
3e643703da60002943497dfb9f1cd70aed0e0530 | 1,595 | package navigation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.time.Duration;
public class CartPage {
@FindBy(className = "cart_quantity_delete")
private WebElement deleteButton;
@FindBy(css = "#center_column > p.cart_navigation.clearfix > a.button.btn.btn-default.standard-checkout.button-medium")
private WebElement proceedToCheckOutButton;
@FindBy(css = "#header_logo > a > img")
private WebElement logo;
private WebDriver driver;
public CartPage(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void clickDeleteButtonToRemoveProduct()
{
deleteButton.click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@id=\"center_column\"]/p")));
}
public boolean productIsDeletedFromCart()
{
return driver.getPageSource().contains("Your shopping cart is empty.");
}
public boolean productIsAddedToCart()
{
return driver.getPageSource().contains("Shopping-cart summary");
}
public void clickProceedToCheckOutButton()
{
proceedToCheckOutButton.click();
}
public void clickOnLogo()
{
logo.click();
}
}
| 27.033898 | 123 | 0.708464 |
8d60c506c8f0033118b5687507291fe20723480d | 203 | package libreria;
public class EditoreInesistente extends Exception {
public EditoreInesistente() {
// TODO Auto-generated constructor stub
System.out.println("Editore inesistente!");
}
}
| 22.555556 | 52 | 0.738916 |
415cc50223d1d46802360fefa2f830cb743098b6 | 5,237 | package uk.jamesdal.perfmock.test.unit.internal;
import java.util.HashSet;
import java.util.Set;
import junit.framework.TestCase;
import org.hamcrest.StringDescription;
import uk.jamesdal.perfmock.States;
import uk.jamesdal.perfmock.internal.StateMachine;
public class StateMachineTests extends TestCase {
States stateMachine = new StateMachine("stateMachineName");
public void testIsInitiallyInNoState() {
for (String state : anyState) {
assertFalse("should not report being in state " + state,
stateMachine.is(state).isActive());
assertTrue("should report not being in state " + state,
stateMachine.isNot(state).isActive());
}
}
public void testCanEnterAState() {
String state = "A";
Set<String> otherStates = except(anyState, state);
stateMachine.is(state).activate();
assertTrue("should report being in state " + state,
stateMachine.is(state).isActive());
assertFalse("should not report not being in state " + state,
stateMachine.isNot(state).isActive());
for (String otherState : otherStates) {
assertFalse("should not report being in state " + otherState,
stateMachine.is(otherState).isActive());
assertTrue("should report not being in state " + otherState,
stateMachine.isNot(otherState).isActive());
}
}
public void testCanChangeState() {
String state = "B";
Set<String> otherStates = except(anyState, state);
stateMachine.is("A").activate();
stateMachine.is(state).activate();
assertTrue("should report being in state " + state,
stateMachine.is(state).isActive());
assertFalse("should not report not being in state " + state,
stateMachine.isNot(state).isActive());
for (String otherState : otherStates) {
assertFalse("should not report being in state " + otherState,
stateMachine.is(otherState).isActive());
assertTrue("should report not being in state " + otherState,
stateMachine.isNot(otherState).isActive());
}
}
public void testCanBePutIntoAnInitialState() {
String initialState = "A";
Set<String> otherStates = except(anyState, initialState);
stateMachine.startsAs(initialState);
assertTrue("should report being in state " + initialState,
stateMachine.is(initialState).isActive());
assertFalse("should not report not being in state " + initialState,
stateMachine.isNot(initialState).isActive());
for (String otherState : otherStates) {
assertFalse("should not report being in state " + otherState,
stateMachine.is(otherState).isActive());
assertTrue("should report not being in state " + otherState,
stateMachine.isNot(otherState).isActive());
}
}
public void testCanBePutIntoANewState() {
String nextState = "B";
Set<String> otherStates = except(anyState, nextState);
stateMachine.startsAs("A");
stateMachine.become(nextState);
assertTrue("should report being in state " + nextState,
stateMachine.is(nextState).isActive());
assertFalse("should not report not being in state " + nextState,
stateMachine.isNot(nextState).isActive());
for (String otherState : otherStates) {
assertFalse("should not report being in state " + otherState,
stateMachine.is(otherState).isActive());
assertTrue("should report not being in state " + otherState,
stateMachine.isNot(otherState).isActive());
}
}
public void testDescribesItselfAsNameAndCurrentState() {
assertEquals("description with no current state",
"stateMachineName has no current state", StringDescription.toString(stateMachine));
stateMachine.is("stateName").activate();
assertEquals("description with a current state",
"stateMachineName is stateName", StringDescription.toString(stateMachine));
assertEquals("description with a current state from toString",
"stateMachineName is stateName", stateMachine.toString());
}
public void testHasSelfDescribingStates() {
assertEquals("stateMachineName is A", StringDescription.toString(stateMachine.is("A")));
assertEquals("stateMachineName is not A", StringDescription.toString(stateMachine.isNot("A")));
}
private <T> Set<T> except(Set<T> s, T e) {
Set<T> result = new HashSet<T>(s);
result.remove(e);
return result;
}
private final Set<String> anyState = new HashSet<String>() {{
add("A");
add("B");
add("C");
add("D");
}};
}
| 39.37594 | 104 | 0.594233 |
2eed40019b9c25c7bdb9f7df15bf5ffed41224eb | 1,460 | package pl.beriko.ioz.web.controller.security;
import javax.faces.context.FacesContext;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import pl.beriko.ioz.web.exception.SecurityViolationException;
import pl.beriko.ioz.web.util.SecurityUtil;
import java.io.Serializable;
import java.security.Permission;
import java.util.concurrent.Callable;
/**
* Project: Suggestion List
* User: Octavian Rusu
* Date: 05/27/2010
*/
public abstract class SecurityController implements Serializable {
private static final long serialVersionUID = 8355511577165829602L;
public String getCheckPermissions() {
if (getPermisssions() != null && !SecurityUtil.hasPermissions(getPermisssions())) {
publishException(new SecurityViolationException("You have no rights to access this page."));
}
return "";
}
protected <T> T execute(Callable<T> c) throws Exception {
try {
return c.call();
} catch (Exception e) {
publishException(e);
throw e;
}
}
protected void publishException(Exception e) {
FacesContext ctx = FacesContext.getCurrentInstance();
ExceptionQueuedEventContext eventContext = new ExceptionQueuedEventContext(ctx, e);
ctx.getApplication().publishEvent(ctx, ExceptionQueuedEvent.class, eventContext);
}
protected abstract Permission[] getPermisssions();
}
| 30.416667 | 104 | 0.713699 |
b132d9c9b19b88c1d9bac7aeea7148f60e993ffc | 1,816 | package org.activiti.designer.features;
import org.activiti.designer.ActivitiImageProvider;
import org.eclipse.bpmn2.Bpmn2Factory;
import org.eclipse.bpmn2.ManualTask;
import org.eclipse.bpmn2.SubProcess;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.ICreateContext;
import org.eclipse.graphiti.mm.pictograms.Diagram;
public class CreateManualTaskFeature extends AbstractCreateFastBPMNFeature {
public static final String FEATURE_ID_KEY = "manualtask";
public CreateManualTaskFeature(IFeatureProvider fp) {
super(fp, "ManualTask", "Add manual task");
}
@Override
public boolean canCreate(ICreateContext context) {
Object parentObject = getBusinessObjectForPictogramElement(context.getTargetContainer());
return (context.getTargetContainer() instanceof Diagram || parentObject instanceof SubProcess);
}
@Override
public Object[] create(ICreateContext context) {
ManualTask newManualTask = Bpmn2Factory.eINSTANCE.createManualTask();
newManualTask.setId(getNextId());
setName("Manual Task", newManualTask, context);
Object parentObject = getBusinessObjectForPictogramElement(context.getTargetContainer());
if (parentObject instanceof SubProcess) {
((SubProcess) parentObject).getFlowElements().add(newManualTask);
} else {
getDiagram().eResource().getContents().add(newManualTask);
}
addGraphicalContent(newManualTask, context);
return new Object[] { newManualTask };
}
@Override
public String getCreateImageId() {
return ActivitiImageProvider.IMG_MANUALTASK;
}
@Override
protected String getFeatureIdKey() {
return FEATURE_ID_KEY;
}
@SuppressWarnings("rawtypes")
@Override
protected Class getFeatureClass() {
return Bpmn2Factory.eINSTANCE.createManualTask().getClass();
}
}
| 30.779661 | 99 | 0.784141 |
44666376c3f316aa290324a395019d723e524808 | 3,484 | /*
* The MIT License (MIT)
* Copyright © 2019-2020 <sky>
*
* 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.sky.meteor.serialization;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.sky.meteor.common.enums.SerializeEnum;
import com.sky.meteor.common.spi.SpiMetadata;
import org.objenesis.Objenesis;
import org.objenesis.ObjenesisStd;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
/**
* @author
*/
@SpiMetadata(name = "protostuff")
public class ProtostuffSerializer implements ObjectSerializer {
private static final SchemaCache CACHED_SCHEMA = SchemaCache.getInstance();
private static final Objenesis OBJENESIS_STD = new ObjenesisStd(true);
private static <T> Schema<T> getSchema(Class<T> cls) {
return (Schema<T>) CACHED_SCHEMA.get(cls);
}
/**
* 序列化对象
*
* @param obj 需要序更列化的对象
* @return byte []
* @throws RuntimeException
*/
@Override
public byte[] serialize(Object obj) throws RuntimeException {
Class cls = obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
Schema schema = getSchema(cls);
ProtostuffIOUtil.writeTo(outputStream, obj, schema, buffer);
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
} finally {
buffer.clear();
}
return outputStream.toByteArray();
}
/**
* 反序列化对象
*
* @param param 需要反序列化的byte []
* @param clazz
* @return 对象
* @throws RuntimeException
*/
@Override
public <T> T deSerialize(byte[] param, Class<T> clazz) throws RuntimeException {
T object;
try {
ByteArrayInputStream inputStream = new ByteArrayInputStream(param);
Class cls = clazz;
object = OBJENESIS_STD.newInstance((Class<T>) cls);
Schema schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(inputStream, object, schema);
return object;
} catch (Exception e) {
throw new RuntimeException(e.getMessage(), e);
}
}
@Override
public byte getSchema() {
return SerializeEnum.PROTOSTUFF.getSerializerCode();
}
}
| 34.156863 | 86 | 0.687715 |
d7c027622cb8897c441bcccf5e645a7857221f80 | 3,703 | /**
* JBoss, Home of Professional Open Source
* Copyright Red Hat, Inc., and individual contributors.
*
* 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.jboss.aerogear.webpush.netty;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerUpgradeHandler;
import io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodecFactory;
import io.netty.handler.codec.http2.Http2CodecUtil;
import io.netty.handler.codec.http2.Http2ServerUpgradeCodec;
import io.netty.handler.ssl.SslContext;
import org.jboss.aerogear.webpush.DefaultWebPushServer;
import org.jboss.aerogear.webpush.WebPushServer;
import org.jboss.aerogear.webpush.WebPushServerConfig;
import org.jboss.aerogear.webpush.datastore.DataStore;
import static io.netty.handler.codec.http.HttpServerUpgradeHandler.UpgradeCodec;
class WebPushChannelInitializer extends ChannelInitializer<SocketChannel> {
private final SslContext sslCtx;
private final DataStore dataStore;
private final WebPushServerConfig config;
private final byte[] privateKey;
WebPushChannelInitializer(final SslContext sslCtx,
final DataStore dataStore,
final WebPushServerConfig config) {
this.sslCtx = sslCtx;
this.dataStore = dataStore;
this.config = config;
privateKey = DefaultWebPushServer.generateAndStorePrivateKey(dataStore, config);
}
@Override
public void initChannel(final SocketChannel ch) {
final WebPushServer webPushServer = new DefaultWebPushServer(dataStore, config, privateKey);
if (sslCtx != null) {
configureSsl(ch, webPushServer);
} else {
configureClearText(ch, webPushServer);
}
}
private void configureSsl(final SocketChannel ch, final WebPushServer webPushServer) {
ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler(webPushServer));
}
private static void configureClearText(final SocketChannel ch, final WebPushServer webPushServer) {
final HttpServerCodec sourceCodec = new HttpServerCodec();
final HttpServerUpgradeHandler upgradeHandler =
new HttpServerUpgradeHandler(sourceCodec, new WebPushCodecFactory(webPushServer), 65536);
ch.pipeline().addLast(sourceCodec);
ch.pipeline().addLast(upgradeHandler);
}
private static class WebPushCodecFactory implements UpgradeCodecFactory {
private final WebPushServer webPushServer;
WebPushCodecFactory(final WebPushServer webPushServer) {
this.webPushServer = webPushServer;
}
@Override
public UpgradeCodec newUpgradeCodec(final CharSequence protocol) {
if (Http2CodecUtil.HTTP_UPGRADE_PROTOCOL_NAME.equals(protocol)) {
return new Http2ServerUpgradeCodec(new WebPushHttp2HandlerBuilder()
.webPushServer(webPushServer)
.build());
} else {
return null;
}
}
}
}
| 39.817204 | 105 | 0.716176 |
3cc33442ce3de6a988ebaae80a2df9615be4ebe0 | 309 | package com.tec.eventbus;
import com.google.common.eventbus.Subscribe;
/**
* @author SUNLEI
* @version V1.0
* @Description: <p>创建日期:2019年12月20日 </p>
* @see
*/
public class TestClass {
@Subscribe
public void getEventbusInfo(String str) {
System.out.println("received : " + str);
}
}
| 18.176471 | 48 | 0.653722 |
c1e1877161e68b5895d64327d7a2c361b24f9c68 | 2,861 | package org.aoc.day10;
import org.aoc.utils.InputReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
public class Day10 {
private static int count1;
private static int count3;
public static void main(String[] args) {
ArrayList<Integer> input = InputReader.convertFileContentToInt(InputReader.readInputFile("day10"))
.stream().sorted().collect(Collectors.toCollection(ArrayList::new));
count1 = 0;
count3 = 0;
HashSet<Integer> adapters = new HashSet<>(input);
int deviceJoltage = Collections.max(input) + 3;
int result1 = part1(adapters, deviceJoltage);
System.out.println("Part 1 : " + result1);
AtomicLong configurations = new AtomicLong(1);
AtomicInteger onesStreak = new AtomicInteger();
input.stream().reduce(0, (prev, next) -> {
part2(prev, next, onesStreak, configurations);
return next;
});
part2(0, 0, onesStreak, configurations);
System.out.println("Part 2 : " + configurations.get());
}
private static int part1(HashSet<Integer> input, int deviceJoltage) {
int startingJoltage = 0;
int gap = 1;
findNextAdapter(startingJoltage, gap, input, deviceJoltage);
return count1 * count3;
}
private static void part2(int prev, int next, AtomicInteger onesStreak, AtomicLong configurations) {
if (next - prev == 1) {
onesStreak.incrementAndGet();
} else {
configurations.set(configurations.get() * getConfigurationsCount(onesStreak.get()));
onesStreak.set(0);
}
}
/**
* Implementation of the Lazy Caterer's sequence
* https://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence
*
* @param streak Number of cuts
* @return Number of pieces that can be created
*/
private static long getConfigurationsCount(int streak) {
streak -= 1;
return (long) (Math.pow(streak, 2.0) + streak + 2) / 2;
}
private static void findNextAdapter(int startingJoltage, int gap, HashSet<Integer> adapters, int deviceJoltage) {
if (startingJoltage + 3 == deviceJoltage) {
incrementCount(3);
} else if (adapters.contains(startingJoltage + gap)) {
incrementCount(gap);
findNextAdapter(startingJoltage + gap, 1, adapters, deviceJoltage);
} else if (gap <= 2) {
findNextAdapter(startingJoltage, gap + 1, adapters, deviceJoltage);
}
}
private static void incrementCount(int gap) {
switch (gap) {
case 1 -> count1++;
case 3 -> count3++;
}
}
}
| 31.788889 | 117 | 0.629151 |
18e25507b1b7e3dce36dab90e1db843366790b92 | 2,068 | package com.nibado.amazon.service.sync.config;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.nibado.amazon.lib.auth.PropertySecrets;
import com.nibado.amazon.lib.sync.Sync;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Configuration
@ConfigurationProperties(prefix = "sync")
public class SyncConfig {
private String region;
private List<Entry> entries = new ArrayList<>();
public List<Entry> getEntries() {
return entries;
}
public void setRegion(final String region) {
this.region = region;
}
public List<Sync> getSyncs() {
log.info("Creating S3 client for region {}", region);
AmazonS3ClientBuilder builder = AmazonS3ClientBuilder.standard();
builder.setRegion(region);
builder.setCredentials(new PropertySecrets());
AmazonS3 client = builder.build();
return getEntries()
.stream()
.map(e -> new Sync(client, e.bucket, e.key, toFile(e.directory)))
.collect(Collectors.toList());
}
private static File toFile(final String dir) {
String directory = dir.trim();
if (directory.startsWith("~")) {
directory = directory.replace("~", System.getProperty("user.home"));
}
File file = new File(directory);
if (!file.exists()) {
throw new IllegalArgumentException(file.getAbsolutePath() + " does not exist");
} else if (!file.isDirectory()) {
throw new IllegalArgumentException(file.getAbsolutePath() + " is not a directory");
}
return file;
}
@Data
public static class Entry {
private String directory;
private String bucket;
private String key;
}
}
| 29.542857 | 95 | 0.662476 |
60fb6b01f14522e3a143cb8f3dad72ed1b4141d6 | 1,546 | /**
* Copyright 2018 辰领科技 lingkj.com
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.lingkj.project.oss.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
/**
* 文件上传
*
* @author admin
*
* @date 2017-03-25 12:13:26
*/
@TableName("sys_oss")
public class SysOssEntity implements Serializable {
private static final long serialVersionUID = 1L;
@TableId
private Long id;
//URL地址
private String url;
//创建时间
private Date createDate;
/**
* 设置:
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取:
*/
public Long getId() {
return id;
}
/**
* 设置:URL地址
*/
public void setUrl(String url) {
this.url = url;
}
/**
* 获取:URL地址
*/
public String getUrl() {
return url;
}
/**
* 设置:创建时间
*/
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
/**
* 获取:创建时间
*/
public Date getCreateDate() {
return createDate;
}
}
| 19.08642 | 80 | 0.682406 |
098d78d29af702090f64a7f27c2ad1045ba60d0a | 565 | package com.deftwun.zombiecopter;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.utils.Logger;
import com.deftwun.zombiecopter.screens.GameScreen;
public class App extends Game {
public static GameScreen gameScreen;
public static GameEngine engine;
public static Assets assets;
@Override
public void create() {
Gdx.app.setLogLevel(Logger.DEBUG);
assets = new Assets();
engine = new GameEngine();
engine.initialize();
gameScreen = new GameScreen();
setScreen(gameScreen);
}
}
| 21.730769 | 52 | 0.716814 |
8a0e5f82af534efc40ce8976626add5789c08a2f | 2,695 | package seedu.room.storage;
import static java.util.Objects.requireNonNull;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Optional;
import java.util.logging.Logger;
import seedu.room.commons.core.LogsCenter;
import seedu.room.commons.exceptions.DataConversionException;
import seedu.room.commons.util.FileUtil;
import seedu.room.model.ReadOnlyResidentBook;
/**
* A class to access ResidentBook data stored as an xml file on the hard disk.
*/
public class XmlResidentBookStorage implements ResidentBookStorage {
private static final Logger logger = LogsCenter.getLogger(XmlResidentBookStorage.class);
private String filePath;
public XmlResidentBookStorage(String filePath) {
this.filePath = filePath;
}
public String getResidentBookFilePath() {
return filePath;
}
@Override
public Optional<ReadOnlyResidentBook> readResidentBook() throws DataConversionException, IOException {
return readResidentBook(filePath);
}
/**
* Similar to {@link #readResidentBook()}
*
* @param filePath location of the data. Cannot be null
* @throws DataConversionException if the file is not in the correct format.
*/
public Optional<ReadOnlyResidentBook> readResidentBook(String filePath) throws DataConversionException,
FileNotFoundException {
requireNonNull(filePath);
File residentBookFile = new File(filePath);
if (!residentBookFile.exists()) {
logger.info("ResidentBook file " + residentBookFile + " not found");
return Optional.empty();
}
ReadOnlyResidentBook residentBookOptional = XmlFileStorage.loadDataFromSaveFile(new File(filePath));
return Optional.of(residentBookOptional);
}
@Override
public void saveResidentBook(ReadOnlyResidentBook residentBook) throws IOException {
saveResidentBook(residentBook, filePath);
}
/**
* Similar to {@link #saveResidentBook(ReadOnlyResidentBook)}
*
* @param filePath location of the data. Cannot be null
*/
public void saveResidentBook(ReadOnlyResidentBook residentBook, String filePath) throws IOException {
requireNonNull(residentBook);
requireNonNull(filePath);
File file = new File(filePath);
FileUtil.createIfMissing(file);
XmlFileStorage.saveDataToFile(file, new XmlSerializableResidentBook(residentBook));
}
//@@author blackroxs
@Override
public void backupResidentBook(ReadOnlyResidentBook residentBook) throws IOException {
saveResidentBook(residentBook, filePath + "-backup.xml");
}
}
| 31.337209 | 108 | 0.721707 |
567bd42c70aa97fa3af44f9c549d3bc85729935e | 1,496 | package ir.codekeshs.scenes;
import ir.codekeshs.Helper;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Category extends Parent {
private final Scene scene;
public Category() {
GridPane root = new GridPane();
root.setBackground(Helper.gameBG("category", 800, 600));
scene = new Scene(root, 800, 600, Color.rgb(250, 240, 240));
root.setAlignment(Pos.CENTER);
root.setHgap(10);
root.setVgap(10);
makeButtons(root);
}
private void makeButtons(GridPane root) {
String url = "src/main/resources/button-images/";
try {
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
int number = i * 2 + j;
Button button = new Button("", new ImageView(new Image(
new FileInputStream(url + number + ".png"))));
root.add(button, i, j);
button.setOnAction(e -> getStage().setScene(new Game(Helper.getCat(number)).getScene()));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public Scene getScene() {
return scene;
}
}
| 30.530612 | 109 | 0.582888 |
10e5949406696022fa5c56170352f947a3914e90 | 3,779 | // Copyright 2017 The Nomulus Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package google.registry.tools;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static google.registry.util.PreconditionsUtils.checkArgumentPresent;
import com.beust.jcommander.IStringConverter;
import com.google.auto.value.AutoValue;
import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.io.BaseEncoding;
import com.google.template.soy.data.SoyListData;
import com.google.template.soy.data.SoyMapData;
import google.registry.flows.domain.DomainFlowUtils;
import java.util.List;
@AutoValue
abstract class DsRecord {
private static final Splitter SPLITTER = Splitter.on(CharMatcher.whitespace()).omitEmptyStrings();
public abstract int keyTag();
public abstract int alg();
public abstract int digestType();
public abstract String digest();
private static DsRecord create(int keyTag, int alg, int digestType, String digest) {
digest = Ascii.toUpperCase(digest);
checkArgument(
BaseEncoding.base16().canDecode(digest),
"digest should be even-lengthed hex, but is %s (length %s)",
digest,
digest.length());
checkArgumentPresent(
DigestType.fromWireValue(digestType),
String.format("DS record uses an unrecognized digest type: %d", digestType));
if (DigestType.fromWireValue(digestType).get().getBytes()
!= BaseEncoding.base16().decode(digest).length) {
throw new IllegalArgumentException(
String.format("DS record has an invalid digest length: %s", digest));
}
if (!DomainFlowUtils.validateAlgorithm(alg)) {
throw new IllegalArgumentException(
String.format("DS record uses an unrecognized algorithm: %d", alg));
}
return new AutoValue_DsRecord(keyTag, alg, digestType, digest);
}
/**
* Parses a string representation of the DS record.
*
* <p>The string format accepted is "[keyTag] [alg] [digestType] [digest]" (i.e., the 4 arguments
* separated by any number of spaces, as it appears in the Zone file)
*/
public static DsRecord parse(String dsRecord) {
List<String> elements = SPLITTER.splitToList(dsRecord);
checkArgument(
elements.size() == 4,
"dsRecord %s should have 4 parts, but has %s",
dsRecord,
elements.size());
return DsRecord.create(
Integer.parseUnsignedInt(elements.get(0)),
Integer.parseUnsignedInt(elements.get(1)),
Integer.parseUnsignedInt(elements.get(2)),
elements.get(3));
}
public SoyMapData toSoyData() {
return new SoyMapData(
"keyTag", keyTag(),
"alg", alg(),
"digestType", digestType(),
"digest", digest());
}
public static SoyListData convertToSoy(List<DsRecord> dsRecords) {
return new SoyListData(dsRecords.stream().map(DsRecord::toSoyData).collect(toImmutableList()));
}
public static class Converter implements IStringConverter<DsRecord> {
@Override
public DsRecord convert(String dsRecord) {
return DsRecord.parse(dsRecord);
}
}
}
| 35.317757 | 100 | 0.71421 |
c2a8beb65ce4407156e9b1d480308e9c7942ff34 | 4,638 | package cc.flogi.dev.smoothchunks.client.handler;
import cc.flogi.dev.smoothchunks.client.SmoothChunksClient;
import cc.flogi.dev.smoothchunks.client.config.LoadAnimation;
import cc.flogi.dev.smoothchunks.client.config.SmoothChunksConfig;
import cc.flogi.dev.smoothchunks.util.UtilEasing;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.render.chunk.ChunkBuilder;
import net.minecraft.client.util.math.MatrixStack;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Direction;
import net.minecraft.util.math.Vec3i;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* @author Caden Kriese (flogic)
*
* Created on 09/27/2020
*/
public final class ChunkAnimationHandler {
/*TODO use Reference2ReferenceLinkedHashMap from FastUtil or just inject the AnimationController directly into BuiltChunk.
* Need to solve concurrency issue as currently #addChunk is called from both render & worker threads.
*/
private static final ChunkAnimationHandler instance = new ChunkAnimationHandler();
private final Map<ChunkBuilder.BuiltChunk, AnimationController> animations = new HashMap<>();
@Getter private final Set<Vec3i> loadedChunks = new HashSet<>();
public static ChunkAnimationHandler get() {
return instance;
}
public void addChunk(ChunkBuilder.BuiltChunk chunk) {
Vec3i origin = chunk.getOrigin();
if (loadedChunks.contains(origin)) return;
loadedChunks.add(origin);
Direction direction = null;
if (SmoothChunksClient.get().getConfig().getLoadAnimation() == LoadAnimation.INWARD
&& MinecraftClient.getInstance().getCameraEntity() != null) {
BlockPos delta = chunk.getOrigin().subtract(MinecraftClient.getInstance().getCameraEntity().getBlockPos());
int dX = Math.abs(delta.getX());
int dZ = Math.abs(delta.getZ());
if (dX > dZ) {
if (delta.getX() > 0) direction = Direction.WEST;
else direction = Direction.EAST;
} else {
if (delta.getZ() > 0) direction = Direction.NORTH;
else direction = Direction.SOUTH;
}
}
animations.putIfAbsent(chunk, new AnimationController(chunk.getOrigin(), direction, System.currentTimeMillis()));
}
public void updateChunk(ChunkBuilder.BuiltChunk chunk, MatrixStack stack) {
SmoothChunksConfig config = SmoothChunksClient.get().getConfig();
AnimationController controller = animations.get(chunk);
if (controller == null || MinecraftClient.getInstance().getCameraEntity() == null) return;
BlockPos finalPos = controller.getFinalPos();
if (config.isDisableNearby()) {
double dX = finalPos.getX() - MinecraftClient.getInstance().getCameraEntity().getPos().getX();
double dZ = finalPos.getZ() - MinecraftClient.getInstance().getCameraEntity().getPos().getZ();
if (dX * dX + dZ * dZ < 32 * 32) return;
}
double completion = (double) (System.currentTimeMillis() - controller.getStartTime()) / config.getDuration() / 1000d;
completion = UtilEasing.easeOutSine(Math.min(completion, 1.0));
switch (config.getLoadAnimation()) {
default:
case DOWNWARD:
stack.translate(0, (finalPos.getY() - completion * finalPos.getY()) * config.getTranslationAmount(), 0);
break;
case UPWARD:
stack.translate(0, (-finalPos.getY() + completion * finalPos.getY()) * config.getTranslationAmount(), 0);
break;
case INWARD:
if (controller.getDirection() == null) break;
Vec3i dirVec = controller.getDirection().getVector();
double mod = -(200 - UtilEasing.easeInOutSine(completion) * 200) * config.getTranslationAmount();
stack.translate(dirVec.getX() * mod, 0, dirVec.getZ() * mod);
break;
case SCALE:
//TODO Find a way to scale centered at the middle of the chunk rather than the origin.
stack.scale((float) completion, (float) completion, (float) completion);
break;
}
if (completion >= 1.0) animations.remove(chunk);
}
@AllArgsConstructor @Data
private static class AnimationController {
private BlockPos finalPos;
private Direction direction;
private long startTime;
}
}
| 41.044248 | 126 | 0.658689 |
226af1cb3363ac59f45730efdb061ac7d44d7184 | 2,015 | package chapter_8;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Parens {
public List<String> getParans(int n) {
List<String> result = new ArrayList<String>();
getParans(n, 0, 0, new StringBuffer(), result);
return result;
}
private void getParans(int n, int numOpeningParams, int numClosingParams, StringBuffer buffer, List<String> result) {
if (numOpeningParams == n && numClosingParams == n) {
result.add(buffer.toString());
} else {
if (numOpeningParams < n) {
buffer.append('(');
numOpeningParams++;
getParans(n, numOpeningParams, numClosingParams, buffer, result);
buffer.setLength(buffer.length() - 1);
numOpeningParams--;
}
if (numClosingParams < numOpeningParams) {
buffer.append(')');
numClosingParams++;
getParans(n, numOpeningParams, numClosingParams, buffer, result);
buffer.setLength(buffer.length() - 1);
numClosingParams--;
}
}
}
public List<String> getParans2(int n) {
List<String> results = new ArrayList<String>();
Set<String> set = getParans2Set(n);
results.addAll(set);
return results;
}
private Set<String> getParans2Set(int n) {
Set<String> set = new HashSet<String>();
String base = "()";
if (n == 1) {
set.add(base);
} else {
Set<String> prevSet = getParans2Set(n - 1);
for (String s : prevSet) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(') {
set.add(s.substring(0, i + 1) + base + s.substring(i + 1, s.length()));
}
}
set.add(s + base);
}
}
return set;
}
}
| 31.484375 | 121 | 0.511166 |
15ae59b412c70f6f5f8b3d37effa51d91239cc9e | 875 | package org.hopter.plugin.security;
import java.util.Set;
/**
* Hopter Security 接口
* <br/>
* 可在应用中实现该接口,或者在 hopter.properties 文件中提供以下基于 SQL 的配置项:
* <ul>
* <li>hopter.plugin.security.jdbc.authc-query: 根据用户名获取密码</li>
* <li>hopter.plugin.security.jdbc.roles-query: 根据用户名获取角色名集合</li>
* <li>hopter.plugin.security.jdbc.permissions-query: 根据角色名获取权限名集合</li>
* </ul>
*
* @author Angus
* @date 2018/12/8
*/
public interface HopterSecurity {
/**
* 根据用户名获取密码
*
* @param username 用户名
* @return 密码
*/
String getPassword(String username);
/**
* 根据用户名获取角色名集合
*
* @param username 角色名
* @return 角色名集合
*/
Set<String> getRoleNameSet(String username);
/**
* 根据角色名获取权限名集合
*
* @param roleName 角色名
* @return 权限名集合
*/
Set<String> getPermissionNameSet(String roleName);
}
| 19.886364 | 75 | 0.617143 |
99fc4eaace856efceb27a64708de5260c82eede5 | 1,282 | package com.irvil.textclassifier;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Config {
private static Config instance;
private final Properties properties = new Properties();
private Config() {
// read config file
try (InputStream inputStream = new FileInputStream(new File("./config/config.ini"))) {
properties.load(inputStream);
} catch (IOException ignored) {
}
}
static Config getInstance() {
// create only one object - Singleton pattern
if (instance == null) {
instance = new Config();
}
return instance;
}
boolean isLoaded() {
return properties.size() > 0;
}
public String getDbPath() {
return getProperty("db_path");
}
public String getDaoType() {
return getProperty("dao_type");
}
public String getDBMSType() {
return getProperty("dbms_type");
}
public String getSQLiteDbFileName() {
return getProperty("sqlite_db_filename");
}
public String getNGramStrategy() {
return getProperty("ngram_strategy");
}
private String getProperty(String property) {
return properties.getProperty(property) != null ? properties.getProperty(property) : "";
}
} | 22.103448 | 92 | 0.687988 |
b6329fefa60922034b5046490904b14dbd294497 | 3,253 | package de.fuberlin.wiwiss.d2rq.expr;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import de.fuberlin.wiwiss.d2rq.algebra.AliasMap;
import de.fuberlin.wiwiss.d2rq.algebra.Attribute;
import de.fuberlin.wiwiss.d2rq.algebra.ColumnRenamer;
import de.fuberlin.wiwiss.d2rq.sql.ConnectedDB;
public class Disjunction extends Expression {
public static Expression create(Collection<Expression> expressions) {
Set<Expression> elements = new HashSet<Expression>(expressions.size());
for (Expression expression: expressions) {
if (expression.isTrue()) {
return Expression.TRUE;
}
if (expression.isFalse()) {
continue;
}
if (expression instanceof Disjunction) {
elements.addAll(((Disjunction) expression).expressions);
} else {
elements.add(expression);
}
}
if (elements.isEmpty()) {
return Expression.FALSE;
}
if (elements.size() == 1) {
return (Expression) elements.iterator().next();
}
return new Disjunction(elements);
}
private Set<Expression> expressions;
private Set<Attribute> attributes = new HashSet<Attribute>();
private Disjunction(Set<Expression> expressions) {
this.expressions = expressions;
for (Expression expression: expressions) {
this.attributes.addAll(expression.attributes());
}
}
public boolean isTrue() {
return false;
}
public boolean isFalse() {
return false;
}
public Set<Attribute> attributes() {
return this.attributes;
}
public Expression renameAttributes(ColumnRenamer columnRenamer) {
Set<Expression> renamedExpressions = new HashSet<Expression>();
for (Expression expression: expressions) {
renamedExpressions.add(expression.renameAttributes(columnRenamer));
}
return Disjunction.create(renamedExpressions);
}
public String toSQL(ConnectedDB database, AliasMap aliases) {
List<String> fragments = new ArrayList<String>(expressions.size());
for (Expression expression: expressions) {
fragments.add(expression.toSQL(database, aliases));
}
Collections.sort(fragments);
StringBuffer result = new StringBuffer("(");
Iterator<String> it = fragments.iterator();
while (it.hasNext()) {
String fragment = it.next();
result.append(fragment);
if (it.hasNext()) {
result.append(" OR ");
}
}
result.append(")");
return result.toString();
}
public String toString() {
List<String> fragments = new ArrayList<String>(expressions.size());
for (Expression expression: expressions) {
fragments.add(expression.toString());
}
Collections.sort(fragments);
StringBuffer result = new StringBuffer("Disjunction(");
Iterator<String> it = fragments.iterator();
while (it.hasNext()) {
String fragment = it.next();
result.append(fragment);
if (it.hasNext()) {
result.append(", ");
}
}
result.append(")");
return result.toString();
}
public boolean equals(Object other) {
if (!(other instanceof Disjunction)) {
return false;
}
Disjunction otherConjunction = (Disjunction) other;
return this.expressions.equals(otherConjunction.expressions);
}
public int hashCode() {
return this.expressions.hashCode();
}
} | 26.884298 | 73 | 0.718106 |
424fa719b2c6e3f90425c24d551309a023d540ef | 277 | package ru.fizteh.fivt.students.LebedevAleksey.Shell01;
public class ParserException extends Exception {
public ParserException(String message) {
super(message);
}
public ParserException(String message, Throwable ex) {
super(message, ex);
}
}
| 23.083333 | 58 | 0.703971 |
0344bc23e9251a62617238a98cc38c0b6962bb75 | 167 | package top.crossoverjie.cicada.server.action.req;
import lombok.Data;
/**
* @author crossoverJie
*/
@Data
public class WorkReq {
private Integer timeStamp;
}
| 13.916667 | 50 | 0.730539 |
c1b8f832aae14e60271dc376f8501baff23f0c99 | 77 | package app.event.channel;
public class ManagerChannel extends AChannel {
}
| 15.4 | 46 | 0.805195 |
c488665d22de517139009d128d16a9e22eef4408 | 417 | package com.github.badpop.jcoinbase.service.account.dto;
import com.github.badpop.jcoinbase.model.account.Rewards;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class RewardsDto {
private final String apy;
private final String formattedApy;
private final String label;
public Rewards toRewards() {
return Rewards.builder().apy(apy).formattedApy(formattedApy).label(label).build();
}
}
| 26.0625 | 86 | 0.784173 |
e80731ff3881bca6f0fbec18a8b630b11d56e214 | 1,406 | package com.example.ShadowSocksShare.service;
import com.example.ShadowSocksShare.BaseTest;
import com.example.ShadowSocksShare.dao.ShadowSocksRepository;
import com.example.ShadowSocksShare.entity.ShadowSocksDetailsEntity;
import com.example.ShadowSocksShare.entity.ShadowSocksEntity;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.web.servlet.MockMvc;
import java.util.Date;
import java.util.HashSet;
@Slf4j
public class ShadowSocksCrawlerServiceTest extends BaseTest {
@Autowired
private MockMvc mvc;
@Autowired
private ShadowSocksCrawlerService iShadowCrawlerServiceImpl;
@Autowired
private ShadowSocksRepository shadowSocksRepository;
@Test
public void getShadowSocks() {
log.debug("{}", iShadowCrawlerServiceImpl.getShadowSocks().getLink(false));
}
public void aa() {
ShadowSocksEntity socksEntity = new ShadowSocksEntity("targetURL", "title", true, new Date());
socksEntity.setShadowSocksSet(new HashSet<>());
ShadowSocksDetailsEntity entity = new ShadowSocksDetailsEntity("216.189.158.147", 5307, "mm", "chacha20", "auth_aes128_sha1", "tls1.2_ticket_auth");
entity.setValid(true);
entity.setRemarks("本账号来自:doub.io/sszhfx/镜像域名:doub.bid/sszhfx/");
entity.setGroup("");
socksEntity.getShadowSocksSet().add(entity);
shadowSocksRepository.save(socksEntity);
}
} | 33.47619 | 150 | 0.802987 |
2617a5286e5c16a31f8ec448fcabf666d377c614 | 2,605 | /**
* Copyright (C) 2015 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.fabric8.servicecatalog.client.internal;
import io.fabric8.kubernetes.client.Config;
import io.fabric8.kubernetes.client.dsl.base.BaseOperation;
import io.fabric8.kubernetes.client.dsl.base.HasMetadataOperation;
import io.fabric8.kubernetes.client.dsl.base.OperationContext;
import io.fabric8.servicecatalog.api.model.*;
import io.fabric8.servicecatalog.api.model.DoneableServiceInstance;
import okhttp3.OkHttpClient;
public class ServiceInstanceOperationsImpl extends HasMetadataOperation<ServiceInstance, ServiceInstanceList, DoneableServiceInstance, ServiceInstanceResource> implements ServiceInstanceResource {
public ServiceInstanceOperationsImpl(OkHttpClient client, Config config) {
this(new OperationContext().withOkhttpClient(client).withConfig(config));
}
public ServiceInstanceOperationsImpl(OperationContext ctx) {
super(ctx.withApiGroupName("servicecatalog.k8s.io").withApiGroupVersion("v1beta1").withPlural("serviceinstances"));
this.type=ServiceInstance.class;
this.listType=ServiceInstanceList.class;
this.doneableType= DoneableServiceInstance.class;
}
@Override
public BaseOperation<ServiceInstance, ServiceInstanceList, DoneableServiceInstance, ServiceInstanceResource> newInstance(OperationContext context) {
return new ServiceInstanceOperationsImpl(context);
}
@Override
public boolean isResourceNamespaced() {
return true;
}
@Override
public ServiceBinding bind(String secretName) {
ServiceInstance item = get();
return new ServiceBindingOperationsImpl(context.withItem(null))
.createNew()
.withNewMetadata()
.withName(item.getMetadata().getName())
.endMetadata()
.withNewSpec()
.withSecretName(secretName)
.withNewInstanceRef(item.getMetadata().getName())
.endSpec()
.done();
}
}
| 40.703125 | 196 | 0.722457 |
23126c32a7c7e5e152836136bef2ab05770b1136 | 4,885 | package textgen;
import java.util.AbstractList;
/** A class that implements a doubly linked list
*
* @author UC San Diego Intermediate Programming MOOC team
*
* @param <E> The type of the elements stored in the list
*/
public class MyLinkedList<E> extends AbstractList<E> {
private static final String INDEX_OUT_OF_BOUNDS_EXCEPTION_INFO = "Size of MyLinkedList: %d Index: %d";
LLNode<E> head;
LLNode<E> tail;
int size;
/** Create a new empty LinkedList */
public MyLinkedList() {
}
/**
* Appends an element to the end of the list
* @param element The element to add
*/
public boolean add(E element ) {
if (element == null) {
throw new NullPointerException("You aren't able to add null to MyLinkedList!");
}
LLNode<E> newNode = new LLNode<>(element);
if (head == null) {
head = newNode;
size++;
return true;
}
if (tail == null) {
tail = newNode;
head.setNext(tail);
tail.setPrev(head);
size++;
return true;
}
tail.setNext(newNode);
newNode.setPrev(tail);
tail = newNode;
size++;
return true;
}
/** Get the element at position index
* @throws IndexOutOfBoundsException if the index is out of bounds. */
public E get(int index) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException(String.format(INDEX_OUT_OF_BOUNDS_EXCEPTION_INFO, size, index));
}
int counter = 0;
LLNode<E> temp = head;
while (temp != null) {
if (counter == index) {
return temp.getData();
} else {
temp = temp.getNext();
counter++;
}
}
return null;
}
/**
* Add an element to the list at the specified index
* @param index The index where the element should be added
* @param element The element to add
* @throws IndexOutOfBoundsException
*/
public void add(int index, E element) {
if (index > size || index < 0) {
throw new IndexOutOfBoundsException(String.format(INDEX_OUT_OF_BOUNDS_EXCEPTION_INFO, size, index));
}
if (element == null) {
throw new NullPointerException("You aren't able to add null to MyLinkedList!");
}
if (index == size) {
add(element);
return;
}
if (index == 0) {
LLNode<E> newNode = new LLNode<>(element);
newNode.setNext(head);
head.setPrev(newNode);
head = newNode;
size++;
return;
}
int counter = 0;
LLNode<E> temp = head;
while (temp != null) {
if (counter == index) {
LLNode<E> newNode = new LLNode<E>(element);
newNode.setNext(temp);
newNode.setPrev(temp.getPrev());
if (temp.getPrev() != null) {
temp.getPrev().setNext(newNode);
}
temp.setPrev(newNode);
size++;
break;
} else {
temp = temp.getNext();
counter++;
}
}
}
/** Return the size of the list */
public int size()
{
return size;
}
/** Remove a node at the specified index and return its data element.
* @param index The index of the element to remove
* @return The data element removed
* @throws IndexOutOfBoundsException If index is outside the bounds of the list
*
*/
public E remove(int index) {
if (index < 0 || index >= size || size == 0) {
throw new IndexOutOfBoundsException(String.format(INDEX_OUT_OF_BOUNDS_EXCEPTION_INFO, size, index));
}
LLNode<E> temp = head;
int counter = 0;
while (temp != null) {
if (counter == index) {
if (temp.getPrev() != null) {
temp.getPrev().setNext(temp.getNext());
}
if (temp.getNext() != null) {
temp.getNext().setPrev(temp.getPrev());
}
if (index == 0) {
head = temp.getNext();
}
size--;
return temp.getData();
}
temp = temp.getNext();
counter++;
}
return null;
}
/**
* Set an index position in the list to a new element
* @param index The index of the element to change
* @param element The new element
* @return The element that was replaced
* @throws IndexOutOfBoundsException if the index is out of bounds.
*/
public E set(int index, E element) {
if (index < 0 || index >= size || size == 0) {
throw new IndexOutOfBoundsException(String.format(INDEX_OUT_OF_BOUNDS_EXCEPTION_INFO, size, index));
}
if (element == null) {
throw new NullPointerException("You aren't able to set null");
}
LLNode<E> temp = head;
int counter = 0;
while (temp != null) {
if (counter == index) {
E data = temp.getData();
temp.setData(element);
return data;
}
temp = temp.getNext();
counter++;
}
return null;
}
}
class LLNode<E> {
LLNode<E> prev;
LLNode<E> next;
E data;
public LLNode(E e) {
this.data = e;
this.prev = null;
this.next = null;
}
public LLNode<E> getPrev() {
return prev;
}
public void setPrev(LLNode<E> prev) {
this.prev = prev;
}
public LLNode<E> getNext() {
return next;
}
public void setNext(LLNode<E> next) {
this.next = next;
}
public E getData() {
return data;
}
public void setData(E data) {
this.data = data;
}
}
| 22.204545 | 103 | 0.63521 |
cc1f0849382fab0631863d7fb930606907c20ba0 | 7,385 | package com.bitdubai.fermat_pip_addon.layer.platform_service.error_manager.developer.bitdubai.version_1;
import com.bitdubai.fermat_api.FermatException;
import com.bitdubai.fermat_api.layer.all_definition.common.system.abstract_classes.AbstractAddon;
import com.bitdubai.fermat_api.layer.all_definition.common.system.utils.AddonVersionReference;
import com.bitdubai.fermat_api.layer.all_definition.common.system.utils.PluginVersionReference;
import com.bitdubai.fermat_api.layer.all_definition.enums.Addons;
import com.bitdubai.fermat_api.layer.all_definition.enums.PlatformComponents;
import com.bitdubai.fermat_api.layer.all_definition.enums.Plugins;
import com.bitdubai.fermat_api.layer.all_definition.enums.UISource;
import com.bitdubai.fermat_api.layer.all_definition.events.interfaces.FermatEvent;
import com.bitdubai.fermat_api.layer.all_definition.navigation_structure.enums.Wallets;
import com.bitdubai.fermat_api.layer.all_definition.util.Version;
import com.bitdubai.fermat_api.layer.dmp_engine.sub_app_runtime.enums.SubApps;
import com.bitdubai.fermat_pip_addon.layer.platform_service.error_manager.developer.bitdubai.version_1.functional.ErrorReport;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.ErrorManager;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedAddonsExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedPlatformExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedPluginExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedSubAppExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedUIExceptionSeverity;
import com.bitdubai.fermat_pip_api.layer.platform_service.error_manager.UnexpectedWalletExceptionSeverity;
/**
* Throw this addon you can report an unexpected error in the platform.
*
* For now, the only functionality of the addon is report in log all problems, but in the near future, the idea is to save all the errors and send to a bitDubai server to be properly controlled.
*
* Created by lnacosta (laion.cj91@gmail.com) on 26/10/2015.
*/
public final class ErrorManagerPlatformServiceAddonRoot extends AbstractAddon implements ErrorManager {
/**
* Constructor without parameters.
*/
public ErrorManagerPlatformServiceAddonRoot() {
super(new AddonVersionReference(new Version()));
}
/**
* ErrorManager Interface implementation.
*/
@Override
public final void reportUnexpectedPlatformException(final PlatformComponents exceptionSource ,
final UnexpectedPlatformExceptionSeverity unexpectedPlatformExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.name(), unexpectedPlatformExceptionSeverity.name(), exception);
}
@Override
public final void reportUnexpectedPluginException(final Plugins exceptionSource ,
final UnexpectedPluginExceptionSeverity unexpectedPluginExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedPluginExceptionSeverity.toString(), exception);
}
@Override
public final void reportUnexpectedPluginException(final PluginVersionReference exceptionSource ,
final UnexpectedPluginExceptionSeverity unexpectedPluginExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedPluginExceptionSeverity.toString(), exception);
}
@Override
public final void reportUnexpectedWalletException(final Wallets exceptionSource ,
final UnexpectedWalletExceptionSeverity unexpectedWalletExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedWalletExceptionSeverity.toString(),exception);
}
@Override
public final void reportUnexpectedAddonsException(final Addons exceptionSource ,
final UnexpectedAddonsExceptionSeverity unexpectedAddonsExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedAddonsExceptionSeverity.toString(), exception);
}
@Override
public final void reportUnexpectedAddonsException(final AddonVersionReference exceptionSource ,
final UnexpectedPluginExceptionSeverity unexpectedPluginExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedPluginExceptionSeverity.toString(), exception);
}
@Override
public final void reportUnexpectedSubAppException(final SubApps exceptionSource ,
final UnexpectedSubAppExceptionSeverity unexpectedSubAppExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedSubAppExceptionSeverity.toString(), exception);
}
@Override
public final void reportUnexpectedUIException(final UISource exceptionSource ,
final UnexpectedUIExceptionSeverity unexpectedAddonsExceptionSeverity,
final Exception exception ) {
processException(exceptionSource.toString(), unexpectedAddonsExceptionSeverity.toString(), exception);
}
@Override
public final void reportUnexpectedEventException(final FermatEvent exceptionSource,
final Exception exception ) {
processException(exceptionSource.toString(), "Unknow", exception);
}
private void processException(final String source, final String severity, final Exception exception){
printErrorReport(source, severity, FermatException.wrapException(exception));
}
private void printErrorReport(final String source, final String severity, final FermatException exception){
System.err.println(new ErrorReport(source, severity, exception).generateReport());
}
}
| 60.04065 | 194 | 0.649289 |
67c8a546d11180d46714d8adce0f204cf22df4e2 | 2,422 | package ericminio.regexp;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class CaptureTest {
@Test
public void simpleMatch() {
Pattern pattern = Pattern.compile("hello");
Matcher matcher = pattern.matcher("hello world");
assertThat(matcher.find(), equalTo(true));
assertThat(matcher.group(0), equalTo("hello"));
}
@Test
public void capturingOneWord() {
Pattern pattern = Pattern.compile("hello (.*)");
Matcher matcher = pattern.matcher("hello world");
assertThat(matcher.find(), equalTo(true));
assertThat(matcher.group(0), equalTo("hello world"));
assertThat(matcher.group(1), equalTo("world"));
}
@Test
public void capturingSeveralWords() {
Pattern pattern = Pattern.compile("hello (.*)");
Matcher matcher = pattern.matcher("hello my friend");
assertThat(matcher.find(), equalTo(true));
assertThat(matcher.group(0), equalTo("hello my friend"));
assertThat(matcher.group(1), equalTo("my friend"));
}
@Test
public void capturingListOfSeveralWords() {
Pattern pattern = Pattern.compile("hello (.*)");
Matcher matcher = pattern.matcher("hello Bob, Jack, and Oliver");
assertThat(matcher.find(), equalTo(true));
assertThat(matcher.group(0), equalTo("hello Bob, Jack, and Oliver"));
assertThat(matcher.group(1), equalTo("Bob, Jack, and Oliver"));
}
@Test
public void capturingListOfSeveralWordsFromPartialMatch() {
Pattern pattern = Pattern.compile("hello (.*)");
Matcher matcher = pattern.matcher("a big hello Bob, Jack, and Oliver");
assertThat(matcher.find(), equalTo(true));
assertThat(matcher.group(0), equalTo("hello Bob, Jack, and Oliver"));
assertThat(matcher.group(1), equalTo("Bob, Jack, and Oliver"));
}
@Test
public void exploring() {
Pattern pattern = Pattern.compile("the feedback is (.*)");
Matcher matcher = pattern.matcher(" Then the feedback is 3 black, 0 white");
assertThat(matcher.find(), equalTo(true));
assertThat(matcher.group(0), equalTo("the feedback is 3 black, 0 white"));
assertThat(matcher.group(1), equalTo("3 black, 0 white"));
}
}
| 33.638889 | 87 | 0.643683 |
5c6227a84570829c00e913b32287f3492680970e | 1,937 | /*
* (C) Copyright 2021 Radix DLT Ltd
*
* Radix DLT Ltd licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the
* License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*
*/
package com.radixdlt.atom.actions;
import com.radixdlt.atom.MutableTokenDefinition;
import com.radixdlt.atom.TxAction;
import com.radixdlt.crypto.ECPublicKey;
public final class CreateMutableToken implements TxAction {
private final ECPublicKey key;
private final String symbol;
private final String name;
private final String description;
private final String iconUrl;
private final String tokenUrl;
public CreateMutableToken(MutableTokenDefinition def) {
this(def.getKey(), def.getSymbol(), def.getName(), def.getDescription(), def.getIconUrl(), def.getTokenUrl());
}
public CreateMutableToken(
ECPublicKey key,
String symbol,
String name,
String description,
String iconUrl,
String tokenUrl
) {
this.key = key;
this.symbol = symbol.toLowerCase();
this.name = name;
this.description = description;
this.iconUrl = iconUrl;
this.tokenUrl = tokenUrl;
}
public ECPublicKey getKey() {
return key;
}
public String getSymbol() {
return symbol;
}
public String getName() {
return name == null ? "" : name;
}
public String getDescription() {
return description == null ? "" : description;
}
public String getIconUrl() {
return iconUrl == null ? "" : iconUrl;
}
public String getTokenUrl() {
return tokenUrl == null ? "" : tokenUrl;
}
}
| 25.155844 | 112 | 0.724832 |
545fc1e41f57af55a1a9103b4d0a3ca09e4fa1aa | 3,441 | package er.communication.mail;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.mail.MessagingException;
import com.webobjects.appserver.WOApplication;
import com.webobjects.appserver.WOComponent;
import com.webobjects.appserver.WOContext;
import com.webobjects.appserver.WORequest;
import com.webobjects.foundation.NSData;
import er.communication.foundation.ERMedia;
import er.communication.foundation.ERRecipient;
import er.extensions.appserver.ERXApplication;
import er.extensions.foundation.ERXProperties;
import er.javamail.ERMailDeliveryHTML;
/**
* Concrete implementation of a mail processor which sends HTML messages<p>
* It uses the sending configuration map to get the component name to use<br>
* <b>Note: </b> the component must implement an accessor data of type Map<String, Object>
*
* @author Philippe Rabier
*
*/
public class ERHTMLMailProcessor extends ERMailProcessor
{
/**
* The key used to get the component name in the sending configuration map
*/
public static final String COMPONENT_NAME = "component";
public void sendMail(ERRecipient recipient, ERMedia media, final String subject, final String textContent)
{
String componentName = (String) getSendingConfiguration().get(COMPONENT_NAME);
String realName = recipient.getFirstName() + " " + recipient.getLastName();
sendMailWithComponent(recipient.getIdentifier(media), realName, subject, textContent, recipient.getLanguage(), componentName);
}
private void sendMailWithComponent(String address, String realName, String subject, String textContent, String language, String component)
{
WOApplication app = WOApplication.application();
// build context
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("accept-language", java.util.Arrays.asList(language));
/* Tells the WORequest object to answer true when request.isUsingWebServer(). When isUsingWebServer() returns true,
the URL contains the host and port number.*/
headers.put("x-webobjects-adaptor-version", java.util.Arrays.asList("4.5"));
// Host for URL
String host = ERXProperties.stringForKeyWithDefault("er.communication.mail.host", app.host());
headers.put("host", java.util.Arrays.asList(host));
// Port number for URL
String port = ERXProperties.stringForKey("er.communication.mail.port");
if (port != null)
headers.put(WORequest.ServerPortHeaderX, java.util.Arrays.asList(port));
WORequest request = new WORequest("GET", app.adaptorPath() + "/" + app.name() + ".woa", "HTTP/1.1", headers, new NSData(), new HashMap());
WOContext ctx = new WOContext(request);
ctx.generateCompleteURLs();
// Init template
WOComponent page = ERXApplication.erxApplication().pageWithName(component, ctx);
page.takeValueForKey(getMergedData(), "data");
// create mail
ERMailDeliveryHTML message = new ERMailDeliveryHTML();
message.setComponent(page);
// TODO add text part with
// message.setAlternativeComponent(alternativeComponent);
// and with
// message.setHiddenPlainTextContent(content);
try
{
message.setSubject(subject);
if (realName != null)
message.setToAddress(address, realName);
else
message.setToAddress(address);
message.setFromAddress(fromEmail());
// send the mail assynchronously
message.sendMail();
} catch (MessagingException e)
{
log.error("method sendMail: failed sending mail.", e);
}
}
}
| 35.112245 | 140 | 0.754722 |
e4a78cdf07fdb1acf63f63fe2e6d614ff30b81c5 | 2,309 | package com.cloudentity.tools.vertx.http.builder;
import com.cloudentity.tools.vertx.tracing.TracingContext;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.http.HttpClientResponse;
import io.vertx.core.http.HttpMethod;
import io.vertx.core.streams.ReadStream;
public interface RequestCtxBuilder extends CallValuesBuilder<RequestCtxBuilder> {
RequestCtxBuilder method(HttpMethod m);
RequestCtxBuilder putHeader(String key, String value);
RequestCtxBuilder addHeader(String key, String value);
Future<HttpClientResponse> end();
Future<HttpClientResponse> end(Buffer b);
Future<HttpClientResponse> end(String b);
Future<HttpClientResponse> end(ReadStream<Buffer> s);
Future<HttpClientResponse> end(Handler<Buffer> bodyHandler);
Future<HttpClientResponse> end(Buffer b, Handler<Buffer> bodyHandler);
Future<HttpClientResponse> end(String b, Handler<Buffer> bodyHandler);
Future<HttpClientResponse> end(ReadStream<Buffer> s, Handler<Buffer> bodyHandler);
Future<SmartHttpResponse> endWithBody();
Future<SmartHttpResponse> endWithBody(Buffer b);
Future<SmartHttpResponse> endWithBody(String b);
Future<SmartHttpResponse> endWithBody(ReadStream<Buffer> s);
Future<HttpClientResponse> end(TracingContext tracingContext);
Future<HttpClientResponse> end(TracingContext tracingContext, Buffer b);
Future<HttpClientResponse> end(TracingContext tracingContext, String b);
Future<HttpClientResponse> end(TracingContext tracingContext, ReadStream<Buffer> s);
Future<HttpClientResponse> end(TracingContext tracingContext, Handler<Buffer> bodyHandler);
Future<HttpClientResponse> end(TracingContext tracingContext, Buffer b, Handler<Buffer> bodyHandler);
Future<HttpClientResponse> end(TracingContext tracingContext, String b, Handler<Buffer> bodyHandler);
Future<HttpClientResponse> end(TracingContext tracingContext, ReadStream<Buffer> s, Handler<Buffer> bodyHandler);
Future<SmartHttpResponse> endWithBody(TracingContext tracingContext);
Future<SmartHttpResponse> endWithBody(TracingContext tracingContext, Buffer b);
Future<SmartHttpResponse> endWithBody(TracingContext tracingContext, String b);
Future<SmartHttpResponse> endWithBody(TracingContext tracingContext, ReadStream<Buffer> s);
}
| 50.195652 | 115 | 0.818536 |
898656ba0949b7a129ca1a997efc579b46795f61 | 4,731 | package org.firstinspires.ftc.teamcode.Lib.ResQLib;
public class RobotConfigMapping {
//*********************************************************************************************
// ENUMERATED TYPES
//
// user defined types
//
//*********************************************************************************************
//*********************************************************************************************
// PRIVATE DATA FIELDS
//
// can be accessed only by this class, or by using the public
// getter and setter methods
//*********************************************************************************************
// motor congtrollers:
// AH00qK3C - bottom of robot
// AL00XPUH - top of robot
// servo controllers:
// AL00VV9L - bottom of robot\
// AL004A89 - top of robot
//Drive Train
private static String leftDriveMotorName = "leftDriveMotor"; //AH00qK3C port 1 (bottom)
private static String rightDriveMotorName = "rightDriveMotor"; //AH00qK3C port 2 (bottom)
//Sweeper
private static String sweeperMotorName = "sweeperMotor"; //AL00XPUH port 2
//Zip Line
private static String leftZipLineServoName = "leftZipLineServo"; //AL00VV9L port 3
private static String rightZipLineServoName = "rightZipLineServo"; //AL00VV9L port 4
//Box Slider
private static String linearSlideServoName = "slideServo"; //AL004A89 port 1
private static String rampServoName = "rampServo"; //AL00VV9L port 1
private static String leftBoxLimitSwitchName = "leftBoxLimitSwitch";
private static String rightBoxLimitSwitchName = "rightBoxLimitSwitch";
//Tape Measure
private static String tapeMeasureMotorName = "tapeMeasureMotor"; //AL00XPUH port 1
private static String tapeMeasureLimitSwitchName = "tapeMeasureLimitSwitch";
private static String tapeMeasureAimingServoName = "tapeMeasureAimingServo"; //AL00VV9L port 5
//Climber Dump
private static String climberDumpServoName = "climberDumpServo"; //AL004A89 port 2
//Bar Grabber
private static String barGrabberServoName = "barGrabberServo"; //AL00VV9L port 2
//*********************************************************************************************
// GETTER and SETTER Methods
//
// allow access to private data fields for example setMotorPower,
// getPositionInTermsOfAttachment
//*********************************************************************************************
public static String getLeftDriveMotorName() {return leftDriveMotorName;}
public static String getRightDriveMotorName() {
return rightDriveMotorName;
}
public static String getSweeperMotorName() {
return sweeperMotorName;
}
public static String getLeftZipLineServoName() {
return leftZipLineServoName;
}
public static String getRightZipLineServoName() {
return rightZipLineServoName;
}
public static String getLinearSlideServoName() {
return linearSlideServoName;
}
public static String getRampServoName() {return rampServoName;}
public static String getLeftBoxLimitSwitchName() {return leftBoxLimitSwitchName; }
public static String getRightBoxLimitSwitchName() {return rightBoxLimitSwitchName;}
public static String getTapeMeasureMotorName() {return tapeMeasureMotorName;}
public static String getTapeMeasureLimitSwitchName() {return tapeMeasureLimitSwitchName;}
public static String getTapeMeasureAimingServoName() {return tapeMeasureAimingServoName;}
public static String getClimberDumpServoName() {return climberDumpServoName;}
public static String getBarGrabberServoName() {return barGrabberServoName;}
//*********************************************************************************************
// Constructors
//
// the function that builds the class when an object is created
// from it
//*********************************************************************************************
//*********************************************************************************************
// Helper Methods
//
// methods that aid or support the major functions in the class
//*********************************************************************************************
//*********************************************************************************************
// MAJOR METHODS
//
// public methods that give the class its functionality
//*********************************************************************************************
}
| 37.251969 | 99 | 0.534137 |
507b18ff019403918d4950f8304112eb77379747 | 2,583 | package ru.stqa.training.selenium.peges.admin;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import ru.stqa.training.selenium.objects.Good;
import ru.stqa.training.selenium.peges.BasePage;
public class AdminAddNewProductPage extends BasePage {
/** Tabs */
private static final By GENERAL_TAB = By.cssSelector("a[href='#tab-general']");
private static final By INFORMATION_TAB = By.cssSelector("a[href='#tab-information']");
private static final By PRICE_TAB = By.cssSelector("a[href='#tab-prices']");
/** Tab General */
private static final By ENABLED_RADIO_BTN = By.xpath("//label[text()=' Enabled']//input");
private static final By NAME_INPUT = By.cssSelector("input[name='name[en]']");
private static final By CODE_INPUT = By.cssSelector("input[name='code']");
private static final By PHOTO_INPUT = By.cssSelector("input[name='new_images[]']");
/** Tab Information */
private static final By MANUFACTURER_SELECT = By.cssSelector("select[name='manufacturer_id']");
private static final By DESCRIPTION_TEXTAREA = By.cssSelector("textarea[name*='description']");
/** Tab Price */
private static final By PURCHASE_PRICE_INPUT = By.cssSelector("input[name='purchase_price']");
private static final By REGULAR_PRICE_USD =By.cssSelector("input[name='prices[USD]']");
/** Button Bar At The Bottom */
private static final By SAVE_BTN = By.cssSelector("button[name='save']");
public AdminAddNewProductPage(WebDriver driver) {
super(driver);
shortWait.until(ExpectedConditions.visibilityOfElementLocated(GENERAL_TAB));
}
public void createNewProduct(Good product) {
clickByElement(GENERAL_TAB);
setProductEnable();
findAndFeelField(NAME_INPUT, product.getName());
findAndFeelField(CODE_INPUT, product.getCode());
attach(PHOTO_INPUT, product.getPhoto());
clickByElement(INFORMATION_TAB);
shortWait.until(ExpectedConditions.visibilityOfElementLocated(MANUFACTURER_SELECT));
findAndFeelField(DESCRIPTION_TEXTAREA, product.getDescription());
clickByElement(PRICE_TAB);
shortWait.until(ExpectedConditions.visibilityOfElementLocated(PURCHASE_PRICE_INPUT));
findAndFeelField(REGULAR_PRICE_USD, product.getRegularPrice());
clickByElement(SAVE_BTN);
}
private void setProductEnable() {
if (!getElement(ENABLED_RADIO_BTN).isSelected()){
clickByElement(ENABLED_RADIO_BTN);
}
}
}
| 44.534483 | 99 | 0.718931 |
e278c07dc509c515b36c2203a5490c41ef7d9405 | 2,037 | // Targeted by JavaCPP version 1.5.8-SNAPSHOT: DO NOT EDIT THIS FILE
package org.bytedeco.bullet.BulletCollision;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import org.bytedeco.bullet.LinearMath.*;
import static org.bytedeco.bullet.global.LinearMath.*;
import static org.bytedeco.bullet.global.BulletCollision.*;
// #ifdef BT_DEBUG_COLLISION_PAIRS
// #endif //BT_DEBUG_COLLISION_PAIRS
@NoOffset @Properties(inherit = org.bytedeco.bullet.presets.BulletCollision.class)
public class btHashedSimplePairCache extends Pointer {
static { Loader.load(); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public btHashedSimplePairCache(Pointer p) { super(p); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public btHashedSimplePairCache(long size) { super((Pointer)null); allocateArray(size); }
private native void allocateArray(long size);
@Override public btHashedSimplePairCache position(long position) {
return (btHashedSimplePairCache)super.position(position);
}
@Override public btHashedSimplePairCache getPointer(long i) {
return new btHashedSimplePairCache((Pointer)this).offsetAddress(i);
}
public btHashedSimplePairCache() { super((Pointer)null); allocate(); }
private native void allocate();
public native void removeAllPairs();
public native Pointer removeOverlappingPair(int indexA, int indexB);
// Add a pair and return the new pair. If the pair already exists,
// no new pair is created and the old one is returned.
public native btSimplePair addOverlappingPair(int indexA, int indexB);
public native btSimplePair getOverlappingPairArrayPtr();
public native @Cast("btSimplePairArray*") @ByRef BT_QUANTIZED_BVH_NODE_Array getOverlappingPairArray();
public native btSimplePair findPair(int indexA, int indexB);
public native int GetCount();
public native int getNumOverlappingPairs();
}
| 37.036364 | 104 | 0.766814 |
49f12cf8fa25b502b8561fc9b38d8ff0565ab57f | 1,660 | package com.ex.library.config;
import com.ex.library.dispatcher.DefaultResponseDispatcher;
import com.ex.library.dispatcher.IResponseDispatcher;
/**
* Author: Jerry
* Date: 2018/10/9
* Version v1.0
* Desc: WebSocket 使用配置
*/
@SuppressWarnings("all")
public class WebSocketSetting {
private static String connectUrl;
private static IResponseDispatcher responseProcessDelivery;
private static boolean reconnectWithNetworkChanged;
/**
* 获取 WebSocket 链接地址
*/
public static String getConnectUrl() {
return connectUrl;
}
/**
* 设置 WebSocket 链接地址,第一次设置有效,
* 必须在启动 WebSocket 线程之前设置
*/
public static void setConnectUrl(String connectUrl) {
WebSocketSetting.connectUrl = connectUrl;
}
/**
* 获取当前已设置的消息分发器
*/
public static IResponseDispatcher getResponseProcessDelivery() {
if (responseProcessDelivery == null) {
responseProcessDelivery = new DefaultResponseDispatcher();
}
return responseProcessDelivery;
}
/**
* 设置消息分发器
*/
public static void setResponseProcessDelivery(IResponseDispatcher responseProcessDelivery) {
WebSocketSetting.responseProcessDelivery = responseProcessDelivery;
}
public static boolean isReconnectWithNetworkChanged() {
return reconnectWithNetworkChanged;
}
/**
* 设置网络连接变化后是否自动重连。
* 如果设置 true 则需要注册广播:
* 并添加 ACCESS_NETWORK_STATE 权限。
*/
public static void setReconnectWithNetworkChanged(boolean reconnectWithNetworkChanged) {
WebSocketSetting.reconnectWithNetworkChanged = reconnectWithNetworkChanged;
}
}
| 25.538462 | 96 | 0.695181 |
63dc72af9b9a5d2f69f194cf04e4f2055b27a0ce | 1,422 | /*
* Iliiazbek Akhmedov
* Copyright (c) 2016.
*/
package codepath.nytarticlesapp.utils;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.SearchView;
import org.parceler.Parcels;
import codepath.nytarticlesapp.network.SearchRequest;
public class NewsSearchListener implements SearchView.OnQueryTextListener {
private final Activity activity;
private final SearchView searchView;
public NewsSearchListener(Activity activity, SearchView searchView) {
this.activity = activity;
this.searchView = searchView;
}
@Override
public boolean onQueryTextSubmit(String query) {
// workaround to avoid issues with some emulators and keyboard devices firing twice if a keyboard enter is used
// see https://code.google.com/p/android/issues/detail?id=24599
searchView.clearFocus();
SearchRequest request = new SearchRequest();
request.setQ(query);
request.setPage(1);
Intent searchRequestIntent = new Intent(Constants.SEARCH_REQUEST_CREATED);
searchRequestIntent.putExtra("data", Parcels.wrap(request));
LocalBroadcastManager.getInstance(activity).sendBroadcast(searchRequestIntent);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
}
| 29.020408 | 119 | 0.731364 |
9472b7fa2aebc590b72e2f5e04d44c434bae3be1 | 7,222 | /*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package a_vcard.android.text;
/**
* This is the interface for text that has markup objects attached to
* ranges of it. Not all text classes have mutable markup or text;
* see {@link Spannable} for mutable markup and {@link Editable} for
* mutable text.
*/
public interface Spanned
extends CharSequence
{
/**
* Bitmask of bits that are relevent for controlling point/mark behavior
* of spans.
*/
public static final int SPAN_POINT_MARK_MASK = 0x33;
/**
* 0-length spans with type SPAN_MARK_MARK behave like text marks:
* they remain at their original offset when text is inserted
* at that offset.
*/
public static final int SPAN_MARK_MARK = 0x11;
/**
* SPAN_MARK_POINT is a synonym for {@link #SPAN_INCLUSIVE_INCLUSIVE}.
*/
public static final int SPAN_MARK_POINT = 0x12;
/**
* SPAN_POINT_MARK is a synonym for {@link #SPAN_EXCLUSIVE_EXCLUSIVE}.
*/
public static final int SPAN_POINT_MARK = 0x21;
/**
* 0-length spans with type SPAN_POINT_POINT behave like cursors:
* they are pushed forward by the length of the insertion when text
* is inserted at their offset.
*/
public static final int SPAN_POINT_POINT = 0x22;
/**
* SPAN_PARAGRAPH behaves like SPAN_INCLUSIVE_EXCLUSIVE
* (SPAN_MARK_MARK), except that if either end of the span is
* at the end of the buffer, that end behaves like _POINT
* instead (so SPAN_INCLUSIVE_INCLUSIVE if it starts in the
* middle and ends at the end, or SPAN_EXCLUSIVE_INCLUSIVE
* if it both starts and ends at the end).
* <p>
* Its endpoints must be the start or end of the buffer or
* immediately after a \n character, and if the \n
* that anchors it is deleted, the endpoint is pulled to the
* next \n that follows in the buffer (or to the end of
* the buffer).
*/
public static final int SPAN_PARAGRAPH = 0x33;
/**
* Non-0-length spans of type SPAN_INCLUSIVE_EXCLUSIVE expand
* to include text inserted at their starting point but not at their
* ending point. When 0-length, they behave like marks.
*/
public static final int SPAN_INCLUSIVE_EXCLUSIVE = SPAN_MARK_MARK;
/**
* Spans of type SPAN_INCLUSIVE_INCLUSIVE expand
* to include text inserted at either their starting or ending point.
*/
public static final int SPAN_INCLUSIVE_INCLUSIVE = SPAN_MARK_POINT;
/**
* Spans of type SPAN_EXCLUSIVE_EXCLUSIVE do not expand
* to include text inserted at either their starting or ending point.
* They can never have a length of 0 and are automatically removed
* from the buffer if all the text they cover is removed.
*/
public static final int SPAN_EXCLUSIVE_EXCLUSIVE = SPAN_POINT_MARK;
/**
* Non-0-length spans of type SPAN_INCLUSIVE_EXCLUSIVE expand
* to include text inserted at their ending point but not at their
* starting point. When 0-length, they behave like points.
*/
public static final int SPAN_EXCLUSIVE_INCLUSIVE = SPAN_POINT_POINT;
/**
* This flag is set on spans that are being used to apply temporary
* styling information on the composing text of an input method, so that
* they can be found and removed when the composing text is being
* replaced.
*/
public static final int SPAN_COMPOSING = 0x100;
/**
* This flag will be set for intermediate span changes, meaning there
* is guaranteed to be another change following it. Typically it is
* used for {@link Selection} which automatically uses this with the first
* offset it sets when updating the selection.
*/
public static final int SPAN_INTERMEDIATE = 0x200;
/**
* The bits numbered SPAN_USER_SHIFT and above are available
* for callers to use to store scalar data associated with their
* span object.
*/
public static final int SPAN_USER_SHIFT = 24;
/**
* The bits specified by the SPAN_USER bitfield are available
* for callers to use to store scalar data associated with their
* span object.
*/
public static final int SPAN_USER = 0xFFFFFFFF << SPAN_USER_SHIFT;
/**
* The bits numbered just above SPAN_PRIORITY_SHIFT determine the order
* of change notifications -- higher numbers go first. You probably
* don't need to set this; it is used so that when text changes, the
* text layout gets the chance to update itself before any other
* callbacks can inquire about the layout of the text.
*/
public static final int SPAN_PRIORITY_SHIFT = 16;
/**
* The bits specified by the SPAN_PRIORITY bitmap determine the order
* of change notifications -- higher numbers go first. You probably
* don't need to set this; it is used so that when text changes, the
* text layout gets the chance to update itself before any other
* callbacks can inquire about the layout of the text.
*/
public static final int SPAN_PRIORITY = 0xFF << SPAN_PRIORITY_SHIFT;
/**
* Return an array of the markup objects attached to the specified
* slice of this CharSequence and whose type is the specified type
* or a subclass of it. Specify Object.class for the type if you
* want all the objects regardless of type.
*/
public <T> T[] getSpans(int start, int end, Class<T> type);
/**
* Return the beginning of the range of text to which the specified
* markup object is attached, or -1 if the object is not attached.
*/
public int getSpanStart(Object tag);
/**
* Return the end of the range of text to which the specified
* markup object is attached, or -1 if the object is not attached.
*/
public int getSpanEnd(Object tag);
/**
* Return the flags that were specified when {@link Spannable#setSpan} was
* used to attach the specified markup object, or 0 if the specified
* object has not been attached.
*/
public int getSpanFlags(Object tag);
/**
* Return the first offset greater than or equal to <code>start</code>
* where a markup object of class <code>type</code> begins or ends,
* or <code>limit</code> if there are no starts or ends greater than or
* equal to <code>start</code> but less than <code>limit</code>. Specify
* <code>null</code> or Object.class for the type if you want every
* transition regardless of type.
*/
@SuppressWarnings("unchecked")
public int nextSpanTransition(int start, int limit, Class type);
}
| 39.25 | 78 | 0.689144 |
eff94aacb16f8ed816b6a0dec198820dd0cf8664 | 1,114 | package livelance.app.support;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo;
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn;
import org.springframework.hateoas.mvc.ResourceAssemblerSupport;
import org.springframework.stereotype.Component;
import livelance.app.model.Rating;
import livelance.app.web.controller.ApiRatingController;
import livelance.app.web.resource.RatingResource;
@Component
public class RatingResourceAsm extends ResourceAssemblerSupport<Rating, RatingResource>{
public RatingResourceAsm() {
super(ApiRatingController.class, RatingResource.class);
}
public RatingResource toResource(Rating rating) {
RatingResource res = new RatingResource();
res.setComment(rating.getComment());
res.setCustomerName(rating.getCustomerName());
res.setRating(rating.getRating());
res.setTimeOfRating(rating.getTimeOfRating());
res.setRid(rating.getId());
res.add(linkTo(methodOn(ApiRatingController.class).get(
rating.getId(), rating.getDeal().getId())).withSelfRel());
return res;
}
}
| 34.8125 | 89 | 0.780969 |
628e2adf0be93f8d1f55e1b56cee7294b47fae1b | 181 | package org.liquidplayer.hemroid;
public class PNG extends Hemroid {
public PNG(android.content.Context context) {
super(context);
loadLibrary("png16");
}
} | 22.625 | 49 | 0.674033 |
725ec30abd341a6bc50f270889b385eec684a7ba | 1,573 | package Parser.Commands.Turtle_Command;
import GraphicsBackend.Turtle;
import Parser.BackendController;
import Parser.Commands.Command;
import Parser.Commands.TurtleCommand;
import Parser.ExecutionException;
import Parser.SLogoException;
import javafx.scene.paint.Color;
/**
* @author kunalupadya
* @author Louis Lee
* @author Dhanush
*/
public class SetPenColorCommand extends TurtleCommand {
public SetPenColorCommand(){
setNumParameters(1);
isOutputCommand = false;
}
@Override
protected void performAction(BackendController backendController, Turtle turtle) throws SLogoException {
int index = (int) getChildren().get(0).getReturnValue();
if (index < 1){
throw new ExecutionException("Palette contains indices starting from 1");
}
if (index > findPaletteLength(backendController)){
throw new ExecutionException("Color index does not exist in Palette");
}
setReturnValue(getChildren().get(0).getReturnValue());
turtle.setPenColor(backendController.getColor((int) getReturnValue() - 1));
}
private int findPaletteLength(BackendController backendController){
int length = 0;
Color [] palette = backendController.getColorPalette();
for (Color color: palette){
if (color != null){
length++;
}
else{
break;
}
}
return length;
}
@Override
public Command copy() {
return new SetPenColorCommand();
}
}
| 27.596491 | 108 | 0.65035 |
6d04d6b2b32d7b402c7ff24c8213ffe028200d09 | 3,634 | package com.xstudio.models.sys;
public class SysRoleAuth {
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column sys_role_auth.id
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
private Integer id;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column sys_role_auth.roleid
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
private Integer roleid;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column sys_role_auth.authname
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
private String authname;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database column sys_role_auth.desc
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
private String desc;
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column sys_role_auth.id
*
* @return the value of sys_role_auth.id
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public Integer getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column sys_role_auth.id
*
* @param id the value for sys_role_auth.id
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public void setId(Integer id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column sys_role_auth.roleid
*
* @return the value of sys_role_auth.roleid
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public Integer getRoleid() {
return roleid;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column sys_role_auth.roleid
*
* @param roleid the value for sys_role_auth.roleid
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public void setRoleid(Integer roleid) {
this.roleid = roleid;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column sys_role_auth.authname
*
* @return the value of sys_role_auth.authname
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public String getAuthname() {
return authname;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column sys_role_auth.authname
*
* @param authname the value for sys_role_auth.authname
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public void setAuthname(String authname) {
this.authname = authname;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column sys_role_auth.desc
*
* @return the value of sys_role_auth.desc
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public String getDesc() {
return desc;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column sys_role_auth.desc
*
* @param desc the value for sys_role_auth.desc
*
* @mbggenerated Fri Apr 29 17:01:42 CST 2016
*/
public void setDesc(String desc) {
this.desc = desc;
}
} | 27.740458 | 82 | 0.632361 |
60b851170fad3d079658aa4355e794360533db50 | 20,148 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/spanner/v1/result_set.proto
package com.google.spanner.v1;
public interface PartialResultSetOrBuilder
extends
// @@protoc_insertion_point(interface_extends:google.spanner.v1.PartialResultSet)
com.google.protobuf.MessageOrBuilder {
/**
*
*
* <pre>
* Metadata about the result set, such as row type information.
* Only present in the first response.
* </pre>
*
* <code>.google.spanner.v1.ResultSetMetadata metadata = 1;</code>
*
* @return Whether the metadata field is set.
*/
boolean hasMetadata();
/**
*
*
* <pre>
* Metadata about the result set, such as row type information.
* Only present in the first response.
* </pre>
*
* <code>.google.spanner.v1.ResultSetMetadata metadata = 1;</code>
*
* @return The metadata.
*/
com.google.spanner.v1.ResultSetMetadata getMetadata();
/**
*
*
* <pre>
* Metadata about the result set, such as row type information.
* Only present in the first response.
* </pre>
*
* <code>.google.spanner.v1.ResultSetMetadata metadata = 1;</code>
*/
com.google.spanner.v1.ResultSetMetadataOrBuilder getMetadataOrBuilder();
/**
*
*
* <pre>
* A streamed result set consists of a stream of values, which might
* be split into many `PartialResultSet` messages to accommodate
* large rows and/or large values. Every N complete values defines a
* row, where N is equal to the number of entries in
* [metadata.row_type.fields][google.spanner.v1.StructType.fields].
* Most values are encoded based on type as described
* [here][google.spanner.v1.TypeCode].
* It is possible that the last value in values is "chunked",
* meaning that the rest of the value is sent in subsequent
* `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value]
* field. Two or more chunked values can be merged to form a
* complete value as follows:
* * `bool/number/null`: cannot be chunked
* * `string`: concatenate the strings
* * `list`: concatenate the lists. If the last element in a list is a
* `string`, `list`, or `object`, merge it with the first element in
* the next list by applying these rules recursively.
* * `object`: concatenate the (field name, field value) pairs. If a
* field name is duplicated, then apply these rules recursively
* to merge the field values.
* Some examples of merging:
* # Strings are concatenated.
* "foo", "bar" => "foobar"
* # Lists of non-strings are concatenated.
* [2, 3], [4] => [2, 3, 4]
* # Lists are concatenated, but the last and first elements are merged
* # because they are strings.
* ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
* # Lists are concatenated, but the last and first elements are merged
* # because they are lists. Recursively, the last and first elements
* # of the inner lists are merged because they are strings.
* ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
* # Non-overlapping object fields are combined.
* {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
* # Overlapping object fields are merged.
* {"a": "1"}, {"a": "2"} => {"a": "12"}
* # Examples of merging objects containing lists of strings.
* {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
* For a more complete example, suppose a streaming SQL query is
* yielding a result set whose rows contain a single string
* field. The following `PartialResultSet`s might be yielded:
* {
* "metadata": { ... }
* "values": ["Hello", "W"]
* "chunked_value": true
* "resume_token": "Af65..."
* }
* {
* "values": ["orl"]
* "chunked_value": true
* "resume_token": "Bqp2..."
* }
* {
* "values": ["d"]
* "resume_token": "Zx1B..."
* }
* This sequence of `PartialResultSet`s encodes two rows, one
* containing the field value `"Hello"`, and a second containing the
* field value `"World" = "W" + "orl" + "d"`.
* </pre>
*
* <code>repeated .google.protobuf.Value values = 2;</code>
*/
java.util.List<com.google.protobuf.Value> getValuesList();
/**
*
*
* <pre>
* A streamed result set consists of a stream of values, which might
* be split into many `PartialResultSet` messages to accommodate
* large rows and/or large values. Every N complete values defines a
* row, where N is equal to the number of entries in
* [metadata.row_type.fields][google.spanner.v1.StructType.fields].
* Most values are encoded based on type as described
* [here][google.spanner.v1.TypeCode].
* It is possible that the last value in values is "chunked",
* meaning that the rest of the value is sent in subsequent
* `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value]
* field. Two or more chunked values can be merged to form a
* complete value as follows:
* * `bool/number/null`: cannot be chunked
* * `string`: concatenate the strings
* * `list`: concatenate the lists. If the last element in a list is a
* `string`, `list`, or `object`, merge it with the first element in
* the next list by applying these rules recursively.
* * `object`: concatenate the (field name, field value) pairs. If a
* field name is duplicated, then apply these rules recursively
* to merge the field values.
* Some examples of merging:
* # Strings are concatenated.
* "foo", "bar" => "foobar"
* # Lists of non-strings are concatenated.
* [2, 3], [4] => [2, 3, 4]
* # Lists are concatenated, but the last and first elements are merged
* # because they are strings.
* ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
* # Lists are concatenated, but the last and first elements are merged
* # because they are lists. Recursively, the last and first elements
* # of the inner lists are merged because they are strings.
* ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
* # Non-overlapping object fields are combined.
* {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
* # Overlapping object fields are merged.
* {"a": "1"}, {"a": "2"} => {"a": "12"}
* # Examples of merging objects containing lists of strings.
* {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
* For a more complete example, suppose a streaming SQL query is
* yielding a result set whose rows contain a single string
* field. The following `PartialResultSet`s might be yielded:
* {
* "metadata": { ... }
* "values": ["Hello", "W"]
* "chunked_value": true
* "resume_token": "Af65..."
* }
* {
* "values": ["orl"]
* "chunked_value": true
* "resume_token": "Bqp2..."
* }
* {
* "values": ["d"]
* "resume_token": "Zx1B..."
* }
* This sequence of `PartialResultSet`s encodes two rows, one
* containing the field value `"Hello"`, and a second containing the
* field value `"World" = "W" + "orl" + "d"`.
* </pre>
*
* <code>repeated .google.protobuf.Value values = 2;</code>
*/
com.google.protobuf.Value getValues(int index);
/**
*
*
* <pre>
* A streamed result set consists of a stream of values, which might
* be split into many `PartialResultSet` messages to accommodate
* large rows and/or large values. Every N complete values defines a
* row, where N is equal to the number of entries in
* [metadata.row_type.fields][google.spanner.v1.StructType.fields].
* Most values are encoded based on type as described
* [here][google.spanner.v1.TypeCode].
* It is possible that the last value in values is "chunked",
* meaning that the rest of the value is sent in subsequent
* `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value]
* field. Two or more chunked values can be merged to form a
* complete value as follows:
* * `bool/number/null`: cannot be chunked
* * `string`: concatenate the strings
* * `list`: concatenate the lists. If the last element in a list is a
* `string`, `list`, or `object`, merge it with the first element in
* the next list by applying these rules recursively.
* * `object`: concatenate the (field name, field value) pairs. If a
* field name is duplicated, then apply these rules recursively
* to merge the field values.
* Some examples of merging:
* # Strings are concatenated.
* "foo", "bar" => "foobar"
* # Lists of non-strings are concatenated.
* [2, 3], [4] => [2, 3, 4]
* # Lists are concatenated, but the last and first elements are merged
* # because they are strings.
* ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
* # Lists are concatenated, but the last and first elements are merged
* # because they are lists. Recursively, the last and first elements
* # of the inner lists are merged because they are strings.
* ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
* # Non-overlapping object fields are combined.
* {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
* # Overlapping object fields are merged.
* {"a": "1"}, {"a": "2"} => {"a": "12"}
* # Examples of merging objects containing lists of strings.
* {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
* For a more complete example, suppose a streaming SQL query is
* yielding a result set whose rows contain a single string
* field. The following `PartialResultSet`s might be yielded:
* {
* "metadata": { ... }
* "values": ["Hello", "W"]
* "chunked_value": true
* "resume_token": "Af65..."
* }
* {
* "values": ["orl"]
* "chunked_value": true
* "resume_token": "Bqp2..."
* }
* {
* "values": ["d"]
* "resume_token": "Zx1B..."
* }
* This sequence of `PartialResultSet`s encodes two rows, one
* containing the field value `"Hello"`, and a second containing the
* field value `"World" = "W" + "orl" + "d"`.
* </pre>
*
* <code>repeated .google.protobuf.Value values = 2;</code>
*/
int getValuesCount();
/**
*
*
* <pre>
* A streamed result set consists of a stream of values, which might
* be split into many `PartialResultSet` messages to accommodate
* large rows and/or large values. Every N complete values defines a
* row, where N is equal to the number of entries in
* [metadata.row_type.fields][google.spanner.v1.StructType.fields].
* Most values are encoded based on type as described
* [here][google.spanner.v1.TypeCode].
* It is possible that the last value in values is "chunked",
* meaning that the rest of the value is sent in subsequent
* `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value]
* field. Two or more chunked values can be merged to form a
* complete value as follows:
* * `bool/number/null`: cannot be chunked
* * `string`: concatenate the strings
* * `list`: concatenate the lists. If the last element in a list is a
* `string`, `list`, or `object`, merge it with the first element in
* the next list by applying these rules recursively.
* * `object`: concatenate the (field name, field value) pairs. If a
* field name is duplicated, then apply these rules recursively
* to merge the field values.
* Some examples of merging:
* # Strings are concatenated.
* "foo", "bar" => "foobar"
* # Lists of non-strings are concatenated.
* [2, 3], [4] => [2, 3, 4]
* # Lists are concatenated, but the last and first elements are merged
* # because they are strings.
* ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
* # Lists are concatenated, but the last and first elements are merged
* # because they are lists. Recursively, the last and first elements
* # of the inner lists are merged because they are strings.
* ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
* # Non-overlapping object fields are combined.
* {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
* # Overlapping object fields are merged.
* {"a": "1"}, {"a": "2"} => {"a": "12"}
* # Examples of merging objects containing lists of strings.
* {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
* For a more complete example, suppose a streaming SQL query is
* yielding a result set whose rows contain a single string
* field. The following `PartialResultSet`s might be yielded:
* {
* "metadata": { ... }
* "values": ["Hello", "W"]
* "chunked_value": true
* "resume_token": "Af65..."
* }
* {
* "values": ["orl"]
* "chunked_value": true
* "resume_token": "Bqp2..."
* }
* {
* "values": ["d"]
* "resume_token": "Zx1B..."
* }
* This sequence of `PartialResultSet`s encodes two rows, one
* containing the field value `"Hello"`, and a second containing the
* field value `"World" = "W" + "orl" + "d"`.
* </pre>
*
* <code>repeated .google.protobuf.Value values = 2;</code>
*/
java.util.List<? extends com.google.protobuf.ValueOrBuilder> getValuesOrBuilderList();
/**
*
*
* <pre>
* A streamed result set consists of a stream of values, which might
* be split into many `PartialResultSet` messages to accommodate
* large rows and/or large values. Every N complete values defines a
* row, where N is equal to the number of entries in
* [metadata.row_type.fields][google.spanner.v1.StructType.fields].
* Most values are encoded based on type as described
* [here][google.spanner.v1.TypeCode].
* It is possible that the last value in values is "chunked",
* meaning that the rest of the value is sent in subsequent
* `PartialResultSet`(s). This is denoted by the [chunked_value][google.spanner.v1.PartialResultSet.chunked_value]
* field. Two or more chunked values can be merged to form a
* complete value as follows:
* * `bool/number/null`: cannot be chunked
* * `string`: concatenate the strings
* * `list`: concatenate the lists. If the last element in a list is a
* `string`, `list`, or `object`, merge it with the first element in
* the next list by applying these rules recursively.
* * `object`: concatenate the (field name, field value) pairs. If a
* field name is duplicated, then apply these rules recursively
* to merge the field values.
* Some examples of merging:
* # Strings are concatenated.
* "foo", "bar" => "foobar"
* # Lists of non-strings are concatenated.
* [2, 3], [4] => [2, 3, 4]
* # Lists are concatenated, but the last and first elements are merged
* # because they are strings.
* ["a", "b"], ["c", "d"] => ["a", "bc", "d"]
* # Lists are concatenated, but the last and first elements are merged
* # because they are lists. Recursively, the last and first elements
* # of the inner lists are merged because they are strings.
* ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", "cd"], "e"]
* # Non-overlapping object fields are combined.
* {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"}
* # Overlapping object fields are merged.
* {"a": "1"}, {"a": "2"} => {"a": "12"}
* # Examples of merging objects containing lists of strings.
* {"a": ["1"]}, {"a": ["2"]} => {"a": ["12"]}
* For a more complete example, suppose a streaming SQL query is
* yielding a result set whose rows contain a single string
* field. The following `PartialResultSet`s might be yielded:
* {
* "metadata": { ... }
* "values": ["Hello", "W"]
* "chunked_value": true
* "resume_token": "Af65..."
* }
* {
* "values": ["orl"]
* "chunked_value": true
* "resume_token": "Bqp2..."
* }
* {
* "values": ["d"]
* "resume_token": "Zx1B..."
* }
* This sequence of `PartialResultSet`s encodes two rows, one
* containing the field value `"Hello"`, and a second containing the
* field value `"World" = "W" + "orl" + "d"`.
* </pre>
*
* <code>repeated .google.protobuf.Value values = 2;</code>
*/
com.google.protobuf.ValueOrBuilder getValuesOrBuilder(int index);
/**
*
*
* <pre>
* If true, then the final value in [values][google.spanner.v1.PartialResultSet.values] is chunked, and must
* be combined with more values from subsequent `PartialResultSet`s
* to obtain a complete field value.
* </pre>
*
* <code>bool chunked_value = 3;</code>
*
* @return The chunkedValue.
*/
boolean getChunkedValue();
/**
*
*
* <pre>
* Streaming calls might be interrupted for a variety of reasons, such
* as TCP connection loss. If this occurs, the stream of results can
* be resumed by re-sending the original request and including
* `resume_token`. Note that executing any other transaction in the
* same session invalidates the token.
* </pre>
*
* <code>bytes resume_token = 4;</code>
*
* @return The resumeToken.
*/
com.google.protobuf.ByteString getResumeToken();
/**
*
*
* <pre>
* Query plan and execution statistics for the statement that produced this
* streaming result set. These can be requested by setting
* [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent
* only once with the last response in the stream.
* This field will also be present in the last response for DML
* statements.
* </pre>
*
* <code>.google.spanner.v1.ResultSetStats stats = 5;</code>
*
* @return Whether the stats field is set.
*/
boolean hasStats();
/**
*
*
* <pre>
* Query plan and execution statistics for the statement that produced this
* streaming result set. These can be requested by setting
* [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent
* only once with the last response in the stream.
* This field will also be present in the last response for DML
* statements.
* </pre>
*
* <code>.google.spanner.v1.ResultSetStats stats = 5;</code>
*
* @return The stats.
*/
com.google.spanner.v1.ResultSetStats getStats();
/**
*
*
* <pre>
* Query plan and execution statistics for the statement that produced this
* streaming result set. These can be requested by setting
* [ExecuteSqlRequest.query_mode][google.spanner.v1.ExecuteSqlRequest.query_mode] and are sent
* only once with the last response in the stream.
* This field will also be present in the last response for DML
* statements.
* </pre>
*
* <code>.google.spanner.v1.ResultSetStats stats = 5;</code>
*/
com.google.spanner.v1.ResultSetStatsOrBuilder getStatsOrBuilder();
}
| 41.371663 | 116 | 0.6081 |
a7fc254811f80736ec8cae0efbccb92c8752c588 | 445 | package net.savantly.sprout.core.module.web.plugin;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
@Getter @Setter
@Accessors(chain = true)
@JsonIgnoreProperties(ignoreUnknown = true)
public class PluginBuildInfo {
private long time;
private String repo;
private String branch;
private String hash;
private long number;
private long pr;
}
| 22.25 | 61 | 0.804494 |
57801b89ff9d00e77389bd3027ebb38560482c9b | 947 | package ba.aljovic.amer.application.exception;
@SuppressWarnings ("UnusedDeclaration")
public class JinniMovieNotFoundException extends Exception
{
private final String movieTitle;
private final String url;
private final Integer id;
public JinniMovieNotFoundException(String movieTitle, String url, Integer id)
{
this.movieTitle = movieTitle;
this.url = url;
this.id = id;
}
public JinniMovieNotFoundException(String movieTitle, String url)
{
this.movieTitle = movieTitle;
this.url = url;
this.id = null;
}
public JinniMovieNotFoundException(String movieTitle)
{
this.movieTitle = movieTitle;
this.url = null;
this.id = null;
}
public String getMovieTitle()
{
return movieTitle;
}
public String getUrl()
{
return url;
}
public Integer getId()
{
return id;
}
}
| 20.586957 | 81 | 0.629356 |
369fa0c0e8ab06852d581054c257150b3e1c238e | 1,257 | /*
* Copyright 2019, Yahoo Inc.
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root for terms.
*/
package com.yahoo.elide.datastores.aggregation.queryengines.sql.query;
import lombok.Builder;
import lombok.Data;
import lombok.NonNull;
/**
* Aids in constructing a SQL query from String fragments.
*/
@Data
@Builder
public class NativeQuery {
private static final String SPACE = " ";
@NonNull
private String fromClause;
@NonNull
private String projectionClause;
@Builder.Default
private String joinClause = "";
@Builder.Default
private String whereClause = "";
@Builder.Default
private String groupByClause = "";
@Builder.Default
private String havingClause = "";
@Builder.Default
private String orderByClause = "";
@Builder.Default
private String offsetLimitClause = "";
@Override
public String toString() {
return String.format("SELECT %s FROM %s", projectionClause, fromClause)
+ SPACE + joinClause
+ SPACE + whereClause
+ SPACE + groupByClause
+ SPACE + havingClause
+ SPACE + orderByClause
+ SPACE + offsetLimitClause;
}
}
| 24.173077 | 79 | 0.645187 |
0386b042f9e33a0343d490259d9e8342d3c88ec6 | 918 | package com.unionpay.mobile.android.pro.views;
import android.os.Handler;
import com.unionpay.mobile.android.model.b;
import java.util.HashMap;
final class g
implements Runnable
{
g(a parama, String paramString, HashMap paramHashMap) {}
public final void run()
{
Object localObject1 = this.c;
Object localObject2 = this.a;
Object localObject3 = a.w(this.c).p;
localObject1 = ((a)localObject1).a((String)localObject2, this.b);
localObject2 = a.x(this.c);
localObject3 = a.x(this.c);
if (localObject1 != null) {}
for (;;)
{
((Handler)localObject2).sendMessage(((Handler)localObject3).obtainMessage(0, localObject1));
return;
localObject1 = null;
}
}
}
/* Location: /Users/gaoht/Downloads/zirom/classes2-dex2jar.jar!/com/unionpay/mobile/android/pro/views/g.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/ | 27 | 122 | 0.667756 |
b0d4b7a67679a35fa8f88c241193c0f3814f1e7b | 6,450 | package net.minecraft.server;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSyntaxException;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import javax.annotation.Nullable;
public class AdvancementDisplay {
private final IChatBaseComponent a;
private final IChatBaseComponent b;
private final ItemStack c;
private final MinecraftKey d;
private final AdvancementFrameType e;
private final boolean f;
private final boolean g;
private final boolean h;
private float i;
private float j;
public AdvancementDisplay(ItemStack itemstack, IChatBaseComponent ichatbasecomponent, IChatBaseComponent ichatbasecomponent1, @Nullable MinecraftKey minecraftkey, AdvancementFrameType advancementframetype, boolean flag, boolean flag1, boolean flag2) {
this.a = ichatbasecomponent;
this.b = ichatbasecomponent1;
this.c = itemstack;
this.d = minecraftkey;
this.e = advancementframetype;
this.f = flag;
this.g = flag1;
this.h = flag2;
}
public void a(float f, float f1) {
this.i = f;
this.j = f1;
}
public IChatBaseComponent a() {
return this.a;
}
public IChatBaseComponent b() {
return this.b;
}
public AdvancementFrameType e() {
return this.e;
}
public boolean i() {
return this.g;
}
public boolean j() {
return this.h;
}
public static AdvancementDisplay a(JsonObject jsonobject) {
IChatMutableComponent ichatmutablecomponent = IChatBaseComponent.ChatSerializer.a(jsonobject.get("title"));
IChatMutableComponent ichatmutablecomponent1 = IChatBaseComponent.ChatSerializer.a(jsonobject.get("description"));
if (ichatmutablecomponent != null && ichatmutablecomponent1 != null) {
ItemStack itemstack = b(ChatDeserializer.t(jsonobject, "icon"));
MinecraftKey minecraftkey = jsonobject.has("background") ? new MinecraftKey(ChatDeserializer.h(jsonobject, "background")) : null;
AdvancementFrameType advancementframetype = jsonobject.has("frame") ? AdvancementFrameType.a(ChatDeserializer.h(jsonobject, "frame")) : AdvancementFrameType.TASK;
boolean flag = ChatDeserializer.a(jsonobject, "show_toast", true);
boolean flag1 = ChatDeserializer.a(jsonobject, "announce_to_chat", true);
boolean flag2 = ChatDeserializer.a(jsonobject, "hidden", false);
return new AdvancementDisplay(itemstack, ichatmutablecomponent, ichatmutablecomponent1, minecraftkey, advancementframetype, flag, flag1, flag2);
} else {
throw new JsonSyntaxException("Both title and description must be set");
}
}
private static ItemStack b(JsonObject jsonobject) {
if (!jsonobject.has("item")) {
throw new JsonSyntaxException("Unsupported icon type, currently only items are supported (add 'item' key)");
} else {
Item item = ChatDeserializer.i(jsonobject, "item");
if (jsonobject.has("data")) {
throw new JsonParseException("Disallowed data tag found");
} else {
ItemStack itemstack = new ItemStack(item);
if (jsonobject.has("nbt")) {
try {
NBTTagCompound nbttagcompound = MojangsonParser.parse(ChatDeserializer.a(jsonobject.get("nbt"), "nbt"));
itemstack.setTag(nbttagcompound);
} catch (CommandSyntaxException commandsyntaxexception) {
throw new JsonSyntaxException("Invalid nbt tag: " + commandsyntaxexception.getMessage());
}
}
return itemstack;
}
}
}
public void a(PacketDataSerializer packetdataserializer) {
packetdataserializer.a(this.a);
packetdataserializer.a(this.b);
packetdataserializer.a(this.c);
packetdataserializer.a((Enum) this.e);
int i = 0;
if (this.d != null) {
i |= 1;
}
if (this.f) {
i |= 2;
}
if (this.h) {
i |= 4;
}
packetdataserializer.writeInt(i);
if (this.d != null) {
packetdataserializer.a(this.d);
}
packetdataserializer.writeFloat(this.i);
packetdataserializer.writeFloat(this.j);
}
public static AdvancementDisplay b(PacketDataSerializer packetdataserializer) {
IChatBaseComponent ichatbasecomponent = packetdataserializer.h();
IChatBaseComponent ichatbasecomponent1 = packetdataserializer.h();
ItemStack itemstack = packetdataserializer.n();
AdvancementFrameType advancementframetype = (AdvancementFrameType) packetdataserializer.a(AdvancementFrameType.class);
int i = packetdataserializer.readInt();
MinecraftKey minecraftkey = (i & 1) != 0 ? packetdataserializer.p() : null;
boolean flag = (i & 2) != 0;
boolean flag1 = (i & 4) != 0;
AdvancementDisplay advancementdisplay = new AdvancementDisplay(itemstack, ichatbasecomponent, ichatbasecomponent1, minecraftkey, advancementframetype, flag, false, flag1);
advancementdisplay.a(packetdataserializer.readFloat(), packetdataserializer.readFloat());
return advancementdisplay;
}
public JsonElement k() {
JsonObject jsonobject = new JsonObject();
jsonobject.add("icon", this.l());
jsonobject.add("title", IChatBaseComponent.ChatSerializer.b(this.a));
jsonobject.add("description", IChatBaseComponent.ChatSerializer.b(this.b));
jsonobject.addProperty("frame", this.e.a());
jsonobject.addProperty("show_toast", this.f);
jsonobject.addProperty("announce_to_chat", this.g);
jsonobject.addProperty("hidden", this.h);
if (this.d != null) {
jsonobject.addProperty("background", this.d.toString());
}
return jsonobject;
}
private JsonObject l() {
JsonObject jsonobject = new JsonObject();
jsonobject.addProperty("item", IRegistry.ITEM.getKey(this.c.getItem()).toString());
if (this.c.hasTag()) {
jsonobject.addProperty("nbt", this.c.getTag().toString());
}
return jsonobject;
}
}
| 37.068966 | 255 | 0.646047 |
c7d5de6dd0863b428505bbedf248c3aefe68caec | 323 | public class NumbersPrintln
{
public static void main(String[] args)
{
int billingDate = 5;
System.out.print("Bills are sent on day ");
System.out.print(billingDate);
System.out.println(" of the month");
System.out.println("Next bill: October " +
billingDate);
}
} | 26.916667 | 50 | 0.600619 |
e9533a39cf2878734e6a539258bed873b982dd66 | 1,146 | package conway.main;
public class World {
private final Cell[][] grid;
public World(int rows, int columns) {
grid = new Cell[rows][columns];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < columns; c++) {
grid[r][c] = new Cell(r, c);
}
}
}
public Cell getCell(int row, int column) {
Cell cell = null;
if (row >= 0 && row < grid.length) {
if (column >= 0 && column < grid[0].length) {
cell = grid[row][column];
}
}
return cell;
}
public int numberOfColumns() {
return grid[0].length;
}
public int numberOfRows() {
return grid.length;
}
public void cycle() {
for (int r = 0; r < numberOfRows(); r++) {
for (int c = 0; c < numberOfColumns(); c++) {
grid[r][c].cycle(this);
}
}
}
public void commit() {
for (int r = 0; r < numberOfRows(); r++) {
for (int c = 0; c < numberOfColumns(); c++) {
grid[r][c].commit();
}
}
}
}
| 22.92 | 57 | 0.431937 |
fced9d2e73f17480ea7f29fd97a613909dfd027d | 1,332 | package com.wjz.activemq.demo;
import java.io.IOException;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;
public class JmsConsumer_Queue_2 {
public static final String DEFAULT_BROKER_BIND_URL = "tcp://192.168.21.131:61616";
public static final String QUEUE_NAME = "queue";
public static void main(String[] args) throws JMSException, IOException {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(DEFAULT_BROKER_BIND_URL);
Connection conn = factory.createConnection();
conn.start();
Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(QUEUE_NAME);
MessageConsumer consumer = session.createConsumer(queue);
consumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
if (message != null && message instanceof TextMessage) {
try {
System.out.println(((TextMessage) message).getText());
} catch (JMSException e) {
e.printStackTrace();
}
}
}
});
System.in.read();
consumer.close();
session.close();
conn.close();
}
}
| 29.6 | 93 | 0.75 |
20666b8605678b4fff9f736e9af3963a0f6f6799 | 202 | package com.alexeyburyanov.smarthotel.ui.myroom;
/**
* Created by Alexey Buryanov 04.04.2018.
*/
public interface MyRoomCheckOutDialogData {
void onBookingClick();
void onCheckOutClick();
}
| 18.363636 | 48 | 0.737624 |
4805a50ec7fd25a73ab618b613845a69f717d30b | 6,834 | package com.stm.main.fragment.main.search.base.activity;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import com.stm.R;
import com.stm.common.dao.User;
import com.stm.common.flag.MarketFragmentFlag;
import com.stm.common.flag.SearchFragmentFlag;
import com.stm.common.util.ToastUtil;
import com.stm.main.fragment.main.search.base.adapter.SearchTabAdapter;
import com.stm.main.fragment.main.search.base.presenter.SearchPresenter;
import com.stm.main.fragment.main.search.base.presenter.impl.SearchPresenterImpl;
import com.stm.main.fragment.main.search.base.view.SearchView;
import com.stm.main.fragment.main.search.fragment.market.fragment.SearchMarketFragment;
import com.stm.main.fragment.main.search.fragment.user.fragment.SearchUserFragment;
import com.stm.main.fragment.main.search.fragment.tag.fragment.SearchTagFragment;
import com.stm.repository.local.SharedPrefersManager;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by ㅇㅇ on 2017-09-01.
*/
public class SearchActivity extends FragmentActivity implements SearchView, TextWatcher, TabLayout.OnTabSelectedListener {
private SearchPresenter searchPresenter;
private ToastUtil toastUtil;
private SharedPrefersManager sharedPrefersManager;
private ProgressDialog progressDialog;
private Handler progressDialogHandler;
private Handler searchTabAdapterHandler;
private SearchTabAdapter searchTabAdapter;
@BindView(R.id.tl_search)
TabLayout tl_search;
@BindView(R.id.vp_search)
ViewPager vp_search;
@BindView(R.id.et_search)
EditText et_search;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ButterKnife.bind(this);
this.toastUtil = new ToastUtil(this);
this.sharedPrefersManager = new SharedPrefersManager(this);
this.progressDialogHandler = new Handler();
this.progressDialog = new ProgressDialog(this);
this.progressDialogHandler = new Handler();
this.searchTabAdapterHandler = new Handler();
User user = sharedPrefersManager.getUser();
this.searchPresenter = new SearchPresenterImpl(this);
this.searchPresenter.init(user);
}
@Override
public void onResume() {
super.onResume();
User user = sharedPrefersManager.getUser();
searchPresenter.onResume(user);
}
@Override
public void showMessage(String message) {
this.toastUtil.showMessage(message);
}
@Override
public void showProgressDialog() {
progressDialog.show();
progressDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
progressDialog.setContentView(R.layout.progress_dialog);
}
@Override
public void goneProgressDialog() {
progressDialogHandler.postDelayed(new Runnable() {
@Override
public void run() {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}, 10);
}
@Override
@OnClick(R.id.iv_search_back)
public void onClickBack() {
searchPresenter.onClickBack();
}
@Override
@OnClick(R.id.iv_search_clear)
public void onClickClear() {
searchPresenter.onClickClear();
}
@Override
public void navigateToBack() {
finish();
}
@Override
public void setTabLayout() {
tl_search.addTab(tl_search.newTab().setText("시장"));
tl_search.addTab(tl_search.newTab().setText("유저"));
tl_search.addTab(tl_search.newTab().setText("태그"));
vp_search.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tl_search));
tl_search.addOnTabSelectedListener(this);
}
@Override
public void setSearchTabAdapter() {
searchTabAdapter = new SearchTabAdapter(getSupportFragmentManager(), this);
searchTabAdapter.addFragment(new SearchMarketFragment());
searchTabAdapter.addFragment(new SearchUserFragment());
searchTabAdapter.addFragment(new SearchTagFragment());
vp_search.setAdapter(searchTabAdapter);
}
@Override
public void setEditText(String message) {
et_search.setText(message);
}
@Override
public void setEditTextChangedListener() {
et_search.addTextChangedListener(this);
}
@Override
public void setUserFragment(String message) {
((SearchUserFragment) searchTabAdapter.getItem(SearchFragmentFlag.USER)).getUserListByKeyword(message);
}
@Override
public void setMarketFragment(String message) {
((SearchMarketFragment) searchTabAdapter.getItem(SearchFragmentFlag.MARKET)).getMarketListByKeyword(message);
}
@Override
public void setTagFragment(String message) {
((SearchTagFragment) searchTabAdapter.getItem(SearchFragmentFlag.STORY)).getStoryListByKeyword(message);
}
@Override
public void setOffscreenPageLimit(int limit) {
vp_search.setOffscreenPageLimit(limit);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
searchPresenter.onTextChanged(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void onTabSelected(TabLayout.Tab tab) {
vp_search.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
@Override
public void setTagFragmentRefresh() {
Fragment fragment = new SearchTagFragment();
searchTabAdapter.setFragment(SearchFragmentFlag.STORY, fragment);
searchPresenter.onChangeFragment();
}
@Override
public void setSearchTabAdapterUser(User user) {
searchTabAdapter.setUser(user);
}
@Override
public void setSearchTabAdapterNotifyDataSetChanged() {
searchTabAdapterHandler.post(new Runnable() {
@Override
public void run() {
searchTabAdapter.notifyDataSetChanged();
}
});
}
}
| 29.713043 | 122 | 0.70998 |
6fd9bb4c8eba5ccb8bd6ed047f3a052b91662761 | 564 | package de.nkilders.neuralnetwork;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author Noah Kilders
*/
public class Neuron implements Serializable {
public double output;
public double bias;
public double error;
public List<Synapse> inSynapses;
public List<Synapse> outSynapses;
public Neuron() {
this.output = 0.0D;
this.bias = 0.5D - Math.random();
this.error = 0.0D;
this.inSynapses = new ArrayList<>();
this.outSynapses = new ArrayList<>();
}
} | 22.56 | 45 | 0.652482 |
b118e7fe514a7173afbb534a0225c505a0e55b05 | 18,499 | /*
* 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.cassandra.cql3.statements;
import java.util.*;
import java.util.stream.Collectors;
import com.google.common.collect.Iterables;
import org.apache.cassandra.auth.Permission;
import org.apache.cassandra.config.*;
import org.apache.cassandra.cql3.*;
import org.apache.cassandra.db.ColumnFamilyStore;
import org.apache.cassandra.db.Keyspace;
import org.apache.cassandra.db.Mutation;
import org.apache.cassandra.db.marshal.AbstractType;
import org.apache.cassandra.db.marshal.BytesType;
import org.apache.cassandra.db.marshal.EmptyType;
import org.apache.cassandra.db.view.View;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.io.sstable.format.SSTableReader;
import org.apache.cassandra.schema.IndexMetadata;
import org.apache.cassandra.schema.Indexes;
import org.apache.cassandra.schema.TableParams;
import org.apache.cassandra.schema.KeyspaceMetadata;
import org.apache.cassandra.service.ClientState;
import org.apache.cassandra.service.MigrationManager;
import org.apache.cassandra.service.QueryState;
import org.apache.cassandra.transport.Event;
import org.apache.cassandra.utils.Pair;
import static org.apache.cassandra.thrift.ThriftValidation.validateColumnFamily;
public class AlterTableStatement extends SchemaAlteringStatement
{
public enum Type
{
ADD, ALTER, DROP, DROP_COMPACT_STORAGE, OPTS, RENAME
}
public final Type oType;
private final TableAttributes attrs;
private final Map<ColumnDefinition.Raw, ColumnDefinition.Raw> renames;
private final List<AlterTableStatementColumn> colNameList;
private final Long deleteTimestamp;
public AlterTableStatement(CFName name,
Type type,
List<AlterTableStatementColumn> colDataList,
TableAttributes attrs,
Map<ColumnDefinition.Raw, ColumnDefinition.Raw> renames,
Long deleteTimestamp)
{
super(name);
this.oType = type;
this.colNameList = colDataList;
this.attrs = attrs;
this.renames = renames;
this.deleteTimestamp = deleteTimestamp;
}
public void checkAccess(ClientState state) throws UnauthorizedException, InvalidRequestException
{
state.hasColumnFamilyAccess(keyspace(), columnFamily(), Permission.ALTER);
}
@Override
public void validate(ClientState state)
{
// validated in announceMigration()
}
@Override
public Event.SchemaChange announceMigration(QueryState queryState, boolean isLocalOnly) throws RequestValidationException
{
KeyspaceMetadata ksm = Schema.instance.getKSMetaData(keyspace());
CFMetaData cfm = validateColumnFamily(ksm, columnFamily());
Pair<CFMetaData, List<ViewDefinition>> x = updateTable(ksm, cfm, queryState.getTimestamp());
MigrationManager.announceColumnFamilyUpdate(x.left, x.right, isLocalOnly);
return new Event.SchemaChange(Event.SchemaChange.Change.UPDATED, Event.SchemaChange.Target.TABLE, keyspace(), columnFamily());
}
public Pair<CFMetaData, List<ViewDefinition>> updateTable(KeyspaceMetadata ksm, CFMetaData meta, long timestamp) throws RequestValidationException
{
validateColumnFamily(ksm, meta.cfName);
if (meta.isView())
throw new InvalidRequestException("Cannot use ALTER TABLE on Materialized View");
CFMetaData cfm;
ColumnIdentifier columnName = null;
ColumnDefinition def = null;
CQL3Type.Raw dataType = null;
boolean isStatic = false;
CQL3Type validator = null;
List<ViewDefinition> viewUpdates = null;
Iterable<ViewDefinition> views = ksm.views(columnFamily());
switch (oType)
{
case ALTER:
cfm = null;
for (AlterTableStatementColumn colData : colNameList)
{
columnName = colData.getColumnName().getIdentifier(meta);
def = meta.getColumnDefinition(columnName);
dataType = colData.getColumnType();
validator = dataType.prepare(keyspace());
// We do not support altering of types and only allow this to for people who have already one
// through the upgrade of 2.x CQL-created SSTables with Thrift writes, affected by CASSANDRA-15778.
if (meta.isDense()
&& meta.compactValueColumn().equals(def)
&& meta.compactValueColumn().type instanceof EmptyType
&& validator != null)
{
if (validator.getType() instanceof BytesType)
cfm = meta.copyWithNewCompactValueType(validator.getType());
else
throw new InvalidRequestException(String.format("Compact value type can only be changed to BytesType, but %s was given.",
validator.getType()));
}
}
if (cfm == null)
throw new InvalidRequestException("Altering of types is not allowed");
else
break;
case ADD:
if (meta.isDense())
throw new InvalidRequestException("Cannot add new column to a COMPACT STORAGE table");
cfm = meta.copy();
for (AlterTableStatementColumn colData : colNameList)
{
columnName = colData.getColumnName().getIdentifier(cfm);
def = cfm.getColumnDefinition(columnName);
dataType = colData.getColumnType();
assert dataType != null;
isStatic = colData.getStaticType();
validator = dataType.prepare(ksm);
if (isStatic)
{
if (!cfm.isCompound())
throw new InvalidRequestException("Static columns are not allowed in COMPACT STORAGE tables");
if (cfm.clusteringColumns().isEmpty())
throw new InvalidRequestException("Static columns are only useful (and thus allowed) if the table has at least one clustering column");
}
if (def != null)
{
switch (def.kind)
{
case PARTITION_KEY:
case CLUSTERING:
throw new InvalidRequestException(String.format("Invalid column name %s because it conflicts with a PRIMARY KEY part", columnName));
default:
throw new InvalidRequestException(String.format("Invalid column name %s because it conflicts with an existing column", columnName));
}
}
AbstractType<?> type = validator.getType();
if (type.isCollection() && type.isMultiCell())
{
if (!cfm.isCompound())
throw new InvalidRequestException("Cannot use non-frozen collections in COMPACT STORAGE tables");
if (cfm.isSuper())
throw new InvalidRequestException("Cannot use non-frozen collections with super column families");
}
ColumnDefinition toAdd = isStatic
? ColumnDefinition.staticDef(cfm, columnName.bytes, type)
: ColumnDefinition.regularDef(cfm, columnName.bytes, type);
CFMetaData.DroppedColumn droppedColumn = meta.getDroppedColumns().get(columnName.bytes);
if (null != droppedColumn)
{
if (droppedColumn.kind != toAdd.kind)
{
String message =
String.format("Cannot re-add previously dropped column '%s' of kind %s, incompatible with previous kind %s",
columnName,
toAdd.kind,
droppedColumn.kind == null ? "UNKNOWN" : droppedColumn.kind);
throw new InvalidRequestException(message);
}
// After #8099, not safe to re-add columns of incompatible types - until *maybe* deser logic with dropped
// columns is pushed deeper down the line. The latter would still be problematic in cases of schema races.
if (!type.isValueCompatibleWith(droppedColumn.type))
{
String message =
String.format("Cannot re-add previously dropped column '%s' of type %s, incompatible with previous type %s",
columnName,
type.asCQL3Type(),
droppedColumn.type.asCQL3Type());
throw new InvalidRequestException(message);
}
// Cannot re-add a dropped counter column. See #7831.
if (meta.isCounter())
throw new InvalidRequestException(String.format("Cannot re-add previously dropped counter column %s", columnName));
}
cfm.addColumnDefinition(toAdd);
// Adding a column to a table which has an include all view requires the column to be added to the view as well
if (!isStatic)
{
for (ViewDefinition view : views)
{
if (view.includeAllColumns)
{
ViewDefinition viewCopy = view.copy();
viewCopy.metadata.addColumnDefinition(ColumnDefinition.regularDef(viewCopy.metadata, columnName.bytes, type));
if (viewUpdates == null)
viewUpdates = new ArrayList<>();
viewUpdates.add(viewCopy);
}
}
}
}
break;
case DROP:
if (!meta.isCQLTable())
throw new InvalidRequestException("Cannot drop columns from a non-CQL3 table");
cfm = meta.copy();
for (AlterTableStatementColumn colData : colNameList)
{
columnName = colData.getColumnName().getIdentifier(cfm);
def = cfm.getColumnDefinition(columnName);
if (def == null)
throw new InvalidRequestException(String.format("Column %s was not found in table %s", columnName, columnFamily()));
switch (def.kind)
{
case PARTITION_KEY:
case CLUSTERING:
throw new InvalidRequestException(String.format("Cannot drop PRIMARY KEY part %s", columnName));
case REGULAR:
case STATIC:
ColumnDefinition toDelete = null;
for (ColumnDefinition columnDef : cfm.partitionColumns())
{
if (columnDef.name.equals(columnName))
{
toDelete = columnDef;
break;
}
}
assert toDelete != null;
cfm.removeColumnDefinition(toDelete);
cfm.recordColumnDrop(toDelete, deleteTimestamp == null ? timestamp : deleteTimestamp);
break;
}
// If the dropped column is required by any secondary indexes
// we reject the operation, as the indexes must be dropped first
Indexes allIndexes = cfm.getIndexes();
if (!allIndexes.isEmpty())
{
ColumnFamilyStore store = Keyspace.openAndGetStore(cfm);
Set<IndexMetadata> dependentIndexes = store.indexManager.getDependentIndexes(def);
if (!dependentIndexes.isEmpty())
throw new InvalidRequestException(String.format("Cannot drop column %s because it has " +
"dependent secondary indexes (%s)",
def,
dependentIndexes.stream()
.map(i -> i.name)
.collect(Collectors.joining(","))));
}
if (!Iterables.isEmpty(views))
throw new InvalidRequestException(String.format("Cannot drop column %s on base table %s with materialized views.",
columnName.toString(),
columnFamily()));
}
break;
case DROP_COMPACT_STORAGE:
if (!meta.isCompactTable())
throw new InvalidRequestException("Cannot DROP COMPACT STORAGE on table without COMPACT STORAGE");
// TODO: Global check of the sstables to be added as part of CASSANDRA-15897.
// Currently this is only a local check of the SSTables versions
for (SSTableReader ssTableReader : Keyspace.open(keyspace()).getColumnFamilyStore(columnFamily()).getLiveSSTables())
{
if (!ssTableReader.descriptor.version.isLatestVersion())
throw new InvalidRequestException("Cannot DROP COMPACT STORAGE until all SSTables are upgraded, please run `nodetool upgradesstables` first.");
}
cfm = meta.asNonCompact();
break;
case OPTS:
if (attrs == null)
throw new InvalidRequestException("ALTER TABLE WITH invoked, but no parameters found");
attrs.validate();
cfm = meta.copy();
TableParams params = attrs.asAlteredTableParams(cfm.params);
if (!Iterables.isEmpty(views) && params.gcGraceSeconds == 0)
{
throw new InvalidRequestException("Cannot alter gc_grace_seconds of the base table of a " +
"materialized view to 0, since this value is used to TTL " +
"undelivered updates. Setting gc_grace_seconds too low might " +
"cause undelivered updates to expire " +
"before being replayed.");
}
if (meta.isCounter() && params.defaultTimeToLive > 0)
throw new InvalidRequestException("Cannot set default_time_to_live on a table with counters");
cfm.params(params);
break;
case RENAME:
cfm = meta.copy();
for (Map.Entry<ColumnDefinition.Raw, ColumnDefinition.Raw> entry : renames.entrySet())
{
ColumnIdentifier from = entry.getKey().getIdentifier(cfm);
ColumnIdentifier to = entry.getValue().getIdentifier(cfm);
cfm.renameColumn(from, to);
// If the view includes a renamed column, it must be renamed in the view table and the definition.
for (ViewDefinition view : views)
{
if (!view.includes(from)) continue;
ViewDefinition viewCopy = view.copy();
ColumnIdentifier viewFrom = entry.getKey().getIdentifier(viewCopy.metadata);
ColumnIdentifier viewTo = entry.getValue().getIdentifier(viewCopy.metadata);
viewCopy.renameColumn(viewFrom, viewTo);
if (viewUpdates == null)
viewUpdates = new ArrayList<>();
viewUpdates.add(viewCopy);
}
}
break;
default:
throw new InvalidRequestException("Can not alter table: unknown option type " + oType);
}
return Pair.create(cfm, viewUpdates);
}
public String toString()
{
return String.format("AlterTableStatement(name=%s, type=%s)",
cfName,
oType);
}
}
| 49.068966 | 167 | 0.526893 |
1432ca03178d8dbc8d4e1744db0b5bcef37569bf | 3,467 | package com.batoulapps.QamarDeen.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class QamarTime {
public static Calendar getTodayCalendar() {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.AM_PM, Calendar.PM);
return c;
}
public static Calendar getGMTCalendar() {
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.AM_PM, Calendar.PM);
return c;
}
/**
* given a gmt calendar at 12:00:00, returns the timestamp of a local
* calendar set at the same date as the gmt calendar at 12:00:00 local
*
* @param gmtCal a gmt calendar
* @return timestamp of 12:00:00 on the same day in the local timezone
*/
public static long getLocalTimeFromGMT(Calendar gmtCal) {
return getLocalCalendarFromGMT(gmtCal).getTimeInMillis();
}
/**
* given a gmt calendar at 12:00:00, returns the local calendar
* set at the same date as the gmt calendar at 12:00:00 local
*
* @param gmtCal a gmt calendar
* @return calendar of 12:00:00 on the same day in the local timezone
*/
public static Calendar getLocalCalendarFromGMT(Calendar gmtCal) {
Calendar localTime = getTodayCalendar();
localTime.set(gmtCal.get(Calendar.YEAR), gmtCal.get(Calendar.MONTH), gmtCal.get(Calendar.DATE));
return localTime;
}
/**
* given a local calendar at 12:00:00, returns the timestamp of a gmt
* calendar set at the same date as the local calendar at 12:00:00 gmt
*
* @param localCal a local calendar
* @return timestamp of 12:00:00 on the same day in gmt
*/
public static long getGMTTimeFromLocal(Calendar localCal) {
Calendar gmtTime = getGMTCalendar();
gmtTime.set(localCal.get(Calendar.YEAR), localCal.get(Calendar.MONTH), localCal.get(Calendar.DATE));
return gmtTime.getTimeInMillis();
}
/**
* given a local date at 12:00:00, returns the timestamp of a gmt
* calendar set at the same date as the local date at 12:00:00 gmt
*
* @param localDate a local date
* @return timestamp of 12:00:00 on the same day in gmt
*/
public static long getGMTTimeFromLocalDate(Date localDate) {
Calendar cal = QamarTime.getTodayCalendar();
cal.setTime(localDate);
return QamarTime.getGMTTimeFromLocal(cal);
}
public static long getMidnightMillis() {
Calendar midnight = Calendar.getInstance();
midnight.set(Calendar.HOUR, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
midnight.set(Calendar.AM_PM, Calendar.AM);
midnight.add(Calendar.DATE, 1);
return midnight.getTimeInMillis();
}
public static String getDateFromMillis(long millis) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(millis);
c.getTime();
return new SimpleDateFormat("EEE, dd MMM yyyy", Locale.getDefault()).format(c.getTime());
}
} | 33.990196 | 108 | 0.653591 |
ba0951e442d9626688398b80787d34206f9979b4 | 715 | package com.yunio.easechat.utils;
import android.util.Log;
public class LogUtils {
public static boolean isDebug() {
return true;
}
public static void d(String tag, String msg) {
if (isDebug()) {
Log.d(tag, msg);
}
}
public static void d(String tag, String msg, Object... args) {
if (isDebug()) {
Log.d(tag, String.format(msg, args));
}
}
public static void e(String tag, String msg) {
if (isDebug()) {
Log.e(tag, msg);
}
}
public static void e(String tag, String msg, Object... args) {
if (isDebug()) {
Log.e(tag, String.format(msg, args));
}
}
}
| 20.428571 | 66 | 0.518881 |
9ec62510c4e8d832f6cd465d2219f15173211dac | 4,415 | /*******************************************************************************
* Copyright 2012 Geoscience Australia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package au.gov.ga.worldwind.animator.animation.camera;
import gov.nasa.worldwind.geom.Position;
import au.gov.ga.worldwind.animator.animation.Animatable;
import au.gov.ga.worldwind.animator.animation.parameter.Parameter;
/**
* A {@link Camera} is an {@link Animatable} object defined by an eye location
* and a look-at position.
* <p/>
* It is used to define and control the camera position inside the WorldWind
* world.
*
* @author James Navin (james.navin@ga.gov.au)
*
*/
public interface Camera extends Animatable
{
/**
* @return The parameter that represents the latitude of the camera 'eye'
*/
Parameter getEyeLat();
/**
* @return The parameter that represents the longitude of the camera 'eye'
*/
Parameter getEyeLon();
/**
* @return The parameter that represents the elevation of the camera 'eye'
*/
Parameter getEyeElevation();
/**
* @return The parameter that represents the latitude of the camera
* 'look-at' point
*/
Parameter getLookAtLat();
/**
* @return The parameter that represents the longitude of the camera
* 'look-at' point
*/
Parameter getLookAtLon();
/**
* @return The parameter that represents the elevation of the camera
* 'look-at' point
*/
Parameter getLookAtElevation();
/**
* @return The parameter that represents the roll of the camera
*/
Parameter getRoll();
/**
* @return The parameter that represents the field-of-view of the camera
*/
Parameter getFieldOfView();
/**
* @return Whether the camera clipping parameters are active or not
*/
boolean isClippingParametersActive();
/**
* Sets the clipping parameters to be active or not.
* <p/>
* If the status changes, this can result in key frame parameters being
* removed entirely from the animation.
*/
void setClippingParametersActive(boolean active);
/**
* @return The parameter that represents the near clipping distance of the
* camera
*/
Parameter getNearClip();
/**
* @return The parameter that represents the near clipping distance of the
* camera
*/
Parameter getFarClip();
/**
* @return The eye position of the camera in the provided frame range
* (inclusive)
*/
Position[] getEyePositionsBetweenFrames(int startFrame, int endFrame);
/**
* @return The lookat position of the camera in the provided frame range
* (inclusive)
*/
Position[] getLookatPositionsBetweenFrames(int startFrame, int endFrame);
/**
* Return the eye position of the camera at the provided frame
*
* @param frame
* The frame at which the eye position is required
*
* @return The eye position of the camera at the provided frame
*/
Position getEyePositionAtFrame(int frame);
/**
* Return the look-at position of the camera at the provided frame
*
* @param frame
* The frame at which the eye position is required
*
* @return The eye position of the camera at the provided frame
*/
Position getLookatPositionAtFrame(int frame);
/**
* Smooths the camera's eye speed through the animation.
* <p/>
* This may result in key frames related to the camera being re-adjusted to
* provide a smooth camera transition.
*/
void smoothEyeSpeed();
/**
* Copy parameters and other globals from the provided camera to this
* camera. Called when swapping between normal and stereo cameras.
*
* @param camera
* Camera to copy state from
*/
void copyStateFrom(Camera camera);
}
| 29.046053 | 81 | 0.650057 |
c68bff2d65d733b5f481636f6330480caa6345c1 | 4,191 | /*
* Copyright (C) 2020 National Institute of Informatics
*
* 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 jp.ad.sinet.stream.android.config;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.Map;
import jp.ad.sinet.stream.android.api.InvalidConfigurationException;
import jp.ad.sinet.stream.android.api.ValueType;
public class ApiParser extends BaseParser {
/* Entry point */
public void parse(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
//parseTopic(myParams);
parseTopics(myParams);
/*
* Workaround for weird crash after unsubscribe() & disconnect().
* https://github.com/eclipse/paho.mqtt.android/issues/238
*
* Here we ignore user-specified clientId, and let the
* library MqttAsyncClient generate a random one instead.
*/
//parseClientId(myParams);
parseConsistency(myParams);
parseValueType(myParams);
parseDataEncryption(myParams);
}
private String mTopic = null;
private void parseTopic(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
String key = "topic"; /* Mandatory */
mTopic = super.parseString(myParams, key, true);
}
@Nullable
public final String getTopic() {
return mTopic;
}
private String[] mTopics = null;
private void parseTopics(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
String key = "topics"; /* Mandatory */
mTopics = super.parseStringList(myParams, key, true);
}
@Nullable
public final String[] getTopics() {
return mTopics;
}
private String mClientId = null;
private void parseClientId(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
String key = "client_id"; /* Optional */
mClientId = super.parseAlphaNumeric(myParams, key, false);
}
@Nullable
public final String getClientId() {
return mClientId;
}
//private int mConsistency = (Consistency.AT_LEAST_ONCE).getQos();
private Integer mConsistency = null;
private void parseConsistency(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
String key = "consistency"; /* Optional */
mConsistency = super.parseConsistency(myParams, key, false);
}
@Nullable
public Integer getConsistency() {
return mConsistency;
}
//private ValueType mValueType = ValueType.BYTE_ARRAY;
private ValueType mValueType = null;
private void parseValueType(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
String key = "value_type"; /* Optional */
mValueType = super.parseValueType(myParams, key, false);
}
@Nullable
public final ValueType getValueType() {
return mValueType;
}
private Boolean mDataEncryption = null;
private void parseDataEncryption(@NonNull Map<String,Object> myParams)
throws InvalidConfigurationException {
String key = "data_encryption"; /* Optional */
mDataEncryption = super.parseBoolean(myParams, key, false);
}
@Nullable
public final Boolean getDataEncryption() {
return mDataEncryption;
}
}
| 32.742188 | 74 | 0.680744 |
bbf57c6ca40456e2d5641d573d6e9b44250ceefb | 384 | package index.project.version.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/** Preliminary test */
@Retention(RUNTIME)
@Target({ TYPE, FIELD, METHOD, CONSTRUCTOR, ANNOTATION_TYPE, PACKAGE, TYPE_USE })
public @interface Alpha { }
| 29.538462 | 81 | 0.794271 |
8bdd3b129b6af4596d8273693813a5402269fe35 | 1,024 | package com.tabnine.binary.requests.autocomplete;
import com.google.gson.annotations.SerializedName;
import com.tabnine.binary.BinaryRequest;
import static java.util.Collections.singletonMap;
public class AutocompleteRequest implements BinaryRequest<AutocompleteResponse> {
public String before;
public String after;
public String filename;
@SerializedName(value = "region_includes_beginning")
public boolean regionIncludesBeginning;
@SerializedName(value = "region_includes_end")
public boolean regionIncludesEnd;
@SerializedName(value = "max_num_results")
public int maxResults;
public int offset;
public int line;
public int character;
public Class<AutocompleteResponse> response() {
return AutocompleteResponse.class;
}
@Override
public Object serialize() {
return singletonMap("Autocomplete", this);
}
public boolean validate(AutocompleteResponse response) {
return this.before.endsWith(response.old_prefix);
}
}
| 29.257143 | 81 | 0.746094 |
3bafabb6b6661635ab9f06c00920b27a784c9b54 | 1,451 | package com.antfortune.freeline.router;
import com.antfortune.freeline.server.EmbedHttpServer;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
public class Router {
private static Router sInstance;
private Map<String, ISchemaAction> mSchemaMap = new HashMap<>();
private Router() {
}
public static Router getInstance() {
synchronized (Router.class) {
if (sInstance == null) {
sInstance = new Router();
}
return sInstance;
}
}
public void registerSchema(ISchemaAction schemaAction) {
if (schemaAction != null) {
mSchemaMap.put(schemaAction.getDescription(), schemaAction);
}
}
public boolean dispatch(
String method,
String path,
HashMap<String, String> headers,
Map<String, String> queries,
InputStream input,
EmbedHttpServer.ResponseOutputStream response) throws Exception {
if (queries == null || queries.size() == 0) {
return false;
}
String description = queries.get(ISchemaAction.DESCRIPTION);
for (String name : mSchemaMap.keySet()) {
if (name.equals(description)) {
mSchemaMap.get(name).handle(method, path, headers, queries, input, response);
return true;
}
}
return false;
}
}
| 25.45614 | 93 | 0.58787 |
d57ade864e72d82cfce48452e166dac44124ff7f | 2,140 | package com.ubayKyu.accountingSystem.repository;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import javax.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.ubayKyu.accountingSystem.entity.CategoryInfo;
import com.ubayKyu.accountingSystem.entity.UserInfo;
public interface CategoryRepository extends JpaRepository<CategoryInfo, Integer> {
@Query(value = "SELECT CategoryID, Category.UserID, Category.CreateDate, Category.CategoryName, Category.Body ,COUNT(Accounting.CategoryName) as Count"
+ " FROM AccountingNote.dbo.Category"
+ " LEFT JOIN AccountingNote.dbo.Accounting"
+ " ON Category.CategoryName = Accounting.CategoryName AND Category.UserID = Accounting.UserID"
+ " WHERE Category.UserID = ?1"
+ " GROUP BY CategoryID,Category.UserID,Category.CreateDate, Category.CategoryName, Category.Body ORDER BY Category.CreateDate DESC"
,countQuery = "SELECT count(*) FROM AccountingNote.dbo.Category WHERE Category.UserID = ?1"
,nativeQuery = true)
public Page<Map<String,Object>> category(@Param("UserID")String userID, Pageable pageable);
@Query(value = "SELECT COUNT(Accounting.CategoryName) as Count"
+ " FROM AccountingNote.dbo.Category"
+ " LEFT JOIN AccountingNote.dbo.Accounting"
+ " ON Category.CategoryName = Accounting.CategoryName AND Category.UserID = Accounting.UserID"
+ " WHERE CategoryID = ?1", nativeQuery = true)
public Long categoryCount(int id);
@Query(value = "SELECT CATEGORYNAME FROM CATEGORY WHERE USERID = ?1", nativeQuery = true)
public List<String> ListOfcategoryName(String userID);
@Modifying
@Transactional
@Query(value = "DELETE FROM CATEGORY WHERE USERID = ?1", nativeQuery = true)
public void deleteUser(String userID);
}
| 45.531915 | 152 | 0.768224 |
ceeb21bdd0c5f8586162ec17f7a44d1d142d55e4 | 1,137 | package org.knowm.xchange.gatecoin.dto.marketdata;
import static org.assertj.core.api.Assertions.assertThat;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import org.junit.Test;
import org.knowm.xchange.gatecoin.dto.marketdata.Results.GatecoinTickerResult;
/** Test GatecoinTicker JSON parsing */
public class TickerJSONTest {
@Test
public void testUnmarshal() throws IOException {
// Read in the JSON from the example resources
InputStream is =
TickerJSONTest.class.getResourceAsStream(
"/org/knowm/xchange/gatecoin/dto/marketdata/example-ticker-data.json");
ObjectMapper mapper = new ObjectMapper();
GatecoinTickerResult gatecoinTickerResult = mapper.readValue(is, GatecoinTickerResult.class);
GatecoinTicker[] gatecoinTicker = gatecoinTickerResult.getTicker();
// Verify that the example data was unmarshalled correctly
assertThat(gatecoinTicker[0].getLast()).isEqualTo(new BigDecimal("241.58"));
assertThat(gatecoinTicker[0].getHigh()).isEqualTo(new BigDecimal("243.17"));
}
}
| 35.53125 | 97 | 0.76869 |
43ad8554bbd0917fe0e28f7d0aa3c0c5f43fe4cf | 2,308 | /*
* Copyright 2005 Joe Walker
*
* 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.directwebremoting.jaxer.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.directwebremoting.extend.Creator;
import org.directwebremoting.extend.EnginePrivate;
import org.directwebremoting.impl.DefaultRemoter;
/**
* This is a customization of {@link DefaultRemoter} which is needed because
* DWR+Jaxer has a different definition of scriptName than plain vanilla DWR
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class JaxerRemoter extends DefaultRemoter
{
/* (non-Javadoc)
* @see org.directwebremoting.Remoter#generateInterfaceScript(java.lang.String, java.lang.String)
*/
@Override
public String generateInterfaceScript(String fullCreatorName, boolean includeDto, String contextServletPath) throws SecurityException
{
Creator creator = creatorManager.getCreator(fullCreatorName, false);
if (creator == null)
{
log.warn("Failed to find creator using: " + fullCreatorName);
throw new SecurityException("Failed to find creator");
}
String scriptName = creator.getJavascript();
StringBuilder buffer = new StringBuilder();
if (includeDto)
buffer.append(createParameterDefinitions(scriptName));
buffer.append(EnginePrivate.getEngineInitScript());
buffer.append(createClassDefinition(scriptName));
buffer.append(createPathDefinition(scriptName, contextServletPath));
buffer.append(createMethodDefinitions(fullCreatorName));
return buffer.toString();
}
/**
* The log stream
*/
private static final Log log = LogFactory.getLog(JaxerRemoter.class);
}
| 36.634921 | 137 | 0.725737 |
a0d01be5ea7e3cc3e0a7b33eac5121e526723692 | 1,401 | package com.example.TaskManager.services;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.example.TaskManager.entities.Task;
import com.example.TaskManager.entities.User;
import com.example.TaskManager.repositories.UserRepository;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private PasswordEncoder passwordEncoder;
@Transactional
public void addTask(Task task, long id) {
Optional<User> user = userRepository.findById(id);
if (user.isPresent()) {
user.get().addTask(task);
System.out.println(user.get());
}
}
public Iterable<User> getAllUsers() {
return userRepository.findAll();
}
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
public User updateUser(User user) {
return userRepository.save(user);
}
public User findUserByUserName(String username) {
User user = userRepository.findByUsername(username);
return user;
}
public User registerUser(User user) {
user.setPassword(passwordEncoder.encode(user.getPassword()));
user.setRoles("ROLE_USER");
return userRepository.save(user);
}
}
| 23.745763 | 68 | 0.768023 |
0bcf52f9caf2bf922acc83d4763a1d27a18d62b3 | 223 | package de.xehpuk.disassembler.codes;
/**
*
* @author xehpuk
*/
public class DStore2 extends DStoreAbstract {
protected DStore2() {
super(2);
}
@Override
public OpCode getOpCode() {
return OpCode.DSTORE_2;
}
} | 13.9375 | 45 | 0.690583 |
5f47adf24dc9002de80d5cc53a0953bec3a641cf | 5,847 | package org.morsi.android.nethack.redux.trackers;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.text.TextUtils;
import android.text.style.TypefaceSpan;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.morsi.android.nethack.redux.GameTrackerActivity;
import org.morsi.android.nethack.redux.R;
import org.morsi.android.nethack.redux.dialogs.LevelDialog;
import org.morsi.android.nethack.redux.util.AndroidMenu;
import org.morsi.android.nethack.redux.util.Level;
import java.util.ArrayList;
public class LevelTracker {
ArrayList<Level> levels;
GameTrackerActivity activity;
public LevelTracker(GameTrackerActivity activity){
this.activity = activity;
levels = new ArrayList<Level>();
}
public void onCreate() {
restorePrefs();
updateOutput();
}
public void newTrackerPopup(){
editing_level = null;
activity.showDialog(AndroidMenu.DIALOG_LEVEL_ID);
}
public void reset(){
levels.clear();
storeFields();
removeAllViews();
}
private boolean hasLevel(String id){
for(Level l : levels)
if(l.id().equals(id))
return true;
return false;
}
private void removeLevel(String id){
ArrayList<Level> to_remove = new ArrayList<Level>();
for(Level l : levels)
if(l.id().equals(id))
to_remove.add(l);
for(Level l : to_remove)
levels.remove(l);
}
public void addLevel(Level level){
if(hasLevel(level.id()))
removeLevel(level.id());
levels.add(level);
}
///
private LinearLayout levelsList(){
return (LinearLayout)activity.findViewById(R.id.levels_list);
}
///
// store values persistently
public static final String PREFS_NAME = "LevelTrackerValues";
private SharedPreferences sharedPrefs(){
return activity.getSharedPreferences(PREFS_NAME, 0);
}
private String levelsPref(){ return sharedPrefs().getString("levels", ""); }
public void restorePrefs() {
for(String level : levelsPref().split(",")) {
if(!level.equals(""))
levels.add(Level.extract(level));
}
}
private String levelsStr(){
ArrayList<String> lvls = new ArrayList<String>();
for(Level l : levels)
lvls.add(l.compact());
return TextUtils.join(",", lvls);
}
public void storeFields(){
SharedPreferences.Editor editor = sharedPrefs().edit();
editor.putString("levels", levelsStr());
editor.commit();
}
private void removeAllViews(){
levelsList().removeAllViews();
}
public void updateOutput(){
removeAllViews();
for(Level l : levels)
displayLevel(l);
}
private void displayLevel(Level level){
LinearLayout layout = new LinearLayout(activity);
TextView level_tv = new TextView(activity);
TextView attrs_tv = new TextView(activity);
ImageView remove = new ImageView(activity);
level_tv.setText(level.id());
attrs_tv.setText(level.toString());
remove.setBackgroundResource(R.drawable.minus);
level_tv.setTypeface(null, Typeface.BOLD);
level_tv.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.15f));
attrs_tv.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 0.8f));
remove.setLayoutParams(new LinearLayout.LayoutParams(0, 30, 0.05f));
level_tv.setPadding(10, 0, 0, 0);
remove.setPadding(0, 0, 10, 0);
EditLevelListener edit_listener = new EditLevelListener(level);
RemoveLevelListener remove_listener = new RemoveLevelListener(layout, level);
level_tv.setOnClickListener(edit_listener);
attrs_tv.setOnClickListener(edit_listener);
remove.setOnClickListener(remove_listener);
layout.addView(level_tv);
layout.addView(attrs_tv);
layout.addView(remove);
levelsList().addView(layout);
ImageView seperator = new ImageView(activity);
seperator.setBackgroundResource(R.drawable.divider);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 10, 0, 20);
seperator.setLayoutParams(params);
seperator.setPadding(0, 2, 0, 2);
levelsList().addView(seperator);
remove_listener.seperator_to_remove = seperator;
}
public Level editing_level;
class EditLevelListener implements Button.OnClickListener {
Level level_to_edit;
EditLevelListener(Level level) {
level_to_edit = level;
}
public void onClick(View v) {
editing_level = level_to_edit;
activity.showDialog(AndroidMenu.DIALOG_LEVEL_ID);
}
}
class RemoveLevelListener implements Button.OnClickListener {
LinearLayout level_view_to_remove;
Level level_to_remove;
ImageView seperator_to_remove;
RemoveLevelListener(LinearLayout level_view, Level level) {
level_view_to_remove = level_view;
level_to_remove = level;
seperator_to_remove = null;
}
public void onClick(View v) {
levels.remove(level_to_remove);
levelsList().removeView(level_view_to_remove);
if(seperator_to_remove != null) levelsList().removeView(seperator_to_remove);
storeFields();
}
}
}
| 29.831633 | 152 | 0.656063 |
df2f5ba01bf0aad0aa29e1661a317b985dba9478 | 1,283 | package manzilin.homework.h_08.Task5;
import java.lang.reflect.Field;
public class Converter {
public static Act convertContractToAct(Contract contract) {
if (contract != null) {
Act act = new Act(contract.getNumber(), contract.getList(), contract.getDate());
return act;
} else {
throw new IllegalArgumentException("Нельзя превратить неправильный договор в акт");
}
}
public static Act anotherConvertContractToAct(Contract contract) {
if (contract != null) {
Act act = new Act();
try {
Field[] fields = Contract.class.getDeclaredFields();
Field[] fieldsAct = Act.class.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
fields[i].setAccessible(true);
fieldsAct[i].setAccessible(true);
Object value = fields[i].get(contract);
fieldsAct[i].set(act, value);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return act;
} else {
throw new IllegalArgumentException("Нельзя превратить неправильный договор в акт");
}
}
}
| 29.837209 | 95 | 0.548714 |
451fe699cf15212878e71c730d5ee41bfb2f8d67 | 2,321 | package br.com.luizalabs.controllers;
import br.com.luizalabs.adapters.AnnouncementAdapter;
import br.com.luizalabs.controllers.entities.AnnouncementDTO;
import br.com.luizalabs.controllers.entities.ProcessingStatusTypeDTO;
import br.com.luizalabs.entities.Announcement;
import br.com.luizalabs.usecases.AnnouncementUseCase;
import br.com.luizalabs.usecases.exceptions.AnnouncementNotFoundException;
import br.com.luizalabs.usecases.exceptions.AnnouncementProcessedException;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.annotation.*;
import javax.validation.Valid;
import java.util.Optional;
@Controller("/announcements")
public class AnnouncementController {
private AnnouncementAdapter announcementAdapter;
private AnnouncementUseCase announcementUseCase;
public AnnouncementController(AnnouncementAdapter announcementAdapter, AnnouncementUseCase announcementUseCase) {
this.announcementAdapter = announcementAdapter;
this.announcementUseCase = announcementUseCase;
}
@Post
public HttpResponse save(@Body @Valid AnnouncementDTO input) {
AnnouncementDTO announcementDTO = input.toBuilder()
.dateTimeOfSending(null)
.status(ProcessingStatusTypeDTO.TO_PROCESS)
.build();
Announcement announcement = announcementAdapter.convertFromInput(announcementDTO);
AnnouncementDTO output = announcementUseCase.save(announcement);
return HttpResponse.created(output);
}
@Get(value = "/{id}")
public HttpResponse findById(Long id) {
Optional<AnnouncementDTO> optional = announcementUseCase.find(id);
if (optional.isPresent()) {
return HttpResponse.ok(optional.get());
}
return HttpResponse.notFound();
}
@Delete(value = "/{id}")
public HttpResponse delete(long id) {
try {
announcementUseCase.delete(id);
} catch (AnnouncementNotFoundException e) {
return HttpResponse.notFound();
} catch (AnnouncementProcessedException e) {
return HttpResponse
.status(HttpStatus.CONFLICT)
.body("Can't delete, the announcement was processed");
}
return HttpResponse.ok();
}
}
| 37.435484 | 117 | 0.717794 |
6cdc5e100a436f7693724df9008fd4c881e40c4f | 7,376 | package com.ibm.javaone2016.demo.furby.sensor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import com.ibm.javaone2016.demo.furby.AbstractSensor;
import com.ibm.javaone2016.demo.furby.sensor.FurbyMotionController.TestAction;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.GpioPinDigitalOutput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.PinState;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
public class FurbyMotionController {
final GpioController gpio;
final GpioPinDigitalInput home;
final GpioPinDigitalOutput forwardPin;
final GpioPinDigitalOutput backwardPin;
int counter=-1;
boolean atHome=false;
boolean seeking=false;
BlockingQueue<Action> actions = new ArrayBlockingQueue<>(1024);
public FurbyMotionController() {
gpio = GpioFactory.getInstance();
home = gpio.provisionDigitalInputPin(RaspiPin.GPIO_07, PinPullResistance.PULL_DOWN);
home.setShutdownOptions(true);
home.addListener(new GpioPinListenerDigital() {
@Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event) {
System.out.println(" --> GPIO PIN STATE CHANGE: " + event.getPin() + " = " + event.getState());
if(event.getState()==PinState.HIGH) {
atHome=true;
if(seeking) {
counter=0;
seeking=false;
setOff();
}
}
}
});
forwardPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "MyLED", PinState.LOW);
backwardPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "MyLED", PinState.LOW);
// set shutdown state for this pin
forwardPin.setShutdownOptions(true, PinState.LOW);
backwardPin.setShutdownOptions(true, PinState.LOW);
drive();
}
private void pause(long time) {
try {
counter+=time;
Thread.sleep(time);
// System.out.println(">"+counter);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setForwards() {
setOff();
forwardPin.high();
backwardPin.low();
}
private void setBackwards() {
setOff();
forwardPin.low();
backwardPin.high();
}
private void setOff() {
forwardPin.low();
backwardPin.low();
}
private void setup() {
if(counter<0) {
// need to be configured.
// move until home reached
actions.add(new Action(){
@Override
public void execute() {
while(!atHome) {
setForwards();
pause(100);
}
}});
}
}
public void sleep() {
setup();
moveTo(100);
}
private void drive() {
Thread r=new Thread(new Runnable() {
@Override
public void run() {
while(true) {
Action a;
try {
a = actions.take();
AbstractSensor.LOG.info("action {}",a.getClass().getName());
a.execute();
AbstractSensor.LOG.info("action completed");
setOff();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
r.start();
}
private void moveTo(final long i) {
actions.add(new Action(){
@Override
public void execute() {
long l=i;
if(l<0) {
l=l*-1;
setBackwards();
}
else {
setForwards();
}
pause(l);
setOff();
}});
}
public void wake() {
setup();
moveTo(200);
drive();
}
public static void main(String[] args) {
FurbyMotionController furby=new FurbyMotionController();
BufferedReader br = null;
// Refer to this http://www.mkyong.com/java/how-to-read-input-from-$
// for JDK 1.6, please use java.io.Console class to read system inp$
br = new BufferedReader(new InputStreamReader(System.in));
while (true) {
System.out.print("Enter something : ");
try {
String input = br.readLine();
long then=System.currentTimeMillis();
switch(input) {
case "q" :
System.exit(0);
break;
case "f" :
furby.moveTo(100);
break;
case "b" :
furby.moveTo(-100);
break;
case "h" :
furby.goHome();
break;
case "c" :
furby.calibrate();
break;
case "s" :
furby.speak();
break;
case "t" :
for(int i=0;i<5;i++){
furby.speak();
}
break;
}
long now=System.currentTimeMillis();
System.out.println("took "+(now-then));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void speak() {
goHome();
setForwards();
moveTo(200);
pause(100);
moveTo(200);
pause(100);
moveTo(-200);
pause(100);
moveTo(-200);
pause(100);
moveTo(-200);
}
private void calibrate() {
goHome();
for(int i=0;i<10;i++) {
long start=System.currentTimeMillis();
seek();
long now=System.currentTimeMillis();
long diff=now-start;
System.out.println(""+diff);
}
}
private void seek() {
// drive forwards until at home
setForwards();
goHome();
}
public static interface Action {
void execute();
}
public class TestAction implements Action {
@Override
public void execute() {
setForwards();
pause(2000);
System.out.println("forwards completed");
setBackwards();
pause(2000);
System.out.println("backwards completed");
setOff();
}
}
public class Chat implements Action {
private char[] chat;
public Chat(String chat) {
this.chat=chat.toCharArray();
}
@Override
public void execute() {
for(char c:chat) {
switch(c) {
case 'h' :
goHome();
break;
case 'f' :
setForwards();
pause(100);
break;
case 'b' :
setBackwards();
pause(100);
break;
case 'p' :
pause(100);
break;
}
}
setOff();
}
}
public class Talk implements Action {
private int turns=0;
public Talk(int seconds) {
turns=seconds;
}
@Override
public void execute() {
while(turns>0) {
turns--;
speak();
}
}
}
public class PauseAction implements Action {
private long time;
public PauseAction(long milliseconds) {
this.time=milliseconds;
}
@Override
public void execute() {
setOff();
pause(time);
}
}
public class GoHomeAction implements Action {
@Override
public void execute() {
seeking=true;
setForwards();
while(!atHome) {
pause(100);
}
System.out.println("at home");
}
}
public class OpenMouthAction implements Action {
private long time;
public OpenMouthAction(long milliseconds) {
this.time=milliseconds;
}
@Override
public void execute() {
System.out.println("mouth for "+time);
setForwards();
pause(time);
}
}
public void run(List<Action> incoming) {
actions.addAll(incoming);
}
public void goHome() {
actions.add(new GoHomeAction());
}
public void run(Action testAction) {
actions.add(testAction);
}
}
| 18.86445 | 102 | 0.620933 |
aa9c6517e37aefa370c2d8c28b0b1bcc069be9b6 | 183 | package eapli.base.gestaomensagens.protocolo;
import eapli.base.gestaomensagens.dominio.Mensagem;
public interface IDescodificar {
Mensagem descodificarMensagem(byte[] data);
}
| 22.875 | 51 | 0.814208 |
5de34fb2efc444d19bf96adc83904856251596ef | 318 | package org.cloudfoundry.autoscaler.exceptions;
public class NoAttachedPolicyException extends Exception{
/**
*
*/
private static final long serialVersionUID = -2621595520272413555L;
public NoAttachedPolicyException(){
super();
}
public NoAttachedPolicyException(String message){
super(message);
}
}
| 19.875 | 68 | 0.767296 |
ed5e1edaeb7f66b6ba46152d69e22834123a7ea7 | 211 | // camel-k:
import org.apache.camel.builder.RouteBuilder;
public class MyRoutes extends RouteBuilder {
@Override
public void configure() throws Exception {
from("timer:tick")
.log("Hello Camel K!");
}
} | 21.1 | 45 | 0.720379 |
95835ad2fcb78f49a0d96193918f0870031af4ca | 1,507 | /*
* Copyright (c) 2004 - 2012 Eike Stepper (Berlin, Germany) and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Simon McDuff - initial API and implementation
* Eike Stepper - maintenance
*/
package org.eclipse.emf.cdo.common.revision;
import org.eclipse.emf.common.util.EList;
import org.eclipse.net4j.util.collection.MoveableList;
/**
* A {@link MoveableList moveable} {@link EList}.
*
* @author Simon McDuff
* @since 2.0
* @noextend This interface is not intended to be extended by clients.
* @noimplement This interface is not intended to be implemented by clients.
* @apiviz.uses {@link CDOElementProxy} - - contains
*/
public interface CDOList extends MoveableList<Object>, EList<Object>
{
/**
* Returns the element at position index of this list and optionally resolves proxies (see CDOElementProxy).
* <p>
*
* @param index
* The position of the element to return from this list.
* @param resolve
* A value of <code>false</code> indicates that {@link CDORevisionUtil#UNINITIALIZED} may be returned for
* unresolved elements. A value of <code>true</code> indicates that it should behave identical to
* {@link CDOList#get(int)}.
*/
public Object get(int index, boolean resolve);
}
| 36.756098 | 116 | 0.708693 |
ee2a5323920b798e694d12ebc412587e652b96fa | 3,904 |
package org.traccar.ORM;
import javax.ws.rs.WebApplicationException;
import java.beans.Introspector;
import java.sql.SQLException;
import org.traccar.database.QueryBuilder;
import org.traccar.Context;
import java.util.*;
public class Query {
private String query;
private String table;
private Class<?> clazz;
private Map<String, Object> queryParams = new LinkedHashMap<>();
public Query(Class<?> clazz) {
this.clazz = clazz;
this.table = getObjectsTableName(clazz);
this.query = "";
}
private String getObjectsTableName(Class<?> baseModel) {
String result = "tc_" + Introspector.decapitalize(baseModel.getSimpleName());
if (!result.endsWith("s")) {result += "s";}
return result;
}
public Query select(String... columns) {
query = "SELECT ";
for(String column : columns){query += column + ", ";}
query = query.substring(0, query.length() - 2);
query += " FROM " + table;
return this;
}
public Query where(String column, Object value) {
if (query.contains("WHERE")) {
query += " AND " + column + " = :" + column;
} else {
query += " WHERE " + column + " = :" + column;
}
queryParams.put(column, value);
return this;
}
public Query where(String column, String operator, Object value) {
if (query.contains("WHERE")) {
query += " AND " + column + " " + operator + " :" + column;
} else {
query += " WHERE " + column + " " + operator + " :" + column;
}
queryParams.put(column, value);
return this;
}
public <T> Collection<T> get() {
try {
if (!query.contains("SELECT")) {
query = "SELECT * FROM " + table + query;
}
QueryBuilder qb = QueryBuilder.create(Context.getDataManager().getDataSource(), query);
for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
qb = qb.setGeneric(entry.getKey(), entry.getValue());
}
return qb.executeQuery((Class<T>) clazz);
} catch (SQLException e) {throw new WebApplicationException(e);}
}
public <T> T first() {
try {
if (!query.contains("SELECT")) {
query = "SELECT * FROM " + table + query;
}
QueryBuilder qb = QueryBuilder.create(Context.getDataManager().getDataSource(), query);
for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
qb = qb.setGeneric(entry.getKey(), entry.getValue());
}
return qb.executeQuerySingle((Class<T>) clazz);
} catch (SQLException e) {throw new WebApplicationException(e);}
}
public <T> Collection<T> delete() {
try {
query = "DELETE FROM " + table + query;
QueryBuilder qb = QueryBuilder.create(Context.getDataManager().getDataSource(), query);
for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
qb = qb.setGeneric(entry.getKey(), entry.getValue());
}
return qb.executeQuery((Class<T>) clazz);
} catch (SQLException e) {throw new WebApplicationException(e);}
}
public <T> Collection<T> update() {
try {
if (!query.contains("SELECT")) {
query = "SELECT * FROM " + table + query;
}
QueryBuilder qb = QueryBuilder.create(Context.getDataManager().getDataSource(), query);
for (Map.Entry<String, Object> entry : queryParams.entrySet()) {
qb = qb.setGeneric(entry.getKey(), entry.getValue());
}
return qb.executeQuery((Class<T>) clazz);
} catch (SQLException e) {throw new WebApplicationException(e);}
}
}
| 35.816514 | 99 | 0.556352 |
69fb0efebb5f49ade2d778c30dfb3caf00365283 | 1,207 | package services;
import util.APIGateway;
import entities.Group;
import entities.User;
import java.util.UUID;
/**
* Class for requests to group_members.svc and group_member.svc
*
*/
public class GroupMembersService
extends APIGateway {
/**
* Gets or sets url to GroupMembers service.
*/
protected static String groupMembersUrl;
/**
* Gets or sets url to GroupMember service.
*/
protected static String groupMemberUrl;
static {
groupMembersUrl = provisioningAPIUrlPrefix + "group_members.svc/%s";
groupMemberUrl = provisioningAPIUrlPrefix + "group_member.svc/%s/member/%s";
}
/**
* Adds users to group.
*
* @param groupGuid Group Guid.
* @param users Array of users.
*
* @return Array of added users.
*/
public static User[] addGroupMembers(UUID groupGuid, User[] users) {
return httpPost(String.format(groupMembersUrl, groupGuid), "application/json", users );
}
/**
* Deletes user from group.
*
* @param groupGuid Group Guid.
* @param userEmail Email of deleted group member.
*/
public static void deleteGroupMember(UUID groupGuid, String userEmail) {
httpDelete(String.format(groupMemberUrl, groupGuid, userEmail), Group.class);
}
}
| 21.945455 | 89 | 0.715824 |
eaa0d6a5e603205626241167b1cf0560ce6cc7e1 | 227 | package cn.luo.yuan.maze.model.skill;
/**
* Created by gluo on 4/27/2017.
*/
public interface MountAble {
boolean isMounted();
void mount();
void unMount();
boolean canMount(SkillParameter parameter);
}
| 15.133333 | 47 | 0.660793 |
25c60bb10c493f2e3c7a5ffe607a58c63f1091dc | 893 | package org.spacebits.components.sensors;
import org.spacebits.components.TypeInfo;
public class SensorProfile {
private TypeInfo sensorType;
private double signalThreshold;
private double signalGain;
public SensorProfile(TypeInfo sensorType, double signalThreshold,
double signalGain) {
super();
this.sensorType = sensorType;
this.signalThreshold = signalThreshold;
this.signalGain = signalGain;
}
public TypeInfo getSensorType() {
return sensorType;
}
public void setSensorType(TypeInfo sensorType) {
this.sensorType = sensorType;
}
public double getSignalThreshold() {
return signalThreshold;
}
public void setSignalThreshold(double signalThreshold) {
this.signalThreshold = signalThreshold;
}
public double getSignalGain() {
return signalGain;
}
public void setSignalGain(double signalGain) {
this.signalGain = signalGain;
}
}
| 16.849057 | 66 | 0.760358 |
91622788043b61d4ef34eadd01abc688a6e0040c | 223 | package ru.podstavkov.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/")
public class MainController {
}
| 20.272727 | 62 | 0.816143 |
3d4af4f35f06eafb4f19111cf713936365632423 | 4,758 | /**
* SiteJournalDealsInfoStruct.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.stats.aggregator.allegroobj.containers;
public class SiteJournalDealsInfoStruct implements java.io.Serializable {
private int dealEventsCount;
private long dealLastEventTime;
public SiteJournalDealsInfoStruct() {
}
public SiteJournalDealsInfoStruct(
int dealEventsCount,
long dealLastEventTime) {
this.dealEventsCount = dealEventsCount;
this.dealLastEventTime = dealLastEventTime;
}
/**
* Gets the dealEventsCount value for this SiteJournalDealsInfoStruct.
*
* @return dealEventsCount
*/
public int getDealEventsCount() {
return dealEventsCount;
}
/**
* Sets the dealEventsCount value for this SiteJournalDealsInfoStruct.
*
* @param dealEventsCount
*/
public void setDealEventsCount(int dealEventsCount) {
this.dealEventsCount = dealEventsCount;
}
/**
* Gets the dealLastEventTime value for this SiteJournalDealsInfoStruct.
*
* @return dealLastEventTime
*/
public long getDealLastEventTime() {
return dealLastEventTime;
}
/**
* Sets the dealLastEventTime value for this SiteJournalDealsInfoStruct.
*
* @param dealLastEventTime
*/
public void setDealLastEventTime(long dealLastEventTime) {
this.dealLastEventTime = dealLastEventTime;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof SiteJournalDealsInfoStruct)) return false;
SiteJournalDealsInfoStruct other = (SiteJournalDealsInfoStruct) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
this.dealEventsCount == other.getDealEventsCount() &&
this.dealLastEventTime == other.getDealLastEventTime();
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
_hashCode += getDealEventsCount();
_hashCode += new Long(getDealLastEventTime()).hashCode();
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(SiteJournalDealsInfoStruct.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://webapi.allegro.pl/service.php", "SiteJournalDealsInfoStruct"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("dealEventsCount");
elemField.setXmlName(new javax.xml.namespace.QName("https://webapi.allegro.pl/service.php", "dealEventsCount"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "int"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("dealLastEventTime");
elemField.setXmlName(new javax.xml.namespace.QName("https://webapi.allegro.pl/service.php", "dealLastEventTime"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "long"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| 32.148649 | 130 | 0.656368 |
51de7491a150daaf5645761a423c1bec3ce40163 | 6,575 | package game.Battles;
import game.client.Button;
import game.client.states.BattleState;
import game.entities.slime.Slime;
import game.entities.slimelord.SlimeLord;
import jig.ResourceManager;
import jig.Vector;
import org.lwjgl.Sys;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import java.util.LinkedList;
public class SlimBox {
public final static String BASIC_UB = "game/client/resource/basic-upgrade.png";
public final static String MORTAR_UB = "game/client/resource/mortar-image.png";
public final static String STRIKER_UB = "game/client/resource/striker-upgrade.png";
public final static String LANCER_UB = "game/client/resource/lancer-upgrade.png";
public final static String ADVANCEDSTRIKER_UB = "game/client/resource/advanced-striker-upgrade.png";
public final static String ADVANCEDLANCER_UB = "game/client/resource/advanced-lancer-upgrade.png";
public Image basic_ub;
public Image morter_ub;
public Image striker_ub;
public Image lancer_ub;
public Image advancedstriker_ub;
public Image advancedlancer_ub;
int width = 100;
int height = 130;
Vector position;
int damage;
int cooldown;
int size;
int maxHP;
int currentHP;
int buttonWidth = 32;
boolean active = false;
Slime slime;
HealthBar healthBar;
LinkedList<String> availableUpgrades;
LinkedList<Button> upgradeButtons;
public SlimBox(){
try{
basic_ub = new Image(BASIC_UB);
morter_ub = new Image(MORTAR_UB);
lancer_ub = new Image(LANCER_UB);
striker_ub = new Image(STRIKER_UB);
advancedlancer_ub = new Image(ADVANCEDLANCER_UB);
advancedstriker_ub = new Image(ADVANCEDSTRIKER_UB);
} catch ( Exception e){
e.printStackTrace();
}
}
public SlimBox( Slime slime, SlimeLord slimeLord ){
try{
basic_ub = new Image(BASIC_UB);
morter_ub = new Image(MORTAR_UB);
lancer_ub = new Image(LANCER_UB);
striker_ub = new Image(STRIKER_UB);
advancedlancer_ub = new Image(ADVANCEDLANCER_UB);
advancedstriker_ub = new Image(ADVANCEDSTRIKER_UB);
} catch ( Exception e){
e.printStackTrace();
}
this.position = slime.getPosition();
this.maxHP = slime.maxHP;
this.currentHP = slime.currentHP;
this.damage = slime.damage;
this.cooldown = slime.currentCooldown;
this.size = slime.size;
this.healthBar = new HealthBar(position.getX()+10, position.getY()+10,
width-20, 20, currentHP, maxHP);
if( slime.clientID == slimeLord.clientID ) {
this.availableUpgrades = slime.getAvailableUpgrades(slimeLord.specialSlimes);
}
initButtons();
}
public void updateBox( Slime slime, SlimeLord slimeLord ){
this.slime = slime;
this.position = slime.getPosition();
this.maxHP = slime.maxHP;
this.currentHP = slime.currentHP;
this.damage = slime.damage;
this.cooldown = slime.currentCooldown;
this.size = slime.size;
this.healthBar = new HealthBar(position.getX()+10, position.getY()+10,
width-20, 20, currentHP, maxHP);
if( slime.clientID == slimeLord.clientID ) {
this.availableUpgrades = slime.getAvailableUpgrades(slimeLord.specialSlimes);
initButtons();
}
}
public void initButtons(){
upgradeButtons = new LinkedList<>();
for( int i = 0; i < availableUpgrades.size(); i++ ){
switch( availableUpgrades.get(i) ){
case "basic":
upgradeButtons.add(new Button((int)position.getX()+(width-buttonWidth),(int)position.getY()+(16*i)+30,
basic_ub));
break;
case "mortar":
upgradeButtons.add(new Button((int)position.getX()+(width-buttonWidth),(int)position.getY()+(16*i)+30,
morter_ub));
break;
case "striker":
upgradeButtons.add(new Button((int)position.getX()+(width-buttonWidth),(int)position.getY()+(16*i)+30,
striker_ub));
break;
case "lancer":
upgradeButtons.add(new Button((int)position.getX()+(width-buttonWidth),(int)position.getY()+(16*i)+30,
lancer_ub));
break;
case "advancedStriker":
upgradeButtons.add(new Button((int)position.getX()+(width-buttonWidth),(int)position.getY()+(16*i)+30,
advancedstriker_ub));
break;
case "advancedLancer":
upgradeButtons.add(new Button((int)position.getX()+(width-buttonWidth),(int)position.getY()+(16*i)+30,
advancedlancer_ub));
break;
default:
System.err.println("Invalid upgrade type: "+availableUpgrades.get(i));
}
}
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isActive() {
return active;
}
public void update(int x, int y){
if(!active){
return;
}
for( int i = 0; i < upgradeButtons.size(); i++ ){
if(upgradeButtons.get(i).checkClick( x, y )){
System.out.println(availableUpgrades.get(i));
slime.upgradeTo(availableUpgrades.get(i));
return;
}
}
}
public void render(Graphics g){
if(!active){
return;
}
Color c = g.getColor();
g.setColor(Color.gray);
g.fillRect(position.getX(), position.getY(), width, height);
healthBar.render(g);
g.setColor(Color.black);
g.drawString((int)healthBar.currentHealth+"/"+(int)healthBar.maxHealth,
healthBar.xpos+2, healthBar.ypos+2);
for( int i = 0; i < upgradeButtons.size(); i++ ){
upgradeButtons.get(i).render(g);
}
g.drawString("dmg:"+damage,healthBar.xpos-2, healthBar.ypos+20);
g.drawString("size:"+size,healthBar.xpos-2, healthBar.ypos+40);
g.drawString("size:"+size,healthBar.xpos-2, healthBar.ypos+40);
g.setColor(c);
}
}
| 32.230392 | 122 | 0.585399 |
76ff3bfb1cd363d626693a7bb9c0885ed9c2dc4b | 222 | package college.com.collegenetwork.dbhelper;
import android.database.sqlite.SQLiteDatabase;
/**
* Created by sushantalone on 08/06/17.
*/
public interface CommandQuery {
long executeQuery( SQLiteDatabase db );
}
| 17.076923 | 46 | 0.756757 |
e8f0bc4c67b435991f49a94b80b46a1ce33ff161 | 6,829 | package net.minecraft.client.gui;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.spectator.ISpectatorMenuObject;
import net.minecraft.client.gui.spectator.ISpectatorMenuRecipient;
import net.minecraft.client.gui.spectator.SpectatorMenu;
import net.minecraft.client.gui.spectator.categories.SpectatorDetails;
import net.minecraft.client.renderer.G;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
public class GuiSpectator extends Gui implements ISpectatorMenuRecipient {
private static final ResourceLocation widgetsResource = new ResourceLocation("textures/gui/widgets.png");
public static final ResourceLocation swidgetsResource = new ResourceLocation("textures/gui/spectator_widgets.png");
private final Minecraft minecraft;
private long time;
private SpectatorMenu spectatorMenu;
public GuiSpectator(Minecraft mcIn) {
this.minecraft = mcIn;
}
public void func_175260_a(int p_175260_1_) {
this.time = Minecraft.getSystemTime();
if (this.spectatorMenu != null) {
this.spectatorMenu.func_178644_b(p_175260_1_);
} else {
this.spectatorMenu = new SpectatorMenu(this);
}
}
private float func_175265_c() {
long i = this.time - Minecraft.getSystemTime() + 5000L;
return MathHelper.clamp_float((float) i / 2000.0F, 0.0F, 1.0F);
}
public void renderTooltip(ScaledResolution res, float partialTicks) {
if (this.spectatorMenu == null) return;
float f = this.func_175265_c();
if (f <= 0.0F) this.spectatorMenu.func_178641_d();
else {
int i = res.getScaledWidth() / 2;
float f1 = this.zLevel;
this.zLevel = -90.0F;
float f2 = (float) res.getScaledHeight() - 22.0F * f;
SpectatorDetails spectatordetails = this.spectatorMenu.func_178646_f();
this.func_175258_a(res, f, i, f2, spectatordetails);
this.zLevel = f1;
}
}
protected void func_175258_a(ScaledResolution res, float p_175258_2_, int p_175258_3_, float p_175258_4_, SpectatorDetails details) {
G.enableRescaleNormal();
G.enableBlend();
G.tryBlendFuncSeparate(770, 771, 1, 0);
G.color(1.0F, 1.0F, 1.0F, p_175258_2_);
this.minecraft.getTextureManager().bindTexture(widgetsResource);
this.drawTexturedModalRect((float) (p_175258_3_ - 91), p_175258_4_, 0, 0, 182, 22);
if (details.func_178681_b() >= 0) {
this.drawTexturedModalRect((float) (p_175258_3_ - 91 - 1 + details.func_178681_b() * 20), p_175258_4_ - 1.0F, 0, 22, 24, 22);
}
RenderHelper.enableGUIStandardItemLighting();
for (int i = 0; i < 9; ++i) {
this.func_175266_a(i, res.getScaledWidth() / 2 - 90 + i * 20 + 2, p_175258_4_ + 3.0F, p_175258_2_, details.func_178680_a(i));
}
RenderHelper.disableStandardItemLighting();
G.disableRescaleNormal();
G.disableBlend();
}
private void func_175266_a(int key, int p_175266_2_, float p_175266_3_, float p_175266_4_, ISpectatorMenuObject menuObj) {
this.minecraft.getTextureManager().bindTexture(swidgetsResource);
if (menuObj != SpectatorMenu.field_178657_a) {
int i = (int) (p_175266_4_ * 255.0F);
G.pushMatrix();
G.translate((float) p_175266_2_, p_175266_3_, 0.0F);
float f = menuObj.func_178662_A_() ? 1.0F : 0.25F;
G.color(f, f, f, p_175266_4_);
menuObj.render(f, i);
G.popMatrix();
String s = KeyBinding.HOTBAR[key].getKeyDisplayString();
if (i > 3 && menuObj.func_178662_A_()) {
this.minecraft.fontRenderer.drawStringWithShadow(s, (float) (p_175266_2_ + 19 - 2 - this.minecraft.fontRenderer.getStringWidth(s)), p_175266_3_ + 6.0F + 3.0F, 16777215 + (i << 24));
}
}
}
public void render(ScaledResolution res) {
//
// NetHandlerPlayClient nhpc = MC.getPlayer().sendQueue;
// Collection<NetworkPlayerInfo> list = nhpc.getPlayerInfoMap();
//
// Map<ScorePlayerTeam, List<NetworkPlayerInfo>> teams = new HashMap<>();
// Collection<ScorePlayerTeam> ts = MC.getWorld().getScoreboard().getTeams();
//
// for (ScorePlayerTeam t : ts) teams.put(t, new ArrayList<>());
// for (NetworkPlayerInfo playerInfo : list) {
// if (playerInfo.getPlayerTeam() != null && teams.containsKey(playerInfo.getPlayerTeam()))
// teams.get(playerInfo.getPlayerTeam()).add(playerInfo);
// }
//
//
// for (ScorePlayerTeam team : teams.keySet()) {
// String s = FontRenderer.getFormatFromString(team.getColorPrefix());
// int i = -1;
// if (s.length() >= 2) i = Minecraft.getMinecraft().fontRenderer.getColorCode(s.charAt(1));
// drawRect(0, 2, 100, 8, i);
//
// for (NetworkPlayerInfo player : teams.get(team)) {
//
//
// GameProfile gameprofile = player.getGameProfile();
//
// EntityPlayer entityplayer = MC.getWorld().getPlayerEntityByUUID(gameprofile.getId());
// MC.i().getTextureManager().bindTexture(player.getLocationSkin());
// Gui.drawScaledCustomSizeModalRect(100, 100, 8.0F, (float) 8, 8, 8, 8, 8, 64.0F, 64.0F);
//
// if (entityplayer != null && entityplayer.isWearing(EnumPlayerModelParts.HAT)) {
// Gui.drawScaledCustomSizeModalRect(100, 100, 40.0F, (float) 8, 8, 8, 8, 8, 64.0F, 64.0F);
// }
//
// }
//
// }
int i = (int) (this.func_175265_c() * 255.0F);
if (i > 3 && this.spectatorMenu != null) {
ISpectatorMenuObject ispectatormenuobject = this.spectatorMenu.func_178645_b();
String s = ispectatormenuobject != SpectatorMenu.field_178657_a ? ispectatormenuobject.getSpectatorName().getFormattedText() : this.spectatorMenu.func_178650_c().func_178670_b().getFormattedText();
if (s != null) {
int j = (res.getScaledWidth() - this.minecraft.fontRenderer.getStringWidth(s)) / 2;
int k = res.getScaledHeight() - 35;
G.pushMatrix();
G.enableBlend();
G.tryBlendFuncSeparate(770, 771, 1, 0);
this.minecraft.fontRenderer.drawStringWithShadow(s, (float) j, (float) k, 16777215 + (i << 24));
G.disableBlend();
G.popMatrix();
}
}
}
public void func_175257_a(SpectatorMenu p_175257_1_) {
this.spectatorMenu = null;
this.time = 0L;
}
public boolean func_175262_a() {
return this.spectatorMenu != null;
}
public void func_175259_b(int p_175259_1_) {
int i;
for (i = this.spectatorMenu.func_178648_e() + p_175259_1_; i >= 0 && i <= 8 && (this.spectatorMenu.func_178643_a(i) == SpectatorMenu.field_178657_a || !this.spectatorMenu.func_178643_a(
i).func_178662_A_()); i += p_175259_1_) {
}
if (i >= 0 && i <= 8) {
this.spectatorMenu.func_178644_b(i);
this.time = Minecraft.getSystemTime();
}
}
public void func_175261_b() {
this.time = Minecraft.getSystemTime();
if (this.func_175262_a()) {
int i = this.spectatorMenu.func_178648_e();
if (i != -1) {
this.spectatorMenu.func_178644_b(i);
}
} else {
this.spectatorMenu = new SpectatorMenu(this);
}
}
}
| 35.201031 | 200 | 0.700249 |
83215ca68b0cccc981a46f296d9ebb32dd029643 | 157 | package bbejeck.guava.common.model;
/**
* User: Bill Bejeck Date: 4/3/13 Time: 9:47 PM
*/
public enum Climate {
SUB_TROPICAL, TEMPERATE, DESERT, HUMID
}
| 17.444444 | 47 | 0.700637 |
68654155d759655ab3b7a241c18e895c026674f4 | 3,910 | package game;
import org.json.JSONObject;
/**
* <h1>GameController</h1>
* <p>This is a layer of abstraction between the Game Class and the ServerController.
* The Class defines a set of methods through which the ServerController can put the
* parsed information through to the game. It also defines methods to return the game
* state to the caller.</p>
*
* @version 1.0
* @since 2021-08-03
* @apiNote MAEDN 3.0
*/
public interface GameController {
/**
* <h1><i>register</i></h1>
* <p>This method generates a new player and assigns a color to that player.
* It also checks if there are 4 players and if so just returns null without creating a
* actual player.</p>
* @param requestedColor - PlayerColor can either be null or a requested color
* @param name - String with the name of the player
* @param clientName - String with the name of the client
* @param clientVersion - Float with the version of the client
* @return PlayerColor - returns the selected color for the player
*/
public PlayerColor register(PlayerColor requestedColor, String name, String clientName, Float clientVersion);
/**
* <h1><i>remove</i></h1>
* <p>This method removes a player from the game. It does not matter if the game
* is already running or not, since it is just going to replace the player with
* a BOT while running or replacing the player with a new one while queuing.
* It does also make the color of the player available again.</p>
* @param color - PlayerColor of the removed player
*/
public void remove(PlayerColor color);
/**
* <h1><i>ready</i></h1>
* <p>This Constructor saves the socket object of the client the
* thread is getting created for and the ServerController object for
* interaction with game logic.</p>
* @param color - PlayerColor of the client that is ready
* @param isReady - Boolean if player is ready or not
* @return Boolean - returns true if all players are ready; false otherwise
*/
public Boolean ready(PlayerColor color, Boolean isReady);
/**
* <h1><i>getState</i></h1>
* <p>This method returns the current game state.</p>
* @return gameState - returns the current game state
*/
public GameState getState();
/**
* <h1><i>currentPlayer</i></h1>
* <p>This method returns the current player in the game logic.</p>
* @return PlayerColor - color of the current player
*/
public PlayerColor currentPlayer();
/**
* <h1><i>currentPlayerIsBot</i></h1>
* <p>This method returns false if the current player is type player
* and true if the current player on the other hand is type BOT.</p>
* @return Boolean - true if current player is BOT; else false
*/
public Boolean currentPlayerIsBot();
/**
* <h1><i>toJSON</i></h1>
* <p>This method is like a toString() and returns the current game state and all players
* with their attributes and figure positions as JSON. It supports the MAEDN protocol
* and is the main way to update the board on the client.</p>
* @return JSONObject - returns the game as JSON
*/
public JSONObject toJSON();
/**
* <h1><i>turn</i></h1>
* <p>This method has two modes:
* Dry run, which is called with null and returns the turn options for
* the current player and second, execute, which is called by an integer starting with
* -1 up to the amount of turn options. After execution it returns OK for successful or finished, if
* the player won the game.</p>
* @param selected - Integer with the selected option or null
* @return JSONObject - returns the turn as JSON or if execute was successful
*/
public JSONObject turn(Integer selected);
/**
* <h1><i>botTurn</i></h1>
* <p>This method executes the turn for the current player automatically and also sets the next player
* in line, after it is finished.</p>
* @param millis - long is the amount of time the turn is going to take in milliseconds
*/
public void botTurn(long millis);
}
| 38.333333 | 110 | 0.710742 |
156f72760663a87ea4fbccff55516ac6e3127c5a | 1,046 | package de.maikmerten.quaketexturetool;
import java.awt.image.IndexColorModel;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author maik
*/
public class PaletteQ1 {
public final static int[] colors;
public final static int fullbrightStart = 224;
public final static IndexColorModel indexColorModel;
static {
colors = new int[256];
byte[] r = new byte[256];
byte[] g = new byte[256];
byte[] b = new byte[256];
InputStream is = PaletteQ1.class.getClassLoader().getResourceAsStream("palette.lmp");
for (int i = 0; i < colors.length; ++i) {
try {
int r_val = is.read();
int g_val = is.read();
int b_val = is.read();
r[i] = (byte) r_val;
g[i] = (byte) g_val;
b[i] = (byte) b_val;
colors[i] = Color.getRGB(r_val, g_val, b_val);
} catch (IOException ex) {
Logger.getLogger(PaletteQ1.class.getName()).log(Level.SEVERE, null, ex);
}
}
indexColorModel = new IndexColorModel(8, 256, r, g, b);
}
}
| 21.791667 | 87 | 0.660612 |
a1f4f45c0b93e235964d1fcf1c38a4a178b6d668 | 3,541 | package de.gg.game.input;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.math.collision.Ray;
import com.google.common.eventbus.EventBus;
import de.damios.guacamole.gdx.DefaultInputProcessor;
import de.gg.game.events.HouseEnterEvent;
import de.gg.game.events.HouseSelectionEvent;
import de.gg.game.model.World;
public class MapSelectionInputController implements DefaultInputProcessor {
private int selectionButton = Buttons.LEFT;
private EventBus eventBus;
private PerspectiveCamera camera;
private short clickedObjectId = -1;
private short newSelectionId = -1;
private short selectedObjectID = -1;
private long lastClickTime = -1;
private static final long DOUBLE_CLICK_TIME = 300;
private World world;
private int clickX, clickY;
public MapSelectionInputController(EventBus bus, PerspectiveCamera camera) {
this.eventBus = bus;
this.camera = camera;
}
public void update() {
if (newSelectionId >= 0) {
if (System.currentTimeMillis()
- lastClickTime > DOUBLE_CLICK_TIME) {
// Einzelklick
onSingleSelection(newSelectionId);
newSelectionId = -1;
}
}
}
@Override
public boolean touchDown(int screenX, int screenY, int pointer,
int button) {
if (button == selectionButton) {
clickedObjectId = getObjectAtPositon(screenX, screenY);
this.clickX = screenX;
this.clickY = screenY;
return clickedObjectId >= 0;
} else {
return false;
}
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return clickedObjectId >= 0;
}
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if (button == selectionButton) {
if (clickedObjectId >= 0) { // Wenn auf Objekt geklickt
if (clickedObjectId == getObjectAtPositon(screenX, screenY)) {
if (System.currentTimeMillis()
- lastClickTime <= DOUBLE_CLICK_TIME) {
if (clickedObjectId == newSelectionId) {
// Doppelklick
onDoubleSelection(newSelectionId);
newSelectionId = -1;
}
} else {
newSelectionId = clickedObjectId;
lastClickTime = System.currentTimeMillis();
}
}
clickedObjectId = -1;
return true;
} else { // Wenn neben Objekt geklickt
resetSelection(); // Altes Objekt deselektieren
}
}
return false;
}
private void onDoubleSelection(int value) {
eventBus.post(new HouseEnterEvent((short) value));
}
public void resetSelection() {
onSingleSelection((short) -1);
}
private void onSingleSelection(short value) {
// Altes Objekt reseten
if (selectedObjectID >= 0) {
world.getBuildingSlots()[selectedObjectID].getBuilding()
.getRenderData().isSelected = false;
}
// Neues Objekt markieren
selectedObjectID = value;
if (selectedObjectID >= 0) {
world.getBuildingSlots()[selectedObjectID].getBuilding()
.getRenderData().isSelected = true;
}
eventBus.post(
new HouseSelectionEvent(selectedObjectID, clickX, clickY));
}
private short getObjectAtPositon(int screenX, int screenY) {
Ray ray = camera.getPickRay(screenX, screenY);
short result = -1;
float distance = -1;
for (short i = 0; i < world.getBuildingSlots().length; ++i) {
final float dist2 = world.getBuildingSlots()[i].getBuilding()
.getRenderData().intersects(ray);
if (dist2 >= 0f && (distance < 0f || dist2 <= distance)) {
result = i;
distance = dist2;
}
}
return result;
}
public void setWorld(World world) {
this.world = world;
}
}
| 25.47482 | 77 | 0.704603 |
a655af0a3da3549e1ad8113f0f1f63230687544a | 500 | package com.leboro.util.game;
import com.leboro.MainActivity;
import com.leboro.R;
import com.leboro.model.api.live.overview.LiveGameOverview;
public class GameUtil {
public static String getGamePeriodString(int quarter) {
if (quarter > 4) {
return MainActivity.context.getString(R.string.game_attr_overtime_res) + String
.valueOf(quarter - 4);
}
return quarter + MainActivity.context.getString(R.string.game_attr_quarter_res);
}
}
| 27.777778 | 91 | 0.694 |