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 |
|---|---|---|---|---|---|
094968a972320af44c455a1cfbcb1bfd210de7e7 | 128 | package com.github.bottlemc.blade;
public interface IScreenInterface {
void openBlankGui();
void closeBlankGui();
}
| 12.8 | 35 | 0.726563 |
9de81b47889971b4411b08198cfc3a09a1c7450a | 9,698 | /*
* Copyright (c) 2020 Tobias Briones. All rights reserved.
*
* SPDX-License-Identifier: MIT
*
* This file is part of Example Project: Factura.
*
* This source code is licensed under the MIT License found in the
* LICENSE file in the root directory of this source tree or at
* https://opensource.org/licenses/MIT.
*/
package io.github.tobiasbriones.ep.factura.ui.mainbilling;
import io.github.tobiasbriones.ep.factura.data.CityDao;
import io.github.tobiasbriones.ep.factura.data.CommunityDao;
import io.github.tobiasbriones.ep.factura.data.ProductDao;
import io.github.tobiasbriones.ep.factura.domain.model.basket.BasketModel;
import io.github.tobiasbriones.ep.factura.domain.model.bill.BillAccessor;
import io.github.tobiasbriones.ep.factura.domain.model.bill.BillModel;
import io.github.tobiasbriones.ep.factura.domain.model.bill.BillMutator;
import io.github.tobiasbriones.ep.factura.domain.model.customer.CustomerModel;
import io.github.tobiasbriones.ep.factura.domain.model.customer.CustomerNameAccessor;
import io.github.tobiasbriones.ep.factura.domain.usecase.PrintBillUseCase;
import io.github.tobiasbriones.ep.factura.io.Printer;
import io.github.tobiasbriones.ep.factura.ui.core.SwingComponent;
import io.github.tobiasbriones.ep.factura.ui.mainbilling.about.About;
import io.github.tobiasbriones.ep.factura.ui.mainbilling.customer.CustomerCreationDialog;
import io.github.tobiasbriones.ep.factura.ui.mainbilling.header.Header;
import io.github.tobiasbriones.ep.factura.ui.mainbilling.items.Items;
import io.github.tobiasbriones.ep.factura.ui.mainbilling.print.Print;
import io.github.tobiasbriones.ep.factura.ui.mainbilling.summary.Summary;
import res.Resource;
import javax.swing.*;
import java.awt.*;
public final class MainBillingWindow implements SwingComponent<JFrame> {
interface Input {
void setCustomer(CustomerModel customer);
void setBill(BillMutator bill);
void showBillPrintedDialog(BillModel bill);
void showSetAllFieldsDialog();
void showAboutDialog();
void showCustomerCreationDialog(BillAccessor accessor);
}
interface ChildViewConfig {
JPanel getHeaderViewComponent();
JScrollPane getItemsViewComponent();
JPanel getSummaryViewComponent();
JPanel getPrintViewComponent();
JPanel getAboutViewComponent();
}
public static MainBillingWindow newInstance(DependencyConfig config) {
final var component = new MainBillingWindow(config);
component.init();
return component;
}
// Again, this would be a record class in Java 17+
public static final class DependencyConfig {
private final BasketModel basket;
private final ProductDao productDao;
private final CityDao cityDao;
private final CommunityDao communityDao;
public DependencyConfig(
BasketModel basket,
ProductDao productDao,
CityDao cityDao,
CommunityDao communityDao
) {
this.basket = basket;
this.productDao = productDao;
this.cityDao = cityDao;
this.communityDao = communityDao;
}
BasketModel basket() { return basket; }
ProductDao productDao() { return productDao; }
CityDao cityDao() { return cityDao; }
CommunityDao communityDao() { return communityDao; }
}
private static final class ChildrenConfig implements ChildViewConfig {
private static ChildrenConfig newInstance(DependencyConfig config) {
return new ChildrenConfig(
Header.newInstance(config.productDao()),
Items.newInstance(config.basket()),
Summary.newInstance(config.basket()),
Print.newInstance(),
About.newInstance()
);
}
private final Header header;
private final Items items;
private final Summary summary;
private final Print print;
private final About about;
private ChildrenConfig(
Header header,
Items items,
Summary summary,
Print print,
About about
) {
this.header = header;
this.items = items;
this.summary = summary;
this.print = print;
this.about = about;
}
@Override
public JPanel getHeaderViewComponent() {
return header.getViewComponent();
}
@Override
public JScrollPane getItemsViewComponent() {
return items.getViewComponent();
}
@Override
public JPanel getSummaryViewComponent() {
return summary.getViewComponent();
}
@Override
public JPanel getPrintViewComponent() {
return print.getViewComponent();
}
@Override
public JPanel getAboutViewComponent() {
return about.getViewComponent();
}
void initChildren(MainBillingMediator mediator) {
mediator.onInitHeader(header);
mediator.onInitItems(items);
mediator.onInitSummary(summary);
mediator.onInitPrint(print);
mediator.onInitAbout(about);
}
void callHeaderSetCustomer(CustomerNameAccessor customer) {
header.onCustomerUpdated(customer);
}
void callHeaderSetBill(BillMutator bill) {
header.onSetBill(bill);
}
}
private final DependencyConfig config;
private final ChildrenConfig childrenConfig;
private final ComponentInput input;
private final MainBillingMediator mediator;
private final MainBillingController controller;
private final MainBillingView view;
private MainBillingWindow(DependencyConfig config) {
this.config = config;
this.childrenConfig = ChildrenConfig.newInstance(config);
this.input = new ComponentInput();
this.mediator = new MainBillingMediator(config.basket());
this.controller = new MainBillingController();
this.view = new MainBillingView(controller, childrenConfig);
}
@Override
public JFrame getViewComponent() {
return view.getViewComponent();
}
public void show() {
view.show();
}
private void init() {
mediator.setComponentInput(input);
childrenConfig.initChildren(mediator);
view.init();
initController();
}
private void initController() {
controller.setView(view);
controller.init();
}
private final class ComponentInput implements Input {
private ComponentInput() {}
@Override
public void setCustomer(CustomerModel customer) {
childrenConfig.callHeaderSetCustomer(customer);
}
// This shouldn't go here. I put it because this example app ends right
// here, and there's nothing else further after printing.
@Override
public void setBill(BillMutator bill) {
childrenConfig.callHeaderSetBill(bill);
bill.setBasket(config.basket());
}
@Override
public void showBillPrintedDialog(BillModel bill) {
final JFrame parent = getViewComponent();
final var printer = new Printer(parent);
final var printUseCase = new PrintBillUseCase(bill);
printUseCase.execute(printer);
}
@Override
public void showSetAllFieldsDialog() {
final String msg = "Llena todos los campos.";
final String title = "Entrada inválida";
final JFrame parent = getViewComponent();
final int type = JOptionPane.WARNING_MESSAGE;
final String iconPath = Resource.getFileLocation("ic_warning_message.png");
final Icon icon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(iconPath));
JOptionPane.showMessageDialog(parent, msg, title, type, icon);
}
@Override
public void showAboutDialog() {
final var lineSeparator = System.lineSeparator();
final String msg = "<html><strong>Example Project: Factura</strong></html>" + lineSeparator +
"Billing application made in Java-Swing." + lineSeparator +
"Great job by studying the Example Projects!" + lineSeparator + lineSeparator +
"© 2019-2020 Tobias Briones.";
final String title = "Factura";
final JFrame parent = getViewComponent();
final int type = JOptionPane.INFORMATION_MESSAGE;
final String iconPath = Resource.getFileLocation("icon.png");
final Icon icon = new ImageIcon(Toolkit.getDefaultToolkit().getImage(iconPath));
JOptionPane.showMessageDialog(parent, msg, title, type, icon);
}
@Override
public void showCustomerCreationDialog(BillAccessor accessor) {
final CustomerCreationDialog dialog = newCustomerCreationDialog(accessor.getCustomer());
showCustomerCreationDialog(dialog);
}
private void showCustomerCreationDialog(CustomerCreationDialog dialog) {
mediator.onInitCustomerCreationDialog(dialog);
dialog.show();
}
private CustomerCreationDialog newCustomerCreationDialog(CustomerModel customer) {
final CityDao cityDao = config.cityDao();
final CommunityDao communityDao = config.communityDao();
return CustomerCreationDialog.newInstance(customer, cityDao, communityDao);
}
}
}
| 33.909091 | 110 | 0.657043 |
e12928629f9241e0ed97a3bf8e1253152a2dd994 | 2,469 | package cn.enjoyedu.independconsumer;
import cn.enjoyedu.config.KafkaConst;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.PartitionInfo;
import org.apache.kafka.common.TopicPartition;
import org.apache.kafka.common.serialization.StringDeserializer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* @author Mark老师 享学课堂 https://enjoy.ke.qq.com
* 往期课程咨询芊芊老师 QQ:2130753077 VIP课程咨询 依娜老师 QQ:2133576719
* 类说明:
*/
public class IndependConsumer {
private static KafkaConsumer<String,String> consumer = null;
public static final String SINGLE_CONSUMER_TOPIC = "single-consumer";
public static void main(String[] args) {
Properties properties = new Properties();
properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
KafkaConst.LOCAL_BROKER);
properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName());
properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
StringDeserializer.class.getName());
/*独立消息消费者*/
consumer= new KafkaConsumer<String, String>(properties);
List<TopicPartition> topicPartitionList = new ArrayList<TopicPartition>();
List<PartitionInfo> partitionInfos
= consumer.partitionsFor(SINGLE_CONSUMER_TOPIC);
if(null!=partitionInfos){
for(PartitionInfo partitionInfo:partitionInfos){
topicPartitionList.add(new TopicPartition(partitionInfo.topic(),
partitionInfo.partition()));
}
}
consumer.assign(topicPartitionList);
try {
while(true){
ConsumerRecords<String, String> records
= consumer.poll(1000);
for(ConsumerRecord<String, String> record:records){
System.out.println(String.format(
"主题:%s,分区:%d,偏移量:%d,key:%s,value:%s",
record.topic(),record.partition(),record.offset(),
record.key(),record.value()));
//do our work
}
}
} finally {
consumer.close();
}
}
}
| 35.782609 | 82 | 0.643175 |
dece01ba24b008878ade96561886d156997f78d9 | 1,580 | /*
* Copyright 2004-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.webflow.engine.model.builder.xml;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.springframework.core.io.Resource;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
* A generic strategy interface encapsulating the logic to load an XML-based document.
*
* @author Keith Donald
*/
public interface DocumentLoader {
/**
* Load the XML-based document from the external resource.
* @param resource the document resource
* @return the loaded (parsed) document
* @throws IOException an exception occured accessing the resource input stream
* @throws ParserConfigurationException an exception occured building the document parser
* @throws SAXException a error occured during document parsing
*/
public Document loadDocument(Resource resource) throws IOException, ParserConfigurationException, SAXException;
} | 37.619048 | 113 | 0.752532 |
039b78f2ed60c5034009782e2f451942ad173e13 | 450 | package com.amar.paysense.api_services;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class PixabayService {
public static PixabayApi createPixabayService() {
Retrofit.Builder builder = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://pixabay.com/");
return builder.build().create(PixabayApi.class);
}
}
| 28.125 | 67 | 0.706667 |
07edc5f653af51000d07cc82c24f8af58d36d3f8 | 1,274 | package com.fermedu.iterative.jpa;
import com.fermedu.iterative.entity.FormulaTraitEntity;
import com.fermedu.iterative.util.JsonUtil;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Arrays;
import java.util.List;
/**
* @Program: iterative-calculation
* @Create: 2020-01-22 18:11
* @Author: JustThink
* @Description:
* @Include:
**/
@RunWith(SpringRunner.class)
@SpringBootTest
class FormulaTraitRepositoryTest {
@Autowired
private FormulaTraitRepository repository;
@Test
void testOnce() {
List<FormulaTraitEntity> entityList = repository.findAll();
System.out.println(JsonUtil.toJson(entityList));
}
@Test
void saveAllTest() {
FormulaTraitEntity formulaTrait1 = new FormulaTraitEntity();
FormulaTraitEntity formulaTrait2 = new FormulaTraitEntity();
List<FormulaTraitEntity> formulaTraitList = Arrays.asList(formulaTrait1, formulaTrait2);
formulaTraitList.stream().forEach(entity -> entity.setLagTime(2));
repository.saveAll(formulaTraitList);
}
} | 27.695652 | 96 | 0.748038 |
003cc9752fdf433bd8d4f40b3d48dacb4d001565 | 1,875 | package com.hfad.todolist;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements NewTaskDialog.NewTaskDialogListener {
ArrayList<ToDo> tasksList;
NewTaskDialog newTaskDialog;
private RecyclerView taskListing;
private DBHelper dbHelper;
private ToDoItemAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView rvTasks = (RecyclerView) findViewById(R.id.taskRecycler);
newTaskDialog = new NewTaskDialog();
dbHelper = new DBHelper(this, DBHelper.DATABASE_NAME, null, 1);
// tasksList = ToDo.createToDoList(5);
tasksList = dbHelper.getTaskList();
adapter = new ToDoItemAdapter(tasksList, dbHelper);
rvTasks.setAdapter(adapter);
rvTasks.setLayoutManager(new LinearLayoutManager(this));
}
public void showDialog(View view){
newTaskDialog.show(this.getSupportFragmentManager(), "New Task");
}
@Override
protected void onResume() {
super.onResume();
}
@Override
public void storeTask(String text, String date) {
Log.i("INFO", text + " " + date);
//add task to db.
int taskId = dbHelper.insertNewTask(text, date);
//update arraylist
adapter.toDoList.add(new ToDo(text, date, 0, taskId));
//update recyclerview
adapter.notifyItemInserted(adapter.toDoList.size());
}
} | 31.25 | 100 | 0.712533 |
e15c2b1d0ad963fcc3fae0bfa634419a18244ac6 | 1,937 | package org.egov.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.repository.DefaultRateLimiterErrorHandler;
import com.marcosbarbero.cloud.autoconfigure.zuul.ratelimit.config.repository.RateLimiterErrorHandler;
import org.egov.tracer.model.CustomException;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@org.springframework.context.annotation.Configuration
public class Configuration {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(new BufferingClientHttpRequestFactory(new SimpleClientHttpRequestFactory()));
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
@Bean
public RateLimiterErrorHandler rateLimitErrorHandler() {
return new DefaultRateLimiterErrorHandler() {
@Override
public void handleSaveError(String key, Exception e) {
throw new RuntimeException( new CustomException("TOO_MANY_REQUESTS", HttpStatus.TOO_MANY_REQUESTS.toString()));
}
@Override
public void handleFetchError(String key, Exception e) {
throw new RuntimeException( new CustomException("TOO_MANY_REQUESTS", HttpStatus.TOO_MANY_REQUESTS.toString()));
}
@Override
public void handleError(String msg, Exception e) {
throw new RuntimeException( new CustomException("TOO_MANY_REQUESTS", HttpStatus.TOO_MANY_REQUESTS.toString()));
}
};
}
}
| 38.74 | 127 | 0.744966 |
048b9a6704fe528148b3468aa6c603e2ec00ebbb | 303 | package com.jrmcdonald.common.ext.spring.reactive.security.authentication;
import org.springframework.security.core.Authentication;
import reactor.core.publisher.Mono;
public interface ReactiveAuthenticationFacade {
Mono<Authentication> getAuthentication();
Mono<String> getCustomerId();
}
| 23.307692 | 74 | 0.811881 |
15e6386f64f35955513a0d2deb32566814fff741 | 6,754 | package engineio_client;
import engineio_client.transports.PollingTransport;
import engineio_client.transports.WebSocketTransport;
import connection.ConnectingTest;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import java.net.ConnectException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.function.BiConsumer;
import static org.junit.Assert.*;
public class EngineSocketTest extends ConnectingTest {
private static final Config pollingConfig;
private static final Config webSocketConfig;
private static final List<Config> configList;
static {
pollingConfig = new Config();
pollingConfig.transports = new String[]{PollingTransport.NAME};
webSocketConfig = new Config();
webSocketConfig.transports = new String[]{WebSocketTransport.NAME};
configList = new LinkedList<Config>() {{
add(pollingConfig);
add(webSocketConfig);
add(new Config());
}};
}
@BeforeClass
public static void beforeClass() {
startServer();
}
@AfterClass
public static void afterClass() {
stopServer();
}
private void testHelper(String testName, Config config, String url, BiConsumer<EngineSocket, CountDownLatch> engineConsumer) {
try {
CountDownLatch latch = new CountDownLatch(1);
EngineSocket engine = new EngineSocket(new URL(url), config);
engineConsumer.accept(engine, latch);
engine.open();
await(testName, latch);
} catch(MalformedURLException e) {
fail("Test '" + testName + "' failed with exception: " + e);
}
}
@Test
public void testOpenForNonExistingHost() {
configList.forEach(config -> {
testHelper("testOpenForNonExistingHost", config, "http://localhost2/",
(engine, latch) -> engine.on(EngineSocket.ERROR, args -> {
assertTrue(args[1] instanceof UnknownHostException);
latch.countDown();
}));
});
}
@Test
public void testOpenForClosedServer() {
configList.forEach(config -> {
testHelper("testOpenForClosedServer", config, "http://localhost:4321/",
(engine, latch) -> engine.on(EngineSocket.ABRUPT_CLOSE, args -> {
assertTrue(args[1] instanceof ConnectException);
latch.countDown();
}));
});
}
@Test
public void testOpenSuccess() {
configList.forEach(config -> {
testHelper("testOpenSuccess", config, engineIOUrl,
(engine, latch) -> {
engine.on(EngineSocket.OPEN, args -> {
engine.close();
latch.countDown();
});
});
});
}
@Test
public void testClientInitiatedClose() {
configList.forEach(config -> {
testHelper("testClientInitiatedClose", config, engineIOUrl,
(engine, latch) -> {
engine.on(EngineSocket.OPEN, args -> engine.close());
engine.on(EngineSocket.CLOSE, args -> latch.countDown());
});
});
}
@Test
public void testServerInitiatedClose() {
configList.forEach(config -> {
testHelper("testServerInitiatedClose", config, engineIOUrl,
(engine, latch) -> {
engine.on(EngineSocket.OPEN, args -> {
engine.send("hello");
engine.send("world");
engine.send("close");
});
engine.on(EngineSocket.CLOSE, args -> latch.countDown());
});
});
}
private void sendAndReceiveHelper(String testName, List<?> messages) {
configList.forEach(config -> {
try {
CountDownLatch latch = new CountDownLatch(messages.size());
EngineSocket engine = new EngineSocket(new URL(engineIOUrl), config);
engine.on(EngineSocket.MESSAGE, args -> {
if(args[0] instanceof byte[])
assertArrayEquals((byte[]) messages.remove(0), (byte[]) args[0]);
else
assertEquals(messages.remove(0), args[0]);
latch.countDown();
});
engine.on(EngineSocket.OPEN, args -> {
messages.forEach(msg -> {
if(msg instanceof byte[])
engine.send((byte[]) msg);
else
engine.send((String) msg);
});
});
engine.open();
await(testName, latch);
engine.close();
} catch (MalformedURLException e) {
fail("Malformed URL: " + engineIOUrl);
}
});
}
@Test
public void testSendAndReceiveString() {
List<String> data = new LinkedList<>();
data.add("hello");
data.add("world");
data.add("running testSendAndReceiveString");
sendAndReceiveHelper("testSendAndReceiveString", data);
}
@Test
public void testSendAndReceiveBinary() {
List<byte[]> data = new LinkedList<>();
data.add(new byte[]{1, 2, 3});
data.add(new byte[]{1});
sendAndReceiveHelper("testSendAndReceiveBinary", data);
}
@Test
public void testSendAndReceiveMixed() {
List<Object> data = new LinkedList<>();
data.add(new byte[]{1, 2, 3});
data.add("hello world");
data.add(new byte[]{3, 2, 1});
data.add("world hello");
sendAndReceiveHelper("testSendAndReceiveMixed", data);
}
@Test
public void testUpgradeSuccess() {
testHelper("testUpgradeSuccess", new Config(), engineIOUrl, (engine, latch) -> {
engine.on(EngineSocket.UPGRADE, args -> latch.countDown());
});
}
@Test
public void testUpgradeFail() {
Config conf = new Config();
testHelper("testUpgradeFail", conf, engineIOUrl, (engine, latch) -> {
engine.on(EngineSocket.UPGRADE_ATTEMPT, args -> conf.queryMap.put("sid", "non-existing-sid"));
engine.on(EngineSocket.UPGRADE_FAIL, args -> latch.countDown());
});
}
}
| 33.270936 | 130 | 0.547231 |
46ce3810c144f76cea846afd60aa824bd6c7dba6 | 1,277 | /*
Foilen Infra UI
https://github.com/foilen/foilen-infra-ui
Copyright (c) 2017-2021 Foilen (https://foilen.com)
The MIT License
http://opensource.org/licenses/MIT
*/
package com.foilen.infra.ui.upgrades.mongodb;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.foilen.infra.ui.repositories.CertAuthorityRepository;
import com.foilen.infra.ui.repositories.CertNodeRepository;
import com.foilen.infra.ui.repositories.documents.CertNode;
@Component
public class V2021081601_Ui_DeleteExtraCA extends AbstractMongoUpgradeTask {
@Autowired
private CertAuthorityRepository certAuthorityRepository;
@Autowired
private CertNodeRepository certNodeRepository;
@Override
public void execute() {
logger.info("Check all the nodes certs");
List<String> usedCertAuthIds = certNodeRepository.findAll().stream().map(CertNode::getCertAuthorityId).sorted().distinct().collect(Collectors.toList());
logger.info("Got {} different ids", usedCertAuthIds.size());
logger.info("Delete all unused CAs");
certAuthorityRepository.deleteAllByIdNotIn(usedCertAuthIds);
}
}
| 29.697674 | 160 | 0.758027 |
6b0251133608916bd30ac616ac96b2a4906580d8 | 560 | package net.neoremind.haguard;
/**
* HaGuard抽象实现
*
* @author hexiufeng, zhangxu
*/
public abstract class AbstractHaGuard implements HaGuard {
/**
* 默认超时时间,默认10s,阻塞fountain主进程的时间
*/
private long defaultTimeoutMs = 10000;
@Override
public boolean takeTokenWithDefaultTimeout() {
return takeToken(defaultTimeoutMs);
}
public long getDefaultTimeoutMs() {
return defaultTimeoutMs;
}
public void setDefaultTimeoutMs(long defaultTimeoutMs) {
this.defaultTimeoutMs = defaultTimeoutMs;
}
}
| 20 | 60 | 0.685714 |
5630f063f7fb622501775f34697e2a04ba795b88 | 2,244 | package connect.ui.activity.wallet.adapter;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import connect.db.green.bean.ContactEntity;
import connect.ui.activity.R;
import connect.utils.glide.GlideUtil;
import connect.view.roundedimageview.RoundedImageView;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
*
* Created by Administrator on 2016/12/22.
*/
public class FriendGridAdapter extends BaseAdapter {
private ArrayList<ContactEntity> mListData = new ArrayList();
@Override
public int getCount() {
return mListData.size();
}
@Override
public Object getItem(int position) {
return mListData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_wallet_friend_grid, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if(TextUtils.isEmpty(mListData.get(position).getAvatar())){
viewHolder.avaterRimg.setImageResource(R.mipmap.message_add_friends2x);
}else{
GlideUtil.loadAvater(viewHolder.avaterRimg,mListData.get(position).getAvatar());
viewHolder.nameTv.setText(mListData.get(position).getUsername());
}
return convertView;
}
public void setNotifyData(List list) {
mListData.clear();
mListData.add(new ContactEntity());
mListData.addAll(list);
notifyDataSetChanged();
}
static class ViewHolder {
@Bind(R.id.avater_rimg)
RoundedImageView avaterRimg;
@Bind(R.id.name_tv)
TextView nameTv;
ViewHolder(View view) {
ButterKnife.bind(this, view);
}
}
}
| 27.036145 | 124 | 0.675579 |
87c3f6937921da36c133c71cbfb13351511c86e2 | 986 | package openmods.integration;
import com.google.common.collect.Lists;
import java.util.List;
import openmods.Log;
public class Integration {
private static final List<IIntegrationModule> modules = Lists.newArrayList();
private static boolean alreadyLoaded;
public static void addModule(IIntegrationModule module) {
if (alreadyLoaded) Log.warn("Trying to add integration module %s after loading. This will not work");
modules.add(module);
}
public static void loadModules() {
if (alreadyLoaded) {
Log.warn("Trying to load integration modules twice, ignoring");
return;
}
for (IIntegrationModule module : modules) {
try {
if (module.canLoad()) {
module.load();
Log.debug("Loaded integration module '%s'", module.name());
} else {
Log.debug("Condition no met for integration module '%s', not loading", module.name());
}
} catch (Throwable t) {
Log.warn(t, "Can't load integration module '%s'", module.name());
}
}
}
}
| 25.947368 | 103 | 0.693712 |
c809dd0fe19602ba53c15f30d9fa0ac7a78ac2d8 | 527 | package com.Yuzhen.ExerciseOnline;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
/**
* 统一异常处理
*/
@ControllerAdvice
public class GlobalExceptionHandleController {
@ExceptionHandler(value = Exception.class)
public String exceptionHandler(Exception e, Model model) {
String message = e.getMessage();
model.addAttribute("errorMessage", message);
return "errorPage";
}
}
| 27.736842 | 64 | 0.753321 |
7242cc0a100573aae8b62188053768ca14d5090e | 322 | package com.example.demo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* @author dequan.yu
* @version V1.0
* @description TODO
* @date 2019/11/27
**/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Order {
private Integer id;
private String source;
}
| 16.1 | 33 | 0.736025 |
54408c5c458fcbdf51d32a131c95a424ee66c5f0 | 689 | package gk.defpub.restservice.validation;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* UniqueUsername annotation.
* <p>
* Date: Nov 14, 2018
* <p>
*
* @author Gleb Kosteiko
*/
@Constraint(validatedBy = UniqueUsernameValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface UniqueUsername {
String message() default "This username is already used";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
| 23.758621 | 61 | 0.748911 |
542b710678ac07a4c9b13085aeea92df8c99a158 | 972 | package com.datadog.profiling.auxiliary.async;
import com.datadog.profiling.controller.RecordingData;
import com.datadog.profiling.controller.RecordingInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Instant;
import javax.annotation.Nonnull;
final class AsyncProfilerRecordingData extends RecordingData {
private final Path recordingFile;
public AsyncProfilerRecordingData(Path recordingFile, Instant start, Instant end) {
super(start, end);
this.recordingFile = recordingFile;
}
@Nonnull
@Override
public RecordingInputStream getStream() throws IOException {
return new RecordingInputStream(Files.newInputStream(recordingFile));
}
@Override
public void release() {
try {
Files.deleteIfExists(recordingFile);
} catch (IOException e) {
e.printStackTrace();
}
}
@Nonnull
@Override
public String getName() {
return "async-profiler";
}
}
| 24.3 | 85 | 0.752058 |
1e404a8d3f6942a28f2f4199f6a6f314c9ed60a3 | 4,658 | /*
* Copyright 2018 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.palisade.policy.service;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import uk.gov.gchq.palisade.ToStringBuilder;
import uk.gov.gchq.palisade.resource.LeafResource;
import uk.gov.gchq.palisade.rule.Rules;
import java.util.HashMap;
import java.util.Map;
import static java.util.Objects.requireNonNull;
/**
* This class contains the mapping of {@link LeafResource}'s to the applicable {@link Policy}
*/
public class MultiPolicy {
private Map<LeafResource, Policy> policies = new HashMap<>();
// no-args constructor required
public MultiPolicy() {
}
/**
* @param policies a mapping of {@link LeafResource}'s to the applicable {@link Policy}
* @return the {@link MultiPolicy}
*/
public MultiPolicy policies(final Map<LeafResource, Policy> policies) {
requireNonNull(policies, "The policies cannot be set to null.");
this.policies.clear();
this.policies.putAll(policies);
return this;
}
public Map<LeafResource, Policy> getPolicies() {
//never null
return policies;
}
public void setPolicies(final Map<LeafResource, Policy> policies) {
policies(policies);
}
/**
* Retrieves the {@link Policy} associated with the given {@link LeafResource}.
* If the resource does not exist then an empty {@link Policy} will be returned.
*
* @param resource the resource that you want the {@link Policy} for.
* @return The {@link Policy} for the given {@link LeafResource}.
*/
public Policy getPolicy(final LeafResource resource) {
requireNonNull(resource, "Cannot search for a policy based on a null resource.");
final Policy policy = getPolicies().get(resource);
requireNonNull(policy, "There are no policies for this resource.");
return policy;
}
/**
* Sets the given {@link Policy} to the given {@link LeafResource} provided
* there isn't already a {@link Policy} assigned to that {@link LeafResource}.
*
* @param resource the resource that you want the {@link Policy} for
* @param policy The {@link Policy} for the given {@link LeafResource}
*/
public void setPolicy(final LeafResource resource, final Policy policy) {
requireNonNull(resource, "Cannot set a policy to a null resource.");
requireNonNull(policy, "Cannot set a null policy to a resource.");
Map<LeafResource, Policy> policies = getPolicies();
if (policies.containsKey(resource)) {
throw new IllegalArgumentException("Policy already exists for resource: " + resource);
}
policies.put(resource, policy);
}
/**
* This extracts the list of record level rules from the {@link Policy} attached to each {@link LeafResource}.
*
* @return a mapping of the {@link LeafResource}'s to the record level {@link Rules} from the policies.
*/
@JsonIgnore
public Map<LeafResource, Rules> getRuleMap() {
Map<LeafResource, Policy> policies = getPolicies();
final Map<LeafResource, Rules> rules = new HashMap<>(policies.size());
policies.forEach((r, p) -> rules.put(r, p.getRecordRules()));
return rules;
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final MultiPolicy that = (MultiPolicy) o;
return new EqualsBuilder()
.append(policies, that.policies)
.isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder(47, 53)
.append(policies)
.toHashCode();
}
@Override
public String toString() {
return new ToStringBuilder(this)
.append("policies", policies)
.toString();
}
}
| 33.753623 | 114 | 0.653499 |
1233c1c35076d738d8b10c48858ef39ddc7bd08d | 930 | package no.nav.registre.skd.consumer.command.tpsf;
import java.util.List;
import java.util.concurrent.Callable;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.web.reactive.function.client.WebClient;
import lombok.AllArgsConstructor;
@AllArgsConstructor
public class GetMeldingsIdsCommand implements Callable<List<Long>> {
private final Long gruppeId;
private final WebClient webClient;
private static final ParameterizedTypeReference<List<Long>> RESPONSE_TYPE = new ParameterizedTypeReference<>() {
};
@Override
public List<Long> call() {
return webClient.get()
.uri(builder ->
builder.path("/v1/endringsmelding/skd/meldinger/{gruppeId}")
.build(gruppeId)
)
.retrieve()
.bodyToMono(RESPONSE_TYPE)
.block();
}
}
| 29.0625 | 116 | 0.654839 |
63ae6ae5344fa56fc613d9eb0698ec9728ae82f5 | 1,524 | /*
* Copyright (c) 1997, 2019 Oracle and/or its affiliates. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Distribution License v. 1.0, which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.sun.xml.ws.sdo.sample.service.types;
import commonj.sdo.Type;
import commonj.sdo.impl.HelperProvider;
import org.eclipse.persistence.sdo.SDODataObject;
public class DeptImpl extends SDODataObject implements Dept {
public static String SDO_URI = "http://sdo.sample.service/types/";
public DeptImpl() {}
// public Type getType() {
// if(type == null){
// Type lookupType = HelperProvider.getTypeHelper().getType(SDO_URI, "Dept");
// setType(lookupType);
// }
// return type;
// }
public java.math.BigInteger getDeptno() {
return getBigInteger("Deptno");
}
public void setDeptno(java.math.BigInteger value) {
set("Deptno" , value);
}
public java.lang.String getDname() {
return getString("Dname");
}
public void setDname(java.lang.String value) {
set("Dname" , value);
}
public java.lang.String getLoc() {
return getString("Loc");
}
public void setLoc(java.lang.String value) {
set("Loc" , value);
}
public java.util.List getEmp() {
return getList("Emp");
}
public void setEmp(java.util.List value) {
set("Emp" , value);
}
}
| 23.446154 | 85 | 0.655512 |
8f491c917b5d51bcfc966b0884257af3d58ba8b1 | 5,190 | package main1;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
import java.awt.Color;
public class MainWindow {
private JFrame frame;
private JTextField TaskT;
private JTextField taskD;
private JTextField timeField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MainWindow() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.getContentPane().setForeground(Color.RED);
frame.getContentPane().setBackground(Color.CYAN);
frame.setBounds(100, 100, 450, 300);
frame.setTitle("To Do App :----- Made By Rahul");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel head = new JLabel("ToDoApp");
head.setHorizontalAlignment(SwingConstants.CENTER);
head.setBounds(82, 11, 233, 14);
frame.getContentPane().add(head);
JLabel TaskTitL = new JLabel("Task Title");
TaskTitL.setHorizontalAlignment(SwingConstants.CENTER);
TaskTitL.setBounds(10, 37, 75, 14);
frame.getContentPane().add(TaskTitL);
TaskT = new JTextField();
TaskT.setBounds(133, 36, 253, 20);
frame.getContentPane().add(TaskT);
TaskT.setColumns(10);
JLabel TDL = new JLabel("Task Description");
TDL.setHorizontalAlignment(SwingConstants.CENTER);
TDL.setBounds(10, 72, 86, 14);
frame.getContentPane().add(TDL);
JTextArea taskDescrip = new JTextArea();
taskDescrip.setBounds(133, 67, 253, 54);
frame.getContentPane().add(taskDescrip);
JLabel lblNewLabel = new JLabel("Task Deadline");
lblNewLabel.setBounds(10, 139, 86, 14);
frame.getContentPane().add(lblNewLabel);
taskD = new JTextField();
taskD.setBounds(133, 136, 253, 20);
frame.getContentPane().add(taskD);
taskD.setColumns(10);
JButton submit = new JButton("Add Tasks");
submit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String title=TaskT.getText();
String dead=taskD.getText();
String descrip=taskDescrip.getText();
String dateT=String.valueOf(java.util.Calendar.getInstance().getTime());
try {
TaskT.setText("");taskD.setText("");taskDescrip.setText("");
Class.forName("oracle.jdbc.driver.OracleDriver");// loading of the class file
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "Rahul",
"Rahul"); // establishing the connection
String tcq = "create table tasks(taskTitle varchar2(50) Not Null, Task_Description Varchar2(300)Not Null, Task_Deadline Varchar2(30),TaskSaved varchar2(30))";
String in="insert into tasks values('"+title+"','"+dead+"','"+descrip+"','"+dateT+"')";
Statement stmt = con.createStatement();// creating statement object
//stmt.execute(tcq);
stmt.execute(in);
JOptionPane.showMessageDialog(frame, "Task Added Successfully");
}
catch(Exception r)
{
System.out.println("Exception = "+r);
}
}
});
submit.setBounds(82, 180, 125, 23);
frame.getContentPane().add(submit);
JButton view = new JButton("View Tasks");
view.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");// loading of the class file
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "Rahul",
"Rahul"); //
String res="select * from tasks";
Statement stmt = con.createStatement();// creating statement object
ResultSet rs=stmt.executeQuery(res);
String sol="The tasks to be done are : \n";
int i=1;
while(rs.next())
{
sol+=i+"\n"+rs.getString(1)+"\n"+rs.getString(2)+"\n"+rs.getString(3)+"\n"+rs.getString(4)+"\n";
i++;
}
JOptionPane.showMessageDialog(frame,sol);
}
catch(Exception r1)
{
System.out.println("Exception caught "+r1);
}
}
});
view.setBounds(254, 180, 132, 23);
frame.getContentPane().add(view);
timeField = new JTextField();
timeField.setBackground(Color.LIGHT_GRAY);
timeField.setHorizontalAlignment(SwingConstants.CENTER);
timeField.setEditable(false);
timeField.setText("Current Time : "+String.valueOf(java.util.Calendar.getInstance().getTime()));
timeField.setBounds(10, 230, 376, 20);
frame.getContentPane().add(timeField);
timeField.setColumns(10);
}
}
| 31.840491 | 163 | 0.67264 |
bcf91bb9867409dd51a063bc968075e417aea08e | 2,055 | package com.github.galleog.piggymetrics.account.event;
import com.github.galleog.piggymetrics.account.domain.Account;
import com.github.galleog.piggymetrics.account.domain.Saving;
import com.github.galleog.piggymetrics.account.repository.AccountRepository;
import com.github.galleog.piggymetrics.auth.grpc.UserRegisteredEventProto.UserRegisteredEvent;
import com.google.common.annotations.VisibleForTesting;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.javamoney.moneta.Money;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import javax.money.CurrencyUnit;
import javax.money.Monetary;
import java.math.BigDecimal;
/**
* Consumer of events on user creation.
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class UserRegisteredEventConsumer {
@VisibleForTesting
public static final CurrencyUnit BASE_CURRENCY = Monetary.getCurrency("USD");
private final AccountRepository accountRepository;
@Transactional
@StreamListener(Sink.INPUT)
public void createAccount(UserRegisteredEvent event) {
logger.info("UserCreated event for user '{}' received", event.getUserName());
if (accountRepository.getByName(event.getUserName()).isPresent()) {
logger.warn("Account for user '{}' already exists", event.getUserName());
return;
}
Saving saving = Saving.builder()
.moneyAmount(Money.of(BigDecimal.ZERO, BASE_CURRENCY))
.interest(BigDecimal.ZERO)
.deposit(false)
.capitalization(false)
.build();
Account account = Account.builder()
.name(event.getUserName())
.saving(saving)
.build();
accountRepository.save(account);
logger.info("Account for user '{}' created", event.getUserName());
}
}
| 36.052632 | 94 | 0.722141 |
aab2cba3f89f67ccf3e4d5225d496b56b972573d | 762 | package ch.epfl.vlsc.truffle.cal.nodes.fifo;
import ch.epfl.vlsc.truffle.cal.CALException;
import com.oracle.truffle.api.frame.VirtualFrame;
import ch.epfl.vlsc.truffle.cal.nodes.CALExpressionNode;
import ch.epfl.vlsc.truffle.cal.runtime.CALFifo;
public class CALReadFIFONode extends CALExpressionNode {
@Child private CALExpressionNode fifo;
public CALReadFIFONode(CALExpressionNode fifo) {
super();
this.fifo = fifo;
}
@Override
public Object executeGeneric(VirtualFrame frame) {
Object fifoObject = fifo.executeGeneric(frame);
if (fifoObject instanceof CALFifo)
return ((CALFifo) fifoObject).removeFirst();
else
throw CALException.typeError(fifo, fifoObject);
}
}
| 30.48 | 59 | 0.712598 |
25371c3ca80fa6f85b62fa3bac70f30c9a7b9aac | 1,535 | package edu.brown.cs.api;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import edu.brown.cs.catan.MasterReferee;
import edu.brown.cs.catan.Referee;
public class ActionFactoryTest {
@Test
public void testCreateNonexistantAction() {
Referee ref = new MasterReferee();
ActionFactory factory = new ActionFactory(ref);
try {
String json = "{action: doesntExist, player: 0}";
factory.createAction(json);
assertTrue(false);
} catch (IllegalArgumentException e) {
assertTrue(true);
} catch (WaitingOnActionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testBadJson() {
Referee ref = new MasterReferee();
ActionFactory factory = new ActionFactory(ref);
try {
String json = "{action: buildSettlement, player: 0";
factory.createAction(json);
assertTrue(false);
} catch (IllegalArgumentException e) {
assertTrue(true);
} catch (WaitingOnActionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testMissingPlayerID() {
Referee ref = new MasterReferee();
ActionFactory factory = new ActionFactory(ref);
try {
String json = "{action: rollDice}";
factory.createAction(json);
assertTrue(false);
} catch (IllegalArgumentException e) {
assertTrue(true);
} catch (WaitingOnActionException e) {
e.printStackTrace();
assertTrue(false);
}
}
}
| 24.758065 | 58 | 0.661889 |
714b3a23021c6a33a8613b7727f1243ee7b2753c | 2,707 | package net.stargraph.test;
/*-
* ==========================License-Start=============================
* stargraph-core
* --------------------------------------------------------------------
* Copyright (C) 2017 Lambda^3
* --------------------------------------------------------------------
* 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.
* ==========================License-End===============================
*/
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import net.stargraph.core.Stargraph;
import net.stargraph.core.index.Indexer;
import net.stargraph.core.search.Searcher;
import net.stargraph.model.KBId;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import java.io.File;
public final class LuceneIndexerTest {
private KBId kbId = KBId.of("obama", "entities"); // Entities uses Lucene. See reference.conf.
private Stargraph stargraph;
@BeforeClass
public void beforeClass() {
ConfigFactory.invalidateCaches();
Config config = ConfigFactory.load().getConfig("stargraph");
File dataRootDir = TestUtils.prepareObamaTestEnv().toFile();
this.stargraph = new Stargraph(config, false);
stargraph.setKBInitSet(kbId.getId());
stargraph.setDataRootDir(dataRootDir);
this.stargraph.initialize();
}
@Test
public void bulkLoadTest() throws Exception {
Indexer indexer = stargraph.getIndexer(kbId);
indexer.load(true, -1);
indexer.awaitLoader();
Searcher searcher = stargraph.getSearcher(kbId);
Assert.assertEquals(searcher.countDocuments(), 756);
}
}
| 39.808824 | 98 | 0.666051 |
2bd2d5abe6e287cfa3e91bd2c42934ac47d38cba | 1,010 | package com.aits.kronos.controller.timeline;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.MouseEvent;
public class LabelTimeMouseEvent extends AbstractTimeLineEvent implements EventHandler<MouseEvent> {
private Label[] times;
private TextField[] fields;
public LabelTimeMouseEvent(ActiveNode activeNode, Label[] times, TextField[] fields) {
super();
setActiveNode(activeNode);
this.times = times;
this.fields = fields;
}
@Override
public void handle(MouseEvent event) {
Label source = (Label) event.getSource();
int i = Integer.parseInt(source.getId().substring(1));
if (getActiveNode().getIndex() != -1) {
fields[getActiveNode().getIndex()].setVisible(false);
times[getActiveNode().getIndex()].setVisible(true);
}
getActiveNode().setIndex(i);
fields[i].setText(parse(times[i].getText()));
times[i].setVisible(false);
fields[i].setVisible(true);
fields[i].requestFocus();
}
} | 29.705882 | 100 | 0.740594 |
b7edab6404ad10483da9a9286c084b5e85b8f394 | 1,463 | package com.mvp.expediademo.di.module;
import com.mvp.expediademo.constants.APIConstants;
import com.mvp.expediademo.di.scope.ApplicationScope;
import com.mvp.expediademo.http.thingstodo.SearchAPIService;
import dagger.Module;
import dagger.Provides;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
@Module
public class APIModule {
@Provides
@ApplicationScope
public OkHttpClient providesClient(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.build();
return okHttpClient;
}
@Provides
@ApplicationScope
public Retrofit provideRetrofit(OkHttpClient client,String baseUrl){
return new Retrofit.Builder()
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(baseUrl)
.client(client)
.build();
}
@Provides
@ApplicationScope
public SearchAPIService getMovieService(){
return provideRetrofit(providesClient(), APIConstants.SEARCH_BASE_URL).create(SearchAPIService.class);
}
}
| 29.26 | 110 | 0.732741 |
637cc65c1b5a1d1ae1e3abbbbb2fbda8d919a616 | 2,191 | package org.anystub.http;
import org.anystub.AnyStubFileLocator;
import org.anystub.AnyStubId;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
@AnySettingsHttp(headers = "classHeader")
public class AnySettingsHttpExtractorTest {
@Test
public void testdiscoverSettingsClass() {
AnyStubId s = AnyStubFileLocator.discoverFile();
AnySettingsHttp anySettingsHttp = AnySettingsHttpExtractor.discoverSettings();
assertNotNull(anySettingsHttp);
assertFalse(anySettingsHttp.allHeaders());
assertArrayEquals(new String[]{"classHeader"}, anySettingsHttp.headers());
}
@Test
@AnySettingsHttp(headers = {"test1", "test2"}, allHeaders = false, bodyTrigger = {"http://", "234"})
public void testdiscoverSettings1() {
AnySettingsHttp anySettingsHttp = AnySettingsHttpExtractor.discoverSettings();
assertNotNull(anySettingsHttp);
Object headers = new String[]{"test1", "test2"};
assertFalse(anySettingsHttp.allHeaders());
assertArrayEquals(new String[]{"test1", "test2"}, anySettingsHttp.headers());
assertArrayEquals(new String[]{"http://", "234"}, anySettingsHttp.bodyTrigger());
}
@Test
@AnySettingsHttp(headers = {})
public void testdiscoverSettings2() {
AnySettingsHttp anySettingsHttp = AnySettingsHttpExtractor.discoverSettings();
assertNotNull(anySettingsHttp);
Object headers = new String[]{"test1", "test2"};
assertFalse(anySettingsHttp.allHeaders());
assertArrayEquals(new String[]{}, anySettingsHttp.headers());
}
@Test
@AnySettingsHttp(allHeaders = true)
void testSettingsInTestLambda() {
AnySettingsHttp anySettingsHttp = AnySettingsHttpExtractor.discoverSettings();
assertNotNull(anySettingsHttp);
assertTrue(anySettingsHttp.allHeaders());
Runnable r = () -> {
AnySettingsHttp anySettingsHttp1 = AnySettingsHttpExtractor.discoverSettings();
assertNotNull(anySettingsHttp1);
assertTrue(anySettingsHttp1.allHeaders());
};
r.run();
}
} | 37.135593 | 104 | 0.695116 |
c7d5c40b804d0ea204d88b063f8fadbcc26a6f2a | 1,899 | /**
* Based on material from Digital Audio with Java, Craig Lindley
* ftp://ftp.prenhall.com/pub/ptr/professional_computer_science.w-022/digital_audio/
*/
package org.hyperdata.beeps.filters;
// The IIR highpass filter designed here has unity gain
public class IIRHighpassFilterDesign extends IIRFilterDesignBase {
public IIRHighpassFilterDesign(int cutoffFrequency,
int sampleRate,
double dampingFactor) {
super(cutoffFrequency, sampleRate, dampingFactor);
}
// Do the design of the filter. Filter response controlled by
// just three coefficients: alpha, beta and gamma.
public void doFilterDesign() {
// Get radians per sample at cutoff frequency
double thetaZero = getThetaZero();
double theSin = parameter / (2.0 * Math.sin(thetaZero));
// Beta relates gain to cutoff freq
beta = 0.5 * ((1.0 - theSin) / (1.0 + theSin));
// Final filter coefficient
gamma = (0.5 + beta) * Math.cos(thetaZero);
// For unity gain
alpha = (0.5 + beta + gamma) / 4.0;
}
// Entry point for testing
public static void main(String [] args) {
if (args.length != 3) {
System.out.println("\nIIR Highpass Filter Design Program");
System.out.println("\nUsage:");
System.out.println("\tIIRHighpassFilterDesign " +
"cutoffFrequency sampleRate dampingFactor");
System.exit(1);
}
// Parse the command line arguments
int cutoffFrequency = new Integer(args[0]).intValue();
int sampleRate = new Integer(args[1]).intValue();
double dampingFactor= new Double(args[2]).doubleValue();
// Instantiate highpass filter designer
IIRHighpassFilterDesign d =
new IIRHighpassFilterDesign(cutoffFrequency,
sampleRate, dampingFactor);
// Do the design
d.doFilterDesign();
// Print out the coefficients
d.printCoefficients();
}
}
| 28.772727 | 85 | 0.671406 |
73196864c23bbd8ca752173f1c6ac7f410eef4d6 | 1,354 | package com.algorand.utils;
import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.isda.cdm.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.annotation.*;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
public class IndexTransaction implements Comparable<IndexTransaction>{
public List<String> transactions;
public String globalKey;
public String type;
public String senderKey;
public int page;
@Override
public int compareTo(IndexTransaction other){
if(this.page < other.page){
return -1;
}
else if(this.page > other.page){
return 1;
}
else{
return 0;
}
}
public IndexTransaction(){}
public IndexTransaction(String globalKey, String type, String senderKey,List<String> algorandTransactionIDs, int page){
this.globalKey = globalKey;
this.transactions = algorandTransactionIDs;
this.type = type;
this.senderKey = senderKey;
this.page = page;
}
} | 26.54902 | 120 | 0.762925 |
79def80e252b34e061c595dc862e5d303bb6d1ac | 284 | package net.smackem.jobotwar.gui;
/**
* Alternate entry point for fat jars.
* See https://stackoverflow.com/questions/52653836/maven-shade-javafx-runtime-components-are-missing
*/
public class JarMain {
public static void main(String[] args) {
App.main(args);
}
}
| 23.666667 | 101 | 0.704225 |
854ef5b00db3db5ddd9140302fee1955757e46bc | 2,309 | package com.smile.core.dao;
import com.smile.core.domain.SysRolePermission;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
@Mapper
public interface SysRolePermissionDAO {
@Delete("delete from sys_role_permission where role_id=#{roleId}")
int remove(@Param("roleId") long roleId);
@Insert("<script> " +
"insert into sys_role_permission " +
"<trim prefix=\"(\" suffix=\")\" suffixOverrides=\",\"> " +
"<if test=\"id != null \"> " +
"id," +
"</if>" +
"<if test=\"permissionId != null \">" +
"permission_id," +
"</if>" +
"<if test=\"roleId != null \"> " +
"role_id," +
"</if>" +
"<if test=\"createdBy != null \">" +
"created_by," +
"</if>" +
"<if test=\"createTime != null \">" +
"create_time," +
"</if> " +
"<if test=\"updatedBy != null \">" +
"updated_by," +
"</if>" +
"<if test=\"updateTime != null \">" +
"update_time," +
"</if>" +
"</trim>" +
"<trim prefix=\"values (\" suffix=\")\" suffixOverrides=\",\">" +
"<if test=\"id != null \">" +
"#{id,jdbcType=BIGINT}," +
"</if>" +
"<if test=\"permissionId != null \">" +
"#{permissionId,jdbcType=BIGINT}," +
"</if>" +
"<if test=\"roleId != null \">" +
"#{roleId,jdbcType=BIGINT}," +
"</if>" +
"<if test=\"createdBy != null \">" +
"#{createdBy,jdbcType=BIGINT}," +
"</if>" +
"<if test=\"createTime != null \">" +
"#{createTime,jdbcType=TIMESTAMP}," +
"</if>" +
"<if test=\"updatedBy != null \">" +
"#{updatedBy,jdbcType=BIGINT}," +
"</if>" +
"<if test=\"updateTime != null \">" +
"#{updateTime,jdbcType=TIMESTAMP}," +
"</if>" +
"</trim>" +
"</script> ")
int insert(SysRolePermission entity);
} | 33.463768 | 77 | 0.442183 |
02a42507b8d6f055a601153dbd966f24b2ecc74f | 2,904 | package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.time.LocalDate;
@Entity
public class Orders
{
@Id
private int orderNumber;
private int productId;
private int memberId;
private int quantity;
private String brand;
private String category;
private BigDecimal extendedPrice;
private BigDecimal unitPrice;
private LocalDate datePurchased;
private String firstName;
private String lastName;
public Orders(int orderNumber, int productId, int memberId, int quantity, BigDecimal extendedPrice, BigDecimal unitPrice, LocalDate datePurchased, String firstName, String lastName)
{
this.orderNumber = orderNumber;
this.productId = productId;
this.memberId = memberId;
this.quantity = quantity;
this.extendedPrice = extendedPrice;
this.unitPrice = unitPrice;
this.datePurchased = datePurchased;
this.firstName = firstName;
this.lastName = lastName;
}
public int getOrderNumber()
{
return orderNumber;
}
public int getProductId()
{
return productId;
}
public int getMemberId()
{
return memberId;
}
public int getQuantity()
{
return quantity;
}
public BigDecimal getExtendedPrice()
{
return extendedPrice;
}
public BigDecimal getUnitPrice()
{
return unitPrice;
}
public LocalDate getDatePurchased()
{
return datePurchased;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getBrand()
{
return brand;
}
public String getCategory()
{
return category;
}
public void setOrderNumber(int orderNumber)
{
this.orderNumber = orderNumber;
}
public void setProductId(int productId)
{
this.productId = productId;
}
public void setMemberId(int memberId)
{
this.memberId = memberId;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public void setBrand(String brand)
{
this.brand = brand;
}
public void setCategory(String category)
{
this.category = category;
}
public void setExtendedPrice(BigDecimal extendedPrice)
{
this.extendedPrice = extendedPrice;
}
public void setUnitPrice(BigDecimal unitPrice)
{
this.unitPrice = unitPrice;
}
public void setDatePurchased(LocalDate datePurchased)
{
this.datePurchased = datePurchased;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
}
| 19.621622 | 185 | 0.631198 |
5e1fae7809cce4e2d076d8dd5689ca56763af02c | 3,432 | /*
* 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.qpid.jms.provider.amqp.builders;
import org.apache.qpid.jms.meta.JmsSessionInfo;
import org.apache.qpid.jms.provider.amqp.AmqpTransactionContext;
import org.apache.qpid.jms.provider.amqp.AmqpTransactionCoordinator;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.messaging.Accepted;
import org.apache.qpid.proton.amqp.messaging.Modified;
import org.apache.qpid.proton.amqp.messaging.Rejected;
import org.apache.qpid.proton.amqp.messaging.Released;
import org.apache.qpid.proton.amqp.messaging.Source;
import org.apache.qpid.proton.amqp.transaction.Coordinator;
import org.apache.qpid.proton.amqp.transaction.TxnCapability;
import org.apache.qpid.proton.amqp.transport.ReceiverSettleMode;
import org.apache.qpid.proton.amqp.transport.SenderSettleMode;
import org.apache.qpid.proton.engine.Sender;
/**
* Resource builder responsible for creating and opening an AmqpTransactionCoordinator instance.
*/
public class AmqpTransactionCoordinatorBuilder extends AmqpResourceBuilder<AmqpTransactionCoordinator, AmqpTransactionContext, JmsSessionInfo, Sender> {
public AmqpTransactionCoordinatorBuilder(AmqpTransactionContext parent, JmsSessionInfo resourceInfo) {
super(parent, resourceInfo);
}
@Override
protected Sender createEndpoint(JmsSessionInfo resourceInfo) {
Coordinator coordinator = new Coordinator();
coordinator.setCapabilities(TxnCapability.LOCAL_TXN);
Symbol[] outcomes = new Symbol[]{ Accepted.DESCRIPTOR_SYMBOL, Rejected.DESCRIPTOR_SYMBOL, Released.DESCRIPTOR_SYMBOL, Modified.DESCRIPTOR_SYMBOL };
Source source = new Source();
source.setOutcomes(outcomes);
String coordinatorName = "qpid-jms:coordinator:" + resourceInfo.getId().toString();
Sender sender = getParent().getSession().getEndpoint().sender(coordinatorName);
sender.setSource(source);
sender.setTarget(coordinator);
sender.setSenderSettleMode(SenderSettleMode.UNSETTLED);
sender.setReceiverSettleMode(ReceiverSettleMode.FIRST);
return sender;
}
@Override
protected AmqpTransactionCoordinator createResource(AmqpTransactionContext parent, JmsSessionInfo resourceInfo, Sender endpoint) {
return new AmqpTransactionCoordinator(resourceInfo, endpoint, parent);
}
@Override
protected boolean isClosePending() {
// When no link terminus was created, the peer will now detach/close us otherwise
// we need to validate the returned remote source prior to open completion.
return getEndpoint().getRemoteTarget() == null;
}
}
| 45.157895 | 155 | 0.770105 |
c316f5e7e4d429db114234f1b172c364c9b83639 | 1,211 | package com.ozipin.filemaster.domain.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.http.HttpStatus;
/**
* 通用返回结果构造器
*
* @author ozipin
* @date 2021/03/31
*/
@ApiModel(value = "通用返回结果构造器")
public class CommonResultVoBuilder<T> {
@ApiModelProperty(value = "状态码", example = "200")
private Integer code;
@ApiModelProperty(value = "是否成功", example = "true")
private Boolean success;
@ApiModelProperty(value = "时间戳")
private String timestamp = String.valueOf(System.currentTimeMillis());
@ApiModelProperty(value = "数据", example = "{}")
private T data;
public CommonResultVoBuilder<T> success(T data){
this.success = true;
this.code = HttpStatus.OK.value();
this.data = data;
return this;
}
public CommonResultVoBuilder<T> fail(T data){
this.success = false;
this.data = data;
return this;
}
public CommonResultVoBuilder<T> fail(T data, int code){
this.code = code;
return fail(data);
}
public CommonResultVo<T> build(){
return new CommonResultVo<T>(code, success, timestamp, data);
}
}
| 24.22 | 74 | 0.652353 |
bbecc469b228aab31bdd1a49a3acacb15b9771f2 | 586 | package com.skubit.comics;
import junit.framework.TestCase;
import android.os.Bundle;
public class SeriesFilterTest extends TestCase {
public void testFilter() throws Exception {
SeriesFilter filter = new SeriesFilter();
filter.creator = "a_creator";
filter.publisher = "a_publisher";
Bundle bundle = SeriesFilter.toBundle(filter);
SeriesFilter filterTest = bundle.getParcelable("com.skubit.comics.SERIES_FILTER");
assertEquals("a_publisher", filterTest.publisher);
assertEquals("a_creator", filterTest.creator);
}
}
| 29.3 | 90 | 0.709898 |
a40c5914408ed6523953073d9418a8f36287c9ec | 258 | package me.noodles.ss.inv;
import org.bukkit.ChatColor;
public class InvNames {
public static String Main;
static {
InvNames.Main = new StringBuilder().append(ChatColor.RED).append(ChatColor.BOLD).append("FROZEN").toString();
}
}
| 17.2 | 117 | 0.686047 |
217b3a3162cd65ebcabac4b177a5558b77e4e3d2 | 3,475 | package de.polocloud.modules.party;
import de.polocloud.api.PoloCloudAPI;
import de.polocloud.api.common.PoloType;
import de.polocloud.api.config.helper.Config;
import de.polocloud.api.exceptions.PoloTypeUnsupportedActionException;
import de.polocloud.api.module.CloudModule;
import de.polocloud.api.module.ModuleCopyType;
import de.polocloud.api.module.info.ModuleInfo;
import de.polocloud.api.module.info.ModuleState;
import de.polocloud.api.module.info.ModuleTask;
import de.polocloud.modules.party.api.IPartyManager;
import de.polocloud.modules.party.api.config.ModuleConfig;
import de.polocloud.modules.party.api.def.SimplePartyManager;
import de.polocloud.modules.party.module.command.PartyCommand;
import de.polocloud.modules.party.module.listener.PlayerJoinListener;
import de.polocloud.modules.party.module.listener.PlayerQuitListener;
import de.polocloud.modules.party.module.listener.PlayerServerListener;
import lombok.Getter;
import java.io.File;
@ModuleInfo(
main = PartyModule.class,
name = "PoloCloud-Party",
version = "1.0",
description = "This is a default Party-Module",
authors = "Lystx",
copyTypes = ModuleCopyType.NONE
)
@Getter
public class PartyModule extends CloudModule {
/**
* The static instance of this module
*/
private static PartyModule instance;
/**
* The config to get all values
*/
private ModuleConfig moduleConfig;
/**
* The manager
*/
private IPartyManager partyManager;
@ModuleTask(id = 1, state = ModuleState.LOADING)
public void loadModule() {
instance = this;
//Setting party manager
this.partyManager = new SimplePartyManager();
//Loading config
this.moduleConfig = configLoader.load(ModuleConfig.class, new ModuleConfig(), new File(dataDirectory, "config.json"), configSaver);
}
@ModuleTask(id = 2, state = ModuleState.STARTING)
public void enableModule() {
//Registering command
PoloCloudAPI.getInstance().getCommandManager().registerCommand(new PartyCommand());
//Registering events
PoloCloudAPI.getInstance().getEventManager().registerListener(this, new PlayerJoinListener());
PoloCloudAPI.getInstance().getEventManager().registerListener(this, new PlayerQuitListener());
PoloCloudAPI.getInstance().getEventManager().registerListener(this, new PlayerServerListener());
}
/**
* Reloads the config
*/
public void reloadConfig() {
//Loading config
this.moduleConfig = configLoader.load(ModuleConfig.class, new ModuleConfig(), new File(dataDirectory, "config.json"), configSaver);
}
@ModuleTask(id = 3, state = ModuleState.STOPPING)
public void disableModule() {
PoloCloudAPI.getInstance().getCommandManager().unregisterCommand(PartyCommand.class);
}
/**
* Gets the {@link PartyModule} instance of this module
* And checks if the current Cloud-Environment equals the {@link PoloType#MASTER}
* Otherwise it will throw a {@link PoloTypeUnsupportedActionException} to let
* the developers now that this is not the right environment to use it on
*/
public static PartyModule getInstance() {
if (PoloCloudAPI.getInstance().getType() != PoloType.MASTER) {
throw new PoloTypeUnsupportedActionException("The PartyModule does not work on any other Instance than the CloudMaster!");
}
return instance;
}
}
| 35.459184 | 139 | 0.72259 |
97da4315c5434157f8e3b85fc7d2b09d8b935e2b | 690 | package decorator.bverage.condiment.impl;
import decorator.bverage.Beverage;
import decorator.bverage.condiment.CondimentDecorator;
public class Soy extends CondimentDecorator{
Beverage beverage;
public Soy(Beverage beverage) {
this.beverage = beverage;
}
public String getDescription(){
return beverage.getDescription()+", Soy ";
}
public double cost(){
double cost=beverage.cost();
if(beverage.getSize()==Size.TALL){
cost+=.1;
}else if(beverage.getSize()==Size.GRANDE){
cost+=1.40;
}else if(beverage.getSize()==Size.VENTI){
cost+=1.70;
}
return cost;
}
}
| 23.793103 | 54 | 0.615942 |
24e30bd72da5c75bbb8c4f1e8b88867198c06123 | 752 | /**
*
* Class PresentationElement.java
*
* Generated by KMFStudio at 14 April 2004 22:36:45
* Visit http://www.cs.ukc.ac.uk/kmf
*
*/
package uk.ac.ukc.cs.kmf.kmfstudio.uml.Foundation.Core;
public interface PresentationElement
extends
uk.ac.ukc.cs.kmf.kmfstudio.uml.UmlElement,
Element
{
/** Get the 'subject' from 'PresentationElement' */
public java.util.Set getSubject();
/** Set the 'subject' from 'PresentationElement' */
public void setSubject(java.util.Set subject);
/** Get the id */
public String getId();
/** Set the id */
public void setId(String id);
/** Override the toString */
public String toString();
/** Delete the object */
public void delete();
/** Clone the object */
public Object clone();
}
| 20.324324 | 55 | 0.680851 |
bf08a598f0be8c951a605e910b0669fc731853bb | 420 | package com.leetcode.service;
import com.leetcode.common.PageReqBody;
import com.leetcode.model.comment.CommentReqBody;
import com.leetcode.model.response.APIResponse;
public interface CommentService {
APIResponse getComments(PageReqBody req);
APIResponse createComment(CommentReqBody request);
APIResponse updateComment(CommentReqBody request);
APIResponse deleteComment(CommentReqBody request);
}
| 26.25 | 54 | 0.816667 |
e7418e7b86fa6c992ccec72f96bfdee6013098ff | 912 | package info.smart_tools.smartactors.database.cached_collection.exception;
import info.smart_tools.smartactors.database.cached_collection.ICachedCollection;
/**
* Exception for error in {@link ICachedCollection} getItem method
*/
public class GetCacheItemException extends Exception {
/**
* Empty constructor for @GetCacheItemException
*/
public GetCacheItemException() {
}
/**
* @param message Message with exception
*/
public GetCacheItemException(final String message) {
super(message);
}
/**
* @param message Message with exception
* @param cause Cause of exception
*/
public GetCacheItemException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* @param cause Cause of exception
*/
public GetCacheItemException(final Throwable cause) {
super(cause);
}
}
| 24 | 81 | 0.678728 |
6ab3ee64908f436b480c0c8cbff937f4e9168c3b | 2,448 | package com.nightlycommit.idea.twigextendedplugin.config.component.parser;
import org.jetbrains.annotations.NotNull;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Daniel Espendiller <daniel@espendiller.net>
*/
public class ParameterServiceCollector {
@NotNull
public static Map<String, String> collect(InputStream stream) {
try {
return collect(DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(stream)
);
} catch (IOException | SAXException | ParserConfigurationException e) {
return Collections.emptyMap();
}
}
@NotNull
public static Map<String, String> collect(File file) {
try {
return collect(DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(file)
);
} catch (SAXException | IOException | ParserConfigurationException e) {
return Collections.emptyMap();
}
}
@NotNull
private static Map<String, String> collect(Document document) {
Map<String, String> parameterMap = new ConcurrentHashMap<>();
Object nodeList;
try {
XPath xpath = XPathFactory.newInstance().newXPath();
XPathExpression xPathExpr = xpath.compile("/container/parameters/parameter[@key]");
nodeList = xPathExpr.evaluate(document, XPathConstants.NODESET);
} catch (XPathExpressionException e) {
return Collections.emptyMap();
}
if(!(nodeList instanceof NodeList)) {
return Collections.emptyMap();
}
for (int i = 0; i < ((NodeList) nodeList).getLength(); i++) {
Element node = (Element) ((NodeList) nodeList).item(i);
String parameterValue = node.hasAttribute("type") && node.getAttribute("type").equals("collection") ? "collection" : node.getTextContent();
parameterMap.put(node.getAttribute("key"), parameterValue);
}
return parameterMap;
}
}
| 32.210526 | 152 | 0.650735 |
a24d705ed586183b0e8e2d9ecd2fe207717f72a9 | 1,749 | package cap5;
// Classe que representa uma apólice de seguro de automóvel.
public class AutoPolicy {
private int accountNumber; // número da conta da apólice
private String makeAndModel; // carro ao qual a apólice é aplicada
private String state; // abreviatura do estado com duas letras
// construtor
public AutoPolicy(int accountNumber, String makeAndModel, String state){
this.accountNumber = accountNumber;
this.makeAndModel = makeAndModel;
this.state = state;
}
// define o accountNumber
public void setAccountNumber(int accountNumber){
this.accountNumber = accountNumber;
}
// retorna o accountNumber
public int getAccountNumber(){
return accountNumber;
}
// configura o makeAndModel
public void setMakeAndModel(String makeAndModel){
this.makeAndModel = makeAndModel;
}
// retorna o makeAndModel
public String getMakeAndModel(){
return makeAndModel;
}
// define o estado
public void setState(String state){
this.state = state;
}
// retorna o estado
public String getState(){
return state;
}
// método predicado é retornado se o estado tem seguros "sem culpa"
public boolean isNoFaultState(){
boolean noFaultState;
// determina se o estado tem seguros de automóvel "sem culpa"
switch (getState()){ //obtém a abreviatura do estado do objeto AutoPolicy
case "MA": case "NJ": case "NY": case "PA":
noFaultState = true;
break;
default:
noFaultState = false;
break;
}
return noFaultState;
}
} | 29.15 | 81 | 0.618067 |
33a92007e1166a4428ee5827860df257c82ad87d | 2,825 | package com.example.androidappcar;
import android.app.Activity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
public class SpeedLimit extends Activity {
Button saveButton, exitButton;
SeekBar forwardBar, reverseBar;
TextView speedForwardInteger, speedReverseInteger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.speed_limit_window);
speedForwardInteger = findViewById(R.id.speedForwardInteger);
speedForwardInteger.setText(ControlCarActivity.getSpeedLimitForward() + "%");
speedReverseInteger = findViewById(R.id.speedReverseInteger);
speedReverseInteger.setText(ControlCarActivity.getSpeedLimitBackwards() + "%");
forwardBar = findViewById(R.id.forwardBar);
forwardBar.setProgress(ControlCarActivity.getSpeedLimitForward() / 10);
forwardBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
speedForwardInteger.setText(forwardBar.getProgress() * 10 + "%");
}
});
reverseBar = findViewById(R.id.reverseBar);
reverseBar.setProgress(ControlCarActivity.getSpeedLimitBackwards() / 10);
reverseBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
speedReverseInteger.setText(reverseBar.getProgress() * 10 + "%");
}
});
saveButton = findViewById(R.id.saveButton);
saveButton.setOnClickListener(e -> {
ControlCarActivity.setSpeedLimitForward(forwardBar.getProgress() * 10);
ControlCarActivity.setSpeedLimitBackwards(reverseBar.getProgress() * 10);
});
exitButton = findViewById(R.id.exitButton);
exitButton.setOnClickListener(e -> finish());
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * 0.9), (int) (height * 0.8));
}
}
| 34.036145 | 91 | 0.666549 |
986951deb104173c3968a960ee62ade71ded56e9 | 3,465 | package eu.openminted.registry.core.dao;
import eu.openminted.registry.core.service.ServiceException;
import org.springframework.context.annotation.Scope;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.stream.Stream;
public abstract class AbstractDao<T> {
private final Class<T> persistentClass;
@PersistenceContext(unitName = "registryEntityManagerFactory")
private EntityManager entityManager;
@SuppressWarnings("unchecked")
public AbstractDao(){
this.persistentClass =(Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
}
@Scope("request")
protected CriteriaBuilder getCriteriaBuilder(){
return entityManager.getCriteriaBuilder();
}
@Scope("request")
protected CriteriaQuery<T> getCriteriaQuery(){
return getCriteriaBuilder().createQuery(persistentClass);
}
protected EntityManager getEntityManager(){
return this.entityManager;
}
@SuppressWarnings("unchecked")
public T getSingleResult(String key, Object value) {
CriteriaQuery<T> criteriaQuery = getCriteriaQuery();
Root<T> root = criteriaQuery.from(persistentClass);
criteriaQuery.distinct(true);
criteriaQuery.select(root).where(getCriteriaBuilder().equal(root.get(key),value));
TypedQuery<T> query = entityManager.createQuery(criteriaQuery);
return query.getResultList().isEmpty() ? null : query.getSingleResult();
}
public List<T> getList(String key, Object value) {
CriteriaQuery<T> criteriaQuery = getCriteriaQuery();
Root<T> root = criteriaQuery.from(persistentClass);
criteriaQuery.distinct(true);
criteriaQuery.select(root).where(getCriteriaBuilder().equal(root.get(key),value));
TypedQuery<T> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
public List<T> getList() {
CriteriaQuery<T> criteriaQuery = getCriteriaQuery();
Root<T> root = criteriaQuery.from(persistentClass);
criteriaQuery.distinct(true);
criteriaQuery.select(root);
TypedQuery<T> query = entityManager.createQuery(criteriaQuery);
return query.getResultList();
}
public Stream<T> getStream() {
CriteriaQuery<T> criteriaQuery = getCriteriaQuery();
Root<T> root = criteriaQuery.from(persistentClass);
criteriaQuery.select(root);
TypedQuery<T> query = entityManager.createQuery(criteriaQuery);
return query.getResultStream();
}
public T update(T entity) {
return entityManager.merge(entity);
}
@Transactional(propagation = Propagation.REQUIRED)
public void persist(T entity) {
try {
entityManager.persist(entity);
entityManager.flush();
}catch (Exception e){
throw new ServiceException(e);
}
}
public void delete(T entity) {
entityManager.remove(entity);
entityManager.flush();
}
}
| 33 | 130 | 0.705916 |
4a04ff87775c561df99568fe47453431522ce390 | 3,414 | package org.estudantinder.Features.Users;
import org.junit.jupiter.api.Test;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.given;
import javax.json.Json;
@QuarkusTest
public class CreateUserTest {
@Test
public void testCreateUserEndpoint() {
String testUser = Json.createObjectBuilder()
.add("name", "TestUser1")
.add("email", "test@email.com")
.add("password", "TestPassword1")
.add("school_year", 3)
.add("birth_date", "2000-02-01")
.add("classroom", "F")
.add("bio", "TEST BIOGRAPHY")
.add("gender", "1")
.add("shift", 1)
.add("subjects_ids", Json.createArrayBuilder()
.add(10)
.add(11)
.add(12))
.add("course_id", 5)
.add("contacts", Json.createObjectBuilder()
.add("whatsapp", 551112345)
.add("instagram", "@testInstagram")
.add("twitter", "@testTwitter")
.add("facebook", "test.facebook"))
.build().toString();
given()
.body(testUser)
.contentType(ContentType.JSON)
.when().post("/users")
.then()
.statusCode(201);
}
@Test
public void testConflictCreateUserEndpoint() {
String testUser = Json.createObjectBuilder()
.add("name", "TestUser1")
.add("email", "test4@email.com")
.add("password", "TestPassword1")
.add("school_year", 3)
.add("birth_date", "2000-02-01")
.add("classroom", "F")
.add("bio", "TEST BIOGRAPHY")
.add("gender", "1")
.add("shift", 1)
.add("subjects_ids", Json.createArrayBuilder()
.add(10)
.add(11)
.add(12))
.add("course_id", 5)
.add("contacts", Json.createObjectBuilder()
.add("whatsapp", 551112345)
.add("instagram", "@testInstagram")
.add("twitter", "@testTwitter")
.add("facebook", "test.facebook"))
.build().toString();
given()
.body(testUser)
.contentType(ContentType.JSON)
.when().post("/users")
.then()
.statusCode(409);
}
@Test
public void testBadRequestConflictCreateUserEndpoint() {
//password without number
String testUser = Json.createObjectBuilder()
.add("name", "TestUser1")
.add("email", "test0@email.com")
.add("password", "TestPassword")
.add("school_year", 3)
.add("birth_date", "2000-02-01")
.add("classroom", "F")
.add("bio", "TEST BIOGRAPHY")
.add("gender", "1")
.add("shift", 1)
.add("subjects_ids", Json.createArrayBuilder()
.add(10)
.add(11)
.add(12))
.add("course_id", 5)
.add("contacts", Json.createObjectBuilder()
.add("whatsapp", 551112345)
.add("instagram", "@testInstagram")
.add("twitter", "@testTwitter")
.add("facebook", "test.facebook"))
.build().toString();
given()
.body(testUser)
.contentType(ContentType.JSON)
.when().post("/users")
.then()
.statusCode(400);
}
}
| 29.431034 | 60 | 0.515231 |
4c0ecde9bb94e3e64cf1cd87e15e3a1ed307b2f2 | 710 | package de.melanx.skyblockbuilder.config;
import de.melanx.skyblockbuilder.template.TemplateInfo;
import io.github.noeppi_noeppi.libx.annotation.config.RegisterConfig;
import io.github.noeppi_noeppi.libx.config.Config;
import net.minecraft.core.BlockPos;
import java.util.List;
import java.util.Map;
@RegisterConfig("templates")
public class TemplateConfig {
@Config("The list of templates being available. The first entry is the default template.")
public static List<TemplateInfo> templates = List.of(new TemplateInfo("default", "default.nbt", "default"));
@Config
public static Map<String, List<BlockPos>> spawns = Map.of("default", List.of(
new BlockPos(6, 3, 5)
));
}
| 32.272727 | 112 | 0.749296 |
c9a575e98f7343f720a71be1dc4ebbcd99488449 | 8,417 | /*
* 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 com.datadistillr.udf;
import io.netty.buffer.DrillBuf;
import org.apache.drill.exec.expr.DrillSimpleFunc;
import org.apache.drill.exec.expr.annotations.FunctionTemplate;
import org.apache.drill.exec.expr.annotations.Output;
import org.apache.drill.exec.expr.annotations.Param;
import org.apache.drill.exec.expr.annotations.Workspace;
import org.apache.drill.exec.expr.holders.BigIntHolder;
import org.apache.drill.exec.expr.holders.Float8Holder;
import org.apache.drill.exec.expr.holders.IntHolder;
import org.apache.drill.exec.expr.holders.VarBinaryHolder;
import org.apache.drill.exec.expr.holders.VarCharHolder;
import org.apache.drill.exec.vector.complex.writer.BaseWriter;
import javax.inject.Inject;
/**
* These UDFs mirror the H3 functionality here: https://h3geo.org/docs/api/indexing.
*/
public class H3IndexingUDFs {
@FunctionTemplate(names = {"geoToH3", "geo_to_h3"},
scope = FunctionTemplate.FunctionScope.SIMPLE,
nulls = FunctionTemplate.NullHandling.NULL_IF_NULL)
public static class GeoToH3Function implements DrillSimpleFunc {
@Param
Float8Holder latitudeHolder;
@Param
Float8Holder longitudeHolder;
@Param
IntHolder resolutionHolder;
@Output
BigIntHolder result;
@Workspace
com.uber.h3core.H3Core h3;
@Override
public void setup() {
try {
h3 = com.uber.h3core.H3Core.newInstance();
} catch (java.io.IOException e) {
h3 = null;
}
}
@Override
public void eval() {
double latitude = latitudeHolder.value;
double longitude = longitudeHolder.value;
int resolution = resolutionHolder.value;
if (h3 == null) {
result.value = 0L;
} else {
result.value = h3.geoToH3(latitude, longitude, resolution);
}
}
}
@FunctionTemplate(names = {"geoToH3Address", "geo_to_h3_address"},
scope = FunctionTemplate.FunctionScope.SIMPLE,
nulls = FunctionTemplate.NullHandling.NULL_IF_NULL)
public static class GeoToH3AddressFunction implements DrillSimpleFunc {
@Param
Float8Holder latitudeHolder;
@Param
Float8Holder longitudeHolder;
@Param
IntHolder resolutionHolder;
@Output
VarCharHolder out;
@Inject
DrillBuf buffer;
@Workspace
com.uber.h3core.H3Core h3;
@Override
public void setup() {
try {
h3 = com.uber.h3core.H3Core.newInstance();
} catch (java.io.IOException e) {
h3 = null;
}
}
@Override
public void eval() {
double latitude = latitudeHolder.value;
double longitude = longitudeHolder.value;
int resolution = resolutionHolder.value;
if (h3 != null) {
String result = h3.geoToH3Address(latitude, longitude, resolution);
byte[] rowStringBytes = result.getBytes(java.nio.charset.StandardCharsets.UTF_8);
buffer = buffer.reallocIfNeeded(rowStringBytes.length);
buffer.setBytes(0, rowStringBytes);
out.start = 0;
out.end = rowStringBytes.length;
out.buffer = buffer;
}
}
}
@FunctionTemplate(names = {"h3ToGeoPoint", "h3_to_geo_point"},
scope = FunctionTemplate.FunctionScope.SIMPLE,
nulls = FunctionTemplate.NullHandling.NULL_IF_NULL)
public static class GeoToH3GeoPoint implements DrillSimpleFunc {
@Param
BigIntHolder h3Input;
@Output
VarBinaryHolder out;
@Inject
DrillBuf buffer;
@Workspace
com.uber.h3core.H3Core h3;
@Override
public void setup() {
try {
h3 = com.uber.h3core.H3Core.newInstance();
} catch (java.io.IOException e) {
h3 = null;
}
}
@Override
public void eval() {
if (h3 == null) {
return;
}
com.uber.h3core.util.GeoCoord coord = h3.h3ToGeo(h3Input.value);
double lon = coord.lng;
double lat = coord.lat;
com.esri.core.geometry.ogc.OGCPoint point = new com.esri.core.geometry.ogc.OGCPoint(
new com.esri.core.geometry.Point(lon, lat), com.esri.core.geometry.SpatialReference.create(4326));
java.nio.ByteBuffer pointBytes = point.asBinary();
out.buffer = buffer;
out.start = 0;
out.end = pointBytes.remaining();
buffer.setBytes(0, pointBytes);
}
}
@FunctionTemplate(names = {"h3ToGeoPoint", "h3_to_geo_point"},
scope = FunctionTemplate.FunctionScope.SIMPLE,
nulls = FunctionTemplate.NullHandling.NULL_IF_NULL)
public static class GeoToH3GeoPointFromString implements DrillSimpleFunc {
@Param
VarCharHolder h3Input;
@Output
VarBinaryHolder out;
@Inject
DrillBuf buffer;
@Workspace
com.uber.h3core.H3Core h3;
@Override
public void setup() {
try {
h3 = com.uber.h3core.H3Core.newInstance();
} catch (java.io.IOException e) {
h3 = null;
}
}
@Override
public void eval() {
if (h3 == null) {
return;
}
String h3InputString = org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.getStringFromVarCharHolder(h3Input);
com.uber.h3core.util.GeoCoord coord = h3.h3ToGeo(h3InputString);
double lon = coord.lng;
double lat = coord.lat;
com.esri.core.geometry.ogc.OGCPoint point = new com.esri.core.geometry.ogc.OGCPoint(
new com.esri.core.geometry.Point(lon, lat), com.esri.core.geometry.SpatialReference.create(4326));
java.nio.ByteBuffer pointBytes = point.asBinary();
out.buffer = buffer;
out.start = 0;
out.end = pointBytes.remaining();
buffer.setBytes(0, pointBytes);
}
}
@FunctionTemplate(names = {"h3ToGeo", "h3_to_geo"},
scope = FunctionTemplate.FunctionScope.SIMPLE)
public static class GeoToH3GeoMap implements DrillSimpleFunc {
@Param
BigIntHolder h3Input;
@Output
BaseWriter.ComplexWriter outWriter;
@Workspace
com.uber.h3core.H3Core h3;
@Override
public void setup() {
try {
h3 = com.uber.h3core.H3Core.newInstance();
} catch (java.io.IOException e) {
h3 = null;
}
}
@Override
public void eval() {
if (h3 == null) {
return;
}
com.uber.h3core.util.GeoCoord coord = h3.h3ToGeo(h3Input.value);
org.apache.drill.exec.vector.complex.writer.BaseWriter.MapWriter queryMapWriter = outWriter.rootAsMap();
double lon = coord.lng;
double lat = coord.lat;
queryMapWriter.float8("latitude").writeFloat8(lat);
queryMapWriter.float8("longitude").writeFloat8(lon);
}
}
@FunctionTemplate(names = {"h3ToGeo", "h3_to_geo"},
scope = FunctionTemplate.FunctionScope.SIMPLE)
public static class GeoToH3GeoMapFromString implements DrillSimpleFunc {
@Param
VarCharHolder h3Input;
@Output
BaseWriter.ComplexWriter outWriter;
@Workspace
com.uber.h3core.H3Core h3;
@Override
public void setup() {
try {
h3 = com.uber.h3core.H3Core.newInstance();
} catch (java.io.IOException e) {
h3 = null;
}
}
@Override
public void eval() {
if (h3 == null) {
return;
}
String h3InputString = org.apache.drill.exec.expr.fn.impl.StringFunctionHelpers.getStringFromVarCharHolder(h3Input);
com.uber.h3core.util.GeoCoord coord = h3.h3ToGeo(h3InputString);
org.apache.drill.exec.vector.complex.writer.BaseWriter.MapWriter queryMapWriter = outWriter.rootAsMap();
double lon = coord.lng;
double lat = coord.lat;
queryMapWriter.float8("latitude").writeFloat8(lat);
queryMapWriter.float8("longitude").writeFloat8(lon);
}
}
}
| 26.805732 | 122 | 0.675538 |
f8066764ec82e9fc6bbbbbca0c100f5a723499ff | 1,266 | package com.qypt.just_syn_asis_version1_0.model;
/**
*
* @author Administrator justson
*
*/
public class EventBussMessage {
private int subscriber;
private String message;
private Object data;
private EventBussMessage(Builder builder)
{
this.subscriber=builder.subscriber;
this.message=builder.message;
this.data=builder.data;
}
public Object getData()
{
return data;
}
public int getSubscriber() {
return subscriber;
}
public void setSubscriber(int subscriber) {
this.subscriber = subscriber;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public static class Builder{
private int subscriber;
private String message;
private Object data;
public Builder()
{
}
public int getSubscriber() {
return subscriber;
}
public Builder setSubscriber(int subscriber) {
this.subscriber = subscriber;
return this;
}
public String getMessage() {
return message;
}
public Builder setMessage(String message) {
this.message = message;
return this;
}
public EventBussMessage build()
{
return new EventBussMessage(this);
}
public Builder setData(Object data)
{
this.data=data;
return this;
}
}
}
| 17.830986 | 48 | 0.703002 |
07ceb85d0bf0785f0fb7924e1f81ea98e416725b | 1,696 | package com.percyvega.lab4sentence.controller;
import java.net.URI;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class SentenceController {
@Autowired
DiscoveryClient discoveryClient;
@Value("${subjectServiceName}")
String subjectServiceName;
@Value("${verbServiceName}")
String verbServiceName;
@Value("${articleServiceName}")
String articleServiceName;
@Value("${adjectiveServiceName}")
String adjectiveServiceName;
@Value("${nounServiceName}")
String nounServiceName;
private RestTemplate restTemplate = new RestTemplate();
@GetMapping
public @ResponseBody String getSentence() {
return
getWordFrom(subjectServiceName) + " " +
getWordFrom(verbServiceName) + " " +
getWordFrom(articleServiceName) + " " +
getWordFrom(adjectiveServiceName) + " " +
getWordFrom(nounServiceName);
}
private String getWordFrom(String serviceName) {
List<ServiceInstance> list = discoveryClient.getInstances(serviceName);
if (list != null && list.size() > 0) {
URI uri = list.get(0).getUri();
if (uri != null) {
return restTemplate.getForObject(uri, String.class);
}
}
return null;
}
}
| 29.754386 | 75 | 0.73408 |
4c8c7418b6a9172774ebe06d18c34e319c369f22 | 273 | package com.cloud.tao.net.model.ordermodel.req;
import com.cloud.tao.net.base.BaseReq;
/**
* Created by gezi-pc on 2016/10/23.
*/
public class AddMessage extends BaseReq{
public String parent_order_id;
public String sub_order_id;
public String message;
}
| 18.2 | 47 | 0.732601 |
7611866d8ecebc22de21dba18e11cf8133e0a9a4 | 383 | package com.alipay.api.response;
import com.alipay.api.AlipayResponse;
/**
* ALIPAY API: alipay.data.aiservice.priceoptimizer.config.sync response.
*
* @author auto create
* @since 1.0, 2019-12-11 20:32:24
*/
public class AlipayDataAiservicePriceoptimizerConfigSyncResponse extends AlipayResponse {
private static final long serialVersionUID = 2499315843432942425L;
}
| 21.277778 | 89 | 0.775457 |
122a4877cf7daf9d736ad6b7c6c323b0270ccec1 | 3,703 | /*
* Copyright 2017 Marcin Szałomski
*
* 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 pl.itrack.client.local.view.widgets;
import com.google.gwt.core.client.Scheduler;
import gwt.material.design.client.constants.HideOn;
import gwt.material.design.client.constants.WavesType;
import gwt.material.design.client.ui.MaterialLink;
import gwt.material.design.client.ui.html.UnorderedList;
import org.jboss.errai.ui.nav.client.local.TransitionTo;
import pl.itrack.client.local.event.PageChange;
import pl.itrack.client.local.event.PageLoaded;
import pl.itrack.client.local.view.FavouritesViewModel;
import pl.itrack.client.local.view.MapTabViewModel;
import pl.itrack.client.local.view.BasePage;
import pl.itrack.client.local.view.HowToViewModel;
import pl.itrack.client.local.view.helpers.Texts;
import javax.annotation.PostConstruct;
import javax.enterprise.event.Event;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
public abstract class NavigationBar extends UnorderedList {
private static final String CSS_CLASS_TAB_ACTIVE = "active";
@Inject private TransitionTo<FavouritesViewModel> toFavourites;
@Inject private TransitionTo<MapTabViewModel> toMap;
@Inject private Event<PageChange> pageChangeEvent;
@Inject protected MaterialLink buttonMap;
@Inject protected MaterialLink buttonFav;
@PostConstruct
public void init() {
configureSimpleButtonLink(buttonMap, Texts.TITLE_MAPS, toMap, isHiddenOnMobile());
configureSimpleButtonLink(buttonFav, Texts.TITLE_FAVOURITES, toFavourites, isHiddenOnMobile());
Scheduler.get().scheduleDeferred(this::addButtons);
}
private void configureSimpleButtonLink(MaterialLink buttonLink, String label, TransitionTo<? extends BasePage> transitTo, boolean hideOnMobile) {
buttonLink.setText(label);
if (hideOnMobile) {
buttonLink.setHideOn(HideOn.HIDE_ON_MED_DOWN);
buttonLink.setWaves(WavesType.LIGHT);
buttonLink.setWaves(WavesType.DEFAULT);
}
buttonLink.addClickHandler(clickEvent -> handleMenuItemClick(transitTo));
}
private void handleMenuItemClick(TransitionTo<? extends BasePage> transitTo) {
transitTo.go();
pageChangeEvent.fire(new PageChange());
}
private void addButtons() {
this.add(buttonMap);
this.add(buttonFav);
}
@SuppressWarnings("unused")
private void updateNavButtons(@Observes PageLoaded event) {
Scheduler.get().scheduleDeferred(() -> selectActiveNavButton(event));
}
void selectActiveNavButton(PageLoaded event) {
if (event.getPageName().equals(FavouritesViewModel.PAGE_NAME) || event.getPageName().equals(HowToViewModel.PAGE_NAME)) {
switchActiveNavButton(buttonFav, buttonMap);
} else {
switchActiveNavButton(buttonMap, buttonFav);
}
}
private void switchActiveNavButton(MaterialLink activeButton, MaterialLink inactiveButton) {
activeButton.getElement().addClassName(CSS_CLASS_TAB_ACTIVE);
inactiveButton.getElement().removeClassName(CSS_CLASS_TAB_ACTIVE);
}
abstract protected boolean isHiddenOnMobile();
}
| 38.175258 | 149 | 0.749122 |
209ac07ae3bad45ace1ce1cf841e7945eb145f7b | 2,229 | /*
* 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.felix.scr.impl.manager;
import java.util.Hashtable;
import java.util.Map;
import junit.framework.TestCase;
public class AbstractComponentManagerTest extends TestCase
{
public void test_copyTo_withoutExclusions()
{
final Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put( "p1", "v1" );
ht.put( "p.2", "v2" );
ht.put( ".p3", "v3" );
final Map<String, Object> dict = AbstractComponentManager.copyToMap( ht, true );
assertNotNull( "Copy result is not null", dict );
assertEquals( "Number of items", 3, dict.size() );
assertEquals( "Value for key p1", "v1", dict.get( "p1" ) );
assertEquals( "Value for key p.2", "v2", dict.get( "p.2" ) );
assertEquals( "Value for key .p3", "v3", dict.get( ".p3" ) );
}
public void test_copyTo_excludingStartingWithDot()
{
final Hashtable<String, String> ht = new Hashtable<String, String>();
ht.put( "p1", "v1" );
ht.put( "p.2", "v2" );
ht.put( ".p3", "v3" );
final Map<String, Object> dict = AbstractComponentManager.copyToMap( ht, false );
assertNotNull( "Copy result is not null", dict );
assertEquals( "Number of items", 2, dict.size() );
assertEquals( "Value for key p1", "v1", dict.get( "p1" ) );
assertEquals( "Value for key p.2", "v2", dict.get( "p.2" ) );
}
}
| 39.105263 | 89 | 0.65231 |
0008702c1196847ceb1d33cae038aea0e58e2bff | 1,340 | import java.util.LinkedList;
class Solution {
public int shortestPathLength(int[][] graph) {
int n = graph.length;
int finalState = (1 << n) - 1; // if n = 4; 1 << 4 => 10000; 10000 - 1? = 1111
LinkedList<int[]> q = new LinkedList<>();
// int[0][1101]: 0: current_node, 1101: visited+nodes
// node 0 jump to node 1
// visited[1][1111] = 1 ? why? 1101 | 0010 = 1111
int[][] visited = new int[n][1 << n]; // 1 << 1 => 10; 1 << 2 => 100; 1 << n => 100000...0;
for (int i = 0; i < n; i++) {
q.add(new int[] { i, 1 << i }); // <{0, 0001}, {1, 0010}, {2, 0100}, {3, 1000}>
}
int steps = 0;
while (q.size() != 0) {
int s = q.size(); // get all the nodes from the same level;
while (s != 0) {
s--;
int[] p = q.removeFirst();
int node = p[0];
int state = p[1];
if (state == finalState)
return steps;
if (visited[node][state] == 1)
continue;
visited[node][state] = 1;
for (int next : graph[node])
q.add(new int[] { next, state | (1 << next) });
}
steps++;
}
return -1;
}
} | 37.222222 | 99 | 0.404478 |
04dcf3e2a1134caae3266c3cf5bf6da06a78f23c | 4,359 | package com.outven.bmtchallange.activities;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.outven.bmtchallange.R;
import com.outven.bmtchallange.helper.Config;
import com.outven.bmtchallange.helper.HidenBar;
import com.outven.bmtchallange.helper.SessionManager;
import java.util.Objects;
import io.sentry.Sentry;
public class ProfilActivity extends AppCompatActivity implements View.OnClickListener {
TextView etName, etPhone, etTanggalLahir,etKelas,etGender, etHp, etEmail;
Button btnLogout, btnEdit;
SessionManager sessionManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profil);
sessionManager = new SessionManager(ProfilActivity.this);
try {
refreshProfil();
} catch (Exception e){
Log.e("Error, ", e.getLocalizedMessage());
sessionManager.loggoutSession();
Toast.makeText(ProfilActivity.this,"Terjadi kesalahan pada server", Toast.LENGTH_LONG).show();
moveToNextPage(ProfilActivity.this);
Sentry.captureException(e);
}
HidenBar.WindowFlag(this, getWindow());
}
private void refreshProfil() {
btnLogout = findViewById(R.id.btnLogout);
btnEdit = findViewById(R.id.btnEdit);
etEmail = findViewById(R.id.etEmail);
etName = findViewById(R.id.etName);
etTanggalLahir = findViewById(R.id.etTanggalLahir);
etPhone = findViewById(R.id.etPhone);
etKelas = findViewById(R.id.etKelas);
etHp = findViewById(R.id.etHp);
etGender = findViewById(R.id.etGender);
// setProfile
etEmail.setText(sessionManager.getUserDetail().get(Config.USER_NISN));
etName.setText(sessionManager.getUserDetail().get(Config.USER_NAME));
etTanggalLahir.setText(sessionManager.getUserDetail().get(Config.USER_LAHIR));
etHp.setText(sessionManager.getUserDetail().get(Config.USER_PHONE));
etGender.setText(radioGenderChecked(Objects.requireNonNull(sessionManager.getUserDetail().get(Config.USER_GENDER))));
etKelas.setText(sessionManager.getUserDetail().get(Config.USER_CLASS));
btnLogout.setOnClickListener(this);
btnEdit.setOnClickListener(this);
}
private String radioGenderChecked(String gender) {
if (gender.equalsIgnoreCase("1")){
return "Laki - laki";
} else {
return "Perempuan";
}
}
private void moveToNextPage(Context context){
Intent intent = new Intent(context, LoginActivity.class);
if (true){
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(intent);
}
@SuppressLint("NonConstantResourceId")
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnLogout:
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
sessionManager.loggoutSession();
Intent intent = new Intent(ProfilActivity.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
overridePendingTransition(R.anim.from_right, R.anim.to_left);
finish();
break;
case R.id.btnEdit:
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
startActivity(new Intent(ProfilActivity.this, EditProfileActivity.class));
overridePendingTransition(R.anim.from_right, R.anim.to_left);
break;
}
}
private long mLastClickTime = 0;
} | 37.25641 | 128 | 0.665749 |
292bc60d68f3763fb2bcc386ba6192b2503a267c | 2,290 | /* SPDX-License-Identifier: Apache-2.0 */
/* Copyright Contributors to the ODPi Egeria project. */
package org.odpi.openmetadata.adapters.repositoryservices.graphrepository.repositoryconnector;
import org.odpi.openmetadata.repositoryservices.connectors.stores.metadatacollectionstore.repositoryconnector.OMRSRepositoryConnector;
import org.odpi.openmetadata.repositoryservices.ffdc.OMRSErrorCode;
import org.odpi.openmetadata.repositoryservices.ffdc.exception.OMRSLogicErrorException;
/**
* The GraphOMRSRepositoryConnector is a connector to a local open metadata repository that uses a graph store
* for its persistence.
*/
public class GraphOMRSRepositoryConnector extends OMRSRepositoryConnector
{
/**
* Default constructor used by the OCF Connector Provider.
*/
public GraphOMRSRepositoryConnector()
{
/*
* Nothing to do (yet !)
*/
}
/**
* Set up the unique Id for this metadata collection.
*
* @param metadataCollectionId String unique Id
*/
@Override
public void setMetadataCollectionId(String metadataCollectionId)
{
String methodName = "setMetadataCollectionId";
super.metadataCollectionId = metadataCollectionId;
try
{
if (metadataCollectionId != null)
{
/*
* Initialize the metadata collection only once the connector is properly set up.
*/
super.metadataCollection = new GraphOMRSMetadataCollection(this, super.serverName,
repositoryHelper, repositoryValidator,
metadataCollectionId, auditLog,
connectionBean.getConfigurationProperties());
}
}
catch (Throwable error)
{
throw new OMRSLogicErrorException(OMRSErrorCode.NULL_METADATA_COLLECTION.getMessageDefinition(repositoryName),
this.getClass().getName(),
methodName,
error);
}
}
} | 37.540984 | 134 | 0.58952 |
e07335bcb8bb134c9594fa83d8bb15e0b75ecf66 | 2,343 | package marubinotto.piggydb.ui.page.control;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import marubinotto.piggydb.ui.page.control.CalendarFocus;
import marubinotto.util.time.DateTime;
import org.junit.Test;
public class CalendarFocusTest {
public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.S";
@Test
public void parseNull() throws Exception {
assertNull(CalendarFocus.parseString(null));
}
// Focus on a month
private CalendarFocus focusOnMonth = CalendarFocus.parseString("201008");
@Test
public void specifiedMonthIsSelected() throws Exception {
assertTrue(this.focusOnMonth.isSelected(
new DateTime(2010, 8, 1), CalendarFocus.Type.MONTH));
}
@Test
public void anotherMonthIsNotSelected() throws Exception {
assertFalse(this.focusOnMonth.isSelected(
new DateTime(2010, 9, 1), CalendarFocus.Type.MONTH));
}
@Test
public void dayIsNotSelected() throws Exception {
assertFalse(this.focusOnMonth.isSelected(
new DateTime(2010, 8, 1), CalendarFocus.Type.DAY));
}
@Test
public void monthInterval() throws Exception {
assertEquals(
"2010-08-01 00:00:00.0",
this.focusOnMonth.toInterval().getStartInstant().format(TIME_FORMAT));
assertEquals(
"2010-08-31 23:59:59.999",
this.focusOnMonth.toInterval().getEndInstant().format(TIME_FORMAT));
}
// Focus on a day
private CalendarFocus focusOnDay = CalendarFocus.parseString("20100830");
@Test
public void specifiedDayIsSelected() throws Exception {
assertTrue(this.focusOnDay.isSelected(
new DateTime(2010, 8, 30), CalendarFocus.Type.DAY));
}
@Test
public void anotherDayIsNotSelected() throws Exception {
assertFalse(this.focusOnDay.isSelected(
new DateTime(2010, 8, 31), CalendarFocus.Type.DAY));
}
@Test
public void monthIsNotSelected() throws Exception {
assertFalse(this.focusOnDay.isSelected(
new DateTime(2010, 8, 30), CalendarFocus.Type.MONTH));
}
@Test
public void dayInterval() throws Exception {
assertEquals(
"2010-08-30 00:00:00.0",
this.focusOnDay.toInterval().getStartInstant().format(TIME_FORMAT));
assertEquals(
"2010-08-30 23:59:59.999",
this.focusOnDay.toInterval().getEndInstant().format(TIME_FORMAT));
}
}
| 27.244186 | 74 | 0.747759 |
fad8dca431591ac4a6c0f99d794020d15c833e90 | 15,119 | package io.flutter.plugin.platform;
import static io.flutter.embedding.engine.systemchannels.PlatformViewsChannel.PlatformViewTouch;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import android.content.Context;
import android.content.res.AssetManager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import io.flutter.embedding.android.FlutterView;
import io.flutter.embedding.android.MotionEventTracker;
import io.flutter.embedding.engine.FlutterJNI;
import io.flutter.embedding.engine.dart.DartExecutor;
import io.flutter.embedding.engine.mutatorsstack.FlutterMutatorView;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.StandardMethodCodec;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
@Config(manifest = Config.NONE)
@RunWith(RobolectricTestRunner.class)
public class PlatformViewsControllerTest {
@Ignore
@Test
public void itNotifiesVirtualDisplayControllersOfViewAttachmentAndDetachment() {
// Setup test structure.
// Create a fake View that represents the View that renders a Flutter UI.
View fakeFlutterView = new View(RuntimeEnvironment.systemContext);
// Create fake VirtualDisplayControllers. This requires internal knowledge of
// PlatformViewsController. We know that all PlatformViewsController does is
// forward view attachment/detachment calls to it's VirtualDisplayControllers.
//
// TODO(mattcarroll): once PlatformViewsController is refactored into testable
// pieces, remove this test and avoid verifying private behavior.
VirtualDisplayController fakeVdController1 = mock(VirtualDisplayController.class);
VirtualDisplayController fakeVdController2 = mock(VirtualDisplayController.class);
// Create the PlatformViewsController that is under test.
PlatformViewsController platformViewsController = new PlatformViewsController();
// Manually inject fake VirtualDisplayControllers into the PlatformViewsController.
platformViewsController.vdControllers.put(0, fakeVdController1);
platformViewsController.vdControllers.put(1, fakeVdController1);
// Execute test & verify results.
// Attach PlatformViewsController to the fake Flutter View.
platformViewsController.attachToView(fakeFlutterView);
// Verify that all virtual display controllers were notified of View attachment.
verify(fakeVdController1, times(1)).onFlutterViewAttached(eq(fakeFlutterView));
verify(fakeVdController1, never()).onFlutterViewDetached();
verify(fakeVdController2, times(1)).onFlutterViewAttached(eq(fakeFlutterView));
verify(fakeVdController2, never()).onFlutterViewDetached();
// Detach PlatformViewsController from the fake Flutter View.
platformViewsController.detachFromView();
// Verify that all virtual display controllers were notified of the View detachment.
verify(fakeVdController1, times(1)).onFlutterViewAttached(eq(fakeFlutterView));
verify(fakeVdController1, times(1)).onFlutterViewDetached();
verify(fakeVdController2, times(1)).onFlutterViewAttached(eq(fakeFlutterView));
verify(fakeVdController2, times(1)).onFlutterViewDetached();
}
@Ignore
@Test
public void itCancelsOldPresentationOnResize() {
// Setup test structure.
// Create a fake View that represents the View that renders a Flutter UI.
View fakeFlutterView = new View(RuntimeEnvironment.systemContext);
// Create fake VirtualDisplayControllers. This requires internal knowledge of
// PlatformViewsController. We know that all PlatformViewsController does is
// forward view attachment/detachment calls to it's VirtualDisplayControllers.
//
// TODO(mattcarroll): once PlatformViewsController is refactored into testable
// pieces, remove this test and avoid verifying private behavior.
VirtualDisplayController fakeVdController1 = mock(VirtualDisplayController.class);
SingleViewPresentation presentation = fakeVdController1.presentation;
fakeVdController1.resize(10, 10, null);
assertEquals(fakeVdController1.presentation != presentation, true);
assertEquals(presentation.isShowing(), false);
}
@Test
public void itUsesActionEventTypeFromFrameworkEventForVirtualDisplays() {
MotionEventTracker motionEventTracker = MotionEventTracker.getInstance();
PlatformViewsController platformViewsController = new PlatformViewsController();
MotionEvent original =
MotionEvent.obtain(
100, // downTime
100, // eventTime
1, // action
0, // x
0, // y
0 // metaState
);
// track an event that will later get passed to us from framework
MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original);
PlatformViewTouch frameWorkTouch =
new PlatformViewTouch(
0, // viewId
original.getDownTime(),
original.getEventTime(),
2, // action
1, // pointerCount
Arrays.asList(Arrays.asList(0, 0)), // pointer properties
Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords
original.getMetaState(),
original.getButtonState(),
original.getXPrecision(),
original.getYPrecision(),
original.getDeviceId(),
original.getEdgeFlags(),
original.getSource(),
original.getFlags(),
motionEventId.getId());
MotionEvent resolvedEvent =
platformViewsController.toMotionEvent(
1, // density
frameWorkTouch,
true // usingVirtualDisplays
);
assertEquals(resolvedEvent.getAction(), frameWorkTouch.action);
assertNotEquals(resolvedEvent.getAction(), original.getAction());
}
@Ignore
@Test
public void itUsesActionEventTypeFromMotionEventForHybridPlatformViews() {
MotionEventTracker motionEventTracker = MotionEventTracker.getInstance();
PlatformViewsController platformViewsController = new PlatformViewsController();
MotionEvent original =
MotionEvent.obtain(
100, // downTime
100, // eventTime
1, // action
0, // x
0, // y
0 // metaState
);
// track an event that will later get passed to us from framework
MotionEventTracker.MotionEventId motionEventId = motionEventTracker.track(original);
PlatformViewTouch frameWorkTouch =
new PlatformViewTouch(
0, // viewId
original.getDownTime(),
original.getEventTime(),
2, // action
1, // pointerCount
Arrays.asList(Arrays.asList(0, 0)), // pointer properties
Arrays.asList(Arrays.asList(0., 1., 2., 3., 4., 5., 6., 7., 8.)), // pointer coords
original.getMetaState(),
original.getButtonState(),
original.getXPrecision(),
original.getYPrecision(),
original.getDeviceId(),
original.getEdgeFlags(),
original.getSource(),
original.getFlags(),
motionEventId.getId());
MotionEvent resolvedEvent =
platformViewsController.toMotionEvent(
1, // density
frameWorkTouch,
false // usingVirtualDisplays
);
assertNotEquals(resolvedEvent.getAction(), frameWorkTouch.action);
assertEquals(resolvedEvent.getAction(), original.getAction());
}
@Test
public void getPlatformViewById__hybridComposition() {
PlatformViewsController platformViewsController = new PlatformViewsController();
int platformViewId = 0;
assertNull(platformViewsController.getPlatformViewById(platformViewId));
PlatformViewFactory viewFactory = mock(PlatformViewFactory.class);
PlatformView platformView = mock(PlatformView.class);
View androidView = mock(View.class);
when(platformView.getView()).thenReturn(androidView);
when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView);
platformViewsController.getRegistry().registerViewFactory("testType", viewFactory);
FlutterJNI jni = new FlutterJNI();
attach(jni, platformViewsController);
// Simulate create call from the framework.
createPlatformView(jni, platformViewsController, platformViewId, "testType");
platformViewsController.initializePlatformViewIfNeeded(platformViewId);
View resultAndroidView = platformViewsController.getPlatformViewById(platformViewId);
assertNotNull(resultAndroidView);
assertEquals(resultAndroidView, androidView);
}
@Test
public void initializePlatformViewIfNeeded__throwsIfViewIsNull() {
PlatformViewsController platformViewsController = new PlatformViewsController();
int platformViewId = 0;
assertNull(platformViewsController.getPlatformViewById(platformViewId));
PlatformViewFactory viewFactory = mock(PlatformViewFactory.class);
PlatformView platformView = mock(PlatformView.class);
when(platformView.getView()).thenReturn(null);
when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView);
platformViewsController.getRegistry().registerViewFactory("testType", viewFactory);
FlutterJNI jni = new FlutterJNI();
attach(jni, platformViewsController);
// Simulate create call from the framework.
createPlatformView(jni, platformViewsController, platformViewId, "testType");
try {
platformViewsController.initializePlatformViewIfNeeded(platformViewId);
} catch (Exception exception) {
assertTrue(exception instanceof IllegalStateException);
assertEquals(
exception.getMessage(),
"PlatformView#getView() returned null, but an Android view reference was expected.");
return;
}
assertTrue(false);
}
@Test
public void initializePlatformViewIfNeeded__throwsIfViewHasParent() {
PlatformViewsController platformViewsController = new PlatformViewsController();
int platformViewId = 0;
assertNull(platformViewsController.getPlatformViewById(platformViewId));
PlatformViewFactory viewFactory = mock(PlatformViewFactory.class);
PlatformView platformView = mock(PlatformView.class);
View androidView = mock(View.class);
when(androidView.getParent()).thenReturn(mock(ViewParent.class));
when(platformView.getView()).thenReturn(androidView);
when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView);
platformViewsController.getRegistry().registerViewFactory("testType", viewFactory);
FlutterJNI jni = new FlutterJNI();
attach(jni, platformViewsController);
// Simulate create call from the framework.
createPlatformView(jni, platformViewsController, platformViewId, "testType");
try {
platformViewsController.initializePlatformViewIfNeeded(platformViewId);
} catch (Exception exception) {
assertTrue(exception instanceof IllegalStateException);
assertEquals(
exception.getMessage(),
"The Android view returned from PlatformView#getView() was already added to a parent view.");
return;
}
assertTrue(false);
}
@Test
public void disposeAndroidView__hybridComposition() {
PlatformViewsController platformViewsController = new PlatformViewsController();
int platformViewId = 0;
assertNull(platformViewsController.getPlatformViewById(platformViewId));
PlatformViewFactory viewFactory = mock(PlatformViewFactory.class);
PlatformView platformView = mock(PlatformView.class);
Context context = RuntimeEnvironment.application.getApplicationContext();
View androidView = new View(context);
when(platformView.getView()).thenReturn(androidView);
when(viewFactory.create(any(), eq(platformViewId), any())).thenReturn(platformView);
platformViewsController.getRegistry().registerViewFactory("testType", viewFactory);
FlutterJNI jni = new FlutterJNI();
attach(jni, platformViewsController);
// Simulate create call from the framework.
createPlatformView(jni, platformViewsController, platformViewId, "testType");
platformViewsController.initializePlatformViewIfNeeded(platformViewId);
assertNotNull(androidView.getParent());
assertTrue(androidView.getParent() instanceof FlutterMutatorView);
// Simulate dispose call from the framework.
disposePlatformView(jni, platformViewsController, platformViewId);
assertNull(androidView.getParent());
// Simulate create call from the framework.
createPlatformView(jni, platformViewsController, platformViewId, "testType");
platformViewsController.initializePlatformViewIfNeeded(platformViewId);
assertNotNull(androidView.getParent());
assertTrue(androidView.getParent() instanceof FlutterMutatorView);
}
private static byte[] encodeMethodCall(MethodCall call) {
ByteBuffer buffer = StandardMethodCodec.INSTANCE.encodeMethodCall(call);
buffer.rewind();
byte[] dest = new byte[buffer.remaining()];
buffer.get(dest);
return dest;
}
private static void createPlatformView(
FlutterJNI jni,
PlatformViewsController platformViewsController,
int platformViewId,
String viewType) {
Map<String, Object> platformViewCreateArguments = new HashMap<>();
platformViewCreateArguments.put("hybrid", true);
platformViewCreateArguments.put("id", platformViewId);
platformViewCreateArguments.put("viewType", viewType);
platformViewCreateArguments.put("direction", 0);
MethodCall platformCreateMethodCall = new MethodCall("create", platformViewCreateArguments);
jni.handlePlatformMessage(
"flutter/platform_views", encodeMethodCall(platformCreateMethodCall), /*replyId=*/ 0);
}
private static void disposePlatformView(
FlutterJNI jni, PlatformViewsController platformViewsController, int platformViewId) {
Map<String, Object> platformViewDisposeArguments = new HashMap<>();
platformViewDisposeArguments.put("hybrid", true);
platformViewDisposeArguments.put("id", platformViewId);
MethodCall platformDisposeMethodCall = new MethodCall("dispose", platformViewDisposeArguments);
jni.handlePlatformMessage(
"flutter/platform_views", encodeMethodCall(platformDisposeMethodCall), /*replyId=*/ 0);
}
private void attach(FlutterJNI jni, PlatformViewsController platformViewsController) {
DartExecutor executor = new DartExecutor(jni, mock(AssetManager.class));
executor.onAttachedToJNI();
Context context = RuntimeEnvironment.application.getApplicationContext();
platformViewsController.attach(context, null, executor);
platformViewsController.attachToView(mock(FlutterView.class));
}
}
| 40.642473 | 103 | 0.737946 |
4b1a0d9f447460d562badbe6c3f6316916d8eca0 | 221 | package Test.Shildt_G.System_class;
/**
* Created by Антон on 18.05.2017.
*/
public class ShowUserDir {
public static void main(String[] args) {
System.out.println(System.getProperty("user.name"));
}
}
| 20.090909 | 60 | 0.669683 |
94afd0369496be3b4d213b5c6546ea16eb439005 | 4,673 | /**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* Connector.java *
* *
* hprose Connector class for Java. *
* *
* LastModified: Apr 23, 2018 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
package hprose.net;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;
public final class Connector extends Thread {
protected final AtomicInteger size = new AtomicInteger(0);
private final Selector selector;
private final ReactorGroup reactor;
private final Queue<Connection> queue = new ConcurrentLinkedQueue<Connection>();
public Connector(int reactorThreads) throws IOException {
this.selector = Selector.open();
this.reactor = new ReactorGroup(reactorThreads);
}
@Override
public final void run() {
reactor.start();
try {
while (!isInterrupted()) {
try {
process();
dispatch();
}
catch (IOException e) {}
}
}
catch (ClosedSelectorException e) {}
reactor.close();
}
public final void close() {
try {
selector.close();
}
catch (IOException e) {}
}
private void process() {
for (;;) {
final Connection conn = queue.poll();
if (conn == null) {
break;
}
try {
conn.connect(selector);
}
catch (Exception e) {
conn.timeoutClose();
}
}
}
private void dispatch() throws IOException {
int n = selector.select();
if (n == 0) return;
Iterator<SelectionKey> it = selector.selectedKeys().iterator();
while (it.hasNext()) {
SelectionKey key = it.next();
it.remove();
if (key.isConnectable()) {
connect(key);
}
}
}
private void connect(SelectionKey key) {
final SocketChannel channel = (SocketChannel) key.channel();
Connection conn = (Connection)key.attachment();
boolean success = false;
if (channel.isConnectionPending()) {
try {
success = channel.finishConnect();
}
catch (IOException e) {
conn.timeoutClose();
}
}
else {
success = true;
}
if (success) {
reactor.register(conn);
key.cancel();
}
}
private void register(Connection conn) {
queue.offer(conn);
selector.wakeup();
}
public final void create(String uri, ConnectionHandler handler, boolean keepAlive, boolean noDelay) throws IOException {
try {
URI u = new URI(uri);
SocketChannel channel = SocketChannel.open();
InetSocketAddress address = new InetSocketAddress(u.getHost(), u.getPort());
Connection conn = new Connection(channel, handler, address);
handler.onConnect(conn);
channel.configureBlocking(false);
channel.socket().setReuseAddress(true);
channel.socket().setKeepAlive(keepAlive);
channel.socket().setTcpNoDelay(noDelay);
register(conn);
}
catch (URISyntaxException e) {
throw new IOException(e.getMessage());
}
}
}
| 33.378571 | 124 | 0.462016 |
622dd484587058caa5d05d6ed2620e6c3253aca3 | 2,144 | /**
* copyright © Nusino Technologies Inc, 2021, All rights reserved.
* dhuang05@gmail.com
*/
package com.nusino.microservices.service.buscalendar.expr.stdexpr.func.builtin;
import com.nusino.microservices.service.buscalendar.expr.stdexpr.func.AddOnExprHandler;
import com.nusino.microservices.service.buscalendar.util.CommonUtil;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
public class EasterSundayFunction implements AddOnExprHandler {
private Pattern EASTER_SUNDAY_PREFIX_REGEX = Pattern.compile("^(EASTER[\\s]{0,})");
private static String KEY_WORD = "SUNDAY";
@Override
public boolean isMyExpr(String expr) {
if(expr == null) {
return false;
}
expr = expr.toUpperCase().trim();
if(EASTER_SUNDAY_PREFIX_REGEX.matcher(expr.toUpperCase().trim()).find()) {
String prefix = CommonUtil.fetchRegexAtGroup(EASTER_SUNDAY_PREFIX_REGEX, expr,1);
expr = expr.substring(prefix.length());
String keyword = getKeyWord();
return keyword.startsWith(expr.trim());
}
return false;
}
@Override
public List<String> exprDescs() {
return Arrays.asList(new String[] {"Easter Sunday"});
}
@Override
public List<LocalDate> calculate(int year, String expr) {
List<LocalDate> dates = new ArrayList<>();
dates.add(findEasterSunday(year));
return dates;
}
protected LocalDate findEasterSunday(int year) {
List<LocalDate> dates = new ArrayList<>();
int g = year % 19;
int c = year / 100;
int h = (c - (c / 4) - ((8 * c + 13) / 25) + 19 * g + 15) % 30;
int i = h - (h / 28) * (1 - (h / 28) * (29 / (h + 1)) * ((21 - g) / 11));
int day = (i - ((year + (year / 4) + i + 2 - c + (c / 4)) % 7) + 28);
int month = 3;
if (day > 31) {
month = month + 1;
day -= 31;
}
return LocalDate.of(year, month, day);
}
protected String getKeyWord() {
return KEY_WORD;
}
}
| 32 | 93 | 0.602146 |
fbed6d44d703afcf17931cb341fb430e3a5d1aee | 33,596 | TOPIC:-SERIALIZATION
--------
VIDEO NO=3
---------
Customized Serialization(Part -1)(1:24:54)
NUMBER OF PICTURES=NULL
------------------
VIDEO COMPLETED=YES
-----------------
(Just check it once)
IMPORTANT EXAMPLES:-
----------------->START OF EXAMPLES<---------------------------
Example=1
=========
NOTE:-
-----
PROGRAME=1
=========
EXPLANATION:-
============
Page 298
Page 298
class Account implements Serializable
{
String Username="Vinay";
transient String Password="Gosling";//Here password is secure,so declare with transient
}
Creating one Account name
Account a1=new Account();
Sopln(a1.username);
Sopln(a1.password);
o/p:-
-----
Vinay
Gosling.
Assume we want to seriliaze this account object.
Account a1=new Account();
FileOutputStream fos=new FileOutputStream ("abc.ser");
ObjectOutputStream oos=new FileOutputStream (oos);
oos.WritObject(a1);
Here JVM is ignore transient variable value and save the default value to file.
here password variable is transient so it saves password as null to "abc.ser" during serialization.
De-serialize
FileInputStream fos=new FileInputStream ("abc.ser");
ObjectInputStream oos=new FileInputStream (oos);
Account a2=(Account)oos.readObject(a1);
Sopln(a2.username+""+a2.password);
o/p:-
---
Vinay
null
Here password is null after de-serilaization.
so there is loss of information.
due to declaring password variable as transient..
If we want to obtain the loss of information happened during
de-serilization then we need to go for Customized de-serilization.
***************************-----END of--->1<--------***************************
Example=2
=========
NOTE:-
-----
PROGRAME=2
=========
import java.io.*;
class Test implements Serializable {
String userName = "Vinay";
transient String pwd = "Gosling";
}
class CustomizedSerializeDemo {
public static void main(String[] args) throws Exception {
Test a1 = new Test();
System.out.println(a1.userName + "........." + a1.pwd);
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Test a2 = (Test) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java CustomizedSerializeDemo
Vinay.........Gosling
Vinay.........null
C:\Users\DELL\Desktop>
EXPLANATION:-
============
During default Serilization there may be a chance of loss of informatio
Bcoz of transient keyword.
***************************-----END of--->2<--------***************************
Example=3
=========
NOTE:-
-----
PROGRAME=3
=========
EXPLANATION:-
============
customized Serilization
Durga sending money from senu,hiding money under mango and sending to his father..
here sender side i.e durga did some extra work by hiding money and placing money..
At reciever side his dad did nt got money directly he got by removing mangos and
wrapping off plastic covers..
Later he got money..receiever also did some eztra work.
Doing Extra work both at sender side and receiever side.
we can acheive customized serilization..
***************************-----END of--->3<--------***************************
Example=4
=========
NOTE:-
-----
PROGRAME=4
=========
EXPLANATION:-
============
Page 299:-
---------
We can implement customized serilization by using the following 2 methods.
1)private void WriteObject(ObjectOutputStream os) throws Exception
This method will be executed automatically at the time serialization.
hence at the time of serilization.If we want to perform any activity ,we have to define that
in inside method only.
2)private void ReadObject(ObjectInputStream is) throws Exception
This method will be executed automatically at the time De-serialization.
hence at the time of De-serilization.If we want to perform any activity ,we have to define that
in inside method only.
Important Point:-
1) Point
The above methods are callback methods bcoz these are executed automatically by the
JVM.
Here 2 mehtods
1)private void WriteObject(ObjectOutputStream os) throws Exception
2)private void ReadObject(ObjectInputStream is) throws Exception
will be executed automatiacally by the JVM..
Programmer cannot call this method..
These types of methods are called call-back methods.
Ex:-
main method-->JVM responsible to call mmain method.
lifecyclemethod or servlet method----> unit method is responsible.
destryoy method,service method()...etc
2)Point(** important point)
While performing which object serialization,we have to do extra work.in the corresponding class
we have to define below 2 methods
EX:-
While performing Account object serialization,if we require to do extra work.
we have to write these below 2 methods in Account class.
If we write in some other class.It might not work
1)private void WriteObject(ObjectOutputStream os) throws Exception
2)private void ReadObject(ObjectInputStream is) throws Exception
***************************-----END of--->4<--------***************************
Example=5
=========
NOTE:-
-----
In the below programe Account Object can provide proper username and pwd..
PROGRAME=5
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
//Point:-1
private void writeObject(ObjectOutputStream os) throws Exception
{
os.defaultWriteObject(); //do default serialization frist.
String epwd = "123" + pwd; //prepare encrypted password
os.writeObject(epwd); //write encrypted passwrd manually to file.
}
//Point:-2
private void readObject(ObjectInputStream is) throws Exception
{
is.defaultReadObject(); //do default De-serialization frist.
String epwd = (String) is.readObject(); // Read encrypted password
pwd = epwd.substring(3); //assign decripted epwd to pwd.
//remove 3 Strings from String using SubString
//and assign to pwd.
}
}
class Test {
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//durga //anushka
//Before Serialization. //Point 1
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization. //Point 2
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Bhaskar.........kajal
C:\Users\DELL\Desktop>
EXPLANATION:-
============
Point:-1
Whenever we are trying to serialize an Account Object JVM is gonna check
wheather there is a writeObject () method is there in class..If its there then
JVM gonna Execute that method..
Point 2:-
When ever we are De-serializing an Account Object JVM is gonna check wheather there is
readObject() method is there in Acoount class.
If its there JVM is gonna Execute readObject() method automatically.
Here Account.class file should be avaliable at in the begining only.
Coz at sendr side writeObject() method will Execute.
Coz at receiever side ReadObject() method will Execute.
Account.class file should should be avaliable at senser and reciever
in the begining only.
Outside of class Programmer cannot call private methods.
But JVM can call private methods outside of class,that flexibity/ability is there for JVM.
1)private void WriteObject(ObjectOutputStream os) throws Exception
2)private void ReadObject(ObjectInputStream is) throws Exception
***************************-----END of--->5<--------***************************
Example=6
=========
NOTE:-
-----
No customized Serialization coz we have commented the methods..
PROGRAME=6
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
//commenting customized serilization methods
/*private void writeObject(ObjectOutputStream os) throws Exception
{
os.defaultWriteObject();
String epwd = "123" + pwd;
os.writeObject(epwd);
}
private void readObject(ObjectInputStream is) throws Exception
{
is.defaultReadObject();
String epwd = (String) is.readObject();
pwd = epwd.substring(3);
}*/
}
class Test {
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//Before Serialization.
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization.
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Bhaskar.........null
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->6<--------***************************
Example=7
=========
NOTE:-
-----
PROGRAME=7
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
}
class Test {
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//Before Serialization.
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization.
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Bhaskar.........null
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->7<--------***************************
Example=8
=========
NOTE:-
-----
PROGRAME=8
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
//commenting customized serilization method
/*
private void writeObject(ObjectOutputStream os) throws Exception
{
os.defaultWriteObject();
String epwd = "123" + pwd;
os.writeObject(epwd);
}*/
private void readObject(ObjectInputStream is) throws Exception
{
is.defaultReadObject();
String epwd = (String) is.readObject();
pwd = epwd.substring(3);
}
}
class Test {
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//Before Serialization.
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization.
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Exception in thread "main" java.io.OptionalDataException
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1496)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at Account.readObject(Test.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2122)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2013)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
at Test.main(Test.java:45)
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->8<--------***************************
Example=9
=========
NOTE:-
-----
PROGRAME=9
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
//commenting customized serilization method
private void writeObject(ObjectOutputStream os) throws Exception
{
os.defaultWriteObject();
String epwd = "123" + pwd;
os.writeObject(epwd);
}
/*
private void readObject(ObjectInputStream is) throws Exception
{
is.defaultReadObject();
String epwd = (String) is.readObject();
pwd = epwd.substring(3);
}*/
}
class Test {
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//Before Serialization.
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization.
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Bhaskar.........null
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->9<--------***************************
Example=10
=========
NOTE:-
-----
Instead of private modifier if we are using any other modifier these 2 methods
won t work..
public void writeObject(ObjectOutputStream os) throws Exception
public void readObject(ObjectInputStream is) throws Exception
Coz JVM undesrtable form is private.
private void writeObject(ObjectOutputStream os) throws Exception
private void readObject(ObjectInputStream is) throws Exception
PROGRAME=10
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
//commenting customized serilization method
public void writeObject(ObjectOutputStream os) throws Exception
{
os.defaultWriteObject();
String epwd = "123" + pwd;
os.writeObject(epwd);
}
public void readObject(ObjectInputStream is) throws Exception
{
is.defaultReadObject();
String epwd = (String) is.readObject();
pwd = epwd.substring(3);
}
}
class Test
{
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//Before Serialization.
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization.
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Bhaskar.........null
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->10<--------***************************
Example=11
=========
NOTE:-
-----
PROGRAME=11
=========
import java.io.*;
class Account implements Serializable {
String userName = "Bhaskar";
transient String pwd = "kajal";
//commenting customized serilization method
public void writeObject(ObjectOutputStream os) throws Exception
{
os.defaultWriteObject();
String epwd = "123" + pwd;
os.writeObject(epwd);
}
public void readObject(ObjectInputStream is) throws Exception
{
is.defaultReadObject();
String epwd = (String) is.readObject();
pwd = epwd.substring(3);
}
}
class Test
{
public static void main(String[] args) throws Exception {
Account a1 = new Account();
System.out.println(a1.userName + "........." + a1.pwd);
//Before Serialization.
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(a1);
//After Serialization.
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Account a2 = (Account) ois.readObject();
System.out.println(a2.userName + "........." + a2.pwd);
}
}
C:\Users\DELL\Desktop>javac Test.java
C:\Users\DELL\Desktop>java Test
Bhaskar.........kajal
Bhaskar.........null
C:\Users\DELL\Desktop>
EXPLANATION:-
============
***************************-----END of--->11<--------***************************
Example=12
=========
NOTE:-
-----
PROGRAME=12
=========
Here once delete Account.class file after compiling and run it..
See wats the output.. did nt check it..check once..
EXPLANATION:-
============
***************************-----END of--->12<--------***************************
Example=13
=========
NOTE:-
-----
PROGRAME=13
=========
EXPLANATION:-
============
***************************-----END of--->13<--------***************************
Example=14
=========
NOTE:-
-----
PROGRAME=14
=========
EXPLANATION:-
============
***************************-----END of--->14<--------***************************
Example=15
=========
NOTE:-
-----
PROGRAME=15
=========
EXPLANATION:-
============
***************************-----END of--->15<--------***************************
Example=16
=========
NOTE:-
-----
PROGRAME=16
=========
EXPLANATION:-
============
***************************-----END of--->16<--------***************************
Example=17
=========
NOTE:-
-----
PROGRAME=17
=========
EXPLANATION:-
============
***************************-----END of--->17<--------***************************
Example=18
=========
NOTE:-
-----
PROGRAME=18
=========
EXPLANATION:-
============
***************************-----END of--->18<--------***************************
Example=19
=========
NOTE:-
-----
PROGRAME=19
=========
EXPLANATION:-
============
***************************-----END of--->19<--------***************************
Example=20
=========
NOTE:-
-----
PROGRAME=20
=========
EXPLANATION:-
============
***************************-----END of--->20<--------***************************
Example=21
=========
NOTE:-
-----
PROGRAME=21
=========
EXPLANATION:-
============
***************************-----END of--->21<--------***************************
Example=22
=========
NOTE:-
-----
PROGRAME=22
=========
EXPLANATION:-
============
***************************-----END of--->22<--------***************************
Example=23
=========
NOTE:-
-----
PROGRAME=23
=========
EXPLANATION:-
============
***************************-----END of--->23<--------***************************
Example=24
=========
NOTE:-
-----
PROGRAME=24
=========
EXPLANATION:-
============
***************************-----END of--->24<--------***************************
Example=25
=========
NOTE:-
-----
PROGRAME=25
=========
EXPLANATION:-
============
***************************-----END of--->25<--------***************************
Example=26
=========
NOTE:-
-----
PROGRAME=26
=========
EXPLANATION:-
============
***************************-----END of--->26<--------***************************
Example=27
=========
NOTE:-
-----
PROGRAME=27
=========
EXPLANATION:-
============
***************************-----END of--->27<--------***************************
Example=28
=========
NOTE:-
-----
PROGRAME=28
=========
EXPLANATION:-
============
***************************-----END of--->28<--------***************************
Example=29
=========
NOTE:-
-----
PROGRAME=29
=========
EXPLANATION:-
============
***************************-----END of--->29<--------***************************
Example=30
=========
NOTE:-
-----
PROGRAME=30
=========
EXPLANATION:-
============
***************************-----END of--->30<--------***************************
Example=31
=========
NOTE:-
-----
PROGRAME=31
=========
EXPLANATION:-
============
***************************-----END of--->31<--------***************************
Example=32
=========
NOTE:-
-----
PROGRAME=32
=========
EXPLANATION:-
============
***************************-----END of--->32<--------***************************
Example=33
=========
NOTE:-
-----
PROGRAME=33
=========
EXPLANATION:-
============
***************************-----END of--->33<--------***************************
Example=34
=========
NOTE:-
-----
PROGRAME=34
=========
EXPLANATION:-
============
***************************-----END of--->34<--------***************************
Example=35
=========
NOTE:-
-----
PROGRAME=35
=========
EXPLANATION:-
============
***************************-----END of--->35<--------***************************
Example=36
=========
NOTE:-
-----
PROGRAME=36
=========
EXPLANATION:-
============
***************************-----END of--->36<--------***************************
Example=37
=========
NOTE:-
-----
PROGRAME=37
=========
EXPLANATION:-
============
***************************-----END of--->37<--------***************************
Example=38
=========
NOTE:-
-----
PROGRAME=38
=========
EXPLANATION:-
============
***************************-----END of--->38<--------***************************
Example=39
=========
NOTE:-
-----
PROGRAME=39
=========
EXPLANATION:-
============
***************************-----END of--->39<--------***************************
Example=40
=========
NOTE:-
-----
PROGRAME=40
=========
EXPLANATION:-
============
***************************-----END of--->40<--------***************************
Example=41
=========
NOTE:-
-----
PROGRAME=41
=========
EXPLANATION:-
============
***************************-----END of--->41<--------***************************
Example=42
=========
NOTE:-
-----
PROGRAME=42
=========
EXPLANATION:-
============
***************************-----END of--->42<--------***************************
Example=43
=========
NOTE:-
-----
PROGRAME=43
=========
EXPLANATION:-
============
***************************-----END of--->43<--------***************************
Example=44
=========
NOTE:-
-----
PROGRAME=44
=========
EXPLANATION:-
============
***************************-----END of--->44<--------***************************
Example=45
=========
NOTE:-
-----
PROGRAME=45
=========
EXPLANATION:-
============
***************************-----END of--->45<--------***************************
Example=46
=========
NOTE:-
-----
PROGRAME=46
=========
EXPLANATION:-
============
***************************-----END of--->46<--------***************************
Example=47
=========
NOTE:-
-----
PROGRAME=47
=========
EXPLANATION:-
============
***************************-----END of--->47<--------***************************
Example=48
=========
NOTE:-
-----
PROGRAME=48
=========
EXPLANATION:-
============
***************************-----END of--->48<--------***************************
Example=49
=========
NOTE:-
-----
PROGRAME=49
=========
EXPLANATION:-
============
***************************-----END of--->49<--------***************************
Example=50
=========
NOTE:-
-----
PROGRAME=50
=========
EXPLANATION:-
============
***************************-----END of--->50<--------***************************
Example=51
=========
NOTE:-
-----
PROGRAME=51
=========
EXPLANATION:-
============
***************************-----END of--->51<--------***************************
Example=52
=========
NOTE:-
-----
PROGRAME=52
=========
EXPLANATION:-
============
***************************-----END of--->52<--------***************************
Example=53
=========
NOTE:-
-----
PROGRAME=53
=========
EXPLANATION:-
============
***************************-----END of--->53<--------***************************
Example=54
=========
NOTE:-
-----
PROGRAME=54
=========
EXPLANATION:-
============
***************************-----END of--->54<--------***************************
Example=55
=========
NOTE:-
-----
PROGRAME=55
=========
EXPLANATION:-
============
***************************-----END of--->55<--------***************************
Example=56
=========
NOTE:-
-----
PROGRAME=56
=========
EXPLANATION:-
============
***************************-----END of--->56<--------***************************
Example=57
=========
NOTE:-
-----
PROGRAME=57
=========
EXPLANATION:-
============
***************************-----END of--->57<--------***************************
Example=58
=========
NOTE:-
-----
PROGRAME=58
=========
EXPLANATION:-
============
***************************-----END of--->58<--------***************************
Example=59
=========
NOTE:-
-----
PROGRAME=59
=========
EXPLANATION:-
============
***************************-----END of--->59<--------***************************
Example=60
=========
NOTE:-
-----
PROGRAME=60
=========
EXPLANATION:-
============
***************************-----END of--->60<--------***************************
Example=61
=========
NOTE:-
-----
PROGRAME=61
=========
EXPLANATION:-
============
***************************-----END of--->61<--------***************************
Example=62
=========
NOTE:-
-----
PROGRAME=62
=========
EXPLANATION:-
============
***************************-----END of--->62<--------***************************
Example=63
=========
NOTE:-
-----
PROGRAME=63
=========
EXPLANATION:-
============
***************************-----END of--->63<--------***************************
Example=64
=========
NOTE:-
-----
PROGRAME=64
=========
EXPLANATION:-
============
***************************-----END of--->64<--------***************************
Example=65
=========
NOTE:-
-----
PROGRAME=65
=========
EXPLANATION:-
============
***************************-----END of--->65<--------***************************
Example=66
=========
NOTE:-
-----
PROGRAME=66
=========
EXPLANATION:-
============
***************************-----END of--->66<--------***************************
Example=67
=========
NOTE:-
-----
PROGRAME=67
=========
EXPLANATION:-
============
***************************-----END of--->67<--------***************************
Example=68
=========
NOTE:-
-----
PROGRAME=68
=========
EXPLANATION:-
============
***************************-----END of--->68<--------***************************
Example=69
=========
NOTE:-
-----
PROGRAME=69
=========
EXPLANATION:-
============
***************************-----END of--->69<--------***************************
Example=70
=========
NOTE:-
-----
PROGRAME=70
=========
EXPLANATION:-
============
***************************-----END of--->70<--------***************************
Example=71
=========
NOTE:-
-----
PROGRAME=71
=========
EXPLANATION:-
============
***************************-----END of--->71<--------***************************
Example=72
=========
NOTE:-
-----
PROGRAME=72
=========
EXPLANATION:-
============
***************************-----END of--->72<--------***************************
Example=73
=========
NOTE:-
-----
PROGRAME=73
=========
EXPLANATION:-
============
***************************-----END of--->73<--------***************************
Example=74
=========
NOTE:-
-----
PROGRAME=74
=========
EXPLANATION:-
============
***************************-----END of--->74<--------***************************
Example=75
=========
NOTE:-
-----
PROGRAME=75
=========
EXPLANATION:-
============
***************************-----END of--->75<--------***************************
Example=76
=========
NOTE:-
-----
PROGRAME=76
=========
EXPLANATION:-
============
***************************-----END of--->76<--------***************************
Example=77
=========
NOTE:-
-----
PROGRAME=77
=========
EXPLANATION:-
============
***************************-----END of--->77<--------***************************
Example=78
=========
NOTE:-
-----
PROGRAME=78
=========
EXPLANATION:-
============
***************************-----END of--->78<--------***************************
Example=79
=========
NOTE:-
-----
PROGRAME=79
=========
EXPLANATION:-
============
***************************-----END of--->79<--------***************************
Example=80
=========
NOTE:-
-----
PROGRAME=80
=========
EXPLANATION:-
============
***************************-----END of--->80<--------***************************
Example=81
=========
NOTE:-
-----
PROGRAME=81
=========
EXPLANATION:-
============
***************************-----END of--->81<--------***************************
Example=82
=========
NOTE:-
-----
PROGRAME=82
=========
EXPLANATION:-
============
***************************-----END of--->82<--------***************************
Example=83
=========
NOTE:-
-----
PROGRAME=83
=========
EXPLANATION:-
============
***************************-----END of--->83<--------***************************
Example=84
=========
NOTE:-
-----
PROGRAME=84
=========
EXPLANATION:-
============
***************************-----END of--->84<--------***************************
Example=85
=========
NOTE:-
-----
PROGRAME=85
=========
EXPLANATION:-
============
***************************-----END of--->85<--------***************************
Example=86
=========
NOTE:-
-----
PROGRAME=86
=========
EXPLANATION:-
============
***************************-----END of--->86<--------***************************
Example=87
=========
NOTE:-
-----
PROGRAME=87
=========
EXPLANATION:-
============
***************************-----END of--->87<--------***************************
Example=88
=========
NOTE:-
-----
PROGRAME=88
=========
EXPLANATION:-
============
***************************-----END of--->88<--------***************************
Example=89
=========
NOTE:-
-----
PROGRAME=89
=========
EXPLANATION:-
============
***************************-----END of--->89<--------***************************
Example=90
=========
NOTE:-
-----
PROGRAME=90
=========
EXPLANATION:-
============
***************************-----END of--->90<--------***************************
Example=91
=========
NOTE:-
-----
PROGRAME=91
=========
EXPLANATION:-
============
***************************-----END of--->91<--------***************************
Example=92
=========
NOTE:-
-----
PROGRAME=92
=========
EXPLANATION:-
============
***************************-----END of--->92<--------***************************
Example=93
=========
NOTE:-
-----
PROGRAME=93
=========
EXPLANATION:-
============
***************************-----END of--->93<--------***************************
Example=94
=========
NOTE:-
-----
PROGRAME=94
=========
EXPLANATION:-
============
***************************-----END of--->94<--------***************************
Example=95
=========
NOTE:-
-----
PROGRAME=95
=========
EXPLANATION:-
============
***************************-----END of--->95<--------***************************
Example=96
=========
NOTE:-
-----
PROGRAME=96
=========
EXPLANATION:-
============
***************************-----END of--->96<--------***************************
Example=97
=========
NOTE:-
-----
PROGRAME=97
=========
EXPLANATION:-
============
***************************-----END of--->97<--------***************************
Example=98
=========
NOTE:-
-----
PROGRAME=98
=========
EXPLANATION:-
============
***************************-----END of--->98<--------***************************
Example=99
=========
NOTE:-
-----
PROGRAME=99
=========
EXPLANATION:-
============
***************************-----END of--->99<--------***************************
Example=100
=========
NOTE:-
-----
PROGRAME=100
=========
EXPLANATION:-
============
***************************-----END of--->100<--------***************************
| 21.674839 | 100 | 0.458001 |
9757180fd3cc20ca648e29dd90643583695992ad | 3,656 | package org.cirdles.topsoil;
import org.cirdles.topsoil.plot.PlotType;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* Created by sbunce on 6/27/2016.
*/
public enum IsotopeSystem {
//Isotope abbreviation, isotope name, array of default headers as strings
GENERIC("Gen", "Generic",
new String[]{"x", "y", "xσ", "yσ", "Corr Coef"},
new PlotType[] {PlotType.SCATTER}),
UPB("UPb", "Uranium Lead",
new String[]{"207Pb*/235U", "206Pb*/238U", "±2σ (%)", "±2σ (%)", "Corr Coef"},
new PlotType[] {PlotType.SCATTER}),
UTH("UTh", "Uranium Thorium",
new String[]{"[234Pb/238U]t", "[230Th/238U]t", "±2σ (%)", "±2σ (%)", "Corr Coef"},
new PlotType[] {PlotType.SCATTER});
/**
* An abbreviation of the {@code IsotopeSystem}'s name.
*/
private final String abbreviation;
/**
* The name of the {@code IsotopeSystem}.
*/
private final String name;
/**
* Default headers for model of an {@code IsotopeSystem}.
*/
private final String[] headers;
/**
* The available {@code PlotType}s for the {@code IsotopeSystem}.
*/
private final PlotType[] plots;
/**
* A {@code List} of all {@code IsotopeSystem}s.
*/
public static final List<IsotopeSystem> ISOTOPE_SYSTEMS;
static {
ISOTOPE_SYSTEMS = Collections.unmodifiableList(Arrays.asList(
GENERIC,
UPB,
UTH
));
}
//***********************
// Constructors
//***********************
IsotopeSystem( String abbr, String name, String [] headers, PlotType[] plots ) {
this.abbreviation = abbr;
this.name = name;
this.headers = headers;
this.plots = plots;
}
//***********************
// Methods
//***********************
/**
* Returns the appropriate {@code IsotopeSystem} for the given name, if one exists.
*
* @param name String name
* @return associated IsotopeSystem
*/
public static IsotopeSystem fromName( String name ) {
for (IsotopeSystem i : values()) {
if (name.equals(i.getName())) {
return i;
}
}
return null;
}
/**
* Returns the appropriate {@code IsotopeSystem} for the given abbreviation, if one exists.
*
* @param abbr String abbreviation
* @return associated IsotopeSystem
*/
public static IsotopeSystem fromAbbreviation( String abbr ) {
for (IsotopeSystem i : values()) {
if (abbr.equals(i.getAbbreviation())) {
return i;
}
}
return null;
}
/**
* Returns the abbreviated name of the {@code IsotopeSystem}.
*
* @return abbreviated String name
*/
public String getAbbreviation() {
return abbreviation;
}
/**
* Returns the name of the {@code IsotopeSystem}.
*
* @return String name
*/
public String getName() {
return name;
}
/**
* Returns the default headers for model of {@code IsotopeSystem}.
*
* @return array of String headers
*/
public String[] getHeaders() {
return headers.clone();
}
/**
* Returns the available {@code PlotType}s for the {@code IsotopeSystem}.
*
* @return array of TopsoilPlotTypes
*/
public PlotType[] getPlots() {
return plots.clone();
}
@Override
public String toString() {
return name;
}
}
| 25.388889 | 95 | 0.536652 |
88062f20926b787dd7ff6c9d24dff009a3b88fb0 | 133 | package com.jzd.jzshop.entity;
/**
* @author LXB
* @description:
* @date :2019/12/2 17:15
*/
public class SendVertifyEntity {
}
| 13.3 | 32 | 0.661654 |
c9437761e0dd5e16989a84e28c367cb9b6f790d3 | 3,908 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition.processing;
import com.yahoo.document.DataType;
import com.yahoo.document.Field;
import com.yahoo.document.ReferenceDataType;
import com.yahoo.searchdefinition.DocumentGraphValidator;
import com.yahoo.searchdefinition.Schema;
import com.yahoo.searchdefinition.SchemaBuilder;
import com.yahoo.searchdefinition.document.SDDocumentType;
import com.yahoo.searchdefinition.parser.ParseException;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author bjorncs
*/
public class ReferenceFieldTestCase {
@SuppressWarnings("deprecation")
@Rule
public final ExpectedException exceptionRule = ExpectedException.none();
@Test
public void reference_fields_are_parsed_from_search_definition() throws ParseException {
SchemaBuilder builder = new SchemaBuilder();
String campaignSdContent =
"search campaign {\n" +
" document campaign {\n" +
" }\n" +
"}";
String salespersonSdContent =
"search salesperson {\n" +
" document salesperson {\n" +
" }\n" +
"}";
String adSdContent =
"search ad {\n" +
" document ad {\n" +
" field campaign_ref type reference<campaign> { indexing: attribute }\n" +
" field salesperson_ref type reference<salesperson> { indexing: attribute }\n" +
" }\n" +
"}";
builder.importString(campaignSdContent);
builder.importString(salespersonSdContent);
builder.importString(adSdContent);
builder.build();
Schema schema = builder.getSchema("ad");
assertSearchContainsReferenceField("campaign_ref", "campaign", schema.getDocument());
assertSearchContainsReferenceField("salesperson_ref", "salesperson", schema.getDocument());
}
@Test
public void cyclic_document_dependencies_are_detected() throws ParseException {
SchemaBuilder builder = new SchemaBuilder();
String campaignSdContent =
"search campaign {\n" +
" document campaign {\n" +
" field ad_ref type reference<ad> { indexing: attribute }\n" +
" }\n" +
"}";
String adSdContent =
"search ad {\n" +
" document ad {\n" +
" field campaign_ref type reference<campaign> { indexing: attribute }\n" +
" }\n" +
"}";
builder.importString(campaignSdContent);
builder.importString(adSdContent);
exceptionRule.expect(DocumentGraphValidator.DocumentGraphException.class);
exceptionRule.expectMessage("Document dependency cycle detected: campaign->ad->campaign.");
builder.build();
}
private static void assertSearchContainsReferenceField(String expectedFieldname,
String referencedDocType,
SDDocumentType documentType) {
Field field = documentType.getDocumentType().getField(expectedFieldname);
assertNotNull("Field does not exist in document type: " + expectedFieldname, field);
DataType dataType = field.getDataType();
assertTrue(dataType instanceof ReferenceDataType);
ReferenceDataType refField = (ReferenceDataType) dataType;
assertEquals(referencedDocType, refField.getTargetType().getName());
}
}
| 42.945055 | 104 | 0.62129 |
c4b36a16917ade6ef849ed00071be32e00a139b0 | 3,181 | package sitevisit.CVSB_3910;
import net.serenitybdd.junit.runners.SerenityRunner;
import net.thucydides.core.annotations.Steps;
import net.thucydides.core.annotations.Title;
import org.junit.Test;
import org.junit.runner.RunWith;
import pages.TestPage;
import steps.*;
import steps.composed.TestTypeCategoryComp;
import steps.util.UtilSteps;
import utils.BaseTestClass;
@RunWith(SerenityRunner.class)
public class CombinationTesting_ReviewScreens_7765 extends BaseTestClass{
@Steps
UtilSteps utilSteps;
@Steps
TestTypeCategoryComp testTypeCategoryComp;
@Steps
TestSteps testSteps;
@Steps
TestTypeDetailsSteps testTypeDetailsSteps;
@Steps
TestTypeCategorySteps testTypeCategorySteps;
@Steps
TestReviewSteps testReviewSteps;
@Steps
SiteVisitSteps siteVisitSteps;
@Steps
OdometerReadingSteps odometerReadingSteps;
@Steps
EUVehicleCategorySteps euVehicleCategorySteps;
@Steps
PreparerSteps preparerSteps;
@Steps
ConfirmationPageSteps confirmationPageSteps;
@Title("CVSB-3910 - AC7 Changes to the submit button for PSV's/singular vehicle tests" +
"AC8 Change to confirmation message on PSV/singular vehicle tests" +
"AC9 Review screen title for singular tests")
@Test
public void testChangesSingularVehicleTests() {
//add psv
utilSteps.showBrowserstackUrl(super.sessionDetails.getBsSessionUrl());
testTypeCategoryComp.goToTestPageBySelectingASpecificVehicle("YV31MEC18GA011900",super.username);
preparerSteps.startTest();
preparerSteps.confirmInPopUp();
testSteps.selectVehicleCategoryOption();
euVehicleCategorySteps.selectOption("M2");
testSteps.selectOdometerReading();
odometerReadingSteps.typeInField("123");
odometerReadingSteps.checkReadingValue("123");
odometerReadingSteps.pressSave();
testSteps.waitUntilPageIsLoaded();
testSteps.addTestTypeFor("YV31MEC18GA011900");
testTypeCategorySteps.waitUntilPageIsLoaded();
testTypeCategorySteps.selectFromTestTypeList("Annual test");
testSteps.waitUntilPageIsLoaded();
testSteps.selectTestType("Annual test", TestPage.TestTypeStatuses.IN_PROGRESS);
testTypeDetailsSteps.pressSave();
//submit and review tests
testSteps.checkReviewAndSubmitButton();
testSteps.clickReviewAndSubmit();
//check psv test
testReviewSteps.checkElementIsDisplayed("Test review");
testReviewSteps.checkElementIsDisplayed("YV31MEC18GA011900");
testReviewSteps.scrollDown();
testReviewSteps.checkElementIsDisplayed("Submit test");
//submit test
testReviewSteps.pressSubmit();
testReviewSteps.pressSubmitInPopUp();
confirmationPageSteps.waitUntilPageIsLoaded();
confirmationPageSteps.checkElementContainingStringIsDisplayed("The tests have been submitted and will be emailed to");
confirmationPageSteps.pressDone();
siteVisitSteps.waitUntilPageIsLoaded();
//validate site visit timeline
siteVisitSteps.checkVehiclePosition("C47WLL",0);
}
}
| 34.204301 | 126 | 0.739076 |
3e20a1cc429e77b4e9b5b9889bbb0e35592712a0 | 1,292 | package com.rideaustin.clients.configuration.elements;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.google.common.collect.ImmutableMap;
import com.rideaustin.clients.configuration.ConfigurationElement;
import com.rideaustin.clients.configuration.ConfigurationItemCache;
import com.rideaustin.filter.ClientType;
import com.rideaustin.rest.model.Location;
import lombok.RequiredArgsConstructor;
@Component
@RequiredArgsConstructor(onConstructor = @__(@Inject))
public class DirectConnectConfigurationElement implements ConfigurationElement {
private static final String CONFIGURATION_KEY = "directConnect";
private final ConfigurationItemCache configurationItemCache;
@Override
public Map getConfiguration(ClientType clientType, Location location, Long cityId) {
return getDefaultConfiguration(clientType, location, cityId);
}
@Override
public Map getDefaultConfiguration(ClientType clientType, Location location, Long cityId) {
return configurationItemCache.getConfigurationForClient(clientType, CONFIGURATION_KEY, cityId)
.map(item -> new HashMap<>(ImmutableMap.of(item.getConfigurationKey(), item.getConfigurationObject())))
.orElse(new HashMap<>());
}
}
| 34.918919 | 109 | 0.816563 |
33b4052cc48f1f049564f7dd5d8544ad9b2e8e29 | 972 | package com.google.zxing.client.result;
public enum ParsedResultType {
ADDRESSBOOK,
EMAIL_ADDRESS,
PRODUCT,
URI,
TEXT,
GEO,
TEL,
SMS,
CALENDAR,
WIFI,
ISBN,
VIN;
static {
ADDRESSBOOK = new ParsedResultType("ADDRESSBOOK", 0);
EMAIL_ADDRESS = new ParsedResultType("EMAIL_ADDRESS", 1);
PRODUCT = new ParsedResultType("PRODUCT", 2);
URI = new ParsedResultType("URI", 3);
TEXT = new ParsedResultType("TEXT", 4);
GEO = new ParsedResultType("GEO", 5);
TEL = new ParsedResultType("TEL", 6);
SMS = new ParsedResultType("SMS", 7);
CALENDAR = new ParsedResultType("CALENDAR", 8);
WIFI = new ParsedResultType("WIFI", 9);
ISBN = new ParsedResultType("ISBN", 10);
VIN = new ParsedResultType("VIN", 11);
a = new ParsedResultType[]{ADDRESSBOOK, EMAIL_ADDRESS, PRODUCT, URI, TEXT, GEO, TEL, SMS, CALENDAR, WIFI, ISBN, VIN};
}
}
| 29.454545 | 125 | 0.608025 |
3e31b278f1e6e2c2e71bc97ac71d57987fcb8c10 | 901 | package com.corkili.pa.common.test.dto;
import static org.junit.Assert.*;
import org.junit.Test;
import com.corkili.pa.common.annotation.Param;
import com.corkili.pa.common.annotation.Params;
import com.corkili.pa.common.dto.Query;
import com.corkili.pa.common.dto.util.Querys;
public class TestQuery {
@Params(params = {
@Param(name = "str", type = String.class),
@Param(name = "integer", type = Integer.class)})
private boolean invoke(Query query) {
return Querys.checkQuery(TestQuery.class, "invoke", query);
}
@Test
public void testQuery() {
Query query = new Query();
query.add("str", "test-case");
query.add("integer", 1);
assertTrue(invoke(query));
assertEquals("test-case", query.get("str", String.class));
assertEquals(Integer.valueOf(1), query.get("integer", Integer.class));
}
}
| 28.15625 | 78 | 0.649279 |
1f147a35116d24eec4583793e7b22d27cce9142e | 4,263 | /*
* (c) Copyright 2021 Palantir Technologies Inc. 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 com.palantir.conjure.java.undertow.example;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.palantir.conjure.java.undertow.lib.BinaryResponseBody;
import com.palantir.conjure.java.undertow.lib.RequestContext;
import com.palantir.logsafe.Preconditions;
import com.palantir.tokens.auth.AuthHeader;
import com.palantir.tokens.auth.BearerToken;
import io.undertow.server.HttpServerExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
final class ExampleResource implements ExampleService {
@Override
public void simple() {}
@Override
public String ping() {
return "pong";
}
@Override
public ListenableFuture<String> pingAsync() {
return Futures.immediateFuture(ping());
}
@Override
public ListenableFuture<Void> voidAsync() {
return Futures.immediateVoidFuture();
}
@Override
public int returnPrimitive() {
return 1;
}
@Override
public BinaryResponseBody binary() {
return Binary.INSTANCE;
}
@Override
public CustomBinaryResponseBody namedBinary() {
return Binary.INSTANCE;
}
@Override
public Optional<BinaryResponseBody> optionalBinary() {
return Optional.of(binary());
}
@Override
public Optional<CustomBinaryResponseBody> optionalNamedBinary() {
return Optional.of(namedBinary());
}
@Override
public String post(String body) {
return Preconditions.checkNotNull(body, "Body is required");
}
@Override
public String queryParam(String queryParameter) {
return Preconditions.checkNotNull(queryParameter, "Query parameter is required");
}
@Override
public String pathParam(String param) {
return Preconditions.checkNotNull(param, "Path parameter is required");
}
@Override
public String headerParam(String headerValue) {
return Preconditions.checkNotNull(headerValue, "Header parameter is required");
}
@Override
public String authenticated(AuthHeader auth) {
return Preconditions.checkNotNull(auth, "AuthHeader is required")
.getBearerToken()
.toString();
}
@Override
public void exchange(HttpServerExchange exchange) {
Preconditions.checkNotNull(exchange, "HttpServerExchange is required");
}
@Override
public void context(RequestContext context) {
Preconditions.checkNotNull(context, "RequestContext is required");
}
@Override
public String cookie(String cookieValue) {
return Preconditions.checkNotNull(cookieValue, "Cookie value parameter is required");
}
@Override
public String optionalCookie(Optional<String> cookieValue) {
return cookieValue.orElse("empty");
}
@Override
public BearerToken authCookie(BearerToken token) {
return Preconditions.checkNotNull(token, "Token parameter is required");
}
@Override
public String optionalBigIntegerCookie(Optional<BigInteger> cookieValue) {
return cookieValue.map(BigInteger::toString).orElse("empty");
}
private enum Binary implements CustomBinaryResponseBody {
INSTANCE;
@Override
public void write(OutputStream responseBody) throws IOException {
responseBody.write("binary".getBytes(StandardCharsets.UTF_8));
}
@Override
public void close() {
// nop
}
}
}
| 28.804054 | 93 | 0.699507 |
408caf662998ff5f589470c94eb747f5b5f1a1a1 | 2,480 | // **********************************************************************
//
// <copyright>
//
// BBN Technologies
// 10 Moulton Street
// Cambridge, MA 02138
// (617) 873-8000
//
// Copyright (C) BBNT Solutions LLC. All rights reserved.
//
// </copyright>
// **********************************************************************
//
// $Source: /cvs/distapps/openmap/src/openmap/com/bbn/openmap/util/propertyEditor/TextPropertyEditor.java,v $
// $RCSfile: TextPropertyEditor.java,v $
// $Revision: 1.4 $
// $Date: 2004/10/14 18:06:31 $
// $Author: dietrick $
//
// **********************************************************************
package com.bbn.openmap.util.propertyEditor;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.beans.PropertyEditorSupport;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* A PropertyEditor that displays a TextField to edit a String.
*/
public class TextPropertyEditor extends PropertyEditorSupport implements
ActionListener, FocusListener {
/** The GUI component of this editor. */
JTextField textField = new JTextField(10);
public boolean supportsCustomEditor() {
return true;
}
/** Returns the editor GUI, ie a JTextField. */
public Component getCustomEditor() {
JPanel jp = new JPanel();
textField.addActionListener(this);
textField.addFocusListener(this);
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
jp.setLayout(gridbag);
c.weightx = 1f;
c.fill = GridBagConstraints.HORIZONTAL;
gridbag.setConstraints(textField, c);
jp.add(textField);
return jp;
}
public void actionPerformed(ActionEvent e) {
//System.out.println("value changed");
firePropertyChange();
}
public void focusGained(FocusEvent e) {}
public void focusLost(FocusEvent e) {
firePropertyChange();
}
/** Sets String in JTextField. */
public void setValue(Object string) {
if (!(string instanceof String))
return;
textField.setText((String) string);
}
/** Returns String from JTextfield. */
public String getAsText() {
return textField.getText();
}
} | 27.555556 | 109 | 0.611694 |
0a86a3fef474e83fe327f984f3fd0fbca106d368 | 1,063 | package net.ravendb.client.documents.operations.replication;
public class ReplicationHubAccess {
private String name;
private String certificateBase64;
private String[] allowedHubToSinkPaths;
private String[] allowedSinkToHubPaths;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCertificateBase64() {
return certificateBase64;
}
public void setCertificateBase64(String certificateBase64) {
this.certificateBase64 = certificateBase64;
}
public String[] getAllowedHubToSinkPaths() {
return allowedHubToSinkPaths;
}
public void setAllowedHubToSinkPaths(String[] allowedHubToSinkPaths) {
this.allowedHubToSinkPaths = allowedHubToSinkPaths;
}
public String[] getAllowedSinkToHubPaths() {
return allowedSinkToHubPaths;
}
public void setAllowedSinkToHubPaths(String[] allowedSinkToHubPaths) {
this.allowedSinkToHubPaths = allowedSinkToHubPaths;
}
}
| 24.72093 | 74 | 0.708373 |
bef639fca0c99f82cbb169109d5807c3cd40e320 | 2,096 | package de.slackspace.openkeepass.api;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import de.slackspace.openkeepass.crypto.Sha256;
import de.slackspace.openkeepass.domain.KeyFileBytes;
import de.slackspace.openkeepass.exception.KeyFileUnreadableException;
import de.slackspace.openkeepass.parser.KeyFileBinaryParser;
import de.slackspace.openkeepass.parser.KeyFileParser;
import de.slackspace.openkeepass.parser.KeyFileXmlParser;
import de.slackspace.openkeepass.parser.SimpleXmlParser;
import de.slackspace.openkeepass.util.StreamUtils;
public class KeyFileReader {
protected List<KeyFileParser> keyFileParsers = new ArrayList<KeyFileParser>();
public KeyFileReader() {
keyFileParsers.add(new KeyFileXmlParser(new SimpleXmlParser()));
keyFileParsers.add(new KeyFileBinaryParser());
}
public byte[] readKeyFile(InputStream keyFileStream) {
byte[] keyFileContent = toByteArray(keyFileStream);
byte[] protectedBuffer = parseKeyFile(keyFileContent);
return hashKeyFileIfNecessary(protectedBuffer);
}
private byte[] parseKeyFile(byte[] keyFileContent) {
for (KeyFileParser parser : keyFileParsers) {
KeyFileBytes keyFileBytes = parser.readKeyFile(keyFileContent);
if (keyFileBytes.isReadable()) {
return keyFileBytes.getBytes();
}
}
throw new KeyFileUnreadableException("Could not parse key file because no parser was able to parse the file");
}
private byte[] toByteArray(InputStream keyFileStream) {
try {
return StreamUtils.toByteArray(keyFileStream);
} catch (IOException e) {
throw new KeyFileUnreadableException("Could not read key file", e);
}
}
private byte[] hashKeyFileIfNecessary(byte[] protectedBuffer) {
if (protectedBuffer.length != 32) {
return Sha256.hash(protectedBuffer);
}
return protectedBuffer;
}
}
| 34.360656 | 119 | 0.695134 |
54c051b856b513c43a005c203e8176baf36bdb61 | 728 | package creational.singleton.example2.after.factory;
import creational.singleton.example2.after.director.Converter;
import creational.singleton.example2.after.implementations.JSONConverter;
import creational.singleton.example2.after.implementations.XMLConverter;
import creational.singleton.example2.after.implementations.YMLConverter;
public class Director {
public static Converter getConverter(ConverterType format) {
switch (format) {
case JSON:
return JSONConverter.getInstance();
case XML:
return new XMLConverter();
case YML:
return new YMLConverter();
default:
return null;
}
}
}
| 30.333333 | 73 | 0.674451 |
bd9edad65c17703634d1cb1f6b06d7685d22ffef | 987 | package fr.cg44.plugin.socle.datacontroller;
import com.jalios.jcms.BasicDataController;
import com.jalios.jcms.ControllerStatus;
import com.jalios.jcms.Data;
import com.jalios.jcms.plugin.PluginComponent;
import com.jalios.util.Util;
import generated.FicheArticle;
public class FicheArticleDataController extends BasicDataController implements PluginComponent {
public ControllerStatus checkIntegrity(Data data) {
FicheArticle itFiche = (FicheArticle) data;
if (! itFiche.getTypeSimple()
&& Util.isEmpty(itFiche.getContenuParagraphe_1())
&& Util.isEmpty(itFiche.getContenuParagraphe_2())
&& Util.isEmpty(itFiche.getContenuParagraphe_3())
&& Util.isEmpty(itFiche.getContenuParagraphe_4())) {
// Type est onglet, pas de contenu -> on retourne une erreur
ControllerStatus status = new ControllerStatus();
status.setProp("msg.edit.empty-field", "Contenu paragraphe des onglets");
return status;
}
return super.checkIntegrity(data);
}
} | 32.9 | 96 | 0.765957 |
afbfc84dc19f2df876332e4fdfe1061c0d8d7925 | 1,047 | package io.hfgbarrigas.reactive.dbcontext.context;
import io.hfgbarrigas.reactive.dbcontext.db.Connection;
import java.util.Objects;
public class DefaultTransactionalContext implements TransactionalContext {
private Connection connection;
private DefaultTransactionalContext() {
}
public DefaultTransactionalContext(Connection connection) {
this.connection = connection;
}
@Override
public Connection getConnection() {
return this.connection;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DefaultTransactionalContext that = (DefaultTransactionalContext) o;
return connection.equals(that.connection);
}
@Override
public int hashCode() {
return Objects.hash(connection);
}
@Override
public String toString() {
return "DefaultTransactionalContext{" +
"connection=" + connection +
'}';
}
}
| 24.348837 | 75 | 0.659026 |
c7a6533cbbd74d608766d0c6ee3959a0f080c0d5 | 3,603 | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. 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.wso2.carbon.protocol.emulator.http.server.handler;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http.LastHttpContent;
import io.netty.util.CharsetUtil;
import static io.netty.handler.codec.http.HttpResponseStatus.HTTP_VERSION_NOT_SUPPORTED;
/**
* This handler checks the http version to see if it can be handled.
*/
public class HttpVersionHandler extends ChannelInboundHandlerAdapter {
private HttpVersion httpVersion;
private boolean responded = false;
public HttpVersionHandler(HttpVersion httpVersion) {
this.httpVersion = httpVersion;
}
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
versionCheck(ctx, msg);
}
private void versionCheck(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest && !httpVersion.equals(((HttpRequest) msg).getProtocolVersion())) {
FullHttpResponse response = populate505VersionError(httpVersion, ((HttpRequest) msg).getProtocolVersion());
ctx.writeAndFlush(response);
responded = true;
} else if (msg instanceof HttpRequest) {
ctx.fireChannelRead(msg);
} else if (msg instanceof HttpContent && !responded) {
ctx.fireChannelRead(msg);
} else if (msg instanceof LastHttpContent && !responded) {
ctx.fireChannelRead(msg);
} else if (msg instanceof LastHttpContent && responded) {
responded = false;
}
}
private FullHttpResponse populate505VersionError(HttpVersion httpVersion, HttpVersion protocolVersion) {
FullHttpResponse response = new DefaultFullHttpResponse(httpVersion, HTTP_VERSION_NOT_SUPPORTED,
Unpooled.copiedBuffer("The " + protocolVersion +
" is not supported " +
"because of the " +
"configurations\n",
CharsetUtil.UTF_8)
);
response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8");
response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());
return response;
}
}
| 44.481481 | 119 | 0.64363 |
82c101085e94d8b5d22ad574bc4b383da69c57d8 | 2,910 | package com.webcheckers.ui;
import com.google.gson.Gson;
import com.webcheckers.appl.GameCenter;
import com.webcheckers.model.GameView;
import com.webcheckers.model.Player;
import spark.*;
import java.util.HashMap;
import java.util.logging.Logger;
import com.webcheckers.util.Message;
import java.util.Objects;
public class PostCheckTurn implements Route{
// Creates logger for class.
private static final Logger LOG = Logger.getLogger(PostCheckTurn.class.getName());
//
// Constants
//
//
// Values used in the View-Model map for rendering the signout view after signout.
//
// Key in HashMap to get the player object
static final String PLAYER_KEY = "key";
//
// Attributes
//
// Game ID of type int associated with current game.
private int gameID;
// GameView associated with the current game.
private final GameCenter gameCenter;
// Freemarker template engine used to render ftl file
private final TemplateEngine templateEngine;
//
// Constructor
//
/**
* The constructor for the {@code POST /checkTurn} route handler.
*
* @param gameCenter - Contains data on all the games being played.
* @param templateEngine - Freemarker template engine used to render ftl file
*/
PostCheckTurn(final GameCenter gameCenter, final TemplateEngine templateEngine){
// Validation
Objects.requireNonNull(gameCenter, "gameCenter must not be null");
Objects.requireNonNull(templateEngine, "templateEngine must not be null");
this.gameCenter = gameCenter;
this.templateEngine = templateEngine;
}
/**
* Renders the game page by providing updated information about
* the view components, players and creates boardView for
* respective player
*
* @param request: the HTTP request
* @param response: the HTTP response
*
* @return The rendered FTL for the game page
*/
@Override
public String handle(Request request, Response response){
LOG.fine("Check Turn accessed.");
// Initializes some objects needed compare turns.
final Session httpSession = request.session();
Player player = httpSession.attribute(PLAYER_KEY);
GameView gameView = gameCenter.getGame(player.getGameID());
Message message;
// Check to see if activeColor has changed to "White/Red".
if(gameView.isActivePlayer(player)) {
message = Message.info("true");
}
else {
// Waits for 5 seconds.
try {
LOG.fine("Going to sleep.");
Thread.sleep(5000);
}catch (InterruptedException e){
System.err.println(e);
}
message = Message.info("false");
}
Gson gson = new Gson();
return gson.toJson(message);
}
}
| 28.811881 | 86 | 0.646048 |
579e08107c6e563e325b1f5771b826e4305b5f8e | 495 | package io.undertow.server.handlers.resource;
import java.io.File;
import java.net.URL;
import java.nio.file.Path;
import java.util.Date;
import java.util.List;
public interface Resource {
String getPath();
Date getLastModified();
String getLastModifiedString();
String getName();
boolean isDirectory();
List<Resource> list();
Long getContentLength();
File getFile();
Path getFilePath();
File getResourceManagerRoot();
Path getResourceManagerRootPath();
URL getUrl();
}
| 14.558824 | 45 | 0.743434 |
ff4837aa87088a3b0100cb2a1642eaeb01d69592 | 11,446 | package org.bndly.common.antivirus.impl;
/*-
* #%L
* Antivirus Impl
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import org.bndly.common.antivirus.api.AVException;
import org.bndly.common.antivirus.api.AVScanException;
import org.bndly.common.antivirus.api.AVService;
import org.bndly.common.antivirus.api.AVServiceFactory;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author cybercon <bndly@cybercon.de>
*/
public class AVServiceFactoryImpl implements AVServiceFactory {
private static final Logger LOG = LoggerFactory.getLogger(AVServiceFactoryImpl.class);
private int connectTimeout = 3000;
private int socketTimeout = 3000;
private int maxConnectionsPerInstance = 10;
private String charset = "UTF-8";
private int defaultChunkSize = 2048;
private long defaultTimeoutMillis = -1;
private int maxCommandRetries = 0;
private final List<CreatedAVService> createdServices = new ArrayList<>();
private final Map<SocketKey, Pool<LazySocket>> socketPools = new ConcurrentHashMap<>();
private static final SocketExceptionHandler DEFAULT_BROKEN_PIPE_HANDLER = new SocketExceptionHandler() {
@Override
public Object handleConnectionReset(SocketException exception, Socket socket, ResponseReader responseReader) {
throw new AVException("connection was reset by remote");
}
@Override
public Object handleBrokenPipe(SocketException exception, Socket socket, ResponseReader responseReader) {
throw new AVException("pipe did break, because remote did close the connection");
}
};
private static interface PoolAccess<E> {
E access(Map<SocketKey, Pool<LazySocket>> pools);
}
private static final class SocketKey {
private final InetAddress address;
private final int port;
public SocketKey(InetAddress address, int port) {
if (address == null) {
throw new IllegalArgumentException("address is not allowed to be null");
}
this.address = address;
this.port = port;
}
public int getPort() {
return port;
}
public InetAddress getAddress() {
return address;
}
@Override
public int hashCode() {
int hash = 5;
hash = 79 * hash + Objects.hashCode(this.address);
hash = 79 * hash + this.port;
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final SocketKey other = (SocketKey) obj;
if (!Objects.equals(this.address, other.address)) {
return false;
}
if (this.port != other.port) {
return false;
}
return true;
}
}
private static final class CreatedAVService {
private final AVService service;
private final SocketKey socketKey;
public CreatedAVService(AVService service, SocketKey socketKey) {
this.service = service;
this.socketKey = socketKey;
}
public AVService getService() {
return service;
}
public InetAddress getInetAddress() {
return socketKey.getAddress();
}
public int getPort() {
return socketKey.getPort();
}
public SocketKey getSocketKey() {
return socketKey;
}
}
public void activate() {
}
public void deactivate() {
accessPools(new PoolAccess<Object>() {
@Override
public Object access(Map<SocketKey, Pool<LazySocket>> pools) {
Iterator<Pool<LazySocket>> iter = pools.values().iterator();
while (iter.hasNext()) {
Pool<LazySocket> next = iter.next();
next.destruct();
iter.remove();
}
return null;
}
});
synchronized (createdServices) {
createdServices.clear();
}
}
private synchronized <E> E accessPools(PoolAccess<E> access) {
return access.access(socketPools);
}
@Override
public AVService createAVService(InetAddress address, int port) {
SocketKey key = new SocketKey(address, port);
SocketManager sr = createSocketRunner(key);
AVService service = new AVServiceImpl(sr, charset, defaultChunkSize, defaultTimeoutMillis);
CreatedAVService cs = new CreatedAVService(service, key);
synchronized (createdServices) {
createdServices.add(cs);
}
return service;
}
private SocketManager createSocketRunner(final SocketKey key) {
return new SocketManager() {
@Override
public <E> E runOnSingleUseSocket(SocketManager.Callback<E> callback) throws AVScanException, IOException {
Socket socket = null;
try {
socket = createFreshSocket(key);
LOG.info("invoking socket callback on a single-use socket");
return (E) callback.runOnSocket(socket, DEFAULT_BROKEN_PIPE_HANDLER);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
LOG.error("failed to close socket: " + e.getMessage(), e);
}
}
}
}
@Override
public LazySocket take() {
try {
LazySocket socket = waitForSocket(key);
if (socket == null) {
LOG.error("could not retrieve a socket. hence the socket callback will not be invoked.");
throw new AVScanException("could not obtain a socket");
}
return socket;
} catch (PoolExhaustedException ex) {
throw new AVScanException("could not obtain a socket", ex);
}
}
@Override
public LazySocket take(long timeoutMillis) {
try {
LazySocket socket = waitForSocket(key, timeoutMillis);
if (socket == null) {
LOG.error("could not retrieve a socket. hence the socket callback will not be invoked.");
throw new AVScanException("could not obtain a socket");
}
return socket;
} catch (PoolExhaustedException ex) {
throw new AVScanException("could not obtain a socket", ex);
}
}
@Override
public void release(LazySocket socket) {
if (socket.isRealSocketClosed()) {
LOG.warn("a closed socket was released. the socket will be dropped as soon as it will be validated.");
} else {
socket.destruct();
}
returnSocket(socket, key);
}
};
}
private LazySocket createLazySocket(final SocketKey key) {
return new LazySocket() {
Socket sock = null;
@Override
public Socket getRealSocket() {
if (sock == null) {
sock = createFreshSocket(key);
}
return sock;
}
@Override
public boolean isRealSocketClosed() {
if (sock == null) {
return false;
}
return sock.isClosed();
}
@Override
public void destruct() {
if (sock != null) {
try {
if (!sock.isClosed()) {
if (LOG.isInfoEnabled()) {
LOG.info("closing socket to {}:{}", key.getAddress().toString(), key.getPort());
}
sock.close();
}
} catch (IOException ex) {
LOG.error("failed to close socket to {}:{}: " + ex.getMessage(), new Object[]{key.getAddress().toString(), key.getPort()}, ex);
throw new IllegalStateException("could not close socket: " + ex.getMessage(), ex);
} finally {
sock = null;
}
}
}
};
}
private Socket createFreshSocket(SocketKey key) {
// open the socket.
if (LOG.isInfoEnabled()) {
LOG.info("creating socket to {}:{}", key.getAddress().toString(), key.getPort());
}
Socket socket;
socket = new Socket();
try {
socket.connect(new InetSocketAddress(key.getAddress(), key.getPort()), connectTimeout);
} catch (IOException ex) {
LOG.error("could not connect to {}:{}: " + ex.getMessage(), key.getAddress().toString(), key.getPort(), ex);
throw new AVException("could not connect socket: " + ex.getMessage(), ex);
}
try {
socket.setSoTimeout(socketTimeout);
} catch (SocketException ex) {
LOG.error("could not set timeout {} on socket to {}:{}: " + ex.getMessage(), new Object[]{socketTimeout, key.getAddress().toString(), key.getPort()}, ex);
throw new AVException("could not set timeout on socket: " + ex.getMessage(), ex);
}
return socket;
}
private LazySocket waitForSocket(final SocketKey key) throws PoolExhaustedException {
Pool<LazySocket> pool = getPoolForKey(key);
return pool.get();
}
private LazySocket waitForSocket(final SocketKey key, long timeoutMillis) throws PoolExhaustedException {
Pool<LazySocket> pool = getPoolForKey(key);
return pool.get(timeoutMillis);
}
private Pool<LazySocket> getPoolForKey(final SocketKey key) {
if (LOG.isInfoEnabled()) {
LOG.info("requesting pool with sockets to {}:{}", key.getAddress().toString(), key.getPort());
}
Pool<LazySocket> pool = accessPools(new PoolAccess<Pool<LazySocket>>() {
@Override
public Pool<LazySocket> access(Map<SocketKey, Pool<LazySocket>> pools) {
Pool<LazySocket> pool = pools.get(key);
if (pool == null) {
LOG.info("pool did not exist yet. creating a new one.");
// create a pool
pool = new Pool<LazySocket>() {
@Override
protected LazySocket createItem() {
return createLazySocket(key);
}
@Override
protected void destroyItem(LazySocket item) {
item.destruct();
}
};
pool.setMaxSize(maxConnectionsPerInstance);
pool.init();
pools.put(key, pool);
LOG.info("pool created and initialized.");
}
return pool;
}
});
return pool;
}
private void returnSocket(LazySocket socket, SocketKey key) {
if (LOG.isInfoEnabled()) {
LOG.info("returning socket {}:{} to pool", key.getAddress().toString(), key.getPort());
}
Pool<LazySocket> pool = getPoolForKey(key);
pool.put(socket);
}
@Override
public void destroyAVService(AVService service) {
synchronized (createdServices) {
Iterator<CreatedAVService> iter = createdServices.iterator();
while (iter.hasNext()) {
CreatedAVService next = iter.next();
if (next.getService() == service) {
iter.remove();
}
}
}
}
@Override
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
@Override
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public void setMaxConnectionsPerInstance(int maxConnectionsPerInstance) {
this.maxConnectionsPerInstance = maxConnectionsPerInstance;
}
public void setCharset(String charset) {
if (charset == null) {
throw new IllegalArgumentException("charset is not allowed to be null");
}
this.charset = charset;
}
public void setDefaultChunkSize(int defaultChunkSize) {
this.defaultChunkSize = defaultChunkSize;
}
public void setMaxCommandRetries(int maxCommandRetries) {
this.maxCommandRetries = maxCommandRetries;
}
public void setDefaultTimeoutMillis(long defaultTimeoutMillis) {
this.defaultTimeoutMillis = defaultTimeoutMillis;
}
}
| 27.514423 | 157 | 0.687751 |
a528d5c679a8bb422eaa8c1f9fcd011b8a417ba1 | 23,080 | class wDNZsvE3JeSur {
}
class PNlvYbej2NO {
}
class cB1pdzBW5MkqG {
}
class hQ {
}
class McE9p_g3WlZH {
public static void CjL6 (String[] dj) throws E_BYVT4RD {
int wEQvz3x = !new DnN5_Vj8bfW()[ true.nY0nJ0DdjK] = -true.QlZolo();
true[ !!!HjOB0edBAMkT.Zaf];
int lLIZQnr = new boolean[ --new LOGmXqhXOQZUT().aZ6GDtjE646zt2()].Wt = ---!!!new int[ --!4.Ub08RLxdQ87eU()].o_0PB_heVgSi;
return;
}
public static void IMbgSznduN6z (String[] f) {
boolean[][][][] fNw = -new y2oNXLzYMg9()[ !-false[ !false.McRADgy]];
boolean[] wURF3aO0omiz;
void G2afoAobrZ_ = -( !-( ( -( !!-FF7oVxPI.t_Pt_84MDXQ).eCa()).Mmer())[ ---!( null[ ( !( this[ !new void[ !( !true.Xd)[ !!-!-( null.jFc9hc).gQx199n()]][ ( !-R9().RAP_ea())[ bJhSWn45z().hpFv1jnYfXGDvY]]]).ZO7EX7gkRo)[ 56[ new boolean[ OSipQ1eSWat().Os][ null.XbRNh()]]]]).cBS_])[ ( !false.Uxk3R).o()];
while ( -new void[ 600780172.g()].CCPljgRzojnWxE()) !this[ -qmP3MIQkTS5m.ODsR()];
if ( null.SK()) if ( AN2Gm8XU3().i()) if ( -!-false[ -this[ -new byIiwGSHhE().m]]) {
return;
}else return;
;
( this.nzHWd5jS_Cxqua).bLhtdVfx7;
false[ !true.GeLzd];
Bj7fymVhHB1tMq BU1rwfjuATE7O = ETzyma2Nf()[ i2HOhs0BV().REJyRxbDrn()];
int[][] VcHbOXwzB;
;
while ( 954023[ !( --!new int[ 77120.WchVwihHTFbQc].KArorMudyuOm).gsmU5x()]) {
boolean FI2iEDmj7m5_CT;
}
-44576886[ !!2994.IViP6BDNGye];
-V()[ --new lsSkc7eXDpQMuA[ false[ ( !this.G).O2E]][ !false[ MSHZuA().cgUIk()]]];
if ( !5916.bSiA_RDZ()) {
void P7SfKzZjPam;
}
Al().uuvHnh0;
--!-ZYODtOhEZMK_()[ ( LyRw().xt())[ 8[ -!true[ -!true[ !!---!new K_WjO76Bz().NBuL()]]]]];
Xmxqr0CjvxH DcHKs;
while ( !false.uGYGJ0ci) return;
-Oh()[ --mP().qdQMI];
}
public boolean kPPzebau () {
czG3FZFN[][][] skDXBNbAO = -!null.Y6Rh5rOtVKICh7() = -aF2yAxuAF_8[ UVl6ULM182At.Na7gnvMe_I];
void[] eRW;
{
void[][][] voSWvLw;
while ( null.NNaJ()) if ( !---!new boolean[ -( null.ptRKfMtmSL()).Dx3].LdzT982CYJ()) {
boolean[][][][][] DNN7SU;
}
QLBfJe[] keV2xDMzjqfZI;
return;
;
int[] QuDoyjU;
void[] M;
!new boolean[ false.TOaCe][ true[ new int[ -new ubSq5nlakmw3b().DkhRbBwC()].BYaL6htmQb]];
boolean[][][] CPiM8na0Y;
KyHh[] vrXbBjXf1;
}
void[] umjRO = JV9d8SB()[ new TxmxKDgZu61A0_().cqXfSq6NgaSF] = -false[ iwRG.m4b3gL()];
vEjdwI7rz[][] v7RTGvpwxs8u = ---!!new ww6WXRjP_U()[ -!new Tk8un().NTex282b67()] = -!-!-!!-!-!041.gnQH6gPGAERYU();
;
if ( ( !new boolean[ z.BaK6()][ NnoXdpVrNY.W5jq3DgXVo5rZp]).P9) ;
{
void URA9ue0E;
int[] CDU1zBWoJXyxs3;
AV8_PK4z[] RUsETgcCUAv1R5;
void P5;
;
{
return;
}
boolean hJizN6UnEhmC;
boolean[] rcq90a4AMc6;
;
void[] lK2P6zPr;
!!-false[ !!-this.kod];
boolean xj;
}
-!-false.jSsd_sgHwh;
}
public boolean[] fQlnrXbBbT (void mzDHWKvZB3) throws sx0xG_NVJ {
int YN = new boolean[ -this.gW].h9i() = -new M_9HVeMfeZbGkq()[ this.Y1QtF()];
{
if ( !this.B09RPzys9w7Nzv) {
y O7mbH;
}
int[] S82knOKX2;
;
;
void vDC09lGCe;
boolean xIHmwljJg;
void[][] HSDt4AQIwPhr;
{
;
}
while ( 54[ false.XW_Mn2u]) if ( -new uLh75vFRyxFIT[ new A65WGNp8Go5().Tk][ true.A6PV8UrKVeP0rA]) {
{
int tQRZc1;
}
}
{
( !!null.GW83FFE()).o;
}
if ( olQa70[ -ybjXKdTY().y3kN89NzmeTlv()]) while ( new NXBj2Ely8q().dR16vgx7_Q7g()) this.q5w();
boolean nQEkBZwji9wBA;
}
int[] d7g0ILk1SOg_R = !null.fHcdQxybyFCShT;
boolean[] LXqElR9UxN;
if ( IxeyKe7WwR[ !!!!new boolean[ !null.eKjlZsK].sptnGALFK0gH]) ;else ;
void[][][] Z = false[ -R().UQayvxdgEn()];
;
int[][] xnwAo1AZbYopxM;
int G5W6NTTG5tgtiX;
TU3zzZ8x[][] zJWg2;
if ( -3832412[ new pwWna6Hx1NXwlz()[ --null.wbp9BTqdUWX]]) return;else return;
int Zq5z;
;
}
public static void tRlTuW (String[] gJzxa) {
if ( -!!!!false.Rznpp2ZD()) !new mULPnGJSe36KX().eg7();
}
public int DiH;
public int wLQJ;
public boolean QNHp () throws Fm {
int OH4mlIt = new eRKDo0Hm68xCE().bHpLrTfv;
void n8BVUoF;
if ( M8Am.N93Gt()) {
void[][] RLETP7;
}
}
public boolean Ox;
public boolean[] hV9JmC608bh (boolean q6CC) throws XyI {
return ( YZ0e.MzIbvkRb)[ new md().lH_l()];
while ( true.x8yL()) {
!null.Kq();
}
bsmOyOjgwDoJ q = -new yK1SmsMGV2tiC().YQ();
}
public void jOAcCKqFcdH;
public wv Spjigjk_ () throws GXsP9aqV2i2Ykv {
boolean C2nw_RURwy = !!!---!!3397.xHXqDIfs;
boolean QGQPz6JpgVVTD = --this[ ---new MR47().PT0basgDQfp];
boolean XbEYEx = -O_B().Lid;
return;
}
public int[][] V () {
-!( new int[ ---false.f5v()].HXbF1ECUWewFu0)[ !!new int[ !new Pe5j2K8s().BrOdZtyTeRL].h()];
{
while ( new int[ YjnmZ().fMLbi][ ( true.Mz()).ya()]) ;
while ( !!--null[ -new rK78H1CpEJpC[ !( null.gJ).g6oldjTu9HxvPI()].AIXlgw3tCYJTS5]) if ( -null[ new KyPax8uCc().yU7ox()]) while ( mLnbQ2gjWEX().S9C()) new YN[ !!false.g].OdiB0;
void[][][][][] ic7ZuDO1guDl8k;
void[] eMsQyYnfqOEl;
while ( -!!!mmokxQovm()[ true.dR]) {
-new igpC6U3V()[ !!new UP1NhyG42().cSsCk4c1O];
}
;
return;
if ( W.IK9LTaUGp) ;
void QZH9U;
GW73Fdk SevGcymnKvK0j;
}
boolean NLtmTgseq1 = !!0[ 0.dsINGf()] = true.UfLH();
if ( MtjlVPe().AEHgPRTlqJ()) ( !!-( DTAMDfEDA3Dw()._qSJJIPcWXd).D())[ --xQ0IME4uC().LTGaSH()];else while ( true.iUxE) return;
while ( null.z4NNk5Zgq143) {
boolean dk;
}
while ( new XDWUdYgjinf6[ this.Z()][ !new _KxW6H_rnw4Gpp().asakmnZe9GmH]) ;
!--1740252.rqeOZ6fZxtCH;
;
return new WnwitHYzgw4EI[ !2675428[ abMb.tEZigpcqbxZ()]][ !true.iDZ2iWv0];
qjB07[] fZiyJNuvjLA;
NmC2y1_4QGM_t F;
}
public boolean[][] fvu_o4wHt;
public static void b (String[] jSz3i3Pjp) {
boolean[] k;
int ZedOXBbTANBeI = !null.skV = false.aeTHCXpE0uRQO;
( this.mMG3E()).Xy82bkXs;
return 20453147.j();
boolean[] HIyr = true[ -!false.u_Wr8chNOIM39()] = new boolean[ WbEylGB.wRa][ !!!!!false.qqAeZ3khr];
if ( !--new zmRtMu().GhbU0C1()) while ( null[ !!null.Ghr]) ;else while ( 54.fR) ;
boolean[][][] E1fiozs = null.aaFZYcEebQRps();
void DSIP81H_Rv;
return 3[ -( 897.x9OOkeSCE)[ -( new KJoCfus()[ !ZPeflm8IuU().v])._0]];
int[] I = DIlYv3rDE11()[ -( uiE6jUjDrD__[ -!null.vo2zEc_SR()]).s8xSdJyFMxJdHW()];
void hPQChgXLohIi;
int lc5f3SprsZc;
boolean PaoS3Oo8vzOS = null[ null[ !!new mlZPHF2AMFVBB().I]];
void SAn61Qd = --!false.ex5Bqc6L = -true.eu0();
}
}
class KQO {
public int T (void EMCKN, int CKc, boolean[][][][] s7yOsahQp, void[] og8M) {
if ( !!-616011742[ false.Bvm3G]) while ( this.W) while ( n4zpX5.lKecDG5gtnAW()) if ( new qia().qE) {
void[][] i73y0fZ;
}
wvI4PZ G7ieYi = false[ !--!new boolean[ -true.NWylJToD1eE8qd][ N.glqBP9Far6KwA()]] = !162[ !false.fusKOUs_gV()];
}
public boolean D8j0DjN5;
public static void J7Q4Uk4tk (String[] UBC) {
boolean[] GQ2jRl;
while ( Ah9R0mRN6Y().wGqm4t) while ( false.kpmv1dc) return;
int[] SztuIyhVxe;
asV VceLQL;
boolean wKU = -true.QTs() = !new boolean[ null.fKMgc777()][ new Q5()[ false.ZESoSSBoUTD_53]];
;
int Bk;
;
int[][][][] Bt = wSO.sB3prI();
qwzuQ0lrc4JlXo[][] PhVKdMu1_S = ( !--new H()[ !new hR3Z1XQZHQB()[ ---!this.jY()]])[ true.db];
boolean lkA = !!this[ f5DR5eGuX().PoYWiWaiQfWQ];
LbQhN2 rKtRf = new void[ !05.gVvt()].RoaFQXnkn;
return;
-true.afYpIk9Xdi1R_();
while ( false._J0fzlnhiL4()) ;
}
public static void EXcUV13 (String[] nmTo5qgresB7T) {
boolean HS002DZ;
}
public void PKAp () throws neXe9tGky {
e5KSG8t()[ -!01352.pI_()];
void buhP2cWtDZN = false.kkVIiHB6ykidE() = this[ ( this.WO())[ new int[ !this.ybrAOU7c8sOFc][ --null[ null.xpDN]]]];
if ( --true[ false.E()]) if ( false.GrgyyvDUmM()) ;else {
void[] v;
}
-new boolean[ null.rzGeRdKVTkqcq].bxeccUQLJkan;
void[][][] f3oPGfDn2J29 = new CS().x5sYJEV_mM();
usLcp9Hq9ZdhH[] H4IxePAjNCJdpI = !new EkMd().hSIDLc = !true.ENljs_MNd;
boolean Dw4 = !-BhaH()[ -null.Ct()] = new int[ !!!-new int[ !-!!-true.u9am5DGoTZAqnD()].tfAIwFxQ()].HejX();
;
;
int Wuy4YkomVaw;
void[][][] xJe7ZD = !this[ false.KnnxjHXzah5()] = !true.bGJDquqo;
-new boolean[ !!new void[ !!( this.pkG_um()).kyRdCOc()][ jzKQawA4E()[ true.isQJO2eqtxMJbZ]]].J9BIPpUXl;
{
if ( new nl().ppE6GL6wykfk()) --!this[ null.NwU5b_mSY()];
boolean ZYQfKwkaEZh;
NGW_HAGAK0e6E B2BY3optv0oe;
kADYvuhneZc[][] cq;
}
while ( --new k8t0fL[ 5.P()][ -true[ -( !-new rza8nEN1_zpO7T().MQsCvO2Bp7Sq())[ ---new pkI5ebn_().kZsXKSoW]]]) return;
;
c[] Zp = false.Sr();
if ( --gFB0a3h.uk()) while ( yNmqfBQDs().xh_WC) return;
}
public Jg_HgluPk0[][][][][] y_iUT6on5ldj (boolean hc1v, VaG1Z R, boolean Uzz0NAHw, lwB5EnV INr9CW, int QWeJJIqgBFwB, boolean[][][] jZHJq0Zw) {
( ( !C5A().uzhZ5izQW1()).zkPO9SCgQa).eG1tO9CtKHdX();
if ( -!-OAg().MUMchzDqK_c()) true.HVeC1NSbG;
;
}
public boolean[][] ef () {
;
{
boolean[][] uig6NjlCxe1z;
void lemYoI4;
RvRU jvrVg3;
{
while ( Rz.c2Trmi82dCzw()) while ( true.AxHSFlrKkHw()) {
lr[] M0vDu;
}
}
z1y[][][][] vQe_;
Ev().yhb;
R rJY;
-false.TDLtFXEcHCWF8N();
if ( -!this.FeIzWp7VLH()) ;
}
int[] Ln;
boolean kMy6Om4kynTFlJ;
while ( true.tdHW()) return;
if ( null.SeVH1TVg()) return;
;
!!!-!( -null.pCepAH4).vdzTQLpq;
n2YNc53z55Rs thCFnyC42;
boolean[] ZTZxp53XrB7I = !-!!null.Ncl70rWB = !!false.gx();
int[] dVGCQWh76;
boolean zlYTENE6UDXw = FHfbrFiRCh.jSe() = this[ -!true[ -!-false.D5hiL()]];
boolean zswcM = !--false.q;
}
public static void QCuZonnYXMxe (String[] RBQ8) throws EVEiLus {
int[] o6dX9Dmj3eSn;
while ( -Q.gqy) return;
IIgloh4 ykoy = !-new void[ ---!!this.cUO5pPu].H4KBD();
while ( !-452.GCKkuiwd()) ;
void aRBl0LQ = new boolean[ !--new mwfmlwQqXXCdD().PJRYRXoJnfoM()][ !-!null.yGiBYN9Y()];
boolean M = !!true.zi() = new sN().S3o;
}
}
class J6uuE {
public static void Ic3oG9s (String[] CEHlGwSy0) throws GA {
boolean[] a9QZqqrlY3HJF;
if ( --!!null[ false[ --this[ false[ !null.L7pqI]]]]) return;
boolean[][] ZgAnTnILB = false.ZzP28Z();
AqHy050 VTxeNC8VbTKQ9;
;
while ( -null.jNLD4ZmtBY6ksa()) return;
}
public gAn[][] HuD_8Q5S2FE () {
sLlI9V62pwUE[] Hz7oRDMjL;
return;
{
boolean[][] bpM1cWqYo9nymI;
;
;
boolean[][] LI1;
}
int LlK;
;
Vvp_L[][] tYnZgy;
{
{
return;
}
while ( 0649.d9BcBL()) --!cG2kZt1XHNC().IbFm4wA();
;
-!this.G04B;
if ( --MmcHyzyq_EL9().S()) {
int[][][] j;
}
void GUM;
return;
boolean fEow724;
{
while ( !new i4mR().NpLw0SjZIFa()) ;
}
void[] QpX2DSMd7;
boolean[][][][][] f2xheMzq2;
WoWoJ8wD5bhCS[] RiT0qAW_4OfnX;
void DS8U5APmSyZXBR;
}
void[] Vnp7fVG3Q90Va7;
void fkM1 = !true.GiyWv() = null[ !q1HEOCgp2A.APf()];
void[] CXSE_3HmGJy = false[ pHWh1D3R_Grr7()[ -XKgS6q6dmjAj()[ !new boolean[ !!new void[ 29786983[ ( !VuAosYuOVa().aPiuTPgHK).zpkpscL()]].w2aMlTTipf()].HUVt3RSdWMl]]];
{
H4JegikQXhR7mV[] lfegmAvI2_tLH7;
return;
{
void[] tHwOVhUc7_B;
}
while ( -d8UGEWO174za76().eSkcc3JxUc_2()) while ( -( !this.zF3ptkZfKYd()).u4vTl1v0VLvkvT) !!-!!-new void[ true[ true[ !!!new HNTx6ReJUR9().X0fJVJkLXhnvvW]]].FX8eRyy5;
int SuNAkVq9;
return;
return;
;
void[][][][][][] BhaNVU;
}
boolean[] PaBful062bPM = ( true[ !( vFA4XDE9J__wP.q_())[ !Z0Tx1()[ !new TV0xnWW()[ -GXScTL2e().Wrv1ndyqKYhmG3()]]]])._jfpjISBC6 = 34785533[ !( -true._V9lnU)[ -false[ !-KyAPdUKScoNIf.akD0_UN9()]]];
;
new int[ !-B().K()].f0_mC;
int Gf4kapv9Hu4N = !!-true.viHku() = -kkNTxcV().em();
while ( new void[ true[ 0[ new int[ !!-!!!!true.OR()][ OElgPoupvye9.Tjf1]]]].JbdGaN7) return;
}
public boolean RGa5gqJHK;
public int[][][][][][] LEku268vURkBt (I2hvmQBJc8uMh3 tZ8i1jsfRT, int NfIHU, CnLtCqqP[][][][] v1ovbuKjE) throws qLQ2B3kED {
if ( this.rE48VwQkRF) return;else {
new int[ new boolean[ !!new int[ !false.LmchPKz9vC6Oqn].tNT6mmgA].mkDJCQb][ false[ !!07910169[ true.at3EiaW9V]]];
}
int kwvSShdV = -!-!!false[ !-!-oniqCiiE9BAd.l5()] = -!!null.l9UZuxONI4Brbb();
boolean TkCOzPvooC;
}
public static void vC7i_ (String[] hLHyWUia_) throws oWl {
{
void zlvuM_SSR;
int[][] gf6xj;
ATQHsjG Znl_6vpfsjsA;
uCXNgP[] SM;
if ( !--new XUOaZhyv3().TNubQX()) new cZr()[ true.eCveGl2S];
int WCitFhacbIt;
int[][] rl97;
if ( NrGOzVESL4Nm().A()) this.vYMEUW();
if ( !null.TKtj()) if ( !!-null.uZ4_Pw3f1()) if ( new s().xhkm_C6UYlxV2T) -!Tej5jOvMd_E7E.z_p0Tplt;
boolean[] sO_ep;
}
;
int nsvfscn = !-!!!!-90145971[ !-new KR84FAtX83().ktzbH7yrH750];
if ( ( iq26fWDDh1Xc.nt6ojRtt6i()).CN) {
-new int[ -new n0LHw().BtZnmto][ new boolean[ !-( new int[ !-new rFJHACMNlEt()._yuL05KKFr()][ null[ -!new void[ this.Idm].b_qrrZ5HZT()]]).wk7Lr6K5XU].jRSaYSPcgx6];
}else return;
int[] VbaJpTRBjK = new _JEEIq().XnW3PG5c() = false.qjghg();
{
boolean[][][][][] tNIFdI0AEW;
void v9;
while ( A0b9cxAw9U()[ !new rKi1U692w().D()]) ;
void hUb47jsT0V;
void[][] c7;
while ( 770555.RCxxmmcj5nl) if ( -----new int[ null[ --!!false.KlID8YM81n]].l0gATKq5AiSF) if ( new Tfwbr9tAgIr().rXoM()) while ( ( new void[ -this.kpm9C].sMaTim7qf).GZeJ1rmyWqx53E()) {
-99600.NJ7HlX1QglJ1();
}
return;
}
HhQGQ r5ezk0j;
uHnwFuGnPD[] TYvu88wg;
A qNqV = ( !DVZUaYl9YH_1().A_)[ new void[ !-zra7jQ.E].mxG] = -new x().jhi4();
if ( true.bm2Sa47mjK) while ( new JV().V()) {
if ( -26271919.N7C) return;
}
boolean spjhjoH7ELx = this[ q5vpqyAbimCti.SW5wgl];
return this[ -!( epGfZ().V())[ ( !--AcYUV.A51L0oEDKwWIKc())[ !this.qly()]]];
int apFiumegc;
dX Ab1MgTDT;
if ( o()[ new ciDwO().Z02E]) -----!null[ !--iKNySWuIgS.Gl_Vlqt()];
}
public int[][] q8_zA7pe1ZPn (int APd_oTFy, int[] B457oh9erWZi, int gZbv6l2Nds, int Dl) {
boolean ui = Pq9GNeP().qPTKAnDMGyNH() = -vjcYI4koGpZS.dkzVU25RVszxEY();
aQ2[][] ZFxt7UH3 = null._MfNDt1k3s;
return;
boolean kDhJAqgkj;
;
return !!--E.oe();
int[][][] L8eA4L = this.izS8okLaSjWCt = -new N7uSOBLlRAWd().Xh9CTyAAmolLMK();
;
return this.wLC0S();
while ( new P8IuPXgH8a().H7J1BKuUaZZ7) null.p1L();
boolean[][][][] U0f = Ew().D = new co27iG3mVFm().WyDY5jm97eM();
}
public boolean yN;
public int[] RpUdK;
public Y[] a8eqkhl152_;
}
class c9C4mcdyHt {
public static void ZqFsF4KX (String[] a) {
{
F58h H;
boolean[] UAFxNvmAChl53;
_dqlvefYx0s m;
{
true.Nq;
}
return;
ZWwTvzryynZEqy izBz3SY9F5hl;
boolean[][][][][] Y29Lzh_ol8l;
void[] xMfq9sNIiHl33;
;
if ( new Cux()[ 03.CGabdgy7L()]) if ( null.N) return;
void be3sfdaM;
boolean[] _KHUX;
boolean fot4KxN1qQIn;
;
{
while ( -new int[ -new TW5FfTOjqZ[ null.BzvJx5pRrW][ -!false.PrB_E5]][ -!null.rWtkeIYN4dY_bl]) {
int u;
}
}
hjli idcQjIPiqtDhD;
false.iViu6FHFuue;
return;
while ( !-!!new _6xiIHcrGT().Y()) if ( false[ -true[ !null.ZIDr8phGk]]) if ( new W0Lqg_hfY().R()) !null.IWeUD();
}
if ( --!-( !true[ 19840[ 6056[ !-false.IrLAD()]]]).De8GVKAYyWRMmD) while ( nFZqJfA.YK) ;
;
{
boolean P0Md9HgYKw;
;
bi7XI4wl3qtDNV[][][] XmYIJdxhOI;
return;
return;
{
while ( new void[ -null[ ---( new void[ !_Ql_tK.jP1mpjdl9T3][ !!null[ !true[ !this.p()]]])[ V6hkFcgg3Zwg2[ !new T2SP_v3BlC[ rUNAJ().n].USxI_S5xQufx4()]]]].DcD()) !!true.skBrxf;
}
}
return ( null.F0d()).m8wVnUUnwgQ2();
int[] BcBzYfoT6IIyET;
!---!new boolean[ ggEAar().WDgkOcCsC1G()].llhbp;
void UbzFBoPqPXmK3a;
while ( !this.m0GKAR6krfKm()) while ( new S5uPdGyP0749().IPZ4J()) ;
;
if ( 483459502.E()) while ( vKE().o0lU) {
void[][] OEv7NXQXN2vKHQ;
}else {
boolean[] R1ArVYG7N;
}
void gpypkfgLDGRLI = !new boolean[ ( !false[ !svWcw_().x34lJUEl()]).YYvh].eqYyZw;
QzXi78V[][] UTY5ul6T4jG;
{
new efilGXayAZD().mrWGi3;
if ( -!-false.No0E55p7Y2VtOs()) !new l4ujx_().C();
return;
while ( true.DhY()) if ( this[ this[ null[ new JJDZsdJo().WnvmTND]]]) {
void[] q5I;
}
s9NUqg[] IHd0MWgx;
{
;
}
void RZxojgoxTQ9j;
void f90Q;
void mrewHWz;
boolean bva1yweDA;
if ( dm3FLFA0().JYYmKY()) while ( ( -dy2rY[ !04[ !true.gzNucJm]]).GxX) if ( !!this[ !-u0IpYRLs7q().NRhyLw]) while ( !!new cw_().OE) ;
boolean LRIKPQWLkQN;
void[][][][][] FL;
if ( false[ B1EQYbzFW74().qq1wGjQ0Eirb()]) return;
return;
gBvc XbzulU;
return;
;
JAFJtm DcB9;
this[ !--this[ --!!new int[ this.u][ 42.dwW]]];
}
int lOL6 = !new boolean[ new dg8i5ow()[ !this.m2Odijssut]].vkVtvK2() = -y2ZoLDB.gtThs8OTp();
return new yTmPN2VM().PsnY();
BGdbKmFNmxZE PFRU;
;
return;
{
;
boolean[] O3;
void[][][][][][][] rctJWSmZqiy2;
void MSvvvIwjkQJQtO;
int ZDiwBPU_H;
wfKBfat85v9IB[][] _0Q;
-doVKZh4zNbikR._NoC8pmOn();
if ( -!null.y2jPYR1aqwi()) while ( true.MHWiZvKY) {
T3j5a[][][] BzQe4EmHDF_;
}
{
Z3[] ycb5QqMa76qDjV;
}
void CUsl81pQ;
this.cG_OTQPFkIgN();
dug2S aiMe208;
;
}
}
public boolean[] caFI;
public static void cGIHqF (String[] R2GLY2VQL6RwKZ) {
while ( -an().Nk()) {
{
while ( --false[ !( null.IUGTszRoqmqm1s).ENJB]) while ( -!!false[ IQY12FkmcZfT0e._v_9IhdYW]) if ( YUaGz4V.N6H) return;
}
}
while ( !-FGu4m().nbB()) while ( new K[ !( -true.P68igRFXsu04Kt).l_()].U_4IDCmf1vq6YO()) --new qGc5JtsY7HPp[ null.kW7P2BFeA][ this.F291JeyAoGrC()];
void wPT8 = null.rSLwXn() = -!-!ly6UtbSIwMlzn()[ ( 4203.hNhqc).xzpT_9LJyeZSIu()];
boolean Ibip1q5wmf4t = new JXFetLfVVqY_().vUEsCULrKA;
boolean UEdDLb7O;
boolean[][] ZQW2CK5J = --true[ !W().KFoQT7tJAkJ8];
while ( !_m_4i4L.GYKlvfo1Et) if ( -true[ 35314.nFxJ33a5iRLXeA]) while ( -( --( ( new zleoym1yQK[ this.q6rMuyZySZH].h5e7Be8()).nVp9NnrkLpRa3)[ -!!!x78qB()[ false[ this.XvCm()]]])[ -!-!( -!new d().J2vg()).SF()]) !new Y().irsxC();
}
public void[][][] ICfJQXOqJgn8G () {
return;
if ( 2.JOgCZkQf()) while ( !false[ new int[ -new r_9rNqp6L6Ix().I_6yFq5()].l2_uv]) while ( new boolean[ qjLxKi6aFM().anR].ifrghT9G) while ( !false.TDqc7n()) while ( null.oxuG3HYH1_Ct) false.JwJhzKs93Ri5;else while ( true[ -!---!9.ppzEBQA5UaeC]) if ( !!null.fUEYcy()) ;
boolean vwyq;
boolean[] tq;
if ( --!!!new t().ozXFwJGCMoWQ) ( 0519.QXeE6PA).uov7_Yc;
;
;
{
while ( false.klfuKYSkDfJx8()) --this.cqYrD0rR;
boolean[] F_rhDpLJQEB;
if ( null.MzfV4K()) ( --true.u)[ uNY8q897b6().wSwxlH];
HsXCx Iro8f1O96;
hyQr73d[] nh6vmmxt_jD;
}
}
public int[] CYGOdnDzmFtK (void[] w7KG4HSbNvYZca, void x01pF85W4nT, sPZv uCdadE, boolean[] Ej2q, boolean SmZmTODFJKFt) {
if ( true.Kk()) ;
-( !-!true.sHASV).Wnsbkb();
eo[][] lvBLHa6eJ;
boolean shV4;
Dt65cqa9gzj ftkW3566J1;
LC[] VpB = null[ !-!!null.V] = !0966[ new lVjdNQ_1tHGEf().cyJ5xDZYV4()];
int[] Cw93sSv;
;
int buDhoTGsL4 = !( true.qF_zcJOu3re39W).Z3FL;
}
public void[][][] bcC3Ja6UH;
}
class cqQfhYrZKop {
}
| 39.452991 | 309 | 0.494584 |
e73e02dc5e0a0ac4e055c05bd727f91cef3edab7 | 738 | package cn.nbbandxdd.survey.exam.controller.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* <p>问卷VO。
*
* @author howcurious
*/
@Data
public class ExamVO {
/**
* <p>问卷编号。
*/
private String examCd;
/**
* <p>问卷类型。
*/
private String typCd;
/**
* <p>重复作答标识。
*/
private String rpetInd;
/**
* <p>倒计时标识。
*/
private String cntdwnInd;
/**
* <p>立即展示答案标识。
*/
private String answImmInd;
/**
* <p>标题。
*/
private String ttl;
/**
* <p>描述。
*/
private String dsc;
/**
* <p>起始时间。
*/
private LocalDateTime bgnTime;
/**
* <p>截止时间。
*/
private LocalDateTime endTime;
}
| 12.3 | 47 | 0.48916 |
64aa8833b734aea75df5e95a40a27aaa9b32db96 | 3,227 | /*
* 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
* <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 it.redhat.hacep.playground.configuration;
import it.redhat.hacep.configuration.JmsConfiguration;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.pool.PooledConnectionFactory;
import javax.enterprise.context.ApplicationScoped;
import javax.jms.ConnectionFactory;
@ApplicationScoped
public class JmsConfigurationImpl implements JmsConfiguration {
@Override
public ConnectionFactory getConnectionFactory() {
ActiveMQConnectionFactory connectionFactory;
if (getQueueSecurity()) {
connectionFactory = new ActiveMQConnectionFactory(getQueueUsername(), getQueuePassword(), getQueueBrokerUrl());
} else {
connectionFactory = new ActiveMQConnectionFactory(getQueueBrokerUrl());
}
return new PooledConnectionFactory(connectionFactory);
}
@Override
public String getQueueName() {
try {
return System.getProperty("queue.name", "facts");
} catch (IllegalArgumentException e) {
return "facts";
}
}
@Override
public int getMaxConsumers() {
try {
return Integer.valueOf(System.getProperty("queue.consumers", "5"));
} catch (IllegalArgumentException e) {
return 5;
}
}
@Override
public String getCommandsQueueName() {
try {
return System.getProperty("commands.queue.name", "commands");
} catch (IllegalArgumentException e) {
return "commands";
}
}
private String getQueueBrokerUrl() {
try {
return System.getProperty("queue.url", "tcp://localhost:61616");
} catch (IllegalArgumentException e) {
return "tcp://localhost:61616";
}
}
private boolean getQueueSecurity() {
try {
return Boolean.valueOf(System.getProperty("queue.security", "false"));
} catch (IllegalArgumentException e) {
return false;
}
}
private String getQueueUsername() {
try {
return System.getProperty("queue.usr", "admin");
} catch (IllegalArgumentException e) {
return "admin";
}
}
private String getQueuePassword() {
try {
return System.getProperty("queue.pwd", "admin");
} catch (IllegalArgumentException e) {
return "admin";
}
}
}
| 31.950495 | 123 | 0.657267 |
5f98c771646abc9f96fd446a8cd2dbab88b22ac3 | 2,003 | package br.com.rgb;
import java.io.*;
/**
* Enum com textos de mesnagens utilizadas entre várias classes para facilitar o envio de parâmetros de String,
* diminuindo a necessidade de checar se o parâmetro enviado é inválido ou não.
* Também é utilizada principalmente para comunicar à engine qual foi a ação do usuário na GUI.
* Implementa a interface Serializable para poder ser escrita e lida em arquivo binário.
*
* @author RGB
* @version 28/02/16
*/
public enum Mensagem implements Serializable
{
NOME("NOME"),
ARQUEIRO("Arqueiro"),
CAVALEIRO("Cavaleiro"),
MAGO("Mago"),
/**
* Enum dedicada para mostrar que algum item pode ser utilizado por todas as classes (arqueiro, cavaleiro e mago).
*/
TODOS("Todos"),
DIFICULDADE_ESCOLHIDA("DIFICULDADE_ESCOLHIDA"),
FACIL("FACIL"),
MEDIO("MEDIO"),
DIFICIL("DIFICIL"),
ATAQUE("ATAQUE"),
ATAQUE0("ATAQUE0"),
ATAQUE1("ATAQUE1"),
ATAQUE2("ATAQUE2"),
ATAQUE3("ATAQUE3"),
ATAQUE4("ATAQUE4"),
ATAQUE5("ATAQUE5"),
ATAQUE6("ATAQUE6"),
ATAQUE7("ATAQUE7"),
ATAQUE8("ATAQUE8"),
ATAQUE9("ATAQUE9"),
ATAQUE10("ATAQUE10"),
FUGIR("FUGIR"),
MENU("MENU"),
OK("OK"),
PROXIMO_INIMIGO("PROXIMO_INIMIGO"),
PROXIMO_INIMIGO_FUGA("PROXIMO_INIMIGO_FUGA"),
REJEITA("REJEITA"),
ACEITA("ACEITA"),
TENTAR_NOVAMENTE("TENTAR_NOVAMENTE"),
NOVO_JOGO("NOVO_JOGO"),
/**
* Enum dedicada para mostrar que nenhuma mensagem foi enviada, ou uma mensagem inválida foi utilizada.
*/
NADA("NADA");
private final String texto;
/**
* Cria uma enum de Mensagem com valor válido para o atributo.
* @param texto String com o texto da mensagem a ser transmitida entre classes.
*/
private Mensagem(String texto)
{
this.texto = texto;
}
/**
* Retorna o valor do texto da mensagem a ser usada entre as classes.
*/
public String valor()
{
return texto;
}
}
| 27.438356 | 118 | 0.648527 |
e6de819595a4d1ca5b0ce958795ba2b4c127a74b | 489 | package cn.edu.cug.cs.gtl.series.ml.clustering.kmedoids;
import cn.edu.cug.cs.gtl.ml.dataset.DataSet;
import cn.edu.cug.cs.gtl.ml.dataset.Label;
import cn.edu.cug.cs.gtl.ml.distances.DistanceMetric;
import cn.edu.cug.cs.gtl.series.ml.Series;
public class PAMClusterer extends cn.edu.cug.cs.gtl.ml.clustering.kmedoids.PAMClusterer<Series, Label>{
public PAMClusterer(DataSet<Series> dataSet, DistanceMetric<Series> distanceMetrics) {
super(dataSet, distanceMetrics);
}
}
| 34.928571 | 103 | 0.770961 |
844839fe769c43fc94408a27ec47521219a3a3cc | 6,716 | /*-
* #%L
* anchor-gui-common
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* 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.
* #L%
*/
package org.anchoranalysis.gui.mergebridge;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import lombok.RequiredArgsConstructor;
import org.anchoranalysis.core.exception.AnchorNeverOccursException;
import org.anchoranalysis.core.functional.checked.CheckedFunction;
import org.anchoranalysis.mpp.bean.regionmap.RegionMembershipWithFlags;
import org.anchoranalysis.mpp.mark.Mark;
import org.anchoranalysis.mpp.mark.MarkCollection;
import org.anchoranalysis.mpp.overlay.OverlayCollectionMarkFactory;
import org.anchoranalysis.overlay.IndexableOverlays;
import org.anchoranalysis.overlay.collection.OverlayCollection;
@RequiredArgsConstructor
public class MergeMarksBridge
implements CheckedFunction<
IndexableDualState<MarkCollection>, IndexableOverlays, AnchorNeverOccursException> {
// START REQUIRED ARGUMENTS
private final Supplier<RegionMembershipWithFlags> regionMembership;
// END REQUIRED ARGUMENTS
private List<ProposalState> lastProposalState;
// From the memory of the last set of proposals, get a particlar indexed items
public ProposalState getLastProposalStateForIndex(int index) {
if (lastProposalState == null) {
assert false;
return ProposalState.UNCHANGED;
}
if (index >= lastProposalState.size()) {
assert false;
return ProposalState.UNCHANGED;
}
assert (lastProposalState.get(index) != null);
return lastProposalState.get(index);
}
// We copy each mark, and change the ID to reflect the following
// 1 = UNCHANGED
// 2 = MODIFIED, ORIGINAL
// 3 = MODIFIED, NEW
// 4 = ADDED (BIRTH)
// 5 = REMOVED (DEATH)
private static void processMarkId(
int id,
Mark selected,
Mark proposal,
MarkCollection marksOut,
List<ProposalState> state) {
if (selected != null) {
if (proposal != null) {
// Normal equality check only considers IDss
if (selected.equalsDeep(proposal)) {
// UNCHANGED
Mark outMark = selected.duplicate();
state.add(ProposalState.UNCHANGED);
marksOut.add(outMark);
} else {
// MODIFIED, ORIGINAL
Mark outMarkModifiedOriginal = selected.duplicate();
state.add(ProposalState.MODIFIED_ORIGINAL);
marksOut.add(outMarkModifiedOriginal);
// MODIFIED, NEW
Mark outMarkModifiedNew = proposal.duplicate();
state.add(ProposalState.MODIFIED_NEW);
marksOut.add(outMarkModifiedNew);
}
} else {
// DEATH
Mark outMark = selected.duplicate();
state.add(ProposalState.REMOVED);
marksOut.add(outMark);
}
} else {
// BIRTH
assert (proposal != null);
Mark outMark = proposal.duplicate();
state.add(ProposalState.ADDED);
marksOut.add(outMark);
}
assert (state.get(state.size() - 1) != null);
}
private void copyAsUnchanged(
MarkCollection src, MarkCollection dest, List<ProposalState> state) {
for (Mark markOld : src) {
Mark markNew = markOld.duplicate();
state.add(ProposalState.UNCHANGED);
dest.add(markNew);
}
}
@Override
// We combine both marks into one
public IndexableOverlays apply(IndexableDualState<MarkCollection> sourceObject) {
MarkCollection mergedMarks = new MarkCollection();
lastProposalState = new ArrayList<>();
// If both are valid we do an actual compare
if (sourceObject.getPrimary() != null && sourceObject.getSecondary() != null) {
Map<Integer, Mark> selectedHash = sourceObject.getPrimary().createIdHashMap();
Map<Integer, Mark> proposalHash = sourceObject.getSecondary().createIdHashMap();
// We now create a HashSet of all the IDs
HashSet<Integer> markIds = new HashSet<>();
markIds.addAll(selectedHash.keySet());
markIds.addAll(proposalHash.keySet());
// We loop through all ids
for (int id : markIds) {
Mark selected = selectedHash.get(id);
Mark proposal = proposalHash.get(id);
processMarkId(id, selected, proposal, mergedMarks, lastProposalState);
}
}
// If one is null, and the other is not, we mark them all as unchanged
if (sourceObject.getPrimary() != null && sourceObject.getSecondary() == null) {
copyAsUnchanged(sourceObject.getPrimary(), mergedMarks, lastProposalState);
}
if (sourceObject.getPrimary() == null && sourceObject.getSecondary() != null) {
copyAsUnchanged(sourceObject.getSecondary(), mergedMarks, lastProposalState);
}
OverlayCollection overlays =
OverlayCollectionMarkFactory.createWithoutColor(
mergedMarks, regionMembership.get());
return new IndexableOverlays(sourceObject.getIndex(), overlays);
}
public int size() {
return lastProposalState.size();
}
}
| 37.104972 | 100 | 0.641155 |
14bad54b34e0495a71f025fa8da7335c350f01ae | 5,483 | /**
* Copyright 2018 Kais OMRI.
*
* 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.github.kaiso.relmongo.util;
import io.github.kaiso.relmongo.annotation.FetchType;
import io.github.kaiso.relmongo.annotation.JoinProperty;
import io.github.kaiso.relmongo.annotation.ManyToOne;
import io.github.kaiso.relmongo.annotation.OneToMany;
import io.github.kaiso.relmongo.annotation.OneToOne;
import io.github.kaiso.relmongo.exception.RelMongoConfigurationException;
import io.github.kaiso.relmongo.model.MappedByMetadata;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
/**
*
* @author Kais OMRI
*
*/
public class AnnotationsUtils {
private AnnotationsUtils() {
super();
}
public static String getCollectionName(Field field) {
String collection = ReflectionsUtil.getGenericType(field).getAnnotation(Document.class).collection();
if (StringUtils.isEmpty(collection)) {
collection = ReflectionsUtil.getGenericType(field).getAnnotation(Document.class).value();
}
if (StringUtils.isEmpty(collection)) {
collection = ReflectionsUtil.getGenericType(field).getSimpleName().toLowerCase();
}
return collection;
}
public static String getJoinProperty(Field field) {
try {
return field.getAnnotation(JoinProperty.class).name();
} catch (Exception e) {
throw new RelMongoConfigurationException("Missing or misconfigured @JoinProperty annotation on Field "
+ field.getName() + " from Class " + field.getDeclaringClass());
}
}
public static FetchType getFetchType(Field field) {
FetchType fetchType = null;
if (field.isAnnotationPresent(OneToMany.class)) {
fetchType = field.getAnnotation(OneToMany.class).fetch();
} else if (field.isAnnotationPresent(OneToOne.class)) {
fetchType = field.getAnnotation(OneToOne.class).fetch();
} else if (field.isAnnotationPresent(ManyToOne.class)) {
fetchType = field.getAnnotation(ManyToOne.class).fetch();
}
return fetchType;
}
public static boolean isMappedBy(Field field) {
MappedByMetadata data = new MappedByMetadata();
if (field.isAnnotationPresent(OneToOne.class)) {
data.setMappedByValue(field.getAnnotation(OneToOne.class).mappedBy());
} else if (field.isAnnotationPresent(ManyToOne.class)) {
data.setMappedByValue(field.getAnnotation(ManyToOne.class).mappedBy());
}
return data.getMappedByValue() != null;
}
public static MappedByMetadata getMappedByInfos(Field field) {
MappedByMetadata data = new MappedByMetadata();
Class<? extends Annotation> targetAnnotation = null;
if (field.isAnnotationPresent(OneToOne.class)) {
data.setMappedByValue(field.getAnnotation(OneToOne.class).mappedBy());
if (data.getMappedByValue() != null) {
targetAnnotation = OneToOne.class;
}
} else if (field.isAnnotationPresent(ManyToOne.class)) {
data.setMappedByValue(field.getAnnotation(ManyToOne.class).mappedBy());
if (data.getMappedByValue() != null) {
targetAnnotation = OneToMany.class;
}
}
if (targetAnnotation == null) {
return data;
}
if (field.isAnnotationPresent(JoinProperty.class)) {
throw new RelMongoConfigurationException("can not use mappedBy and @JoinProperty on the same field "
+ field.getName() + " of class " + field.getDeclaringClass().getName());
}
Field targetProp;
Class<?> type = ReflectionsUtil.getGenericType(field);
try {
targetProp = type.getDeclaredField(data.getMappedByValue());
ReflectionUtils.makeAccessible(targetProp);
if (!targetProp.isAnnotationPresent(targetAnnotation)) {
throw new RelMongoConfigurationException("misconfigured bidirectional mapping, the field \""
+ field.getName() + "\" declared in " + field.getDeclaringClass().getName()
+ " declares a mappedBy property linked to the field \"" + data.getMappedByValue()
+ "\" of class " + type.getName()
+ " so you must use compatible RelMongo annotations on the these fields");
}
data.setMappedByJoinProperty(getJoinProperty(targetProp));
} catch (NoSuchFieldException | SecurityException ex) {
throw new RelMongoConfigurationException("unable to find field with name " + data.getMappedByValue()
+ " in the type " + type.getCanonicalName(), ex);
}
return data;
}
}
| 41.225564 | 114 | 0.667518 |
aec9a01b631a0009c3b3d073c0a4f46f9186e97a | 738 | package com.lucidworks.apollo.suggester;
import java.util.List;
import junit.framework.TestCase;
public class TestFileQueryCollector extends TestCase {
public void testFileQueryCollector( ) {
MockSuggestionProcessor sugProc = new MockSuggestionProcessor( );
FileQueryCollector fileQC = new FileQueryCollector( "TestFileQueryCollector/testQueries.txt" );
fileQC.setSuggestionProcessor( sugProc );
fileQC.run( );
List<QuerySuggestion> suggestions = sugProc.getSuggestions( );
System.out.println( "Got " + ((suggestions != null) ? suggestions.size( ) : 0) + " suggestions!" );
for (QuerySuggestion suggestion: suggestions ) {
System.out.println( suggestion.getQuery( ) );
}
}
} | 33.545455 | 103 | 0.714092 |
2e781de25eaf32233a94073b005964b8d041d855 | 383 | package com.lfp.zt.javabase.annontation;
import java.lang.annotation.*;
/**
* Project: zt-javabase
* Title:
* Description:
* Date: 2019-01-06
* Copyright: Copyright (c) 2019
* Company:
*
* @author ZhuTao
* @version 2.0
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Inherited
public @interface TimeAble {
String value() default "";
}
| 16.652174 | 40 | 0.699739 |
4bf553866bf3d3912d3e95092a6103722fa261be | 3,255 | package ecomod.common.blocks;
import ecomod.api.EcomodAPI;
import ecomod.api.EcomodStuff;
import ecomod.api.pollution.PollutionData;
import ecomod.common.pollution.PollutionUtils;
import ecomod.common.pollution.config.PollutionSourcesConfig;
import ecomod.common.utils.EMUtils;
import ecomod.core.EMConsts;
import ecomod.core.stuff.EMConfig;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.Explosion;
import net.minecraft.world.World;
import net.minecraftforge.fluids.BlockFluidFinite;
public class BlockFluidPollution extends BlockFluidFinite {
public BlockFluidPollution()
{
super(EcomodStuff.concentrated_pollution, Material.WATER);
setCreativeTab(EcomodStuff.ecomod_creative_tabs);
setUnlocalizedName(EMConsts.modid+".block."+EcomodStuff.concentrated_pollution.getName());
setResistance(0.5F);
}
public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn)
{
if(worldIn.isRemote)
return;
EcomodAPI.emitPollution(worldIn, EMUtils.blockPosToPair(pos), PollutionSourcesConfig.getSource("concentrated_pollution_explosion_pollution"), true);
if(EMConfig.isConcentratedPollutionExplosive)
worldIn.newExplosion(explosionIn.getExplosivePlacedBy(), pos.getX(), pos.getY(), pos.getZ(), 3F, true, true);
}
public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, IBlockState state, Entity entityIn)
{
if(worldIn.isRemote || entityIn == null)
return;
if(entityIn instanceof EntityLivingBase)
{
if(entityIn.ticksExisted % 20 == 0)
if(!PollutionUtils.isEntityRespirating((EntityLivingBase) entityIn, true))
{
((EntityLivingBase)entityIn).addPotionEffect(new PotionEffect(Potion.getPotionFromResourceLocation("hunger"), 220, 2));
((EntityLivingBase)entityIn).addPotionEffect(new PotionEffect(Potion.getPotionFromResourceLocation("nausea"), 220, 2));
((EntityLivingBase)entityIn).addPotionEffect(new PotionEffect(Potion.getPotionFromResourceLocation("poison"), 180, 1));
}
}
}
@Override
public int tryToFlowVerticallyInto(World world, BlockPos pos, int amtToInput)
{
BlockPos other = pos.add(0, densityDir, 0);
if (other.getY() < 0 || other.getY() >= world.getHeight())
{
PollutionData adv_filter_reduction = PollutionSourcesConfig.getSource("advanced_filter_reduction");
if(adv_filter_reduction != null && adv_filter_reduction.compareTo(PollutionData.getEmpty()) != 0)
{
int amount = this.getQuantaValue(world, pos) * 1000 / this.quantaPerBlock;
if(amount > 0)
EcomodAPI.emitPollution(world, EMUtils.blockPosToPair(pos), new PollutionData(-adv_filter_reduction.getAirPollution() * amount / 2, -adv_filter_reduction.getWaterPollution() * amount / 4, 0), true);
}
world.setBlockToAir(pos);
return 0;
}
return super.tryToFlowVerticallyInto(world, pos, amtToInput);
}
}
| 38.294118 | 212 | 0.743472 |
e3a240c2404b7aa1c518cad6354ac4687d79be36 | 732 | package com.zensar.Spring.main;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.zensar.Spring.performers.Performer;
import com.zensar.Spring.performers.PoeticJuggler;
public class ZensarIdolMain {
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("performers.xml");
Performer juggler = context.getBean("Pyare Mohan", Performer.class);
juggler.perform();
Performer brawler = context.getBean("Lambert Eskel", Performer.class);
brawler.perform();
Performer poeticJuggler = context.getBean("Taylor Swift", Performer.class);
poeticJuggler.perform();
}
}
| 27.111111 | 84 | 0.781421 |
bea30b907e9bc00bb6c19501cb9504aca59da1dc | 851 | package com.myframe.dao.mybatis.dialect;
/**
* Oracle物理分页实现。
*
* @author wyzfzu (wyzfzu@qq.com)
*/
public class OracleDialect extends Dialect {
public String getLimitString(String sql, int offset, int limit) {
sql = sql.trim();
boolean isForUpdate = false;
if (sql.toLowerCase().endsWith(" for update")) {
sql = sql.substring(0, sql.length() - 11);
isForUpdate = true;
}
StringBuilder pagingSelect = new StringBuilder(sql.length() + 100);
pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ")
.append(sql)
.append(" ) row_ ) where rownum_ > ")
.append(offset)
.append(" and rownum_ <= ")
.append(offset + limit);
if (isForUpdate) {
pagingSelect.append(" for update");
}
return pagingSelect.toString();
}
}
| 26.59375 | 78 | 0.607521 |
c90150bccce21b2384f141cbd3f437e7701f9560 | 2,081 | //
// $Id$
package com.threerings.bang.client.bui;
import com.jme.renderer.Renderer;
import com.jmex.bui.BContainer;
import com.jmex.bui.BDecoratedWindow;
import com.jmex.bui.BLabel;
import com.jmex.bui.background.ImageBackground;
import com.jmex.bui.layout.GroupLayout;
import com.threerings.bang.util.BasicContext;
/**
* A popup window with the fancy steel background that has a special slot for a
* title and for buttons at the bottom.
*/
public class SteelWindow extends BDecoratedWindow
{
public SteelWindow (BasicContext ctx, String title)
{
super(ctx.getStyleSheet(), null);
setStyleClass("steelwindow");
((GroupLayout)getLayoutManager()).setGap(20);
add(_header = new BLabel(title, "window_title"), GroupLayout.FIXED);
add(_contents = new BContainer());
add(_buttons = GroupLayout.makeHBox(GroupLayout.CENTER), GroupLayout.FIXED);
// load up our custom header image
_headimg = new ImageBackground(
ImageBackground.FRAME_X, ctx.loadImage("ui/window/header_steel.png"));
}
@Override // documentation inherited
protected void wasAdded ()
{
super.wasAdded();
_headimg.wasAdded();
}
@Override // documentation inherited
protected void wasRemoved ()
{
super.wasRemoved();
_headimg.wasRemoved();
}
@Override // documentation inherited
protected void renderBackground (Renderer renderer)
{
// we don't call super because we need to jimmy things up a bit
int hwidth = _header.getWidth() + 2*HEADER_EDGE;
int hheight = _headimg.getMinimumHeight();
getBackground().render(renderer, 0, 0, _width, _height-hheight+OVERLAP, _alpha);
_headimg.render(renderer, (_width - hwidth)/2, _height - hheight, hwidth, hheight, _alpha);
}
protected BLabel _header;
protected BContainer _contents;
protected BContainer _buttons;
protected ImageBackground _headimg;
protected static final int OVERLAP = 23;
protected static final int HEADER_EDGE = 90;
}
| 30.15942 | 99 | 0.688611 |
7db415b7f410b39ff9f716bb4bf447d1a228f9e4 | 29,426 | package com.gb.istandwithrefugeesapp;
/*
* Copyright (C) 2016 Dev-iL
* 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
*
*
* Based on the work of George MacKerron @ https://github.com/jawj/OverlappingMarkerSpiderfier
*
* Attempt was made to stick to the original method and variable names and to include most of the original comments.
*
* Note: this version is intended to work with android-maps-extensions.
*/
import java.util.*;
import android.graphics.Color;
import android.graphics.Point;
import com.androidmapsextensions.*;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
public class OverlappingMarkerSpiderfier {
/** Corresponds to line 12 of original code*/
private static final String VERSION = "0.3.3"; //version of original code.
private static final String LOGTAG = "MarkerSpiderfier";
private static final double TWO_PI = Math.PI * 2;
private static final double RADIUS_SCALE_FACTOR = 10; // TODO: needs to be computed according to the device px density & zoom lvl
private static final double SPIRAL_ANGLE_STEP = 0.2; //in radians
// Passable params' names
private static final String ARG_KEEP_SPIDERFIED = "keepSpiderfied";
private static final String ARG_MARK_WONT_HIDE = "markersWontHide";
private static final String ARG_MARK_WONT_MOVE = "markersWontMove";
private static final String ARG_NEARBY_DISTANCE = "nearbyDistance";
private static final String ARG_CS_SWITCHOVER = "circleSpiralSwitchover";
private static final String ARG_LEG_WEIGHT = "legWeight";
private final GoogleMap gm;
private Projection proj;
/////// START OF PASSABLE PARAMS ///////
/** By default, the OverlappingMarkerSpiderfier works like Google Earth, in that when you click a spiderfied marker,
* the markers unspiderfy before any other action takes place.
* Since this can make it tricky for the user to work through a set of markers one by one, you can override this
* behaviour by setting the keepSpiderfied option to true. */
private boolean keepSpiderfied = false;
/** By default, change events for each added marker’s position and visibility are observed (so that, if a
* spiderfied marker is moved or hidden, all spiderfied markers are unspiderfied, and the new position is respected
* where applicable). However, if you know that you won’t be moving and/or hiding any of the markers you add to
* this instance, you can save memory (a closure per marker in each case) by setting the options named
* markersWontMove and/or markersWontHide to true. */
private boolean markersWontHide = false;
private boolean markersWontMove = false;
//
/////// END OF PASSABLE PARAMS ////////
private int spiderfiedZIndex = 1000; // ensure spiderfied markersInCluster are on top
private int highlightedLegZIndex = 20; // ensure highlighted leg is always on top
private class _omsData{
private LatLng usualPosition;
private Polyline leg;
LatLng getUsualPosition() {
return usualPosition;
}
public Polyline getLeg() {
return leg;
}
_omsData leg(Polyline newLeg){
if(leg!=null)
leg.remove();
leg=newLeg;
return this; // return self, for chaining
}
_omsData usualPosition(LatLng newUsualPos){
usualPosition=newUsualPos;
return this; // return self, for chaining
}
}
private class MarkerData{
final Marker marker;
final Point markerPt;
boolean willSpiderfy = false;
MarkerData(Marker mark, Point pt){
marker = mark;
markerPt = pt;
}
public MarkerData(Marker mark, Point pt, boolean spiderfication){
marker = mark;
markerPt = pt;
willSpiderfy = spiderfication;
}
}
private class LegColor{
private final int type_satellite;
private final int type_normal; // in the javascript version this is known as "roadmap"
LegColor(int set, int road){
type_satellite = set;
type_normal = road;
}
public LegColor(String set, String road){
type_satellite = Color.parseColor(set);
type_normal = Color.parseColor(road);
}
public int getType_satellite() {
return type_satellite;
}
int getType_normal() {
return type_normal;
}
}
private final LegColor usual = new LegColor(0xAAFFFFFF,0xAA0F0F0F);
public final LegColor highlighted = new LegColor(0xAAFF0000,0xAAFF0000);
/** Corresponds to line 292 of original code */
/* // TODO Class seems unnecessary
private class ProjHelper { // moved here from the end of the file
private GoogleMap googM;
public ProjHelper(GoogleMap gm){
googM = gm;
}
public Projection getProjection
public void draw(){
// dummy function (?!)
}
}*/
//the following lists are initialized later
private List<Marker> markersInCluster; // refers to the current clicked cluster
private List<Marker> spiderfiedClusters; // as the name suggests
private List<Marker> spiderfiedUnclusteredMarkers; // intended to hold makers that were tightly packed but not clustered before spiderfying
private boolean spiderfying = false; //needed for recursive spiderfication
private boolean isAnythingSpiderfied = false;
private float zoomLevelOnLastSpiderfy;
private final HashMap<Marker,_omsData> omsData= new HashMap<>();
private final HashMap<Marker,Boolean> spiderfyable = new HashMap<>();
////////////////////////////////////////////////////////////////////////////////////
///////////////////////////// METHODS BEGIN HERE /////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
/** Corresponds to line 53 of original code*/
public OverlappingMarkerSpiderfier(GoogleMap gm, Object ... varArgs) throws IllegalArgumentException {
this.gm=gm;
int mt = gm.getMapType();
// ProjHelper projHelper = new ProjHelper(gm);
if (varArgs.length > 0)
assignVarArgs(varArgs);
initMarkerArrays();
// Listeners:
gm.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition cameraPosition) {
if(spiderfiedClusters.size()>0 && cameraPosition.zoom != zoomLevelOnLastSpiderfy)
unspiderfyAll();
}
});
}
/** Corresponds to line 61 of original code*/
private void initMarkerArrays(){ //TODO: call on unspiderfyall?
markersInCluster = new ArrayList<>();
List<Marker> displayedMarkers = new ArrayList<>();
spiderfiedClusters = new ArrayList<>();
spiderfiedUnclusteredMarkers = new ArrayList<>();
}
/** Corresponds to line 65 of original code
* Adds marker to be tracked.*/ /*
private Marker addMarker(Marker marker){
if(!isSpiderfyalbe(marker)){
// markerListenerRefs = [ge.addListener(marker, 'click', (event) => @spiderListener(marker, event))]
if (!markersWontHide){
//markerListenerRefs.push(ge.addListener(marker, 'visible_changed', => @markerChangeListener(marker, no)))
markerChangeListener(marker,"visible_changed",false);
}
if (!markersWontMove){
//markerListenerRefs.push(ge.addListener(marker, 'position_changed', => @markerChangeListener(marker, yes)))
markerChangeListener(marker,"position_changed",false);
}
markersInCluster.add(marker);
setSpiderfyalbe(marker, true);
}
return marker;
}
*/
/** Corresponds to line 77 of original code*//*
private void markerChangeListener(Marker marker,String action, boolean positionChanged){
if (omsData.containsKey(marker) && (positionChanged || !marker.isVisible()) && !(spiderfying || unspiderfying) ){
unspiderfy(positionChanged ? marker : null);
}
}
*/
/** Corresponds to line 81 of original code*//*
private List<Marker> getMarkersInCluster(){
// Meant to return a COPY of the original markersInCluster' list; Currently, this is a SHALLOW copy and might cause problems.
List<Marker> markersCopy = new ArrayList<Marker>(markersInCluster);
return markersCopy;
}
*/
/** Corresponds to line 83 of original code
* Removes marker from those being tracked. This does not remove the marker from the map (to remove a marker from
* the map you must call setMap(null) on it, as per usual). *//*
private void removeMarker(Marker marker){
if (omsData.containsKey(marker))
unspiderfy(marker);
int i = markersInCluster.indexOf(marker);
if (i>=0){
// Remove listeners
//TODO?
markersInCluster.remove(i);
}
}
*/
/** Corresponds to line 93 of original code
* Removes every marker from being tracked. Much quicker than calling removeMarker in a loop, since that has
* to search the markers array every time. This does not remove the markers from the map (to remove the markers
* from the map you must call setMap(null) on each of them, as per usual).*//*
private void clearMarkers(){
for (Marker marker : markersInCluster) {
// Remove listeners (methinks this is redundant in java due to "garbage collection")
unspiderfy(marker);
}
initMarkerArrays();
}
*/
/**
* Lines 102-117 in original code seems irrelevant in java
*/
/** Corresponds to line 119 of original code
// available listeners: click(marker), spiderfy(markersInCluster), unspiderfy(markersInCluster) */
private List<Point> generatePtsCircle (int count, Point centerPt){
int circleFootSeparation = 23;
int circumference = circleFootSeparation * ( 2 + count);
double legLength = circumference / TWO_PI * RADIUS_SCALE_FACTOR; // = radius from circumference
double angleStep = TWO_PI / count;
double angle;
List<Point> points = new ArrayList<>(count);
for (int ind = 0; ind < count; ind++) {
double circleStartAngle = TWO_PI / 12;
angle = circleStartAngle + ind * angleStep;
points.add(new Point((int)(centerPt.x + legLength * Math.cos(angle)),(int)(centerPt.y + legLength * Math.sin(angle))));
}
return points;
}
/** Corresponds to line 128 of original code*/
private List<Point> generatePtsSpiral (int count, Point centerPt){
int spiralLengthStart = 11;
double legLength = spiralLengthStart * RADIUS_SCALE_FACTOR;
double angle = 0;
List<Point> points = new ArrayList<>(count);
for (int ind = 0; ind < count; ind++) {
int spiralFootSeparation = 40;
angle += spiralFootSeparation / legLength + ind * SPIRAL_ANGLE_STEP;
points.add(new Point((int)(centerPt.x + legLength * Math.cos(angle)),(int)(centerPt.y + legLength * Math.sin(angle))));
int spiralLengthFactor = 12;
legLength += TWO_PI * spiralLengthFactor / angle;
}
return points;
}
public void spiderListener(Marker cluster){ /** Corresponds to line 138 of original code*/
if (isAnythingSpiderfied && !spiderfying){ // unspiderfy everything before spiderfying anything new
unspiderfyAll();
}
List<MarkerData> closeMarkers = new ArrayList<>();
List<MarkerData> displayedFarMarkers = new ArrayList<>();
/* nearbyDistance is the pixel radius within which a marker is considered to be overlapping a clicked marker. */
int nearbyDistance = 20;
int nDist = nearbyDistance;
int pxSq = nDist * nDist;
Point mPt, markerPt = llToPt(cluster.getPosition());
List<Marker> tmpMarkersInCluster = new ArrayList<>();
tmpMarkersInCluster.addAll(cluster.getMarkers());
markersInCluster.addAll(cluster.getMarkers());
/*
if (!spiderfying)
displayedMarkers = gm.getDisplayedMarkers(); //could be very slow
List<Marker> markersToConsider = new ArrayList<Marker>();
markersToConsider.addAll(displayedMarkers); markersToConsider.addAll(markersInCluster);
LatLngBounds llb = gm.getProjection().getVisibleRegion().latLngBounds;
for (Marker markers_item : markersToConsider) {
if(!llb.contains(markers_item.getPosition()) || markers_item == cluster)
continue;
mPt = proj.toScreenLocation(markers_item.getPosition());
if (ptDistanceSq(mPt,markerPt) < pxSq)
closeMarkers.add(new MarkerData(markers_item,mPt));
else
displayedFarMarkers.add(new MarkerData(markers_item,mPt));
}
if (closeMarkers.size() > 0) {// 0 => only the one clicked is displayed => none nearby
//TODO Probably missing something here
}
*/
for (Marker markers_item : tmpMarkersInCluster) {
if (markers_item.isCluster()) {
recursiveAddMarkersToSpiderfy(markers_item);
}
mPt = proj.toScreenLocation(markers_item.getPosition());
if (ptDistanceSq(mPt,markerPt) < pxSq)
closeMarkers.add(new MarkerData(markers_item,mPt));
else
displayedFarMarkers.add(new MarkerData(markers_item,mPt));
}
spiderfy(closeMarkers,displayedFarMarkers);
spiderfiedClusters.add(cluster);
zoomLevelOnLastSpiderfy = gm.getCameraPosition().zoom;
}
private void recursiveAddMarkersToSpiderfy(Marker markers_item) {
List<Marker> nestedMarkers = markers_item.getMarkers();
for (Marker nestedMarker : nestedMarkers) {
if (!nestedMarker.isCluster()) // inception.... (cluster within a cluster within a cl.....)
tryAddMarker(markersInCluster,nestedMarker);
else
recursiveAddMarkersToSpiderfy(markers_item);
}
}
/** Corresponds to line 161 of original code.
* Returns an array of markers within nearbyDistance pixels of marker — i.e. those that will be spiderfied when
* marker is clicked.
* - *Don’t* call this method in a loop over all your markers, since this can take a very long time.
* - The return value of this method may change any time the zoom level changes, and when any marker is added,
* moved, hidden or removed. Hence you’ll very likely want call it (and take appropriate action) every time the
* map’s zoom_changed event fires and any time you add, move, hide or remove a marker.
* - Note also that this method relies on the map’s Projection object being available, and thus cannot be called
* until the map’s first idle event fires. *//*
private List<Marker> markersNearMarker(Marker marker) {
int nDist = nearbyDistance;
int pxSq = nDist * nDist;
Point markerPt = proj.toScreenLocation(marker.getPosition()); //using android maps api instead of llToPt and ptToLl
Point mPt;
List<Marker> markersNearMarker = new ArrayList<Marker>();
for (Marker markers_item : markersInCluster) {
if(!markers_item.isVisible() /* || markers_item instanceof Marker || (markers_item.map != null) * /){
//no idea whether check for the rest of the conditions; remove space in "* /" if uncommenting block.
continue;
}
mPt = proj.toScreenLocation(omsData.containsKey(marker) ? omsData.get(markers_item).usualPosition : markers_item.getPosition());
if (ptDistanceSq(mPt,markerPt) < pxSq){
markersNearMarker.add(markers_item);
if (firstonly){
firstonly = false;
break;
}
}
}
return markersNearMarker;
}
*/
/**
* Corresponds to line 176 of original code
*
* Returns an array of all markers that are near one or more other markersInCluster — i.e. those will be
* spiderfied when clicked.
* This method is several orders of magnitude faster than looping over all markersInCluster calling markersNearMarker
* (primarily because it only does the expensive business of converting lat/lons to pixel coordinates once per marker).
*
* @param marker
* @return
*/
/*
private List<Marker> markersNearAnyOtherMarker(Marker marker){
try {waitForMapIdle();} catch (InterruptedException e){}
int nDist = nearbyDistance;
int pxSq = nDist * nDist;
int numMarkers = markersInCluster.size();
List<MarkerData> nearbyMarkerData = new ArrayList<MarkerData>(numMarkers);
Point pt;
for (Marker markers_item : markersInCluster) {
pt = proj.toScreenLocation(omsData.containsKey(marker) ? omsData.get(markers_item).usualPosition : markers_item.getPosition());
nearbyMarkerData.add(new MarkerData(markers_item,pt,false));
}
Marker m1, m2;
MarkerData m1Data, m2Data;
for (int i1=0; i1 < numMarkers; i1++) {
m1 = markersInCluster.get(i1);
if(!m1.isVisible() /* || (markers_item.map != null) * /){ //remove space from "* /" if uncommenting block
continue;
}
m1Data = nearbyMarkerData.get(i1);
if(m1Data.willSpiderfy)
continue;
for(int i2=0; i2 < numMarkers; i2++){
m2 = markersInCluster.get(i2);
if(i2==i1 || !m2.isVisible())
continue;
m2Data = nearbyMarkerData.get(i2);
if(i2 < i1 && !m2Data.willSpiderfy)
continue;
if(ptDistanceSq(m1Data.markerPt,m2Data.markerPt) < pxSq){
m1Data.willSpiderfy=true;
m2Data.willSpiderfy=true;
break;
}
}
}
ArrayList<Marker> toSpiderfy = new ArrayList<Marker>(numMarkers);
for (int i=0; i < numMarkers; i++) {
if (nearbyMarkerData.get(i).willSpiderfy)
toSpiderfy.add(nearbyMarkerData.get(i).marker);
}
return toSpiderfy;
}
*/
/** Corresponds to line 198 of original code.*/
/* private Marker highlight (Marker marker){
_omsData data = omsData.get(marker);
switch (gm.getMapType()){
case GoogleMap.MAP_TYPE_NORMAL:
data.leg.setColor(highlighted.getType_normal());
data.leg.setZIndex(highlightedLegZIndex);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
data.leg.setColor(highlighted.getType_satellite());
data.leg.setZIndex(highlightedLegZIndex);
break;
default:
throw new IllegalArgumentException("Passed array is empty.");
}
return marker;
}
*/
/** Corresponds to line 202 of original code*//*
private void unhighlight (Marker marker){
_omsData data = omsData.get(marker);
switch (gm.getMapType()){
case GoogleMap.MAP_TYPE_NORMAL:
data.leg.setColor(usual.getType_normal());
data.leg.setZIndex(usualLegZIndex);
break;
case GoogleMap.MAP_TYPE_SATELLITE:
data.leg.setColor(usual.getType_satellite());
data.leg.setZIndex(usualLegZIndex);
break;
default:
throw new IllegalArgumentException("Passed array is empty.");
}
}
*/
/** Corresponds to line 207 of original code*/
// renamed original inputs as follows: markersData => clusteredMarkersData; nonNearbyMarkers => nearbyMarkers
private void spiderfy(List<MarkerData> clusteredMarkersData,List<MarkerData> nearbyMarkers){
// List<MarkerData> listToUse;
// if ( clusteredMarkersData.size() == 0 && markersInCluster.size() > 0){ //could happen when GoogleMap.clusterSize is too large
//// listToUse = nearbyMarkers;
// listToUse = new ArrayList<MarkerData>();
// listToUse.addAll(nearbyMarkers);
// for (MarkerData markerData : nearbyMarkers) {
// if (markerData.marker.isCluster()){
//// spiderfiedClusters.add(markerData.marker);
// listToUse.remove(markerData);
// }
// }
// }
// else
// listToUse=clusteredMarkersData;
List<MarkerData> listToUse = new ArrayList<>();
listToUse.addAll(clusteredMarkersData); listToUse.addAll(nearbyMarkers); //could be terrible... :P
spiderfying = true;
int numFeet = listToUse.size(); // numFeet is representative of the amount of markers in the cluster
// Compute the positions of the clustered markers after spiderfication
List<Point> nearbyMarkerPts = new ArrayList<>(numFeet);
for (MarkerData markerData : listToUse) {
nearbyMarkerPts.add(markerData.markerPt);
}
Point bodyPt = ptAverage(nearbyMarkerPts);
List<Point> footPts;
/* circleSpiralSwitchover is the lowest number of markers that will be fanned out into a spiral instead of a circle.
0 -> always spiral; Infinity -> always circle. */
int circleSpiralSwitchover = 6;
if (numFeet >= circleSpiralSwitchover){
footPts=generatePtsSpiral(numFeet,bodyPt);
Collections.reverse(footPts);
}
else
footPts=generatePtsCircle(numFeet,bodyPt);
for (int ind =0; ind < numFeet; ind++){
Point footPt = footPts.get(ind);
LatLng footLl = ptToLl(footPt);
MarkerData nearestMarkerData = listToUse.get(ind);
Marker clusterNearestMarker = nearestMarkerData.marker;
int usualLegZIndex = 0;/* This determines the thickness of the lines joining spiderfied markers to their original locations.
The Android default for Polylines is 10F */
float legWeight = 3F;
Polyline leg = gm.addPolyline(new PolylineOptions()
.add(clusterNearestMarker.getPosition(), footLl)
.color(usual.getType_normal())
.width(legWeight)
.zIndex(usualLegZIndex));
omsData.put(clusterNearestMarker,new _omsData()
.leg(leg)
.usualPosition(clusterNearestMarker.getPosition()));
// lines 228-233 in original code seem irrelevant in java
clusterNearestMarker.setClusterGroup(ClusterGroup.NOT_CLUSTERED);
clusterNearestMarker.animatePosition(footLl);
// set clusterNearestMarker zIndex is unavailable in android :\
spiderfiedUnclusteredMarkers.add(clusterNearestMarker);
}
isAnythingSpiderfied=true;
spiderfying=false;
// trigger("spiderfy",spiderfiedUnclusteredMarkers,nearbyMarkers); // ?! Todo: find an idea what to do with this.
}
/**
* Corresponds to line 241 of original code
*
* Returns any spiderfied markers to their original positions, and triggers any listeners you may have set for this event.
* Unless no markersInCluster are spiderfied, in which case it does nothing.
*/
private void unspiderfy(Marker markerToUnspiderfy){ //241
// this function has to return everything to its original state
if (markerToUnspiderfy!=null){ //Todo: make sure that this "if" is needed at all
boolean unspiderfying = true;
if(markerToUnspiderfy.isCluster()){
List<Marker> unspiderfiedMarkers = new ArrayList<>(), nonNearbyMarkers = new ArrayList<>();
for (Marker marker : markersInCluster) {
if(omsData.containsKey(marker)){// ignoring the possibility that (params.markerNotToMove != null)
marker.setPosition(omsData.get(marker).leg(null).getUsualPosition());
marker.setClusterGroup(ClusterGroup.DEFAULT);
//skipped lines 250-254 from original code
unspiderfiedMarkers.add(marker);
} else
nonNearbyMarkers.add(marker);
}
} else { // if a regular (non-cluster) marker
markerToUnspiderfy.setPosition(omsData.get(markerToUnspiderfy).leg(null).getUsualPosition());
markerToUnspiderfy.setClusterGroup(ClusterGroup.DEFAULT);
//skipped lines 250-254 from original code
// spiderfiedUnclusteredMarkers.remove(markerToUnspiderfy); <== will be done by the calling function
}
unspiderfying =false;
}
}
private int ptDistanceSq(Point pt1, Point pt2){ /** Corresponds to line 264 of original code*/
int dx = pt1.x - pt2.x;
int dy = pt1.y - pt2.y;
return (dx * dx + dy * dy);
}
private Point ptAverage(List<Point> pts){ /** Corresponds to line 269 of original code*/
int sumX=0, sumY=0, numPts=pts.size();
for (Point pt : pts) {
sumX += pt.x;
sumY += pt.y;
}
return new Point(sumX / numPts,sumY / numPts);
}
private Point llToPt(LatLng ll) { /** Corresponds to line 276 of original code*/
proj = gm.getProjection();
return proj.toScreenLocation(ll); // the android maps api equivalent
}
private LatLng ptToLl(Point pt){ /** Corresponds to line 277 of original code*/
proj = gm.getProjection();
return proj.fromScreenLocation(pt); // the android maps api equivalent
}
/** Corresponds to line 279 of original code *//*
private int minDistExtract(List<Integer> distances){
if(distances.size()==0)
throw new IllegalArgumentException("Passed array is empty.");
int bestVal = distances.get(0);
int bestValInd = 0;
for (int ind=1; ind < distances.size(); ind++) {
if(distances.get(ind) < bestVal){
bestValInd=ind;
}
}
distances.remove(bestValInd);
return bestValInd;
}
*/
/* arrIndexOf is irrelevant in java - Corresponds to line 287 of original code */
/** ////////// BELOW ARE HELPER FUNCTION NOT FOUND IN THE ORIGINAL CODE /////////// */
private void waitForMapIdle() throws InterruptedException{
while (proj==null){ // check for "idle" event on map (i.e. no animation is playing)
Thread.sleep(50);// "Must wait for 'idle' event on map before calling whatever's next"
}
}
private void setSpiderfyalbe(Marker marker, boolean mode){
spiderfyable.put(marker,mode);
}
private boolean isSpiderfyalbe(Marker marker){
return spiderfyable.containsKey(marker) ? spiderfyable.get(marker) : false;
}
public boolean isAnythingSpiderfied() {
return spiderfiedClusters !=null;
}
//Right now method only checks the structure + names
private void assignVarArgs(Object[] varArgs){
int varLen=varArgs.length;
if(varLen % 2 != 0){
throw new IllegalArgumentException("Number of args is uneven.");
}
for(int ind=0; ind<varLen; ind=+2){
String key = (String) varArgs[ind];
if(key.equals(ARG_KEEP_SPIDERFIED)){}
else if(key.equals(ARG_MARK_WONT_HIDE)){}
else if(key.equals(ARG_MARK_WONT_MOVE)){}
else if(key.equals(ARG_NEARBY_DISTANCE)){}
else if(key.equals(ARG_CS_SWITCHOVER)){}
else if(key.equals(ARG_LEG_WEIGHT)){}
else throw new IllegalArgumentException("Invalid argument name.");
}
}
private void unspiderfyAll() {
for (Marker lastSpiderfiedCluster : spiderfiedClusters) {
unspiderfy(lastSpiderfiedCluster);
}
for (Marker marker : spiderfiedUnclusteredMarkers) {
unspiderfy(marker);
}
initMarkerArrays(); //hopefully, return to the initial state
isAnythingSpiderfied=false;
}
private void tryAddMarker(Collection<Marker> collection, Marker obj){
if (collection.contains(obj)){}
else {
collection.add(obj);
}
}
} | 42.708273 | 143 | 0.625433 |
d75eb77b6a422ac1bca920d547b998c716b5bf1e | 1,540 | /*
* Copyright (C) 2015 Brian Dupras
*
* 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.
*/
/**
* Probabilistic data structures for Guava.
*
* <p>This package is a part of the open-source <a target="_top" href="https://github.com/bdupras/guava-probably">Guava-Probably
* library</a>.
*
* <h2>Contents</h2>
*
* <h3>Probabilistic Filters</h3>
*
* <ul>
*
* <li>{@link com.duprasville.guava.probably.ProbabilisticFilter} - interface defining basic methods
* of probabilistic filters: {@link com.duprasville.guava.probably.ProbabilisticFilter#add(Object)},
* {@link com.duprasville.guava.probably.ProbabilisticFilter#contains(Object)}, and {@link
* com.duprasville.guava.probably.ProbabilisticFilter#currentFpp()}.</li>
*
* <li>{@link com.duprasville.guava.probably.CuckooFilter} - Cuckoo filter implementation that
* supports deletion.</li>
*
* <li>{@link com.duprasville.guava.probably.BloomFilter} - Bloom filter implementation backed by
* Guava's BloomFilter.</li>
*
* </ul>
*/
package com.duprasville.guava.probably;
| 37.560976 | 128 | 0.736364 |
b16f6c49889ad726bc95900015acfc23f110d741 | 2,558 | /*
* Copyright (C) 2018-2022 FusionSoft
*
* 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 ru.fusionsoft.database.snapshot.query.pg;
import ru.fusionsoft.database.mapping.fields.DbdEnumField;
/**
* The only type of {@link PgMessageFormatQuery} of {@link DbdEnumField}.
* @since 0.1
*/
public class PgEnumsQuery extends PgMessageFormatQuery<DbdEnumField> {
/**
* Instantiates a new Pg enums query.
*/
public PgEnumsQuery() {
super(
String.join(
"",
"SELECT \n",
" n.nspname AS {0}, \n",
" t.typname AS {1}, \n",
" r.rolname AS {2}, \n",
" pg_catalog.obj_description ( t.oid, 'pg_type' ) AS {3},\n",
" ARRAY( \n",
" SELECT e.enumlabel\n",
" FROM pg_catalog.pg_enum e\n",
" WHERE e.enumtypid = t.oid\n",
" ORDER BY e.oid \n",
" ) AS {4}\n",
"FROM pg_type t \n",
"LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace \n",
"LEFT JOIN pg_roles r ON r.oid = t.typowner\n",
"WHERE (\n",
" t.typrelid = 0 \n",
" OR (\n",
" SELECT c.relkind = 'c' \n",
" FROM pg_catalog.pg_class c \n",
" WHERE c.oid = t.typrelid\n",
" )\n",
") \n",
"AND NOT EXISTS(\n",
" SELECT 1 \n",
" FROM pg_catalog.pg_type el \n",
" WHERE el.oid = t.typelem \n",
" AND el.typarray = t.oid\n",
")\n",
"AND n.nspname NOT IN ('pg_catalog', 'information_schema')\n",
"AND t.typtype = 'e'"
),
DbdEnumField.SCHEMA,
DbdEnumField.ENUM,
DbdEnumField.OWNER,
DbdEnumField.DESCRIPTION,
DbdEnumField.ELEMENTS
);
}
}
| 35.041096 | 85 | 0.507819 |
e4ca0faa6c189719cc5beab286c5bbba5eda4bfa | 411 | package baobab.pet.data.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import baobab.pet.data.domain.Book;
import baobab.pet.data.domain.User;
import baobab.pet.data.domain.WriteAccess;
public interface WriteAccessRepository extends JpaRepository<WriteAccess, Long> {
WriteAccess findOneByBookAndUser(Book book, User user);
void deleteByBookAndUser(Book book, User user);
}
| 34.25 | 81 | 0.815085 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.