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 |
|---|---|---|---|---|---|
263b4a255a04b47ad4fb914e3d3b2f9cba7cd543 | 2,743 |
//----------------------------------------------------
// The following code was generated by Java(tm) CUP v0.9d
// Fri May 07 07:55:04 MSD 2010
//----------------------------------------------------
package jasmin;
/** JavaCup generated class containing symbol constants. */
public class sym {
/* terminals */
static final int FROM = 27;
static final int DSIGNATURE = 19;
static final int SYNTHETIC = 59;
static final int OUTER = 37;
static final int DCLASS = 3;
static final int DVAR = 13;
static final int DSUPER = 10;
static final int SIGNATURE = 29;
static final int ENUM = 55;
static final int INVISIBLE = 39;
static final int INNER = 36;
static final int Insn = 68;
static final int TABLESWITCH = 61;
static final int STACK = 30;
static final int Int = 69;
static final int LOOKUPSWITCH = 60;
static final int TRANSIENT = 52;
static final int PROTECTED = 48;
static final int FINAL = 44;
static final int DSOURCE = 11;
static final int EQ = 63;
static final int CLASS = 34;
static final int DDEBUG = 17;
static final int ABSTRACT = 43;
static final int DINTERFACE = 15;
static final int NATIVE = 46;
static final int DTHROWS = 12;
static final int USE = 42;
static final int INTERFACE = 45;
static final int VARARGS = 57;
static final int DDEPRECATED = 22;
static final int DSET = 9;
static final int DFIELD = 5;
static final int VISIBLE = 38;
static final int DLIMIT = 6;
static final int PUBLIC = 49;
static final int DEND = 4;
static final int DENCLOSING = 18;
static final int DMETHOD = 8;
static final int STRICT = 58;
static final int DANNOTATION = 24;
static final int EOF = 0;
static final int DEFAULT = 62;
static final int VISIBLEPARAM = 40;
static final int OFFSET = 31;
static final int DATTRIBUTE = 21;
static final int IS = 26;
static final int METHOD = 28;
static final int DBYTECODE = 16;
static final int error = 1;
static final int SYNCHRONIZED = 51;
static final int Word = 67;
static final int SEP = 64;
static final int ANNOTATION = 54;
static final int BRIDGE = 56;
static final int COLON = 65;
static final int USING = 25;
static final int DLINE = 7;
static final int FIELD = 33;
static final int DCATCH = 2;
static final int VOLATILE = 53;
static final int LOCALS = 32;
static final int DINNER = 23;
static final int Relative = 71;
static final int INVISIBLEPARAM = 41;
static final int DIMPLEMENTS = 14;
static final int DSTACK = 20;
static final int PRIVATE = 47;
static final int TO = 35;
static final int STATIC = 50;
static final int Str = 66;
static final int Num = 70;
};
| 31.895349 | 60 | 0.643821 |
297cb9c6e72e0acc3a4cb057598270eb2fa5a396 | 3,434 | package net.sourceforge.kolmafia.textui.command;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import net.sourceforge.kolmafia.AdventureResult;
import net.sourceforge.kolmafia.KoLConstants;
import net.sourceforge.kolmafia.KoLConstants.MafiaState;
import net.sourceforge.kolmafia.KoLmafia;
import net.sourceforge.kolmafia.KoLmafiaCLI;
import net.sourceforge.kolmafia.RequestLogger;
import net.sourceforge.kolmafia.objectpool.ItemPool;
import net.sourceforge.kolmafia.persistence.ItemDatabase;
import net.sourceforge.kolmafia.persistence.ItemFinder;
import net.sourceforge.kolmafia.request.ZapRequest;
import net.sourceforge.kolmafia.session.StoreManager;
public class ComparisonShopCommand extends AbstractCommand implements Comparator<AdventureResult> {
public ComparisonShopCommand() {
this.usage =
"[?] [+]<item> [,[-]item]... [; <cmds>] - compare prices, do cmds with \"it\" replaced with best.";
this.flags = KoLmafiaCLI.FULL_LINE_CMD;
}
@Override
public void run(final String cmd, String parameters) {
boolean expensive = cmd.equals("expensive");
String commands = null;
int pos = parameters.indexOf(";");
if (pos != -1) {
commands = parameters.substring(pos + 1).trim();
parameters = parameters.substring(0, pos).trim();
}
String[] pieces = parameters.split("\\s*,\\s*");
TreeSet<String> names = new TreeSet<>();
for (int i = 0; i < pieces.length; ++i) {
String piece = pieces[i];
if (piece.startsWith("+")) {
AdventureResult item = ItemFinder.getFirstMatchingItem(piece.substring(1).trim());
if (item == null) {
return;
}
names.addAll(Arrays.asList(ZapRequest.getZapGroup(item.getItemId())));
} else if (piece.startsWith("-")) {
names.removeAll(ItemDatabase.getMatchingNames(piece.substring(1).trim()));
} else {
names.addAll(ItemDatabase.getMatchingNames(piece));
}
}
if (names.size() == 0) {
KoLmafia.updateDisplay(MafiaState.ERROR, "No matching items!");
return;
}
if (KoLmafiaCLI.isExecutingCheckOnlyCommand) {
RequestLogger.printList(Arrays.asList(names.toArray()));
return;
}
List<AdventureResult> results = new ArrayList<>();
for (String name : names) {
int itemId = ItemDatabase.getItemId(name);
AdventureResult item = ItemPool.get(itemId);
if (!ItemDatabase.isTradeable(itemId) || StoreManager.getMallPrice(item) <= 0) {
continue;
}
if (!KoLmafia.permitsContinue()) {
return;
}
results.add(item);
}
if (results.size() == 0) {
KoLmafia.updateDisplay(MafiaState.ERROR, "No tradeable items!");
return;
}
Collections.sort(results, this);
if (expensive) {
Collections.reverse(results);
}
if (commands != null) {
this.CLI.executeLine(commands.replaceAll("\\bit\\b", results.get(0).getName()));
return;
}
for (AdventureResult item : results) {
RequestLogger.printLine(
item.getName()
+ " @ "
+ KoLConstants.COMMA_FORMAT.format(StoreManager.getMallPrice(item)));
}
}
public int compare(final AdventureResult o1, final AdventureResult o2) {
return StoreManager.getMallPrice(o1) - StoreManager.getMallPrice(o2);
}
}
| 34.34 | 107 | 0.672685 |
802170aa86f3f1ff3e917315ef7b366ca0af158c | 385 | package VC.Checker;
import VC.ASTs.Decl;
public class IdEntry
{
protected String id;
protected Decl attr;
protected int level;
protected IdEntry previousEntry;
IdEntry(String paramString, Decl paramDecl, int paramInt, IdEntry paramIdEntry)
{
this.id = paramString;
this.attr = paramDecl;
this.level = paramInt;
this.previousEntry = paramIdEntry;
}
}
| 19.25 | 81 | 0.719481 |
0089e87789bc228c659b3f15cdcb1fd93adcbadc | 734 | package example1;
import net.sf.jColtrane.annotations.methods.EndDocument;
import net.sf.jColtrane.annotations.methods.EndElement;
import net.sf.jColtrane.annotations.methods.StartDocument;
import net.sf.jColtrane.annotations.methods.StartElement;
public class HelloWorld {
@StartDocument
public void executeInStartDocument(){
System.out.println("Hello World!!!\n");
}
@EndDocument
public void executeInEndDocument(){
System.out.println("Bye bye World!!!\n");
}
@StartElement
public void executeInStartElement(){
System.out.println("Executing something in start element\n");
}
@EndElement
public void executeInEndElement(){
System.out.println("Executing something in end element\n");
}
}
| 22.242424 | 64 | 0.753406 |
161115f2faf175588bcc75ae2dc2bc696a09cdc9 | 3,120 | package org.simpleframework.transport;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import junit.framework.TestCase;
public class TransportCursorTest extends TestCase {
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
private static final String SOURCE = ALPHABET + "\r\n";
public void testCursor() throws IOException {
byte[] data = SOURCE.getBytes("ISO-8859-1");
InputStream source = new ByteArrayInputStream(data);
Transport transport = new StreamTransport(source, System.out);
ByteCursor cursor = new TransportCursor(transport);
byte[] buffer = new byte[1024];
assertEquals(cursor.ready(), data.length);
assertEquals(26, cursor.read(buffer, 0, 26));
assertEquals(26, cursor.reset(26));
assertEquals(new String(buffer, 0, 26), ALPHABET);
assertEquals(cursor.ready(), data.length);
assertEquals(26, cursor.read(buffer, 0, 26));
assertEquals(26, cursor.reset(26));
assertEquals(new String(buffer, 0, 26), ALPHABET);
assertEquals(cursor.ready(), data.length);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(4, cursor.reset(26));
assertEquals(new String(buffer, 0, 4), "abcd");
assertEquals(cursor.ready(), data.length);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(4, cursor.reset(26));
assertEquals(new String(buffer, 0, 4), "abcd");
assertEquals(cursor.ready(), data.length);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(new String(buffer, 0, 4), "abcd");
assertEquals(cursor.ready(), data.length - 4);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(new String(buffer, 0, 4), "efgh");
assertEquals(cursor.ready(), data.length - 8);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(new String(buffer, 0, 4), "ijkl");
assertEquals(cursor.ready(), data.length - 12);
assertEquals(12, cursor.reset(12));
assertEquals(10, cursor.read(buffer, 0, 10));
assertEquals(new String(buffer, 0, 10), "abcdefghij");
cursor.push("1234".getBytes("ISO-8859-1"));
cursor.push("5678".getBytes("ISO-8859-1"));
cursor.push("90".getBytes("ISO-8859-1"));
assertEquals(cursor.ready(), 10);
assertEquals(2, cursor.read(buffer, 0, 2));
assertEquals(new String(buffer, 0, 2), "90");
assertEquals(cursor.ready(), 8);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(new String(buffer, 0, 4), "5678");
assertEquals(cursor.ready(), 4);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(new String(buffer, 0, 4), "1234");
assertEquals(4, cursor.reset(4));
assertEquals(cursor.ready(), 4);
assertEquals(4, cursor.read(buffer, 0, 4));
assertEquals(new String(buffer, 0, 4), "1234");
assertEquals(8, cursor.read(buffer, 0, 8));
assertEquals(new String(buffer, 0, 8), "klmnopqr");
}
}
| 37.142857 | 71 | 0.633654 |
4cbf4bd83ee1f2cccdf27ba75b8a1afedf85c4a0 | 163 | package me.ifydev.factionify.spigot.events.custom;
/**
* @author Innectic
* @since 07/28/2018
*/
public class FactionGlobalRuleChange {
// TODO
}
| 16.3 | 51 | 0.662577 |
dca958f301036a64182304b79a1b5d38c413f695 | 1,244 | package com.yoti.api.client.shareurl;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import com.yoti.api.client.shareurl.extension.Extension;
import com.yoti.api.client.shareurl.policy.DynamicPolicy;
import org.junit.Test;
import org.mockito.Mock;
public class DynamicScenarioTest {
private static final String SOME_ENDPOINT = "someEndpoint";
@Mock DynamicPolicy dynamicPolicyMock;
@Mock Extension<?> extension1Mock;
@Mock Extension<?> extension2Mock;
@Test
public void shouldBuildADynamicScenario() {
DynamicScenario result = DynamicScenario.builder()
.withCallbackEndpoint(SOME_ENDPOINT)
.withPolicy(dynamicPolicyMock)
.withExtension(extension1Mock)
.withExtension(extension2Mock)
.build();
assertThat(result.callbackEndpoint(), equalTo(SOME_ENDPOINT));
assertThat(result.policy(), equalTo(dynamicPolicyMock));
assertThat(result.extensions(), hasSize(2));
assertThat(result.extensions(), hasItems(extension1Mock, extension2Mock));
}
}
| 32.736842 | 82 | 0.722669 |
6dbf00a7f368560348f878d9b5bbcbe79aa2d552 | 3,245 | package com.dianping.cat.status.datasource;
import com.dianping.cat.status.AbstractCollector;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;
public abstract class DataSourceCollector extends AbstractCollector {
private Map<String, Object> lastValueMap = new HashMap<String, Object>();
protected MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
protected DatabaseParserHelper databaseParser = new DatabaseParserHelper();
protected static final char SPLIT = '.';
private static final Integer ERROR_INT = -1;
private static final Long ERROR_LONG = -1l;
private static final String ERROR_ATTRIBUTE = "unknown";
private Integer diffLast(String key, Integer value) {
Object lastValue = lastValueMap.get(key);
if (lastValue != null) {
lastValueMap.put(key, value);
return value - (Integer) lastValue;
} else {
lastValueMap.put(key, value);
return value;
}
}
private Long diffLast(String key, Long value) {
Object lastValue = lastValueMap.get(key);
if (lastValue != null) {
lastValueMap.put(key, value);
return value - (Long) lastValue;
} else {
lastValueMap.put(key, value);
return value;
}
}
protected String getConnection(Map<String, Integer> datasources, String key) {
Integer index = datasources.get(key);
if (index == null) {
datasources.put(key, 0);
return key;
} else {
index++;
datasources.put(key, index);
return key + '[' + index + ']';
}
}
@Override
public String getDescription() {
return "datasource.c3p0";
}
@Override
public String getId() {
return "datasource.c3p0";
}
protected Integer getIntegerAttribute(ObjectName objectName, String attribute, Boolean isDiff) {
try {
Integer value = (Integer) mbeanServer.getAttribute(objectName, attribute);
if (isDiff) {
return diffLast(objectName.getCanonicalName() + attribute, value);
} else {
return value;
}
} catch (Exception e) {
return ERROR_INT;
}
}
protected Long getLongAttribute(ObjectName objectName, String attribute, Boolean isDiff) {
try {
Long value = (Long) mbeanServer.getAttribute(objectName, attribute);
if (isDiff) {
return diffLast(objectName.getCanonicalName() + attribute, value);
} else {
return value;
}
} catch (Exception e) {
return ERROR_LONG;
}
}
protected String getStringAttribute(ObjectName objectName, String attribute) {
try {
return (String) mbeanServer.getAttribute(objectName, attribute);
} catch (Exception e) {
return ERROR_ATTRIBUTE;
}
}
protected Boolean isRandomName(String name) {
return name != null && name.length() > 30;
}
}
| 30.046296 | 100 | 0.605855 |
2d52c3f9dfde42310062bd735677da35499e1b1d | 436 | package com.west2.fzuTimeMachine.service;
/**
* @description: redis 服务接口
* @author: hlx 2018-10-27
**/
public interface RedisService {
/**
* 非阻塞取锁
*/
boolean tryLock(String key, String value);
/**
* 释放锁
*/
void unLock(String key, String value);
/**
* 添加排行榜(原子性)
*
* @param keysAndArgs 键和时光排行视图 字节数组
*/
void addRank(byte[][] keysAndArgs);
}
| 16.769231 | 47 | 0.536697 |
bfe9106f39716fe250403da32388e745d44ff6f3 | 10,961 | /*******************************************************************************
* Copyright 2013 Geoscience Australia
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package au.gov.ga.earthsci.layer.delegator;
import gov.nasa.worldwind.avlist.AVList;
import gov.nasa.worldwind.event.Message;
import gov.nasa.worldwind.layers.Layer;
import gov.nasa.worldwind.render.DrawContext;
import java.awt.Point;
import java.beans.IntrospectionException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map.Entry;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import au.gov.ga.earthsci.common.util.AbstractPropertyChangeBean;
import au.gov.ga.earthsci.common.util.IPropertyChangeBean;
/**
* Abstract {@link Layer} implementation that delegates methods to another
* {@link Layer} instance.
* <p/>
* Also implements {@link IPropertyChangeBean}. All setters will fire a property
* change. Any changed properties (ie opacity, name, etc) will be recorded, and
* set on any new layers passed to the {@link #setLayer(Layer)} method.
*
* @author Michael de Hoog (michael.dehoog@ga.gov.au)
*/
public abstract class AbstractLayerDelegator<L extends Layer> extends AbstractPropertyChangeBean implements
ILayerDelegator<L>
{
private static final Logger logger = LoggerFactory.getLogger(AbstractLayerDelegator.class);
private final PropertyChangeListener propertyChangeListener = new PropertyChangeListener()
{
@Override
public void propertyChange(PropertyChangeEvent evt)
{
firePropertyChange(new PropertyChangeEvent(AbstractLayerDelegator.this, evt.getPropertyName(),
evt.getOldValue(), evt.getNewValue()));
}
};
private L layer = createDummyLayer();
private Set<String> propertiesChanged = new HashSet<String>();
private boolean propertiesChangedTracking = true;
private final Object layerSemaphore = new Object();
/**
* @return A dummy layer that does nothing; used for storage of property
* values before the real layer is set on this delegator
*/
protected abstract L createDummyLayer();
/**
* Is the given layer an instance of a dummy layer that would be created by
* the {@link #createDummyLayer()} method.
*
* @param layer
* Layer to test
* @return True if the given layer is a dummy layer
*/
protected abstract boolean isDummyLayer(L layer);
@Override
public L getLayer()
{
return layer;
}
@Override
public void setLayer(L layer)
{
if (layer == null)
{
throw new NullPointerException("Layer delegate is null"); //$NON-NLS-1$
}
if (layer == this)
{
throw new IllegalArgumentException("Cannot delegate to itself"); //$NON-NLS-1$
}
Layer oldValue;
synchronized (layerSemaphore)
{
oldValue = getLayer();
copyProperties(oldValue, layer);
this.layer.removePropertyChangeListener(propertyChangeListener);
this.layer = layer;
this.layer.addPropertyChangeListener(propertyChangeListener);
}
firePropertyChange("layer", oldValue, layer); //$NON-NLS-1$
}
@Override
public Layer getGrandLayer()
{
Layer layer = getLayer();
if (layer instanceof ILayerDelegator)
{
ILayerDelegator<?> delegator = (ILayerDelegator<?>) layer;
return delegator.getGrandLayer();
}
return layer;
}
@Override
public boolean isLayerSet()
{
return !isDummyLayer(layer);
}
@Override
public boolean isGrandLayerSet()
{
if (layer instanceof ILayerDelegator<?>)
{
return ((ILayerDelegator<?>) layer).isGrandLayerSet();
}
return isLayerSet();
}
/**
* Copy the changed properties between layers, by calling the getters of the
* from layer and the setters on the to layer.
*
* @param from
* Layer to get property values from
* @param to
* Layer to set property values on
*/
private void copyProperties(Layer from, Layer to)
{
if (from == to)
{
return;
}
synchronized (propertiesChanged)
{
setPropertiesChangedTrackingEnabled(false);
for (String property : propertiesChanged)
{
try
{
PropertyDescriptor fromPropertyDescriptor = new PropertyDescriptor(property, from.getClass());
PropertyDescriptor toPropertyDescriptor = new PropertyDescriptor(property, to.getClass());
Method getter = fromPropertyDescriptor.getReadMethod();
Method setter = toPropertyDescriptor.getWriteMethod();
Object value = getter.invoke(from);
setter.invoke(to, value);
}
catch (IntrospectionException e)
{
//ignore (invalid property name)
}
catch (Exception e)
{
logger.error("Error copying value between layers for property: " + property, e); //$NON-NLS-1$
}
}
setPropertiesChangedTrackingEnabled(true);
}
}
@Override
public void firePropertyChange(PropertyChangeEvent propertyChangeEvent)
{
super.firePropertyChange(propertyChangeEvent);
addChangedProperty(propertyChangeEvent.getPropertyName());
}
@Override
public void firePropertyChange(String propertyName, Object oldValue, Object newValue)
{
super.firePropertyChange(propertyName, oldValue, newValue);
addChangedProperty(propertyName);
}
public void setPropertiesChangedTrackingEnabled(boolean enabled)
{
propertiesChangedTracking = enabled;
}
private void addChangedProperty(String propertyName)
{
synchronized (propertiesChanged)
{
if (propertiesChangedTracking && !"layer".equals(propertyName)) //$NON-NLS-1$
{
propertiesChanged.add(propertyName);
}
}
}
@Override
public void propertyChange(PropertyChangeEvent evt)
{
firePropertyChange(evt);
}
//////////////////////
// Layer delegation //
//////////////////////
@Override
public void dispose()
{
layer.dispose();
}
@Override
public void onMessage(Message msg)
{
layer.onMessage(msg);
}
@Override
public Object setValue(String key, Object value)
{
return layer.setValue(key, value);
}
@Override
public boolean isEnabled()
{
return layer.isEnabled();
}
@Override
public void setEnabled(boolean enabled)
{
boolean oldValue = isEnabled();
layer.setEnabled(enabled);
firePropertyChange("enabled", oldValue, enabled); //$NON-NLS-1$
}
@Override
public String getName()
{
return layer.getName();
}
@Override
public void setName(String name)
{
String oldValue = getName();
layer.setName(name);
firePropertyChange("name", oldValue, name); //$NON-NLS-1$
}
@Override
public AVList setValues(AVList avList)
{
return layer.setValues(avList);
}
@Override
public String getRestorableState()
{
return layer.getRestorableState();
}
@Override
public double getOpacity()
{
return layer.getOpacity();
}
@Override
public void restoreState(String stateInXml)
{
layer.restoreState(stateInXml);
}
@Override
public Object getValue(String key)
{
return layer.getValue(key);
}
@Override
public void setOpacity(double opacity)
{
double oldValue = getOpacity();
layer.setOpacity(opacity);
firePropertyChange("opacity", oldValue, opacity); //$NON-NLS-1$
}
@Override
public Collection<Object> getValues()
{
return layer.getValues();
}
@Override
public String getStringValue(String key)
{
return layer.getStringValue(key);
}
@Override
public boolean isPickEnabled()
{
return layer.isPickEnabled();
}
@Override
public Set<Entry<String, Object>> getEntries()
{
return layer.getEntries();
}
@Override
public boolean hasKey(String key)
{
return layer.hasKey(key);
}
@Override
public Object removeKey(String key)
{
return layer.removeKey(key);
}
@Override
public void setPickEnabled(boolean isPickable)
{
boolean oldValue = isPickEnabled();
layer.setPickEnabled(isPickable);
firePropertyChange("pickEnabled", oldValue, isPickable); //$NON-NLS-1$
}
@Override
public void preRender(DrawContext dc)
{
layer.preRender(dc);
}
@Override
public void render(DrawContext dc)
{
layer.render(dc);
}
@Override
public void pick(DrawContext dc, Point pickPoint)
{
layer.pick(dc, pickPoint);
}
@Override
public boolean isAtMaxResolution()
{
return layer.isAtMaxResolution();
}
@Override
public boolean isMultiResolution()
{
return layer.isMultiResolution();
}
@Override
public double getScale()
{
return layer.getScale();
}
@Override
public boolean isNetworkRetrievalEnabled()
{
return layer.isNetworkRetrievalEnabled();
}
@Override
public void setNetworkRetrievalEnabled(boolean networkRetrievalEnabled)
{
boolean oldValue = isNetworkRetrievalEnabled();
layer.setNetworkRetrievalEnabled(networkRetrievalEnabled);
firePropertyChange("networkRetrievalEnabled", oldValue, networkRetrievalEnabled); //$NON-NLS-1$
}
@Override
public AVList copy()
{
return layer.copy();
}
@Override
public void setExpiryTime(long expiryTime)
{
long oldValue = getExpiryTime();
layer.setExpiryTime(expiryTime);
firePropertyChange("expiryTime", oldValue, expiryTime); //$NON-NLS-1$
}
@Override
public AVList clearList()
{
return layer.clearList();
}
@Override
public long getExpiryTime()
{
return layer.getExpiryTime();
}
@Override
public double getMinActiveAltitude()
{
return layer.getMinActiveAltitude();
}
@Override
public void setMinActiveAltitude(double minActiveAltitude)
{
double oldValue = getMinActiveAltitude();
layer.setMinActiveAltitude(minActiveAltitude);
firePropertyChange("minActiveAltitude", oldValue, minActiveAltitude); //$NON-NLS-1$
}
@Override
public double getMaxActiveAltitude()
{
return layer.getMaxActiveAltitude();
}
@Override
public void setMaxActiveAltitude(double maxActiveAltitude)
{
double oldValue = getMaxActiveAltitude();
layer.setMaxActiveAltitude(maxActiveAltitude);
firePropertyChange("maxActiveAltitude", oldValue, maxActiveAltitude); //$NON-NLS-1$
}
@Override
public boolean isLayerInView(DrawContext dc)
{
return layer.isLayerInView(dc);
}
@Override
public boolean isLayerActive(DrawContext dc)
{
return layer.isLayerActive(dc);
}
@Override
public Double getMaxEffectiveAltitude(Double radius)
{
return layer.getMaxEffectiveAltitude(radius);
}
@Override
public Double getMinEffectiveAltitude(Double radius)
{
return layer.getMinEffectiveAltitude(radius);
}
}
| 22.693582 | 107 | 0.719916 |
5de7087743f8171e3f7aaa4b8d066449b20c5c5f | 18,247 | package com.moises.moneytextinput.textInput;
import android.content.Context;
import android.support.annotation.StringDef;
import android.text.InputType;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.EditText;
import com.moises.moneytextinput.Constants;
import com.moises.moneytextinput.R;
import com.moises.moneytextinput.moneyMaskEu.MoneyMaskDecimalNumbersEu;
import com.moises.moneytextinput.moneyMaskUs.MoneyMaskDecimalNumbers;
import com.moises.moneytextinput.moneyMaskUs.MoneyMaskWholeNoCentsNumbers;
import com.moises.moneytextinput.moneyMaskUs.MoneyMaskWholeNumbers;
/**
* Created by moisesordunogomez on 26/09/16.
*/
public class MoneyTextInput extends EditText{
public String inicial = this.getContext().getString(R.string.currency_dollar)+this.getContext().getString(R.string.tag_init_amount);
// private String currencySymbol =this.getContext().getString(R.string.currency_dollar);
private String currencySymbol =this.getContext().getString(R.string.currency_dollar);
//states, a MoneyMaskDecimalNumbers, b MoneyMaskWholeNumbers, c MoneyMaskWholeNoCentsNumbers
private String state=Constants.DECIMAL;
public MoneyTextInput(Context context) {
super(context);
}
private MoneyMaskDecimalNumbers moneyMaskDecimalNumbers;
private MoneyMaskWholeNumbers moneyMaskWholeNumbers;
private MoneyMaskWholeNoCentsNumbers moneyMaskWholeNoCentsNumbers;
@StringDef({
Constants.DOLLAR,
Constants.YEN,
Constants.EURO,
Constants.WON,
Constants.REAL,
Constants.POUND,
Constants.RIYAL
})
private @interface currencySymbols {}
@StringDef({
Constants.DECIMAL,
Constants.WHOLE,
Constants.WHOLE_NO_CENTS
})
private @interface states {}
public void setMaxAmount(int maxAmount){
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setMaxAmount(maxAmount);
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setMaxAmount(maxAmount);
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setMaxAmount(maxAmount);
break;
}
}
public MoneyTextInput(Context context, AttributeSet attrs) {
super(context, attrs);
this.setGravity(Gravity.RIGHT | Gravity.CENTER_VERTICAL );
this.setInputType(InputType.TYPE_CLASS_NUMBER);
this.setText(inicial);
// this.setText(this.getContext().getString(R.string.currency_dollar)+this.getContext().getString(R.string.tag_init_amount_no_zeroes));
this.setSelection(this.getText().length(), this.getText().length());
moneyMaskDecimalNumbers =new MoneyMaskDecimalNumbers(this);
moneyMaskWholeNumbers =new MoneyMaskWholeNumbers(this);
moneyMaskWholeNoCentsNumbers = new MoneyMaskWholeNoCentsNumbers(this);
// this.addTextChangedListener(moneyMaskWholeNoCentsNumbers);
this.addTextChangedListener(moneyMaskDecimalNumbers);
}
public String bringCleanAmountNoCents(){
String amount=this.getText().toString();
if(state.equals(Constants.WHOLE_NO_CENTS))amount+="00";
for(int i=0;i<currencySymbol.length();i++){
String sToRemove="";
sToRemove+= currencySymbol.charAt(i);
amount=amount.replace(sToRemove,".");
}
amount=amount.replaceAll("[,.+]", "");
return amount.substring(0,amount.length()-2);
}
public String bringCleanAmount(){
String amount=this.getText().toString();
if(state.equals(Constants.WHOLE_NO_CENTS))amount+="00";
for(int i=0;i<currencySymbol.length();i++){
String sToRemove="";
sToRemove+= currencySymbol.charAt(i);
amount=amount.replace(sToRemove,",");
}
amount=amount.replaceAll("[,+]", "");
return amount;
}
//check if the amount is zero
public boolean isValueEmpty(){
String amount=this.getText().toString();
if(state.equals(Constants.WHOLE_NO_CENTS))amount+="00";
for(int i=0;i<currencySymbol.length();i++){
String sToRemove="";
sToRemove+= currencySymbol.charAt(i);
amount=amount.replace(sToRemove,",");
}
amount=amount.replaceAll("[,.+]", "");
float floatAmount = Float.parseFloat(amount);
return floatAmount==0;
}
public void setSymbol(@currencySymbols String symbol){
switch (symbol){
case Constants.DOLLAR:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_dollar));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_dollar));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_dollar));
break;
}
this.setText(this.getContext().getString(R.string.currency_dollar)+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_dollar);
break;
case Constants.YEN:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_yen));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_yen));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_yen));
break;
}
this.setText(this.getContext().getString(R.string.currency_yen)+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_yen);
break;
case Constants.EURO:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_euro));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_euro));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_euro));
break;
}
this.setText(this.getContext().getString(R.string.currency_euro) + this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol = this.getContext().getString(R.string.currency_euro);
break;
case Constants.WON:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_won));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_won));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_won));
break;
}
this.setText(this.getContext().getString(R.string.currency_won)+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_won);
break;
case Constants.REAL:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_real));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_real));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_real));
break;
}
this.setText(this.getContext().getString(R.string.currency_real)+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_real);
break;
case Constants.POUND:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_pound));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_pound));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_pound));
}
this.setText(this.getContext().getString(R.string.currency_pound)+this.getContext().getString(R.string.tag_init_amount));
// this.setText(this.getContext().getString(R.string.currency_pound));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_pound);
break;
case Constants.RIYAL:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_riyal));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_riyal));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_riyal));
}
this.setText(this.getContext().getString(R.string.currency_riyal)+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_riyal);
break;
default:
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_dollar));
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_dollar));
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(this.getContext().getString(R.string.currency_dollar));
}
this.setText(this.getContext().getString(R.string.currency_dollar)+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=this.getContext().getString(R.string.currency_dollar);
break;
}
}
public void setSideTextAndSymbol(String sideText,@currencySymbols String symbol){
String symbolAndSideText;
switch (symbol){
case Constants.DOLLAR:
symbolAndSideText=sideText+this.getContext().getString(R.string.currency_dollar);
break;
case Constants.YEN:
symbolAndSideText=sideText+this.getContext().getString(R.string.currency_yen);
break;
case Constants.EURO:
symbolAndSideText=sideText+this.getContext().getString(R.string.currency_euro);
break;
case Constants.WON:
symbolAndSideText=sideText+=this.getContext().getString(R.string.currency_won);
break;
case Constants.REAL:
symbolAndSideText=sideText+=this.getContext().getString(R.string.currency_real);
break;
case Constants.POUND:
symbolAndSideText=sideText+=this.getContext().getString(R.string.currency_pound);
break;
case Constants.RIYAL:
symbolAndSideText=sideText+=this.getContext().getString(R.string.currency_riyal);
break;
default:
symbolAndSideText=sideText+=this.getContext().getString(R.string.currency_dollar);
break;
}
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(symbolAndSideText);
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(symbolAndSideText);
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(symbolAndSideText);
}
this.setText(symbolAndSideText+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=symbolAndSideText;
}
public void setSideTextNoSymbol(String sideText){
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol(sideText);
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol(sideText);
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol(sideText);
break;
}
this.setText(sideText+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol=sideText;
}
public void setNoSymbol(){
switch (state){
case Constants.DECIMAL:
moneyMaskDecimalNumbers.setCurrencySymbol("");
break;
case Constants.WHOLE:
moneyMaskWholeNumbers.setCurrencySymbol("");
break;
case Constants.WHOLE_NO_CENTS:
moneyMaskWholeNoCentsNumbers.setCurrencySymbol("");
break;
}
this.setText(""+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
currencySymbol="";
}
public void setState(@states String newState){
switch (newState){
case Constants.DECIMAL:
if(state.equals(Constants.WHOLE))this.removeTextChangedListener(moneyMaskWholeNumbers);
if(state.equals(Constants.WHOLE_NO_CENTS))this.removeTextChangedListener(moneyMaskWholeNoCentsNumbers);
this.addTextChangedListener(moneyMaskDecimalNumbers);
state=Constants.DECIMAL;
break;
case Constants.WHOLE:
if(state.equals(Constants.WHOLE))this.removeTextChangedListener(moneyMaskWholeNumbers);
if(state.equals(Constants.WHOLE_NO_CENTS))this.removeTextChangedListener(moneyMaskWholeNoCentsNumbers);
this.addTextChangedListener(moneyMaskWholeNumbers);
state=Constants.WHOLE;
break;
case Constants.WHOLE_NO_CENTS:
if(state.equals(Constants.DECIMAL))this.removeTextChangedListener(moneyMaskDecimalNumbers);
if(state.equals(Constants.WHOLE))this.removeTextChangedListener(moneyMaskWholeNumbers);
this.setText(this.getContext().getString(R.string.currency_dollar)+this.getContext().getString(R.string.tag_init_amount_no_zeroes));
this.setSelection(this.getText().length(), this.getText().length());
this.addTextChangedListener(moneyMaskWholeNoCentsNumbers);
state=Constants.WHOLE_NO_CENTS;
break;
default:
if(state.equals(Constants.WHOLE))this.removeTextChangedListener(moneyMaskWholeNumbers);
if(state.equals(Constants.WHOLE_NO_CENTS))this.removeTextChangedListener(moneyMaskWholeNoCentsNumbers);
this.addTextChangedListener(moneyMaskDecimalNumbers);
state=Constants.DECIMAL;
break;
}
}
public void reset(){
this.setText(currencySymbol+this.getContext().getString(R.string.tag_init_amount));
this.setSelection(this.getText().length(), this.getText().length());
}
// https://msdn.microsoft.com/en-us/library/ee825488(v=cs.20).aspx
}
| 45.054321 | 148 | 0.614567 |
9c189b5f599709eb713f768eda3d7d6674653507 | 1,164 | package io.github.glytching.tranquil.cache;
import java.util.LinkedHashMap;
import java.util.Map;
/** A LRU implementation of {@link Cache}. */
public class LRUCache implements Cache {
private static final boolean SORT_BY_ACCESS = true;
private static final float LOAD_FACTOR = 0.75F;
private final Map<String, Object> delegate;
private final int maxSize;
public LRUCache(int maxSize) {
this.maxSize = maxSize;
this.delegate = new LinkedHashMap<>(maxSize, LOAD_FACTOR, SORT_BY_ACCESS);
}
@Override
public Object get(String key) {
return this.delegate.get(key);
}
@Override
@SuppressWarnings("unchecked")
public <T> T get(Class<T> clazz, String key) {
return (T) get(key);
}
@Override
public void put(String key, Object value) {
if (this.delegate.containsKey(key)) {
this.delegate.remove(key);
} else if (this.delegate.size() >= this.maxSize) {
if (this.delegate.keySet().iterator().hasNext()) {
this.delegate.remove(this.delegate.keySet().iterator().next());
}
}
this.delegate.put(key, value);
}
@Override
public int size() {
return delegate.size();
}
}
| 23.755102 | 78 | 0.674399 |
08d030262dd2da8e68d4cebca212578b86d6e8f2 | 2,926 | package org.nearbyshops.enduserappnew.Model.ModelStatusCodes;
// :: staff functions
// confirmOrder()
// setOrderPacked()
// handoverToDelivery()
// acceptReturn()
// unpackOrder()
// paymentReceived()
// delivery guy functions
// AcceptPackage() | DeclinePackage()
// Return() | Deliver()
public class OrderStatusHomeDelivery {
public static final int ORDER_PLACED = 1; // Confirm (Staff)
public static final int ORDER_CONFIRMED = 2; // Pack (Staff)
public static final int ORDER_PACKED = 3; // handover to delivery (Staff)
public static final int HANDOVER_REQUESTED = 4; // handover requested | Accept Package : Decline (Delivery Guy)
public static final int OUT_FOR_DELIVERY = 5;// out for delivery | Return : Delivered (Delivery Guy)
// public static final int PENDING_DELIVERY = 6;
public static final int RETURN_REQUESTED = 6;// Return Requested | Accept Return (Staff)
public static final int RETURNED_ORDERS = 7;// Returned Orders | Unpack : HandoverToDelivery (Staff)
public static final int DELIVERED = 8;// Delivered | Payment Received (Staff)
public static final int PAYMENT_RECEIVED = 9;// Payment Received-Complete
// public static final int RETURN_REQUESTED_BY_USER = 10;// Return-Requested
// public static final int CANCELLED_BY_SHOP = 19;
// public static final int CANCELLED_BY_USER = 20;
public static final int CANCELLED_WITH_DELIVERY_GUY = 19;
public static final int CANCELLED = 20;
// cancellation can be done only upto order is packed - status is order_Packed
public static String getStatusString(int orderStatus)
{
String statusString = "";
if(orderStatus==ORDER_PLACED)
{
statusString = "Order Placed";
}
else if(orderStatus==ORDER_CONFIRMED)
{
statusString = "Order Confirmed";
}
else if(orderStatus ==ORDER_PACKED)
{
statusString = "Order Packed";
}
else if(orderStatus==HANDOVER_REQUESTED)
{
statusString = "Order Packed";
}
else if(orderStatus==OUT_FOR_DELIVERY)
{
statusString = "Out for Delivery";
}
else if(orderStatus==RETURN_REQUESTED)
{
statusString = "Order Returned";
}
else if(orderStatus==RETURNED_ORDERS)
{
statusString = "Order Returned";
}
else if(orderStatus==DELIVERED)
{
statusString = "Delivered";
}
else if(orderStatus==PAYMENT_RECEIVED)
{
statusString = "Delivered";
}
else if(orderStatus==CANCELLED_WITH_DELIVERY_GUY)
{
statusString = "Order Cancelled";
}
else if(orderStatus==CANCELLED)
{
statusString = "Order Cancelled";
}
return statusString;
}
}
| 25.666667 | 115 | 0.627478 |
5962e34b9e59eaa8027c7bc2ef87386ea3dbd041 | 1,938 | /*
* Copyright 2010-2020 Australian Signals Directorate
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package au.gov.asd.tac.constellation.visual.opengl.renderer;
/**
* Assign unique texture units.
* <p>
* Different parts of the scene use different textures; for instance,
* SceneBatchStore uses one texture for storing x,y,z coordinates and another
* for storing icons. By assigning the texture unit identifiers here, we can
* track which texture units are used for drawing across classes.
* <p>
* JOGL uses a texture unit for text: don't clash with it.
*
* @author algol
*/
public class TextureUnits {
// Texture unit index values for rendering textures.
/**
* Used by SceneBatchStore for storing x,y,z coordinates.
*/
public static final int VERTICES = 0;
/**
* Used by SceneBatchStore for storing icons to draw nodes.
*/
public static final int ICONS = 1;
/**
* Used by SceneBatchStore for storing vertex flags.
*/
public static final int VERTEX_FLAGS = 2;
/**
* Used by PlaneBatchStore for storing overlay images.
*/
public static final int PLANES = 3;
/**
* Used by SceneBatchStore for the text font texture.
*/
public static final int GLYPHS = 4;
/**
* Used by SceneBatchStore for storing information about the characters in
* labels
*/
public static final int GLYPH_INFO = 5;
}
| 30.28125 | 78 | 0.695046 |
dbfa4c66e7c767063eaf9c127dd0bf76b0e63d6f | 465 | package modele;
import java.rmi.Remote;
import java.rmi.RemoteException;
public interface InterfaceMorpion extends Remote {
public void initGrille() throws RemoteException;
public void PlacerX(int c) throws RemoteException;
public void PlacerO(int c) throws RemoteException;
public int testRanc(int a, int b, int c) throws RemoteException;
public int testGagnant() throws RemoteException;
public void AfficheGrille()throws RemoteException;
}
| 31 | 66 | 0.782796 |
8c4757f39d2039a38df8f992303ea70089b80b6f | 5,507 | /*
* 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.dubbo.rpc.protocol.tri;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.utils.ReflectUtils;
import org.apache.dubbo.rpc.protocol.tri.support.MockAbstractStreamImpl;
import org.apache.dubbo.triple.TripleWrapper;
import com.google.protobuf.ByteString;
import io.netty.handler.codec.http2.Http2Headers;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum.MESSAGE_KEY;
import static org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum.STATUS_DETAIL_KEY;
import static org.apache.dubbo.rpc.protocol.tri.TripleHeaderEnum.STATUS_KEY;
/**
* {@link AbstractStream}
*/
public class AbstractStreamTest {
private URL url = URL.valueOf("test://127.0.0.1/test");
private AbstractStream stream = new MockAbstractStreamImpl(url);
@Test
public void testTransportError() {
Exception exception = getException();
OutboundTransportObserver transportObserver = Mockito.mock(OutboundTransportObserver.class);
stream.subscribe(transportObserver);
GrpcStatus grpcStatus = GrpcStatus
.fromCode(GrpcStatus.Code.INTERNAL)
.withDescription("TEST")
.withCause(exception);
Map<String, Object> attachments = new HashMap<>();
attachments.put("strKey", "v1");
attachments.put("binKey", new byte[]{1});
attachments.put(String.valueOf(Http2Headers.PseudoHeaderName.PATH.value()), "path");
attachments.put(CommonConstants.GROUP_KEY, "group");
stream.transportError(grpcStatus, attachments, false);
ArgumentCaptor<DefaultMetadata> metadataArgumentCaptor = ArgumentCaptor.forClass(DefaultMetadata.class);
Mockito.verify(transportObserver, Mockito.times(2)).onMetadata(metadataArgumentCaptor.capture(), Mockito.anyBoolean());
DefaultMetadata defaultMetadata = metadataArgumentCaptor.getValue();
Assertions.assertEquals(defaultMetadata.get(STATUS_KEY.getHeader()), String.valueOf(grpcStatus.code.code));
Assertions.assertEquals(defaultMetadata.get(MESSAGE_KEY.getHeader()), grpcStatus.description);
Assertions.assertNotNull(defaultMetadata.get(STATUS_DETAIL_KEY.getHeader()));
Assertions.assertTrue(defaultMetadata.contains("strKey".toLowerCase(Locale.ROOT)));
Assertions.assertTrue(defaultMetadata.contains("binKey".toLowerCase(Locale.ROOT) + TripleConstant.GRPC_BIN_SUFFIX));
Assertions.assertFalse(defaultMetadata.contains(String.valueOf(Http2Headers.PseudoHeaderName.PATH.value())));
Assertions.assertFalse(defaultMetadata.contains(CommonConstants.GROUP_KEY));
// test parseMetadataToAttachmentMap
Map<String, Object> attachmentMap = stream.parseMetadataToAttachmentMap(defaultMetadata);
Assertions.assertTrue(attachmentMap.containsKey("strKey".toLowerCase(Locale.ROOT)));
Assertions.assertTrue(attachmentMap.containsKey("binKey".toLowerCase(Locale.ROOT)));
}
@Test
public void testPackUnPack() {
TripleWrapper.TripleRequestWrapper requestWrapper = TripleWrapper.TripleRequestWrapper.newBuilder()
.addArgTypes(ReflectUtils.getDesc(String.class))
.addArgs(ByteString.copyFrom("TEST_ARG".getBytes(StandardCharsets.UTF_8)))
.setSerializeType(TripleConstant.HESSIAN4)
.build();
byte[] bytes = stream.pack(requestWrapper);
TripleWrapper.TripleRequestWrapper unpackedData = stream.unpack(bytes, TripleWrapper.TripleRequestWrapper.class);
Assertions.assertEquals(unpackedData.getArgTypes(0), requestWrapper.getArgTypes(0));
Assertions.assertEquals(unpackedData.getArgs(0), requestWrapper.getArgs(0));
Assertions.assertEquals(unpackedData.getArgs(0), requestWrapper.getArgs(0));
Assertions.assertEquals(unpackedData.getSerializeType(), requestWrapper.getSerializeType());
}
@Test
public void testCodec() {
String str = "BCN";
String base64ASCII = stream.encodeBase64ASCII(str.getBytes(StandardCharsets.UTF_8));
byte[] bytes = stream.decodeASCIIByte(base64ASCII);
Assertions.assertEquals(str, new String(bytes, StandardCharsets.UTF_8));
}
private Exception getException() {
Exception exception = null;
try {
int count = 1 / 0;
} catch (Exception e) {
exception = e;
}
return exception;
}
}
| 45.891667 | 127 | 0.739423 |
f40b54620ce14abd9c590e21af10d55f329c0699 | 247 | package com.example.fmodule.message.contacts;
import com.example.fmodule.other.ContactData;
import java.util.ArrayList;
import easynet.network.AResponse;
public class PContacts extends AResponse {
public ArrayList<ContactData> contacts;
}
| 20.583333 | 45 | 0.809717 |
3289aaa0980f3a16076cad7460c581453b3aa740 | 496 | package Graph;
public class Test {
public static void main(String[] args) {
Graph g = new Graph(7, true);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(2, 0);
g.addEdge(2, 1);
g.addEdge(2, 5);
g.addEdge(2, 4);
g.addEdge(4, 1);
g.addEdge(0, 1);
g.addEdge(2, 5);
g.addEdge(2, 6);
g.addEdge(2, 1);
Traversal t = new Traversal(g);
// t.doBFS(1);
// t.refresh();
// t.doDFS(1);
t.refresh();
MotherVertex mv = new MotherVertex(g);
mv.motherVertexExists();
}
}
| 17.714286 | 41 | 0.582661 |
5e12384ba95a0e0db470d8fc7b12899431763f8e | 611 | package edu.scripps.yates.utilities.index;
import java.io.File;
public class FileRecordReservation {
private long currentLastPosition;
public FileRecordReservation(File file) {
this.currentLastPosition = file.length();
}
/**
* It returns the position in which the record should be written in the file
*
* @param recordToAppend
* @return
*/
public synchronized long reserveRecord(byte[] recordToAppend) {
long ret = currentLastPosition;
currentLastPosition += recordToAppend.length;
return ret;
}
public synchronized long getCurrentposition() {
return currentLastPosition;
}
}
| 21.068966 | 77 | 0.751227 |
37cac3374c82d5d5b832ecdfe1415dbecd51f9e1 | 3,657 | /*
* Copyright 2019 Datadog
*
* 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.datadog.profiling.controller.oracle;
import com.datadog.profiling.controller.RecordingData;
import com.datadog.profiling.controller.RecordingInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.Instant;
import java.util.Date;
import javax.annotation.Nonnull;
import javax.management.ObjectName;
/** Implementation for profiling recordings. */
public class OracleJdkRecordingData extends RecordingData {
private final ObjectName recordingId;
private final String name;
private final JfrMBeanHelper helper;
OracleJdkRecordingData(
@Nonnull String name,
@Nonnull ObjectName recordingId,
@Nonnull Instant start,
@Nonnull Instant end,
@Nonnull JfrMBeanHelper helper) {
super(start, end);
this.name = name;
this.recordingId = recordingId;
this.helper = helper;
}
@Override
@Nonnull
public RecordingInputStream getStream() throws IOException {
return new RecordingInputStream(new JfrRecordingStream());
}
@Override
public void release() {
// noop
}
@Override
@Nonnull
public String getName() {
return name;
}
@Override
public String toString() {
return "OracleJdkRecording: " + getName();
}
private class JfrRecordingStream extends InputStream {
private byte[] buf = new byte[0];
private int count = 0;
private int pos = 0;
private boolean closed = false;
private boolean endOfStream = false;
private long streamId = -1L;
@Override
public synchronized int read() throws IOException {
ensureOpen();
if (pos >= buf.length) {
if (closed || endOfStream) {
return -1;
}
fill();
if (endOfStream) {
return -1;
}
}
return buf[pos++] & 0xff;
}
private void ensureOpen() throws IOException {
if (closed) {
throw new IOException("Stream closed"); // $NON-NLS-1$
}
}
@Override
public synchronized int available() throws IOException {
ensureOpen();
if (pos >= buf.length) {
if (closed || endOfStream) {
return -1;
}
fill();
if (endOfStream) {
return -1;
}
}
return count - pos;
}
@Override
public void close() throws IOException {
if (closed) {
return;
}
closed = true;
try {
if (streamId != -1) {
helper.closeStream(streamId);
}
helper.closeRecording(recordingId);
} catch (Exception e) {
throw new IOException(e);
}
}
private void fill() throws IOException {
if (streamId == -1L) {
streamId =
helper.openStream(
recordingId, new Date(start.toEpochMilli()), new Date(end.toEpochMilli()));
}
buf = helper.readStream(streamId);
if (buf != null) {
count += buf.length;
pos = 0;
} else {
pos = 0;
count = 0;
buf = new byte[0];
endOfStream = true;
}
}
}
}
| 24.709459 | 91 | 0.622915 |
6dbb5b8466fd449cac9df909d634f28cac8f9c7a | 142 | package edu.prahlad.springbasics.movierecommendersystem.lesson10;
public interface Filter {
String[] getRecommendations(String movie);
}
| 23.666667 | 65 | 0.809859 |
36495dcb91383eb6d01330fd74e2824e8b493913 | 1,912 | package net.labymod.serverapi.common.sticker;
import com.google.gson.JsonArray;
import net.labymod.serverapi.api.LabyService;
import net.labymod.serverapi.api.payload.PayloadCommunicator;
import net.labymod.serverapi.api.player.LabyModPlayer;
import net.labymod.serverapi.api.player.LabyModPlayerService;
import net.labymod.serverapi.api.sticker.Sticker;
import net.labymod.serverapi.api.sticker.StickerTransmitter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
public class DefaultStickerTransmitter implements StickerTransmitter {
private static final String STICKER_API_CHANNEL = "sticker_api";
private final PayloadCommunicator payloadCommunicator;
private final LabyModPlayerService<?> labyPlayerService;
private final List<Sticker> stickers;
public DefaultStickerTransmitter(LabyService service) {
this.payloadCommunicator = service.getPayloadCommunicator();
this.labyPlayerService = service.getLabyPlayerService();
this.stickers = new ArrayList<>();
}
/** {@inheritDoc} */
@Override
public StickerTransmitter addSticker(Sticker sticker) {
this.stickers.add(sticker);
return this;
}
/** {@inheritDoc} */
@Override
public StickerTransmitter addStickers(Sticker... stickers) {
this.stickers.addAll(Arrays.asList(stickers));
return this;
}
/** {@inheritDoc} */
@Override
public void transmit(UUID receiverUniqueId) {
JsonArray stickers = new JsonArray();
for (Sticker sticker : this.stickers) {
stickers.add(sticker.asJsonObject());
}
this.stickers.clear();
this.payloadCommunicator.sendLabyModMessage(receiverUniqueId, STICKER_API_CHANNEL, stickers);
}
/** {@inheritDoc} */
@Override
public void broadcastTransmit() {
for (LabyModPlayer<?> player : this.labyPlayerService.getPlayers()) {
this.transmit(player.getUniqueId());
}
}
}
| 29.415385 | 97 | 0.754184 |
3409cec01b857f29d73ec3ade91a40b24bd0c9ee | 5,506 | package model.JDBC;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import model.Copa;
import model.Jogador;
public class CopaDAO {
public void addCopa(Copa copa){
String sql = "INSERT INTO copa ( nome, quantidade, premio, valorpartida) VALUES ( ?, ?, ?, ?)";
ConnectionFactory con = new ConnectionFactory();
try {
PreparedStatement stmt = con.getConnection().prepareStatement(sql);
stmt.setString(1, copa.getNome());
stmt.setInt(2, copa.getQuantidade());
stmt.setDouble(3, copa.getPremio());
stmt.setDouble(4, copa.getValorpartida());
stmt.execute();
stmt.close();
con.getConnection().close();
System.out.println("Foi");
} catch (Exception e) {
System.out.println("Nao foi");
}
}
public ObservableList<Copa> selectCopa(){
ObservableList<Copa> copas = FXCollections.observableArrayList();
String sql = "SELECT * FROM copa";
ConnectionFactory con = new ConnectionFactory();
try {
PreparedStatement stmt = con.getConnection().prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
Copa copa = new Copa();
copa.setId_copa(rs.getInt("id_copa"));
copa.setNome(rs.getString("nome"));
copa.setPremio(rs.getDouble("premio"));
copa.setQuantidade(rs.getInt("quantidade"));
copa.setValorpartida(rs.getDouble("valorpartida"));
copas.add(copa);
// System.out.println("BOM");
}
con.getConnection().close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(JogadorDAO.class.getName()).log(Level.SEVERE, null, ex);
// System.out.println("ruim");
}
return copas;
}
public void delete(int c){
String sql = "DELETE FROM copa WHERE id_copa = ?";
ConnectionFactory con = new ConnectionFactory();
try{
PreparedStatement stm = con.getConnection().prepareStatement(sql);
stm.setInt(1, c);
stm.execute();
stm.close();
con.getConnection().close();
}catch(Exception ee){
ee.printStackTrace();
}
}
/////////////////////////////////////////////////////////////////////////////////////////
public ObservableList<Copa> selectCopaPart(int id){
ObservableList<Copa> copas = FXCollections.observableArrayList();
String sql = "SELECT * FROM copa WHERE id_copa = ?";
ConnectionFactory con = new ConnectionFactory();
try {
PreparedStatement stmt = con.getConnection().prepareStatement(sql);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
Copa copa = new Copa();
copa.setId_copa(rs.getInt("id_copa"));
copa.setNome(rs.getString("nome"));
copa.setPremio(rs.getDouble("premio"));
copa.setQuantidade(rs.getInt("quantidade"));
copa.setValorpartida(rs.getDouble("valorpartida"));
copas.add(copa);
// System.out.println("BOM");
}
con.getConnection().close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(JogadorDAO.class.getName()).log(Level.SEVERE, null, ex);
// System.out.println("ruim");
}
return copas;
}
public ObservableList<Copa> selectCopaNome(String nome){
ObservableList<Copa> copas = FXCollections.observableArrayList();
String sql = "SELECT * FROM copa WHERE nome = ?";
ConnectionFactory con = new ConnectionFactory();
try {
PreparedStatement stmt = con.getConnection().prepareStatement(sql);
stmt.setString(1, nome);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
Copa copa = new Copa();
copa.setId_copa(rs.getInt("id_copa"));
copa.setNome(rs.getString("nome"));
copa.setPremio(rs.getDouble("premio"));
copa.setQuantidade(rs.getInt("quantidade"));
copa.setValorpartida(rs.getDouble("valorpartida"));
copas.add(copa);
// System.out.println("BOM");
}
con.getConnection().close();
rs.close();
} catch (SQLException ex) {
Logger.getLogger(JogadorDAO.class.getName()).log(Level.SEVERE, null, ex);
// System.out.println("ruim");
}
return copas;
}
}
| 41.089552 | 111 | 0.499818 |
4113ae213cf8690b9de250a3b51c763155991f10 | 1,523 | package com.egoveris.edt.ws.controller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@ComponentScan
@EnableSwagger2
@EnableWebMvc
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build().apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
ApiInfo apiInfo = new ApiInfo("Rest API",
"Rest API Example",
"1",
"",
new Contact("E", "http://desa.egoveris.com", "lmancild@everis.com"),
"Apache License",
"");
return apiInfo;
}
}
| 35.418605 | 108 | 0.624425 |
5de963ced00308ed51e90fceea545e30f9d887ed | 383 | package com.szss;
import akka.actor.UntypedActor;
/**
* Created by zcg on 16/8/8.
*/
public class TestActor1 extends UntypedActor {
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof String){
System.out.println("TestActor1 message is "+message);
}else {
unhandled(message);
}
}
}
| 21.277778 | 65 | 0.629243 |
7fa53f3bcda9f5c9b7343628806dc6cf72677f36 | 17,697 | /*
* 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.beam.sdk.extensions.sql.meta.provider.bigquery;
import java.util.List;
import java.util.Map;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.avatica.util.Casing;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.avatica.util.TimeUnit;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.config.NullCollation;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.type.RelDataType;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.rel.type.RelDataTypeSystem;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlAbstractDateTimeLiteral;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlCall;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlDataTypeSpec;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlDialect;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlIdentifier;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlIntervalLiteral;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlIntervalQualifier;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlKind;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlLiteral;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlNode;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlOperator;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlSetOperator;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlSyntax;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlTimestampLiteral;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.SqlWriter;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.dialect.BigQuerySqlDialect;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.fun.SqlTrimFunction;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.parser.SqlParserPos;
import org.apache.beam.vendor.calcite.v1_20_0.org.apache.calcite.sql.type.BasicSqlType;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
// TODO(CALCITE-3381): some methods below can be deleted after updating vendor Calcite version.
// Calcite v1_20_0 does not have type translation implemented, but later (unreleased) versions do.
@SuppressWarnings({
"nullness" // TODO(https://issues.apache.org/jira/browse/BEAM-10402)
})
public class BeamBigQuerySqlDialect extends BigQuerySqlDialect {
public static final SqlDialect.Context DEFAULT_CONTEXT =
SqlDialect.EMPTY_CONTEXT
.withDatabaseProduct(SqlDialect.DatabaseProduct.BIG_QUERY)
.withIdentifierQuoteString("`")
.withNullCollation(NullCollation.LOW)
.withUnquotedCasing(Casing.UNCHANGED)
.withQuotedCasing(Casing.UNCHANGED)
.withCaseSensitive(false);
public static final SqlDialect DEFAULT = new BeamBigQuerySqlDialect(DEFAULT_CONTEXT);
// List of BigQuery Specific Operators needed to form Syntactically Correct SQL
private static final SqlOperator UNION_DISTINCT =
new SqlSetOperator("UNION DISTINCT", SqlKind.UNION, 14, false);
private static final SqlSetOperator EXCEPT_DISTINCT =
new SqlSetOperator("EXCEPT DISTINCT", SqlKind.EXCEPT, 14, false);
private static final SqlSetOperator INTERSECT_DISTINCT =
new SqlSetOperator("INTERSECT DISTINCT", SqlKind.INTERSECT, 18, false);
// ZetaSQL defined functions that need special unparsing
private static final List<String> FUNCTIONS_USING_INTERVAL =
ImmutableList.of(
"date_add",
"date_sub",
"datetime_add",
"datetime_sub",
"time_add",
"time_sub",
"timestamp_add",
"timestamp_sub");
private static final Map<String, String> EXTRACT_FUNCTIONS =
ImmutableMap.<String, String>builder()
.put("$extract", "")
.put("$extract_date", "DATE")
.put("$extract_time", "TIME")
.put("$extract_datetime", "DATETIME")
.build();
public static final String DOUBLE_POSITIVE_INF_WRAPPER = "double_positive_inf";
public static final String DOUBLE_NEGATIVE_INF_WRAPPER = "double_negative_inf";
public static final String DOUBLE_NAN_WRAPPER = "double_nan";
// ZetaSQL has no literal representation of NaN and infinity, so we need to CAST from strings
private static final Map<String, String> DOUBLE_LITERAL_WRAPPERS =
ImmutableMap.<String, String>builder()
.put(DOUBLE_POSITIVE_INF_WRAPPER, "CAST('+inf' AS FLOAT64)")
.put(DOUBLE_NEGATIVE_INF_WRAPPER, "CAST('-inf' AS FLOAT64)")
.put(DOUBLE_NAN_WRAPPER, "CAST('NaN' AS FLOAT64)")
.build();
public static final String NUMERIC_LITERAL_WRAPPER = "numeric_literal";
public static final String IN_ARRAY_OPERATOR = "$in_array";
public BeamBigQuerySqlDialect(Context context) {
super(context);
}
@Override
public String quoteIdentifier(String val) {
return quoteIdentifier(new StringBuilder(), val).toString();
}
@Override
public SqlNode emulateNullDirection(SqlNode node, boolean nullsFirst, boolean desc) {
return emulateNullDirectionWithIsNull(node, nullsFirst, desc);
}
@Override
public boolean supportsNestedAggregations() {
return false;
}
@Override
public void unparseOffsetFetch(SqlWriter writer, SqlNode offset, SqlNode fetch) {
unparseFetchUsingLimit(writer, offset, fetch);
}
@Override
public void unparseCall(
final SqlWriter writer, final SqlCall call, final int leftPrec, final int rightPrec) {
switch (call.getKind()) {
case POSITION:
final SqlWriter.Frame frame = writer.startFunCall("STRPOS");
writer.sep(",");
call.operand(1).unparse(writer, leftPrec, rightPrec);
writer.sep(",");
call.operand(0).unparse(writer, leftPrec, rightPrec);
if (3 == call.operandCount()) {
throw new UnsupportedOperationException(
"3rd operand Not Supported for Function STRPOS in Big Query");
}
writer.endFunCall(frame);
break;
case ROW:
final SqlWriter.Frame structFrame = writer.startFunCall("STRUCT");
for (SqlNode operand : call.getOperandList()) {
writer.sep(",");
operand.unparse(writer, leftPrec, rightPrec);
}
writer.endFunCall(structFrame);
break;
case UNION:
if (!((SqlSetOperator) call.getOperator()).isAll()) {
SqlSyntax.BINARY.unparse(writer, UNION_DISTINCT, call, leftPrec, rightPrec);
}
break;
case EXCEPT:
if (!((SqlSetOperator) call.getOperator()).isAll()) {
SqlSyntax.BINARY.unparse(writer, EXCEPT_DISTINCT, call, leftPrec, rightPrec);
}
break;
case INTERSECT:
if (!((SqlSetOperator) call.getOperator()).isAll()) {
SqlSyntax.BINARY.unparse(writer, INTERSECT_DISTINCT, call, leftPrec, rightPrec);
}
break;
case TRIM:
unparseTrim(writer, call, leftPrec, rightPrec);
break;
case OTHER_FUNCTION:
String funName = call.getOperator().getName();
if (DOUBLE_LITERAL_WRAPPERS.containsKey(funName)) {
// self-designed function dealing with the unparsing of ZetaSQL DOUBLE positive
// infinity, negative infinity and NaN
unparseDoubleLiteralWrapperFunction(writer, funName);
break;
} else if (NUMERIC_LITERAL_WRAPPER.equals(funName)) {
// self-designed function dealing with the unparsing of ZetaSQL NUMERIC literal
unparseNumericLiteralWrapperFunction(writer, call, leftPrec, rightPrec);
break;
} else if (FUNCTIONS_USING_INTERVAL.contains(funName)) {
unparseFunctionsUsingInterval(writer, call, leftPrec, rightPrec);
break;
} else if (EXTRACT_FUNCTIONS.containsKey(funName)) {
unparseExtractFunctions(writer, call, leftPrec, rightPrec);
break;
} else if (IN_ARRAY_OPERATOR.equals(funName)) {
unparseInArrayOperator(writer, call, leftPrec, rightPrec);
break;
} // fall through
default:
super.unparseCall(writer, call, leftPrec, rightPrec);
}
}
/** BigQuery interval syntax: INTERVAL int64 time_unit. */
@Override
public void unparseSqlIntervalLiteral(
SqlWriter writer, SqlIntervalLiteral literal, int leftPrec, int rightPrec) {
SqlIntervalLiteral.IntervalValue interval =
(SqlIntervalLiteral.IntervalValue) literal.getValue();
writer.keyword("INTERVAL");
if (interval.getSign() == -1) {
writer.print("-");
}
Long intervalValueInLong;
try {
intervalValueInLong = Long.parseLong(literal.getValue().toString());
} catch (NumberFormatException e) {
throw new UnsupportedOperationException(
"Only INT64 is supported as the interval value for BigQuery.");
}
writer.literal(intervalValueInLong.toString());
unparseSqlIntervalQualifier(writer, interval.getIntervalQualifier(), RelDataTypeSystem.DEFAULT);
}
@Override
public void unparseSqlIntervalQualifier(
SqlWriter writer, SqlIntervalQualifier qualifier, RelDataTypeSystem typeSystem) {
final String start = validate(qualifier.timeUnitRange.startUnit).name();
if (qualifier.timeUnitRange.endUnit == null) {
writer.keyword(start);
} else {
throw new UnsupportedOperationException("Range time unit is not supported for BigQuery.");
}
}
/**
* For usage of TRIM, LTRIM and RTRIM in BQ see <a
* href="https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#trim">
* BQ Trim Function</a>.
*/
private void unparseTrim(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
final String operatorName;
SqlLiteral trimFlag = call.operand(0);
SqlLiteral valueToTrim = call.operand(1);
switch (trimFlag.getValueAs(SqlTrimFunction.Flag.class)) {
case LEADING:
operatorName = "LTRIM";
break;
case TRAILING:
operatorName = "RTRIM";
break;
default:
operatorName = call.getOperator().getName();
break;
}
final SqlWriter.Frame trimFrame = writer.startFunCall(operatorName);
call.operand(2).unparse(writer, leftPrec, rightPrec);
/**
* If the trimmed character is non space character then add it to the target sql. eg: TRIM(BOTH
* 'A' from 'ABCD' Output Query: TRIM('ABC', 'A')
*/
if (!valueToTrim.toValue().matches("\\s+")) {
writer.literal(",");
call.operand(1).unparse(writer, leftPrec, rightPrec);
}
writer.endFunCall(trimFrame);
}
private void unparseDoubleLiteralWrapperFunction(SqlWriter writer, String funName) {
writer.literal(DOUBLE_LITERAL_WRAPPERS.get(funName));
}
private void unparseNumericLiteralWrapperFunction(
SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
writer.literal("NUMERIC '");
call.operand(0).unparse(writer, leftPrec, rightPrec);
writer.literal("'");
}
/**
* For usage of INTERVAL, see <a
* href="https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators#timestamp_add">
* BQ TIMESTAMP_ADD function</a> for example.
*/
private void unparseFunctionsUsingInterval(
SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
// e.g. TIMESTAMP_ADD syntax:
// TIMESTAMP_ADD(timestamp_expression, INTERVAL int64_expression date_part)
int operandCount = call.operandCount();
if (operandCount == 2) {
// operand0: timestamp_expression
// operand1: SqlIntervalLiteral (INTERVAL int64_expression date_part)
super.unparseCall(writer, call, leftPrec, rightPrec);
} else if (operandCount == 3) {
// operand0: timestamp_expression
// operand1: int64_expression
// operand2: date_part
final SqlWriter.Frame frame = writer.startFunCall(call.getOperator().getName());
call.operand(0).unparse(writer, leftPrec, rightPrec);
writer.literal(",");
writer.literal("INTERVAL");
call.operand(1).unparse(writer, leftPrec, rightPrec);
call.operand(2).unparse(writer, leftPrec, rightPrec);
writer.endFunCall(frame);
} else {
throw new IllegalArgumentException(
String.format(
"Unable to unparse %s with %d operands.",
call.getOperator().getName(), operandCount));
}
}
private void unparseExtractFunctions(
SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
String funName = call.getOperator().getName();
int operandCount = call.operandCount();
SqlNode tz = null;
final SqlWriter.Frame frame = writer.startFunCall("EXTRACT");
if (!funName.equals("$extract") && (operandCount == 1 || operandCount == 2)) {
// EXTRACT(DATE/TIME/DATETIME FROM timestamp_expression [AT TIME ZONE tz])
// operand0: timestamp_expression
// operand1: tz (optional)
writer.literal(EXTRACT_FUNCTIONS.get(funName));
if (operandCount == 2) {
tz = call.operand(1);
}
} else if (funName.equals("$extract") && (operandCount == 2 || operandCount == 3)) {
// EXTRACT(date_part FROM timestamp_expression [AT TIME ZONE tz])
// operand0: timestamp_expression
// operand1: date_part
// operand2: tz (optional)
call.operand(1).unparse(writer, leftPrec, rightPrec);
if (operandCount == 3) {
tz = call.operand(2);
}
} else {
throw new IllegalArgumentException(
String.format("Unable to unparse %s with %d operands.", funName, operandCount));
}
writer.literal("FROM");
call.operand(0).unparse(writer, leftPrec, rightPrec);
if (tz != null) {
writer.literal("AT TIME ZONE");
tz.unparse(writer, leftPrec, rightPrec);
}
writer.endFunCall(frame);
}
private void unparseInArrayOperator(SqlWriter writer, SqlCall call, int leftPrec, int rightPrec) {
call.operand(0).unparse(writer, leftPrec, rightPrec);
writer.literal("IN UNNEST(");
call.operand(1).unparse(writer, leftPrec, rightPrec);
writer.literal(")");
}
private TimeUnit validate(TimeUnit timeUnit) {
switch (timeUnit) {
case MICROSECOND:
case MILLISECOND:
case SECOND:
case MINUTE:
case HOUR:
case DAY:
case WEEK:
case MONTH:
case QUARTER:
case YEAR:
case ISOYEAR:
return timeUnit;
default:
throw new UnsupportedOperationException(
"Time unit " + timeUnit + " is not supported for BigQuery.");
}
}
/**
* BigQuery data type reference: <a
* href="https://cloud.google.com/bigquery/docs/reference/standard-sql/data-types">Bigquery
* Standard SQL Data Types</a>.
*/
@Override
public SqlNode getCastSpec(final RelDataType type) {
if (type instanceof BasicSqlType) {
switch (type.getSqlTypeName()) {
// BigQuery only supports INT64 for integer types.
case BIGINT:
case INTEGER:
case TINYINT:
case SMALLINT:
return typeFromName(type, "INT64");
// BigQuery only supports FLOAT64(aka. Double) for floating point types.
case FLOAT:
case DOUBLE:
return typeFromName(type, "FLOAT64");
case DECIMAL:
return typeFromName(type, "NUMERIC");
case BOOLEAN:
return typeFromName(type, "BOOL");
case CHAR:
case VARCHAR:
return typeFromName(type, "STRING");
case VARBINARY:
case BINARY:
return typeFromName(type, "BYTES");
case DATE:
return typeFromName(type, "DATE");
case TIME:
return typeFromName(type, "TIME");
case TIMESTAMP:
return typeFromName(type, "TIMESTAMP");
default:
break;
}
}
return super.getCastSpec(type);
}
private static SqlNode typeFromName(RelDataType type, String name) {
return new SqlDataTypeSpec(
new SqlIdentifier(name, SqlParserPos.ZERO),
type.getPrecision(),
-1,
null,
null,
SqlParserPos.ZERO);
}
@Override
public void unparseDateTimeLiteral(
SqlWriter writer, SqlAbstractDateTimeLiteral literal, int leftPrec, int rightPrec) {
if (literal instanceof SqlTimestampLiteral) {
// 'Z' stands for +00 timezone offset, which is guaranteed in TIMESTAMP literal
writer.literal("TIMESTAMP '" + literal.toFormattedString() + "Z'");
} else {
super.unparseDateTimeLiteral(writer, literal, leftPrec, rightPrec);
}
}
}
| 40.682759 | 112 | 0.692151 |
036730291a052c455a3cf3e675779787cc8d9610 | 981 | package com.com.demo.heatmap.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import com.com.demo.heatmap.entity.PageEvent;
@Repository
public interface PageEventRepository extends JpaRepository<PageEvent, Long> {
PageEvent save(PageEvent pageEvent);
List<PageEvent> findByUrlHashAndEventType(String urlHash, String eventType);
@Query(nativeQuery = true, value = "select page_section, sum(stay_time) stay_time from page_events where URL_HASH=? and event_type='position' group by page_section order by page_section")
List<Object[]> findStayTimeByUrlHashAndEventTypeGroupByPosition(String urlHash);
@Query(nativeQuery = true, value = "select cursor_x, cursor_y, count(*) sum from page_events where url_hash=? and event_type='click' group by cursor_x, cursor_y")
List<Object[]> findByUrlHashGroupByCursor(String urlHash);
} | 42.652174 | 188 | 0.812436 |
6f13b5e4d957e847ba8487394c998036354e9668 | 4,479 | package edu.umass.cs.jfoley.coop.experiments.generic;
import ciir.jfoley.chai.collections.Pair;
import ciir.jfoley.chai.io.IO;
import ciir.jfoley.chai.io.LinesIterable;
import ciir.jfoley.chai.time.Debouncer;
import org.lemurproject.galago.core.parse.TagTokenizer;
import org.lemurproject.galago.core.retrieval.LocalRetrieval;
import org.lemurproject.galago.core.retrieval.Results;
import org.lemurproject.galago.core.retrieval.query.Node;
import org.lemurproject.galago.core.util.IterUtils;
import org.lemurproject.galago.utility.Parameters;
import org.lemurproject.galago.utility.StringPooler;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
* @author jfoley
*/
public class FastSDM {
public static class Effectiveness {
public static void main(String[] args) throws Exception {
Parameters retP = Parameters.create();
IterUtils.addToParameters(retP, SDM2.class);
LocalRetrieval target = new LocalRetrieval("/mnt/scratch3/jfoley/robust.galago", retP);
Map<String, String> queries = new TreeMap<>();
for (String line : LinesIterable.fromFile("/home/jfoley/code/queries/robust04/rob04.titles.tsv").slurp()) {
String[] row = line.split("\t");
queries.put(row[0].trim(), row[1].trim());
}
TagTokenizer tok = new TagTokenizer();
try (PrintWriter trecrun = IO.openPrintWriter("latest.trecrun")) {
for (Map.Entry<String, String> kv : queries.entrySet()) {
String qid = kv.getKey();
String text = kv.getValue();
List<String> terms = tok.tokenize(text).terms;
Node sdm = new Node("sdm2");
sdm.addTerms(terms);
long startTime = System.currentTimeMillis();
Parameters qp = Parameters.create();
qp.set("fast", true);
qp.set("stopUnigrams", true);
qp.set("stopUnordered", true);
Results res = target.transformAndExecuteQuery(sdm, qp);
long endTime = System.currentTimeMillis();
System.err.println(qid + "\t" + (endTime - startTime));
res.printToTrecrun(trecrun, qid, "sdm-fast");
}
}
}
}
public static class Efficiency {
public static void main(String[] args) throws Exception {
String op = "sdm";
String queryset = "mq";
int queryIter = 2;
StringPooler.disable();
Parameters retP = Parameters.create();
//retP.put("nodeStatisticsCacheSize", 0L);
retP.put("namesCacheSize", 100_000);
IterUtils.addToParameters(retP, SDM2.class);
LocalRetrieval target = new LocalRetrieval("/mnt/scratch3/jfoley/robust.galago", retP);
String queryFile;
switch (queryset) {
case "mq":
queryFile = "/home/jfoley/code/queries/million_query_track/mq.20001-60000.tsv";
break;
case "robust":
queryFile = "/home/jfoley/code/queries/robust04/rob04.titles.tsv";
break;
default: throw new IllegalArgumentException("queryset");
}
Map<String, String> queries = new TreeMap<>();
for (String line : LinesIterable.fromFile(queryFile).slurp()) {
String[] row = line.split("\t");
queries.put(row[0].trim(), row[1].trim());
}
Debouncer msg = new Debouncer();
TagTokenizer tok = new TagTokenizer();
try(PrintWriter timeWriter = IO.openPrintWriter(queryset+"."+op+".runtimes.tsv")) {
for (int i = 0; i < queryIter; i++) {
final int iterationNumber = i;
queries.entrySet().parallelStream().map(kv -> {
String qid = kv.getKey();
String text = kv.getValue();
if(msg.ready()) {
System.err.println(iterationNumber+"."+qid);
}
List<String> terms = tok.tokenize(text).terms;
Node sdm = new Node(op);
sdm.addTerms(terms);
long startTime = System.currentTimeMillis();
Parameters qp = Parameters.create();
qp.set("fast", true);
qp.set("stopUnigrams", true);
qp.set("stopUnordered", true);
Results res = target.transformAndExecuteQuery(sdm, qp);
long endTime = System.currentTimeMillis();
return Pair.of(qid, (endTime - startTime));
}).sequential().sorted(Pair.cmpLeft()).forEach(pr -> {
timeWriter.println(pr.left + "\t" + pr.right);
});
}
}
// done
}
}
}
| 36.414634 | 113 | 0.623577 |
e15961f062a6bd0d5d11b9c2fa8ef4a3b666be7e | 252 | package com.learning.java.Bot;
import java.util.Scanner;
/**
* Created by Aditya Rajput on 4/23/2017.
*/
public interface Element {
default void nonUsed(){}
static void voiceEcho(){
System.out.println("!");
}
}
| 15.75 | 42 | 0.599206 |
c07cbcc55d5c3644f65ac10d3e508ef9f77e030c | 1,700 | package com.scorelab.kute.kute.PrivateVehicles.App.DataModels;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Created by nipunarora on 10/06/17.
*/
public class Person implements Serializable {
/***************** Defing Properties ***********/
//Add provision for vehicle
//Make these variables private
public String id,name,img_base64,occupation,other_details,contact_phone,vehicle;
//Implement in some other way public Boolean is_friend; // This will indicate whether the given person is users friend
public ArrayList<Route> route_list;
public String token;
/*********** Properties Defined *******/
public Person() {
}
/****************** This constructor will configure for the list item
****************** rest detail will be filled later when person detail activity is called *******/
public Person(String name,String id,String img_base64,String token1) //Add id and img_url(Not being added right now because we dont have the backend for now)
{
this.name=name;
this.img_base64=img_base64;
this.id=id;
this.token=token1;
}
/************** This method will be invoked when we load personDetail Activity **********/
public void completePersonDetail(String occupation,String other_details,String phone,String vehicle)
{
this.occupation=occupation;
this.other_details=other_details;
this.contact_phone=phone;
this.vehicle=vehicle;
}
public void addRoutelist(ArrayList<Route>list)
{
this.route_list=list;
}
public Person(String id, String name) {
this.id = id;
this.name = name;
}
}
| 31.481481 | 163 | 0.648824 |
67e05bf0e4b9a15c63465637769ef28cffc3bfb4 | 3,497 | package org.int4.dirk.core;
import java.util.List;
import java.util.Set;
import org.int4.dirk.annotations.Opt;
import org.int4.dirk.api.Injector;
import org.int4.dirk.api.TypeLiteral;
import org.int4.dirk.api.instantiation.UnsatisfiedResolutionException;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import jakarta.inject.Inject;
import jakarta.inject.Provider;
public class InjectionTargetExtensionTest {
Injector injector = Injectors.manual();
@Test
void shouldGetInstancesForNestedTypes() throws Exception {
injector.registerInstance("A");
assertThat(injector.<Provider<String>>getInstance(new TypeLiteral<Provider<String>>() {}).get()).isEqualTo("A");
assertThat(injector.<Provider<Provider<String>>>getInstance(new TypeLiteral<Provider<Provider<String>>>() {}).get().get()).isEqualTo("A");
Provider<Integer> integerProvider = injector.getInstance(new TypeLiteral<Provider<Integer>>() {});
assertThat(integerProvider).isInstanceOf(Provider.class);
assertThatThrownBy(() -> integerProvider.get())
.isExactlyInstanceOf(UnsatisfiedResolutionException.class);
Provider<Provider<Integer>> integerProviderProvider = injector.getInstance(new TypeLiteral<Provider<Provider<Integer>>>() {});
assertThat(integerProviderProvider).isInstanceOf(Provider.class);
assertThat(integerProviderProvider.get()).isInstanceOf(Provider.class);
assertThatThrownBy(() -> integerProviderProvider.get().get())
.isExactlyInstanceOf(UnsatisfiedResolutionException.class);
}
public void shouldInjectAvailableTypeInVariousNestedTargets() throws Exception {
injector.register(IntegerProviderInjected.class);
IntegerProviderInjected instance = injector.getInstance(IntegerProviderInjected.class);
assertThat(instance.b.get()).isNull();
assertThat(instance.c.get()).isEmpty();
assertThat(instance.d.get()).isNull();
assertThat(instance.e.get()).isEmpty();
assertThat(instance.f.get()).isNull();
assertThat(instance.h.get().get()).isNull();
}
public void shouldInjectDefaultsInVariousTargets() throws Exception {
injector.registerInstance("A");
injector.register(IntegerProviderInjected.class);
StringProviderInjected instance = injector.getInstance(StringProviderInjected.class);
assertThat(instance.a.get()).isEqualTo("A");
assertThat(instance.b.get()).isEqualTo("A");
assertThat(instance.c.get()).containsExactly("A");
assertThat(instance.d.get()).containsExactly("A");
assertThat(instance.e.get()).containsExactly("A");
assertThat(instance.f.get()).containsExactly("A");
assertThat(instance.g.get().get()).isEqualTo("A");
assertThat(instance.h.get().get()).isEqualTo("A");
}
public static class StringProviderInjected {
@Inject Provider<String> a;
@Inject @Opt Provider<String> b;
@Inject Provider<List<String>> c;
@Inject @Opt Provider<List<String>> d;
@Inject Provider<Set<String>> e;
@Inject @Opt Provider<Set<String>> f;
@Inject Provider<Provider<String>> g;
@Inject @Opt Provider<Provider<String>> h;
}
public static class IntegerProviderInjected {
@Inject @Opt Provider<Integer> b;
@Inject Provider<List<Integer>> c;
@Inject @Opt Provider<List<Integer>> d;
@Inject Provider<Set<Integer>> e;
@Inject @Opt Provider<Set<Integer>> f;
@Inject @Opt Provider<Provider<Integer>> h;
}
}
| 38.855556 | 142 | 0.739777 |
89704ffacee2c6e781baf460ffe9e94f02a90d8d | 152 | package io.cattle.platform.core.addon;
import io.github.ibuildthecloud.gdapi.annotation.Type;
@Type(list = false)
public class BaseMachineConfig {
}
| 16.888889 | 54 | 0.789474 |
096031d990042dbfa229eef1cf9610f81973e627 | 405 | package com.paito.biz.auction.dao;
import com.paito.biz.auction.dto.AuctionDO;
import java.util.List;
/**
* Created by patrick on 16/2/4.
*/
public interface IAuctionDAO {
public List<AuctionDO> findAuctionList(Long userId, Integer status);
void saveAuction(AuctionDO auctionDO);
void auditAuction(AuctionDO auctionDO);
List<AuctionDO> findAuctionListByStatus(Integer status);
}
| 19.285714 | 72 | 0.748148 |
694aafde1793194a8375c39bc96d536c02ab2a91 | 1,559 | package com.treyzania.mc.zaniportals;
import java.util.List;
import org.bukkit.configuration.file.FileConfiguration;
import com.treyzania.mc.zaniportals.adapters.PortalConfig;
public class ZaniPortalsBukkitConfig implements PortalConfig {
public List<Integer> signPlaceBlockIds;
public List<Integer> portalStructureBlockIds;
public int portalBlockId;
public int maxPortalBlocks;
protected ZaniPortalsBukkitConfig(FileConfiguration fc) {
this.signPlaceBlockIds = fc.getIntegerList("PortalStructure.SignPlaceOnBlocks");
this.portalStructureBlockIds = fc.getIntegerList("PortalStructure.PortalFrameBlocks");
this.portalBlockId = fc.getInt("PortalStructure.PortalBlock");
this.maxPortalBlocks = fc.getInt("PortalStructure.MaxPortalBlocks");
}
@Override
public int[] getFrameBlockIds() {
// No easy way to get convert the list of Integers into an array of ints.
int[] array = new int[portalStructureBlockIds.size()];
for (int i = 0; i < portalStructureBlockIds.size(); i++) {
array[i] = portalStructureBlockIds.get(i);
}
return array;
}
@Override
public int getPortalBlockId() {
return this.portalBlockId;
}
@Override
public int getMaxPortalSize() {
return this.maxPortalBlocks;
}
@Override
public boolean isBlockImportant(int id) {
// Very simple checks here.
if (id == this.portalBlockId) return true;
if (this.portalStructureBlockIds.contains(Integer.valueOf(id))) return true;
if (this.signPlaceBlockIds.contains(Integer.valueOf(id))) return true;
return false;
}
}
| 25.557377 | 88 | 0.754971 |
c7eb1fcebd417ea62f16274836dae0dfafe4b436 | 1,339 | package com.alipay.api.domain;
import com.alipay.api.AlipayObject;
import com.alipay.api.internal.mapping.ApiField;
/**
* 口碑视图规则模型
*
* @author auto create
* @since 1.0, 2020-03-31 22:04:35
*/
public class KbdishCommRuleShowInfo extends AlipayObject {
private static final long serialVersionUID = 2576125795817388335L;
/**
* 规则扩展
*/
@ApiField("tag_ext_info")
private String tagExtInfo;
/**
* 键值如下:
组维度的规则:
minLimit:组最小选择份数
maxLimit:组最大选择份数
required:是否必选
selectNum:可选选项数量,默认不限制
fold:是否折叠到进阶选择里
change: 是否可以置换
明细维度的规则:
minLimit:明细最小选择份数
maxLimit:明细最大选择份数
addPrice:加价
addPriceStep:加价步长,默认为1
defaultNum:默认份数
default:是否默认
required:是否必选
规格组维度的规则:
default: 是否默认
规则标签明细的规则:
default: 是否默认
sort: 排序值
hidden:是否隐藏
*/
@ApiField("tag_name")
private String tagName;
/**
* 规则值 数字 或者是否 , 数字 或者true/false
*/
@ApiField("tag_value")
private String tagValue;
public String getTagExtInfo() {
return this.tagExtInfo;
}
public void setTagExtInfo(String tagExtInfo) {
this.tagExtInfo = tagExtInfo;
}
public String getTagName() {
return this.tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
public String getTagValue() {
return this.tagValue;
}
public void setTagValue(String tagValue) {
this.tagValue = tagValue;
}
}
| 17.166667 | 68 | 0.707991 |
8b21c8e72b8e9250a00807fcea3cf6193f805e43 | 1,067 | /*
* Copyright (C) 2007 XStream Committers.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
* Created on 07. October 2007 by Guilherme Silveira
*/
package com.thoughtworks.acceptance.annotations;
import com.thoughtworks.acceptance.AbstractBuilderAcceptanceTest;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.builder.XStreamBuilder;
public class XStreamBuilderAnnotationsTest extends AbstractBuilderAcceptanceTest {
@XStreamAlias("annotated")
public static class Annotated {
}
public void testHandleCorrectlyAnnotatedClasses() {
XStreamBuilder builder = new XStreamBuilder() {
{
handle(Annotated.class).with(annotated());
}
};
Annotated root = new Annotated();
String expected = "<annotated/>";
assertBothWays(builder.buildXStream(), root, expected);
}
}
| 27.358974 | 82 | 0.710403 |
d3d19af5e5366fe435c6821058b71f3a85564f63 | 27,616 | /*
* Copyright 2016 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.elasticsearch.model;
import static java.lang.String.format;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.netflix.frigga.Names;
import com.netflix.spinnaker.clouddriver.core.services.Front50Service;
import com.netflix.spinnaker.clouddriver.helpers.OperationPoller;
import com.netflix.spinnaker.clouddriver.model.EntityTags;
import com.netflix.spinnaker.clouddriver.model.EntityTagsProvider;
import com.netflix.spinnaker.config.ElasticSearchConfigProperties;
import com.netflix.spinnaker.kork.core.RetrySupport;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.ClearScroll;
import io.searchbox.core.Delete;
import io.searchbox.core.Index;
import io.searchbox.core.Search;
import io.searchbox.core.SearchResult;
import io.searchbox.core.SearchScroll;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.DeleteIndex;
import io.searchbox.params.Parameters;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class ElasticSearchEntityTagsProvider implements EntityTagsProvider {
private static final Logger log = LoggerFactory.getLogger(ElasticSearchEntityTagsProvider.class);
private final ApplicationContext applicationContext;
private final RetrySupport retrySupport;
private final ObjectMapper objectMapper;
private final Front50Service front50Service;
private final JestClient jestClient;
private final String activeElasticSearchIndex;
private final String mappingTypeName;
@Autowired
public ElasticSearchEntityTagsProvider(
ApplicationContext applicationContext,
RetrySupport retrySupport,
ObjectMapper objectMapper,
Front50Service front50Service,
JestClient jestClient,
ElasticSearchConfigProperties elasticSearchConfigProperties) {
this.applicationContext = applicationContext;
this.retrySupport = retrySupport;
this.objectMapper = objectMapper;
this.front50Service = front50Service;
this.jestClient = jestClient;
this.activeElasticSearchIndex = elasticSearchConfigProperties.getActiveIndex();
this.mappingTypeName = elasticSearchConfigProperties.getMappingTypeName();
}
@Override
public Collection<EntityTags> getAll(
String cloudProvider,
String application,
String entityType,
List<String> entityIds,
String idPrefix,
String account,
String region,
String namespace,
Map<String, Object> tags,
int maxResults) {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
if (cloudProvider != null) {
// restrict to a specific cloudProvider (optional)
queryBuilder =
queryBuilder.must(QueryBuilders.termQuery("entityRef.cloudProvider", cloudProvider));
}
if (application != null) {
// restrict to a specific application (optional)
queryBuilder =
queryBuilder.must(QueryBuilders.termQuery("entityRef.application", application));
}
if (entityIds != null && !entityIds.isEmpty()) {
// restrict to a specific set of entityIds (optional)
queryBuilder = queryBuilder.must(QueryBuilders.termsQuery("entityRef.entityId", entityIds));
}
if (account != null) {
// restrict to a specific set of entityIds (optional)
queryBuilder = queryBuilder.must(QueryBuilders.termQuery("entityRef.account", account));
}
if (region != null) {
// restrict to a specific set of entityIds (optional)
queryBuilder = queryBuilder.must(QueryBuilders.termQuery("entityRef.region", region));
}
if (idPrefix != null) {
// restrict to a specific id prefix (optional)
queryBuilder = queryBuilder.must(QueryBuilders.wildcardQuery("id", idPrefix));
}
if (entityType != null) {
queryBuilder =
queryBuilder.must(
QueryBuilders.wildcardQuery("entityRef.entityType", entityType.toLowerCase()));
}
if (tags != null) {
for (Map.Entry<String, Object> entry : tags.entrySet()) {
// each key/value pair maps to a distinct nested `tags` object and must be a unique query
// snippet
queryBuilder =
queryBuilder.must(
applyTagsToBuilder(
namespace, Collections.singletonMap(entry.getKey(), entry.getValue())));
}
}
if ((tags == null || tags.isEmpty()) && namespace != null) {
// this supports a search akin to /tags?namespace=my_namespace which should return all
// entities with _any_ tag in
// the given namespace ... ensures that the namespace filter is applied even if no tag
// criteria provided
queryBuilder = queryBuilder.must(applyTagsToBuilder(namespace, Collections.emptyMap()));
}
return search(queryBuilder, maxResults);
}
@Override
public Optional<EntityTags> get(String id) {
return get(id, Collections.emptyMap());
}
@Override
public Optional<EntityTags> get(String id, Map<String, Object> tags) {
BoolQueryBuilder queryBuilder =
QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("_id", id));
if (tags != null) {
for (Map.Entry<String, Object> entry : tags.entrySet()) {
// each key/value pair maps to a distinct nested `tags` object and must be a unique query
// snippet
queryBuilder =
queryBuilder.must(
applyTagsToBuilder(
null, Collections.singletonMap(entry.getKey(), entry.getValue())));
}
}
List<EntityTags> entityTags = search(queryBuilder, 1);
return entityTags.isEmpty() ? Optional.empty() : Optional.of(entityTags.get(0));
}
@Override
public void index(EntityTags entityTags) {
try {
Index action =
new Index.Builder(
objectMapper.convertValue(prepareForWrite(objectMapper, entityTags), Map.class))
.index(activeElasticSearchIndex)
.type(mappingTypeName)
.id(URLEncoder.encode(entityTags.getId(), "UTF-8"))
.build();
JestResult jestResult = jestClient.execute(action);
if (!jestResult.isSucceeded()) {
throw new ElasticSearchException(
format(
"Failed to index %s, reason: '%s'",
entityTags.getId(), jestResult.getErrorMessage()));
}
} catch (IOException e) {
throw new ElasticSearchException(
format("Failed to index %s, reason: '%s'", entityTags.getId(), e.getMessage()));
}
}
@Override
public void bulkIndex(Collection<EntityTags> multipleEntityTags) {
Lists.partition(new ArrayList<>(multipleEntityTags), 1000)
.forEach(
tags -> {
Bulk.Builder builder = new Bulk.Builder().defaultIndex(activeElasticSearchIndex);
for (EntityTags entityTags : tags) {
Map tag =
objectMapper.convertValue(prepareForWrite(objectMapper, entityTags), Map.class);
builder =
builder.addAction(
new Index.Builder(tag)
.index(activeElasticSearchIndex)
.type(mappingTypeName)
.id(entityTags.getId())
.build());
}
Bulk bulk = builder.build();
retrySupport.retry(
() -> {
try {
JestResult jestResult = jestClient.execute(bulk);
if (!jestResult.isSucceeded()) {
throw new ElasticSearchException(
format(
"Failed to index bulk entity tags, reason: '%s'",
jestResult.getErrorMessage()));
}
return true;
} catch (IOException e) {
String message =
format("Failed to index bulk entity tags, reason: '%s'", e.getMessage());
log.error(message + " ... retrying!");
throw new ElasticSearchException(message);
}
},
5,
1000,
false);
});
}
@Override
public void delete(String id) {
try {
EntityTags entityTags = get(id).orElse(null);
if (entityTags == null) {
// EntityTags w/ id = :id does not actually exist
return;
}
Delete action =
new Delete.Builder(id).index(activeElasticSearchIndex).type(mappingTypeName).build();
JestResult jestResult = jestClient.execute(action);
if (!jestResult.isSucceeded()) {
throw new ElasticSearchException(
format("Failed to delete %s, reason: '%s'", id, jestResult.getErrorMessage()));
}
} catch (IOException e) {
throw new ElasticSearchException(
format("Failed to delete %s, reason: '%s'", id, e.getMessage()));
}
}
@Override
public void bulkDelete(Collection<EntityTags> multipleEntityTags) {
Lists.partition(new ArrayList<>(multipleEntityTags), 1000)
.forEach(
tags -> {
Bulk.Builder builder = new Bulk.Builder().defaultIndex(activeElasticSearchIndex);
for (EntityTags entityTags : tags) {
builder =
builder.addAction(
new Delete.Builder(entityTags.getId()).type(mappingTypeName).build());
}
Bulk bulk = builder.build();
try {
JestResult jestResult = jestClient.execute(bulk);
if (!jestResult.isSucceeded()) {
throw new ElasticSearchException(
format(
"Failed to bulk delete entity tags, reason: '%s'",
jestResult.getErrorMessage()));
}
} catch (IOException e) {
throw new ElasticSearchException(
format("Failed to bulk delete entity tags, reason: '%s'", e.getMessage()));
}
});
}
@Override
public void reindex() {
try {
log.info("Deleting Index {}", activeElasticSearchIndex);
jestClient.execute(new DeleteIndex.Builder(activeElasticSearchIndex).build());
log.info("Deleted Index {}", activeElasticSearchIndex);
log.info("Creating Index {}", activeElasticSearchIndex);
jestClient.execute(new CreateIndex.Builder(activeElasticSearchIndex).build());
log.info("Created Index {}", activeElasticSearchIndex);
} catch (IOException e) {
throw new ElasticSearchException(
"Unable to re-create index '" + activeElasticSearchIndex + "'");
}
Collection<EntityTags> entityTags = front50Service.getAllEntityTags(true);
Collection<EntityTags> filteredEntityTags =
getElasticSearchEntityTagsReconciler().filter(entityTags);
log.info(
"Indexing {} entity tags ({} orphans have been excluded)",
filteredEntityTags.size(),
entityTags.size() - filteredEntityTags.size());
bulkIndex(
filteredEntityTags.stream()
.filter(e -> e.getEntityRef() != null)
.collect(Collectors.toList()));
log.info("Indexed {} entity tags", filteredEntityTags.size());
}
@Override
public Map delta() {
Collection<EntityTags> allEntityTagsFront50 = front50Service.getAllEntityTags(false);
Map<String, List<EntityTags>> entityTagsByEntityTypeFront50 =
allEntityTagsFront50.stream()
.collect(
Collectors.groupingBy(
e ->
Optional.ofNullable(
Optional.ofNullable(e.getEntityRef())
.orElse(new EntityTags.EntityRef())
.getEntityType())
.orElse("unknown")));
Map<String, List<EntityTags>> entityTagsByEntityTypeElasticsearch = new HashMap<>();
entityTagsByEntityTypeFront50
.keySet()
.forEach(
entityType -> {
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder =
queryBuilder.must(QueryBuilders.termQuery("entityRef.entityType", entityType));
entityTagsByEntityTypeElasticsearch.put(
entityType, fetchAll(queryBuilder, 5000, "2m"));
});
Map<String, Map> metadata = new HashMap<>();
entityTagsByEntityTypeFront50
.keySet()
.forEach(
entityType -> {
Map<String, Object> entityTypeMetadata = new HashMap<>();
metadata.put(entityType, entityTypeMetadata);
Set<String> entityIdsFront50 =
entityTagsByEntityTypeFront50.get(entityType).stream()
.map(EntityTags::getId)
.collect(Collectors.toSet());
Set<String> entityIdsElasticsearch =
entityTagsByEntityTypeElasticsearch.get(entityType).stream()
.map(EntityTags::getId)
.collect(Collectors.toSet());
entityTypeMetadata.put("front50_count", entityIdsFront50.size());
entityTypeMetadata.put("elasticsearch_count", entityIdsElasticsearch.size());
if (!entityIdsFront50.equals(entityIdsElasticsearch)) {
Set<String> entityIdsMissingInFront50 =
entityIdsElasticsearch.stream()
.filter(e -> !entityIdsFront50.contains(e))
.collect(Collectors.toSet());
Set<String> entityIdsMissingInElasticsearch =
entityIdsFront50.stream()
.filter(e -> !entityIdsElasticsearch.contains(e))
.collect(Collectors.toSet());
log.warn(
"'{}' missing in Front50 ({}) {}",
entityType,
entityIdsMissingInFront50.size(),
entityIdsMissingInFront50);
log.warn(
"'{}' missing in Elasticsearch ({}) {}",
entityType,
entityIdsMissingInElasticsearch.size(),
entityIdsMissingInElasticsearch);
entityTypeMetadata.put("front50_missing", entityIdsMissingInFront50);
entityTypeMetadata.put("front50_missing_count", entityIdsMissingInFront50.size());
entityTypeMetadata.put("elasticsearch_missing", entityIdsMissingInElasticsearch);
entityTypeMetadata.put(
"elasticsearch_missing_count", entityIdsMissingInElasticsearch.size());
}
});
return metadata;
}
@Override
public void verifyIndex(EntityTags entityTags) {
OperationPoller.retryWithBackoff(
o -> {
// verify that the indexed document can be retrieved (accounts for index lag)
Map<String, Object> entityTagsCriteria = new HashMap<>();
entityTags.getTags().stream()
.filter(entityTag -> entityTag != null && entityTag.getValueType() != null)
.forEach(
entityTag -> {
switch (entityTag.getValueType()) {
case object:
entityTagsCriteria.put(entityTag.getName(), "*");
break;
default:
entityTagsCriteria.put(
entityTag.getName(), entityTag.getValueForRead(objectMapper));
}
});
if (!get(entityTags.getId(), entityTagsCriteria).isPresent()) {
throw new ElasticSearchException(
format(
"Failed to index %s, reason: 'no document found with id'", entityTags.getId()));
}
return true;
},
1000,
3);
}
@Override
public Map reconcile(String cloudProvider, String account, String region, boolean dryRun) {
return getElasticSearchEntityTagsReconciler()
.reconcile(this, cloudProvider, account, region, dryRun);
}
@Override
public Map<String, Object> deleteByNamespace(
String namespace, boolean dryRun, boolean deleteFromSource) {
List<EntityTags> entityTagsForNamespace = getAllMatchingEntityTags(namespace, null);
for (EntityTags entityTags : entityTagsForNamespace) {
// ensure that all tags (and their metadata) in the offending namespace are removed
entityTags.setTags(
entityTags.getTags().stream()
.filter(e -> !namespace.equalsIgnoreCase(e.getNamespace()))
.collect(Collectors.toList()));
Set<String> tagNames =
entityTags.getTags().stream()
.map(e -> e.getName().toLowerCase())
.collect(Collectors.toSet());
entityTags.setTagsMetadata(
entityTags.getTagsMetadata().stream()
.filter(e -> tagNames.contains(e.getName().toLowerCase()))
.collect(Collectors.toList()));
}
Map results =
new HashMap() {
{
put(
"affectedIds",
entityTagsForNamespace.stream()
.map(EntityTags::getId)
.collect(Collectors.toList()));
put("deletedFromSource", false);
put("deletedFromElasticsearch", false);
}
};
if (!dryRun) {
bulkIndex(entityTagsForNamespace);
results.put("deletedFromElasticsearch", true);
if (deleteFromSource) {
Lists.partition(entityTagsForNamespace, 50).forEach(front50Service::batchUpdate);
results.put("deletedFromSource", true);
}
}
return results;
}
@Override
public Map<String, Object> deleteByTag(String tag, boolean dryRun, boolean deleteFromSource) {
List<EntityTags> entityTagsForTag = getAllMatchingEntityTags(null, tag);
for (EntityTags entityTags : entityTagsForTag) {
// ensure that all matching tags (and their metadata) are removed
entityTags.setTags(
entityTags.getTags().stream()
.filter(e -> !tag.equalsIgnoreCase(e.getName()))
.collect(Collectors.toList()));
Set<String> tagNames =
entityTags.getTags().stream()
.map(e -> e.getName().toLowerCase())
.collect(Collectors.toSet());
entityTags.setTagsMetadata(
entityTags.getTagsMetadata().stream()
.filter(e -> tagNames.contains(e.getName().toLowerCase()))
.collect(Collectors.toList()));
}
Map results =
new HashMap() {
{
put(
"affectedIds",
entityTagsForTag.stream().map(EntityTags::getId).collect(Collectors.toList()));
put("deletedFromSource", false);
put("deletedFromElasticsearch", false);
}
};
if (!dryRun) {
bulkIndex(entityTagsForTag);
results.put("deletedFromElasticsearch", true);
if (deleteFromSource) {
Lists.partition(entityTagsForTag, 50).forEach(front50Service::batchUpdate);
results.put("deletedFromSource", true);
}
}
return results;
}
private List<EntityTags> getAllMatchingEntityTags(String namespace, String tag) {
Set<String> entityTagsIdentifiers = new HashSet<>();
List<EntityTags> entityTagsForTag =
front50Service.getAllEntityTags(false).stream()
.filter(
e ->
e.getTags().stream()
.anyMatch(
t ->
(namespace != null && namespace.equalsIgnoreCase(t.getNamespace()))
|| (tag != null && tag.equalsIgnoreCase(t.getName()))))
.collect(Collectors.toList());
entityTagsIdentifiers.addAll(
entityTagsForTag.stream().map(e -> e.getId().toLowerCase()).collect(Collectors.toSet()));
if (tag != null) {
BoolQueryBuilder queryBuilder =
QueryBuilders.boolQuery()
.must(applyTagsToBuilder(null, Collections.singletonMap(tag, "*")));
fetchAll(queryBuilder, 5000, "2m")
.forEach(
entityTags -> {
if (!entityTagsIdentifiers.contains(entityTags.getId())) {
entityTagsForTag.add(entityTags);
entityTagsIdentifiers.add(entityTags.getId().toLowerCase());
}
});
}
if (namespace != null) {
BoolQueryBuilder queryBuilder =
QueryBuilders.boolQuery().must(applyTagsToBuilder(namespace, Collections.emptyMap()));
fetchAll(queryBuilder, 5000, "2m")
.forEach(
entityTags -> {
if (!entityTagsIdentifiers.contains(entityTags.getId())) {
entityTagsForTag.add(entityTags);
entityTagsIdentifiers.add(entityTags.getId().toLowerCase());
}
});
}
return entityTagsForTag;
}
private QueryBuilder applyTagsToBuilder(String namespace, Map<String, Object> tags) {
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
if (tags != null && !tags.isEmpty()) {
for (Map.Entry<String, Object> entry : flatten(new HashMap<>(), null, tags).entrySet()) {
// restrict to specific tags (optional)
boolQueryBuilder.must(QueryBuilders.termQuery("tags.name", entry.getKey()));
if (!entry.getValue().equals("*")) {
boolQueryBuilder.must(QueryBuilders.matchQuery("tags.value", entry.getValue()));
}
}
}
if (namespace != null) {
boolQueryBuilder.must(QueryBuilders.termQuery("tags.namespace", namespace));
}
return QueryBuilders.nestedQuery("tags", boolQueryBuilder, ScoreMode.Avg);
}
/** Elasticsearch requires that all search criteria be flattened (vs. nested) */
private Map<String, Object> flatten(
Map<String, Object> accumulator, String rootKey, Map<String, Object> criteria) {
criteria.forEach(
(k, v) -> {
if (v instanceof Map) {
flatten(accumulator, (rootKey == null) ? "" + k : rootKey + "." + k, (Map) v);
} else {
accumulator.put((rootKey == null) ? "" + k : rootKey + "." + k, v);
}
});
return accumulator;
}
private List<EntityTags> search(QueryBuilder queryBuilder, int maxResults) {
SearchSourceBuilder searchSourceBuilder =
new SearchSourceBuilder().query(queryBuilder).size(maxResults);
String searchQuery = searchSourceBuilder.toString();
Search.Builder searchBuilder =
new Search.Builder(searchQuery).addIndex(activeElasticSearchIndex);
try {
SearchResult searchResult = jestClient.execute(searchBuilder.build());
return searchResult.getHits(Map.class).stream()
.map(h -> h.source)
.map(s -> prepareForRead(objectMapper, s))
.collect(Collectors.toList());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private List<EntityTags> fetchAll(QueryBuilder queryBuilder, int scrollSize, String scrollTime) {
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(queryBuilder);
Search.Builder builder =
new Search.Builder(searchSourceBuilder.toString()).addIndex(activeElasticSearchIndex);
Search search =
builder
.setParameter(Parameters.SIZE, scrollSize)
.setParameter(Parameters.SCROLL, scrollTime)
.build();
List<EntityTags> allEntityTags = new ArrayList<>();
JestResult result;
try {
result = jestClient.execute(search);
} catch (IOException e) {
throw new RuntimeException(e);
}
Collection<EntityTags> entityTags = result.getSourceAsObjectList(EntityTags.class);
allEntityTags.addAll(entityTags);
String scrollId = result.getJsonObject().get("_scroll_id").getAsString();
try {
while (entityTags.size() > 0) {
SearchScroll scroll = new SearchScroll.Builder(scrollId, scrollTime).build();
try {
result = jestClient.execute(scroll);
} catch (IOException e) {
throw new RuntimeException(e);
}
entityTags = result.getSourceAsObjectList(EntityTags.class);
allEntityTags.addAll(entityTags);
scrollId = result.getJsonObject().getAsJsonPrimitive("_scroll_id").getAsString();
}
return allEntityTags;
} finally {
try {
jestClient.execute(new ClearScroll.Builder().addScrollId(scrollId).build());
} catch (IOException e) {
log.warn("Unable to clear scroll id {}", scrollId, e);
}
}
}
private ElasticSearchEntityTagsReconciler getElasticSearchEntityTagsReconciler() {
return applicationContext.getBean(ElasticSearchEntityTagsReconciler.class);
}
private static EntityTags prepareForWrite(ObjectMapper objectMapper, EntityTags entityTags) {
EntityTags copyOfEntityTags =
objectMapper.convertValue(
objectMapper.convertValue(entityTags, Map.class), EntityTags.class);
copyOfEntityTags
.getTags()
.forEach(entityTag -> entityTag.setValue(entityTag.getValueForWrite(objectMapper)));
String application = copyOfEntityTags.getEntityRef().getApplication();
if (application == null || application.trim().isEmpty()) {
try {
Names names = Names.parseName(copyOfEntityTags.getEntityRef().getEntityId());
copyOfEntityTags.getEntityRef().setApplication(names.getApp());
} catch (Exception e) {
log.error(
"Unable to extract application name (entityId: {})",
copyOfEntityTags.getEntityRef().getEntityId(),
e);
}
}
return copyOfEntityTags;
}
private static EntityTags prepareForRead(ObjectMapper objectMapper, Map indexedEntityTags) {
EntityTags entityTags = objectMapper.convertValue(indexedEntityTags, EntityTags.class);
entityTags
.getTags()
.forEach(entityTag -> entityTag.setValue(entityTag.getValueForRead(objectMapper)));
return entityTags;
}
}
| 37.018767 | 100 | 0.619894 |
65f983cc14d448e0b075c78031d2bb0370ea63a3 | 7,643 | package com.example.misha.myapplication.module.schedule.edit;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Spinner;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager.widget.ViewPager.SimpleOnPageChangeListener;
import com.example.misha.myapplication.CustomSpinnerAdapterWeeks;
import com.example.misha.myapplication.R;
import com.example.misha.myapplication.common.core.BaseMainFragment;
import com.example.misha.myapplication.common.core.BasePresenter;
import com.example.misha.myapplication.data.preferences.Preferences;
import com.example.misha.myapplication.module.schedule.TabDaysAdapter;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import org.jetbrains.annotations.NotNull;
import static com.example.misha.myapplication.data.preferences.Preferences.DARK_THEME;
import static com.example.misha.myapplication.data.preferences.Preferences.LIGHT_THEME;
public class EditScheduleFragment extends BaseMainFragment implements EditScheduleFragmentView, View.OnClickListener, AdapterView.OnItemSelectedListener {
private EditScheduleFragmentPagerAdapter pagerAdapter;
private TabDaysAdapter adapterTabDays;
private Spinner spinner;
private ViewPager viewPager;
private FloatingActionButton mainFab, evenWeekFab, unevenWeekFab;
private Animation fabOpen, fabClose, rotateForward, rotateBackward;
private RecyclerView dayTabs;
private CustomSpinnerAdapterWeeks customSpinnerAdapterWeeks;
private EditSchedulePresenter presenter;
@Override
public void onResume() {
super.onResume();
spinner = new Spinner(getContext());
spinner.setBackgroundColor(Color.TRANSPARENT);
spinner.setAdapter(customSpinnerAdapterWeeks);
spinner.setOnItemSelectedListener(this);
presenter.init();
getContext().getToolbar().addView(spinner);
getContext().setCurrentTitle(null);
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
presenter.onWeekSelected(position);
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
presenter = new EditSchedulePresenter(getContext());
setHasOptionsMenu(true);
customSpinnerAdapterWeeks = new CustomSpinnerAdapterWeeks(getContext());
pagerAdapter = new EditScheduleFragmentPagerAdapter(getChildFragmentManager());
adapterTabDays = new TabDaysAdapter((position, view) -> presenter.onPageSelected(position));
}
public View onCreateView(@NotNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_edit_schedule, container, false);
viewPager = view.findViewById(R.id.viewPager);
viewPager.addOnPageChangeListener(new SimpleOnPageChangeListener() {
@Override
public void onPageSelected(int position) {
presenter.onPageSwiped(position);
}
});
evenWeekFab = view.findViewById(R.id.even_weekFab);
unevenWeekFab = view.findViewById(R.id.uneven_weekFab);
viewPager.setAdapter(pagerAdapter);
viewPager.setOffscreenPageLimit(6);
dayTabs = view.findViewById(R.id.rv_tab);
dayTabs.setAdapter(adapterTabDays);
mainFab = view.findViewById(R.id.main_fab);
fabOpen = AnimationUtils.loadAnimation(getContext(), R.anim.fab_open);
fabClose = AnimationUtils.loadAnimation(getContext(), R.anim.fab_close);
rotateForward = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_forward);
rotateBackward = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_backward);
mainFab.setOnClickListener(this);
evenWeekFab.setOnClickListener(this);
unevenWeekFab.setOnClickListener(this);
return view;
}
@Override
public void onCreateOptionsMenu(@NotNull Menu menu, @NotNull MenuInflater inflater) {
inflater.inflate(R.menu.menu_empty, menu);
if (Preferences.getInstance().getSelectedTheme().equals(DARK_THEME)) {
menu.findItem(R.id.btn_edit).setIcon(R.drawable.ic_ok_white);
}
if (Preferences.getInstance().getSelectedTheme().equals(LIGHT_THEME)) {
menu.findItem(R.id.btn_edit).setIcon(R.drawable.ic_ok_black);
}
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
@NonNull
@Override
protected BasePresenter getSchedulePagePresenter() {
return presenter;
}
@Override
public void selectWeek(int position) {
pagerAdapter.setWeek(position);
adapterTabDays.updateData(position);
adapterTabDays.setSelection(viewPager.getCurrentItem());
dayTabs.setAdapter(adapterTabDays);
}
@Override
public void selectCurrentDay(int currentDay) {
int selectedDayTab = Preferences.getInstance().getSelectedPositionTabDays();
viewPager.setCurrentItem(selectedDayTab);
adapterTabDays.setSelection(selectedDayTab);
}
@Override
public void selectCurrentWeek(int currentWeek) {
spinner.setSelection(currentWeek);
}
@Override
public void swipePage(int position) {
adapterTabDays.setSelection(position);
}
@Override
public void selectPage(int position) {
viewPager.setCurrentItem(position);
}
@Override
public void onPause() {
super.onPause();
getContext().getToolbar().removeView(spinner);
}
@Override
public boolean onOptionsItemSelected(@NotNull MenuItem item) {
if (item.getItemId() == R.id.btn_edit) {
getContext().getSupportFragmentManager().popBackStack();
}
return super.onOptionsItemSelected(item);
}
public void animateFAB() {
if (Preferences.getInstance().getFabOpen()) {
mainFab.startAnimation(rotateBackward);
evenWeekFab.startAnimation(fabClose);
unevenWeekFab.startAnimation(fabClose);
evenWeekFab.setClickable(false);
unevenWeekFab.setClickable(false);
Preferences.getInstance().setFabOpen(false);
} else {
mainFab.startAnimation(rotateForward);
evenWeekFab.startAnimation(fabOpen);
unevenWeekFab.startAnimation(fabOpen);
evenWeekFab.setClickable(true);
unevenWeekFab.setClickable(true);
Preferences.getInstance().setFabOpen(true);
}
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.main_fab:
presenter.onButtonClicked(R.id.main_fab);
break;
case R.id.even_weekFab:
presenter.onButtonClicked(R.id.even_weekFab);
break;
case R.id.uneven_weekFab:
presenter.onButtonClicked(R.id.uneven_weekFab);
break;
}
}
}
| 35.882629 | 154 | 0.704566 |
18aed94feabb26a56ab00071c5eeb293140f8418 | 9,376 | /*
* Copyright 1999-2020 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.pojo.Cluster;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.naming.core.v2.ServiceManager;
import com.alibaba.nacos.naming.core.v2.index.ServiceStorage;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.metadata.NamingMetadataManager;
import com.alibaba.nacos.naming.core.v2.metadata.ServiceMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.pojo.ServiceView;
import com.alibaba.nacos.naming.utils.ServiceUtil;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.StringJoiner;
import java.util.stream.Collectors;
/**
* Catalog service for v1.x .
*
* @author xiweng.yy
*/
@Component()
public class CatalogServiceV2Impl implements CatalogService {
private final ServiceStorage serviceStorage;
private final NamingMetadataManager metadataManager;
public CatalogServiceV2Impl(ServiceStorage serviceStorage, NamingMetadataManager metadataManager) {
this.serviceStorage = serviceStorage;
this.metadataManager = metadataManager;
}
@Override
public Object getServiceDetail(String namespaceId, String groupName, String serviceName) throws NacosException {
Service service = Service.newService(namespaceId, groupName, serviceName);
if (!ServiceManager.getInstance().containSingleton(service)) {
throw new NacosException(NacosException.NOT_FOUND,
String.format("service %s@@%s is not found!", groupName, serviceName));
}
Optional<ServiceMetadata> metadata = metadataManager.getServiceMetadata(service);
ServiceMetadata detailedService = metadata.orElseGet(ServiceMetadata::new);
ObjectNode serviceObject = JacksonUtils.createEmptyJsonNode();
serviceObject.put("name", serviceName);
serviceObject.put("groupName", groupName);
serviceObject.put("protectThreshold", detailedService.getProtectThreshold());
serviceObject.replace("selector", JacksonUtils.transferToJsonNode(detailedService.getSelector()));
serviceObject.replace("metadata", JacksonUtils.transferToJsonNode(detailedService.getExtendData()));
ObjectNode detailView = JacksonUtils.createEmptyJsonNode();
detailView.replace("service", serviceObject);
List<com.alibaba.nacos.api.naming.pojo.Cluster> clusters = new ArrayList<>();
for (String each : serviceStorage.getClusters(service)) {
ClusterMetadata clusterMetadata =
detailedService.getClusters().containsKey(each) ? detailedService.getClusters().get(each)
: new ClusterMetadata();
com.alibaba.nacos.api.naming.pojo.Cluster clusterView = new Cluster();
clusterView.setName(each);
clusterView.setHealthChecker(clusterMetadata.getHealthChecker());
clusterView.setMetadata(clusterMetadata.getExtendData());
clusterView.setUseIPPort4Check(clusterMetadata.isUseInstancePortForCheck());
clusterView.setDefaultPort(80);
clusterView.setDefaultCheckPort(clusterMetadata.getHealthyCheckPort());
clusterView.setServiceName(service.getGroupedServiceName());
clusters.add(clusterView);
}
detailView.replace("clusters", JacksonUtils.transferToJsonNode(clusters));
return detailView;
}
@Override
public List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName,
String clusterName) throws NacosException {
Service service = Service.newService(namespaceId, groupName, serviceName);
if (!ServiceManager.getInstance().containSingleton(service)) {
throw new NacosException(NacosException.NOT_FOUND,
String.format("service %s@@%s is not found!", groupName, serviceName));
}
if (!serviceStorage.getClusters(service).contains(clusterName)) {
throw new NacosException(NacosException.NOT_FOUND, "cluster " + clusterName + " is not found!");
}
ServiceInfo serviceInfo = serviceStorage.getData(service);
ServiceInfo result = ServiceUtil.selectInstances(serviceInfo, clusterName);
return result.getHosts();
}
@Override
public Object pageListService(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize,
String instancePattern, boolean ignoreEmptyService) throws NacosException {
ObjectNode result = JacksonUtils.createEmptyJsonNode();
List<ServiceView> serviceViews = new LinkedList<>();
Collection<Service> services = patternServices(namespaceId, groupName, serviceName);
if (ignoreEmptyService) {
services = services.stream().filter(each -> 0 != serviceStorage.getData(each).ipCount())
.collect(Collectors.toList());
}
result.put("count", services.size());
services = doPage(services, pageNo - 1, pageSize);
for (Service each : services) {
ServiceMetadata serviceMetadata = metadataManager.getServiceMetadata(each).orElseGet(ServiceMetadata::new);
ServiceView serviceView = new ServiceView();
serviceView.setName(each.getName());
serviceView.setGroupName(each.getGroup());
serviceView.setClusterCount(serviceStorage.getClusters(each).size());
serviceView.setIpCount(serviceStorage.getData(each).ipCount());
serviceView.setHealthyInstanceCount(countHealthyInstance(serviceStorage.getData(each)));
serviceView.setTriggerFlag(isProtectThreshold(serviceView, serviceMetadata) ? "true" : "false");
serviceViews.add(serviceView);
}
result.set("serviceList", JacksonUtils.transferToJsonNode(serviceViews));
return result;
}
private int countHealthyInstance(ServiceInfo data) {
int result = 0;
for (Instance each : data.getHosts()) {
if (each.isHealthy()) {
result++;
}
}
return result;
}
private boolean isProtectThreshold(ServiceView serviceView, ServiceMetadata metadata) {
return (serviceView.getHealthyInstanceCount() * 1.0 / serviceView.getIpCount()) <= metadata
.getProtectThreshold();
}
@Override
public Object pageListServiceDetail(String namespaceId, String groupName, String serviceName, int pageNo,
int pageSize) throws NacosException {
return null;
}
private Collection<Service> patternServices(String namespaceId, String group, String serviceName) {
boolean noFilter = StringUtils.isBlank(serviceName) && StringUtils.isBlank(group);
if (noFilter) {
return ServiceManager.getInstance().getSingletons(namespaceId);
}
Collection<Service> result = new LinkedList<>();
StringJoiner regex = new StringJoiner(Constants.SERVICE_INFO_SPLITER);
regex.add(getRegexString(group));
regex.add(getRegexString(serviceName));
String regexString = regex.toString();
for (Service each : ServiceManager.getInstance().getSingletons(namespaceId)) {
if (each.getGroupedServiceName().matches(regexString)) {
result.add(each);
}
}
return result;
}
private String getRegexString(String target) {
return StringUtils.isBlank(target) ? Constants.ANY_PATTERN
: Constants.ANY_PATTERN + target + Constants.ANY_PATTERN;
}
private Collection<Service> doPage(Collection<Service> services, int pageNo, int pageSize) {
if (services.size() < pageSize) {
return services;
}
Collection<Service> result = new LinkedList<>();
int i = 0;
for (Service each : services) {
if (i++ < pageNo * pageSize) {
continue;
}
result.add(each);
if (result.size() >= pageSize) {
break;
}
}
return result;
}
}
| 44.647619 | 119 | 0.685687 |
b468ce571279c9ffc582206aeb1fadd4544b41de | 2,513 | package com.seantcanavan.backoff;
import com.seantcanavan.backoff.exception.AttemptsExceededException;
import com.seantcanavan.backoff.exception.UnexpectedExceptionException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class BackOffExecuteServiceTest {
@Test
public void execute_With100PercentChanceToFailAndNoAllowedExceptionDefined_ShouldThrowUnexpectedExceptionException() {
BackOffService backOffService = new BackOffService();
BackOffExecuteTestImplementation backOffFunctionTestImplementation = new BackOffExecuteTestImplementation();
backOffFunctionTestImplementation.setRequiredFails(10);
backOffFunctionTestImplementation.setFailChance(100);
assertThrows(UnexpectedExceptionException.class,
()->{
backOffService.execute(backOffFunctionTestImplementation);
});
}
@Test
public void execute_With100PercentChanceToFailAndAllowedExceptionDefined_ShouldThrowAttemptsExceededException() {
BackOffService backOffService = new BackOffService(UnsupportedOperationException.class.getSimpleName());
backOffService.setBackoffSequence(new int[]{1, 1, 1, 1, 1, 1});
BackOffExecuteTestImplementation backOffFunctionTestImplementation = new BackOffExecuteTestImplementation();
backOffFunctionTestImplementation.setRequiredFails(10);
backOffFunctionTestImplementation.setFailChance(100);
assertThrows(AttemptsExceededException.class,
()->{
backOffService.execute(backOffFunctionTestImplementation);
});
}
@Test
public void execute_WithHighChanceToFailAndAllowedExceptionDefined_ShouldEventuallySucceedAndReturnResult() {
BackOffService backOffService = new BackOffService(UnsupportedOperationException.class.getSimpleName());
backOffService.setBackoffSequence(new int[]{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1});
BackOffExecuteTestImplementation backOffFunctionTestImplementation = new BackOffExecuteTestImplementation();
backOffFunctionTestImplementation.setFailChance(75);
backOffFunctionTestImplementation.setOperand(1);
backOffFunctionTestImplementation.setValue(0);
Result result = backOffService.execute(backOffFunctionTestImplementation);
assertEquals(result.getIntResult(), 1);
}
}
| 47.415094 | 122 | 0.760844 |
80e574ca7532bab74faa998389c92e5e13c524ee | 3,699 | package com.young.db.dao;
import com.young.db.entity.YoungGoodsSpecification;
import com.young.db.entity.YoungGoodsSpecificationExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface YoungGoodsSpecificationMapper {
long countByExample(YoungGoodsSpecificationExample example);
int deleteByExample(YoungGoodsSpecificationExample example);
int deleteByPrimaryKey(Integer id);
int insert(YoungGoodsSpecification record);
int insertSelective(YoungGoodsSpecification record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
YoungGoodsSpecification selectOneByExample(YoungGoodsSpecificationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
YoungGoodsSpecification selectOneByExampleSelective(@Param("example") YoungGoodsSpecificationExample example, @Param("selective") YoungGoodsSpecification.Column ... selective);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
List<YoungGoodsSpecification> selectByExampleSelective(@Param("example") YoungGoodsSpecificationExample example, @Param("selective") YoungGoodsSpecification.Column ... selective);
List<YoungGoodsSpecification> selectByExample(YoungGoodsSpecificationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
YoungGoodsSpecification selectByPrimaryKeySelective(@Param("id") Integer id, @Param("selective") YoungGoodsSpecification.Column ... selective);
YoungGoodsSpecification selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
YoungGoodsSpecification selectByPrimaryKeyWithLogicalDelete(@Param("id") Integer id, @Param("andLogicalDeleted") boolean andLogicalDeleted);
int updateByExampleSelective(@Param("record") YoungGoodsSpecification record, @Param("example") YoungGoodsSpecificationExample example);
int updateByExample(@Param("record") YoungGoodsSpecification record, @Param("example") YoungGoodsSpecificationExample example);
int updateByPrimaryKeySelective(YoungGoodsSpecification record);
int updateByPrimaryKey(YoungGoodsSpecification record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
int logicalDeleteByExample(@Param("example") YoungGoodsSpecificationExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table young_goods_specification
*
* @mbg.generated
* @project https://github.com/itfsw/mybatis-generator-plugin
*/
int logicalDeleteByPrimaryKey(Integer id);
} | 39.774194 | 183 | 0.751554 |
66c6544163bb6208e0f18a4238fe6313e4b59876 | 2,112 | package com.example.demo.security;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
import org.springframework.stereotype.Component;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import static com.auth0.jwt.algorithms.Algorithm.HMAC512;
@Component
public class JWTAuthenticationVerificationFilter extends BasicAuthenticationFilter {
public JWTAuthenticationVerificationFilter(AuthenticationManager authenticationManager) {
super(authenticationManager);
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws IOException, ServletException {
String header = request.getHeader(SecurityConstants.HEADER_STRING);
if (header == null || !header.startsWith(SecurityConstants.TOKEN_PREFIX)){
chain.doFilter(request,response);
return;
}
UsernamePasswordAuthenticationToken authentication = getAuthentication(request);
SecurityContextHolder.getContext().setAuthentication(authentication);
chain.doFilter(request,response);
}
private UsernamePasswordAuthenticationToken getAuthentication(HttpServletRequest request){
String token = request.getHeader(SecurityConstants.HEADER_STRING);
if(token != null){
String user = JWT.require(HMAC512(SecurityConstants.SECRET.getBytes())).build()
.verify(token.replace(SecurityConstants.TOKEN_PREFIX,""))
.getSubject();
if(user != null){
return new UsernamePasswordAuthenticationToken(user,null,new ArrayList<>());
}
return null;
}
return null;
}
}
| 37.052632 | 110 | 0.789773 |
d390055cf606232714b7280d98617497bcbcd6ec | 324 | import io.github.kits.Strings;
import io.github.kits.log.Logger;
import junit.framework.TestCase;
/**
* @author whimthen
* @version 1.0.0
* @since 1.0.0
*/
public class StringsTest extends TestCase {
public void testIndentRight() {
String source = "haha";
Logger.info(Strings.indentRight(source, 3) + "=");
}
}
| 18 | 52 | 0.694444 |
b1dc65865064e45f5e4d306f6bb98c2a6e2aa336 | 4,452 | /*
* 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.phoenix.expression.aggregator;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.expression.function.SingleAggregateFunction;
import org.apache.phoenix.schema.KeyValueSchema;
import org.apache.phoenix.schema.KeyValueSchema.KeyValueSchemaBuilder;
import org.apache.phoenix.schema.ValueBitSet;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.util.SizedUtil;
/**
*
* Represents an ordered list of Aggregators
*
*
* @since 0.1
*/
abstract public class Aggregators {
protected final int estimatedByteSize;
protected final KeyValueSchema schema;
protected final ImmutableBytesWritable ptr = new ImmutableBytesWritable();
protected final ValueBitSet valueSet;
protected final Aggregator[] aggregators;
protected final SingleAggregateFunction[] functions;
public int getEstimatedByteSize() {
return estimatedByteSize;
}
public Aggregators(SingleAggregateFunction[] functions, Aggregator[] aggregators, int minNullableIndex) {
this.functions = functions;
this.aggregators = aggregators;
this.estimatedByteSize = calculateSize(aggregators);
this.schema = newValueSchema(aggregators, minNullableIndex);
this.valueSet = ValueBitSet.newInstance(schema);
}
public KeyValueSchema getValueSchema() {
return schema;
}
public int getMinNullableIndex() {
return schema.getMinNullable();
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(this.getClass().getName() + " [" + functions.length + "]:");
for (int i = 0; i < functions.length; i++) {
SingleAggregateFunction function = functions[i];
buf.append("\t" + i + ") " + function );
}
return buf.toString();
}
/**
* Return the aggregate functions
*/
public SingleAggregateFunction[] getFunctions() {
return functions;
}
/**
* Aggregate over aggregators
* @param result the single row Result from scan iteration
*/
abstract public void aggregate(Aggregator[] aggregators, Tuple result);
protected static int calculateSize(Aggregator[] aggregators) {
int size = SizedUtil.ARRAY_SIZE /*aggregators[]*/ + (SizedUtil.POINTER_SIZE * aggregators.length);
for (Aggregator aggregator : aggregators) {
size += aggregator.getSize();
}
return size;
}
/**
* Get the ValueSchema for the Aggregators
*/
private static KeyValueSchema newValueSchema(Aggregator[] aggregators, int minNullableIndex) {
KeyValueSchemaBuilder builder = new KeyValueSchemaBuilder(minNullableIndex);
for (int i = 0; i < aggregators.length; i++) {
Aggregator aggregator = aggregators[i];
builder.addField(aggregator);
}
return builder.build();
}
/**
* @return byte representation of the ValueSchema
*/
public byte[] toBytes(Aggregator[] aggregators) {
return schema.toBytes(aggregators, valueSet, ptr);
}
public int getAggregatorCount() {
return aggregators.length;
}
public Aggregator[] getAggregators() {
return aggregators;
}
abstract public Aggregator[] newAggregators();
public void reset(Aggregator[] aggregators) {
for (int i = 0; i < aggregators.length; i++) {
aggregators[i].reset();
}
}
protected Aggregator getAggregator(int position) {
return aggregators[position];
}
}
| 32.977778 | 109 | 0.676325 |
4f52c103bc146871181dfeda4df55dd3d976e5a7 | 1,905 | package org.drools.ruleflow.core;
/*
* Copyright 2005 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Represents a join node in a RuleFlow.
* A join is a special kind of node with multiple incoming connections and
* one outgoing connection. The type of join decides when the outgoing
* connections will be triggered (based on which incoming connections have
* been triggered).
*
* @author <a href="mailto:kris_verlaenen@hotmail.com">Kris Verlaenen</a>
*/
public interface Join
extends
Node {
int TYPE_UNDEFINED = 0;
/**
* The outgoing connection of a join of this type is triggered
* when all its incoming connections have been triggered.
*/
int TYPE_AND = 1;
/**
* The outgoing connection of a join of this type is triggered
* when one of its incoming connections has been triggered.
*/
int TYPE_XOR = 2;
/**
* Sets the type of the join.
*
* @param type The type of the join
* @throws IllegalArgumentException if type is null
*/
void setType(int type);
/**
* Returns the type of the join.
*
* @return the type of the join.
*/
int getType();
/**
* Convenience method for returning the outgoing connection of the join
*
* @return the outgoing connection of the join
*/
Connection getTo();
}
| 28.432836 | 75 | 0.667717 |
811a95495a5d273e380b19ee346872eb95c026b0 | 1,019 | package com.mixpanel.mixpanelapi;
import org.json.JSONObject;
/**
* Thrown when the library detects malformed or invalid Mixpanel messages.
*
* Mixpanel messages are represented as JSONObjects, but not all JSONObjects represent valid Mixpanel messages.
* MixpanelMessageExceptions are thrown when a JSONObject is passed to the Mixpanel library that can't be
* passed on to the Mixpanel service.
*
* This is a runtime exception, since in most cases it is thrown due to errors in your application architecture.
*/
public class MixpanelMessageException extends RuntimeException {
private static final long serialVersionUID = -6256936727567434262L;
private JSONObject mBadMessage = null;
/* package */ MixpanelMessageException(String message, JSONObject cause) {
super(message);
mBadMessage = cause;
}
/**
* @return the (possibly null) JSONObject message associated with the failure
*/
public JSONObject getBadMessage() {
return mBadMessage;
}
}
| 30.878788 | 112 | 0.73896 |
2005a302f9c8e641bd1677071e5e87fef0d6053f | 819 | package leetcode.lc089_gray_code;
import java.util.List;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
public final class LC089GrayCodeTests {
private int[] freeze(final List<Integer> list) {
int[] result = new int[list.size()];
for (int i = 0; i < result.length; i++) {
result[i] = list.get(i);
}
return result;
}
@Test
public void test4() throws Exception {
int[] expected = { 0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8 };
assertArrayEquals(expected, freeze(new LC089GrayCode().grayCode(4)));
}
@Test
public void test0() throws Exception {
int[] expected = { 0 };
assertArrayEquals(expected, freeze(new LC089GrayCode().grayCode(0)));
}
}
| 27.3 | 82 | 0.610501 |
bcb4174981845f07635385b043d67fc536167890 | 12,338 | /*
* Copyright © 2021 the original author or authors (photowey@gmail.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.photowey.redis.in.action.lock;
import com.photowey.redis.in.action.engine.redis.IRedisEngine;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.SetParams;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition;
import java.util.stream.Collectors;
/**
* {@code RedisLock}
*
* @author photowey
* @date 2021/10/29
* @since 1.0.0
*/
@Slf4j
@Component
public class RedisLock implements IRedisLock {
private static final long LOCK_TIME = 1000L;
private static final long RETRY_LOCK_INTERVAL = 10;
private static final String REDIS_DIST_LOCK_NS = "redis:dist:lock:ns:";
private static final Object LOCK = new Object();
private static final DelayQueue<LockData<LockItem>> DELAY_QUEUE = new DelayQueue<>();
private static final ThreadLocal<String> LOCKERS = new ThreadLocal<>();
private static final ThreadLocal<String> LOCK_NAMES = new ThreadLocal<>();
private final IRedisEngine redisEngine;
private final ExecutorService executorService;
private static final AtomicBoolean ONCE = new AtomicBoolean(false);
@Getter
@Setter
private Thread ownerThread;
@Getter
@Setter
private String lockName = "default:lock";
public RedisLock(IRedisEngine redisEngine) {
this.redisEngine = redisEngine;
this.executorService = Executors.newSingleThreadExecutor();
}
@PostConstruct
public void init() throws Exception {
String releaseScript = this.readLua("release.lua");
String pexpireScript = this.readLua("pexpire.lua");
LUA_SCRIPTS.put("release", releaseScript);
LUA_SCRIPTS.put("pexpire", pexpireScript);
}
@Override
public void lock() {
this.lock(this.getLockName());
}
@Override
public void lock(String lockName) {
synchronized (LOCK) {
while (!tryLock(lockName)) {
try {
LOCK.wait();
} catch (InterruptedException e) {
}
}
}
}
@Override
public boolean tryLock() {
return this.tryLock(this.getLockName());
}
@Override
public boolean tryLock(String lockName) {
Thread t = Thread.currentThread();
// 说明本线程正在持有锁
if (ownerThread == t) {
return true;
} else if (ownerThread != null) {
// 说明本进程中有别的线程正在持有分布式锁
return false;
}
try (Jedis jedis = this.redisEngine.jedisEngine().jedis()) {
String token = this.createLockToken();
synchronized (this) {
if ((ownerThread == null) && this.setNx(jedis, token, lockName)) {
// 抢锁成功
LOCKERS.set(token);
LOCK_NAMES.set(lockName);
this.setOwnerThread(t);
// 启动-心跳线程
if(!ONCE.getAndSet(true)) {
executorService.execute(new HeartBeat());
}
// 发送延迟消息
DELAY_QUEUE.add(new LockData<>(LOCK_TIME, new LockItem(lockName, token, true, Thread.currentThread())));
log.info("current thread:[{}],acquire lock:[{}] successfully...", Thread.currentThread().getName(), lockName);
return true;
}
}
}
return false;
}
@Override
public void unlock() {
synchronized (LOCK) {
if (ownerThread != Thread.currentThread()) {
throw new IllegalStateException("not support release other's lock!");
}
try (Jedis jedis = this.redisEngine.jedisEngine().jedis()) {
Long result = eval(jedis, releaseLockLua(), LOCK_NAMES.get(), LOCKERS.get());
if (result != 0L) {
log.info("current thread:[{}],release lock:[{}] successfully...", Thread.currentThread().getName(), LOCK_NAMES.get());
} else {
log.info("current thread:[{}],release lock:[{}] failure...", Thread.currentThread().getName(), LOCK_NAMES.get());
}
} catch (Exception e) {
DELAY_QUEUE.add(new LockData<>(RETRY_LOCK_INTERVAL, new LockItem(LOCK_NAMES.get(), LOCKERS.get(), false, Thread.currentThread())));
throw new RuntimeException("release the lock exception", e);
} finally {
LOCKERS.remove();
String lockerName = LOCK_NAMES.get();
LOCK_NAMES.remove();
this.setOwnerThread(null);
log.info("current thread:[{}],release local lock:[{}] successfully...", Thread.currentThread().getName(), lockerName);
}
LOCK.notifyAll();
}
}
@Override
public Condition newCondition() {
throw new UnsupportedOperationException("not support new condition!");
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
throw new UnsupportedOperationException("not support try-lock with timeout!");
}
@Override
public void lockInterruptibly() throws InterruptedException {
throw new UnsupportedOperationException("not support lock with interruptibly!");
}
@PreDestroy
public void destroy() {
executorService.shutdown();
}
public String createLockToken() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
public boolean setNx(Jedis jedis, String token, String lockName) {
SetParams params = new SetParams();
params.px(LOCK_TIME);
params.nx();
return "OK".equals(jedis.set(REDIS_DIST_LOCK_NS + lockName, token, params));
}
public Long eval(Jedis jedis, String script, String key, String value) {
return (Long) jedis.eval(script, Collections.singletonList(REDIS_DIST_LOCK_NS + key), Collections.singletonList(value));
}
public Long eval(Jedis jedis, String script, String key, String value, String time) {
return (Long) jedis.eval(script, Collections.singletonList(REDIS_DIST_LOCK_NS + key), Arrays.asList(value, time));
}
private class HeartBeat implements Runnable {
@Override
public void run() {
log.info("--- >>> watch dog thread running <<< ---");
while (!Thread.currentThread().isInterrupted()) {
try {
LockItem lockItem = DELAY_QUEUE.take().getData();
try (Jedis jedis = redisEngine.jedisEngine().jedis()) {
Thread lockThread = lockItem.getOwner();
boolean dead = !lockThread.isAlive() || !lockItem.isDelayed();
if (dead) {
// 线程死亡或者释放锁操作
this.handleDead(jedis, lockItem, lockThread);
} else {
// 续期操作
this.handleDelay(lockItem, jedis, lockThread);
}
} catch (Exception e) {
throw new RuntimeException("delay the current lock exception", e);
}
} catch (InterruptedException e) {
log.error("the current watch dog thread was interrupted", e);
break;
}
}
log.info("--- >>> the watch dog thread down <<< ---");
}
private void handleDelay(LockItem lockItem, Jedis jedis, Thread lockThread) {
Long result = -1L;
try {
// 判断本地锁所有权是否已释放,未释放需要续期
if (ownerThread == lockItem.getOwner()) {
result = eval(jedis, delayLockLua(), lockItem.getKey(), lockItem.getValue(), String.valueOf(LOCK_TIME));
} else {
result = 0L;
}
} catch (Exception e) {
log.error("handle delay lock:[{}] exception", lockItem.getKey(), e);
} finally {
if (result == -1L) {
DELAY_QUEUE.add(new LockData<>(RETRY_LOCK_INTERVAL, new LockItem(lockItem.getKey(), lockItem.getValue(), true, lockThread)));
log.info("handle delay lock:[{}] exception and retry now", lockItem.getKey());
} else if (result == 0L) {
log.info("handle delay lock:[{}] the lock released,bye~bye~", lockItem.getKey());
} else {
DELAY_QUEUE.add(new LockData<>(LOCK_TIME, new LockItem(lockItem.getKey(), lockItem.getValue(), true, lockThread)));
log.info("handle delay lock:[{}] the lock running,go next~", lockItem.getKey());
}
}
}
private void handleDead(Jedis jedis, LockItem lockItem, Thread lockThread) {
Long result = -1L;
try {
result = eval(jedis, releaseLockLua(), lockItem.getKey(), lockItem.getValue());
} catch (Exception e) {
log.error("handle dead-thread lock:[{}] exception", lockItem.getKey(), e);
} finally {
if (result == -1L) {
DELAY_QUEUE.add(new LockData<>(RETRY_LOCK_INTERVAL, new LockItem(lockItem.getKey(), lockItem.getValue(), false, lockThread)));
log.info("handle dead-thread lock:[{}] exception and retry now", lockItem.getKey());
} else if (result == 0L) {
log.info("handle dead-thread lock:[{}] release failure...not exists or not the master of this lock, maybe!", lockItem.getKey());
} else {
log.info("handle dead-thread lock:[{}] release successfully...bye~bye~", lockItem.getKey());
}
}
}
}
private final static String DEFAULT_RELEASE_LOCK_LUA =
"if redis.call('get', KEYS[1]) == ARGV[1]\n" +
"then\n" +
" return redis.call('del', KEYS[1])\n" +
"else\n" +
" return 0\n" +
"end";
private final static String DEFAULT_DELAY_LOCK_LUA =
"if redis.call('get', KEYS[1]) == ARGV[1]\n" +
"then\n" +
" return redis.call('pexpire', KEYS[1], ARGV[2])\n" +
"else\n" +
" return 0\n" +
"end";
private static final Map<String, String> LUA_SCRIPTS = new HashMap<>(3);
public String delayLockLua() {
return StringUtils.hasText(LUA_SCRIPTS.get("pexpire")) ? LUA_SCRIPTS.get("pexpire") : DEFAULT_DELAY_LOCK_LUA;
}
public String releaseLockLua() {
return StringUtils.hasText(LUA_SCRIPTS.get("release")) ? LUA_SCRIPTS.get("release") : DEFAULT_RELEASE_LOCK_LUA;
}
public String readLua(final String luaScript) throws Exception {
return Files.readAllLines(Paths.get(ClassLoader.getSystemResource(luaScript).toURI()))
.stream().filter(each -> !each.startsWith("---")).map(each -> each + System.lineSeparator()).collect(Collectors.joining());
}
}
| 39.168254 | 148 | 0.579592 |
6f30c6553db6e9078412a35be9315bef6d597cad | 4,063 | package com.telran.cheaptrip.pages;
import com.google.common.io.Files;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class MainPageHelper extends PageBase {
public MainPageHelper(WebDriver driver) {
super(driver);
}
@FindBy(css = ".hide-xs.md.title-default.hydrated")
WebElement slogan;
@FindBy(css = "ion-buttons.select.buttons-last-slot.sc-ion-buttons-md-h.sc-ion-buttons-md-s.md.hydrated")
WebElement selectLang;
@FindBy(css = "ion-item.select-interface-option")
List<WebElement> langList;
@FindBy(id = "ion-rb-38-lbl")
WebElement russianLang;
@FindBy(tagName = "ion-card-title")
WebElement title;
@FindBy(name = "ion-input-0")
WebElement fromWhere;
@FindBy(name = "ion-input-1")
WebElement toWhere;
@FindBy(css = "ion-button.ion-color-primary")
WebElement letsGoButton;
@FindBy(css = ".md.button.in-toolbar.in-toolbar-color.ion-activatable.ion-focusable.hydrated")
WebElement hamburger;
@FindBy(xpath = "//*[contains(text(),'Contacts')]")
WebElement contacts;
@FindBy(xpath = "//ion-item//ion-label[@id='ion-input-0-lbl']//..//..//ion-item//ion-list")
WebElement submitCityFrom;
@FindBy(xpath = "//ion-item//ion-label[@id='ion-input-1-lbl']//..//..//ion-item//ion-list")
WebElement submitCityTo;
@FindBy(css = ".city")
List<WebElement> resultsList;
@FindBy(css = ".select.buttons-first-slot.sc-ion-buttons-md-h.sc-ion-buttons-md-s.md.hydrated")
WebElement currencyButton;
@FindBy(css = ".popover-content.sc-ion-popover-md")
List<WebElement> currencyList;
@FindBy(css = ".sc-ion-select-popover.md.in-item.interactive.radio-checked.hydrated")
WebElement currencyUsd;
public boolean isSloganContainsText(String text) {
return slogan.getText().contains(text);
}
public void selectRussianLanguage() {
selectLang.click();
waitUntilElementVisible(russianLang, 3);
langList.get(1).click();
}
public boolean isLanguageOnPageRussian(String text) {
return title.getText().contains(text);
}
public void findRoute(String fromCity, String toCity) {
inputTextToField(fromWhere, fromCity);
submitCityFrom.click();
inputTextToField(toWhere, toCity);
submitCityTo.click();
letsGoButton.click();
}
public void findContacts() {
hamburger.click();
waitUntilElementVisible(contacts, 3);
contacts.click();
}
public boolean isContactsIsVisible(String text) {
return contacts.getText().contains(text);
}
public boolean isNeededCurrencyIsPresent(String text){
return currencyButton.getText().contains(text);
}
public void inputCityFromField(String cityFrom) {
inputTextToField(fromWhere, cityFrom);
waitUntilElementVisible(submitCityFrom, 5);
submitCityFrom.click();
}
public void inputCityToField(String cityTo) {
inputTextToField(toWhere, cityTo);
waitUntilElementVisible(submitCityTo, 5);
submitCityTo.click();
}
public void clickOnLetsGoButton() {
letsGoButton.click();
}
public boolean searchResultIsDisplayed() {
return resultsList.size() > 0;
}
public void changeCurrency() {
currencyButton.click();
waitUntilElementVisible(currencyUsd,5);
currencyList.get(1).click();
}
public String takeScreenshot() {
File tmp = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File screenshot = new File("screenshot" + System.currentTimeMillis() + ".png");
try {
Files.copy(tmp, screenshot);
} catch (IOException e) {
e.printStackTrace();
}
return screenshot.getAbsolutePath();
}
}
| 28.815603 | 109 | 0.666256 |
d25e9cd4dde6ff03a8ce6b70a5977f3438c14963 | 2,471 | package com.adminportal.controller;
import java.security.Principal;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.adminportal.domain.Comment;
import com.adminportal.domain.Contact;
import com.adminportal.domain.User;
import com.adminportal.repository.CommentRepository;
import com.adminportal.service.AdminService;
import com.adminportal.service.CommentService;
@Controller
@RequestMapping("/comment")
public class CommentController {
@Autowired
private AdminService adminService;
@Autowired
private CommentRepository commentRepository;
@Autowired
private CommentService commentService;
@RequestMapping("/commentList")
public String commentList(Model model,Principal principal) {
List<Comment> commentList = commentService.findAll();
model.addAttribute("commentList",commentList);
User adminUser = adminService.findAdminByUsername(principal.getName());
if(adminUser !=null) {
model.addAttribute("adminUser",adminUser);
}
return "commentList";
}
@RequestMapping("/updateComment")
public String updateUser(@RequestParam("id") Long id, Model model,Principal principal) {
Comment comment = commentService.findOne(id);
User adminUser = adminService.findAdminByUsername(principal.getName());
if(adminUser !=null) {
model.addAttribute("adminUser",adminUser);
}
model.addAttribute("comment", comment);
return "updateComment";
}
@RequestMapping(value = "/updateComment", method = RequestMethod.POST)
public String updateCommentPost(@ModelAttribute("comment") Comment comment, HttpServletRequest request) {
commentService.save(comment);
return "redirect:/comment/commentList";
}
@RequestMapping(value = "/remove", method = RequestMethod.POST)
public String removeContact(
@ModelAttribute("id") String id, Model model
) {
commentRepository.deleteCommentById(Long.parseLong(id.substring(10)));
List<Comment> commentList = commentService.findAll();
model.addAttribute("commentList",commentList);
return "redirect:/comment/commentList";
}
}
| 28.732558 | 106 | 0.785107 |
1495d2063cec203a8aa915dfb2811b82600f1492 | 180 | package timus;
public class SimpleExpression_2066 {
public static int findMinOutcome(int a, int b, int c){
return a - ((b * c) > (b + c) ? (b * c) : (b + c));
}
}
| 22.5 | 59 | 0.555556 |
637cefae470ae0a9a96430973831a1afb896906d | 5,083 | /**
* @Company JBINFO
* @Title: ReceiveSuiteTicketTest.java
* @Package org.bana.wechat.cp.callback.result.ticket
* @author Liu Wenjie
* @date 2018年1月26日 上午10:36:39
* @version V1.0
*/
package org.bana.springboot.wechat.cp.callback.listner;
import java.io.IOException;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import org.bana.springboot.wechat.cp.WechatCpAutoConfiguration;
import org.bana.springboot.wechat.cp.WechatCpProperties;
import org.bana.springboot.wechat.cp.WechatCpTestConfig;
import org.bana.wechat.common.util.BeanXmlUtil;
import org.bana.wechat.cp.app.WechatAppManager;
import org.bana.wechat.cp.app.WechatCorpSuiteConfig;
import org.bana.wechat.cp.callback.BaseWechatCpCallbackHandler;
import org.bana.wechat.cp.callback.WechatCpCallbackHandler;
import org.bana.wechat.cp.callback.result.ticket.SuiteTicket;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
/**
* @ClassName: ReceiveSuiteTicketTest
* @Description: 测试suiteTicket回调的处理方法
* @author Liu Wenjie
*/
@RunWith(SpringRunner.class)
@ContextConfiguration(classes={WechatCpTestConfig.class,WechatCpAutoConfiguration.class})
public class ReceiveSuiteTicketTest {
private String callBackStr = "<xml>"+
"<SuiteId><![CDATA[ww4asffe99e54c0f4c]]></SuiteId>"+
" <InfoType> <![CDATA[suite_ticket]]></InfoType>"+
" <TimeStamp>1403610513</TimeStamp>"+
"<SuiteTicket><![CDATA[asdfasfdasdfasdf]]></SuiteTicket>"+
"</xml>";
@Autowired
private WechatCpCallbackHandler callBackHandler;
@Autowired
private WechatAppManager wechatAppManager;
@Autowired WechatCpProperties wechatCpProperties;
private WXBizMsgCrypt wxCrypt;
private String suiteId;
@Before
public void init(){
suiteId = wechatCpProperties.getSuiteId();
WechatCorpSuiteConfig suiteConfig = wechatAppManager.getSuiteConfig(suiteId);
wxCrypt = new WXBizMsgCrypt(suiteConfig.getToken(), suiteConfig.getEncodingAesKey(), suiteId);
}
@Test
public void test() {
System.out.println(BeanXmlUtil.xmlToBean(callBackStr, SuiteTicket.class));
}
private HttpServletRequest initRequest() throws IOException{
MockHttpServletRequest request = new MockHttpServletRequest(); //创建Mock对象
String postData = "<xml>"+
"<Encrypt><![CDATA[3TEt0eaGYmA9WYHRFsmWwrZPWyxXZMPQKkhNjvwd0Kh9Dh19bSsUBo7hj+a1RjQuK25akVqLkg3WVajHFlnQYEkNTlkN0050mpdrazglchvzMncU8QmsoAnpp6Uj5iw9HZhwDzDBBiWdebSb56QNUtSS6bFPyiSnk/j5mmVjZYurAY9VMxQ45cQxOod7jRZM0UW73PZslK+ve28AbasGErNnMC0V3rBsDWkIo/tGzbF+7q49wuEXY0VoD2n51Lu0zvX36Q2E+5fRysqmXOtI1z0jKd/IDeZm8kaL/KZHudQuhRXQ8BLx6/6WqAt4BRSNjSIiUkI6l/GZ8BZzTX5ROg==]]></Encrypt>"+
"<ToUserName><![CDATA[ww4asffe99e54c0f4c]]></ToUserName>"+
"<AgentID><![CDATA[toAgentID]]></AgentID>"+
"</xml>";
request.setContent(postData.getBytes("UTF-8")); //设置流的内容
request.setCharacterEncoding("UTF-8");
request.setParameter(BaseWechatCpCallbackHandler.PARAM_NONCE,"741159830"); //传入参数
request.setParameter(BaseWechatCpCallbackHandler.PARAM_SIGNATURE,"3d058933c288a128ce644094a795b7337f2d1985");
request.setParameter(BaseWechatCpCallbackHandler.PARAM_TIMESTAMP,"1403610513");
return request;
}
@Test
public void testEncrypt(){
// String nonce = getRandomStr(9);
// String encryptMsg = wxCrypt.EncryptMsg(callBackStr, "1403610513", nonce);
// System.out.println(encryptMsg);
// System.out.println(wxCrypt.DecryptMsg(msgSignature, timeStamp, nonce, postData));
}
@Test
public void testDecrypt(){
String postData = "<xml>"+
"<Encrypt><![CDATA[3TEt0eaGYmA9WYHRFsmWwrZPWyxXZMPQKkhNjvwd0Kh9Dh19bSsUBo7hj+a1RjQuK25akVqLkg3WVajHFlnQYEkNTlkN0050mpdrazglchvzMncU8QmsoAnpp6Uj5iw9HZhwDzDBBiWdebSb56QNUtSS6bFPyiSnk/j5mmVjZYurAY9VMxQ45cQxOod7jRZM0UW73PZslK+ve28AbasGErNnMC0V3rBsDWkIo/tGzbF+7q49wuEXY0VoD2n51Lu0zvX36Q2E+5fRysqmXOtI1z0jKd/IDeZm8kaL/KZHudQuhRXQ8BLx6/6WqAt4BRSNjSIiUkI6l/GZ8BZzTX5ROg==]]></Encrypt>"+
"<ToUserName><![CDATA[ww4asffe99e54c0f4c]]></ToUserName>"+
"<AgentID><![CDATA[toAgentID]]></AgentID>"+
"</xml>";
// String decryptMsg = wxCrypt.DecryptMsg("3d058933c288a128ce644094a795b7337f2d1985", "1403610513", "741159830", postData);
// System.out.println(decryptMsg);
}
@Test
public void testHandleSuiteTieckt() throws IOException{
callBackHandler.handleSuiteMessage(suiteId, initRequest());
}
public static String getRandomStr(int num){
if(num <= 0){
num = 16;
}
String base = "0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < num; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
}
| 39.403101 | 383 | 0.760181 |
ec6ae1b0b0ef503fea1f8b9b98665fd3d24ef67c | 390 | package com.example.omdbdemo.movies.dataproviders.db.repository;
import com.example.omdbdemo.movies.dataproviders.db.entity.MovieEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface MovieEntityRepository extends JpaRepository<MovieEntity, String> {
boolean existsByTitle(String title);
}
| 35.454545 | 83 | 0.846154 |
f3de3b427f0e1fcb639e08184f9b6f06b9e1391e | 1,487 |
import java.util.*;
public class Main {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
int tt = input.nextInt();
while (tt-- > 0) {
int n = input.nextInt(), k = input.nextInt();
// int[] rem = new int[k];
HashMap<Integer, Integer> rem = new HashMap<>();
long count = 0;int temp;long remainder = Integer.MAX_VALUE;
// for (int i = 0; i < k; i++)
// rem[i] = 0;
for (int i = 0; i < n; i++) {
temp = input.nextInt();
if (rem.containsKey(temp % k)) {
rem.put((temp) % k, rem.get(temp % k) + 1);
} else {
rem.put(temp % k, 1);
}
// rem[temp % k]++;
if (temp % k != 0) {
if (count < rem.get(temp % k)) {
count = rem.get(temp % k);
remainder = temp % k;
} else if (count == rem.get(temp % k)) {
remainder = Math.min(remainder, temp % k);
}
}
}
// System.out.println(Arrays.toString(rem)+" "+count+" "+remainder);
if (count == 0) {
System.out.println(0);
} else {
System.out.println((count - 1) * k + (k - remainder) + 1);
}
}
input.close();
}
} | 33.795455 | 80 | 0.39072 |
ea4e356f54bfda28f83291ef552231fdffe40f79 | 1,228 | package br.com.zup.desafios.proposta.config.security;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests(authorizeRequests ->
authorizeRequests
// .antMatchers(API + "/**").hasAuthority("SCOPE_primeiro-escopo")
.antMatchers("/h2/**").permitAll()
.anyRequest().permitAll())
.oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
.headers().frameOptions().sameOrigin()
.and().csrf().disable();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/**");
}
}
| 40.933333 | 124 | 0.733713 |
8472676f20e235eaa87f475d5965609abd48e7f8 | 3,425 | /**
* CollectionAdapterDiffUtilCallback.java
* Implements a DiffUtil Callback
* A CollectionAdapterDiffUtilCallback is a DiffUtil.Callback that compares two lists of stations
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-20 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistorone.collection;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DiffUtil;
import org.y20k.transistorone.core.Station;
import org.y20k.transistorone.helpers.TransistorKeys;
import java.util.ArrayList;
/**
* CollectionAdapterDiffUtilCallback class
*/
public class CollectionAdapterDiffUtilCallback extends DiffUtil.Callback implements TransistorKeys {
/* Define log tag */
private static final String LOG_TAG = CollectionAdapterDiffUtilCallback.class.getSimpleName();
/* Main class variables */
private final ArrayList<Station> mOldStations;
private final ArrayList<Station> mNewStations;
/* Constructor */
public CollectionAdapterDiffUtilCallback(ArrayList<Station> oldStations, ArrayList<Station> newStations) {
mOldStations = oldStations;
mNewStations = newStations;
}
@Override
public int getOldListSize() {
return mOldStations.size();
}
@Override
public int getNewListSize() {
return mNewStations.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
// Called by the DiffUtil to decide whether two objects represent the same Item.
Station oldStation = mOldStations.get(oldItemPosition);
Station newStation = mNewStations.get(newItemPosition);
return oldStation.getStreamUri().equals(newStation.getStreamUri());
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
// Called by the DiffUtil when it wants to check whether two items have the same data. DiffUtil uses this information to detect if the contents of an item has changed.
Station oldStation = mOldStations.get(oldItemPosition);
Station newStation = mNewStations.get(newItemPosition);
if (oldStation.getStationName().equals(newStation.getStationName()) &&
oldStation.getPlaybackState() == newStation.getPlaybackState() &&
oldStation.getStationImageSize() == newStation.getStationImageSize()) {
return true;
} else {
return false;
}
}
@Nullable
@Override
public Object getChangePayload(int oldItemPosition, int newItemPosition) {
Station oldStation = mOldStations.get(oldItemPosition);
Station newStation = mNewStations.get(newItemPosition);
if (!(oldStation.getStationName().equals(newStation.getStationName()))) {
return HOLDER_UPDATE_NAME;
} else if (oldStation.getPlaybackState() != newStation.getPlaybackState()) {
return HOLDER_UPDATE_PLAYBACK_STATE;
} else if (oldStation.getStationImageSize() != newStation.getStationImageSize()) {
return HOLDER_UPDATE_IMAGE;
} else if (oldStation.getSelectionState() != newStation.getSelectionState()) {
return HOLDER_UPDATE_SELECTION_STATE;
} else {
return super.getChangePayload(oldItemPosition, newItemPosition);
}
}
} | 34.59596 | 175 | 0.709781 |
73990d93984d4c19d740f11a79d7cb166773543e | 645 | package com.company.registers;
public class StampedValue <T>{
public long stamp;
public T value;
// initial value with zero timestamp
public StampedValue(T init) {
this.stamp = 0;
this.value = init;
}
// later values with timestamp provided
public StampedValue(long stamp, T value) {
this.stamp = stamp;
this.value = value;
}
public static StampedValue max(StampedValue x, StampedValue y) {
if (x.stamp > y.stamp) {
return x;
} else {
return y;
}
}
public static StampedValue MIN_VALUE = new StampedValue(null);
}
| 24.807692 | 68 | 0.592248 |
a877c6376d6b5ccc580026cef89c76bda625171f | 2,030 | package com.kylinolap.cube.dataGen;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.kylinolap.common.util.JsonUtil;
/**
* Created by honma on 5/29/14.
*/
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.NONE, getterVisibility = JsonAutoDetect.Visibility.NONE, isGetterVisibility = JsonAutoDetect.Visibility.NONE, setterVisibility = JsonAutoDetect.Visibility.NONE)
public class GenConfig {
@JsonProperty("columnConfigs")
private ArrayList<ColumnConfig> columnConfigs;
private HashMap<String, ColumnConfig> cache = new HashMap<String, ColumnConfig>();
public ArrayList<ColumnConfig> getColumnConfigs() {
return columnConfigs;
}
public void setColumnConfigs(ArrayList<ColumnConfig> columnConfigs) {
this.columnConfigs = columnConfigs;
}
public ColumnConfig getColumnConfigByName(String columnName) {
columnName = columnName.toLowerCase();
if (cache.containsKey(columnName))
return cache.get(columnName);
for (ColumnConfig cConfig : columnConfigs) {
if (cConfig.getColumnName().toLowerCase().equals(columnName)) {
cache.put(columnName, cConfig);
return cConfig;
}
}
cache.put(columnName, null);
return null;
}
public static GenConfig loadConfig(InputStream stream) {
try {
GenConfig config = JsonUtil.readValue(stream, GenConfig.class);
return config;
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (JsonParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 31.71875 | 220 | 0.689163 |
6d2f74acc9aafe00593fc1019c0eea4ce195e734 | 1,837 | package ru.stqa.ptf.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.stqa.ptf.addressbook.model.ContactData;
import ru.stqa.ptf.addressbook.model.Contacts;
import ru.stqa.ptf.addressbook.model.GroupData;
import ru.stqa.ptf.addressbook.model.Groups;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.junit.MatcherAssert.assertThat;
public class AddContactToGroupTest extends TestBase {
@BeforeMethod
public void ensurePrecondition() {
app.goTo().contactPage();
if (app.db().contacts().size() == 0) {
app.contact().createNewContact(new ContactData().withName("Andrew").withLastName("Dzhodzhua").withEmail("Head@mail.ru"), true);
}
}
@BeforeMethod
public void ensurePreconditions() {
app.goTo().groupPage();
if (app.db().groups().size() == 0) {
app.group().create(new GroupData().withName("Test1").withHeader("Test").withFooter("Test"));
}
app.goTo().contactPage();
}
@Test
public void testAddContactToGroup() {
Groups groups = app.db().groups();
Contacts contactWithGroup = app.db().contacts();
ContactData contact = contactWithGroup.iterator().next();
GroupData group = groups.iterator().next();
if(contact.getGroups().size() == 0)
{
app.contact().addContactToGroup(contact, group);
}
else if (group.getId() != contact.getGroups().iterator().next().getId()) {
app.contact().addContactToGroup(contact, group);
} else {
System.out.println("Контакт уже находится в выбранной группе");
}
assertThat(app.contact().getContactCount(), equalTo(contactWithGroup.size()));
verifyContactListInUi();
}
}
| 32.22807 | 139 | 0.650517 |
5f2047012899e69594521b457d2a5745701ab782 | 454 | package pl.mkrystek.mkbot.task.impl;
import pl.mkrystek.mkbot.message.SkypeMessage;
import pl.mkrystek.mkbot.task.ReplyTask;
public class HelloTask extends ReplyTask {
private static final String TASK_NAME = "hello";
public HelloTask() {
super(TASK_NAME);
}
@Override
public String performAction(SkypeMessage skypeMessage) {
return String.format("Hello to you too, dear %s!", skypeMessage.getUsername());
}
}
| 23.894737 | 87 | 0.711454 |
53e73a5b5bd9b38c8d0580e4a96d9bb65b4e7803 | 341 | package com.birdwind.autoTransaction.base.view.abstracts;
import com.birdwind.autoTransaction.base.view.BaseListItem;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public abstract class AbstractListItem implements BaseListItem {
private Serializable text;
private Serializable value;
}
| 21.3125 | 64 | 0.815249 |
4eba23aff4424977bd9841969edb01c6e1aa109b | 3,713 | package org.apache.ofbiz.webapp.visit;
import lombok.experimental.FieldNameConstants;
import java.io.Serializable;
import lombok.Getter;
import lombok.Setter;
import java.sql.Timestamp;
import org.apache.ofbiz.entity.GenericValue;
import java.util.List;
import java.util.ArrayList;
/**
* Server Hit
*/
@FieldNameConstants
public class ServerHit implements Serializable {
public static final long serialVersionUID = 1883136938459198464L;
public static final String NAME = "ServerHit";
/**
* Visit Id
*/
@Getter
@Setter
private String visitId;
/**
* Content Id
*/
@Getter
@Setter
private String contentId;
/**
* Hit Start Date Time
*/
@Getter
@Setter
private Timestamp hitStartDateTime;
/**
* Hit Type Id
*/
@Getter
@Setter
private String hitTypeId;
/**
* Num Of Bytes
*/
@Getter
@Setter
private Long numOfBytes;
/**
* Running Time Millis
*/
@Getter
@Setter
private Long runningTimeMillis;
/**
* User Login Id
*/
@Getter
@Setter
private String userLoginId;
/**
* Status Id
*/
@Getter
@Setter
private String statusId;
/**
* Request Url
*/
@Getter
@Setter
private String requestUrl;
/**
* Referrer Url
*/
@Getter
@Setter
private String referrerUrl;
/**
* Server Ip Address
*/
@Getter
@Setter
private String serverIpAddress;
/**
* Server Host Name
*/
@Getter
@Setter
private String serverHostName;
/**
* Last Updated Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedStamp;
/**
* Last Updated Tx Stamp
*/
@Getter
@Setter
private Timestamp lastUpdatedTxStamp;
/**
* Created Stamp
*/
@Getter
@Setter
private Timestamp createdStamp;
/**
* Created Tx Stamp
*/
@Getter
@Setter
private Timestamp createdTxStamp;
/**
* Internal Content Id
*/
@Getter
@Setter
private String internalContentId;
/**
* Party Id
*/
@Getter
@Setter
private String partyId;
/**
* Id By Ip Contact Mech Id
*/
@Getter
@Setter
private String idByIpContactMechId;
/**
* Ref By Web Contact Mech Id
*/
@Getter
@Setter
private String refByWebContactMechId;
public ServerHit(GenericValue value) {
visitId = (String) value.get(FIELD_VISIT_ID);
contentId = (String) value.get(FIELD_CONTENT_ID);
hitStartDateTime = (Timestamp) value.get(FIELD_HIT_START_DATE_TIME);
hitTypeId = (String) value.get(FIELD_HIT_TYPE_ID);
numOfBytes = (Long) value.get(FIELD_NUM_OF_BYTES);
runningTimeMillis = (Long) value.get(FIELD_RUNNING_TIME_MILLIS);
userLoginId = (String) value.get(FIELD_USER_LOGIN_ID);
statusId = (String) value.get(FIELD_STATUS_ID);
requestUrl = (String) value.get(FIELD_REQUEST_URL);
referrerUrl = (String) value.get(FIELD_REFERRER_URL);
serverIpAddress = (String) value.get(FIELD_SERVER_IP_ADDRESS);
serverHostName = (String) value.get(FIELD_SERVER_HOST_NAME);
lastUpdatedStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_STAMP);
lastUpdatedTxStamp = (Timestamp) value.get(FIELD_LAST_UPDATED_TX_STAMP);
createdStamp = (Timestamp) value.get(FIELD_CREATED_STAMP);
createdTxStamp = (Timestamp) value.get(FIELD_CREATED_TX_STAMP);
internalContentId = (String) value.get(FIELD_INTERNAL_CONTENT_ID);
partyId = (String) value.get(FIELD_PARTY_ID);
idByIpContactMechId = (String) value
.get(FIELD_ID_BY_IP_CONTACT_MECH_ID);
refByWebContactMechId = (String) value
.get(FIELD_REF_BY_WEB_CONTACT_MECH_ID);
}
public static ServerHit fromValue(org.apache.ofbiz.entity.GenericValue value) {
return new ServerHit(value);
}
public static List<ServerHit> fromValues(List<GenericValue> values) {
List<ServerHit> entities = new ArrayList<>();
for (GenericValue value : values) {
entities.add(new ServerHit(value));
}
return entities;
}
} | 20.977401 | 80 | 0.722866 |
7e663f39dd0d8145c2bdb01831052528e63f32b8 | 1,021 | package me.bytebeats.algo.designs;
public class VersionControlImpl extends VersionControl {
@Override
boolean isBadVersion(int version) {
return false;
}
// public int firstBadVersion(int n) {
// int low = 1;
// int high = n;
// int mid = 0;
// while (low <= high) {
// mid = low + (high - low) / 2;
// if (!isBadVersion(mid)) {
// low = mid + 1;
// } else {
// if (!isBadVersion(mid - 1)) {
// return mid;
// } else {
// high = mid - 1;
// }
// }
// }
// return 1;
// }
public int firstBadVersion(int n) {
int left = 1;
int right = n;
while (left < right) {
int mid = left + (right - left) / 2;
if (isBadVersion(mid)) {
right = mid;
} else {
left = mid + 1;
}
}
return left;
}
}
| 24.309524 | 56 | 0.394711 |
18912b416396c6de2ab7275df67478b209bd4d05 | 763 | import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class CCISMockMain extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("./CCISView.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Luke Robillard - CSCI 13 Final Project - JUnitTests");
stage.show();
}
public static void JUnitRun()
{
launch();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
| 23.121212 | 81 | 0.623853 |
326bf4e7132dccec21d7d360cf3e481510f5537d | 2,753 | package application.crypto;
import application.card.JavaCardHelper;
import application.log.LogHelper;
import application.log.LogLevel;
import common.ErrorResult;
import common.Result;
import common.SuccessResult;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Created by Patrick on 24.06.2015.
*/
public class CryptographyHelper
{
public static Result<ImportedKeys> readKeysFromFile(Path filePath)
{
if (!Files.exists(filePath))
{
LogHelper.log(LogLevel.FAILURE, "Reading %s failed. File doesn't exists.", filePath);
return new ErrorResult<>("Reading %s failed. File %s doesn't exists.", filePath);
}
try
{
BufferedReader br = new BufferedReader(new FileReader(filePath.toString()));
BigInteger privateMod = CryptographyHelper.readLineAsBigInteger(br);
BigInteger privateExp = CryptographyHelper.readLineAsBigInteger(br);
BigInteger publicMod = CryptographyHelper.readLineAsBigInteger(br);
BigInteger publicExp = CryptographyHelper.readLineAsBigInteger(br);
return new SuccessResult<>(new ImportedKeys(privateMod, privateExp, publicMod, publicExp));
}
catch (IOException e)
{
LogHelper.log(LogLevel.FAILURE, "Reading line from %s failed", filePath);
return new ErrorResult<>("Reading %s failed. Please check that %s matches the requirements.", filePath);
}
}
/**
* Executes readline with the given buffered reader
* Converts the read string to an BigInteger
* @param br reader of the keyfile
* @return Line as BigInteger
* @throws IOException thrown if something went wrong with readline()
* @throws NumberFormatException thrown if read line can't be converted to a BigInteger
*/
public static BigInteger readLineAsBigInteger(BufferedReader br) throws IOException, NumberFormatException
{
String str = br.readLine();
if (str == null)
{
throw new IOException();
}
return new BigInteger(str);
}
public static byte[] stripLeadingZero(byte[] value)
{
byte[] result = value;
if (value[0] == 0)
{
result = new byte[value.length - 1];
System.arraycopy(value, 1, result, 0, result.length);
}
return result;
}
public static byte[] addLeadingZero(byte[] value)
{
byte[] result = new byte[value.length + 1];
result[0] = 0;
System.arraycopy(value, 0, result, 1, value.length);
return result;
}
}
| 31.643678 | 116 | 0.651653 |
3056fc24afada25a7a25dd1f64c7c9698da1ee61 | 225 | package com.javadude.observer;
import java.util.Calendar;
@Observer // not needed, but can be nice for marking your intent
public interface SunListener {
void sunRose(Calendar calendar);
void sunSet(Calendar calendar);
}
| 22.5 | 64 | 0.782222 |
403f62f492f4792fd81f1cf64e3b15fdd02e4ffc | 417 | package com.mochen.web.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.mochen.web.entity.xdo.ComplexWebStudentDO;
import org.apache.ibatis.annotations.Mapper;
import java.util.Set;
/**
* <p>
* 学生 Mapper 接口
* </p>
*
* @author 姚广举
* @since 2022-03-10
*/
@Mapper
public interface ComplexWebStudentMapper extends BaseMapper<ComplexWebStudentDO> {
Set<Integer> getSchoolList();
}
| 18.954545 | 82 | 0.745803 |
ba9eb4e987c0b3c082e92dacb323f797cb74a931 | 1,560 | /*
* ModeShape (http://www.modeshape.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.modeshape.sequencer.msoffice.powerpoint;
import java.util.Collections;
import java.util.List;
import org.apache.poi.hpsf.SummaryInformation;
import org.modeshape.sequencer.msoffice.MSOfficeMetadata;
/**
* Metadata for Microsoft Powerpoint decks.
*/
public class PowerpointMetadata {
private List<SlideMetadata> slides = Collections.emptyList();
private MSOfficeMetadata metadata;
public MSOfficeMetadata getMetadata() {
return metadata;
}
public void setMetadata( MSOfficeMetadata metadata ) {
this.metadata = metadata;
}
public void setMetadata( SummaryInformation info ) {
if (info != null) {
metadata = new MSOfficeMetadata();
metadata.setSummaryInformation(info);
}
}
public List<SlideMetadata> getSlides() {
return slides;
}
public void setSlides( List<SlideMetadata> slides ) {
this.slides = slides;
}
}
| 28.363636 | 75 | 0.702564 |
4a4e195faa403f26ce9e9fe354badb629b9d4da0 | 5,502 | /*
* Copyright 2015 Allette Systems (Australia)
* http://www.allette.com.au
*
* 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.pageseeder.flint.lucene.search;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.CompressionTools;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.util.BytesRef;
import org.pageseeder.flint.lucene.util.Beta;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.DataFormatException;
/**
* A set of utility methods for dealing with search fields.
*
* @author Christophe Lauret
* @version 12 August 2010
*/
public final class Fields {
/** Utility class */
private Fields() {
}
/**
* Returns a mapping of fields with a default boost value of 1.0.
*
* @param fields the list of fields to create the map.
* @return the corresponding map with each field value mapped to a boost value of 1.0
*/
@Beta
public static Map<String, Float> asBoostMap(List<String> fields) {
Map<String, Float> map = new LinkedHashMap<>();
for (String f : fields) {
map.put(f, 1.0f);
}
return map;
}
/**
* Indicates whether the given field name is valid.
*
* <p>This method does not check for the existence of the field.
*
* @param field the name of the field to check.
* @return <code>true</code> if the field name is a valid name for the index;
* <code>false</code> otherwise.
*/
@Beta
public static boolean isValidName(String field) {
return field != null && field.length() > 0;
}
/**
* Returns a list of valid field names.
*
* @param fields the list of fields to create the map.
* @return a list of valid field names.
*/
@Beta
public static List<String> filterNames(List<String> fields) {
List<String> names = new ArrayList<String>();
for (String f : fields) {
if (isValidName(f)) {
names.add(f);
}
}
return names;
}
/**
* Returns a list of possible field values from the specified text.
*
* <p>You can use this method to extract the list of terms or phrase values to create a query.
*
* <p>Spaces are ignored unless they are within double quotation marks.
*
* <p>See examples below:
* <pre>
* |Big| => [Big]
* |Big bang| => [Big, bang]
* | Big bang | => [Big, bang]
* |The "Big bang"| => [The, "Big bang"]
* |The "Big bang| => [The, "Big, bang]
* </pre>
*
* <p>Note: this class does not excludes terms which could be considered stop words by the index.
*
* @param text The text for which values are needed.
* @return the corresponding list of values.
*/
@Beta
public static List<String> toValues(String text) {
List<String> values = new ArrayList<String>();
Pattern p = Pattern.compile("(\\\"[^\\\"]+\\\")|(\\S+)");
Matcher m = p.matcher(text);
while (m.find()) {
values.add(m.group());
}
return values;
}
/**
* Returns the string value of the specified field.
*
* <p>This method will automatically decompress the value of the field if it is binary.
*
* @param f The field
* @return The value of the field as a string.
*/
public static String toString(IndexableField f) {
if (f == null) return null;
String value = f.stringValue();
// is it a compressed field?
if (value == null) {
BytesRef binary = f.binaryValue();
if (binary != null) try {
value = CompressionTools.decompressString(binary);
} catch (DataFormatException ex) {
// strange but true, unable to decompress
LoggerFactory.getLogger(Fields.class).error("Failed to decompress field value", ex);
return null;
}
}
return value;
}
/**
* Returns the terms for a field
*
* @param field The field
* @param text The text to analyze
* @param analyzer The analyzer
*
* @return the corresponding list of terms produced by the analyzer.
*
* @throws IOException
*/
public static List<String> toTerms(String field, String text, Analyzer analyzer) {
List<String> terms = new ArrayList<String>();
try {
TokenStream stream = analyzer.tokenStream(field, new StringReader(text));
CharTermAttribute attribute = stream.addAttribute(CharTermAttribute.class);
stream.reset();
while (stream.incrementToken()) {
String term = attribute.toString();
terms.add(term);
}
stream.end();
stream.close();
} catch (IOException ex) {
// Should not occur since we use a StringReader
ex.printStackTrace();
}
return terms;
}
}
| 30.065574 | 99 | 0.657034 |
5d2d4c6efe0fb0e1189022fdf775adb8bc6a0119 | 12,871 | package jdbi_modules.internal;
import jdbi_modules.Module;
import jdbi_modules.ModuleMeta;
import jdbi_modules.SqlGenerator;
import jdbi_modules.Store;
import org.jdbi.v3.core.Handle;
import org.jdbi.v3.core.mapper.ColumnMapper;
import org.jdbi.v3.core.statement.Query;
import org.jdbi.v3.core.statement.StatementContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.sql.ResultSet;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.Stack;
import java.util.function.Consumer;
import java.util.stream.Collectors;
/**
* @param <Type> The Type this module maps to
* @param <KeyType> The Type of the Key, to access this modules submodules
* @param <SqlType> The SqlType of the SqlGenerator
* @param <Generator> The Type of the SqlGenerator
* @since 14.04.2018
*/
public class ModuleMetaGenerator<Type, KeyType, SqlType extends jdbi_modules.SqlType, Generator extends SqlGenerator<SqlType>> {
private final String modulePrefix;
private final Module<Type, KeyType, SqlType, Generator> prototype;
private final Map<Class<?>, Object> baseStore;
private final Map<java.lang.reflect.Type, ColumnMapper<?>> commonColumnMapperMap;
private final Map<KeyType, ModuleMetaGenerator<Object, Object, SqlType, SqlGenerator<SqlType>>> submodules;
/**
* @param prefixGenerator a prefix generator
* @param prototype the module
* @param store the public store
* @param commonColumnMapperMap the common shared column mapper map
*/
@SuppressWarnings("unchecked")
public ModuleMetaGenerator(final Iterator<String> prefixGenerator,
final Module<Type, KeyType, SqlType, Generator> prototype,
final Map<Class<?>, Object> store,
final Map<java.lang.reflect.Type, ColumnMapper<?>> commonColumnMapperMap) {
this.modulePrefix = prefixGenerator.next();
this.prototype = prototype;
this.baseStore = store;
this.commonColumnMapperMap = commonColumnMapperMap;
this.submodules = prototype.submodules().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> new ModuleMetaGenerator<>(prefixGenerator, e.getValue(), store, commonColumnMapperMap)));
}
private SqlType genSql(final Set<Consumer<Query>> queryModifierApplyer) {
final Iterator<String> prefixGenerator = new PrefixGenerator("m");
final Stack<String> prefixStack = new Stack<>();
prefixStack.push(this.modulePrefix);
SqlType sql = prototype.sqlGenerator().sql(queryModifierApplyer, prefixGenerator, prototype.queryModifiers(), prefixStack);
sql = this.appendSqlRecursive(sql, prefixGenerator, queryModifierApplyer, prefixStack);
return sql;
}
private SqlType appendSqlRecursive(final SqlType sql, final Iterator<String> prefixGenerator, final Set<Consumer<Query>> queryModifierApplier, final Stack<String> prefixStack) {
SqlType sqlAccu = sql;
for (final ModuleMetaGenerator<Object, Object, SqlType, SqlGenerator<SqlType>> moduleMeta : submodules.values()) {
prefixStack.push(moduleMeta.modulePrefix);
sqlAccu = moduleMeta.prototype.sqlGenerator().append(queryModifierApplier,
prefixGenerator, moduleMeta.prototype.queryModifiers(), sqlAccu, prefixStack);
sqlAccu = moduleMeta.appendSqlRecursive(sqlAccu, prefixGenerator, queryModifierApplier, prefixStack);
prefixStack.pop();
}
return sqlAccu;
}
private ModuleMetaImpl<Type, KeyType, SqlType, Generator> initialize(final @NotNull ResultSet resultSet, final @NotNull StatementContext statementContext) {
final Store store = Store.of(new HashMap<>(baseStore));
store.place(ResultSet.class, resultSet);
store.place(StatementContext.class, statementContext);
final RowView rowView = new RowView(modulePrefix, prototype.rowMapper(), commonColumnMapperMap, resultSet, statementContext);
store.place(RowView.class, rowView);
final Map<KeyType, FallbackMeta<Object>> fallbacks = prototype.fallbacks().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> new FallbackMeta<>(e.getValue(), rowView, baseStore)));
return new ModuleMetaImpl<>(prototype, modulePrefix, resultSet, statementContext, rowView, store, fallbacks,
submodules.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().initialize(resultSet, statementContext))));
}
private Query createQuery(final Handle handle) {
final Set<Consumer<Query>> queryModifierApplyer = new HashSet<>();
final Query query = handle.select(genSql(queryModifierApplyer).toQuery());
queryModifierApplyer.forEach(qm -> qm.accept(query));
return query;
}
/**
* Executes the generator, creates the query, sends the request and maps.
*
* @param handle the handle to create the query from
* @param seed the seed of the root module
* @param <C> the seed type
* @return the seed, filled with the mapped values
*/
public <C extends Collection<Type>> C run(final Handle handle, final C seed) {
return createQuery(handle).scanResultSet(((resultSetSupplier, ctx) -> {
final ResultSet resultSet = resultSetSupplier.get();
final ModuleMetaImpl<Type, KeyType, SqlType, Generator> initialize = initialize(resultSet, ctx);
while (resultSet.next()) {
initialize.call(seed);
}
return seed;
}));
}
/**
* @param <Type> The Type this module maps to
* @param <KeyType> The Type of the Key, to access this modules submodules
* @param <SqlType> The SqlType of the SqlGenerator
* @param <Generator> The Type of the SqlGenerator
*/
@SuppressWarnings("WeakerAccess")
static final class ModuleMetaImpl<Type, KeyType, SqlType extends jdbi_modules.SqlType, Generator extends SqlGenerator<SqlType>> implements ModuleMeta<KeyType> {
private final String prefix;
private final ResultSet resultSet;
private final StatementContext statementContext;
private final RowView rowView;
private final Store store;
private final Map<KeyType, FallbackMeta<Object>> fallbacks;
private final Map<KeyType, ModuleMetaImpl<Object, Object, SqlType, SqlGenerator<SqlType>>> submodules;
private final Module<Type, KeyType, SqlType, Generator> prototype;
@Nullable
private CollectorImpl<Collection<Type>, Type> collector = null;
private ModuleMetaImpl(final Module<Type, KeyType, SqlType, Generator> prototype,
final String prefix,
final ResultSet resultSet,
final StatementContext statementContext,
final RowView rowView,
final Store store,
final Map<KeyType, FallbackMeta<Object>> fallbacks,
final Map<KeyType, ModuleMetaImpl<Object, Object, SqlType, SqlGenerator<SqlType>>> submodules) {
this.prototype = prototype;
this.prefix = prefix;
this.resultSet = resultSet;
this.statementContext = statementContext;
this.rowView = rowView;
this.store = store;
this.fallbacks = fallbacks;
this.submodules = submodules;
this.prototype.prepare(this.prefix, store);
}
@NotNull
@Override
public String getModulePrefix() {
return prefix;
}
@NotNull
@Override
public Store getStore() {
return store;
}
@Override
@SuppressWarnings("unchecked")
public <T> ModuleMeta<KeyType> callSubmodule(final @NotNull KeyType key, final @NotNull Collection<T> collection) {
final ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>> module = (ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>>) submodules.get(key);
if (Objects.nonNull(module)) {
module.call(collection);
return this;
}
final FallbackMeta<T> fallbackMeta = (FallbackMeta<T>) fallbacks.get(key);
if (Objects.nonNull(fallbackMeta)) {
fallbackMeta.call(collection);
}
return this;
}
@Override
@SuppressWarnings("unchecked")
public <T> ModuleMeta<KeyType> callSubmodule(final @NotNull KeyType key,
final @NotNull Collection<T> collection,
final @NotNull Consumer<T> enricher) {
final ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>> module = (ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>>) submodules.get(key);
if (Objects.nonNull(module)) {
module.call(collection, enricher);
return this;
}
final FallbackMeta<T> fallbackMeta = (FallbackMeta<T>) fallbacks.get(key);
if (Objects.nonNull(fallbackMeta)) {
fallbackMeta.call(collection, enricher);
}
return this;
}
@Override
@SuppressWarnings("unchecked")
public <T, CollectionType extends Collection<T>> ModuleMeta<KeyType> callSubmodule(final @NotNull KeyType key,
final @NotNull CollectionType collection,
final @NotNull Consumer<T> enricher,
final @NotNull Consumer<T> accessed) {
final ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>> module = (ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>>) submodules.get(key);
if (Objects.nonNull(module)) {
module.call(collection, enricher, accessed);
return this;
}
final FallbackMeta<T> fallbackMeta = (FallbackMeta<T>) fallbacks.get(key);
if (Objects.nonNull(fallbackMeta)) {
fallbackMeta.call(collection, enricher, accessed);
}
return this;
}
@Override
public <T> T callSubmodule(final @NotNull KeyType key, final @Nullable T obj) {
final ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>> module = (ModuleMetaImpl<T, KeyType, SqlType, SqlGenerator<SqlType>>) submodules.get(key);
final List<T> list = new LinkedList<>();
if (obj != null) {
list.add(obj);
}
if (Objects.nonNull(module)) {
module.call(list);
return list.stream().findFirst().orElse(null);
}
final FallbackMeta<T> fallbackMeta = (FallbackMeta<T>) fallbacks.get(key);
if (Objects.nonNull(fallbackMeta)) {
fallbackMeta.call(list);
return list.stream().findFirst().orElse(null);
}
return null;
}
public <CollectionType extends Collection<Type>> void call(final @NotNull CollectionType collection) {
if (Objects.isNull(collector)) {
collector = new CollectorImpl<>(collection, rowView, resultSet, statementContext);
}
collector.useCollection(collection);
prototype.map(collector, this, rowView, store);
}
public <CollectionType extends Collection<Type>> void call(final @NotNull CollectionType collection,
final @NotNull Consumer<Type> enricher) {
this.call(collection);
Objects.requireNonNull(collector).applyOnAdded(enricher);
}
public <CollectionType extends Collection<Type>> void call(final @NotNull CollectionType collection,
final @NotNull Consumer<Type> enricher,
final @NotNull Consumer<Type> accessed) {
this.call(collection, enricher);
Objects.requireNonNull(collector).applyOnAccessed(accessed);
}
}
}
| 48.569811 | 181 | 0.622329 |
93d9a77314a3f67151f803d11bb24cf012877456 | 704 | package cc.mrbird.febs.app.entity;
import lombok.Data;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
/**
* Entity
*
* @author 冷酷的苹果
* @date 2020-05-06 09:17:12
*/
@Data
@TableName("t_label_to_office")
public class LabelToOffice {
/**
* 关联办公室信息与标签
*/
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
/**
* 办公室标签id
*/
@TableField("office_label_id")
private Integer officeLabelId;
/**
* 办公室id
*/
@TableField("office_id")
private Integer officeId;
}
| 18.051282 | 54 | 0.676136 |
0d8d5b0293f996958f1ba4443815765567c0b45e | 9,395 | /*
* Copyright 2015 - 2019 TU Dortmund
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.learnlib.alex.integrationtests.resources;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.jayway.jsonpath.JsonPath;
import de.learnlib.alex.integrationtests.resources.api.UserApi;
import de.learnlib.alex.integrationtests.resources.api.WebhookApi;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.http.HttpStatus;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
public class WebhookResourceIT extends AbstractResourceIT {
private String jwtUser1;
private String jwtUser2;
private UserApi userApi;
private WebhookApi webhookApi;
@Before
public void pre() {
userApi = new UserApi(client, port);
webhookApi = new WebhookApi(client, port);
userApi.create("{\"email\":\"test1@test.de\",\"password\":\"test\"}");
userApi.create("{\"email\":\"test2@test.de\",\"password\":\"test\"}");
jwtUser1 = userApi.login("test1@test.de", "test");
jwtUser2 = userApi.login("test2@test.de", "test");
}
@Test
public void shouldCreateAWebhook() {
final String wh = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final Response res1 = webhookApi.create(wh, jwtUser1);
assertEquals(HttpStatus.OK.value(), res1.getStatus());
JsonPath.read(res1.readEntity(String.class), "$.id");
}
@Test
public void shouldNotCreateAWebhookWithTheSameUrlTwice() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final String wh2 = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
webhookApi.create(wh1, jwtUser1);
final Response res2 = webhookApi.create(wh2, jwtUser1);
assertEquals(HttpStatus.BAD_REQUEST.value(), res2.getStatus());
assertEquals(1, getNumberOfWebhooks(jwtUser1));
}
@Test
public void shouldNotCreateWebhookWithEmptyEventList() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", new ArrayList<>());
final Response res1 = webhookApi.create(wh1, jwtUser1);
assertEquals(HttpStatus.BAD_REQUEST.value(), res1.getStatus());
assertEquals(0, getNumberOfWebhooks(jwtUser1));
}
@Test
public void shouldUpdateWebhook() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", Collections.singletonList("PROJECT_CREATED"));
final Response res1 = webhookApi.create(wh1, jwtUser1);
final JsonNode whNode = objectMapper.readTree(res1.readEntity(String.class));
((ObjectNode) whNode).put("name", "updatedName");
((ObjectNode) whNode).put("url", "http://test2");
final Response res2 = webhookApi.update(whNode.toString(), jwtUser1);
Assert.assertEquals(Response.Status.OK.getStatusCode(), res2.getStatus());
JSONAssert.assertEquals(whNode.toString(), res2.readEntity(String.class), true);
}
@Test
public void shouldFailToUpdateWebhookIfEventsAreEmpty() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", Collections.singletonList("PROJECT_CREATED"));
final Response res1 = webhookApi.create(wh1, jwtUser1);
final String wh1String = res1.readEntity(String.class);
final JsonNode whNode = objectMapper.readTree(wh1String);
((ObjectNode) whNode).putArray("events");
final Response res2 = webhookApi.update(whNode.toString(), jwtUser1);
Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), res2.getStatus());
}
@Test
public void shouldFailToUpdateWebhookIfUrlExists() throws Exception {
webhookApi.create(createWebhookJson("test", "http://exists", Collections.singletonList("PROJECT_CREATED")), jwtUser1);
final String wh1 = createWebhookJson("test", "http://test", Collections.singletonList("PROJECT_CREATED"));
final Response res1 = webhookApi.create(wh1, jwtUser1);
final String wh1String = res1.readEntity(String.class);
final JsonNode whNode = objectMapper.readTree(wh1String);
((ObjectNode) whNode).put("url", "http://exists");
final Response res2 = webhookApi.update(whNode.toString(), jwtUser1);
Assert.assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), res2.getStatus());
}
@Test
public void shouldDeleteAWebhook() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final Response res1 = webhookApi.create(wh1, jwtUser1);
final Integer id = JsonPath.read(res1.readEntity(String.class), "id");
final Response res2 = webhookApi.delete(id, jwtUser1);
assertEquals(HttpStatus.NO_CONTENT.value(), res2.getStatus());
assertEquals(0, getNumberOfWebhooks(jwtUser1));
}
@Test
public void shouldDeleteWebhooks() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final Response res1 = webhookApi.create(wh1, jwtUser1);
final Integer id1 = JsonPath.read(res1.readEntity(String.class), "id");
final String wh2 = createWebhookJson("test2", "http://test2", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final Response res2 = webhookApi.create(wh2, jwtUser1);
final Integer id2 = JsonPath.read(res2.readEntity(String.class), "id");
final Response res3 = webhookApi.delete(Arrays.asList(id1, id2), jwtUser1);
assertEquals(HttpStatus.NO_CONTENT.value(), res3.getStatus());
assertEquals(0, getNumberOfWebhooks(jwtUser1));
}
@Test
public void shouldFailToDeleteWebhooksIfOneDoesNotExist() throws Exception {
final String wh1 = createWebhookJson("test", "http://test1", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final Response res1 = webhookApi.create(wh1, jwtUser1);
final int id1 = JsonPath.read(res1.readEntity(String.class), "$.id");
final Response res3 = webhookApi.delete(Arrays.asList(id1, -1), jwtUser1);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), res3.getStatus());
assertEquals(1, getNumberOfWebhooks(jwtUser1));
}
@Test
public void shouldNotDeleteAWebhookOfAnotherUser() throws Exception {
final String wh = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
final Response res1 = webhookApi.create(wh, jwtUser2);
final Integer id = JsonPath.read(res1.readEntity(String.class), "id");
final Response res2 = webhookApi.delete(id, jwtUser1);
assertEquals(HttpStatus.UNAUTHORIZED.value(), res2.getStatus());
assertEquals(1, getNumberOfWebhooks(jwtUser2));
}
@Test
public void shouldFailToDeleteAnUnknownWebhook() throws Exception {
final String wh1 = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
webhookApi.create(wh1, jwtUser1);
final String wh2 = createWebhookJson("test", "http://test", Arrays.asList("PROJECT_CREATED", "PROJECT_DELETED"));
webhookApi.create(wh2, jwtUser2);
final Response res = webhookApi.delete(-1, jwtUser1);
assertEquals(HttpStatus.NOT_FOUND.value(), res.getStatus());
assertEquals(1, getNumberOfWebhooks(jwtUser1));
assertEquals(1, getNumberOfWebhooks(jwtUser2));
}
@Test
public void shouldGetAllEvents() {
final Response res = webhookApi.getEvents(jwtUser1);
final List<String> events = res.readEntity(new GenericType<List<String>>() {
});
assertFalse(events.isEmpty());
}
private int getNumberOfWebhooks(String jwt) throws Exception {
final Response res = webhookApi.get(jwt);
return objectMapper.readTree(res.readEntity(String.class)).size();
}
private String createWebhookJson(String name, String url, List<String> events) {
events = events.stream().map(e -> "\"" + e + "\"").collect(Collectors.toList());
return "{"
+ "\"name\":\"" + name + "\""
+ ",\"url\":\"" + url + "\""
+ ",\"events\":[" + String.join(",", events) + "]"
+ "}";
}
}
| 43.09633 | 126 | 0.688451 |
0249c06d9c4d0abbd32970326e763cf6d5ce4a6d | 251 | package uk.nhs.adaptors.gp2gp.ehr.model;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
@Builder
public class SendCommonTemplateParameters {
private final String fromAsid;
private final String document;
}
| 17.928571 | 43 | 0.788845 |
74e837eab0503ec88f8c4786ebd97a12378e14c3 | 12,584 | /*
* 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 grakn.client.rpc;
import com.google.protobuf.ByteString;
import grakn.client.GraknClient.Transaction;
import grakn.client.GraknOptions;
import grakn.client.common.exception.GraknClientException;
import grakn.client.concept.ConceptManager;
import grakn.client.logic.LogicManager;
import grakn.client.query.QueryManager;
import grakn.protocol.GraknGrpc;
import grakn.protocol.TransactionProto;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Function;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static grakn.client.common.proto.OptionsProtoBuilder.options;
import static grakn.client.common.exception.ErrorMessage.Client.TRANSACTION_CLOSED;
import static grakn.client.common.exception.ErrorMessage.Client.UNKNOWN_REQUEST_ID;
import static grakn.client.common.tracing.TracingProtoBuilder.tracingData;
import static grakn.common.util.Objects.className;
public class TransactionRPC implements Transaction {
private final Transaction.Type type;
private final ConceptManager conceptManager;
private final LogicManager logicManager;
private final QueryManager queryManager;
private final SynchronizedStreamObserver<TransactionProto.Transaction.Req> requestObserver;
private final ResponseCollectors collectors;
private final int networkLatencyMillis;
private final AtomicBoolean isOpen;
TransactionRPC(SessionRPC session, ByteString sessionId, Type type, GraknOptions options) {
try {
this.type = type;
conceptManager = new ConceptManager(this);
logicManager = new LogicManager(this);
queryManager = new QueryManager(this);
collectors = new ResponseCollectors();
// Opening the StreamObserver exposes these atomics to another thread, so we must initialize them first.
isOpen = new AtomicBoolean(true);
requestObserver = new SynchronizedStreamObserver<>(GraknGrpc.newStub(session.channel()).transaction(responseObserver()));
final TransactionProto.Transaction.Req.Builder openRequest = TransactionProto.Transaction.Req.newBuilder()
.putAllMetadata(tracingData())
.setOpenReq(TransactionProto.Transaction.Open.Req.newBuilder()
.setSessionId(sessionId)
.setType(TransactionProto.Transaction.Type.forNumber(type.id()))
.setOptions(options(options)));
final Instant startTime = Instant.now();
final TransactionProto.Transaction.Open.Res res = execute(openRequest).getOpenRes();
final Instant endTime = Instant.now();
networkLatencyMillis = (int) ChronoUnit.MILLIS.between(startTime, endTime) - res.getProcessingTimeMillis();
} catch (StatusRuntimeException e) {
throw GraknClientException.of(e);
}
}
@Override
public Type type() {
return type;
}
@Override
public boolean isOpen() {
return isOpen.get();
}
@Override
public ConceptManager concepts() {
return conceptManager;
}
@Override
public LogicManager logic() {
return logicManager;
}
@Override
public QueryManager query() {
return queryManager;
}
@Override
public void commit() {
final TransactionProto.Transaction.Req.Builder commitReq = TransactionProto.Transaction.Req.newBuilder()
.putAllMetadata(tracingData())
.setCommitReq(TransactionProto.Transaction.Commit.Req.getDefaultInstance());
try {
execute(commitReq);
} finally {
close();
}
}
@Override
public void rollback() {
final TransactionProto.Transaction.Req.Builder rollbackReq = TransactionProto.Transaction.Req.newBuilder()
.putAllMetadata(tracingData())
.setRollbackReq(TransactionProto.Transaction.Rollback.Req.getDefaultInstance());
execute(rollbackReq);
}
@Override
public void close() {
close(new Response.Done.Completed());
}
private void close(Response.Done doneResponse) {
if (isOpen.compareAndSet(true, false)) {
collectors.clear(doneResponse);
try {
requestObserver.onCompleted();
} catch (StatusRuntimeException e) {
throw GraknClientException.of(e);
}
}
}
public TransactionProto.Transaction.Res execute(TransactionProto.Transaction.Req.Builder request) {
return executeAsync(request, res -> res).get();
}
public <T> QueryFuture<T> executeAsync(TransactionProto.Transaction.Req.Builder request, Function<TransactionProto.Transaction.Res, T> transformResponse) {
if (!isOpen.get()) throw new GraknClientException(TRANSACTION_CLOSED);
final ResponseCollector.Single responseCollector = new ResponseCollector.Single();
final UUID requestId = UUID.randomUUID();
request.setId(requestId.toString());
collectors.put(requestId, responseCollector);
requestObserver.onNext(request.build());
return new QueryFuture<>(responseCollector, transformResponse);
}
public <T> Stream<T> stream(TransactionProto.Transaction.Req.Builder request, Function<TransactionProto.Transaction.Res, Stream<T>> transformResponse) {
if (!isOpen.get()) throw new GraknClientException(TRANSACTION_CLOSED);
final ResponseCollector.Multiple responseCollector = new ResponseCollector.Multiple();
final UUID requestId = UUID.randomUUID();
request.setId(requestId.toString());
request.setLatencyMillis(networkLatencyMillis);
collectors.put(requestId, responseCollector);
requestObserver.onNext(request.build());
final ResponseIterator<T> responseIterator = new ResponseIterator<>(requestId, requestObserver, responseCollector, transformResponse);
return StreamSupport.stream(((Iterable<T>) () -> responseIterator).spliterator(), false);
}
private StreamObserver<TransactionProto.Transaction.Res> responseObserver() {
return new StreamObserver<TransactionProto.Transaction.Res>() {
@Override
public void onNext(TransactionProto.Transaction.Res res) {
if (!isOpen.get()) return;
final UUID requestId = UUID.fromString(res.getId());
final ResponseCollector collector = collectors.get(requestId);
assert collector != null : UNKNOWN_REQUEST_ID.message(requestId);
collector.add(new Response.Result(res));
}
@Override
public void onError(Throwable ex) {
assert ex instanceof StatusRuntimeException : "The server sent an exception of unexpected type " + ex;
// TODO: this isn't nice - an error from one request isn't really appropriate for all of them (see #180)
close(new Response.Done.Error((StatusRuntimeException) ex));
}
@Override
public void onCompleted() {
close(new Response.Done.Completed());
}
};
}
private static class ResponseCollectors {
private final ConcurrentMap<UUID, ResponseCollector> collectors;
private ResponseCollectors() {
collectors = new ConcurrentHashMap<>();
}
private ResponseCollector get(UUID requestId) {
return collectors.get(requestId);
}
private synchronized void put(UUID requestId, ResponseCollector collector) {
collectors.put(requestId, collector);
}
private synchronized void clear(Response.Done doneResponse) {
collectors.values().parallelStream().forEach(collector -> collector.add(doneResponse));
collectors.clear();
}
}
abstract static class ResponseCollector {
private final AtomicBoolean isDone;
/** gRPC response messages, errors, and notifications of abrupt termination are all sent to this blocking queue. */
private final BlockingQueue<Response> responseBuffer;
ResponseCollector() {
isDone = new AtomicBoolean(false);
responseBuffer = new LinkedBlockingQueue<>();
}
void add(Response response) {
responseBuffer.add(response);
if (!(response instanceof Response.Result) || isLastResponse(response.read())) isDone.set(true);
}
boolean isDone() {
return isDone.get();
}
TransactionProto.Transaction.Res take() throws InterruptedException {
return responseBuffer.take().read();
}
TransactionProto.Transaction.Res take(long timeout, TimeUnit unit) throws InterruptedException, TimeoutException {
final Response response = responseBuffer.poll(timeout, unit);
if (response != null) return response.read();
else throw new TimeoutException();
}
abstract boolean isLastResponse(TransactionProto.Transaction.Res response);
static class Single extends ResponseCollector {
@Override
boolean isLastResponse(TransactionProto.Transaction.Res response) {
return true;
}
}
static class Multiple extends ResponseCollector {
@Override
boolean isLastResponse(TransactionProto.Transaction.Res response) {
return response.getDone();
}
}
}
abstract static class Response {
abstract TransactionProto.Transaction.Res read();
static class Result extends Response {
private final TransactionProto.Transaction.Res response;
Result(TransactionProto.Transaction.Res response) {
this.response = response;
}
@Override
TransactionProto.Transaction.Res read() {
return response;
}
@Override
public String toString() {
return className(getClass()) + "{" + response + "}";
}
}
static abstract class Done extends Response {
static class Completed extends Done {
@Override
TransactionProto.Transaction.Res read() {
throw new GraknClientException(TRANSACTION_CLOSED);
}
@Override
public String toString() {
return className(getClass()) + "{}";
}
}
static class Error extends Done {
private final StatusRuntimeException error;
Error(StatusRuntimeException error) {
// TODO: parse different gRPC errors into specific GraknClientException
this.error = error;
}
@Override
TransactionProto.Transaction.Res read() {
throw GraknClientException.of(error);
}
@Override
public String toString() {
return className(getClass()) + "{" + error + "}";
}
}
}
}
}
| 37.676647 | 159 | 0.654641 |
c2d61d5c66ca6edf06ae23e55765ffc5111ce9a2 | 4,792 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.opensearch.index.analysis;
import org.apache.lucene.analysis.Analyzer;
import org.opensearch.Version;
import org.opensearch.cluster.metadata.IndexMetadata;
import org.opensearch.common.settings.Settings;
import org.opensearch.common.xcontent.XContentBuilder;
import org.opensearch.common.xcontent.XContentFactory;
import org.opensearch.index.mapper.MappedFieldType;
import org.opensearch.index.mapper.MapperService;
import org.opensearch.indices.analysis.PreBuiltAnalyzers;
import org.opensearch.plugins.Plugin;
import org.opensearch.test.OpenSearchSingleNodeTestCase;
import org.opensearch.test.InternalSettingsPlugin;
import java.io.IOException;
import java.util.Collection;
import java.util.Locale;
import static org.opensearch.test.VersionUtils.randomVersion;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
public class PreBuiltAnalyzerTests extends OpenSearchSingleNodeTestCase {
@Override
protected boolean forbidPrivateIndexSettings() {
return false;
}
@Override
protected Collection<Class<? extends Plugin>> getPlugins() {
return pluginList(InternalSettingsPlugin.class);
}
public void testThatDefaultAndStandardAnalyzerAreTheSameInstance() {
Analyzer currentStandardAnalyzer = PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.CURRENT);
Analyzer currentDefaultAnalyzer = PreBuiltAnalyzers.DEFAULT.getAnalyzer(Version.CURRENT);
// special case, these two are the same instance
assertThat(currentDefaultAnalyzer, is(currentStandardAnalyzer));
}
public void testThatInstancesAreTheSameAlwaysForKeywordAnalyzer() {
assertThat(PreBuiltAnalyzers.KEYWORD.getAnalyzer(Version.CURRENT),
is(PreBuiltAnalyzers.KEYWORD.getAnalyzer(Version.V_6_0_0)));
}
public void testThatInstancesAreCachedAndReused() {
assertSame(PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.CURRENT),
PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.CURRENT));
// same es version should be cached
assertSame(PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.V_6_2_1),
PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.V_6_2_1));
assertNotSame(PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.V_6_0_0),
PreBuiltAnalyzers.STANDARD.getAnalyzer(Version.V_6_0_1));
// Same Lucene version should be cached:
assertSame(PreBuiltAnalyzers.STOP.getAnalyzer(Version.V_6_2_1),
PreBuiltAnalyzers.STOP.getAnalyzer(Version.V_6_2_2));
}
public void testThatAnalyzersAreUsedInMapping() throws IOException {
int randomInt = randomInt(PreBuiltAnalyzers.values().length-1);
PreBuiltAnalyzers randomPreBuiltAnalyzer = PreBuiltAnalyzers.values()[randomInt];
String analyzerName = randomPreBuiltAnalyzer.name().toLowerCase(Locale.ROOT);
Version randomVersion = randomVersion(random());
Settings indexSettings = Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, randomVersion).build();
NamedAnalyzer namedAnalyzer = new PreBuiltAnalyzerProvider(analyzerName, AnalyzerScope.INDEX,
randomPreBuiltAnalyzer.getAnalyzer(randomVersion)).get();
XContentBuilder mapping = XContentFactory.jsonBuilder().startObject().startObject("type")
.startObject("properties").startObject("field").field("type", "text")
.field("analyzer", analyzerName).endObject().endObject().endObject().endObject();
MapperService mapperService = createIndex("test", indexSettings, "type", mapping).mapperService();
MappedFieldType fieldType = mapperService.fieldType("field");
assertThat(fieldType.getTextSearchInfo().getSearchAnalyzer(), instanceOf(NamedAnalyzer.class));
NamedAnalyzer fieldMapperNamedAnalyzer = fieldType.getTextSearchInfo().getSearchAnalyzer();
assertThat(fieldMapperNamedAnalyzer.analyzer(), is(namedAnalyzer.analyzer()));
}
}
| 46.076923 | 118 | 0.759808 |
80d159ab641402c87c9c0fa9b0f46b8d9722f7f1 | 4,875 | package com.yy.service.rush.realtime;
import com.yy.dao.repository.TrainOrderRepository;
import com.yy.dao.repository.TrainTicketRepository;
import com.yy.integration.rail.OrderCenter;
import com.yy.integration.rail.OrderSubmitter;
import com.yy.dao.entity.TrainOrder;
import com.yy.dao.entity.WxAccount;
import com.yy.other.exception.UnfinishedOrderException;
import com.yy.other.domain.FindResult;
import com.yy.service.rush.observer.Finder;
import com.yy.service.notification.SendMsgService;
import com.yy.service.rush.AbstractOrderContext;
import com.yy.service.rush.OrderAction;
import com.yy.service.rush.realtime.states.RealTimePayingState;
import com.yy.common.util.SleepUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Component
public class RealTimeOrderAction extends OrderAction {
@Autowired
private SendMsgService sendMsgService;
@Autowired
private TrainTicketRepository trainTicketRepository;
@Autowired
private TrainOrderRepository trainOrderRepository;
/**
* 查询是否有符合要求的车票
*
* @param context
* @return
*/
public boolean findRealTime(AbstractOrderContext context) {
return Finder.findRealTime(context).isFound();
}
/**
* 提交订单
*
* @param context
* @return
*/
public boolean submitRealTime(AbstractOrderContext context) throws UnfinishedOrderException {
FindResult findResult = context.getFindResult();
if (findResult == null) {
return false;
}
WxAccount wxAccount = context.getWxAccount();
String sequenceNo = OrderSubmitter.submitRealTime(
wxAccount.getUsername(),
wxAccount.getPassword(),
findResult.getTrain().getSecretStr(),
findResult.getDate(),
context.getOrder().getFromStation(),
context.getOrder().getToStation(),
Arrays.asList(context.getOrder().getPeople().split("/")),
findResult.getSeats()
);
return sequenceNo != null;
}
/**
* 保存已抢到到车票
*
* @param context
* @return
*/
public boolean saveUnpaidRealTimeOrder(AbstractOrderContext context) {
WxAccount wxAccount = context.getWxAccount();
FindResult findResult = context.getFindResult();
if (findResult == null) {
return false;
}
OrderCenter.Result result = OrderCenter.findUnpaidOrder(wxAccount.getUsername(), wxAccount.getPassword(),
findResult.getTrain(), context.getOrder().getOrderId());
while (result == null) {
SleepUtil.sleepRandomTime(1000, 2000);
result = OrderCenter.findUnpaidOrder(wxAccount.getUsername(), wxAccount.getPassword(),
findResult.getTrain(), context.getOrder().getOrderId());
}
trainOrderRepository.save(result.getTrainOrder());
trainTicketRepository.save(result.getTickets());
return true;
}
/**
* 通知用户付款
*
* @param context
*/
public boolean notifyRealTimePay(AbstractOrderContext context) {
TrainOrder trainOrder = trainOrderRepository.findByUserOrderId(context.getOrder().getOrderId());
if (trainOrder == null) {
return false;
}
if (!(context.getState() instanceof RealTimePayingState)) {
return false;
}
sendMsgService.send(context.getOrder(), trainOrder.getSequenceNo());
return true;
}
/**
* 检查用户是否支付
*
* @param context
* @return 支付成功或者失败
*/
public boolean checkRealTimePay(AbstractOrderContext context) {
WxAccount wxAccount = context.getWxAccount();
String orderId = context.getOrder().getOrderId();
TrainOrder trainOrder = trainOrderRepository.findByUserOrderId(orderId);
boolean isUntraveledOrder = false;
long expiredTime = System.currentTimeMillis() + 30 * 60000;
while (context.isRunning() && System.currentTimeMillis() < expiredTime) {
isUntraveledOrder = OrderCenter.isUntraveledOrder(wxAccount.getUsername(), wxAccount.getPassword(), trainOrder.getSequenceNo());
if (isUntraveledOrder) {
break;
}
//30秒钟检测一次
SleepUtil.sleep(30000);
}
return isUntraveledOrder;
}
public boolean cancelUnpaidRealTimeOrder(AbstractOrderContext context) {
WxAccount wxAccount = context.getWxAccount();
String orderId = context.getOrder().getOrderId();
TrainOrder trainOrder = trainOrderRepository.findByUserOrderId(orderId);
return OrderCenter.cancelNoCompleteOrder(wxAccount.getUsername(), wxAccount.getPassword(), trainOrder.getSequenceNo());
}
}
| 33.390411 | 140 | 0.66441 |
917818f2238acde36f6ca4c5c442b302bb6e2706 | 538 | package org.gitrust.fileindexer.indexer;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
@Builder
@Getter
@ToString
public class FileDocument {
public static final String FIELD_SIZE = "fileSize";
public static final String FIELD_NAME = "fileName";
public static final String FIELD_PATH = "filePath";
public static final String FIELD_MD5_HEX = "fileMd5Hex";
private long fileSize;
private String fileName;
private String absolutePath;
private int docId;
private String md5Hex;
}
| 24.454545 | 60 | 0.750929 |
033d695cab04a96ca94de75e4aa8ca3fba1e8029 | 1,668 | package com.honeyedoak.ppksecuredws;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.honeyedoak.ppksecuredws.model.SecuredJson;
import com.honeyedoak.ppksecuredws.model.UnsecuredJson;
import com.honeyedoak.cryptoutils.AsymmetricCryptoService;
import com.honeyedoak.cryptoutils.SymmetricCryptoService;
import com.honeyedoak.cryptoutils.exception.CryptoException;
import java.io.IOException;
import java.security.Key;
public class GenericSecureJsonConverterImpl<T> extends AbstractSecureConverter implements GenericSecureJsonConverter<T> {
public GenericSecureJsonConverterImpl(String charset, int oneTimePasswordLength, String keystoreLocation, String keystorePassword, SymmetricCryptoService symmetricCryptoService, AsymmetricCryptoService asymmetricCryptoService) {
super(charset, oneTimePasswordLength, keystoreLocation, keystorePassword, symmetricCryptoService, asymmetricCryptoService);
}
@Override
public SecuredJson secureJson(T object, Key key) throws CryptoException {
try {
return this.secureJson(new ObjectMapper().writerFor(getParameterClass()).writeValueAsString(object), key);
} catch (JsonProcessingException e) {
throw new CryptoException(e);
}
}
@Override
public UnsecuredJson<T> unsecureJsonToObject(SecuredJson securedJson) throws CryptoException {
try {
UnsecuredJson<String> unsecuredJson = this.unsecureJson(securedJson);
return new UnsecuredJson<>(new ObjectMapper().readerFor(getParameterClass()).readValue(unsecuredJson.getObject()), unsecuredJson.getClientKey());
} catch (IOException e) {
throw new CryptoException(e);
}
}
}
| 42.769231 | 229 | 0.827338 |
b0358def4b5f5a726d9543296ca439a61cd0d551 | 6,033 | package com.opcon.ui.views;
import android.content.Context;
import android.graphics.Color;
import android.support.annotation.ColorRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.opcon.R;
import com.opcon.ui.utils.NotifierConstantUtils;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Mahmut Taşkiran on 06/03/2017.
*/
public class VerticalPacketPickerView extends RecyclerView {
private PacketAdapter mAdapter;
private LinearLayoutManager mLayoutManager;
@Nullable private List<Integer> mPacketFilter;
public void setPacketFilter(List<Integer> filter) {
mPacketFilter = filter;
if (mAdapter != null) {
mAdapter.filterPackets(mPacketFilter);
}
}
public void showTitles(boolean showTitles) {
if (mAdapter != null) {
mAdapter.showTitles = showTitles;
mAdapter.notifyDataSetChanged();
}
}
public void setPacket(int packet) {
mAdapter.setComponent(packet);
mLayoutManager.scrollToPosition(mAdapter.findPosition(packet));
}
public interface SpecialPacketSelectListener {
void onSpecialPacketSelected(int id, String title);
}
public void setListener(SpecialPacketSelectListener l) {
mAdapter.setListener(l);
}
public void setForSender(boolean forSender) {
this.mAdapter.setForSender(forSender);
}
public VerticalPacketPickerView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
mLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
setLayoutManager(mLayoutManager);
mAdapter = new PacketAdapter(NotifierConstantUtils.getPackets());
setAdapter(mAdapter);
}
private static class PacketAdapter extends RecyclerView.Adapter<PacketAdapter.ComponentHolder> {
private int mSelectedPacket = -1;
private SpecialPacketSelectListener mListener;
List<NotifierConstantUtils.Component> mPackets;
List<NotifierConstantUtils.Component> mOPackets;
boolean mForSender;
boolean showTitles = true;
public void filterPackets(@Nullable List<Integer> f){
if (f == null ){
NotifierConstantUtils.Component component = mPackets.get(0);
mPackets = mOPackets;
mOPackets.remove(component);
mOPackets.add(0, component);
} else {
List<NotifierConstantUtils.Component> newPackets = new ArrayList<>();
if (mOPackets != null) {
for (NotifierConstantUtils.Component mPacket : mOPackets) {
if (f.contains(mPacket.uid)) {
newPackets.add(mPacket);
}
}
}
mPackets = newPackets;
}
notifyDataSetChanged();
}
public PacketAdapter(List<NotifierConstantUtils.Component> packets) {
mPackets = packets;
mOPackets = mPackets;
}
public void setForSender(boolean forSender) {
this.mForSender = forSender;
}
public void setComponent(int id) {
mSelectedPacket = id;
notifyDataSetChanged();
}
private int gc(Context c, @ColorRes int ccc) {
return c.getResources().getColor(ccc);
}
@Override public int getItemCount() {
return mPackets.size();
}
@Override public ComponentHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ComponentHolder(inflater.inflate(R.layout.row_occ, parent, false), this);
}
int findPosition(int id) {
for (int i = 0; i < mPackets.size(); i++) {
if (mPackets.get(i).uid == id) {
return i;
}
}
return 0;
}
@Override public void onBindViewHolder(ComponentHolder holder, int position) {
holder.withComponent(mPackets.get(position));
}
public void setListener(SpecialPacketSelectListener listener) {
this.mListener = listener;
}
public static class ComponentHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private CircleRelativeLayout mCrl;
private ImageView mIcon;
private TextView mDesc;
private PacketAdapter ref;
public ComponentHolder(View itemView, PacketAdapter ref) {
super(itemView);
this.ref = ref;
mCrl = (CircleRelativeLayout) itemView.findViewById(R.id.crl);
mIcon = (ImageView) itemView.findViewById(R.id.icon);
mDesc = (TextView) itemView.findViewById(R.id.title);
itemView.setOnClickListener(this);
}
public void withComponent(NotifierConstantUtils.Component component) {
mIcon.setImageResource(component.icon);
Context c = mDesc.getContext();
if (ref.showTitles) {
mDesc.setVisibility(VISIBLE);
mDesc.setText(NotifierConstantUtils.getPacketTitle(c, component.uid, ref.mForSender));
} else {
mDesc.setVisibility(GONE);
}
int color = NotifierConstantUtils.getPacketColor(component.uid);
if (component.uid == ref.mSelectedPacket) {
mCrl.setColor(ref.gc(c, R.color.white));
mCrl.setStrokeWidth(2);
mCrl.setStrokeColor(color);
mIcon.setColorFilter(color);
} else {
mCrl.setColor(color);
mCrl.setStrokeWidth(0);
mIcon.setColorFilter(Color.WHITE);
}
}
@Override
public void onClick(View v) {
int p = getAdapterPosition();
if (p == -1) return;
ref.mSelectedPacket = ref.mPackets.get(p).uid;
if (ref.mListener != null)
ref.mListener.onSpecialPacketSelected(ref.mSelectedPacket, NotifierConstantUtils.getPacketTitle(v.getContext(), ref.mSelectedPacket, ref.mForSender));
ref.notifyDataSetChanged();
}
}
}
}
| 30.469697 | 161 | 0.685231 |
2f2de6bd295b27745f2c17f4d84895be637b4caf | 22,386 | package mod.goony.entity;
import java.util.List;
import javax.annotation.Nullable;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import mod.goony.entity.EntityVicuna.EntityAIPanic;
import mod.goony.sounds.SoundEvents2;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityAgeable;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.ai.EntityAIAvoidEntity;
import net.minecraft.entity.ai.EntityAIBase;
import net.minecraft.entity.ai.EntityAIHurtByTarget;
import net.minecraft.entity.ai.EntityAILeapAtTarget;
import net.minecraft.entity.ai.EntityAIMate;
import net.minecraft.entity.ai.EntityAIOcelotAttack;
import net.minecraft.entity.ai.EntityAISwimming;
import net.minecraft.entity.ai.EntityAITargetNonTamed;
import net.minecraft.entity.ai.EntityAITempt;
import net.minecraft.entity.ai.EntityAIWanderAvoidWater;
import net.minecraft.entity.ai.EntityAIWatchClosest;
import net.minecraft.entity.ai.RandomPositionGenerator;
import net.minecraft.entity.monster.EntitySpider;
import net.minecraft.entity.passive.EntityAnimal;
import net.minecraft.entity.passive.EntityChicken;
import net.minecraft.entity.passive.EntityCow;
import net.minecraft.entity.passive.EntityLlama;
import net.minecraft.entity.passive.EntityPig;
import net.minecraft.entity.passive.EntityRabbit;
import net.minecraft.entity.passive.EntitySheep;
import net.minecraft.entity.passive.EntityTameable;
import net.minecraft.entity.passive.EntityWolf;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.pathfinding.Path;
import net.minecraft.pathfinding.PathNavigate;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EntitySelectors;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.SoundEvent;
import net.minecraft.util.datafix.DataFixer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.World;
import net.minecraft.world.storage.loot.LootTableList;
public class EntityPampasFox extends EntityTameable
{
public class AIAvoidEntity extends EntityAIBase {
public AIAvoidEntity(EntityPampasFox entityPampasFox, Class<EntityPuma> class1, float f, double d, double e) {
// TODO Auto-generated constructor stub
}
@Override
public boolean shouldExecute() {
// TODO Auto-generated method stub
return false;
}
}
public class AISpiderTarget extends EntityAIBase {
public AISpiderTarget(EntityPampasFox entityPuma, Class<EntityPlayer> class1) {
// TODO Auto-generated constructor stub
}
@Override
public boolean shouldExecute() {
// TODO Auto-generated method stub
return false;
}
}
private static final DataParameter<Integer> OCELOT_VARIANT = EntityDataManager.<Integer>createKey(EntityPampasFox.class, DataSerializers.VARINT);
private EntityAIAvoidEntity<EntityPlayer> avoidEntity;
/** The tempt AI task for this mob, used to prevent taming while it is fleeing. */
private EntityAITempt aiTempt;
public EntityPampasFox(World worldIn)
{
super(worldIn);
this.setSize(1.4F, 1.4F);
}
protected void initEntityAI()
{
this.tasks.addTask(4, new EntityAILeapAtTarget(this, 0.4F));
this.tasks.addTask(1, new EntityAIPanic(this, 2.0D));
this.tasks.addTask(1, new EntityAISwimming(this));
this.tasks.addTask(8, new EntityAIOcelotAttack(this));
this.tasks.addTask(12, new EntityPampasFox.AIAvoidEntity(this, EntityPuma.class, 8.0F, 2.2D, 2.2D));
this.tasks.addTask(9, new EntityAIMate(this, 0.8D));
this.tasks.addTask(10, new EntityAIWanderAvoidWater(this, 0.8D, 1.0000001E-5F));
this.tasks.addTask(11, new EntityAIWatchClosest(this, EntityPlayer.class, 10.0F));
this.targetTasks.addTask(1, new EntityAITargetNonTamed(this, EntityChicken.class, false, (Predicate)null));
this.targetTasks.addTask(1, new EntityAITargetNonTamed(this, EntityRabbit.class, false, (Predicate)null));
this.targetTasks.addTask(1, new EntityAITargetNonTamed(this, EntityGuineaPig.class, false, (Predicate)null));
this.targetTasks.addTask(1, new EntityAITargetNonTamed(this, EntityChinchilla.class, false, (Predicate)null));
this.targetTasks.addTask(1, new EntityAITargetNonTamed(this, EntityAndeanGoose.class, false, (Predicate)null));
}
protected void entityInit()
{
super.entityInit();
this.dataManager.register(OCELOT_VARIANT, Integer.valueOf(0));
}
public void updateAITasks()
{
if (this.getMoveHelper().isUpdating())
{
double d0 = this.getMoveHelper().getSpeed();
if (d0 == 0.6D)
{
this.setSneaking(true);
this.setSprinting(false);
}
else if (d0 == 1.33D)
{
this.setSneaking(false);
this.setSprinting(true);
}
else
{
this.setSneaking(false);
this.setSprinting(false);
}
}
else
{
this.setSneaking(false);
this.setSprinting(false);
}
}
/**
* Determines if an entity can be despawned, used on idle far away entities
*/
protected boolean canDespawn()
{
return !this.isTamed() && this.ticksExisted > 2400;
}
protected void applyEntityAttributes()
{
super.applyEntityAttributes();
this.getEntityAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(10.0D);
this.getEntityAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D);
}
public void fall(float distance, float damageMultiplier)
{
}
public static void registerFixesOcelot(DataFixer fixer)
{
EntityLiving.registerFixesMob(fixer, EntityPampasFox.class);
}
/**
* (abstract) Protected helper method to write subclass entity data to NBT.
*/
public void writeEntityToNBT(NBTTagCompound compound)
{
super.writeEntityToNBT(compound);
compound.setInteger("CatType", this.getTameSkin());
}
/**
* (abstract) Protected helper method to read subclass entity data from NBT.
*/
public void readEntityFromNBT(NBTTagCompound compound)
{
super.readEntityFromNBT(compound);
this.setTameSkin(compound.getInteger("CatType"));
}
@Nullable
protected SoundEvent getAmbientSound()
{
if (this.isTamed())
{
if (this.isInLove())
{
return SoundEvents.ENTITY_WOLF_AMBIENT;
}
else
{
return this.rand.nextInt(4) == 0 ? SoundEvents.ENTITY_WOLF_AMBIENT : SoundEvents.ENTITY_WOLF_AMBIENT;
}
}
else
{
return SoundEvents.ENTITY_WOLF_AMBIENT;
}
}
protected SoundEvent getHurtSound(DamageSource p_184601_1_)
{
return SoundEvents.ENTITY_WOLF_HURT;
}
protected SoundEvent getDeathSound()
{
return SoundEvents.ENTITY_WOLF_DEATH;
}
/**
* Returns the volume for the sounds this mob makes.
*/
protected float getSoundVolume()
{
return 0.4F;
}
public boolean attackEntityAsMob(Entity entityIn)
{
return entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), 8.0F);
}
/**
* Called when the entity is attacked.
*/
public boolean attackEntityFrom(DamageSource source, float amount)
{
if (this.isEntityInvulnerable(source))
{
return false;
}
else
{
if (this.aiSit != null)
{
this.aiSit.setSitting(false);
}
return super.attackEntityFrom(source, amount);
}
}
@Nullable
protected ResourceLocation getLootTable()
{
return LootTableList.ENTITIES_OCELOT;
}
public boolean processInteract(EntityPlayer player, EnumHand hand)
{
ItemStack itemstack = player.getHeldItem(hand);
if (this.isTamed())
{
if (this.isOwner(player) && !this.world.isRemote && !this.isBreedingItem(itemstack))
{
this.aiSit.setSitting(!this.isSitting());
}
}
else if ((this.aiTempt == null || this.aiTempt.isRunning()) && itemstack.getItem() == Items.FISH && player.getDistance(this) < 9.0D)
{
if (!player.capabilities.isCreativeMode)
{
itemstack.shrink(1);
}
if (!this.world.isRemote)
{
if (this.rand.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, player))
{
this.setTamedBy(player);
this.setTameSkin(1 + this.world.rand.nextInt(3));
this.playTameEffect(true);
this.aiSit.setSitting(true);
this.world.setEntityState(this, (byte)7);
}
else
{
this.playTameEffect(false);
this.world.setEntityState(this, (byte)6);
}
}
return true;
}
return super.processInteract(player, hand);
}
public EntityPampasFox createChild(EntityAgeable ageable)
{
EntityPampasFox entityocelot = new EntityPampasFox(this.world);
if (this.isTamed())
{
entityocelot.setOwnerId(this.getOwnerId());
entityocelot.setTamed(true);
entityocelot.setTameSkin(this.getTameSkin());
}
return entityocelot;
}
/**
* Checks if the parameter is an item which this animal can be fed to breed it (wheat, carrots or seeds depending on
* the animal type)
*/
public boolean isBreedingItem(ItemStack stack)
{
return stack.getItem() == Items.FISH;
}
/**
* Returns true if the mob is currently able to mate with the specified mob.
*/
public boolean canMateWith(EntityAnimal otherAnimal)
{
if (otherAnimal == this)
{
return false;
}
else if (!this.isTamed())
{
return false;
}
else if (!(otherAnimal instanceof EntityPampasFox))
{
return false;
}
else
{
EntityPampasFox entityocelot = (EntityPampasFox)otherAnimal;
if (!entityocelot.isTamed())
{
return false;
}
else
{
return this.isInLove() && entityocelot.isInLove();
}
}
}
public int getTameSkin()
{
return ((Integer)this.dataManager.get(OCELOT_VARIANT)).intValue();
}
public void setTameSkin(int skinId)
{
this.dataManager.set(OCELOT_VARIANT, Integer.valueOf(skinId));
}
/**
* Checks if the entity's current position is a valid location to spawn this entity.
*/
public boolean getCanSpawnHere()
{
return this.world.rand.nextInt(3) != 0;
}
/**
* Checks that the entity is not colliding with any blocks / liquids
*/
public boolean isNotColliding()
{
if (this.world.checkNoEntityCollision(this.getEntityBoundingBox(), this) && this.world.getCollisionBoxes(this, this.getEntityBoundingBox()).isEmpty() && !this.world.containsAnyLiquid(this.getEntityBoundingBox()))
{
BlockPos blockpos = new BlockPos(this.posX, this.getEntityBoundingBox().minY, this.posZ);
if (blockpos.getY() < this.world.getSeaLevel())
{
return false;
}
IBlockState iblockstate = this.world.getBlockState(blockpos.down());
Block block = iblockstate.getBlock();
if (block == Blocks.GRASS || block.isLeaves(iblockstate, this.world, blockpos.down()))
{
return true;
}
}
return false;
}
/**
* Get the name of this object. For players this returns their username
*/
public String getName()
{
if (this.hasCustomName())
{
return this.getCustomNameTag();
}
else
{
return this.isTamed() ? I18n.translateToLocal("entity.Cat.name") : super.getName();
}
}
protected void setupTamedAI()
{
if (this.avoidEntity == null)
{
this.avoidEntity = new EntityAIAvoidEntity<EntityPlayer>(this, EntityPlayer.class, 16.0F, 0.8D, 1.33D);
}
this.tasks.removeTask(this.avoidEntity);
if (!this.isTamed())
{
this.tasks.addTask(4, this.avoidEntity);
}
}
/**
* Called only once on an entity when first time spawned, via egg, mob spawner, natural spawning etc, but not called
* when entity is reloaded from nbt. Mainly used for initializing attributes and inventory
*/
@Nullable
public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, @Nullable IEntityLivingData livingdata)
{
livingdata = super.onInitialSpawn(difficulty, livingdata);
if (this.getTameSkin() == 0 && this.world.rand.nextInt(7) == 0)
{
for (int i = 0; i < 2; ++i)
{
EntityPampasFox entityocelot = new EntityPampasFox(this.world);
entityocelot.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotationYaw, 0.0F);
entityocelot.setGrowingAge(-24000);
this.world.spawnEntity(entityocelot);
}
}
return livingdata;
}
public float getGallopTicks() {
// TODO Auto-generated method stub
return 0;
}
public class EntityAIAvoidEntity<T extends Entity> extends EntityAIBase
{
private final Predicate<Entity> canBeSeenSelector;
/** The entity we are attached to */
protected EntityCreature entity;
private final double farSpeed;
private final double nearSpeed;
protected T closestLivingEntity;
private final float avoidDistance;
/** The PathEntity of our entity */
private Path entityPathEntity;
/** The PathNavigate of our entity */
private final PathNavigate entityPathNavigate;
/** Class of entity this behavior seeks to avoid */
private final Class<T> classToAvoid;
private final Predicate <? super T > avoidTargetSelector;
public EntityAIAvoidEntity(EntityCreature entityIn, Class<T> classToAvoidIn, float avoidDistanceIn, double farSpeedIn, double nearSpeedIn)
{
this(entityIn, classToAvoidIn, Predicates.alwaysTrue(), avoidDistanceIn, farSpeedIn, nearSpeedIn);
}
public EntityAIAvoidEntity(EntityCreature entityIn, Class<T> classToAvoidIn, Predicate <? super T > avoidTargetSelectorIn, float avoidDistanceIn, double farSpeedIn, double nearSpeedIn)
{
this.canBeSeenSelector = new Predicate<Entity>()
{
public boolean apply(@Nullable Entity p_apply_1_)
{
return p_apply_1_.isEntityAlive() && EntityAIAvoidEntity.this.entity.getEntitySenses().canSee(p_apply_1_) && !EntityAIAvoidEntity.this.entity.isOnSameTeam(p_apply_1_);
}
};
this.entity = entityIn;
this.classToAvoid = classToAvoidIn;
this.avoidTargetSelector = avoidTargetSelectorIn;
this.avoidDistance = avoidDistanceIn;
this.farSpeed = farSpeedIn;
this.nearSpeed = nearSpeedIn;
this.entityPathNavigate = entityIn.getNavigator();
this.setMutexBits(1);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
public boolean shouldExecute()
{
List<T> list = this.entity.world.<T>getEntitiesWithinAABB(this.classToAvoid, this.entity.getEntityBoundingBox().grow((double)this.avoidDistance, 3.0D, (double)this.avoidDistance), Predicates.and(EntitySelectors.CAN_AI_TARGET, this.canBeSeenSelector, this.avoidTargetSelector));
if (list.isEmpty())
{
return false;
}
else
{
this.closestLivingEntity = list.get(0);
Vec3d vec3d = RandomPositionGenerator.findRandomTargetBlockAwayFrom(this.entity, 16, 7, new Vec3d(this.closestLivingEntity.posX, this.closestLivingEntity.posY, this.closestLivingEntity.posZ));
if (vec3d == null)
{
return false;
}
else if (this.closestLivingEntity.getDistanceSq(vec3d.x, vec3d.y, vec3d.z) < this.closestLivingEntity.getDistance(this.entity))
{
return false;
}
else
{
this.entityPathEntity = this.entityPathNavigate.getPathToXYZ(vec3d.x, vec3d.y, vec3d.z);
return this.entityPathEntity != null;
}
}
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean shouldContinueExecuting()
{
return !this.entityPathNavigate.noPath();
}
/**
* Execute a one shot task or start executing a continuous task
*/
public void startExecuting()
{
this.entityPathNavigate.setPath(this.entityPathEntity, this.farSpeed);
}
/**
* Reset the task's internal state. Called when this task is interrupted by another one
*/
public void resetTask()
{
this.closestLivingEntity = null;
}
/**
* Keep ticking a continuous task that has already been started
*/
public void updateTask()
{
if (this.entity.getDistance(this.closestLivingEntity) < 49.0D)
{
this.entity.getNavigator().setSpeed(this.nearSpeed);
}
else
{
this.entity.getNavigator().setSpeed(this.farSpeed);
}
}
}
public class EntityAIPanic extends EntityAIBase
{
protected final EntityCreature creature;
protected double speed;
protected double randPosX;
protected double randPosY;
protected double randPosZ;
public EntityAIPanic(EntityCreature creature, double speedIn)
{
this.creature = creature;
this.speed = speedIn;
this.setMutexBits(1);
}
/**
* Returns whether the EntityAIBase should begin execution.
*/
public boolean shouldExecute()
{
if (this.creature.getRevengeTarget() == null && !this.creature.isBurning())
{
return false;
}
else
{
if (this.creature.isBurning())
{
BlockPos blockpos = this.getRandPos(this.creature.world, this.creature, 5, 4);
if (blockpos != null)
{
this.randPosX = (double)blockpos.getX();
this.randPosY = (double)blockpos.getY();
this.randPosZ = (double)blockpos.getZ();
return true;
}
}
return this.findRandomPosition();
}
}
protected boolean findRandomPosition()
{
Vec3d vec3d = RandomPositionGenerator.findRandomTarget(this.creature, 5, 4);
if (vec3d == null)
{
return false;
}
else
{
this.randPosX = vec3d.x;
this.randPosY = vec3d.y;
this.randPosZ = vec3d.z;
return true;
}
}
/**
* Execute a one shot task or start executing a continuous task
*/
public void startExecuting()
{
this.creature.getNavigator().tryMoveToXYZ(this.randPosX, this.randPosY, this.randPosZ, this.speed);
}
/**
* Returns whether an in-progress EntityAIBase should continue executing
*/
public boolean shouldContinueExecuting()
{
return !this.creature.getNavigator().noPath();
}
@Nullable
private BlockPos getRandPos(World worldIn, Entity entityIn, int horizontalRange, int verticalRange)
{
BlockPos blockpos = new BlockPos(entityIn);
int i = blockpos.getX();
int j = blockpos.getY();
int k = blockpos.getZ();
float f = (float)(horizontalRange * horizontalRange * verticalRange * 2);
BlockPos blockpos1 = null;
BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos();
for (int l = i - horizontalRange; l <= i + horizontalRange; ++l)
{
for (int i1 = j - verticalRange; i1 <= j + verticalRange; ++i1)
{
for (int j1 = k - horizontalRange; j1 <= k + horizontalRange; ++j1)
{
blockpos$mutableblockpos.setPos(l, i1, j1);
IBlockState iblockstate = worldIn.getBlockState(blockpos$mutableblockpos);
if (iblockstate.getMaterial() == Material.WATER)
{
float f1 = (float)((l - i) * (l - i) + (i1 - j) * (i1 - j) + (j1 - k) * (j1 - k));
if (f1 < f)
{
f = f1;
blockpos1 = new BlockPos(blockpos$mutableblockpos);
}
}
}
}
}
return blockpos1;
}
}
} | 32.256484 | 286 | 0.620298 |
6901feface34145a83dfdefaa071234bb76d799a | 984 | package org.mirko.cache.example.service;
import org.mirko.cache.example.dao.NotFoundException;
import org.mirko.cache.example.model.User;
import java.util.List;
/**
* Service layer for CRUD operations around a User
*/
public interface UserServices {
/**
* Save a user if the id is specified and exist, otherwise insert a new one
*
* @param user the user
*/
void save(User user);
/**
* Get a user from Id
*
* @param id the user id
* @return the user or null if nothing is found
*/
User findById(long id) throws NotFoundException;
/**
* Get all the user in the database
*
* @return the user list
*/
List<User> getAll();
/**
* Delete a user from the database
*
* @param id the user id
* @throws NotFoundException if the id doesn't exist in the database
*/
void delete(long id) throws NotFoundException;
/**
* Generate and save a user for each line in names.txt
*/
void loadUsers();
} | 21.391304 | 77 | 0.651423 |
5df3ce5fbc694184cc571876536d19b4a474b2a9 | 19,807 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.yarn.server.resourcemanager.recovery.records
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|recovery
operator|.
name|records
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
operator|.
name|Public
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceStability
operator|.
name|Unstable
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|Credentials
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ApplicationAttemptId
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|Container
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ContainerExitStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|FinalApplicationStatus
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|api
operator|.
name|records
operator|.
name|ResourceInformation
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|proto
operator|.
name|YarnServerResourceManagerRecoveryProtos
operator|.
name|ApplicationAttemptStateDataProto
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|RMServerUtils
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|server
operator|.
name|resourcemanager
operator|.
name|rmapp
operator|.
name|attempt
operator|.
name|RMAppAttemptState
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|yarn
operator|.
name|util
operator|.
name|Records
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Map
import|;
end_import
begin_comment
comment|/* * Contains the state data that needs to be persisted for an ApplicationAttempt */
end_comment
begin_class
annotation|@
name|Public
annotation|@
name|Unstable
DECL|class|ApplicationAttemptStateData
specifier|public
specifier|abstract
class|class
name|ApplicationAttemptStateData
block|{
DECL|method|newInstance ( ApplicationAttemptId attemptId, Container container, Credentials attemptTokens, long startTime, RMAppAttemptState finalState, String finalTrackingUrl, String diagnostics, FinalApplicationStatus amUnregisteredFinalStatus, int exitStatus, long finishTime, Map<String, Long> resourceSecondsMap, Map<String, Long> preemptedResourceSecondsMap)
specifier|public
specifier|static
name|ApplicationAttemptStateData
name|newInstance
parameter_list|(
name|ApplicationAttemptId
name|attemptId
parameter_list|,
name|Container
name|container
parameter_list|,
name|Credentials
name|attemptTokens
parameter_list|,
name|long
name|startTime
parameter_list|,
name|RMAppAttemptState
name|finalState
parameter_list|,
name|String
name|finalTrackingUrl
parameter_list|,
name|String
name|diagnostics
parameter_list|,
name|FinalApplicationStatus
name|amUnregisteredFinalStatus
parameter_list|,
name|int
name|exitStatus
parameter_list|,
name|long
name|finishTime
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|resourceSecondsMap
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|preemptedResourceSecondsMap
parameter_list|)
block|{
name|ApplicationAttemptStateData
name|attemptStateData
init|=
name|Records
operator|.
name|newRecord
argument_list|(
name|ApplicationAttemptStateData
operator|.
name|class
argument_list|)
decl_stmt|;
name|attemptStateData
operator|.
name|setAttemptId
argument_list|(
name|attemptId
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setMasterContainer
argument_list|(
name|container
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setAppAttemptTokens
argument_list|(
name|attemptTokens
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setState
argument_list|(
name|finalState
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setFinalTrackingUrl
argument_list|(
name|finalTrackingUrl
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setDiagnostics
argument_list|(
name|diagnostics
operator|==
literal|null
condition|?
literal|""
else|:
name|diagnostics
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setStartTime
argument_list|(
name|startTime
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setFinalApplicationStatus
argument_list|(
name|amUnregisteredFinalStatus
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setAMContainerExitStatus
argument_list|(
name|exitStatus
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setFinishTime
argument_list|(
name|finishTime
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setMemorySeconds
argument_list|(
name|RMServerUtils
operator|.
name|getOrDefault
argument_list|(
name|resourceSecondsMap
argument_list|,
name|ResourceInformation
operator|.
name|MEMORY_MB
operator|.
name|getName
argument_list|()
argument_list|,
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setVcoreSeconds
argument_list|(
name|RMServerUtils
operator|.
name|getOrDefault
argument_list|(
name|resourceSecondsMap
argument_list|,
name|ResourceInformation
operator|.
name|VCORES
operator|.
name|getName
argument_list|()
argument_list|,
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setPreemptedMemorySeconds
argument_list|(
name|RMServerUtils
operator|.
name|getOrDefault
argument_list|(
name|preemptedResourceSecondsMap
argument_list|,
name|ResourceInformation
operator|.
name|MEMORY_MB
operator|.
name|getName
argument_list|()
argument_list|,
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setPreemptedVcoreSeconds
argument_list|(
name|RMServerUtils
operator|.
name|getOrDefault
argument_list|(
name|preemptedResourceSecondsMap
argument_list|,
name|ResourceInformation
operator|.
name|VCORES
operator|.
name|getName
argument_list|()
argument_list|,
literal|0L
argument_list|)
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setResourceSecondsMap
argument_list|(
name|resourceSecondsMap
argument_list|)
expr_stmt|;
name|attemptStateData
operator|.
name|setPreemptedResourceSecondsMap
argument_list|(
name|preemptedResourceSecondsMap
argument_list|)
expr_stmt|;
return|return
name|attemptStateData
return|;
block|}
DECL|method|newInstance ( ApplicationAttemptId attemptId, Container masterContainer, Credentials attemptTokens, long startTime, Map<String, Long> resourceSeondsMap, Map<String, Long> preemptedResourceSecondsMap)
specifier|public
specifier|static
name|ApplicationAttemptStateData
name|newInstance
parameter_list|(
name|ApplicationAttemptId
name|attemptId
parameter_list|,
name|Container
name|masterContainer
parameter_list|,
name|Credentials
name|attemptTokens
parameter_list|,
name|long
name|startTime
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|resourceSeondsMap
parameter_list|,
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|preemptedResourceSecondsMap
parameter_list|)
block|{
return|return
name|newInstance
argument_list|(
name|attemptId
argument_list|,
name|masterContainer
argument_list|,
name|attemptTokens
argument_list|,
name|startTime
argument_list|,
literal|null
argument_list|,
literal|"N/A"
argument_list|,
literal|""
argument_list|,
literal|null
argument_list|,
name|ContainerExitStatus
operator|.
name|INVALID
argument_list|,
literal|0
argument_list|,
name|resourceSeondsMap
argument_list|,
name|preemptedResourceSecondsMap
argument_list|)
return|;
block|}
DECL|method|getProto ()
specifier|public
specifier|abstract
name|ApplicationAttemptStateDataProto
name|getProto
parameter_list|()
function_decl|;
comment|/** * The ApplicationAttemptId for the application attempt * @return ApplicationAttemptId for the application attempt */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getAttemptId ()
specifier|public
specifier|abstract
name|ApplicationAttemptId
name|getAttemptId
parameter_list|()
function_decl|;
DECL|method|setAttemptId (ApplicationAttemptId attemptId)
specifier|public
specifier|abstract
name|void
name|setAttemptId
parameter_list|(
name|ApplicationAttemptId
name|attemptId
parameter_list|)
function_decl|;
comment|/* * The master container running the application attempt * @return Container that hosts the attempt */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getMasterContainer ()
specifier|public
specifier|abstract
name|Container
name|getMasterContainer
parameter_list|()
function_decl|;
DECL|method|setMasterContainer (Container container)
specifier|public
specifier|abstract
name|void
name|setMasterContainer
parameter_list|(
name|Container
name|container
parameter_list|)
function_decl|;
comment|/** * The application attempt tokens that belong to this attempt * @return The application attempt tokens that belong to this attempt */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getAppAttemptTokens ()
specifier|public
specifier|abstract
name|Credentials
name|getAppAttemptTokens
parameter_list|()
function_decl|;
DECL|method|setAppAttemptTokens (Credentials attemptTokens)
specifier|public
specifier|abstract
name|void
name|setAppAttemptTokens
parameter_list|(
name|Credentials
name|attemptTokens
parameter_list|)
function_decl|;
comment|/** * Get the final state of the application attempt. * @return the final state of the application attempt. */
DECL|method|getState ()
specifier|public
specifier|abstract
name|RMAppAttemptState
name|getState
parameter_list|()
function_decl|;
DECL|method|setState (RMAppAttemptState state)
specifier|public
specifier|abstract
name|void
name|setState
parameter_list|(
name|RMAppAttemptState
name|state
parameter_list|)
function_decl|;
comment|/** * Get the original not-proxied<em>final tracking url</em> for the * application. This is intended to only be used by the proxy itself. * * @return the original not-proxied<em>final tracking url</em> for the * application */
DECL|method|getFinalTrackingUrl ()
specifier|public
specifier|abstract
name|String
name|getFinalTrackingUrl
parameter_list|()
function_decl|;
comment|/** * Set the final tracking Url of the AM. * @param url */
DECL|method|setFinalTrackingUrl (String url)
specifier|public
specifier|abstract
name|void
name|setFinalTrackingUrl
parameter_list|(
name|String
name|url
parameter_list|)
function_decl|;
comment|/** * Get the<em>diagnositic information</em> of the attempt * @return<em>diagnositic information</em> of the attempt */
DECL|method|getDiagnostics ()
specifier|public
specifier|abstract
name|String
name|getDiagnostics
parameter_list|()
function_decl|;
DECL|method|setDiagnostics (String diagnostics)
specifier|public
specifier|abstract
name|void
name|setDiagnostics
parameter_list|(
name|String
name|diagnostics
parameter_list|)
function_decl|;
comment|/** * Get the<em>start time</em> of the application. * @return<em>start time</em> of the application */
DECL|method|getStartTime ()
specifier|public
specifier|abstract
name|long
name|getStartTime
parameter_list|()
function_decl|;
DECL|method|setStartTime (long startTime)
specifier|public
specifier|abstract
name|void
name|setStartTime
parameter_list|(
name|long
name|startTime
parameter_list|)
function_decl|;
comment|/** * Get the<em>final finish status</em> of the application. * @return<em>final finish status</em> of the application */
DECL|method|getFinalApplicationStatus ()
specifier|public
specifier|abstract
name|FinalApplicationStatus
name|getFinalApplicationStatus
parameter_list|()
function_decl|;
DECL|method|setFinalApplicationStatus ( FinalApplicationStatus finishState)
specifier|public
specifier|abstract
name|void
name|setFinalApplicationStatus
parameter_list|(
name|FinalApplicationStatus
name|finishState
parameter_list|)
function_decl|;
DECL|method|getAMContainerExitStatus ()
specifier|public
specifier|abstract
name|int
name|getAMContainerExitStatus
parameter_list|()
function_decl|;
DECL|method|setAMContainerExitStatus (int exitStatus)
specifier|public
specifier|abstract
name|void
name|setAMContainerExitStatus
parameter_list|(
name|int
name|exitStatus
parameter_list|)
function_decl|;
comment|/** * Get the<em>finish time</em> of the application attempt. * @return<em>finish time</em> of the application attempt */
DECL|method|getFinishTime ()
specifier|public
specifier|abstract
name|long
name|getFinishTime
parameter_list|()
function_decl|;
DECL|method|setFinishTime (long finishTime)
specifier|public
specifier|abstract
name|void
name|setFinishTime
parameter_list|(
name|long
name|finishTime
parameter_list|)
function_decl|;
comment|/** * Get the<em>memory seconds</em> (in MB seconds) of the application. * @return<em>memory seconds</em> (in MB seconds) of the application */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getMemorySeconds ()
specifier|public
specifier|abstract
name|long
name|getMemorySeconds
parameter_list|()
function_decl|;
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|setMemorySeconds (long memorySeconds)
specifier|public
specifier|abstract
name|void
name|setMemorySeconds
parameter_list|(
name|long
name|memorySeconds
parameter_list|)
function_decl|;
comment|/** * Get the<em>vcore seconds</em> of the application. * @return<em>vcore seconds</em> of the application */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getVcoreSeconds ()
specifier|public
specifier|abstract
name|long
name|getVcoreSeconds
parameter_list|()
function_decl|;
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|setVcoreSeconds (long vcoreSeconds)
specifier|public
specifier|abstract
name|void
name|setVcoreSeconds
parameter_list|(
name|long
name|vcoreSeconds
parameter_list|)
function_decl|;
comment|/** * Get the<em>preempted memory seconds</em> * (in MB seconds) of the application. * @return<em>preempted memory seconds</em> * (in MB seconds) of the application */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getPreemptedMemorySeconds ()
specifier|public
specifier|abstract
name|long
name|getPreemptedMemorySeconds
parameter_list|()
function_decl|;
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|setPreemptedMemorySeconds (long memorySeconds)
specifier|public
specifier|abstract
name|void
name|setPreemptedMemorySeconds
parameter_list|(
name|long
name|memorySeconds
parameter_list|)
function_decl|;
comment|/** * Get the<em>preempted vcore seconds</em> * of the application. * @return<em>preempted vcore seconds</em> * of the application */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getPreemptedVcoreSeconds ()
specifier|public
specifier|abstract
name|long
name|getPreemptedVcoreSeconds
parameter_list|()
function_decl|;
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|setPreemptedVcoreSeconds (long vcoreSeconds)
specifier|public
specifier|abstract
name|void
name|setPreemptedVcoreSeconds
parameter_list|(
name|long
name|vcoreSeconds
parameter_list|)
function_decl|;
comment|/** * Get the aggregated number of resources preempted that the application has * allocated times the number of seconds the application has been running. * * @return map containing the resource name and aggregated preempted * resource-seconds */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getResourceSecondsMap ()
specifier|public
specifier|abstract
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|getResourceSecondsMap
parameter_list|()
function_decl|;
comment|/** * Set the aggregated number of resources that the application has * allocated times the number of seconds the application has been running. * * @param resourceSecondsMap map containing the resource name and aggregated * resource-seconds */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|setResourceSecondsMap ( Map<String, Long> resourceSecondsMap)
specifier|public
specifier|abstract
name|void
name|setResourceSecondsMap
parameter_list|(
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|resourceSecondsMap
parameter_list|)
function_decl|;
comment|/** * Get the aggregated number of resources preempted that the application has * allocated times the number of seconds the application has been running. * * @return map containing the resource name and aggregated preempted * resource-seconds */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|getPreemptedResourceSecondsMap ()
specifier|public
specifier|abstract
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|getPreemptedResourceSecondsMap
parameter_list|()
function_decl|;
comment|/** * Set the aggregated number of resources preempted that the application has * allocated times the number of seconds the application has been running. * * @param preemptedResourceSecondsMap map containing the resource name and * aggregated preempted resource-seconds */
annotation|@
name|Public
annotation|@
name|Unstable
DECL|method|setPreemptedResourceSecondsMap ( Map<String, Long> preemptedResourceSecondsMap)
specifier|public
specifier|abstract
name|void
name|setPreemptedResourceSecondsMap
parameter_list|(
name|Map
argument_list|<
name|String
argument_list|,
name|Long
argument_list|>
name|preemptedResourceSecondsMap
parameter_list|)
function_decl|;
block|}
end_class
end_unit
| 20.783841 | 814 | 0.812692 |
184f7443f45a6bf9f200d011b395bafb9f04a294 | 3,174 | package com.horowitz.mickey;
import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.io.IOException;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import com.horowitz.commons.Settings;
public class ImageLocator extends JPanel {
private Settings _settings;
private ScreenScanner _scanner;
private MouseRobot _mouse;
private JTextArea _console;
private JPanel _buttonsPanel;
public ImageLocator() {
super();
_buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
setLayout(new BorderLayout());
add(_buttonsPanel);
_console = new JTextArea(5, 20);
add(new JScrollPane(_console), BorderLayout.SOUTH);
_settings = Settings.createSettings("mickey.settings");
_scanner = new ScreenScanner(_settings);
try {
_mouse = new MouseRobot();
} catch (AWTException e) {
}
// registerImageButton("Bobby2.bmp");
// registerImageButton("Mahatma2.bmp");
// registerImageButton("George2.bmp");
// registerImageButton("Otto2.bmp");
// registerImageButton("Jules2.bmp");
// registerImageButton("Sam2.bmp");
// registerImageButton("Alan2.bmp");
// registerImageButton("Wolfgang2.bmp");
// registerImageButton("Mizuki2.bmp");
// registerImageButton("Lucy2.bmp");
// registerImageButton("Giovanni2.bmp");
// registerImageButton("Ethan2.bmp");
// registerImageButton("int/brCorner.bmp");
// registerImageButton("loginFB.bmp");
registerImageButton("int/Del.bmp");
registerImageButton("int/brEdge.bmp");
//registerImageButton("publish3.bmp");
}
private void registerImageButton(final String imageName) {
JButton button = new JButton(new AbstractAction(imageName) {
@Override
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
locate(imageName);
}
}).start();
}
});
_buttonsPanel.add(button);
}
private void locate(String imageName) {
try {
Pixel p = _scanner.generateImageData(imageName).findImage(new Rectangle(0, 0, 1000, 800));
if (p != null) {
System.err.println("Found it " + p);
_console.append("Found it " + p + "\n");
_mouse.savePosition();
_mouse.mouseMove(p);
_mouse.delay(2000);
_mouse.restorePosition();
} else {
_console.append("Coudn't find " + imageName + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} catch (RobotInterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Image Locator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ImageLocator il = new ImageLocator();
frame.getContentPane().add(il, BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
| 27.128205 | 96 | 0.665406 |
3df761d7121edd81b865cd57182c17087352428d | 440 | package io.github.thanktoken.core.api.validate;
import io.github.thanktoken.core.api.validate.failure.ThankValidationFailure;
/**
* Interface for an object {@link #add(ThankValidationFailure) collecting} {@link ThankValidationFailure}s.
*
* @since 1.0.0
*/
public interface ThankValidationFailureReceiver {
/**
* @param failure the {@link ThankValidationFailure} to receive.
*/
void add(ThankValidationFailure failure);
}
| 24.444444 | 107 | 0.756818 |
5270d8687563edfa0bdd414023ee2669a9b738d2 | 593 | package com.googlecode.objectify.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* <p>When placed on an entity field of type Key, the key will be used as the parent
* ancestor for entity grouping.</p>
*
* <p>This annotation can only be placed on a single Key field within each entity.</p>
*
* @author Jeff Schnitzer <jeff@infohazard.org>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Parent
{
} | 29.65 | 87 | 0.738617 |
55d385ff69bf74fa12ecd6ac9da22a0cf07fde2b | 594 | package com.zhazhapan.demo.netty.codec.jackson;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
/**
* @author pantao
* @since 2018/6/5
*/
public class JacksonClientHandlerInitializer extends ChannelInitializer<Channel> {
@Override
protected void initChannel(Channel ch) {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new JacksonDecoder<JacksonBean>(JacksonBean.class));
pipeline.addLast(new JacksonEncoder());
pipeline.addLast(new JacksonClientHandler());
}
}
| 28.285714 | 82 | 0.740741 |
af0dbd2c23d429b617f316788f06420feb0951b4 | 9,034 | /******************************************************************************
* 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.exactpro.sf.configuration.dictionary;
import static com.exactpro.sf.common.messages.structures.StructureUtils.getAttributeValue;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.exactpro.sf.common.messages.structures.IDictionaryStructure;
import com.exactpro.sf.common.messages.structures.IFieldStructure;
import com.exactpro.sf.common.messages.structures.IMessageStructure;
import com.exactpro.sf.configuration.dictionary.converter.SailfishDictionaryToQuckfixjConverter;
import com.exactpro.sf.configuration.dictionary.interfaces.IDictionaryValidator;
import com.exactpro.sf.services.fix.FixMessageHelper;
import com.exactpro.sf.util.AbstractTest;
public class SfDictionaryConverterTest extends AbstractTest {
private static IDictionaryStructure dictionary;
private IDictionaryStructure newSfDictionary;
private static IDictionaryValidator dictionaryValidator;
private static SailfishDictionaryToQuckfixjConverter converter;
private static Transformer transformer;
private static final TransformerFactory transformerFactory = TransformerFactory.newInstance();
private static final Logger logger = LoggerFactory.getLogger(SfDictionaryConverterTest.class);
private static final String fileName = "FIX50.CONVERTER.TEST.xml";
private static final String outputFolder = "testConvert";
private final List<String> entityTypes = new ArrayList<>(Arrays.asList(FixMessageHelper.MESSAGE_ENTITY,
FixMessageHelper.HEADER_ENTITY, FixMessageHelper.TRAILER_ENTITY));
@BeforeClass
public static void initClass() {
ClassLoader classLoader = SfDictionaryConverterTest.class.getClassLoader();
try (InputStream in = classLoader.getResourceAsStream("fix/qfj2dict.xsl");
InputStream inTypes = classLoader.getResourceAsStream("fix/types.xml")) {
dictionaryValidator = new FullFIXDictionaryValidatorFactory().createDictionaryValidator();
converter = new SailfishDictionaryToQuckfixjConverter();
File xsl = new File(outputFolder, "qfj2dict.xsl");
File types = new File("types.xml");
try (OutputStream out = FileUtils.openOutputStream(xsl);
OutputStream outTypes = FileUtils.openOutputStream(types)) {
IOUtils.copy(in, FileUtils.openOutputStream(xsl));
IOUtils.copy(inTypes, FileUtils.openOutputStream(types));
}
try (InputStream inXsl = new FileInputStream(xsl)) {
transformer = transformerFactory.newTransformer(new StreamSource(inXsl));
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
Assert.fail(e.getMessage());
}
}
@Test
public void testConvert() throws Exception {
try {
try (InputStream in = getClass().getClassLoader().getResourceAsStream("dictionary/" + fileName);
InputStream inConverter = SailfishDictionaryToQuckfixjConverter.class.getClassLoader()
.getResourceAsStream("dictionary/" + fileName)) {
dictionary = loadMessageDictionary(in);
converter.convertToQuickFixJ(inConverter, outputFolder);
}
String sessionDictionary = new File(
outputFolder, "FIXT11.xml").getAbsolutePath();
transformer.setParameter("sessionDictionary", sessionDictionary);
String pathToNewSfDict = outputFolder + File.separator + fileName;
try (InputStream in = new FileInputStream(
outputFolder + File.separator + "FIX50.xml");
OutputStream out = FileUtils.openOutputStream(new File(pathToNewSfDict))) {
StreamResult result = new StreamResult(out);
transformer.transform(new StreamSource(in), result);
}
try (InputStream in = new FileInputStream(pathToNewSfDict)) {
newSfDictionary = loadMessageDictionary(in);
}
List<DictionaryValidationError> errors = dictionaryValidator.validate(newSfDictionary, true, null);
Assert.assertEquals(0, errors.size());
for(IMessageStructure message : dictionary.getMessages().values()) {
if(entityTypes.contains(getAttributeValue(message, FixMessageHelper.ATTRIBUTE_ENTITY_TYPE))) {
assertEqualsMessage(message, newSfDictionary.getMessages().get(message.getName()));
}
}
for(IMessageStructure complexMessage : newSfDictionary.getMessages().values()) {
if(!entityTypes.contains(getAttributeValue(complexMessage, FixMessageHelper.ATTRIBUTE_ENTITY_TYPE))) {
assertEqualsMessage(complexMessage, dictionary.getMessages().get(complexMessage.getName()));
}
}
for(IFieldStructure field : newSfDictionary.getFields().values()) {
assertEqualsField(field, dictionary.getFields().get(field.getName()));
}
} finally {
File del = new File(outputFolder);
if(del.exists()) {
FileUtils.deleteDirectory(del);
}
File types = new File("types.xml");
if(types.exists()) {
types.delete();
}
}
}
private void assertEqualsField(IFieldStructure expected, IFieldStructure actual) {
Assert.assertEquals(expected.getName(), actual.getName());
Assert.assertEquals(expected.getJavaType().value(), actual.getJavaType().value());
Assert.assertEquals(expected.getAttributes().size(), actual.getAttributes().size());
for(String attrName : expected.getAttributes().keySet()) {
Assert.assertEquals(expected.getAttributes().get(attrName).getValue(),
actual.getAttributes().get(attrName).getValue());
}
Assert.assertEquals(expected.getValues().size(), actual.getValues().size());
if (expected.getValues() != null) {
Assert.assertEquals(expected.getValues().size(), actual.getValues().size());
for (String value : expected.getValues().keySet()) {
Assert.assertEquals(expected.getValues().get(value).getName(), actual.getValues().get(value).getName());
Assert.assertEquals(expected.getValues().get(value).getValue(),
actual.getValues().get(value).getValue());
}
}
}
private void assertEqualsMessage(IMessageStructure expected, IMessageStructure actual) {
Assert.assertEquals(expected.getName(), actual.getName());
Assert.assertEquals(expected.getAttributes().size(), actual.getAttributes().size());
for(String attrName : expected.getAttributes().keySet()) {
Assert.assertEquals(expected.getAttributes().get(attrName).getValue(),
actual.getAttributes().get(attrName).getValue());
}
Assert.assertEquals(expected.getFields().size(), actual.getFields().size());
for(String fieldName : expected.getFields().keySet()) {
assertEqualsMessageField(expected.getFields().get(fieldName), actual.getFields().get(fieldName));
}
}
private void assertEqualsMessageField(IFieldStructure expected, IFieldStructure actual) {
Assert.assertEquals(expected.getName(), actual.getName());
Assert.assertEquals(expected.getReferenceName(), actual.getReferenceName());
Assert.assertEquals(expected.getStructureType().name(), actual.getStructureType().name());
Assert.assertEquals(expected.isRequired(), actual.isRequired());
}
}
| 47.547368 | 120 | 0.67091 |
7a1682e757fa0b9122c3a9ba0397f26860dfd16d | 495 | package com.example.android.support.wearable.notifications;
import android.support.v4.app.NotificationCompat;
/**
* Base class for notification priority presets.
*/
public abstract class PriorityPreset extends NamedPreset {
public PriorityPreset(int nameResId) {
super(nameResId);
}
/** Apply the priority to a notification builder */
public abstract void apply(NotificationCompat.Builder builder,
NotificationCompat.WearableExtender wearableOptions);
}
| 29.117647 | 66 | 0.753535 |
9342af017c85d1018352be389912644bc859c172 | 14,518 | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.cloud.solutions.bqtodatadog.accumulator;
import static org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument;
import com.google.auto.value.AutoValue;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.flogger.GoogleLogger;
import java.io.Serializable;
import java.util.Iterator;
import javax.annotation.Nullable;
import org.apache.beam.sdk.coders.Coder;
import org.apache.beam.sdk.coders.KvCoder;
import org.apache.beam.sdk.state.BagState;
import org.apache.beam.sdk.state.CombiningState;
import org.apache.beam.sdk.state.StateSpec;
import org.apache.beam.sdk.state.StateSpecs;
import org.apache.beam.sdk.state.TimeDomain;
import org.apache.beam.sdk.state.Timer;
import org.apache.beam.sdk.state.TimerSpec;
import org.apache.beam.sdk.state.TimerSpecs;
import org.apache.beam.sdk.transforms.Combine;
import org.apache.beam.sdk.transforms.DoFn;
import org.apache.beam.sdk.transforms.PTransform;
import org.apache.beam.sdk.transforms.ParDo;
import org.apache.beam.sdk.transforms.windowing.BoundedWindow;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.sdk.values.PCollection;
import org.joda.time.Duration;
import org.joda.time.Instant;
/**
* Generic batching function that implements all the required functionality for batching.
*/
@AutoValue
public abstract class GroupByBatchSize<K, InputT, OutputT>
extends PTransform<PCollection<KV<K, InputT>>, PCollection<OutputT>> {
abstract BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> batchAccumulatorFactory();
@Nullable
abstract Duration maxBufferDuration();
public static <K, InputT, OutputT> GroupByBatchSize<K, InputT, OutputT> withAccumulator(
BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> accumulatorFactory) {
return new AutoValue_GroupByBatchSize.Builder<K, InputT, OutputT>()
.batchAccumulatorFactory(accumulatorFactory)
.build();
}
public GroupByBatchSize<K, InputT, OutputT> withMaxBufferDuration(Duration duration) {
checkArgument(
duration != null && duration.isLongerThan(Duration.ZERO),
"Provide non-zero buffer duration");
return toBuilder().maxBufferDuration(duration).build();
}
@AutoValue.Builder
public abstract static class Builder<K, InputT, OutputT> {
abstract Builder<K, InputT, OutputT> batchAccumulatorFactory(
BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> batchAccumulatorFactory);
abstract Builder<K, InputT, OutputT> maxBufferDuration(Duration maxBufferDuration);
abstract GroupByBatchSize<K, InputT, OutputT> build();
}
abstract Builder<K, InputT, OutputT> toBuilder();
@Override
public PCollection<OutputT> expand(PCollection<KV<K, InputT>> input) {
Duration allowedLateness = input.getWindowingStrategy().getAllowedLateness();
checkArgument(
input.getCoder() instanceof KvCoder,
"coder specified in the input PCollection is not a KvCoder");
KvCoder<K, InputT> inputCoder = (KvCoder<K, InputT>) input.getCoder();
Coder<InputT> valueCoder = inputCoder.getValueCoder();
return input.apply(
ParDo.of(
new BatchBySizeFn<>(
allowedLateness,
maxBufferDuration(),
valueCoder,
batchAccumulatorFactory())));
}
static class BatchBySizeFn<K, InputT, OutputT> extends DoFn<KV<K, InputT>, OutputT> {
private static final GoogleLogger logger = GoogleLogger.forEnclosingClass();
private static final String END_OF_WINDOW_ID = "endOFWindow";
private static final String END_OF_BUFFERING_ID = "endOfBuffering";
private static final String BATCH_ID = "batch";
private static final String NUM_ELEMENTS_IN_BATCH_ID = "numElementsInBatch";
private final Duration allowedLateness;
private final Duration maxBufferingDuration;
@TimerId(END_OF_WINDOW_ID)
private final TimerSpec windowTimer = TimerSpecs.timer(TimeDomain.EVENT_TIME);
@TimerId(END_OF_BUFFERING_ID)
private final TimerSpec bufferingTimer = TimerSpecs.timer(TimeDomain.PROCESSING_TIME);
@StateId(BATCH_ID)
private final StateSpec<BagState<InputT>> batchSpec;
@StateId(NUM_ELEMENTS_IN_BATCH_ID)
private final StateSpec<CombiningState<Long, long[], Long>> numElementsInBatchSpec;
private final BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> accumulatorFactory;
BatchBySizeFn(
Duration allowedLateness,
Duration maxBufferingDuration,
Coder<InputT> inputValueCoder,
BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> accumulatorFactory) {
this.allowedLateness = allowedLateness;
this.maxBufferingDuration = maxBufferingDuration;
this.batchSpec = StateSpecs.bag(inputValueCoder);
this.numElementsInBatchSpec =
StateSpecs.combining(
new Combine.BinaryCombineLongFn() {
@Override
public long identity() {
return 0L;
}
@Override
public long apply(long left, long right) {
return left + right;
}
});
this.accumulatorFactory = accumulatorFactory;
}
@ProcessElement
public void processElement(
@TimerId(END_OF_WINDOW_ID) Timer windowTimer,
@TimerId(END_OF_BUFFERING_ID) Timer bufferingTimer,
@StateId(BATCH_ID) BagState<InputT> buffer,
@StateId(NUM_ELEMENTS_IN_BATCH_ID) CombiningState<Long, long[], Long> numElementsInBatch,
@Element KV<K, InputT> element,
BoundedWindow window,
OutputReceiver<OutputT> receiver) {
Instant windowEnds = window.maxTimestamp().plus(allowedLateness);
logger.atFine().log(
"*** SET TIMER *** to point in time %s for window %s", windowEnds, window);
windowTimer.set(windowEnds);
logger.atFine().log("*** BATCH *** Add element for window %s", window);
buffer.add(element.getValue());
// Blind add is supported with combiningState
numElementsInBatch.add(1L);
long num = numElementsInBatch.read();
if (num == 1 && maxBufferingDuration != null) {
// This is the first element in batch. Start counting buffering time if a limit was
// set.
bufferingTimer.offset(maxBufferingDuration).setRelative();
}
BatchedElements<InputT, OutputT> batchedElements =
new BatchMaker<>(/*noUnbatched*/ false, accumulatorFactory).makeBatches(buffer);
if (!batchedElements.batches().isEmpty()) {
flushBatch(batchedElements, receiver, buffer, numElementsInBatch, bufferingTimer);
}
}
@OnTimer(END_OF_BUFFERING_ID)
public void onBufferingTimer(
OutputReceiver<OutputT> receiver,
@Timestamp Instant timestamp,
@StateId(BATCH_ID) BagState<InputT> buffer,
@StateId(NUM_ELEMENTS_IN_BATCH_ID) CombiningState<Long, long[], Long> numElementsInBatch,
@TimerId(END_OF_BUFFERING_ID) Timer bufferingTimer) {
logger.atFine().log(
"*** END OF BUFFERING *** for timer timestamp %s with buffering duration %s",
timestamp, maxBufferingDuration);
BatchedElements<InputT, OutputT> batchedElements =
new BatchMaker<>(/*noUnbatched=*/ true, accumulatorFactory).makeBatches(buffer);
flushBatch(batchedElements, receiver, buffer, numElementsInBatch, null);
}
@OnTimer(END_OF_WINDOW_ID)
public void onWindowTimer(
OutputReceiver<OutputT> receiver,
@Timestamp Instant timestamp,
@StateId(BATCH_ID) BagState<InputT> buffer,
@StateId(NUM_ELEMENTS_IN_BATCH_ID) CombiningState<Long, long[], Long> numElementsInBatch,
@TimerId(END_OF_BUFFERING_ID) Timer bufferingTimer,
BoundedWindow window) {
logger.atFine().log(
"*** END OF WINDOW *** for timer timestamp %s in windows %s",
timestamp, window.toString());
BatchedElements<InputT, OutputT> batchedElements =
new BatchMaker<>(/*noUnbatched=*/ true, accumulatorFactory).makeBatches(buffer);
flushBatch(batchedElements, receiver, buffer, numElementsInBatch, bufferingTimer);
}
private static class BatchMaker<InputT, OutputT> {
private final boolean noUnbatched;
private final BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> accumulatorFactory;
public BatchMaker(
boolean noUnbatched,
BatchAccumulator.BatchAccumulatorFactory<InputT, OutputT> accumulatorFactory) {
this.noUnbatched = noUnbatched;
this.accumulatorFactory = accumulatorFactory;
}
public BatchedElements<InputT, OutputT> makeBatches(BagState<InputT> buffer) {
ImmutableList.Builder<BatchAccumulator.Batch<OutputT>> batchBuilder =
ImmutableList.builder();
BatchAccumulator<InputT, OutputT> accumulator = accumulatorFactory.newAccumulator();
Iterable<InputT> unBatchedElements = buffer.read();
while (!Iterables.isEmpty(
unBatchedElements = accumulator.addAllElements(unBatchedElements))) {
batchBuilder.add(accumulator.makeBatch());
accumulator = accumulatorFactory.newAccumulator();
}
if (noUnbatched) {
batchBuilder.add(accumulator.makeBatch());
}
return BatchedElements.<InputT, OutputT>builder()
.batches(batchBuilder.build())
.unBatchedElements(ImmutableList.copyOf(unBatchedElements))
.build();
}
}
@AutoValue
abstract static class BatchedElements<InputT, OutputT> {
abstract ImmutableList<BatchAccumulator.Batch<OutputT>> batches();
abstract ImmutableList<InputT> unBatchedElements();
public static <InputT, OutputT> Builder<InputT, OutputT> builder() {
return new AutoValue_GroupByBatchSize_BatchBySizeFn_BatchedElements.Builder<>();
}
@AutoValue.Builder
abstract static class Builder<InputT, OutputT> {
public abstract Builder<InputT, OutputT> batches(
ImmutableList<BatchAccumulator.Batch<OutputT>> batches);
public abstract Builder<InputT, OutputT> unBatchedElements(
ImmutableList<InputT> unBatchedElements);
public abstract BatchedElements<InputT, OutputT> build();
}
}
// outputs the batch
private void flushBatch(
BatchedElements<InputT, OutputT> batchedElements,
OutputReceiver<OutputT> receiver,
BagState<InputT> buffer,
CombiningState<Long, long[], Long> numElementsInBatch,
@Nullable Timer bufferingTimer) {
batchedElements.batches().forEach(batch -> sendBatchAndLog(batch, receiver));
buffer.clear();
logger.atFine().log("*** BATCH *** clear");
batchedElements.unBatchedElements().forEach(buffer::add);
logger.atFine().log(
"*** ADDED unflushed elements: %s", batchedElements.unBatchedElements().size());
numElementsInBatch.clear();
numElementsInBatch.add((long) batchedElements.unBatchedElements().size());
// We might reach here due to batch size being reached or window expiration. Reset the
// buffering timer (if not null) since the state is empty now. It'll be extended again
// if a new element arrives prior to the expiration time set here.
if (bufferingTimer != null && maxBufferingDuration != null) {
bufferingTimer.offset(maxBufferingDuration).setRelative();
}
}
private static <OutputT> void sendBatchAndLog(
BatchAccumulator.Batch<OutputT> batch, OutputReceiver<OutputT> receiver) {
receiver.output(batch.get());
logger.atFine().log("**** Batched Report:%n%s", batch.report());
}
}
/**
* Provides mechanism to batch input data of type {@code <I>} using some business logic.
*
* @param <InputT> the type of input data type
* @param <OutputT> the type of output data type
*/
public static interface BatchAccumulator<InputT, OutputT> extends Serializable {
/**
* Offer one element to be added to the batch.
*
* @param element the element to be added.
* @return true if addition successful, false otherwise.
*/
boolean addElement(InputT element);
default ImmutableList<InputT> addAllElements(Iterable<InputT> elements) {
return addAllElements(elements.iterator());
}
/**
* Adds all elements in the Iterable to the accumulator.
*
* @param elements the elements to add to accumulator.
* @return List of elements that could not be added due to accumulator full.
*/
default ImmutableList<InputT> addAllElements(Iterator<InputT> elements) {
while (elements.hasNext()) {
InputT element = elements.next();
if (!addElement(element)) {
return ImmutableList.<InputT>builder().add(element).addAll(elements).build();
}
}
return ImmutableList.of();
}
/**
* Accumulator factory interface to instanciate new accumulator instances.
*/
interface BatchAccumulatorFactory<InputT, OutputT> extends Serializable {
BatchAccumulator<InputT, OutputT> newAccumulator();
}
/**
* Returns the accumulated elements as batch of type O.
*/
Batch<OutputT> makeBatch();
/**
* Provides interface to access attributes of the Batch and the batched data object.
*
* @param <T> the type of batched data object.
*/
interface Batch<T> {
/**
* Returns the batched elements.
*/
T get();
/**
* The number of elements in the batch.
*/
int elementsCount();
/**
* The serialized size of the batch.
*/
int serializedSize();
/**
* A printable report of statistics.
*/
String report();
}
}
} | 36.385965 | 104 | 0.693553 |
256a7b8268113c6cf75b6676303c2cd96df95893 | 427 | package hazelnut.core;
import org.jetbrains.annotations.NotNull;
public interface MessageChannel extends AutoCloseable {
@NotNull String channelId();
@Override
void close() throws Exception;
interface Inbound extends MessageChannel {}
interface Outbound extends MessageChannel {
void send(final @NotNull HazelnutMessage<?> message);
}
interface Duplex extends Outbound, Inbound {}
}
| 20.333333 | 61 | 0.730679 |
801f5b1100ce009e346ebdfb585f4e5557595003 | 13,038 | package org.deeplearning4j.examples.recurrent.character.melodl4j;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Track;
/*
* @author Donald A. Smith
*
* A NoteSequence is a sequence of notes played on a single track.
*
*/
public class NoteSequence implements Comparable<NoteSequence> {
private static boolean trace = false;
private long startTick;
private int trackNumber;
private int channel;
private List<Note> notes = new ArrayList<Note>();
private List<InstrumentChange> instrumentChanges = new ArrayList<InstrumentChange>();
private final int resolution;
private int instrument;
private double averageNoteDuration = -1;
public NoteSequence(long startTick, int track, int channel, int resolution) {
this.startTick = startTick;
this.trackNumber = track;
this.channel = channel;
this.resolution = resolution;
}
public int getResolution() {
return resolution;
}
public int getMaxRawNote() {
int max = Integer.MIN_VALUE;
for (Note note : getNotes()) {
int val = note.getRawNote();
if (val > max) {
max = val;
}
}
return max;
}
public double getAverageNoteDuration() {
if (averageNoteDuration < 0) {
averageNoteDuration = getAverageNoteDurationExpensive();
}
return averageNoteDuration;
}
public double getAverageNoteDurationExpensive() {
long sumDurations = 0;
int noteCount = 0;
for (Note note : getNotes()) {
noteCount++;
sumDurations += note.getDuration();
}
return noteCount == 0 ? 0 : (0.0 + sumDurations) / noteCount;
}
public int getMaxPitchGapAbsolute() {
int max = Integer.MIN_VALUE;
int lastPitch = Integer.MIN_VALUE;
for (Note note : getNotes()) {
int val = note.getRawNote();
if (lastPitch == Integer.MIN_VALUE) {
lastPitch = val;
continue;
}
int gap = Math.abs(val - lastPitch);
if (gap > max) {
max = gap;
}
lastPitch = val;
}
return max;
}
public int getMinRawNote() {
int min = Integer.MAX_VALUE;
for (Note note : getNotes()) {
int val = note.getRawNote();
if (val < min) {
min = val;
}
}
return min;
}
public boolean isValid() {
int min = getMinPitch();
int max = getMaxPitch();
if (min >= max || min < 0 || getMaxPitchGapAbsolute() > 16) {
return false;
}
return true;
}
public void addInstrumentChange(int instrumentNumber, long startTick) {
if (instrumentNumber == instrument) {
if (trace) {
System.out.println("Duplicate instrument change to " + Midi2MelodyStrings.programs[instrumentNumber]);
}
return;
}
if (trace) {
System.out.println("Adding instrument change for " + instrumentNumber
+ " (" + Midi2MelodyStrings.programs[instrumentNumber] + ") for channel " + channel + " at tick " + startTick);
}
instrumentChanges.add(new InstrumentChange(instrumentNumber, startTick, channel));
instrument = instrumentNumber;
}
public Sequence toSequence() throws InvalidMidiDataException {
Sequence sequence = new Sequence(Sequence.PPQ, resolution);
Track track = sequence.createTrack();
if (trace) {
System.out.println("Playing track " + trackNumber + ", channel " + channel);
}
for (InstrumentChange change : instrumentChanges) {
change.addMidiEvents(track);
}
for (Note note : notes) {
note.addMidiEvents(track);
}
return sequence;
}
public void play(Sequencer sequencer) throws MidiUnavailableException, InvalidMidiDataException {
Sequence sequence = toSequence();
sequencer.setSequence(sequence);
sequencer.setTickPosition(0);
sequencer.open();
sequencer.start();
}
public long getStartTick() {
return startTick;
}
public long getEndTick() {
return notes.get(notes.size() - 1).getEndTick();
}
public int getNumberOfDistinctPitches() {
int counts[] = new int[128];
int count = 0;
for (Note note : getNotes()) {
if (counts[note.getRawNote()] == 0) {
count++;
}
counts[note.getRawNote()]++;
}
if (count < 3) {
System.out.print(count + " ");
}
return count;
}
public long getDuration() {
return getEndTick() - getStartTick();
}
public double getProportionSilence() {
long totalDuration = getDuration();
long totalRests = 0;
Note lastNote = null;
for (Note note : notes) {
if (lastNote != null) {
totalRests += note.getStartTick() - lastNote.getEndTick();
}
lastNote = note;
}
return (0.0 + totalRests) / totalDuration;
}
public long getLongestNoteDuration() {
long longest = 0;
for (Note note : getNotes()) {
if (note.getDuration() > longest) {
longest = note.getDuration();
}
}
return longest;
}
public Iterable<Note> getNotes() {
final Iterator<Note> iterator = notes.iterator();
return new Iterable<Note>() {
@Override
public Iterator<Note> iterator() {
return iterator;
}
};
}
public long getShortetNoteDuration() {
long shortest = Long.MAX_VALUE;
for (Note note : getNotes()) {
long duration = note.getDuration();
if (duration > 0 && duration < shortest) {
shortest = note.getDuration();
}
}
return shortest;
}
public long getLongestRest() {
long longest = 0;
Note lastNote = notes.get(0);
for (Note note : notes) {
long rest = note.getStartTick() - lastNote.getEndTick();
if (rest > longest) {
longest = rest;
}
lastNote = note;
}
return longest;
}
public int getTrack() {
return trackNumber;
}
public int getChannel() {
return channel;
}
public void verifyMonotonicIncreasing() {
NoteOrInstrumentChange previous = null;
for (NoteOrInstrumentChange noteOrInstrumentChange : notes) {
if (previous != null) {
if (previous.getStartTick() > noteOrInstrumentChange.getStartTick()) {
System.err.println("Not monitonic: " + previous + " and " + noteOrInstrumentChange);
}
}
previous = noteOrInstrumentChange;
}
}
// Return count removed
public int removeAllButHigherOrLowerNotes(boolean higher) {
//throw new RuntimeException("Not implemented yet");
int countRemoved = 0;
Iterator<Note> iterator = notes.iterator();
while (iterator.hasNext()) {
Note note = iterator.next();
if (aHigherOrLowerPitchedNoteOverlapsThisNote(note, higher)) {
iterator.remove();
countRemoved++;
}
}
return countRemoved;
}
private boolean aHigherOrLowerPitchedNoteOverlapsThisNote(Note note1, boolean higher) {
for (Note note2 : getNotes()) {
if (note2.getStartTick() >= note1.getEndTick()) {
break;
}
if ((higher ? note2.getRawNote() > note1.getRawNote() : note2.getRawNote() < note1.getRawNote()) && ticksOverlapInTime(note1, note2)) {
return true;
}
}
return false;
}
private boolean ticksDontOverlapInTime(Note note1, Note note2) {
return note1.getEndTick() <= note2.getStartTick() || note2.getEndTick() <= note1.getStartTick();
}
private boolean ticksOverlapInTime(Note note1, Note note2) {
return !ticksDontOverlapInTime(note1, note2);
}
public int countOfNotesHavingPolyphony() {
verifyMonotonicIncreasing();
Set<Note> notesOn = new HashSet<Note>();
int count = 0;
for (Note note : getNotes()) {
Iterator<Note> iterator = notesOn.iterator();
while (iterator.hasNext()) {
Note onNote = iterator.next();
if (note.getStartTick() >= onNote.endTick()) {
iterator.remove();
} else {
count++;
}
}
notesOn.add(note);
}
return count;
}
@Override
public int compareTo(NoteSequence other) {
int diff = trackNumber - other.trackNumber;
if (diff != 0) {
return diff;
}
diff = channel - other.channel;
if (diff != 0) {
return diff;
}
long diffLong = startTick - other.startTick;
if (diffLong > 0) {
return 1;
}
if (diffLong < 0) {
return -1;
}
return 0;
}
public boolean equals(Object other) {
return compareTo((NoteSequence) other) == 0;
}
public void removeLeadingSilence() {
long firstRealNoteTick = getFirstRealNoteTick();
if (firstRealNoteTick >= 0) {
for (NoteOrInstrumentChange note : notes) {
if (note.getStartTick() >= firstRealNoteTick) {
note.setStartTick(1 + note.getStartTick() - firstRealNoteTick);
}
}
}
}
private long getFirstRealNoteTick() {
return notes.size() > 0 ? notes.get(0).getStartTick() : -1;
}
public void add(Note note) {
averageNoteDuration = -1;
notes.add(note);
}
public long getLastTick() {
return notes.isEmpty() ? 0L : notes.get(notes.size() - 1).getStartTick();
}
public void toString(StringBuilder sb, boolean verbose) {
sb.append("NoteSequence with track = " + trackNumber);
sb.append(", channel = " + channel);
sb.append(", noteCount = " + notes.size());
sb.append(", count of polyphonic notes = " + countOfNotesHavingPolyphony());
sb.append(", startTick = " + startTick);
sb.append(", and " + notes.size() + " notes");
if (verbose) {
for (NoteOrInstrumentChange note : notes) {
sb.append(" ");
sb.append(note);
sb.append("\n");
}
}
}
public int getMinPitch() {
int minPitch = Integer.MAX_VALUE;
for (Note note : notes) {
if (note.getRawNote() < minPitch) {
minPitch = note.getRawNote();
}
}
return minPitch;
}
public int getMaxPitch() {
int maxPitch = 0;
for (Note note : notes) {
if (note.getRawNote() > maxPitch) {
maxPitch = note.getRawNote();
}
}
return maxPitch;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
toString(sb, false);
return sb.toString();
}
public String toString(boolean verbose) {
StringBuilder sb = new StringBuilder();
toString(sb, verbose);
return sb.toString();
}
public int getLength() {
return notes.size();
}
public Note get(int i) {
return notes.get(i);
}
public int getLengthOfLongestSequenceOfRepeatedNotes() {
int count = 0;
int max = 0;
int lastRawNote = -1;
for (Note note : getNotes()) {
int rawNote = note.getRawNote();
if (rawNote == lastRawNote) {
count++;
if (count > max) {
max = count;
}
} else {
count = 0;
}
lastRawNote = rawNote;
}
return max;
}
public int getNumberOfRepeatedNotes() {
int count = 0;
int lastRawNote = -1;
for (Note note : getNotes()) {
int rawNote = note.getRawNote();
if (rawNote == lastRawNote) {
count++;
}
lastRawNote = rawNote;
}
return count;
}
public double getNumberOfNotes() {
return notes.size();
}
}
| 29.037862 | 147 | 0.540344 |
9c2beec0acddcbb3ab7d2cbfd117bfec500fd288 | 2,228 | package ftn.ktsnvt.culturalofferings.dto;
import java.util.Date;
import java.util.List;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Positive;
public class CommentDTO {
private Long id;
@NotBlank(message = "Comment text cannot be empty")
private String text;
private Date date;
private List<Long> imageIds;
@NotNull(message = "Cultural offering id must be provided")
@Positive(message = "Cultural offering id must be a positive number")
private Long culturalOfferingId;
@NotNull(message = "User id must be provided")
@Positive(message = "User id must be a positive number")
private Long userId;
public CommentDTO() {}
public CommentDTO(Long id, @NotBlank(message = "Comment text cannot be empty") String text, Date date, List<Long> images, @NotNull(message = "Cultural offering id must be provided") @Positive(message = "Cultural offering id must be a positive number") Long culturalOffering, @NotNull(message = "User id must be provided") @Positive(message = "User id must be a positive number") Long user) {
this.id = id;
this.text = text;
this.date = date;
this.imageIds = images;
this.culturalOfferingId = culturalOffering;
this.userId = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<Long> getImageIds() {
return imageIds;
}
public void setImageIds(List<Long> imageIds) {
this.imageIds = imageIds;
}
public Long getCulturalOfferingId() {
return culturalOfferingId;
}
public void setCulturalOfferingId(Long culturalOfferingId) {
this.culturalOfferingId = culturalOfferingId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
}
| 25.609195 | 395 | 0.655296 |
6f2b48388a8886acb99345b6dba8ae6019a066a0 | 3,689 | package net.silentchaos512.funores.lib;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.MobEntity;
import net.minecraft.entity.monster.EndermiteEntity;
import net.minecraft.item.Item;
import net.minecraft.tags.ITag;
import net.minecraft.util.RegistryKey;
import net.minecraft.world.World;
import net.minecraftforge.common.Tags;
import net.silentchaos512.funores.FunOres;
import net.silentchaos512.funores.block.LootDropOre;
import net.silentchaos512.funores.block.LootDropOreWithSpawn;
import net.silentchaos512.funores.config.Config;
import net.silentchaos512.lib.block.IBlockProvider;
import net.silentchaos512.utils.Lazy;
import javax.annotation.Nullable;
import java.util.Locale;
import java.util.function.Supplier;
public enum Ores implements IBlockProvider {
// Peaceful
BAT(EntityType.BAT),
CHICKEN(EntityType.CHICKEN),
COW(EntityType.COW),
PIG(EntityType.PIG),
RABBIT(EntityType.RABBIT),
SHEEP(EntityType.SHEEP),
SQUID(EntityType.SQUID),
// Fish
COD(EntityType.COD),
SALMON(EntityType.SALMON),
PUFFERFISH(EntityType.PUFFERFISH),
// Hostile
CREEPER(EntityType.CREEPER),
ENDERMAN(EntityType.ENDERMAN, World.OVERWORLD, () -> new LootDropOreWithSpawn(EntityType.ENDERMAN::create) {
@Nullable
@Override
public LivingEntity getBreakSpawn(BlockState state, World world) {
if (FunOres.RANDOM.nextFloat() < Config.COMMON.endermiteSpawnChance.get())
return new EndermiteEntity(EntityType.ENDERMITE, world);
return null;
}
}),
GUARDIAN(EntityType.GUARDIAN),
PHANTOM(EntityType.PHANTOM),
SKELETON(EntityType.SKELETON, World.OVERWORLD),
SLIME(EntityType.SLIME),
SPIDER(EntityType.SPIDER),
WITCH(EntityType.WITCH),
ZOMBIE(EntityType.ZOMBIE, World.OVERWORLD),
// Hostile (Nether)
BLAZE(EntityType.BLAZE, World.NETHER),
GHAST(EntityType.GHAST, World.NETHER),
MAGMA_CUBE(EntityType.MAGMA_CUBE, World.NETHER),
WITHER_SKELETON(EntityType.WITHER_SKELETON, World.NETHER),
PIGLIN(EntityType.PIGLIN, World.NETHER),
HOGLIN(EntityType.HOGLIN, World.NETHER);
private final EntityType<? extends MobEntity> entityType;
private final Lazy<LootDropOre> block;
private final RegistryKey<World> dimensionType;
private final ITag.INamedTag<Block> replacesBlock;
Ores(EntityType<? extends MobEntity> entityType) {
this(entityType, World.OVERWORLD, LootDropOre::new);
}
Ores(EntityType<? extends MobEntity> entityType, RegistryKey<World> dim) {
this(entityType, dim, LootDropOre::new);
}
Ores(EntityType<? extends MobEntity> entityType, RegistryKey<World> dim, Supplier<LootDropOre> blockFactory) {
this.block = Lazy.of(blockFactory);
this.dimensionType = dim;
this.replacesBlock = this.dimensionType == World.NETHER ? Tags.Blocks.NETHERRACK : Tags.Blocks.STONE;
this.entityType = entityType;
}
public EntityType<? extends MobEntity> getEntityType() {
return entityType;
}
public String getName() {
return name().toLowerCase(Locale.ROOT);
}
public String getBlockName() {
return getName() + "_ore";
}
public RegistryKey<World> getDimensionType() {
return dimensionType;
}
public ITag.INamedTag<Block> getReplacesBlock() {
return replacesBlock;
}
@Override
public Block asBlock() {
return block.get();
}
@Override
public Item asItem() {
return asBlock().asItem();
}
}
| 32.359649 | 114 | 0.714015 |
aeaa02085b79f4afce10beb88266748ebc4731ea | 5,561 | /*
* Copyright 2018 TWO SIGMA OPEN SOURCE, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.twosigma.beakerx.table;
import com.twosigma.beakerx.jvm.serialization.BeakerObjectConverter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.stream.Stream;
import static com.twosigma.beakerx.table.TableDisplay.LIST_OF_MAPS_SUBTYPE;
import static com.twosigma.beakerx.table.TableDisplay.PAGE_SIZE;
public class TableDisplayMapModel extends TableDisplayModel {
private Stream<Map<String, Object>> v;
private Iterator<Map<String, Object>> valuesIterator;
private BeakerObjectConverter serializer;
private List<Map<String, Object>> initValues = new ArrayList<>();
public TableDisplayMapModel(Stream<Map<String, Object>> v, BeakerObjectConverter serializer) {
this.v = v;
this.valuesIterator = v.iterator();
this.serializer = serializer;
this.values = new ArrayList<>();
this.columns = new ArrayList<>();
this.classes = new ArrayList<>();
this.subtype = LIST_OF_MAPS_SUBTYPE;
this.initValues = nextValuesPage();
createColumnNameAndType(initValues, serializer);
}
public void initValues() {
addToValues(buildValues(initValues));
initValues = null;
}
private List<Map<String, Object>> allValues() {
List<Map<String, Object>> list = new ArrayList<>();
while (valuesIterator.hasNext()) {
list.add(valuesIterator.next());
}
return list;
}
public List<List<?>> takeAllData() {
List<List<?>> items = buildValues(allValues());
addToValues(items);
return values;
}
public List<List<?>> takeNextPage() {
List<List<?>> items = buildValues(nextValuesPage());
addToValues(items);
return items;
}
private void addToValues(List<List<?>> items) {
values.addAll(items);
}
private List<List<?>> buildValues(List<Map<String, Object>> v) {
List<List<?>> values = new ArrayList<>();
for (Map<String, Object> m : v) {
List<Object> vals = new ArrayList<>();
for (String cn : columns) {
if (m.containsKey(cn)) {
vals.add(getValueForSerializer(m.get(cn), serializer));
} else
vals.add(null);
}
values.add(vals);
}
return values;
}
private List<Map<String, Object>> nextValuesPage(Iterator<Map<String, Object>> valuesIterator) {
List<Map<String, Object>> list = new ArrayList<>();
int i = 0;
while (i < PAGE_SIZE && valuesIterator.hasNext()) {
list.add(valuesIterator.next());
i++;
}
return list;
}
private List<Map<String, Object>> nextValuesPage() {
return nextValuesPage(valuesIterator);
}
private void createColumnNameAndType(List<Map<String, Object>> values, BeakerObjectConverter serializer) {
// create columns
if (values.size() > 0) {
// Every column gets inspected at least once, so put every column in
// a list with null for the initial type
ArrayList<String> columnOrder = new ArrayList<String>();
ArrayList<String> columnsToCheck = new ArrayList<String>();
Map<String, String> typeTracker = new LinkedHashMap<String, String>();
Map<String, Object> firstRow = values.get(0);
for (String columnName : firstRow.keySet()) {
columnOrder.add(columnName);
columnsToCheck.add(columnName);
typeTracker.put(columnName, null);
}
// Visit each row and track the row's type. If some value is found to
// contain a string, the column is marked as string based and is no
// longer typechecked
List<String> columnsToRemove = new ArrayList<String>();
for (Map<String, Object> row : values) {
// Remove any columns requested from prior iteration
for (String columnToRemove : columnsToRemove) {
columnsToCheck.remove(columnToRemove);
}
columnsToRemove = new ArrayList<String>();
ListIterator<String> columnCheckIterator = columnsToCheck.listIterator();
while (columnCheckIterator.hasNext()) {
String columnToCheck = columnCheckIterator.next();
String currentType = typeTracker.get(columnToCheck);
if (currentType == null || !currentType.equals("string")) {
Object rowItem = row.get(columnToCheck);
if (rowItem != null) {
String colType = rowItem.getClass().getName();
String beakerColType = serializer.convertType(colType);
typeTracker.put(columnToCheck, beakerColType);
if (beakerColType.equals("string")) {
columnsToRemove.add(columnToCheck);
}
}
}
}
}
// Put results of type checking into `columns` and `classes`
for (String columnName : columnOrder) {
String columnType = typeTracker.get(columnName);
columns.add(columnName);
classes.add(columnType);
}
}
}
}
| 33.299401 | 108 | 0.664269 |
70a5efa977f83cdae5042aa3d8c50e9a13b5308a | 966 | package com.rideaustin;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
/**
* Created by Sergey Petrov on 16/05/2017.
*/
public abstract class RequestMatcher {
public abstract Result match(@NonNull RequestStats requestStats);
protected static Result success() {
return new Result(true, null);
}
protected static Result fail() {
return fail(null);
}
protected static Result fail(@Nullable String message) {
return new Result(false, message);
}
public static class Result {
private boolean isSuccess;
private String message;
private Result(boolean isSuccess, @Nullable String message) {
this.isSuccess = isSuccess;
this.message = message;
}
public boolean isSuccess() {
return isSuccess;
}
public String getMessage() {
return message;
}
}
}
| 20.553191 | 69 | 0.627329 |
971e2b8aee58dbbfb54de89e9f219c29e8ac0edf | 847 | package com.moralok.concurrency.ch7.sec4;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
/**
* @author moralok
* @since 2021/3/7
*/
public class AtomicIntegerFieldUpdaterTest {
private static AtomicIntegerFieldUpdater<User> ai = AtomicIntegerFieldUpdater.newUpdater(User.class, "old");
public static void main(String[] args) {
User tom = new User("tom", 15);
System.out.println(ai.getAndIncrement(tom));
System.out.println(ai.get(tom));
}
private static class User {
private String name;
public volatile int old;
public User(String name, int old) {
this.name = name;
this.old = old;
}
public String getName() {
return name;
}
public int getOld() {
return old;
}
}
}
| 23.527778 | 112 | 0.606848 |
2a14777ac34f5a6d633a4ca155a23186f1d8e4c0 | 24,468 | package com.appleframework.data.hbase.antlr.manual.visitor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
import org.apache.hadoop.hbase.filter.Filter;
import org.apache.hadoop.hbase.filter.FilterList;
import org.apache.hadoop.hbase.filter.FilterList.Operator;
import org.apache.hadoop.hbase.filter.RegexStringComparator;
import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
import com.appleframework.data.hbase.antlr.auto.StatementsBaseVisitor;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.AndconditionContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.BetweenconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.BetweenvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.CidContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.ConditioncContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.ConstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.ConstantListContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.EqualconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.EqualvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.GreaterconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.GreaterequalconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.GreaterequalvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.GreatervarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.InconstantlistContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.ConditionwrapperContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.InvarlistContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.IsmissingcContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.IsnotmissingcContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.IsnotnullcContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.IsnullcContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.LessconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.LessequalconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.LessequalvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.LessvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.MatchconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.MatchvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotbetweenconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotbetweenvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotequalconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotequalvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotinconstantlistContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotinvarlistContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotmatchconstantContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.NotmatchvarContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.OrconditionContext;
import com.appleframework.data.hbase.antlr.auto.StatementsParser.VarContext;
import com.appleframework.data.hbase.antlr.manual.ContextUtil;
import com.appleframework.data.hbase.config.HBaseColumnSchema;
import com.appleframework.data.hbase.config.HBaseTableConfig;
import com.appleframework.data.hbase.config.SimpleHbaseRuntimeSetting;
import com.appleframework.data.hbase.exception.SimpleHBaseException;
import com.appleframework.data.hbase.util.BytesUtil;
import com.appleframework.data.hbase.util.Util;
/**
* FilterVisitor.
*
* @author xinzhi.zhang
* */
@SuppressWarnings("deprecation")
public class FilterVisitor extends StatementsBaseVisitor<Filter> {
private HBaseTableConfig hbaseTableConfig;
private Map<String, Object> para;
private SimpleHbaseRuntimeSetting runtimeSetting;
public FilterVisitor(HBaseTableConfig hbaseTableConfig,
Map<String, Object> para, SimpleHbaseRuntimeSetting runtimeSetting) {
this.hbaseTableConfig = hbaseTableConfig;
this.para = para;
this.runtimeSetting = runtimeSetting;
}
@Override
public Filter visitOrcondition(OrconditionContext ctx) {
List<ConditioncContext> conditioncContextList = ctx.conditionc();
List<Filter> filters = new ArrayList<Filter>();
for (ConditioncContext conditioncContext : conditioncContextList) {
filters.add(conditioncContext.accept(this));
}
FilterList filterList = new FilterList(Operator.MUST_PASS_ONE, filters);
return filterList;
}
@Override
public Filter visitAndcondition(AndconditionContext ctx) {
List<ConditioncContext> conditioncContextList = ctx.conditionc();
List<Filter> filters = new ArrayList<Filter>();
for (ConditioncContext conditioncContext : conditioncContextList) {
filters.add(conditioncContext.accept(this));
}
FilterList filterList = new FilterList(Operator.MUST_PASS_ALL, filters);
return filterList;
}
@Override
public Filter visitConditionwrapper(ConditionwrapperContext ctx) {
return ctx.conditionc().accept(this);
}
@Override
public Filter visitEqualvar(EqualvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilter(hbaseColumnSchema, CompareOp.EQUAL, object);
}
@Override
public Filter visitEqualconstant(EqualconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilter(hbaseColumnSchema, CompareOp.EQUAL, object);
}
@Override
public Filter visitIsnullc(IsnullcContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
return constructFilter(hbaseColumnSchema, CompareOp.EQUAL,
BytesUtil.EMPTY, true);
}
@Override
public Filter visitIsnotnullc(IsnotnullcContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
return constructFilter(hbaseColumnSchema, CompareOp.NOT_EQUAL,
BytesUtil.EMPTY, true);
}
@Override
public Filter visitNotequalconstant(NotequalconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilter(hbaseColumnSchema, CompareOp.NOT_EQUAL, object);
}
@Override
public Filter visitNotequalvar(NotequalvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilter(hbaseColumnSchema, CompareOp.NOT_EQUAL, object);
}
@Override
public Filter visitLessvar(LessvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilter(hbaseColumnSchema, CompareOp.LESS, object);
}
@Override
public Filter visitLessconstant(LessconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilter(hbaseColumnSchema, CompareOp.LESS, object);
}
@Override
public Filter visitLessequalconstant(LessequalconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilter(hbaseColumnSchema, CompareOp.LESS_OR_EQUAL,
object);
}
@Override
public Filter visitLessequalvar(LessequalvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilter(hbaseColumnSchema, CompareOp.LESS_OR_EQUAL,
object);
}
@Override
public Filter visitGreaterconstant(GreaterconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilter(hbaseColumnSchema, CompareOp.GREATER, object);
}
@Override
public Filter visitGreatervar(GreatervarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilter(hbaseColumnSchema, CompareOp.GREATER, object);
}
@Override
public Filter visitGreaterequalvar(GreaterequalvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilter(hbaseColumnSchema, CompareOp.GREATER_OR_EQUAL,
object);
}
@Override
public Filter visitGreaterequalconstant(GreaterequalconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilter(hbaseColumnSchema, CompareOp.GREATER_OR_EQUAL,
object);
}
private static Filter constructFilter(HBaseColumnSchema hbaseColumnSchema,
CompareOp compareOp, Object object) {
Util.checkNull(hbaseColumnSchema);
byte[] value = hbaseColumnSchema.getTypeHandler().toBytes(
hbaseColumnSchema.getType(), object);
return constructFilter(hbaseColumnSchema, compareOp, value, true);
}
private static Filter constructFilter(HBaseColumnSchema hbaseColumnSchema,
CompareOp compareOp, byte[] value, boolean filterIfMissing) {
Util.checkNull(hbaseColumnSchema);
Util.checkNull(compareOp);
Util.checkNull(value);
byte[] familyBytes = hbaseColumnSchema.getFamilyBytes();
byte[] qualifierBytes = hbaseColumnSchema.getQualifierBytes();
SingleColumnValueFilter singleColumnValueFilter = new SingleColumnValueFilter(
familyBytes, qualifierBytes, compareOp, value);
singleColumnValueFilter.setFilterIfMissing(filterIfMissing);
return singleColumnValueFilter;
}
@Override
public Filter visitIsnotmissingc(IsnotmissingcContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
return constructFilter(hbaseColumnSchema, CompareOp.GREATER_OR_EQUAL,
BytesUtil.EMPTY, true);
}
@Override
public Filter visitIsmissingc(IsmissingcContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
return constructFilter(hbaseColumnSchema, CompareOp.LESS,
BytesUtil.EMPTY, false);
}
@Override
public Filter visitNotmatchconstant(NotmatchconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilterWithRegex(hbaseColumnSchema, CompareOp.NOT_EQUAL,
object);
}
@Override
public Filter visitNotmatchvar(NotmatchvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilterWithRegex(hbaseColumnSchema, CompareOp.NOT_EQUAL,
object);
}
@Override
public Filter visitMatchvar(MatchvarContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilterWithRegex(hbaseColumnSchema, CompareOp.EQUAL,
object);
}
@Override
public Filter visitMatchconstant(MatchconstantContext ctx) {
CidContext cidContext = ctx.cid();
ConstantContext constantContext = ctx.constant();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parseConstant(hbaseColumnSchema,
constantContext, runtimeSetting);
return constructFilterWithRegex(hbaseColumnSchema, CompareOp.EQUAL,
object);
}
private static Filter constructFilterWithRegex(
HBaseColumnSchema hbaseColumnSchema, CompareOp compareOp,
Object object) {
Util.checkNull(hbaseColumnSchema);
Util.checkNull(compareOp);
Util.checkNull(object);
if (compareOp != CompareOp.EQUAL && compareOp != CompareOp.NOT_EQUAL) {
throw new SimpleHBaseException(
"only EQUAL or NOT_EQUAL can use regex match. compareOp = "
+ compareOp);
}
if (object.getClass() != String.class) {
throw new SimpleHBaseException(
"only String can use regex match. object = " + object);
}
if (hbaseColumnSchema.getType() != String.class) {
throw new SimpleHBaseException(
"only String can use regex match. hbaseColumnSchema = "
+ hbaseColumnSchema);
}
byte[] familyBytes = hbaseColumnSchema.getFamilyBytes();
byte[] qualifierBytes = hbaseColumnSchema.getQualifierBytes();
RegexStringComparator regexStringComparator = new RegexStringComparator(
(String) object);
SingleColumnValueFilter singleColumnValueFilter = new SingleColumnValueFilter(
familyBytes, qualifierBytes, compareOp, regexStringComparator);
singleColumnValueFilter.setFilterIfMissing(true);
return singleColumnValueFilter;
}
@Override
public Filter visitNotinconstantlist(NotinconstantlistContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
ConstantListContext constantListContext = ctx.constantList();
List<ConstantContext> constantContextList = constantListContext
.constant();
List<Object> list = ContextUtil.parseConstantList(hbaseColumnSchema,
constantContextList, runtimeSetting);
return constructFilterForContain(hbaseColumnSchema,
CompareOp.NOT_EQUAL, list, Operator.MUST_PASS_ALL);
}
@SuppressWarnings("unchecked")
@Override
public Filter visitNotinvarlist(NotinvarlistContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilterForContain(hbaseColumnSchema,
CompareOp.NOT_EQUAL, (List<Object>) object,
Operator.MUST_PASS_ALL);
}
@SuppressWarnings("unchecked")
@Override
public Filter visitInvarlist(InvarlistContext ctx) {
CidContext cidContext = ctx.cid();
VarContext varContext = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
Object object = ContextUtil.parsePara(varContext, para);
return constructFilterForContain(hbaseColumnSchema, CompareOp.EQUAL,
(List<Object>) object, Operator.MUST_PASS_ONE);
}
@Override
public Filter visitInconstantlist(InconstantlistContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
ConstantListContext constantListContext = ctx.constantList();
List<ConstantContext> constantContextList = constantListContext
.constant();
List<Object> list = ContextUtil.parseConstantList(hbaseColumnSchema,
constantContextList, runtimeSetting);
return constructFilterForContain(hbaseColumnSchema, CompareOp.EQUAL,
list, Operator.MUST_PASS_ONE);
}
private static Filter constructFilterForContain(
HBaseColumnSchema hbaseColumnSchema, CompareOp compareOp,
List<Object> list, Operator operator) {
Util.checkNull(hbaseColumnSchema);
Util.checkNull(compareOp);
Util.checkNull(list);
Util.checkNull(operator);
List<Filter> filters = new ArrayList<Filter>();
for (Object obj : list) {
filters.add(constructFilter(hbaseColumnSchema, compareOp, obj));
}
FilterList filterList = new FilterList(operator, filters);
return filterList;
}
@Override
public Filter visitNotbetweenconstant(NotbetweenconstantContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
List<ConstantContext> constantContextList = ctx.constant();
List<Object> list = ContextUtil.parseConstantList(hbaseColumnSchema,
constantContextList, runtimeSetting);
Filter startFilter = constructFilter(hbaseColumnSchema, CompareOp.LESS,
list.get(0));
Filter endFilter = constructFilter(hbaseColumnSchema,
CompareOp.GREATER, list.get(1));
FilterList filterList = new FilterList(Operator.MUST_PASS_ONE,
Arrays.asList(startFilter, endFilter));
return filterList;
}
@Override
public Filter visitNotbetweenvar(NotbetweenvarContext ctx) {
CidContext cidContext = ctx.cid();
List<VarContext> varContextList = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
List<Object> list = ContextUtil.parseParaList(varContextList, para);
Filter startFilter = constructFilter(hbaseColumnSchema, CompareOp.LESS,
list.get(0));
Filter endFilter = constructFilter(hbaseColumnSchema,
CompareOp.GREATER, list.get(1));
FilterList filterList = new FilterList(Operator.MUST_PASS_ONE,
Arrays.asList(startFilter, endFilter));
return filterList;
}
@Override
public Filter visitBetweenvar(BetweenvarContext ctx) {
CidContext cidContext = ctx.cid();
List<VarContext> varContextList = ctx.var();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
List<Object> list = ContextUtil.parseParaList(varContextList, para);
Filter startFilter = constructFilter(hbaseColumnSchema,
CompareOp.GREATER_OR_EQUAL, list.get(0));
Filter endFilter = constructFilter(hbaseColumnSchema,
CompareOp.LESS_OR_EQUAL, list.get(1));
FilterList filterList = new FilterList(Operator.MUST_PASS_ALL,
Arrays.asList(startFilter, endFilter));
return filterList;
}
@Override
public Filter visitBetweenconstant(BetweenconstantContext ctx) {
CidContext cidContext = ctx.cid();
HBaseColumnSchema hbaseColumnSchema = ContextUtil
.parseHBaseColumnSchema(hbaseTableConfig, cidContext);
List<ConstantContext> constantContextList = ctx.constant();
List<Object> list = ContextUtil.parseConstantList(hbaseColumnSchema,
constantContextList, runtimeSetting);
Filter startFilter = constructFilter(hbaseColumnSchema,
CompareOp.GREATER_OR_EQUAL, list.get(0));
Filter endFilter = constructFilter(hbaseColumnSchema,
CompareOp.LESS_OR_EQUAL, list.get(1));
FilterList filterList = new FilterList(Operator.MUST_PASS_ALL,
Arrays.asList(startFilter, endFilter));
return filterList;
}
}
| 42.926316 | 94 | 0.699935 |
dc3afbf7e07d96640a37852090c08c6815e4b3bb | 1,340 | /**
*
*/
package org.danyuan.application.lession.day001.lesson021;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.TilePane;
import javafx.stage.Stage;
/**
* 作 者: wth
*/
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
/*
* (non-Javadoc)
*
* javafx.application.Application#start(javafx.stage.Stage)
*/
@Override
public void start(Stage primaryStage) throws Exception {
Button btn1 = new Button("button1");
Button btn2 = new Button("button2");
Button btn3 = new Button("button3");
Button btn4 = new Button("button4");
Button btn5 = new Button("button5");
Button btn6 = new Button("button6");
Button btn7 = new Button("button7");
Button btn8 = new Button("button8");
TilePane tilePane = new TilePane();
tilePane.getChildren().addAll(btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8);
tilePane.setVgap(10); // 间距
tilePane.setHgap(10); //
tilePane.setPadding(new Insets(10));
TilePane.setMargin(btn1,new Insets(20)); // 导致其他空间都有间距
Scene scene = new Scene(tilePane);
primaryStage.setScene(scene);
primaryStage.setTitle(" TilePane布局类");
primaryStage.setWidth(400);
primaryStage.setHeight(400);
primaryStage.show();
}
}
| 22.711864 | 73 | 0.709701 |
c17749e3b1b733880f937e6dc027b50583a9b137 | 2,821 | /*
*
* 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 nanocad;
/*Copyright (c) 2004,University of Illinois at Urbana-Champaign. All rights reserved.
Developed by:
Chemistry and Computational Biology Group
NCSA, University of Illinois at Urbana-Champaign
http://ncsa.uiuc.edu/GridChem
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal with 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:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimers.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimers in the documentation
and/or other materials provided with the distribution.
3. Neither the names of Chemistry and Computational Biology Group , NCSA,
University of Illinois at Urbana-Champaign, nor the names of its contributors
may be used to endorse or promote products derived from this Software without
specific prior written permission.
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 CONTRIBUTORS 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 WITH THE SOFTWARE.
*/
public interface MyLongTaskInterface {
public void go() throws Exception;
public int getLengthOfTask();
public int getCurrent();
public void stop();
public boolean done();
}// end public interface MyLongTaskInterface
| 42.742424 | 86 | 0.780574 |
3610fd818373953cbde202f539ae26e77a9b4eda | 423 | package com.xiaoliu.learn;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @description: 提供者服务A启动类
* @author: liufb
* @create: 2020/7/31 11:10
**/
@SpringBootApplication
public class ProviderServiceAApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderServiceAApplication.class, args);
}
}
| 23.5 | 71 | 0.761229 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.