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
|
|---|---|---|---|---|---|
0287f77e3fb47403e4f2110b8d40b6af2af40f0b
| 2,808
|
package nl.tudelft.fa.core.lobby.actor;
import akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.Props;
import akka.japi.pf.ReceiveBuilder;
import nl.tudelft.fa.core.lobby.message.Join;
import nl.tudelft.fa.core.lobby.message.JoinException;
import nl.tudelft.fa.core.lobby.message.JoinSuccess;
import nl.tudelft.fa.core.lobby.message.Refresh;
import scala.PartialFunction;
import scala.runtime.BoxedUnit;
/**
* This actor handles the joining process between a balancer and a lobby.
*
* @author Fabian Mastenbroek
*/
public class LobbyBalancerMediator extends AbstractActor {
/**
* The {@link LobbyBalancerActor} that created this mediator.
*/
private ActorRef balancer;
/**
* The {@link Join} this mediator handles.
*/
private Join req;
/**
* Construct a {@link LobbyBalancerMediator} instance.
*
* @param balancer The {@link LobbyBalancerActor} that created this mediator.
* @param req The join request this mediator handles.
*/
private LobbyBalancerMediator(ActorRef balancer, Join req) {
this.balancer = balancer;
this.req = req;
}
/**
* This method defines the initial actor behavior, it must return a partial function with the
* actor logic.
*
* @return The initial actor behavior as a partial function.
*/
@Override
public PartialFunction<Object, BoxedUnit> receive() {
return ReceiveBuilder
.match(JoinSuccess.class, this::success)
.match(JoinException.class, this::failure)
.build();
}
/**
* This method is invoked whenever the joining process ended successfully.
*
* @param res The {@link JoinSuccess} response from the lobby.
*/
private void success(JoinSuccess res) {
req.getHandler().tell(res, sender());
context().stop(self());
}
/**
* This method is invoked whenever the joining process ended in a failure.
*
* @param error The error that occurred.
*/
private void failure(JoinException error) {
// Update the balancer's caches and retry
balancer.tell(Refresh.INSTANCE, self());
balancer.tell(req, req.getHandler());
context().stop(self());
}
/**
* Create {@link Props} instance for an actor of this type.
*
* @param balancer The lobby balancer that created this mediator.
* @param req The join request to handle.
* @return A Props for creating this actor, which can then be further configured
* (e.g. calling `.withDispatcher()` on it)
*/
public static Props props(ActorRef balancer, Join req) {
return Props.create(LobbyBalancerMediator.class,
() -> new LobbyBalancerMediator(balancer, req));
}
}
| 31.2
| 97
| 0.658832
|
50cc0506497f51324cc87e005c6c26d7c6001a05
| 1,071
|
package com.devepos.adt.saat.internal.search;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.fieldassist.IContentProposal;
import org.eclipse.swt.graphics.Image;
import com.devepos.adt.saat.internal.search.contentassist.SearchParameterProposal;
/**
* Parameter for object search that only supports <code>true</code> and
* <code>false</code>
*
* @author stockbal
*/
public class BooleanSearchParameter extends SearchParameter implements ISearchProposalProvider {
public BooleanSearchParameter(final QueryParameterName parameterName, final String description,
final Image image) {
super(parameterName, description, image, false, false, false);
}
@Override
public List<IContentProposal> getProposalList(final String query) throws CoreException {
return Arrays.asList(new SearchParameterProposal(Boolean.TRUE.toString(), getParameterName(),
null, null), new SearchParameterProposal(Boolean.FALSE.toString(), getParameterName(), null,
null));
}
}
| 32.454545
| 100
| 0.774977
|
b14a262ee8bb0158d6d3d47866ec29287de90c0e
| 2,976
|
/***********************************************************************************************************************
*
* Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.api.common.typeutils.base;
import java.io.IOException;
import eu.stratosphere.core.memory.DataInputView;
import eu.stratosphere.core.memory.MemorySegment;
import eu.stratosphere.types.StringValue;
public final class StringComparator extends BasicTypeComparator<String> {
private static final long serialVersionUID = 1L;
private static final int HIGH_BIT = 0x1 << 7;
private static final int HIGH_BIT2 = 0x1 << 13;
private static final int HIGH_BIT2_MASK = 0x3 << 6;
public StringComparator(boolean ascending) {
super(ascending);
}
@Override
public int compare(DataInputView firstSource, DataInputView secondSource) throws IOException {
String s1 = StringValue.readString(firstSource);
String s2 = StringValue.readString(secondSource);
int comp = s1.compareTo(s2);
return ascendingComparison ? comp : -comp;
}
@Override
public boolean supportsNormalizedKey() {
return true;
}
@Override
public boolean supportsSerializationWithKeyNormalization() {
return false;
}
@Override
public int getNormalizeKeyLen() {
return Integer.MAX_VALUE;
}
@Override
public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
return true;
}
@Override
public void putNormalizedKey(String record, MemorySegment target, int offset, int len) {;
final int limit = offset + len;
final int end = record.length();
int pos = 0;
while (pos < end && offset < limit) {
char c = record.charAt(pos++);
if (c < HIGH_BIT) {
target.put(offset++, (byte) c);
}
else if (c < HIGH_BIT2) {
target.put(offset++, (byte) ((c >>> 7) | HIGH_BIT));
if (offset < limit) {
target.put(offset++, (byte) c);
}
}
else {
target.put(offset++, (byte) ((c >>> 10) | HIGH_BIT2_MASK));
if (offset < limit) {
target.put(offset++, (byte) (c >>> 2));
}
if (offset < limit) {
target.put(offset++, (byte) c);
}
}
}
while (offset < limit) {
target.put(offset++, (byte) 0);
}
}
@Override
public StringComparator duplicate() {
return new StringComparator(ascendingComparison);
}
}
| 27.302752
| 120
| 0.641465
|
490b63563c03a7f438d486127040494889e4c512
| 3,415
|
/*******************************************************************************
* Copyright 2011-2014 Sergey Tarasevich
*
* 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.nostra13.universalimageloader.cache.memory.impl;
import com.nostra13.universalimageloader.cache.memory.LimitedMemoryCache;
import ohos.media.image.PixelMap;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Limited {@link PixelMap PixelMap} cache. Provides {@link PixelMap PixelMaps} storing. Size of all stored PixelMaps will not to
* exceed size limit. When cache reaches limit size then the PixelMap which has the largest size is deleted from
* cache.<br />
* <br />
* <b>NOTE:</b> This cache uses strong and weak references for stored PixelMaps. Strong references - for limited count of
* PixelMaps (depends on cache size), weak references - for all other cached PixelMaps.
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
* @since 1.0.0
*/
public class LargestLimitedMemoryCache extends LimitedMemoryCache {
/**
* Contains strong references to stored objects (keys) and sizes of the objects. If hard cache
* size will exceed limit then object with the largest size is deleted (but it continue exist at
*/
private final Map<PixelMap, Integer> valueSizes = Collections.synchronizedMap(new HashMap<PixelMap, Integer>());
public LargestLimitedMemoryCache(int sizeLimit) {
super(sizeLimit);
}
@Override
public boolean put(String key, PixelMap value) {
if (super.put(key, value)) {
valueSizes.put(value, getSize(value));
return true;
} else {
return false;
}
}
@Override
public PixelMap remove(String key) {
PixelMap value = super.get(key);
if (value != null) {
valueSizes.remove(value);
}
return super.remove(key);
}
@Override
public void clear() {
valueSizes.clear();
super.clear();
}
@Override
protected int getSize(PixelMap value) {
return value.getBytesNumberPerRow() * value.getImageInfo().size.height;
}
@Override
protected PixelMap removeNext() {
Integer maxSize = null;
PixelMap largestValue = null;
Set<Entry<PixelMap, Integer>> entries = valueSizes.entrySet();
synchronized (valueSizes) {
for (Entry<PixelMap, Integer> entry : entries) {
if (largestValue == null) {
largestValue = entry.getKey();
maxSize = entry.getValue();
} else {
Integer size = entry.getValue();
if (size > maxSize) {
maxSize = size;
largestValue = entry.getKey();
}
}
}
}
valueSizes.remove(largestValue);
return largestValue;
}
@Override
protected Reference<PixelMap> createReference(PixelMap value) {
return new WeakReference<PixelMap>(value);
}
}
| 31.330275
| 129
| 0.691947
|
e54621f94b7a8fbb147e320121e820f76a8d3f00
| 316
|
package idawi.ui.cmd;
import java.io.Serializable;
import java.util.function.Consumer;
import idawi.Component;
import j4u.CommandLine;
public abstract class CommandBackend implements Serializable {
public CommandLine cmdline;
abstract void runOnServer(Component thing, Consumer<Object> out) throws Throwable;
}
| 24.307692
| 83
| 0.81962
|
5ea236f862bbf97ba211d95097e1bca08f37d233
| 4,613
|
package ts.eclipse.ide.json.ui;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IPath;
import org.eclipse.jface.text.IDocument;
import org.eclipse.json.jsonpath.IJSONPath;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.widgets.FormToolkit;
import ts.eclipse.ide.core.utils.WorkbenchResourceUtil;
import ts.eclipse.ide.json.ui.internal.tsconfig.TsconfigEditorMessages;
import ts.eclipse.ide.ui.utils.DialogUtils;
public class TextAndBrowseButton extends Composite {
private final String checkBoxLabel;
private final FormToolkit toolkit;
private final IFile tsconfigFile;
private final boolean isFile;
private Text textField;
private Button checkbox;
private Button browseButton;
public TextAndBrowseButton(String checkBoxLabel, FormToolkit toolkit, IFile tsconfigFile, boolean isFile,
Composite parent, int style) {
super(parent, style);
this.checkBoxLabel = checkBoxLabel;
this.toolkit = toolkit;
this.tsconfigFile = tsconfigFile;
this.isFile = isFile;
createBody(this);
}
private void createBody(Composite parent) {
boolean fromWorkspace = tsconfigFile != null;
Composite composite = parent;
composite.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
GridLayout layout = new GridLayout(fromWorkspace ? 3 : 2, false);
layout.marginWidth = 0;
layout.marginBottom = 0;
layout.marginTop = 0;
layout.marginHeight = 0;
layout.verticalSpacing = 0;
composite.setLayout(layout);
if (fromWorkspace) {
// Display checkbox if tsconfig file comes from workspace (and from
// file system)
checkbox = getToolkit().createButton(composite, checkBoxLabel, SWT.CHECK);
} else {
// Otherwise, display a simple label.
getToolkit().createLabel(composite, checkBoxLabel, SWT.NONE);
}
textField = getToolkit().createText(composite, "");
textField.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));
if (fromWorkspace) {
browseButton = getToolkit().createButton(composite, TsconfigEditorMessages.Button_browse,
SWT.PUSH);
textField.setEnabled(false);
browseButton.setEnabled(false);
if (checkbox != null) {
checkbox.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
updateEnable();
if (!checkbox.getSelection()) {
textField.setText("");
}
}
});
}
if (!isFile) {
browseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IResource resource = DialogUtils.openFolderDialog(textField.getText(),
tsconfigFile.getProject(), false, browseButton.getShell());
if (resource != null) {
IPath path = WorkbenchResourceUtil.getRelativePath(resource, tsconfigFile.getParent());
textField.setText(path.toString());
}
}
});
} else {
browseButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
IResource resource = DialogUtils.openResourceDialog(tsconfigFile.getProject(),
browseButton.getShell());
if (resource != null) {
IPath path = WorkbenchResourceUtil.getRelativePath(resource, tsconfigFile.getParent());
textField.setText(path.toString());
}
}
});
}
}
}
public void bind(IJSONPath path, IDocument document, DataBindingContext context) {
if (checkbox != null) {
bindExists(checkbox, path, document, context);
}
bind(textField, path, document, context);
}
private void bindExists(Button checkbox, IJSONPath path, IDocument document, DataBindingContext context) {
JSONBindingUIHelper.bindExists(checkbox, path, null, document, context);
}
private void bind(Text text, IJSONPath path, IDocument document, DataBindingContext context) {
JSONBindingUIHelper.bind(text, path, "", document, context);
}
public FormToolkit getToolkit() {
return toolkit;
}
public void updateEnable() {
textField.setEnabled(checkbox.getSelection());
browseButton.setEnabled(checkbox.getSelection());
}
}
| 32.716312
| 108
| 0.718405
|
102be3db6dad1d0c4cab6dd30e2918e1ca0d67b0
| 9,312
|
package messaging;
import static io.grpc.MethodDescriptor.generateFullMethodName;
import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ClientCalls.asyncClientStreamingCall;
import static io.grpc.stub.ClientCalls.asyncServerStreamingCall;
import static io.grpc.stub.ClientCalls.asyncUnaryCall;
import static io.grpc.stub.ClientCalls.blockingServerStreamingCall;
import static io.grpc.stub.ClientCalls.blockingUnaryCall;
import static io.grpc.stub.ClientCalls.futureUnaryCall;
import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall;
import static io.grpc.stub.ServerCalls.asyncClientStreamingCall;
import static io.grpc.stub.ServerCalls.asyncServerStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnaryCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall;
import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall;
/**
*/
@javax.annotation.Generated(
value = "by gRPC proto compiler (version 1.32.1)",
comments = "Source: service.proto")
public final class MapleServiceGrpc {
private MapleServiceGrpc() {}
public static final String SERVICE_NAME = "messaging.MapleService";
// Static method descriptors that strictly reflect the proto.
private static volatile io.grpc.MethodDescriptor<messaging.Service.RequestEvent,
messaging.Service.ResponseEvent> getEventsStreamMethod;
@io.grpc.stub.annotations.RpcMethod(
fullMethodName = SERVICE_NAME + '/' + "EventsStream",
requestType = messaging.Service.RequestEvent.class,
responseType = messaging.Service.ResponseEvent.class,
methodType = io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
public static io.grpc.MethodDescriptor<messaging.Service.RequestEvent,
messaging.Service.ResponseEvent> getEventsStreamMethod() {
io.grpc.MethodDescriptor<messaging.Service.RequestEvent, messaging.Service.ResponseEvent> getEventsStreamMethod;
if ((getEventsStreamMethod = MapleServiceGrpc.getEventsStreamMethod) == null) {
synchronized (MapleServiceGrpc.class) {
if ((getEventsStreamMethod = MapleServiceGrpc.getEventsStreamMethod) == null) {
MapleServiceGrpc.getEventsStreamMethod = getEventsStreamMethod =
io.grpc.MethodDescriptor.<messaging.Service.RequestEvent, messaging.Service.ResponseEvent>newBuilder()
.setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
.setFullMethodName(generateFullMethodName(SERVICE_NAME, "EventsStream"))
.setSampledToLocalTracing(true)
.setRequestMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
messaging.Service.RequestEvent.getDefaultInstance()))
.setResponseMarshaller(io.grpc.protobuf.lite.ProtoLiteUtils.marshaller(
messaging.Service.ResponseEvent.getDefaultInstance()))
.build();
}
}
}
return getEventsStreamMethod;
}
/**
* Creates a new async stub that supports all call types for the service
*/
public static MapleServiceStub newStub(io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MapleServiceStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MapleServiceStub>() {
@java.lang.Override
public MapleServiceStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MapleServiceStub(channel, callOptions);
}
};
return MapleServiceStub.newStub(factory, channel);
}
/**
* Creates a new blocking-style stub that supports unary and streaming output calls on the service
*/
public static MapleServiceBlockingStub newBlockingStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MapleServiceBlockingStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MapleServiceBlockingStub>() {
@java.lang.Override
public MapleServiceBlockingStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MapleServiceBlockingStub(channel, callOptions);
}
};
return MapleServiceBlockingStub.newStub(factory, channel);
}
/**
* Creates a new ListenableFuture-style stub that supports unary calls on the service
*/
public static MapleServiceFutureStub newFutureStub(
io.grpc.Channel channel) {
io.grpc.stub.AbstractStub.StubFactory<MapleServiceFutureStub> factory =
new io.grpc.stub.AbstractStub.StubFactory<MapleServiceFutureStub>() {
@java.lang.Override
public MapleServiceFutureStub newStub(io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MapleServiceFutureStub(channel, callOptions);
}
};
return MapleServiceFutureStub.newStub(factory, channel);
}
/**
*/
public static abstract class MapleServiceImplBase implements io.grpc.BindableService {
/**
*/
public io.grpc.stub.StreamObserver<messaging.Service.RequestEvent> eventsStream(
io.grpc.stub.StreamObserver<messaging.Service.ResponseEvent> responseObserver) {
return asyncUnimplementedStreamingCall(getEventsStreamMethod(), responseObserver);
}
@java.lang.Override public final io.grpc.ServerServiceDefinition bindService() {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getEventsStreamMethod(),
asyncBidiStreamingCall(
new MethodHandlers<
messaging.Service.RequestEvent,
messaging.Service.ResponseEvent>(
this, METHODID_EVENTS_STREAM)))
.build();
}
}
/**
*/
public static final class MapleServiceStub extends io.grpc.stub.AbstractAsyncStub<MapleServiceStub> {
private MapleServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected MapleServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MapleServiceStub(channel, callOptions);
}
/**
*/
public io.grpc.stub.StreamObserver<messaging.Service.RequestEvent> eventsStream(
io.grpc.stub.StreamObserver<messaging.Service.ResponseEvent> responseObserver) {
return asyncBidiStreamingCall(
getChannel().newCall(getEventsStreamMethod(), getCallOptions()), responseObserver);
}
}
/**
*/
public static final class MapleServiceBlockingStub extends io.grpc.stub.AbstractBlockingStub<MapleServiceBlockingStub> {
private MapleServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected MapleServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MapleServiceBlockingStub(channel, callOptions);
}
}
/**
*/
public static final class MapleServiceFutureStub extends io.grpc.stub.AbstractFutureStub<MapleServiceFutureStub> {
private MapleServiceFutureStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected MapleServiceFutureStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new MapleServiceFutureStub(channel, callOptions);
}
}
private static final int METHODID_EVENTS_STREAM = 0;
private static final class MethodHandlers<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final MapleServiceImplBase serviceImpl;
private final int methodId;
MethodHandlers(MapleServiceImplBase serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_EVENTS_STREAM:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.eventsStream(
(io.grpc.stub.StreamObserver<messaging.Service.ResponseEvent>) responseObserver);
default:
throw new AssertionError();
}
}
}
private static volatile io.grpc.ServiceDescriptor serviceDescriptor;
public static io.grpc.ServiceDescriptor getServiceDescriptor() {
io.grpc.ServiceDescriptor result = serviceDescriptor;
if (result == null) {
synchronized (MapleServiceGrpc.class) {
result = serviceDescriptor;
if (result == null) {
serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME)
.addMethod(getEventsStreamMethod())
.build();
}
}
}
return result;
}
}
| 39.457627
| 122
| 0.724656
|
c95ae75a1b493abd643369b515f2886a23256f35
| 982
|
package unicss;
/**
*
* @author wb-wy698919
* @version $Id: MyExecutor.java, v 0.1 2020/5/22 10:59 wb-698919.wyi Exp $
*/
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MyExecutor extends Thread {
private int index;
public MyExecutor(int i) {
this.index = i;
}
public void run() {
try {
System.out.println("[" + this.index + "] start....");
Thread.sleep((int) (Math.random() * 10000));
System.out.println("[" + this.index + "] end.");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
ExecutorService service = Executors.newFixedThreadPool(4);
for (int i = 0; i < 10; i++) {
service.execute(new MyExecutor(i));
//service.submit(new MyExecutor(i));
}
System.out.println("submit finish");
service.shutdown();
}
}
| 25.842105
| 75
| 0.565173
|
7b95edc34a6fef7547f3539c05c07fd8b94bfdb9
| 1,591
|
/*
* Copyright 2011,2012 Metamarkets Group 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.metamx.common.parsers;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Class that can parse Strings into Maps.
*/
public interface Parser<K, V>
{
/**
* Parse a String into a Map.
*
* @throws ParseException if the String cannot be parsed
*/
public Map<K, V> parse(String input);
/**
* Set the fieldNames that you expect to see in parsed Maps. Deprecated; Parsers should not, in general, be
* expected to know what fields they will return. Some individual types of parsers do need to know (like a TSV
* parser) and those parsers have their own way of setting field names.
*/
@Deprecated
public void setFieldNames(Iterable<String> fieldNames);
/**
* Returns the fieldNames that we expect to see in parsed Maps, if known, or null otherwise. Deprecated; Parsers
* should not, in general, be expected to know what fields they will return.
*/
@Deprecated
public List<String> getFieldNames();
}
| 31.82
| 114
| 0.720302
|
7e62a3b83f4c62f20fcdafaea0d51f2ba88daf9e
| 2,613
|
/*
* 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.common.collection.ring;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
/**
* A {@link Pointer} that will always stay behind a number of other {@link Pointer} instances, which can be safely and dynamically
* added or removed.
*
* @author Randall Hauch (rhauch@redhat.com)
*/
public class TrailingPointer extends Pointer implements DependentOnPointers {
private static final Pointer[] EMPTY_ARRAY = new Pointer[0];
private static final AtomicReferenceFieldUpdater<TrailingPointer, Pointer[]> STAY_BEHIND_UPDATER = AtomicReferenceFieldUpdater.newUpdater(TrailingPointer.class,
Pointer[].class,
"stayBehinds");
private volatile Pointer[] stayBehinds;
public TrailingPointer( Pointer... stayBehinds ) {
this(INITIAL_VALUE, stayBehinds);
}
public TrailingPointer( long initialValue,
Pointer... stayBehinds ) {
super(initialValue);
this.stayBehinds = stayBehinds == null ? EMPTY_ARRAY : stayBehinds;
}
@Override
public long get() {
return Math.max(INITIAL_VALUE, Pointers.getMinimum(stayBehinds, Long.MAX_VALUE) - 1L);
}
@Override
public void stayBehind( Pointer... pointers ) {
Pointers.add(this, STAY_BEHIND_UPDATER, null, pointers);
}
@Override
public boolean ignore( Pointer pointer ) {
return Pointers.remove(this, STAY_BEHIND_UPDATER, pointer);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('[');
for (Pointer pointer : stayBehinds) {
sb.append(pointer).append(",");
}
sb.append(']');
return sb.toString();
}
}
| 35.794521
| 164
| 0.613854
|
4099cca02775bf895854153c93828b135866b7f3
| 1,300
|
package com.mobgen.halo.android.content.models;
import android.os.Parcel;
import android.support.annotation.Keep;
/**
* Represents the parenthesis opened or closed.
*/
@Keep
public class Parenthesis implements SearchExpression {
/**
* Opened or closed.
*/
private boolean mOpened;
public static final Creator<Parenthesis> CREATOR = new Creator<Parenthesis>() {
public Parenthesis createFromParcel(Parcel source) {
return new Parenthesis(source);
}
public Parenthesis[] newArray(int size) {
return new Parenthesis[size];
}
};
/**
* Constructor for the parenthesis.
*
* @param opened True if opened, false otherwise.
*/
public Parenthesis(boolean opened) {
mOpened = opened;
}
protected Parenthesis(Parcel in) {
this.mOpened = in.readByte() != 0;
}
/**
* Checks if the parenthesis is opened.
*
* @return True if the parenthesis are opened. False otherwise
*/
public boolean isOpened() {
return mOpened;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeByte(mOpened ? (byte) 1 : (byte) 0);
}
}
| 22.033898
| 83
| 0.615385
|
f00767f2f206120d5f3e9c93a4a979bf959c2995
| 2,059
|
package com.ctrip.xpipe.redis.core.protocal.cmd;
import com.ctrip.xpipe.api.command.CommandFuture;
import com.ctrip.xpipe.api.command.CommandFutureListener;
import com.ctrip.xpipe.api.server.Server.SERVER_ROLE;
import com.ctrip.xpipe.netty.ByteBufUtils;
import com.ctrip.xpipe.redis.core.AbstractRedisTest;
import com.ctrip.xpipe.redis.core.protocal.MASTER_STATE;
import com.ctrip.xpipe.redis.core.protocal.pojo.Role;
import com.ctrip.xpipe.redis.core.protocal.pojo.SlaveRole;
import com.ctrip.xpipe.simpleserver.Server;
import com.ctrip.xpipe.testutils.MemoryPrinter;
import org.junit.Assert;
import org.junit.Test;
import java.util.concurrent.CountDownLatch;
/**
* @author wenchao.meng
*
* Sep 16, 2016
*/
public class RoleCommandTest extends AbstractRedisTest{
@Test
public void test() throws Exception{
SlaveRole role = new SlaveRole(SERVER_ROLE.KEEPER, "localhost", randomPort(), MASTER_STATE.REDIS_REPL_CONNECT, 0L);
Server server = startServer(ByteBufUtils.readToString(role.format()));
RoleCommand roleCommand = new RoleCommand(LOCAL_HOST, server.getPort(), scheduled);
Role real = roleCommand.execute().get();
logger.info("[test]{}", real);
Assert.assertEquals(role, real);
}
@Test
public void testNettyThreadLocalHoldingObjects() throws Exception {
SlaveRole role = new SlaveRole(SERVER_ROLE.KEEPER, "localhost", randomPort(), MASTER_STATE.REDIS_REPL_CONNECT, 0L);
Server server = startServer(ByteBufUtils.readToString(role.format()));
int tasks = 5;
CountDownLatch latch = new CountDownLatch(tasks);
long before = MemoryPrinter.getFreeMemory();
for(int i = 0; i < tasks; i++) {
RoleCommand roleCommand = new RoleCommand(LOCAL_HOST, server.getPort(), scheduled);
roleCommand.execute().addListener(new CommandFutureListener<Role>() {
@Override
public void operationComplete(CommandFuture<Role> commandFuture) throws Exception {
latch.countDown();
}
});
}
latch.await();
long after = MemoryPrinter.getFreeMemory();
logger.info("[delta]{}", after - before);
}
}
| 32.68254
| 117
| 0.756192
|
f16a11dea4315c7bdca60178ebd8beb0d5b1dbcc
| 365
|
package com.zto.testcase.model;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
@Data
public class BasePO implements Serializable {
private static final long serialVersionUID = 1L;
private Date createTime;
private Date updateTime;
private String createUser;
private String updateUser;
private String user;
}
| 15.869565
| 52
| 0.745205
|
d646266f7807e9f45adb1d636cf274cfb12136d5
| 610
|
package com.blamejared.crafttweaker.api.zencode;
import com.blamejared.crafttweaker.api.CraftTweakerAPI;
import com.blamejared.crafttweaker.api.annotation.ZenRegister;
import org.openzen.zencode.java.ZenCodeGlobals;
import org.openzen.zencode.java.ZenCodeType;
@ZenRegister
@ZenCodeType.Name("crafttweaker.api.Globals")
public class CraftTweakerGlobals {
@ZenCodeGlobals.Global
public static void println(String msg) {
CraftTweakerAPI.LOGGER.info(msg);
}
@ZenCodeGlobals.Global
public static void print(String msg) {
println(msg);
}
}
| 24.4
| 62
| 0.72623
|
905dbb45f8cb2b2c0454edc79d2020d8316a5b26
| 3,504
|
/*******************************************************************************
* Copyright 2014 Univocity Software Pty 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.univocity.parsers.tsv;
import com.univocity.parsers.common.*;
/**
* A very fast TSV parser implementation.
*
* @author Univocity Software Pty Ltd - <a href="mailto:parsers@univocity.com">parsers@univocity.com</a>
* @see TsvFormat
* @see TsvParserSettings
* @see TsvWriter
* @see AbstractParser
*/
public class TsvParser extends AbstractParser<TsvParserSettings> {
private final boolean ignoreTrailingWhitespace;
private final boolean ignoreLeadingWhitespace;
private final boolean joinLines;
private final char newLine;
private final char escapeChar;
private final char escapedTabChar;
/**
* The TsvParser supports all settings provided by {@link TsvParserSettings}, and requires this configuration to be properly initialized.
*
* @param settings the parser configuration
*/
public TsvParser(TsvParserSettings settings) {
super(settings);
ignoreTrailingWhitespace = settings.getIgnoreTrailingWhitespaces();
ignoreLeadingWhitespace = settings.getIgnoreLeadingWhitespaces();
joinLines = settings.isLineJoiningEnabled();
TsvFormat format = settings.getFormat();
newLine = format.getNormalizedNewline();
escapeChar = settings.getFormat().getEscapeChar();
escapedTabChar = format.getEscapedTabChar();
}
@Override
protected void initialize() {
output.trim = ignoreTrailingWhitespace;
}
/**
* {@inheritDoc}
*/
@Override
protected void parseRecord() {
if (ignoreLeadingWhitespace && ch != '\t' && ch <= ' ' && whitespaceRangeStart < ch) {
ch = input.skipWhitespace(ch, '\t', escapeChar);
}
while (ch != newLine) {
parseField();
if (ch != newLine) {
ch = input.nextChar();
if (ch == newLine) {
output.emptyParsed();
}
}
}
}
private void parseField() {
if (ignoreLeadingWhitespace && ch != '\t' && ch <= ' ' && whitespaceRangeStart < ch) {
ch = input.skipWhitespace(ch, '\t', escapeChar);
}
if (ch == '\t') {
output.emptyParsed();
} else {
while (ch != '\t' && ch != newLine) {
if (ch == escapeChar) {
ch = input.nextChar();
if (ch == 't' || ch == escapedTabChar) {
output.appender.append('\t');
} else if (ch == 'n') {
output.appender.append('\n');
} else if (ch == '\\') {
output.appender.append('\\');
} else if (ch == 'r') {
output.appender.append('\r');
} else if (ch == newLine && joinLines) {
output.appender.append(newLine);
} else {
output.appender.append(escapeChar);
if (ch == newLine || ch == '\t') {
break;
}
output.appender.append(ch);
}
ch = input.nextChar();
} else {
ch = output.appender.appendUntil(ch, input, '\t', escapeChar, newLine);
}
}
output.valueParsed();
}
}
}
| 29.445378
| 138
| 0.635274
|
b4c1f39205d03b1d7bab05636c8a54d0fb3a0a92
| 1,317
|
package com.rosendo.ejercicioentregable4;
import java.util.ArrayList;
public class GestorSeries {
public ArrayList<Serie> getSeries() {
ArrayList<Serie> series=new ArrayList<Serie>();
series.add(new Serie("Pocoyó", "La historia de Pocoyó",2005,4,"https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_700,h_474/http://www.mamisybebes.com/wp-content/uploads/2007/08/Pocoyo-logo-post1.jpg"));
series.add(new Serie("Doraemon", "La historia de Doraemon",1973,4,"https://www.latercera.com/resizer/WpZBplzkLu8X4DNZX4oQB38DjDg=/900x600/smart/arc-anglerfish-arc2-prod-copesa.s3.amazonaws.com/public/6NVTT7OLVRCMLDZ33LWJAAIBQI.png"));
series.add(new Serie("Peppa Pig", "La historia de Peppa Pig",2004,6,"https://wallery.app/dufovot/peppa-pig-house-wallpaper-500x667.jpg"));
series.add(new Serie("LadyBug","La historia de LadyBug",2015,4,"https://gaptain.com/blog/wp-content/uploads/2018/05/Juego-Ladybug.jpg"));
series.add(new Serie("Bob Esponja","La historia de Bob",1999,13,"https://sp-ao.shortpixel.ai/client/to_webp,q_glossy,ret_img,w_960,h_720/https://www.cosas-que-pasan.com/wp-content/uploads/portada-facebook-bob-esponja.jpg"));
series.add(new Serie("Pokémon","la histoia de pokemon",1997,24,"https://somoskudasai.com/wp-content/uploads/2019/08/portada-pokemon.jpg"));
return series;
}
}
| 69.315789
| 236
| 0.766135
|
cc654ba51d5454e73a507003b03289cb34c136e6
| 9,159
|
package com.thomsonreuters.upa.codec;
import com.thomsonreuters.upa.codec.Qos;
/**
* UPA {@link RequestMsg} is used by an OMM consumer to express interest in a
* particular information stream. The request's msgKey members help identify the
* stream and priority information can be used to indicate the streams
* importance to the consumer. {@link Qos} information can be used to express
* either a specific desired QoS or a range of acceptable qualities of service
* that can satisfy the request.
* <p>
* When a {@link RequestMsg} is issued with a new streamId, this is considered
* a request to open the stream. If requested information is available and the
* consumer is entitled to receive the information, this will typically result
* in a {@link RefreshMsg} being delivered to the consumer, though a
* {@link StatusMsg} is also possible - either message can be used to indicate a
* stream is open. If information is not available or the user is not entitled,
* a {@link StatusMsg} is typically delivered to provide more detailed
* information to the consumer.
* <p>
* Issuing a {@link RequestMsg} on an existing stream allows a consumer to
* modify some parameters associated with the stream. Also known as a reissue,
* this can be used to Pause or Resume a stream, change a Dynamic View, increase
* or decrease the streams priority or request that a new refresh is delivered.
*
*
* @see Msg
* @see RequestMsgFlags
*/
public interface RequestMsg extends Msg
{
/**
* Checks the presence of the Extended Header presence flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkHasExtendedHdr();
/**
* Checks the presence of the Priority presence flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkHasPriority();
/**
* Checks the presence of the Streaming indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkStreaming();
/**
* Checks the presence of the Message Key presence flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkMsgKeyInUpdates();
/**
* Checks the presence of the Conflation Info presence flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkConfInfoInUpdates();
/**
* Checks the presence of the No Refresh indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkNoRefresh();
/**
* Checks the presence of the Quality of Service presence flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkHasQos();
/**
* Checks the presence of the Worst Quality of Service presence flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkHasWorstQos();
/**
** Checks the presence of the Private Stream indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
**
** @return true - if exists; false if does not exist.
**/
public boolean checkPrivateStream();
/**
* Checks the presence of the Pause indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkPause();
/**
* Checks the presence of the View indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkHasView();
/**
* Checks the presence of the Batch indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
*
* @return true - if exists; false if does not exist.
*/
public boolean checkHasBatch();
/**
** Checks the presence of the Qualified Stream indication flag.
*
* <p>Flags may also be bulk-get via {@link Msg#flags()}.
*
* @see Msg#flags()
**
** @return true - if exists; false if does not exist.
**/
public boolean checkQualifiedStream();
/**
* Applies the Extended Header presence flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyHasExtendedHdr();
/**
* Applies the Priority presence flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyHasPriority();
/**
* Applies the Streaming indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyStreaming();
/**
* Applies the Message Key presence flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyMsgKeyInUpdates();
/**
* Applies the Conflation Information in Updates indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyConfInfoInUpdates();
/**
* Applies the No Refresh indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyNoRefresh();
/**
* Applies the Quality of Service presence flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyHasQos();
/**
* Applies the Worst Quality of Service presence flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyHasWorstQos();
/**
** Applies the Private Stream indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
**/
public void applyPrivateStream();
/**
* Applies the Pause indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyPause();
/**
* Applies the View indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyHasView();
/**
* Applies the Batch indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
*/
public void applyHasBatch();
/**
** Applies the Qualified Stream indication flag.
*
* <p>Flags may also be bulk-set via {@link Msg#flags(int)}.
*
* @see Msg#flags(int)
**/
public void applyQualifiedStream();
/**
* Priority Structure (priority for the requested stream).
*
* @return the priority
*/
public Priority priority();
/**
* QoS for the requested stream.
* <ul>
* <li>When specified without a worstQos member, this is the only allowable
* QoS for the requested stream. If this QoS is unavailable, the stream is not opened.</li>
* <li>When specified with a worstQos, this is the best in the range of
* allowable QoSs. When a QoS range is specified, any QoS within the range
* is acceptable for servicing the stream.</li>
* </ul>
* <p>
* If neither qos nor worstQos are present on the request, this indicates
* that any available QoS will satisfy the request. Some components may
* require qos on initial request and reissue messages.
*
* @return the qos
*/
public Qos qos();
/**
* The least acceptable QoS for the requested stream. When specified with a
* qos value, this is the worst in the range of allowable QoSs. When a QoS
* range is specified, any QoS within the range is acceptable for servicing the stream.
*
* @return the worstQos
*/
public Qos worstQos();
}
| 28.095092
| 95
| 0.600066
|
f7819061a2ca0b9462308f72a2b4b03d25ff7f78
| 17,541
|
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.identity.application.mgt.listener;
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException;
import org.wso2.carbon.identity.application.common.model.ApplicationBasicInfo;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import org.wso2.carbon.identity.application.mgt.dao.ApplicationDAO;
import org.wso2.carbon.identity.core.model.IdentityEventListenerConfig;
import org.wso2.carbon.identity.core.util.IdentityCoreConstants;
import org.wso2.carbon.identity.core.util.IdentityUtil;
/**
* Abstract implementation for the {@link ApplicationMgtListener}.
*/
public abstract class AbstractApplicationMgtListener implements ApplicationMgtListener {
public boolean doPreCreateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPostCreateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPreUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPostUpdateApplication(ServiceProvider serviceProvider, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPreDeleteApplication(String applicationName, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPostDeleteApplication(String applicationName, String tenantDomain, String userName)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPreGetServiceProvider(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPostGetServiceProvider(ServiceProvider serviceProvider, String applicationName,
String tenantDomain) throws IdentityApplicationManagementException {
return true;
}
public boolean doPreGetServiceProviderByClientId(String clientId, String clientType,
String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
public boolean doPostGetServiceProviderByClientId(ServiceProvider serviceProvider, String clientId,
String clientType,
String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPreGetAllApplicationBasicInfo(String tenantDomain, String username)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPostGetAllApplicationBasicInfo(ApplicationDAO appDAO, String tenantDomain, String username)
throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions before getting all applications' basic information for matching filter.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain
* @param username
* @param filter
* @return
* @throws IdentityApplicationManagementException
*/
public boolean doPreGetApplicationBasicInfo(String tenantDomain, String username, String filter)
throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information for matching filter.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param appDAO
* @param tenantDomain
* @param username
* @param filter
* @return
* @throws IdentityApplicationManagementException
*/
public boolean doPostGetApplicationBasicInfo(ApplicationDAO appDAO, String tenantDomain, String username,
String filter) throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information with pagination.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param appDAO
* @param tenantDomain
* @param username
* @return
* @throws IdentityApplicationManagementException
* @Deprecated The logic in pagination is improved to use an offset and a limit. Hence deprecating this method to
* use {@link AbstractApplicationMgtListener#doPreGetApplicationBasicInfo(String, String, int, int)} method.
*/
public boolean doPostGetPaginatedApplicationBasicInfo(ApplicationDAO appDAO, String tenantDomain, String username,
int pageNumber)
throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information for matching filter with
* pagination.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param appDAO
* @param tenantDomain
* @param username
* @param filter
* @return
* @throws IdentityApplicationManagementException
*/
public boolean doPostGetPaginatedApplicationBasicInfo(ApplicationDAO appDAO, String tenantDomain, String username,
int pageNumber,
String filter) throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions before getting all applications' basic information with pagination.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain
* @param username
* @return
* @throws IdentityApplicationManagementException
*/
@Deprecated
public boolean doPreGetPaginatedApplicationBasicInfo(String tenantDomain, String username, int pageNumber)
throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information with pagination.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain
* @param username
* @param applicationBasicInfoList
* @return
* @throws IdentityApplicationManagementException
* @Deprecated The logic in pagination is improved to use an offset and a limit. Hence deprecating this method to
* use {@link AbstractApplicationMgtListener#doPostGetApplicationBasicInfo(String, String, int, int,
* ApplicationBasicInfo[])} method.
*/
@Deprecated
public boolean doPostGetPaginatedApplicationBasicInfo(String tenantDomain, String username, int pageNumber,
ApplicationBasicInfo[] applicationBasicInfoList) throws
IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions before getting all applications' basic information with pagination based on the
* offset and limit.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain Tenant Domain.
* @param username User name.
* @param offset Starting index of the count.
* @param limit Counting value.
* @return A boolean value.
* @throws IdentityApplicationManagementException
*/
public boolean doPreGetApplicationBasicInfo(String tenantDomain, String username, int offset, int limit)
throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information with pagination based on the
* offset and limit.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain Tenant Domain.
* @param username User name.
* @param offset Starting index of the count.
* @param limit Counting value.
* @param applicationBasicInfoList Array of {@link ApplicationBasicInfo} instances.
* @return A boolean value.
* @throws IdentityApplicationManagementException
*/
public boolean doPostGetApplicationBasicInfo(String tenantDomain, String username, int offset, int limit
, ApplicationBasicInfo[] applicationBasicInfoList) throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions before getting all applications' basic information for matching filter with
* pagination.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain
* @param username
* @param filter
* @return
* @throws IdentityApplicationManagementException
* @Deprecated The logic in pagination is improved to use an offset and a limit. Hence deprecating this method to
* use {@link AbstractApplicationMgtListener#doPreGetApplicationBasicInfo(String, String, String, int, int)} method.
*/
@Deprecated
public boolean doPreGetPaginatedApplicationBasicInfo(String tenantDomain, String username, int pageNumber, String
filter) throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information for matching filter with
* pagination.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain
* @param username
* @param filter
* @param applicationBasicInfoList
* @return
* @throws IdentityApplicationManagementException
* @Deprecated The logic in pagination is improved to use an offset and a limit. Hence deprecating this method to
* use {@link AbstractApplicationMgtListener#doPostGetApplicationBasicInfo(String, String, String, int, int,
* ApplicationBasicInfo[])} method.
*/
@Deprecated
public boolean doPostGetPaginatedApplicationBasicInfo(String tenantDomain, String
username, int pageNumber, String filter, ApplicationBasicInfo[] applicationBasicInfoList) throws
IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions before getting all applications' basic information for matching filter with
* pagination based on the offset and limit.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain Tenant Domain.
* @param username User name.
* @param filter Application name filter.
* @param offset Starting index of the count.
* @param limit Counting value.
* @return A boolean value.
* @throws IdentityApplicationManagementException
*/
public boolean doPreGetApplicationBasicInfo(String tenantDomain, String username, String filter, int offset,
int limit) throws IdentityApplicationManagementException {
return true;
}
/**
* Define any additional actions after getting all applications' basic information for matching filter with
* pagination based on the offset and limit.
* This method will be included in ApplicationMgtListener interface when Java 8 is supported.
*
* @param tenantDomain Tenant Domain.
* @param username User name.
* @param filter Application name filter.
* @param offset Starting index of the count.
* @param limit Counting value.
* @param applicationBasicInfoList Array of {@link ApplicationBasicInfo} instances.
* @return A boolean value.
* @throws IdentityApplicationManagementException
*/
public boolean doPostGetApplicationBasicInfo(String tenantDomain, String username, String filter, int offset,
int limit, ApplicationBasicInfo[] applicationBasicInfoList)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPreGetApplicationExcludingFileBasedSPs(String applicationName, String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPostGetApplicationExcludingFileBasedSPs(ServiceProvider serviceProvider, String applicationName,
String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPreGetServiceProviderNameByClientId(String clientId, String clientType, String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPostGetServiceProviderNameByClientId(String name, String clientId, String clientType,
String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPreGetServiceProviderNameByClientIdExcludingFileBasedSPs(String name, String clientId, String type,
String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPostGetServiceProviderNameByClientIdExcludingFileBasedSPs(String name, String clientId,
String type, String tenantDomain) {
return true;
}
@Override
public void doImportServiceProvider(ServiceProvider serviceProvider) throws IdentityApplicationManagementException {
return;
}
@Override
public void doExportServiceProvider(ServiceProvider serviceProvider, Boolean exportSecrets)
throws IdentityApplicationManagementException {
return;
}
@Override
public void onPreCreateInbound(ServiceProvider serviceProvider, boolean isUpdate) throws
IdentityApplicationManagementException {
return;
}
@Override
public boolean doPreCreateApplicationTemplate(ServiceProvider serviceProvider, String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
@Override
public boolean doPreUpdateApplicationTemplate(ServiceProvider serviceProvider, String tenantDomain)
throws IdentityApplicationManagementException {
return true;
}
public boolean isEnable() {
IdentityEventListenerConfig identityEventListenerConfig = IdentityUtil.readEventListenerProperty
(ApplicationMgtListener.class.getName(), this.getClass().getName());
if (identityEventListenerConfig == null) {
return true;
}
if (StringUtils.isNotBlank(identityEventListenerConfig.getEnable())) {
return Boolean.parseBoolean(identityEventListenerConfig.getEnable());
} else {
return true;
}
}
public int getExecutionOrderId() {
IdentityEventListenerConfig identityEventListenerConfig = IdentityUtil.readEventListenerProperty
(ApplicationMgtListener.class.getName(), this.getClass().getName());
int orderId;
if (identityEventListenerConfig == null) {
orderId = IdentityCoreConstants.EVENT_LISTENER_ORDER_ID;
} else {
orderId = identityEventListenerConfig.getOrder();
}
if (orderId != IdentityCoreConstants.EVENT_LISTENER_ORDER_ID) {
return orderId;
}
return getDefaultOrderId();
}
}
| 39.066815
| 120
| 0.685993
|
2b2729254b388572741d934d69a96a87f338f143
| 1,837
|
package io.github.Leonardo0013YT.UltraCTW.menus;
import io.github.Leonardo0013YT.UltraCTW.UltraCTW;
import io.github.Leonardo0013YT.UltraCTW.game.GameFlag;
import io.github.Leonardo0013YT.UltraCTW.game.GamePlayer;
import io.github.Leonardo0013YT.UltraCTW.shop.Shop;
import io.github.Leonardo0013YT.UltraCTW.shop.ShopItem;
import io.github.Leonardo0013YT.UltraCTW.team.FlagTeam;
import io.github.Leonardo0013YT.UltraCTW.upgrades.Upgrade;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
public class FlagMenu {
private UltraCTW plugin;
public FlagMenu(UltraCTW plugin) {
this.plugin = plugin;
}
public void createMainUpgradeMenu(Player p) {
Inventory inv = Bukkit.createInventory(null, 36, plugin.getLang().get("menus.upgrades.title"));
GameFlag gf = plugin.getGm().getGameFlagByPlayer(p);
FlagTeam ft = gf.getTeamPlayer(p);
GamePlayer gp = gf.getGamePlayer(p);
for (Upgrade upgrade : plugin.getUm().getUpgrades().values()) {
inv.setItem(upgrade.getSlot(), upgrade.getIcon(ft, gp));
}
p.openInventory(inv);
}
public void createMainBuffDebuffMenu(Player p) {
Inventory inv = Bukkit.createInventory(null, 36, plugin.getLang().get("menus.buffDebuff.title"));
for (Shop shop : plugin.getUm().getShops().values()) {
inv.setItem(shop.getSlot(), shop.getIcon());
}
p.openInventory(inv);
}
public void createShopItemsMenu(Player p, Shop shop, GamePlayer gp) {
Inventory inv = Bukkit.createInventory(null, 36, plugin.getLang().get("menus.buffItems.title"));
for (ShopItem upgrade : shop.getItems().values()) {
inv.setItem(upgrade.getSlot(), upgrade.getIcon(gp));
}
p.openInventory(inv);
}
}
| 37.489796
| 105
| 0.693522
|
a935cda6aacb8d9b865841bfa3f57a5ce5fa56fb
| 1,367
|
package com.techreturners.exercise001;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Exercise001 {
// In this Kata, you will be given an array of numbers in which two numbers occur once and the rest occur only twice.
// Your task will be to return the sum of the numbers that occur only once.
// For example, repeats([4,5,7,5,4,8]) = 15 because only the numbers 7 and 8 occur once, and their sum is 15.
// More examples in exercise001 test cases.
// Good luck!
public int singles(int [] arr) {
// Add your code here!
List<Integer> numbers = new ArrayList<Integer>(arr.length);
for (int i : arr)
{
numbers.add(i);
}
int count;
List<Integer> singleDigits = new ArrayList<>();
for (int num : numbers) {
count = Collections.frequency(numbers, num);
if (count == 1) {
singleDigits.add(num);
}
}
return sumOfNumbers(singleDigits);
}
private static int sumOfNumbers (List < Integer > singleDigits) {
int sum = 0;
for (int digit : singleDigits) {
sum = sum + digit;
}
return sum;
}
}
| 29.717391
| 122
| 0.556693
|
0c0d04b87bc7eb39447c786cde1bd64cf22ed2e2
| 72,850
|
package org.drip.product.creator;
/*
* -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*/
/*!
* Copyright (C) 2017 Lakshmi Krishnamurthy
* Copyright (C) 2016 Lakshmi Krishnamurthy
* Copyright (C) 2015 Lakshmi Krishnamurthy
* Copyright (C) 2014 Lakshmi Krishnamurthy
* Copyright (C) 2013 Lakshmi Krishnamurthy
* Copyright (C) 2012 Lakshmi Krishnamurthy
* Copyright (C) 2011 Lakshmi Krishnamurthy
*
* This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model
* libraries targeting analysts and developers
* https://lakshmidrip.github.io/DRIP/
*
* DRIP is composed of four main libraries:
*
* - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/
* - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/
* - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/
* - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/
*
* - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options,
* Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA
* Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV
* Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM
* Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics.
*
* - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy
* Incorporator, Holdings Constraint, and Transaction Costs.
*
* - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality.
*
* - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning.
*
* 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.
*/
/**
* BondRefDataBuilder holds the entire set of static parameters for the bond product. In particular, it contains
* the bond identifier parameters (ISIN, CUSIP, BBG ID, name short name), the issuer level parameters
* (Ticker, category, industry, issue type, issuer country, issuer country code, collateral type,
* description, security type, unique Bloomberg ID, long company name, issuer name, SPN or the credit
* curve string), issue parameters (issue amount, issue price, outstanding amount, minimum piece,
* minimum increment, par amount, lead manager, exchange code, country of incorporation, country of
* guarantor, country of domicile, industry sector, industry group, industry sub-group, senior/sub),
* coupon parameters (coupon rate, coupon frequency, coupon type, day count), maturity parameters
* (maturity date, maturity type, final maturity, redemption value), date parameters (announce, first
* settle, first coupon, interest accrual start, next coupon, previous coupon, penultimate coupon, and
* issue dates), embedded option parameters (callable, putable, has been exercised), currency parameters
* (trade, coupon, and redemption currencies), floater parameters (floater flag, floating coupon
* convention, current coupon, rate index, spread), trade status, ratings (SnP, Moody, and Fitch), and
* whether the bond is private placement, is registered, is a bearer bond, is reverse convertible, is a
* structured note, can be unit traded, is perpetual or has defaulted.
*
* @author Lakshmi Krishnamurthy
*/
public class BondRefDataBuilder implements org.drip.product.params.Validatable {
private static final boolean m_bBlog = false;
private static final boolean m_bDisplayWarnings = true;
/**
* ISIN
*/
public java.lang.String _strISIN = "";
/**
* CUSIP
*/
public java.lang.String _strCUSIP = "";
/**
* Bloomberg ID
*/
public java.lang.String _strBBGID = "";
/**
* Issuer Category
*/
public java.lang.String _strIssuerCategory = "";
/**
* Ticker
*/
public java.lang.String _strTicker = "";
/**
* Series
*/
public java.lang.String _strSeries = "";
/**
* Name
*/
public java.lang.String _strName = "";
/**
* Short Name
*/
public java.lang.String _strShortName = "";
/**
* Issuer Industry
*/
public java.lang.String _strIssuerIndustry = "";
/**
* Coupon Type
*/
public java.lang.String _strCouponType = "";
/**
* Maturity Type
*/
public java.lang.String _strMaturityType = "";
/**
* Calculation Type
*/
public java.lang.String _strCalculationType = "";
/**
* Day Count Code
*/
public java.lang.String _strDayCountCode = "";
/**
* Market Issue Type
*/
public java.lang.String _strMarketIssueType = "";
/**
* Issue Country Code
*/
public java.lang.String _strIssueCountryCode = "";
/**
* Issue Country
*/
public java.lang.String _strIssueCountry = "";
/**
* Collateral Type
*/
public java.lang.String _strCollateralType = "";
/**
* Issue Amount
*/
public double _dblIssueAmount = java.lang.Double.NaN;
/**
* Outstanding Amount
*/
public double _dblOutstandingAmount = java.lang.Double.NaN;
/**
* Minimum Piece
*/
public double _dblMinimumPiece = java.lang.Double.NaN;
/**
* Minimum Increment
*/
public double _dblMinimumIncrement = java.lang.Double.NaN;
/**
* Par Amount
*/
public double _dblParAmount = java.lang.Double.NaN;
/**
* Lead Manager
*/
public java.lang.String _strLeadManager = "";
/**
* Exchange Code
*/
public java.lang.String _strExchangeCode = "";
/**
* Redemption Value
*/
public double _dblRedemptionValue = java.lang.Double.NaN;
/**
* Announce Date
*/
public org.drip.analytics.date.JulianDate _dtAnnounce = null;
/**
* First Settle Date
*/
public org.drip.analytics.date.JulianDate _dtFirstSettle = null;
/**
* First Coupon Date
*/
public org.drip.analytics.date.JulianDate _dtFirstCoupon = null;
/**
* Interest Accrual Start Date
*/
public org.drip.analytics.date.JulianDate _dtInterestAccrualStart = null;
/**
* Issue Date
*/
public org.drip.analytics.date.JulianDate _dtIssue = null;
/**
* Next Coupon Date
*/
public org.drip.analytics.date.JulianDate _dtNextCouponDate = null;
/**
* Callable flag
*/
public boolean _bIsCallable = false;
/**
* Putable flag
*/
public boolean _bIsPutable = false;
/**
* Sinkable flag
*/
public boolean _bIsSinkable = false;
/**
* Bloomberg Parent
*/
public java.lang.String _strBBGParent = "";
/**
* Country of Incorporation
*/
public java.lang.String _strCountryOfIncorporation = "";
/**
* Industry Sector
*/
public java.lang.String _strIndustrySector = "";
/**
* Industry Group
*/
public java.lang.String _strIndustryGroup = "";
/**
* Industry Sub Group
*/
public java.lang.String _strIndustrySubgroup = "";
/**
* Country of Guarantor
*/
public java.lang.String _strCountryOfGuarantor = "";
/**
* Country of Domicile
*/
public java.lang.String _strCountryOfDomicile = "";
/**
* Description
*/
public java.lang.String _strDescription = "";
/**
* Security Type
*/
public java.lang.String _strSecurityType = "";
/**
* Previous Coupon Date
*/
public org.drip.analytics.date.JulianDate _dtPrevCouponDate = null;
/**
* Unique Bloomberg ID
*/
public java.lang.String _strBBGUniqueID = "";
/**
* Long Company Name
*/
public java.lang.String _strLongCompanyName = "";
/**
* Flag indicating Structured Note
*/
public boolean _bIsStructuredNote = false;
/**
* Flag indicating whether unit traded
*/
public boolean _bIsUnitTraded = false;
/**
* Flag indicating is reverse convertible
*/
public boolean _bIsReversibleConvertible = false;
/**
* Redemption Currency
*/
public java.lang.String _strRedemptionCurrency = "";
/**
* Coupon Currency
*/
public java.lang.String _strCouponCurrency = "";
/**
* Trade Currency
*/
public java.lang.String _strTradeCurrency = "";
/**
* Is this a Bearer Bond
*/
public boolean _bIsBearer = false;
/**
* Is this registered
*/
public boolean _bIsRegistered = false;
/**
* Has this been called
*/
public boolean _bHasBeenCalled = false;
/**
* Issuer Name
*/
public java.lang.String _strIssuer = "";
/**
* Penultimate Coupon Date
*/
public org.drip.analytics.date.JulianDate _dtPenultimateCouponDate = null;
/**
* Float Coupon Convention
*/
public java.lang.String _strFloatCouponConvention = "";
/**
* Current Coupon
*/
public double _dblCurrentCoupon = java.lang.Double.NaN;
/**
* Is this bond a floater
*/
public boolean _bIsFloater = false;
/**
* Trade Status
*/
public boolean _bTradeStatus = false;
/**
* CDR Country Code
*/
public java.lang.String _strCDRCountryCode = "";
/**
* CDR Settle Code
*/
public java.lang.String _strCDRSettleCode = "";
/**
* Final Maturity Date
*/
public org.drip.analytics.date.JulianDate _dtFinalMaturity = null;
/**
* Is this a private placement
*/
public boolean _bIsPrivatePlacement = false;
/**
* Is this bond perpetual
*/
public boolean _bIsPerpetual = false;
/**
* Has this bond defaulted
*/
public boolean _bIsDefaulted = false;
/**
* Spread over the floater index for this bond
*/
public double _dblFloatSpread = java.lang.Double.NaN;
/**
* Floating rate index
*/
public java.lang.String _strRateIndex = "";
/**
* Moody's Rating
*/
public java.lang.String _strMoody = "";
/**
* SnP rating
*/
public java.lang.String _strSnP = "";
/**
* Fitch Rating
*/
public java.lang.String _strFitch = "";
/**
* Senior or Sub-ordinate
*/
public java.lang.String _strSnrSub = "";
/**
* Issuer SPN
*/
public java.lang.String _strIssuerSPN = "";
/**
* Issue Price
*/
public double _dblIssuePrice = java.lang.Double.NaN;
/**
* Coupon
*/
public double _dblCoupon = java.lang.Double.NaN;
/**
* Maturity
*/
public org.drip.analytics.date.JulianDate _dtMaturity = null;
private org.drip.analytics.date.JulianDate reconcileStartDate()
{
if (null != _dtInterestAccrualStart) return _dtInterestAccrualStart;
if (null != _dtFirstCoupon) return _dtFirstCoupon;
if (null != _dtIssue) return _dtIssue;
if (null != _dtFirstSettle) return _dtFirstSettle;
return _dtAnnounce;
}
/**
* Create BondRefDataBuilder object from java ResultSet SQL
*
* @param rs SQL ResultSet
*
* @return BondRefDataBuilder object
*/
public static final BondRefDataBuilder CreateFromResultSet (
final java.sql.ResultSet rs)
{
try {
BondRefDataBuilder brdb = new BondRefDataBuilder();
if (null == (brdb._strISIN = rs.getString ("ISIN"))) return null;
if (null == (brdb._strCUSIP = rs.getString ("CUSIP"))) return null;
brdb._strBBGID = rs.getString ("BBG_ID");
brdb._strIssuerCategory = rs.getString ("IssuerCategory");
brdb._strTicker = rs.getString ("Ticker");
if (!org.drip.quant.common.NumberUtil.IsValid (brdb._dblCoupon = rs.getDouble ("Coupon")))
return null;
brdb._dtMaturity = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry (rs.getDate
("Maturity"));
brdb._strSeries = rs.getString ("Series");
brdb._strName = rs.getString ("Name");
brdb._strShortName = rs.getString ("ShortName");
brdb._strIssuerIndustry = rs.getString ("IssuerIndustry");
brdb._strCouponType = rs.getString ("CouponType");
brdb._strMaturityType = rs.getString ("MaturityType");
brdb._strCalculationType = rs.getString ("CalculationType");
brdb._strDayCountCode = rs.getString ("DayCountConv");
brdb._strMarketIssueType = rs.getString ("MarketIssueType");
brdb._strIssueCountryCode = rs.getString ("IssueCountryCode");
brdb._strIssueCountry = rs.getString ("IssueCountry");
brdb._strCollateralType = rs.getString ("CollateralType");
brdb._dblIssueAmount = rs.getDouble ("IssueAmount");
brdb._dblOutstandingAmount = rs.getDouble ("OutstandingAmount");
brdb._dblMinimumPiece = rs.getDouble ("MinimumPiece");
brdb._dblMinimumIncrement = rs.getDouble ("MinimumIncrement");
brdb._dblParAmount = rs.getDouble ("ParAmount");
brdb._strLeadManager = rs.getString ("LeadManager");
brdb._strExchangeCode = rs.getString ("ExchangeCode");
brdb._dblRedemptionValue = rs.getDouble ("RedemptionValue");
brdb._dtNextCouponDate = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry (rs.getDate
("NextCouponDate"));
if (null == (brdb._dtAnnounce = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry
(rs.getDate ("AnnounceDate"))))
return null;
if (null == (brdb._dtFirstSettle = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry
(rs.getDate ("FirstSettleDate"))))
return null;
if (null == (brdb._dtFirstCoupon = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry
(rs.getDate ("FirstCouponDate"))))
return null;
if (null == (brdb._dtInterestAccrualStart =
org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry (rs.getDate ("AccrualStartDate"))))
return null;
if (null == (brdb._dtIssue = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry (rs.getDate
("IssueDate"))))
return null;
brdb._bIsCallable = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("IsCallable"));
brdb._bIsPutable = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("IsPutable"));
brdb._bIsSinkable = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("IsSinkable"));
brdb._strBBGParent = rs.getString ("BBGParent");
brdb._strCountryOfIncorporation = rs.getString ("CountryOfIncorporation");
brdb._strIndustrySector = rs.getString ("IndustrySector");
brdb._strIndustryGroup = rs.getString ("IndustryGroup");
brdb._strIndustrySubgroup = rs.getString ("IndustrySubgroup");
brdb._strCountryOfGuarantor = rs.getString ("CountryOfGuarantor");
brdb._strCountryOfDomicile = rs.getString ("CountryOfDomicile");
brdb._strDescription = rs.getString ("Description");
brdb._strSecurityType = rs.getString ("SecurityType");
brdb._dtPrevCouponDate = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry (rs.getDate
("PrevCouponDate"));
brdb._strBBGUniqueID = rs.getString ("BBUniqueID");
brdb._strLongCompanyName = rs.getString ("LongCompanyName");
brdb._strRedemptionCurrency = rs.getString ("RedemptionCurrency");
if (null == brdb._strRedemptionCurrency || brdb._strRedemptionCurrency.isEmpty()) return null;
brdb._strCouponCurrency = rs.getString ("CouponCurrency");
if (null == brdb._strCouponCurrency || brdb._strCouponCurrency.isEmpty()) return null;
brdb._bIsStructuredNote = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("StructuredNote"));
brdb._bIsUnitTraded = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("UnitTraded"));
brdb._bIsReversibleConvertible = org.drip.quant.common.StringUtil.ParseFromUnitaryString
(rs.getString ("ReverseConvertible"));
brdb._strTradeCurrency = rs.getString ("TradeCurrency");
if (null == brdb._strTradeCurrency || brdb._strTradeCurrency.isEmpty()) return null;
brdb._bIsBearer = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("Bearer"));
brdb._bIsRegistered = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("Registered"));
brdb._bHasBeenCalled = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("Called"));
brdb._strIssuer = rs.getString ("Issuer");
brdb._dtPenultimateCouponDate = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry
(rs.getDate ("PenultimateCouponDate"));
brdb._strFloatCouponConvention = rs.getString ("FloatCouponConvention");
brdb._dblCurrentCoupon = rs.getDouble ("CurrentCoupon");
brdb._bIsFloater = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("Floater"));
brdb._bTradeStatus = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("TradeStatus"));
brdb._strCDRCountryCode = rs.getString ("CDRCountryCode");
brdb._strCDRSettleCode = rs.getString ("CDRSettleCode");
brdb._strFloatCouponConvention = rs.getString ("FloatCouponConvention");
brdb._dtFinalMaturity = org.drip.analytics.date.DateUtil.MakeJulianFromRSEntry (rs.getDate
("FinalMaturity"));
brdb._bIsPrivatePlacement = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("PrivatePlacement"));
brdb._bIsPerpetual = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("Perpetual"));
brdb._bIsDefaulted = org.drip.quant.common.StringUtil.ParseFromUnitaryString (rs.getString
("Defaulted"));
brdb._dblFloatSpread = rs.getDouble ("FloatSpread");
brdb._strRateIndex = rs.getString ("RateIndex");
brdb._strMoody = rs.getString ("Moody");
brdb._strSnP = rs.getString ("SnP");
brdb._strFitch = rs.getString ("Fitch");
brdb._strSnrSub = rs.getString ("SnrSub");
brdb._strIssuerSPN = rs.getString ("SPN");
brdb._dblIssuePrice = rs.getDouble ("IssuePrice");
return brdb;
} catch (java.lang.Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Empty BondRefDataBuilder ctr - uninitialized members
*/
public BondRefDataBuilder()
{
}
/**
* BondRefDataBuilder de-serialization from input JSON Map
*
* @param mapJSON Input JSON Map
*
* @throws java.lang.Exception Thrown if BondRefDataBuilder cannot be properly de-serialized
*/
public BondRefDataBuilder (
final org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String> mapJSON)
throws java.lang.Exception
{
if (null == mapJSON || 0 == mapJSON.size())
throw new java.lang.Exception ("BondRefDataBuilder de-serializer: Invalid input JSON Map");
// double dblVersion = mapJSON.get ("version");
_strISIN = mapJSON.get ("isin");
_strCUSIP = mapJSON.get ("cusip");
_strBBGID = mapJSON.get ("bbgid");
_strIssuerCategory = mapJSON.get ("issuercategory");
_strTicker = mapJSON.get ("ticker");
_strSeries = mapJSON.get ("series");
_strName = mapJSON.get ("name");
_strShortName = mapJSON.get ("shortname");
_strIssuerIndustry = mapJSON.get ("issuerindustry");
_strCouponType = mapJSON.get ("coupontype");
_strMaturityType = mapJSON.get ("maturitytype");
_strCalculationType = mapJSON.get ("calculationtype");
_strDayCountCode = mapJSON.get ("daycountcode");
_strMarketIssueType = mapJSON.get ("marketissuetype");
_strIssueCountryCode = mapJSON.get ("issuecountrycode");
_strIssueCountry = mapJSON.get ("issuecountry");
_strCollateralType = mapJSON.get ("collateraltype");
_dblIssueAmount = new java.lang.Double (mapJSON.get ("issueamount"));
_dblOutstandingAmount = new java.lang.Double (mapJSON.get ("outstandingamount"));
_dblMinimumPiece = new java.lang.Double (mapJSON.get ("minimumpiece"));
_dblMinimumIncrement = new java.lang.Double (mapJSON.get ("minimumincrement"));
_dblParAmount = new java.lang.Double (mapJSON.get ("paramount"));
_strLeadManager = mapJSON.get ("leadmanager");
_strExchangeCode = mapJSON.get ("exchangecode");
_dblRedemptionValue = new java.lang.Double (mapJSON.get ("redemptionvalue"));
_dtAnnounce = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get ("announcedate"),
"-");
_dtFirstSettle = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("firstsettledate"), "-");
_dtFirstCoupon = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("firstcoupondate"), "-");
_dtInterestAccrualStart = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("interestaccrualstartdate"), "-");
_dtIssue = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get ("issuedate"), "-");
_dtNextCouponDate = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("nextcoupondate"), "-");
_bIsCallable = new java.lang.Boolean (mapJSON.get ("iscallable"));
_bIsPutable = new java.lang.Boolean (mapJSON.get ("isputabale"));
_bIsSinkable = new java.lang.Boolean (mapJSON.get ("issinkable"));
_strBBGParent = mapJSON.get ("bbgparent");
_strCountryOfIncorporation = mapJSON.get ("countryofincorporation");
_strIndustrySector = mapJSON.get ("industrysector");
_strIndustryGroup = mapJSON.get ("industrygroup");
_strIndustrySubgroup = mapJSON.get ("industrysubgroup");
_strCountryOfGuarantor = mapJSON.get ("countryofguarantor");
_strCountryOfDomicile = mapJSON.get ("countryofdomicile");
_strDescription = mapJSON.get ("description");
_strSecurityType = mapJSON.get ("securitytype");
_dtPrevCouponDate = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("prevcoupondate"), "-");
_strBBGUniqueID = mapJSON.get ("bbguniqueid");
_strLongCompanyName = mapJSON.get ("longcompanyname");
_bIsStructuredNote = new java.lang.Boolean (mapJSON.get ("isstructurednote"));
_bIsUnitTraded = new java.lang.Boolean (mapJSON.get ("isunittraded"));
_bIsReversibleConvertible = new java.lang.Boolean (mapJSON.get ("isreversibleconvertible"));
_strRedemptionCurrency = mapJSON.get ("redemptioncurrency");
_strCouponCurrency = mapJSON.get ("couponcurrency");
_strTradeCurrency = mapJSON.get ("tradecurrency");
_bIsBearer = new java.lang.Boolean (mapJSON.get ("isbearer"));
_bIsRegistered = new java.lang.Boolean (mapJSON.get ("isregistered"));
_bHasBeenCalled = new java.lang.Boolean (mapJSON.get ("hasbeencalled"));
_strIssuer = mapJSON.get ("issuer");
_dtPenultimateCouponDate = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("penultimatecoupondate"), "-");
_strFloatCouponConvention = mapJSON.get ("floatcouponconvention");
_dblCurrentCoupon = new java.lang.Double (mapJSON.get ("currentcoupon"));
_bIsFloater = new java.lang.Boolean (mapJSON.get ("isfloater"));
_bTradeStatus = new java.lang.Boolean (mapJSON.get ("tradestatus"));
_strCDRCountryCode = mapJSON.get ("cdrcountrycode");
_strCDRSettleCode = mapJSON.get ("cdrsettlecode");
_dtFinalMaturity = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get
("finalmaturitydate"), "-");
_bIsPrivatePlacement = new java.lang.Boolean (mapJSON.get ("isprivateplacement"));
_bIsPerpetual = new java.lang.Boolean (mapJSON.get ("isperpetual"));
_bIsDefaulted = new java.lang.Boolean (mapJSON.get ("isdefaulted"));
_dblFloatSpread = new java.lang.Double (mapJSON.get ("floatspread"));
_strRateIndex = mapJSON.get ("rateindex");
_strMoody = mapJSON.get ("moody");
_strSnP = mapJSON.get ("snp");
_strFitch = mapJSON.get ("fitch");
_strSnrSub = mapJSON.get ("snrsub");
_strIssuerSPN = mapJSON.get ("issuerspn");
_dblIssuePrice = new java.lang.Double (mapJSON.get ("issueprice"));
_dblCoupon = new java.lang.Double (mapJSON.get ("coupon"));
_dtMaturity = org.drip.analytics.date.DateUtil.MakeJulianFromYYYYMMDD (mapJSON.get ("maturitydate"),
"-");
}
/**
* Set the ISIN
*
* @param strISIN ISIN
*
* @return True (success), false (failure)
*/
public boolean setISIN (
final java.lang.String strISIN)
{
if (null == strISIN || strISIN.isEmpty()) return false;
_strISIN = strISIN;
return true;
}
/**
* Set the CUSIP
*
* @param strCUSIP CUSIP
*
* @return True (success), false (failure)
*/
public boolean setCUSIP (
final java.lang.String strCUSIP)
{
if (null == strCUSIP || strCUSIP.isEmpty()) return false;
_strCUSIP = strCUSIP;
return true;
}
/**
* Set the Bloomberg ID
*
* @param strBBGID Bloomberg ID String
*
* @return True (success), false (failure)
*/
public boolean setBBGID (
final java.lang.String strBBGID)
{
if (null == (_strBBGID = strBBGID)) _strBBGID = "";
return true;
}
/**
* Set the Issuer Category
*
* @param strIssuerCategory Issuer Category
*
* @return True (success), false (failure)
*/
public boolean setIssuerCategory (
final java.lang.String strIssuerCategory)
{
if (null == (_strIssuerCategory = strIssuerCategory)) _strIssuerCategory = "";
return true;
}
/**
* Set the Issuer Ticker
*
* @param strTicker Ticker
*
* @return True (success), false (failure)
*/
public boolean setTicker (
final java.lang.String strTicker)
{
if (null == (_strTicker = strTicker)) _strTicker = "";
return true;
}
/**
* Set the Issuer Series
*
* @param strSeries series
*
* @return True (success), false (failure)
*/
public boolean setSeries (
final java.lang.String strSeries)
{
if (null == (_strSeries = strSeries)) _strSeries = "";
return true;
}
/**
* Set the Issuer Name
*
* @param strName Name
*
* @return True (success), false (failure)
*/
public boolean setName (
final java.lang.String strName)
{
if (null == (_strName = strName)) _strName = "";
return true;
}
/**
* Set the Issuer Short Name
*
* @param strShortName Short Name
*
* @return True (success), false (failure)
*/
public boolean setShortName (
final java.lang.String strShortName)
{
if (null == (_strShortName = strShortName)) _strShortName = "";
return true;
}
/**
* Set the Issuer Industry
*
* @param strIssuerIndustry Issuer Industry
*
* @return True (success), false (failure)
*/
public boolean setIssuerIndustry (
final java.lang.String strIssuerIndustry)
{
if (null == (_strIssuerIndustry = strIssuerIndustry)) _strIssuerIndustry = "";
return true;
}
/**
* Set the Coupon Type
*
* @param strCouponType Coupon Type
*
* @return True (success), false (failure)
*/
public boolean setCouponType (
final java.lang.String strCouponType)
{
if (null == (_strCouponType = strCouponType)) _strCouponType = "";
return true;
}
/**
* Set the Maturity Type
*
* @param strMaturityType Maturity Type
*
* @return True (success), false (failure)
*/
public boolean setMaturityType (
final java.lang.String strMaturityType)
{
if (null == (_strMaturityType = strMaturityType)) _strMaturityType = "";
return true;
}
/**
* Set the Calculation Type
*
* @param strCalculationType Calculation Type
*
* @return True (success), false (failure)
*/
public boolean setCalculationType (
final java.lang.String strCalculationType)
{
if (null == (_strCalculationType = strCalculationType)) _strCalculationType = "";
return true;
}
/**
* Set the Day Count Code
*
* @param strDayCountCode Day Count Code
*
* @return True (success), false (failure)
*/
public boolean setDayCountCode (
final java.lang.String strDayCountCode)
{
_strDayCountCode = "Unknown DC";
try {
_strDayCountCode = org.drip.analytics.support.Helper.ParseFromBBGDCCode
(strDayCountCode);
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad dayCount " + strDayCountCode + " for ISIN " +
_strISIN);
return false;
}
return true;
}
/**
* Set the Market Issue Type
*
* @param strMarketIssueType Market Issue Type
*
* @return True (success), false (failure)
*/
public boolean setMarketIssueType (
final java.lang.String strMarketIssueType)
{
if (null == (_strMarketIssueType = strMarketIssueType)) _strMarketIssueType = "";
return true;
}
/**
* Set the Issue Country Code
*
* @param strIssueCountryCode Issue Country Code
*
* @return True (success), false (failure)
*/
public boolean setIssueCountryCode (
final java.lang.String strIssueCountryCode)
{
if (null == (_strIssueCountryCode = strIssueCountryCode)) _strIssueCountryCode = "";
return true;
}
/**
* Set the Issue Country
*
* @param strIssueCountry Issue Country
*
* @return True (success), false (failure)
*/
public boolean setIssueCountry (
final java.lang.String strIssueCountry)
{
if (null == (_strIssueCountry = strIssueCountry)) _strIssueCountry = "";
return true;
}
/**
* Set the Collateral Type
*
* @param strCollateralType Collateral Type
*
* @return True (success), false (failure)
*/
public boolean setCollateralType (
final java.lang.String strCollateralType)
{
if (null == (_strCollateralType = strCollateralType)) _strCollateralType = "";
return true;
}
/**
* Set the Issue Amount
*
* @param strIssueAmount Issue Amount
*
* @return True (success), false (failure)
*/
public boolean setIssueAmount (
final java.lang.String strIssueAmount)
{
try {
_dblIssueAmount = new java.lang.Double (strIssueAmount.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Issue Amount " + strIssueAmount + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Outstanding Amount
*
* @param strOutstandingAmount Outstanding Amount
*
* @return True (success), false (failure)
*/
public boolean setOutstandingAmount (
final java.lang.String strOutstandingAmount)
{
try {
_dblOutstandingAmount = new java.lang.Double (strOutstandingAmount.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Outstanding Amount " + strOutstandingAmount + " for ISIN " +
_strISIN);
}
return false;
}
/**
* Set the Minimum Piece
*
* @param strMinimumPiece Minimum Piece
*
* @return True (success), false (failure)
*/
public boolean setMinimumPiece (
final java.lang.String strMinimumPiece)
{
try {
_dblMinimumPiece = new java.lang.Double (strMinimumPiece.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Minimum Piece " + strMinimumPiece + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Minimum Increment
*
* @param strMinimumIncrement Minimum Increment
*
* @return True (success), false (failure)
*/
public boolean setMinimumIncrement (
final java.lang.String strMinimumIncrement)
{
try {
_dblMinimumIncrement = new java.lang.Double (strMinimumIncrement.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Minimum Increment " + strMinimumIncrement + " for ISIN " +
_strISIN);
}
return false;
}
/**
* Set the Par Amount
*
* @param strParAmount Par Amount
*
* @return True (success), false (failure)
*/
public boolean setParAmount (
final java.lang.String strParAmount)
{
try {
_dblParAmount = new java.lang.Double (strParAmount.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Par Amount " + strParAmount + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Lead Manager
*
* @param strLeadManager Lead Manager
*
* @return True (success), false (failure)
*/
public boolean setLeadManager (
final java.lang.String strLeadManager)
{
if (null == (_strLeadManager = strLeadManager)) _strLeadManager = "";
return true;
}
/**
* Set the Exchange Code
*
* @param strExchangeCode Exchange Code
*
* @return True (success), false (failure)
*/
public boolean setExchangeCode (
final java.lang.String strExchangeCode)
{
if (null == (_strExchangeCode = strExchangeCode)) _strExchangeCode = "";
return true;
}
/**
* Set the Redemption Value
*
* @param strRedemptionValue Redemption Value
*
* @return True (success), false (failure)
*/
public boolean setRedemptionValue (
final java.lang.String strRedemptionValue)
{
try {
_dblRedemptionValue = new java.lang.Double (strRedemptionValue.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Redemption Value " + strRedemptionValue + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Announce Date
*
* @param strAnnounce Announce Date String
*
* @return True (success), false (failure)
*/
public boolean setAnnounce (
final java.lang.String strAnnounce)
{
try {
_dtAnnounce = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate (strAnnounce.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Announce " + strAnnounce + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the First Settle
*
* @param strFirstSettle First Settle
*
* @return True (success), false (failure)
*/
public boolean setFirstSettle (
final java.lang.String strFirstSettle)
{
try {
_dtFirstSettle = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strFirstSettle.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad First Settle " + strFirstSettle + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the First Coupon
*
* @param strFirstCoupon First Coupon
*
* @return True (success), false (failure)
*/
public boolean setFirstCoupon (
final java.lang.String strFirstCoupon)
{
try {
_dtFirstCoupon = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strFirstCoupon.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad First Coupon " + strFirstCoupon + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Interest Accrual Start Date
*
* @param strInterestAccrualStart Interest Accrual Start Date
*
* @return True (success), false (failure)
*/
public boolean setInterestAccrualStart (
final java.lang.String strInterestAccrualStart)
{
try {
_dtInterestAccrualStart = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strInterestAccrualStart.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Announce " + strInterestAccrualStart + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Issue Date
*
* @param strIssue Issue Date
*
* @return True (success), false (failure)
*/
public boolean setIssue (
final java.lang.String strIssue)
{
try {
_dtIssue = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate (strIssue.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Issue " + strIssue + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Next Coupon Date
*
* @param strNextCouponDate Next Coupon Date
*
* @return True (success), false (failure)
*/
public boolean setNextCouponDate (
final java.lang.String strNextCouponDate)
{
try {
_dtNextCouponDate = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strNextCouponDate.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Next Coupon Date " + strNextCouponDate + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set whether is Callable
*
* @param strCallable Callable?
*
* @return True (success), false (failure)
*/
public boolean setIsCallable (
final java.lang.String strCallable)
{
if (null == strCallable) _bIsCallable = false;
if ("1".equalsIgnoreCase (strCallable))
_bIsCallable = true;
else
_bIsCallable = false;
return true;
}
/**
* Set whether is Putable
*
* @param strPutable Putable?
*
* @return True (success), false (failure)
*/
public boolean setIsPutable (
final java.lang.String strPutable)
{
if (null == strPutable) _bIsPutable = false;
if ("1".equalsIgnoreCase (strPutable))
_bIsPutable = true;
else
_bIsPutable = false;
return true;
}
/**
* Set whether is Sinkable
*
* @param strSinkable Sinkable?
*
* @return True (success), false (failure)
*/
public boolean setIsSinkable (
final java.lang.String strSinkable)
{
if (null == strSinkable) _bIsSinkable = false;
if ("1".equalsIgnoreCase (strSinkable))
_bIsSinkable = true;
else
_bIsSinkable = false;
return true;
}
/**
* Set the Bloomberg Parent
*
* @param strBBGParent Bloomberg Parent?
*
* @return True (success), false (failure)
*/
public boolean setBBGParent (
final java.lang.String strBBGParent)
{
if (null == (_strBBGParent = strBBGParent)) _strBBGParent = "";
return true;
}
/**
* Set the Country Of Incorporation
*
* @param strCountryOfIncorporation Country Of Incorporation
*
* @return True (success), false (failure)
*/
public boolean setCountryOfIncorporation (
final java.lang.String strCountryOfIncorporation)
{
if (null == (_strCountryOfIncorporation = strCountryOfIncorporation))
_strCountryOfIncorporation = "";
return true;
}
/**
* Set the Industry Sector
*
* @param strIndustrySector Industry Sector
*
* @return True (success), false (failure)
*/
public boolean setIndustrySector (
final java.lang.String strIndustrySector)
{
if (null == (_strIndustrySector = strIndustrySector)) _strIndustrySector = "";
return true;
}
/**
* Set the Industry Group
*
* @param strIndustryGroup Industry Group
*
* @return True (success), false (failure)
*/
public boolean setIndustryGroup (
final java.lang.String strIndustryGroup)
{
if (null == (_strIndustryGroup = strIndustryGroup)) _strIndustryGroup = "";
return true;
}
/**
* Set the Industry Subgroup
*
* @param strIndustrySubgroup Industry Subgroup
*
* @return True (success), false (failure)
*/
public boolean setIndustrySubgroup (
final java.lang.String strIndustrySubgroup)
{
if (null == (_strIndustrySubgroup = strIndustrySubgroup)) _strIndustrySubgroup = "";
return true;
}
/**
* Set the Country Of Guarantor
*
* @param strCountryOfGuarantor Country Of Guarantor
*
* @return True (success), false (failure)
*/
public boolean setCountryOfGuarantor (
final java.lang.String strCountryOfGuarantor)
{
if (null == (_strCountryOfGuarantor = strCountryOfGuarantor)) _strCountryOfGuarantor = "";
return true;
}
/**
* Set the Country Of Domicile
*
* @param strCountryOfDomicile Country Of Domicile
*
* @return True (success), false (failure)
*/
public boolean setCountryOfDomicile (
final java.lang.String strCountryOfDomicile)
{
if (null == (_strCountryOfDomicile = strCountryOfDomicile)) _strCountryOfDomicile = "";
return true;
}
/**
* Set the Description
*
* @param strDescription Description
*
* @return True (success), false (failure)
*/
public boolean setDescription (
final java.lang.String strDescription)
{
if (null == (_strDescription = strDescription)) _strDescription = "";
return true;
}
/**
* Set the Security Type
*
* @param strSecurityType Security Type
*
* @return True (success), false (failure)
*/
public boolean setSecurityType (
final java.lang.String strSecurityType)
{
if (null == (_strSecurityType = strSecurityType)) _strSecurityType = "";
return true;
}
/**
* Set the Previous Coupon Date
*
* @param strPrevCouponDate Previous Coupon Date
*
* @return True (success), false (failure)
*/
public boolean setPrevCouponDate (
final java.lang.String strPrevCouponDate)
{
try {
_dtPrevCouponDate = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strPrevCouponDate.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Prev Coupon Date " + strPrevCouponDate + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Unique Bloomberg ID
*
* @param strBBGUniqueID BBGUniqueID
*
* @return True (success), false (failure)
*/
public boolean setBBGUniqueID (
final java.lang.String strBBGUniqueID)
{
if (null == (_strBBGUniqueID = strBBGUniqueID)) _strBBGUniqueID = "";
return true;
}
/**
* Set the Long Company Name
*
* @param strLongCompanyName Long Company Name
*
* @return True (success), false (failure)
*/
public boolean setLongCompanyName (
final java.lang.String strLongCompanyName)
{
if (null == (_strLongCompanyName = strLongCompanyName)) _strLongCompanyName = "";
return true;
}
/**
* Set the Flag indicating Structured Note
*
* @param strIsStructuredNote Flag indicating Structured Note
*
* @return True (success), false (failure)
*/
public boolean setIsStructuredNote (
final java.lang.String strIsStructuredNote)
{
if (null == strIsStructuredNote) _bIsStructuredNote = false;
if ("1".equalsIgnoreCase (strIsStructuredNote))
_bIsStructuredNote = true;
else
_bIsStructuredNote = false;
return true;
}
/**
* Set the Flag indicating Unit Traded
*
* @param strIsUnitTraded Flag indicating Unit Traded
*
* @return True (success), false (failure)
*/
public boolean setIsUnitTraded (
final java.lang.String strIsUnitTraded)
{
if (null == strIsUnitTraded) _bIsUnitTraded = false;
if ("1".equalsIgnoreCase (strIsUnitTraded))
_bIsUnitTraded = true;
else
_bIsUnitTraded = false;
return true;
}
/**
* Set the Flag indicating Reverse Convertible
*
* @param strIsReversibleConvertible Flag indicating Reverse Convertible
*
* @return True (success), false (failure)
*/
public boolean setIsReversibleConvertible (
final java.lang.String strIsReversibleConvertible)
{
if (null == strIsReversibleConvertible) _bIsReversibleConvertible = false;
if ("1".equalsIgnoreCase (strIsReversibleConvertible))
_bIsReversibleConvertible = true;
else
_bIsReversibleConvertible = false;
return true;
}
/**
* Set the Redemption Currency
*
* @param strRedemptionCurrency Redemption Currency
*
* @return True (success), false (failure)
*/
public boolean setRedemptionCurrency (
final java.lang.String strRedemptionCurrency)
{
if (null == (_strRedemptionCurrency = strRedemptionCurrency)) return false;
return true;
}
/**
* Set the Coupon Currency
*
* @param strCouponCurrency Coupon Currency
*
* @return True (success), false (failure)
*/
public boolean setCouponCurrency (
final java.lang.String strCouponCurrency)
{
if (null == (_strCouponCurrency = strCouponCurrency)) return false;
return true;
}
/**
* Set the Trade Currency
*
* @param strTradeCurrency Trade Currency
*
* @return True (success), false (failure)
*/
public boolean setTradeCurrency (
final java.lang.String strTradeCurrency)
{
if (null == (_strTradeCurrency = strTradeCurrency)) return false;
return true;
}
/**
* Set the Flag indicating Bearer Bond
*
* @param strIsBearer Flag indicating Bearer Bond
*
* @return True (success), false (failure)
*/
public boolean setIsBearer (
final java.lang.String strIsBearer)
{
if (null == strIsBearer) _bIsBearer = false;
if ("1".equalsIgnoreCase (strIsBearer))
_bIsBearer = true;
else
_bIsBearer = false;
return true;
}
/**
* Set the Flag Registered
*
* @param strIsRegistered Flag indicating Is Registered
*
* @return True (success), false (failure)
*/
public boolean setIsRegistered (
final java.lang.String strIsRegistered)
{
if (null == strIsRegistered) _bIsRegistered = false;
if ("1".equalsIgnoreCase (strIsRegistered))
_bIsRegistered = true;
else
_bIsRegistered = false;
return true;
}
/**
* Set the Flag indicating If bond has been called
*
* @param strHasBeenCalled Flag indicating If bond has been called
*
* @return True (success), false (failure)
*/
public boolean setHasBeenCalled (
final java.lang.String strHasBeenCalled)
{
if (null == strHasBeenCalled) _bHasBeenCalled = false;
if ("1".equalsIgnoreCase (strHasBeenCalled))
_bHasBeenCalled = true;
else
_bHasBeenCalled = false;
return true;
}
/**
* Set the Issuer
*
* @param strIssuer Issuer Name
*
* @return True (success), false (failure)
*/
public boolean setIssuer (
final java.lang.String strIssuer)
{
if (null == (_strIssuer = strIssuer)) _strIssuer = "";
return true;
}
/**
* Set the Penultimate Coupon Date
*
* @param strPenultimateCouponDate setPenultimateCouponDate
*
* @return True (success), false (failure)
*/
public boolean setPenultimateCouponDate (
final java.lang.String strPenultimateCouponDate)
{
try {
_dtPenultimateCouponDate = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strPenultimateCouponDate.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Penultimate Coupon Date " + strPenultimateCouponDate + " for ISIN "
+ _strISIN);
}
return false;
}
/**
* Set the Float Coupon Convention
*
* @param strFloatCouponConvention Float Coupon Convention
*
* @return True (success), false (failure)
*/
public boolean setFloatCouponConvention (
final java.lang.String strFloatCouponConvention)
{
if (null == (_strFloatCouponConvention = strFloatCouponConvention)) _strFloatCouponConvention = "";
return true;
}
/**
* Set the Current Coupon
*
* @param strCurrentCoupon Current Coupon
*
* @return True (success), false (failure)
*/
public boolean setCurrentCoupon (
final java.lang.String strCurrentCoupon)
{
if (null == strCurrentCoupon || strCurrentCoupon.isEmpty() || "null".equalsIgnoreCase
(strCurrentCoupon))
_dblCurrentCoupon = 0.;
else {
try {
_dblCurrentCoupon = new java.lang.Double (strCurrentCoupon.trim()).doubleValue();
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Current Coupon " + strCurrentCoupon + " for ISIN " + _strISIN);
}
}
return false;
}
/**
* Set the Floater Flag
*
* @param strIsFloater Flag indicating Is Floater
*
* @return True (success), false (failure)
*/
public boolean setIsFloater (
final java.lang.String strIsFloater)
{
if (null == strIsFloater) _bIsFloater = false;
if ("1".equalsIgnoreCase (strIsFloater))
_bIsFloater = true;
else
_bIsFloater = false;
return true;
}
/**
* Set Trade Status
*
* @param strTradeStatus Trade Status
*
* @return True (success), false (failure)
*/
public boolean setTradeStatus (
final java.lang.String strTradeStatus)
{
if (null == strTradeStatus) _bTradeStatus = false;
if ("1".equalsIgnoreCase (strTradeStatus))
_bTradeStatus = true;
else
_bTradeStatus = false;
return true;
}
/**
* Set the CDR Country Code
*
* @param strCDRCountryCode CDR Country Code
*
* @return True (success), false (failure)
*/
public boolean setCDRCountryCode (
final java.lang.String strCDRCountryCode)
{
if (null == (_strCDRCountryCode = strCDRCountryCode)) _strCDRCountryCode = "";
return true;
}
/**
* Set the CDR Settle Code
*
* @param strCDRSettleCode CDR Settle Code
*
* @return True (success), false (failure)
*/
public boolean setCDRSettleCode (
final java.lang.String strCDRSettleCode)
{
if (null == (_strCDRSettleCode = strCDRSettleCode)) _strCDRSettleCode = "";
return true;
}
/**
* Set the Final Maturity
*
* @param strFinalMaturity Final Maturity
*
* @return True (success), false (failure)
*/
public boolean setFinalMaturity (
final java.lang.String strFinalMaturity)
{
try {
_dtFinalMaturity = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strFinalMaturity.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog)
System.out.println ("Bad Final Maturity " + strFinalMaturity + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Private Placement Flag
*
* @param strIsPrivatePlacement Flag indicating Is Private Placement
*
* @return True (success), false (failure)
*/
public boolean setIsPrivatePlacement (
final java.lang.String strIsPrivatePlacement)
{
if (null == strIsPrivatePlacement) _bIsPrivatePlacement = false;
if ("1".equalsIgnoreCase (strIsPrivatePlacement))
_bIsPrivatePlacement = true;
else
_bIsPrivatePlacement = false;
return true;
}
/**
* Set the Perpetual Flag
*
* @param strIsPerpetual Flag indicating Is Perpetual
*
* @return True (success), false (failure)
*/
public boolean setIsPerpetual (
final java.lang.String strIsPerpetual)
{
if (null == strIsPerpetual) _bIsPerpetual = false;
if ("1".equalsIgnoreCase (strIsPerpetual))
_bIsPerpetual = true;
else
_bIsPerpetual = false;
return true;
}
/**
* Set the Defaulted Flag
*
* @param strIsDefaulted Flag indicating Is Defaulted
*
* @return True (success), false (failure)
*/
public boolean setIsDefaulted (
final java.lang.String strIsDefaulted)
{
if (null == strIsDefaulted) _bIsDefaulted = false;
if ("1".equalsIgnoreCase (strIsDefaulted))
_bIsDefaulted = true;
else
_bIsDefaulted = false;
return true;
}
/**
* Set the Float Spread
*
* @param strFloatSpread Float Spread
*
* @return True (success), false (failure)
*/
public boolean setFloatSpread (
final java.lang.String strFloatSpread)
{
try {
_dblFloatSpread = new java.lang.Double (strFloatSpread.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Float Spread " + strFloatSpread + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the Rate Index
*
* @param strRateIndex Rate Index
*
* @return True (success), false (failure)
*/
public boolean setRateIndex (
final java.lang.String strRateIndex)
{
if (null == (_strRateIndex = strRateIndex)) _strRateIndex = "";
return true;
}
/**
* Set the Moodys Rating
*
* @param strMoody Moodys Rating
*
* @return True (success), false (failure)
*/
public boolean setMoody (
final java.lang.String strMoody)
{
if (null == (_strMoody = strMoody)) _strMoody = "";
return true;
}
/**
* Set the SnP Rating
*
* @param strSnP SnP Rating
*
* @return True (success), false (failure)
*/
public boolean setSnP (
final java.lang.String strSnP)
{
if (null == (_strSnP = strSnP)) _strSnP = "";
return true;
}
/**
* Set the Fitch Rating
*
* @param strFitch Fitch Rating
*
* @return True (success), false (failure)
*/
public boolean setFitch (
final java.lang.String strFitch)
{
if (null == (_strFitch = strFitch)) _strFitch = "";
return true;
}
/**
* Set Senior or Sub-ordinate
*
* @param strSnrSub Senior or Sub-ordinate
*
* @return True (success), false (failure)
*/
public boolean setSnrSub (
final java.lang.String strSnrSub)
{
if (null == (_strSnrSub = strSnrSub)) _strSnrSub = "";
return true;
}
/**
* Set Issuer SPN
*
* @param strIssuerSPN Issuer SPN
*
* @return True (success), false (failure)
*/
public boolean setIssuerSPN (
final java.lang.String strIssuerSPN)
{
if (null == (_strIssuerSPN = strIssuerSPN)) _strIssuerSPN = "";
return true;
}
/**
* Set Issue Price
*
* @param strIssuePrice Issue Price
*
* @return True (success), false (failure)
*/
public boolean setIssuePrice (
final java.lang.String strIssuePrice)
{
try {
_dblIssuePrice = new java.lang.Double (strIssuePrice.trim()).doubleValue();
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Issue Price " + strIssuePrice + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the coupon
*
* @param strCoupon Coupon
*
* @return True (success), false (failure)
*/
public boolean setCoupon (
final java.lang.String strCoupon)
{
if (null == strCoupon || strCoupon.isEmpty() || "null".equalsIgnoreCase (strCoupon)) _dblCoupon = 0.;
try {
_dblCoupon = new java.lang.Double (strCoupon.trim());
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad coupon " + strCoupon + " for ISIN " + _strISIN);
}
return false;
}
/**
* Set the maturity
*
* @param strMaturity maturity
*
* @return True (success), false (failure)
*/
public boolean setMaturity (
final java.lang.String strMaturity)
{
try {
if (null == (_dtMaturity = org.drip.analytics.date.DateUtil.MakeJulianDateFromBBGDate
(strMaturity.trim())))
return false;
return true;
} catch (java.lang.Exception e) {
if (m_bBlog) System.out.println ("Bad Maturity " + strMaturity + " for ISIN " + _strISIN);
}
return false;
}
@Override public boolean validate()
{
if (null == _strISIN || _strISIN.isEmpty() || null == _strCUSIP || _strCUSIP.isEmpty()) {
if (m_bDisplayWarnings)
System.out.println ("Check ISIN[" + _strISIN + "] or CUSIP[" + _strCUSIP + "]");
return false;
}
if (null == _dtInterestAccrualStart) {
if (null == (_dtInterestAccrualStart = reconcileStartDate())) {
if (m_bDisplayWarnings)
System.out.println ("All possible date init candidates are null for ISIN " + _strISIN);
return false;
}
}
if (null == _dtFirstCoupon) _dtFirstCoupon = reconcileStartDate();
if (null == _dtIssue) _dtIssue = reconcileStartDate();
if (null == _dtFirstSettle) _dtFirstSettle = reconcileStartDate();
if (null == _dtAnnounce) _dtAnnounce = reconcileStartDate();
return true;
}
/**
* Create an SQL Insert string for the given object
*
* @return SQL Insert string
*/
public java.lang.String makeSQLInsert()
{
java.lang.StringBuilder sb = new java.lang.StringBuilder();
sb.append ("insert into BondRefData values(");
sb.append ("'").append (_strISIN).append ("', ");
sb.append ("'").append (_strCUSIP).append ("', ");
sb.append ("'").append (_strBBGID).append ("', ");
sb.append ("'").append (_strIssuerCategory).append ("', ");
sb.append ("'").append (_strTicker).append ("', ");
sb.append ("'").append (_strSeries).append ("', ");
sb.append ("'").append (_strName).append ("', ");
sb.append ("'").append (_strShortName).append ("', ");
sb.append ("'").append (_strIssuerIndustry).append ("', ");
sb.append ("'").append (_strCouponType).append ("', ");
sb.append ("'").append (_strMaturityType).append ("', ");
sb.append ("'").append (_strCalculationType).append ("', ");
sb.append ("'").append (_strDayCountCode).append ("', ");
sb.append ("'").append (_strMarketIssueType).append ("', ");
sb.append ("'").append (_strIssueCountryCode).append ("', ");
sb.append ("'").append (_strIssueCountry).append ("', ");
sb.append ("'").append (_strCollateralType).append ("', ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblIssueAmount))
sb.append ("null, ");
else
sb.append (_dblIssueAmount).append (", ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblOutstandingAmount))
sb.append ("null, ");
else
sb.append (_dblOutstandingAmount).append (", ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblMinimumPiece))
sb.append ("null, ");
else
sb.append (_dblMinimumPiece).append (", ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblMinimumIncrement))
sb.append ("null, ");
else
sb.append (_dblMinimumIncrement).append (", ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblParAmount))
sb.append ("null, ");
else
sb.append (_dblParAmount).append (", ");
sb.append ("'").append (_strLeadManager).append ("', ");
sb.append ("'").append (_strExchangeCode).append ("', ");
sb.append (_dblRedemptionValue).append (", ");
sb.append ("'").append (_dtAnnounce.toOracleDate()).append ("', ");
sb.append ("'").append (_dtFirstSettle.toOracleDate()).append ("', ");
sb.append ("'").append (_dtFirstCoupon.toOracleDate()).append ("', ");
sb.append ("'").append (_dtInterestAccrualStart.toOracleDate()).append ("', ");
sb.append ("'").append (_dtIssue.toOracleDate()).append ("', ");
if (null == _dtNextCouponDate)
sb.append ("null, ");
else
sb.append ("'").append (_dtNextCouponDate.toOracleDate()).append ("', ");
sb.append ("'").append (_bIsCallable ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsPutable ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsSinkable ? 1 : 0).append ("', ");
sb.append ("'").append (_strBBGParent).append ("', "); // Done
sb.append ("'").append (_strCountryOfIncorporation).append ("', ");
sb.append ("'").append (_strIndustrySector).append ("', ");
sb.append ("'").append (_strIndustryGroup).append ("', ");
sb.append ("'").append (_strIndustrySubgroup).append ("', ");
sb.append ("'").append (_strCountryOfGuarantor).append ("', ");
sb.append ("'").append (_strCountryOfDomicile).append ("', ");
sb.append ("'").append (_strDescription).append ("', ");
sb.append ("'").append (_strSecurityType).append ("', ");
if (null == _dtPrevCouponDate)
sb.append ("null, ");
else
sb.append ("'").append (_dtPrevCouponDate.toOracleDate()).append ("', ");
sb.append ("'").append (_strBBGUniqueID).append ("', ");
sb.append ("'").append (_strLongCompanyName).append ("', ");
sb.append ("'").append (_strRedemptionCurrency).append ("', ");
sb.append ("'").append (_strCouponCurrency).append ("', ");
sb.append ("'").append (_bIsStructuredNote ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsUnitTraded ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsReversibleConvertible ? 1 : 0).append ("', ");
sb.append ("'").append (_strTradeCurrency).append ("', ");
sb.append ("'").append (_bIsBearer ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsRegistered ? 1 : 0).append ("', ");
sb.append ("'").append (_bHasBeenCalled ? 1 : 0).append ("', ");
sb.append ("'").append (_strIssuer).append ("', ");
if (null == _dtPenultimateCouponDate)
sb.append ("null, ");
else
sb.append ("'").append (_dtPenultimateCouponDate.toOracleDate()).append ("', ");
sb.append ("'").append (_strFloatCouponConvention).append ("', ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblCurrentCoupon))
sb.append ("null, ");
else
sb.append (_dblCurrentCoupon).append (", ");
sb.append ("'").append (_bIsFloater ? 1 : 0).append ("', ");
sb.append ("'").append (_bTradeStatus ? 1 : 0).append ("', ");
sb.append ("'").append (_strCDRCountryCode).append ("', ");
sb.append ("'").append (_strCDRSettleCode).append ("', ");
if (null == _dtFinalMaturity)
sb.append ("null, ");
else
sb.append ("'").append (_dtFinalMaturity.toOracleDate()).append ("', ");
sb.append ("'").append (_bIsPrivatePlacement ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsPerpetual ? 1 : 0).append ("', ");
sb.append ("'").append (_bIsDefaulted ? 1 : 0).append ("', ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblFloatSpread))
sb.append ("null, ");
else
sb.append (_dblFloatSpread).append (", ");
sb.append ("'").append (_strRateIndex).append ("', ");
sb.append ("'").append (_strMoody).append ("', ");
sb.append ("'").append (_strSnP).append ("', ");
sb.append ("'").append (_strFitch).append ("', ");
sb.append ("'").append (_strSnrSub).append ("', ");
sb.append ("'").append (_strIssuerSPN).append ("', ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblIssuePrice))
sb.append ("null, ");
else
sb.append (_dblIssuePrice).append (", ");
if (!org.drip.quant.common.NumberUtil.IsValid (_dblCoupon))
sb.append ("null, ");
else
sb.append (_dblCoupon).append (", ");
if (null == _dtMaturity)
sb.append ("null");
else
sb.append ("'").append (_dtMaturity.toOracleDate()).append ("'");
return sb.append (")").toString();
}
/**
* Create an SQL Delete string for the given object
*
* @return SQL Delete string
*/
public java.lang.String makeSQLDelete()
{
java.lang.StringBuilder sb = new java.lang.StringBuilder();
sb.append ("delete from BondRefData where ISIN = '").append (_strISIN).append
("' or CUSIP = '").append (_strCUSIP).append ("'");
return sb.toString();
}
public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String> toJSON()
{
org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String> mapJSON = new
org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.String>();
mapJSON.put ("version", "" + org.drip.quant.common.StringUtil.VERSION);
if (null == _strISIN || _strISIN.isEmpty())
mapJSON.put ("isin", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("isin", _strISIN);
if (null == _strCUSIP || _strCUSIP.isEmpty())
mapJSON.put ("cusip", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("cusip", _strCUSIP);
if (null == _strBBGID || _strBBGID.isEmpty())
mapJSON.put ("bbgid", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("bbgid", _strBBGID);
if (null == _strIssuerCategory || _strIssuerCategory.isEmpty())
mapJSON.put ("issuercategory", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuercategory", _strIssuerCategory);
if (null == _strTicker || _strTicker.isEmpty())
mapJSON.put ("ticker", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("ticker", _strTicker);
if (null == _strSeries || _strSeries.isEmpty())
mapJSON.put ("series", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("series", _strSeries);
if (null == _strName || _strName.isEmpty())
mapJSON.put ("name", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("name", _strName);
if (null == _strShortName || _strShortName.isEmpty())
mapJSON.put ("shortname", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("shortname", _strShortName);
if (null == _strIssuerIndustry || _strIssuerIndustry.isEmpty())
mapJSON.put ("issuerindustry", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuerindustry", _strIssuerIndustry);
if (null == _strCouponType || _strCouponType.isEmpty())
mapJSON.put ("coupontype", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("coupontype", _strCouponType);
if (null == _strMaturityType || _strMaturityType.isEmpty())
mapJSON.put ("maturitytype", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("maturitytype", _strMaturityType);
if (null == _strCalculationType || _strCalculationType.isEmpty())
mapJSON.put ("calculationtype", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("calculationtype", _strCalculationType);
if (null == _strDayCountCode || _strDayCountCode.isEmpty())
mapJSON.put ("daycountcode", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("daycountcode", _strDayCountCode);
if (null == _strMarketIssueType || _strMarketIssueType.isEmpty())
mapJSON.put ("marketissuetype", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("marketissuetype", _strMarketIssueType);
if (null == _strIssueCountryCode || _strIssueCountryCode.isEmpty())
mapJSON.put ("issuecountrycode", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuecountrycode", _strIssueCountryCode);
if (null == _strIssueCountry || _strIssueCountry.isEmpty())
mapJSON.put ("issuecountry", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuecountry", _strIssueCountry);
if (null == _strCollateralType || _strCollateralType.isEmpty())
mapJSON.put ("collateraltype", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("collateraltype", _strCollateralType);
mapJSON.put ("issueamount", "" + _dblIssueAmount);
mapJSON.put ("outstandingamount", "" + _dblOutstandingAmount);
mapJSON.put ("minimumpiece", "" + _dblMinimumPiece);
mapJSON.put ("minimumincrement", "" + _dblMinimumIncrement);
mapJSON.put ("paramount", "" + _dblParAmount);
if (null == _strLeadManager || _strLeadManager.isEmpty())
mapJSON.put ("leadmanager", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("leadmanager", _strLeadManager);
if (null == _strExchangeCode || _strExchangeCode.isEmpty())
mapJSON.put ("exchangecode", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("exchangecode", _strExchangeCode);
mapJSON.put ("redemptionvalue", "" + _dblRedemptionValue);
if (null == _dtAnnounce)
mapJSON.put ("announcedate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("announcedate", _dtAnnounce.toYYYYMMDD ("-"));
if (null == _dtFirstSettle)
mapJSON.put ("firstsettledate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("firstsettledate", _dtFirstSettle.toYYYYMMDD ("-"));
if (null == _dtFirstCoupon)
mapJSON.put ("firstcoupondate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("firstcoupondate", _dtFirstCoupon.toYYYYMMDD ("-"));
if (null == _dtInterestAccrualStart)
mapJSON.put ("interestaccrualstartdate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("interestaccrualstartdate", _dtInterestAccrualStart.toYYYYMMDD ("-"));
if (null == _dtIssue)
mapJSON.put ("issuedate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuedate", _dtIssue.toYYYYMMDD ("-"));
if (null == _dtNextCouponDate)
mapJSON.put ("nextcoupondate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("nextcoupondate", _dtNextCouponDate.toYYYYMMDD ("-"));
mapJSON.put ("iscallable", "" + _bIsCallable);
mapJSON.put ("isputable", "" + _bIsPutable);
mapJSON.put ("issinkable", "" + _bIsSinkable);
if (null == _strBBGParent || _strBBGParent.isEmpty())
mapJSON.put ("bbgparent", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("bbgparent", _strBBGParent);
if (null == _strCountryOfIncorporation || _strCountryOfIncorporation.isEmpty())
mapJSON.put ("countryofincorporation", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("countryofincorporation", _strCountryOfIncorporation);
if (null == _strIndustrySector || _strIndustrySector.isEmpty())
mapJSON.put ("industrysector", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("industrysector", _strIndustrySector);
if (null == _strIndustryGroup || _strIndustryGroup.isEmpty())
mapJSON.put ("industrygroup", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("industrygroup", _strIndustryGroup);
if (null == _strIndustrySubgroup || _strIndustrySubgroup.isEmpty())
mapJSON.put ("industrysubgroup", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("industrysubgroup", _strIndustrySubgroup);
if (null == _strCountryOfGuarantor || _strCountryOfGuarantor.isEmpty())
mapJSON.put ("countryofguarantor", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("countryofguarantor", _strCountryOfGuarantor);
if (null == _strCountryOfDomicile || _strCountryOfDomicile.isEmpty())
mapJSON.put ("countryofdomicile", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("countryofdomicile", _strCountryOfDomicile);
if (null == _strDescription || _strDescription.isEmpty())
mapJSON.put ("description", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("description", _strDescription);
if (null == _strSecurityType || _strSecurityType.isEmpty())
mapJSON.put ("securitytype", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("securitytype", _strSecurityType);
if (null == _dtPrevCouponDate)
mapJSON.put ("prevcoupondate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("prevcoupondate", _dtPrevCouponDate.toYYYYMMDD ("-"));
if (null == _strBBGUniqueID || _strBBGUniqueID.isEmpty())
mapJSON.put ("bbguniqueid", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("bbguniqueid", _strBBGUniqueID);
if (null == _strLongCompanyName || _strLongCompanyName.isEmpty())
mapJSON.put ("longcompanyname", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("longcompanyname", _strLongCompanyName);
mapJSON.put ("isstructurednote", "" + _bIsStructuredNote);
mapJSON.put ("isunittraded", "" + _bIsUnitTraded);
mapJSON.put ("isreversibleconvertible", "" + _bIsReversibleConvertible);
if (null == _strRedemptionCurrency || _strRedemptionCurrency.isEmpty())
mapJSON.put ("redemptioncurrency", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("redemptioncurrency", _strRedemptionCurrency);
if (null == _strCouponCurrency || _strCouponCurrency.isEmpty())
mapJSON.put ("couponcurrency", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("couponcurrency", _strCouponCurrency);
if (null == _strTradeCurrency || _strTradeCurrency.isEmpty())
mapJSON.put ("tradecurrency", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("tradecurrency", _strTradeCurrency);
mapJSON.put ("isbearer", "" + _bIsBearer);
mapJSON.put ("isregistered", "" + _bIsRegistered);
mapJSON.put ("hasbeencalled", "" + _bHasBeenCalled);
if (null == _strIssuer || _strIssuer.isEmpty())
mapJSON.put ("issuer", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuer", _strIssuer);
if (null == _dtPenultimateCouponDate)
mapJSON.put ("penultimatecoupondate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("penultimatecoupondate", _dtPenultimateCouponDate.toYYYYMMDD ("-"));
if (null == _strFloatCouponConvention || _strFloatCouponConvention.isEmpty())
mapJSON.put ("floatcouponconvention", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("floatcouponconvention", _strFloatCouponConvention);
mapJSON.put ("currentcoupon", "" + _dblCurrentCoupon);
mapJSON.put ("isfloater", "" + _bIsFloater);
mapJSON.put ("tradestatus", "" + _bTradeStatus);
if (null == _strCDRCountryCode || _strCDRCountryCode.isEmpty())
mapJSON.put ("cdrcountrycode", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("cdrcountrycode", _strCDRCountryCode);
if (null == _strCDRSettleCode || _strCDRSettleCode.isEmpty())
mapJSON.put ("cdrsettlecode", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("cdrsettlecode", _strCDRSettleCode);
if (null == _dtFinalMaturity)
mapJSON.put ("finalmaturitydate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("finalmaturitydate", _dtFinalMaturity.toYYYYMMDD ("-"));
mapJSON.put ("isprivateplacement", "" + _bIsPrivatePlacement);
mapJSON.put ("isperpetual", "" + _bIsPerpetual);
mapJSON.put ("isdefaulted", "" + _bIsDefaulted);
mapJSON.put ("floatspread", "" + _dblFloatSpread);
if (null == _strRateIndex || _strRateIndex.isEmpty())
mapJSON.put ("rateindex", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("rateindex", _strRateIndex);
if (null == _strMoody || _strMoody.isEmpty())
mapJSON.put ("moody", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("moody", _strMoody);
if (null == _strSnP || _strSnP.isEmpty())
mapJSON.put ("snp", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("snp", _strSnP);
if (null == _strFitch || _strFitch.isEmpty())
mapJSON.put ("fitch", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("fitch", _strFitch);
if (null == _strSnrSub || _strSnrSub.isEmpty())
mapJSON.put ("snrsub", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("snrsub", _strSnrSub);
if (null == _strIssuerSPN || _strIssuerSPN.isEmpty())
mapJSON.put ("issuerspn", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("issuerspn", _strIssuerSPN);
mapJSON.put ("issueprice", "" + _dblIssuePrice);
mapJSON.put ("coupon", "" + _dblCoupon);
if (null == _dtMaturity)
mapJSON.put ("maturitydate", org.drip.quant.common.StringUtil.NULL_SER_STRING);
else
mapJSON.put ("maturitydate", _dtMaturity.toYYYYMMDD ("-"));
return mapJSON;
}
}
| 24.275242
| 112
| 0.688881
|
97972e8f606688b29d664185beadd43092c3f344
| 3,360
|
/*
* Copyright 2014-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nebhale.gpxconverter;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Optional;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.IntStream;
import java.util.stream.Stream;
abstract class AbstractRouteCodec implements RouteCodec {
final <T> void addElementIfPresent(Node parent, String tagName, T item, BiConsumer<Element, T> consumer) {
Optional.ofNullable(item)
.ifPresent(i -> {
Element element = getDocument(parent).createElement(tagName);
parent.appendChild(element);
consumer.accept(element, i);
});
}
final void ifAttributePresentDouble(Node root, String attributeName, Consumer<Double> consumer) {
getAttribute((Element) root, attributeName)
.map(Double::parseDouble)
.ifPresent(consumer);
}
final void ifAttributePresentString(Node root, String attributeName, Consumer<String> consumer) {
getAttribute((Element) root, attributeName)
.ifPresent(consumer);
}
final void ifNodePresent(Node root, String tagName, Consumer<Node> consumer) {
getElements(root, tagName)
.findFirst()
.ifPresent(consumer);
}
final void ifValuePresentDouble(Node root, String tagName, Consumer<Double> consumer) {
getElements(root, tagName)
.findFirst()
.map(Node::getTextContent)
.map(Double::parseDouble)
.ifPresent(consumer);
}
final void ifValuePresentString(Node root, String tagName, Consumer<String> consumer) {
getElements(root, tagName)
.findFirst()
.map(Node::getTextContent)
.ifPresent(consumer);
}
final void withNodes(Node root, String tagName, Consumer<Node> consumer) {
getElements(root, tagName)
.forEach(consumer);
}
private Optional<String> getAttribute(Element root, String attributeName) {
return Optional.ofNullable(root.getAttribute(attributeName))
.filter(StringUtils::hasText);
}
private Document getDocument(Node parent) {
return parent instanceof Document ? (Document) parent : parent.getOwnerDocument();
}
private Stream<Node> getElements(Node root, String tagName) {
return stream(root.getChildNodes())
.filter(node -> tagName.equals(node.getNodeName()));
}
private Stream<Node> stream(NodeList nodeList) {
return IntStream.range(0, nodeList.getLength())
.mapToObj(nodeList::item);
}
}
| 33.6
| 110
| 0.675595
|
54b4acefe871fccb506cc148052ac456e4ad742a
| 868
|
/*
* Copyright (c) 2015 EMC Corporation
* All Rights Reserved
*/
package com.emc.sa.service.vipr.block.tasks;
import java.net.URI;
import java.util.List;
import com.emc.sa.service.vipr.tasks.ViPRExecutionTask;
import com.emc.storageos.model.RelatedResourceRep;
public class GetUnmanagedCGsForProtectionSystem extends ViPRExecutionTask<List<RelatedResourceRep>> {
private URI protectionSystem;
public GetUnmanagedCGsForProtectionSystem(String protectionSystem) {
this(uri(protectionSystem));
}
public GetUnmanagedCGsForProtectionSystem(URI protectionSystem) {
this.protectionSystem = protectionSystem;
provideDetailArgs(protectionSystem);
}
@Override
public List<RelatedResourceRep> executeTask() throws Exception {
return getClient().unmanagedCGs().listByProtectionSystem(protectionSystem);
}
}
| 28.933333
| 101
| 0.763825
|
06b668597f83a5ebae97aa70cfcd0643dc63d57b
| 1,508
|
package com.slimgears.rxrepo.query;
import com.slimgears.rxrepo.expressions.Aggregator;
import com.slimgears.rxrepo.expressions.PropertyExpression;
import com.slimgears.rxrepo.expressions.UnaryOperationExpression;
import io.reactivex.Observable;
import io.reactivex.functions.IntFunction;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;
@SuppressWarnings("WeakerAccess")
public abstract class LiveSelectQuery<T> {
public abstract Observable<T> first();
public abstract Observable<List<? extends T>> toList();
public abstract <R, E extends UnaryOperationExpression<T, Collection<T>, R>> Observable<R> aggregate(Aggregator<T, T, R, E> aggregator);
public Observable<Long> count() {
return aggregate(Aggregator.count());
}
public Observable<T[]> toArray(IntFunction<T[]> arrayCreator) {
return toList().map(list -> list.toArray(arrayCreator.apply(list.size())));
}
public <R> R apply(Function<LiveSelectQuery<T>, R> mapper) {
return mapper.apply(this);
}
@SafeVarargs
public final Observable<Notification<T>> observe(PropertyExpression<T, ?, ?>... properties) {
return observe(Arrays.asList(properties));
}
public Observable<Notification<T>> observe() {
return observe(Collections.emptyList());
}
protected abstract Observable<Notification<T>> observe(Collection<PropertyExpression<T, ?, ?>> properties);
}
| 34.272727
| 140
| 0.730106
|
69f0958c384c83f12c87c254dfaef1ddffb3ec68
| 3,448
|
package ru.rabotyaga.baranov;
import android.app.Activity;
import android.app.LoaderManager;
import android.content.Loader;
import android.os.Bundle;
import android.app.Fragment;
import android.util.Log;
import java.util.List;
public class LoaderRetainFragment extends Fragment implements LoaderManager.LoaderCallbacks<List<Article>>{
public final static String TAG = LoaderRetainFragment.class.getSimpleName();
private LoaderManager.LoaderCallbacks<List<Article>> mCallbacks;
private ArticleLoader mArticleLoader;
private List<Article> mArticleList;
private MyDatabase mDatabase;
private String mQuery;
private boolean mExactSearch = false;
private boolean mLoadFinished = false;
public LoaderRetainFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
mDatabase = MyDatabase.getInstance(getActivity());
// init loader with null args
getLoaderManager().initLoader(0, null, this);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
//noinspection unchecked
mCallbacks = (LoaderManager.LoaderCallbacks<List<Article>>) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement LoaderManager.LoaderCallbacks");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (mLoadFinished) {
mCallbacks.onLoadFinished(mArticleLoader, mArticleList);
}
}
@Override
public void onDestroy() {
Log.d(TAG, "onDestroy!");
super.onDestroy();
if (mDatabase != null) {
mDatabase.close();
Log.d(TAG, "mDatabase closed!");
}
}
void setExactSearch(boolean exactSearch) {
setQuery(mQuery, exactSearch);
}
void setQuery(String query, boolean exactSearch) {
Log.d(TAG, String.format("called setQuery(str,bool) : (%s, %b)", query, exactSearch));
if ((query == null || !query.equals(mQuery) || exactSearch != mExactSearch) && isAdded()) {
mQuery = query;
mExactSearch = exactSearch;
Bundle args = new Bundle();
args.putString(ArticleLoader.ARG_QUERY, mQuery);
args.putBoolean(ArticleLoader.ARG_EXACT_SEARCH, mExactSearch);
getLoaderManager().restartLoader(0, args, this);
}
}
boolean getExactSearch() {
return mExactSearch;
}
public Loader<List<Article>> onCreateLoader(int id, Bundle args) {
mLoadFinished = false;
mArticleList = null;
mArticleLoader = null;
return mCallbacks.onCreateLoader(id, args);
}
public void onLoadFinished(Loader<List<Article>> loader, List<Article> articleList) {
mLoadFinished = true;
mArticleLoader = (ArticleLoader) loader;
mArticleList = articleList;
mCallbacks.onLoadFinished(loader, articleList);
}
public void onLoaderReset(Loader<List<Article>> loader) {
mCallbacks.onLoaderReset(loader);
}
}
| 28.97479
| 107
| 0.651972
|
4633d4c9da5d860a6543e7f15cbc697bbc177df4
| 3,736
|
package com.ctosb.study.mongodb;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Filters;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.Document;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Set;
public class Dao {
public static void main(String[] args) {
MongoClient mongo = new MongoClient("172.88.88.206", 27017);
MongoDatabase database = mongo.getDatabase("dbtest");
MongoCollection<Document> collection = database.getCollection("cc");
Dao dao = new Dao();
dao.insert(collection);
dao.update(collection);
// dao.delete(collection);
// dao.find(collection);
}
private static String name = "name";
private static String age = "age";
private static String high = "high";
/**
* 插入数据
*
* @param collection
* @author Alan
* @time 2015-10-27 下午03:22:47
*/
public void insert(MongoCollection<Document> collection) {
List<Document> list = new ArrayList<Document>();
long t1 = System.currentTimeMillis();
for (int i = 0; i < 10000; i++) {
Document document = new Document();
document.put(name, "zhangsan" + i);
document.put(age, new Random().nextInt(100));
document.put(high, new Random().nextInt(200));
list.add(document);
}
long t2 = System.currentTimeMillis();
System.out.println("------------构建数据完成,耗时" + (t2 - t1) + "ms-----------------");
collection.insertMany(list);
long t3 = System.currentTimeMillis();
System.out.println("------------数据插入完成,耗时" + (t3 - t2) + "ms-----------------");
System.out.println("------------插入了" + list.size() + "条记录-----------");
}
/**
* 删除数据
*
* @param collection
* @author Alan
* @time 2015-10-27 下午03:22:31
*/
public void delete(MongoCollection<Document> collection) {
long t2 = System.currentTimeMillis();
DeleteResult result = collection.deleteMany(Filters.eq("name", "zhangsan1"));
long t3 = System.currentTimeMillis();
System.out.println("------------删除数据完成,耗时" + (t3 - t2) + "ms-----------------");
System.out.println("------------删除了" + result.getDeletedCount() + "条记录-----------");
}
/**
* 更新数据
*
* @param collection
* @author Alan
* @time 2015-10-27 下午03:22:23
*/
public void update(MongoCollection<Document> collection) {
long t2 = System.currentTimeMillis();
UpdateResult result = collection.updateMany(Filters.eq("name", "zhangsan1"), new Document("$set", new Document("age1", "12s")));
long t3 = System.currentTimeMillis();
System.out.println("------------更新数据耗时" + (t3 - t2) + "ms-----------------");
System.out.println("------------更新了" + result.getModifiedCount() + "条记录-----------");
System.out.println("------------总数据量为" + collection.count());
}
/**
* 查找数据
*
* @param collection
* @author Alan
* @time 2015-10-27 下午03:22:13
*/
public void find(MongoCollection<Document> collection) {
FindIterable<Document> iterable = collection.find();
for (Document document : iterable) {
Set<String> keySet = document.keySet();
for (String key : keySet) {
// System.out.print(key+":"+document.get(key) + " ");
}
System.out.println();
}
System.out.println("---------数据搜索完成----------");
}
}
| 33.963636
| 136
| 0.571467
|
0c8f8ae2fb2ffd071516cdad3aaf4f0d9bc2edf0
| 1,533
|
package db.entities;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "national_grade")
public class NationalGrade {
@DatabaseField(generatedId = true, useGetSet = true)
private int id;
@DatabaseField(canBeNull = false, useGetSet = true, unique = true)
private String name;
@DatabaseField(canBeNull = false, useGetSet = true, columnName = "min_national_score")
private int minNationalScore;
@DatabaseField(canBeNull = false, useGetSet = true, columnName = "max_national_score")
private int maxNationalScore;
public NationalGrade() {
}
public NationalGrade(int id, String name, int minNationalScore, int maxNationalScore) {
this.id = id;
this.name = name;
this.minNationalScore = minNationalScore;
this.maxNationalScore = maxNationalScore;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getMinNationalScore() {
return minNationalScore;
}
public void setMinNationalScore(int minNationalScore) {
this.minNationalScore = minNationalScore;
}
public int getMaxNationalScore() {
return maxNationalScore;
}
public void setMaxNationalScore(int maxNationalScore) {
this.maxNationalScore = maxNationalScore;
}
}
| 24.333333
| 91
| 0.671885
|
8933defd03300969d45cc4272f0bf8b54fa09c1d
| 10,201
|
/*
* MIT License
*
* Copyright (c) 2018 dkzwm
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.dkzwm.widget.esl.graphics;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.support.annotation.ColorInt;
import android.util.TypedValue;
public class MIUIDrawer extends Drawer {
protected Paint mBackgroundPaint;
protected Paint mArrowPaint;
protected Path mBackgroundPath = new Path();
protected Path mArrowPath = new Path();
protected float mBackgroundFixedSize;
protected float mArrowStrokeWidth;
protected int mBackgroundMaxDynamicSize;
protected int mArrowHeight;
protected int mArrowWidth;
@ColorInt protected int mBackgroundColor = Color.BLACK;
@ColorInt protected int mArrowColor = Color.WHITE;
public MIUIDrawer(Context context) {
super(context);
mBackgroundPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mBackgroundPaint.setColor(mBackgroundColor);
mBackgroundPaint.setStrokeWidth(1);
mBackgroundPaint.setStyle(Paint.Style.FILL);
mBackgroundPaint.setAlpha((int) (0.74f * 255));
mArrowStrokeWidth =
(int)
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
2,
mContext.getResources().getDisplayMetrics());
mArrowHeight =
(int)
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
12,
mContext.getResources().getDisplayMetrics());
mArrowWidth =
(int)
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
5f,
mContext.getResources().getDisplayMetrics());
mArrowPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mArrowPaint.setStyle(Paint.Style.STROKE);
mArrowPaint.setColor(mArrowColor);
mArrowPaint.setStrokeWidth(mArrowStrokeWidth);
mArrowPaint.setStrokeJoin(Paint.Join.ROUND);
mBackgroundFixedSize = context.getResources().getDisplayMetrics().heightPixels / 3.5f;
mBackgroundMaxDynamicSize =
(int)
TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
26,
mContext.getResources().getDisplayMetrics());
}
public void setBackgroundMaxDynamicSize(int size) {
mBackgroundMaxDynamicSize = size;
requestInvalidate();
}
public void setBackgroundFixedSize(int size) {
mBackgroundFixedSize = size;
requestInvalidate();
}
public void setBackgroundColor(@ColorInt int color) {
if (mBackgroundColor != color) {
mBackgroundColor = color;
mBackgroundPaint.setColor(mBackgroundColor);
requestInvalidate();
}
}
public void setArrowColor(@ColorInt int color) {
if (mArrowColor != color) {
mArrowColor = color;
mArrowPaint.setColor(mArrowColor);
requestInvalidate();
}
}
public void setArrowStrokeWidth(float arrowStrokeWidth) {
if (mArrowStrokeWidth != arrowStrokeWidth) {
mArrowStrokeWidth = arrowStrokeWidth;
mArrowPaint.setStrokeWidth(mArrowStrokeWidth);
requestInvalidate();
}
}
public void setArrowHeight(int arrowHeight) {
mArrowHeight = arrowHeight;
requestInvalidate();
}
public void setArrowWidth(int arrowWidth) {
mArrowWidth = arrowWidth;
requestInvalidate();
}
@Override
public int getMaxSize() {
return mBackgroundMaxDynamicSize;
}
@Override
public void drawLeft(Canvas canvas, PointF downPoint, PointF movedPoint) {
mBackgroundPath.reset();
int size = (int) Math.min(movedPoint.x, mBackgroundMaxDynamicSize);
mBackgroundPath.moveTo(0, 0);
mBackgroundPath.cubicTo(
0,
mBackgroundFixedSize / 5,
size,
mBackgroundFixedSize / 3,
size,
mBackgroundFixedSize / 2);
mBackgroundPath.cubicTo(
size,
mBackgroundFixedSize / 3 * 2,
0,
mBackgroundFixedSize / 5 * 4,
0,
mBackgroundFixedSize);
mBackgroundPath.offset(0, downPoint.y - mBackgroundFixedSize / 2f);
canvas.drawPath(mBackgroundPath, mBackgroundPaint);
if (size >= mBackgroundMaxDynamicSize / 2.5f) {
mArrowPath.reset();
mArrowPath.moveTo(size / 2f + mArrowWidth / 2f, downPoint.y + mArrowHeight / 2f);
mArrowPath.lineTo(size / 2f - mArrowWidth / 2f, downPoint.y);
mArrowPath.lineTo(size / 2f + mArrowWidth / 2f, downPoint.y - mArrowHeight / 2f);
canvas.drawPath(mArrowPath, mArrowPaint);
}
}
@Override
public void drawTop(Canvas canvas, PointF downPoint, PointF movedPoint) {
mBackgroundPath.reset();
int size = (int) Math.min(movedPoint.y, mBackgroundMaxDynamicSize);
mBackgroundPath.moveTo(0, 0);
mBackgroundPath.cubicTo(
mBackgroundFixedSize / 5, 0,
mBackgroundFixedSize / 3, size,
mBackgroundFixedSize / 2, size);
mBackgroundPath.cubicTo(
mBackgroundFixedSize / 3 * 2,
size,
mBackgroundFixedSize / 5 * 4,
0,
mBackgroundFixedSize,
0);
mBackgroundPath.offset(downPoint.x - mBackgroundFixedSize / 2f, 0);
canvas.drawPath(mBackgroundPath, mBackgroundPaint);
if (size >= mBackgroundMaxDynamicSize / 2.5f) {
mArrowPath.reset();
mArrowPath.moveTo(downPoint.x + mArrowHeight / 2f, size / 2f + mArrowWidth / 2f);
mArrowPath.lineTo(downPoint.x, size / 2f - mArrowWidth / 2f);
mArrowPath.lineTo(downPoint.x - mArrowHeight / 2f, size / 2f + mArrowWidth / 2f);
canvas.drawPath(mArrowPath, mArrowPaint);
}
}
@Override
public void drawRight(Canvas canvas, PointF downPoint, PointF movedPoint) {
mBackgroundPath.reset();
int size = (int) Math.min(mWidth - movedPoint.x, mBackgroundMaxDynamicSize);
mBackgroundPath.moveTo(0, 0);
mBackgroundPath.cubicTo(
0,
mBackgroundFixedSize / 5,
-size,
mBackgroundFixedSize / 3,
-size,
mBackgroundFixedSize / 2);
mBackgroundPath.cubicTo(
-size,
mBackgroundFixedSize / 3 * 2,
0,
mBackgroundFixedSize / 5 * 4,
0,
mBackgroundFixedSize);
mBackgroundPath.offset(mWidth, downPoint.y - mBackgroundFixedSize / 2f);
canvas.drawPath(mBackgroundPath, mBackgroundPaint);
if (size >= mBackgroundMaxDynamicSize / 2.5f) {
final int x = mWidth - size;
mArrowPath.reset();
mArrowPath.moveTo(x + size / 2f - mArrowWidth / 2f, downPoint.y + mArrowHeight / 2f);
mArrowPath.lineTo(x + size / 2f + mArrowWidth / 2f, downPoint.y);
mArrowPath.lineTo(x + size / 2f - mArrowWidth / 2f, downPoint.y - mArrowHeight / 2f);
canvas.drawPath(mArrowPath, mArrowPaint);
}
}
@Override
public void drawBottom(Canvas canvas, PointF downPoint, PointF movedPoint) {
mBackgroundPath.reset();
int size = (int) Math.min(mHeight - movedPoint.y, mBackgroundMaxDynamicSize);
mBackgroundPath.moveTo(0, 0);
mBackgroundPath.cubicTo(
mBackgroundFixedSize / 5, 0,
mBackgroundFixedSize / 3, -size,
mBackgroundFixedSize / 2, -size);
mBackgroundPath.cubicTo(
mBackgroundFixedSize / 3 * 2,
-size,
mBackgroundFixedSize / 5 * 4,
0,
mBackgroundFixedSize,
0);
mBackgroundPath.offset(downPoint.x - mBackgroundFixedSize / 2f, mHeight);
canvas.drawPath(mBackgroundPath, mBackgroundPaint);
if (size >= mBackgroundMaxDynamicSize / 2.5f) {
final int y = mHeight - size;
mArrowPath.reset();
mArrowPath.moveTo(downPoint.x + mArrowHeight / 2f, y + size / 2f - mArrowWidth / 2f);
mArrowPath.lineTo(downPoint.x, y + size / 2f + mArrowWidth / 2f);
mArrowPath.lineTo(downPoint.x - mArrowHeight / 2f, y + size / 2f - mArrowWidth / 2f);
canvas.drawPath(mArrowPath, mArrowPaint);
}
}
@Override
public boolean canTrigger(int edge, float x) {
return x >= getMaxSize() / 3 * 2;
}
}
| 39.692607
| 97
| 0.603764
|
b47672511a701a2d2e195c9ce45b1af97ce0cbc7
| 1,243
|
package com.example.dowy.foodapp.model;
import java.io.Serializable;
public class ItemProduto implements Serializable {
private String idProduto;
private String nomeProduto;
private String urlImagem;
private long valor;
private long preco;
private int quantidade;
public ItemProduto() {
}
public String getIdProduto() {
return idProduto;
}
public void setIdProduto(String idProduto) {
this.idProduto = idProduto;
}
public String getNomeProduto() {
return nomeProduto;
}
public long getPreco() {
return preco;
}
public void setPreco(long preco) {
this.preco = preco;
}
public void setNomeProduto(String nomeProduto) {
this.nomeProduto = nomeProduto;
}
public String getUrlImagem() {
return urlImagem;
}
public void setUrlImagem(String urlImagem) {
this.urlImagem = urlImagem;
}
public long getValor() {
return valor;
}
public void setValor(long valor) {
this.valor = valor;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
}
| 19.123077
| 52
| 0.629123
|
619eb1f27af369f09f63305fb25923f3c9ee5ed7
| 2,015
|
package com.itkjb.exercise.juc;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;
/**
* Copyright (C), 2021-2099
*
* @Author: lix
* @Date: 2021/6/7 3:54 下午
* @Description: 阻塞队列 示例
* @Version: V1.0.0
*/
public class BlockingQueueDemo {
public static void main(String[] args) throws InterruptedException {
BlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(3);
// 第一组
System.out.println(blockingQueue.add("a"));
System.out.println(blockingQueue.add("b"));
System.out.println(blockingQueue.add("c"));
System.out.println(blockingQueue.element());
System.out.println(blockingQueue.add("x"));
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
System.out.println(blockingQueue.remove());
// 第二组
/*System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.offer("x"));
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());
System.out.println(blockingQueue.poll());*/
// 第三组
/*
blockingQueue.put("a");
blockingQueue.put("b");
blockingQueue.put("c");
blockingQueue.put("x");
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
System.out.println(blockingQueue.take());
*/
// 第四组
/*System.out.println(blockingQueue.offer("a"));
System.out.println(blockingQueue.offer("b"));
System.out.println(blockingQueue.offer("c"));
System.out.println(blockingQueue.offer("a", 3L, TimeUnit.SECONDS));*/
}
}
| 34.741379
| 77
| 0.642184
|
b56ef390a37c606e0bd0aadd048d8d751722b39c
| 2,204
|
/*
# Copyright © 2021 Argela Technologies
#
# 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 tr.com.argela.nfv.onap.serviceManager.onap.rest.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
*
* @author Nebi Volkan UNLENEN(unlenen@gmail.com)
*/
public class Customer {
String id;
String name;
String versionId = "";
String type = "";
@JsonIgnore
Service service;
public Customer() {
}
public Customer(String id, String name, String versionId, String type) {
this.id = id;
this.name = name;
this.versionId = versionId;
this.type = type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getVersionId() {
return versionId;
}
public void setVersionId(String versionId) {
this.versionId = versionId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Service getService() {
return service;
}
public void setService(Service service) {
this.service = service;
}
@Override
public String toString() {
return "Customer{" + "id=" + id + ", name=" + name + ", type=" + type + '}';
}
public void copy(Customer customerOnap) {
this.id = customerOnap.getId();
this.name = customerOnap.getName();
this.versionId = customerOnap.getVersionId();
this.type = customerOnap.getType();
}
}
| 22.721649
| 84
| 0.626588
|
b5ceb2c821e1e92dd36c0db438313ebe76c67add
| 4,257
|
package net.ibizsys.paas.appmodel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.ibizsys.paas.controller.IViewController;
import net.ibizsys.paas.core.IApplication;
import net.ibizsys.paas.ctrlhandler.ICtrlHandler;
import net.ibizsys.paas.ctrlhandler.ICtrlRender;
import net.ibizsys.paas.ctrlmodel.IAppMenuModel;
import net.ibizsys.paas.web.AjaxActionResult;
import net.ibizsys.paas.web.IWebContext;
import net.ibizsys.paas.web.Page;
/**
* 应用程序模型接口
* @author lionlau
*
*/
public interface IApplicationModel extends IApplication
{
/**
* 下载临时文件
*/
final static String UTILPAGE_DOWNLOADTMPFILE = "DOWNLOADTMPFILE";
/**
* 登录路径
*/
final static String UTILPAGE_LOGIN = "LOGIN";
/**
* 注销路径
*/
final static String UTILPAGE_LOGOUT = "LOGOUT";
/**
* 访问被拒绝
*/
final static String UTILPAGE_ACCESSDENY = "ACCESSDENY";
/**
* 系统处理错误
*/
final static String UTILPAGE_INTERNALERROR = "INTERNALERROR";
/**
* 获取部件绘制器接口
* @param strCtrlType 部件类型
* @param strRender 绘制器标识
* @return
*/
ICtrlRender getCtrlRender(String strCtrlType,String strRender);
/**
* 建立HTTP访问上下文对象
* @param 视图控制器接口
* @param request
* @param response
* @return
* @throws Exception
*/
IWebContext createWebContext(IViewController iViewController,HttpServletRequest request,HttpServletResponse response) throws Exception;
/**
* 过滤请求,如果处理,返回true
* @param iViewController 视图控制器接口
* @param request
* @param response
* @return
* @throws Exception
*/
boolean doFilter(IViewController iViewController, HttpServletRequest request,HttpServletResponse response) throws Exception;
/**
* 过滤请求,如果处理,返回true
* @param page 页面对象
* @param request
* @param response
* @return
* @throws Exception
*/
boolean doFilter(Page page, HttpServletRequest request,HttpServletResponse response) throws Exception;
/**
* 过滤控件的操作
* @param iViewController
* @param request
* @param response
* @param strCtrlId
* @param strAction
* @param ajaxActionResult
* @return
* @throws Exception
*/
AjaxActionResult doViewCtrlAjaxAction(IViewController iViewController,HttpServletRequest request,HttpServletResponse response,String strCtrlId,String strAction,ICtrlHandler iCtrlHandler) throws Exception;
/**
* 过滤视图的操作
* @param iViewController
* @param request
* @param response
* @param strCtrlId 部件标识
* @param strAction 请求操作
* @param ajaxActionResult 反馈对象
* @return
* @throws Exception
*/
AjaxActionResult doFilterViewAction(IViewController iViewController,HttpServletRequest request,HttpServletResponse response,String strAction,AjaxActionResult ajaxActionResult) throws Exception;
/**
* 获取功能页面路径
* @param strUtilType
* @return
* @throws Exception
*/
String getUtilPageUrl(String strUtilType)throws Exception;
/**
* 安装运行时数据
*/
void installRTDatas() throws Exception;
/**
* 注册应用视图
* @param iAppViewModel
* @throws Exception
*/
void registerAppView(IAppViewModel iAppViewModel)throws Exception;
/**
* 获取应用视图
* @param strAppViewId
* @param bTryMode 尝试模式
* @return
* @throws Exception
*/
IAppViewModel getAppView(String strAppViewId,boolean bTryMode)throws Exception;
/**
* 获取应用实体视图
* @param strDEViewId
* @param bTryMode
* @return
* @throws Exception
*/
IAppDEViewModel getAppViewByDEViewId(String strDEViewId,boolean bTryMode)throws Exception;
/**
* 获取应用框架辅助对象
* @return
*/
IAppPFHelper getAppPFHelper();
/**
* 获取指定用户模式的应用菜单模型
* @param strUserMode
* @return
* @throws Exception
*/
IAppMenuModel getAppMenuModel(String strUserMode)throws Exception;
/**
* 注册应用用户模式菜单
* @param strUserMode
* @param strAppMenuModelId
* @throws Exception
*/
void registerUserModeMenu(String strUserMode,String strAppMenuModelId)throws Exception;
// /**
// * 获取表单项配置
// * @param iFormItemModel
// * @param iWebContext
// * @param iDataObject
// * @param bUpdate
// * @return
// * @throws Exception
// */
// JSONObject getFormItemConfig(IFormItemModel iFormItemModel,IWebContext iWebContext, IDataObject iDataObject, boolean bUpdate) throws Exception;
}
| 18.836283
| 205
| 0.717407
|
1864cec05d9644584163d20663d37624641c9a59
| 3,374
|
/*
* Copyright 2017 Dagmar Prokopova <xproko26@stud.fit.vutbr.cz>.
*
* 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 cz.vutbr.fit.xproko26.pivis.model.names;
import java.util.ArrayList;
/**
* NameTable represents the storage of all names used in the visualized expression
* and process definitions in the current model context. The index of the name
* value in this list uniquely identifies the name. This index is used by
* {@link NameRef NameRef} class as the unique identifier.
* @author Dagmar Prokopova
*/
public class NameTable extends ArrayList<NameValue>{
private static final long serialVersionUID = 1L;
/**
* Creates new record in the table in which the passed name value is stored.
* Also returns newly created name reference which points to this value.
* @param nv name value to be added
* @return name reference
*/
public NameRef createName(NameValue nv) {
add(nv);
NameRef nr = new NameRef(size()-1);
if (nv.isPrivate()) {
nr.setPrivate();
}
if (nv.isProcess()) {
nr.setProcess();
}
nr.setDefProcess(nv.isDefProcess());
return nr;
}
/**
* Creates the new record in the table to which the copy of the existing
* name value is stored. The name value to be replicated is specified by
* name reference passed as an argument. Also the name reference pointing
* to the newly created record is returned.
* @param ref name reference to the original name which shall be replicated
* @return name reference of newly created copy
*/
public NameRef replicateName(NameRef ref) {
add(get(ref.getRef()).copy());
NameRef nr = new NameRef(size()-1);
if (ref.isPrivate()) {
nr.setPrivate();
}
if (ref.isProcess()) {
nr.setProcess();
}
nr.setDefProcess(ref.isDefProcess());
nr.setSource(ref.getSource());
return nr;
}
/**
* Returns the name value for specified name reference.
* @param n name reference
* @return name value
*/
public NameValue getNameValue(NameRef n) {
return get(n.getRef());
}
/**
* Returns newly created name reference for name value passed as an argument
* if there is a name value stored in the table which matches the passed value..
* If there is no such name value, null is returned instead.
* @param nv name value
* @return name reference
*/
public NameRef getNameRef(NameValue nv) {
for(int i = 0; i < size(); i++) {
NameValue n = get(i);
if (n.getLabel().equals(nv.getLabel())) {
return new NameRef(i);
}
}
return null;
}
}
| 33.405941
| 84
| 0.627742
|
e1318ee251fa9dfa7c6883e95b4007ae13e85e42
| 11,713
|
package com.sudoplay.mc.pwcustom.modules.portals.world;
import net.minecraft.block.Block;
import net.minecraft.block.BlockPortal;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.ChunkPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.Teleporter;
import net.minecraft.world.WorldServer;
public class TeleporterCustom
extends Teleporter {
private IBlockState portalFrameBlockState;
private IBlockState portalBlockState;
private Block portalBlock;
public TeleporterCustom(WorldServer worldIn, IBlockState portalFrameBlockState, IBlockState portalBlockState) {
super(worldIn);
this.portalFrameBlockState = portalFrameBlockState;
this.portalBlockState = portalBlockState;
this.portalBlock = portalBlockState.getBlock();
}
@Override
public void placeInPortal(Entity entityIn, float rotationYaw) {
if (!this.placeInExistingPortal(entityIn, rotationYaw)) {
this.makePortal(entityIn);
this.placeInExistingPortal(entityIn, rotationYaw);
}
}
@Override
public boolean placeInExistingPortal(Entity entityIn, float rotationYaw) {
double d0 = -1.0D;
int i = MathHelper.floor(entityIn.posX);
int j = MathHelper.floor(entityIn.posZ);
boolean flag1 = true;
Object object = BlockPos.ORIGIN;
long k = ChunkPos.asLong(i, j);
if (destinationCoordinateCache.containsKey(k)) {
PortalPosition portalPosition = destinationCoordinateCache.get(k);
d0 = 0.0D;
object = portalPosition;
portalPosition.lastUpdateTime = this.world.getTotalWorldTime();
flag1 = false;
} else {
BlockPos blockpos4 = new BlockPos(entityIn);
for (int l = -128; l <= 128; ++l) {
BlockPos blockpos1;
for (int i1 = -128; i1 <= 128; ++i1) {
for (BlockPos blockpos = blockpos4.add(l, this.world.getActualHeight() - 1 - blockpos4.getY(), i1);
blockpos.getY() >= 0;
blockpos = blockpos1) {
blockpos1 = blockpos.down();
if (this.world.getBlockState(blockpos).getBlock() == this.portalBlock) {
while (this.world.getBlockState(blockpos1 = blockpos.down()).getBlock() == this.portalBlock) {
blockpos = blockpos1;
}
double d1 = blockpos.distanceSq(blockpos4);
if (d0 < 0.0D || d1 < d0) {
d0 = d1;
object = blockpos;
}
}
}
}
}
}
if (d0 >= 0.0D) {
if (flag1) {
destinationCoordinateCache.put(
k,
new PortalPosition((BlockPos) object, this.world.getTotalWorldTime())
);
}
double d4 = ((BlockPos) object).getX() + 0.5D;
double d5 = ((BlockPos) object).getY() + 0.5D;
double d6 = ((BlockPos) object).getZ() + 0.5D;
EnumFacing enumfacing = null;
if (this.world.getBlockState(((BlockPos) object).west()).getBlock() == this.portalBlock) {
enumfacing = EnumFacing.NORTH;
}
if (this.world.getBlockState(((BlockPos) object).east()).getBlock() == this.portalBlock) {
enumfacing = EnumFacing.SOUTH;
}
if (this.world.getBlockState(((BlockPos) object).north()).getBlock() == this.portalBlock) {
enumfacing = EnumFacing.EAST;
}
if (this.world.getBlockState(((BlockPos) object).south()).getBlock() == this.portalBlock) {
enumfacing = EnumFacing.WEST;
}
EnumFacing enumfacing1 = EnumFacing.getHorizontal(MathHelper.floor(entityIn.rotationYaw * 4.0F / 360.0F + 0.5D) & 3);
if (enumfacing != null) {
EnumFacing enumfacing2 = enumfacing.rotateYCCW();
BlockPos blockpos2 = ((BlockPos) object).offset(enumfacing);
boolean flag2 = func_180265_a(blockpos2);
boolean flag3 = func_180265_a(blockpos2.offset(enumfacing2));
if (flag3 && flag2) {
object = ((BlockPos) object).offset(enumfacing2);
enumfacing = enumfacing.getOpposite();
enumfacing2 = enumfacing2.getOpposite();
BlockPos blockpos3 = ((BlockPos) object).offset(enumfacing);
flag2 = func_180265_a(blockpos3);
flag3 = func_180265_a(blockpos3.offset(enumfacing2));
}
float f6 = 0.5F;
float f1 = 0.5F;
if (!flag3 && flag2) {
f6 = 1.0F;
} else if (flag3 && !flag2) {
f6 = 0.0F;
} else if (flag3) {
f1 = 0.0F;
}
d4 = ((BlockPos) object).getX() + 0.5D;
d5 = ((BlockPos) object).getY() + 0.5D;
d6 = ((BlockPos) object).getZ() + 0.5D;
d4 += enumfacing2.getFrontOffsetX() * f6 + enumfacing.getFrontOffsetX() * f1;
d6 += enumfacing2.getFrontOffsetZ() * f6 + enumfacing.getFrontOffsetZ() * f1;
float f2 = 0.0F;
float f3 = 0.0F;
float f4 = 0.0F;
float f5 = 0.0F;
if (enumfacing == enumfacing1) {
f2 = 1.0F;
f3 = 1.0F;
} else if (enumfacing == enumfacing1.getOpposite()) {
f2 = -1.0F;
f3 = -1.0F;
} else if (enumfacing == enumfacing1.rotateY()) {
f4 = 1.0F;
f5 = -1.0F;
} else {
f4 = -1.0F;
f5 = 1.0F;
}
double d2 = entityIn.motionX;
double d3 = entityIn.motionZ;
entityIn.motionX = d2 * f2 + d3 * f5;
entityIn.motionZ = d2 * f4 + d3 * f3;
entityIn.rotationYaw = rotationYaw - enumfacing1.getHorizontalIndex() * 90 + enumfacing.getHorizontalIndex() * 90;
} else {
entityIn.motionX = entityIn.motionY = entityIn.motionZ = 0.0D;
}
entityIn.setLocationAndAngles(d4, d5, d6, entityIn.rotationYaw, entityIn.rotationPitch);
return true;
} else {
return false;
}
}
private boolean func_180265_a(BlockPos p_180265_1_) {
return !this.world.isAirBlock(p_180265_1_) || !this.world.isAirBlock(p_180265_1_.up());
}
@Override
public boolean makePortal(Entity entityIn) {
int i = 16;
double d0 = -1.0D;
int j = MathHelper.floor(entityIn.posX);
int k = MathHelper.floor(entityIn.posY);
int l = MathHelper.floor(entityIn.posZ);
int i1 = j;
int j1 = k;
int k1 = l;
int l1 = 0;
int i2 = this.random.nextInt(4);
BlockPos.MutableBlockPos blockPos = new BlockPos.MutableBlockPos();
for (int j2 = j - 16; j2 <= j + 16; ++j2) {
double d1 = (double) j2 + 0.5D - entityIn.posX;
for (int l2 = l - 16; l2 <= l + 16; ++l2) {
double d2 = (double) l2 + 0.5D - entityIn.posZ;
label293:
for (int j3 = this.world.getActualHeight() - 1; j3 >= 0; --j3) {
if (this.world.isAirBlock(blockPos.setPos(j2, j3, l2))) {
while (j3 > 0 && this.world.isAirBlock(blockPos.setPos(j2, j3 - 1, l2))) {
--j3;
}
for (int k3 = i2; k3 < i2 + 4; ++k3) {
int l3 = k3 % 2;
int i4 = 1 - l3;
if (k3 % 4 >= 2) {
l3 = -l3;
i4 = -i4;
}
for (int j4 = 0; j4 < 3; ++j4) {
for (int k4 = 0; k4 < 4; ++k4) {
for (int l4 = -1; l4 < 4; ++l4) {
int i5 = j2 + (k4 - 1) * l3 + j4 * i4;
int j5 = j3 + l4;
int k5 = l2 + (k4 - 1) * i4 - j4 * l3;
blockPos.setPos(i5, j5, k5);
if (l4 < 0 && !this.world.getBlockState(blockPos)
.getMaterial()
.isSolid() || l4 >= 0 && !this.world.isAirBlock(blockPos)) {
continue label293;
}
}
}
}
double d5 = (double) j3 + 0.5D - entityIn.posY;
double d7 = d1 * d1 + d5 * d5 + d2 * d2;
if (d0 < 0.0D || d7 < d0) {
d0 = d7;
i1 = j2;
j1 = j3;
k1 = l2;
l1 = k3 % 4;
}
}
}
}
}
}
if (d0 < 0.0D) {
for (int l5 = j - 16; l5 <= j + 16; ++l5) {
double d3 = (double) l5 + 0.5D - entityIn.posX;
for (int j6 = l - 16; j6 <= l + 16; ++j6) {
double d4 = (double) j6 + 0.5D - entityIn.posZ;
label231:
for (int i7 = this.world.getActualHeight() - 1; i7 >= 0; --i7) {
if (this.world.isAirBlock(blockPos.setPos(l5, i7, j6))) {
while (i7 > 0 && this.world.isAirBlock(blockPos.setPos(l5, i7 - 1, j6))) {
--i7;
}
for (int k7 = i2; k7 < i2 + 2; ++k7) {
int j8 = k7 % 2;
int j9 = 1 - j8;
for (int j10 = 0; j10 < 4; ++j10) {
for (int j11 = -1; j11 < 4; ++j11) {
int j12 = l5 + (j10 - 1) * j8;
int i13 = i7 + j11;
int j13 = j6 + (j10 - 1) * j9;
blockPos.setPos(j12, i13, j13);
if (j11 < 0 && !this.world.getBlockState(blockPos)
.getMaterial()
.isSolid() || j11 >= 0 && !this.world.isAirBlock(blockPos)) {
continue label231;
}
}
}
double d6 = (double) i7 + 0.5D - entityIn.posY;
double d8 = d3 * d3 + d6 * d6 + d4 * d4;
if (d0 < 0.0D || d8 < d0) {
d0 = d8;
i1 = l5;
j1 = i7;
k1 = j6;
l1 = k7 % 2;
}
}
}
}
}
}
}
int i6 = i1;
int k2 = j1;
int k6 = k1;
int l6 = l1 % 2;
int i3 = 1 - l6;
if (l1 % 4 >= 2) {
l6 = -l6;
i3 = -i3;
}
if (d0 < 0.0D) {
j1 = MathHelper.clamp(j1, 70, this.world.getActualHeight() - 10);
k2 = j1;
for (int j7 = -1; j7 <= 1; ++j7) {
for (int l7 = 1; l7 < 3; ++l7) {
for (int k8 = -1; k8 < 3; ++k8) {
int k9 = i6 + (l7 - 1) * l6 + j7 * i3;
int k10 = k2 + k8;
int k11 = k6 + (l7 - 1) * i3 - j7 * l6;
boolean flag = k8 < 0;
this.world.setBlockState(
new BlockPos(k9, k10, k11),
flag ? this.portalFrameBlockState : Blocks.AIR.getDefaultState()
);
}
}
}
}
IBlockState iblockstate = this.portalBlockState
.withProperty(BlockPortal.AXIS, l6 == 0 ? EnumFacing.Axis.Z : EnumFacing.Axis.X);
for (int i8 = 0; i8 < 4; ++i8) {
for (int l8 = 0; l8 < 4; ++l8) {
for (int l9 = -1; l9 < 4; ++l9) {
int l10 = i6 + (l8 - 1) * l6;
int l11 = k2 + l9;
int k12 = k6 + (l8 - 1) * i3;
boolean flag1 = l8 == 0 || l8 == 3 || l9 == -1 || l9 == 3;
this.world.setBlockState(
new BlockPos(l10, l11, k12),
flag1 ? this.portalFrameBlockState : iblockstate,
2
);
}
}
for (int i9 = 0; i9 < 4; ++i9) {
for (int i10 = -1; i10 < 4; ++i10) {
int i11 = i6 + (i9 - 1) * l6;
int i12 = k2 + i10;
int l12 = k6 + (i9 - 1) * i3;
BlockPos blockpos = new BlockPos(i11, i12, l12);
this.world.notifyNeighborsOfStateChange(blockpos, this.world.getBlockState(blockpos).getBlock(), false);
}
}
}
return true;
}
}
| 31.486559
| 123
| 0.504397
|
582758090d1a868b81b5eb413720cb851cc0b22b
| 3,782
|
/*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 software.amazon.smithy.model.loader;
import static software.amazon.smithy.model.node.Node.loadArrayOfString;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import software.amazon.smithy.model.SourceException;
import software.amazon.smithy.model.node.ArrayNode;
import software.amazon.smithy.model.node.Node;
import software.amazon.smithy.model.node.ObjectNode;
import software.amazon.smithy.model.selector.Selector;
import software.amazon.smithy.model.validation.Severity;
import software.amazon.smithy.model.validation.ValidatedResult;
import software.amazon.smithy.model.validation.ValidationEvent;
import software.amazon.smithy.utils.ListUtils;
final class ValidationLoader {
private static final List<String> SEVERITIES = ListUtils.of("DANGER", "WARNING", "NOTE");
private static final List<String> VALIDATOR_PROPERTIES = ListUtils.of(
"name", "id", "message", "severity", "namespaces", "selector", "configuration");
private ValidationLoader() {}
static ValidatedResult<List<ValidatorDefinition>> loadValidators(Map<String, Node> metadata) {
if (!metadata.containsKey("validators")) {
return ValidatedResult.empty();
}
List<ValidationEvent> events = new ArrayList<>();
List<ValidatorDefinition> result = new ArrayList<>();
Node node = metadata.get("validators");
try {
ArrayNode values = node.expectArrayNode("validators must be an array. Found {type}.");
for (Node element : values.getElements()) {
try {
ObjectNode definition = element.expectObjectNode(
"Each element of `validators` must be an object. Found {type}.");
result.add(ValidationLoader.loadSingleValidator(definition));
} catch (SourceException e) {
events.add(ValidationEvent.fromSourceException(e));
}
}
} catch (SourceException e) {
events.add(ValidationEvent.fromSourceException(e));
}
return new ValidatedResult<>(result, events);
}
private static ValidatorDefinition loadSingleValidator(ObjectNode node) {
node.warnIfAdditionalProperties(VALIDATOR_PROPERTIES);
String name = node.expectStringMember("name").getValue();
String id = node.getStringMemberOrDefault("id", name);
ValidatorDefinition def = new ValidatorDefinition(name, id);
def.sourceLocation = node.getSourceLocation();
def.message = node.getStringMemberOrDefault("message", null);
def.severity = node.getStringMember("severity")
.map(value -> value.expectOneOf(SEVERITIES))
.map(value -> Severity.fromString(value).get())
.orElse(null);
node.getMember("namespaces").ifPresent(value -> def.namespaces.addAll(loadArrayOfString("namespaces", value)));
def.configuration = node.getObjectMember("configuration").orElse(Node.objectNode());
node.getStringMember("selector").ifPresent(selector -> {
def.selector = Selector.fromNode(selector);
});
return def;
}
}
| 42.977273
| 119
| 0.683236
|
4f2d97f1877b95bac9c0f83649c35b6b7afd418f
| 4,095
|
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.vividus.http.client;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.util.Optional;
import java.util.stream.Stream;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.Header;
public class HttpResponse
{
private URI from;
private String method;
private int statusCode;
private long responseTimeInMs;
private byte[] responseBody;
private Header[] responseHeaders;
public Optional<Header> getHeaderByName(String headerName)
{
return getHeadersByName(headerName).findFirst();
}
public Stream<Header> getHeadersByName(String headerName)
{
return Stream.of(responseHeaders).filter(header -> header.getName().equals(headerName));
}
public String getMethod()
{
return method;
}
public void setMethod(String method)
{
this.method = method;
}
public int getStatusCode()
{
return statusCode;
}
public void setStatusCode(int statusCode)
{
this.statusCode = statusCode;
}
public long getResponseTimeInMs()
{
return responseTimeInMs;
}
public void setResponseTimeInMs(long responseTimeInMs)
{
this.responseTimeInMs = responseTimeInMs;
}
public byte[] getResponseBody()
{
return ArrayUtils.clone(responseBody);
}
public void setResponseBody(byte[] responseBody)
{
this.responseBody = ArrayUtils.clone(responseBody);
}
public String getResponseBodyAsString()
{
return responseBody != null ? new String(responseBody, StandardCharsets.UTF_8) : null;
}
public Header[] getResponseHeaders()
{
return ArrayUtils.clone(responseHeaders);
}
public void setResponseHeaders(Header... responseHeaders)
{
this.responseHeaders = ArrayUtils.clone(responseHeaders);
}
public URI getFrom()
{
return from;
}
public void setFrom(URI from)
{
this.from = from;
}
public HttpResponse verifyStatusCode(int... codes)
{
if (!ArrayUtils.contains(codes, statusCode))
{
StringBuilder builder = new StringBuilder("Service returned response with unexpected status code: [")
.append(statusCode).append("]. Expected code is one of: ");
throw new ExternalServiceException(appendWithSeparators(builder, codes, ", ").toString());
}
return this;
}
public HttpResponse verifyStatusCodeInRange(int fromCodeInclusive, int toCodeInclusive)
{
if (statusCode < fromCodeInclusive || statusCode > toCodeInclusive)
{
String msg = String.format("Service returned response with unexpected status code: [%d]. Expected code "
+ "from range [%d - %d]", statusCode, fromCodeInclusive, toCodeInclusive);
throw new ExternalServiceException(msg);
}
return this;
}
@Override
public String toString()
{
return statusCode + " : " + getResponseBodyAsString();
}
private StringBuilder appendWithSeparators(StringBuilder builder, int[] codes, String separator)
{
if (codes != null && codes.length > 0)
{
builder.append(codes[0]);
for (int i = 1; i < codes.length; i++)
{
builder.append(separator).append(codes[i]);
}
}
return builder;
}
}
| 26.940789
| 116
| 0.648352
|
678f28bf6d8cb60482f290827b72cc08e1fb5f05
| 27,729
|
package me.ele.uetool;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.annotation.IntDef;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SwitchCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.List;
import me.ele.uetool.base.Element;
import me.ele.uetool.base.IAttrs;
import me.ele.uetool.base.ItemArrayList;
import me.ele.uetool.base.item.AddMinusEditItem;
import me.ele.uetool.base.item.BitmapItem;
import me.ele.uetool.base.item.BriefDescItem;
import me.ele.uetool.base.item.EditTextItem;
import me.ele.uetool.base.item.Item;
import me.ele.uetool.base.item.SwitchItem;
import me.ele.uetool.base.item.TextItem;
import me.ele.uetool.base.item.TitleItem;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_ADD_MINUS_EDIT;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_BITMAP;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_BRIEF_DESC;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_EDIT_TEXT;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_SWITCH;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_TEXT;
import static me.ele.uetool.AttrsDialog.Adapter.ViewType.TYPE_TITLE;
import static me.ele.uetool.base.DimenUtil.dip2px;
import static me.ele.uetool.base.DimenUtil.getScreenHeight;
import static me.ele.uetool.base.DimenUtil.getScreenWidth;
/**
* 属性编辑 dialog
*/
public class AttrsDialog extends Dialog {
private RecyclerView vList;
private Adapter adapter = new Adapter();
private RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
public AttrsDialog(Context context) {
super(context, R.style.uet_Theme_Holo_Dialog_background_Translucent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.uet_dialog_attrs);
vList = findViewById(R.id.list);
vList.setAdapter(adapter);
vList.setLayoutManager(layoutManager);
}
public void show(Element element) {
show();
Window dialogWindow = getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
dialogWindow.setGravity(Gravity.LEFT | Gravity.TOP);
lp.x = element.getRect().left;
lp.y = element.getRect().bottom;
lp.width = getScreenWidth() - dip2px(30);
lp.height = getScreenHeight() / 2;
dialogWindow.setAttributes(lp);
adapter.notifyDataSetChanged(element);
layoutManager.scrollToPosition(0);
}
/**
* 一般情况下是按了「ValidViews」开关后
* dialog 需要显示该元素的 view tree
*
* 这里添加一组 BriefDescItem「简述条目」
* recycler view 用的 item
*
* @param positionStart positionStart
* @param validElements validElements
* @param targetElement targetElement
*/
public void notifyValidViewItemInserted(int positionStart, List<Element> validElements, Element targetElement) {
List<Item> validItems = new ArrayList<>();
for (int i = 0, N = validElements.size(); i < N; i++) {
Element element = validElements.get(i);
validItems.add(new BriefDescItem(element, targetElement.equals(element)));
}
adapter.notifyValidViewItemInserted(positionStart, validItems);
}
/**
* 关闭「ValidViews」
*
* @param positionStart positionStart
*/
public final void notifyItemRangeRemoved(int positionStart) {
adapter.notifyValidViewItemRemoved(positionStart);
}
/**
* 设置 recycler view adapter 回调
*
* @param callback callback
*/
public void setAttrDialogCallback(AttrDialogCallback callback) {
adapter.setAttrDialogCallback(callback);
}
/**
* recycler view adapter 回调
*/
public interface AttrDialogCallback {
void enableMove();
void showValidViews(int position, boolean isChecked);
void selectView(Element element);
}
/**
* recycler view adapter
*/
public static class Adapter extends RecyclerView.Adapter {
private List<Item> items = new ItemArrayList<>();
private List<Item> validItems = new ArrayList<>();
private AttrDialogCallback callback;
/**
* 设置 recycler view adapter 回调
*
* @param callback callback
*/
public void setAttrDialogCallback(AttrDialogCallback callback) {
this.callback = callback;
}
/**
* 更新关于这个元素的 属性列表「可编辑功能列表」
*
* @param element element
*/
public void notifyDataSetChanged(Element element) {
items.clear();
for (String attrsProvider : UETool.getInstance().getAttrsProvider()) {
try {
IAttrs attrs = (IAttrs) Class.forName(attrsProvider).newInstance();
items.addAll(attrs.getAttrs(element));
} catch (Exception e) {
e.printStackTrace();
}
}
notifyDataSetChanged();
}
/**
* 展开关于这个元素的 view tree
*
* @param positionStart positionStart
* @param validItems validItems
*/
public void notifyValidViewItemInserted(int positionStart, List<Item> validItems) {
this.validItems.addAll(validItems);
items.addAll(positionStart, validItems);
notifyItemRangeInserted(positionStart, validItems.size());
}
/**
* 关闭关于这个元素的 view tree
*/
public void notifyValidViewItemRemoved(int positionStart) {
items.removeAll(validItems);
notifyItemRangeRemoved(positionStart, validItems.size());
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
switch (viewType) {
case TYPE_TITLE:
return TitleViewHolder.newInstance(parent);
case TYPE_TEXT:
return TextViewHolder.newInstance(parent);
case TYPE_EDIT_TEXT:
return EditTextViewHolder.newInstance(parent);
case TYPE_SWITCH:
return SwitchViewHolder.newInstance(parent, callback);
case TYPE_ADD_MINUS_EDIT:
return AddMinusEditViewHolder.newInstance(parent);
case TYPE_BITMAP:
return BitmapInfoViewHolder.newInstance(parent);
case TYPE_BRIEF_DESC:
return BriefDescViewHolder.newInstance(parent, callback);
}
throw new RuntimeException(viewType + " is an unknown view type!");
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
if (holder.getClass() == TitleViewHolder.class) {
((TitleViewHolder) holder).bindView((TitleItem) getItem(position));
} else if (holder.getClass() == TextViewHolder.class) {
((TextViewHolder) holder).bindView((TextItem) getItem(position));
} else if (holder.getClass() == EditTextViewHolder.class) {
((EditTextViewHolder) holder).bindView((EditTextItem) getItem(position));
} else if (holder.getClass() == SwitchViewHolder.class) {
((SwitchViewHolder) holder).bindView((SwitchItem) getItem(position));
} else if (holder.getClass() == AddMinusEditViewHolder.class) {
((AddMinusEditViewHolder) holder).bindView((AddMinusEditItem) getItem(position));
} else if (holder.getClass() == BitmapInfoViewHolder.class) {
((BitmapInfoViewHolder) holder).bindView((BitmapItem) getItem(position));
} else if (holder.getClass() == BriefDescViewHolder.class) {
((BriefDescViewHolder) holder).bindView((BriefDescItem) getItem(position));
}
}
@Override
public int getItemViewType(int position) {
Item item = getItem(position);
if (item.getClass() == TitleItem.class) {
return TYPE_TITLE;
} else if (item.getClass() == TextItem.class) {
return TYPE_TEXT;
} else if (item.getClass() == EditTextItem.class) {
return TYPE_EDIT_TEXT;
} else if (item.getClass() == SwitchItem.class) {
return TYPE_SWITCH;
} else if (item.getClass() == AddMinusEditItem.class) {
return TYPE_ADD_MINUS_EDIT;
} else if (item.getClass() == BitmapItem.class) {
return TYPE_BITMAP;
} else if (item.getClass() == BriefDescItem.class) {
return TYPE_BRIEF_DESC;
}
throw new RuntimeException("Unknown item type.");
}
@Override
public int getItemCount() {
return items.size();
}
@Nullable
@SuppressWarnings("unchecked")
protected <T extends Item> T getItem(int adapterPosition) {
if (adapterPosition < 0 || adapterPosition >= items.size()) {
return null;
}
return (T) items.get(adapterPosition);
}
@IntDef({
TYPE_TITLE,
TYPE_TEXT,
TYPE_EDIT_TEXT,
TYPE_SWITCH,
TYPE_ADD_MINUS_EDIT,
TYPE_BITMAP,
TYPE_BRIEF_DESC,
})
@Retention(RetentionPolicy.SOURCE)
@interface ViewType {
int TYPE_TITLE = 1;
int TYPE_TEXT = 2;
int TYPE_EDIT_TEXT = 3;
int TYPE_SWITCH = 4;
int TYPE_ADD_MINUS_EDIT = 5;
int TYPE_BITMAP = 6;
int TYPE_BRIEF_DESC = 7;
}
public static abstract class BaseViewHolder<T extends Item>
extends RecyclerView.ViewHolder {
protected T item;
public BaseViewHolder(View itemView) {
super(itemView);
}
public void bindView(T t) {
item = t;
}
}
/**
* 标题 cell
*/
public static class TitleViewHolder extends BaseViewHolder<TitleItem> {
private TextView vTitle;
public TitleViewHolder(View itemView) {
super(itemView);
vTitle = itemView.findViewById(R.id.title);
}
public static TitleViewHolder newInstance(ViewGroup parent) {
return new TitleViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.uet_cell_title, parent, false));
}
@Override
public void bindView(TitleItem titleItem) {
super.bindView(titleItem);
vTitle.setText(titleItem.getName());
}
}
/**
* 文本 cell
* 「class」信息等
*/
public static class TextViewHolder extends BaseViewHolder<TextItem> {
private TextView vName;
private TextView vDetail;
public TextViewHolder(View itemView) {
super(itemView);
vName = itemView.findViewById(R.id.name);
vDetail = itemView.findViewById(R.id.detail);
}
public static TextViewHolder newInstance(ViewGroup parent) {
return new TextViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.uet_cell_text, parent, false));
}
@Override
public void bindView(final TextItem textItem) {
super.bindView(textItem);
vName.setText(textItem.getName());
vDetail.setText(textItem.getDetail());
vDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (textItem.isEnableCopy()) {
Util.clipText(textItem.getDetail());
}
}
});
}
}
/**
* 可编辑属性的 cell
* 「文案」「文案大小」「颜色」「宽度」
* 「高度」「Padding left right top bottom」
*
* @param <T> T
*/
public static class EditTextViewHolder<T extends EditTextItem>
extends BaseViewHolder<T> {
protected TextView vName;
protected EditText vDetail;
@Nullable
private View vColor;
protected TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
try {
if (item.getType() == EditTextItem.Type.TYPE_TEXT) {
TextView textView = ((TextView) (item.getElement().getView()));
if (!TextUtils.equals(textView.getText().toString(), s.toString())) {
textView.setText(s.toString());
}
} else if (item.getType() == EditTextItem.Type.TYPE_TEXT_SIZE) {
TextView textView = ((TextView) (item.getElement().getView()));
float textSize = Float.valueOf(s.toString());
if (textView.getTextSize() != textSize) {
textView.setTextSize(textSize);
}
} else if (item.getType() == EditTextItem.Type.TYPE_TEXT_COLOR) {
TextView textView = ((TextView) (item.getElement().getView()));
int color = Color.parseColor(vDetail.getText().toString());
if (color != textView.getCurrentTextColor()) {
vColor.setBackgroundColor(color);
textView.setTextColor(color);
}
} else if (item.getType() == EditTextItem.Type.TYPE_WIDTH) {
View view = item.getElement().getView();
int width = dip2px(Integer.valueOf(s.toString()));
if (Math.abs(width - view.getWidth()) >= dip2px(1)) {
view.getLayoutParams().width = width;
view.requestLayout();
}
} else if (item.getType() == EditTextItem.Type.TYPE_HEIGHT) {
View view = item.getElement().getView();
int height = dip2px(Integer.valueOf(s.toString()));
if (Math.abs(height - view.getHeight()) >= dip2px(1)) {
view.getLayoutParams().height = height;
view.requestLayout();
}
} else if (item.getType() == EditTextItem.Type.TYPE_PADDING_LEFT) {
View view = item.getElement().getView();
int paddingLeft = dip2px(Integer.valueOf(s.toString()));
if (Math.abs(paddingLeft - view.getPaddingLeft()) >= dip2px(1)) {
view.setPadding(paddingLeft, view.getPaddingTop(),
view.getPaddingRight(), view.getPaddingBottom());
}
} else if (item.getType() == EditTextItem.Type.TYPE_PADDING_RIGHT) {
View view = item.getElement().getView();
int paddingRight = dip2px(Integer.valueOf(s.toString()));
if (Math.abs(paddingRight - view.getPaddingRight()) >= dip2px(1)) {
view.setPadding(view.getPaddingLeft(), view.getPaddingTop(),
paddingRight, view.getPaddingBottom());
}
} else if (item.getType() == EditTextItem.Type.TYPE_PADDING_TOP) {
View view = item.getElement().getView();
int paddingTop = dip2px(Integer.valueOf(s.toString()));
if (Math.abs(paddingTop - view.getPaddingTop()) >= dip2px(1)) {
view.setPadding(view.getPaddingLeft(), paddingTop,
view.getPaddingRight(), view.getPaddingBottom());
}
} else if (item.getType() == EditTextItem.Type.TYPE_PADDING_BOTTOM) {
View view = item.getElement().getView();
int paddingBottom = dip2px(Integer.valueOf(s.toString()));
if (Math.abs(paddingBottom - view.getPaddingBottom()) >= dip2px(1)) {
view.setPadding(view.getPaddingLeft(), view.getPaddingTop(),
view.getPaddingRight(), paddingBottom);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void afterTextChanged(Editable s) {
}
};
public EditTextViewHolder(View itemView) {
super(itemView);
vName = itemView.findViewById(R.id.name);
vDetail = itemView.findViewById(R.id.detail);
vColor = itemView.findViewById(R.id.color);
vDetail.addTextChangedListener(textWatcher);
}
public static EditTextViewHolder newInstance(ViewGroup parent) {
return new EditTextViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.uet_cell_edit_text, parent, false));
}
@Override
public void bindView(final T editTextItem) {
super.bindView(editTextItem);
vName.setText(editTextItem.getName());
vDetail.setText(editTextItem.getDetail());
if (vColor != null) {
try {
vColor.setBackgroundColor(Color.parseColor(editTextItem.getDetail()));
vColor.setVisibility(View.VISIBLE);
} catch (Exception e) {
vColor.setVisibility(View.GONE);
}
}
}
}
/**
* 加减号编辑 cell,同时具备 可编辑属性 的功能
* 「文案」「文案大小」「颜色」「宽度」
* 「高度」「Padding left right top bottom」
*/
public static class AddMinusEditViewHolder extends EditTextViewHolder<AddMinusEditItem> {
private View vAdd;
private View vMinus;
public AddMinusEditViewHolder(View itemView) {
super(itemView);
vAdd = itemView.findViewById(R.id.add);
vMinus = itemView.findViewById(R.id.minus);
vAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
int textSize = Integer.valueOf(vDetail.getText().toString());
vDetail.setText(String.valueOf(++textSize));
} catch (Exception e) {
e.printStackTrace();
}
}
});
vMinus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
int textSize = Integer.valueOf(vDetail.getText().toString());
if (textSize > 0) {
vDetail.setText(String.valueOf(--textSize));
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static AddMinusEditViewHolder newInstance(ViewGroup parent) {
return new AddMinusEditViewHolder(LayoutInflater.from(parent.getContext()).inflate(
R.layout.uet_cell_add_minus_edit, parent, false));
}
@Override
public void bindView(AddMinusEditItem editTextItem) {
super.bindView(editTextItem);
}
}
/**
* 开关 cell
* 「Move」「ValidViews」「isBold」
*/
public static class SwitchViewHolder extends BaseViewHolder<SwitchItem> {
private TextView vName;
private SwitchCompat vSwitch;
public SwitchViewHolder(View itemView, final AttrDialogCallback callback) {
super(itemView);
vName = itemView.findViewById(R.id.name);
vSwitch = itemView.findViewById(R.id.switch_view);
vSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
try {
if (item.getType() == SwitchItem.Type.TYPE_MOVE) {
if (callback != null && isChecked) {
callback.enableMove();
}
return;
} else if (item.getType() == SwitchItem.Type.TYPE_SHOW_VALID_VIEWS) {
item.setChecked(isChecked);
if (callback != null) {
callback.showValidViews(getAdapterPosition(), isChecked);
}
return;
}
if (item.getElement().getView() instanceof TextView) {
TextView textView = ((TextView) (item.getElement().getView()));
if (item.getType() == SwitchItem.Type.TYPE_IS_BOLD) {
textView.setTypeface(null,
isChecked ? Typeface.BOLD : Typeface.NORMAL);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public static SwitchViewHolder newInstance(ViewGroup parent, AttrDialogCallback callback) {
return new SwitchViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.uet_cell_switch, parent, false), callback);
}
@Override
public void bindView(SwitchItem switchItem) {
super.bindView(switchItem);
vName.setText(switchItem.getName());
vSwitch.setChecked(switchItem.isChecked());
}
}
/**
* bitmap cell
* 「color」「background」
*/
public static class BitmapInfoViewHolder extends BaseViewHolder<BitmapItem> {
private final int imageHeight = dip2px(58);
private TextView vName;
private ImageView vImage;
private TextView vInfo;
public BitmapInfoViewHolder(View itemView) {
super(itemView);
vName = itemView.findViewById(R.id.name);
vImage = itemView.findViewById(R.id.image);
vInfo = itemView.findViewById(R.id.info);
}
public static BitmapInfoViewHolder newInstance(ViewGroup parent) {
return new BitmapInfoViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.uet_cell_bitmap_info, parent, false));
}
@Override
public void bindView(BitmapItem bitmapItem) {
super.bindView(bitmapItem);
vName.setText(bitmapItem.getName());
Bitmap bitmap = bitmapItem.getBitmap();
int height = Math.min(bitmap.getHeight(), imageHeight);
int width = (int) ((float) height / bitmap.getHeight() * bitmap.getWidth());
ViewGroup.LayoutParams layoutParams = vImage.getLayoutParams();
layoutParams.width = width;
layoutParams.height = height;
vImage.setImageBitmap(bitmap);
vInfo.setText(bitmap.getWidth() + "px*" + bitmap.getHeight() + "px");
}
}
/**
* 描述 cell
* 只有一个 text
*/
public static class BriefDescViewHolder extends BaseViewHolder<BriefDescItem> {
private TextView vDesc;
public BriefDescViewHolder(View itemView, final AttrDialogCallback callback) {
super(itemView);
vDesc = (TextView) itemView;
vDesc.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (callback != null) {
callback.selectView(item.getElement());
}
}
});
}
public static BriefDescViewHolder newInstance(ViewGroup parent, AttrDialogCallback callback) {
return new BriefDescViewHolder(LayoutInflater.from(parent.getContext())
.inflate(R.layout.uet_cell_brief_view_desc, parent, false), callback);
}
@Override
public void bindView(BriefDescItem briefDescItem) {
super.bindView(briefDescItem);
View view = briefDescItem.getElement().getView();
StringBuilder sb = new StringBuilder();
sb.append(view.getClass().getName());
String resName = Util.getResourceName(view.getId());
if (!TextUtils.isEmpty(resName)) {
sb.append("@").append(resName);
}
vDesc.setText(sb.toString());
vDesc.setSelected(briefDescItem.isSelected());
}
}
}
}
| 37.624152
| 116
| 0.538462
|
8385295a5e1bdd66d5c3c096566f6276488dea41
| 1,987
|
// Copyright (c) Facebook, Inc. and its affiliates.
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
package com.facebook.ads.injkit.crashshield.safe_components;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.View;
@SuppressLint({"EmptyCatchBlock", "CatchGeneralException"})
public class SafeView extends View {
public boolean onMeasureCalled;
public boolean safe_onMeasureCalled;
public SafeView(Context context) {
super(context);
}
public SafeView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SafeView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SafeView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
public boolean performClick() {
try {
safe_performClick();
} catch (Throwable t) {
}
return super.performClick();
}
// Subclasses that implement performClick() will have their method
// change automatically to this by crashshield
public boolean safe_performClick() {
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
onMeasureCalled = true;
try {
safe_onMeasure(widthMeasureSpec, heightMeasureSpec);
} catch (Throwable t) {
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
protected void safe_onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
safe_onMeasureCalled = true;
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onDraw(Canvas canvas) {
try {
safe_onDraw(canvas);
} catch (Throwable t) {
}
super.onDraw(canvas);
}
protected void safe_onDraw(Canvas canvas) {}
}
| 24.8375
| 91
| 0.72924
|
933ee43060e44c929b2d8d99d27aa23003db83b2
| 5,648
|
/**
* Copyright 2015-2018 Tobias Gierke <tobias.gierke@code-sourcery.de>
*
* 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.codesourcery.javr.assembler.arch;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import de.codesourcery.javr.assembler.arch.AbstractArchitecture.InstructionEncoding;
/**
* A binary prefix tree used to look up instructions my bit patterns.
*
* TODO: Currently not used anymore...
*
* @author tobias.gierke@code-sourcery.de
*/
public class PrefixTree
{
private final Node root = new Node("");
private static final class Node
{
public Node parent;
public Node bitOne;
public Node bitZero;
public final List<InstructionEncoding> encodings = new ArrayList<>();
public final String path;
public Node(String path) {
this.path = path;
}
@Override
public String toString() {
return toString(0);
}
public void add(InstructionEncoding enc) {
Validate.notNull(enc, "encoding must not be NULL");
this.encodings.add( enc );
// decoding process will pick the encoding with the most specific (=largest number of matching bits)
// pattern and fail if two candidate encodings end up having the same number of
// fixed bits in their masks
// sort encodings by
final Comparator<InstructionEncoding> cmp = (a,b) ->
{
// sort descending by pattern length
return Integer.compare( b.encoder.getOpcodeBitCount() , a.encoder.getOpcodeBitCount() );
};
this.encodings.sort( cmp );
}
public String toString(int depth)
{
String result = "";
if ( bitOne != null ) {
result += bitOne.toString( depth+1);
}
if ( bitZero != null ) {
result += bitZero.toString( depth+1 );
}
final String padding = StringUtils.repeat( "_" , depth );
final String lines = ""+encodings.stream().map( s -> s.mnemonic ).collect(Collectors.joining(",") );
return padding+path+": "+lines+"\n"+result;
}
}
public String toString()
{
return root.toString(0);
}
public void add(InstructionEncoding encoding)
{
final String pattern = encoding.encoder.getTrimmedPattern();
Node current = root;
for ( int i = 0 , len = pattern.length() ; i < len ; i++ )
{
final char c = pattern.charAt(i);
if ( c == '0' )
{
if ( current.bitZero != null ) {
current = current.bitZero;
}
else
{
final Node n = new Node( pattern.substring(0,i+1) );
n.parent = current;
current.bitZero= n;
current = n;
}
}
else if ( c == '1' )
{
if ( current.bitOne != null ) {
current = current.bitOne;
}
else
{
final Node n = new Node( pattern.substring(0,i+1) );
n.parent = current;
current.bitOne = n;
current = n;
}
}
else
{
break;
}
}
// System.out.println("Adding '"+encoding.mnemonic.toUpperCase()+" to "+current.path+" (trimmed: "+pattern+")");
current.add( encoding );
}
public List<InstructionEncoding> getMatches(int value)
{
Node current = root;
int mask=0b10000000_00000000_00000000_00000000;
for ( int i = 0 ; i < 32 ; i++ )
{
final boolean bitSet = (value & mask)!=0;
if ( bitSet )
{
if ( current.bitOne == null ) {
return pick( current , value );
}
current = current.bitOne;
} else {
if ( current.bitZero == null ) {
return pick( current , value );
}
current = current.bitZero;
}
mask >>>= 1;
}
return null;
}
private List<InstructionEncoding> pick(Node node,int value)
{
// look for matches
final List<InstructionEncoding> result = new ArrayList<>();
for ( InstructionEncoding enc : node.encodings )
{
if ( enc.encoder.matches( value ) )
{
result.add( enc );
}
}
if ( result.isEmpty() && node.parent != null )
{
return pick(node.parent,value);
}
return result;
}
}
| 32.274286
| 119
| 0.51682
|
1eefa9e29351c342b406295dc8a4b2d691cf1584
| 440
|
package com.github.mengweijin.quickboot.sample.system.service;
import com.github.mengweijin.quickboot.jpa.service.BaseService;
import com.github.mengweijin.quickboot.sample.system.entity.Address;
import com.github.mengweijin.quickboot.sample.system.repository.AddressRepository;
/**
* @author Meng Wei Jin
* @date Create in 2019-07-28 0:36
**/
public interface AddressService extends BaseService<Address, Long, AddressRepository> {
}
| 31.428571
| 87
| 0.806818
|
1d643e1d59270f91f190724833e367e48121ec2a
| 2,304
|
package edu.fiuba.algo3.vista;
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.text.Font;
import java.awt.*;
public abstract class Panel extends Component {
protected Label ejercitos = new Label();
protected Label paisOrigen = new Label("");
protected Label paisDestino = new Label("");
Panel(){
paisOrigen.setLayoutX(1030);
paisOrigen.setLayoutY(300);
paisOrigen.setPrefHeight(25);
paisOrigen.setPrefWidth(250);
paisOrigen.toFront();
paisDestino.setLayoutX(1030);
paisDestino.setLayoutY(350);
paisDestino.setPrefHeight(25);
paisDestino.setPrefWidth(250);
//ejercitos.setStyle("-fx-text-fill: black");
ejercitos.setLayoutX(900);
ejercitos.setLayoutY(60);
ejercitos.setPrefHeight(90);
ejercitos.setPrefWidth(200);
}
public Label crearLabelCabezera(String texto){
Label cantidadRestante = new Label();
cantidadRestante.setStyle("-fx-text-fill: black");
cantidadRestante.setText(texto);
cantidadRestante.setLayoutX(920);
cantidadRestante.setLayoutY(20);
cantidadRestante.setPrefHeight(100);
cantidadRestante.setPrefWidth(400);
return cantidadRestante;
}
public void limpiarPaises() {
paisOrigen.setText("");
paisDestino.setText("");
}
public void setPaisOrigen(String pais) {
paisOrigen.setText(pais);
}
public void setPaisDestino(String pais) {
paisDestino.setText(pais);
}
public abstract void setContactos(Panel panelAtaque);
public abstract void ocultar();
public abstract void mostrar();
public abstract Panel siguientePanel(boolean sigueRonda);
EventHandler<KeyEvent> permitirNumeros = new EventHandler<>(){
@Override
public void handle(KeyEvent event){
TextField textoEjercitos = (TextField) event.getSource();
textoEjercitos.textProperty().addListener((observable, oldValue, newValue) -> {
if(!newValue.matches("[0-9]*")){
textoEjercitos.setText(oldValue);
}
});
}
};
}
| 28.444444
| 91
| 0.650608
|
ff15b75fa489958a9a4747d46e4856d176d70667
| 232
|
package com.ftme.common.model;
import com.ftme.common.model.base.BaseItems;
/**
* Generated by JFinal.
*/
@SuppressWarnings("serial")
public class Items extends BaseItems<Items> {
public static final Items dao = new Items();
}
| 19.333333
| 45
| 0.737069
|
135fe4b3df64e1391faf1b83ac94c3af00a0a0f8
| 1,900
|
package br.com.zupacademy.malkon.proposta.form;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import br.com.zupacademy.malkon.proposta.dominio.Biometria;
public class BiometriaForm {
@NotEmpty
@NotNull
private List<String> biometria;
public BiometriaForm(List<String> biometria) {
this.biometria = biometria;
}
public BiometriaForm() {
}
public List<String> getBiometria() {
return biometria;
}
public List<Biometria> toBiometria(String idCartao) {
List<Biometria> listaDeBiometrias = new ArrayList<>();
for (String umaBiometria : biometria) {
String umaBiometriaCodificada = Base64.getEncoder().encodeToString(umaBiometria.getBytes());
/*
* Testa se a biometria é válida. Para testar se ela é inválida, adicione
* qualquer caractere à biometria após ela ser codificada e uma exceção será
* lançada. Ex: if (IsBase64String(umaBiometriaCodificada + "22"))
*/
if (IsBase64String(umaBiometriaCodificada)) {
Biometria biometria = new Biometria(idCartao, umaBiometriaCodificada);
listaDeBiometrias.add(biometria);
} else {
throw new IllegalArgumentException();
}
}
return listaDeBiometrias;
}
/*
* Para uma biometria codificada ser considerada válida no algoritmo Base64 o
* número de caracteres dela deve ser divisível por 4 e ela só pode conter os
* caracteres deste pattern do regex
*/
private boolean IsBase64String(String biometriaCodificada) {
Pattern p = Pattern.compile("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$");
Matcher matcher = p.matcher(biometriaCodificada);
biometriaCodificada = biometriaCodificada.trim();
return (biometriaCodificada.length() % 4 == 0) && matcher.lookingAt();
}
}
| 29.230769
| 98
| 0.735789
|
06c7001e1324b9ec4325b6fe9b134c928987b47f
| 1,664
|
package linkedin;
import utils.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class FindLeavesOfBinaryTree {
public static void main(String [] args) {
TreeNode node1 = new TreeNode(1);
TreeNode node2 = new TreeNode(2);
TreeNode node3 = new TreeNode(3);
TreeNode node4 = new TreeNode(4);
TreeNode node5 = new TreeNode(5);
node1.left = node2;
node2.left = node4;
node2.right = node5;
node1.right = node3;
FindLeavesOfBinaryTree findLeaves = new FindLeavesOfBinaryTree();
List<List<Integer>> lists = findLeaves.findLeaves(node1);
for (List<Integer> list : lists) {
System.out.println(list);
}
}
public List<List<Integer>> findLeaves(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if (root == null) return list;
while(true) {
List<Integer> leaves = new ArrayList<>();
boolean noChildren = processLeaves(root, leaves);
list.add(leaves);
if (noChildren) {
break;
}
}
return list;
}
boolean processLeaves(TreeNode root, List<Integer> leaves) {
if (root == null) return true;
if (root.left == null && root.right == null) {
leaves.add(root.val);
return true;
}
boolean isLeaf = processLeaves(root.left, leaves);
if (isLeaf) {
root.left = null;
}
isLeaf = processLeaves(root.right, leaves);
if (isLeaf) {
root.right = null;
}
return false;
}
}
| 27.733333
| 73
| 0.55649
|
55f4fe850eea98237dee8a5b7cb67eeccec7b91c
| 1,730
|
package com.lichkin.activiti.services.impl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;
import com.lichkin.activiti.beans.LKActivitiTaskInfo;
import com.lichkin.activiti.beans.in.impl.LKActivitiGetPendingProcessIn;
import com.lichkin.activiti.beans.out.impl.LKActivitiGetPendingProcessOut;
import com.lichkin.activiti.services.LKActivitiCommonService;
import com.lichkin.framework.utils.LKBeanUtils;
/**
* 获取待办流程服务类
* @author SuZhou LichKin Information Technology Co., Ltd.
*/
@Service
public class LKActivitiGetPendingProcessService extends LKActivitiCommonService {
public List<LKActivitiGetPendingProcessOut> getPendingProcess(LKActivitiGetPendingProcessIn in) {
List<Task> taskList = taskService.createTaskQuery().taskAssignee(in.getUserId()).active().orderByTaskCreateTime().asc().list();
Set<String> idsSet = new HashSet<>();
List<LKActivitiTaskInfo> taskInfoList = new ArrayList<>();
for (Task task : taskList) {
idsSet.add(task.getProcessInstanceId());
LKActivitiTaskInfo taskInfo = new LKActivitiTaskInfo();
taskInfo.setProcessInstanceId(task.getProcessInstanceId());
taskInfo.setTaskName(task.getName());
taskInfo.setTaskStartTime(task.getCreateTime());
taskInfoList.add(taskInfo);
}
setProcessInfo(taskInfoList, idsSet);
List<LKActivitiGetPendingProcessOut> outList = new ArrayList<>();
for (LKActivitiTaskInfo taskInfo : taskInfoList) {
LKActivitiGetPendingProcessOut out = new LKActivitiGetPendingProcessOut(taskInfo.getProcessInstanceId());
outList.add(LKBeanUtils.copyProperties(taskInfo, out));
}
return outList;
}
}
| 36.041667
| 129
| 0.79711
|
bbffafd3e266ef8d17e8758c0f17168dcfacacc4
| 5,731
|
package com.ttech.jpe.metric.prometheus.observe;
import com.ttech.jpe.metric.prometheus.type.*;
import io.prometheus.client.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static java.util.Arrays.stream;
@Component
public class MetricsRegistry {
private Map<CounterMetric, Counter> counterMetricsList;
private Map<GaugeMetric, Gauge> gaugeMetricsList;
private Map<SummaryMetric, Summary> summaryMetricsList;
private Map<HistogramMetric, Histogram> histogramMetricsList;
public MetricsRegistry(CollectorRegistry registry) {
counterMetricsList = new HashMap<>();
stream(CounterMetric.values()).forEach(metric -> {
Counter.Builder counterBuilder = Counter.build()
.name(metric.getParams().get(MetricParamType.NAME))
.help(metric.getParams().get(MetricParamType.HELPTEXT));
String labels = metric.getParams().get(MetricParamType.LABELNAME);
if (!StringUtils.isEmpty(labels))
counterBuilder.labelNames(metric.getParams().get(MetricParamType.LABELNAME).split(";"));
Counter counter = counterBuilder.register(registry);
counterMetricsList.put(metric, counter);
});
gaugeMetricsList = new HashMap<>();
stream(GaugeMetric.values()).forEach(metric -> {
Gauge.Builder gaugeBuilder = Gauge.build()
.name(metric.getParams().get(MetricParamType.NAME))
.help(metric.getParams().get(MetricParamType.HELPTEXT));
String labels = metric.getParams().get(MetricParamType.LABELNAME);
if (!StringUtils.isEmpty(labels))
gaugeBuilder.labelNames(metric.getParams().get(MetricParamType.LABELNAME).split(";"));
Gauge gauge = gaugeBuilder.register(registry);
gaugeMetricsList.put(metric, gauge);
});
summaryMetricsList = new HashMap<>();
stream(SummaryMetric.values()).forEach(metric -> {
List<String[]> quantileList = stream(metric.getParams().get(MetricParamType.QUANTILE).split(";"))
.map(s -> s.split(","))
.collect(Collectors.toList());
Summary.Builder summaryBuilder = Summary.build()
.name(metric.getParams().get(MetricParamType.NAME))
.help(metric.getParams().get(MetricParamType.HELPTEXT))
.maxAgeSeconds(Long.parseLong(metric.getParams().get(MetricParamType.TIMEWINDOWSECS)));
String labels = metric.getParams().get(MetricParamType.LABELNAME);
if (!StringUtils.isEmpty(labels))
summaryBuilder.labelNames(labels.split(";"));
quantileList.forEach(quantile -> summaryBuilder.quantile(Double.parseDouble(quantile[0]), Double.parseDouble(quantile[1])));
Summary summary = summaryBuilder.register(registry);
summaryMetricsList.put(metric, summary);
});
histogramMetricsList = new HashMap<>();
stream(HistogramMetric.values()).forEach(metric -> {
double[] buckets = stream(metric.getParams().get(MetricParamType.BUCKET).split(","))
.mapToDouble(Double::parseDouble)
.toArray();
Histogram.Builder histogramBuilder = Histogram.build()
.name(metric.getParams().get(MetricParamType.NAME))
.help(metric.getParams().get(MetricParamType.HELPTEXT))
.buckets(buckets);
String labels = metric.getParams().get(MetricParamType.LABELNAME);
if (!StringUtils.isEmpty(labels))
histogramBuilder.labelNames(metric.getParams().get(MetricParamType.LABELNAME).split(";"));
Histogram histogram = histogramBuilder.register(registry);
histogramMetricsList.put(metric, histogram);
});
}
public void observe(IMetric metric, double val, String... labels) {
boolean hasLabels = labels != null;
switch (metric.getMetricType()) {
case GAUGE:
if (hasLabels)
gaugeMetricsList.get(metric).labels(labels).set(val);
else
gaugeMetricsList.get(metric).set(val);
break;
case HISTOGRAM:
if (hasLabels)
histogramMetricsList.get(metric).labels(labels).observe(val);
else
histogramMetricsList.get(metric).observe(val);
break;
case SUMMARY:
if (hasLabels)
summaryMetricsList.get(metric).labels(labels).observe(val);
else
summaryMetricsList.get(metric).observe(val);
break;
case COUNTER:
if (hasLabels)
counterMetricsList.get(metric).labels(labels).inc(val);
else
counterMetricsList.get(metric).inc(val);
break;
}
}
public double getCounterValue(CounterMetric metric, String... labels) {
if (labels != null)
return counterMetricsList.get(metric).labels(labels).get();
else
return counterMetricsList.get(metric).get();
}
public void clearMetric(CounterMetric metric) {
counterMetricsList.get(metric).clear();
}
}
| 37.953642
| 137
| 0.593265
|
6b33b088c799d2e117ae954f18254c56762677bf
| 4,790
|
package com.ebay.dss.zds.magic;
import com.ebay.dss.zds.dao.ZetaNotebookRepository;
import com.ebay.dss.zds.interpreter.interpreters.Interpreter;
import com.ebay.dss.zds.magic.exception.ZetaMagicHandleException;
import com.ebay.dss.zds.magic.exception.ZetaVariableInjectionException;
import com.ebay.dss.zds.magic.pattern.DynamicReplaceMatcher;
import com.ebay.dss.zds.magic.pattern.MagicPattern;
import com.ebay.dss.zds.magic.pattern.PatternHandler;
import com.ebay.dss.zds.model.NotebookVariable;
import com.ebay.dss.zds.model.NotebookVarsMap;
import com.ebay.dss.zds.model.ZetaNotebook;
import com.ebay.dss.zds.websocket.notebook.dto.CodeWithSeq;
import org.codehaus.plexus.util.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import static com.ebay.dss.zds.model.NotebookVariable.PATTERN_A;
import static com.ebay.dss.zds.model.NotebookVariable.PATTERN_B;
/**
* Created by tatian on 2020-10-22.
*/
@Component
public class DynamicVariableHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DynamicVariableHandler.class);
@Autowired
private ZetaNotebookRepository repository;
@Value("${zds.notebook.dynamicVariable.enable:#{true}}")
private volatile boolean enabled;
private HandleStateContext notHandled(Interpreter interpreter) {
return HandleStateContext.forwarded(interpreter);
}
public final HandleStateContext handle(Interpreter interpreter, CodeWithSeq codeWithSeq, ZetaNotebook notebook, NotebookVarsMap someVarsMap)
throws ZetaMagicHandleException, ZetaVariableInjectionException {
if (!enabled) {
LOGGER.info("The dynamic variable is not enabled");
return notHandled(interpreter);
}
if (someVarsMap != null) {
// try match magic
/** the comment pos should align with code, if there is no comment in code, the comment should be null or empty**/
MagicPattern.MatcherAndPattern matcherAndPattern = MagicPattern.tryMatch(codeWithSeq.getCode(), codeWithSeq.getCommentPos());
if (matcherAndPattern.isMatched()) {
LOGGER.info("Handling zeta magic statement: {} for note: {}, nt: {}",
matcherAndPattern.pattern.name(), notebook.getId(), notebook.getNt());
// if handled it will return a not null VariableHandlerCallback instance
// otherwise it will throw exception
PatternHandler patternHandler = matcherAndPattern.pattern.getHandler();
return patternHandler.handle(new HandleContext(interpreter, matcherAndPattern.matcher, codeWithSeq, notebook, someVarsMap, repository));
}
// try match variables
LOGGER.info("Injecting variables for statement: {}, note: {}, nt: {}",
codeWithSeq.getStatementId(), notebook.getId(), notebook.getNt());
try {
DynamicReplaceMatcher drMatcher = DynamicReplaceMatcher.matchAllAndReplace(
codeWithSeq.getCode(),
(String matchedVar) -> matchAndReplaceVars(matchedVar, someVarsMap),
/** the comment pos should align with code, if there is no comment in code, the comment should be null or empty**/
codeWithSeq.getCommentPos(),
PATTERN_A, PATTERN_B);
if (drMatcher.replaced) {
codeWithSeq.setCode(drMatcher.result);
LOGGER.info("Code replaced to: {}", drMatcher.result);
return new HandleStateContext(HandleState.INJECTED, ExecutionAgent.forwardAgent(interpreter));
}
} catch (Exception ex) {
throw ex instanceof NullPointerException ?
new ZetaVariableInjectionException(ExceptionUtils.getFullStackTrace(ex))
: new ZetaVariableInjectionException(ex);
}
} else {
LOGGER.info("Can't find any vars in note: {}, nt: {}, skip vars handling", notebook.getId(), notebook.getNt());
}
return notHandled(interpreter);
}
public static String matchAndReplaceVars(String nameWithClause, NotebookVarsMap varsMap) {
// only check the head and tail since the pattern already matched
String varName = NotebookVariable.getTrimmedVariableName(nameWithClause);
String value = "";
NotebookVariable variable = varsMap.get(varName);
if (variable != null && variable.value != null) {
value = variable.value;
LOGGER.info("Variable: {} injected to: {}", varName, value);
} else {
LOGGER.info("Can't find any value for variable: {}, leave it to empty string", varName);
}
return value;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| 42.767857
| 144
| 0.722756
|
6df28b8d049b427dce4a56f448f0b6ca71ded4ca
| 334
|
package online.pizzacrust.autoverify.trello.api;
import com.google.common.collect.BiMap;
import online.pizzacrust.roblox.api.Robloxian;
public interface Database {
BiMap<Robloxian, String> getRegistrationEntries();
void refresh() throws Exception;
void register(Robloxian entry, String discord) throws Exception;
}
| 20.875
| 68
| 0.778443
|
cdf7625dff931ef40bbabd1ae6f5801d79032ab4
| 1,958
|
package cn.navigational.impl;
import cn.navigational.base.BaseVerticle;
import cn.navigational.enums.EventBusDataType;
import cn.navigational.utils.ExceptionUtils;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Objects;
import static cn.navigational.config.Constants.*;
import static cn.navigational.utils.ExceptionUtils.nullableStr;
import static cn.navigational.utils.ResponseUtils.*;
public class RestVerticle extends BaseVerticle {
protected Logger logger = LogManager.getLogger();
/**
* 将请求信息转发到对应的子路由上去
*
* @param rcx http请求上下文
*/
protected void sendMessage(RoutingContext rcx) {
final JsonObject msg = rcx.getBodyAsJson();
final String requestAPi = msg.getString(EVENT_ADDRESS);
vertx.eventBus().<JsonObject>request(requestAPi, msg, _rs -> {
if (_rs.failed()) {
response(rcx, executeException(_rs.cause()));
return;
}
response(rcx, _rs.result().body());
});
}
/**
* 拦截http异常状态码,根据http状态码自定义回复信息#目前只处理500/404
*
* @param router http请求路由
*/
protected void exHandler(Router router) {
router.errorHandler(500, _routingContext -> {
_routingContext.failure().printStackTrace();
response(_routingContext, executeException(_routingContext.failure()));
});
router.errorHandler(404, _routingContext -> {
final JsonObject info = responseTemplate("你访问的资源去了火星", 404, false, EventBusDataType.JSON);
response(_routingContext, info);
});
}
private JsonObject executeException(Throwable _t) {
logger.error("Event bus 请求失败:{}", _t.getMessage());
_t.printStackTrace();
return responseFailed(ERROR_MESSAGE, 500);
}
}
| 30.59375
| 102
| 0.670582
|
49a81a22239ae2fdd4a7dae95a5d9b7d2fc6e05b
| 191
|
package com.jmelzer.myttr.model;
/**
* Created by cicgfp on 04.03.2018.
*/
public enum LigaPosType {
AUFSTEIGER,
AUF_RELEGATION,
NOTHING,
AB_RELEGATION,
ABSTEIGER;
}
| 12.733333
| 35
| 0.659686
|
333ea8a93d78009fd0ba9ba780baa39bc2587366
| 2,668
|
package com.nbware.push.model;
import java.util.Date;
public class ReservedSendRequest {
private int msgMngId;
private String content;
private String receiverId;
private int result;
private Date requestDateTime;
private String title;
private Date showDate;
private char receiverType;
private String imgUrl;
private int successCnt;
private int failCnt;
private Date sendDate;
public int getSuccessCnt() {
return successCnt;
}
public void setSuccessCnt(int successCnt) {
this.successCnt = successCnt;
}
public int getFailCnt() {
return failCnt;
}
public void setFailCnt(int failCnt) {
this.failCnt = failCnt;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public int getMsgMngId() {
return msgMngId;
}
public void setMsgMngId(int msgMngId) {
this.msgMngId = msgMngId;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getReceiverId() {
return receiverId;
}
public void setReceiverId(String receiverId) {
this.receiverId = receiverId;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public Date getRequestDateTime() {
return requestDateTime;
}
public void setRequestDateTime(Date requestDateTime) {
this.requestDateTime = requestDateTime;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Date getShowDate() {
return showDate;
}
public void setShowDate(Date showDate) {
this.showDate = showDate;
}
public char getReceiverType() {
return receiverType;
}
public void setReceiverType(char receiverType) {
this.receiverType = receiverType;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ReservedSendRequest [msgMngId=");
builder.append(msgMngId);
builder.append(", content=");
builder.append(content);
builder.append(", receiverId=");
builder.append(receiverId);
builder.append(", result=");
builder.append(result);
builder.append(", requestDateTime=");
builder.append(requestDateTime);
builder.append(", title=");
builder.append(title);
builder.append(", showDate=");
builder.append(showDate);
builder.append(", receiverType=");
builder.append(receiverType);
builder.append(", imgUrl=");
builder.append(imgUrl);
builder.append("]");
return builder.toString();
}
}
| 18.921986
| 55
| 0.718141
|
c47ab59904657c43a554d24fa29599a92e6a4ab0
| 1,468
|
package datamodel.ignitiondelay;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.FileUtils;
import com.google.common.base.CharMatcher;
import com.google.common.base.Splitter;
import com.google.common.collect.Iterables;
import datamodel.ModelValue;
/**
* The Ignition delay currently implemented is the defined as the first maximum
* in temperature increase as a function of reaction time.
* @author Nick
*
*/
public class IgnitionDelayModelValue extends ModelValue {
public double value;
public IgnitionDelayModelValue(){
type = ModelValue.IGNITION_DELAY;
}
@Override
public void setValue(File f) {
read(f);
}
public void read(File f){
List<String> lines = null;
try {
lines = FileUtils.readLines(f, "UTF-8");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (String line : lines) {
Iterable<String> results = Splitter.on(CharMatcher.anyOf(","))
.trimResults().omitEmptyStrings().split(line);
String[] pieces = Iterables.toArray(results, String.class);
if (line.startsWith("Ignition_time_1_by_max_dT/dt")) {
value = Double.parseDouble(pieces[pieces.length-1]);
}
}
}
@Override
public double getSSQValue() {
return Math.pow(value, 2);
}
}
| 23.677419
| 80
| 0.698229
|
4d6060c5e4e81d3d0f9d233c25c332a530915bc4
| 6,002
|
package com.example.subastaya;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class AuctionActivity extends ActionBarActivity {
private Auction auction;
private Product product;
private MainProductInfoFragment mainProductInfo;
private OfferFormFragment offerForm;
private AuthUser user = null;
private ImageView prev;
private ImageView next;
private Boolean canGoPrev = false; // checks if the user is able to go click on prev button
private Boolean canGoNext = false; // checks if the user is able to go click on prev button
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_auction);
getIntent();
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
@Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String query = intent.getStringExtra(MainActivity.EXTRA_QUERY);
this.user = (AuthUser) intent.getSerializableExtra(MainActivity.EXTRA_USER);
this.offerForm = (OfferFormFragment) getSupportFragmentManager().findFragmentById(R.id.offerform_fragment);
this.mainProductInfo = (MainProductInfoFragment) getSupportFragmentManager().findFragmentById(R.id.mainproductinfo_fragment);
this.prev = (ImageView) findViewById(R.id.prevArrow);
this.next = (ImageView) findViewById(R.id.nextArrow);
this.auction = new AuctionImpl(query);
mainProductInfo.setLoading();
disableActions();
this.auction.nextProduct(new Callback<AuctionResponse>() {
@Override
public void success(AuctionResponse auctionResponse, Response arg1) {
/*
*/
if (auctionResponse.getState() == AuctionState.API_ERROR) {
//displayServerError();
//return;
} else if (auctionResponse.getState() == AuctionState.EMPTY_RESULTS) {
mainProductInfo.showEmptyResultsMessage();
return;
}
product = auctionResponse.getProduct();
displayCurrentProduct();
canGoNext = auctionResponse.hasNext();
canGoPrev = auctionResponse.hasPrevious();
updateActionEnableing();
}
@Override
public void failure(RetrofitError arg0) {
}
});
}
public void disableActions() {
this.next.setVisibility(View.GONE);
this.prev.setVisibility(View.GONE);
}
public void updateActionEnableing() {
if ( canGoNext ) {
this.next.setVisibility(View.VISIBLE);
} else {
this.next.setVisibility(View.GONE);
}
if ( canGoPrev ) {
this.prev.setVisibility(View.VISIBLE);
} else {
this.prev.setVisibility(View.GONE);
}
}
public void displayCurrentProduct() {
this.mainProductInfo.setContent(this.product);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.auction, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_auction,
container, false);
return rootView;
}
}
public void nextProduct(View view) {
if ( this.canGoNext ) {
this.canGoNext = false;
this.canGoPrev = false;
mainProductInfo.setLoading();
disableActions();
this.auction.nextProduct(new Callback<AuctionResponse>() {
@Override
public void success(AuctionResponse auctionResponse, Response arg1) {
if (auctionResponse.getState() == AuctionState.API_ERROR) {
//displayServerError();
//return;
}
product = auctionResponse.getProduct();
displayCurrentProduct();
canGoNext = auctionResponse.hasNext();
canGoPrev = auctionResponse.hasPrevious();
updateActionEnableing();
}
@Override
public void failure(RetrofitError arg0) {
}
});
}
}
public void prevProduct(View view) {
if ( this.canGoPrev ) {
this.canGoNext = false;
this.canGoPrev = false;
mainProductInfo.setLoading();
disableActions();
this.auction.prevProduct(new Callback<AuctionResponse>() {
@Override
public void success(AuctionResponse auctionResponse, Response arg1) {
if (auctionResponse.getState() == AuctionState.API_ERROR) {
//displayServerError();
//return;
}
product = auctionResponse.getProduct();
displayCurrentProduct();
canGoNext = auctionResponse.hasNext();
canGoPrev = auctionResponse.hasPrevious();
updateActionEnableing();
}
@Override
public void failure(RetrofitError arg0) {
}
});
}
}
public void offer(View view) {
this.offerForm.offer(view, user, product);
}
}
| 27.916279
| 130
| 0.695268
|
ae39d1c4b95c78c15cb135fa71caa43154001948
| 482
|
package proxy.ch02;
import proxy.ch01.TargetObjectService;
public class TimeProxy implements TargetObjectService {
TargetObjectService targetObjectService;
public TimeProxy(TargetObjectService targetObjectService) {
this.targetObjectService = targetObjectService;
}
@Override
public void query(String name) {
System.out.println("time-------------------start");
targetObjectService.query(name);
System.out.println("time-------------------end");
}
}
| 22.952381
| 61
| 0.707469
|
dae8abe4125fcc287e775ea4419102257df54c0e
| 428
|
package com.hongliangjie.fugue.topicmodeling;
import com.hongliangjie.fugue.Message;
/**
* Created by liangjie on 10/29/14.
*/
public abstract class TopicModel {
public abstract void train(int start, int end);
public abstract void test(int start, int end);
public abstract void train();
public abstract void test();
public abstract void setMessage(Message m);
public abstract Message getMessage();
}
| 26.75
| 51
| 0.728972
|
f667e524ccfa39b8aafff027822f52ed6e684cc1
| 6,090
|
package frc.robot.commands;
import frc.robot.Constants;
import frc.robot.subsystems.ClimbAngle;
import frc.robot.subsystems.ClimbHook;
import frc.robot.subsystems.ClimbLift;
import edu.wpi.first.wpilibj.Timer;
import edu.wpi.first.wpilibj2.command.CommandBase;
import com.ctre.phoenix.motorcontrol.NeutralMode;
import com.revrobotics.CANSparkMax.IdleMode;
public class Climb_LiftForNextBar_HitBarAndBumpDown extends CommandBase {
@SuppressWarnings({"PMD.UnusedPrivateField", "PMD.SingularField"})
private final ClimbAngle angleSubsystem;
private final ClimbHook hookSubsystem;
private final ClimbLift liftSubsystem;
private boolean commandDone = false;
private boolean hooksSet = false;
private int climbStep = 0;
private Timer currentLimitTimeout = new Timer();
private Timer timer0 = new Timer();
/**
* @param angleSubsystem
* @param hookSubsystem
* @param liftSubsystem
*/
public Climb_LiftForNextBar_HitBarAndBumpDown(ClimbAngle angleSubsystem, ClimbHook hookSubsystem, ClimbLift liftSubsystem) {
addRequirements(angleSubsystem, hookSubsystem, liftSubsystem);
this.angleSubsystem = angleSubsystem;
this.hookSubsystem = hookSubsystem;
this.liftSubsystem = liftSubsystem;
}
@Override
public void initialize() {
// wpilib bug workaround
commandDone = false;
hooksSet = false;
angleSubsystem.setNeutralMode(NeutralMode.Coast); // coast the arm motors
liftSubsystem.setIdleMode(IdleMode.kBrake); // brake the lift motors
climbStep = 9; // start on step 9
}
@Override
public void execute() {
switch(climbStep) {
case 0: // SAFE MODE
System.out.println("ERROR: Winch exceeded current limit! Activating safe mode...");
hookSubsystem.set(true); // extend the hooks
// brake all motors
angleSubsystem.setNeutralMode(NeutralMode.Brake);
liftSubsystem.setIdleMode(IdleMode.kBrake);
// cut all power to angle
angleSubsystem.enablePID(false);
angleSubsystem.setPower(0);
angleSubsystem.stop();
// cut all power to lift
liftSubsystem.enablePID(false);
liftSubsystem.setPower(0);
liftSubsystem.stop();
commandDone = true; // we're done
climbStep = 1; // do nothing for remainder of command
break;
case 1:
; // do nothing
break;
case 9: // run winch a little to give us some slack
if (liftSubsystem.getLeftEncoderDistance() > 5 &&
liftSubsystem.getRightEncoderDistance() > 5) {
liftSubsystem.setPower(0);
climbStep = 10;
} else {
liftSubsystem.enablePID(false);
liftSubsystem.setPower(0.1);
}
break;
case 10: // run angle to get us off the bar
// if we're at the setpoint
if (angleSubsystem.getLeftEncoderDistance() > 60 &&
angleSubsystem.getRightEncoderDistance() > 60) {
climbStep = 11;
} else { // if we're not there yet
angleSubsystem.enablePID(true);
angleSubsystem.setPosition(78);
}
break;
case 11:
if (liftSubsystem.getLeftEncoderDistance() > 9 &&
liftSubsystem.getRightEncoderDistance() > 9) {
liftSubsystem.setPower(0);
climbStep = 12;
} else {
liftSubsystem.enablePID(false);
liftSubsystem.setPower(0.1);
}
break;
case 12: // winch out while avoiding the bar
// if we're at the setpoint
if (liftSubsystem.getLeftEncoderDistance() > 32.8 &&
liftSubsystem.getRightEncoderDistance() > 32.8) {
liftSubsystem.setPower(0);
if (timer0.get() > 0.0) {
climbStep = 13;
timer0.stop();
}
} else { // if we're not there yet
// go 33 inches out
liftSubsystem.enablePID(false);
liftSubsystem.setPower(0.2);
timer0.reset();
timer0.start();
if ((liftSubsystem.getLeftEncoderDistance() > 20 && liftSubsystem.getLeftEncoderDistance() < 21) &&
(liftSubsystem.getRightEncoderDistance() > 20 && liftSubsystem.getRightEncoderDistance() < 21)) {
angleSubsystem.enablePID(true);
angleSubsystem.setPosition(70);
}
}
break;
case 13: // bump down to get hook around bar
if (angleSubsystem.getLeftEncoderDistance() < 65 &&
angleSubsystem.getRightEncoderDistance() < 65) {
climbStep = 14;
} else {
angleSubsystem.enablePID(true);
angleSubsystem.setPosition(40);
}
break;
case 14: // angle back up for final send
if (angleSubsystem.getLeftEncoderDistance() > 95 &&
angleSubsystem.getRightEncoderDistance() > 95) {
climbStep = 15;
} else {
angleSubsystem.enablePID(true);
angleSubsystem.setPosition(110);
}
break;
case 15: // finish
commandDone = true;
climbStep = 1; // make loop do nothing
break;
}
// safe mode trigger
// if we're exceeding current limit:
if(liftSubsystem.getLeftMotorCurrent() > Constants.Climb.lift.maxCurrentThreshold ||
liftSubsystem.getRightMotorCurrent() > Constants.Climb.lift.maxCurrentThreshold) {
if (currentLimitTimeout.get() > Constants.Climb.lift.maxCurrentTimeout) { // if the timeout has expired while the current is exceeded
currentLimitTimeout.stop(); // stop the timeout timer
climbStep = 0; // go to safe mode!
}
} else { // if the current has not exceeded threshold
currentLimitTimeout.reset(); // full reset the timer
currentLimitTimeout.start();
}
}
@Override
public void end(boolean interrupted) {
}
@Override
public boolean isFinished() {
//return commandDone;
return false; // force never-ending for testing
}
}
| 26.025641
| 142
| 0.625123
|
7628d7030f2224eaea74c2a5abc6171358a2e104
| 4,210
|
/* FeatureIDE - A Framework for Feature-Oriented Software Development
* Copyright (C) 2005-2013 FeatureIDE team, University of Magdeburg, Germany
*
* This file is part of FeatureIDE.
*
* FeatureIDE is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FeatureIDE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FeatureIDE. If not, see <http://www.gnu.org/licenses/>.
*
* See http://www.fosd.de/featureide/ for further information.
*/
package de.ovgu.featureide.fm.ui.editors;
import java.util.Collection;
import java.util.Iterator;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.gef.ui.actions.PrintAction;
import org.eclipse.ui.IWorkbenchPart;
import de.ovgu.featureide.fm.core.Constraint;
import de.ovgu.featureide.fm.core.FMPoint;
import de.ovgu.featureide.fm.core.Feature;
import de.ovgu.featureide.fm.core.FeatureModel;
import de.ovgu.featureide.fm.core.FeatureModelLayout;
/**
* TODO A PrintAction for the FeatureModelEditor that temporarily moves the
* feature diagram to the top-left corner
*
* @author Fabian Benduhn
*/
public class FMPrintAction extends PrintAction {
/**
* @param part
*/
public FMPrintAction(IWorkbenchPart part) {
super(part);
}
@Override
public void run() {
if (!(this.getWorkbenchPart() instanceof FeatureModelEditor))
return;
FeatureModelEditor fmEditor = (FeatureModelEditor) this
.getWorkbenchPart();
FeatureModel featureModel = fmEditor.getFeatureModel();
FeatureModelLayout layout = featureModel.getLayout();
int layoutOld = layout.getLayoutAlgorithm();
Collection<Feature> features = featureModel.getFeatures();
Iterator<Feature> featureIter = features.iterator();
Point minP = FeatureUIHelper.getLocation(featureIter.next()).getCopy();
move(featureModel, layout, features, featureIter, minP);
//print
super.run();
moveBack(featureModel, layout, layoutOld, features, minP);
return;
}
private void move(FeatureModel featureModel, FeatureModelLayout layout,
Collection<Feature> features, Iterator<Feature> featureIter,
Point minP) {
layout.setLayout(0);
while (featureIter.hasNext()) {
Feature f = featureIter.next();
Point p = FeatureUIHelper.getLocation(f);
if (p.x < minP.x)
minP.x=p.x;
if (p.y < minP.y)
minP.y=p.y;
}
moveFeatures(features, minP);
moveConstraints(featureModel, minP);
moveLegend(featureModel, layout, minP);
}
private void moveBack(FeatureModel featureModel, FeatureModelLayout layout,
int layoutOld, Collection<Feature> features, Point minP) {
Point minPneg = new Point(-minP.x, -minP.y);
moveFeatures(features, minPneg);
moveConstraints(featureModel, minPneg);
moveLegend(featureModel, layout, minPneg);
layout.setLayout(layoutOld);
}
private void moveLegend(FeatureModel featureModel,
FeatureModelLayout layout, Point minP) {
FMPoint legendPos = layout.getLegendPos();
Point newLegendPos = new Point(legendPos.x - minP.x, legendPos.y
- minP.y);
FeatureUIHelper.getLegendFigure(featureModel).setLocation(newLegendPos);
layout.setLegendPos(newLegendPos.x, newLegendPos.y);
}
private void moveConstraints(FeatureModel featureModel, Point minP) {
for (Constraint c : featureModel.getConstraints()) {
Point newPoint = new Point(
FeatureUIHelper.getLocation(c).getCopy().x - minP.x,
FeatureUIHelper.getLocation(c).getCopy().y - minP.y);
FeatureUIHelper.setLocation(c, newPoint);
}
}
private void moveFeatures(Collection<Feature> features, Point minP) {
for (Feature f : features) {
Point newPoint = new Point(
FeatureUIHelper.getLocation(f).getCopy().x - minP.x,
FeatureUIHelper.getLocation(f).getCopy().y - minP.y);
FeatureUIHelper.setLocation(f, newPoint);
}
}
}
| 32.635659
| 78
| 0.743943
|
994b61e71cec4d4b6805c9ada7b0dac1ae5978c6
| 152
|
package com.backbase.flow.example.interaction.dto;
import lombok.Data;
@Data
public class PersonSearchCriteriaDTO {
private String idNumber;
}
| 12.666667
| 50
| 0.776316
|
479eb3835f021d2ec0190d17afc336fc4847bfe4
| 276
|
package top.auzqy.design.pattern.behavioral.visitor.example1.eg1_1;
public class WordFile extends ResourceFile {
public WordFile(String filePath) {
super(filePath);
}
@Override
public void extract2txt() {
//...
System.out.println("Extract WORD.");
}
}
| 19.714286
| 67
| 0.699275
|
8ffaaa9328229d28e0df6301162bb27c929f3c84
| 1,101
|
package com.brainmatics.trainingjee201801.springboot.aplikasispringboot.entity;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.hibernate.annotations.GenericGenerator;
@Entity @Table(name = "kabupaten_kota")
@Getter @Setter @EqualsAndHashCode(of = {"id"}) @ToString
public class KabupatenKota implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "uuid" )
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
@NotNull @Size(min = 3)
private String kode;
@NotNull @Size(min = 3)
private String nama;
@ManyToOne
@JoinColumn(name = "id_provinsi")
private Provinsi provinsi;
}
| 27.525
| 79
| 0.760218
|
67f234a245fba6a8dac1fb7f1330e6ec0caaeb9b
| 731
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.search.documents.test.environment.models;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Author {
@JsonProperty(value = "FirstName")
private String firstName;
@JsonProperty(value = "LastName")
private String lastName;
public String firstName() {
return this.firstName;
}
public Author firstName(String firstName) {
this.firstName = firstName;
return this;
}
public String lastName() {
return this.lastName;
}
public Author lastName(String lastName) {
this.lastName = lastName;
return this;
}
}
| 22.84375
| 60
| 0.673051
|
362d2fcd1441cf55128dde71ba1245c80a2bd4a3
| 2,153
|
package kr.dogfoot.hwplib.writer.bodytext.paragraph;
import java.io.IOException;
import kr.dogfoot.hwplib.object.bodytext.paragraph.header.ParaHeader;
import kr.dogfoot.hwplib.object.etc.HWPTag;
import kr.dogfoot.hwplib.object.fileheader.FileVersion;
import kr.dogfoot.hwplib.util.compoundFile.writer.StreamWriter;
/**
* 문단 헤더 레코드를 쓰기 위한 객체
*
* @author neolord
*/
public class ForParaHeader {
/**
* 문단 헤더 레코드를 쓴다.
*
* @param ph
* 문단 헤더 레코드
* @param sw
* 스트림 라이터
* @throws IOException
*/
public static void write(ParaHeader ph, StreamWriter sw) throws IOException {
recordHeader(ph, sw);
lastInList_TextCount(ph, sw);
sw.writeUInt4(ph.getControlMask().getValue());
sw.writeUInt2(ph.getParaShapeId());
sw.writeUInt1(ph.getStyleId());
sw.writeUInt1(ph.getDivideSort().getValue());
sw.writeUInt2(ph.getCharShapeCount());
sw.writeUInt2(ph.getRangeTagCount());
sw.writeUInt2(ph.getLineAlignCount());
sw.writeUInt4(ph.getInstanceID());
if (sw.getFileVersion().isOver(5, 0, 3, 2)) {
sw.writeUInt2(ph.getIsMergedByTrack());
}
}
/**
* 문단 헤더 레코드의 레코드 헤더를 쓴다.
*
* @param ph
* 문단 헤더 레코드
* @param sw
* 스트림 라이터
* @throws IOException
*/
private static void recordHeader(ParaHeader ph, StreamWriter sw)
throws IOException {
sw.writeRecordHeader(HWPTag.PARA_HEADER, getSize(sw.getFileVersion()));
}
/**
* 문단 헤더 레코드의 크기를 반환한다.
*
* @param version
* 파일 버전
* @return 문단 헤더 레코드의 크기
*/
private static int getSize(FileVersion version) {
int size = 0;
size += 22;
if (version.isOver(5, 0, 3, 2)) {
size += 2;
}
return size;
}
/**
* 문단 리스트에서 마지막 문단여부와 문자수를 쓴다.
*
* @param ph
* 문단 헤더 레코드
* @param sw
* 스트림 라이터
* @throws IOException
*/
private static void lastInList_TextCount(ParaHeader ph, StreamWriter sw)
throws IOException {
long value = 0;
if (ph.isLastInList()) {
value += 0x80000000;
}
value += ph.getCharacterCount() & 0x7fffffff;
sw.writeUInt4(value);
}
}
| 23.659341
| 79
| 0.623316
|
f5bf65670fe8078868ecf66b3b19757b92341b45
| 4,915
|
package com.solucionesdigitales.vote.entity.partner;
import java.time.LocalDate;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.index.Indexed;
import org.springframework.data.mongodb.core.mapping.DBRef;
import org.springframework.data.mongodb.core.mapping.Document;
import com.solucionesdigitales.vote.entity.Congress;
import com.solucionesdigitales.vote.entity.Photo;
import com.solucionesdigitales.vote.entity.PoliticalParty;
import com.solucionesdigitales.vote.entity.user.User;
@Document(collection = "partners")
public class Partner {
@Id
private String id;
@Indexed
private int sku;
private String name;
private String apPaterno;
private String apMaterno;
private LocalDate fechaCumplianos;
private String email;
private String comisiones;
private String distrito;
private String legislatura;
private String telefono;
@DBRef
private PoliticalParty partido;
@DBRef
private User user;
@DBRef
private Congress congreso;
@DBRef
private Photo foto;
private int tipoPartner;//1 LEGISLATOR, 2 OPERATOR
private int status;
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(String id) {
this.id = id;
}
/**
* @return the sku
*/
public int getSku() {
return sku;
}
/**
* @param sku the sku to set
*/
public void setSku(int sku) {
this.sku = sku;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
public String getApPaterno() {
return apPaterno;
}
public void setApPaterno(String apPaterno) {
this.apPaterno = apPaterno;
}
public String getApMaterno() {
return apMaterno;
}
public void setApMaterno(String apMaterno) {
this.apMaterno = apMaterno;
}
/**
* @return the fechaCumplianos
*/
public LocalDate getFechaCumplianos() {
return fechaCumplianos;
}
/**
* @param fechaCumplianos the fechaCumplianos to set
*/
public void setFechaCumplianos(LocalDate fechaCumplianos) {
this.fechaCumplianos = fechaCumplianos;
}
/**
* @return the email
*/
public String getEmail() {
return email;
}
/**
* @param email the email to set
*/
public void setEmail(String email) {
this.email = email;
}
public String getTelefono() {
return telefono;
}
public void setTelefono(String telefono) {
this.telefono = telefono;
}
/**
* @return the comisiones
*/
public String getComisiones() {
return comisiones;
}
/**
* @param comisiones the comisiones to set
*/
public void setComisiones(String comisiones) {
this.comisiones = comisiones;
}
/**
* @return the distrito
*/
public String getDistrito() {
return distrito;
}
/**
* @param distrito the distrito to set
*/
public void setDistrito(String distrito) {
this.distrito = distrito;
}
/**
* @return the legislatura
*/
public String getLegislatura() {
return legislatura;
}
/**
* @param legislatura the legislatura to set
*/
public void setLegislatura(String legislatura) {
this.legislatura = legislatura;
}
/**
* @return the partido
*/
public PoliticalParty getPartido() {
return partido;
}
/**
* @param partido the partido to set
*/
public void setPartido(PoliticalParty partido) {
this.partido = partido;
}
/**
* @return the congreso
*/
public Congress getCongreso() {
return congreso;
}
/**
* @param congreso the congreso to set
*/
public void setCongreso(Congress congreso) {
this.congreso = congreso;
}
/**
* @return the foto
*/
public Photo getFoto() {
return foto;
}
/**
* @param foto the foto to set
*/
public void setFoto(Photo foto) {
this.foto = foto;
}
public int getTipoPartner() {
return tipoPartner;
}
public void setTipoPartner(int tipoPartner) {
this.tipoPartner = tipoPartner;
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Partner [id=" + id + ", sku=" + sku + ", name=" + name + ", apPaterno=" + apPaterno + ", apMaterno="
+ apMaterno + ", fechaCumplianos=" + fechaCumplianos + ", email=" + email + ", comisiones=" + comisiones
+ ", distrito=" + distrito + ", legislatura=" + legislatura + ", telefono=" + telefono + ", partido="
+ partido + ", user=" + user + ", congreso=" + congreso + ", foto=, tipoPartner="
+ tipoPartner + ", status=" + status + "]";
}
}
| 21.557018
| 111
| 0.646592
|
6908be4cb8ac6982eba2840ad30bd618536c0406
| 4,003
|
package ca.marklauman.tools.preferences;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.preference.PreferenceManager;
import android.util.AttributeSet;
import android.widget.LinearLayout;
/** Generic structure for a preference. */
@SuppressWarnings({"SameParameterValue", "WeakerAccess", "unused"})
public abstract class Preference<T> extends LinearLayout {
/** The listener to be notified if this preference changes */
private PreferenceListener listener;
/** The id to pass to the listener */
private int listenId;
/** The key used to save the preference */
protected String key;
// ======= DEFINED METHODS ======= //
public Preference(Context context) {
super(context);
}
public Preference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public Preference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public Preference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
/** The same as setListener(listener, 0)
* @param listener The new listener for this Preference */
public void setListener(PreferenceListener listener) {
setListener(listener, 0);
}
/** Assign a listener to this preference. The listener will be alerted when
* the preference changes value.
* @param listener The new listener.
* @param id An identifier, which will be passed to the listener when the value changes. */
public void setListener(PreferenceListener listener, int id) {
this.listener = listener;
listenId = id;
}
/** Call this when you wish to notify the listeners of a change. */
public void alertListener() {
if(listener != null)
listener.preferenceChanged(listenId);
}
/** Set the key used to save values.
* If a key is specified, then the preference will save its value to the
* default sharedPreference of the activity.
* Automatically triggers a reload if the key has changed. */
public void setKey(String key) {
// Check if the keys are the same
if (key == null) {
if (this.key == null) return;
} else {
if(key.equals(this.key)) return;
}
// The keys are not the same
this.key = key;
reload();
}
/** Get the key used to save the preference */
public String getKey() {
return key;
}
/** The same as calling {@link #setValue(Object, boolean)} with notify set to {@code false}. */
public void setValue(T value) {
setValue(value, false);
}
/** Get the default SharedPreferences for this context.
* (useful utility method) */
protected SharedPreferences getSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(getContext());
}
// ======= ABSTRACT METHODS ======= //
/** Load this preference's value from the default SharedPreferences of this activity.
* If this changes the value of the preference, notify listeners. */
abstract public void reload();
/** Set the value of this preference.
* @param value The new value of the preference.
* @param notify If the listeners should be notified of the change */
abstract public void setValue(T value, boolean notify);
/** Get the value of this preference. */
abstract public T getValue();
/** Interface used for those who wish to listen to a Preference */
public interface PreferenceListener {
/** Called when a preference is changed.
* @param id The id passed to the preference when the listener was set. */
void preferenceChanged(int id);
}
}
| 35.741071
| 99
| 0.666
|
85d1781b187b31425a26a994b652d3299d0be1e0
| 1,856
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.eclipse.birt.chart.model.data;
import java.math.BigDecimal;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Big Number Data Element</b></em>'.
* <!-- end-user-doc -->
*
* <!-- begin-model-doc -->
* Element BigNUmberDataElement represents a DataElement which BigDecimal value.
* <!-- end-model-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.eclipse.birt.chart.model.data.BigNumberDataElement#getValue <em>Value</em>}</li>
* </ul>
* </p>
*
* @see org.eclipse.birt.chart.model.data.DataPackage#getBigNumberDataElement()
* @model extendedMetaData="name='BigNumberDataElement' kind='elementOnly'"
* @generated
*/
public interface BigNumberDataElement extends DataElement
{
/**
* Returns the value of the '<em><b>Value</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Value</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Value</em>' attribute.
* @see #setValue(BigDecimal)
* @see org.eclipse.birt.chart.model.data.DataPackage#getBigNumberDataElement_Value()
* @model dataType="org.eclipse.emf.ecore.xml.type.Decimal" required="true"
* extendedMetaData="kind='element' name='Value'"
* @generated
*/
BigDecimal getValue( );
/**
* Sets the value of the '{@link org.eclipse.birt.chart.model.data.BigNumberDataElement#getValue <em>Value</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Value</em>' attribute.
* @see #getValue()
* @generated
*/
void setValue( BigDecimal value );
/**
* @generated
*/
BigNumberDataElement copyInstance( );
} // BigNumberDataElement
| 27.294118
| 125
| 0.655172
|
078a43214a4e5ccb631f6b78b879be65ba175a42
| 4,435
|
package phoenix.kmeans;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Kmeans<T extends IItem> {
/**
* 所有数据列表
*/
private List<T> items ;
/**
* 数据类别
*/
private Class<T> clazz ;
/**
* 中心点集合
*/
private List<T> seedList;
/**
* 分类数
*/
private int k = 1;
public Kmeans(List<T> list, int k,Class<T> clazz) {
this.items = list;
this.k = k;
this.clazz = clazz;
}
/**
* 执行聚类运算
* @return
*/
public Result run() throws InstantiationException, IllegalAccessException {
(clazz.newInstance()).prehandle(items);
seedList = new ArrayList<T>(items.subList(0,k)); //默认选几个数据点当中心
@SuppressWarnings("unchecked")
List<T>[] results = new ArrayList[k];
boolean centerChanged = true;
while (centerChanged) {
centerChanged = false;
//清空结果数组
for (int i = 0; i < k; i++) {
if(results[i]==null){
results[i]=new ArrayList<T>();
}else{
results[i].clear();
}
}
//运算每个数据点与种子的距离,投放到距离近的种子对应的结果集中
T tmp_item;
int min_index=0;
double min_dist=Double.MAX_VALUE,tmp_dist;
for (int i = 0; i < items.size(); i++) {
tmp_item = items.get(i);
min_dist=Double.MAX_VALUE;
for (int j = 0; j < seedList.size(); j++) {
tmp_dist = seedList.get(j).distance(tmp_item);
if(tmp_dist<min_dist){
min_index=j;
min_dist=tmp_dist;
}
}
results[min_index].add(tmp_item);
}
//找新的中心点,更换掉种子
for (int i = 0; i < k; i++) {
if(results[i]==null || results[i].size()==0){
continue;
}
T t_new = findNewCenter(results[i]);
if (!seedList.get(i).equals(t_new)){
centerChanged = true;
seedList.set(i, t_new);
}
}
System.out.println("==");
}
return new Result(true, results, seedList);
}
/**
* 得到新聚类中心对象
* @param ps
* @return
*/
public T findNewCenter(List<T> ps) throws InstantiationException,IllegalAccessException {
T t = clazz.newInstance();
int fieldnum = t.getDimensionNum();
double[] ds = new double[fieldnum];
double[] tmpd;
for (T vo : ps) {
tmpd = vo.getDatas();
for (int i = 0; i < fieldnum; i++) {
ds[i] += tmpd[i];
}
}
for (int i = 0; i < fieldnum; i++) {
ds[i] = ds[i] / ps.size();
}
t.initPoint(ds);
return t;
}
public void loadDataFile(String filepath,int dimensionNum,Class<T> clazz,String split)
throws NumberFormatException, IOException, InstantiationException, IllegalAccessException{
List<T> list = new ArrayList<T>();
File file = new File(filepath);
BufferedReader reader = new BufferedReader(new FileReader(file));
String tempString = null;
T p = null ;
while ((tempString = reader.readLine()) != null) {
p = clazz.newInstance();
double[] s = new double[dimensionNum];
for(int i=0; i <dimensionNum ;i++){
s[i]=Double.parseDouble(tempString.split(split)[i]);
}
p.initPoint(s);
list.add(p);
}
reader.close();
items = list ;
}
public class Result {
/**
* 处理结果
*/
public boolean success = true ;
/**
* 数据分组后的结果
*/
public List<T>[] classifyResults ;
/**
* 中心点集合
*/
public List<T> cores ;
public Result(boolean success,List<T>[] classifyResults,List<T> cores){
this.success = success;
this.classifyResults = classifyResults;
this.cores = cores;
}
}
}
| 28.986928
| 102
| 0.471251
|
81d1ae98ee377e34ca8e82f6a47ba43fed0188af
| 935
|
package com.goldenapple.marble.block;
import com.goldenapple.marble.Marble;
import com.goldenapple.marble.reference.Reference;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
public class BlockCommon extends Block{
String name;
public BlockCommon(String name, Material material){
super(material);
this.name = name;
this.setCreativeTab(Marble.MarbleCreativeTab);
this.setBlockName(name);
}
@Override
public String getUnlocalizedName(){
return "tile." + Reference.MOD_ID.toLowerCase() + ":" + name;
}
@Override
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister register){
blockIcon = register.registerIcon(Reference.MOD_ID.toLowerCase() + ":" + name);
}
}
| 29.21875
| 87
| 0.722995
|
c73f4272c750050f77786fc57d00976661c328e9
| 493
|
package Basic.TestModifier;
import Basic.JavaModifier;
//测试修饰符protected
public class JavaModifierTest2 extends JavaModifier {
public static void main(String[] args) {
//受保护的protected方法在不同的包中的子类(JavaModifierTest2)是能访问的
JavaModifierTest2 O = new JavaModifierTest2();
O.setpd(123);
System.out.println(O.getpd());
//注意:这样还是不能访问
JavaModifier O1 = new JavaModifier();
//O1.setpd(123);
//System.out.println(O1.getpd());
}
}
| 24.65
| 58
| 0.659229
|
9d9eee889090ac16cde358cab440aae50eabd9e8
| 189
|
package test.targets.java.library;
public class Point {
public static String getCoordinates(String test) {
return "Real library returns the actual request parameter";
}
}
| 21
| 64
| 0.719577
|
d875a74f49f39092a07e3dc2ea442caa59fe33f1
| 893
|
/*
* NumberLiteralTokenFactory.java
*
* Created on 15 September 2003, 23:45
*/
package org.tigris.lazer.cj.java;
//import java.util.regex.Matcher;
//import java.util.regex.Pattern;
/**
*
* @author Bob Tarling
*/
public class NumberLiteralTokenFactory // extends AbstractTokenFactory
{
// private static Pattern numberPattern =
// Pattern.compile("((0[xX][0-9A-Fa-f]+)|([0-9]*\\.)?[0-9]+([eE][-+]?[0-9]+)?[fFdD]?)");
// private Matcher matcher;
/** Creates a new instance of BlockCommentTokenFactory */
public NumberLiteralTokenFactory() {
}
// public boolean isApplicable(String text) {
// matcher = numberPattern.matcher(text);
// return matcher.lookingAt();
// }
// public Token createToken(String text, int start) {
// int position = matcher.end();
// return TokenFactory.createToken(text.substring(start, position),
// NumberTokenType.getInstance());
// }
}
| 22.897436
| 89
| 0.683091
|
a95ad866f73f49db7c6b98f837e5de70b5755c1a
| 5,380
|
package com.example.ewallet;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.w3c.dom.Text;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.prefs.Preferences;
public class MainActivity extends AppCompatActivity {
ArrayList<Items> ItemsList;
int addPrice,chkBalance,newBalance,Balance;
String addCategory;
private AlertDialog dialog;
private Button buttonIncomeExpenseDialog,buttonEnter;
private EditText category,price;
private RadioGroup radioGroup;
private RadioButton radioButton,radioIncome,radioExpense;
private ListView listViewItem;
private TextView textBalance;
@Override
protected void onStart() {
super.onStart();
//get Balance from share Preferences
SharedPreferences preferencesGetNewBalance = getSharedPreferences("shared preferences",MODE_PRIVATE);
Balance = preferencesGetNewBalance.getInt("New Balance",Balance);
textBalance.setText(""+Balance);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
if(AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_YES){
setTheme(R.style.DarkTheme);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//load data from JSON
LoadData();
listViewItem = (ListView) findViewById(R.id.ItemList);
textBalance = (TextView) findViewById(R.id.Balance);
buttonIncomeExpenseDialog = (Button) findViewById(R.id.IncomeExpenseDialog);
buttonIncomeExpenseDialog.setBackgroundResource(R.drawable.button_default);
MainAdapter adapter = new MainAdapter(MainActivity.this,ItemsList);
listViewItem.setAdapter(adapter);
}
public void OpenDialog(View view){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.activity_dialog);
dialog = builder.create();
dialog.show();
category = dialog.findViewById(R.id.Category);
price = dialog.findViewById(R.id.Price);
radioGroup = dialog.findViewById(R.id.radioGroup);
radioIncome = dialog.findViewById(R.id.Income);
radioExpense = dialog.findViewById(R.id.Expense);
radioExpense.setChecked(true);
}
public void CloseDialog(View view){
// get add category from user input
addCategory = category.getText().toString();
// get add price from user input
try {
addPrice = Integer.parseInt(price.getText().toString());
}catch (NumberFormatException e){
addPrice = 0;
}
// get check radio button id from user input
int radioID = radioGroup.getCheckedRadioButtonId();
radioButton = dialog.findViewById(radioID);
if(radioButton == radioExpense){
addPrice = -addPrice;
}else{
addPrice = addPrice;
}
// get balance from Text View
chkBalance = Integer.parseInt(textBalance.getText().toString());
// Calculate balance
chkBalance = chkBalance + addPrice;
SharedPreferences preferencesSetCalcualteBalance = getSharedPreferences("shared preferences",MODE_PRIVATE);
preferencesSetCalcualteBalance.edit().putInt("New Balance",chkBalance).apply();
textBalance.setText(""+chkBalance);
if(addCategory!=null && addPrice!=0){
ItemsList.add(new Items(addCategory,addPrice));
SharedPreferences sharedPreferences = getSharedPreferences("shared list preferences",MODE_PRIVATE);
Gson gson = new Gson();
String json = gson.toJson(ItemsList);
sharedPreferences.edit().putString("take list",json).apply();
}
dialog.dismiss();
}
public void LoadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared list preferences",MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("take list",null);
Type type = new TypeToken<ArrayList<Items>>() {}.getType();
ItemsList = gson.fromJson(json,type);
if(ItemsList == null){
ItemsList = new ArrayList<>();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actionbar,menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.setting:
startActivity(new Intent(MainActivity.this, Setting.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
| 36.351351
| 115
| 0.685688
|
1fe2988d20bc6ae723a65574a3757d02fd77b7e9
| 2,763
|
/*
* Copyright (c) 2017 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.metric;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import com.spotify.heroic.common.Histogram;
import com.spotify.heroic.common.Series;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import lombok.Data;
@Data
public class SeriesSetsSummarizer {
private final HashSet<String> uniqueKeys = new HashSet<>();
private final Multimap<String, String> tags = HashMultimap.create();
private final Multimap<String, String> resource = HashMultimap.create();
private final Histogram.Builder seriesSize = Histogram.builder();
public void add(Set<Series> series) {
this.seriesSize.add(series.size());
for (final Series s : series) {
uniqueKeys.add(s.getKey());
for (Map.Entry<String, String> e : s.getTags().entrySet()) {
tags.put(e.getKey(), e.getValue());
}
for (Map.Entry<String, String> e : s.getResource().entrySet()) {
resource.put(e.getKey(), e.getValue());
}
}
}
public Summary end() {
final Histogram.Builder tagsSize = Histogram.builder();
final Histogram.Builder resourceSize = Histogram.builder();
for (final Map.Entry<String, Collection<String>> e : this.tags.asMap().entrySet()) {
tagsSize.add(e.getValue().size());
}
for (final Map.Entry<String, Collection<String>> e : this.resource.asMap().entrySet()) {
resourceSize.add(e.getValue().size());
}
return new Summary(uniqueKeys.size(), tagsSize.build(), resourceSize.build(),
seriesSize.build());
}
@Data
public static class Summary {
final long uniqueKeys;
final Histogram tagsSize;
final Histogram resourceSize;
final Histogram seriesSize;
}
}
| 34.111111
| 96
| 0.672096
|
73e7579a263850bf3b419673771b97a82d2bc519
| 8,458
|
package winterwell.jtwitter;
import java.net.HttpURLConnection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Connect to the streaming API.
* <p>
* Duplicate messages may be delivered when reconnecting to the Streaming API.
*
* @author Daniel
*/
public class TwitterStream extends AStream {
public static enum KMethod {
/**
* Follow hashtags, users or regions
*/
filter,
/** Everything! Requires special access privileges! */
firehose,
/** Requires special access privileges! */
links,
/**
* New-style retweets. Requires special access privileges! From
* dev.twitter.com: <i>Few applications require this level of access.
* Creative use of a combination of other resources and various access
* levels can satisfy nearly every application use case.</i>
* */
retweet,
/**
* Spritzer or Garden-hose: A sample of tweets, suitable for trend
* analysis. <br>
* The default level (spritzer) is roughly 1% of all public tweets. <br>
* The upgraded level (garden-hose - apply to Twitter for this) is 10%. <br>
* In both cases the algorithm is based on the tweet-id modulo 100.
*/
sample
}
/**
* Maximum number of keywords which most of us can track.
* @see #setTrackKeywords(List)
*/
public static int MAX_KEYWORDS = 400;
/**
* Maximum character length of a tracked keyword or phrase.
* @see #setTrackKeywords(List)
*/
public static final int MAX_KEYWORD_LENGTH = 60;
/**
* Maximum users who can be tracked.
* @see #setFollowUsers(List)
*/
public static final int MAX_USERS = 5000;
/**
* Used to help avoid breaking api limits.
*/
static Map<String, AStream> user2stream = new ConcurrentHashMap();
private List<Long> follow;
private List<double[]> locns;
KMethod method = KMethod.sample;
private List<String> track;
/**
*
* @param client
* This will have it's timeout set to 90 seconds. So you probably
* don't want to reuse the object with the REST api.
*/
public TwitterStream(Twitter jtwit) {
super(jtwit);
}
@Override
HttpURLConnection connect2() throws Exception {
connect3_rateLimit();
String url = "https://stream.twitter.com/"+Twitter.API_VERSION+"/statuses/"+method+".json";
Map<String, String> vars = new HashMap();
if (follow != null && follow.size() != 0) {
vars.put("follow", InternalUtils.join(follow, 0, Integer.MAX_VALUE));
}
if (track != null && track.size() != 0) {
vars.put("track", InternalUtils.join(track, 0, Integer.MAX_VALUE));
}
// If filtering, check we have a filter
if (vars.isEmpty() && method==KMethod.filter) {
throw new IllegalStateException("No filters set for "+this);
}
vars.put("delimited", "length");
// use post in case it's a long set of vars
HttpURLConnection con = client.post2_connect(url, vars);
return con;
}
/**
* Protect the rate limits & _help_ you avoid annoying Twitter (only
* locally! And forgetful! Do NOT rely on this)
*/
private void connect3_rateLimit() {
if (jtwit.getScreenName() == null)
return; // dunno
AStream s = user2stream.get(jtwit.getScreenName());
if (s != null && s.isConnected())
throw new TwitterException.TooManyLogins(
"One account, one stream (running: "
+ s
+ "; trying to run"
+ this
+ ").\n But streams OR their filter parameters, so one stream can do a lot.");
// memory paranoia
if (user2stream.size() > 500) {
// oh well -- forget stuff (this Map is just a safety check)
user2stream = new ConcurrentHashMap<String, AStream>();
}
user2stream.put(jtwit.getScreenName(), this);
}
@Override
int fillInOutages2(Twitter jtwit2, Outage outage) {
int cnt = 0;
if (method != KMethod.filter)
throw new UnsupportedOperationException();
// keywords?
if (track != null) {
for (String keyword : track) {
List<Status> msgs = jtwit.search(keyword);
for (Status status : msgs) {
if (tweets.contains(status)) {
continue;
}
tweets.add(status);
cnt++;
}
}
}
// users?
if (follow != null) {
for (Long user : follow) {
List<Status> msgs = jtwit.getUserTimeline(user);
for (Status status : msgs) {
if (tweets.contains(status)) {
continue;
}
tweets.add(status);
cnt++;
}
}
}
// regions?
if (locns != null && ! locns.isEmpty())
throw new UnsupportedOperationException("TODO"); // TODO
return cnt;
}
/**
* @return Can be null
*/
public List<String> getTrackKeywords() {
return track;
}
/**
* @param userIds Upto 5,000 userids to follow
* @throws IllegalArgumentException if userIds is too big
*/
public void setFollowUsers(List<Long> userIds) throws IllegalArgumentException {
method = KMethod.filter;
if (userIds!=null && userIds.size() > MAX_USERS) {
throw new IllegalArgumentException("Track upto 5000 users - not "+userIds.size());
}
follow = userIds;
}
/**
* @return user-ids which are followed, or null.
*/
public List<Long> getFollowUsers() {
return follow;
}
/**
* TODO This is not implemented yet!
* 25 0.1-360 degree location boxes.
*
* Only tweets that are both created using the Geotagging API and are placed
* from within a tracked bounding box will be included in the stream – the
* user’s location field is not used to filter tweets
*
* @param boundingBoxes
* Each element consists of longitude/latitude south-west,
* north-east.
*/
@Deprecated // TODO
public void setLocation(List<double[]> boundingBoxes) {
method = KMethod.filter;
this.locns = boundingBoxes;
throw new RuntimeException("TODO! Not implemented yet (sorry)");
}
/**
* Set the method. The default is "sample", as this is the only one which
* works with no extra settings.
*
* @param method
*/
void setMethod(KMethod method) {
this.method = method;
}
/**
* See https://dev.twitter.com/docs/streaming-api/methods#track
* <p>
* Terms are exact-matched, and also exact-matched ignoring punctuation.
* Each term may be up to 60 characters long.
* <p>
* Exact matching on phrases, that is, keywords with spaces,
* is not supported. Keywords containing punctuation will only exact match
* tokens and, other than keywords prefixed by # and @, will tend to
* never match. Non-space separated languages, such as CJK and
* Arabic, are currently unsupported as tokenization only occurs on
* whitespace and punctuation. Other UTF-8 phrases should exact match
* correctly, but will not substitute similar characters to their
* least-common-denominator. For all these cases, consider falling back
* to the Search REST API.
*
* @param keywords
* The default access level allows up to 400 track keywords
* (exceeding this will give an exception -- adjust {@link #MAX_KEYWORDS} if you
* have special privileges).
* You can include phrases, separating words with a space.
* @see TwitterStream#MAX_KEYWORDS
* @see TwitterStream#MAX_KEYWORD_LENGTH
*/
public void setTrackKeywords(List<String> keywords) {
if (keywords.size() > MAX_KEYWORDS) {
throw new IllegalArgumentException("Too many tracked terms: "+keywords.size()+" ("+MAX_KEYWORDS+" limit)");
}
// check them for length
for (String kw : keywords) {
if (kw.length() > MAX_KEYWORD_LENGTH) {
throw new IllegalArgumentException("Track term too long: "+kw+" (60 char limit)");
}
}
// we don't check >400 'cos you might have special access
this.track = keywords;
method = KMethod.filter;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("TwitterStream");
sb.append("[" + method);
if (track != null) {
sb.append(" track:" + InternalUtils.join(track, 0, 5));
}
if (follow != null && follow.size() > 0) {
sb.append(" follow:" + InternalUtils.join(follow, 0, 5));
}
if (locns != null) {
sb.append(" in:" + InternalUtils.join(locns, 0, 5));
}
sb.append(" by:" + jtwit.getScreenNameIfKnown());
sb.append("]");
return sb.toString();
}
/**
* default: false
* If true, json is only sent to listeners, and polling based access
* via {@link #getTweets()} will return no results.
* @see #addListener(IListen)
*/
public void setListenersOnly(boolean listenersOnly) {
this.listenersOnly = listenersOnly;
}
}
| 28.38255
| 110
| 0.666115
|
4202cea9fa252160962e34aa834db1049a7eae86
| 360
|
package br.com.podrao.auth.infra.mappers;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import br.com.podrao.auth.core.models.UsuarioDto;
import br.com.podrao.auth.infra.entities.UsuarioEntity;
@Mapper
public interface InfraUsuarioMapper {
@Mapping(target = "email", source = "source.username")
UsuarioDto converter(UsuarioEntity source);
}
| 24
| 55
| 0.794444
|
8fac2372cada6f6f2675a47d819f5ccb7e2864d6
| 1,005
|
package com.github.combinedmq.rabbitmq;
import com.github.combinedmq.configuration.Configuration;
import lombok.Data;
/**
* @author xiaoyu
*/
@Data
public class RabbitMqConfiguration implements Configuration {
private String host;
private Integer port;
private String username;
private String password;
private String virtualHost;
private ProducerPool producerPool;
private ConsumerListener consumerListener;
@Data
public static class ProducerPool {
private Integer maxTotal;
private Integer maxIdle;
private Integer minIdle;
private Integer maxWaitMillis;
private Integer minEvictableIdleTimeMillis;
private Integer timeBetweenEvictionRunsMillis;
private Boolean testOnBorrow;
private Boolean testOnReturn;
private Boolean testWhileIdle;
}
@Data
public static class ConsumerListener {
private Integer concurrency = 1;
private Integer prefetchCount = 1;
}
}
| 25.769231
| 61
| 0.716418
|
22d628ec10e9fd1d08c4b2c6cfa3d15c0e2d9431
| 1,611
|
/**
* Copyright 2016 ZTE Corporation.
*
* 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.openo.holmes.common.utils;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.openo.holmes.common.utils.bean.TestBean;
public class JacksonUtilTest {
@Test
public void testBeanToJson() throws Exception {
TestBean o = new TestBean();
o.setId("id");
String result = JacksonUtil.beanToJson(o);
assertThat("{\"id\":\"id\"}", equalTo(result));
}
@Test
public void jsonToBean_json_null() throws Exception {
String jsonNull = null;
TestBean testBean = JacksonUtil.jsonToBean(jsonNull, TestBean.class);
assertThat(testBean.getId(), equalTo(null));
}
@Test
public void jsonToBean_json_normal() throws Exception {
String json = "{\"id\":\"id\"}";
TestBean testBean = JacksonUtil.jsonToBean(json, TestBean.class);
assertThat(testBean.getId(), equalTo("id"));
}
}
| 32.877551
| 78
| 0.671012
|
dcd870539c74dcaa6f95193bb739ef6a534a8373
| 6,324
|
/*
* Copyright 2019-2020 The Polypheny Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file incorporates code covered by the following terms:
*
* 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.polypheny.db.rel.rules;
import org.polypheny.db.plan.RelOptRuleCall;
import org.polypheny.db.plan.RelOptRuleOperand;
import org.polypheny.db.plan.RelOptUtil;
import org.polypheny.db.rel.RelNode;
import org.polypheny.db.rel.core.RelFactories;
import org.polypheny.db.rel.logical.LogicalJoin;
import org.polypheny.db.rel.logical.LogicalProject;
import org.polypheny.db.tools.RelBuilderFactory;
/**
* MultiJoinProjectTransposeRule implements the rule for pulling
* {@link org.polypheny.db.rel.logical.LogicalProject}s that are on top of a
* {@link MultiJoin} and beneath a
* {@link org.polypheny.db.rel.logical.LogicalJoin} so the
* {@link org.polypheny.db.rel.logical.LogicalProject} appears above the
* {@link org.polypheny.db.rel.logical.LogicalJoin}.
*
* In the process of doing so, also save away information about the respective fields that are referenced in the expressions in the {@link org.polypheny.db.rel.logical.LogicalProject} we're pulling up, as
* well as the join condition, in the resultant {@link MultiJoin}s
*
* For example, if we have the following sub-query:
*
* <blockquote><pre>(select X.x1, Y.y1 from X, Y where X.x2 = Y.y2 and X.x3 = 1 and Y.y3 = 2)</pre></blockquote>
*
* The {@link MultiJoin} associated with (X, Y) associates x1 with X and y1 with Y. Although x3 and y3 need to be read due to the filters, they are not required after the row scan has completed and therefore are not saved.
* The join fields, x2 and y2, are also tracked separately.
*
* Note that by only pulling up projects that are on top of {@link MultiJoin}s, we preserve projections on top of row scans.
*
* See the superclass for details on restrictions regarding which {@link org.polypheny.db.rel.logical.LogicalProject}s cannot be pulled.
*/
public class MultiJoinProjectTransposeRule extends JoinProjectTransposeRule {
public static final MultiJoinProjectTransposeRule MULTI_BOTH_PROJECT =
new MultiJoinProjectTransposeRule(
operand(
LogicalJoin.class,
operand( LogicalProject.class, operand( MultiJoin.class, any() ) ),
operand( LogicalProject.class, operand( MultiJoin.class, any() ) ) ),
RelFactories.LOGICAL_BUILDER,
"MultiJoinProjectTransposeRule: with two LogicalProject children" );
public static final MultiJoinProjectTransposeRule MULTI_LEFT_PROJECT =
new MultiJoinProjectTransposeRule(
operand(
LogicalJoin.class,
some( operand( LogicalProject.class, operand( MultiJoin.class, any() ) ) ) ),
RelFactories.LOGICAL_BUILDER,
"MultiJoinProjectTransposeRule: with LogicalProject on left" );
public static final MultiJoinProjectTransposeRule MULTI_RIGHT_PROJECT =
new MultiJoinProjectTransposeRule(
operand(
LogicalJoin.class,
operand( RelNode.class, any() ),
operand( LogicalProject.class, operand( MultiJoin.class, any() ) ) ),
RelFactories.LOGICAL_BUILDER,
"MultiJoinProjectTransposeRule: with LogicalProject on right" );
/**
* Creates a MultiJoinProjectTransposeRule.
*/
public MultiJoinProjectTransposeRule( RelOptRuleOperand operand, RelBuilderFactory relBuilderFactory, String description ) {
super( operand, description, false, relBuilderFactory );
}
// override JoinProjectTransposeRule
@Override
protected boolean hasLeftChild( RelOptRuleCall call ) {
return call.rels.length != 4;
}
// override JoinProjectTransposeRule
@Override
protected boolean hasRightChild( RelOptRuleCall call ) {
return call.rels.length > 3;
}
// override JoinProjectTransposeRule
@Override
protected LogicalProject getRightChild( RelOptRuleCall call ) {
if ( call.rels.length == 4 ) {
return call.rel( 2 );
} else {
return call.rel( 3 );
}
}
// override JoinProjectTransposeRule
protected RelNode getProjectChild( RelOptRuleCall call, LogicalProject project, boolean leftChild ) {
// Locate the appropriate MultiJoin based on which rule was fired and which projection we're dealing with
MultiJoin multiJoin;
if ( leftChild ) {
multiJoin = call.rel( 2 );
} else if ( call.rels.length == 4 ) {
multiJoin = call.rel( 3 );
} else {
multiJoin = call.rel( 4 );
}
// Create a new MultiJoin that reflects the columns in the projection above the MultiJoin
return RelOptUtil.projectMultiJoin( multiJoin, project );
}
}
| 42.72973
| 222
| 0.687065
|
999c257d1f71a64af37ca4b4445f264c470ce36d
| 2,027
|
package uk.gov.dft.bluebadge.webapp.citizen.service;
import java.util.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import uk.gov.dft.bluebadge.webapp.citizen.client.messageservice.MessageApiClient;
import uk.gov.dft.bluebadge.webapp.citizen.client.messageservice.model.ApplicationSavedMessageRequest;
import uk.gov.dft.bluebadge.webapp.citizen.client.messageservice.model.SaveAndReturnCodeMessageRequest;
import uk.gov.dft.bluebadge.webapp.citizen.config.RedisSessionConfig;
@Slf4j
@Service
public class MessageService {
private MessageApiClient api;
private RedisSessionConfig redisSessionConfig;
@Autowired
MessageService(MessageApiClient api, RedisSessionConfig redisSessionConfig) {
this.api = api;
this.redisSessionConfig = redisSessionConfig;
}
public void sendReturnToApplicationCodeEmail(
String emailAddress, String code, String expiryTime) {
Assert.notNull(emailAddress, "Email address required for send email.");
Assert.notNull(code, "Code required for send email.");
Assert.notNull(expiryTime, "Expiry time required for send message.");
log.info("Sending save and return code via email.");
UUID result =
api.sendSaveAndReturnCodeMessage(
new SaveAndReturnCodeMessageRequest(emailAddress, code, expiryTime));
log.info("Message service result {}", result);
}
public void sendApplicationSavedEmail(String emailAddress, String expiryTime) {
Assert.notNull(emailAddress, "Email address required for send email.");
Assert.notNull(expiryTime, "Expiry time required for send message.");
log.info("Sending save and return code via email.");
UUID result =
api.sendApplicationSavedEmail(
new ApplicationSavedMessageRequest(
emailAddress, expiryTime, redisSessionConfig.getSaveReturnLink()));
log.info("Message service result {}", result);
}
}
| 41.367347
| 103
| 0.770597
|
9a38fcf8f0ca061d837535579633aec7a8ca7a35
| 2,355
|
package com.sj.spending.transaction.controller;
import com.sj.spending.logic.data.ImportedTransaction;
import com.sj.spending.transaction.data.entity.ImportedTransactionEntity;
import com.sj.spending.transaction.data.repo.ImportedTransactionRepository;
import com.sj.spending.transaction.data.dto.ImportedTransactionDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/api/v1/importedTransactions")
public class ImportedTransactionV1Controller {
private final ImportedTransactionRepository importedTransactionRepository;
@Autowired
public ImportedTransactionV1Controller(ImportedTransactionRepository importedTransactionRepository) {
this.importedTransactionRepository = importedTransactionRepository;
}
@RequestMapping(value = "/{importedTransactionId}", method = RequestMethod.GET)
public ImportedTransactionDto findImportedTransaction(@PathVariable(value = "importedTransactionId") long importedTransactionId) {
return importedTransactionRepository.findById(importedTransactionId)
.map(t -> ImportedTransactionDto.from(t))
.orElse(null);
}
@RequestMapping(method = RequestMethod.GET)
public List<ImportedTransactionDto> findImportedTransactions() {
return importedTransactionRepository.findAll().stream()
.map(t -> ImportedTransactionDto.from(t))
.collect(Collectors.toList());
}
@RequestMapping(value = "/{transactionId}", method = RequestMethod.PUT)
public ImportedTransactionDto updateImportedTransaction(@RequestBody ImportedTransactionDto transaction) {
ImportedTransactionEntity entity = importedTransactionRepository.findById(transaction.getImportedTransactionId()).get();
ImportedTransaction.copy(transaction, entity);
ImportedTransactionEntity saved = importedTransactionRepository.save(entity);
return ImportedTransactionDto.from(saved);
}
}
| 44.433962
| 134
| 0.789809
|
b24c8f033b70998b3eb69495fb4e04093342c738
| 81
|
package net.moonlightflower.wc3libs.dataTypes.app;
public class TileIdList {
}
| 13.5
| 50
| 0.802469
|
67ca985e78310bd353be8770b3ed718f1792b0b7
| 2,710
|
package ch.unisg.roster.roster;
import ch.unisg.roster.roster.application.port.in.AddRosterItemPort;
import ch.unisg.roster.roster.domain.Roster;
import ch.unisg.roster.roster.domain.Task;
import ch.unisg.roster.roster.domain.valueobject.ExecutorType;
import org.json.JSONObject;
import org.json.JSONException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.*;
import static org.assertj.core.api.BDDAssertions.*;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class AddNewAssignmentToRosterServiceSystemTest {
@Autowired
private TestRestTemplate restTemplate;
@Autowired
private AddRosterItemPort addRosterItemPort;
@Test
void addNewAssignmentToRosterService() throws JSONException {
String taskId = "TEST-ID";
String executorType = "TEST-TYPE";
String inputData = "TEST-DATA";
String executorURI = "TEST-URI";
ResponseEntity response = whenAddNewAssignmentToRoster(taskId, executorType, inputData, executorURI);
JSONObject responseJson = new JSONObject(response.getBody().toString());
String respTaskId = responseJson.getString("taskID");
String respTaskType = responseJson.getJSONObject("taskType").getString("value");
String respInputData = responseJson.getString("inputData");
then(response.getStatusCode()).isEqualTo(HttpStatus.OK);
then(respTaskId).isEqualTo(respTaskId);
then(respTaskType).isEqualTo(executorType);
then(respInputData).isEqualTo(inputData);
then(Roster.getInstance().getRosterMap().size()).isEqualTo(1);
}
private ResponseEntity whenAddNewAssignmentToRoster(
String taskId,
String executorType,
String inputData,
String executorURI) throws JSONException {
Roster roster = Roster.getInstance();
roster.getRosterMap().clear();
roster.addTaskToQueue(new Task(taskId, new ExecutorType(executorType), inputData));
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
String jsonPayLoad = new JSONObject()
.put("executorType", executorType)
.put("executorURI", executorURI)
.toString();
HttpEntity<String> request = new HttpEntity<>(jsonPayLoad, headers);
return restTemplate.exchange(
"/task/apply/",
HttpMethod.POST,
request,
Object.class
);
}
}
| 33.04878
| 109
| 0.70738
|
2835fe89774946d6182faa31809d9ad9a61f9f0e
| 93
|
package biz.iteksolutions.escpos.parser;
public class EscposCommand extends Command {
}
| 18.6
| 45
| 0.784946
|
0a88ef1804d29266ce198d043aaa0a40dacdf97c
| 7,193
|
/* Copyright IBM Corp. 2018
*
* 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.ibm.ta.modresorts;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Arrays;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ibm.ta.modresorts.exception.ExceptionHandler;
public class WeatherServlet extends HttpServlet {
// local OS environment variable key name. The key value should provide an API key that will be used to
// get weather information from site: http://www.wunderground.com
private static final String WEATHER_API_KEY = "WEATHER_API_KEY";
static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(WeatherServlet.class.getName());
/**
* constructor
*/
public WeatherServlet() {
super();
}
/**
* Returns the weather information for a given city
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
String methodName = "doGet";
logger.entering(WeatherServlet.class.getName(), methodName);
String city = request.getParameter("selectedCity");
logger.log(Level.FINE, "requested city is " + city);
String weatherAPIKey = System.getenv(WEATHER_API_KEY);
String mockedKey = mockKey(weatherAPIKey);
logger.log(Level.FINE, "weatherAPIKey is " + mockedKey);
if (weatherAPIKey != null && weatherAPIKey.trim().length() > 0) {
logger.info("weatherAPIKey is found, system will provide the real time weather data for the city " + city);
getRealTimeWeatherData(city, weatherAPIKey, response);
}else {
logger.info("weatherAPIKey is not found, will provide the weather data dated August 10th, 2018 for the city " + city);
getDefaultWeatherData(city, response);
}
}
private void getRealTimeWeatherData(String city, String apiKey, HttpServletResponse response)
throws ServletException, IOException {
String resturl = null;
String resturlbase = Constants.WUNDERGROUND_API_PREFIX + apiKey + Constants.WUNDERGROUND_API_PART;
if (Constants.PARIS.equals(city)) {
resturl = resturlbase + "France/Paris.json";
} else if (Constants.LAS_VEGAS.equals(city)) {
resturl = resturlbase + "NV/Las_Vegas.json";
} else if (Constants.SAN_FRANCISCO.equals(city)) {
resturl = resturlbase + "/CA/San_Francisco.json";
} else if (Constants.MIAMI.equals(city)) {
resturl = resturlbase + "FL/Miami.json";
} else if (Constants.CORK.equals(city)) {
resturl = resturlbase + "ireland/cork.json";
} else if (Constants.BARCELONA.equals(city)) {
resturl = resturlbase + "Spain/Barcelona.json";
}else {
String errorMsg = "Sorry, the weather information for your selected city: " + city +
" is not available. Valid selections are: " + Arrays.toString(Constants.SUPPORTED_CITIES);
ExceptionHandler.handleException(null, errorMsg, logger);
}
URL obj;
HttpURLConnection con = null;
try {
obj = new URL(Objects.requireNonNull(resturl));
con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("GET");
} catch (MalformedURLException e1) {
String errorMsg = "Caught MalformedURLException. Please make sure the url is correct.";
ExceptionHandler.handleException(e1, errorMsg, logger);
}catch (ProtocolException e2) {
String errorMsg = "Caught ProtocolException: " + e2.getMessage() + ". Not able to set request method to http connection.";
ExceptionHandler.handleException(e2, errorMsg, logger);
} catch (IOException e3) {
String errorMsg = "Caught IOException: " + e3.getMessage() + ". Not able to open connection.";
ExceptionHandler.handleException(e3, errorMsg, logger);
}
int responseCode = Objects.requireNonNull(con).getResponseCode();
logger.log(Level.FINEST, "Response Code: " + responseCode);
if (responseCode >= 200 && responseCode < 300) {
BufferedReader in = null;
ServletOutputStream out = null;
try {
in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder responseStr = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
responseStr.append(inputLine);
}
response.setContentType("application/json");
out = response.getOutputStream();
out.print(responseStr.toString());
logger.log(Level.FINE, "responseStr: " + responseStr);
} catch (Exception e) {
String errorMsg = "Problem occured when processing the weather server response.";
ExceptionHandler.handleException(e, errorMsg, logger);
} finally {
if (in != null) {
in.close();
}
if (out!= null) {
out.close();
}
}
} else {
String errorMsg = "REST API call " + resturl + " returns an error response: " + responseCode;
ExceptionHandler.handleException(null, errorMsg, logger);
}
}
private void getDefaultWeatherData(String city, HttpServletResponse response)
throws ServletException, IOException {
DefaultWeatherData defaultWeatherData = null;
try {
defaultWeatherData = new DefaultWeatherData(city);
}catch (UnsupportedOperationException e) {
ExceptionHandler.handleException(e, e.getMessage(), logger);
}
ServletOutputStream out = null;
try {
String responseStr = Objects.requireNonNull(defaultWeatherData).getDefaultWeatherData();
response.setContentType("application/json");
out = response.getOutputStream();
out.print(responseStr);
logger.log(Level.FINEST, "responseStr: " + responseStr);
} catch (Exception e) {
String errorMsg = "Problem occured when getting the default weather data.";
ExceptionHandler.handleException(e, errorMsg, logger);
} finally {
if (out!= null) {
out.close();
}
}
}
/**
* Returns the weather information for a given city
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
private static String mockKey(String toBeMocked) {
if (toBeMocked == null) {
return null;
}
String lastToKeep = toBeMocked.substring(toBeMocked.length()-3);
return "*********" + lastToKeep;
}
}
| 34.581731
| 125
| 0.713471
|
81f97248fd66c3998251537f605ed7be35efcccc
| 3,306
|
package me.ehp246.aufjms.util;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;
import java.util.function.Consumer;
import org.assertj.core.util.Arrays;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.mrbean.MrBeanModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import me.ehp246.aufjms.api.jms.Invocation;
/**
* @author Lei Yang
*
*/
public class TestUtil {
@SuppressWarnings("unchecked")
public static <T> T newProxy(final Class<T> t, final Consumer<Invocation> consumer) {
return (T) (Proxy.newProxyInstance(TestUtil.class.getClassLoader(), new Class[] { t },
(proxy, method, args) -> {
consumer.accept(new Invocation() {
@Override
public Object target() {
return proxy;
}
@Override
public Method method() {
return method;
}
@Override
public List<?> args() {
return args == null ? List.of() : Arrays.asList(args);
}
});
return null;
}));
}
@SuppressWarnings("unchecked")
public static <T> InvocationCaptor<T> newCaptor(final Class<T> t) {
final var captured = new Invocation[1];
final var proxy = (T) (Proxy.newProxyInstance(TestUtil.class.getClassLoader(), new Class[] { t },
(target, method, args) -> {
captured[0] = new Invocation() {
@Override
public Object target() {
return target;
}
@Override
public Method method() {
return method;
}
@Override
public List<?> args() {
return args == null ? List.of() : Arrays.asList(args);
}
};
return null;
}));
return new InvocationCaptor<T>() {
@Override
public T proxy() {
return proxy;
}
@Override
public Invocation invocation() {
return captured[0];
}
};
}
public interface InvocationCaptor<T> {
T proxy();
Invocation invocation();
}
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper().setSerializationInclusion(Include.NON_NULL)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).registerModule(new JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).registerModule(new MrBeanModule())
.registerModule(new ParameterNamesModule());
}
| 32.732673
| 115
| 0.533273
|
3507de2be11f87d06d8c4d65f658730d6507be1e
| 198
|
package io.github.service.impl;
import org.springframework.stereotype.Service;
import io.github.service.UserTestService;
@Service
public class UserTestServiceImpl implements UserTestService {
}
| 18
| 61
| 0.833333
|
4c70f6d283636f2200f9b3f9ba20514b41493cb6
| 7,038
|
/*
* Copyright 2008-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.hasor.utils.ref;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.AbstractList;
import java.util.Arrays;
import java.util.Collection;
/**
* 弱引用列表,WeakArrayList是修改自org.arakhne.util.ref下的WeakArrayList
* @version : 2013-11-8
* @author (网络收集)
*/
public class WeakArrayList<T> extends AbstractList<T> {
private static final Object NULL_VALUE = new Object();
private final transient ReferenceQueue<T> queue;
private Object[] data;
private int size;
private boolean enquedElement;
private static <T> T maskNull(final T value) {
return (T) (value == null ? WeakArrayList.NULL_VALUE : value);
}
private static <T> T unmaskNull(final T value) {
return value == WeakArrayList.NULL_VALUE ? null : value;
}
public WeakArrayList(final int initialCapacity) {
this.queue = new ReferenceQueue<T>();
this.enquedElement = false;
if (initialCapacity < 0) {
throw new IllegalArgumentException("Illegal Capacity: " + initialCapacity);
}
this.data = new Object[initialCapacity];
this.size = 0;
}
public WeakArrayList() {
this(10);
}
public WeakArrayList(final Collection<? extends T> c) {
this.queue = new ReferenceQueue<T>();
this.enquedElement = false;
this.data = new Object[c.size()];
this.size = this.data.length;
int i = 0;
for (T t : c) {
this.data[i] = this.createRef(t);
++i;
}
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < this.size; ++i) {
Object obj;
Reference<?> ref = (Reference<?>) this.data[i];
if (this.data[i] == null) {
obj = null;
} else {
obj = ref.get();
}
buffer.append('{');
buffer.append(obj == null ? null : obj.toString());
buffer.append('}');
}
return buffer.toString();
}
private Reference<T> createRef(final T obj) {
return new WeakReference<T>(WeakArrayList.maskNull(obj), this.queue);
}
public void ensureCapacity(final int minCapacity) {
this.modCount += 1;
int oldCapacity = this.data.length;
if (minCapacity > oldCapacity) {
Object[] oldData = this.data;
int newCapacity = oldCapacity * 3 / 2 + 1;
if (newCapacity < minCapacity) {
newCapacity = minCapacity;
}
this.data = Arrays.copyOf(oldData, newCapacity);
}
}
public void trimToSize() {
this.modCount += 1;
int oldCapacity = this.data.length;
if (this.size < oldCapacity) {
this.data = Arrays.copyOf(this.data, this.size);
}
}
@SuppressWarnings("unchecked")
public int expurge() {
int j;
while (this.queue.poll() != null) {
this.enquedElement = true;
}
if (this.enquedElement) {
j = 0;
for (int i = 0; i < this.size; ++i) {
Reference<T> ref = (Reference<T>) this.data[i];
if (ref == null || ref.isEnqueued() || ref.get() == null) {
if (ref != null) {
ref.clear();
}
this.data[i] = null;
} else {
if (i != j) {
this.data[j] = this.data[i];
this.data[i] = null;
}
++j;
}
}
this.enquedElement = false;
} else {
j = this.size;
}
while (this.queue.poll() != null) {
this.enquedElement = true;
}
this.size = j;
return this.size;
}
protected void assertRange(final int index, final boolean allowLast) {
int csize = this.expurge();
if (index < 0) {
throw new IndexOutOfBoundsException("invalid negative value: " + Integer.toString(index));
}
if (allowLast && index > csize) {
throw new IndexOutOfBoundsException("index>" + csize + ": " + Integer.toString(index));
}
if (!allowLast && index >= csize) {
throw new IndexOutOfBoundsException("index>=" + csize + ": " + Integer.toString(index));
}
}
@Override
public int size() {
return this.expurge();
}
@Override
@SuppressWarnings("unchecked")
public T get(final int index) {
Object value;
do {
this.assertRange(index, false);
value = ((Reference<T>) this.data[index]).get();
} while (value == null);
return (T) WeakArrayList.unmaskNull(value);
}
@Override
@SuppressWarnings("unchecked")
public T set(final int index, final T element) {
Object oldValue;
Reference<T> ref;
do {
this.assertRange(index, false);
ref = (Reference<T>) this.data[index];
oldValue = ref.get();
} while (oldValue == null);
ref.clear();
this.data[index] = this.createRef(element);
this.modCount += 1;
return (T) WeakArrayList.unmaskNull(oldValue);
}
@Override
public void add(final int index, final T element) {
this.assertRange(index, true);
this.ensureCapacity(this.size + 1);
System.arraycopy(this.data, index, this.data, index + 1, this.size - index);
this.data[index] = this.createRef(element);
this.size += 1;
this.modCount += 1;
}
@Override
@SuppressWarnings("unchecked")
public T remove(final int index) {
Object oldValue;
Reference<T> ref;
do {
this.assertRange(index, false);
ref = (Reference<T>) this.data[index];
oldValue = ref.get();
} while (oldValue == null);
ref.clear();
System.arraycopy(this.data, index + 1, this.data, index, this.size - index - 1);
this.data[this.size - 1] = null;
this.size -= 1;
this.modCount += 1;
return (T) WeakArrayList.unmaskNull(oldValue);
}
}
| 34.841584
| 102
| 0.54632
|
0ced20bc2546a168a7d63bcdb228d2113c0b3cf8
| 3,914
|
package com.experts.core.biller.statemachine.api.rovo.awsxray.domain;
import com.experts.core.biller.statemachine.api.rovo.awsxray.domain.entities.mongo.BaseEntity;
import com.experts.core.biller.statemachine.api.rovo.awsxray.domain.entities.mongo.SaltHash;
import com.experts.core.biller.statemachine.api.rovo.awsxray.exceptions.PersistenceRuntimeException;
import com.experts.core.biller.statemachine.api.rovo.awsxray.utils.MongodbPersistenceUtil;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.annotation.Resource;
import static com.experts.core.biller.statemachine.api.rovo.awsxray.config.MongoSpringConfig.BCRYPT_ENCODER;
public class BaseMongoService<E extends BaseEntity> {
@Resource
protected Datastore mongoDataStore;
@Resource(name = BCRYPT_ENCODER)
protected PasswordEncoder passwordEncoder;
protected final Class<E> clazz;
protected BaseMongoService(Class<E> clazz) {
this.clazz = clazz;
}
public ObjectId persist(E entity) throws PersistenceRuntimeException {
if (entity instanceof SaltHash) {
SaltHash credentialEntity = (SaltHash)entity;
credentialEntity.setPasswordHash(passwordEncoder.encode(credentialEntity.getPassword()));
credentialEntity.setPassword(null);
}
mongoDataStore.save(entity);
return entity.getId();
}
public E get(String uuid) {
return get(uuid, false);
}
public E get(String uuid, boolean includeDisabled) {
return get(uuid, includeDisabled, true);
}
public E get(String uuid, boolean includeDisabled, boolean includeFields, String ... fields) {
if ((uuid == null) || uuid.isEmpty()) {
return null;
}
Query<E> query = mongoDataStore.find(clazz).field("uuid")
.equal(MongodbPersistenceUtil.sanitize(uuid));
if (!includeDisabled) {
query.field("disabled").notEqual(true);
}
if((fields != null) && (fields.length > 0 )){
for (String field : fields) {
query.project(field, includeFields);
}
}
return query.get();
}
public ObjectId getId(final String uuid) {
return getId(uuid, false);
}
public ObjectId getId(final String uuid, final boolean includeDisabled) {
if ((uuid == null) || uuid.isEmpty()) {
return null;
}
Query<E> query = mongoDataStore.find(clazz).field("uuid")
.equal(MongodbPersistenceUtil.sanitize(uuid));
if (!includeDisabled) {
query.field("disabled").notEqual(true);
}
query.project("_id", true);
E entity = query.get();
if (entity == null) {
return null;
} else {
return entity.getId();
}
}
public E get(final ObjectId id) {
return get(id, false, true);
}
public E get(final ObjectId id, final boolean includeDisabled) {
return get(id, includeDisabled, true);
}
public E get(final ObjectId id, final boolean includeDisabled, final boolean includeFields, final String... fields) {
if ((id == null)) {
return null;
}
Query<E> query = mongoDataStore.find(clazz).field("id").equal(id);
if (!includeDisabled) {
query.field("disabled").notEqual(true);
}
if((fields != null) && (fields.length > 0 )){
for (String field : fields) {
query.project(field, includeFields);
}
}
return query.get();
}
public E getLatest() {
Query<E> query = mongoDataStore.find(clazz).field("disabled").notEqual(true).order("-lastChange");
return query.get();
}
}
| 30.578125
| 121
| 0.633112
|
06cae3928c4652f40cba989be2481d9d439460ed
| 10,159
|
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.util.math.base;
import java.math.BigDecimal;
import java.math.BigInteger;
import net.sf.mmm.util.math.api.NumberConversionException;
import net.sf.mmm.util.math.api.NumberType;
/**
* This is the implementation of the {@link NumberType} interface.
*
* @see net.sf.mmm.util.math.base.MathUtilImpl#getNumberType(Class)
* @param <NUMBER> is the generic type of the {@link #getNumberClass() represented number-class}.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.1
*/
public abstract class NumberTypeImpl<NUMBER extends Number> implements NumberType<NUMBER> {
/** The maximum delta allowed for {@link #valueOf(Number, boolean)}. */
private static final double REQUIRED_PRECISION = 0.0000001;
/** The {@link NumberTypeImpl} for {@link Byte}. */
public static final NumberTypeImpl<Byte> BYTE = new NumberTypeImpl<Byte>(1, Byte.valueOf(Byte.MIN_VALUE),
Byte.valueOf(Byte.MAX_VALUE)) {
@Override
public Class<Byte> getNumberClass() {
return Byte.class;
}
@Override
public boolean isDecimal() {
return false;
}
@Override
protected Byte convert(Number number) {
return Byte.valueOf(number.byteValue());
}
@Override
protected Byte parse(String number) throws NumberFormatException {
return Byte.valueOf(number);
}
};
/** The {@link NumberTypeImpl} for {@link Short}. */
public static final NumberTypeImpl<Short> SHORT = new NumberTypeImpl<Short>(2, Short.valueOf(Short.MIN_VALUE),
Short.valueOf(Short.MAX_VALUE)) {
@Override
public Class<Short> getNumberClass() {
return Short.class;
}
@Override
public boolean isDecimal() {
return false;
}
@Override
protected Short convert(Number number) {
return Short.valueOf(number.shortValue());
}
@Override
protected Short parse(String number) throws NumberFormatException {
return Short.valueOf(number);
}
};
/** The {@link NumberTypeImpl} for {@link Integer}. */
public static final NumberTypeImpl<Integer> INTEGER = new NumberTypeImpl<Integer>(3,
Integer.valueOf(Integer.MIN_VALUE), Integer.valueOf(Integer.MAX_VALUE)) {
@Override
public Class<Integer> getNumberClass() {
return Integer.class;
}
@Override
public boolean isDecimal() {
return false;
}
@Override
protected Integer convert(Number number) {
return Integer.valueOf(number.intValue());
}
@Override
protected Integer parse(String number) throws NumberFormatException {
return Integer.valueOf(number);
}
};
/** The {@link NumberTypeImpl} for {@link Long}. */
public static final NumberTypeImpl<Long> LONG = new NumberTypeImpl<Long>(4, Long.valueOf(Long.MIN_VALUE),
Long.valueOf(Long.MAX_VALUE)) {
@Override
public Class<Long> getNumberClass() {
return Long.class;
}
@Override
public boolean isDecimal() {
return false;
}
@Override
protected Long convert(Number number) {
return Long.valueOf(number.longValue());
}
@Override
protected Long parse(String number) throws NumberFormatException {
return Long.valueOf(number);
}
};
/** The {@link NumberTypeImpl} for {@link Float}. */
public static final NumberTypeImpl<Float> FLOAT = new NumberTypeImpl<Float>(5, Float.valueOf(Float.MIN_VALUE),
Float.valueOf(Float.MAX_VALUE)) {
@Override
public Class<Float> getNumberClass() {
return Float.class;
}
@Override
public boolean isDecimal() {
return true;
}
@Override
protected Float convert(Number number) {
return Float.valueOf(number.floatValue());
}
@Override
protected Float parse(String number) throws NumberFormatException {
return Float.valueOf(number);
}
};
/** The {@link NumberTypeImpl} for {@link Double}. */
public static final NumberTypeImpl<Double> DOUBLE = new NumberTypeImpl<Double>(6,
Double.valueOf(Double.MIN_VALUE), Double.valueOf(Double.MAX_VALUE)) {
@Override
public Class<Double> getNumberClass() {
return Double.class;
}
@Override
public boolean isDecimal() {
return true;
}
@Override
protected Double convert(Number number) {
return Double.valueOf(number.doubleValue());
}
@Override
protected Double parse(String number) throws NumberFormatException {
return Double.valueOf(number);
}
};
/** The {@link NumberTypeImpl} for {@link BigInteger}. */
public static final NumberTypeImpl<BigInteger> BIG_INTEGER = new NumberTypeImpl<BigInteger>(7, null, null) {
@Override
public Class<BigInteger> getNumberClass() {
return BigInteger.class;
}
@Override
public boolean isDecimal() {
return false;
}
@Override
protected BigInteger convert(Number number) {
return BigInteger.valueOf(number.longValue());
}
@Override
protected BigInteger parse(String number) throws NumberFormatException {
return new BigInteger(number);
}
};
/** The {@link NumberTypeImpl} for {@link BigDecimal}. */
public static final NumberTypeImpl<BigDecimal> BIG_DECIMAL = new NumberTypeImpl<BigDecimal>(8, null, null) {
@Override
public Class<BigDecimal> getNumberClass() {
return BigDecimal.class;
}
@Override
public boolean isDecimal() {
return true;
}
@Override
protected BigDecimal convert(Number number) {
return BigDecimal.valueOf(number.doubleValue());
}
@Override
protected BigDecimal parse(String number) throws NumberFormatException {
return new BigDecimal(number);
}
};
private final int exactness;
private final NUMBER minimumValue;
private final NUMBER maximumValue;
/**
* The constructor.
*
* @param exactness is the internal exactness level for {@link #getExactnessDifference(NumberType)}.
* @param min is the {@link #getMinimumValue() minimum value}.
* @param max is the {@link #getMaximumValue() maximum value}.
*/
NumberTypeImpl(int exactness, NUMBER min, NUMBER max) {
super();
this.exactness = exactness;
this.minimumValue = min;
this.maximumValue = max;
}
/**
* This method converts the given {@code number} to the {@link #getNumberClass() number-class} represented by this
* object. Like a cast this operation may loose precision (e.g. when converting a {@link Double} to {@link Integer})
* without warning. Use {@link #valueOf(Number, boolean)} instead to avoid this.
*
* @param number is the number to convert.
* @return the converted number.
*/
protected abstract NUMBER convert(Number number);
@Override
@SuppressWarnings("unchecked")
public NUMBER valueOf(Number number, boolean failIfUnprecise) throws NumberConversionException {
if (number == null) {
return null;
}
if (getNumberClass().equals(number.getClass())) {
// cast is not yet supported by GWT
return (NUMBER) number;
// return getNumberClass().cast(number);
}
NUMBER converted = convert(number);
if (failIfUnprecise) {
double delta = number.doubleValue() - converted.doubleValue();
if (delta == 0) {
// e.g. to detect precision loss for BigDecimal
delta = number.longValue() - converted.longValue();
}
if (delta < 0) {
delta = -delta;
}
if (delta > REQUIRED_PRECISION) {
throw new NumberConversionException(number, getNumberClass());
}
// TODO: BigInt / BigDecimal
}
return converted;
}
@Override
public NUMBER valueOf(String number) throws NumberConversionException {
try {
return parse(number);
} catch (NumberFormatException e) {
throw new NumberConversionException(e, number, getNumberClass());
}
}
/**
* This method gets an instance of the {@link #getNumberClass() represented number-class} with the numeric value
* identified by the given string {@code number}.
*
* @param number is the string to be parsed as number.
* @return the parsed number of the according type.
* @throws NumberConversionException if the given {@code number} has an illegal format.
* @throws NumberFormatException if the given {@code number} has an illegal format. This exception will be converted
* to a {@link NumberConversionException}.
*/
protected abstract NUMBER parse(String number) throws NumberConversionException, NumberFormatException;
/**
* This method gets the difference of the exactness of this {@link NumberTypeImpl} and the given {@code otherType}.
* <br>
* <b>ATTENTION:</b><br>
* Some types such as {@link Double} and {@link BigInteger} are NOT really comparable so the exactness difference
* might only make sense if the compared {@link NumberTypeImpl types} are both {@link #isDecimal() decimal} or both
* {@link #isDecimal() non-decimal} (mathematical integers). However the order of typical types is:<br>
* <ol>
* <li>{@link Byte}</li>
* <li>{@link Short}</li>
* <li>{@link Integer}</li>
* <li>{@link Long}</li>
* <li>{@link Float}</li>
* <li>{@link Double}</li>
* <li>{@link BigInteger}</li>
* <li>{@link BigDecimal}</li>
* </ol>
*
* @param otherType is the {@link NumberTypeImpl} to compare with.
* @return the difference of the exactness. Will be {@code 0} if this {@link NumberTypeImpl} is equal to
* {@code otherType}, positive if this {@link NumberTypeImpl} is more exact (later in the examples above) and
* negative if {@code otherType} is more exact.
*/
@Override
public int getExactnessDifference(NumberType<?> otherType) {
return this.exactness - ((NumberTypeImpl<?>) otherType).exactness;
}
@Override
public NUMBER getMinimumValue() {
return this.minimumValue;
}
@Override
public NUMBER getMaximumValue() {
return this.maximumValue;
}
}
| 26.18299
| 119
| 0.669849
|
6c8c690239cfd36b18c7a8046a2225fb24374136
| 2,067
|
package br.com.oole.config;
import java.text.ParseException;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import br.com.oole.DAO.JogadorDAO;
import br.com.oole.DAO.OlheiroDAO;
import br.com.oole.models.Jogador;
import br.com.oole.models.Olheiro;
@Configuration
@Profile("test")
public class TestConfig {
@Autowired
private BCryptPasswordEncoder bc;
@Autowired
private JogadorDAO jogadorDAO;
@Autowired
private OlheiroDAO olheiroDAO;
@Bean
public boolean instantiateDatabase() throws ParseException {
Jogador j1 = new Jogador(null,"José","20/11/2001","97106015040","Masculino","Centroavante","","jsoe",bc.encode("123456"),"jose@gmail.com","91985397070", "Brasileiro","66635110","Parque Verde","Belém","Pará","Rod.Augusto Montenegro 5955");
Jogador j2 = new Jogador(null,"Marcio","31/12/1999","97106015040","Masculino","Goleiro","Asma","Marcio","123456","Marcio@gmail.com","91985397070","Brasileiro","66635110","Parque Verde","Belém","Pará","Rod.Augusto Montenegro 5955");
Jogador j3 = new Jogador(null,"Luana","20/11/2001","97106015040","Feminino","Zagueira","","Luana","123456","Luana@gmail.com","91985397070", "Brasileiro","66635110","Parque Verde","Belém","Pará","Rod.Augusto Montenegro 5955");
jogadorDAO.saveAll(Arrays.asList(j1,j2,j3));
Olheiro o1 = new Olheiro(null,"Raimundo","18/05/1969","65434460057","Masculino","rai","456123","rai@gmail.com","32154878", "Brasileiro","66635110","Parque Verde","Belém","Pará","Rod.Augusto Montenegro 5955");
Olheiro o2 = new Olheiro(null,"Cassio","18/05/1969","65434460050","Masculino","csi",bc.encode("123456"),"caasio@gmail.com","32154878", "Brasileiro","76435510","Centro","São Paulo","São Paulo","Avenida Paulista");
olheiroDAO.save(o1);
olheiroDAO.save(o2);
return true;
}
}
| 41.34
| 240
| 0.742622
|
1c278ad13c180989ea0479adfbc226eede083267
| 359
|
package com.example.Weathers.services;
public class WeathersServicesException extends Exception {
public WeathersServicesException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public WeathersServicesException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
| 21.117647
| 68
| 0.779944
|
c019556ea007b67edcfbe1945d62351e9209bd77
| 651
|
package com.psc.vote.vote.domain;
public class Vote {
String userName;
String optionValueId;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getOptionValueId() {
return optionValueId;
}
public void setOptionValueId(String optionValueId) {
this.optionValueId = optionValueId;
}
@Override
public String toString() {
return "Vote{" +
"userName='" + userName + '\'' +
", optionValueId='" + optionValueId + '\'' +
'}';
}
}
| 20.34375
| 60
| 0.56682
|
9df08b91ad87975a51f88f1973982a045c0c0f5d
| 285
|
/**
* The accounting package handles all transfers of various assets including 1) cash, 2) properties 3) houses
* and 4) free bail cards. If we ever had to, we could set up auditting here to make sure no cash or properties
* were ever "lost".
*/
package org.monsim.api.accounting;
| 47.5
| 112
| 0.736842
|
a01b6e427f702f1eb7fc9fbe6e16e0fc75336580
| 2,304
|
/*
* Copyright (C) 2018 Seoul National University
*
* 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 edu.snu.mist.core.master.lb.allocation;
import edu.snu.mist.core.master.TaskAddressInfoMap;
import edu.snu.mist.core.master.TaskInfoRWLock;
import edu.snu.mist.core.master.TaskStatsMap;
import edu.snu.mist.formats.avro.IPAddress;
import javax.inject.Inject;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The group-unaware round-robin query allocation scheduler.
*/
public final class RoundRobinQueryAllocationManager implements QueryAllocationManager {
/**
* The AtomicInteger used for round-robin scheduling.
*/
private final AtomicInteger currentIndex;
/**
* The task stats map.
*/
private final TaskStatsMap taskStatsMap;
/**
* The task address info map.
*/
private final TaskAddressInfoMap taskAddressInfoMap;
/**
* The read/write lock for task info update.
*/
private final TaskInfoRWLock taskInfoRWLock;
@Inject
private RoundRobinQueryAllocationManager(
final TaskAddressInfoMap taskAddressInfoMap,
final TaskStatsMap taskStatsMap,
final TaskInfoRWLock taskInfoRWLock) {
super();
this.currentIndex = new AtomicInteger();
this.taskStatsMap = taskStatsMap;
this.taskAddressInfoMap = taskAddressInfoMap;
this.taskInfoRWLock = taskInfoRWLock;
}
@Override
public IPAddress getAllocatedTask(final String appId) {
taskInfoRWLock.readLock().lock();
final List<String> taskList = taskStatsMap.getTaskList();
final int myIndex = currentIndex.getAndIncrement() % taskList.size();
final IPAddress result = taskAddressInfoMap.getClientToTaskAddress(taskList.get(myIndex));
taskInfoRWLock.readLock().unlock();
return result;
}
}
| 31.135135
| 94
| 0.746528
|
e24dbb872253782ed7d41f0107bf758750ee554a
| 2,297
|
package com.example.TelikiEdvHCI;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import androidx.fragment.app.Fragment;
public class MainFragmentChoise extends Fragment implements View.OnClickListener {
Button Bn_athlete, Bn_sport, Bn_squad, Bn_query,Bn_firebase;
public MainFragmentChoise(){
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View view = inflater.inflate(R.layout.fragment_choise,container, false);
Bn_athlete = view.findViewById(R.id.athleteButton);
Bn_athlete.setOnClickListener(this);
Bn_sport = view.findViewById(R.id.sportsButton);
Bn_sport.setOnClickListener(this);
Bn_squad = view.findViewById(R.id.squadButton);
Bn_squad.setOnClickListener(this);
Bn_query = view.findViewById(R.id.queryButton);
Bn_query.setOnClickListener(this);
Bn_firebase = view.findViewById(R.id.firebaseButton);
Bn_firebase.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.athleteButton:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new AthleteFragment()).addToBackStack(null).commit();
break;
case R.id.sportsButton:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new SportFragment()).addToBackStack(null).commit();
break;
case R.id.squadButton :
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new SquadFragment()).addToBackStack(null).commit();
break;
case R.id.queryButton:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new QueryFragment()).addToBackStack(null).commit();
break;
case R.id.firebaseButton:
MainActivity.fragmentManager.beginTransaction().replace(R.id.fragment_container, new InsertFragment()).addToBackStack(null).commit();
break;
}
}
}
| 30.626667
| 150
| 0.681323
|
1bfb477300899cec90321d2964ef094fafebe4c8
| 268
|
package pd;
import pd.modules.IModule;
import testexec.IVariableReplacer;
public interface IVar {
public abstract String getValue(IVariableReplacer variableReplacer);
public abstract IModule getModule();
public abstract String getName();
}
| 20.615385
| 73
| 0.742537
|
78769c33a936e1457eb4565b5afb674364d0532d
| 1,243
|
package org.folio.search.configuration;
import static java.util.Collections.singletonList;
import static org.folio.spring.integration.XOkapiHeaders.TENANT;
import static org.folio.spring.integration.XOkapiHeaders.TOKEN;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import feign.RequestTemplate;
import org.folio.search.utils.types.UnitTest;
import org.folio.spring.FolioExecutionContext;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@UnitTest
@ExtendWith(MockitoExtension.class)
class FeignRequestInterceptorTest {
@InjectMocks private FeignRequestInterceptor requestInterceptor;
@Mock private FolioExecutionContext folioExecutionContext;
@Mock private RequestTemplate requestTemplate;
@Test
void apply_positive() {
when(folioExecutionContext.getToken()).thenReturn("token");
when(folioExecutionContext.getTenantId()).thenReturn("tenantId");
requestInterceptor.apply(requestTemplate);
verify(requestTemplate).header(TOKEN, singletonList("token"));
verify(requestTemplate).header(TENANT, singletonList("tenantId"));
}
}
| 34.527778
| 70
| 0.815768
|
4ba7fe9ade5a2dbc6ec1e4e56c6c78432dd8c87b
| 1,272
|
package org.mycat.web.service;
import org.hx.rainbow.common.context.RainbowContext;
import org.hx.rainbow.common.core.service.BaseService;
import org.mycat.web.util.DataSourceUtils;
import org.mycat.web.util.DataSourceUtils.MycatPortType;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@Lazy
@Service
public class ExplainService extends BaseService{
private static final String NAMESPACE = "EXPLAINSQL";
public RainbowContext base(RainbowContext context,String cmd) {
String datasource = (String)context.getAttr("ds");
if(datasource == null || datasource.isEmpty()){
return context;
}
try {
if(!DataSourceUtils.getInstance().register(datasource, DataSourceUtils.MycatPortType.MYCAT_SERVER)){
context.setSuccess(false);
context.setMsg("数据源连接失败!");
logger.error(datasource + ":服务端口,数据源连接失败!");
return context;
}
} catch (Exception e) {
}
context.setDs(datasource + MycatPortType.MYCAT_SERVER);
super.query(context, NAMESPACE, cmd);
return context;
}
public RainbowContext explainMycat(RainbowContext context) {
return base(context,"explainMycat");
}
public RainbowContext explainMysql(RainbowContext context) {
return base(context,"explainMysql");
}
}
| 28.909091
| 103
| 0.759434
|
e875f8d200421c6ddf34fb981ef8eedbc7f8be01
| 252
|
package org.tdar.core.bean;
/**
* not yet used, version of tDAR
*
* @author abrin
*
*/
public enum TdarVersion {
AZIMUTH,
BALK,
CADASTER,
DEBITAGE,
EOLIAN,
FLUVIAL,
GRID,
HARRIS,
INSITU,
JAR,
KNAP;
}
| 11.454545
| 32
| 0.555556
|
f7b3d8e4b736cabdd0920964a12a832f1f2b5fca
| 5,742
|
package ua.com.fielden.platform.sample.domain.crit_gen;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Stream;
import ua.com.fielden.platform.dao.QueryExecutionModel;
import ua.com.fielden.platform.entity.fetch.IFetchProvider;
import ua.com.fielden.platform.entity.query.fluent.fetch;
import ua.com.fielden.platform.entity.query.model.EntityResultQueryModel;
import ua.com.fielden.platform.pagination.IPage;
import ua.com.fielden.platform.security.user.User;
public class LastLevelEntityDaoStub implements ILastLevelEntity {
@Override
public String getUsername() {
// TODO Auto-generated method stub
return null;
}
@Override
public User getUser() {
// TODO Auto-generated method stub
return null;
}
@Override
public Class<LastLevelEntity> getEntityType() {
// TODO Auto-generated method stub
return null;
}
@Override
public Class<? extends Comparable<?>> getKeyType() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean isStale(final Long entityId, final Long version) {
// TODO Auto-generated method stub
return false;
}
@Override
public LastLevelEntity findById(final boolean filtered, final Long id, final fetch<LastLevelEntity> fetchModel) {
// TODO Auto-generated method stub
return null;
}
@Override
public LastLevelEntity findById(final Long id) {
// TODO Auto-generated method stub
return null;
}
@Override
public LastLevelEntity findByKey(final Object... keyValues) {
// TODO Auto-generated method stub
return null;
}
@Override
public LastLevelEntity findByKeyAndFetch(final boolean filtered, final fetch<LastLevelEntity> fetchModel, final Object... keyValues) {
// TODO Auto-generated method stub
return null;
}
@Override
public IPage<LastLevelEntity> firstPage(final QueryExecutionModel<LastLevelEntity, ?> query, final int pageCapacity) {
// TODO Auto-generated method stub
return null;
}
@Override
public IPage<LastLevelEntity> getPage(final QueryExecutionModel<LastLevelEntity, ?> query, final int pageNo, final int pageCapacity) {
// TODO Auto-generated method stub
return null;
}
@Override
public IPage<LastLevelEntity> getPage(final QueryExecutionModel<LastLevelEntity, ?> query, final int pageNo, final int pageCount, final int pageCapacity) {
// TODO Auto-generated method stub
return null;
}
@Override
public LastLevelEntity save(final LastLevelEntity entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean entityExists(final LastLevelEntity entity) {
return "EntityKey".equals(entity.getKey());
}
@Override
public boolean entityExists(final Long id) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean entityWithKeyExists(final Object... keyValues) {
for (final Object keyValue : keyValues) {
if (!"EntityKey".equals(keyValue)) {
return false;
}
}
return true;
}
@Override
public LastLevelEntity getEntity(final QueryExecutionModel<LastLevelEntity, ?> model) {
// TODO Auto-generated method stub
return null;
}
@Override
public int count(final EntityResultQueryModel<LastLevelEntity> model, final Map<String, Object> paramValues) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int count(final EntityResultQueryModel<LastLevelEntity> model) {
// TODO Auto-generated method stub
return 0;
}
@Override
public List<LastLevelEntity> getAllEntities(final QueryExecutionModel<LastLevelEntity, ?> query) {
// TODO Auto-generated method stub
return null;
}
@Override
public byte[] export(final QueryExecutionModel<LastLevelEntity, ?> query, final String[] propertyNames, final String[] propertyTitles) throws IOException {
// TODO Auto-generated method stub
return null;
}
@Override
public List<LastLevelEntity> getFirstEntities(final QueryExecutionModel<LastLevelEntity, ?> query, final int numberOfEntities) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean stop() {
return true;
}
@Override
public Optional<Integer> progress() {
return Optional.empty();
}
@Override
public LastLevelEntity findByEntityAndFetch(final fetch<LastLevelEntity> fetchModel, final LastLevelEntity entity) {
// TODO Auto-generated method stub
return null;
}
@Override
public IFetchProvider<LastLevelEntity> getFetchProvider() {
// TODO Auto-generated method stub
return null;
}
@Override
public LastLevelEntity new_() {
// TODO Auto-generated method stub
return null;
}
@Override
public Stream<LastLevelEntity> stream(final QueryExecutionModel<LastLevelEntity, ?> qem, final int fetchSize) {
// TODO Auto-generated method stub
return null;
}
@Override
public Stream<LastLevelEntity> stream(final QueryExecutionModel<LastLevelEntity, ?> qem) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean exists(final EntityResultQueryModel<LastLevelEntity> model, final Map<String, Object> paramValues) {
// TODO Auto-generated method stub
return false;
}
}
| 28.854271
| 159
| 0.674504
|
16cc3f5e30e94b2e709faaf201296d56e246783f
| 1,988
|
package pl.pkk82.filehierarchygenerator.util;
import static org.assertj.core.api.BDDAssertions.then;
import java.util.List;
import com.google.common.collect.Lists;
import org.assertj.core.api.ListAssert;
import org.junit.Test;
public class ListUtilTest {
private List<String> list;
@Test
public void shouldNotInsertBetweenWhenNull() {
givenListAs(null);
whenInsertBetween("b");
thenList().isNull();
}
@Test
public void shouldNotInsertBetweenWhenOneElement() {
givenListAs(Lists.newArrayList("a"));
whenInsertBetween("b");
thenList().containsOnly("a");
}
@Test
public void shouldInsertBetweenWhenTwoElements() {
givenListAs(Lists.newArrayList("a", "d"));
whenInsertBetween("b", "c");
thenList().containsOnly("a", "b", "c", "d");
}
@Test
public void shouldInsertBetweenWhenThreeElements() {
givenListAs(Lists.newArrayList("a", "d", "g"));
whenInsertBetween("x", "y");
thenList().containsOnly("a", "x", "y", "d", "x", "y", "g");
}
@Test
public void shouldNotInsertBeforeWhenNull() {
givenListAs(null);
whenInsertBefore("x", "y");
thenList().isNull();
}
@Test
public void shouldInsertBefore() {
givenListAs(Lists.newArrayList("c"));
whenInsertBefore("a", "b");
thenList().containsOnly("a", "b", "c");
}
@Test
public void shouldNotInsertAfterWhenNull() {
givenListAs(null);
whenInsertAfter("x", "y");
thenList().isNull();
}
@Test
public void shouldInsertAfter() {
givenListAs(Lists.newArrayList("a"));
whenInsertBefore("b", "c");
thenList().containsOnly("a", "b", "c");
}
private void givenListAs(List<String> list) {
this.list = list;
}
private void whenInsertBetween(String... elements) {
ListUtil.insertBetween(list, elements);
}
private void whenInsertBefore(String... elements) {
ListUtil.insertBefore(list, elements);
}
private void whenInsertAfter(String... elements) {
ListUtil.insertAfter(list, elements);
}
private ListAssert<String> thenList() {
return then(list);
}
}
| 21.376344
| 61
| 0.695171
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.