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 |
|---|---|---|---|---|---|
b3275dcc7ad75382b5fe3625bfa2ed4d56dcb579 | 561 | import java.util.Arrays;
class PascalsTriangleIi {
public int[] getRow(int rowIndex) {
int[] list = new int[rowIndex];
int[] previousList = new int[rowIndex];
for (int i = 0; i < rowIndex; i++) {
list[0] = 1;
for (int j = 1; j < i; j++) {
list[j] = previousList[j - 1] + previousList[j];
}
list[i] = 1;
previousList = list.clone();
}
return list;
}
public static void main(String[] args) {
System.out.println(Arrays.toString(new PascalsTriangleIi().getRow(Integer.parseInt(args[0]))));
}
} | 26.714286 | 99 | 0.58467 |
f583be596f64f799d2cf2f37dea5d8cd677083f9 | 1,165 | package panda.bean.handler;
import java.lang.reflect.Type;
import java.util.List;
import panda.bean.Beans;
import panda.lang.reflect.Types;
/**
*
* @param <T> class type
*/
@SuppressWarnings("rawtypes")
public class ListBeanHandler<T extends List> extends AbstractArrayBeanHandler<T> {
protected Type elementType;
/**
* Constructor
* @param beans bean handler factory
* @param type bean type
*/
public ListBeanHandler(Beans beans, Type type) {
super(beans, type);
elementType = Types.getCollectionElementType(type);
}
@Override
protected Type getElementType() {
return elementType;
}
@Override
protected int getSize(T list) {
return list.size();
}
@Override
protected Object getElement(T list, int index) {
return list.get(index);
}
@Override
protected boolean isValidSetIndex(T array, int index) {
return index >= 0;
}
@Override
@SuppressWarnings("unchecked")
protected boolean setElement(T list, int index, Object value) {
// append null elements
if (index >= list.size()) {
for (int i = list.size(); i <= index; i++) {
list.add(null);
}
}
list.set(index, value);
return true;
}
}
| 18.790323 | 82 | 0.688412 |
0bd5125c00b0d69db52a228da5518ecd20aa092e | 9,146 | package com.bkromhout.minerva.data;
import com.bkromhout.minerva.C;
import com.bkromhout.minerva.realm.RBookList;
import com.bkromhout.minerva.realm.RBookListItem;
import io.realm.Realm;
import io.realm.RealmResults;
import io.realm.Sort;
/**
* Provides static methods to help with reordering {@link RBookListItem}s when they are dragged.
*/
public class ListItemPositionHelper {
/**
* Moves the {@link RBookListItem} whose unique ID is {@code itemToMoveId} to somewhere before the {@link
* RBookListItem} whose unique ID is {@code targetItemId}.
* @param itemToMoveId Unique ID of item to move.
* @param targetItemId Unique ID of item which item whose unique ID is {@code itemToMoveId} will be moved before.
*/
public static void moveItemToBefore(long itemToMoveId, long targetItemId) {
try (Realm realm = Realm.getDefaultInstance()) {
moveItemToBefore(realm.where(RBookListItem.class).equalTo("uniqueId", itemToMoveId).findFirst(),
realm.where(RBookListItem.class).equalTo("uniqueId", targetItemId).findFirst());
}
}
/**
* Moves {@code itemToMove} to somewhere before {@code targetItem}.
* @param itemToMove Item to move.
* @param targetItem Item which {@code itemToMove} will be moved before.
*/
private static void moveItemToBefore(RBookListItem itemToMove, RBookListItem targetItem) {
if (itemToMove == null || targetItem == null) throw new IllegalArgumentException("Neither item may be null.");
if (itemToMove.uniqueId == targetItem.uniqueId) return;
RBookList bookList = targetItem.owningList;
// Get the items which come before targetItem.
RealmResults<RBookListItem> beforeTarget = bookList.listItems
.where()
.lessThan("pos", targetItem.pos)
.findAllSorted("pos", Sort.DESCENDING);
// Move itemToMove to between beforeTarget.first()/null and targetItem.
moveItemToBetween(bookList, itemToMove, beforeTarget.isEmpty() ? null : beforeTarget.first(), targetItem);
}
/**
* Moves the {@link RBookListItem} whose unique ID is {@code itemToMoveId} to somewhere after the {@link
* RBookListItem} whose unique ID is {@code targetItemId}.
* @param itemToMoveId Unique ID of item to move.
* @param targetItemId Unique ID of item which item whose unique ID is {@code itemToMoveId} will be moved after.
*/
public static void moveItemToAfter(long itemToMoveId, long targetItemId) {
try (Realm realm = Realm.getDefaultInstance()) {
moveItemToAfter(realm.where(RBookListItem.class).equalTo("uniqueId", itemToMoveId).findFirst(),
realm.where(RBookListItem.class).equalTo("uniqueId", targetItemId).findFirst());
}
}
/**
* Moves {@code itemToMove} to somewhere after {@code targetItem}.
* @param itemToMove Item to move.
* @param targetItem Item which {@code itemToMove} will be moved after.
*/
private static void moveItemToAfter(RBookListItem itemToMove, RBookListItem targetItem) {
if (itemToMove == null || targetItem == null) throw new IllegalArgumentException("Neither item may be null.");
if (itemToMove.uniqueId == targetItem.uniqueId) return;
RBookList bookList = targetItem.owningList;
// Get the items which come after targetItem.
RealmResults<RBookListItem> afterTarget = bookList.listItems
.where()
.greaterThan("pos", targetItem.pos)
.findAllSorted("pos");
// Move itemToMove to between targetItem and afterTarget.first()/null.
moveItemToBetween(bookList, itemToMove, targetItem, afterTarget.isEmpty() ? null : afterTarget.first());
}
/**
* Moves {@code itemToMove} to between {@code item1} and {@code item2} in {@code bookList}. If {@code item1} and
* {@code item2} aren't consecutive items, behavior is undefined. It is assumed that {@code itemToMove}, {@code
* item1}, and {@code item2} are all owned by {@code bookList}.
* <p>
* If {@code itemToMove} is the same as either {@code item1} or {@code item2} then this method does nothing.<br/>If
* {@code item1} is {@code null}, then {@code itemToMove} will be put after {@code item1} with the standard position
* gap.<br/>If {@code item2} is {@code null}, then {@code itemToMove} will be put before {@code item2} with the
* standard position gap.
* <p>
* Please note that passing {@code null} for one of the items assumes that the non-null item is either the first (if
* it's {@code item2}), or the last (if it's {@code item1}) item in {@code bookList}. If this isn't the case, some
* items will likely have colliding position values when this method finishes.
* <p>
* If there's no space between {@code item1} and {@code item2}, the whole list will have its items re-spaced before
* moving the item.
* <p>
* The current spacing gap can be found at {@link C#LIST_ITEM_GAP}.
* @param bookList The book list which owns {@code itemToMove}, {@code item1}, and {@code item2}.
* @param itemToMove The item which is being moved.
* @param item1 The item which will now precede {@code itemToMove}.
* @param item2 The item which will now follow {@code itemToMove}.
*/
private static void moveItemToBetween(RBookList bookList, RBookListItem itemToMove, RBookListItem item1,
RBookListItem item2) {
bookList.throwIfSmartList();
if (itemToMove == null || (item1 == null && item2 == null))
throw new IllegalArgumentException("itemToMove, or both of item1 and item2 are null.");
// Check if itemToMove is the same as either item1 or item2.
if ((item1 != null && itemToMove.equals(item1)) || (item2 != null && itemToMove.equals(item2))) return;
// Try to find the new position for the item, and make sure we didn't get a null back.
Long newPos = findMiddlePos(bookList, item1, item2);
if (newPos == null) {
// If newPos is null, we need to re-sort the items before moving itemToMove.
bookList.resetPositions();
newPos = findMiddlePos(bookList, item1, item2);
if (newPos == null)
throw new IllegalArgumentException("Couldn't find space between item1 and item2 after re-spacing");
}
// Get Realm, update itemToMove, then close Realm.
try (Realm realm = Realm.getDefaultInstance()) {
final Long finalNewPos = newPos;
realm.executeTransaction(tRealm -> itemToMove.pos = finalNewPos);
}
}
/**
* Find the position number that is between the two given items. It is assumed that both {@code item1} and {@code
* item2} are owned by {@code bookList}. If there are no positions between the items, or if {@code item1} and {@code
* item2} aren't consecutive items (and there is already an item halfway between them), {@code null} is returned.
* <p>
* {@code null} can be passed for ONE of {@code item1} or {@code item2}:<br/>If {@code item1} is {@code null}, the
* number returned will be {@code item1.getPosition() + gap}<br/>If {@code item2} is {@code null}, the number
* returned will be {@code item2.getPosition() - gap}.<br/>(The current spacing gap can be found at {@link
* com.bkromhout.minerva.C#LIST_ITEM_GAP}.)
* <p>
* Please note that passing {@code null} for one of the items assumes that the non-null item is either the first (if
* it's {@code item2}), or the last (if it's {@code item1}) item in {@code bookList}. If this isn't the case, the
* returned position might already be in use.
* @param bookList The list which owns {@code item1} and {@code item2}.
* @param item1 The earlier item (which the returned position will follow).
* @param item2 The later item (which the returned position will precede).
* @return The position number between the two items, or {@code null} if there's no space between the items.
*/
private static Long findMiddlePos(RBookList bookList, RBookListItem item1, RBookListItem item2) {
// Handle nulls which should throw IllegalArgumentException.
if (item1 == null && item2 == null) throw new IllegalArgumentException("Both items are null.");
// Handle acceptable nulls.
if (item1 == null) return item2.pos - C.LIST_ITEM_GAP;
if (item2 == null) return item1.pos + C.LIST_ITEM_GAP;
// Get positions, make sure that item2 doesn't precede item1 and isn't in the same position as item1.
Long p1 = item1.pos, p2 = item2.pos;
if (p2 <= p1) throw new IllegalArgumentException("item2 was before or at the same position as item1.");
// Calculate middle.
Long pos = (p1 + p2) / 2L;
// Make sure there isn't an item in the calculated position. If there is, return null.
return bookList.listItems.where().equalTo("pos", pos).findFirst() == null ? pos : null;
}
}
| 55.096386 | 120 | 0.662694 |
0e035d389369046a100c8c128cb5fbcabb8c42a7 | 684 | package cn.gsein.xuan.common.util;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
/**
* 日期和时间处理的工具类
*
* @author G. Seinfeld
* @since 2020/06/09
*/
public final class DateUtil {
private DateUtil() {
}
public static LocalDateTime now() {
return LocalDateTime.now();
}
public static Date nowDate() {
return new Date();
}
/**
* 将LocalDateTime转为Date
*/
public static Date toDate(LocalDateTime localDateTime) {
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
return Date.from(zonedDateTime.toInstant());
}
}
| 19.542857 | 83 | 0.660819 |
4b7228b58d5e402641179df4a8f871d9f2a14897 | 2,931 | /*
* Copyright 2013 SEARCH Group, Incorporated.
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. SEARCH Group 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 gov.nij.bundles.intermediaries.ers;
import java.util.Iterator;
import javax.xml.namespace.NamespaceContext;
/**
*
* This class implements a NamespaceContext that assist with internal Xpath queries. These namespaces only address
* the Entity Resolution SSP however this class is not meant to deal with namespaces for the
* actual payloads inside of the entity container.
*
*/
final class EntityResolutionNamespaceContext implements NamespaceContext
{
static final String MERGE_NAMESPACE = "http://nij.gov/IEPD/Exchange/EntityMergeRequestMessage/1.0";
static final String MERGE_RESULT_NAMESPACE = "http://nij.gov/IEPD/Exchange/EntityMergeResultMessage/1.0";
static final String ER_EXT_NAMESPACE = "http://nij.gov/IEPD/Extensions/EntityResolutionExtensions/1.0";
static final String MERGE_RESULT_EXT_NAMESPACE = "http://nij.gov/IEPD/Extensions/EntityMergeResultMessageExtensions/1.0";
static final String STRUCTURES_NAMESPACE = "http://niem.gov/niem/structures/2.0";
static final String NC_NAMESPACE = "http://niem.gov/niem/niem-core/2.0";
static final String JXDM_NAMESPACE = "http://niem.gov/niem/domains/jxdm/4.1";
public String getNamespaceURI(String prefix)
{
if ("er-ext".equals(prefix))
{
return EntityResolutionNamespaceContext.ER_EXT_NAMESPACE;
} else if ("merge".equals(prefix))
{
return EntityResolutionNamespaceContext.MERGE_NAMESPACE;
} else if ("merge-result".equals(prefix))
{
return EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE;
} else if ("merge-result-ext".equals(prefix))
{
return EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE;
} else if ("s".equals(prefix))
{
return EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE;
} else if ("nc".equals(prefix))
{
return EntityResolutionNamespaceContext.NC_NAMESPACE;
} else if ("jxdm".equals(prefix))
{
return EntityResolutionNamespaceContext.JXDM_NAMESPACE;
}
return null;
}
public String getPrefix(String arg0)
{
return null;
}
@SuppressWarnings("rawtypes")
public Iterator getPrefixes(String arg0)
{
return null;
}
} | 36.6375 | 122 | 0.747868 |
9c99a2d1dab2197d43a97a6f7c7c063b93efb31c | 560 | package PatikaJava;
import java.util.Scanner;
public class Patika31 {
public static void main(String[] args) {
Scanner inp = new Scanner(System.in);
System.out.print("Bir sayı giriniz : ");
int n = inp.nextInt();
inp.close();
int fib = 0;
int next = 1;
int temp;
System.out.print(n + " elemanlı fibonacci serisi : ");
for (int i = 0; i < n; i++) {
System.out.print(fib + " ");
temp = fib;
fib = next;
next += temp;
}
}
}
| 23.333333 | 62 | 0.491071 |
5539d3b62aac97775bde069f77e395c3ef66d472 | 3,332 | package com.spider.test;
import java.util.Random;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class MyThread implements Runnable {
private static final Logger logger = LoggerFactory.getLogger(MyThread.class);
private boolean flag;
@Override
public void run() {
logger.info("线程- "+Thread.currentThread().getName()+" 进入"+" flag:"+flag);
// if(!Thread.currentThread().getName().equals("main")) {
// try {
// logger.info("线程:"+Thread.currentThread().getName()+" 休息1s "+flag);
// Thread.sleep(1000);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
if(flag) {
logger.info("线程-"+Thread.currentThread().getName());
try {
logger.info("线程-"+Thread.currentThread().getName()+" 休息5秒");
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
logger.info(UrlQueue.isEmpty()?"列队为空":"列队不为空 "+UrlQueue.getElement());
while(!UrlQueue.isEmpty()) {
flag = true;
String url = UrlQueue.outElement();
logger.info("线程-" + Thread.currentThread().getName() + " 开始处理URL:"+url+" | 全局flag设置为:"+flag);
int i = Integer.parseInt(String.valueOf(url.charAt(5)));
if(i%2==0) {
int j = new Random().nextInt(100);
UrlQueue.addElement("wURL-"+j);
logger.info("w添加 URL-"+j+" 到列队");
}
}
logger.info("线程-" + Thread.currentThread().getName() + ": 结束...");
}
}
public class TestThread {
private static final Logger logger = LoggerFactory.getLogger(TestThread.class);
public static void main(String[] args) {
initThread();
initQueue();
}
private static void initThread() {
for(int i=0;i<3;i++) {
new Thread(new MyThread()).start();
}
}
private static void initQueue() {
// try {
for(int i=0;i<=10; i++) {
UrlQueue.addElement("fURL-"+i);
logger.info("f添加 URL-"+i+" 到列队");
// TimeUnit.SECONDS.sleep(1);
}
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
}
}
class UrlQueue {
private static BlockingDeque<String> urlDeques = new LinkedBlockingDeque<>();
public static void addElement(String url) {
try {
urlDeques.putLast(url);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String outElement() {
try {
return urlDeques.takeFirst();
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
public static void addFirstElement(String url){
try {
urlDeques.putFirst(url);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static String getElement() {
return urlDeques.peek();
}
public static boolean isEmpty() {
return urlDeques.isEmpty();
}
public static int size() {
return urlDeques.size();
}
public static boolean isContains(String url) {
return urlDeques.contains(url);
}
}
/*
Random random = new Random();
if(random.nextBoolean()) {
int i = random.nextInt();
UrlQueue.addElement("RandomURL-"+i);
logger.info("Random添加 URL-"+i+" 到列队");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
*/ | 24.321168 | 97 | 0.632053 |
0f61dd5a7c396b562f03b7c2816e04c8cd53413f | 1,109 | package com.sequenceiq.cloudbreak.converter;
import javax.inject.Inject;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.api.endpoint.v4.imagecatalog.requests.UpdateImageCatalogV4Request;
import com.sequenceiq.cloudbreak.domain.ImageCatalog;
import com.sequenceiq.cloudbreak.service.image.ImageCatalogService;
@Component
public class UpdateImageCatalogRequestToImageCatalogConverter extends AbstractConversionServiceAwareConverter<UpdateImageCatalogV4Request, ImageCatalog> {
@Inject
private ImageCatalogService imageCatalogService;
@Override
public ImageCatalog convert(UpdateImageCatalogV4Request source) {
ImageCatalog original = imageCatalogService.findByResourceCrn(source.getCrn());
ImageCatalog imageCatalog = new ImageCatalog();
imageCatalog.setImageCatalogUrl(source.getUrl());
imageCatalog.setName(source.getName());
imageCatalog.setId(original.getId());
imageCatalog.setResourceCrn(source.getCrn());
imageCatalog.setCreator(original.getCreator());
return imageCatalog;
}
}
| 36.966667 | 154 | 0.791704 |
935414fff80caf16a3081c5541462d8e478bb54d | 1,040 | package com.wechat.testdemo;
import android.content.Context;
import android.os.SystemClock;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.lsjwzh.test.Util;
public abstract class TestListAdapter extends BaseAdapter {
protected Context context;
public long bindCost = 0;
public TestListAdapter(Context context) {
this.context = context;
}
@Override
public int getCount() {
return Util.TEST_LIST_ITEM_COUNT;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public final View getView(int position, View convertView, ViewGroup parent) {
long start = SystemClock.elapsedRealtime();
convertView = bindView(position, convertView, parent);
long end = SystemClock.elapsedRealtime();
bindCost += (end - start);
return convertView;
}
public abstract View bindView(int position, View convertView, ViewGroup parent);
} | 22.12766 | 82 | 0.736538 |
fc71a6b6f01d9b87d22a1e28b28f2b7c011dd2a0 | 4,901 | package de.k7bot.moderation;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentHashMap.KeySetView;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import de.k7bot.Klassenserver7bbot;
import de.k7bot.util.LiteSQL;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.TextChannel;
public class SystemNotificationChannelHolder {
private final ConcurrentHashMap<Guild, TextChannel> systemchannellist = new ConcurrentHashMap<>();
/**
* Synchronises the Local SystemchannelList with the database and checks if
* there are new Guilds and lists their SystemChannels.
*/
public void checkSysChannelList() {
LiteSQL sqlite = Klassenserver7bbot.INSTANCE.getDB();
Klassenserver7bbot.INSTANCE.shardMan.getGuilds().forEach(gu -> {
if (!this.systemchannellist.containsKey(gu)) {
this.systemchannellist.put(gu, gu.getSystemChannel());
}
});
try {
ResultSet set = sqlite.onQuery("SELECT guildId, syschannelId FROM botutil");
List<Guild> dblist = new ArrayList<>();
if (set != null) {
while (set.next()) {
Guild guild = Klassenserver7bbot.INSTANCE.shardMan.getGuildById(set.getLong("guildId"));
if (guild != null) {
dblist.add(guild);
if (!this.systemchannellist.containsKey(guild)) {
TextChannel channel = guild.getTextChannelById(set.getLong("syschannelId"));
if (channel != null) {
this.systemchannellist.put(guild, channel);
} else {
this.systemchannellist.put(guild, guild.getSystemChannel());
sqlite.onUpdate(
"UPDATE botutil SET syschannelId=" + guild.getSystemChannel().getIdLong()
+ " WHERE guildId=" + set.getLong("guildId"));
}
}
}
}
}
this.systemchannellist.keySet().forEach(key -> {
if (dblist.contains(key)) {
sqlite.onUpdate("UPDATE botutil SET syschannelId=" + this.systemchannellist.get(key).getIdLong()
+ " WHERE guildId=" + key.getIdLong());
} else {
sqlite.onUpdate("INSERT INTO botutil(guildId, syschannelId) VALUES(" + key.getIdLong() + ", "
+ this.systemchannellist.get(key).getIdLong() + ")");
}
});
;
} catch (SQLException e) {
e.printStackTrace();
}
List<Guild> listedguilds = Klassenserver7bbot.INSTANCE.shardMan.getGuilds();
KeySetView<Guild, TextChannel> alreadylisted = systemchannellist.keySet();
listedguilds.forEach(guild -> {
if ((!alreadylisted.contains(guild)) || (systemchannellist.get(guild) == null)) {
systemchannellist.put(guild, guild.getSystemChannel());
}
});
}
/**
* Puts the given {@link net.dv8tion.jda.api.entities.TextChannel SystemChannel}
* into the Hashmap keyed by his {@link Guild}.
*
* @param channel <br>
* The {@link net.dv8tion.jda.api.entities.TextChannel
* SystemChannel} wich u want to use in this {@link Guild}.
*/
public void insertChannel(TextChannel channel) {
checkSysChannelList();
Guild guild = channel.getGuild();
if (!systemchannellist.containsKey(guild)) {
systemchannellist.put(guild, channel);
Klassenserver7bbot.INSTANCE.getDB().onUpdate("INSERT INTO botutil(guildId, syschannelId) VALUES("
+ guild.getIdLong() + ", " + channel.getIdLong() + ")");
} else {
systemchannellist.replace(guild, channel);
Klassenserver7bbot.INSTANCE.getDB().onUpdate("UPDATE botutil SET syschannelId = " + channel.getIdLong()
+ " WHERE guildId = " + guild.getIdLong());
}
}
/**
* @param guild <br>
* The {@link Guild} for which you want the SystemChannel.
* @return The {@link net.dv8tion.jda.api.entities.TextChannel SystemChannel}
* for the Guild or {@code null} if no channel is listed.
*/
@Nullable
public TextChannel getSysChannel(@Nonnull Guild guild) {
return systemchannellist.get(guild);
}
/**
* @param guildId <br>
* The Id of the {@link Guild} for which you want the
* SystemChannel.
* @return The {@link net.dv8tion.jda.api.entities.TextChannel SystemChannel}
* for the Guild or {@code null} if no channel is listed.
*/
@Nullable
public TextChannel getSysChannel(@Nonnull Long guildId) throws NullPointerException {
Guild guild = Klassenserver7bbot.INSTANCE.shardMan.getGuildById(guildId);
return systemchannellist.get(guild);
}
/**
* Only used if you want the full ConcurrentHashMap! If you want only one
* {@link net.dv8tion.jda.api.entities.TextChannel SystemChannel} please use
* {@link SystemNotificationChannelHolder#getSysChannel()}
*
* @return The current HashMap of SystemChannels wich is used by the Bot.
*/
public ConcurrentHashMap<Guild, TextChannel> getHashMap() {
return systemchannellist;
}
}
| 29.70303 | 106 | 0.690063 |
ae2324da515f17fa25db3e3a1848494e7a8c71b0 | 3,880 | package com.internship.pbt.bizarechat.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import com.internship.pbt.bizarechat.R;
import com.internship.pbt.bizarechat.presentation.model.ContactsFriends;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class FriendsAdapter extends RecyclerView.Adapter<FriendsAdapter.FriendsHolder> {
private List<ContactsFriends> items;
private Context context;
public FriendsAdapter(List<ContactsFriends> items) {
this.items = items;
}
public List<ContactsFriends> getItems() {
return items;
}
@Override
public FriendsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_invite_friends, parent, false);
FriendsHolder holder = new FriendsHolder(view, this);
return holder;
}
public void setContext(Context context) {
this.context = context;
}
@Override
public void onBindViewHolder(FriendsHolder holder, int position) {
final ContactsFriends friend = items.get(position);
holder.setPosition(position);
holder.mName.setText(friend.getName());
holder.mEmail.setText(friend.getEmail());
if (friend.getUserPic() != null) {
holder.mImageView.setImageBitmap(friend.getUserPic());
} else {
holder.mImageView.setImageDrawable(context.getResources().getDrawable(R.drawable.user_icon));
}
if (friend.isChecked()) {
holder.mName.setTextColor(context.getResources().getColor(R.color.black));
} else {
holder.mName.setTextColor(context.getResources().getColor(R.color.chats_item_last_message));
}
//in some cases, it will prevent unwanted situations
holder.mCheckBox.setOnCheckedChangeListener(null);
//if true, your checkbox will be selected, else unselected
holder.mCheckBox.setChecked(friend.isChecked());
holder.mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
friend.setChecked(isChecked);
if (isChecked) {
holder.mName.setTextColor(context.getResources().getColor(R.color.black));
} else {
holder.mName.setTextColor(context.getResources().getColor(R.color.chats_item_last_message));
}
}
});
}
@Override
public int getItemCount() {
return items.size();
}
public static class FriendsHolder extends RecyclerView.ViewHolder {
ContactsFriends item;
FriendsAdapter adapter;
CircleImageView mImageView;
CheckBox mCheckBox;
int position;
TextView mName,
mEmail;
public FriendsHolder(View itemView, FriendsAdapter adapter) {
super(itemView);
this.adapter = adapter;
mImageView = (CircleImageView) itemView.findViewById(R.id.friend_pic);
mName = (TextView) itemView.findViewById(R.id.friend_name);
mEmail = (TextView) itemView.findViewById(R.id.friend_email);
mCheckBox = (CheckBox) itemView.findViewById(R.id.check_friend);
}
public FriendsHolder setPosition(int position) {
this.position = position;
return this;
}
public void setItem(ContactsFriends item) {
this.item = item;
}
}
}
| 32.881356 | 112 | 0.662113 |
fb1d9f45c0448721388b2a796d54b5a73b19f6e5 | 4,079 | /*
* 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.geode.internal.cache.partitioned.rebalance;
import java.util.List;
import org.apache.logging.log4j.Logger;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.cache.FixedPartitionAttributesImpl;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.internal.cache.partitioned.rebalance.PartitionedRegionLoadModel.Bucket;
import org.apache.geode.internal.cache.partitioned.rebalance.PartitionedRegionLoadModel.Member;
import org.apache.geode.internal.cache.partitioned.rebalance.PartitionedRegionLoadModel.Move;
import org.apache.geode.internal.logging.LogService;
/**
* A director to move primaries to improve the load balance of a fixed partition region. This is
* most commonly used as an FPRDirector
*
*/
public class MovePrimariesFPR extends RebalanceDirectorAdapter {
private static final Logger logger = LogService.getLogger();
private PartitionedRegionLoadModel model;
@Override
public void initialize(PartitionedRegionLoadModel model) {
this.model = model;
}
@Override
public void membershipChanged(PartitionedRegionLoadModel model) {
initialize(model);
}
@Override
public boolean nextStep() {
makeFPRPrimaryForThisNode();
return false;
}
/**
* Move all primary from other to this
*/
private void makeFPRPrimaryForThisNode() {
PartitionedRegion partitionedRegion = model.getPartitionedRegion();
List<FixedPartitionAttributesImpl> FPAs = partitionedRegion.getFixedPartitionAttributesImpl();
InternalDistributedMember targetId = partitionedRegion.getDistributionManager().getId();
Member target = model.getMember(targetId);
for (Bucket bucket : model.getBuckets()) {
if (bucket != null) {
for (FixedPartitionAttributesImpl fpa : FPAs) {
if (fpa.hasBucket(bucket.getId()) && fpa.isPrimary()) {
Member source = bucket.getPrimary();
if (source != target) {
// HACK: In case we don't know who is Primary at this time
// we just set source as target too for stat purposes
source = (source == null || source == model.INVALID_MEMBER) ? target : source;
if (logger.isDebugEnabled()) {
logger.debug(
"PRLM#movePrimariesForFPR: For Bucket#{}, moving primary from source {} to target {}",
bucket.getId(), bucket.getPrimary(), target);
}
boolean successfulMove = model.movePrimary(new Move(source, target, bucket));
// We have to move the primary otherwise there is some problem!
Assert.assertTrue(successfulMove,
" Fixed partitioned region not able to move the primary!");
if (successfulMove) {
if (logger.isDebugEnabled()) {
logger.debug(
"PRLM#movePrimariesForFPR: For Bucket#{}, moved primary from source {} to target {}",
bucket.getId(), bucket.getPrimary(), target);
}
bucket.setPrimary(target, bucket.getPrimaryLoad());
}
}
}
}
}
}
}
}
| 39.990196 | 107 | 0.69012 |
eebb175c7c46d178921da5bb26e42c4dacad718f | 380 | package com.github.neuralnetworks.training.events;
import com.github.neuralnetworks.calculation.NetworkCalculator;
import com.github.neuralnetworks.events.TrainingEvent;
public class PhaseFinishedEvent extends TrainingEvent
{
private static final long serialVersionUID = -5239379347414855784L;
public PhaseFinishedEvent(NetworkCalculator<?> source)
{
super(source);
}
}
| 23.75 | 68 | 0.826316 |
4b8e8ecd14a45c026e68794d72f07db8bf3216cd | 687 | package com.rabbit.services;
import java.io.UnsupportedEncodingException;
import org.apache.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import com.alibaba.fastjson.JSON;
import com.rabbit.dto.Person;
public class QueueTwoLitener implements MessageListener{
Logger log=Logger.getLogger(QueueTwoLitener.class.getName());
public void onMessage(Message message) {
String json;
try {
json = new String(message.getBody(),"UTF-8");
Person parse=JSON.parseObject(json, Person.class);
log.info("person :" +parse );
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
| 23.689655 | 62 | 0.751092 |
4c1852739b2507831e0cded7da27bb0fbe3bb5f7 | 2,433 | /*
* (C) Copyright 2013-2018 Nuxeo (http://nuxeo.com/) and others.
*
* 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.
*
* Contributors:
* dmetzler
*/
package org.nuxeo.ecm.multi.tenant;
import static org.apache.http.HttpStatus.SC_OK;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.nuxeo.ecm.core.test.annotations.Granularity;
import org.nuxeo.ecm.core.test.annotations.RepositoryConfig;
import org.nuxeo.ecm.restapi.test.BaseTest;
import org.nuxeo.ecm.restapi.test.RestServerFeature;
import org.nuxeo.jaxrs.test.CloseableClientResponse;
import org.nuxeo.runtime.test.runner.Deploy;
import org.nuxeo.runtime.test.runner.Features;
import org.nuxeo.runtime.test.runner.FeaturesRunner;
import com.fasterxml.jackson.databind.JsonNode;
/**
* @since 5.8
*/
@RunWith(FeaturesRunner.class)
@Features({ RestServerFeature.class })
@RepositoryConfig(cleanup = Granularity.METHOD, init = MultiTenantRepositoryInit.class)
@Deploy("org.nuxeo.ecm.multi.tenant")
@Deploy("org.nuxeo.ecm.platform.userworkspace.core")
@Deploy("org.nuxeo.ecm.core.cache")
@Deploy("org.nuxeo.ecm.default.config")
@Deploy("org.nuxeo.ecm.multi.tenant:multi-tenant-test-contrib.xml")
@Deploy("org.nuxeo.ecm.multi.tenant:multi-tenant-enabled-default-test-contrib.xml")
public class TestRestAPIWithMultiTenant extends BaseTest {
@Test
public void restAPICanAccessTenantSpecifyingDomainPart() throws IOException {
service = getServiceFor("user1", "user1");
try (CloseableClientResponse response = getResponse(RequestType.GET, "path/domain1/");
InputStream stream = response.getEntityInputStream()) {
assertEquals(SC_OK, response.getStatus());
JsonNode node = mapper.readTree(stream);
assertEquals("/domain1", node.get("path").asText());
}
}
}
| 36.863636 | 94 | 0.748459 |
87e0ce3a1ba97ea19e3957327215425a04ba8892 | 836 | package src.language_basics.operators.logical_operators;
public class LogicalOperators {
public static void main(String[] args) {
// create variables
int a = 3, b = 5, c = 8;
// && (logical AND) operator
System.out.println((b > a) && (c > b)); // true && true = true
System.out.println((b > a) && (c < b)); // true && false = false
// || (logical OR) operator
System.out.println((b < a) || (c > b)); // false || true = true
System.out.println((b > a) || (c < b)); // true || false = true
System.out.println((b < a) || (c < b)); // false || false = false
// ! (inverter) operator
System.out.println((a == b)); // false
System.out.println(!(a == b)); // !false = true
System.out.println(!(b > a)); // !true = false
}
}
| 32.153846 | 73 | 0.510766 |
478f23e915cef7aa9790da5bd78dd7b71d5fe9d1 | 7,826 | /*
* --------------------------------------------------------------------------------------------------------------------
* <copyright company="Aspose">
* Copyright (c) 2018 Aspose.Slides for Cloud
* </copyright>
* <summary>
* 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.
* </summary>
* --------------------------------------------------------------------------------------------------------------------
*/
package com.aspose.slides.model;
import java.util.Objects;
import com.aspose.slides.model.ResourceUri;
import com.aspose.slides.model.SmartArtNode;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
/**
* Smart art node.
*/
@ApiModel(description = "Smart art node.")
public class SmartArtNode {
@SerializedName(value = "nodes", alternate = { "Nodes" })
private List<SmartArtNode> nodes = null;
@SerializedName(value = "shapes", alternate = { "Shapes" })
private ResourceUri shapes;
@SerializedName(value = "isAssistant", alternate = { "IsAssistant" })
private Boolean isAssistant;
@SerializedName(value = "text", alternate = { "Text" })
private String text;
/**
* Organization chart layout type associated with current node.
*/
@JsonAdapter(OrgChartLayoutEnum.Adapter.class)
public enum OrgChartLayoutEnum {
INITIAL("Initial"),
STANDART("Standart"),
BOTHHANGING("BothHanging"),
LEFTHANGING("LeftHanging"),
RIGHTHANGING("RightHanging");
private String value;
OrgChartLayoutEnum(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return String.valueOf(value);
}
public static OrgChartLayoutEnum fromValue(String text) {
for (OrgChartLayoutEnum b : OrgChartLayoutEnum.values()) {
if (String.valueOf(b.value).equals(text)) {
return b;
}
}
return null;
}
public static class Adapter extends TypeAdapter<OrgChartLayoutEnum> {
@Override
public void write(final JsonWriter jsonWriter, final OrgChartLayoutEnum enumeration) throws IOException {
jsonWriter.value(enumeration.getValue());
}
@Override
public OrgChartLayoutEnum read(final JsonReader jsonReader) throws IOException {
String value = jsonReader.nextString();
return OrgChartLayoutEnum.fromValue(String.valueOf(value));
}
}
}
@SerializedName(value = "orgChartLayout", alternate = { "OrgChartLayout" })
private OrgChartLayoutEnum orgChartLayout;
public SmartArtNode() {
super();
}
public SmartArtNode nodes(List<SmartArtNode> nodes) {
this.nodes = nodes;
return this;
}
public SmartArtNode addNodesItem(SmartArtNode nodesItem) {
if (this.nodes == null) {
this.nodes = new ArrayList<SmartArtNode>();
}
this.nodes.add(nodesItem);
return this;
}
/**
* Node list.
* @return nodes
**/
@ApiModelProperty(value = "Node list.")
public List<SmartArtNode> getNodes() {
return nodes;
}
public void setNodes(List<SmartArtNode> nodes) {
this.nodes = nodes;
}
public SmartArtNode shapes(ResourceUri shapes) {
this.shapes = shapes;
return this;
}
/**
* Gets or sets the link to shapes.
* @return shapes
**/
@ApiModelProperty(value = "Gets or sets the link to shapes.")
public ResourceUri getShapes() {
return shapes;
}
public void setShapes(ResourceUri shapes) {
this.shapes = shapes;
}
public SmartArtNode isAssistant(Boolean isAssistant) {
this.isAssistant = isAssistant;
return this;
}
/**
* True for and assistant node.
* @return isAssistant
**/
@ApiModelProperty(required = true, value = "True for and assistant node.")
public Boolean isIsAssistant() {
return isAssistant;
}
public void setIsAssistant(Boolean isAssistant) {
this.isAssistant = isAssistant;
}
public SmartArtNode text(String text) {
this.text = text;
return this;
}
/**
* Node text.
* @return text
**/
@ApiModelProperty(value = "Node text.")
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public SmartArtNode orgChartLayout(OrgChartLayoutEnum orgChartLayout) {
this.orgChartLayout = orgChartLayout;
return this;
}
/**
* Organization chart layout type associated with current node.
* @return orgChartLayout
**/
@ApiModelProperty(required = true, value = "Organization chart layout type associated with current node.")
public OrgChartLayoutEnum getOrgChartLayout() {
return orgChartLayout;
}
public void setOrgChartLayout(OrgChartLayoutEnum orgChartLayout) {
this.orgChartLayout = orgChartLayout;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SmartArtNode smartArtNode = (SmartArtNode) o;
return true && Objects.equals(this.nodes, smartArtNode.nodes) && Objects.equals(this.shapes, smartArtNode.shapes) && Objects.equals(this.isAssistant, smartArtNode.isAssistant) && Objects.equals(this.text, smartArtNode.text) && Objects.equals(this.orgChartLayout, smartArtNode.orgChartLayout);
}
@Override
public int hashCode() {
return Objects.hash(nodes, shapes, isAssistant, text, orgChartLayout);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SmartArtNode {\n");
sb.append(" nodes: ").append(toIndentedString(nodes)).append("\n");
sb.append(" shapes: ").append(toIndentedString(shapes)).append("\n");
sb.append(" isAssistant: ").append(toIndentedString(isAssistant)).append("\n");
sb.append(" text: ").append(toIndentedString(text)).append("\n");
sb.append(" orgChartLayout: ").append(toIndentedString(orgChartLayout)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
private static final Map<String, Object> typeDeterminers = new Hashtable<String, Object>();
}
| 28.772059 | 296 | 0.668285 |
34ce76378a11864c24cb3299f18382671c216e01 | 803 | //,temp,AMQ6059Test.java,171,179,temp,XACompletionTest.java,1131,1144
//,3
public class xxx {
protected void sendMessagesWithTo(ConnectionFactory factory, int messagesExpected, Destination destination) throws Exception {
javax.jms.Connection connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
for (int i = 0; i < messagesExpected; i++) {
LOG.debug("Sending message " + (i + 1) + " of " + messagesExpected);
producer.send(session.createTextMessage("test message " + (i + 1)));
}
connection.close();
}
}; | 42.263158 | 130 | 0.67995 |
ccb87f37cbd95862caa84710a261f1b5e946c1bd | 3,214 | /*
* Copyright © 02.10.2015 by O.I.Mudannayake. All Rights Reserved.
*/
package history;
import salesreturn.NewSRNController;
import database.sql.type.SalesReturnSQL;
import java.awt.event.ActionEvent;
import javax.swing.table.DefaultTableModel;
import controller.Controller;
import ui.support.Frame;
import controller.ControllerFactory;
import controller.Interface;
import database.sql.SQLStatement;
import database.sql.SQLFactory;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import ui.support.Info;
/**
*
* @author Ivantha
*/
public class SRNHistoryController implements Controller{
private final SRNHistory view = new SRNHistory();
private final SalesReturnSQL salesReturnSQL = (SalesReturnSQL) SQLFactory.getSQLStatement(SQLStatement.SALES_RETURN);
private String srnNoSearchPhrase = "";
private String invoiceNoSearchPhrase = "";
private String employeeIDSearchPhrase = "";
private String greaterThanSearchPhrase = "";
private String lessThanSearchPhrase = "";
public SRNHistoryController() {
//Update view
view.updateViewInternalFrameListener(new InternalFrameAdapter() {
@Override
public void internalFrameActivated(InternalFrameEvent e) {
SRNHistoryController.this.updateView();
}
});
//New button
view.addNewButtonActionListener((ActionEvent e) -> {
NewSRNController newSRNController = (NewSRNController) ControllerFactory.getController(Interface.NEW_SRN);
newSRNController.showView();
});
//Edit button
view.addEditButtonActionListener((ActionEvent e) -> {
Info.error("Invalid function", "This feature is not yet implemented");
});
//Remove button
view.addRemoveButtonActionListener((ActionEvent e) -> {
Info.error("Invalid function", "This feature is not yet implemented");
});
//Search
view.addSearchKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
srnNoSearchPhrase = view.srnNoTextField.getText().trim();
invoiceNoSearchPhrase = view.invoiceNoTextField.getText().trim();
employeeIDSearchPhrase = view.employeeTextField.getText().trim();
greaterThanSearchPhrase = view.greaterThanTextField.getText().trim();
lessThanSearchPhrase = view.lessThanTextField.getText().trim();
SRNHistoryController.this.updateView();
}
});
view.addSearchActionlistener((ActionEvent e) -> {
SRNHistoryController.this.updateView();
});
}
@Override
public void showView(){
this.updateView();
Frame.showInternalFrame(view);
}
@Override
public void updateView(){
DefaultTableModel dtm = (DefaultTableModel) view.srnTable.getModel();
dtm.setRowCount(0);
salesReturnSQL.showSRN(dtm);
}
@Override
public void clearView() {}
}
| 34.191489 | 121 | 0.662103 |
03f42d6bb71ac5e9d5e6a0ebb49fd3a075add26d | 115 | /*
* This is a header...
*/
package com.devonfw.ide.sonarqube.batch.api;
class ClassDao extends ClassTwoDao {
} | 14.375 | 44 | 0.704348 |
e7d1302e738f6005e9629c254936ac7b914baa5c | 916 | /*
*
* * Copyright 2020 New Relic Corporation. All rights reserved.
* * SPDX-License-Identifier: Apache-2.0
*
*/
package com.newrelic.agent.service.module;
import com.newrelic.agent.AgentConnectionEstablishedListener;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
public class JarCollectorConnectionListener implements AgentConnectionEstablishedListener {
private final String defaultAppName;
private final AtomicBoolean shouldSendAllJars;
public JarCollectorConnectionListener(String defaultAppName, AtomicBoolean shouldSendAllJars) {
this.defaultAppName = defaultAppName;
this.shouldSendAllJars = shouldSendAllJars;
}
@Override
public void onEstablished(String appName, String agentRunToken, Map<String, String> requestMetadata) {
if (appName.equals(defaultAppName)) {
shouldSendAllJars.set(true);
}
}
}
| 30.533333 | 106 | 0.754367 |
c2f5f753b6456ee51a30819162d074423eb1b60e | 4,993 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.specmodels.processor;
import com.facebook.litho.specmodels.internal.ImmutableList;
import com.facebook.litho.specmodels.model.InjectPropModel;
import com.facebook.litho.specmodels.model.PropModel;
import com.facebook.litho.specmodels.model.SpecModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.annotation.processing.Filer;
import javax.lang.model.element.Name;
import javax.tools.FileObject;
import javax.tools.JavaFileManager;
import javax.tools.StandardLocation;
/**
* This store retains prop names across multi-module annotation processor runs. This is needed as
* prop names are derived from method parameters which aren't persisted in the Java 7 bytecode and
* thus cannot be inferred if compilation occurs across modules.
*
* <p>The props names are serialized and stored as resources within the output JAR, where they can
* be read from again at a later point in time.
*/
public class PropNameInterStageStore {
private final Filer mFiler;
private static final String BASE_PATH = "_STRIPPED_RESOURCES/litho/";
private static final String FILE_EXT = ".props";
public PropNameInterStageStore(Filer filer) {
this.mFiler = filer;
}
/**
* @return List of names in order of definition. List may be empty if there are no custom props
* defined. Value may not be present if loading for the given spec model failed, i.e. we don't
* have inter-stage resources on the class path to facilitate the lookup.
*/
public Optional<ImmutableList<String>> loadNames(Name qualifiedName) {
final Optional<FileObject> resource =
getResource(mFiler, StandardLocation.CLASS_PATH, "", BASE_PATH + qualifiedName + FILE_EXT);
return resource.map(
r -> {
final List<String> props = new ArrayList<>();
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(r.openInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
props.add(line);
}
} catch (final IOException err) {
// This can only happen due to buggy build systems.
throw new RuntimeException(err);
}
return ImmutableList.copyOf(props);
});
}
/** Saves the prop names of the given spec model at a well-known path within the resources. */
public void saveNames(SpecModel specModel) throws IOException {
// This is quite important, because we must not open resources without writing to them
// due to a bug in the Buck caching layer.
if (specModel.getRawProps().isEmpty()) {
return;
}
final FileObject outputFile =
mFiler.createResource(
StandardLocation.CLASS_OUTPUT, "", BASE_PATH + specModel.getSpecTypeName() + FILE_EXT);
try (Writer writer =
new BufferedWriter(new OutputStreamWriter(outputFile.openOutputStream()))) {
for (final PropModel propModel : specModel.getRawProps()) {
writer.write(propModel.getName() + "\n");
}
for (final InjectPropModel propModel : specModel.getRawInjectProps()) {
writer.write(propModel.getName() + "\n");
}
}
}
/**
* Helper method for obtaining resources from a {@link Filer}, taking care of some javac
* peculiarities.
*/
private static Optional<FileObject> getResource(
final Filer filer,
final JavaFileManager.Location location,
final String packageName,
final String filePath) {
try {
final FileObject resource = filer.getResource(location, packageName, filePath);
resource.openInputStream().close();
return Optional.of(resource);
} catch (final Exception e) {
// ClientCodeException can be thrown by a bug in the javac ClientCodeWrapper
if (!(e instanceof FileNotFoundException
|| e.getClass().getName().equals("com.sun.tools.javac.util.ClientCodeException"))) {
throw new RuntimeException(
String.format("Error opening resource %s/%s", packageName, filePath), e.getCause());
}
return Optional.empty();
}
}
}
| 37.825758 | 100 | 0.703585 |
2f43b34c1843cee7b8e2ed070eb8d84a90155dea | 87 | /**
* JPA domain objects.
*/
package com.diviso.graeshoppe.shopkeepergateway.domain;
| 17.4 | 55 | 0.747126 |
e7eada952168dbeb98e697f12d7e557ff571dab2 | 12,254 | /**
* CARIS oscar - Open Spatial Component ARchitecture
*
* Copyright 2016 CARIS <http://www.caris.com>
*
* 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.caris.oscarexchange4j.theme;
import java.awt.Color;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.caris.oscarexchange4j.theme.exceptions.ValidationException;
import com.caris.oscarexchange4j.theme.services.Services;
import com.caris.oscarexchange4j.util.OXUtil;
/**
* This class represents an Oscar Theme
*
* @author tcoburn
*
*/
public class Theme {
/**
* The theme version.
*/
final double version = 1.0;
/**
* Number of zoom levels allowed.
*/
public static final String PARAM_ZOOMLEVELS = "numzoomlevels";
/**
* The id.
*/
int id;
/**
* Theme parameters.
*/
private Map<String, String> parameters = new HashMap<String, String>();
/**
* Theme name.
*/
String name;
/**
* Theme covers.
*/
Set<Cover> covers;
/**
* The position object.
*/
private Position position;
/**
* The layers that a theme contains.
*/
List<ThemeLayer> layers;
/**
* Path pointing to legend graphic.
*/
private String legend;
Services services;
/**
* Represents the position it should take when dealing with a group of
* themes.
*/
int displayOrder;
/**
* Coordinate system.
*/
String srs;
/**
* Background colour.
*/
String backgroundColor;
/**
* selection style options
*/
SelectionStyle selectionStyle;
/**
* Get the background colour.
*
* @return String The background color
*/
public String getBackgroundColor() {
return this.backgroundColor;
}
/**
* Set the background colour.
*
* @param backgroundColor
* the backgroundColor to set
*/
public void setBackgroundColor(String backgroundColor) {
this.backgroundColor = backgroundColor;
}
/**
* Set the background colour.
*
* @param red
* The red value (0-255)
* @param green
* The green value (0-255).
* @param blue
* The blue value (0-255).
*/
public void setBackgroundColor(int red, int green, int blue) {
this.setBackgroundColor(OXUtil.RGBToHex(red, green, blue));
}
/**
* Set the background colour.
*
* @param color
* The background colour.
*/
public void setBackgroundColor(Color color) {
this.setBackgroundColor(OXUtil.ColorToHex(color));
}
/**
* Set the selection style.
*
* @param selectionStyle
* The selection style for this theme.
*/
public void setSelectionStyle(SelectionStyle selectionStyle) {
this.selectionStyle = selectionStyle;
}
/**
* Get the selection style.
*
* @return The selection style for this theme.
*/
public SelectionStyle getSelectionStyle() {
return selectionStyle;
}
/**
* Get the display order.
*
* @return The position of where it should be displayed.
*/
public int getDisplayOrder() {
return displayOrder;
}
/**
* Set the display order.
*
* @param displayOrder
* The position of where it should be displayed.
*/
public void setDisplayOrder(int displayOrder) {
this.displayOrder = displayOrder;
}
/**
* Get the list of layers for this theme.
*
* @return The list of layers associated to the theme.
*/
public List<ThemeLayer> getLayers() {
return layers;
}
/**
* Set the list of layers for this theme.
*
* @param layers
* Set the layers to the theme.
*/
public void setLayers(List<ThemeLayer> layers) {
for (ThemeLayer layer : layers)
this.addLayer(layer);
}
/**
* Add a layer to this theme.
*
* @param layer
* Add a single layer to the current theme.
*/
public void addLayer(ThemeLayer layer) {
if (this.layers == null)
this.layers = new ArrayList<ThemeLayer>();
try {
if (layer.validate())
this.layers.add(layer);
} catch (ValidationException e) {
e.printStackTrace();
}
}
/**
* Get the services used by this theme.
*
* @return The services in this theme.
*/
public Services getServices() {
return services;
}
/**
* Set the services for this theme.
*
* @param services
* The services to be used by the theme.
*/
public void setServices(Services services) {
this.services = services;
}
/**
* Get the theme identifier.
*
* @return The theme identifier.
*/
public int getId() {
return this.id;
}
/**
* Get the covers for this theme.
*
* @return A set of covers for the theme.
*/
public Set<Cover> getCovers() {
return this.covers;
}
/**
* Get the theme name.
*
* @return The theme name.
*/
public String getName() {
return this.name;
}
/**
* Set the theme id.
*
* @param id
* The theme id.
*/
public void setId(int id) {
this.id = id;
}
/**
* Set the theme name.
*
* @param name
* The theme name.
*/
public void setName(String name) {
this.name = name;
}
/**
* Set the theme covers.
*
* @param covers
* A set of theme covers.
*/
public void setCovers(Set<Cover> covers) {
this.covers = covers;
}
/**
* Get the theme version.
*
* @return The theme version.
*/
public double getVersion() {
return this.version;
}
/**
* Get the theme parameters.
*
* @return The theme parameters.
*/
public Map<String, String> getParameters() {
return parameters;
}
/**
* Set the theme parameters.
*
* @param parameters
* The theme parameters.
*/
public void setParameters(Map<String, String> parameters) {
this.parameters = parameters;
}
/**
* Add a value to the theme's parameter table.
*
* @param key
* The key for the value that is used for lookup.
* @param value
* The value to store associated to the key.
*/
public void addParameter(String key, String value) {
this.parameters.put(key, value);
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((backgroundColor == null) ? 0 : backgroundColor.hashCode());
result = prime * result + ((covers == null) ? 0 : covers.hashCode());
result = prime * result + displayOrder;
result = prime * result + id;
result = prime * result + ((layers == null) ? 0 : layers.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result
+ ((parameters == null) ? 0 : parameters.hashCode());
result = prime * result
+ ((selectionStyle == null) ? 0 : selectionStyle.hashCode());
result = prime * result
+ ((services == null) ? 0 : services.hashCode());
result = prime * result + ((srs == null) ? 0 : srs.hashCode());
long temp;
temp = Double.doubleToLongBits(version);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Theme))
return false;
Theme other = (Theme) obj;
if (backgroundColor == null) {
if (other.backgroundColor != null)
return false;
} else if (!backgroundColor.equals(other.backgroundColor))
return false;
if (covers == null) {
if (other.covers != null)
return false;
} else if (!covers.equals(other.covers))
return false;
if (displayOrder != other.displayOrder)
return false;
if (id != other.id)
return false;
if (layers == null) {
if (other.layers != null)
return false;
} else if (!layers.equals(other.layers))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (parameters == null) {
if (other.parameters != null)
return false;
} else if (!parameters.equals(other.parameters))
return false;
if (selectionStyle == null) {
if (other.selectionStyle != null)
return false;
} else if (!selectionStyle.equals(other.selectionStyle))
return false;
if (services == null) {
if (other.services != null)
return false;
} else if (!services.equals(other.services))
return false;
if (srs == null) {
if (other.srs != null)
return false;
} else if (!srs.equals(other.srs))
return false;
if (Double.doubleToLongBits(version) != Double
.doubleToLongBits(other.version))
return false;
return true;
}
/**
* Get the spatial reference system key.
*
* @return The spatial reference system key.
*/
public String getSRS() {
return this.srs;
}
/**
* Set the spatial reference system key.
*
* @param srs
* The spatial reference system key.
*/
public void setSRS(String srs) {
this.srs = srs;
}
/**
* Returns the position object.
*
* @return the position
*/
public Position getPosition() {
return position;
}
/**
* Sets the position object.
*
* @param position
* the position to set
*/
public void setPosition(Position position) {
this.position = position;
}
/**
* Return the path to the legend.
*
* @return The path to the legend
*/
public String getLegend() {
return legend;
}
/**
* Set the path to the legend.
*
* @param legend
* The path to the legend.
*/
public void setLegend(String legend) {
this.legend = legend;
}
} | 24.95723 | 80 | 0.517219 |
4d05589738a16f57e203c8c91af9dbdfbd8c5ed6 | 1,166 | package com.ruoyi.company.service;
import java.util.List;
import com.ruoyi.company.domain.Company_JmrJob;
/**
* 企业岗位管理3.0Service接口
*
* @author ruoyi
* @date 2020-09-28
*/
public interface Company_IJmrJobService
{
/**
* 查询企业岗位管理3.0
*
* @param jId 企业岗位管理3.0ID
* @return 企业岗位管理3.0
*/
public Company_JmrJob selectJmrJobById(Integer jId);
/**
* 查询企业岗位管理3.0列表
*
* @param companyJmrJob 企业岗位管理3.0
* @return 企业岗位管理3.0集合
*/
public List<Company_JmrJob> selectJmrJobList(Company_JmrJob companyJmrJob);
/**
* 新增企业岗位管理3.0
*
* @param companyJmrJob 企业岗位管理3.0
* @return 结果
*/
public int insertJmrJob(Company_JmrJob companyJmrJob);
/**
* 修改企业岗位管理3.0
*
* @param companyJmrJob 企业岗位管理3.0
* @return 结果
*/
public int updateJmrJob(Company_JmrJob companyJmrJob);
/**
* 批量删除企业岗位管理3.0
*
* @param ids 需要删除的数据ID
* @return 结果
*/
public int deleteJmrJobByIds(String ids);
/**
* 删除企业岗位管理3.0信息
*
* @param jId 企业岗位管理3.0ID
* @return 结果
*/
public int deleteJmrJobById(Integer jId);
}
| 18.507937 | 79 | 0.602916 |
3fa0488500e5d57edbbf6c30f9f0e3b8cc26768a | 1,222 | package demo;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import codeanalyzer.*;
/**
*
* @author dimitrakallini
*
*/
public class DemoClient {
/**
*
* @param filepath The source code file path
* @param sourceCodeAnalyzerType The analyzer type (regex or strcomp)
* @param sourceFileLocation The location of the file (local or web)
* @param outputFilePath The file path for the output file
* @param outputFileType The output file type (csv or json)
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String filepath = "src/main/resources/TestClass.java";
String sourceCodeAnalyzerType = "regex";
String sourceFileLocation = "local";
String outputFilePath = "output_metrics";
String outputFileType = "csv";
if(args.length == 5) {
filepath = args[0];
sourceCodeAnalyzerType = args[1];
sourceFileLocation = args[2];
outputFilePath = args[3];
outputFileType = args[4];
} else if (args.length != 0) {
System.out.println("Incorrect number of arguments.");
System.exit(1);
}
Metrics.calculateMetrics(filepath, sourceCodeAnalyzerType, sourceFileLocation, outputFilePath, outputFileType);
}
}
| 26 | 113 | 0.715221 |
f7a81cf4d745517afc9f3548b339fd07df5f24c4 | 2,207 | // Generated from /Users/andrew/Documents/Languague structures/cos382LanguageStructs/Basketball/Basketball.g4 by ANTLR 4.6
import org.antlr.v4.runtime.tree.ParseTreeVisitor;
/**
* This interface defines a complete generic visitor for a parse tree produced
* by {@link BasketballParser}.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public interface BasketballVisitor<T> extends ParseTreeVisitor<T> {
/**
* Visit a parse tree produced by {@link BasketballParser#start}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitStart(BasketballParser.StartContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#shot}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitShot(BasketballParser.ShotContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#rebound}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitRebound(BasketballParser.ReboundContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#assist}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitAssist(BasketballParser.AssistContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#assistAtt}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitAssistAtt(BasketballParser.AssistAttContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#player}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitPlayer(BasketballParser.PlayerContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#turnover}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitTurnover(BasketballParser.TurnoverContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#foul}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitFoul(BasketballParser.FoulContext ctx);
/**
* Visit a parse tree produced by {@link BasketballParser#freethrow}.
* @param ctx the parse tree
* @return the visitor result
*/
T visitFreethrow(BasketballParser.FreethrowContext ctx);
} | 33.439394 | 122 | 0.730856 |
06765fb20f5a01862a654316cff5efb099c263df | 1,986 | /*
* Copyright © 2009 HotPads (admin@hotpads.com)
*
* 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.datarouter.util.bytes;
import java.util.List;
import java.util.stream.Collectors;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.datarouter.scanner.Scanner;
import io.datarouter.util.Java9;
public class FloatByteToolTests{
@Test
public void testComparableBytes(){
List<Float> interestingFloats = Scanner.of(
Float.NEGATIVE_INFINITY,
-Float.MAX_VALUE,
-Float.MIN_NORMAL,
-Float.MIN_VALUE,
-0F,
+0F,
Float.MIN_VALUE,
Float.MIN_NORMAL,
Float.MAX_VALUE,
Float.POSITIVE_INFINITY,
Float.NaN)
.sort()
.list();
List<Float> roundTripped = interestingFloats.stream()
.map(FloatByteTool::toComparableBytes)
.sorted(Java9::compareUnsigned)
.map(bytes -> FloatByteTool.fromComparableBytes(bytes, 0))
.collect(Collectors.toList());
Assert.assertEquals(roundTripped, interestingFloats);
}
@Test
public void testBytes1(){
float floatA = 123.456f;
byte[] bytesA = FloatByteTool.getBytes(floatA);
float backA = FloatByteTool.fromBytes(bytesA, 0);
Assert.assertTrue(floatA == backA);
float floatB = -123.456f;
byte[] bytesB = FloatByteTool.getBytes(floatB);
float backB = FloatByteTool.fromBytes(bytesB, 0);
Assert.assertTrue(floatB == backB);
Assert.assertTrue(Java9.compareUnsigned(bytesA, bytesB) < 0); //positives and negatives are reversed
}
}
| 28.782609 | 102 | 0.730111 |
70ed657b1e12bce27154ec1888f70de58fa56d0c | 2,881 | import javax.swing.*;
import java.util.*;
public class Skyline extends JFrame
{
// Eclipse wanted this
private static final long serialVersionUID = 1L;
// Stores what time is considered dawn
private Date zeroTime;
// Where we draw everything
private TerminaCanvas canvas;
// Number of milliseconds since zeroTime
private long time;
// System time at the last update of the canvas
private long timeOfLastUpdate;
public static void main( String[] args )
{
// creates the window
Skyline frame = new Skyline( "Majora" );
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
// put the canvas in the window
frame.addComponentsToFrame();
// make the frame respect the canvas' size
frame.pack();
frame.setResizable( false );
frame.setVisible( true );
// tell the canvas its being displayed so that it can create the off-screen buffer
frame.canvas.setIsDisplayed( true );
int iHour, ai[];
while ( true )
{
// set the time
frame.time = (int) ( System.currentTimeMillis() - frame.zeroTime.getTime() );
// synchronize the canvas' time with our time
frame.canvas.setTime( frame.time );
// calculate what hour of the day the Skyline will reflect
iHour = (int) ( ( ( frame.time / 1000 ) / 60 ) + 6 ) % 24;
// paint every quarter (or twentieth) of a second
if ( System.currentTimeMillis() - frame.timeOfLastUpdate > 50 )
{
// now is when the last update happened for next time
frame.timeOfLastUpdate = System.currentTimeMillis();
// determine whether to turn windows on or off, depending on whether it's day or night
boolean lit = !( ( ( ( iHour - 6 ) % 24 ) + 24 ) % 24 < 12 );
//System.out.print( iHour + "\t" );
// use iHour again to for determining window behavior
iHour = ( ( ( ( iHour - 6 ) % 12 ) + 12 ) % 12 ) + 6;
//System.out.println( iHour + "\t" );
// turn some windows on or off - lots on during night, off during day, none at sunset/rise
for ( int i = 0; i < 5 * ( 6 - Math.abs( 12 - iHour ) ); i++ )
{
ai = TerminaCanvas.getRandomWindowCoordinate();
frame.canvas.setWindow(ai[0], ai[1], ai[2], lit);
}
// toggle some windows during dusk
for ( int i = 0; i < 5 * Math.abs( 12 - iHour ); i++ )
{
ai = TerminaCanvas.getRandomWindowCoordinate();
frame.canvas.setWindow( ai[0], ai[1], ai[2], !frame.canvas.getWindow( ai[0], ai[1], ai[2] ) );
}
// repaint the canvas
frame.canvas.repaint();
}
}
}
public Skyline( String name )
{
// call the superclass' constructor with the window name
super( name );
// create a new canvas to draw on
canvas = new TerminaCanvas();
// set the zeroTime as now - a Date object holds the time it was initialized
zeroTime = new Date();
time = 0;
timeOfLastUpdate = zeroTime.getTime();
}
private void addComponentsToFrame()
{
this.add( canvas );
}
}
| 27.438095 | 99 | 0.649774 |
3020d24d39e7dca57e5e86fd4b8c56aed20b2d07 | 6,156 | package org.sagebionetworks.bridge.exporter.scheduler;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
import com.amazonaws.services.dynamodbv2.document.Item;
import com.amazonaws.services.dynamodbv2.document.Table;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.mockito.ArgumentCaptor;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class BridgeExporterSchedulerTest {
private static final ObjectMapper JSON_OBJECT_MAPPER = new ObjectMapper();
private static final String TEST_SCHEDULER_NAME = "test-scheduler";
private static final String TEST_SQS_QUEUE_URL = "test-sqs-queue";
private static final String TEST_TIME_ZONE = "Asia/Tokyo";
private AmazonSQSClient mockSqsClient;
private BridgeExporterScheduler scheduler;
private Item schedulerConfig;
@BeforeMethod
public void before() {
// mock now
DateTime mockNow = DateTime.parse("2016-02-01T16:47:55.273+0900");
DateTimeUtils.setCurrentMillisFixed(mockNow.getMillis());
// mock DDB
Table mockConfigTable = mock(Table.class);
schedulerConfig = new Item().withString("sqsQueueUrl", TEST_SQS_QUEUE_URL)
.withString("timeZone", TEST_TIME_ZONE);
when(mockConfigTable.getItem("schedulerName", TEST_SCHEDULER_NAME)).thenReturn(schedulerConfig);
// mock SQS
mockSqsClient = mock(AmazonSQSClient.class);
// set up scheduler
scheduler = new BridgeExporterScheduler();
scheduler.setDdbExporterConfigTable(mockConfigTable);
scheduler.setSqsClient(mockSqsClient);
}
@AfterMethod
public void after() {
// reset now
DateTimeUtils.setCurrentMillisSystem();
}
@Test
public void defaultScheduleType() throws Exception {
// No scheduleType in DDB config. No setup needed. Just call test helper directly.
dailyScheduleHelper();
}
@Test
public void dailyScheduleType() throws Exception {
schedulerConfig.withString("scheduleType", "DAILY");
dailyScheduleHelper();
}
@Test
public void invalidScheduleType() throws Exception {
// falls back to DAILY
schedulerConfig.withString("scheduleType", "INVALID_TYPE");
dailyScheduleHelper();
}
// Helper method for all daily schedule test cases.
private void dailyScheduleHelper() throws Exception {
// execute
scheduler.schedule(TEST_SCHEDULER_NAME);
// validate
ArgumentCaptor<String> sqsMessageCaptor = ArgumentCaptor.forClass(String.class);
verify(mockSqsClient).sendMessage(eq(TEST_SQS_QUEUE_URL), sqsMessageCaptor.capture());
String sqsMessage = sqsMessageCaptor.getValue();
JsonNode sqsMessageNode = JSON_OBJECT_MAPPER.readTree(sqsMessage);
assertEquals(sqsMessageNode.size(), 3);
String endDateTimeStr = sqsMessageNode.get("endDateTime").textValue();
assertEquals(DateTime.parse(endDateTimeStr), DateTime.parse("2016-02-01T00:00:00.000+0900"));
assertTrue(sqsMessageNode.get("useLastExportTime").booleanValue());
assertEquals(sqsMessageNode.get("tag").textValue(), "[scheduler=" + TEST_SCHEDULER_NAME + ";date=2016-01-31]");
}
@Test
public void hourlyScheduleType() throws Exception {
// Add hourly schedule type param. For realism, also add study whitelist.
schedulerConfig.withString("scheduleType", "HOURLY").withString("requestOverrideJson",
"{\"studyWhitelist\":[\"hourly-study\"]}");
// execute
scheduler.schedule(TEST_SCHEDULER_NAME);
// validate
ArgumentCaptor<String> sqsMessageCaptor = ArgumentCaptor.forClass(String.class);
verify(mockSqsClient).sendMessage(eq(TEST_SQS_QUEUE_URL), sqsMessageCaptor.capture());
String sqsMessage = sqsMessageCaptor.getValue();
JsonNode sqsMessageNode = JSON_OBJECT_MAPPER.readTree(sqsMessage);
assertEquals(sqsMessageNode.size(), 4);
String endDateTimeStr = sqsMessageNode.get("endDateTime").textValue();
assertEquals(DateTime.parse(endDateTimeStr), DateTime.parse("2016-02-01T16:00:00.000+0900"));
JsonNode studyWhitelistNode = sqsMessageNode.get("studyWhitelist");
assertEquals(studyWhitelistNode.size(), 1);
assertEquals(studyWhitelistNode.get(0).textValue(), "hourly-study");
assertTrue(sqsMessageNode.get("useLastExportTime").booleanValue());
assertEquals(sqsMessageNode.get("tag").textValue(), "[scheduler=" + TEST_SCHEDULER_NAME + ";endDateTime=" +
endDateTimeStr + "]");
}
@Test
public void withRequestOverride() throws Exception {
// add request override
schedulerConfig.withString("requestOverrideJson", "{\"foo\":\"bar\"}");
// execute
scheduler.schedule(TEST_SCHEDULER_NAME);
// validate
ArgumentCaptor<String> sqsMessageCaptor = ArgumentCaptor.forClass(String.class);
verify(mockSqsClient).sendMessage(eq(TEST_SQS_QUEUE_URL), sqsMessageCaptor.capture());
String sqsMessage = sqsMessageCaptor.getValue();
JsonNode sqsMessageNode = JSON_OBJECT_MAPPER.readTree(sqsMessage);
assertEquals(sqsMessageNode.size(), 4);
String endDateTimeStr = sqsMessageNode.get("endDateTime").textValue();
assertEquals(DateTime.parse(endDateTimeStr), DateTime.parse("2016-02-01T00:00:00.000+0900"));
assertTrue(sqsMessageNode.get("useLastExportTime").booleanValue());
assertEquals(sqsMessageNode.get("tag").textValue(), "[scheduler=" + TEST_SCHEDULER_NAME + ";date=2016-01-31]");
assertEquals(sqsMessageNode.get("foo").textValue(), "bar");
}
}
| 40.768212 | 119 | 0.710526 |
1172e7045ec4fb07436787b9c087a8ba2cfabc6c | 481 | package com.example.eureka.ribbon.client.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RibbonService {
@Autowired
private RestTemplate restTemplate;
public String hello(String name) {
String url = "http://eureka-client/hello?name=" + name;
return restTemplate.getForObject(url, String.class);
}
}
| 25.315789 | 63 | 0.754678 |
add44f16706764fd46018747de3ac574e9146d2f | 494 | package com.bumptech.glide.p103f.p104a;
import android.graphics.Bitmap;
import android.widget.ImageView;
/* renamed from: com.bumptech.glide.f.a.b */
/* compiled from: BitmapImageViewTarget */
public class C5969b extends C5971d<Bitmap> {
public C5969b(ImageView view) {
super(view);
}
/* access modifiers changed from: protected */
/* renamed from: a */
public void mo18696a(Bitmap resource) {
((ImageView) this.f10538c).setImageBitmap(resource);
}
}
| 26 | 60 | 0.692308 |
5627ae9c5dfe8e1e7ab5c6e822671d997e2db1b1 | 589 | package org.dayatang.utils;
/**
* 通用日志接口
* @author yyang (<a href="mailto:gdyangyu@gmail.com">gdyangyu@gmail.com</a>)
*
*/
public interface Logger {
void debug(String msg, Object... args);
void debug(String msg, Throwable t);
void info(String msg, Object... args);
void info(String msg, Throwable t);
void trace(String format, Object... args);
void trace(String msg, Throwable t);
void warn(String format, Object... args);
void warn(String msg, Throwable t);
void error(String format, Object... args);
void error(String msg, Throwable t);
}
| 18.40625 | 77 | 0.662139 |
1c25f2e97c92d00b932eb0e2bf98cd61fd496c98 | 15,539 | package client.ui;
import client.client.ServerService;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Vector;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;
import javax.swing.border.EmptyBorder;
/**
* 聊天窗口
*
* @author BoluBoLu
*/
public final class ChatWindow extends JFrame {
/**
* 聊天窗口的最大化,最小化,关闭和发送消息按钮
*/
private JButton minBtn, closeBtn, maxBtn, sendButton;
/**
* 聊天窗口位置移动
*/
private WindowMoveAdapter adapter;
/**
* 聊天窗口的顶部、输入框、群成员列表
*/
private JPanel headPanel, inputPanel, groupListPanel;
/**
* 好友的头像,用户名和签名
*/
private JLabel friendAvatar, friendName, friendTag;
/**
* 好友头像的文件名,用户名,个性签名,ID,自己的ID和姓名
*/
private String friendAvatarString, friendNameString, friendTagString, friendID, selfID, selfName;
/**
* 主区域和群区域
*/
private Box mainBox, groupBox;
/**
* 聊天框、输入框、群的滑动条
*/
private JScrollPane chatScroll, inputScroll, groupScroll;
/**
* 文本输入域
*/
private JTextArea input;
/**
* 头像
*/
private Image avatar;
/**
* 消息数量
*/
private int messageNum = 0;
/**
* 是否是群
*/
private boolean isGroup;
/**
* 聊天框的构造方法
*
* @param selfID 自己的ID
* @param selfName 自己的用户名
* @param friendID 好友的ID
* @param friendAvatarString 好友的头像文件名
* @param friendNameString 好友的用户名
* @param friendTagString 好友的签名内容
* @param isGroup 是否是群
*/
public ChatWindow(String selfID, String selfName, String friendID, String friendAvatarString,
String friendNameString, String friendTagString, boolean isGroup) {
this.selfID = selfID;
this.selfName = selfName;
this.friendID = friendID;
this.friendAvatarString = friendAvatarString;
this.friendNameString = friendNameString;
this.friendTagString = friendTagString;
this.isGroup = isGroup;
setTitle("波噜波噜- " + selfName + " 与 " + friendNameString + " 的会话");
setLayout(null);
/**
* 好友头像加载
*/
avatar = (GetAvatar
.getAvatarImage(friendID, isGroup ? "./res/avatar/Group/" : "./res/avatar/User/", friendAvatarString))
.getImage().getScaledInstance(90, 90, Image.SCALE_DEFAULT);
setIconImage(avatar);
setSize(750, 700);
init();
setUndecorated(true);
getRootPane().setWindowDecorationStyle(JRootPane.NONE);
setLocationRelativeTo(null);
setVisible(true);
}
/**
* 窗口初始化
*/
private void init() {
/**
* 关闭按钮
*/
closeBtn = new JButton("");
closeBtn.setMargin(new Insets(0, 0, 0, 0));
closeBtn.setBounds(730, 0, 20, 20);
closeBtn.setContentAreaFilled(false);
closeBtn.setBorderPainted(false);
closeBtn.setFocusPainted(false);
closeBtn.setToolTipText("关闭窗口");
closeBtn.setIcon(new ImageIcon("./res/UI/chatUI/closeOrigin.png"));
closeBtn.setRolloverIcon(new ImageIcon("./res/UI/chatUI/closeHover.png"));
closeBtn.setPressedIcon(new ImageIcon("./res/UI/chatUI/closeClick.png"));
closeBtn.addActionListener(new CloseListener(this, friendID, isGroup));
/**
* 最大化按钮
*/
maxBtn = new JButton();
maxBtn.setMargin(new Insets(0, 0, 0, 0));
maxBtn.setBounds(710, 0, 20, 20);
maxBtn.setContentAreaFilled(false);
maxBtn.setFocusPainted(false);
maxBtn.setBorderPainted(false);
maxBtn.setToolTipText("最大化");
maxBtn.setIcon(new ImageIcon("./res/UI/chatUI/maxOrigin.png"));
maxBtn.setRolloverIcon(new ImageIcon("./res/UI/chatUI/maxHover.png"));
maxBtn.setPressedIcon(new ImageIcon("./res/UI/chatUI/maxClick.png"));
maxBtn.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
if (getExtendedState() == JFrame.NORMAL) {
//最大化,改变窗体大小
maxBtn.setIcon(new ImageIcon("./res/UI/chatUI/restoreOrigin.png"));
maxBtn.setRolloverIcon(new ImageIcon("./res/UI/chatUI/restoreHover.png"));
maxBtn.setPressedIcon(new ImageIcon("./res/UI/chatUI/restoreClick.png"));
setExtendedState(JFrame.MAXIMIZED_BOTH);
closeBtn.setBounds(getWidth() - 20, 0, 20, 20);
maxBtn.setBounds(getWidth() - 40, 0, 20, 20);
minBtn.setBounds(getWidth() - 60, 0, 20, 20);
headPanel.setBounds(0, 0, getWidth(), 120);
if (isGroup) {
chatScroll.setBounds(0, 120, getWidth() - 200, getHeight() - 320);
inputPanel.setBounds(0, getHeight() - 200, getWidth() - 200, 200);
sendButton.setBounds(inputPanel.getWidth() - 280, inputPanel.getHeight() - 28, 70, 24);
groupListPanel.setBounds(getWidth() - 200, 120, 200, getHeight() - 120);
groupScroll.setBounds(0, 0, 200, getHeight() - 120);
} else {
chatScroll.setBounds(0, 120, getWidth(), getHeight() - 320);
inputPanel.setBounds(0, getHeight() - 200, getWidth(), 200);
sendButton.setBounds(inputPanel.getWidth() - 80, inputPanel.getHeight() - 28, 70, 24);
}
input.setBounds(0, 0, inputPanel.getWidth(), 170);
inputScroll.setBounds(0, 0, inputPanel.getWidth(), 170);
adapter.setCanMove(false);
} else if (getExtendedState() == JFrame.MAXIMIZED_BOTH) {
//最小化,改变窗体大小
maxBtn.setIcon(new ImageIcon("./res/UI/chatUI/maxOrigin.png"));
maxBtn.setRolloverIcon(new ImageIcon("./res/UI/chatUI/maxHover.png"));
maxBtn.setPressedIcon(new ImageIcon("./res/UI/chatUI/maxClick.png"));
setExtendedState(JFrame.NORMAL);
closeBtn.setBounds(getWidth() - 20, 0, 20, 20);
maxBtn.setBounds(getWidth() - 40, 0, 20, 20);
minBtn.setBounds(getWidth() - 60, 0, 20, 20);
headPanel.setBounds(0, 0, getWidth(), 120);
if (isGroup) {
chatScroll.setBounds(0, 120, getWidth() - 200, getHeight() - 320);
inputPanel.setBounds(0, getHeight() - 200, getWidth() - 200, 200);
sendButton.setBounds(inputPanel.getWidth() - 280, inputPanel.getHeight() - 28, 70, 24);
groupListPanel.setBounds(750, 120, 200, 580);
groupScroll.setBounds(0, 0, 200, 580);
} else {
chatScroll.setBounds(0, 120, getWidth(), getHeight() - 320);
inputPanel.setBounds(0, getHeight() - 200, getWidth(), 200);
sendButton.setBounds(inputPanel.getWidth() - 80, inputPanel.getHeight() - 28, 70, 24);
}
input.setBounds(0, 0, inputPanel.getWidth(), 170);
inputScroll.setBounds(0, 0, inputPanel.getWidth(), 170);
adapter.setCanMove(true);
}
}
});
/**
* 最小化按钮
*/
minBtn = new JButton();
minBtn.setMargin(new Insets(0, 0, 0, 0));
minBtn.setBounds(690, 0, 20, 20);
minBtn.setContentAreaFilled(false);
minBtn.setBorderPainted(false);
minBtn.setFocusPainted(false);
minBtn.setToolTipText("最小化");
minBtn.setIcon(new ImageIcon("./res/UI/chatUI/minOrigin.png"));
minBtn.setRolloverIcon(new ImageIcon("./res/UI/chatUI/minHover.png"));
minBtn.setPressedIcon(new ImageIcon("./res/UI/chatUI/minClick.png"));
minBtn.addActionListener(new ActionListener() {
@Override public void actionPerformed(ActionEvent e) {
setExtendedState(JFrame.ICONIFIED);
}
});
/**
* 顶部条 拖动可以移动窗口
*/
headPanel = new ImagePanel(Toolkit.getDefaultToolkit().createImage("./res/UI/img/grandeur-light.png"));
headPanel.setLayout(null);
headPanel.setBackground(new Color(122, 180, 202));
adapter = new WindowMoveAdapter();
headPanel.addMouseMotionListener(adapter);
headPanel.addMouseListener(adapter);
headPanel.addMouseListener(new MouseListener() {
@Override public void mouseReleased(MouseEvent e) {
}
@Override public void mousePressed(MouseEvent e) {
}
@Override public void mouseExited(MouseEvent e) {
}
@Override public void mouseEntered(MouseEvent e) {
}
@Override public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
// 最大化
}
}
});
/**
* 好友头像
*/
friendAvatar = new JLabel(new ImageIcon(friendAvatarString));
friendAvatar.setBounds(15, 10, 90, 90);
friendAvatar.setIcon(new ImageIcon(avatar));
headPanel.add(friendAvatar);
/**
* 好友名字
*/
friendName = new JLabel(friendNameString);
friendName.setBounds(120, 25, 200, 22);
friendName.setFont(new Font("黑体", Font.BOLD, 20));
headPanel.add(friendName);
/**
* 好友个性签名
*/
friendTag = new JLabel(friendTagString);
friendTag.setBounds(120, 65, 200, 15);
friendTag.setFont(new Font("宋体", Font.BOLD, 14));
headPanel.add(friendTag);
/**
* 主面板(背景、滚动条等)
*/
mainBox = Box.createVerticalBox();
// mainBox.setOpaque(true);
chatScroll = new JScrollPane(mainBox);
chatScroll.setBorder(new EmptyBorder(0, 0, 0, 0));
//滚动条
JScrollBar jsb = chatScroll.getVerticalScrollBar();
jsb.setUI(new ScrollBar());
chatScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// 设置滚动速率
jsb.setUnitIncrement(20);
chatScroll.setBounds(0, 120, 750, 380);
/**
* 获取聊天记录
*/
Vector<String> record = ServerService.getChatRecord(selfID, friendID, isGroup);
for (int i = 0; i < record.size(); i++) {
/**
* res[0] 消息发送时间 res[1] fromId res[2] toId res[3] message
*/
String[] res = record.get(i).split("```", 4);
// 聊天面板显示用户昵称
String fromName = res[1].equals(selfID) ? selfName
: MainWindow.getFriend().containsKey(res[1]) ? MainWindow.getFriend().get(res[1]).getFriendName()
: ("陌生人:" + res[1]);
if (res.length == 4) {
if (res[1].equals(selfID)) {
//如果是自己发的消息
addMessage(fromName, res[0], res[3], true, true);
} else {
//如果是别人发的消息
addMessage(fromName, res[0], res[3], true, false);
}
}
}
// 设置自动滑到底
chatScroll.getViewport().setViewPosition(new Point(0, chatScroll.getHeight() + 100000));
/**
* 输入框
*/
inputPanel = new ImagePanel(Toolkit.getDefaultToolkit().createImage("./res/UI/img/grandeur-windy.png"));
inputPanel.setLayout(null);
inputPanel.setBounds(0, 500, 750, 200);
input = new JTextArea();
input.setFont(new Font("黑体", Font.PLAIN, 20));
input.setBorder(new EmptyBorder(0, 0, 0, 0));
input.setBounds(0, 0, 750, 170);
input.setLineWrap(true);
inputScroll = new JScrollPane(input);
inputScroll.setBounds(0, 0, 750, 170);
inputScroll.setBorder(new EmptyBorder(0, 0, 0, 0));
inputScroll.getVerticalScrollBar().setUI(new ScrollBar());
inputScroll.getVerticalScrollBar().setUnitIncrement(15);
inputPanel.add(inputScroll);
/**
* 发送按钮
*/
sendButton = new JButton("发送");
sendButton.setBorderPainted(false);
sendButton.setFocusPainted(false);
sendButton.setMargin(new Insets(0, 0, 0, 0));
sendButton.setBackground(new Color(238, 238, 238));
sendButton.setFont(new Font("黑体", Font.BOLD, 15));
sendButton.setBounds(670, 172, 70, 24);
Send2FriendListener send2FriendListener = new Send2FriendListener(selfName, friendID, isGroup);
send2FriendListener.setMessage(input);
send2FriendListener.setTempChat(this);
sendButton.addActionListener(send2FriendListener);
inputPanel.add(sendButton);
//监听回车事件
input.addKeyListener(new KeyAdapter() {
@Override public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == KeyEvent.VK_ENTER) {
send2FriendListener.enter();
}
}
});
/**
* 群聊额外列表
*/
if (isGroup) {
groupBox = Box.createVerticalBox();
Vector<String> members = ServerService.getGroupMembers(friendID);
for (int i = 0; i < members.size(); i++) {
String tempMember = members.get(i);
ImageIcon icon = new ImageIcon("./res/UI/img/defaultAvatar.png");
String content = "陌生人(" + tempMember + ")";
if (tempMember.equals(selfID)) {
content = "我自己";
icon = new ImageIcon(GetAvatar.getAvatarImage(selfID, "./res/avatar/User/", "").getImage()
.getScaledInstance(30, 30, Image.SCALE_DEFAULT));
}
Box peopleBox = Box.createHorizontalBox();
peopleBox.setBounds(0, 0, 200, 60);
if (MainWindow.getFriend().containsKey(tempMember)) {
icon = GetAvatar.getAvatarImage(tempMember, "./res/avatar/User/",
MainWindow.getFriend().get(tempMember).getFriendAvatar());
content = MainWindow.getFriend().get(tempMember).getFriendName() + "(" + MainWindow.getFriend()
.get(tempMember).getFriendID() + ")";
}
icon = new ImageIcon(icon.getImage().getScaledInstance(30, 30, Image.SCALE_DEFAULT));
JLabel iconLabel = new JLabel(icon);
JLabel nameLabel = new JLabel(content);
JLabel blank = new JLabel();
iconLabel.setPreferredSize(new Dimension(80, 30));
nameLabel.setPreferredSize(new Dimension(80, 30));
peopleBox.add(iconLabel);
peopleBox.add(nameLabel);
JPanel peoplePanel = new ImagePanel(Toolkit.getDefaultToolkit().createImage("./res/UI/img/white.png"));
peoplePanel.add(peopleBox);
groupBox.add(peoplePanel);
}
groupScroll = new JScrollPane(groupBox);
groupScroll.getVerticalScrollBar().setUI(new ScrollBar());
groupScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
// 设置滚动速率
groupScroll.getVerticalScrollBar().setUnitIncrement(16);
groupScroll.setBounds(0, 0, 200, 580);
groupScroll.setBorder(new EmptyBorder(0, 0, 0, 0));
groupListPanel = new ImagePanel(Toolkit.getDefaultToolkit().createImage("./res/UI/img/group.png"));
groupListPanel.setBounds(750, 120, 200, 580);
groupListPanel.add(groupScroll);
groupListPanel.setBorder(new EmptyBorder(0, 4, 0, 0));
//其他更改位置的按钮
closeBtn.setBounds(930, 0, 20, 20);
maxBtn.setBounds(910, 0, 20, 20);
minBtn.setBounds(890, 0, 20, 20);
headPanel.setBounds(0, 0, 950, 120);
setSize(950, 700);
add(groupListPanel);
} else {
setSize(750, 700);
headPanel.setBounds(0, 0, 750, 120);
closeBtn.setBounds(730, 0, 20, 20);
maxBtn.setBounds(710, 0, 20, 20);
minBtn.setBounds(690, 0, 20, 20);
}
headPanel.add(closeBtn);
headPanel.add(maxBtn);
headPanel.add(minBtn);
add(headPanel);
add(chatScroll);
add(inputPanel);
}
/**
* 对象的messageNum的getter方法
*
* @return 对象属性 messageNum
*/
public int getMessageNum() {
return messageNum;
}
/**
* 对象的messageNum的setter方法
*
* @param messageNum 需要set的值
*/
public void setMessageNum(int messageNum) {
this.messageNum = messageNum;
}
/**
* 增加消息
*
* @param userName 用户名
* @param sendTime 发送时间
* @param message 消息内容
* @param isOld 是否是以前的消息
* @param isSelf 是否是自己的消息
*/
public void addMessage(String userName, String sendTime, String message, boolean isOld, boolean isSelf) {
String head = "<html><div style =\"font-size:12px;color:#0d171f\">";
String tail = "</div></html>";
sendTime = " <span style=\"font-size:10px;color:#d39325\"> " + sendTime + " </span>";
message = "<html><div style =\"font-size:14px;background-color:white;padding:2px 8px;border:1px solid;" + (isOld
? "color:#acacac" : "") + "\">" + message + "</div><br/></html>";
//聊天记录分立
if (isSelf) {
JLabel jLabel = new JLabel(head + sendTime + userName + tail, JLabel.RIGHT);
mainBox.add(jLabel);
JLabel jLabel2 = new JLabel(message, JLabel.RIGHT);
mainBox.add(jLabel2);
} else {
mainBox.add(new JLabel(head + " " + userName + sendTime + tail));
mainBox.add(new JLabel(message));
}
//设置新消息自动滑到底
chatScroll.getViewport().setViewPosition(new Point(0, chatScroll.getHeight() + 100000));
}
} | 32.171843 | 114 | 0.683699 |
4cf0fbf2904b1190c5b90bea8ac03b9898795584 | 3,522 | package com.mocean.modules;
import com.mocean.exception.MoceanErrorException;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
class TransmitterTest {
//this is test for v1
@Test
public void testErrorResponseWith2xxStatusCode() throws IOException {
String jsonErrorResponse = new String(Files.readAllBytes(Paths.get("src", "test", "resources", "error_response.json")), StandardCharsets.UTF_8);
Transmitter transmitter = new Transmitter();
try {
transmitter.formatResponse(jsonErrorResponse, 202, false, null);
fail();
} catch (MoceanErrorException ex) {
assertEquals(ex.getMessage(), ex.getErrorResponse().toString());
assertEquals(jsonErrorResponse, ex.getErrorResponse().toString());
assertEquals(ex.getErrorResponse().getStatus(), "1");
}
try {
transmitter.formatResponse(jsonErrorResponse, 200, false, null);
} catch (MoceanErrorException ex) {
assertEquals(ex.getMessage(), ex.getErrorResponse().toString());
assertEquals(jsonErrorResponse, ex.getErrorResponse().toString());
assertEquals(ex.getErrorResponse().getStatus(), "1");
}
String xmlErrorResponse = new String(Files.readAllBytes(Paths.get("src", "test", "resources", "error_response.json")), StandardCharsets.UTF_8);
try {
transmitter.formatResponse(xmlErrorResponse, 202, false, null);
} catch (MoceanErrorException ex) {
assertEquals(ex.getMessage(), ex.getErrorResponse().toString());
assertEquals(xmlErrorResponse, ex.getErrorResponse().toString());
assertEquals(ex.getErrorResponse().getStatus(), "1");
}
try {
transmitter.formatResponse(xmlErrorResponse, 200, false, null);
} catch (MoceanErrorException ex) {
assertEquals(ex.getMessage(), ex.getErrorResponse().toString());
assertEquals(xmlErrorResponse, ex.getErrorResponse().toString());
assertEquals(ex.getErrorResponse().getStatus(), "1");
}
}
@Test
public void testErrorResponseWith4xxStatusCode() throws IOException {
String errorResponse = new String(Files.readAllBytes(Paths.get("src", "test", "resources", "error_response.json")), StandardCharsets.UTF_8);
Transmitter transmitter = new Transmitter();
try {
transmitter.formatResponse(errorResponse, 400, false, null);
} catch (MoceanErrorException ex) {
assertEquals(ex.getMessage(), ex.getErrorResponse().toString());
assertEquals(errorResponse, ex.getErrorResponse().toString());
assertEquals(ex.getErrorResponse().getStatus(), "1");
assertEquals(ex.getErrorResponse().getErrMsg(), "Authorization failed");
}
}
@Test
public void testUrlEncodeUTF8() throws IOException {
HashMap<String, String> testMap = new HashMap<>();
testMap.put("Testing Only", "Hello World,");
testMap.put("Another Test", "World, Hello");
String encodedContent = (new Transmitter()).urlEncodeUTF8(testMap);
assertEquals(encodedContent, "Another+Test=World%2C+Hello&Testing+Only=Hello+World%2C");
}
} | 42.95122 | 152 | 0.667235 |
5537dfe627d71d6dbfe4c6ac28092d31a9743ecb | 15,646 | /*
* Copyright (c) 2016, University of Oslo
*
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.client.sdk.ui.adapters;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import org.hisp.dhis.client.sdk.ui.R;
import org.hisp.dhis.client.sdk.ui.models.ReportEntity;
import org.hisp.dhis.client.sdk.ui.views.CircleView;
import java.util.ArrayList;
import java.util.List;
import static org.hisp.dhis.client.sdk.utils.Preconditions.isNull;
public abstract class EndlessReportEntityAdapter extends RecyclerView.Adapter {
private final int VIEW_TYPE_ITEM = 0;
private final int VIEW_TYPE_LOADING = 1;
private final List<ReportEntity> reportEntities;
private final LayoutInflater layoutInflater;
private final RecyclerView recyclerView;
private final EndlessScrollListener endlessScrollListener;
// interaction listener
private OnReportEntityInteractionListener onReportEntityInteractionListener;
private boolean loading;
public EndlessReportEntityAdapter(RecyclerView recyclerView) {
this.recyclerView = recyclerView;
isNull(recyclerView, "RecyclerView must not be null");
Context context = recyclerView.getContext();
isNull(context, "RecyclerView must have valid Context");
layoutInflater = LayoutInflater.from(context);
this.reportEntities = new ArrayList<>();
endlessScrollListener = new EndlessScrollListener();
recyclerView.addOnScrollListener(endlessScrollListener);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == VIEW_TYPE_ITEM) {
return new ReportEntityViewHolder(layoutInflater.inflate(
R.layout.recyclerview_report_entity_item, parent, false));
} else if (viewType == VIEW_TYPE_LOADING) {
return new LoadingViewHolder(layoutInflater.inflate(R.layout.loading_view, parent, false));
}
return null;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ReportEntityViewHolder) {
ReportEntity reportEntity = reportEntities.get(position);
((ReportEntityViewHolder) holder).update(reportEntity);
}
}
@Override
public int getItemCount() {
return reportEntities.size();
}
@Override
public int getItemViewType(int position) {
return isLoadingView(position) ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM;
}
public void setOnReportEntityInteractionListener(OnReportEntityInteractionListener onInteractionListener) {
this.onReportEntityInteractionListener = onInteractionListener;
}
public void swapData(@Nullable List<ReportEntity> reportEntities) {
this.reportEntities.clear();
if (reportEntities != null) {
this.reportEntities.addAll(reportEntities);
}
notifyDataSetChanged();
}
public interface OnReportEntityInteractionListener {
void onReportEntityClicked(ReportEntity reportEntity);
void onDeleteReportEntity(ReportEntity reportEntity);
}
private final class LoadingViewHolder extends RecyclerView.ViewHolder {
public LoadingViewHolder(View itemView) {
super(itemView);
}
}
private final class ReportEntityViewHolder extends RecyclerView.ViewHolder {
ReportEntity reportEntity;
final View statusIconContainer;
final CircleView statusBackground;
final ImageView statusIcon;
final OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
final View deleteButton;
final Drawable drawableSent;
final Drawable drawableOffline;
final Drawable drawableError;
final int colorSent;
final int colorOffline;
final int colorError;
public ReportEntityViewHolder(View itemView) {
super(itemView);
statusIconContainer = itemView.findViewById(R.id.status_icon_container);
statusBackground = (CircleView) itemView
.findViewById(R.id.circleview_status_background);
statusIcon = (ImageView) itemView
.findViewById(R.id.imageview_status_icon);
deleteButton = itemView.findViewById(R.id.delete_button);
onRecyclerViewItemClickListener = new OnRecyclerViewItemClickListener();
itemView.setOnClickListener(onRecyclerViewItemClickListener);
deleteButton.setOnClickListener(new OnDeleteButtonClickListener());
Context context = itemView.getContext();
drawableSent = ContextCompat.getDrawable(context, R.drawable.ic_tick);
drawableOffline = ContextCompat.getDrawable(context, R.drawable.ic_offline);
drawableError = ContextCompat.getDrawable(context, R.drawable.ic_error);
colorSent = ContextCompat.getColor(context, R.color.color_material_green_default);
colorOffline = ContextCompat.getColor(context, R.color.color_accent_default);
colorError = ContextCompat.getColor(context, R.color.color_material_red_default);
}
private void showEntityDeletionConfirmationDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(deleteButton.getContext());
builder.setTitle(R.string.delete_report_entity_dialog_title).setMessage(R.string.delete_report_entity_dialog_message).setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (onReportEntityInteractionListener != null) {
int entityIndex = reportEntities.indexOf(reportEntity);
reportEntities.remove(reportEntity);
notifyItemRemoved(entityIndex);
onReportEntityInteractionListener.onDeleteReportEntity(reportEntity);
} else {
Toast.makeText(deleteButton.getContext(), R.string.report_entity_deletion_error, Toast.LENGTH_SHORT).show();
}
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create().show();
}
public void update(ReportEntity reportEntity) {
this.reportEntity = reportEntity;
onRecyclerViewItemClickListener.setReportEntity(reportEntity);
switch (reportEntity.getStatus()) {
// TODO: show deleteButton for all statuses when deletion is supported in SDK
case SENT: {
deleteButton.setVisibility(View.GONE);
statusBackground.setFillColor(colorSent);
statusIcon.setImageDrawable(drawableSent);
break;
}
case TO_POST: {
deleteButton.setVisibility(View.VISIBLE);
statusBackground.setFillColor(colorOffline);
statusIcon.setImageDrawable(drawableOffline);
break;
}
case TO_UPDATE: {
deleteButton.setVisibility(View.GONE);
statusBackground.setFillColor(colorOffline);
statusIcon.setImageDrawable(drawableOffline);
break;
}
case ERROR: {
deleteButton.setVisibility(View.GONE);
statusBackground.setFillColor(colorError);
statusIcon.setImageDrawable(drawableError);
break;
}
}
/*lineOne.setText(reportEntity.getLineOne());
lineTwo.setText(reportEntity.getLineTwo());
lineThree.setText(reportEntity.getLineThree());*/
}
private void showStatusDialog(Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(R.string.drawer_item_status);
switch (reportEntity.getStatus()) {
case SENT: {
Drawable mutableSentIcon = ContextCompat.getDrawable(context, R.drawable.ic_tick).mutate();
mutableSentIcon.setColorFilter(colorSent, PorterDuff.Mode.MULTIPLY);
builder.setIcon(mutableSentIcon);
builder.setMessage(R.string.sync_status_ok_message);
break;
}
case TO_UPDATE:
case TO_POST: {
Drawable mutableOfflineIcon = ContextCompat.getDrawable(context, R.drawable.ic_offline).mutate();
mutableOfflineIcon.setColorFilter(colorOffline, PorterDuff.Mode.MULTIPLY);
builder.setIcon(mutableOfflineIcon);
builder.setMessage(R.string.sync_status_offline_message);
break;
}
case ERROR: {
Drawable mutableDrawableError = ContextCompat.getDrawable(context, R.drawable.ic_error).mutate();
mutableDrawableError.setColorFilter(colorError, PorterDuff.Mode.MULTIPLY);
builder.setIcon(mutableDrawableError);
builder.setMessage(R.string.sync_status_error_message);
break;
}
}
builder.setPositiveButton(R.string.sync_now, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//TODO: sync this report entity
dialog.dismiss();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
private class OnDeleteButtonClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
if (onReportEntityInteractionListener != null) {
showEntityDeletionConfirmationDialog();
} else {
Toast.makeText(v.getContext(), R.string.report_entity_deletion_error, Toast.LENGTH_SHORT).show();
}
}
}
}
public void addItem(ReportEntity reportEntity) {
reportEntities.add(reportEntity);
notifyItemInserted(reportEntities.size() - 1);
}
private class OnRecyclerViewItemClickListener implements View.OnClickListener {
private ReportEntity reportEntity;
public void setReportEntity(ReportEntity reportEntity) {
this.reportEntity = reportEntity;
}
@Override
public void onClick(View view) {
if (onReportEntityInteractionListener != null) {
onReportEntityInteractionListener.onReportEntityClicked(reportEntity);
}
}
}
private class EndlessScrollListener extends RecyclerView.OnScrollListener {
// number of items to the bottom of the list where we start fetching new items
public static final int BOTTOM_ITEM_TRESHOLD = 3;
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (!loading && bottomTresholdReached(recyclerView)) {
loading = true;
showLoadingView();
onLoadData();
}
}
private boolean bottomTresholdReached(RecyclerView recyclerView) {
int visibleItemCount = recyclerView.getChildCount();
int totalItemCount = recyclerView.getLayoutManager().getItemCount();
int firstVisibleItem = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();
return totalItemCount - visibleItemCount < (firstVisibleItem + BOTTOM_ITEM_TRESHOLD);
}
}
private void showLoadingView() {
if (!loadingViewIsShowing()) {
reportEntities.add(null);
notifyItemInserted(reportEntities.size() - 1);
}
}
public void addLoadedItems(List<ReportEntity> newItems) {
hideLoadingView();
reportEntities.addAll(newItems);
notifyDataSetChanged();
loading = false;
}
private void hideLoadingView() {
if (!reportEntities.isEmpty() && loadingViewIsShowing()) {
reportEntities.remove(reportEntities.size() - 1);
notifyItemRemoved(reportEntities.size());
}
}
private boolean loadingViewIsShowing() {
return isLoadingView(reportEntities.size() - 1);
}
private boolean isLoadingView(int position) {
return reportEntities.get(position) == null;
}
/**
* Do your fetching of data items
* Add fetched items with {@link #addLoadedItems(List)}
*/
public abstract void onLoadData();
/**
* Hides the loading view
* Call when there are no more items to fetch
*/
public void onLoadFinished() {
recyclerView.removeOnScrollListener(endlessScrollListener);
hideLoadingView();
}
}
| 38.536946 | 204 | 0.654225 |
fdadc9501d8d37b15bb84ce6a926c601eb2a7de4 | 316 | package com.kodexa.client;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class ContentClassification {
private String label;
private String taxonomy;
private String selector;
private Float confidence;
}
| 19.75 | 61 | 0.78481 |
4715f1661d755fccfc09b163c3962c69cc2ab9cb | 1,589 | package com.mailchimp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
/**
* Sort the tests with {@link InSequence} and sets the tests with no InSequence defined as first.
*
* @author stevensnoeijen
*/
public class InSequenceRunner extends BlockJUnit4ClassRunner {
public InSequenceRunner(Class clazz) throws InitializationError {
super(clazz);
}
@Override
protected List computeTestMethods() {
//super returns an unmodified list and need to be copied to able be sorted
List<FrameworkMethod> tests = new ArrayList<>(super.computeTestMethods());
Collections.sort(tests, (FrameworkMethod o1, FrameworkMethod o2) -> {
//if both are InSequence sort
if (o1.getAnnotation(InSequence.class) != null
&& o2.getAnnotation(InSequence.class) != null) {
int o1Order = o1.getAnnotation(InSequence.class).value();
int o2Order = o2.getAnnotation(InSequence.class).value();
return Integer.compare(o1Order, o2Order);
} else if (o1.getAnnotation(InSequence.class) != null) {//check if one InSequence
return 1;
} else if (o2.getAnnotation(InSequence.class) != null) {
return -1;
} else {
//none
return 0;//do this as last
}
});
return tests;
}
}
| 35.311111 | 97 | 0.636879 |
cce9d7e39c820d73003bb1b42f01e98df8e72a3e | 2,285 | package com.restdocs.action.util;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiFileFactory;
import com.intellij.psi.PsiManager;
import com.restdocs.action.common.RestServiceNode;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.util.List;
import java.util.Properties;
import static com.intellij.openapi.fileTypes.FileTypes.PLAIN_TEXT;
public class FileUtil {
public void createFile(Project project, String fileName, List<RestServiceNode> services) {
PsiFile psiFile = PsiFileFactory.getInstance(project).createFileFromText(fileName, PLAIN_TEXT, createHtmlFile(services));
PsiDirectory directory = PsiManager.getInstance(project).findDirectory(project.getBaseDir());
PsiFile file = directory.findFile(fileName);
if (file == null) {
ApplicationManager.getApplication().runWriteAction(() -> {
directory.add(psiFile);
});
} else {
ApplicationManager.getApplication().runWriteAction(() -> {
file.delete();
directory.add(psiFile);
});
}
}
private String createHtmlFile(List<RestServiceNode> services) {
VelocityContext context = new VelocityContext();
context.put("services", services);
String templatePath = "template.html";
InputStream input = getClass().getClassLoader().getResourceAsStream(templatePath);
VelocityEngine engine = new VelocityEngine();
Properties props = new Properties();
props.put("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
props.put("runtime.log.logsystem.log4j.category", "velocity");
props.put("runtime.log.logsystem.log4j.logger", "velocity");
engine.init(props);
StringWriter writer = new StringWriter();
engine.evaluate(context, writer, "REST", new InputStreamReader(input));
return writer.toString().replace("\n", "").replace("\r", "");
}
} | 38.728814 | 129 | 0.701969 |
25d3f1cec60e05e3b9af8784d61a5d898610c59c | 616 | package org.jetbrains.dekaf.jdbc;
import org.jetbrains.dekaf.assertions.PatternAssert;
import org.junit.Test;
import static org.jetbrains.dekaf.jdbc.H2dbIntermediateProvider.H2DB_CONNECTION_STRING_EXAMPLE;
import static org.jetbrains.dekaf.jdbc.H2dbIntermediateProvider.H2DB_CONNECTION_STRING_PATTERN;
/**
* @author Leonid Bushuev from JetBrains
*/
public class H2dbInterServiceProviderUnitTest {
@Test
public void connectionStringExample_matches_connectionStringPattern() {
PatternAssert.assertThat(H2DB_CONNECTION_STRING_PATTERN)
.fits(H2DB_CONNECTION_STRING_EXAMPLE);
}
} | 28 | 95 | 0.806818 |
c0d6f267913419a32d50dddc101a2fde55c612ed | 800 | package de.o0o0o0.v7.beans.factory.support;
import de.o0o0o0.v7.config.RuntimeBeanReference;
import de.o0o0o0.v7.config.TypedStringValue;
public class BeanDefinitionValueResolver {
private final DefaultBeanFactory factory;
public BeanDefinitionValueResolver(DefaultBeanFactory factory) {
this.factory = factory;
}
public Object resolveValueIfNecessary(Object value) {
if (value instanceof RuntimeBeanReference) {
String refName = ((RuntimeBeanReference) value).getBeanName();
return factory.getBean(refName);
} else if (value instanceof TypedStringValue) {
return ((TypedStringValue) value).getValue();
}
// TODO
throw new RuntimeException("the value " + value + " has not implemented");
}
}
| 33.333333 | 82 | 0.695 |
6468479f59241b02bbe698e387926ea2faf89b3d | 4,998 | package com.github.filipmalczak.vent.mongo.service;
import com.github.filipmalczak.vent.api.model.Success;
import com.github.filipmalczak.vent.api.temporal.TemporalService;
import com.github.filipmalczak.vent.mongo.model.CollectionDescriptor;
import com.github.filipmalczak.vent.mongo.model.CollectionPeriodDescriptor;
import com.github.filipmalczak.vent.mongo.model.events.Event;
import lombok.AllArgsConstructor;
import lombok.Value;
import org.springframework.data.mongodb.core.ReactiveMongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.time.LocalDateTime;
import java.util.Optional;
import java.util.function.Supplier;
import static com.github.filipmalczak.vent.helper.Struct.list;
import static com.github.filipmalczak.vent.mongo.utils.CollectionsUtils.COLLECTIONS_MONGO_COLLECTION;
import static com.github.filipmalczak.vent.mongo.utils.CollectionsUtils.MONGO_COLLECTION_NAME_MAPPER;
import static reactor.core.publisher.Mono.just;
@AllArgsConstructor
public class CollectionService {
private final ReactiveMongoOperations operations;
private final TemporalService temporalService;
@Value(staticConstructor = "with")
public static class NameAndNow {
final String name;
final LocalDateTime now;
public <E extends Event<E>> E align(E event){
return event.withOccuredOn(now);
}
}
public Mono<NameAndNow> mongoCollectionName(String ventCollectionName){
return mongoCollectionName(ventCollectionName, temporalService);
}
public Mono<NameAndNow> mongoCollectionName(String ventCollectionName, Supplier<LocalDateTime> at){
//todo introduce archivization
//make sure that supplier is called in reactive context (and not outside of some publisher)
return getMongoCollectionNameForCurrentPeriod(ventCollectionName).map(s -> NameAndNow.with(s, at.get()));
}
public Mono<String> getMongoCollectionNameForCurrentPeriod(String ventCollectionName){
return manageIfNeededAndGet(ventCollectionName).
map(CollectionDescriptor::getCurrentPeriod).
map(CollectionPeriodDescriptor::getMongoCollectionName);
}
public Flux<CollectionDescriptor> getAllCollections(){
return operations.findAll(CollectionDescriptor.class, COLLECTIONS_MONGO_COLLECTION);
}
public Flux<String> getAllCollectionNames(){
return getAllCollections().map(CollectionDescriptor::getVentCollectionName);
}
//todo maybe return Mono<Yes> (empty on No) instead of Mono<Boolean>?
public Mono<Boolean> isManaged(String ventCollectionName){
return operations.
exists(
Query.query(
Criteria.
where("ventCollectionName").
is(ventCollectionName)
),
CollectionDescriptor.class,
COLLECTIONS_MONGO_COLLECTION
);
}
public Mono<CollectionDescriptor> getDescriptor(String ventCollectionName){
return operations.findOne(
Query.query(
Criteria.
where("ventCollectionName").
is(ventCollectionName)
),
CollectionDescriptor.class,
COLLECTIONS_MONGO_COLLECTION
);
}
public Mono<CollectionDescriptor> manageIfNeededAndGet(String ventCollectionName){
return getDescriptor(ventCollectionName).switchIfEmpty(createManaged(ventCollectionName));
}
private Mono<CollectionDescriptor> createManaged(String ventCollectionName){
return Mono.
fromCallable(temporalService::now).
flatMap( now ->
operations.insert(
new CollectionDescriptor(
ventCollectionName,
new CollectionPeriodDescriptor(
now,
null,
MONGO_COLLECTION_NAME_MAPPER.
toMongoCollectionName(
ventCollectionName,
now,
Optional.empty()
)
),
list()
),
COLLECTIONS_MONGO_COLLECTION
)
);
}
public Mono<Success> manage(String ventCollectionName){
//fixme between isManaged and optionally inserting there's a gap that is perfect for race conditions
return isManaged(ventCollectionName).flatMap(isMngd ->
isMngd ?
just(Success.NO_OP_SUCCESS):
createManaged(ventCollectionName).map( newCollection ->
Success.SUCCESS
)
);
}
}
| 38.744186 | 113 | 0.65066 |
12e367d49422d6517718d0288b7240883edfbf4e | 437 | package de.quinscape.domainql.beans;
/**
* Class containing byte[] data;
*/
public class BinaryBean
{
private String name;
private byte[] data;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public byte[] getData()
{
return data;
}
public void setData(byte[] data)
{
this.data = data;
}
}
| 12.485714 | 36 | 0.546911 |
32fa20854baa735a3945cff964c30e669cf9a9af | 451 | package com.wsk.dao;
import com.wsk.pojo.AdminInformation;
public interface AdminInformationMapper {
int deleteByPrimaryKey(Integer id);
int insert(AdminInformation record);
int insertSelective(AdminInformation record);
AdminInformation selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(AdminInformation record);
int updateByPrimaryKey(AdminInformation record);
AdminInformation selectByNo(int ano);
} | 23.736842 | 61 | 0.789357 |
e499b491b9f8baa8c990318287b23a26fccd543a | 739 | package com.jabbour.ems.security;
import com.jabbour.ems.backend.service.UserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class AppUserDetailsService implements UserDetailsService {
private final UserService userService;
public AppUserDetailsService(UserService userService) {
this.userService = userService;
}
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
return userService.findByUsername(s);
}
} | 29.56 | 86 | 0.807848 |
a3331c2666c9ff9743b125f5b6f3b37a7422606a | 429 | package com.idugalic.queryside.team.web;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import com.idugalic.queryside.team.domain.Team;
import com.idugalic.queryside.team.repository.TeamRepository;
/**
* A JPA repository for {@link Team}.
*
* @author idugalic
*
*/
@RepositoryRestResource(collectionResourceRel = "team", path = "team")
interface MyTeamRepository extends TeamRepository {
}
| 25.235294 | 76 | 0.783217 |
76257bf3373da82dc9e85cdd3d224ebd2d40e670 | 13,451 | /*! ******************************************************************************
*
* Hop : The Hop Orchestration Platform
*
* http://www.project-hop.org
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package org.apache.hop.databases.teradata;
import org.apache.commons.lang.StringUtils;
import org.apache.hop.core.Const;
import org.apache.hop.core.database.BaseDatabaseMeta;
import org.apache.hop.core.database.IDatabase;
import org.apache.hop.core.database.DatabaseMeta;
import org.apache.hop.core.database.DatabaseMetaPlugin;
import org.apache.hop.core.gui.plugin.GuiPlugin;
import org.apache.hop.core.row.IValueMeta;
import org.apache.hop.core.util.Utils;
import java.util.Map;
/**
* Contains NCR Teradata specific information through static final members
*
* @author Matt
* @since 26-jul-2006
*/
@DatabaseMetaPlugin(
type = "TERADATA",
typeDescription = "Teradata"
)
@GuiPlugin( id = "GUI-TeradataDatabaseMeta" )
public class TeradataDatabaseMeta extends BaseDatabaseMeta implements IDatabase {
@Override
public int[] getAccessTypeList() {
return new int[] {
DatabaseMeta.TYPE_ACCESS_NATIVE, DatabaseMeta.TYPE_ACCESS_ODBC };
}
@Override
public boolean isTeradataVariant() {
return true;
}
/**
* @see IDatabase#getNotFoundTK(boolean)
*/
@Override
public int getNotFoundTK( boolean useAutoinc ) {
if ( supportsAutoInc() && useAutoinc ) {
return 1;
}
return super.getNotFoundTK( useAutoinc );
}
@Override
public String getDriverClass() {
return "com.teradata.jdbc.TeraDriver";
}
@Override
public String getURL( String hostname, String port, String databaseName ) {
if ( getAccessType() == DatabaseMeta.TYPE_ACCESS_NATIVE ) {
String url = "jdbc:teradata://" + hostname;
// port is not appended here; instead it is appended via the DBS_PORT extra option
if ( !StringUtils.isEmpty( databaseName ) ) {
url += "/DATABASE=" + databaseName;
}
return url;
} else {
return "jdbc:odbc:" + databaseName;
}
}
/**
* Checks whether or not the command setFetchSize() is supported by the JDBC driver...
*
* @return true is setFetchSize() is supported!
*/
@Override
public boolean isFetchSizeSupported() {
return false;
}
/**
* @return true if the database supports bitmap indexes
*/
@Override
public boolean supportsBitmapIndex() {
return false;
}
@Override
public String getSqlTableExists( String tablename ) {
return "show table " + tablename;
}
@Override
public String getSqlColumnExists( String columnname, String tablename ) {
return "SELECT * FROM DBC.columns WHERE tablename =" + tablename + " AND columnname =" + columnname;
}
/**
* @param tableName The table to be truncated.
* @return The SQL statement to truncate a table: remove all rows from it without a transaction
*/
@Override
public String getTruncateTableStatement( String tableName ) {
return "DELETE FROM " + tableName;
}
/**
* Generates the SQL statement to add a column to the specified table For this generic type, i set it to the most
* common possibility.
*
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param useAutoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to add a column to the specified table
*/
@Override
public String getAddColumnStatement( String tablename, IValueMeta v, String tk, boolean useAutoinc,
String pk, boolean semicolon ) {
return "ALTER TABLE " + tablename + " ADD " + getFieldDefinition( v, tk, pk, useAutoinc, true, false );
}
/**
* Generates the SQL statement to modify a column in the specified table
*
* @param tablename The table to add
* @param v The column defined as a value
* @param tk the name of the technical key field
* @param useAutoinc whether or not this field uses auto increment
* @param pk the name of the primary key field
* @param semicolon whether or not to add a semi-colon behind the statement.
* @return the SQL statement to modify a column in the specified table
*/
@Override
public String getModifyColumnStatement( String tablename, IValueMeta v, String tk, boolean useAutoinc,
String pk, boolean semicolon ) {
return "ALTER TABLE " + tablename + " MODIFY " + getFieldDefinition( v, tk, pk, useAutoinc, true, false );
}
@Override
public String getFieldDefinition( IValueMeta v, String tk, String pk, boolean useAutoinc,
boolean addFieldname, boolean addCr ) {
String retval = "";
String fieldname = v.getName();
int length = v.getLength();
int precision = v.getPrecision();
if ( addFieldname ) {
retval += fieldname + " ";
}
int type = v.getType();
switch ( type ) {
case IValueMeta.TYPE_TIMESTAMP:
case IValueMeta.TYPE_DATE:
retval += "TIMESTAMP";
break;
case IValueMeta.TYPE_BOOLEAN:
retval += "CHAR(1)";
break;
case IValueMeta.TYPE_NUMBER:
case IValueMeta.TYPE_INTEGER:
case IValueMeta.TYPE_BIGNUMBER:
if ( fieldname.equalsIgnoreCase( tk ) || // Technical key
fieldname.equalsIgnoreCase( pk ) // Primary key
) {
retval += "INTEGER"; // TERADATA has no Auto-increment functionality nor Sequences!
} else {
if ( length > 0 ) {
if ( precision > 0 || length > 9 ) {
retval += "DECIMAL(" + length + ", " + precision + ")";
} else {
if ( length > 5 ) {
retval += "INTEGER";
} else {
if ( length < 3 ) {
retval += "BYTEINT";
} else {
retval += "SMALLINT";
}
}
}
} else {
retval += "DOUBLE PRECISION";
}
}
break;
case IValueMeta.TYPE_STRING:
if ( length > 64000 ) {
retval += "CLOB";
} else {
retval += "VARCHAR";
if ( length > 0 ) {
retval += "(" + length + ")";
} else {
retval += "(64000)"; // Maybe use some default DB String length?
}
}
break;
default:
retval += " UNKNOWN";
break;
}
if ( addCr ) {
retval += Const.CR;
}
return retval;
}
@Override
public String getExtraOptionSeparator() {
return ",";
}
@Override
public String getExtraOptionIndicator() {
return "/";
}
@Override
public String getExtraOptionsHelpText() {
return "http://www.info.ncr.com/eTeradata-BrowseBy-Results.cfm?pl=&PID=&title=%25&release="
+ "&kword=CJDBC&sbrn=7&nm=Teradata+Tools+and+Utilities+-+Java+Database+Connectivity+(JDBC)";
}
@Override
public int getDefaultDatabasePort() {
return 1025;
}
/**
* @return an array of reserved words for the database type...
*/
@Override
public String[] getReservedWords() {
return new String[] {
"ABORT", "ABORTSESSION", "ABS", "ACCESS_LOCK", "ACCOUNT", "ACOS", "ACOSH", "ADD", "ADD_MONTHS", "ADMIN",
"AFTER", "AGGREGATE", "ALL", "ALTER", "AMP", "AND", "ANSIDATE", "ANY", "ARGLPAREN", "AS", "ASC", "ASIN",
"ASINH", "AT", "ATAN", "ATAN2", "ATANH", "ATOMIC", "AUTHORIZATION", "AVE", "AVERAGE", "AVG", "BEFORE",
"BEGIN", "BETWEEN", "BIGINT", "BINARY", "BLOB", "BOTH", "BT", "BUT", "BY", "BYTE", "BYTEINT", "BYTES",
"CALL", "CASE", "CASE_N", "CASESPECIFIC", "CAST", "CD", "CHAR", "CHAR_LENGTH", "CHAR2HEXINT", "CHARACTER",
"CHARACTER_LENGTH", "CHARACTERS", "CHARS", "CHECK", "CHECKPOINT", "CLASS", "CLOB", "CLOSE", "CLUSTER",
"CM", "COALESCE", "COLLATION", "COLLECT", "COLUMN", "COMMENT", "COMMIT", "COMPRESS", "CONSTRAINT",
"CONSTRUCTOR", "CONSUME", "CONTAINS", "CONTINUE", "CONVERT_TABLE_HEADER", "CORR", "COS", "COSH", "COUNT",
"COVAR_POP", "COVAR_SAMP", "CREATE", "CROSS", "CS", "CSUM", "CT", "CUBE", "CURRENT", "CURRENT_DATE",
"CURRENT_TIME", "CURRENT_TIMESTAMP", "CURSOR", "CV", "CYCLE", "DATABASE", "DATABLOCKSIZE", "DATE",
"DATEFORM", "DAY", "DEALLOCATE", "DEC", "DECIMAL", "DECLARE", "DEFAULT", "DEFERRED", "DEGREES", "DEL",
"DELETE", "DESC", "DETERMINISTIC", "DIAGNOSTIC", "DISABLED", "DISTINCT", "DO", "DOMAIN", "DOUBLE", "DROP",
"DUAL", "DUMP", "DYNAMIC", "EACH", "ECHO", "ELSE", "ELSEIF", "ENABLED", "END", "EQ", "EQUALS", "ERROR",
"ERRORFILES", "ERRORTABLES", "ESCAPE", "ET", "EXCEPT", "EXEC", "EXECUTE", "EXISTS", "EXIT", "EXP",
"EXPLAIN", "EXTERNAL", "EXTRACT", "FALLBACK", "FASTEXPORT", "FETCH", "FIRST", "FLOAT", "FOR", "FOREIGN",
"FORMAT", "FOUND", "FREESPACE", "FROM", "FULL", "FUNCTION", "GE", "GENERATED", "GIVE", "GRANT", "GRAPHIC",
"GROUP", "GROUPING", "GT", "HANDLER", "HASH", "HASHAMP", "HASHBAKAMP", "HASHBUCKET", "HASHROW", "HAVING",
"HELP", "HOUR", "IDENTITY", "IF", "IMMEDIATE", "IN", "INCONSISTENT", "INDEX", "INITIATE", "INNER",
"INOUT", "INPUT", "INS", "INSERT", "INSTANCE", "INSTEAD", "INT", "INTEGER", "INTEGERDATE", "INTERSECT",
"INTERVAL", "INTO", "IS", "ITERATE", "JAR", "JOIN", "JOURNAL", "KEY", "KURTOSIS", "LANGUAGE", "LARGE",
"LE", "LEADING", "LEAVE", "LEFT", "LIKE", "LIMIT", "LN", "LOADING", "LOCAL", "LOCATOR", "LOCK", "LOCKING",
"LOG", "LOGGING", "LOGON", "LONG", "LOOP", "LOWER", "LT", "MACRO", "MAP", "MAVG", "MAX", "MAXIMUM",
"MCHARACTERS", "MDIFF", "MERGE", "METHOD", "MIN", "MINDEX", "MINIMUM", "MINUS", "MINUTE", "MLINREG",
"MLOAD", "MOD", "MODE", "MODIFIES", "MODIFY", "MONITOR", "MONRESOURCE", "MONSESSION", "MONTH", "MSUBSTR",
"MSUM", "MULTISET", "NAMED", "NATURAL", "NE", "NEW", "NEW_TABLE", "NEXT", "NO", "NONE", "NOT", "NOWAIT",
"NULL", "NULLIF", "NULLIFZERO", "NUMERIC", "OBJECT", "OBJECTS", "OCTET_LENGTH", "OF", "OFF", "OLD",
"OLD_TABLE", "ON", "ONLY", "OPEN", "OPTION", "OR", "ORDER", "ORDERING", "OUT", "OUTER", "OUTPUT", "OVER",
"OVERLAPS", "OVERRIDE", "PARAMETER", "PASSWORD", "PERCENT", "PERCENT_RANK", "PERM", "PERMANENT",
"POSITION", "PRECISION", "PREPARE", "PRESERVE", "PRIMARY", "PRIVILEGES", "PROCEDURE", "PROFILE",
"PROTECTION", "PUBLIC", "QUALIFIED", "QUALIFY", "QUANTILE", "QUEUE", "RADIANS", "RANDOM", "RANGE_N",
"RANK", "READS", "REAL", "RECURSIVE", "REFERENCES", "REFERENCING", "REGR_AVGX", "REGR_AVGY", "REGR_COUNT",
"REGR_INTERCEPT", "REGR_R2", "REGR_SLOPE", "REGR_SXX", "REGR_SXY", "REGR_SYY", "RELATIVE", "RELEASE",
"RENAME", "REPEAT", "REPLACE", "REPLCONTROL", "REPLICATION", "REQUEST", "RESTART", "RESTORE", "RESULT",
"RESUME", "RET", "RETRIEVE", "RETURN", "RETURNS", "REVALIDATE", "REVOKE", "RIGHT", "RIGHTS", "ROLE",
"ROLLBACK", "ROLLFORWARD", "ROLLUP", "ROW", "ROW_NUMBER", "ROWID", "ROWS", "SAMPLE", "SAMPLEID", "SCROLL",
"SECOND", "SEL", "SELECT", "SESSION", "SET", "SETRESRATE", "SETS", "SETSESSRATE", "SHOW", "SIN", "SINH",
"SKEW", "SMALLINT", "SOME", "SOUNDEX", "SPECIFIC", "SPOOL", "SQL", "SQLEXCEPTION", "SQLTEXT",
"SQLWARNING", "SQRT", "SS", "START", "STARTUP", "STATEMENT", "STATISTICS", "STDDEV_POP", "STDDEV_SAMP",
"STEPINFO", "STRING_CS", "SUBSCRIBER", "SUBSTR", "SUBSTRING", "SUM", "SUMMARY", "SUSPEND", "TABLE", "TAN",
"TANH", "TBL_CS", "TEMPORARY", "TERMINATE", "THEN", "THRESHOLD", "TIME", "TIMESTAMP", "TIMEZONE_HOUR",
"TIMEZONE_MINUTE", "TITLE", "TO", "TOP", "TRACE", "TRAILING", "TRANSACTION", "TRANSFORM", "TRANSLATE",
"TRANSLATE_CHK", "TRIGGER", "TRIM", "TRUE", "TYPE", "UC", "UDTCASTAS", "UDTCASTLPAREN", "UDTMETHOD",
"UDTTYPE", "UDTUSAGE", "UESCAPE", "UNDEFINED", "UNDO", "UNION", "UNIQUE", "UNTIL", "UPD", "UPDATE",
"UPPER", "UPPERCASE", "USER", "USING", "VALUE", "VALUES", "VAR_POP", "VAR_SAMP", "VARBYTE", "VARCHAR",
"VARGRAPHIC", "VARYING", "VIEW", "VOLATILE", "WHEN", "WHERE", "WHILE", "WIDTH_BUCKET", "WITH", "WITHOUT",
"WORK", "YEAR", "ZEROIFNULL", "ZONE" };
}
/**
* Overrides parent behavior to allow <code>getDatabasePortNumberString</code> value to override value of
* <code>DBS_PORT</code> extra option.
*/
@Override
public Map<String, String> getExtraOptions() {
Map<String, String> map = super.getExtraOptions();
if ( !Utils.isEmpty( getPort() ) ) {
map.put( getPluginId() + ".DBS_PORT", getPort() );
}
return map;
}
}
| 40.51506 | 115 | 0.597948 |
7f123075e232818e8afa8fa4d33090edc06ef7f9 | 379 | package org.sample;
public class TestBreakContinue {
public static void main(String[] args) {
int i = 0;
outer: while (true) {
System.out.println(i);
while (true) {
i++;
if (i == 1) {
continue; // inner
}
if (i == 3) {
continue outer;
}
if (i == 5) {
break; //inner
}
if (i == 7) {
break outer;
}
}
}
}
} | 14.576923 | 41 | 0.480211 |
5db5626505d6469b9768f541fdce5156b9001b21 | 432 | package eann.genetics.operators.util;
public record DesirabilityPair<T>(T element, double desirability) implements Comparable<DesirabilityPair<T>> {
@Override
public int compareTo(DesirabilityPair<T> o) {
return Double.compare(desirability, o.desirability);
}
public static <T> DesirabilityPair<T> of(T element, double desirability) {
return new DesirabilityPair<>(element, desirability);
}
}
| 30.857143 | 110 | 0.726852 |
b772ea05b1174d32468ee81b9ea67b1fb2ab1bd4 | 2,137 | package org.wso2.andes.server.virtualhost;
import org.wso2.andes.management.common.mbeans.ManagedAMQChannel;
import org.wso2.andes.server.AMQChannel;
import org.wso2.andes.server.management.AMQManagedObject;
import org.wso2.andes.transport.flow.control.FlowControlConstants;
import javax.management.MBeanNotificationInfo;
import javax.management.NotCompliantMBeanException;
import javax.management.Notification;
import javax.management.ObjectName;
import javax.management.monitor.MonitorNotification;
public class AMQChannelMBean extends AMQManagedObject implements ManagedAMQChannel {
private AMQChannel channel;
private long notificationSequence = 0;
public AMQChannelMBean(AMQChannel channel) throws NotCompliantMBeanException {
super(ManagedAMQChannel.class, ManagedAMQChannel.TYPE);
this.channel = channel;
}
@Override
public String getObjectInstanceName() {
return ObjectName.quote(getName());
}
/**
* Returns metadata of the Notifications sent by this MBean.
*/
@Override
public MBeanNotificationInfo[] getNotificationInfo()
{
String[] notificationTypes = new String[] { MonitorNotification.THRESHOLD_VALUE_EXCEEDED };
String name = MonitorNotification.class.getName();
String description = "Per connection message processing rate threshold exceeded";
MBeanNotificationInfo info = new MBeanNotificationInfo(notificationTypes, name, description);
return new MBeanNotificationInfo[] { info };
}
private AMQChannel getAMQChannel() {
return channel;
}
@Override
public void thresholdExceeded(int count) throws Exception {
_broadcaster.sendNotification(
new Notification(
FlowControlConstants.FLOW_CONTROL_PER_CONNECTION_MESSAGE_THRESHOLD_EXCEEDED,
this,
++notificationSequence,
"Per connection message threshold exceeded"
)
);
}
@Override
public String getName() {
return "AMQChannel" + channel.getId();
}
}
| 32.876923 | 101 | 0.705194 |
9e1427dcc71723299c6159209076979f93f6c191 | 1,546 | package io.sphere.sdk.orders.messages;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.sphere.sdk.messages.GenericMessageImpl;
import io.sphere.sdk.messages.MessageDerivateHint;
import io.sphere.sdk.messages.UserProvidedIdentifiers;
import io.sphere.sdk.orders.Order;
import java.time.ZonedDateTime;
@JsonDeserialize(as = OrderDeletedMessage.class)//important to override annotation in Message class
public final class OrderDeletedMessage extends GenericMessageImpl<Order> implements SimpleOrderMessage {
public static final String MESSAGE_TYPE = "OrderDeleted";
public static final MessageDerivateHint<OrderDeletedMessage> MESSAGE_HINT =
MessageDerivateHint.ofSingleMessageType(MESSAGE_TYPE, OrderDeletedMessage.class, Order.referenceTypeId());
private final Order order;
@JsonCreator
private OrderDeletedMessage(final String id, final Long version, final ZonedDateTime createdAt, final ZonedDateTime lastModifiedAt,
final JsonNode resource, final Long sequenceNumber, final Long resourceVersion, final String type, final UserProvidedIdentifiers resourceUserProvidedIdentifiers, final Order order) {
super(id, version, createdAt, lastModifiedAt, resource, sequenceNumber, resourceVersion, type,resourceUserProvidedIdentifiers, Order.class);
this.order = order;
}
public Order getOrder() {
return order;
}
}
| 44.171429 | 214 | 0.788486 |
2d1474eef0c7c7f94070ea564f102f62211ebbef | 3,829 | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.components.signin;
import static org.mockito.Mockito.verify;
import android.accounts.Account;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.chromium.base.test.BaseRobolectricTestRunner;
import org.chromium.components.signin.AccountManagerFacade.ChildAccountStatusListener;
import org.chromium.components.signin.test.util.FakeAccountManagerFacade;
import java.util.Collections;
import java.util.List;
/** Unit tests for {@link AccountUtils} */
@RunWith(BaseRobolectricTestRunner.class)
public class AccountUtilsTest {
private static final Account CHILD_ACCOUNT1 = AccountUtils.createAccountFromName(
FakeAccountManagerFacade.generateChildEmail("account1@gmail.com"));
private static final Account CHILD_ACCOUNT2 = AccountUtils.createAccountFromName(
FakeAccountManagerFacade.generateChildEmail("account2@gmail.com"));
private static final Account ADULT_ACCOUNT1 =
AccountUtils.createAccountFromName("adult.account1@gmail.com");
private static final Account ADULT_ACCOUNT2 =
AccountUtils.createAccountFromName("adult.account2@gmail.com");
private static final Account EDU_ACCOUNT =
AccountUtils.createAccountFromName("edu.account1@school.com");
private final FakeAccountManagerFacade mFakeFacade = new FakeAccountManagerFacade();
@Rule
public final MockitoRule mMockitoRule = MockitoJUnit.rule();
@Mock
private ChildAccountStatusListener mListenerMock;
@Test
public void testChildAccountStatusWhenNoAccountsOnDevice() {
AccountUtils.checkChildAccountStatus(mFakeFacade, Collections.emptyList(), mListenerMock);
verify(mListenerMock).onStatusReady(ChildAccountStatus.NOT_CHILD, null);
}
@Test
public void testChildAccountStatusWhenFirstAccountIsChildAndSecondIsEdu() {
// This is a supported configuration (where the second account might be an EDU account).
AccountUtils.checkChildAccountStatus(
mFakeFacade, List.of(CHILD_ACCOUNT1, EDU_ACCOUNT), mListenerMock);
verify(mListenerMock).onStatusReady(ChildAccountStatus.REGULAR_CHILD, CHILD_ACCOUNT1);
}
@Test
public void testChildAccountStatusWhenFirstAccountIsEduAndSecondIsChild() {
// This is an unsupported configuration (the Kids Module ensures that if a child account
// is present then it must be the default one). This test is here for completeness.
AccountUtils.checkChildAccountStatus(
mFakeFacade, List.of(EDU_ACCOUNT, CHILD_ACCOUNT1), mListenerMock);
verify(mListenerMock).onStatusReady(ChildAccountStatus.NOT_CHILD, null);
}
@Test
public void testChildAccountStatusWhenTwoAdultAccountsOnDevice() {
AccountUtils.checkChildAccountStatus(
mFakeFacade, List.of(ADULT_ACCOUNT1, ADULT_ACCOUNT2), mListenerMock);
verify(mListenerMock).onStatusReady(ChildAccountStatus.NOT_CHILD, null);
}
@Test
public void testChildAccountStatusWhenOnlyOneAdultAccountOnDevice() {
AccountUtils.checkChildAccountStatus(mFakeFacade, List.of(ADULT_ACCOUNT1), mListenerMock);
verify(mListenerMock).onStatusReady(ChildAccountStatus.NOT_CHILD, null);
}
@Test
public void testChildAccountStatusWhenOnlyOneChildAccountOnDevice() {
AccountUtils.checkChildAccountStatus(mFakeFacade, List.of(CHILD_ACCOUNT1), mListenerMock);
verify(mListenerMock).onStatusReady(ChildAccountStatus.REGULAR_CHILD, CHILD_ACCOUNT1);
}
}
| 43.022472 | 98 | 0.765996 |
cc5fbadf11b390ff2ea329d893d35ea431fa87a6 | 4,450 | package com.coderman.controller.business;
import com.coderman.business.service.ProductCategoryService;
import com.coderman.common.annotation.ControllerEndpoint;
import com.coderman.common.response.ResponseBean;
import com.coderman.common.vo.business.ProductCategoryTreeNodeVO;
import com.coderman.common.vo.business.ProductCategoryVO;
import com.coderman.common.vo.system.PageVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 物资分类管理
*
* @Author zhangyukang
* @Date 2020/3/16 17:16
* @Version 1.0
**/
@Api(tags = "物资类别接口")
@RestController
@RequestMapping("/productCategory")
public class ProductCategoryController {
@Autowired
private ProductCategoryService productCategoryService;
/**
* 物资分类列表
*
* @return
*/
@ApiOperation(value = "分类列表", notes = "物资分类列表,根据物资分类名模糊查询")
@GetMapping("/findProductCategoryList")
public ResponseBean findProductCategoryList(
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize") Integer pageSize,
ProductCategoryVO productCategoryVO) {
PageVO<ProductCategoryVO> departmentsList = productCategoryService.findProductCategoryList(pageNum, pageSize, productCategoryVO);
return ResponseBean.success(departmentsList);
}
/**
* 分类树形结构(分页)
*
* @return
*/
@ApiOperation(value = "分类树形结构")
@GetMapping("/categoryTree")
public ResponseBean categoryTree(@RequestParam(value = "pageNum", required = false) Integer pageNum,
@RequestParam(value = "pageSize", required = false) Integer pageSize) {
PageVO<ProductCategoryTreeNodeVO> pageVO = productCategoryService.categoryTree(pageNum, pageSize);
return ResponseBean.success(pageVO);
}
/**
* 获取父级分类树:2级树
*
* @return
*/
@ApiOperation(value = "父级分类树")
@GetMapping("/getParentCategoryTree")
public ResponseBean getParentCategoryTree() {
List<ProductCategoryTreeNodeVO> parentTree = productCategoryService.getParentCategoryTree();
return ResponseBean.success(parentTree);
}
/**
* 查询所有分类
*
* @return
*/
@ApiOperation(value = "所有分类")
@GetMapping("/findAll")
public ResponseBean findAll() {
List<ProductCategoryVO> productCategoryVOS = productCategoryService.findAll();
return ResponseBean.success(productCategoryVOS);
}
/**
* 添加物资分类
*
* @return
*/
@ControllerEndpoint(exceptionMessage = "物资分类添加失败", operation = "物资分类添加")
@RequiresPermissions({"productCategory:add"})
@ApiOperation(value = "添加分类")
@PostMapping("/add")
public ResponseBean add(@RequestBody @Validated ProductCategoryVO productCategoryVO) {
productCategoryService.add(productCategoryVO);
return ResponseBean.success();
}
/**
* 编辑物资分类
*
* @param id
* @return
*/
@ApiOperation(value = "编辑分类")
@RequiresPermissions({"productCategory:edit"})
@GetMapping("/edit/{id}")
public ResponseBean edit(@PathVariable Long id) {
ProductCategoryVO productCategoryVO = productCategoryService.edit(id);
return ResponseBean.success(productCategoryVO);
}
/**
* 更新物资分类
*
* @return
*/
@ControllerEndpoint(exceptionMessage = "物资分类更新失败", operation = "物资分类更新")
@ApiOperation(value = "更新分类")
@RequiresPermissions({"productCategory:update"})
@PutMapping("/update/{id}")
public ResponseBean update(@PathVariable Long id, @RequestBody @Validated ProductCategoryVO productCategoryVO) {
productCategoryService.update(id, productCategoryVO);
return ResponseBean.success();
}
/**
* 删除物资分类
*
* @param id
* @return
*/
@ControllerEndpoint(exceptionMessage = "物资分类删除失败", operation = "物资分类删除")
@ApiOperation(value = "删除分类")
@RequiresPermissions({"productCategory:delete"})
@DeleteMapping("/delete/{id}")
public ResponseBean delete(@PathVariable Long id) {
productCategoryService.delete(id);
return ResponseBean.success();
}
}
| 30.689655 | 137 | 0.682697 |
2b85a8e86b4466f4058a826d8478a91bd79fa220 | 1,006 | /*
* 1.ask interviewer to resolve ambiguity - what data type? how much data? what
* assumption? who is users?
* 1.1 [Q1] -
* 1.2 [Q2] -
* 1.3 [Q3] -
*
* 2.design algorithm - space & time complexity? what happen if huge amount of
* data? did u make right trade-off? what scenario has different trade-off?
* 2.1 [Idea] -
* 2.2 [Time complexity] - O()
* 2.3 [Space complexity] - O()
* 2.4 [If huge amount of data] -
*
* 3.write pseudocode first, but make sure tell interviewer you will write real
* code later
* 3.1 Write code on paper
* 3.2 Test code on paper
*
* 4.write code on a moderate pace
* 4.1 Type code as-is on paper into computer, list all compile and other errors
*
* 5.test code and carefully fix mistakes - extreme case, 0, negative, null,
* max, min? user input error (null, negative value)? general case?
* 5.1[Unit tests]
*/
public class Template {
public static void test() {
}
public static void main(String[] argv) {
test();
}
}
| 27.189189 | 80 | 0.646123 |
6032f181efc2b82b1955ba3e5bb5769b8c7a8731 | 53 | /**
*
* @author Dave
*
*/
package views.formdata; | 8.833333 | 23 | 0.566038 |
e254e9be4b7c855acab39a7053f6f510a25d539a | 1,971 | /*******************************************************************************
* Copyright 2009-2018 Exactpro (Exactpro Systems Limited)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.exactprosystems.jf.tool.wizard.related.refactor;
import com.exactprosystems.jf.api.common.i18n.R;
import com.exactprosystems.jf.api.wizard.WizardCommand;
import com.exactprosystems.jf.documents.matrix.Matrix;
import com.exactprosystems.jf.documents.matrix.parser.Tokens;
import com.exactprosystems.jf.tool.Common;
import com.exactprosystems.jf.tool.wizard.CommandBuilder;
import java.util.List;
public class RefactorSetField extends Refactor
{
private List<WizardCommand> command;
private String message;
public RefactorSetField(Matrix matrix, Tokens token, String value, List<Integer> itemIds)
{
int size = itemIds.size();
this.message = String.format(R.REFACTOR_SET_FIELD_MESSAGE.get(), token, value, Common.getRelativePath(matrix.getNameProperty().get()), size);
CommandBuilder builder = CommandBuilder.start();
itemIds.forEach(c -> builder.findAndHandleMatrixItem(matrix, c, i -> i.set(token, value)));
this.command = builder.build();
}
public List<WizardCommand> getCommands()
{
return this.command;
}
@Override
public String toString()
{
return this.message;
}
}
| 37.903846 | 150 | 0.674784 |
b2574f30eccdc1ecd1fc0926faa05f857e0f47d7 | 2,750 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.sdk.install.patch;
import com.android.annotations.NonNull;
import com.android.repository.api.LocalPackage;
import com.android.repository.api.ProgressIndicator;
import com.android.repository.api.RepoManager;
import com.android.repository.impl.installer.AbstractUninstaller;
import com.android.repository.io.FileOpUtils;
import java.nio.file.Path;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Generates a patch that deletes all the files in the given package.
*/
class PatchUninstaller extends AbstractUninstaller implements PatchOperation {
private final LocalPackage myPatcher;
private final Path myEmptyDir;
private Path myGeneratedPatch;
public PatchUninstaller(@NotNull LocalPackage p, @NotNull RepoManager mgr) {
super(p, mgr);
myPatcher = PatchInstallerUtil.getLatestPatcher(getRepoManager());
myEmptyDir = FileOpUtils.getNewTempDir("PatchUninstaller", p.getLocation().getFileSystem());
registerStateChangeListener((op, progress) -> {
if (getInstallStatus() == InstallStatus.COMPLETE) {
FileOpUtils.deleteFileOrFolder(getLocation(progress));
}
});
}
@NotNull
@Override
public LocalPackage getPatcher(@NotNull ProgressIndicator progressIndicator) {
return myPatcher;
}
@NotNull
@Override
public Path getNewFilesRoot() {
return myEmptyDir;
}
@NotNull
@Override
public String getNewVersionName() {
return "<None>";
}
@Override
@Nullable
public LocalPackage getExisting() {
return getPackage();
}
@Override
protected boolean doPrepare(@Nullable Path installTemp,
@NonNull ProgressIndicator progress) {
if (myPatcher == null) {
return false;
}
myGeneratedPatch = PatchInstallerUtil.generatePatch(this, installTemp, progress);
return myGeneratedPatch != null;
}
@Override
protected boolean doComplete(@Nullable Path installTemp,
@NotNull ProgressIndicator progress) {
return PatchInstallerUtil.installPatch(this, myGeneratedPatch, progress);
}
}
| 31.609195 | 96 | 0.735273 |
dbdbbace9145e3b45449c1289477972c4da23b1d | 6,625 | // Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 board;
import bitpattern.BitPattern;
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author michele
*/
public class GetFlipTest {
final GetFlip FLIPPER = GetFlip.load();
@Test
public void testFlip() {
Board board = new Board();
ArrayList<Long> possibleMoves = new ArrayList<>(Arrays.asList(
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "---X----\n"
+ "---X----\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"),
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "--------\n"
+ "--XX----\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"),
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"
+ "----XX--\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"),
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"
+ "----X---\n"
+ "----X---\n"
+ "--------\n"
+ "--------\n")));
for (long flip : possibleMoves) {
int move = Long.numberOfTrailingZeros(flip & ~(board.getPlayer() | board.getOpponent()));
long newFlip = FLIPPER.getFlip(move, board.getPlayer(), board.getOpponent());
if (flip != newFlip) {
System.out.println(board);
System.out.println(BitPattern.patternToString(flip));
System.out.println(BitPattern.patternToString(newFlip));
assert(false);
}
}
assertEquals(0, FLIPPER.getFlip(0, board.getPlayer(), board.getOpponent()));
}
@Test
public void testFlipManyDir() {
PossibleMovesFinderImproved movesFinder = new PossibleMovesFinderImproved();
Board board = new Board("--------\n"
+ "-O-O----\n"
+ "--XX--O-\n"
+ "---X-X--\n"
+ "---XX---\n"
+ "--------\n"
+ "--------\n"
+ "--------\n", false);
ArrayList<Long> possibleMoves = new ArrayList<>(Arrays.asList(
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "---X----\n"
+ "---X-X--\n"
+ "---XX---\n"
+ "---X----\n"
+ "--------\n"
+ "--------\n"),
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "--X-----\n"
+ "---X----\n"
+ "----X---\n"
+ "-----X--\n"
+ "--------\n"
+ "--------\n"),
BitPattern.parsePattern("--------\n"
+ "--------\n"
+ "--X-----\n"
+ "-X------\n"
+ "--------\n"
+ "--------\n"
+ "--------\n"
+ "--------\n")));
for (long flip : possibleMoves) {
int move = Long.numberOfTrailingZeros(flip & ~(board.getPlayer() | board.getOpponent()));
long newFlip = FLIPPER.getFlip(move, board.getPlayer(), board.getOpponent());
if (flip != newFlip) {
System.out.println(board);
System.out.println(BitPattern.patternToString(flip));
System.out.println(BitPattern.patternToString(newFlip));
assert(false);
}
}
}
@Test
public void testFindPossibleMovesRandom() {
PossibleMovesFinderImproved movesFinder = new PossibleMovesFinderImproved();
int n = 100000;
boolean movesFound[] = new boolean[64];
for (int i = 0; i < n; i++) {
Arrays.fill(movesFound, false);
Board board = Board.randomBoard();
long[] flips = movesFinder.possibleMoves(board);
for (long flip : flips) {
int move = Long.numberOfTrailingZeros(flip & ~(board.getPlayer() | board.getOpponent()));
long newFlip = 0;
if (board.getEmptySquares() == 1) {
newFlip = FLIPPER.getFlipLast(move, board.getOpponent());
newFlip = newFlip & ~board.getPlayer();
} else {
newFlip = FLIPPER.getFlip(move, board.getPlayer(), board.getOpponent());
}
if (flip != newFlip) {
System.out.println(board);
System.out.println(board.getEmptySquares());
System.out.println(BitPattern.patternToString(flip));
System.out.println(BitPattern.patternToString(newFlip));
assert(false);
}
movesFound[move] = true;
}
for (int move = 0; move < movesFound.length; ++move) {
if (!movesFound[move]) {
if (FLIPPER.getFlip(move, board.getPlayer(), board.getOpponent()) != 0) {
System.out.println(board);
System.out.println(move);
assert(false);
}
}
}
}
}
}
| 38.74269 | 97 | 0.393962 |
2169a5a92ad279cc8c5b8fe04441a026e7b0a45f | 2,134 | package org.artifactory.storage.db.upgrades.versions;
import org.apache.commons.lang.RandomStringUtils;
import org.artifactory.storage.db.DbType;
import org.artifactory.storage.db.itest.DbTestUtils;
import org.artifactory.storage.db.upgrades.common.UpgradeBaseTest;
import org.artifactory.storage.db.version.ArtifactoryDBVersion;
import org.artifactory.version.ArtifactoryVersion;
import org.testng.annotations.BeforeClass;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import static org.artifactory.storage.db.version.ArtifactoryDBVersion.convert;
import static org.artifactory.storage.db.version.ArtifactoryDBVersion.v100;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertFalse;
/**
* Author: gidis
*/
public class ArtifactoryDBVersionTest extends UpgradeBaseTest {
@BeforeClass
@Override
protected void springTestContextPrepareTestInstance() throws Exception {
super.springTestContextPrepareTestInstance();
rollBackTo300Version();
convert(getFromVersion(v100), jdbcHelper, storageProperties.getDbType());
}
public void test300DBChanges() throws IOException, SQLException {
// Now the DB is like in 3.0.x, should be missing the new tables of 3.1.x
try (Connection connection = jdbcHelper.getDataSource().getConnection()) {
assertFalse(DbTestUtils.isTableMissing(connection));
}
}
public void test311DBChanges() throws IOException, SQLException {
try (Connection connection = jdbcHelper.getDataSource().getConnection()) {
assertEquals(DbTestUtils.getColumnSize(connection, "node_props", "prop_value"), 4000);
if (storageProperties.getDbType() == DbType.MSSQL) {
return; // RTFACT-5768
}
jdbcHelper.executeUpdate("INSERT INTO node_props VALUES(?, ?, ?, ?)",
15, 15, "longProp", RandomStringUtils.randomAscii(3999));
}
}
private ArtifactoryVersion getFromVersion(ArtifactoryDBVersion version) {
return version.getComparator().getFrom();
}
}
| 38.107143 | 98 | 0.732427 |
97a925699c85c4d679a944ed91327e31adbc60df | 1,041 | /*
* Copyright (C) 2019 Center for Information Management, Inc.
*
* This program is proprietary.
* Redistribution without permission is strictly prohibited.
* For more information, contact <http://www.ciminc.com>
*/
package com.patterns.creational.factory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
*
* @author david
* @version $LastChangedRevision $LastChangedDate Last Modified Author:
* $LastChangedBy
*/
public class ShapeFactory {
private static final Logger log = LoggerFactory.getLogger(ShapeFactory.class);
//use getShape method to get object of type shape
public Shape getShape(String shapeType) {
if (shapeType == null) {
return null;
}
if (shapeType.equalsIgnoreCase("CIRCLE")) {
return new Circle();
} else if (shapeType.equalsIgnoreCase("RECTANGLE")) {
return new Rectangle();
} else if (shapeType.equalsIgnoreCase("SQUARE")) {
return new Square();
}
return null;
}
}
| 24.785714 | 82 | 0.6561 |
a8455e46ce048525fd8113433824709e2e489d8c | 4,355 | package com.infochimps.wukong.storm;
import java.util.Map;
import java.util.HashMap;
import java.util.Arrays;
import org.apache.log4j.Logger;
import backtype.storm.generated.StormTopology;
import backtype.storm.tuple.Fields;
import storm.trident.Stream;
import storm.trident.TridentTopology;
import storm.trident.operation.BaseFunction;
import storm.trident.operation.TridentCollector;
import backtype.storm.tuple.Values;
import storm.trident.tuple.TridentTuple;
public class TopologyBuilder extends Builder {
private static class CombineMetadata extends BaseFunction {
@Override
public void execute(TridentTuple tuple, TridentCollector collector) {
String content = tuple.getStringByField("content");
String metadata = tuple.getStringByField("metadata");
Integer lineNumber = tuple.getIntegerByField("linenumber");
LOG.debug(String.format("%s\t%s\t%s", metadata, content, lineNumber));
collector.emit(new Values(String.format("%s\t%s\t%s", metadata, content, lineNumber)));
}
}
private SpoutBuilder spoutBuilder;
private DataflowBuilder dataflowBuilder;
private StateBuilder stateBuilder;
static Logger LOG = Logger.getLogger(TopologyBuilder.class);
public TopologyBuilder() {
this.spoutBuilder = new SpoutBuilder();
this.dataflowBuilder = new DataflowBuilder(spoutBuilder);
this.stateBuilder = new StateBuilder();
}
@Override
public Boolean valid() {
if (topologyName() == null) {
LOG.error("Must set a topology name using the " + TOPOLOGY_NAME + " property");
return false;
}
if (!spoutBuilder.valid()) { return false; }
if (!dataflowBuilder.valid()) { return false; }
if (!stateBuilder.valid()) { return false; }
return true;
}
@Override
public void logInfo() {
LOG.info("\n");
spoutBuilder.logInfo();
dataflowBuilder.logInfo();
stateBuilder.logInfo();
}
public StormTopology topology() {
TridentTopology top = new TridentTopology();
Stream spoutOutput = top.newStream(topologyName(), spoutBuilder.spout())
.parallelismHint(spoutBuilder.inputParallelism());
Stream possiblyShuffledSpoutOutput;
if (needToShuffleSpoutOutput()) {
possiblyShuffledSpoutOutput = spoutOutput.shuffle();
} else {
possiblyShuffledSpoutOutput = spoutOutput;
}
Stream dataflowInput;
if (spoutBuilder.isBlobSpout()) {
dataflowInput = possiblyShuffledSpoutOutput.each(new Fields("content", "metadata", "linenumber"), new CombineMetadata(), new Fields("str"));
} else {
dataflowInput = possiblyShuffledSpoutOutput;
}
Stream dataflowOutput = dataflowInput.each(new Fields("str"), dataflowBuilder.dataflow(), new Fields("_wukong"))
.parallelismHint(dataflowBuilder.dataflowParallelism());
dataflowOutput.partitionPersist(stateBuilder.state(), new Fields("_wukong"), stateBuilder.updater());
return top.build();
}
public static String usage() {
String s = "\n"
+ "Dynamically assemble and launch a parametrized Storm topology that\n"
+ "embeds Wukong dataflow(s). The current overall \"shape\" of the\n"
+ "topology is\n"
+ "\n"
+ " spout -> wukong dataflow -> state\n"
+ "\n"
+ "The available spouts read from Kafka or S3. The only available state\n"
+ "is Kafka.\n"
+ "\n"
+ "TOPOLOGY OPTIONS\n"
+ "\n"
+ "The following options can be used for any topology:\n"
+ "\n"
+ " " + String.format("%10s", TOPOLOGY_NAME) + " Name of the Storm topology that will be launched (Required)\n"
+ " " + String.format("%10s", KAFKA_HOSTS) + " Comma-separated list of Kafka host (and optional port) pairs (Default: " + DEFAULT_KAFKA_HOSTS + ")\n"
+ " " + String.format("%10s", ZOOKEEPER_HOSTS) + " Comma-separated list of Zookeeper host (and optional port) pairs (Default: " + DEFAULT_ZOOKEEPER_HOSTS + ")\n"
+ "\n"
+ SpoutBuilder.usage()
+ "\n"
+ DataflowBuilder.usage()
+ "\n"
+ StateBuilder.usage()
+ "\n";
return s;
}
private Boolean needToShuffleSpoutOutput() {
return (dataflowBuilder.dataflowParallelism() > spoutBuilder.inputParallelism());
}
public static String TOPOLOGY_NAME = "wukong.topology";
public String topologyName() {
return prop(TOPOLOGY_NAME);
}
}
| 33.244275 | 169 | 0.685189 |
aa59b300adf0209592221fa1e0ac6a915b0bb3f8 | 1,422 | /**
* Written by Azul Systems, and released to the public domain,
* as explained at http://creativecommons.org/publicdomain/zero/1.0/
*/
package org.HdrHistogram.HistogramLogAnalyzer.charts;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Random;
class ColorHelper {
private static ArrayList<Color> colors = new ArrayList<Color>();
static {
colors.add(Color.RED);
colors.add(Color.BLUE);
colors.add(Color.GREEN);
colors.add(Color.MAGENTA);
colors.add(Color.CYAN);
}
private static void ensureSize(int size) {
while (colors.size() < size) {
Random r = new Random();
colors.add(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
}
}
static Color getColor(int i) {
ensureSize(i + 1);
return colors.get(i);
}
static Color getSLAColor() {
return new Color(255, 204, 102);
}
static Color getHPLColor(String percentileString) {
switch (percentileString) {
case "99%":
case "99.0%":
return Color.GREEN;
case "99.9%":
return Color.BLUE;
case "99.99%":
return new Color(128, 0, 128); // purple
case "Max":
return Color.RED;
}
throw new RuntimeException("unexpected HPL: "+percentileString);
}
}
| 25.854545 | 82 | 0.57384 |
283616cb77faa3106f9d557a57a35f891086ddb5 | 1,221 | package com.example.lib_lyn;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectUtils {
public static boolean isMobile(Context context) {
if (!isConnected(context))
{
return false;
}
ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connMgr.getActiveNetworkInfo();
if (info == null) {
return false;
}
return ConnectivityManager.TYPE_MOBILE == info.getType();
}
public static boolean isWIFI(Context context) {
if (!isConnected(context))
{
return false;
}
ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connMgr.getActiveNetworkInfo();
if (info == null) {
return false;
}
return ConnectivityManager.TYPE_WIFI == info.getType();
}
public static boolean isConnected(Context context) {
ConnectivityManager connMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connMgr.getActiveNetworkInfo();
if (info == null) {
return false;
}
return info.isAvailable();
}
}
| 25.4375 | 61 | 0.744472 |
530ea734aadc7867f4d0efd10a35965cb7ec9ddc | 1,019 | package com.github.erav.treemod;
import com.github.erav.treemod.traverse.KeysPrintAction;
import net.minidev.json.JSONObject;
import net.minidev.json.JSONValue;
import com.github.erav.treemod.traverse.JSONTraverser;
import net.minidev.json.parser.ParseException;
import org.junit.Test;
/**
* @author adoneitan@gmail.com
* @since 30 May 2016
*/
public class KeysPrintActionTest
{
@Test
public void testTraverse() throws ParseException
{
KeysPrintAction p = new KeysPrintAction();
JSONTraverser t = new JSONTraverser(p);
JSONObject jo = (JSONObject) JSONValue.parseWithException(
"{" +
"\"k0\":{" +
"\"k01\":{" +
"\"k011\":\"v2\"" +
"}" +
"}," +
"\"k1\":{" +
"\"k11\":{" +
"\"k111\":\"v5\"" +
"}," +
"\"k12\":{" +
"\"k121\":\"v5\"" +
"}" +
"}," +
"\"k3\":{" +
"\"k31\":{" +
"\"k311\":\"v5\"," +
"\"k312\":\"v6\"," +
"\"k313\":\"v7\"" +
"}" +
"}" +
"}"
);
t.traverse(jo);
}
} | 21.680851 | 60 | 0.52208 |
f802f2984da01cadcb81c6ab466b4273cc0ac766 | 8,539 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.media;
import android.content.Context;
import android.graphics.ImageFormat;
import android.util.Log;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
/**
* This class extends the VideoCapture base class for manipulating a Tango
* device's cameras, namely the associated Depth (z-Buffer), Fisheye and back-
* facing 4MP video capture devices. These devices are differentiated via the
* |id| passed on constructor, according to the index correspondence in
* |s_CAM_PARAMS|; all devices |id| are index 0 towards the parent VideoCapture.
**/
@SuppressWarnings("deprecation")
public class VideoCaptureTango extends VideoCaptureCamera {
private static class CamParams {
final int mId;
final String mName;
final int mWidth;
final int mHeight;
CamParams(int id, String name, int width, int height) {
mId = id;
mName = name;
mWidth = width;
mHeight = height;
}
}
private ByteBuffer mFrameBuffer = null;
private final int mTangoCameraId;
// The indexes must coincide with |CAM_PARAMS| defined below.
private static final int DEPTH_CAMERA_ID = 0;
private static final int FISHEYE_CAMERA_ID = 1;
private static final int FOURMP_CAMERA_ID = 2;
private static final CamParams CAM_PARAMS[] = {
new CamParams(DEPTH_CAMERA_ID, "depth", 320, 240),
new CamParams(FISHEYE_CAMERA_ID, "fisheye", 640, 480),
new CamParams(FOURMP_CAMERA_ID, "4MP", 1280, 720) };
// SuperFrame size definitions. Note that total size is the amount of lines
// multiplied by 3/2 due to Chroma components following.
private static final int SF_WIDTH = 1280;
private static final int SF_HEIGHT = 1168;
private static final int SF_FULL_HEIGHT = SF_HEIGHT * 3 / 2;
private static final int SF_LINES_HEADER = 16;
private static final int SF_LINES_FISHEYE = 240;
private static final int SF_LINES_RESERVED = 80; // Spec says 96.
private static final int SF_LINES_DEPTH = 60;
private static final int SF_LINES_DEPTH_PADDED = 112; // Spec says 96.
private static final int SF_LINES_BIGIMAGE = 720;
private static final int SF_OFFSET_4MP_CHROMA = 112;
private static final byte CHROMA_ZERO_LEVEL = 127;
private static final String TAG = "VideoCaptureTango";
static int numberOfCameras() {
return CAM_PARAMS.length;
}
static String getName(int index) {
if (index >= CAM_PARAMS.length) return "";
return CAM_PARAMS[index].mName;
}
static CaptureFormat[] getDeviceSupportedFormats(int id) {
ArrayList<CaptureFormat> formatList = new ArrayList<CaptureFormat>();
if (id == DEPTH_CAMERA_ID) {
formatList.add(new CaptureFormat(320, 180, 5, ImageFormat.YV12));
} else if (id == FISHEYE_CAMERA_ID) {
formatList.add(new CaptureFormat(640, 480, 30, ImageFormat.YV12));
} else if (id == FOURMP_CAMERA_ID) {
formatList.add(new CaptureFormat(1280, 720, 20, ImageFormat.YV12));
}
return formatList.toArray(new CaptureFormat[formatList.size()]);
}
VideoCaptureTango(Context context,
int id,
long nativeVideoCaptureDeviceAndroid) {
// All Tango cameras are like the back facing one for the generic VideoCapture code.
super(context, 0, nativeVideoCaptureDeviceAndroid);
mTangoCameraId = id;
}
@Override
protected void setCaptureParameters(
int width,
int height,
int frameRate,
android.hardware.Camera.Parameters cameraParameters) {
mCaptureFormat = new CaptureFormat(CAM_PARAMS[mTangoCameraId].mWidth,
CAM_PARAMS[mTangoCameraId].mHeight,
frameRate,
ImageFormat.YV12);
// Connect Tango SuperFrame mode. Available sf modes are "all",
// "big-rgb", "small-rgb", "depth", "ir".
cameraParameters.set("sf-mode", "all");
}
@Override
protected void allocateBuffers() {
mFrameBuffer = ByteBuffer.allocateDirect(
mCaptureFormat.mWidth * mCaptureFormat.mHeight * 3 / 2);
// Prefill Chroma to their zero-equivalent for the cameras that only
// provide Luma component.
Arrays.fill(mFrameBuffer.array(), CHROMA_ZERO_LEVEL);
}
@Override
protected void setPreviewCallback(android.hardware.Camera.PreviewCallback cb) {
mCamera.setPreviewCallback(cb);
}
@Override
public void onPreviewFrame(byte[] data, android.hardware.Camera camera) {
mPreviewBufferLock.lock();
try {
if (!mIsRunning) return;
if (data.length == SF_WIDTH * SF_FULL_HEIGHT) {
if (mTangoCameraId == DEPTH_CAMERA_ID) {
int sizeY = SF_WIDTH * SF_LINES_DEPTH;
int startY =
SF_WIDTH * (SF_LINES_HEADER + SF_LINES_FISHEYE + SF_LINES_RESERVED);
// Depth is composed of 16b samples in which only 12b are
// used. Throw away lowest 4 resolution bits. Android
// platforms are big endian, LSB in lowest address. In this
// case Chroma components are unused. No need to write them
// explicitly since they're filled to 128 on creation.
byte depthsample;
for (int j = startY; j < startY + 2 * sizeY; j += 2) {
depthsample = (byte) ((data[j + 1] << 4) | ((data[j] & 0xF0) >> 4));
mFrameBuffer.put(depthsample);
}
for (int j = 0; j < mCaptureFormat.mWidth * mCaptureFormat.mHeight - sizeY;
++j) {
mFrameBuffer.put((byte) 0);
}
} else if (mTangoCameraId == FISHEYE_CAMERA_ID) {
int sizeY = SF_WIDTH * SF_LINES_FISHEYE;
int startY = SF_WIDTH * SF_LINES_HEADER;
// Fisheye is black and white so Chroma components are unused. No need to write
// them explicitly since they're filled to 128 on creation.
ByteBuffer.wrap(data, startY, sizeY).get(mFrameBuffer.array(), 0, sizeY);
} else if (mTangoCameraId == FOURMP_CAMERA_ID) {
int startY = SF_WIDTH * (SF_LINES_HEADER + SF_LINES_FISHEYE
+ SF_LINES_RESERVED + SF_LINES_DEPTH_PADDED);
int sizeY = SF_WIDTH * SF_LINES_BIGIMAGE;
// The spec is completely inaccurate on the location, sizes
// and format of these channels.
int startU = SF_WIDTH * (SF_HEIGHT + SF_OFFSET_4MP_CHROMA);
int sizeU = SF_WIDTH * SF_LINES_BIGIMAGE / 4;
int startV = (SF_WIDTH * SF_HEIGHT * 5 / 4) + SF_WIDTH * SF_OFFSET_4MP_CHROMA;
int sizeV = SF_WIDTH * SF_LINES_BIGIMAGE / 4;
// Equivalent to the following |for| loop but much faster:
// for (int i = START; i < START + SIZE; ++i)
// mFrameBuffer.put(data[i]);
ByteBuffer.wrap(data, startY, sizeY)
.get(mFrameBuffer.array(), 0, sizeY);
ByteBuffer.wrap(data, startU, sizeU)
.get(mFrameBuffer.array(), sizeY, sizeU);
ByteBuffer.wrap(data, startV, sizeV)
.get(mFrameBuffer.array(), sizeY + sizeU, sizeV);
} else {
Log.e(TAG, "Unknown camera, #id: " + mTangoCameraId);
return;
}
mFrameBuffer.rewind(); // Important!
nativeOnFrameAvailable(mNativeVideoCaptureDeviceAndroid,
mFrameBuffer.array(),
mFrameBuffer.capacity(),
getCameraRotation());
}
} finally {
mPreviewBufferLock.unlock();
}
}
}
| 44.942105 | 99 | 0.585549 |
b5fae553270a8fb5cbf7cee8586ff78bf78f4fa6 | 340 | package com.javacreed.api.domain.primitives.jpa.optional;
import java.math.BigDecimal;
import com.javacreed.api.domain.primitives.optional.BigDecimalBasedDomainPrimitive;
public abstract class BigDecimalBasedAttributeConverter<T extends BigDecimalBasedDomainPrimitive>
extends ObjectBasedAttributeConverter<T, BigDecimal> {}
| 37.777778 | 98 | 0.838235 |
edec5823a3dcafe5f75334cdd5653bb41855dce4 | 9,119 | package com.composum.sling.core.setup.util;
import com.composum.sling.core.usermanagement.core.UserManagementService;
import org.apache.jackrabbit.api.JackrabbitSession;
import org.apache.jackrabbit.api.security.user.Authorizable;
import org.apache.jackrabbit.api.security.user.Group;
import org.apache.jackrabbit.api.security.user.UserManager;
import org.apache.jackrabbit.commons.cnd.CndImporter;
import org.apache.jackrabbit.commons.cnd.ParseException;
import org.apache.jackrabbit.vault.fs.io.Archive;
import org.apache.jackrabbit.vault.packaging.InstallContext;
import org.apache.jackrabbit.vault.packaging.PackageException;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.RepositoryException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
public class SetupUtil {
private static final Logger LOG = LoggerFactory.getLogger(SetupUtil.class);
/**
* Creates or updates a set of groups, users and system users
*
* @param ctx the installation context
* @param groups map of group names (including path, e.g. composum/plaform/composum-platform-users) to list of
* users (have to exist already)
* @param systemUsers map of system user names (including path, e.g. system/composum/platform/composum-platform-service)
* to list of group names (without path). The groups have to exist already, or be created with parameter groups
* @param users map of user names (including path) to list of group names (without path). The groups
* have to exist already, or be created with parameter groups
* @throws PackageException
*/
public static void setupGroupsAndUsers(InstallContext ctx,
Map<String, List<String>> groups,
Map<String, List<String>> systemUsers,
Map<String, List<String>> users) throws PackageException {
UserManagementService userManagementService = getService(UserManagementService.class);
try {
JackrabbitSession session = (JackrabbitSession) ctx.getSession();
UserManager userManager = session.getUserManager();
if (groups != null) {
for (Map.Entry<String, List<String>> entry : groups.entrySet()) {
Group group = userManagementService.getOrCreateGroup(session, userManager, entry.getKey());
if (group != null) {
for (String memberName : entry.getValue()) {
userManagementService.assignToGroup(session, userManager, memberName, group);
}
}
}
session.save();
}
if (systemUsers != null) {
for (Map.Entry<String, List<String>> entry : systemUsers.entrySet()) {
Authorizable user = userManagementService.getOrCreateUser(session, userManager, entry.getKey(), true);
if (user != null) {
for (String groupName : entry.getValue()) {
userManagementService.assignToGroup(session, userManager, user, groupName);
}
}
}
session.save();
}
if (users != null) {
for (Map.Entry<String, List<String>> entry : users.entrySet()) {
Authorizable user = userManagementService.getOrCreateUser(session, userManager, entry.getKey(), false);
if (user != null) {
for (String groupName : entry.getValue()) {
userManagementService.assignToGroup(session, userManager, user, groupName);
}
}
}
session.save();
}
} catch (RepositoryException | RuntimeException rex) {
LOG.error(rex.getMessage(), rex);
throw new PackageException(rex);
}
}
/**
* check a list of bundles (symbolic name, version) for the right version and active state
*
* @param ctx the package install context
* @param bundlesToCheck the 'list' to check; key: symbolic name, value: version
* @param waitToStartSeconds the seconds to wait to check start; must be greater than 1
* @param timeoutSeconds the timeout for the bundle check in seconds
* @throws PackageException if the check fails
*/
public static void checkBundles(InstallContext ctx, Map<String, String> bundlesToCheck,
int waitToStartSeconds, int timeoutSeconds)
throws PackageException {
try {
// wait to give the bundle installer a chance to install bundles
Thread.sleep(waitToStartSeconds * 1000);
} catch (InterruptedException ignore) {
}
LOG.info("Check bundles...");
BundleContext bundleContext = FrameworkUtil.getBundle(ctx.getSession().getClass()).getBundleContext();
int ready = 0;
for (int i = 0; i < timeoutSeconds; i++) {
ready = 0;
for (Bundle bundle : bundleContext.getBundles()) {
String version = bundlesToCheck.get(bundle.getSymbolicName());
if (version != null && version.equals(bundle.getVersion().toString())
&& bundle.getState() == Bundle.ACTIVE) {
ready++;
}
}
if (ready == bundlesToCheck.size()) {
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException ignore) {
}
}
if (ready < bundlesToCheck.size()) {
LOG.error("Checked bundles not ready - installation failed!");
throw new PackageException("bundles not ready");
} else {
LOG.info("Checked bundles are up and ready.");
}
}
/**
* retrieve a service during setup
*/
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> type) {
Bundle serviceBundle = FrameworkUtil.getBundle(type);
BundleContext serviceBundleContext = serviceBundle.getBundleContext();
ServiceReference serviceReference = serviceBundleContext.getServiceReference(type.getName());
return (T) serviceBundleContext.getService(serviceReference);
}
/**
* Updates existing nodetypes. This might be neccesary for changes in nodetypes.cnd, since the normal package installation does not change
* existing node types. It's probably sensible to do this only after checking that the current definition in the
* {@link javax.jcr.nodetype.NodeTypeManager} of the changed node type is not current.
*/
public static void updateNodeTypes(InstallContext ctx) throws PackageException {
Archive archive = ctx.getPackage().getArchive();
try {
try (InputStream stream = archive.openInputStream(archive.getEntry("/META-INF/vault/nodetypes.cnd"))) {
InputStreamReader cndReader = new InputStreamReader(stream);
CndImporter.registerNodeTypes(cndReader, ctx.getSession(), true);
}
} catch (ParseException | RepositoryException | IOException e) {
LOG.error("Failed to update node types.", e);
throw new PackageException("Failed to update node types.", e);
}
}
/**
* Updates existing nodetypes if an up to date check fails. This might be neccesary for changes in nodetypes.cnd, since the normal package installation does not change
* existing node types.
*
* @param upToDateCheck if this does return true, the update is skipped. Probably involves <code>ctx.getSession().getWorkspace().getNodeTypeManager()</code>.
*/
public static void updateNodeTypesConditionally(InstallContext ctx, Callable<Boolean> upToDateCheck) throws PackageException {
try {
if (!Boolean.TRUE.equals(upToDateCheck.call())) {
LOG.info("up to date check failed - updating node types.");
updateNodeTypes(ctx);
if (!Boolean.TRUE.equals(upToDateCheck.call())) {
LOG.error("up to date check still fails even after package installation!");
// That's probably a bug or obsolete check - we do not throw up here since this is likely not a showstopper
}
}
} catch (PackageException e) {
throw e;
} catch (Exception e) {
LOG.error("Error during current check", e);
}
}
}
| 47.494792 | 171 | 0.614322 |
214ebbe0e71ac31a4a158be67b1035e6f4d3442d | 3,559 | package util;
import exceptions.AutomationException;
import io.restassured.response.Response;
import org.apache.commons.exec.environment.EnvironmentUtils;
import org.openqa.selenium.remote.DesiredCapabilities;
import util.backend.GenericData;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Objects;
import java.util.Properties;
import static io.restassured.RestAssured.given;
public class LoaderBrowserstackLocalImpl implements Loader {
private static Properties properties;
private static final String FILE_PATH = "conf/environment.properties";
static {
try {
properties = new Properties();
properties.load(Objects.requireNonNull(EnvironmentUtils.class.getClassLoader().getResourceAsStream(FILE_PATH)));
} catch (Exception e) {
e.printStackTrace();
throw new AutomationException("Could not load environment setup");
}
}
public static String getUsername() {
return properties.getProperty("browserstack.username");
}
public static String getPassword() {
return properties.getProperty("browserstack.password");
}
@Override
public DesiredCapabilities loadCapabilities() {
DesiredCapabilities caps = new DesiredCapabilities();
Response response = given().auth().basic(getUsername(), getPassword())
.get("https://api.browserstack.com/automate/browsers.json");
String supportedVersions = "";
if (properties.getProperty("browserstack.browser.version").toLowerCase().equals("latest")) {
supportedVersions = GenericData.extractJsonArrayValueFromJsonString(response.asString(),
"$[?(@.os=='" + properties.getProperty("browserstack.os") + "' && " +
"@.os_version=='" + properties.getProperty("browserstack.os.version") + "' && " +
"@.browser=='" + properties.getProperty("browserstack.browser").toLowerCase() + "' && " +
"@.browser_version=~/^((?!beta).)*$/i)]").toString();
String latestSupportedVersion = GenericData.extractStringValueFromJsonString
(supportedVersions, "$[-1].browser_version");
caps.setCapability("browser_version", latestSupportedVersion);
}
else {
caps.setCapability("browser_version", properties.getProperty("browserstack.browser.version"));
}
caps.setCapability("os", properties.getProperty("browserstack.os"));
caps.setCapability("os_version", properties.getProperty("browserstack.os.version"));
caps.setCapability("resolution", "2048x1536");
caps.setCapability("browser", properties.getProperty("browserstack.browser"));
caps.setCapability("browserstack.local", properties.getProperty("browserstack.local"));
caps.setCapability("browserstack.selenium_version", properties.getProperty("browserstack.selenium.version"));
caps.setCapability("name", properties.getProperty("local.name"));
caps.setCapability("browserstack.video", "true");
caps.setCapability("browserstack.idleTimeout", "300");
caps.setCapability("browserstack.networkLogs", "true");
caps.setCapability("browserstack.debug", "true");
return caps;
}
@Override
public URL loadUrl() throws MalformedURLException {
return new URL("http://" + getUsername() + ":" + getPassword() + "@" + properties.getProperty("browserstack.hostname") + "/wd/hub");
}
}
| 45.050633 | 140 | 0.670975 |
c362f336d2ec62337f9ae63bcbe7261f0a2c7668 | 3,492 | /*
* 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.
*
* $Header:$
*/
package org.apache.beehive.netui.compiler.typesystem.impl.declaration;
import org.apache.beehive.netui.compiler.typesystem.declaration.Declaration;
import org.apache.beehive.netui.compiler.typesystem.declaration.AnnotationInstance;
import org.apache.beehive.netui.compiler.typesystem.declaration.Modifier;
import org.apache.beehive.netui.compiler.typesystem.util.SourcePosition;
import org.apache.beehive.netui.compiler.typesystem.impl.env.SourcePositionImpl;
import org.apache.beehive.netui.compiler.typesystem.impl.DelegatingImpl;
import org.apache.beehive.netui.compiler.typesystem.impl.WrapperFactory;
import java.util.Collection;
import java.util.Set;
import java.util.HashSet;
public class DeclarationImpl
extends DelegatingImpl
implements Declaration
{
private AnnotationInstance[] _annotations;
private Set _modifiers;
public DeclarationImpl( com.sun.mirror.declaration.Declaration delegate )
{
super( delegate );
}
public String getDocComment()
{
return getDelegate().getDocComment();
}
public AnnotationInstance[] getAnnotationInstances()
{
if ( _annotations == null )
{
Collection<com.sun.mirror.declaration.AnnotationMirror> delegateCollection = getDelegate().getAnnotationMirrors();
AnnotationInstance[] array = new AnnotationInstance[delegateCollection.size()];
int j = 0;
for ( com.sun.mirror.declaration.AnnotationMirror i : delegateCollection )
{
array[j++] = WrapperFactory.get().getAnnotationInstance( i, this );
}
_annotations = array;
}
return _annotations;
}
public Set getModifiers()
{
if ( _modifiers == null )
{
Collection<com.sun.mirror.declaration.Modifier> delegateCollection = getDelegate().getModifiers();
Set modifiers = new HashSet();
for ( com.sun.mirror.declaration.Modifier i : delegateCollection )
{
modifiers.add( ModifierImpl.get( i ) );
}
_modifiers = modifiers;
}
return _modifiers;
}
public String getSimpleName()
{
return getDelegate().getSimpleName();
}
public SourcePosition getPosition()
{
return SourcePositionImpl.get( getDelegate().getPosition() );
}
public boolean hasModifier( Modifier modifier )
{
return getModifiers().contains( modifier );
}
protected com.sun.mirror.declaration.Declaration getDelegate()
{
return ( com.sun.mirror.declaration.Declaration ) super.getDelegate();
}
}
| 33.902913 | 126 | 0.690149 |
03a276ff9a57c3a3526666caca02f6111546945b | 1,610 | package br.com.proposta.microservico.proposta.responses;
import br.com.proposta.microservico.proposta.entidades.Proposta;
import java.net.URI;
// TODO Proposta Response 1) coloque o id da carteira se existir vinculo e qual carteira é exemplo :
// idCarteira String
// carteira Carteira
public class PropostaResponse {
private String cpfOuCnpj;
private String email;
private String nome;
private String endereco;
private Double salario;
private URI url;
private ElegibilidadeProposta elegibilidadeProposta;
private String idCartao;
public PropostaResponse(Proposta proposta, URI url) {
this.cpfOuCnpj = proposta.getDocumento();
this.email = proposta.getEmail();
this.nome = proposta.getNome();
this.endereco = proposta.getEndereco();
this.salario = proposta.getSalario();
this.url = url;
this.elegibilidadeProposta = proposta.getElegibilidadeProposta();
this.idCartao = proposta.getCartao().getIdCartao();
}
public String getCpfOuCnpj() {
return cpfOuCnpj;
}
public String getEmail() {
return email;
}
public String getNome() {
return nome;
}
public String getEndereco() {
return endereco;
}
public Double getSalario() {
return salario;
}
public URI getUrl() {
return url;
}
public String getIdCartao() {
return idCartao;
}
public ElegibilidadeProposta getElegibilidadeProposta() {
return elegibilidadeProposta;
}
}
| 25.555556 | 101 | 0.646584 |
e56b212a6a62c286fc985621bc95ca05f7bb9e77 | 7,061 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: tensorflow/core/framework/op_def.proto
package org.tensorflow.proto.framework;
public final class OpDefProtos {
private OpDefProtos() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions(
(com.google.protobuf.ExtensionRegistryLite) registry);
}
static final com.google.protobuf.Descriptors.Descriptor
internal_static_tensorflow_OpDef_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_tensorflow_OpDef_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_tensorflow_OpDef_ArgDef_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_tensorflow_OpDef_ArgDef_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_tensorflow_OpDef_AttrDef_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_tensorflow_OpDef_AttrDef_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_tensorflow_OpDeprecation_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_tensorflow_OpDeprecation_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor
internal_static_tensorflow_OpList_descriptor;
static final
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internal_static_tensorflow_OpList_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n&tensorflow/core/framework/op_def.proto" +
"\022\ntensorflow\032*tensorflow/core/framework/" +
"attr_value.proto\032%tensorflow/core/framew" +
"ork/types.proto\032/tensorflow/core/framewo" +
"rk/resource_handle.proto\"\224\006\n\005OpDef\022\014\n\004na" +
"me\030\001 \001(\t\022+\n\tinput_arg\030\002 \003(\0132\030.tensorflow" +
".OpDef.ArgDef\022,\n\noutput_arg\030\003 \003(\0132\030.tens" +
"orflow.OpDef.ArgDef\022\026\n\016control_output\030\024 " +
"\003(\t\022\'\n\004attr\030\004 \003(\0132\031.tensorflow.OpDef.Att" +
"rDef\022.\n\013deprecation\030\010 \001(\0132\031.tensorflow.O" +
"pDeprecation\022\017\n\007summary\030\005 \001(\t\022\023\n\013descrip" +
"tion\030\006 \001(\t\022\026\n\016is_commutative\030\022 \001(\010\022\024\n\014is" +
"_aggregate\030\020 \001(\010\022\023\n\013is_stateful\030\021 \001(\010\022\"\n" +
"\032allows_uninitialized_input\030\023 \001(\010\032\343\001\n\006Ar" +
"gDef\022\014\n\004name\030\001 \001(\t\022\023\n\013description\030\002 \001(\t\022" +
"\"\n\004type\030\003 \001(\0162\024.tensorflow.DataType\022\021\n\tt" +
"ype_attr\030\004 \001(\t\022\023\n\013number_attr\030\005 \001(\t\022\026\n\016t" +
"ype_list_attr\030\006 \001(\t\022B\n\013handle_data\030\007 \003(\013" +
"2-.tensorflow.ResourceHandleProto.DtypeA" +
"ndShape\022\016\n\006is_ref\030\020 \001(\010\032\275\001\n\007AttrDef\022\014\n\004n" +
"ame\030\001 \001(\t\022\014\n\004type\030\002 \001(\t\022,\n\rdefault_value" +
"\030\003 \001(\0132\025.tensorflow.AttrValue\022\023\n\013descrip" +
"tion\030\004 \001(\t\022\023\n\013has_minimum\030\005 \001(\010\022\017\n\007minim" +
"um\030\006 \001(\003\022-\n\016allowed_values\030\007 \001(\0132\025.tenso" +
"rflow.AttrValue\"5\n\rOpDeprecation\022\017\n\007vers" +
"ion\030\001 \001(\005\022\023\n\013explanation\030\002 \001(\t\"\'\n\006OpList" +
"\022\035\n\002op\030\001 \003(\0132\021.tensorflow.OpDefB\201\001\n\036org." +
"tensorflow.proto.frameworkB\013OpDefProtosP" +
"\001ZMgithub.com/tensorflow/tensorflow/tens" +
"orflow/go/core/framework/op_def_go_proto" +
"\370\001\001b\006proto3"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
org.tensorflow.proto.framework.AttrValueProtos.getDescriptor(),
org.tensorflow.proto.framework.TypesProtos.getDescriptor(),
org.tensorflow.proto.framework.ResourceHandle.getDescriptor(),
});
internal_static_tensorflow_OpDef_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_tensorflow_OpDef_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_tensorflow_OpDef_descriptor,
new java.lang.String[] { "Name", "InputArg", "OutputArg", "ControlOutput", "Attr", "Deprecation", "Summary", "Description", "IsCommutative", "IsAggregate", "IsStateful", "AllowsUninitializedInput", });
internal_static_tensorflow_OpDef_ArgDef_descriptor =
internal_static_tensorflow_OpDef_descriptor.getNestedTypes().get(0);
internal_static_tensorflow_OpDef_ArgDef_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_tensorflow_OpDef_ArgDef_descriptor,
new java.lang.String[] { "Name", "Description", "Type", "TypeAttr", "NumberAttr", "TypeListAttr", "HandleData", "IsRef", });
internal_static_tensorflow_OpDef_AttrDef_descriptor =
internal_static_tensorflow_OpDef_descriptor.getNestedTypes().get(1);
internal_static_tensorflow_OpDef_AttrDef_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_tensorflow_OpDef_AttrDef_descriptor,
new java.lang.String[] { "Name", "Type", "DefaultValue", "Description", "HasMinimum", "Minimum", "AllowedValues", });
internal_static_tensorflow_OpDeprecation_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_tensorflow_OpDeprecation_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_tensorflow_OpDeprecation_descriptor,
new java.lang.String[] { "Version", "Explanation", });
internal_static_tensorflow_OpList_descriptor =
getDescriptor().getMessageTypes().get(2);
internal_static_tensorflow_OpList_fieldAccessorTable = new
com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_tensorflow_OpList_descriptor,
new java.lang.String[] { "Op", });
org.tensorflow.proto.framework.AttrValueProtos.getDescriptor();
org.tensorflow.proto.framework.TypesProtos.getDescriptor();
org.tensorflow.proto.framework.ResourceHandle.getDescriptor();
}
// @@protoc_insertion_point(outer_class_scope)
}
| 55.598425 | 209 | 0.748761 |
de62bca8132da1c33763807d7aa039ff31280ac4 | 5,341 | /*
* 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.nifi.provenance;
import org.apache.nifi.provenance.search.SearchableField;
import org.apache.nifi.provenance.search.SearchableFieldType;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class SearchableFields {
public static final SearchableField Identifier = new NamedSearchableField("Identifier", "identifier", "Identifier", false);
public static final SearchableField EventTime = new NamedSearchableField("EventTime", "time", "Event Time", false, SearchableFieldType.DATE);
public static final SearchableField FlowFileUUID = new NamedSearchableField("FlowFileUUID", "uuid", "FlowFile UUID", false);
public static final SearchableField Filename = new NamedSearchableField("Filename", "filename", "Filename", false);
public static final SearchableField EventType = new NamedSearchableField("EventType", "eventType", "Event Type", false);
public static final SearchableField TransitURI = new NamedSearchableField("TransitURI", "transitUri", "Transit URI", false);
public static final SearchableField ComponentID = new NamedSearchableField("ProcessorID", "processorId", "Component ID", false);
public static final SearchableField AlternateIdentifierURI = new NamedSearchableField("AlternateIdentifierURI", "alternateIdentifierUri", "Alternate Identifier URI", false);
public static final SearchableField FileSize = new NamedSearchableField("FileSize", "fileSize", "File Size", false, SearchableFieldType.DATA_SIZE);
public static final SearchableField Details = new NamedSearchableField("Details", "details", "Details", false, SearchableFieldType.STRING);
public static final SearchableField Relationship = new NamedSearchableField("Relationship", "relationship", "Relationship", false, SearchableFieldType.STRING);
public static final SearchableField LineageStartDate
= new NamedSearchableField("LineageStartDate", "lineageStartDate", "Lineage Start Date", false, SearchableFieldType.DATE);
public static final SearchableField LineageIdentifier
= new NamedSearchableField("LineageIdentifiers", "lineageIdentifier", "Lineage Identifier", false, SearchableFieldType.STRING);
public static final SearchableField ContentClaimSection
= new NamedSearchableField("ContentClaimSection", "contentClaimSection", "Content Claim Section", false, SearchableFieldType.STRING);
public static final SearchableField ContentClaimContainer
= new NamedSearchableField("ContentClaimContainer", "contentClaimContainer", "Content Claim Container", false, SearchableFieldType.STRING);
public static final SearchableField ContentClaimIdentifier
= new NamedSearchableField("ContentClaimIdentifier", "contentClaimIdentifier", "Content Claim Identifier", false, SearchableFieldType.STRING);
public static final SearchableField ContentClaimOffset
= new NamedSearchableField("ContentClaimOffset", "contentClaimOffset", "Content Claim Offset", false, SearchableFieldType.LONG);
public static final SearchableField SourceQueueIdentifier
= new NamedSearchableField("SourceQueueIdentifier", "sourceQueueIdentifier", "Source Queue Identifier", false, SearchableFieldType.STRING);
private static final Map<String, SearchableField> standardFields;
static {
final SearchableField[] searchableFields = new SearchableField[]{
EventTime, FlowFileUUID, Filename, EventType, TransitURI,
ComponentID, AlternateIdentifierURI, FileSize, Relationship, Details,
LineageStartDate, LineageIdentifier, ContentClaimSection, ContentClaimContainer, ContentClaimIdentifier,
ContentClaimOffset, SourceQueueIdentifier};
final Map<String, SearchableField> fields = new HashMap<>();
for (final SearchableField field : searchableFields) {
fields.put(field.getIdentifier(), field);
}
standardFields = Collections.unmodifiableMap(fields);
}
private SearchableFields() {
}
public static Collection<SearchableField> getStandardFields() {
return standardFields.values();
}
public static SearchableField getSearchableField(final String fieldIdentifier) {
return standardFields.get(fieldIdentifier);
}
public static SearchableField newSearchableAttribute(final String attributeName) {
return new NamedSearchableField(attributeName, attributeName, attributeName, true);
}
}
| 58.054348 | 177 | 0.764838 |
ef564f8b5114dd96a98e64f3b7892b56195d54a8 | 1,158 | /**
* Copyright © 2018 by afei. All rights reserved.
*
* @author: afei
* @date: 2018年11月15日
*/
public class Solution {
private static int tenthMax = Integer.MAX_VALUE / 10;
private static int tenthMin = Integer.MIN_VALUE / 10;
public static void main(String[] args) {
System.out.println(reverse(Integer.MAX_VALUE));
System.out.println(reverse(Integer.MIN_VALUE));
System.out.println(reverse(-12345));
System.out.println(reverse(54321));
}
public static int reverse(int x) {
int reverse = 0;
while (x != 0) {
int pop = x % 10;
// 如果 temp = rev * 10 + pop 导致溢出
// 那么一定有 rev >= Integer.MAX_VALUE / 10
// 如果 rev == Integer.MAX_VALUE / 10,只要 pop > 7 也会溢出
if (reverse > tenthMax || (reverse == tenthMax && pop > 7)) {
return 0;
}
// 对于负数,理由同上
if (reverse < tenthMin || (reverse == tenthMin && pop < -8)) {
return 0;
}
reverse *= 10;
reverse += pop;
x /= 10;
}
return reverse;
}
}
| 28.243902 | 74 | 0.506908 |
1ff98eff1b9c974fabf7cdc245d68c009fd0fafd | 1,624 | package ru.csc.java.demos.d99;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.GZIPOutputStream;
public class YetAnotherArchiveWriter implements AutoCloseable {
private final DataOutputStream outputStream;
public YetAnotherArchiveWriter(Path outputFile) throws IOException {
this.outputStream = new DataOutputStream(Files.newOutputStream(
outputFile,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING));
}
public void addDirectoryRecursively(Path directory) throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
addFile(file, directory, attrs);
return FileVisitResult.CONTINUE;
}
});
}
private void addFile(Path file, Path baseDirectory, BasicFileAttributes fileAttributes) throws IOException {
outputStream.writeUTF(baseDirectory.relativize(file).toString());
outputStream.writeLong(fileAttributes.creationTime().toMillis());
outputStream.writeLong(fileAttributes.lastModifiedTime().toMillis());
try (OutputStream contentStream = new GZIPOutputStream(new EmbeddedOutputStream(outputStream))) {
Files.copy(file, contentStream);
}
}
@Override
public void close() throws IOException {
outputStream.close();
}
}
| 36.909091 | 112 | 0.711823 |
83b0c7d3fe61a98b72954b420f4819ee2b9bd879 | 8,998 | /**
* Copyright 2020 XEBIALABS
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package integration.util;
import static io.restassured.RestAssured.baseURI;
import static io.restassured.RestAssured.given;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import com.google.common.collect.Maps;
import java.util.Scanner;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public final class SeleniumTestHelper {
private static final String BASE_URI = "http://localhost:15516/api/v1";
private static RequestSpecification httpRequest = null;
private static final String IMPORT_CONFIG = "/config";
private static final String IMPORT_TEMPLATE = "/templates/import";
private static final String START_RELEASE_SELENIUM = "/templates/Applications/Release832b197247d146298a22732556c67e80/start";
private static final String GET_RELEASE_PREFIX = "/releases/";
private static final String GET_VARIABLES_SUFFIX = "/variableValues";
private SeleniumTestHelper() {
/*
* Private Constructor will prevent the instantiation of this class directly
*/
}
static {
baseURI = BASE_URI;
// Configure authentication
httpRequest = given().auth().preemptive().basic("admin", "admin");
}
public static void initializeXLR() throws InterruptedException{
System.out.println("Pausing for 1.5 minutes, waiting for XLR to start. ");
Thread.sleep(90000);
// Load server config for the python/selenium server where scripts are run
try {
// Load config
JSONObject requestParamsConfig = getRequestParamsFromFile(getResourceFilePath("docker/initialize/data/server-configs.json"));
httpRequest.header("Content-Type", "application/json");
httpRequest.header("Accept", "application/json");
httpRequest.body(requestParamsConfig.toJSONString());
// Post server config
Response response = httpRequest.post(IMPORT_CONFIG);
if (response.getStatusCode() != 200) {
System.out.println("Status line, import server was " + response.getStatusLine() + "");
} else {
//String responseId = response.jsonPath().getString("id");
}
} catch (Exception e) {
e.printStackTrace();
}
try {
// Load the template
JSONObject requestParams = new JSONObject();
httpRequest.body(requestParams.toJSONString());
httpRequest.contentType("multipart/form-data");
httpRequest.multiPart(new File(getResourceFilePath("docker/initialize/data/release-template-selenium.json")));
} catch (Exception e) {
e.printStackTrace();
}
// Post template
Response response = httpRequest.post(IMPORT_TEMPLATE);
if (response.getStatusCode() != 200) {
System.out.println("Status line, import template was " + response.getStatusLine() + "");
} else {
String postResponseId = response.jsonPath().getString("id");
}
}
public static String getSeleniumReleaseResult() throws InterruptedException{
org.json.JSONObject releaseResultJSON = null;
String responseId = "";
String releaseResultStr = "";
// Prepare httpRequest, start the release
JSONObject requestParams = getRequestParams();
Response response = given().auth().preemptive().basic("admin", "admin")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.body(requestParams.toJSONString())
.post(START_RELEASE_SELENIUM);
///////// retrieve the planned release id.
if (response.getStatusCode() != 200) {
System.out.println("Status line, Start release was " + response.getStatusLine() );
} else {
responseId = response.jsonPath().getString("id");
System.out.println("Start release was successful, id = "+ responseId);
}
///////// Get Archived responses
// Sleep so XLR can finish processing releases
System.out.println("Pausing for 2 minutes, waiting for release to complete. If most requests fail with 404, consider sleeping longer.");
Thread.sleep(120000);
//////////
response = given().auth().preemptive().basic("admin", "admin")
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.body(requestParams.toJSONString())
.get(GET_RELEASE_PREFIX + responseId + GET_VARIABLES_SUFFIX);
if (response.getStatusCode() != 200) {
System.out.println("Status line for get variables was " + response.getStatusLine() + "");
} else {
//releaseResult = response.jsonPath().get("phases[0].tasks[1].comments[0].text").toString();
releaseResultStr = response.jsonPath().prettyPrint();
}
// Return the comments attached to the finished release so we can test for success
return releaseResultStr;
}
/////////////////// Util methods
public static String getResourceFilePath(String filePath){
// Working with resource files instead of the file system - OS Agnostic
String resourcePath = "";
ClassLoader classLoader = SeleniumTestHelper.class.getClassLoader();
try {
resourcePath = new File (classLoader.getResource(filePath).toURI()).getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
//System.out.println("resourcePath = " + resourcePath);
return resourcePath;
}
public static String readFile(String path) {
StringBuilder result = new StringBuilder("");
File file = new File(path);
try (Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
result.append(line).append("\n");
}
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
public static JSONObject getRequestParamsFromFile(String filePath) {
JSONObject requestParams = new JSONObject();
//JSON parser object to parse read file
JSONParser jsonParser = new JSONParser();
try (FileReader reader = new FileReader(filePath))
{
//Read JSON file
Object obj = jsonParser.parse(reader);
requestParams = (JSONObject) obj;
//System.out.println(requestParams);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
return requestParams;
}
public static JSONObject getRequestParams() {
// must use intermediate parameterized HashMap to avoid warnings
HashMap<String,Object> params = new HashMap<String,Object>();
params.put("releaseTitle", "release from api");
//params.put("variables", new JSONObject());
//params.put("releaseVariables", new JSONObject());
//params.put("releasePasswordVariables", new JSONObject());
//params.put("scheduledStartDate", null);
//params.put("autoStart", false);
JSONObject requestParams = new JSONObject(params);
return requestParams;
}
} | 42.847619 | 463 | 0.6517 |
41d247fc4ad3240884513fc2b9a9c3339feacb17 | 3,757 | package tv.twitch.moonmoon.rpengine2.util;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import java.util.*;
import java.util.stream.Collectors;
public class Countdown extends TimerTask {
private final Set<UUID> playerIds;
private final ChatColor color;
private final ChatColor goColor;
private final String sound;
private final float volume;
private final float pitch;
private final String goSound;
private final float goVolume;
private final float goPitch;
private final Runnable callback;
private int timeSecs;
public Countdown(
Set<UUID> playerIds,
ChatColor color,
ChatColor goColor,
String sound,
float volume,
float pitch,
String goSound,
float goVolume,
float goPitch,
int timeSecs,
Runnable callback
) {
this.playerIds = Objects.requireNonNull(playerIds);
this.color = Objects.requireNonNull(color);
this.goColor = Objects.requireNonNull(goColor);
this.sound = Objects.requireNonNull(sound);
this.volume = volume;
this.pitch = pitch;
this.goSound = Objects.requireNonNull(goSound);
this.goVolume = goVolume;
this.goPitch = goPitch;
this.timeSecs = timeSecs;
this.callback = callback;
}
@Override
public void run() {
List<Player> players = getPlayers();
if (timeSecs == 0) {
for (Player player : players) {
player.playSound(player.getLocation(), goSound, goVolume, goPitch);
player.sendTitle("" + goColor + ChatColor.BOLD + "GO!",
null, 0, 10, 5
);
}
cancel();
if (callback != null) {
callback.run();
}
return;
}
for (Player player : players) {
player.playSound(player.getLocation(), sound, volume, pitch);
player.sendTitle(
"" + color + ChatColor.BOLD + timeSecs,
null, 0, 10, 5
);
}
timeSecs--;
}
public void start() {
new Timer().scheduleAtFixedRate(this, 0, 1000);
}
public static Countdown from(
FileConfiguration config,
Set<UUID> playerIds,
int timeSecs,
Runnable callback
) {
float volume = (float) config.getDouble("countdown.volume", 0.5);
float pitch = (float) config.getDouble("countdown.pitch", 1);
float goVolume = (float) config.getDouble("countdown.goVolume", 0.5);
float goPitch = (float) config.getDouble("countdown.goPitch", 1);
String sound = config.getString(
"countdown.sound", "minecraft:ui.button.click"
);
String goSound = config.getString(
"countdown.goSound", "minecraft:block.bell.use"
);
ChatColor color = StringUtils.getChatColor(
config.getString("countdown.color", "")
).orElse(ChatColor.WHITE);
ChatColor goColor = StringUtils.getChatColor(
config.getString("countdown.goColor", "")
).orElse(ChatColor.WHITE);
return new Countdown(
playerIds,
color,
goColor,
sound,
volume,
pitch,
goSound,
goVolume,
goPitch,
timeSecs,
callback
);
}
private List<Player> getPlayers() {
return playerIds.stream()
.map(Bukkit::getPlayer)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
}
| 28.037313 | 83 | 0.571999 |
887a2e69374c980ae4aed7651c378fe4c5b5b100 | 4,227 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.app.backup;
import android.content.Context;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import java.io.File;
import java.io.FileDescriptor;
/**
* Base class for the {@link android.app.backup.FileBackupHelper} implementation.
*/
class FileBackupHelperBase {
private static final String TAG = "FileBackupHelperBase";
int mPtr;
Context mContext;
boolean mExceptionLogged;
FileBackupHelperBase(Context context) {
mPtr = ctor();
mContext = context;
}
protected void finalize() throws Throwable {
try {
dtor(mPtr);
} finally {
super.finalize();
}
}
/**
* Check the parameters so the native code doesn't have to throw all the exceptions
* since it's easier to do that from Java.
*/
static void performBackup_checked(ParcelFileDescriptor oldState, BackupDataOutput data,
ParcelFileDescriptor newState, String[] files, String[] keys) {
if (files.length == 0) {
return;
}
// files must be all absolute paths
for (String f: files) {
if (f.charAt(0) != '/') {
throw new RuntimeException("files must have all absolute paths: " + f);
}
}
// the length of files and keys must be the same
if (files.length != keys.length) {
throw new RuntimeException("files.length=" + files.length
+ " keys.length=" + keys.length);
}
// oldStateFd can be null
FileDescriptor oldStateFd = oldState != null ? oldState.getFileDescriptor() : null;
FileDescriptor newStateFd = newState.getFileDescriptor();
if (newStateFd == null) {
throw new NullPointerException();
}
int err = performBackup_native(oldStateFd, data.mBackupWriter, newStateFd, files, keys);
if (err != 0) {
// TODO: more here
throw new RuntimeException("Backup failed 0x" + Integer.toHexString(err));
}
}
boolean writeFile(File f, BackupDataInputStream in) {
int result = -1;
// Create the enclosing directory.
File parent = f.getParentFile();
parent.mkdirs();
result = writeFile_native(mPtr, f.getAbsolutePath(), in.mData.mBackupReader);
if (result != 0) {
// Bail on this entity. Only log one failure per helper object.
if (!mExceptionLogged) {
Log.e(TAG, "Failed restoring file '" + f + "' for app '"
+ mContext.getPackageName() + "\' result=0x"
+ Integer.toHexString(result));
mExceptionLogged = true;
}
}
return (result == 0);
}
public void writeNewStateDescription(ParcelFileDescriptor fd) {
int result = writeSnapshot_native(mPtr, fd.getFileDescriptor());
// TODO: Do something with the error.
}
boolean isKeyInList(String key, String[] list) {
for (String s: list) {
if (s.equals(key)) {
return true;
}
}
return false;
}
private static native int ctor();
private static native void dtor(int ptr);
native private static int performBackup_native(FileDescriptor oldState,
int data, FileDescriptor newState, String[] files, String[] keys);
private static native int writeFile_native(int ptr, String filename, int backupReader);
private static native int writeSnapshot_native(int ptr, FileDescriptor fd);
}
| 32.767442 | 96 | 0.618405 |
fb61e3ed228cbe1ba7c06bb35872ef886db73063 | 740 | package models;
import org.bson.types.ObjectId;
import de.caluga.morphium.annotations.Entity;
import de.caluga.morphium.annotations.Id;
import de.caluga.morphium.annotations.Reference;
import de.caluga.morphium.annotations.caching.Cache;
@Entity(translateCamelCase = true)
@Cache
public class Item {
@Id
private ObjectId id;
private String name;
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Item [id=" + id + ", name=" + name + "]";
}
// private EmbeddedObject emb;
// @Reference
// private MyEntity otherEntity;
}
| 16.086957 | 52 | 0.704054 |
4de83b1632d1592704f83dccfcd647782585ba7d | 860 | package im.wangbo.java.leetcode.dynamic;
/**
* See https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/23/dynamic-programming/54/
*
* 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
*
* 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
*
* 注意:给定 n 是一个正整数。
*
* 示例 1:
*
* 输入: 2
* 输出: 2
* 解释: 有两种方法可以爬到楼顶。
* 1. 1 阶 + 1 阶
* 2. 2 阶
* 示例 2:
*
* 输入: 3
* 输出: 3
* 解释: 有三种方法可以爬到楼顶。
* 1. 1 阶 + 1 阶 + 1 阶
* 2. 1 阶 + 2 阶
* 3. 2 阶 + 1 阶
*
* @author Elvis Wang
*/
class ClimbStairsSolution {
public int climbStairs(int n) {
if (n <= 0) return 0;
if (n == 1) return 1;
if (n == 2) return 2;
// n > 2
final int[] cache = new int[n];
cache[0] = 1;
cache[1] = 2;
for (int i = 2; i < n; i++) {
cache[i] = cache[i - 1] + cache[i - 2];
}
return cache[n-1];
}
}
| 17.916667 | 109 | 0.495349 |
7389adf7f3db0ba7d9d8aa942aca8a310910195d | 59 | package vn.tripi.restclient;
public interface BaseAPI {
}
| 11.8 | 28 | 0.779661 |
13b36e49ba5078a9d7ce77744fdd46befbdb9cac | 1,604 | /*
* XNAT http://www.xnat.org
* Copyright (c) 2020, Washington University School of Medicine
* All Rights Reserved
*
* Released under the Simplified BSD.
*/
package org.nrg.xnatx.plugins.rapidViewer.services.impl;
import java.util.List;
import org.nrg.framework.orm.hibernate.AbstractHibernateEntityService;
import org.nrg.xnatx.plugins.rapidViewer.entities.WorkItem;
import org.nrg.xnatx.plugins.rapidViewer.entities.WorkItem.WorkItemStatus;
import org.nrg.xnatx.plugins.rapidViewer.entities.WorkList;
import org.nrg.xnatx.plugins.rapidViewer.repositories.WorkItemRepository;
import org.nrg.xnatx.plugins.rapidViewer.services.WorkItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;
/**
* Manages {@link WorkList} data objects in Hibernate.
*/
@Service
@Slf4j
public class HibernateWorkItemService extends AbstractHibernateEntityService<WorkItem, WorkItemRepository>
implements WorkItemService {
@Transactional
@Override
public WorkItem findById(Long id) {
log.trace("Requested WorkListItem with ID \"{}\"", id);
return getDao().findByUniqueProperty("id", id);
}
@Transactional
@Override
public List<WorkItem> getWorkItems(Long workListId) {
return _dao.getWorkItems(workListId);
}
@Transactional
@Override
public List<WorkItem> getWorkItemsByStatus(Long workListId, WorkItemStatus status) {
return _dao.getWorkItemsByStatus(workListId, status);
}
@Autowired
private WorkItemRepository _dao;
}
| 29.703704 | 106 | 0.802369 |
48e44335afc6888cd022843698352d8d906a8020 | 6,097 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.j2cl.maven;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.project.DefaultProjectBuildingRequest;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuilder;
import org.apache.maven.project.ProjectBuildingException;
import org.apache.maven.project.ProjectBuildingRequest;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import walkingkooka.collect.map.Maps;
import walkingkooka.text.CharSequences;
import java.util.List;
import java.util.Map;
import java.util.Optional;
final class J2clMavenMiddlewareImpl implements J2clMavenMiddleware {
static J2clMavenMiddleware with(final ArtifactHandlerManager artifactHandlerManager,
final MavenSession mavenSession,
final ProjectBuilder projectBuilder,
final List<ArtifactRepository> remoteArtifactRepositories,
final List<RemoteRepository> remoteRepositories,
final RepositorySystemSession repositorySession,
final RepositorySystem repositorySystem) {
return new J2clMavenMiddlewareImpl(artifactHandlerManager,
mavenSession,
projectBuilder,
remoteArtifactRepositories,
remoteRepositories,
repositorySession,
repositorySystem);
}
private J2clMavenMiddlewareImpl(final ArtifactHandlerManager artifactHandlerManager,
final MavenSession mavenSession,
final ProjectBuilder projectBuilder,
final List<ArtifactRepository> remoteArtifactRepositories,
final List<RemoteRepository> remoteRepositories,
final RepositorySystemSession repositorySession,
final RepositorySystem repositorySystem) {
this.artifactHandlerManager = artifactHandlerManager;
this.mavenSession = mavenSession;
this.projectBuilder = projectBuilder;
this.remoteArtifactRepositories = remoteArtifactRepositories;
this.remoteRepositories = remoteRepositories;
this.repositorySession = repositorySession;
this.repositorySystem = repositorySystem;
}
/**
* Fetches the {@link ArtifactHandler} for the given type.
*/
@Override
public MavenProject mavenProject(final J2clArtifactCoords coords,
final J2clClasspathScope scope) {
MavenProject mavenProject = this.coordToMavenProject.get(coords);
if (null == mavenProject) {
mavenProject = this.mavenProject0(coords.mavenArtifact(scope, this.artifactHandler(coords.typeOrDefault())));
this.coordToMavenProject.put(coords, mavenProject);
}
return mavenProject;
}
/**
* Cache of coords to project.
*/
private final Map<J2clArtifactCoords, MavenProject> coordToMavenProject = Maps.concurrent();
private ArtifactHandler artifactHandler(final String type) {
return this.artifactHandlerManager.getArtifactHandler(type);
}
private ArtifactHandlerManager artifactHandlerManager;
private MavenProject mavenProject0(final Artifact artifact) {
final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(this.mavenSession.getProjectBuildingRequest());
request.setProject(null);
request.setResolveDependencies(true);
request.setRemoteRepositories(this.remoteArtifactRepositories);
try {
return this.projectBuilder.build(artifact, false, request)
.getProject();
} catch (final ProjectBuildingException cause) {
throw new J2clException("Unable to fetch MavenProject for " + CharSequences.quoteAndEscape(artifact.toString()), cause);
}
}
@Override
public Optional<J2clPath> mavenFile(final String coords) {
final ArtifactRequest request = new ArtifactRequest()
.setRepositories(this.remoteRepositories)
.setArtifact(new DefaultArtifact(coords));
J2clPath file;
try {
file = J2clPath.with(this.repositorySystem.resolveArtifact(this.repositorySession, request).getArtifact().getFile().toPath());
} catch (final ArtifactResolutionException cause) {
file = null;
}
return Optional.ofNullable(file);
}
private final MavenSession mavenSession;
private final ProjectBuilder projectBuilder;
private final List<ArtifactRepository> remoteArtifactRepositories;
private final List<RemoteRepository> remoteRepositories;
private final RepositorySystemSession repositorySession;
private final RepositorySystem repositorySystem;
}
| 43.55 | 138 | 0.697228 |
c07401f62037bab81d351c17edc9ffbc5178127f | 3,972 | package com.tradenity.sdk.services;
import com.tradenity.sdk.client.TradenityClient;
import com.tradenity.sdk.model.*;
import com.tradenity.sdk.resources.ResourcePage;
import com.tradenity.sdk.resources.TableRateRuleResource;
import retrofit2.Call;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class TableRateRuleService extends AbstractService{
TableRateRuleResource tableRateRuleResource;
public TableRateRuleService(TradenityClient client) {
super(client);
}
protected TableRateRuleResource getTableRateRuleResource(){
if(tableRateRuleResource == null) {
tableRateRuleResource = resourceFactory.create(TableRateRuleResource.class);
}
return tableRateRuleResource;
}
public Page<TableRateRule> findAll(PageRequest pageRequest){
Call<ResourcePage<TableRateRule>> call = getTableRateRuleResource().index(pageRequest.asMap());
return createPage(call);
}
public Page<TableRateRule> search(Map<String, Object> fields, PageRequest pageRequest){
Map<String, Object> params = new HashMap<>(fields);
if(pageRequest != null) {
params.putAll(pageRequest.asMap());
}
Call<ResourcePage<TableRateRule>> call = getTableRateRuleResource().index(params);
return createPage(call);
}
public TableRateRule findBy(String attribute, String value){
return findOne(Collections.<String, Object>singletonMap(attribute, value));
}
public TableRateRule findBy(String attribute, BaseModel model){
return findBy(attribute, model.getId());
}
public Page<TableRateRule> findAll(){
return findAll(new PageRequest());
}
public Page<TableRateRule> findAllBy(String attribute, String value){
return search(attribute, value);
}
public Page<TableRateRule> findAllBy(String attribute, BaseModel model){
return findAllBy(attribute, model.getId());
}
public Page<TableRateRule> findAllBy(String attribute, String value, PageRequest pageRequest){
return search(Collections.<String, Object>singletonMap(attribute, value), pageRequest);
}
public Page<TableRateRule> findAllBy(String attribute, BaseModel model, PageRequest pageRequest){
return findAllBy(attribute, model.getId(), pageRequest);
}
public Page<TableRateRule> search(String attribute, Object value){
return search(Collections.singletonMap(attribute, value), new PageRequest());
}
public Page<TableRateRule> search(Map<String, Object> fields){
return search(fields, new PageRequest());
}
public TableRateRule findOne(Map<String, Object> fields){
List<TableRateRule> content = search(fields).getContent();
if(content != null && content.size() > 0) {
return content.get(0);
}else{
return null;
}
}
public TableRateRule findById(String id){
Call<TableRateRule> call = getTableRateRuleResource().findOne(id);
return createInstance(call);
}
public TableRateRule create(TableRateRule tableRateRule){
Call<TableRateRule> call = getTableRateRuleResource().save(tableRateRule);
return createInstance(call);
}
public TableRateRule update(TableRateRule tableRateRule){
Call<TableRateRule> call = getTableRateRuleResource().update(tableRateRule.getId(), tableRateRule);
return createInstance(call);
}
public TableRateRule replace(TableRateRule tableRateRule){
Call<TableRateRule> call = getTableRateRuleResource().replace(tableRateRule.getId(), tableRateRule);
return createInstance(call);
}
public void delete(String id){
Call<Void> call = getTableRateRuleResource().delete(id);
run(call);
}
public void delete(TableRateRule tableRateRule){
delete(tableRateRule.getId());
}
} | 33.661017 | 109 | 0.700403 |
3168a729f51e5ea9e32bb0889b645a9ef0c3922b | 271 | package org.aspenos.app.aosmailserver.registry;
import java.lang.*;
import java.util.*;
import java.sql.*;
import org.aspenos.util.*;
import org.aspenos.app.aosmailserver.defs.*;
/**
*
*/
public interface IMailServerRegistry extends IRegistry {
}
| 15.941176 | 57 | 0.693727 |
1e44f863813964e792f6223376fc6f7181318cee | 6,484 | package net.minecraft.entity.ai;
import net.minecraft.entity.player.*;
import net.minecraft.util.*;
import net.minecraft.block.material.*;
import net.minecraft.world.pathfinder.*;
import net.minecraft.world.*;
import net.minecraft.init.*;
import net.minecraft.entity.*;
import net.minecraft.item.*;
import net.minecraft.block.*;
public class EntityAIControlledByPlayer extends EntityAIBase
{
private final EntityLiving thisEntity;
private final float maxSpeed;
private float currentSpeed;
private boolean speedBoosted;
private int speedBoostTime;
private int maxSpeedBoostTime;
public EntityAIControlledByPlayer(final EntityLiving entitylivingIn, final float maxspeed) {
this.thisEntity = entitylivingIn;
this.maxSpeed = maxspeed;
this.setMutexBits(7);
}
@Override
public void startExecuting() {
this.currentSpeed = 0.0f;
}
@Override
public void resetTask() {
this.speedBoosted = false;
this.currentSpeed = 0.0f;
}
@Override
public boolean shouldExecute() {
return this.thisEntity.isEntityAlive() && this.thisEntity.riddenByEntity != null && this.thisEntity.riddenByEntity instanceof EntityPlayer && (this.speedBoosted || this.thisEntity.canBeSteered());
}
@Override
public void updateTask() {
final EntityPlayer entityplayer = (EntityPlayer)this.thisEntity.riddenByEntity;
final EntityCreature entitycreature = (EntityCreature)this.thisEntity;
float f = MathHelper.wrapAngleTo180_float(entityplayer.rotationYaw - this.thisEntity.rotationYaw) * 0.5f;
if (f > 5.0f) {
f = 5.0f;
}
if (f < -5.0f) {
f = -5.0f;
}
this.thisEntity.rotationYaw = MathHelper.wrapAngleTo180_float(this.thisEntity.rotationYaw + f);
if (this.currentSpeed < this.maxSpeed) {
this.currentSpeed += (this.maxSpeed - this.currentSpeed) * 0.01f;
}
if (this.currentSpeed > this.maxSpeed) {
this.currentSpeed = this.maxSpeed;
}
final int i = MathHelper.floor_double(this.thisEntity.posX);
final int j = MathHelper.floor_double(this.thisEntity.posY);
final int k = MathHelper.floor_double(this.thisEntity.posZ);
float f2 = this.currentSpeed;
if (this.speedBoosted) {
if (this.speedBoostTime++ > this.maxSpeedBoostTime) {
this.speedBoosted = false;
}
f2 += f2 * 1.15f * MathHelper.sin(this.speedBoostTime / (float)this.maxSpeedBoostTime * 3.1415927f);
}
float f3 = 0.91f;
if (this.thisEntity.onGround) {
f3 = this.thisEntity.worldObj.getBlockState(new BlockPos(MathHelper.floor_float((float)i), MathHelper.floor_float((float)j) - 1, MathHelper.floor_float((float)k))).getBlock().slipperiness * 0.91f;
}
final float f4 = 0.16277136f / (f3 * f3 * f3);
final float f5 = MathHelper.sin(entitycreature.rotationYaw * 3.1415927f / 180.0f);
final float f6 = MathHelper.cos(entitycreature.rotationYaw * 3.1415927f / 180.0f);
final float f7 = entitycreature.getAIMoveSpeed() * f4;
float f8 = Math.max(f2, 1.0f);
f8 = f7 / f8;
final float f9 = f2 * f8;
float f10 = -(f9 * f5);
float f11 = f9 * f6;
if (MathHelper.abs(f10) > MathHelper.abs(f11)) {
if (f10 < 0.0f) {
f10 -= this.thisEntity.width / 2.0f;
}
if (f10 > 0.0f) {
f10 += this.thisEntity.width / 2.0f;
}
f11 = 0.0f;
}
else {
f10 = 0.0f;
if (f11 < 0.0f) {
f11 -= this.thisEntity.width / 2.0f;
}
if (f11 > 0.0f) {
f11 += this.thisEntity.width / 2.0f;
}
}
final int l = MathHelper.floor_double(this.thisEntity.posX + f10);
final int i2 = MathHelper.floor_double(this.thisEntity.posZ + f11);
final int j2 = MathHelper.floor_float(this.thisEntity.width + 1.0f);
final int k2 = MathHelper.floor_float(this.thisEntity.height + entityplayer.height + 1.0f);
final int l2 = MathHelper.floor_float(this.thisEntity.width + 1.0f);
if (i != l || k != i2) {
final Block block = this.thisEntity.worldObj.getBlockState(new BlockPos(i, j, k)).getBlock();
final boolean flag = !this.isStairOrSlab(block) && (block.getMaterial() != Material.air || !this.isStairOrSlab(this.thisEntity.worldObj.getBlockState(new BlockPos(i, j - 1, k)).getBlock()));
if (flag && 0 == WalkNodeProcessor.func_176170_a(this.thisEntity.worldObj, this.thisEntity, l, j, i2, j2, k2, l2, false, false, true) && 1 == WalkNodeProcessor.func_176170_a(this.thisEntity.worldObj, this.thisEntity, i, j + 1, k, j2, k2, l2, false, false, true) && 1 == WalkNodeProcessor.func_176170_a(this.thisEntity.worldObj, this.thisEntity, l, j + 1, i2, j2, k2, l2, false, false, true)) {
entitycreature.getJumpHelper().setJumping();
}
}
if (!entityplayer.capabilities.isCreativeMode && this.currentSpeed >= this.maxSpeed * 0.5f && this.thisEntity.getRNG().nextFloat() < 0.006f && !this.speedBoosted) {
final ItemStack itemstack = entityplayer.getHeldItem();
if (itemstack != null && itemstack.getItem() == Items.carrot_on_a_stick) {
itemstack.damageItem(1, entityplayer);
if (itemstack.stackSize == 0) {
final ItemStack itemstack2 = new ItemStack(Items.fishing_rod);
itemstack2.setTagCompound(itemstack.getTagCompound());
entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = itemstack2;
}
}
}
this.thisEntity.moveEntityWithHeading(0.0f, f2);
}
private boolean isStairOrSlab(final Block blockIn) {
return blockIn instanceof BlockStairs || blockIn instanceof BlockSlab;
}
public boolean isSpeedBoosted() {
return this.speedBoosted;
}
public void boostSpeed() {
this.speedBoosted = true;
this.speedBoostTime = 0;
this.maxSpeedBoostTime = this.thisEntity.getRNG().nextInt(841) + 140;
}
public boolean isControlledByPlayer() {
return !this.isSpeedBoosted() && this.currentSpeed > this.maxSpeed * 0.3f;
}
}
| 44.108844 | 405 | 0.621376 |
c3b47253c4661a421c4dd7ccfc610cd4536bf66b | 1,822 | package kr.spring.batch.chapter14.batch;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.JobParametersValidator;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
import java.util.ArrayList;
import java.util.List;
/**
* kr.spring.batch.chapter14.batch.ImportValidator
*
* @author 배성혁 sunghyouk.bae@gmail.com
* @since 13. 8. 18. 오후 9:31
*/
public class ImportValidator implements JobParametersValidator, ResourceLoaderAware {
public static final String PARAM_INPUT_RESOURCE = "inputResource";
public static final String PARAM_REPORT_RESOURCE = "reportResource";
private ResourceLoader resourceLoader;
@Override
public void validate(JobParameters parameters) throws JobParametersInvalidException {
List<String> missing = new ArrayList<String>();
checkParameter(PARAM_INPUT_RESOURCE, parameters, missing);
checkParameter(PARAM_REPORT_RESOURCE, parameters, missing);
if (!missing.isEmpty()) {
throw new JobParametersInvalidException("Missing parameters: " + missing);
}
if (!resourceLoader.getResource(parameters.getString(PARAM_INPUT_RESOURCE)).exists()) {
throw new JobParametersInvalidException(
"The input file: " + parameters.getString(PARAM_INPUT_RESOURCE) + " does not exist");
}
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
private void checkParameter(String key, JobParameters parameters, List<String> missing) {
if (!parameters.getParameters().containsKey(key)) {
missing.add(key);
}
}
}
| 36.44 | 101 | 0.73326 |
dd22caf07e1a343b629181418bcf0e5f7773ddcb | 3,040 | package org.alcha.algalona.models.wow.dataResources;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Created by Alcha on Sep 16, 2017 @ 00:23.</p>
*/
public class PetType {
private int mId;
private String mKey;
private String mName;
private int mTypeAbilityId;
private int mStrongAgainstId;
private int mWeakAgainstId;
public PetType() {
}
@Override
public String toString() {
return "Id=" + mId + "; " +
"Key=" + mKey + "; " +
"Name=" + mName + "; " +
"TypeAbilityId=" + mTypeAbilityId + "; " +
"StrongAgainstId=" + mStrongAgainstId + "; " +
"WeakAgainstId=" + mWeakAgainstId;
}
public static PetType newInstanceFromJson(JsonObject jsonObject) {
PetType type = new PetType();
if (jsonObject.has("id"))
type.setId(jsonObject.get("id").getAsInt());
else type.setId(-1);
if (jsonObject.has("key"))
type.setKey(jsonObject.get("key").getAsString());
else type.setKey("");
if (jsonObject.has("name"))
type.setName(jsonObject.get("name").getAsString());
else type.setName("");
if (jsonObject.has("typeAbilityId"))
type.setTypeAbilityId(jsonObject.get("typeAbilityId").getAsInt());
else type.setTypeAbilityId(-1);
if (jsonObject.has("strongAgainstId"))
type.setStrongAgainstId(jsonObject.get("strongAgainstId").getAsInt());
else type.setStrongAgainstId(-1);
if (jsonObject.has("weakAgainstId"))
type.setWeakAgainstId(jsonObject.get("weakAgainstId").getAsInt());
else type.setWeakAgainstId(-1);
return type;
}
public static List<PetType> parseJsonArray(JsonArray jsonArray) {
List<PetType> petTypes = new ArrayList<>();
for (JsonElement element : jsonArray)
petTypes.add(PetType.newInstanceFromJson(element.getAsJsonObject()));
return petTypes;
}
public int getId() {
return mId;
}
public void setId(int id) {
mId = id;
}
public String getKey() {
return mKey;
}
public void setKey(String key) {
mKey = key;
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public int getTypeAbilityId() {
return mTypeAbilityId;
}
public void setTypeAbilityId(int typeAbilityId) {
mTypeAbilityId = typeAbilityId;
}
public int getStrongAgainstId() {
return mStrongAgainstId;
}
public void setStrongAgainstId(int strongAgainstId) {
mStrongAgainstId = strongAgainstId;
}
public int getWeakAgainstId() {
return mWeakAgainstId;
}
public void setWeakAgainstId(int weakAgainstId) {
mWeakAgainstId = weakAgainstId;
}
}
| 24.715447 | 82 | 0.604276 |
2cf31d11297c3db75f7adade7c28c7ad297f2202 | 1,472 | /*
* web: org.nrg.xnat.turbine.modules.screens.ImageUpload
* XNAT http://www.xnat.org
* Copyright (c) 2005-2017, Washington University School of Medicine and Howard Hughes Medical Institute
* All Rights Reserved
*
* Released under the Simplified BSD.
*/
package org.nrg.xnat.turbine.modules.screens;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;
import org.nrg.xdat.om.ArcArchivespecification;
import org.nrg.xdat.turbine.modules.screens.SecureScreen;
import org.nrg.xnat.turbine.utils.ArcSpecManager;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
/**
* @author timo
*
*/
public class ImageUpload extends SecureScreen {
/* (non-Javadoc)
* @see org.apache.turbine.modules.screens.VelocityScreen#doBuildTemplate(org.apache.turbine.util.RunData, org.apache.velocity.context.Context)
*/
protected void doBuildTemplate(final RunData data, final Context context)
throws MalformedURLException {
final Date d = Calendar.getInstance().getTime();
final SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss");
context.put("uploadID", formatter.format(d));
final ArcArchivespecification arc = ArcSpecManager.GetInstance();
context.put("arc", arc);
final URL url = new URL(arc.getSiteUrl());
context.put("hostname", url.getHost());
}
}
| 32.711111 | 147 | 0.73981 |
6f7a60c0c107212e4c0ac9967dd9cbe90c4a0fd7 | 1,645 | package panda.mvc.view.tag.ui;
import panda.ioc.annotation.IocBean;
/**
* <!-- START SNIPPET: javadoc -->
* <p/>
* A tag that creates a HTML <button >.This tag supports the same attributes as the "url" tag,
* including nested parameters using the "param" tag.
* <p/>
* <!-- END SNIPPET: javadoc -->
* <p/>
* <p/>
* <b>Examples</b>
* <p/>
*
* <pre>
* <!-- START SNIPPET: example1 -->
* <s:button id="link1" theme="ajax" href="/DoIt.action">
* <img border="none" src="<%=request.getContextPath()%>/images/delete.gif"/>
* <s:param name="id" value="1"/>
* </s:button>
* <!-- END SNIPPET: example1 -->
* </pre>
*/
@IocBean(singleton=false)
public class Button extends UIBean {
protected String btype;
protected String icon;
protected String sicon;
protected String label;
@Override
public boolean usesBody() {
return true;
}
/**
* @return the btype
*/
public String getBtype() {
return btype;
}
/**
* @return the icon
*/
public String getIcon() {
return icon;
}
/**
* @return the sicon
*/
public String getSicon() {
return sicon;
}
/**
* @param btype the btype to set
*/
public void setBtype(String btype) {
this.btype = btype;
}
/**
* @param icon the icon to set
*/
public void setIcon(String icon) {
this.icon = icon;
}
/**
* @param sicon the sicon to set
*/
public void setSicon(String sicon) {
this.sicon = sicon;
}
/**
* @return the label
*/
public String getLabel() {
return label;
}
/**
* @param label the label to set
*/
public void setLabel(String label) {
this.label = label;
}
}
| 17.135417 | 100 | 0.609119 |
55721cc145c7b21d20e0b39b714828f5c4640dc1 | 8,041 | /*
* Copyright 2021 EPAM Systems, Inc
*
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. 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.epam.deltix.qsrv.hf.archive;
import com.epam.deltix.qsrv.hf.BaseTopicReadingTest;
import com.epam.deltix.qsrv.hf.RatePrinter;
import com.epam.deltix.qsrv.hf.StubData;
import com.epam.deltix.qsrv.hf.pub.md.RecordClassDescriptor;
import com.epam.deltix.qsrv.hf.tickdb.pub.Messages;
import com.epam.deltix.qsrv.hf.tickdb.pub.topic.MessagePoller;
import com.epam.deltix.qsrv.hf.tickdb.pub.topic.MessageProcessor;
import com.epam.deltix.qsrv.hf.topic.consumer.DirectReaderFactory;
import com.epam.deltix.util.io.idlestrat.YieldingIdleStrategy;
import io.aeron.Aeron;
import io.aeron.CommonContext;
import io.aeron.Subscription;
import io.aeron.archive.Archive;
import io.aeron.archive.ArchivingMediaDriver;
import io.aeron.archive.client.AeronArchive;
import io.aeron.driver.MediaDriver;
import org.agrona.collections.MutableLong;
import org.junit.Assert;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author Alexei Osipov
*/
public class AeronArchiveReadTest {
private static final int TEST_DURATION_MS = 60 * 1000;
static final int REPLAY_STREAM_ID = 88888;
private final Aeron aeron;
private final AeronArchive aeronArchive;
private AtomicBoolean running;
public AeronArchiveReadTest(Aeron aeron, AeronArchive aeronArchive) {
this.aeron = aeron;
this.aeronArchive = aeronArchive;
}
public static void main(String[] args) throws Exception {
File archiveDir = new File(AeronArchiveWriteTest.ARCHIVE_DIR);
MediaDriver.Context driverCtx = new MediaDriver.Context()
.dirDeleteOnStart(true)
.spiesSimulateConnection(true);
Archive.Context archiveCtx = new Archive.Context()
.archiveDir(archiveDir);
ArchivingMediaDriver archivingMediaDriver = ArchivingMediaDriver.launch(
driverCtx,
archiveCtx
);
//Archive archive = archivingMediaDriver.archive();
Aeron client = Aeron.connect();
AeronArchive aeronArchive = AeronArchive.connect(new AeronArchive.Context()
.aeron(client)
//.controlResponseStreamId(archiveCtx.controlStreamId())
//.ownsAeronClient(false)
);
AeronArchiveReadTest test = new AeronArchiveReadTest(client, aeronArchive);
test.executeTest();
client.close();
archivingMediaDriver.close();
}
void executeTest() throws Exception {
String replayChannel = CommonContext.IPC_CHANNEL;
int replayStreamId = REPLAY_STREAM_ID;
List<RecordClassDescriptor> types = Collections.singletonList(Messages.ERROR_MESSAGE_DESCRIPTOR);
AtomicLong messagesReceivedCounter = new AtomicLong(0);
List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<Throwable>());
BaseTopicReadingTest.MessageValidator messageValidator = new BaseTopicReadingTest.MessageValidator();
Runnable runnable = createReader(messagesReceivedCounter, replayChannel, replayStreamId, types, messageValidator, AeronArchiveWriteTest.MESSAGE_COUNT_TO_SEND);
Thread readerThread = new Thread(runnable);
readerThread.setName("READER");
readerThread.setUncaughtExceptionHandler((t, e) -> exceptions.add(e));
readerThread.start();
long recordingId = findRecordingId();
Subscription replaySub = aeronArchive.replay(recordingId, 0, Long.MAX_VALUE, replayChannel, replayStreamId);
replaySub.close();
//aeronArchive.archiveProxy().replay(recordingId, 0, Long.MAX_VALUE, replayChannel, replayStreamId);
// Let test to work
//Thread.sleep(TEST_DURATION_MS);
readerThread.join(TEST_DURATION_MS);
// Let reader finish off the queue
//Thread.sleep(1000);
// Stop reader
stopReader();
readerThread.join(1000);
Assert.assertFalse(readerThread.isAlive());
Assert.assertTrue("Exception in threads", exceptions.isEmpty());
Assert.assertTrue(messagesReceivedCounter.get() > 0);
System.out.println("Message count: " + messagesReceivedCounter);
}
private long findRecordingId() {
final MutableLong foundRecordingId = new MutableLong();
final int recordingsFound = aeronArchive.listRecordingsForUri(
0L,
100,
AeronArchiveWriteTest.ORIGINAL_CHANNEL,
AeronArchiveWriteTest.ORIGINAL_DATA_STREAM_ID,
(
controlSessionId,
correlationId,
recordingId,
startTimestamp,
stopTimestamp,
startPosition,
stopPosition,
initialTermId,
segmentFileLength,
termBufferLength,
mtuLength,
sessionId,
streamId,
strippedChannel,
originalChannel,
sourceIdentity
) -> foundRecordingId.set(recordingId));
if (recordingsFound == 0) {
throw new IllegalStateException(
"No recordings found for channel=" + AeronArchiveWriteTest.ORIGINAL_CHANNEL + " streamId=" + AeronArchiveWriteTest.ORIGINAL_DATA_STREAM_ID);
}
return foundRecordingId.get();
}
protected Runnable createReader(AtomicLong messagesReceivedCounter, String channel, int dataStreamId, List<RecordClassDescriptor> types, BaseTopicReadingTest.MessageValidator messageValidator, long expectedMessageCount) {
AtomicBoolean runningFlag = new AtomicBoolean(true);
running = runningFlag;
return () -> {
MessagePoller messagePoller = new DirectReaderFactory().createPoller(aeron, false, channel, dataStreamId, types, StubData.getStubMappingProvider());
RatePrinter ratePrinter = new RatePrinter("Reader");
YieldingIdleStrategy idleStrategy = new YieldingIdleStrategy();
MessageProcessor processor = m -> {
messageValidator.validate(m);
messagesReceivedCounter.incrementAndGet();
ratePrinter.inc();
};
long startTime = System.nanoTime();
boolean x = true;
while (runningFlag.get() && messagesReceivedCounter.get() < expectedMessageCount) {
idleStrategy.idle(
messagePoller.processMessages(100, processor)
);
}
long stopTime = System.nanoTime();
messagePoller.close();
long timeDeltaNanos = stopTime - startTime;
System.out.printf("Messages: %d\n", messagesReceivedCounter.get());
System.out.printf("Seconds: %.3f\n", ((float) timeDeltaNanos) / 1_000_000_000 );
System.out.printf("Rate: %.3f k msg/s\n", ((float) messagesReceivedCounter.get() * 1_000_000) / timeDeltaNanos);
};
}
protected void stopReader() {
running.set(false);
}
}
| 38.109005 | 225 | 0.660614 |
49a6e90abdef498a9f716509374a2d4924aaf643 | 1,856 | package com.ibm.nmon.data.transform;
import com.ibm.nmon.data.DataRecord;
import com.ibm.nmon.data.DataSet;
import com.ibm.nmon.data.DataType;
import com.ibm.nmon.data.SubDataType;
/**
* Post processor to add a <code>Network Interface (Total)</code> data type that aggregates data for
* all network interfaces.
*/
public final class WindowsNetworkPostProcessor implements DataPostProcessor {
@Override
public void addDataTypes(DataSet data) {
SubDataType total = null;
for (DataType type : data.getTypes()) {
if (type.getId().contains("Network Interface")) {
total = new SubDataType("Network Interface", "Total", "Network Interface", type.getFields().toArray(
new String[type.getFieldCount()]));
break;
}
}
if (total != null) {
data.addType(total);
}
}
@Override
public void postProcess(DataSet data, DataRecord record) {
DataType total = data.getType("Network Interface" + " (Total)");
if (total == null) {
return;
}
int totalFieldCount = total.getFieldCount();
double[] totalData = new double[totalFieldCount];
for (int i = 0; i < totalData.length; i++) {
totalData[i] = 0;
}
for (DataType type : data.getTypes()) {
if (type.getId().startsWith("Network Interface") && (type != total)) {
if (record.hasData(type)) {
double[] typeData = record.getData(type);
// assume ordering is the same for all types
for (int i = 0; i < totalFieldCount; i++) {
totalData[i] += typeData[i];
}
}
}
}
record.addData(total, totalData);
}
}
| 30.933333 | 116 | 0.553341 |
5fa1ff0c68aae13cf67107277806fccf3f17e2a2 | 475 | package party.threebody.skean.dict.domain.criteria;
public class RelFilterNode extends FilterNode {
private Pred pred;
public Pred getPred() {
return pred;
}
public void setPred(Pred pred) {
this.pred = pred;
}
public enum Pred {
subOf(9), instOf(8), subsOf(3), subtOf(3),
supOf(3), defOf(2), supsOf(2), suptOf(2);
private int cost;
Pred(int cost) {
this.cost = cost;
}
}
}
| 19.791667 | 51 | 0.564211 |
1b54ff86fbb55f0af373d4c72f996f8ad06c2ec1 | 689 | package com.nottoomanyitems.stepup;
import de.guntram.mcmod.fabrictools.ConfigurationProvider;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
public class Main implements ClientModInitializer {
public static final String MODNAME="StepUp";
@Override
public void onInitializeClient() {
ConfigurationProvider.register(MODNAME, new ConfigHandler());
ConfigHandler.load(ConfigurationProvider.getSuggestedFile("stepup"));
StepChanger stepChanger = new StepChanger();
stepChanger.setKeyBindings();
ClientTickEvents.END_CLIENT_TICK.register(stepChanger);
}
}
| 34.45 | 77 | 0.764877 |
d064da3bd8038b327d99b11b62bc9e2337f04d11 | 1,238 | package com.jjh.android.boundservicedemo;
import android.app.Service;
import android.os.Binder;
import android.os.IBinder;
import android.content.Intent;
import android.util.Log;
import java.util.Date;
public class BoundService extends Service {
private static final String TAG = "BoundService";
// Binding support
private IBinder binder = new DemoBinder();
public class DemoBinder extends Binder {
BoundService getService() {
return BoundService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind()");
return binder;
}
@Override
public void onRebind(Intent intent) {
Log.d(TAG, "onRebind()");
super.onRebind(intent);
}
@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "onUnbind()");
return true;
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate()");
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy()");
}
// Functionality offered by service
public Date getDate() {
Log.d(TAG, "getDate()");
return new Date();
}
}
| 21.344828 | 53 | 0.608239 |
a6b2ffaf86a747827abc6e9585b60507720d9548 | 14,402 | /*
* Copyright 2006-2021 The JGUIraffe Team.
*
* 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 net.sf.jguiraffe.gui.builder.components.tags.table;
import net.sf.jguiraffe.gui.builder.components.FormBuilderException;
import net.sf.jguiraffe.gui.layout.NumberWithUnit;
/**
* <p>
* A helper class that provides functionality for managing the widths of the
* columns of a table.
* </p>
* <p>
* An instance of this class is created and initialized by {@link TableTag}. It
* can be used by platform-specific table implementations. It helps storing the
* column widths of a table and provides some helper methods for calculating
* widths if columns with a relative width are involved. Because this
* functionality is not platform-specific it is collected in this helper class.
* </p>
* <p>
* Implementation note: This class is not thread-safe.
* </p>
*
* @author Oliver Heger
* @version $Id: TableColumnWidthController.java 205 2012-01-29 18:29:57Z oheger $
*/
public final class TableColumnWidthController implements
TableColumnRecalibrator, TableColumnWidthCalculator
{
/** Constant for percent calculations. */
private static final double PERCENT = 100;
/** An array with the original fixed widths of the columns. */
private final NumberWithUnit[] originalWidths;
/** An array with the current fixed widths. */
private final int[] fixedWidths;
/** Stores the current percent values. */
private final double[] percentValues;
/** The number of columns with a percent width. */
private final int numberOfColumnsWithPercentWidth;
/**
* Creates a new instance of {@code TableColumnWidthController}. This
* constructor is used internally. Clients create instances using the static
* factory method.
*
* @param orgWidths an array with the original width definitions for columns
* with fixed width
* @param percents the current percent widths for all columns
* @param percentCnt the number of columns with a percent width
*/
private TableColumnWidthController(NumberWithUnit[] orgWidths,
double[] percents, int percentCnt)
{
originalWidths = orgWidths;
percentValues = percents;
numberOfColumnsWithPercentWidth = percentCnt;
fixedWidths = new int[orgWidths.length];
}
/**
* Creates a new instance of {@link TableColumnWidthController} and
* initializes it with the information provided by the given {@code
* TableTag}. This factory method first checks whether the widths of the
* columns managed by the table tag are valid; if not, an exception is
* thrown. Then an instance is created and initialized with the column
* widths.
*
* @param tt the {@code TableTag} (must not be <b>null</b>)
* @return a new instance of this class
* @throws FormBuilderException if the widths of the table's columns are
* invalid
* @throws IllegalArgumentException if the tag is <b>null</b>
*/
public static TableColumnWidthController newInstance(TableTag tt)
throws FormBuilderException
{
if (tt == null)
{
throw new IllegalArgumentException("TableTag must not be null!");
}
NumberWithUnit[] widths = new NumberWithUnit[tt.getColumnCount()];
int sumPercents = 0;
int percentCnt = 0;
int undefPercentCnt = 0;
for (int i = 0; i < widths.length; i++)
{
TableColumnTag colTag = tt.getColumn(i);
checkColumnWidthSpec(colTag);
if (isPercentWidth(colTag))
{
sumPercents += colTag.getPercentWidth();
percentCnt++;
if (colTag.getPercentWidth() == 0)
{
undefPercentCnt++;
}
}
else
{
widths[i] = colTag.getColumnWidth();
}
}
return new TableColumnWidthController(widths,
calculateInitialPercentValues(tt, percentCnt, sumPercents,
undefPercentCnt), percentCnt);
}
/**
* Returns the number of columns managed by this instance.
*
* @return the number of columns
*/
public int getColumnCount()
{
return originalWidths.length;
}
/**
* Tests whether the column with the specified index has a relative width.
* This means that the width is specified as a percent value.
*
* @param index the index of the column (0-based)
* @return a flag whether this column has a percent width
*/
public boolean isPercentWidth(int index)
{
return originalWidths[index] == null;
}
/**
* Returns the original fixed width of the specified column. This is the
* value defined by the {@code width} attribute of the table column tag. If
* the column in question does not have a fixed width, this method returns
* <b>null</b>.
*
* @param index the index of the column (0-based)
* @return the original width of this column or <b>null</b>
*/
public NumberWithUnit getOriginalFixedWidth(int index)
{
return originalWidths[index];
}
/**
* Returns the fixed width (in pixels) of the column with the specified
* index. Here the width of the column transformed into pixels is returned.
* If this column does not have a fixed width, this method returns 0.
*
* @param index the index of the column (0-based)
* @return the fixed width of this column in pixels
*/
public int getFixedWidth(int index)
{
return fixedWidths[index];
}
/**
* Sets the fixed width of the column with the specified index (in pixels).
* This method is intended to be called by a platform-specific table
* implementation. When the table is created the {@link NumberWithUnit}
* values for column widths have to be transformed to pixel values. If later
* the width of the column changes, this value has to be updated.
*
* @param index the index of the column (0-based)
* @param width the new fixed width of the column
*/
public void setFixedWidth(int index, int width)
{
fixedWidths[index] = width;
}
/**
* Returns the relative width (in percent) of the column with the specified
* index. If the column in question does not have a percent width, this
* method returns 0.
*
* @param index the index of the column (0-based)
* @return the width of this column in percent
*/
public int getPercentValue(int index)
{
return roundInt(percentValues[index] * PERCENT);
}
/**
* Returns the number of columns managed by this controller whose width is
* specified as a percent value.
*
* @return the number of columns with a percent value as width
*/
public int getNumberOfColumnWithPercentWidth()
{
return numberOfColumnsWithPercentWidth;
}
/**
* {@inheritDoc} This implementation evaluates the current widths of columns
* with fixed or percent widths.
*/
public int[] calculateWidths(int totalSize)
{
int[] widths = new int[getColumnCount()];
int sum = 0;
// handle columns with a fixed width
for (int i = 0; i < widths.length; i++)
{
if (!isPercentWidth(i))
{
widths[i] = fixedWidths[i];
sum += fixedWidths[i];
}
}
// handle columns with a percent width
int remaining = totalSize - sum;
if (remaining > 0)
{
for (int i = 0; i < widths.length; i++)
{
if (isPercentWidth(i))
{
widths[i] = roundInt(remaining * percentValues[i]);
}
}
}
return widths;
}
/**
* {@inheritDoc} This implementation adjusts the current width values for
* columns with a fixed width and recalculates the percent values for the
* other columns.
*/
public void recalibrate(int[] columnSizes)
{
if (columnSizes == null)
{
throw new IllegalArgumentException(
"Array with column sizes must not be null!");
}
if (columnSizes.length != getColumnCount())
{
throw new IllegalArgumentException(
"Wrong number of elements in columns array!");
}
int totalSize = sumUpTotalSize(columnSizes);
int fixedSize = recalibrateFixedWidths(columnSizes);
double remainingSize = totalSize - fixedSize;
for (int i = 0; i < columnSizes.length; i++)
{
if (isPercentWidth(i))
{
percentValues[i] = (remainingSize == 0) ? 0
: columnSizes[i] / remainingSize;
}
}
}
/**
* Performs the recalibration of columns with a fixed width. This method
* also sums up the width of all columns with a fixed width.
*
* @param columnSizes the array with the column sizes
* @return the sum of the widths of the columns with a fixed width
*/
private int recalibrateFixedWidths(int[] columnSizes)
{
int fixedWidth = 0;
for (int i = 0; i < columnSizes.length; i++)
{
if (!isPercentWidth(i))
{
fixedWidths[i] = columnSizes[i];
fixedWidth += columnSizes[i];
}
}
return fixedWidth;
}
/**
* Validates the width specification for the specified column tag. Throws an
* exception if the specification is invalid, i.e. if both a fixed and a
* relative width is specified or if the percent value is invalid.
*
* @param colTag the column tag to be checked
* @throws FormBuilderException if the width specification is invalid
*/
private static void checkColumnWidthSpec(TableColumnTag colTag)
throws FormBuilderException
{
if (colTag.getColumnWidth() != null)
{
if (colTag.getPercentWidth() != 0)
{
throw new FormBuilderException(
"Column has both a fixed and a relative width!");
}
}
else
{
if (colTag.getPercentWidth() < 0 || colTag.getPercentWidth() > PERCENT)
{
throw new FormBuilderException(String.format(
"Invalid percent width %d!", colTag.getPercentWidth()));
}
}
}
/**
* Tests whether the column represented by the column tag has a percent
* width.
*
* @param colTag the column tag
* @return a flag whether this column has a percent value
*/
private static boolean isPercentWidth(TableColumnTag colTag)
{
return colTag.getColumnWidth() == null;
}
/**
* Calculates the percent values for all columns. This method is needed if
* the sum of percent values is less than 100. In this case the difference
* to 100 is determined, and the remaining number is added to all columns
* with an undefined percent value in equal parts.
*
* @param tt the table tag
* @param percentCnt the number of columns with a percent value
* @param sumPercents the sum of the percent values
* @param undefPercentCnt the number of columns with an undefined percent
* value
* @return an array with all percent values
* @throws FormBuilderException if the sum of percent values is invalid
*/
private static double[] calculateInitialPercentValues(TableTag tt,
int percentCnt, int sumPercents, int undefPercentCnt)
throws FormBuilderException
{
if (sumPercents > PERCENT)
{
throw new FormBuilderException(
"Sum of percent values is greater than 100: " + sumPercents);
}
double[] percents = new double[tt.getColumnCount()];
if (undefPercentCnt > 0)
{
double delta = (PERCENT - sumPercents) / undefPercentCnt;
for (int i = 0; i < percents.length; i++)
{
TableColumnTag colTag = tt.getColumn(i);
if (isPercentWidth(colTag))
{
double percentWidth =
(colTag.getPercentWidth() != 0) ? colTag
.getPercentWidth() : delta;
percents[i] = percentWidth / PERCENT;
}
}
}
else if (percentCnt > 0)
{
double delta = (PERCENT - sumPercents) / percentCnt / PERCENT;
for (int i = 0; i < percents.length; i++)
{
TableColumnTag colTag = tt.getColumn(i);
if (isPercentWidth(colTag))
{
percents[i] = colTag.getPercentWidth() / PERCENT + delta;
}
}
}
return percents;
}
/**
* Helper method for calculating the sum of the given array with column
* sizes.
*
* @param columnSizes an array with column sizes
* @return the sum of the sizes
*/
private static int sumUpTotalSize(int[] columnSizes)
{
int totalSize = 0;
for (int columnSize : columnSizes)
{
totalSize += columnSize;
}
return totalSize;
}
/**
* Helper method for rounding a double value to an int.
*
* @param value the value
* @return the rounded integer value
*/
private static int roundInt(double value)
{
return (int) Math.round(value);
}
}
| 33.26097 | 83 | 0.602486 |
cf134b7793a757984e90a10a05b25d28d90031d5 | 955 | /*
* https://www.hackerrank.com/challenges/the-hurdle-race/problem
*/
package com.mycom.hackerrank.algorithm.implementations;
import java.util.Arrays;
import com.mycom.hackerrank.algorithm.utils.ReadFile;
/**
* @author hongquan.doan
*
*/
public class HurdleRace {
/**
* The wording is unambiguous, it says that "Each time Dan drinks a magic beverage,
* the maximum height he can jump during the race increases by unit"
* ==> each drink can increase by 01 unit
*
* Each drink lasts the whole race, so you are correct that you only need
* to calculate the difference between the highest hurdle and his current maximum.
*
* @param args
*/
public static void main(String[] args) {
String f = "./samples/hurdlerace.txt";
// int n = ReadFile.readFileInt(f, 0)[0];
int k = ReadFile.readFileInt(f, 0)[1];
int[] h = ReadFile.readFileInt(f, 1);
Arrays.sort(h);
System.out.println(Math.max(0, h[h.length - 1] - k));
}
}
| 27.285714 | 85 | 0.692147 |
cf86d68fc7f21f476136fe4bec1aef6edb83a41b | 328 |
package edu.spcollege.ecox.signin;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
*
* @author atillman
*/
@Controller
public class SignInController {
@RequestMapping(value = "signin")
public String signin() {
return "signin/signin";
}
}
| 17.263158 | 62 | 0.731707 |
bd91eb29453ea7eb00acc59fe6cad532f4a6736c | 4,722 | package edu.georgetown.library.fileAnalyzer.util;
import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
import gov.loc.repository.bagit.Bag;
import gov.loc.repository.bagit.BagFactory;
import gov.loc.repository.bagit.BagInfoTxt;
import gov.loc.repository.bagit.transformer.impl.DefaultCompleter;
import gov.loc.repository.bagit.writer.Writer;
import gov.loc.repository.bagit.writer.impl.FileSystemWriter;
public class FABagHelper {
public enum STAT {
VALID,
INVALID,
ERROR
}
public static final String P_INSTID = "inst-id";
public static final String P_ITEMUID = "item-uid";
public static final String P_SRCORG = "source-org";
public static final String P_BAGTOTAL = "bag-total";
public static final String P_BAGCOUNT = "bag-count";
public static final String P_BAGCOUNTSTR = "bag-count-str";
public static final String P_INTSENDDESC = "internal-sender-desc";
public static final String P_INTSENDID = "internal-sender-id";
public static final String P_TITLE = "title";
public static final String P_ACCESS = "access";
FABagHelperData data = new FABagHelperData();
public static Pattern pBagCountStr = Pattern.compile("^(\\d+) of (\\d+|\\?)$");
public FABagHelper(File source) {
this.data.source = source;
this.data.parent = source.getParentFile();
data.bf = new BagFactory();
data.bag = data.bf.createBag();
}
public void validate() throws IncompleteSettingsException {
StringBuilder sb = new StringBuilder();
validateImpl(sb);
if (sb.length() > 0) {
throw new IncompleteSettingsException(sb.toString());
}
}
public void validateImpl(StringBuilder sb) throws IncompleteSettingsException {
}
public void createBagFile() throws IncompleteSettingsException {
validate();
data.newBag = new File(data.parent, data.source.getName() + "_bag");
}
public Bag getBag() {
return data.bag;
}
public void generateBagInfoFiles() throws IOException, IncompleteSettingsException {
validate();
if (data.newBag == null) throw new IncompleteSettingsException("Bag File must be created - call createBagFile()");
DefaultCompleter comp = new DefaultCompleter(data.bf);
comp.setGenerateBagInfoTxt(true);
comp.setUpdateBaggingDate(true);
comp.setUpdateBagSize(true);
comp.setUpdatePayloadOxum(true);
comp.setGenerateTagManifest(false);
data.bag = comp.complete(data.bag);
}
public void writeBagFile() throws IOException, IncompleteSettingsException {
validate();
if (data.newBag == null) throw new IncompleteSettingsException("Bag File must be created - call createBagFile()");
Writer writer = new FileSystemWriter(data.bf);
data.bag.write(writer, data.newBag);
data.bag.close();
}
public String getFinalBagName() throws IncompleteSettingsException {
validate();
if (data.newBag == null) throw new IncompleteSettingsException("Bag File must be created - call createBagFile() and writeBagFile()");
return data.newBag.getName();
}
public void setBagCountStr(String countStr) throws IncompleteSettingsException {
BagInfoTxt bit = data.bag.getBagInfoTxt();
if (bit == null) {
throw new IncompleteSettingsException("Bag info file must be generated before the count can be set");
}
bit.setBagCount(countStr);
}
public static void validateBagCount(String bagNum, String bagTot) throws IncompleteSettingsException {
int ibagNum = 0;
try {
ibagNum = Integer.parseInt(bagNum);
} catch(NumberFormatException e) {
throw new IncompleteSettingsException(String.format("Bag Number (%s) must be numeric", bagNum));
}
if (ibagNum < 1) {
throw new IncompleteSettingsException(String.format("Bag Number (%d) must be 1 or larger", ibagNum));
}
if (!bagTot.equals("?")) {
try {
int ibagTot = Integer.parseInt(bagTot);
if (ibagTot < 1) {
throw new IncompleteSettingsException(String.format("Bag Total (%d) must be 1 or larger", ibagTot));
}
if (ibagNum > ibagTot) {
throw new IncompleteSettingsException(String.format("Bag Num (%d) cannot be larger than Bag Total(%d)", ibagNum, ibagTot));
}
} catch(NumberFormatException e) {
throw new IncompleteSettingsException(String.format("Bag Total (%s) must be '?' or numeric", bagTot));
}
}
}
}
| 38.080645 | 155 | 0.658831 |
3447ec7d25f78dc2deb7ff84a964e6a99a78416f | 1,858 | package com.kfyty.boot.beans.factory;
import com.kfyty.boot.proxy.ScopeProxyInterceptorProxy;
import com.kfyty.support.autoconfig.BeanFactoryAware;
import com.kfyty.support.autoconfig.beans.BeanDefinition;
import com.kfyty.support.autoconfig.beans.BeanFactory;
import com.kfyty.support.autoconfig.beans.FactoryBean;
import com.kfyty.support.proxy.factory.DynamicProxyFactory;
import com.kfyty.support.utils.AopUtil;
/**
* 描述: 为非单例 bean 创建作用域代理
*
* @author kfyty725
* @date 2021/7/11 12:43
* @email kfyty725@hotmail.com
*/
public class ScopeProxyFactoryBean<T> implements BeanFactoryAware, FactoryBean<T> {
/**
* 作用域代理原 bean 名称前缀
*/
public static final String SCOPE_PROXY_SOURCE_PREFIX = "scope.proxy.source.";
private BeanFactory beanFactory;
private final String beanName;
private final BeanDefinition sourceBeanDefinition;
public ScopeProxyFactoryBean(BeanDefinition sourceBeanDefinition) {
this.beanName = sourceBeanDefinition.getBeanName();
this.sourceBeanDefinition = sourceBeanDefinition;
if (!this.beanName.startsWith(SCOPE_PROXY_SOURCE_PREFIX)) {
sourceBeanDefinition.setBeanName(SCOPE_PROXY_SOURCE_PREFIX + sourceBeanDefinition.getBeanName());
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public String getBeanName() {
return this.beanName;
}
@Override
public Class<?> getBeanType() {
return this.sourceBeanDefinition.getBeanType();
}
@Override
public T getObject() {
Object proxy = DynamicProxyFactory.create(true).createProxy(this.getBeanType());
AopUtil.addProxyInterceptorPoint(proxy, new ScopeProxyInterceptorProxy(this.beanFactory, this.sourceBeanDefinition));
return (T) proxy;
}
}
| 31.491525 | 125 | 0.734661 |
7e1cb50dca5eec91cf910b8faeff4ae99ca71a73 | 7,583 | package com.simonbaars.clonerefactor.settings;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import com.simonbaars.clonerefactor.refactoring.enums.RefactoringStrategy;
public class Settings {
private static final String CLONEREFACTOR_PROPERTIES = "clonerefactor.properties";
private static final Settings settings = new Settings();
// General
private CloneType cloneType;
private Scope scope;
// Clone detection thresholds
private int minAmountOfLines;
private int minAmountOfTokens;
private int minAmountOfNodes;
private int minCloneClassSize;
// Type-specific settings
private double type2VariabilityPercentage;
private double type3GapSize;
// Transform the AST and refactor the code
private RefactoringStrategy refactoringStrategy;
private boolean printProgress;
private Settings(Builder builder) {
this.cloneType = builder.cloneType;
this.scope = builder.scope;
this.minAmountOfLines = builder.minAmountOfLines;
this.minAmountOfTokens = builder.minAmountOfTokens;
this.minAmountOfNodes = builder.minAmountOfNodes;
this.minCloneClassSize = builder.minCloneClassSize;
this.type2VariabilityPercentage = builder.type2VariabilityPercentage;
this.type3GapSize = builder.type3GapSize;
this.refactoringStrategy = builder.refactoringStrategy;
this.printProgress = builder.printProgress;
}
private Settings() {
try (InputStream input = Settings.class.getClassLoader().getResourceAsStream(CLONEREFACTOR_PROPERTIES)) {
Properties prop = new Properties();
prop.load(input);
cloneType = CloneType.valueOf(prop.getProperty("clone_type"));
scope = Scope.valueOf(prop.getProperty("scope"));
minAmountOfLines = Integer.parseInt(prop.getProperty("min_lines"));
minAmountOfTokens = Integer.parseInt(prop.getProperty("min_tokens"));
minAmountOfNodes = Integer.parseInt(prop.getProperty("min_statements"));
setMinCloneClassSize(Integer.parseInt(prop.getProperty("min_clone_class_size")));
type2VariabilityPercentage = percentageStringToDouble(prop.getProperty("max_type2_variability_percentage"));
type3GapSize = percentageStringToDouble(prop.getProperty("max_type3_gap_size"));
refactoringStrategy = RefactoringStrategy.valueOf(prop.getProperty("refactoring_strategy"));
printProgress = prop.getProperty("print_progress").equalsIgnoreCase("true");
} catch (IOException ex) {
throw new IllegalStateException("Could not get settings! Please check for the existence of the properties file!");
}
}
private float percentageStringToDouble(String property) {
return Float.parseFloat(property.endsWith("%") ? property.substring(0, property.length()-1) : property);
}
@Override
public String toString() {
return String.format(
"Settings [cloneType=%s, scope=%s, minAmountOfLines=%s, minAmountOfTokens=%s, minAmountOfNodes=%s, minCloneClassSize=%s, type2VariabilityPercentage=%s, type3GapSize=%s, refactoringStrategy=%s]",
cloneType, scope, minAmountOfLines, minAmountOfTokens, minAmountOfNodes, minCloneClassSize, type2VariabilityPercentage, type3GapSize, refactoringStrategy);
}
/*
* Getters and setters
*/
public static Settings get() {
return settings;
}
public CloneType getCloneType() {
return cloneType;
}
public int getMinAmountOfLines() {
return minAmountOfLines;
}
public int getMinAmountOfTokens() {
return minAmountOfTokens;
}
public int getMinAmountOfNodes() {
return minAmountOfNodes;
}
public boolean useLiteratureTypeDefinitions() {
return !getCloneType().isRefactoringOriented();
}
public double getType2VariabilityPercentage() {
return type2VariabilityPercentage;
}
public double getType3GapSize() {
return type3GapSize;
}
public void setCloneType(CloneType cloneType) {
this.cloneType = cloneType;
}
public void setMinAmountOfLines(int minAmountOfLines) {
this.minAmountOfLines = minAmountOfLines;
}
public void setMinAmountOfTokens(int minAmountOfTokens) {
this.minAmountOfTokens = minAmountOfTokens;
}
public void setMinAmountOfNodes(int minAmountOfNodes) {
this.minAmountOfNodes = minAmountOfNodes;
}
public void setType2VariabilityPercentage(double type2VariabilityPercentage) {
this.type2VariabilityPercentage = type2VariabilityPercentage;
}
public void setType3GapSize(double type3GapSize) {
this.type3GapSize = type3GapSize;
}
public Scope getScope() {
return scope;
}
public void setScope(Scope scope) {
this.scope = scope;
}
public RefactoringStrategy getRefactoringStrategy() {
return refactoringStrategy;
}
public void setRefactoringStrategy(RefactoringStrategy refactoringStrategy) {
this.refactoringStrategy = refactoringStrategy;
}
public int getMinCloneClassSize() {
return minCloneClassSize;
}
public void setMinCloneClassSize(int minCloneClassSize) {
this.minCloneClassSize = minCloneClassSize;
}
public boolean isPrintProgress() {
return printProgress;
}
public void setPrintProgress(boolean printProgress) {
this.printProgress = printProgress;
}
/**
* Creates builder to build {@link Settings}.
* @return created builder
*/
public static Builder builder() {
return new Builder();
}
/**
* Builder to build {@link Settings}.
*/
public static final class Builder {
private CloneType cloneType;
private Scope scope;
private int minAmountOfLines;
private int minAmountOfTokens;
private int minAmountOfNodes;
private int minCloneClassSize;
private double type2VariabilityPercentage;
private double type3GapSize;
private RefactoringStrategy refactoringStrategy;
private boolean printProgress;
private Builder() {
Settings s = settings;
this.cloneType = s.cloneType;
this.scope = s.scope;
this.minAmountOfLines = s.minAmountOfLines;
this.minAmountOfTokens = s.minAmountOfTokens;
this.minAmountOfNodes = s.minAmountOfNodes;
this.minCloneClassSize = s.minCloneClassSize;
this.type2VariabilityPercentage = s.type2VariabilityPercentage;
this.type3GapSize = s.type3GapSize;
this.refactoringStrategy = s.refactoringStrategy;
this.printProgress = s.printProgress;
}
public Builder withCloneType(CloneType cloneType) {
this.cloneType = cloneType;
return this;
}
public Builder withScope(Scope scope) {
this.scope = scope;
return this;
}
public Builder withMinAmountOfLines(int minAmountOfLines) {
this.minAmountOfLines = minAmountOfLines;
return this;
}
public Builder withMinAmountOfTokens(int minAmountOfTokens) {
this.minAmountOfTokens = minAmountOfTokens;
return this;
}
public Builder withMinAmountOfNodes(int minAmountOfNodes) {
this.minAmountOfNodes = minAmountOfNodes;
return this;
}
public Builder withMinCloneClassSize(int minCloneClassSize) {
this.minCloneClassSize = minCloneClassSize;
return this;
}
public Builder withType2VariabilityPercentage(double type2VariabilityPercentage) {
this.type2VariabilityPercentage = type2VariabilityPercentage;
return this;
}
public Builder withType3GapSize(double type3GapSize) {
this.type3GapSize = type3GapSize;
return this;
}
public Builder withRefactoringStrategy(RefactoringStrategy refactoringStrategy) {
this.refactoringStrategy = refactoringStrategy;
return this;
}
public Builder withPrintProgress(boolean printProgress) {
this.printProgress = printProgress;
return this;
}
public Settings build() {
return new Settings(this);
}
}
}
| 29.165385 | 198 | 0.763154 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.