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 |
|---|---|---|---|---|---|
170544a73ca9ce59717e5f2a563a1fdcd4748b9b | 21,731 | /*
* Copyright 2002-2019 Barcelona Supercomputing Center (www.bsc.es)
*
* 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 es.bsc.compss.scheduler.types;
import static org.junit.Assert.fail;
import es.bsc.compss.components.impl.ResourceScheduler;
import es.bsc.compss.types.CoreElement;
import es.bsc.compss.types.CoreElementDefinition;
import es.bsc.compss.types.fake.FakeWorker;
import es.bsc.compss.types.implementations.Implementation;
import es.bsc.compss.types.implementations.MethodType;
import es.bsc.compss.types.implementations.definition.ImplementationDefinition;
import es.bsc.compss.types.resources.MethodResourceDescription;
import es.bsc.compss.types.resources.components.Processor;
import es.bsc.compss.util.CoreManager;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
public class ResourceSchedulerTest {
private static final String METHOD = MethodType.METHOD.toString();
private static final long DEFAULT_MIN_EXECUTION_TIME = Long.MAX_VALUE;
private static final long DEFAULT_AVG_EXECUTION_TIME = 100L;
private static final long DEFAULT_MAX_EXECUTION_TIME = Long.MIN_VALUE;
private static final long DEFAULT_EXECUTION_COUNT = 0L;
private static final long SET_MIN_EXECUTION_TIME = 2;
private static final long SET_AVG_EXECUTION_TIME = 5;
private static final long SET_MAX_EXECUTION_TIME = 10;
private static final long SET_EXECUTION_COUNT = 3L;
private static final String SET_PROFILE =
"{\"maxTime\":" + (SET_MAX_EXECUTION_TIME) + ",\"executions\":" + (SET_EXECUTION_COUNT) + ",\"avgTime\":"
+ (SET_AVG_EXECUTION_TIME) + ",\"minTime\":" + (SET_MIN_EXECUTION_TIME) + "}";
private static final String SET_AND_UPDATED_PROFILE =
"{\"maxTime\":" + (SET_MAX_EXECUTION_TIME + 1) + ",\"executions\":" + (SET_EXECUTION_COUNT + 1)
+ ",\"avgTime\":" + (SET_AVG_EXECUTION_TIME + 1) + ",\"minTime\":" + (SET_MIN_EXECUTION_TIME + 1) + "}";
private static FakeWorker worker;
/**
* Sets up the class environment before launching the unit tests.
*/
@BeforeClass
public static void setUpClass() {
// Method resource description and its slots
Processor p = new Processor();
p.setComputingUnits(4);
MethodResourceDescription description = new MethodResourceDescription();
description.addProcessor(p);
worker = new FakeWorker(description, 4);
CoreElementDefinition cedA = new CoreElementDefinition();
cedA.setCeSignature("methodA");
ImplementationDefinition<?> implDef = null;
implDef = ImplementationDefinition.defineImplementation(METHOD, "ClassA.methodA",
new MethodResourceDescription(), "ClassA", "methodA");
cedA.addImplementation(implDef);
implDef = ImplementationDefinition.defineImplementation(METHOD, "ClassB.methodA",
new MethodResourceDescription(), "ClassB", "methodA");
cedA.addImplementation(implDef);
CoreManager.registerNewCoreElement(cedA);
CoreElementDefinition cedB = new CoreElementDefinition();
cedB.setCeSignature("methodB");
implDef = ImplementationDefinition.defineImplementation(METHOD, "ClassA.methodB",
new MethodResourceDescription(), "ClassA", "methodB");
cedB.addImplementation(implDef);
CoreManager.registerNewCoreElement(cedB);
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void testNull() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker, null, null);
for (CoreElement ce : CoreManager.getAllCores()) {
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on null test");
}
}
}
}
@Test
public void testEmpty() {
ResourceScheduler<MethodResourceDescription> rs =
new ResourceScheduler<>(worker, new JSONObject("{\"implementations\":{}}"), null);
for (CoreElement ce : CoreManager.getAllCores()) {
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on empty test");
}
}
}
}
@Test
public void testMethodB() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassA.methodB\":" + SET_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodB test");
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId() + " core "
+ impl.getCoreId() + " on MethodB test");
}
}
}
@Test
public void testMethodBUpdated() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassA.methodB\":" + SET_AND_UPDATED_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodB updated test");
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkSetAndIncreasedProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId() + " core "
+ impl.getCoreId() + " on MethodB updated test");
}
}
}
@Test
public void testMethodANullSet() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassB.methodA\":" + SET_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
if (impl.getImplementationId() == 0) {
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA null-set test");
}
} else {
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA null-set test");
}
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA null-set test");
}
}
}
@Test
public void testMethodASetNull() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassA.methodA\":" + SET_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
if (impl.getImplementationId() == 1) {
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-null test");
}
} else {
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-null test");
}
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-null test");
}
}
}
@Test
public void testMethodASetSet() {
ResourceScheduler<MethodResourceDescription> rs =
new ResourceScheduler<>(worker, new JSONObject("{\"implementations\":{\"ClassA.methodA\":" + SET_PROFILE
+ "," + "\"ClassB.methodA\":" + SET_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-set test");
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-set test");
}
}
}
@Test
public void testMethodAUpdatedNull() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassA.methodA\":" + SET_AND_UPDATED_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
if (impl.getImplementationId() == 1) {
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA updated-null test");
}
} else {
try {
this.checkSetAndIncreasedProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA updated-null test");
}
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA updated-null test");
}
}
}
@Test
public void testMethodANullUpdated() {
ResourceScheduler<MethodResourceDescription> rs = new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassB.methodA\":" + SET_AND_UPDATED_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
if (impl.getImplementationId() == 0) {
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA null-updated test");
}
} else {
try {
this.checkSetAndIncreasedProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA null-updated test");
}
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA null-updated test");
}
}
}
@Test
public void testMethodASetUpdated() {
ResourceScheduler<MethodResourceDescription> rs =
new ResourceScheduler<>(worker, new JSONObject("{\"implementations\":{\"ClassA.methodA\":" + SET_PROFILE
+ "," + "\"ClassB.methodA\":" + SET_AND_UPDATED_PROFILE + "}}"), null);
CoreElement ce = CoreManager.getCore(0);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
if (impl.getImplementationId() == 0) {
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-updated test");
}
} else {
try {
this.checkSetAndIncreasedProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for set implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-updated test");
}
}
}
ce = CoreManager.getCore(1);
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkUnsetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on MethodA set-updated test");
}
}
}
@Test
public void testAllSet() {
ResourceScheduler<
MethodResourceDescription> rs =
new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassA.methodA\":" + SET_PROFILE + ","
+ "\"ClassB.methodA\":" + SET_PROFILE + "," + "\"ClassA.methodB\":" + SET_PROFILE + "}}"),
null);
for (CoreElement ce : CoreManager.getAllCores()) {
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on all set test");
}
}
}
}
@Test
public void testAllSetCopy() {
ResourceScheduler<
MethodResourceDescription> rs =
new ResourceScheduler<>(worker,
new JSONObject("{\"implementations\":{\"ClassA.methodA\":" + SET_PROFILE + ","
+ "\"ClassB.methodA\":" + SET_PROFILE + "," + "\"ClassA.methodB\":" + SET_PROFILE + "}}"),
null);
JSONObject jo = rs.toJSONObject();
rs = new ResourceScheduler<>(worker, jo, null);
for (CoreElement ce : CoreManager.getAllCores()) {
for (Implementation impl : ce.getImplementations()) {
Profile p = rs.getProfile(impl);
try {
checkSetProfile(p);
} catch (CheckerException cEx) {
fail("Invalid " + cEx.getFeature() + " for unset implementation " + impl.getImplementationId()
+ " core " + impl.getCoreId() + " on copy test");
}
}
}
}
private void checkSetProfile(Profile p) throws CheckerException {
if (p.getExecutionCount() != SET_EXECUTION_COUNT) {
throw new CheckerException("execution count");
}
if (p.getMinExecutionTime() != SET_MIN_EXECUTION_TIME) {
throw new CheckerException("min execution time");
}
if (p.getAverageExecutionTime() != SET_AVG_EXECUTION_TIME) {
throw new CheckerException("max average time");
}
if (p.getMaxExecutionTime() != SET_MAX_EXECUTION_TIME) {
throw new CheckerException("max execution time");
}
}
private void checkSetAndIncreasedProfile(Profile p) throws CheckerException {
if (p.getExecutionCount() != SET_EXECUTION_COUNT + 1) {
throw new CheckerException("execution count");
}
if (p.getMinExecutionTime() != SET_MIN_EXECUTION_TIME + 1) {
throw new CheckerException("min execution time");
}
if (p.getAverageExecutionTime() != SET_AVG_EXECUTION_TIME + 1) {
throw new CheckerException("max average time");
}
if (p.getMaxExecutionTime() != SET_MAX_EXECUTION_TIME + 1) {
throw new CheckerException("max execution time");
}
}
private void checkUnsetProfile(Profile p) throws CheckerException {
if (p.getExecutionCount() != DEFAULT_EXECUTION_COUNT) {
throw new CheckerException("execution count");
}
if (p.getMinExecutionTime() != DEFAULT_MIN_EXECUTION_TIME) {
throw new CheckerException("min execution time");
}
if (p.getAverageExecutionTime() != DEFAULT_AVG_EXECUTION_TIME) {
throw new CheckerException("max average time");
}
if (p.getMaxExecutionTime() != DEFAULT_MAX_EXECUTION_TIME) {
throw new CheckerException("max execution time");
}
}
private class CheckerException extends Exception {
/**
* All Runtime Exceptions have serial ID 2L.
*/
private static final long serialVersionUID = 2L;
private final String feature;
public CheckerException(String feature) {
this.feature = feature;
}
public String getFeature() {
return feature;
}
}
}
| 42.032882 | 119 | 0.565183 |
d8dedaab1756177e49e0a724bb8d16700dfe607f | 716 | package de.adorsys.ledgers.sca.db.domain;
public enum AuthCodeStatus {
/*
* The authorization process is created, but the authorization code was not sent to the user.
*
* This occurs, when the operation creates authorization requirement at initialization.
*
*/
INITIATED,
/*
* The authorization code was generated and sent to the user. From the
* moment the code is sent, expiration starts counting.
*/
SENT,
/*
* The user successfully validated the authorization code.
*/
VALIDATED,
/*
* The validation of the code failed.
*/
FAILED,
/*
* The code is expired.
*/
EXPIRED,
/*
* The underlying process is executed. Entries can be removed from the database.
*/
DONE;
}
| 21.69697 | 94 | 0.695531 |
f691ebaf6ea6583ad487a1365604ed2944e48250 | 15,384 | /* Copyright (c) 2009 Google 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.google.appengine.demos.sticky.server;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.jdo.JDOHelper;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Transaction;
import javax.jdo.annotations.Element;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.users.User;
/**
* An application specific Api wrapper around the {@link DatastoreService}.
* Creating a {@link Store} is relatively expensive so one should be mindful not
* to create these unnecessarily. For example, in a servlet, the Store should be
* stored as a field in the store to avoid creating it on every request.
*
*
*/
public class Store {
public class Api {
/**
* The JDO persistence manager used for all calls.
*/
private final PersistenceManager manager;
private Api() {
manager = factory.getPersistenceManager();
}
/**
* Begin a new transaction.
*
* @return the transaction
*/
public Transaction begin() {
final Transaction tx = manager.currentTransaction();
tx.begin();
return tx;
}
/**
* Close the connection to the data store. Clients are expected to guarantee
* that close will be called. This will also rollback any active
* transaction.
*/
public void close() {
final Transaction tx = manager.currentTransaction();
if (tx.isActive()) {
tx.rollback();
}
manager.close();
}
/**
* Gets the author by email.
*
* @param email
* the author's email
* @return the author
* @throws JDOObjectNotFoundException
*/
public Author getAuthor(String email) {
return manager.getObjectById(Author.class, email);
}
/**
* Gets a note from the data store.
*
* @param key
* the note's key
* @return
*/
public Note getNote(Key key) {
return manager.getObjectById(Note.class, key);
}
/**
* Looks in the data store for an author with a matching email. If the
* author does not exist, a new one will be created. The newly created
* author will also have access to a newly created surface.
*
* @param user
* the user for which an author object is needed
* @return an author object
*/
public Author getOrCreateNewAuthor(User user) {
try {
return getAuthor(user.getEmail());
} catch (JDOObjectNotFoundException e) {
final Transaction txA = begin();
final Surface surface = new Surface("My First Surface");
surface.addAuthorName(user.getNickname());
saveSurface(surface);
txA.commit();
final Transaction txB = begin();
final Author author = new Author(user.getEmail(), user.getNickname());
author.addSurface(surface);
saveAuthor(author);
txB.commit();
return author;
}
}
/**
* Gets a surface from the data store.
*
* @param key
* the surface's key
* @return
*/
public Surface getSurface(Key key) {
return manager.getObjectById(Surface.class, key);
}
/**
* Persist an author to the data store.
*
* @param author
* the author to be persisted
* @return <code>author</code>, for call chaining
*/
public Author saveAuthor(Author author) {
return manager.makePersistent(author);
}
/**
* Persist a note to the data store.
*
* @param note
* the note to be persisted
* @return <code>note</code>, for call chaining
*/
public Note saveNote(Note note) {
note.lastUpdatedAt = new Date();
return manager.makePersistent(note);
}
/**
* Persist a surface to the data store.
*
* @param surface
* the surface to be persisted
* @return <code>surface</code>, for call chaining
*/
public Surface saveSurface(Surface surface) {
surface.lastUpdatedAt = new Date();
return manager.makePersistent(surface);
}
/**
* Attempts to get the author with the given email. If there is no known
* author with that email, <code>null</code> will be returned.
*
* @param email
* the author's email
* @return the author or <code>null</code> if the author can't be found
*/
public Author tryGetAuthor(String email) {
try {
return getAuthor(email);
} catch (JDOObjectNotFoundException e) {
return null;
}
}
}
/**
* An ORM object representing an author.
*/
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public static class Author {
/**
* The author's email. Serves as the primary key for this object.
*/
@PrimaryKey
private String email;
/**
* The author's name.
*/
@Persistent
private String name;
/**
* The keys of all surfaces this author has access to.
*/
@Persistent(defaultFetchGroup = "true")
@Element(dependent = "true")
private List<Key> surfaceKeys = new ArrayList<Key>();
/**
* Construct a new author.
*
* @param email
* the author's email
* @param name
* the author's name
*/
public Author(String email, String name) {
this.name = name;
setEmail(email);
}
/**
* Give this author access to a surface.
*
* @param surface
* the surface the author is being granted access to.
*/
public void addSurface(Surface surface) {
final List<Key> keys = new ArrayList<Key>(surfaceKeys);
keys.add(surface.getKey());
setSurfaceKeys(keys);
}
/**
* Gets the author's email.
*
* @return
*/
public String getEmail() {
return email;
}
/**
* Gets the author's name.
*
* @return
*/
public String getName() {
return name;
}
/**
* Returns the keys for each surface that the author has access to.
*
* @return
*/
public List<Key> getSurfaceKeys() {
return surfaceKeys;
}
/**
* Returns whether this author has access to a particular surface.
*
* @param surfaceKey
* the key of the surface
* @return <code>true</code> if the author does have access,
* <code>false</code> otherwise
*/
public boolean hasSurface(Key surfaceKey) {
for (Key key : surfaceKeys) {
if (key.equals(surfaceKey)) {
return true;
}
}
return false;
}
/**
* Sets the author's email.
*
* @param email
*/
public void setEmail(String email) {
this.email = email;
}
/**
* Sets the author's name.
*
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* Reassigns the collection of surface keys. This is required to ensure that
* the ORM will persist element collections.
*
* @param keys
*/
private void setSurfaceKeys(List<Key> keys) {
surfaceKeys = keys;
}
}
/**
* An ORM object representing a note.
*/
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public static class Note {
/**
* An auto-generated primary key for this object. This key will be a child
* key of the owning surface's key.
*/
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
/**
* The x position of the note.
*/
@Persistent
private int x;
/**
* The y position of the note.
*/
@Persistent
private int y;
/**
* The width of the note.
*
* <p>
* NOTE: The application does not currently provide the ability to resize
* notes.
* </p>
*/
@Persistent
private int width;
/**
* The height of the note
*
* <p>
* NOTE: The application does not currently provide the ability to resize
* notes.
* </p>
*/
@Persistent
private int height;
/**
* The text content of the note.
*/
@Persistent
private String content;
/**
* The date of the last time this object was persisted.
*/
@Persistent
private Date lastUpdatedAt = new Date();
/**
* The email of the author created this note.
*/
@Persistent
private String authorEmail;
/**
* The name of the author who created this note.
*/
@Persistent
private String authorName;
/**
* Create a new note.
*
* @param owner
* the author who created this note
* @param x
* @param y
* @param width
* @param height
*/
public Note(Author owner, int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
authorEmail = owner.getEmail();
authorName = owner.getName();
}
/**
* The author's email.
*
* @return
*/
public String getAuthorEmail() {
return authorEmail;
}
/**
* The author's name.
*
* @return
*/
public String getAuthorName() {
return authorName;
}
/**
* The text of the note. This value is not escaped in anyway and should
* never be used as html on the client.
*
* @return unsafe text content
*/
public String getContent() {
return content;
}
/**
* Gets the height of the note.
*
* @return
*/
public int getHeight() {
return height;
}
/**
* Gets the object's primary key.
*
* @return
*/
public Key getKey() {
return key;
}
/**
* Gets the date of the last time this object was persisted.
*
* @return
*/
public Date getLastUpdatedAt() {
return lastUpdatedAt;
}
/**
* Gets the width of the note.
*
* @return
*/
public int getWidth() {
return width;
}
/**
* Gets the x position of the note.
*
* @return
*/
public int getX() {
return x;
}
/**
* Gets the y position of the note.
*
* @return
*/
public int getY() {
return y;
}
/**
* Indicates whether the given author is the owner of this note.
*
* @param author
* the author
* @return <code>true</code> if <code>author</code> is the owner of the
* note, <code>false</code> otherwise.
*/
public boolean isOwnedBy(Author author) {
return author.getEmail().equals(authorEmail);
}
/**
* Sets the content.
*
* @param content
*/
public void setContent(String content) {
this.content = content;
}
/**
* Sets the height of the note.
*
* @param height
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Sets the width of the note.
*
* @param width
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Sets the x position of the note.
*
* @param x
*/
public void setX(int x) {
this.x = x;
}
/**
* Sets the y position of the note.
*
* @param y
*/
public void setY(int y) {
this.y = y;
}
}
/**
* A JDO object representing a surface.
*/
@PersistenceCapable(identityType = IdentityType.APPLICATION)
public static class Surface {
/**
* An auto-generated primary key.
*/
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
/**
* The title of the surface.
*/
@Persistent
private String title;
/**
* The date of the last time this surface was persisted.
*/
@Persistent
private Date lastUpdatedAt;
/**
* The name of each author that has access to this surface.
*/
@Persistent(defaultFetchGroup = "true")
private List<String> authorNames = new ArrayList<String>();
/**
* The notes that are stuck to this surface.
*/
@Element(dependent = "true")
private List<Note> notes = new ArrayList<Note>();
/**
* Create a new surface.
*
* @param title
*/
public Surface(String title) {
this.title = title;
}
/**
* Add the name to the author names. Calls to this method are generally
* paired with a call to {@link Author#addSurface(Surface)}.
*
* @param name
*/
public void addAuthorName(String name) {
final List<String> names = new ArrayList<String>(authorNames);
names.add(name);
setAuthorNames(names);
}
/**
* Gets the collection of author names.
*
* @return
*/
public List<String> getAuthorNames() {
return authorNames;
}
/**
* Gets the primary key for this object.
*
* @return
*/
public Key getKey() {
return key;
}
/**
* Gets the date of the last time this object was persisted.
*
* @return
*/
public Date getLastUpdatedAt() {
return lastUpdatedAt;
}
/**
* Gets all the notes that are stuck to this surface.
*
* @return
*/
public List<Note> getNotes() {
return notes;
}
/**
* Get the surface's title.
*
* @return
*/
public String getTitle() {
return title;
}
/**
* Sets the surface's title.
*
* @param title
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Reassigns the collection of author names. This is required to ensure that
* the ORM persists element collections.
*
* @param names
*/
private void setAuthorNames(List<String> names) {
authorNames = names;
}
}
private final PersistenceManagerFactory factory;
/**
* Create a new Store based on a particular config.
*
* @param config
*/
public Store(String config) {
this.factory = JDOHelper.getPersistenceManagerFactory(config);
}
/**
* Starts a data store session and returns an Api object to use.
*
* @return
*/
public Api getApi() {
return new Api();
}
}
| 22.231214 | 80 | 0.580148 |
a0411c867b61439145a21e2403417ba6b52b10f8 | 287 | package org.twuni.common.net.exception;
import java.io.IOException;
public class ConnectionClosedException extends IOException {
public ConnectionClosedException() {
super( "Connection closed." );
}
public ConnectionClosedException( String message ) {
super( message );
}
}
| 17.9375 | 60 | 0.759582 |
db0a0efadcbe7d049b36e9b9ca900695e66b0832 | 608 | package org.cyclops.integrateddynamics.item;
import net.minecraft.item.Item;
import org.cyclops.cyclopscore.config.extendedconfig.ItemConfig;
import org.cyclops.integrateddynamics.IntegratedDynamics;
/**
* Config for the labeller.
* @author rubensworks
*/
public class ItemLabellerConfig extends ItemConfig {
public ItemLabellerConfig() {
super(
IntegratedDynamics._instance,
"labeller",
eConfig -> new ItemLabeller(new Item.Properties()
.group(IntegratedDynamics._instance.getDefaultItemGroup()))
);
}
}
| 26.434783 | 83 | 0.675987 |
21e158ac5c018b67b666374cfc9e54c016136bc3 | 855 | package com.sherlocky.springboot2.aop4logging.service;
import com.sherlocky.springboot2.aop4logging.aop.annotation.SherlockLogAnnotation;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;
/**
* 简单Service示例,测试AOP Logging
* @author: zhangcx
* @date: 2019/1/25 10:42
*/
@Service
public class SampleService {
/**
* 简单的方法测试 Sherlock AOP Aspect
* @param id
* @param name
* @param age
* @param address
* @return
*/
@SherlockLogAnnotation("构建数据结果")
public Map<String, String> buildData(String id, String name, int age, String address) {
Map<String, String> data = new HashMap<>();
data.put("id", id);
data.put("name", name);
data.put("age", String.valueOf(age));
data.put("address", address);
return data;
}
}
| 23.75 | 91 | 0.649123 |
393591de213219b49af2a612cf7a91faff780958 | 790 | package com.kkasztel.utils;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Supplier;
import lombok.RequiredArgsConstructor;
@RequiredArgsConstructor(staticName = "of")
public class CachedSupplier<T> implements Supplier<T> {
private final Supplier<T> delegate;
private final AtomicReference<T> value = new AtomicReference<>();
@Override
public T get() {
T val = value.get();
if (val == null) {
synchronized (value) {
val = value.get();
if (val == null) {
val = delegate.get();
value.set(val);
}
}
}
return val;
}
public synchronized void invalidate() {
value.set(null);
}
}
| 23.939394 | 69 | 0.565823 |
36ea81b90f5dce4e58c364c49a24a5c53021162a | 12,305 | /*
* 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.netbeans.modules.java.lsp.server.protocol;
import java.util.List;
import java.util.Objects;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.jsonrpc.validation.NonNull;
import org.eclipse.lsp4j.util.Preconditions;
import org.eclipse.xtext.xbase.lib.Pure;
import org.eclipse.xtext.xbase.lib.util.ToStringBuilder;
/**
* Information about a test suite.
*
* @author Dusan Balek
*/
public final class TestSuiteInfo {
/**
* The test suite name to be displayed by the Test Explorer.
*/
@NonNull
private String name;
/**
* The file containing this suite (if known).
*/
private String file;
/**
* The range within the specified file where the suite definition is located (if known).
*/
private Range range;
/**
* The state of the tests suite. Can be one of the following values:
* "loaded" | "started" | "completed" | "errored"
*/
@NonNull
private String state;
/**
* The test cases of the test suite.
*/
private List<TestCaseInfo> tests;
public TestSuiteInfo() {
this("", "");
}
public TestSuiteInfo(@NonNull final String name, @NonNull final String state) {
this.name = Preconditions.checkNotNull(name, "name");
this.state = Preconditions.checkNotNull(state, "state");
}
public TestSuiteInfo(@NonNull final String name, final String file, final Range range, @NonNull final String state, final List<TestCaseInfo> tests) {
this(name, state);
this.file = file;
this.range = range;
this.tests = tests;
}
/**
* The test suite name to be displayed by the Test Explorer.
*/
@Pure
@NonNull
public String getName() {
return name;
}
/**
* The test suite name to be displayed by the Test Explorer.
*/
public void setSuiteName(@NonNull final String name) {
this.name = Preconditions.checkNotNull(name, "name");
}
/**
* The file containing this suite (if known).
*/
@Pure
public String getFile() {
return file;
}
/**
* The file containing this suite (if known).
*/
public void setFile(final String file) {
this.file = file;
}
/**
* The range within the specified file where the suite definition is located (if known).
*/
@Pure
public Range getRange() {
return range;
}
/**
* The range within the specified file where the suite definition is located (if known).
*/
public void setRange(final Range range) {
this.range = range;
}
/**
* The state of the tests suite. Can be one of the following values:
* "loaded" | "started" | "completed" | "errored"
*/
@Pure
@NonNull
public String getState() {
return state;
}
/**
* The state of the tests suite. Can be one of the following values:
* "loaded" | "started" | "completed" | "errored"
*/
public void setState(@NonNull final String state) {
this.state = Preconditions.checkNotNull(state, "state");
}
/**
* The test cases of the test suite.
*/
@Pure
public List<TestCaseInfo> getTests() {
return tests;
}
/**
* The test cases of the test suite.
*/
public void setTests(List<TestCaseInfo> tests) {
this.tests = tests;
}
@Override
@Pure
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("name", name);
b.add("file", file);
b.add("range", range);
b.add("state", state);
b.add("tests", tests);
return b.toString();
}
@Override
@Pure
public int hashCode() {
int hash = 7;
hash = 67 * hash + Objects.hashCode(this.name);
hash = 67 * hash + Objects.hashCode(this.file);
hash = 67 * hash + Objects.hashCode(this.range);
hash = 67 * hash + Objects.hashCode(this.state);
hash = 67 * hash + Objects.hashCode(this.tests);
return hash;
}
@Override
@Pure
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TestSuiteInfo other = (TestSuiteInfo) obj;
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.file, other.file)) {
return false;
}
if (!Objects.equals(this.range, other.range)) {
return false;
}
if (!Objects.equals(this.state, other.state)) {
return false;
}
if (!Objects.equals(this.tests, other.tests)) {
return false;
}
return true;
}
/**
* Information about a test case.
*/
public static final class TestCaseInfo {
/**
* The test case ID.
*/
@NonNull
private String id;
/**
* The name to be displayed by the Test Explorer for this test case.
*/
@NonNull
private String name;
/**
* The file containing this test case (if known).
*/
private String file;
/**
* The range within the specified file where the test case definition is located (if known).
*/
private Range range;
/**
* The state of the test case. Can be one of the following values:
* "loaded" | "started" | "passed" | "failed" | "skipped" | "errored"
*/
@NonNull
private String state;
/**
* Stack trace for a test failure.
*/
private List<String> stackTrace;
public TestCaseInfo() {
this("", "", "");
}
public TestCaseInfo(@NonNull final String id, @NonNull final String name, @NonNull final String state) {
this.id = Preconditions.checkNotNull(id, "id");
this.name = Preconditions.checkNotNull(name, "name");
this.state = Preconditions.checkNotNull(state, "state");
}
public TestCaseInfo(@NonNull final String id, @NonNull final String name, final String file, final Range range, @NonNull final String state, final List<String> stackTrace) {
this(id, name, state);
this.file = file;
this.range = range;
this.stackTrace = stackTrace;
}
/**
* The test case ID.
*/
@Pure
@NonNull
public String getId() {
return id;
}
/**
* The test case ID.
*/
public void setId(@NonNull final String id) {
this.id = Preconditions.checkNotNull(id, "id");
}
/**
* The name to be displayed by the Test Explorer for this test case.
*/
@Pure
@NonNull
public String getName() {
return name;
}
/**
* The name to be displayed by the Test Explorer for this test case.
*/
public void setName(@NonNull final String name) {
this.name = Preconditions.checkNotNull(name, "name");
}
/**
* The file containing this test case (if known).
*/
@Pure
public String getFile() {
return file;
}
/**
* The file containing this test case (if known).
*/
public void setFile(final String file) {
this.file = file;
}
/**
* The range within the specified file where the test case definition is located (if known).
*/
@Pure
public Range getRange() {
return range;
}
/**
* The range within the specified file where the test case definition is located (if known).
*/
public void setRange(final Range range) {
this.range = range;
}
/**
* The state of the test case. Can be one of the following values:
* "loaded" | "started" | "passed" | "failed" | "skipped" | "errored"
*/
@Pure
@NonNull
public String getState() {
return state;
}
/**
* The state of the test case. Can be one of the following values:
* "loaded" | "started" | "passed" | "failed" | "skipped" | "errored"
*/
public void setState(@NonNull final String state) {
this.state = Preconditions.checkNotNull(state, "state");
}
/**
* Stack trace for a test failure.
*/
@Pure
public List<String> getStackTrace() {
return stackTrace;
}
/**
* Stack trace for a test failure.
*/
public void setStackTrace(final List<String> stackTrace) {
this.stackTrace = stackTrace;
}
@Override
@Pure
public String toString() {
ToStringBuilder b = new ToStringBuilder(this);
b.add("id", id);
b.add("name", name);
b.add("file", file);
b.add("range", range);
b.add("state", state);
b.add("stackTrace", stackTrace);
return b.toString();
}
@Override
@Pure
public int hashCode() {
int hash = 5;
hash = 97 * hash + Objects.hashCode(this.id);
hash = 97 * hash + Objects.hashCode(this.name);
hash = 97 * hash + Objects.hashCode(this.file);
hash = 97 * hash + Objects.hashCode(this.range);
hash = 97 * hash + Objects.hashCode(this.state);
hash = 97 * hash + Objects.hashCode(this.stackTrace);
return hash;
}
@Override
@Pure
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final TestCaseInfo other = (TestCaseInfo) obj;
if (!Objects.equals(this.id, other.id)) {
return false;
}
if (!Objects.equals(this.name, other.name)) {
return false;
}
if (!Objects.equals(this.file, other.file)) {
return false;
}
if (!Objects.equals(this.range, other.range)) {
return false;
}
if (!Objects.equals(this.state, other.state)) {
return false;
}
if (!Objects.equals(this.stackTrace, other.stackTrace)) {
return false;
}
return true;
}
}
/**
* Constants for test states.
*/
public static final class State {
private State() {}
public static final String Loaded = "loaded";
public static final String Started = "started";
public static final String Completed = "completed";
public static final String Passed = "passed";
public static final String Failed = "failed";
public static final String Skipped = "skipped";
public static final String Errored = "errored";
}
}
| 27.466518 | 181 | 0.544575 |
5ad448400733423c4e2c754ead6dc98c093db1a0 | 4,292 | /***************************************************************************
* Copyright 2001-2009 The VietSpider All rights reserved. *
**************************************************************************/
package org.vietspider.html.util;
import java.io.File;
import java.util.List;
import org.vietspider.chars.CharsDecoder;
import org.vietspider.chars.refs.RefsDecoder;
import org.vietspider.common.io.DataReader;
import org.vietspider.html.HTMLDocument;
import org.vietspider.html.HTMLNode;
import org.vietspider.html.Name;
import org.vietspider.html.NodeIterator;
import org.vietspider.html.parser.EncodingDetector;
import org.vietspider.html.parser.HTMLParser2;
import org.vietspider.html.parser.NodeImpl;
import org.vietspider.token.attribute.Attribute;
import org.vietspider.token.attribute.Attributes;
/**
* Author : Nhu Dinh Thuan
* nhudinhthuan@yahoo.com
* Apr 27, 2009
*/
public class HTMLParserDetector extends HTMLParser2 {
private String charset = null;
private boolean decode = false;
public HTMLParserDetector() {
}
public HTMLParserDetector(String charset_) {
this.charset = charset_;
if(charset != null && charset.trim().length() < 1) charset = null;
}
public HTMLDocument loadDocument(File file) throws Exception {
DataReader reader = new DataReader();
byte [] bytes = reader.load(file);
return charset != null ? createDocument(bytes, charset) : detectDocument(bytes);
}
public HTMLDocument createDocument(byte [] bytes) throws Exception {
if(charset != null) {
char [] chars = CharsDecoder.decode(charset, bytes, 0, bytes.length);
if(decode) chars = new RefsDecoder().decode(chars);
return createDocument(chars);
}
return detectDocument(bytes);
}
private HTMLDocument detectDocument(byte [] bytes) throws Exception {
this.charset = detectCharset(bytes);
char [] chars = CharsDecoder.decode(charset, bytes, 0, bytes.length);
if(decode) chars = new RefsDecoder().decode(chars);
return createDocument(chars);
}
public String detectCharset(byte [] bytes) {
EncodingDetector encodingDetector = new EncodingDetector();
String codeCharset = encodingDetector.detect(bytes);
if(codeCharset == null) codeCharset = "utf-8";
try {
HTMLDocument document = createDocument(bytes, codeCharset);
String docCharset = getCharset(document);
if(docCharset == null
|| charset.equalsIgnoreCase(docCharset)) return codeCharset;
return docCharset;
} catch (Exception e) {
return codeCharset;
}
}
public String getCharset(HTMLDocument document) throws Exception {
HTMLNode root = document.getRoot();
NodeIterator iterator = root.iterator();
while(iterator.hasNext()) {
HTMLNode n = iterator.next();
if(!n.isNode(Name.META)) continue;
if(n.isNode(Name.BODY)) break;
Attributes attributes = n.getAttributes();
Attribute attribute = attributes.get("http-equiv");
if(attribute == null || attribute.getValue() == null) continue;
if(!"content-type".equalsIgnoreCase(attribute.getValue().trim())) continue ;
attribute = attributes.get("content");
if(attribute == null) continue;
String link = attribute.getValue();
if(link == null) continue;
int index = link.toLowerCase().indexOf("=");
return link.substring(index+1);
}
return null;
}
public List<NodeImpl> createTokens(byte [] bytes) throws Exception {
if(charset != null) {
char [] chars = CharsDecoder.decode(charset, bytes, 0, bytes.length);
if(decode) chars = new RefsDecoder().decode(chars);
return createTokens(chars);
}
this.charset = detectCharset(bytes);
char [] chars = CharsDecoder.decode(charset, bytes, 0, bytes.length);
if(decode) chars = new RefsDecoder().decode(chars);
return createTokens(chars);
}
public String getCharset() { return charset; }
public void setCharset(String charset) { this.charset = charset; }
public boolean isDecode() { return decode; }
public void setDecode(boolean decode) { this.decode = decode; }
}
| 35.766667 | 85 | 0.649581 |
7c055dd61b362d68b6f5b0acf3cc89e5bac611f8 | 328 | package com.google.gson.p192b;
import java.util.Comparator;
/* renamed from: com.google.gson.b.v */
/* compiled from: LinkedTreeMap */
class C10162v implements Comparator<Comparable> {
C10162v() {
}
/* renamed from: a */
public int compare(Comparable a, Comparable b) {
return a.compareTo(b);
}
}
| 20.5 | 52 | 0.658537 |
13bce6f2ff88d2b2d94289a9ec31ee2014e221f1 | 321 | import java.util.concurrent.atomic.*;
public class GetAndSet implements MyLock {
AtomicBoolean isOccupied = new AtomicBoolean(false);
public void lock() {
while (isOccupied.getAndSet(true)) {
Thread.yield();
// skip();
}
}
public void unlock() {
isOccupied.set(false);
}
}
| 20.0625 | 56 | 0.626168 |
1df3cd7889f8894e804d4e5247850eb488a845af | 284 | package language_elements.expression;
public abstract class PostExpression extends Expression {
private Expression expression;
public PostExpression(Expression e) {
super(e.getPosition());
this.expression = e;
}
public Expression getExpression() {
return expression;
}
} | 20.285714 | 57 | 0.771127 |
557590cd32232223b1b2ab25945830088a09d4ab | 2,704 | package eg.mahmoudShawky.metar.utils.concurrent;
import android.os.AsyncTask;
import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import eg.mahmoudShawky.metar.utils.Utils;
/***
* @author mahmoud.shawky
*
* Help to run a block of code in background and and pass the result to forground if needed
* It can be aware of lifecycle
*/
public class SimpleAsyncTask {
private static final ExecutorService EXECUTOR_SERVICE =
Executors.newFixedThreadPool(Math.max(2, Math.min(Runtime.getRuntime().availableProcessors() - 1, 4)),
Executors.defaultThreadFactory());
/**
* Runs a task in the background and passes the result of the computation to a task that is run
* on the main thread. Will only invoke the {@code foregroundTask} if the provided {@link Lifecycle}
* is in a valid (i.e. visible) state at that time. In this way, it is very similar to
* {@link AsyncTask}, but is safe in that you can guarantee your task won't be called when your
* view is in an invalid state.
*/
public static <E> void run(@NonNull Lifecycle lifecycle, @NonNull BackgroundTask<E> backgroundTask, @NonNull ForegroundTask<E> foregroundTask) {
if (!isValid(lifecycle)) {
return;
}
EXECUTOR_SERVICE.execute(() -> {
final E result = backgroundTask.run();
if (isValid(lifecycle)) {
Utils.runOnMain(() -> {
if (isValid(lifecycle)) {
foregroundTask.run(result);
}
});
}
});
}
/**
* Runs a task in the background and passes the result of the computation to a task that is run on
* the main thread. Essentially {@link AsyncTask}, but lambda-compatible.
*/
public static <E> void run(@NonNull BackgroundTask<E> backgroundTask, @NonNull ForegroundTask<E> foregroundTask) {
EXECUTOR_SERVICE.execute(() -> {
final E result = backgroundTask.run();
Utils.runOnMain(() -> foregroundTask.run(result));
});
}
public static void run(@NonNull BackgroundVoidTask backgroundTask) {
EXECUTOR_SERVICE.execute(backgroundTask::run);
}
private static boolean isValid(@NonNull Lifecycle lifecycle) {
return lifecycle.getCurrentState().isAtLeast(Lifecycle.State.CREATED);
}
public interface BackgroundTask<E> {
E run();
}
public interface BackgroundVoidTask {
void run();
}
public interface ForegroundTask<E> {
void run(E result);
}
}
| 33.382716 | 148 | 0.64497 |
d8322437bab9dd0e671effed493738ae2b624daa | 1,740 | package xml.model;
import java.util.Objects;
import java.util.Optional;
public class XmlElement implements VisitableElement {
private String name;
private Attributes attributes;
protected XmlElement(AbstractBuilder<?> builder) {
name = Objects.requireNonNull(builder.name);
attributes = builder.attributes;
}
protected XmlElement(XmlElement other) {
name = other.name;
attributes = other.attributes;
}
public String name() {
return name;
}
public Optional<Attributes> attributes() {
return Optional.ofNullable(attributes);
}
public XmlElementWithChildren withChild(VisitableElement child) {
return new XmlElementWithChildren.Builder()
.withName(name)
.withAttributes(attributes)
.withChild(child)
.build();
}
@Override
public <R> R accept(ElementVisitor<R> visitor) {
return visitor.visit(this);
}
protected static abstract class AbstractBuilder<T extends AbstractBuilder<T>> {
private String name;
private Attributes attributes;
public T withName(String name) {
this.name = name;
return getThis();
}
public T withAttributes(Attributes attributes) {
this.attributes = attributes;
return getThis();
}
protected abstract T getThis();
}
public static class Builder extends AbstractBuilder<Builder> {
public XmlElement build() {
return new XmlElement(this);
}
protected Builder getThis() {
return this;
}
}
}
| 25.217391 | 83 | 0.591954 |
38840cb716cb55fdf067ee5f707ac620a0767b74 | 1,160 | package com.bdoemu.core.network.receivable;
import com.bdoemu.commons.model.enums.EStringTable;
import com.bdoemu.commons.network.ReceivablePacket;
import com.bdoemu.core.network.GameClient;
import com.bdoemu.core.network.sendable.SMNak;
import com.bdoemu.core.network.sendable.SMTradeGameStart;
import com.bdoemu.gameserver.model.creature.player.Player;
import com.bdoemu.gameserver.model.creature.player.trade.Bargain;
public class CMTradeGameStart extends ReceivablePacket<GameClient> {
private int _npcSessionId;
public CMTradeGameStart(final short opcode) {
super(opcode);
}
protected void read() {
_npcSessionId = readD();
}
public void runImpl() {
Player player = getClient().getPlayer();
if (player != null) {
if (player.getCurrentWp() >= 5) {
Bargain bargain = new Bargain(player, -3, 3, 3);
bargain.createDice();
player.setTradeShopBargain(bargain);
player.addWp(-5);
} else
player.sendPacket(new SMNak(EStringTable.eErrNoMentalNotEnoughWp, CMTradeGameStart.class));
}
}
}
| 33.142857 | 107 | 0.674138 |
4d5224b2a8db844f02f533ab3d66db4d0abbc7e2 | 5,157 | /*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.musicplayer;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
/**
* Main activity: shows media player buttons. This activity shows the media player buttons and
* lets the user click them. No media handling is done here -- everything is done by passing
* Intents to our {@link MusicService}.
* */
public class MainActivity extends Activity implements OnClickListener {
/**
* The URL we suggest as default when adding by URL. This is just so that the user doesn't
* have to find an URL to test this sample.
*/
final String SUGGESTED_URL = "http://www.vorbis.com/music/Epoq-Lepidoptera.ogg";
Button mPlayButton;
Button mPauseButton;
Button mSkipButton;
Button mRewindButton;
Button mStopButton;
Button mEjectButton;
/**
* Called when the activity is first created. Here, we simply set the event listeners and
* start the background service ({@link MusicService}) that will handle the actual media
* playback.
*/
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPlayButton = (Button) findViewById(R.id.playbutton);
mPauseButton = (Button) findViewById(R.id.pausebutton);
mSkipButton = (Button) findViewById(R.id.skipbutton);
mRewindButton = (Button) findViewById(R.id.rewindbutton);
mStopButton = (Button) findViewById(R.id.stopbutton);
mEjectButton = (Button) findViewById(R.id.ejectbutton);
mPlayButton.setOnClickListener(this);
mPauseButton.setOnClickListener(this);
mSkipButton.setOnClickListener(this);
mRewindButton.setOnClickListener(this);
mStopButton.setOnClickListener(this);
mEjectButton.setOnClickListener(this);
}
public void onClick(View target) {
// Send the correct intent to the MusicService, according to the button that was clicked
if (target == mPlayButton)
startService(new Intent(MusicService.ACTION_PLAY));
else if (target == mPauseButton)
startService(new Intent(MusicService.ACTION_PAUSE));
else if (target == mSkipButton)
startService(new Intent(MusicService.ACTION_SKIP));
else if (target == mRewindButton)
startService(new Intent(MusicService.ACTION_REWIND));
else if (target == mStopButton)
startService(new Intent(MusicService.ACTION_STOP));
else if (target == mEjectButton) {
showUrlDialog();
}
}
/**
* Shows an alert dialog where the user can input a URL. After showing the dialog, if the user
* confirms, sends the appropriate intent to the {@link MusicService} to cause that URL to be
* played.
*/
void showUrlDialog() {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this);
alertBuilder.setTitle("Manual Input");
alertBuilder.setMessage("Enter a URL (must be http://)");
final EditText input = new EditText(this);
alertBuilder.setView(input);
input.setText(SUGGESTED_URL);
alertBuilder.setPositiveButton("Play!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int whichButton) {
// Send an intent with the URL of the song to play. This is expected by
// MusicService.
Intent i = new Intent(MusicService.ACTION_URL);
Uri uri = Uri.parse(input.getText().toString());
i.setData(uri);
startService(i);
}
});
alertBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int whichButton) {}
});
alertBuilder.show();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE:
case KeyEvent.KEYCODE_HEADSETHOOK:
startService(new Intent(MusicService.ACTION_TOGGLE_PLAYBACK));
return true;
}
return super.onKeyDown(keyCode, event);
}
}
| 38.485075 | 98 | 0.67578 |
10a0f61ff210a0df385eed2e5424b270ac1c76b1 | 4,507 | package com.cloudentity.tools.vertx.shutdown;
import com.cloudentity.tools.vertx.bus.ServiceVerticle;
import io.vertx.core.CompositeFuture;
import io.vertx.core.Future;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* This verticle can be used to store cleanup operations that will be executed on ShutdownVerticle un-deployment.
* It is deployed by VertxBootstrap on its start and un-deployed either on VertxBootstrap un-deployment or start failure.
*/
public class ShutdownVerticle extends ServiceVerticle implements ShutdownService {
private static final Logger log = LoggerFactory.getLogger(ShutdownVerticle.class);
List<Supplier<Future>> shutdownActions = new ArrayList<>();
private boolean isShutdown = false;
private static final String CONFIG_PATH = "shutdown-service";
private static final String DISABLE_EXIT_PROPERTY_NAME = "disableExit";
private static final String EXIT_DELAY_PROPERTY_NAME = "exitDelay";
public static final String DISABLE_EXIT_SYSTEM_PROPERTY_NAME = CONFIG_PATH + "." + DISABLE_EXIT_PROPERTY_NAME;
private boolean disableExitFromSystem = false;
private boolean disableExit = false;
private int exitDelay = 10;
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, runnable -> {
Thread thread = Executors.defaultThreadFactory().newThread(runnable);
thread.setDaemon(true);
return thread;
});
/**
* @param disableExitFromSystem if set to true JVM exit task would not be started
* use it for tests
*/
public ShutdownVerticle(boolean disableExitFromSystem) {
this.disableExitFromSystem = disableExitFromSystem;
}
/**
* by default setting `disableExitFromSystem` to true to disable JVM exit task
*/
public ShutdownVerticle() {
this(true);
}
@Override
protected void initService() {
this.disableExit = this.disableExitFromSystem
|| getDisabledConfigFromSystemProperties()
|| getDisabledConfigFromVerticleConfig();
if (!disableExit) {
this.exitDelay = getExitDelayConfigFromVerticleConfig();
}
}
@Override
public Future<Void> registerShutdownAction(Supplier<Future> action) {
if (isShutdown) {
log.warn("System is in shutdown state. Executing action immediately");
return action.get()
.compose(any -> Future.failedFuture(new SystemInShutdownStateException("System is in shutdown state. Action was executed. Failing as system is shutting down.")));
}
else {
shutdownActions.add(action);
log.info("New shutdown action has been registered. Keeping {} actions now", shutdownActions.size());
return Future.succeededFuture();
}
}
@Override
public void stop(Future s) {
isShutdown = true;
log.info("Stopping ShutdownVerticle. Executing {} registered actions", shutdownActions.size());
CompositeFuture.all(
shutdownActions.stream().map(a -> a.get()).collect(Collectors.toList())
).map(x -> shutdownJVM()).setHandler(s);
}
private Void shutdownJVM() {
if (!disableExit) {
log.info("Creating background thread which will kill JVM if application would not shutdown properly in {} sec", exitDelay);
scheduler.schedule(() -> {
log.warn("Shutting down JVM with -1 signal");
System.exit(-1);
}, exitDelay, TimeUnit.SECONDS);
} else {
log.info("Shutdown jvm is disabled. Skipping");
}
scheduler.shutdown();
return null;
}
private int getExitDelayConfigFromVerticleConfig() {
return Optional.ofNullable(getConfig()).map(c -> c.getInteger(EXIT_DELAY_PROPERTY_NAME, 10)).orElse(10);
}
private boolean getDisabledConfigFromSystemProperties() {
return Boolean.parseBoolean(System.getProperty(DISABLE_EXIT_SYSTEM_PROPERTY_NAME));
}
private boolean getDisabledConfigFromVerticleConfig() {
return Optional.ofNullable(getConfig()).map(c -> c.getBoolean(DISABLE_EXIT_PROPERTY_NAME, false)).orElse(false);
}
public static class SystemInShutdownStateException extends RuntimeException {
SystemInShutdownStateException(String message) {
super(message);
}
}
@Override
public String configPath() {
return CONFIG_PATH;
}
}
| 34.669231 | 172 | 0.733304 |
8ade310ca67e4891c076d64d2d70cf0949f386ae | 3,912 | /*
* Copyright (c) 2020. https://rxmicro.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.rxmicro.examples.data.r2dbc.postgresql.close.resources.delete;
import io.reactivex.rxjava3.core.Completable;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.core.Maybe;
import io.reactivex.rxjava3.core.Single;
import io.rxmicro.data.sql.VariableValues;
import io.rxmicro.data.sql.operation.Delete;
import io.rxmicro.data.sql.r2dbc.postgresql.PostgreSQLRepository;
import io.rxmicro.examples.data.r2dbc.postgresql.close.resources.model.Product;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import static io.rxmicro.examples.data.r2dbc.postgresql.close.resources.Constants.PRODUCT_TABLE_NAME;
@PostgreSQLRepository
@VariableValues({
"${table}", PRODUCT_TABLE_NAME
})
public interface DeleteSuccessfulDataRepository {
@Delete("DELETE FROM ${table} WHERE id = 1")
Mono<Void> deleteOne01();
@Delete("DELETE FROM ${table} WHERE id = 2")
Mono<Boolean> deleteOne02();
@Delete("DELETE FROM ${table} WHERE id = 3")
Mono<Integer> deleteOne03();
@Delete("DELETE FROM ${table} WHERE id = 4")
Completable deleteOne04();
@Delete("DELETE FROM ${table} WHERE id = 5")
Single<Boolean> deleteOne05();
@Delete("DELETE FROM ${table} WHERE id = 6")
Single<Integer> deleteOne06();
@Delete("DELETE FROM ${table} WHERE id = 7")
CompletableFuture<Void> deleteOne07();
@Delete("DELETE FROM ${table} WHERE id = 8")
CompletableFuture<Boolean> deleteOne08();
@Delete("DELETE FROM ${table} WHERE id = 9")
CompletableFuture<Integer> deleteOne09();
@Delete("DELETE FROM ${table} WHERE id = 10")
CompletionStage<Void> deleteOne10();
@Delete("DELETE FROM ${table} WHERE id = 11")
CompletionStage<Boolean> deleteOne11();
@Delete("DELETE FROM ${table} WHERE id = 12")
CompletionStage<Integer> deleteOne12();
// -----------------------------------------------------------------------------------------------------------------
@Delete("DELETE FROM ${table} WHERE id = 13 RETURNING *")
Mono<Product> deleteOne13();
@Delete("DELETE FROM ${table} WHERE id = 14 RETURNING *")
Maybe<Product> deleteOne14();
@Delete("DELETE FROM ${table} WHERE id = 15 RETURNING *")
CompletableFuture<Optional<Product>> deleteOne15();
@Delete("DELETE FROM ${table} WHERE id = 16 RETURNING *")
CompletionStage<Optional<Product>> deleteOne16();
// -----------------------------------------------------------------------------------------------------------------
@Delete("DELETE FROM ${table} WHERE id = 17 RETURNING *")
Mono<List<Product>> deleteMany17();
@Delete("DELETE FROM ${table} WHERE id = 18 RETURNING *")
Flux<Product> deleteMany18();
@Delete("DELETE FROM ${table} WHERE id = 19 RETURNING *")
Single<List<Product>> deleteMany19();
@Delete("DELETE FROM ${table} WHERE id = 20 RETURNING *")
Flowable<Product> deleteMany20();
@Delete("DELETE FROM ${table} WHERE id = 21 RETURNING *")
CompletableFuture<List<Product>> deleteMany21();
@Delete("DELETE FROM ${table} WHERE id = 22 RETURNING *")
CompletionStage<List<Product>> deleteMany22();
}
| 34.928571 | 120 | 0.665389 |
29f94387de8377d29972640d0b5e85e06b347637 | 85 | package ru.krogenit.bfsr.network;
public enum EnumGui {
SelectFaction, Destroyed
}
| 14.166667 | 33 | 0.788235 |
62cb163eb7b7b3165c04b71135c3edffb9f46177 | 1,249 | package com.softonic.instamaterial.domain.model;
public class Photo {
private String id;
private String userId;
private String sourceUrl;
private String description;
private Photo(Builder builder) {
id = builder.id;
userId = builder.userId;
sourceUrl = builder.sourceUrl;
description = builder.description;
}
public String getId() {
return id;
}
public String getUserId() {
return userId;
}
public String getSourceUrl() {
return sourceUrl;
}
public String getDescription() {
return description;
}
public static Builder Builder() {
return new Builder();
}
public static class Builder {
private String id;
private String userId;
private String sourceUrl;
private String description;
public Builder id(String id) {
this.id = id;
return this;
}
public Builder userId(String userId) {
this.userId = userId;
return this;
}
public Builder sourceUrl(String sourceUrl) {
this.sourceUrl = sourceUrl;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Photo build() {
return new Photo(this);
}
}
}
| 18.641791 | 52 | 0.65012 |
7babb63c1d66c92f7892294b6fc55cef4fb6d767 | 1,483 | package com.anthonynsimon.url;
/**
* URLBuilder is a helper class for the construction of a URL object.
*/
final class URLBuilder {
private String scheme;
private String username;
private String password;
private String host;
private String path;
private String rawPath;
private String query;
private String fragment;
private String opaque;
public URL build() {
return new URL(scheme, username, password, host, path, rawPath, query, fragment, opaque);
}
public URLBuilder setScheme(String scheme) {
this.scheme = scheme;
return this;
}
public URLBuilder setUsername(String username) {
this.username = username;
return this;
}
public URLBuilder setPassword(String password) {
this.password = password;
return this;
}
public URLBuilder setHost(String host) {
this.host = host;
return this;
}
public URLBuilder setPath(String path) {
this.path = path;
return this;
}
public URLBuilder setRawPath(String rawPath) {
this.rawPath = rawPath;
return this;
}
public URLBuilder setQuery(String query) {
this.query = query;
return this;
}
public URLBuilder setFragment(String fragment) {
this.fragment = fragment;
return this;
}
public URLBuilder setOpaque(String opaque) {
this.opaque = opaque;
return this;
}
}
| 22.469697 | 97 | 0.627107 |
c023907037a8bc27e622f03168065715060668f1 | 2,168 | package com.yimuyun.lowraiseapp.ui;
import android.content.Intent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.yimuyun.lowraiseapp.R;
import com.yimuyun.lowraiseapp.base.RootActivity;
import com.yimuyun.lowraiseapp.base.contract.UserContract;
import com.yimuyun.lowraiseapp.presenter.UserPresenter;
import org.jsoup.helper.StringUtil;
import butterknife.BindView;
import butterknife.OnClick;
/**
* @author will on 2017/6/10 12:14
* @email pengweiqiang64@163.com
* @description
* @Version
*/
public class LoginActivity extends RootActivity<UserPresenter> implements UserContract.View{
@BindView(R.id.et_user_name)
EditText mEtUserName;
@BindView(R.id.et_password)
EditText mEtPassword;
@BindView(R.id.tv_forget_password)
TextView mTvForgetPassword;
@BindView(R.id.btn_login)
Button mBtnLogin;
@Override
protected int getLayout() {
return R.layout.activity_login;
}
@Override
protected void initEventAndData() {
}
@OnClick(R.id.btn_login)
public void btnLogin(View v){
login();
}
@OnClick(R.id.tv_forget_password)
public void forgetPassword(View v){
Intent intent = new Intent(mContext,ForgetPasswordActivity.class);
startActivity(intent);
}
private void login(){
String userName = mEtUserName.getText().toString().trim();
String password = mEtPassword.getText().toString().trim();
if(StringUtil.isBlank(userName)){
showErrorMsgToast("请输入账号");
mEtUserName.requestFocus();
return;
}
if(StringUtil.isBlank(password)){
showErrorMsgToast("请输入密码");
mEtPassword.requestFocus();
return;
}
stateLoading();
mPresenter.login(userName,password);
}
@Override
protected void initInject() {
getActivityComponent().inject(this);
}
@Override
public void loginSuccess() {
Intent intent = new Intent(mContext,MainActivity.class);
startActivity(intent);
finish();
}
}
| 24.359551 | 92 | 0.674815 |
96560bc8dec394a8d2f2967b2a3d4e6f3e6af44a | 2,428 | /**
* Copyright 2008-2010 Digital Enterprise Research Institute (DERI)
*
* 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.deri.any23.extractor;
import java.io.PrintStream;
import java.util.Collection;
/**
* This interface models an error reporter.
*
* @author Michele Mostarda (michele.mostarda@gmail.com)
*/
public interface ErrorReporter {
/**
* Notifies an error occurred while performing an extraction on an input stream.
*
* @param level error level.
* @param msg error message.
* @param row error row.
* @param col error column.
*/
void notifyError(ErrorLevel level, String msg, int row, int col);
/**
* Prints out an errors report.
*
* @param ps
*/
void printErrorsReport(PrintStream ps);
/**
* Returns all the collected errors.
*
* @return a collection of {@link org.deri.any23.extractor.ErrorReporter.Error}s.
*/
Collection<Error> getErrors();
/**
* Possible error levels.
*/
enum ErrorLevel {
WARN,
ERROR,
FATAL
}
/**
* This class defines a generic error traced by this extraction result.
*/
public class Error {
private ErrorLevel level;
private String message;
private int row, col;
Error(ErrorLevel l, String msg, int r, int c) {
level = l;
message = msg;
row = r;
col = c;
}
public ErrorLevel getLevel() {
return level;
}
public String getMessage() {
return message;
}
public int getRow() {
return row;
}
public int getCol() {
return col;
}
@Override
public String toString() {
return String.format("%s: \t'%s' \t(%d,%d)", level, message, row, col);
}
}
}
| 24.039604 | 85 | 0.59514 |
824de8e852311f7b2fb6125d77533145e81d90a9 | 3,969 | package io.github.yidasanqian;
import io.github.yidasanqian.domain.Order;
import io.github.yidasanqian.domain.User;
import io.github.yidasanqian.utils.JsonUtil;
import io.github.yidasanqian.utils.TypeReference;
import org.junit.Assert;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.Map;
public class JsonUtilTest {
public String parseJson(String name) {
String json = null;
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(getClass()
.getClassLoader()
.getResource(name)
.getFile()
));
StringBuilder builder = new StringBuilder();
String tmp = null;
while ((tmp = reader.readLine()) != null) {
builder.append(tmp);
}
json = builder.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
@Test
public void testToMap() {
String name = "json/user-with-address.json";
String json = parseJson(name);
Map result = JsonUtil.toMap(json);
System.out.println("JsonUtilTest.testToMap: result ==> " + result);
}
@Test
public void testToList() {
String name = "json/array.json";
String json = parseJson(name);
List result = JsonUtil.toList(json);
System.out.println("JsonUtilTest.testToList: result ==> " + result);
}
@Test
public void testToListWithType() {
String name = "json/list.json";
String json = parseJson(name);
TypeReference<List<User>> typeReference = new TypeReference<List<User>>() {
};
List<User> result = JsonUtil.toList(json, typeReference.getType());
for (int i = 0; i < result.size(); i++) {
User user = result.get(i);
System.out.println("JsonUtilTest.testToListWithType: user ==> " + user);
}
}
@Test
public void testToJsonString() {
User user = new User();
user.setId(1);
user.setUsername("yidasanqian");
String result = JsonUtil.toJsonString(user);
System.out.println("JsonUtilTest.testToJsonString: result ==> " + result);
}
@Test
public void testToPojo() {
String json = parseJson("json/user.json");
User user = JsonUtil.toPojo(json, User.class);
System.out.println("JsonUtilTest.testToPojo: user ==> " + user);
}
@Test
public void testConvertToMap() {
String json = parseJson("json/user.json");
User pojoValue = JsonUtil.toPojo(json, User.class);
Map<String, Object> propertyMap = JsonUtil.convertToMap(pojoValue);
System.out.println("JsonUtilTest.testConvertToMap: propertyMap ==> " + propertyMap);
}
@Test
public void testConvertFromMap() {
String json = parseJson("json/user.json");
User pojoValue = JsonUtil.toPojo(json, User.class);
Map<String, Object> propertyMap = JsonUtil.convertToMap(pojoValue);
User user = JsonUtil.convertFromMap(propertyMap, User.class);
System.out.println("JsonUtilTest.testConvertFromMap: user ==> " + user);
}
@Test
public void testDateFormat() {
Date updateAt = new Date();
System.out.println("JacksonTest.testDateFormat: updateAt ==> " + updateAt);
Order order = new Order();
order.setId(1);
order.setTraceNo(110);
order.setUpdateAt(updateAt);
String orderJson = JsonUtil.toJsonWithDateFormat(order, "yyyy年MM月dd日 HH时mm分ss秒");
System.out.println("JacksonTest.testDateFormat: orderJson ==> " + orderJson);
Assert.assertNotNull(orderJson);
}
}
| 33.352941 | 92 | 0.61678 |
341899cb9f5073dd7a79cb898ea5c829155ffa7b | 3,215 | package com.twu.biblioteca;
import java.util.ArrayList;
import java.util.Scanner;
public class BibliotecaApp {
public static User actualUser;
public static User librarian = new User ("000-0000","0","Librarian","librarian@bangalore.com","00000000");
public static void main(String[] args) {
ArrayList<User> userList = new ArrayList<User>();
User user1 = new User("111-1111","1","David Davila","david.davila@thoughtworks.com","09999736900");
User user2 = new User("222-2222","2","Melany Torres","meltorres9@hotmail.com","0999789732");
userList.add(librarian);
userList.add(user1);
userList.add(user2);
Library library = new Library();
library.addItems();
login(userList, library);
}
private static void mainMenu(Library library) {
int optionChosen = 5;
Scanner scanner = new Scanner(System.in);
while (optionChosen != 0) {
showMainMenu();
optionChosen = getOptionChosen(library, scanner);
}
}
public static void login(ArrayList<User> userList, Library library){
Scanner scanner = new Scanner(System.in);
String actualLibraryNumber = "";
while (true) {
System.out.print("Enter your library number: ");
actualLibraryNumber = scanner.next();
for (User user : userList) {
checkLibraryNumber(library, scanner, actualLibraryNumber, user);
}
if(actualUser==null){
System.out.println("Incorrect Information.");
}
}
}
private static void checkLibraryNumber(Library library, Scanner scanner, String actualLibraryNumber, User user) {
if(user.getLibraryNumber().equals(actualLibraryNumber)) {
System.out.print("Enter your password: ");
String actualPassword = scanner.next();
checkPassword(library, user, actualPassword);
}
}
public static void checkPassword(Library library, User user, String actualPassword) {
if (user.getPassword().equals(actualPassword)){
actualUser = user;
System.out.println("Welcome to Biblioteca. Your one-stop-shop for great book titles in Bangalore!\n \n");
mainMenu(library);
}
}
private static int getOptionChosen(Library library, Scanner scanner) {
User user = new User();
int optionChosen;
optionChosen = scanner.nextInt();
switch (optionChosen) {
case 1:
actualUser.optionUserInfo();
break;
case 2:
library.optionBooks();
break;
case 3:
library.optionMovies();
case 0:
System.out.println("Bye!");
break;
default:
System.out.println("Please select a valid option!");
}
return optionChosen;
}
private static void showMainMenu() {
System.out.println("Choose an option to continue:");
System.out.println("1. User Info");
System.out.println("2. Books");
System.out.println("3. Movies");
System.out.println("0. Quit");
}
} | 26.138211 | 117 | 0.596267 |
9b6218303b29aaa7c937aa0275644a2abaf9d07f | 842 | package edu.fiuba.algo3.vista;
import edu.fiuba.algo3.modelo.objetivos.Objetivo;
import edu.fiuba.algo3.modelo.observables.Observer;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
public class VistaObjetivo implements Observer {
private Image imagenObjetivo;
private ImageView view;
private Objetivo objetivo;
public VistaObjetivo(Objetivo objetivo) {
this.objetivo = objetivo;
this.imagenObjetivo = new Image("Objetivo.png");
this.view = new ImageView(imagenObjetivo);
view.setPreserveRatio(true);
view.setFitWidth(100);
view.setFitHeight(100);
}
public ImageView obtenerImagen() {
return this.view;
}
public String obtenerDescripcion() { return objetivo.obtenerDescripcion(); }
@Override
public void update() {}
}
| 26.3125 | 80 | 0.706651 |
46d2d8401aad2d990c6eccf49da5aa58565539c7 | 815 | package xyz.kotlout.kotlout.controller;
import androidx.annotation.NonNull;
/**
* Enum to signify open and closed experiments (published/unpublished)
*/
public enum ExperimentGroup {
OPEN("Open Experiments"),
CLOSED("Closed Experiments");
private final String text;
/**
* Hidden constructor used to store the string representation as part of the enum.
*
* @param text String that the enum should represent.
*/
ExperimentGroup(String text) {
this.text = text;
}
/**
* Used to get enum entries by order.
*
* @param id order of the enum entry.
* @return enum entry.
*/
public static ExperimentGroup getByOrder(int id) {
if (id == 0) {
return OPEN;
}
return CLOSED;
}
@NonNull
@Override
public String toString() {
return text;
}
}
| 18.953488 | 84 | 0.658896 |
7f60749db0f6bc95124986fe2b00a5b22378044b | 3,750 | package au.gov.qld.fire.jms.web.module.job;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import au.gov.qld.fire.jms.domain.job.JobCalendar;
import au.gov.qld.fire.jms.domain.job.JobCalendarItem;
import au.gov.qld.fire.jms.domain.job.JobSearchCriteria;
import au.gov.qld.fire.jms.web.module.AbstractDispatchAction;
import au.gov.qld.fire.web.SessionConstants;
import au.gov.qld.fire.web.WebUtils;
/*
* @author Valeri SHIBAEV (mailto:shibaevv@apollosoft.net)
*/
public class JobCalendarAction extends AbstractDispatchAction
{
/* (non-Javadoc)
* @see au.gov.qld.fire.jms.web.module.AbstractDispatchAction#populateRequest(org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest)
*/
@Override
protected void populateRequest(ActionForm form, HttpServletRequest request) throws Exception
{
//set references
}
/* (non-Javadoc)
* @see au.gov.qld.fire.jms.web.module.AbstractDispatchAction#populateForm(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest)
*/
@Override
protected void populateForm(ActionMapping mapping, ActionForm form, HttpServletRequest request)
throws Exception
{
//Search by FCA, FileNo or Building Name (%)
String fileId = request.getParameter(SessionConstants.FILE_ID);
String fcaId = request.getParameter(SessionConstants.FCA_ID);
JobSearchCriteria criteria = new JobSearchCriteria();
criteria.setFileNo(fileId);
criteria.setFcaNo(fcaId);
JobCalendar entity = new JobCalendar(WebUtils.getYear(request), WebUtils.getMonth(request));
for (List<JobCalendarItem> items : entity.getItems())
{
for (JobCalendarItem item : items)
{
if (item != null)
{
item.setItems(getActionService().findJobActionTodoByDueDate(criteria, item.getDate()));
}
}
}
request.setAttribute(SessionConstants.ENTITIES, entity.getItems());
}
/**
*
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward find(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
LOG.debug("INSIDE find().. ");
try
{
populateRequest(form, request);
populateForm(mapping, form, request);
return mapping.getInputForward();
}
catch (Exception e)
{
saveErrors(request, response, toActionErrors(e));
populateRequest(form, request);
return mapping.getInputForward();
}
}
/**
* Present print.
* @param mapping
* @param form
* @param request
* @param response
* @return
* @throws Exception
*/
public ActionForward print(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception
{
LOG.debug("INSIDE print()..");
try
{
//populateForm(mapping, form, request);
return null;
}
catch (Exception e)
{
saveErrors(request, response, toActionErrors(e));
return null;
}
}
} | 32.608696 | 195 | 0.631733 |
9efa27f729abd538924ff97cd8496afc0fe7ee61 | 905 | import java.io.*;
class maxvowel
{
public static void main()throws IOException
{
String S, W, W1;
int i,j,max,v;
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
System.out.println("Enter String");
S=br.readLine();
W=""; W1="";
S=S+""; max=0;
for(i=0;i<S.length();i++)
{
if (S.charAt(i)==' ')
{
v=0;
for(j=0; j<W.length();j++)
if (W.charAt(j)=='A'||W.charAt(j)=='a'||W.charAt(j)=='E'||W.charAt(j)=='e'||W.charAt(j)=='I'||W.charAt(j)=='i'||W.charAt(j)=='O'||W.charAt(j)=='o'||W.charAt(j)=='U'||W.charAt(j)=='u')
v++;
if (v>max)
{
max=v;
W1=W;
}
W="";
}
W=W+S.charAt(i);
}
System.out.println(W1+"count"+max);
}
}
| 27.424242 | 195 | 0.41105 |
51d7b6735426eeeae3ba1843ac6afdc54d08f70d | 247 | package org.cyy.fw.android.dborm;
/**
* UID generator<BR>
*
* @author d00207889
* @version [RCS Client V100R001C03, 2014-7-1]
*/
public interface UniqueIDGenerator {
/**
* Generate UID
*
* @return UID
*/
Object generateUID();
}
| 13.722222 | 46 | 0.639676 |
fbf63ed9d68258e94e26de843f66baa963caa98b | 2,610 | package com.danielflower.apprunner.runners;
import com.danielflower.apprunner.io.LineConsumer;
import com.danielflower.apprunner.problems.ProjectCannotStartException;
import org.apache.commons.exec.CommandLine;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Model;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.danielflower.apprunner.runners.MavenRunner.loadPomModel;
public class LeinRunner implements AppRunner {
public static final Logger log = LoggerFactory.getLogger(LeinRunner.class);
public static final String[] startCommands = new String[]{"lein do test, uberjar, pom", "java -jar target/{artifactid}-{version}-standalone.jar"};
private final File projectRoot;
private final CommandLineProvider javaCmd;
private final CommandLineProvider leinCmd;
private Killer watchDog;
public LeinRunner(File projectRoot, CommandLineProvider javaCmd, CommandLineProvider leinCmd) {
this.projectRoot = projectRoot;
this.javaCmd = javaCmd;
this.leinCmd = leinCmd;
}
@Override
public File getInstanceDir() {
return projectRoot;
}
public void start(LineConsumer buildLogHandler, LineConsumer consoleLogHandler, Map<String, String> envVarsForApp, Waiter startupWaiter) throws ProjectCannotStartException {
runLein(buildLogHandler, envVarsForApp, "do", "test,", "uberjar,", "pom");
Model model = loadPomModel(new File(projectRoot, "pom.xml"));
String jarName = model.getArtifactId() + "-" + model.getVersion() + "-standalone.jar";
CommandLine command = javaCmd.commandLine(envVarsForApp);
command.addArgument("-jar").addArgument("target" + File.separator + jarName);
watchDog = ProcessStarter.startDaemon(buildLogHandler, consoleLogHandler, envVarsForApp, command, projectRoot, startupWaiter);
}
private void runLein(LineConsumer buildLogHandler, Map<String, String> envVarsForApp, String... arguments) {
CommandLine command = leinCmd.commandLine(envVarsForApp);
for (String argument : arguments)
command.addArgument(argument);
buildLogHandler.consumeLine("Running lein " + StringUtils.join(arguments, " ") + " with " + command);
ProcessStarter.run(buildLogHandler, envVarsForApp, command, projectRoot, TimeUnit.MINUTES.toMillis(20));
}
public void shutdown() {
if (watchDog != null) {
watchDog.destroyProcess();
watchDog.stop();
}
}
}
| 39.545455 | 177 | 0.72682 |
264bd593466f69098e2644931b968bcaaebaf51e | 1,453 | package com.cflint;
import java.math.BigInteger;
public class CFLintStats {
// Epoch timestamp for XML format output
private long timestamp = System.currentTimeMillis() / 1000L;
// Number of files
private long fileCount;
// Number of lines
private BigInteger totalLines = BigInteger.ZERO;
// Bug counts for current execution
private BugCounts counts = new BugCounts();
public CFLintStats() {
super();
}
public CFLintStats(final long timestamp, final long fileCount, final BigInteger totalLines) {
super();
this.timestamp = timestamp;
this.fileCount = fileCount;
this.totalLines = totalLines;
}
public CFLintStats(final long timestamp, final long fileCount, final BigInteger totalLines, final BugCounts counts) {
super();
this.timestamp = timestamp;
this.fileCount = fileCount;
this.totalLines = totalLines;
this.counts = counts;
}
public void addFile(final long numberOfLines) {
fileCount++;
totalLines = totalLines.add(BigInteger.valueOf(numberOfLines));
}
public long getTimestamp() {
return timestamp;
}
public long getFileCount() {
return fileCount;
}
public BigInteger getTotalLines() {
return totalLines;
}
public BugCounts getCounts() {
return counts;
}
}
| 25.946429 | 122 | 0.624226 |
0a68e2ff8eed23641a9e83ca32d3d858c932c09e | 659 | /**
* @Author: KingZhao
*/
package com.jcommerce.core.dao.impl;
import java.util.List;
import com.jcommerce.core.dao.AutoManageDAO;
import com.jcommerce.core.model.AutoManage;
public class AutoManageDAOImpl extends DAOImpl implements AutoManageDAO {
public AutoManageDAOImpl() {
modelClass = AutoManage.class;
}
public List<AutoManage> getAutoManageList() {
return getList();
}
public AutoManage getAutoManage(int id) {
return (AutoManage)getById(id);
}
public void saveAutoManage(AutoManage obj) {
save(obj);
}
public void removeAutoManage(int id) {
deleteById(id);
}
}
| 19.969697 | 73 | 0.676783 |
3e377a9f67875798513c79bc3a6cdf73d63e9d7b | 8,652 | package jflex.core;
import java.io.File;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Set;
import java_cup.runtime.Symbol;
import jflex.core.unicode.CharClasses;
import jflex.core.unicode.ILexScan;
import jflex.core.unicode.UnicodeProperties;
import jflex.l10n.ErrorMessages;
import jflex.logging.Out;
import jflex.scanner.LexicalStates;
import jflex.scanner.ScannerException;
public abstract class AbstractLexScan implements ILexScan {
int bufferSize = 16384;
File file;
private final Deque<File> files = new ArrayDeque<>();
StringBuilder userCode = new StringBuilder();
String classCode;
String initCode;
String initThrow;
String eofCode;
String eofThrow;
String lexThrow;
String eofVal;
public String scanErrorException;
String cupSymbol = "sym";
StringBuilder string = new StringBuilder();
@SuppressWarnings("WeakerAccess") // used in generated LexScan
UnicodeProperties unicodeProperties;
boolean charCount;
boolean lineCount;
boolean columnCount;
boolean cupCompatible;
boolean cup2Compatible;
boolean cupDebug;
boolean isInteger;
boolean isIntWrap;
boolean isPublic;
boolean isFinal;
boolean isAbstract;
boolean bolUsed;
boolean standalone;
boolean debugOption;
boolean eofclose;
String isImplementing;
String isExtending;
String className = "Yylex";
String functionName;
String tokenType;
String visibility = "public";
List<String> ctorArgs = new ArrayList<>();
List<String> ctorTypes = new ArrayList<>();
LexicalStates states = new LexicalStates();
List<Action> actions = new ArrayList<>();
// CharClasses.init() is delayed until UnicodeProperties.init() has been called,
// since the max char code won't be known until then.
final CharClasses charClasses = new CharClasses();
@Override
public UnicodeProperties getUnicodeProperties() {
return unicodeProperties;
}
// TODO(regisd) Return an immutable representation of char classes
@SuppressWarnings("unused") // Used in generated LexParse
public CharClasses getCharClasses() {
return charClasses;
}
public void setFile(File file) {
this.file = file;
}
@SuppressWarnings("unused") // Used in generated LexScan
Symbol symbol(int type, Object value) {
return new Symbol(type, lexLine(), lexColumn(), value);
}
@SuppressWarnings("unused") // Used in generated LexScan
Symbol symbol(int type) {
return new Symbol(type, lexLine(), lexColumn());
}
/**
* Updates line and column count to the beginning of the first non whitespace character in yytext,
* but leaves yyline()+lexColumn() untouched.
*/
@SuppressWarnings("unused") // Used in generated LexScan
Symbol symbol_countUpdate(int type, Object value) {
int lc = lexLine();
int cc = lexColumn();
String text = lexText();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c != '\n' && c != '\r' && c != ' ' && c != '\t') {
return new Symbol(type, lc, cc, value);
}
if (c == '\n') {
lc++;
cc = 0;
} else {
cc++;
}
}
return new Symbol(type, lexLine(), lexColumn(), value);
}
@SuppressWarnings("unused") // Used in generated LexScan
String makeMacroIdent() {
String matched = lexText().trim();
return matched.substring(1, matched.length() - 1).trim();
}
@SuppressWarnings("SameParameterValue") // Generated LexScan uses different parameters
public static String conc(Object a, Object b) {
if (a == null && b == null) {
return null;
}
if (a == null) {
return b.toString();
}
if (b == null) {
return a.toString();
}
return a.toString() + b.toString();
}
public static String concExc(Object a, Object b) {
if (a == null && b == null) {
return null;
}
if (a == null) {
return b.toString();
}
if (b == null) {
return a.toString();
}
return a.toString() + ", " + b.toString();
}
@SuppressWarnings({"unused", "UnusedException"}) // Used in generated LexScan
void populateDefaultVersionUnicodeProperties() {
try {
unicodeProperties = new UnicodeProperties();
} catch (UnicodeProperties.UnsupportedUnicodeVersionException e) {
throw new ScannerException(file, ErrorMessages.UNSUPPORTED_UNICODE_VERSION, lexLine());
}
}
@SuppressWarnings("WeakerAccess") // Used in generated LexScan
void initUnicodeCharClasses() {
charClasses.init(unicodeProperties.getMaximumCodePoint(), this);
}
// Used in generated LexScan
// ScannerException is descriptive enough
@SuppressWarnings({"unused", "UnusedException"})
void includeFile(String filePath) {
File f = new File(file.getParentFile(), filePath);
if (!f.canRead()) {
throw new ScannerException(file, ErrorMessages.NOT_READABLE, lexLine());
}
// check for cycle
if (files.contains(f)) {
throw new ScannerException(file, ErrorMessages.FILE_CYCLE, lexLine());
}
try {
lexPushStream(f);
files.push(file);
file = f;
Out.println("Including \"" + file + "\"");
} catch (IOException e) {
throw new ScannerException(file, ErrorMessages.NOT_READABLE, lexLine());
}
}
@SuppressWarnings("unused") // Used in generated LexScan
File popFile() {
return files.pop();
}
public Iterable<Action> actions() {
return actions;
}
public File file() {
return file;
}
public String classCode() {
return classCode;
}
public String initCode() {
return initCode;
};
public String initThrow() {
return initThrow;
};
public String eofCode() {
return eofCode;
};
public String eofThrow() {
return eofThrow;
};
public String lexThrow() {
return lexThrow;
};
public String eofVal() {
return eofVal;
};
public String scanErrorException() {
return scanErrorException;
};
public String userCode() {
return userCode.toString();
}
public String cupSymbol() {
return cupSymbol;
};
public boolean charCount() {
return charCount;
};
public boolean lineCount() {
return lineCount;
};
public boolean columnCount() {
return columnCount;
};
public boolean cupCompatible() {
return cupCompatible;
};
public boolean cup2Compatible() {
return cup2Compatible;
};
public boolean cupDebug() {
return cupDebug;
};
public boolean isInteger() {
return isInteger;
};
public boolean isIntWrap() {
return isIntWrap;
};
public boolean isPublic() {
return isPublic;
};
public boolean isFinal() {
return isFinal;
};
public boolean isAbstract() {
return isAbstract;
};
public boolean bolUsed() {
return bolUsed;
};
public boolean standalone() {
return standalone;
};
public boolean debugOption() {
return debugOption;
};
public boolean eofclose() {
return eofclose;
};
public String isImplementing() {
return isImplementing;
};
public String isExtending() {
return isExtending;
};
public String className() {
return className;
};
public String functionName() {
return functionName;
};
public String tokenType() {
return tokenType;
};
public String visibility() {
return visibility;
};
public Set<String> stateNames() {
return states.names();
}
public int getStateNumber(String name) {
return states.getNumber(name);
}
public int ctorArgsCount() {
return ctorArgs.size();
}
public String ctorType(int i) {
return ctorTypes.get(i);
}
public String ctorArg(int i) {
return ctorArgs.get(i);
}
public int bufferSize() {
return bufferSize;
}
/**
* Returns the current line number.
*
* @deprecated Use {@link #lexLine} directly.
*/
@Deprecated
public int currentLine() {
return lexLine();
}
@SuppressWarnings("unused") // Used by generated LexScan
/** @deprecated Use {@link #columnCoount} */
@Deprecated
public boolean isColumnCount() {
return columnCount;
}
@SuppressWarnings("WeakerAccess") // Implemented by generated LexScan
protected abstract int lexLine();
@SuppressWarnings("WeakerAccess") // Implemented by generated LexScan
protected abstract int lexColumn();
@SuppressWarnings("WeakerAccess") // Implemented by generated LexScan
protected abstract String lexText();
@SuppressWarnings("WeakerAccess") // Implemented by generated LexScan
protected abstract void lexPushStream(File f) throws IOException;
}
| 22.071429 | 100 | 0.66632 |
4d29893af13020a85bf7b079fe4f35a4434d6c05 | 8,714 | package com.linkedin.thirdeye.tools;
import com.linkedin.thirdeye.anomaly.utils.DetectionResourceHttpUtils;
import com.linkedin.thirdeye.datalayer.bao.AnomalyFunctionManager;
import com.linkedin.thirdeye.datalayer.bao.AutotuneConfigManager;
import com.linkedin.thirdeye.datalayer.dto.AnomalyFunctionDTO;
import com.linkedin.thirdeye.datalayer.dto.AutotuneConfigDTO;
import com.linkedin.thirdeye.datalayer.util.DaoProviderUtil;
import com.linkedin.thirdeye.detector.email.filter.PrecisionRecallEvaluator;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.apache.commons.lang.StringUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class to support fetching results from autotune endpoint, fetching evaluation results from evaluation endpoint
* Also provide ways to write map to csv, read from csv to Map of Strings
*/
public class AutoTuneAlertFilterTool {
private static final Logger LOG = LoggerFactory.getLogger(AutoTuneAlertFilterTool.class);
public static AnomalyFunctionManager anomalyFunctionDAO;
public static AutotuneConfigManager autotuneConfigDAO;
private static final int APPLICATION_PORT = 1867;
private static final String LOCALHOST = "localhost";
private DetectionResourceHttpUtils httpUtils;
public static String CSVSEPERATOR = ",";
public static String CSVESCAPE = ";";
public AutoTuneAlertFilterTool(File persistenceFile, String authToken){
DaoProviderUtil.init(persistenceFile);
anomalyFunctionDAO = DaoProviderUtil
.getInstance(com.linkedin.thirdeye.datalayer.bao.jdbc.AnomalyFunctionManagerImpl.class);
autotuneConfigDAO = DaoProviderUtil
.getInstance(com.linkedin.thirdeye.datalayer.bao.jdbc.AutotuneConfigManagerImpl.class);
httpUtils = new DetectionResourceHttpUtils(LOCALHOST, APPLICATION_PORT, authToken);
}
public static class EvaluationNode{
private Properties alertFilterEval;
private static final String ID = "Id";
private static final String METRICNAME = "metricName";
private static final String ALERTFILTERSTR = "alertFilterStr";
private static final String COLLECTION = "collection";
private static List<String> getHeaders(){
List<String> headers = new ArrayList<>();
headers.addAll(Arrays.asList(COLLECTION, METRICNAME, ID, ALERTFILTERSTR));
headers.addAll(PrecisionRecallEvaluator.getPropertyNames());
return headers;
}
public EvaluationNode(Long Id, String metricName, String collection, String alertFilterStr,
Properties alertFilterEvaluations){
alertFilterEvaluations.put(ID, Id);
alertFilterEvaluations.put(METRICNAME, metricName);
alertFilterEvaluations.put(COLLECTION, collection);
alertFilterEvaluations.put(ALERTFILTERSTR, alertFilterStr);
this.alertFilterEval = alertFilterEvaluations;
}
public String toCSVString(){
StringBuilder res = new StringBuilder();
for(String header : getHeaders()){
res.append(alertFilterEval.get(header))
.append(CSVSEPERATOR);
}
return res.toString();
}
public static String getCSVSchema(){
return StringUtils.join(getHeaders(), CSVSEPERATOR);
}
}
public String getTunedAlertFilterByFunctionId(Long functionId, String startTimeISO, String endTimeISO, String AUTOTUNE_TYPE, String holidayStarts, String holidayEnds) throws Exception{
try {
return httpUtils.runAutoTune(functionId, startTimeISO, endTimeISO, AUTOTUNE_TYPE, holidayStarts, holidayEnds);
} catch (Exception e) {
LOG.warn(e.getMessage());
}
return null;
}
public String evaluateAlertFilterByFunctionId(Long functionId, String startTimeISO, String endTimeISO, String holidayStarts, String holidayEnds){
try{
return httpUtils.getEvalStatsAlertFilter(functionId, startTimeISO, endTimeISO, holidayStarts, holidayEnds);
} catch (Exception e) {
LOG.warn(e.getMessage());
}
return null;
}
public String evaluateAlertFilterByAutoTuneId(Long autotuneId, String startTimeISO, String endTimeISO, String holidayStarts, String holidayEnds){
try{
return httpUtils.evalAutoTune(autotuneId, startTimeISO, endTimeISO, holidayStarts, holidayEnds);
} catch (Exception e){
LOG.warn(e.getMessage());
}
return null;
}
public void writeMapToCSV(Map<String, String> map, String fileName, String headers) throws IOException {
BufferedWriter bw = new BufferedWriter(new FileWriter(fileName));
if (headers != null){
bw.write(headers);
bw.newLine();
}
for (Map.Entry<String, String> pair : map.entrySet()) {
bw.write(pair.getKey() + "," + pair.getValue());
bw.newLine();
}
bw.close();
}
public EvaluationNode evalAnomalyFunctionAlertFilterToEvalNode(Long functionID, String startTimeISO, String endTimeISO, String holidayStarts, String holidayEnds)
throws IOException, JSONException {
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(functionID);
String metricName = anomalyFunctionSpec.getFunctionName();
String collection = anomalyFunctionSpec.getCollection();
String metricAlertFilter = (anomalyFunctionSpec.getAlertFilter() == null)? "null": anomalyFunctionSpec.getAlertFilter().toString().replaceAll(CSVSEPERATOR, CSVESCAPE);
String evals = evaluateAlertFilterByFunctionId(functionID, startTimeISO, endTimeISO, holidayStarts, holidayEnds);
Properties alertFilterEvaluations = jsonStringToProperties(evals);
return new EvaluationNode(functionID, metricName, collection, metricAlertFilter, alertFilterEvaluations);
}
public EvaluationNode evalAutoTunedAlertFilterToEvalNode(Long autotuneId, String startTimeISO, String endTimeISO, String holidayStarts, String holidayEnds) throws IOException, JSONException{
AutotuneConfigDTO autotuneConfigDTO = autotuneConfigDAO.findById(autotuneId);
long functionId = autotuneConfigDTO.getFunctionId();
AnomalyFunctionDTO anomalyFunctionSpec = anomalyFunctionDAO.findById(functionId);
String metricName = anomalyFunctionSpec.getFunctionName();
String collection = anomalyFunctionSpec.getCollection();
String metricAlertFilter = autotuneConfigDTO.getConfiguration().toString().replaceAll(CSVSEPERATOR, CSVESCAPE);
String evals = evaluateAlertFilterByAutoTuneId(autotuneId, startTimeISO, endTimeISO, holidayStarts, holidayEnds);
Properties alertFilterEvaluations = jsonStringToProperties(evals);
return new EvaluationNode(autotuneId, metricName, collection, metricAlertFilter, alertFilterEvaluations);
}
private Properties jsonStringToProperties(String jsonStr) throws JSONException {
Properties res = new Properties();
if (jsonStr != null) {
JSONObject jsonVal = new JSONObject(jsonStr);
Iterator<String> nameltr = jsonVal.keys();
while (nameltr.hasNext()) {
String key = nameltr.next();
String eval = jsonVal.getString(key);
res.put(key, eval);
}
}
return res;
}
public List<Long> getAllFunctionIdsByCollection(String Collection){
List<AnomalyFunctionDTO> anomalyFunctionSpecs = anomalyFunctionDAO.findAllByCollection(Collection);
List<Long> functionIds = new ArrayList<>();
for(AnomalyFunctionDTO anomalyFunctionSpec: anomalyFunctionSpecs){
functionIds.add(anomalyFunctionSpec.getId());
}
return functionIds;
}
public Boolean checkAnomaliesHasLabels(Long functionId, String startTimeISO, String endTimeISO, String holidayStarts, String holidayEnds, String authToken){
DetectionResourceHttpUtils httpUtils = new DetectionResourceHttpUtils(LOCALHOST, APPLICATION_PORT, authToken);
try{
return Boolean.valueOf(httpUtils.checkHasLabels(functionId, startTimeISO, endTimeISO, holidayStarts, holidayEnds));
} catch (Exception e) {
LOG.warn(e.getMessage());
}
return null;
}
public String getInitAutoTuneByFunctionId(Long functionId, String startTimeISO, String endTimeISO, String AUTOTUNE_TYPE, int nExpected,String holidayStarts, String holidayEnds, String authToken) throws Exception{
DetectionResourceHttpUtils httpUtils = new DetectionResourceHttpUtils(LOCALHOST, APPLICATION_PORT, authToken);
try {
return httpUtils.initAutoTune(functionId, startTimeISO, endTimeISO, AUTOTUNE_TYPE, nExpected, holidayStarts, holidayEnds);
} catch (Exception e) {
LOG.warn(e.getMessage());
}
return null;
}
}
| 41.69378 | 214 | 0.765664 |
2ed66c809fd6cc8de91957f7d2221c96f097bcd1 | 3,297 | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.jni.internal.platformmisc;
import java.io.File;
import java.io.IOException;
import com.microsoft.tfs.jni.PlatformMisc;
import com.microsoft.tfs.util.Check;
import com.microsoft.tfs.util.Platform;
/**
* An implementation of the {@link PlatformMisc} interface that uses native
* methods.
*
* @threadsafety thread-safe
*/
public class NativePlatformMisc implements PlatformMisc {
private final PlatformMisc backend;
public NativePlatformMisc() {
if (Platform.isCurrentPlatform(Platform.WINDOWS))
backend = new WindowsNativePlatformMisc();
else if (Platform.isCurrentPlatform(Platform.MAC_OS_X))
backend = new MacOsNativePlatformMisc();
else
backend = new LinuxNativePlatformMisc();
}
@Override
public String getHomeDirectory(final String username) {
Check.notNull(username, "username"); //$NON-NLS-1$
if (Platform.isCurrentPlatform(Platform.GENERIC_UNIX) == false) {
return null;
}
return backend.getHomeDirectory(username);
}
@Override
public boolean changeCurrentDirectory(final String directory) {
Check.notNull(directory, "directory"); //$NON-NLS-1$
if (backend.changeCurrentDirectory(directory)) {
/*
* We must set this variable for Java classes to have any idea that
* the paths have changed. Canonical path is much nicer to
* view/debug, so try that first.
*/
try {
System.setProperty("user.dir", new File(directory).getCanonicalPath()); //$NON-NLS-1$
} catch (final IOException e) {
System.setProperty("user.dir", new File(directory).getAbsolutePath()); //$NON-NLS-1$
}
return true;
}
return false;
}
@Override
public int getDefaultCodePage() {
if (Platform.isCurrentPlatform(Platform.WINDOWS) == false) {
return -1;
}
return backend.getDefaultCodePage();
}
@Override
public String getComputerName() {
final String name = backend.getComputerName();
if (name == null || name.length() == 0) {
return null;
}
return name;
}
@Override
public String getEnvironmentVariable(final String name) {
Check.notNullOrEmpty(name, "name"); //$NON-NLS-1$
String value = backend.getEnvironmentVariable(name);
return value == null || value.length() == 0 ? null : value;
}
@Override
public String expandEnvironmentString(final String value) {
Check.notNull(value, "value"); //$NON-NLS-1$
if (Platform.isCurrentPlatform(Platform.WINDOWS) == false) {
return value;
}
return backend.expandEnvironmentString(value);
}
@Override
public String getCurrentIdentityUser() {
return backend.getCurrentIdentityUser();
}
@Override
public String getWellKnownSID(final int wellKnownSIDType, final String domainSIDString) {
return backend.getWellKnownSID(wellKnownSIDType, domainSIDString);
}
}
| 28.921053 | 101 | 0.636336 |
76bfe762e0095dc6e9868488179aed914c1258e7 | 6,407 | package org.basex.core.cmd;
import static org.basex.core.Text.*;
import static org.basex.util.Token.*;
import org.basex.core.*;
import org.basex.query.path.*;
import org.basex.util.*;
import org.basex.util.list.*;
/**
* Evaluates the 'find' command and processes a simplified request as XQuery.
*
* @author BaseX Team 2005-13, BSD License
* @author Christian Gruen
*/
public final class Find extends AQuery {
/** Start from root node. */
private final boolean root;
/**
* Default constructor.
* @param query simplified query
*/
public Find(final String query) {
this(query, false);
}
/**
* Default constructor.
* @param query simplified query
* @param rt start from root node
*/
public Find(final String query, final boolean rt) {
super(Perm.NONE, true, query);
root = rt;
}
@Override
protected boolean run() {
final String query = find(args[0], context, root);
final boolean ok = query(query);
final StringBuilder sb = new StringBuilder();
if(options.get(MainOptions.QUERYINFO)) {
sb.append(NL).append(QUERY_CC).append(NL).append(query).append(NL);
}
sb.append(info());
error(sb.toString());
return ok;
}
@Override
public boolean updating(final Context ctx) {
return updating(ctx, find(args[0], ctx, root));
}
@Override
public void databases(final LockResult lr) {
lr.read.add(DBLocking.CTX);
}
/**
* Creates an XQuery representation for the specified query.
* @param query query
* @param ctx database context
* @param root start from root node
* @return query
*/
public static String find(final String query, final Context ctx, final boolean root) {
// treat input as XQuery
if(query.startsWith("/")) return query;
final boolean r = root || ctx.root();
if(query.isEmpty()) return r ? "/" : ".";
// parse user input
final String qu = query.replaceAll(" \\+", " ");
final String[] terms = split(qu);
String pre = "";
String preds = "";
for(String term : terms) {
if(term.startsWith("@=")) {
preds += "[@* = \"" + term.substring(2) + "\"]";
} else if(term.startsWith("=")) {
preds += "[text() = \"" + term.substring(1) + "\"]";
} else if(term.startsWith("~")) {
preds += "[text() contains text \"" + term.substring(1) +
"\" using fuzzy]";
} else if(term.startsWith("@")) {
if(term.length() == 1) continue;
preds += "[@* contains text \"" + term.substring(1) + "\"]";
term = term.substring(1);
// add valid name tests
if(XMLToken.isName(token(term))) {
pre += (r ? "" : ".") + "//@" + term + " | ";
}
} else {
preds += "[text() contains text \"" + term + "\"]";
// add valid name tests
if(XMLToken.isName(token(term))) {
pre += (r ? "/" : "") + Axis.DESC + "::*:" + term + " | ";
}
}
}
if(pre.isEmpty() && preds.isEmpty()) return root ? "/" : ".";
// create final string
final TokenBuilder tb = new TokenBuilder();
final String tag = "*";
tb.add(pre + (r ? "/" : "") + Axis.DESCORSELF + "::" + tag + preds);
return tb.toString();
}
/**
* Creates an XQuery representation for the specified table query.
* @param filter filter terms
* @param cols filter columns
* @param elem element flag
* @param tag root tag
* @param root root flag
* @return query
*/
public static String findTable(final StringList filter, final TokenList cols, final BoolList elem,
final byte[] tag, final boolean root) {
final TokenBuilder tb = new TokenBuilder();
final int is = filter.size();
for(int i = 0; i < is; ++i) {
final String[] spl = split(filter.get(i));
for(final String s : spl) {
byte[] term = token(s);
if(contains(term, '"')) term = replace(term, '"', ' ');
term = trim(term);
if(term.length == 0) continue;
tb.add('[');
final boolean elm = elem.get(i);
tb.add(elm ? ".//" : "@");
tb.add("*:");
tb.add(cols.get(i));
if(term[0] == '<' || term[0] == '>') {
tb.add(term[0]);
tb.addLong(calcNum(substring(term, 1)));
} else {
tb.add(" contains text \"");
tb.add(term);
tb.add('"');
}
tb.add(']');
}
}
return tb.isEmpty() ? "/" : (root ? "/" : "") +
Axis.DESCORSELF + "::*:" + string(tag) + tb;
}
/**
* Returns an long value for the specified token. The suffixes "kb", "mb"
* and "gb" are considered in the calculation.
* @param tok token to be converted
* @return long
*/
private static long calcNum(final byte[] tok) {
int tl = tok.length;
final int s1 = tok.length < 1 ? 0 : lc(tok[tl - 1]);
final int s2 = tok.length < 2 ? 0 : lc(tok[tl - 2]);
int f = 0;
// evaluate suffixes
if(s1 == 'k') { tl -= 1; f = 10; }
if(s1 == 'm') { tl -= 1; f = 20; }
if(s1 == 'g') { tl -= 1; f = 30; }
if(s1 == 'b' && s2 == 'k') { tl -= 2; f = 10; }
if(s1 == 'b' && s2 == 'm') { tl -= 2; f = 20; }
if(s1 == 'b' && s2 == 'g') { tl -= 2; f = 30; }
final long i = toLong(tok, 0, tl) << f;
return i == Long.MIN_VALUE ? 0 : i;
}
/**
* Splits the string and returns an array.
* @param str string to be split
* @return array
*/
private static String[] split(final String str) {
final int l = str.length();
final String[] split = new String[l];
int s = 0;
char delim = 0;
final StringBuilder sb = new StringBuilder();
for(int i = 0; i < l; ++i) {
final char c = str.charAt(i);
if(delim == 0) {
if(c == '\'' || c == '"') {
delim = c;
} else if(!XMLToken.isChar(c) && c != '@' && c != '='
&& c != '<' && c != '>' && c != '~') {
if(sb.length() != 0) {
split[s++] = sb.toString();
sb.setLength(0);
}
} else {
sb.append(c);
}
} else {
if(c == delim) {
delim = 0;
if(sb.length() != 0) {
split[s++] = sb.toString();
sb.setLength(0);
}
} else {
if(c != '\'' && c != '"') sb.append(c);
}
}
}
if(sb.length() != 0) split[s++] = sb.toString();
return Array.copyOf(split, s);
}
}
| 28.730942 | 100 | 0.518495 |
19331cbaffd5f26a646d851250eddb1e099ebb84 | 499 | package com.github.cyc.wanandroid.http;
/**
* HTTP码
*/
public interface HttpCode {
/**
* 成功
*/
int SUCCESS = 0;
/**
* 未知错误
*/
int ERROR_UNKNOWN = 1000;
/**
* HTTP错误
*/
int ERROR_HTTP = 1001;
/**
* 网络错误
*/
int ERROR_NETWORK = 1002;
/**
* 解析错误
*/
int ERROR_PARSE = 1003;
/**
* SSL错误
*/
int ERROR_SSL = 1004;
/**
* 登录失效,需要重新登录
*/
int ERROR_LOGIN_INVALID = -1001;
}
| 11.340909 | 39 | 0.448898 |
a2dc515daf5807e48f164c4eef35d53506602116 | 5,256 | package org.naddeo.elm.parser;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Assert;
import org.junit.Before;
import org.naddeo.elm.StreamSizeData;
import org.naddeo.elm.TestData;
import org.naddeo.elm.lang.LiteralFactory;
import java_cup.runtime.Symbol;
import static java.lang.String.format;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.naddeo.elm.parser.GeneratedSymbolClassMatcher.returnsClass;
import static org.naddeo.elm.parser.StreamSizeMatcher.containsThisMany;
public abstract class BaseGrammarTest
{
public static final LiteralFactory LITERAL_FACTORY = new LiteralFactory();
private static final String _parseFailMsg = "'%s' rule did not accept the following valid input:\n%s";
private static final String _displayFailMsg = "'%s' rule's pojo did not produce a valid, parsable graphql string:\n%s";
private boolean previouslyInitialized = false;
protected abstract ForcedStatement getTestedRule();
private ElmParser parser = null;
private OutputStream output = null;
@Before
public void _init() throws IOException
{
previouslyInitialized = true;
PipedInputStream input = new PipedInputStream();
output = new PipedOutputStream(input);
parser = new ElmParser(new ElmLexer(new InputStreamReader(input)));
}
private Symbol parse(String input) throws Exception
{
output.write(input.getBytes());
output.close();
return parser.parse();
}
private String parseFailMessage(String input)
{
return format(_parseFailMsg, getTestedRule().rule, input);
}
private String displayFailMessage(String input)
{
return format(_displayFailMsg, getTestedRule().rule, input);
}
private Symbol assertCan(String query, Function<String, String> messageFunction)
{
throwIfNotInitialized();
Symbol symbol = null;
try {
symbol = parse(getTestedRule().create(query));
} catch (Exception e) {
e.printStackTrace();
Assert.fail(messageFunction.apply(query));
}
return symbol;
}
/**
* Assert that a graphql query can be parsed
* @param query a graphql query
* @return the output of the parser
*/
Symbol assertCanParse(String query)
{
return assertCan(query, this::parseFailMessage);
}
/**
* Same as {@link #assertCanParse(String)}, except the error message is worded
* around parsing the string that was generated by {@link Displayable#getDisplay()}.
* @param query a graphql string that was generated by calling {@link Displayable#getDisplay()}
* @return the output of the parser
*/
private Symbol assertCanDisplay(String query)
{
return assertCan(query, this::displayFailMessage);
}
protected static Collection<TestData[]> parameterize(TestData[] data)
{
return Arrays.stream(data).map(d -> new TestData[]{d}).collect(Collectors.toList());
}
protected <T> Symbol assertCanParse(TestData<T> data)
{
Symbol symbol = assertCanParse(data.getTest().getParserInput());
assertThat(assertMessage(), symbol, returnsClass(data.getTest().getExpectedClass()));
assertThat(assertMessage(), symbol.value, equalTo(data.getTest().getPojoValue()));
assertStreamSizes(data);
return symbol;
}
/**
* Assert that a given GraphQL pojo's toDisplay method returns a valid, parsable graphql string.
* @param data current test case
*/
<T> void assertCanDisplay(TestData<T> data)
{
// TODO remove this if check once everything implements the Displayable interface
// This will mean that every object is tested in both directions, from parsing to printing.
if (data.getTest().getPojoValue() instanceof Displayable) {
Displayable displayable = (Displayable) data.getTest().getPojoValue();
String graphQL = displayable.getDisplay();
assertCanDisplay(graphQL);
}
}
/**
* Assert that each of the stream functions returns the expected number of results
* @param data The data to test
*/
private <T> void assertStreamSizes(TestData<T> data)
{
for (StreamSizeData<T> entry : data.getTest().getStreamSizes()) {
Stream stream = entry.getStreamFunction().apply(data.getTest().getPojoValue());
assertThat(entry.toString(), stream, containsThisMany(entry.getExpectedResults(), entry.getStreamReturnType()));
}
}
private String assertMessage()
{
return String.format("grammar rule '%s': ", getTestedRule().rule);
}
private void throwIfNotInitialized()
{
if (!previouslyInitialized) {
throw new IllegalStateException("super.init() was never called. This should go an @Before method.");
}
}
}
| 33.265823 | 124 | 0.684932 |
ec3538facb34f3f05166af983a1bb2fc81f44927 | 705 | package rlbot;
import rlbot.manager.BotManager;
import rlbot.manager.BotManagerSocket;
import rlbot.pyinterop.SocketServer;
/**
* See JavaAgent.py for usage instructions
*/
public class JavaExample {
public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalArgumentException("You must pass in a port as an argument!");
}
int pythonInteropPort = Integer.parseInt(args[0]); // 24008 currently set in python
BotManager flatBotManager = new BotManagerSocket();
flatBotManager.setRefreshRate(120);
SocketServer server = new SamplePythonInterface(pythonInteropPort, flatBotManager);
server.start();
}
}
| 27.115385 | 91 | 0.695035 |
fa201a6455d045645ef7c2c1ab51e7b067e2572f | 2,130 | package crazypants.enderio.machine.farm;
import java.util.UUID;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.network.play.client.C15PacketClientSettings;
import net.minecraft.server.management.ItemInWorldManager;
import net.minecraft.stats.StatBase;
import net.minecraft.util.ChunkCoordinates;
import net.minecraft.util.DamageSource;
import net.minecraft.util.IChatComponent;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import com.mojang.authlib.GameProfile;
import cpw.mods.fml.common.FMLCommonHandler;
public class FakeFarmPlayer extends EntityPlayerMP {
private static final UUID uuid = UUID.fromString("c1ddfd7f-120a-4437-8b64-38660d3ec62d");
private static GameProfile DUMMY_PROFILE = new GameProfile(uuid, "[EioFarmer]");
public FakeFarmPlayer(WorldServer world) {
super(FMLCommonHandler.instance().getMinecraftServerInstance(), world, DUMMY_PROFILE, new ItemInWorldManager(world));
}
@Override
public boolean canCommandSenderUseCommand(int i, String s) {
return false;
}
@Override
public ChunkCoordinates getPlayerCoordinates() {
return new ChunkCoordinates(0, 0, 0);
}
@Override
public void addChatComponentMessage(IChatComponent chatmessagecomponent) {
}
@Override
public void addStat(StatBase par1StatBase, int par2) {
}
@Override
public void openGui(Object mod, int modGuiId, World world, int x, int y, int z) {
}
@Override
public boolean isEntityInvulnerable() {
return true;
}
@Override
public boolean canAttackPlayer(EntityPlayer player) {
return false;
}
@Override
public void onDeath(DamageSource source) {
return;
}
@Override
public void onUpdate() {
return;
}
@Override
public void travelToDimension(int dim) {
return;
}
@Override
public void func_147100_a(C15PacketClientSettings pkt) {
return;
}
@Override
public boolean canPlayerEdit(int par1, int par2, int par3, int par4, ItemStack par5ItemStack) {
return true;
}
}
| 24.204545 | 121 | 0.756338 |
ee0ea110cf82d4250ddd0d85227672b3e10c0bb6 | 13,183 | /**
*/
package substationStandard.LNNodes.LNGroupY.impl;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import substationStandard.Dataclasses.DPC;
import substationStandard.Dataclasses.INS;
import substationStandard.Dataclasses.SPC;
import substationStandard.Enumerations.SwitchingCapabilityKind;
import substationStandard.LNNodes.LNGroupY.LNGroupYPackage;
import substationStandard.LNNodes.LNGroupY.YPSH;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>YPSH</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getOpTmh <em>Op Tmh</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getPos <em>Pos</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getBlkOpn <em>Blk Opn</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getBlkCls <em>Blk Cls</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getChaMotEna <em>Cha Mot Ena</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getShOpCap <em>Sh Op Cap</em>}</li>
* <li>{@link substationStandard.LNNodes.LNGroupY.impl.YPSHImpl#getMaxOpCap <em>Max Op Cap</em>}</li>
* </ul>
*
* @generated
*/
public class YPSHImpl extends GroupYImpl implements YPSH {
/**
* The cached value of the '{@link #getOpTmh() <em>Op Tmh</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getOpTmh()
* @generated
* @ordered
*/
protected INS opTmh;
/**
* The cached value of the '{@link #getPos() <em>Pos</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getPos()
* @generated
* @ordered
*/
protected DPC pos;
/**
* The cached value of the '{@link #getBlkOpn() <em>Blk Opn</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBlkOpn()
* @generated
* @ordered
*/
protected SPC blkOpn;
/**
* The cached value of the '{@link #getBlkCls() <em>Blk Cls</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBlkCls()
* @generated
* @ordered
*/
protected SPC blkCls;
/**
* The cached value of the '{@link #getChaMotEna() <em>Cha Mot Ena</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getChaMotEna()
* @generated
* @ordered
*/
protected SPC chaMotEna;
/**
* The default value of the '{@link #getShOpCap() <em>Sh Op Cap</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShOpCap()
* @generated
* @ordered
*/
protected static final SwitchingCapabilityKind SH_OP_CAP_EDEFAULT = SwitchingCapabilityKind.NONE;
/**
* The cached value of the '{@link #getShOpCap() <em>Sh Op Cap</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getShOpCap()
* @generated
* @ordered
*/
protected SwitchingCapabilityKind shOpCap = SH_OP_CAP_EDEFAULT;
/**
* The default value of the '{@link #getMaxOpCap() <em>Max Op Cap</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMaxOpCap()
* @generated
* @ordered
*/
protected static final SwitchingCapabilityKind MAX_OP_CAP_EDEFAULT = SwitchingCapabilityKind.NONE;
/**
* The cached value of the '{@link #getMaxOpCap() <em>Max Op Cap</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getMaxOpCap()
* @generated
* @ordered
*/
protected SwitchingCapabilityKind maxOpCap = MAX_OP_CAP_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected YPSHImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return LNGroupYPackage.Literals.YPSH;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public INS getOpTmh() {
if (opTmh != null && opTmh.eIsProxy()) {
InternalEObject oldOpTmh = (InternalEObject)opTmh;
opTmh = (INS)eResolveProxy(oldOpTmh);
if (opTmh != oldOpTmh) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupYPackage.YPSH__OP_TMH, oldOpTmh, opTmh));
}
}
return opTmh;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public INS basicGetOpTmh() {
return opTmh;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setOpTmh(INS newOpTmh) {
INS oldOpTmh = opTmh;
opTmh = newOpTmh;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__OP_TMH, oldOpTmh, opTmh));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DPC getPos() {
if (pos != null && pos.eIsProxy()) {
InternalEObject oldPos = (InternalEObject)pos;
pos = (DPC)eResolveProxy(oldPos);
if (pos != oldPos) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupYPackage.YPSH__POS, oldPos, pos));
}
}
return pos;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DPC basicGetPos() {
return pos;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setPos(DPC newPos) {
DPC oldPos = pos;
pos = newPos;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__POS, oldPos, pos));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SPC getBlkOpn() {
if (blkOpn != null && blkOpn.eIsProxy()) {
InternalEObject oldBlkOpn = (InternalEObject)blkOpn;
blkOpn = (SPC)eResolveProxy(oldBlkOpn);
if (blkOpn != oldBlkOpn) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupYPackage.YPSH__BLK_OPN, oldBlkOpn, blkOpn));
}
}
return blkOpn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SPC basicGetBlkOpn() {
return blkOpn;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBlkOpn(SPC newBlkOpn) {
SPC oldBlkOpn = blkOpn;
blkOpn = newBlkOpn;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__BLK_OPN, oldBlkOpn, blkOpn));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SPC getBlkCls() {
if (blkCls != null && blkCls.eIsProxy()) {
InternalEObject oldBlkCls = (InternalEObject)blkCls;
blkCls = (SPC)eResolveProxy(oldBlkCls);
if (blkCls != oldBlkCls) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupYPackage.YPSH__BLK_CLS, oldBlkCls, blkCls));
}
}
return blkCls;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SPC basicGetBlkCls() {
return blkCls;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBlkCls(SPC newBlkCls) {
SPC oldBlkCls = blkCls;
blkCls = newBlkCls;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__BLK_CLS, oldBlkCls, blkCls));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SPC getChaMotEna() {
if (chaMotEna != null && chaMotEna.eIsProxy()) {
InternalEObject oldChaMotEna = (InternalEObject)chaMotEna;
chaMotEna = (SPC)eResolveProxy(oldChaMotEna);
if (chaMotEna != oldChaMotEna) {
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, LNGroupYPackage.YPSH__CHA_MOT_ENA, oldChaMotEna, chaMotEna));
}
}
return chaMotEna;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SPC basicGetChaMotEna() {
return chaMotEna;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setChaMotEna(SPC newChaMotEna) {
SPC oldChaMotEna = chaMotEna;
chaMotEna = newChaMotEna;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__CHA_MOT_ENA, oldChaMotEna, chaMotEna));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SwitchingCapabilityKind getShOpCap() {
return shOpCap;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setShOpCap(SwitchingCapabilityKind newShOpCap) {
SwitchingCapabilityKind oldShOpCap = shOpCap;
shOpCap = newShOpCap == null ? SH_OP_CAP_EDEFAULT : newShOpCap;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__SH_OP_CAP, oldShOpCap, shOpCap));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public SwitchingCapabilityKind getMaxOpCap() {
return maxOpCap;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setMaxOpCap(SwitchingCapabilityKind newMaxOpCap) {
SwitchingCapabilityKind oldMaxOpCap = maxOpCap;
maxOpCap = newMaxOpCap == null ? MAX_OP_CAP_EDEFAULT : newMaxOpCap;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, LNGroupYPackage.YPSH__MAX_OP_CAP, oldMaxOpCap, maxOpCap));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case LNGroupYPackage.YPSH__OP_TMH:
if (resolve) return getOpTmh();
return basicGetOpTmh();
case LNGroupYPackage.YPSH__POS:
if (resolve) return getPos();
return basicGetPos();
case LNGroupYPackage.YPSH__BLK_OPN:
if (resolve) return getBlkOpn();
return basicGetBlkOpn();
case LNGroupYPackage.YPSH__BLK_CLS:
if (resolve) return getBlkCls();
return basicGetBlkCls();
case LNGroupYPackage.YPSH__CHA_MOT_ENA:
if (resolve) return getChaMotEna();
return basicGetChaMotEna();
case LNGroupYPackage.YPSH__SH_OP_CAP:
return getShOpCap();
case LNGroupYPackage.YPSH__MAX_OP_CAP:
return getMaxOpCap();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case LNGroupYPackage.YPSH__OP_TMH:
setOpTmh((INS)newValue);
return;
case LNGroupYPackage.YPSH__POS:
setPos((DPC)newValue);
return;
case LNGroupYPackage.YPSH__BLK_OPN:
setBlkOpn((SPC)newValue);
return;
case LNGroupYPackage.YPSH__BLK_CLS:
setBlkCls((SPC)newValue);
return;
case LNGroupYPackage.YPSH__CHA_MOT_ENA:
setChaMotEna((SPC)newValue);
return;
case LNGroupYPackage.YPSH__SH_OP_CAP:
setShOpCap((SwitchingCapabilityKind)newValue);
return;
case LNGroupYPackage.YPSH__MAX_OP_CAP:
setMaxOpCap((SwitchingCapabilityKind)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case LNGroupYPackage.YPSH__OP_TMH:
setOpTmh((INS)null);
return;
case LNGroupYPackage.YPSH__POS:
setPos((DPC)null);
return;
case LNGroupYPackage.YPSH__BLK_OPN:
setBlkOpn((SPC)null);
return;
case LNGroupYPackage.YPSH__BLK_CLS:
setBlkCls((SPC)null);
return;
case LNGroupYPackage.YPSH__CHA_MOT_ENA:
setChaMotEna((SPC)null);
return;
case LNGroupYPackage.YPSH__SH_OP_CAP:
setShOpCap(SH_OP_CAP_EDEFAULT);
return;
case LNGroupYPackage.YPSH__MAX_OP_CAP:
setMaxOpCap(MAX_OP_CAP_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case LNGroupYPackage.YPSH__OP_TMH:
return opTmh != null;
case LNGroupYPackage.YPSH__POS:
return pos != null;
case LNGroupYPackage.YPSH__BLK_OPN:
return blkOpn != null;
case LNGroupYPackage.YPSH__BLK_CLS:
return blkCls != null;
case LNGroupYPackage.YPSH__CHA_MOT_ENA:
return chaMotEna != null;
case LNGroupYPackage.YPSH__SH_OP_CAP:
return shOpCap != SH_OP_CAP_EDEFAULT;
case LNGroupYPackage.YPSH__MAX_OP_CAP:
return maxOpCap != MAX_OP_CAP_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (ShOpCap: ");
result.append(shOpCap);
result.append(", MaxOpCap: ");
result.append(maxOpCap);
result.append(')');
return result.toString();
}
} //YPSHImpl
| 25.158397 | 124 | 0.654176 |
a1000fd10f29fa75d80b0a6c636ec99fe52e973e | 2,541 | /*
* Copyright 2012 Cyril A. Karpenko
*
* 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.redshape.ui.components;
import com.redshape.ui.Dispatcher;
import com.redshape.ui.application.UnhandledUIException;
import com.redshape.ui.application.events.AppEvent;
import com.redshape.ui.application.events.EventType;
import com.redshape.ui.application.events.IEventHandler;
import com.redshape.utils.ILambda;
import com.redshape.utils.InvocationException;
import org.apache.log4j.Logger;
import javax.swing.*;
import java.awt.event.ActionEvent;
public class InteractionAction extends AbstractAction {
private static final Logger log = Logger.getLogger(InteractionAction.class);
private static final long serialVersionUID = 323352518927504082L;
private AppEvent event;
private IEventHandler handler;
public InteractionAction( String name, IEventHandler handler ) {
this(name, (EventType) null );
this.handler = handler;
}
public InteractionAction( String name, EventType type ) {
this( name, new AppEvent( type ) );
}
public InteractionAction( String name, AppEvent event ) {
super(name);
this.event = event;
}
@Override
public void actionPerformed( ActionEvent e ) {
try {
if ( this.handler == null ) {
Dispatcher.get().forwardEvent( this.event );
} else {
this.handler.handle( new AppEvent(null, e.getSource() ) );
}
} catch ( Throwable ex ) {
log.error( ex.getMessage(), ex );
}
}
public static <T, V> InteractionAction createAction( String name,
final T context, final ILambda<V> fn ) {
return new InteractionAction(name,
new IEventHandler() {
private static final long serialVersionUID = 3043897656511284411L;
@Override
public void handle(AppEvent event) {
try {
fn.invoke( context, event );
} catch ( InvocationException e ) {
throw new UnhandledUIException( e.getMessage(), e );
}
}
}
);
}
}
| 29.546512 | 80 | 0.69697 |
f40a5f09516c93c1cfb65c1bf2bef221843a360d | 7,528 | /**
* The MIT License (MIT)
*
* Copyright (c) 2018 hover-raft (tools4j), Anton Anufriev, Marco Terzer
*
* 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 org.dev4fx.raft.state;
import org.agrona.MutableDirectBuffer;
import org.dev4fx.raft.log.api.PersistentState;
import org.dev4fx.raft.sbe.*;
import org.dev4fx.raft.timer.Timer;
import org.dev4fx.raft.transport.Publisher;
import org.slf4j.Logger;
import java.util.Objects;
import java.util.function.BiFunction;
public class AppendRequestHandler implements BiFunction<AppendRequestDecoder, Logger, Transition> {
private final PersistentState persistentState;
private final VolatileState volatileState;
private final Timer electionTimeout;
private final MessageHeaderEncoder messageHeaderEncoder;
private final AppendResponseEncoder appendResponseEncoder;
private final MutableDirectBuffer encoderBuffer;
private final Publisher publisher;
private final int serverId;
public AppendRequestHandler(final PersistentState persistentState,
final VolatileState volatileState,
final Timer electionTimeout,
final MessageHeaderEncoder messageHeaderEncoder,
final AppendResponseEncoder appendResponseEncoder,
final MutableDirectBuffer encoderBuffer,
final Publisher publisher,
final int serverId) {
this.persistentState = Objects.requireNonNull(persistentState);
this.volatileState = Objects.requireNonNull(volatileState);
this.electionTimeout = Objects.requireNonNull(electionTimeout);
this.messageHeaderEncoder = Objects.requireNonNull(messageHeaderEncoder);
this.appendResponseEncoder = Objects.requireNonNull(appendResponseEncoder);
this.encoderBuffer = Objects.requireNonNull(encoderBuffer);
this.publisher = Objects.requireNonNull(publisher);
this.serverId = serverId;
}
@Override
public Transition apply(final AppendRequestDecoder appendRequestDecoder, final Logger logger) {
final HeaderDecoder header = appendRequestDecoder.header();
final int appendRequestTerm = header.term();
final int leaderId = header.sourceId();
final int currentTerm = persistentState.currentTerm();
final LogKeyDecoder prevLogKeyDecoder = appendRequestDecoder.prevLogKey();
final long requestPrevIndex = prevLogKeyDecoder.index();
final int requestPrevTermAtIndex = prevLogKeyDecoder.term();
final boolean successful;
long matchLogIndex = -1;
if (appendRequestTerm < currentTerm) {
successful = false;
} else {
final long leaderCommitIndex = appendRequestDecoder.commitLogIndex();
final LogContainment containment = persistentState.contains(requestPrevIndex, requestPrevTermAtIndex);
switch (containment) {
case IN:
matchLogIndex = appendToLog(requestPrevIndex, appendRequestDecoder, logger);
//From paper: If leaderCommit > commitIndex, set commitIndex =
// min(leaderCommit, index of last new entry).
// I think, "index of last new entry" implies not empty persistentState entries.
if (leaderCommitIndex > volatileState.commitIndex()) {
volatileState.commitIndex(Long.min(leaderCommitIndex, matchLogIndex));
}
successful = true;
break;
case OUT:
successful = false;
break;
case CONFLICT:
persistentState.truncate(requestPrevIndex);
successful = false;
break;
default:
throw new IllegalStateException("Unknown LogContainment " + containment);
}
electionTimeout.restart();
}
final int headerLength = messageHeaderEncoder.wrap(encoderBuffer, 0)
.schemaId(AppendResponseEncoder.SCHEMA_ID)
.version(AppendResponseEncoder.SCHEMA_VERSION)
.blockLength(AppendResponseEncoder.BLOCK_LENGTH)
.templateId(AppendResponseEncoder.TEMPLATE_ID)
.encodedLength();
appendResponseEncoder.wrap(encoderBuffer, headerLength)
.header()
.destinationId(leaderId)
.sourceId(serverId)
.term(currentTerm);
appendResponseEncoder
.matchLogIndex(matchLogIndex)
.prevLogIndex(requestPrevIndex)
.successful(successful ? BooleanType.T : BooleanType.F);
publisher.publish(encoderBuffer, 0, headerLength + appendResponseEncoder.encodedLength());
return Transition.STEADY;
}
private long appendToLog(final long prevLogIndex, final AppendRequestDecoder appendRequestDecoder, final Logger logger) {
long nextIndex = prevLogIndex;
for (final AppendRequestDecoder.LogEntriesDecoder logEntryDecoder : appendRequestDecoder.logEntries()) {
nextIndex++;
final int nextTermAtIndex = logEntryDecoder.term();
final int commandHeaderLength = AppendRequestDecoder.LogEntriesDecoder.commandHeaderLength();
final int offset = appendRequestDecoder.limit() + commandHeaderLength;
final int length = logEntryDecoder.commandLength();
final LogContainment containment = persistentState.contains(nextIndex, nextTermAtIndex);
switch (containment) {
case OUT:
persistentState.append(nextTermAtIndex,
appendRequestDecoder.buffer(),
offset,
length);
//logger.info("Appended index {}, term {}, offset {}, length {}", nextIndex, nextTermAtIndex, offset, length);
break;
case IN:
//logger.info("Skipped index {}, term {}", nextIndex, nextTermAtIndex);
break;
default:
throw new IllegalStateException("Should not be in conflict");
}
appendRequestDecoder.limit(offset + length);
}
return nextIndex;
}
}
| 45.902439 | 130 | 0.649442 |
ff2c1471adc85f5693155ba312f780e6a131d518 | 2,161 | package org.apache.maven.surefire.its;
/*
* 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.
*/
import com.googlecode.junittoolbox.ParallelParameterized;
import org.apache.maven.surefire.its.fixture.Settings;
import org.apache.maven.surefire.its.fixture.SurefireLauncher;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized.Parameters;
import java.util.Arrays;
/**
* JUnit test project using multiple method patterns, including wildcards in class and method names.
*/
@RunWith( ParallelParameterized.class )
public class TestMultipleMethodPatternsIT
extends AbstractTestMultipleMethodPatterns
{
private final Settings settings;
public TestMultipleMethodPatternsIT( Settings settings )
{
this.settings = settings;
}
@Parameters
public static Iterable<Object[]> data()
{
return Arrays.asList( new Object[][]{
{ Settings.JUNIT4_TEST },
{ Settings.JUNIT47_TEST },
{ Settings.JUNIT4_INCLUDES },
{ Settings.JUNIT47_INCLUDES },
{ Settings.JUNIT4_INCLUDES_EXCLUDES },
{ Settings.JUNIT47_INCLUDES_EXCLUDES }
} );
}
@Override
protected Settings getSettings()
{
return settings;
}
@Override
protected SurefireLauncher unpack()
{
return unpack( "junit48-multiple-method-patterns", "_" + settings.path() );
}
}
| 31.318841 | 100 | 0.710782 |
d9c604fd683f784da80296328d335581d6c662c1 | 1,058 | package Application.UI;
import Application.Constants;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class AlertPopUp {
private static Stage window;
public static void display(String message) {
window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
VBox layout = new VBox(10);
Label label = new Label(message);
Button ok = new Button(Constants.OK.getValue());
ok.setOnAction(e -> close());
layout.getChildren().addAll(label, ok);
layout.setAlignment(Pos.CENTER);
layout.setPadding(new Insets(10));
//use this for just one component
//layout.setMargin(child, value);
Scene scene = new Scene(layout);
ok.setMinSize(50, 30);
window.setMinWidth(250);
window.setScene(scene);
window.setTitle(Constants.ALERT.getValue());
window.show();
}
private static void close() {
window.close();
}
}
| 24.604651 | 50 | 0.73724 |
c412fd686bfab95cd5032bf5ce4461fee101f33d | 357 | package com.dev.kolun.alex.binservlet.util;
import lombok.experimental.UtilityClass;
import java.time.Instant;
@UtilityClass
public class TimeUtil {
public static long startTime() {
return Instant.now().toEpochMilli();
}
public static long endTime(long startTime) {
return Instant.now().toEpochMilli() - startTime;
}
}
| 18.789474 | 56 | 0.70028 |
97575865b22f8ef470e006276b7e765eadccfdd0 | 22,866 | /*
*/
package gov.osti.connectors.github;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import gov.osti.connectors.GitHub;
import java.util.Date;
/**
*
* @author ensornl
*/
@JsonIgnoreProperties (ignoreUnknown = true)
public class Repository {
/** attributes **/
private Long id;
private String name=null;
@JsonProperty("full_name")
private String fullName = null;
private Owner owner = null;
@JsonProperty("private")
private Boolean isPrivate = false;
@JsonProperty("html_url")
private String htmlUrl = null;
private String description = null;
@JsonProperty("fork")
private Boolean isFork = false;
private String url = null;
@JsonProperty("forks_url")
private String forksUrl = null;
@JsonProperty("collaborators_url")
private String collaboratorsUrl = null;
@JsonProperty("teams_url")
private String teamsUrl = null;
@JsonProperty("hooks_url")
private String hooksUrl = null;
@JsonProperty("issue_events_url")
private String issueEventsUrl = null;
@JsonProperty("events_url")
private String eventsUrl = null;
@JsonProperty("assignees_url")
private String assigneesUrl = null;
@JsonProperty("branches_url")
private String branchesUrl = null;
@JsonProperty("tags_url")
private String tagsUrl = null;
@JsonProperty("blobs_url")
private String blobsUrl = null;
@JsonProperty("git_tags_url")
private String gitTagsUrl = null;
@JsonProperty("git_refs_url")
private String gitReferencesUrl = null;
@JsonProperty("trees_url")
private String treesUrl = null;
@JsonProperty("statuses_url")
private String statusesUrl = null;
@JsonProperty("languages_url")
private String languagesUrl = null;
@JsonProperty("contributors_url")
private String contributorsUrl = null;
@JsonProperty("commits_url")
private String commitsUrl = null;
@JsonProperty("comments_url")
private String commentsUrl = null;
@JsonProperty("archive_url")
private String archiveUrl = null;
@JsonProperty("downloads_url")
private String downloadsUrl = null;
@JsonProperty("issues_url")
private String issuesUrl = null;
@JsonProperty("pulls_url")
private String pullsUrl = null;
@JsonProperty("notifications_url")
private String notificationsUrl = null;
@JsonProperty("labels_url")
private String labelsUrl = null;
@JsonProperty("releases_url")
private String releasesUrl = null;
@JsonProperty("created_at")
private Date dateCreated = null;
@JsonProperty("updated_at")
private Date dateUpdated = null;
@JsonProperty("pushed_at")
private Date datePushed = null;
@JsonProperty("git_url")
private String gitUrl = null;
@JsonProperty("ssh_url")
private String sshUrl = null;
@JsonProperty("clone_url")
private String cloneUrl = null;
@JsonProperty("svn_url")
private String svnUrl = null;
private String homepage = null;
private Long size = 0L;
private String language = null;
@JsonProperty("has_issues")
private Boolean hasIssues = false;
@JsonProperty("has_wiki")
private Boolean hasWiki = false;
@JsonProperty("has_downloads")
private Boolean hasDownloads = false;
@JsonProperty("has_pages")
private Boolean hasPages = false;
private Integer forks = 0;
@JsonProperty("open_issues_count")
private Integer openIssuesCount = 0;
@JsonProperty("open_issues")
private Integer openIssues = 0;
@JsonProperty("default_branch")
private String defaultBranch = null;
@JsonProperty("network_count")
private Integer networkCount = 0;
@JsonProperty("subscribers_count")
private Integer subscribersCount = 0;
private Organization organization = null;
public Repository() {
}
/**
* Get the unique github ID.
* @return the id the ID
*/
public Long getId() {
return id;
}
/**
* Set a unique ID value
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* Get the repository name.
* @return the name
*/
public String getName() {
return name;
}
/**
* Set a repository name.
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* The Owner information for this repository.
*
* @return the owner information
*/
public Owner getOwner() {
return owner;
}
/**
* Set an Owner reference for this repository.
*
* @param owner the owner to set
*/
public void setOwner(Owner owner) {
this.owner = owner;
}
/**
* Whether or not this repository is "private".
* @return the isPrivate
*/
public Boolean getIsPrivate() {
return isPrivate;
}
/**
* @param isPrivate the isPrivate to set
*/
public void setIsPrivate(Boolean isPrivate) {
this.isPrivate = isPrivate;
}
/**
* the HTML URL if any.
* @return the URL to the HTML description/project page
*/
public String getHtmlUrl() {
return htmlUrl;
}
/**
* @param htmlUrl the htmlUrl to set
*/
public void setHtmlUrl(String htmlUrl) {
this.htmlUrl = htmlUrl;
}
/**
* A description of the github repository project.
* @return the description
*/
public String getDescription() {
return description;
}
/**
* Set a description for the repository.
*
* @param description the description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Has this project been forked?
* @return true if forked, false if not
*/
public Boolean getIsFork() {
return isFork;
}
/**
* Set whether or not this project has been forked.
* @param isFork set whether or not the project was forked
*/
public void setIsFork(Boolean isFork) {
this.isFork = isFork;
}
/**
* The base reference URL for the repository.
*
* @return the url
*/
public String getUrl() {
return url;
}
/**
* Set a base reference URL.
*
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* URL for information about project forks, if any
* @return the forksUrl
*/
public String getForksUrl() {
return forksUrl;
}
/**
* @param forksUrl the forksUrl to set
*/
public void setForksUrl(String forksUrl) {
this.forksUrl = forksUrl;
}
/**
* URL to API call for retrieving collaborator information for this project.
*
* @return the collaboratorsUrl
*/
public String getCollaboratorsUrl() {
return collaboratorsUrl;
}
/**
* @param collaboratorsUrl the collaboratorsUrl to set
*/
public void setCollaboratorsUrl(String collaboratorsUrl) {
this.collaboratorsUrl = collaboratorsUrl;
}
/**
* URL to API call referencing team information, if any
* @return the teamsUrl
*/
public String getTeamsUrl() {
return teamsUrl;
}
/**
* @param teamsUrl the teamsUrl to set
*/
public void setTeamsUrl(String teamsUrl) {
this.teamsUrl = teamsUrl;
}
/**
* @return the hooksUrl
*/
public String getHooksUrl() {
return hooksUrl;
}
/**
* @param hooksUrl the hooksUrl to set
*/
public void setHooksUrl(String hooksUrl) {
this.hooksUrl = hooksUrl;
}
/**
* @return the issueEventsUrl
*/
public String getIssueEventsUrl() {
return issueEventsUrl;
}
/**
* @param issueEventsUrl the issueEventsUrl to set
*/
public void setIssueEventsUrl(String issueEventsUrl) {
this.issueEventsUrl = issueEventsUrl;
}
/**
* @return the eventsUrl
*/
public String getEventsUrl() {
return eventsUrl;
}
/**
* @param eventsUrl the eventsUrl to set
*/
public void setEventsUrl(String eventsUrl) {
this.eventsUrl = eventsUrl;
}
/**
* @return the assigneesUrl
*/
public String getAssigneesUrl() {
return assigneesUrl;
}
/**
* @param assigneesUrl the assigneesUrl to set
*/
public void setAssigneesUrl(String assigneesUrl) {
this.assigneesUrl = assigneesUrl;
}
/**
* @return the branchesUrl
*/
public String getBranchesUrl() {
return branchesUrl;
}
/**
* @param branchesUrl the branchesUrl to set
*/
public void setBranchesUrl(String branchesUrl) {
this.branchesUrl = branchesUrl;
}
/**
* @return the tagsUrl
*/
public String getTagsUrl() {
return tagsUrl;
}
/**
* @param tagsUrl the tagsUrl to set
*/
public void setTagsUrl(String tagsUrl) {
this.tagsUrl = tagsUrl;
}
/**
* @return the blobsUrl
*/
public String getBlobsUrl() {
return blobsUrl;
}
/**
* @param blobsUrl the blobsUrl to set
*/
public void setBlobsUrl(String blobsUrl) {
this.blobsUrl = blobsUrl;
}
/**
* @return the gitTagsUrl
*/
public String getGitTagsUrl() {
return gitTagsUrl;
}
/**
* @param gitTagsUrl the gitTagsUrl to set
*/
public void setGitTagsUrl(String gitTagsUrl) {
this.gitTagsUrl = gitTagsUrl;
}
/**
* @return the gitReferencesUrl
*/
public String getGitReferencesUrl() {
return gitReferencesUrl;
}
/**
* @param gitReferencesUrl the gitReferencesUrl to set
*/
public void setGitReferencesUrl(String gitReferencesUrl) {
this.gitReferencesUrl = gitReferencesUrl;
}
/**
* @return the treesUrl
*/
public String getTreesUrl() {
return treesUrl;
}
/**
* @param treesUrl the treesUrl to set
*/
public void setTreesUrl(String treesUrl) {
this.treesUrl = treesUrl;
}
/**
* @return the statusesUrl
*/
public String getStatusesUrl() {
return statusesUrl;
}
/**
* @param statusesUrl the statusesUrl to set
*/
public void setStatusesUrl(String statusesUrl) {
this.statusesUrl = statusesUrl;
}
/**
* @return the languagesUrl
*/
public String getLanguagesUrl() {
return languagesUrl;
}
/**
* @param languagesUrl the languagesUrl to set
*/
public void setLanguagesUrl(String languagesUrl) {
this.languagesUrl = languagesUrl;
}
/**
* @return the contributorsUrl
*/
public String getContributorsUrl() {
return contributorsUrl;
}
/**
* @param contributorsUrl the contributorsUrl to set
*/
public void setContributorsUrl(String contributorsUrl) {
this.contributorsUrl = contributorsUrl;
}
/**
* @return the commitsUrl
*/
public String getCommitsUrl() {
return commitsUrl;
}
/**
* @param commitsUrl the commitsUrl to set
*/
public void setCommitsUrl(String commitsUrl) {
this.commitsUrl = commitsUrl;
}
/**
* @return the commentsUrl
*/
public String getCommentsUrl() {
return commentsUrl;
}
/**
* @param commentsUrl the commentsUrl to set
*/
public void setCommentsUrl(String commentsUrl) {
this.commentsUrl = commentsUrl;
}
/**
* @return the archiveUrl
*/
public String getArchiveUrl() {
return archiveUrl;
}
/**
* @param archiveUrl the archiveUrl to set
*/
public void setArchiveUrl(String archiveUrl) {
this.archiveUrl = archiveUrl;
}
/**
* @return the downloadsUrl
*/
public String getDownloadsUrl() {
return downloadsUrl;
}
/**
* @param downloadsUrl the downloadsUrl to set
*/
public void setDownloadsUrl(String downloadsUrl) {
this.downloadsUrl = downloadsUrl;
}
/**
* @return the issuesUrl
*/
public String getIssuesUrl() {
return issuesUrl;
}
/**
* @param issuesUrl the issuesUrl to set
*/
public void setIssuesUrl(String issuesUrl) {
this.issuesUrl = issuesUrl;
}
/**
* @return the pullsUrl
*/
public String getPullsUrl() {
return pullsUrl;
}
/**
* @param pullsUrl the pullsUrl to set
*/
public void setPullsUrl(String pullsUrl) {
this.pullsUrl = pullsUrl;
}
/**
* @return the notificationsUrl
*/
public String getNotificationsUrl() {
return notificationsUrl;
}
/**
* @param notificationsUrl the notificationsUrl to set
*/
public void setNotificationsUrl(String notificationsUrl) {
this.notificationsUrl = notificationsUrl;
}
/**
* @return the labelsUrl
*/
public String getLabelsUrl() {
return labelsUrl;
}
/**
* @param labelsUrl the labelsUrl to set
*/
public void setLabelsUrl(String labelsUrl) {
this.labelsUrl = labelsUrl;
}
/**
* @return the releasesUrl
*/
public String getReleasesUrl() {
return releasesUrl;
}
/**
* @param releasesUrl the releasesUrl to set
*/
public void setReleasesUrl(String releasesUrl) {
this.releasesUrl = releasesUrl;
}
/**
* @return the dateCreated
*/
public Date getDateCreated() {
return dateCreated;
}
/**
* @param dateCreated the dateCreated to set
*/
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
/**
* @return the dateUpdated
*/
public Date getDateUpdated() {
return dateUpdated;
}
/**
* @param dateUpdated the dateUpdated to set
*/
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
/**
* @return the datePushed
*/
public Date getDatePushed() {
return datePushed;
}
/**
* @param datePushed the datePushed to set
*/
public void setDatePushed(Date datePushed) {
this.datePushed = datePushed;
}
/**
* @return the gitUrl
*/
public String getGitUrl() {
return gitUrl;
}
/**
* @param gitUrl the gitUrl to set
*/
public void setGitUrl(String gitUrl) {
this.gitUrl = gitUrl;
}
/**
* @return the sshUrl
*/
public String getSshUrl() {
return sshUrl;
}
/**
* @param sshUrl the sshUrl to set
*/
public void setSshUrl(String sshUrl) {
this.sshUrl = sshUrl;
}
/**
* @return the cloneUrl
*/
public String getCloneUrl() {
return cloneUrl;
}
/**
* @param cloneUrl the cloneUrl to set
*/
public void setCloneUrl(String cloneUrl) {
this.cloneUrl = cloneUrl;
}
/**
* @return the svnUrl
*/
public String getSvnUrl() {
return svnUrl;
}
/**
* @param svnUrl the svnUrl to set
*/
public void setSvnUrl(String svnUrl) {
this.svnUrl = svnUrl;
}
/**
* @return the homepage
*/
public String getHomepage() {
return homepage;
}
/**
* @param homepage the homepage to set
*/
public void setHomepage(String homepage) {
this.homepage = homepage;
}
/**
* @return the size
*/
public Long getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(Long size) {
this.size = size;
}
/**
* @return the language
*/
public String getLanguage() {
return language;
}
/**
* @param language the language to set
*/
public void setLanguage(String language) {
this.language = language;
}
/**
* @return the hasIssues
*/
public Boolean getHasIssues() {
return hasIssues;
}
/**
* @param hasIssues the hasIssues to set
*/
public void setHasIssues(Boolean hasIssues) {
this.hasIssues = hasIssues;
}
/**
* @return the hasWiki
*/
public Boolean getHasWiki() {
return hasWiki;
}
/**
* @param hasWiki the hasWiki to set
*/
public void setHasWiki(Boolean hasWiki) {
this.hasWiki = hasWiki;
}
/**
* @return the hasDownloads
*/
public Boolean getHasDownloads() {
return hasDownloads;
}
/**
* @param hasDownloads the hasDownloads to set
*/
public void setHasDownloads(Boolean hasDownloads) {
this.hasDownloads = hasDownloads;
}
/**
* @return the hasPages
*/
public Boolean getHasPages() {
return hasPages;
}
/**
* @param hasPages the hasPages to set
*/
public void setHasPages(Boolean hasPages) {
this.hasPages = hasPages;
}
/**
* @return the forks
*/
public Integer getForks() {
return forks;
}
/**
* @param forks the forks to set
*/
public void setForks(Integer forks) {
this.forks = forks;
}
/**
* @return the openIssuesCount
*/
public Integer getOpenIssuesCount() {
return openIssuesCount;
}
/**
* @param openIssuesCount the openIssuesCount to set
*/
public void setOpenIssuesCount(Integer openIssuesCount) {
this.openIssuesCount = openIssuesCount;
}
/**
* @return the openIssues
*/
public Integer getOpenIssues() {
return openIssues;
}
/**
* @param openIssues the openIssues to set
*/
public void setOpenIssues(Integer openIssues) {
this.openIssues = openIssues;
}
/**
* @return the defaultBranch
*/
public String getDefaultBranch() {
return defaultBranch;
}
/**
* @param defaultBranch the defaultBranch to set
*/
public void setDefaultBranch(String defaultBranch) {
this.defaultBranch = defaultBranch;
}
/**
* @return the networkCount
*/
public Integer getNetworkCount() {
return networkCount;
}
/**
* @param networkCount the networkCount to set
*/
public void setNetworkCount(Integer networkCount) {
this.networkCount = networkCount;
}
/**
* @return the subscribersCount
*/
public Integer getSubscribersCount() {
return subscribersCount;
}
/**
* @param subscribersCount the subscribersCount to set
*/
public void setSubscribersCount(Integer subscribersCount) {
this.subscribersCount = subscribersCount;
}
/**
* @return the organization
*/
public Organization getOrganization() {
return organization;
}
/**
* @param organization the organization to set
*/
public void setOrganization(Organization organization) {
this.organization = organization;
}
/**
* @return the fullName
*/
public String getFullName() {
return fullName;
}
/**
* @param fullName the fullName to set
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}
}
| 24.990164 | 84 | 0.511239 |
965c1131215ef230b6e00b7bbd112fc20f4ac2c1 | 980 | package de.uni_freiburg.informatik.dbis.sempala.translator.op;
import com.hp.hpl.jena.shared.PrefixMapping;
import com.hp.hpl.jena.sparql.algebra.op.OpDistinct;
import de.uni_freiburg.informatik.dbis.sempala.translator.ImpalaOpVisitor;
import de.uni_freiburg.informatik.dbis.sempala.translator.Tags;
import de.uni_freiburg.informatik.dbis.sempala.translator.sql.SQLStatement;
/**
*
* @author Antony Neu
*/
public class ImpalaDistinct extends ImpalaOp1 {
// TODO: Proper implementation
@SuppressWarnings("unused")
private final OpDistinct opDistinct;
public ImpalaDistinct(OpDistinct _opDistinct, ImpalaOp _subOp,
PrefixMapping _prefixes) {
super(_subOp, _prefixes);
opDistinct = _opDistinct;
resultName = Tags.DISTINCT;
}
@Override
public void visit(ImpalaOpVisitor impalaOpVisitor) {
impalaOpVisitor.visit(this);
}
@Override
public SQLStatement translate(String name, SQLStatement child) {
// TODO Auto-generated method stub
return null;
}
}
| 25.128205 | 75 | 0.786735 |
03784dd117e4f2ab8139e1337b4e6cda0e3160fa | 6,215 | package com.xncoding.pos.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
/**
* RabbitConfig
*最核心的类就是RabbitMQ的配置类,在里面定制模版类、声明交换机、队列、绑定交换机到队列。
* @author XiongNeng
* @version 1.0
* @since 2018/3/1
*/
@Configuration
public class RabbitConfig {
@Resource
private RabbitTemplate rabbitTemplate;
/**
* 定制化amqp模版 可根据需要定制多个
* <p>
* <p>
* 此处为模版类定义 Jackson消息转换器
* ConfirmCallback接口用于实现消息发送到RabbitMQ交换器后接收ack回调 即消息发送到exchange ack
* ReturnCallback接口用于实现消息发送到RabbitMQ 交换器,但无相应队列与交换器绑定时的回调 即消息发送不到任何一个队列中 ack
*
* @return the amqp template
*/
// @Primary
@Bean
public AmqpTemplate amqpTemplate() {
Logger log = LoggerFactory.getLogger(RabbitTemplate.class);
// 使用jackson 消息转换器
rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());
rabbitTemplate.setEncoding("UTF-8");
// 用于确认消息是否成功路由到相关队列,消息发送失败返回到队列中,yml需要配置 publisher-returns: true
rabbitTemplate.setMandatory(true);
rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
String correlationId = message.getMessageProperties().getCorrelationId();
log.debug("消息:{} 发送失败, 应答码:{} 原因:{} 交换机: {} 路由键: {}", correlationId, replyCode, replyText, exchange, routingKey);
System.out.println("消息:"+correlationId+" 发送失败, 应答码:"+replyCode+" 原因:"+replyText+" 交换机: "+exchange+" 路由键: "+routingKey);
});
// 用于确认消息是否成功发送到exchange,yml需要配置 publisher-confirms: true
rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
if (ack) {
log.debug("消息发送到exchange成功,id: {}", correlationData.getId());
System.out.println("消息发送到exchange成功,id: "+ correlationData.getId());
} else {
log.debug("消息发送到exchange失败,原因: {}", cause);
System.out.println("消息发送到exchange失败,原因: " + cause);
}
});
return rabbitTemplate;
}
/* ----------------------------------------------------------------------------Direct exchange test--------------------------------------------------------------------------- */
/**
* 声明Direct交换机 支持持久化.
*
* @return the exchange
*/
@Bean("directExchange")
public Exchange directExchange() {
return ExchangeBuilder.directExchange("DIRECT_EXCHANGE").durable(true).build();//durable字段表示持久化
}//durable字段表示持久化
/**
* 声明一个队列 支持持久化.
*
* @return the queue
*/
@Bean("directQueue")
public Queue directQueue() {
return QueueBuilder.durable("DIRECT_QUEUE").build();
}//durable字段表示持久化
/**
* 通过绑定键 将指定队列绑定到一个指定的交换机.
*
* @param queue the queue
* @param exchange the exchange
* @return the binding
*/
@Bean
public Binding directBinding(@Qualifier("directQueue") Queue queue,
@Qualifier("directExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("DIRECT_ROUTING_KEY").noargs();
}
/* ----------------------------------------------------------------------------Fanout exchange test--------------------------------------------------------------------------- */
/**
* 声明 fanout 交换机.
*
* @return the exchange
*/
@Bean("fanoutExchange")
public FanoutExchange fanoutExchange() {
return (FanoutExchange) ExchangeBuilder.fanoutExchange("FANOUT_EXCHANGE").durable(true).build();//durable字段表示持久化
}
/**
* Fanout queue A.
*
* @return the queue
*/
@Bean("fanoutQueueA")
public Queue fanoutQueueA() {
return QueueBuilder.durable("FANOUT_QUEUE_A").build();
}
/**
* Fanout queue B .
*
* @return the queue
*/
@Bean("fanoutQueueB")
public Queue fanoutQueueB() {
return QueueBuilder.durable("FANOUT_QUEUE_B").build();
}
/**
* 绑定队列A 到Fanout 交换机.
*
* @param queue the queue
* @param fanoutExchange the fanout exchange
* @return the binding
*/
@Bean
public Binding bindingA(@Qualifier("fanoutQueueA") Queue queue,
@Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue).to(fanoutExchange);
}
/**
* 绑定队列B 到Fanout 交换机.
*
* @param queue the queue
* @param fanoutExchange the fanout exchange
* @return the binding
*/
@Bean
public Binding bindingB(@Qualifier("fanoutQueueB") Queue queue,
@Qualifier("fanoutExchange") FanoutExchange fanoutExchange) {
return BindingBuilder.bind(queue).to(fanoutExchange);
}
/* ----------------------------------------------------------------------------top exchange test--------------------------------------------------------------------------- */
/**
* 声明top交换机 支持持久化.
*
* @return the exchange
*/
@Bean("topExchange")
public TopicExchange topExchange() {
return (TopicExchange)ExchangeBuilder.topicExchange("TOP_EXCHANGE").durable(true).build();//durable字段表示持久化
}
/**
* 声明一个队列 支持持久化.
*
* @return the queue
*/
@Bean("topQueue")
public Queue topQueue() {
return QueueBuilder.durable("TOP_QUEUE").build();
}
/**
* 通过绑定键 将指定队列绑定到一个指定的交换机.
*
* @param queue the queue
* @param exchange the exchange
* @return the binding
*/
@Bean
public Binding topBinding(@Qualifier("topQueue") Queue queue,
@Qualifier("topExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("TOP_ROUTING_KEY.#").noargs();//#是允许匹配多个单词,*是匹配一个单词
}
}
| 31.709184 | 181 | 0.580692 |
78e6383bdc52cfae3005324774936dfefe71e75c | 5,581 | package org.broadinstitute.ddp.model.user;
import java.io.Serializable;
import java.time.LocalDate;
import java.time.ZoneId;
import org.jdbi.v3.core.mapper.reflect.ColumnName;
import org.jdbi.v3.core.mapper.reflect.JdbiConstructor;
public class UserProfile implements Serializable {
private long userId;
private String firstName;
private String lastName;
private SexType sexType;
private LocalDate birthDate;
private Long preferredLangId;
private String preferredLangCode;
private ZoneId timeZone;
private Boolean doNotContact;
private Boolean isDeceased;
private Boolean skipLanguagePopup;
@JdbiConstructor
public UserProfile(@ColumnName("user_id") long userId,
@ColumnName("first_name") String firstName,
@ColumnName("last_name") String lastName,
@ColumnName("sex") SexType sexType,
@ColumnName("birth_date") LocalDate birthDate,
@ColumnName("preferred_language_id") Long preferredLangId,
@ColumnName("iso_language_code") String preferredLangCode,
@ColumnName("time_zone") ZoneId timeZone,
@ColumnName("do_not_contact") Boolean doNotContact,
@ColumnName("is_deceased") Boolean isDeceased,
@ColumnName("skip_language_popup") Boolean skipLanguagePopup) {
this.userId = userId;
this.firstName = firstName;
this.lastName = lastName;
this.sexType = sexType;
this.birthDate = birthDate;
this.preferredLangId = preferredLangId;
this.preferredLangCode = preferredLangCode;
this.timeZone = timeZone;
this.doNotContact = doNotContact;
this.isDeceased = isDeceased;
this.skipLanguagePopup = skipLanguagePopup;
}
public long getUserId() {
return userId;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public SexType getSexType() {
return sexType;
}
public LocalDate getBirthDate() {
return birthDate;
}
public Long getPreferredLangId() {
return preferredLangId;
}
public String getPreferredLangCode() {
return preferredLangCode;
}
public ZoneId getTimeZone() {
return timeZone;
}
public Boolean getDoNotContact() {
return doNotContact;
}
public Boolean getIsDeceased() {
return isDeceased;
}
public Boolean getSkipLanguagePopup() {
return skipLanguagePopup;
}
public enum SexType {
FEMALE, MALE, INTERSEX, PREFER_NOT_TO_ANSWER
}
public static class Builder {
private UserProfile profile;
public Builder(long userId) {
profile = new UserProfile(userId, null, null, null, null, null, null, null, null, null, null);
}
public Builder(UserProfile other) {
profile = new UserProfile(
other.getUserId(),
other.getFirstName(),
other.getLastName(),
other.getSexType(),
other.getBirthDate(),
other.getPreferredLangId(),
other.getPreferredLangCode(),
other.getTimeZone(),
other.getDoNotContact(),
other.getIsDeceased(),
other.getSkipLanguagePopup());
}
public Builder setFirstName(String firstName) {
profile.firstName = firstName;
return this;
}
public Builder setLastName(String lastName) {
profile.lastName = lastName;
return this;
}
public Builder setSexType(SexType sexType) {
profile.sexType = sexType;
return this;
}
public Builder setBirthDate(LocalDate birthDate) {
profile.birthDate = birthDate;
return this;
}
public Builder setPreferredLangId(Long preferredLangId) {
profile.preferredLangId = preferredLangId;
// This one is not really being used when creating new profile objects,
// so null it out so we don't have a mismatch with lang id.
profile.preferredLangCode = null;
return this;
}
public Builder setTimeZone(ZoneId timeZone) {
profile.timeZone = timeZone;
return this;
}
public Builder setDoNotContact(Boolean doNotContact) {
profile.doNotContact = doNotContact;
return this;
}
public Builder setIsDeceased(Boolean isDeceased) {
profile.isDeceased = isDeceased;
return this;
}
public Builder setSkipLanguagePopup(Boolean skipLanguagePopup) {
profile.skipLanguagePopup = skipLanguagePopup;
return this;
}
public UserProfile build() {
return new UserProfile(
profile.userId,
profile.firstName,
profile.lastName,
profile.sexType,
profile.birthDate,
profile.preferredLangId,
profile.preferredLangCode,
profile.timeZone,
profile.doNotContact,
profile.isDeceased,
profile.skipLanguagePopup);
}
}
}
| 30.497268 | 106 | 0.583766 |
ab8828d8e7e6660911d6b2243dae7f469a7ac04d | 1,466 | package com.tal.file.transform.controller.media.en;
import com.tal.file.transform.controller.media.Mct;
import com.tal.file.transform.common.storage.StorageFile;
import com.tal.file.transform.common.storage.StorageZone;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class EnMct implements Mct {
protected static final Logger log = LoggerFactory.getLogger(EnMct.class);
@Autowired
StorageZone zone;
@Autowired
MctPipeline pipeline;
@Autowired
MctPresets presets;
@Override
public long getDuration(String storPath) {
StorageFile file = zone.lookup(storPath);
return pipeline.getDuration(file.getFullPath());
}
@Override
public String transfer(String storPath, String pipeline, String preset, String mime) {
StorageFile srcFile = zone.lookup(storPath);
StorageFile targetFile = zone.create(storPath + Mct.KEY_TRANSFER);
this.pipeline.transfer(srcFile.getFullPath(), targetFile.getFullPath(), preset, mime);
return targetFile.getUrl();
}
@Override
public String thumbnail(String storPath, String mime) {
StorageFile srcFile = zone.lookup(storPath);
StorageFile targetFile = zone.create(storPath + Mct.KEY_THUMBNAIL);
pipeline.thumbnail(srcFile.getFullPath(), targetFile.getFullPath(), mime);
return targetFile.getUrl();
}
}
| 27.148148 | 89 | 0.755116 |
4649343cdc2e20ee6067bf303fba12a4ec5fcb3c | 3,766 | package com.awarematics.postmedia.transform;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
//import org.postgresql.pljava.annotation.Function;
import org.apache.commons.io.FileUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.locationtech.jts.geom.Coordinate;
import com.awarematics.postmedia.mgeom.MGeometryFactory;
import com.awarematics.postmedia.types.mediamodel.MDouble;
import com.awarematics.postmedia.types.mediamodel.MPoint;
import com.awarematics.postmedia.types.mediamodel.MVideo;
public class InsertBddData {
static double[] coordinate1_x;
static double[] coordinate1_y;
static long[] timeArray;
static double[] doubleaccx;
static double[] doubleaccy;
static double[] doubleaccz;
static double[] doublegyrox;
static double[] doublegyroy;
static double[] doublegyroz;
static MPoint mp = null;
static MVideo mv = null;
static MDouble mb = null;
// int num = 1;
public static void main(String args[]) throws IOException {
String[] result = new String[112];
//BddDataToPostgre("D://train/", "mpoint");
//String[] result = new String[4325];
String writerContent = "";
for (int i = 0; i < result.length; i++) {
writerContent = writerContent + "insert into trackMDB (id, licence, type, model) values( " + (i + 1) + ", 'mt" + String.format("%04d", i+1)+"','passanger',"+"'car"
+ "');";
}
File file = new File("D:\\insertmpoint_track.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter writer = new FileWriter(file);
writer.write(writerContent);
writer.flush();
writer.close();
}
// @Function
public static String[] BddDataToPostgre(String uri, String type) throws IOException {
String[] bdd = null;
ArrayList<String> bddString = new ArrayList<String>();
for (int numof = 1; numof <= 69926; numof++) {
long[] timeArray;
try {
File file = new File(uri + "/1 (" + numof + ").json");
String content = FileUtils.readFileToString(file, "UTF-8");
JSONObject jsonObject = new JSONObject(content);
JSONArray getJsonArray = jsonObject.getJSONArray("gps");
String[] rideid = content.split("rideID");
String name1 = rideid[1].split("\",")[0].replaceAll("\"\\: \"", "").substring(0, 8);
String[] filename = content.split("filename");
String name2 = filename[1].split("\",")[0].replaceAll("\"\\: \"", "").substring(0, 8);
String videoName = name1 + "-" + name2 + ".mov";
int num = getJsonArray.length();
if (num > 0) {
coordinate1_x = new double[num];
coordinate1_y = new double[num];
Coordinate[] coordinate1 = new Coordinate[num];
timeArray = new long[num];
for (int j = 0; j < num; j++) {
String[] array = getJsonArray.get(j).toString().split(":");
String result_x = array[3].split(",")[0];
String result_y = array[6].split(",")[0];
String time = array[5].split(",")[0];
coordinate1_x[j] = Double.valueOf(result_x);
coordinate1_y[j] = Double.valueOf(result_y);
timeArray[j] = Long.parseLong(time);
coordinate1[j] = new Coordinate();
coordinate1[j].y = coordinate1_x[j];
coordinate1[j].x = coordinate1_y[j];
}
MGeometryFactory geometryFactory = new MGeometryFactory();
mp = geometryFactory.createMPoint(coordinate1, timeArray);
if (mp != null) {
bddString.add(videoName);
}
} else
continue;
} catch (Exception e) {
// System.out.println(numof);
continue;
// e.printStackTrace();
}
}
bdd = new String[bddString.size()];
for (int i = 0; i < bdd.length; i++)
bdd[i] = bddString.get(i);
return bdd;
}
} | 34.87037 | 167 | 0.640733 |
986b8ea3c41f1cc02a8439a0f0a0601fbb493bd1 | 2,487 | /*
* Copyright (C) 2006 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.server.am;
import android.content.IntentFilter;
import android.util.PrintWriterPrinter;
import android.util.Printer;
import java.io.PrintWriter;
final class BroadcastFilter extends IntentFilter {
// Back-pointer to the list this filter is in.
final ReceiverList receiverList;
final String packageName;
final String requiredPermission;
final int owningUid;
final int owningUserId;
BroadcastFilter(IntentFilter _filter, ReceiverList _receiverList,
String _packageName, String _requiredPermission, int _owningUid, int _userId) {
super(_filter);
receiverList = _receiverList;
packageName = _packageName;
requiredPermission = _requiredPermission;
owningUid = _owningUid;
owningUserId = _userId;
}
public void dump(PrintWriter pw, String prefix) {
dumpInReceiverList(pw, new PrintWriterPrinter(pw), prefix);
receiverList.dumpLocal(pw, prefix);
}
public void dumpBrief(PrintWriter pw, String prefix) {
dumpBroadcastFilterState(pw, prefix);
}
public void dumpInReceiverList(PrintWriter pw, Printer pr, String prefix) {
super.dump(pr, prefix);
dumpBroadcastFilterState(pw, prefix);
}
void dumpBroadcastFilterState(PrintWriter pw, String prefix) {
if (requiredPermission != null) {
pw.print(prefix); pw.print("requiredPermission="); pw.println(requiredPermission);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("BroadcastFilter{");
sb.append(Integer.toHexString(System.identityHashCode(this)));
sb.append(" u");
sb.append(owningUserId);
sb.append(' ');
sb.append(receiverList);
sb.append('}');
return sb.toString();
}
}
| 33.16 | 94 | 0.685163 |
0486582a02e7d0ccdc141e78d7a90df7396fd5b6 | 859 | package jp.s64.gradle.dependenciespreloader;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
public class PreloadDependenciesTask extends DefaultTask {
static final String TASK_NAME = "preloadDependencies";
@TaskAction
public void run() {
getProject().allprojects(project -> {
project.getConfigurations().forEach(configuration -> {
if (configuration.isCanBeResolved()) {
configuration.resolve();
} else {
dbg(configuration.getName() + "is not can be resolved");
}
});
});
msg("All configurations already loaded.");
}
private static void msg(String msg) {
System.out.println(msg);
}
private void dbg(String msg) {
getLogger().debug(msg);
}
}
| 26.030303 | 76 | 0.592549 |
0610117394d958b643e9d15064fd809f6cb9490c | 405 | package com.java.advanced.features.generics.tutorial.t04_bounded_type_parameters._00_bound;
/**
* 限定的类型参数允许调用在范围中定义的方法。
*
* @author wangzhichao
* @since 2020/4/23
*/
public class NaturalNumber<T extends Integer> {
private T n;
public NaturalNumber(T n) {
this.n = n;
}
public boolean isEven() {
// 限定类型参数允许调用在范围中定义的方法。
return n.intValue() % 2 == 0;
}
}
| 19.285714 | 91 | 0.644444 |
0ed6a5273e20d4fd9666c4c4863ac9606d0af158 | 4,886 | package pt.inescid.safecloudfs.cloud;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Iterables.contains;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.jclouds.ContextBuilder;
import org.jclouds.apis.ApiMetadata;
import org.jclouds.apis.Apis;
import org.jclouds.blobstore.BlobStore;
import org.jclouds.blobstore.BlobStoreContext;
import org.jclouds.blobstore.domain.Blob;
import org.jclouds.domain.Location;
import org.jclouds.openstack.swift.v1.SwiftApiMetadata;
import org.jclouds.providers.ProviderMetadata;
import org.jclouds.providers.Providers;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.io.ByteSource;
import pt.inescid.safecloudfs.utils.CloudAccounts;
import pt.inescid.safecloudfs.utils.CloudAccounts.CloudAccount;
import pt.inescid.safecloudfs.utils.SafeCloudFSProperties;
import pt.inescid.safecloudfs.utils.SafeCloudFSUtils;
public class CloudUtils {
public static final Map<String, ApiMetadata> allApis = Maps.uniqueIndex(Apis.viewableAs(BlobStoreContext.class),
Apis.idFunction());
public static final Map<String, ProviderMetadata> appProviders = Maps
.uniqueIndex(Providers.viewableAs(BlobStoreContext.class), Providers.idFunction());
public static final Set<String> allKeys = ImmutableSet
.copyOf(Iterables.concat(appProviders.keySet(), allApis.keySet()));
public static int PARAMETERS = 4;
public static String INVALID_SYNTAX = "Invalid number of parameters. Syntax is: \"provider\" \"identity\" \"credential\" \"containerName\".";
public static CloudBroker pingClouds() {
String containerName = "safecloudfsping";
CloudAccount[] cloudAccounts = CloudAccounts.getAllAccounts();
if (cloudAccounts.length != 1) {
if (cloudAccounts.length < (3 * SafeCloudFSProperties.cloudsF + 1)) {
System.err.println("To tolerate f=" + SafeCloudFSProperties.cloudsF
+ " faulty clouds it is necessary to setup at least " + (3 * SafeCloudFSProperties.cloudsF + 1)
+ " clouds in the accounts.json file");
System.exit(-1);
}
}
SafeCloudFSProperties.cloudsN = cloudAccounts.length;
if (SafeCloudFSUtils.cloudContexts == null) {
SafeCloudFSUtils.cloudContexts = new BlobStoreContext[CloudAccounts.getAccountsSize()];
}
for (int i = 0; i < cloudAccounts.length; i++) {
containerName = "safecloudfsping" + i;
CloudAccount account = cloudAccounts[i];
checkArgument(contains(allKeys, account.provider), "provider %s not in supported list: %s",
account.provider, allKeys);
SafeCloudFSUtils.cloudContexts[i] = null;
if(account.endpoint != null) {
Properties overrides = new Properties();
overrides.setProperty("jclouds.endpoint", account.endpoint);
overrides.setProperty("jclouds.trust-all-certs", "true");
overrides.setProperty("jclouds.relax-hostname", "true");
SafeCloudFSUtils.cloudContexts[i] = ContextBuilder.newBuilder(account.provider)
.credentials(account.identity, account.credential).endpoint(account.endpoint).overrides(overrides).buildView(BlobStoreContext.class);
}else {
SafeCloudFSUtils.cloudContexts[i] = ContextBuilder.newBuilder(account.provider)
.credentials(account.identity, account.credential).buildView(BlobStoreContext.class);
}
BlobStore blobStore = null;
try {
ApiMetadata apiMetadata = SafeCloudFSUtils.cloudContexts[i].unwrap().getProviderMetadata()
.getApiMetadata();
blobStore = SafeCloudFSUtils.cloudContexts[i].getBlobStore();
// Create Container
Location location = null;
if (apiMetadata instanceof SwiftApiMetadata) {
location = Iterables.getFirst(blobStore.listAssignableLocations(), null);
}
blobStore.createContainerInLocation(location, containerName);
String blobName = "ping";
byte[] byteArray = "ping".getBytes();
ByteSource payload = ByteSource.wrap(byteArray);
// Add Blob
Blob blob = null;
try {
blob = blobStore.blobBuilder(blobName).payload(payload).contentLength(payload.size()).build();
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
blobStore.putBlob(containerName, blob);
} catch (Exception e) {
e.printStackTrace();
SafeCloudFSUtils.LOGGER.severe(e.getMessage());
System.exit(-1);
} finally {
blobStore.deleteContainer(containerName);
}
}
CloudBroker cloudUploader = null;
if (SafeCloudFSProperties.cloudsN == 1) {
cloudUploader = new SingleCloudBroker(SafeCloudFSProperties.uploadMethod,
SafeCloudFSUtils.cloudContexts[0]);
} else {
cloudUploader = new MultipleCloudBroker(SafeCloudFSProperties.uploadMethod,
SafeCloudFSUtils.cloudContexts);
}
return cloudUploader;
}
}
| 31.121019 | 142 | 0.74867 |
cf56c4d15e9f8fb0641cfdd91a6aff3841e7ec4e | 3,505 | /*
* @(#)AbstractTheme.java 2007-9-30
*
* Copyright 2004-2007 WXXR Network Technology Co. Ltd.
* All rights reserved.
*
* WXXR PROPRIETARY/CONFIDENTIAL.
*/
package com.wxxr.nirvana.workbench.impl;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.wxxr.nirvana.platform.IConfigurationElement;
import com.wxxr.nirvana.theme.IDesktop;
import com.wxxr.nirvana.theme.ITheme;
import com.wxxr.nirvana.theme.IThemeManager;
import com.wxxr.nirvana.workbench.ICreateRenderContext;
import com.wxxr.nirvana.workbench.IRender;
import com.wxxr.nirvana.workbench.config.BaseContributionItem;
/**
* @author fudapeng
*
*/
public class ThemeImpl extends BaseContributionItem implements ITheme {
protected String id;
protected String description;
protected IThemeManager manager;
private Desktop desktop;
private boolean defaultTheme = false;
private ResourceRef[] resourcerefs;
private String ATT_RESOURCE = "resource";
private static final String ATT_CLASS = "class";
private static final String ATT_RENDER = "render";
private ICreateRenderContext context;
private final Log log = LogFactory.getLog(ThemeImpl.class);
public ThemeImpl(ICreateRenderContext createRender) {
this.context = createRender;
}
/*
* (non-Javadoc)
*
* @see com.wxxr.web.platform.interfaces.Theme#getDescription()
*/
public String getDescription() {
return description;
}
/**
* @param description
* the description to set
*/
public void setDescription(String description) {
this.description = description;
}
public final void applyConfigure(IConfigurationElement config) {
applyConfigure(config, false);
}
public void destroy() {
}
public void init(IThemeManager manager, IConfigurationElement config) {
this.manager = manager;
applyConfigure(config, true);
try {
initDesktop(config.getChildren("desktop")[0]);
} catch (Exception e) {
log.error(" initDesktop error ", e);
}
initResources(config);
}
private void initResources(IConfigurationElement config) {
IConfigurationElement[] children = config.getChildren(ATT_RESOURCE);
if (children != null && children.length > 0) {
resourcerefs = new ResourceRef[children.length];
int i = 0;
for (IConfigurationElement child : children) {
ResourceRef ref = new ResourceRef(child);
resourcerefs[i] = ref;
i++;
}
}
}
private void initDesktop(IConfigurationElement config) throws Exception {
if (desktop == null) {
desktop = new Desktop();
String renderId = elem.getAttribute(ATT_RENDER);
IRender render = null;
if (StringUtils.isNotBlank(renderId)) {
render = context.createRender(renderId);
}
desktop.init(config, render);
}
}
protected void applyConfigure(IConfigurationElement config, boolean init) {
if (init) {
id = config.getAttribute("id");
description = config.getAttribute("description");
defaultTheme = config.getAttribute("default") == null ? false
: true;
setConfigurationElement(config);
}
}
public IThemeManager getThemeManager() {
return manager;
}
/**
* @return the id
*/
public String getId() {
return id;
}
/**
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
}
public IDesktop getDesktop() {
return desktop;
}
public boolean isDefault() {
return defaultTheme;
}
public ResourceRef[] getResourceRefs() {
return resourcerefs;
}
}
| 23.059211 | 76 | 0.719258 |
994985b4a22383d23874dae9488661995925ca1b | 2,122 | package org.hit.android.haim.chat.server.config;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.hit.android.haim.chat.server.model.repository.ChannelRepository;
import org.hit.android.haim.chat.server.model.repository.MessageRepository;
import org.hit.android.haim.chat.server.model.repository.UserRepository;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.AbstractMongoClientConfiguration;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import java.util.Collection;
import java.util.Collections;
/**
* @author Haim Adrian
* @since 14-Apr-21
*/
@Configuration
@EnableMongoRepositories(basePackageClasses = { ChannelRepository.class, UserRepository.class, MessageRepository.class })
public class MongoConfig extends AbstractMongoClientConfiguration {
private static final String MONGO_DB_URL = "%s@chat.aeiil.mongodb.net";
private static final String MONGO_DB_NAME = "chat";
@Value("${spring.datasource.username}")
private String mongoUser;
@Value("${spring.datasource.password}")
private String mongoPwd;
@Override
protected String getDatabaseName() {
return MONGO_DB_NAME;
}
@Override
public MongoClient mongoClient() {
String urlWithUserAndPass = String.format(MONGO_DB_URL, mongoUser + ":" + mongoPwd);
ConnectionString connectionString = new ConnectionString("mongodb+srv://" + urlWithUserAndPass + "/" + MONGO_DB_NAME + "?retryWrites=true&w=majority");
MongoClientSettings mongoClientSettings = MongoClientSettings.builder().applyConnectionString(connectionString).build();
return MongoClients.create(mongoClientSettings);
}
@Override
public Collection<String> getMappingBasePackages() {
return Collections.singleton("org.hit.android.haim.chat.server.model.bean");
}
}
| 40.037736 | 160 | 0.757776 |
53c805b076fa599310505951a29f1bab170ebf33 | 11,972 | /*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.examples.common.experimental.impl;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.TreeSet;
import java.util.function.Function;
import org.junit.jupiter.api.Test;
public class IntervalTreeTest {
private static class Interval {
final int start;
final int end;
public Interval(int start, int end) {
this.start = start;
this.end = end;
}
public int getStart() {
return start;
}
public int getEnd() {
return end;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Interval interval = (Interval) o;
return start == interval.start && end == interval.end;
}
@Override
public int hashCode() {
return Objects.hash(start, end);
}
@Override
public String toString() {
return "(" + start + ", " + end + ")";
}
}
private IntervalTree<Interval, Integer> getIntegerIntervalTree() {
return new IntervalTree<>(Interval::getStart, Interval::getEnd);
}
@Test
public void testNonConsecutiveIntervals() {
IntervalTree<Interval, Integer> tree = getIntegerIntervalTree();
tree.add(new Interval(0, 2));
tree.add(new Interval(3, 4));
tree.add(new Interval(5, 7));
Iterable<IntervalCluster<Interval, Integer>> clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(3);
Iterator<IntervalCluster<Interval, Integer>> iterator = clusterList.iterator();
IntervalCluster<Interval, Integer> intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(new Interval(0, 2));
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(new Interval(3, 4));
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(new Interval(5, 7));
assertThat(intervalCluster.hasOverlap()).isFalse();
}
@Test
public void testConsecutiveIntervals() {
IntervalTree<Interval, Integer> tree = getIntegerIntervalTree();
tree.add(new Interval(0, 2));
tree.add(new Interval(2, 4));
tree.add(new Interval(4, 7));
Iterable<IntervalCluster<Interval, Integer>> clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(1);
Iterator<IntervalCluster<Interval, Integer>> iterator = clusterList.iterator();
IntervalCluster<Interval, Integer> intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(new Interval(0, 2), new Interval(2, 4), new Interval(4, 7));
}
@Test
public void testDuplicateIntervals() {
IntervalTree<Interval, Integer> tree = getIntegerIntervalTree();
Interval a = new Interval(0, 2);
Interval b = new Interval(4, 7);
tree.add(a);
tree.add(a);
tree.add(b);
Iterable<IntervalCluster<Interval, Integer>> clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(2);
Iterator<IntervalCluster<Interval, Integer>> iterator = clusterList.iterator();
IntervalCluster<Interval, Integer> intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(a, a);
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(b);
}
@Test
public void testIntervalRemoval() {
IntervalTree<Interval, Integer> tree = getIntegerIntervalTree();
Interval a = new Interval(0, 2);
Interval b = new Interval(2, 4);
Interval c = new Interval(4, 7);
tree.add(a);
tree.add(b);
tree.add(c);
tree.remove(b);
Iterable<IntervalCluster<Interval, Integer>> clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(2);
Iterator<IntervalCluster<Interval, Integer>> iterator = clusterList.iterator();
IntervalCluster<Interval, Integer> intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(new Interval(0, 2));
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(new Interval(4, 7));
}
@Test
public void testOverlappingInterval() {
IntervalTree<Interval, Integer> tree = getIntegerIntervalTree();
Interval a = new Interval(0, 2);
Interval b = new Interval(1, 3);
Interval c = new Interval(2, 4);
Interval d = new Interval(5, 6);
Interval e = new Interval(7, 9);
Interval f = new Interval(7, 9);
tree.add(a);
tree.add(b);
tree.add(c);
tree.add(d);
tree.add(e);
tree.add(f);
Iterable<IntervalCluster<Interval, Integer>> clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(3);
Iterator<IntervalCluster<Interval, Integer>> iterator = clusterList.iterator();
IntervalCluster<Interval, Integer> intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(a, b, c);
assertThat(intervalCluster.hasOverlap()).isTrue();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(d);
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(e, f);
assertThat(intervalCluster.hasOverlap()).isTrue();
tree.remove(b);
clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(3);
iterator = clusterList.iterator();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(a, c);
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(d);
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(e, f);
assertThat(intervalCluster.hasOverlap()).isTrue();
tree.remove(f);
clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(3);
iterator = clusterList.iterator();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(a, c);
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(d);
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(e);
assertThat(intervalCluster.hasOverlap()).isFalse();
Interval g = new Interval(6, 7);
tree.add(g);
clusterList = tree.getConsecutiveIntervalData().getIntervalClusters();
assertThat(clusterList).hasSize(2);
iterator = clusterList.iterator();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(a, c);
assertThat(intervalCluster.hasOverlap()).isFalse();
intervalCluster = iterator.next();
assertThat(intervalCluster).containsExactly(d, g, e);
assertThat(intervalCluster.hasOverlap()).isFalse();
}
// Compare the mutable version with the recompute version
@Test
public void testRandomIntervals() {
Random random = new Random(1);
Map<Interval, Interval> intervalToInstanceMap = new HashMap<>();
TreeSet<IntervalSplitPoint<Interval, Integer>> splitPoints = new TreeSet<>();
IntervalTree<Interval, Integer> tree = new IntervalTree<>(Interval::getStart, Interval::getEnd);
for (int i = 0; i < 10000; i++) {
// Create a random interval
int from = random.nextInt(50);
int to = from + random.nextInt(50);
Interval interval = intervalToInstanceMap.computeIfAbsent(new Interval(from, to), Function.identity());
org.optaplanner.examples.common.experimental.impl.Interval<Interval, Integer> treeInterval =
new org.optaplanner.examples.common.experimental.impl.Interval<>(interval, Interval::getStart,
Interval::getEnd);
splitPoints.add(treeInterval.getStartSplitPoint());
splitPoints.add(treeInterval.getEndSplitPoint());
// Get the split points from the set (since those split points have collections)
IntervalSplitPoint<Interval, Integer> startSplitPoint = splitPoints.floor(treeInterval.getStartSplitPoint());
IntervalSplitPoint<Interval, Integer> endSplitPoint = splitPoints.floor(treeInterval.getEndSplitPoint());
// Create the collections if they do not exist
if (startSplitPoint.startIntervalToCountMap == null) {
startSplitPoint.createCollections();
}
if (endSplitPoint.endIntervalToCountMap == null) {
endSplitPoint.createCollections();
}
// Either add or remove the interval
if (startSplitPoint.containsIntervalStarting(treeInterval) && random.nextBoolean()) {
startSplitPoint.removeIntervalStartingAtSplitPoint(treeInterval);
endSplitPoint.removeIntervalEndingAtSplitPoint(treeInterval);
if (startSplitPoint.isEmpty()) {
splitPoints.remove(startSplitPoint);
}
if (endSplitPoint.isEmpty()) {
splitPoints.remove(endSplitPoint);
}
tree.remove(interval);
} else {
startSplitPoint.addIntervalStartingAtSplitPoint(treeInterval);
endSplitPoint.addIntervalEndingAtSplitPoint(treeInterval);
tree.add(interval);
}
// Recompute all interval clusters
IntervalSplitPoint<Interval, Integer> current = splitPoints.first();
List<IntervalCluster<Interval, Integer>> intervalClusterList = new ArrayList<>();
while (current != null) {
intervalClusterList.add(new IntervalCluster<>(splitPoints, current));
current = splitPoints.higher(intervalClusterList.get(intervalClusterList.size() - 1).getEndSplitPoint());
}
// Verify the mutable version matches the recompute version
assertThat(tree.getConsecutiveIntervalData().getIntervalClusters()).containsExactlyElementsOf(intervalClusterList);
}
}
}
| 39.381579 | 127 | 0.65127 |
b30e485b08951ada44c8eeed5261d161cbd14545 | 5,141 | /*
* Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tencentcloudapi.dbbrain.v20210527.models;
import com.tencentcloudapi.common.AbstractModel;
import com.google.gson.annotations.SerializedName;
import com.google.gson.annotations.Expose;
import java.util.HashMap;
public class KillMySqlThreadsRequest extends AbstractModel{
/**
* 实例ID。
*/
@SerializedName("InstanceId")
@Expose
private String InstanceId;
/**
* kill会话任务的阶段,取值包括:"Prepare"-准备阶段,"Commit"-提交阶段。
*/
@SerializedName("Stage")
@Expose
private String Stage;
/**
* 需要kill的sql会话ID列表,此参数用于Prepare阶段。
*/
@SerializedName("Threads")
@Expose
private Long [] Threads;
/**
* 执行ID,此参数用于Commit阶段。
*/
@SerializedName("SqlExecId")
@Expose
private String SqlExecId;
/**
* 服务产品类型,支持值包括: "mysql" - 云数据库 MySQL, "cynosdb" - 云数据库 CynosDB for MySQL,默认为"mysql"。
*/
@SerializedName("Product")
@Expose
private String Product;
/**
* Get 实例ID。
* @return InstanceId 实例ID。
*/
public String getInstanceId() {
return this.InstanceId;
}
/**
* Set 实例ID。
* @param InstanceId 实例ID。
*/
public void setInstanceId(String InstanceId) {
this.InstanceId = InstanceId;
}
/**
* Get kill会话任务的阶段,取值包括:"Prepare"-准备阶段,"Commit"-提交阶段。
* @return Stage kill会话任务的阶段,取值包括:"Prepare"-准备阶段,"Commit"-提交阶段。
*/
public String getStage() {
return this.Stage;
}
/**
* Set kill会话任务的阶段,取值包括:"Prepare"-准备阶段,"Commit"-提交阶段。
* @param Stage kill会话任务的阶段,取值包括:"Prepare"-准备阶段,"Commit"-提交阶段。
*/
public void setStage(String Stage) {
this.Stage = Stage;
}
/**
* Get 需要kill的sql会话ID列表,此参数用于Prepare阶段。
* @return Threads 需要kill的sql会话ID列表,此参数用于Prepare阶段。
*/
public Long [] getThreads() {
return this.Threads;
}
/**
* Set 需要kill的sql会话ID列表,此参数用于Prepare阶段。
* @param Threads 需要kill的sql会话ID列表,此参数用于Prepare阶段。
*/
public void setThreads(Long [] Threads) {
this.Threads = Threads;
}
/**
* Get 执行ID,此参数用于Commit阶段。
* @return SqlExecId 执行ID,此参数用于Commit阶段。
*/
public String getSqlExecId() {
return this.SqlExecId;
}
/**
* Set 执行ID,此参数用于Commit阶段。
* @param SqlExecId 执行ID,此参数用于Commit阶段。
*/
public void setSqlExecId(String SqlExecId) {
this.SqlExecId = SqlExecId;
}
/**
* Get 服务产品类型,支持值包括: "mysql" - 云数据库 MySQL, "cynosdb" - 云数据库 CynosDB for MySQL,默认为"mysql"。
* @return Product 服务产品类型,支持值包括: "mysql" - 云数据库 MySQL, "cynosdb" - 云数据库 CynosDB for MySQL,默认为"mysql"。
*/
public String getProduct() {
return this.Product;
}
/**
* Set 服务产品类型,支持值包括: "mysql" - 云数据库 MySQL, "cynosdb" - 云数据库 CynosDB for MySQL,默认为"mysql"。
* @param Product 服务产品类型,支持值包括: "mysql" - 云数据库 MySQL, "cynosdb" - 云数据库 CynosDB for MySQL,默认为"mysql"。
*/
public void setProduct(String Product) {
this.Product = Product;
}
public KillMySqlThreadsRequest() {
}
/**
* NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy,
* and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy.
*/
public KillMySqlThreadsRequest(KillMySqlThreadsRequest source) {
if (source.InstanceId != null) {
this.InstanceId = new String(source.InstanceId);
}
if (source.Stage != null) {
this.Stage = new String(source.Stage);
}
if (source.Threads != null) {
this.Threads = new Long[source.Threads.length];
for (int i = 0; i < source.Threads.length; i++) {
this.Threads[i] = new Long(source.Threads[i]);
}
}
if (source.SqlExecId != null) {
this.SqlExecId = new String(source.SqlExecId);
}
if (source.Product != null) {
this.Product = new String(source.Product);
}
}
/**
* Internal implementation, normal users should not use it.
*/
public void toMap(HashMap<String, String> map, String prefix) {
this.setParamSimple(map, prefix + "InstanceId", this.InstanceId);
this.setParamSimple(map, prefix + "Stage", this.Stage);
this.setParamArraySimple(map, prefix + "Threads.", this.Threads);
this.setParamSimple(map, prefix + "SqlExecId", this.SqlExecId);
this.setParamSimple(map, prefix + "Product", this.Product);
}
}
| 28.247253 | 106 | 0.61914 |
87f246ed54fa9a67fea2664d3ce04ea2ad0eb3c8 | 2,767 | /****************************************************************
* Licensed to the AOS Community (AOS) under one or more *
* contributor license agreements. See the NOTICE file *
* distributed with this work for additional information *
* regarding copyright ownership. The AOS 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 aos.algo.fibonacci.f2;
import javax.swing.text.*;
import javax.swing.text.html.*;
import javax.swing.text.html.parser.*;
import java.io.*;
import java.net.*;
import java.util.*;
public class ReportAttributes extends HTMLEditorKit.ParserCallback {
public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes,
int position) {
this.listAttributes(attributes);
}
private void listAttributes(AttributeSet attributes) {
System.out.println();
Enumeration e = attributes.getAttributeNames();
while (e.hasMoreElements()) {
Object name = e.nextElement();
Object value = attributes.getAttribute(name);
if (!attributes.containsAttribute(name.toString(), value)) {
System.out.println("containsAttribute() fails");
}
if (!attributes.isDefined(name.toString())) {
System.out.println("isDefined() fails");
}
System.out.println(name + "=" + value);
}
}
public void handleSimpleTag(HTML.Tag tag, MutableAttributeSet attributes,
int position) {
this.listAttributes(attributes);
}
public static void main(String... args) {
ParserGetter kit = new ParserGetter();
HTMLEditorKit.Parser parser = kit.getParser();
HTMLEditorKit.ParserCallback callback
= new ReportAttributes();
try {
URL u = new URL(args[0]);
InputStream in = u.openStream();
InputStreamReader r = new InputStreamReader(in);
parser.parse(r, callback, false);
}
catch (IOException e) {
System.err.println(e);
}
}
}
| 36.893333 | 76 | 0.594507 |
8860694eb7e1dc71080fecceac0fadba54686520 | 2,704 | /*
* Copyright (C) 2017 Raul Hernandez Lopez @raulh82vlc
*
* 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.raulh82vlc.TransactionsViewer.domain.models;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Transaction adapted to UI needs
*
* @author Raul Hernandez Lopez.
*/
public class TransactionUI implements Parcelable {
private String amounPerTransactionPrev;
private String amountPerTransactionCurrent;
private String currencyPrev;
private String currencyCurrent;
public TransactionUI(String currencyPrev, String currencyCurrent, String amounPerTransactionPrev,
String amountPerTransactionCurrent) {
this.currencyPrev = currencyPrev;
this.currencyCurrent = currencyCurrent;
this.amounPerTransactionPrev = amounPerTransactionPrev;
this.amountPerTransactionCurrent = amountPerTransactionCurrent;
}
private TransactionUI(Parcel in) {
currencyPrev = in.readString();
currencyCurrent = in.readString();
amounPerTransactionPrev = in.readString();
amountPerTransactionCurrent = in.readString();
}
public static final Creator<TransactionUI> CREATOR = new Creator<TransactionUI>() {
@Override
public TransactionUI createFromParcel(Parcel in) {
return new TransactionUI(in);
}
@Override
public TransactionUI[] newArray(int size) {
return new TransactionUI[size];
}
};
public String getAmounPerTransactionPrev() {
return amounPerTransactionPrev;
}
public String getAmountPerTransactionCurrent() {
return amountPerTransactionCurrent;
}
public String getCurrencyPrev() {
return currencyPrev;
}
public String getCurrencyCurrent() {
return currencyCurrent;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(currencyPrev);
dest.writeString(currencyCurrent);
dest.writeString(amounPerTransactionPrev);
dest.writeString(amountPerTransactionCurrent);
}
}
| 30.044444 | 101 | 0.700814 |
21951886b8fe47fc62677a05bcf06ca6cf8b2b1d | 827 | // -----------------------------------------------------------------------
// <copyright file="MessageType.java" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------
package com.microsoft.store.partnercenter.models.serviceincidents;
import com.fasterxml.jackson.annotation.JsonProperty;
/***
* Represents the status of partner center services.
*/
public enum MessageType
{
/***
* Default type none.
*/
@JsonProperty( "None" ) NONE,
/***
* Active incident.
*/
@JsonProperty( "Incident" ) INCIDENT,
/***
* Message center message.
*/
@JsonProperty( "MessageCenter" ) MESSAGECENTER,
/***
* All types.
*/
@JsonProperty( "All" ) ALL
}
| 22.351351 | 74 | 0.519952 |
e27d6825faf696b71664767cf798e068bf147d8f | 750 | package com.fun.uncle.hello.spring.cloud.alibaba.rocketmq.provider.service.Impl;
import com.fun.uncle.hello.spring.cloud.alibaba.rocketmq.provider.service.ProviderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
/**
* @Description:
* @Author: Xian
* @CreateDate: 2020/1/20 13:38
* @Version: 0.0.1-SNAPSHOT
*/
@Service
public class ProviderServiceImpl implements ProviderService {
@Autowired
private MessageChannel output;
@Override
public void send(String message) {
output.send(MessageBuilder.withPayload(message).build());
}
}
| 30 | 90 | 0.777333 |
5fee3904f20695947a5d34d90d335965ddd87003 | 2,593 | package ca.gc.aafc.transaction.api.entities;
import java.util.Map;
import javax.transaction.Transactional;
import org.junit.jupiter.api.Test;
import ca.gc.aafc.transaction.api.BaseIntegrationTest;
import ca.gc.aafc.transaction.api.testsupport.factories.TransactionFactory;
import ca.gc.aafc.transaction.api.testsupport.factories.TransactionManagedAttributeFactory;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
@Transactional
public class TransactionCrudIT extends BaseIntegrationTest {
@Test
public void testCreate() {
TransactionManagedAttribute newTransactionManagedAttribute = TransactionManagedAttributeFactory
.newManagedAttribute()
.build();
managedAttributeService.createAndFlush(newTransactionManagedAttribute);
Transaction newTransaction = TransactionFactory.newTransaction()
.managedAttributes(Map.of(newTransactionManagedAttribute.getKey(), "anything"))
.build();
assertNull(newTransaction.getId());
transactionService.createAndFlush(newTransaction);
assertNotNull(newTransaction.getId());
assertNotNull(newTransaction.getMaterialToBeReturned());
//cleanup
transactionService.delete(newTransaction);
transactionService.flush();
managedAttributeService.delete(newTransactionManagedAttribute);
}
@Test
public void testFind() {
TransactionManagedAttribute newTransactionManagedAttribute = TransactionManagedAttributeFactory
.newManagedAttribute()
.build();
managedAttributeService.createAndFlush(newTransactionManagedAttribute);
Transaction newTransaction = TransactionFactory.newTransaction()
.managedAttributes(Map.of(newTransactionManagedAttribute.getKey(), "anything"))
.build();
transactionService.createAndFlush(newTransaction);
Transaction foundTransaction = transactionService.findOne(newTransaction.getUuid(), Transaction.class);
assertEquals(newTransaction.getId(), foundTransaction.getId());
assertEquals(newTransaction.getUuid(), foundTransaction.getUuid());
assertEquals(newTransaction.getManagedAttributes().get(newTransactionManagedAttribute.getKey()),
foundTransaction.getManagedAttributes().get(newTransactionManagedAttribute.getKey()));
assertNotNull(foundTransaction.getCreatedOn());
//cleanup
transactionService.delete(newTransaction);
transactionService.flush();
managedAttributeService.delete(newTransactionManagedAttribute);
}
}
| 38.132353 | 107 | 0.792518 |
86de9c8939be507e25729aa4dd2fbcd72f5b714b | 1,120 | package Game.ComputerFunctions;
import Game.*;
import Assignments.*;
/**
A function that is run within Computer.java.
Reward a player redirect experience.
*/
import java.util.*;
import Assignments.*;
import Hackscript.Model.*;
public class redirectXP extends function{
public redirectXP(Computer MyComputer){
super(MyComputer);
}
public void execute(ApplicationData MyApplicationData){
if(MyApplicationData.getParameters() instanceof Integer){
int type=(Integer)MyApplicationData.getParameters();
float amount=Computer.commodityXP[type];
float mult = 1.0f;
amount *= mult;
amount+=(Float)super.getComputer().getStats().get("Redirecting");
if(amount < 300.0f && mult < 0) amount = 300.0f;
super.getComputer().getStats().put("Redirecting",amount);
}else{
float amount=(Float)MyApplicationData.getParameters();
float mult = 1.0f;
amount *= mult;
amount+=(Float)super.getComputer().getStats().get("Redirecting");
if(amount < 300.0f && mult < 0) amount = 300.0f;
super.getComputer().getStats().put("Redirecting",amount);
}
super.getComputer().sendDamagePacket();
}
}
| 28.717949 | 68 | 0.71875 |
c2b291a384fdc30ba74f4d5d7cce98597b5a2147 | 1,159 | package org.springframework.fu.jafu.redis;
import org.springframework.boot.autoconfigure.data.redis.RedisReactiveInitializer;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.support.GenericApplicationContext;
import java.util.function.Consumer;
/**
* JaFu DSL for reactive Redis configuration.
*
* @author Andreas Gebhardt
*/
public class ReactiveRedisDsl extends AbstractRedisDsl<ReactiveRedisDsl> {
public ReactiveRedisDsl(final Consumer<ReactiveRedisDsl> dsl) {
super(dsl);
}
@Override
protected ReactiveRedisDsl getSelf() {
return this;
}
public static ApplicationContextInitializer<GenericApplicationContext> reactiveRedis() {
return new ReactiveRedisDsl(dsl -> {
});
}
public static ApplicationContextInitializer<GenericApplicationContext> reactiveRedis(final Consumer<ReactiveRedisDsl> dsl) {
return new ReactiveRedisDsl(dsl);
}
@Override
public void initialize(GenericApplicationContext context) {
super.initialize(context);
new RedisReactiveInitializer().initialize(context);
}
}
| 28.268293 | 128 | 0.750647 |
52df2e7ff89ca5c8d3ff1b4fabc48aecb98ee149 | 955 | package de.komoot.photon.searcher;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilder;
/**
* Created by Sachin Dole on 2/12/2015.
*/
public class BaseElasticsearchSearcher implements ElasticsearchSearcher {
private Client client;
public BaseElasticsearchSearcher(Client client) {
this.client = client;
}
@Override
public SearchResponse search(QueryBuilder queryBuilder, Integer limit) {
TimeValue timeout = TimeValue.timeValueSeconds(7);
return client.prepareSearch("photon").
setSearchType(SearchType.QUERY_AND_FETCH).
setQuery(queryBuilder).
setSize(limit).
setTimeout(timeout).
execute().
actionGet();
}
}
| 28.088235 | 76 | 0.690052 |
5f02ed58da8bd1a6a6c4e89eca668f5bb5f3bac3 | 109 | package com.yw.car.widget.swipetoloadlayout;
public interface OnLoadMoreListener {
void onLoadMore();
}
| 18.166667 | 44 | 0.779817 |
7cb4c7d8ec1b04d193e91b20173fb2f87e458124 | 5,751 | package pd.log;
import static pd.log.LogUtil.getHostname;
import static pd.log.LogUtil.writeLine;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicBoolean;
import pd.time.Ctime;
/**
* FileLogger holds a thread writing down records to avoid latency from IO
*/
public class FileLogger implements ILogger {
class Record {
long timestamp;
LogLevel level;
String message;
Object[] messageArguments;
}
class ThreadedLogWriter {
private final String logPrefix = ThreadedLogWriter.class.getSimpleName();
private final ILogger logger = ConsoleLogger.defaultInstance;
private final BlockingQueue<Record> queue = new LinkedBlockingQueue<Record>();
private final AtomicBoolean isRunning = new AtomicBoolean(false);
private final AtomicBoolean isStopped = new AtomicBoolean(true);
private Thread workerThread = new Thread(new Runnable() {
@Override
public void run() {
isRunning.set(true);
isStopped.set(false);
logger.logVerbose("%s: logger thread started", logPrefix);
synchronized (isRunning) {
isRunning.notify();
}
while (isRunning.get() || !queue.isEmpty()) {
if (isStopped.get()) {
break;
}
Record record;
try {
record = queue.take();
} catch (InterruptedException e) {
logger.logVerbose("%s: logger thread interrupted, %d remaining", logPrefix, queue.size());
isRunning.set(false);
continue;
}
doLog(record.timestamp, record.level, record.message, record.messageArguments);
}
isStopped.set(true);
logger.logVerbose("%s: logger thread stopped, %d remaining", logPrefix, queue.size());
logger.flush();
}
});
public ThreadedLogWriter() {
workerThread.start();
synchronized (isRunning) {
try {
isRunning.wait(50);
} catch (InterruptedException e) {
// dummy
}
}
}
public void add(long timestamp, LogLevel level, String message, Object... messageArguments) {
if (!isRunning.get()) {
logger.logVerbose("{}: logger is not running", logPrefix);
return;
}
Record entry = new Record();
entry.timestamp = timestamp;
entry.level = level;
entry.message = message;
entry.messageArguments = messageArguments;
if (!queue.offer(entry)) {
logger.logVerbose("{}: fail to add log message", logPrefix);
}
}
}
private final LogLevel maxLevel;
private final ThreadedLogWriter writer = new ThreadedLogWriter();
private final String dstRoot;
private final String dstPrefix;
private final long dstInterval;
public FileLogger(String dstRoot, String dstPrefix, long dstInterval) {
this(dstRoot, dstPrefix, dstInterval, LogLevel.MAX_LEVEL);
}
public FileLogger(String dstRoot, String dstPrefix, long dstInterval, LogLevel maxLevel) {
this.dstRoot = dstRoot;
this.dstPrefix = dstPrefix;
this.dstInterval = dstInterval;
this.maxLevel = maxLevel;
}
@Override
public void flush() {
while (!writer.queue.isEmpty()) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// dummy
}
}
}
protected String getLogFileBasename(long timestamp, LogLevel level) {
timestamp -= timestamp % dstInterval;
String timePart = Ctime.toUtcString("%04d%02d%02d%02d%02d%02dZ", timestamp);
String logLevelPart = level.ordinal() <= LogLevel.WARNING.ordinal() ? "warning" : "verbose";
return String.format("%s_%s_%s.%s.log", dstPrefix, timePart, getHostname(), logLevelPart);
}
@Override
public void log(LogLevel level, String message, Object... messageArguments) {
writer.add(Ctime.now(), level, message, messageArguments);
}
@Override
public void close() throws IOException {
if (!writer.isRunning.get()) {
return;
}
writer.workerThread.interrupt();
try {
writer.workerThread.join(2000);
} catch (InterruptedException e) {
// dummy
}
writer.isStopped.set(true);
}
public boolean isStopped() {
return writer.isStopped.get();
}
public void doLog(long timestamp, LogLevel level, String message, Object... messageArguments) {
if (level.ordinal() > maxLevel.ordinal()) {
return;
}
File dir = new File(dstRoot);
if (!dir.exists()) {
dir.mkdirs();
} else if (!dir.isDirectory()) {
throw new RuntimeException(String.format("[%s] is not directory", dstRoot));
}
File logFile = new File(dstRoot, getLogFileBasename(timestamp, level));
try (FileWriter w = new FileWriter(logFile, true)) {
writeLine(w, ",", timestamp, getHostname(), level, message);
w.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 31.42623 | 114 | 0.567032 |
037973c5bf3b2b3f93f06269c9babf0ad0cd3464 | 2,351 | /*
* Copyright 2019 wjybxx
*
* 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 iBn 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.wjybxx.fastjgame.kafka;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* {@link LogBuilder}的默认实现
*
* @author wjybxx
* @version 1.0
* date - 2019/12/15
* github - https://github.com/hl845740757
*/
public class DefaultLogBuilder implements LogBuilder {
private final String topic;
private final Map<String, Object> dataMap = new LinkedHashMap<>();
public DefaultLogBuilder(String topic) {
this.topic = topic;
}
public DefaultLogBuilder append(String key, final String value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, final int value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, final long value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, final float value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, final double value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, final Enum value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, final boolean value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, byte value) {
dataMap.put(key, value);
return this;
}
public DefaultLogBuilder append(String key, short value) {
dataMap.put(key, value);
return this;
}
String getTopic() {
return topic;
}
Map<String, Object> getDataMap() {
return dataMap;
}
}
| 25.554348 | 76 | 0.656316 |
3b9251a8f7b3d9fa761e02d5b2f6f30221666df9 | 2,681 | /*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fr.swift.jdbc.druid.sql.ast;
import com.fr.swift.jdbc.druid.sql.visitor.SQLASTVisitor;
import com.fr.swift.jdbc.druid.util.FnvHash;
import java.util.Collections;
import java.util.List;
public class SQLArrayDataType extends SQLObjectImpl implements SQLDataType {
private String dbType;
private SQLDataType componentType;
public SQLArrayDataType(SQLDataType componentType) {
setComponentType(componentType);
}
public SQLArrayDataType(SQLDataType componentType, String dbType) {
this.dbType = dbType;
setComponentType(componentType);
}
@Override
public String getName() {
return "ARRAY";
}
@Override
public long nameHashCode64() {
return FnvHash.Constants.ARRAY;
}
@Override
public void setName(String name) {
throw new UnsupportedOperationException();
}
@Override
public List<SQLExpr> getArguments() {
return Collections.emptyList();
}
@Override
public Boolean getWithTimeZone() {
return null;
}
@Override
public void setWithTimeZone(Boolean value) {
throw new UnsupportedOperationException();
}
@Override
public boolean isWithLocalTimeZone() {
return false;
}
@Override
public void setWithLocalTimeZone(boolean value) {
throw new UnsupportedOperationException();
}
@Override
public void setDbType(String dbType) {
dbType = dbType;
}
@Override
public String getDbType() {
return dbType;
}
@Override
protected void accept0(SQLASTVisitor visitor) {
if (visitor.visit(this)) {
acceptChild(visitor, componentType);
}
visitor.endVisit(this);
}
public SQLArrayDataType clone() {
return null;
}
public SQLDataType getComponentType() {
return componentType;
}
public void setComponentType(SQLDataType x) {
if (x != null) {
x.setParent(this);
}
this.componentType = x;
}
}
| 24.372727 | 76 | 0.664677 |
cf6fd4466b4dab14fe40575aced0cd7015cb194a | 461 | package br.com.proposta.repository;
import br.com.proposta.card.Card;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;
import java.util.Optional;
public interface CardRepository extends JpaRepository<Card, Long> {
// @Query("select c from Card c where c.idCard=:idCard")
// Card verifyIdCard(String idCard);
Optional<Card> findByCardNumber(String idCard);
}
| 30.733333 | 67 | 0.78308 |
76afdf58524cf2a5d0ef1c63fc5f213735372249 | 1,844 | package com.gtt.shoppingproductback.dto.in;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Date;
public class OrderIn {
private Integer customerId;
private String shipAddress;
private String productName;
private Double unitPrice;
private Integer quantity;
private Double totalPrice;
private Double shipPrice;
private Date createTime;
public Integer getCustomerId() {
return customerId;
}
public void setCustomerId(Integer customerId) {
this.customerId = customerId;
}
public String getShipAddress() {
return shipAddress;
}
public void setShipAddress(String shipAddress) {
this.shipAddress = shipAddress;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Double getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(Double unitPrice) {
this.unitPrice = unitPrice;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
public Double getShipPrice() {
return shipPrice;
}
public void setShipPrice(Double shipPrice) {
this.shipPrice = shipPrice;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}
| 21.952381 | 62 | 0.670824 |
bb0217e728cce8f23f5d89b7bfe1bb9947e33823 | 2,737 | package seedu.homerce.commons.core;
/**
* Container for user visible messages.
*/
public class Messages {
public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command, please use the help command to see the"
+ " available commands in Homerce.";
public static final String MESSAGE_NOT_EDITED = "No changes in details detected. "
+ "At least one field to edit must be provided.";
public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
public static final String MESSAGE_MULTIPLE_PARAMETERS = "Please only input one parameter";
// ============== Client related messages ===========
public static final String MESSAGE_CLIENT_INVALID_DELETION = "The client you want to delete is being scheduled"
+ " today or at a future appointment, it cannot be deleted.";
public static final String MESSAGE_CLIENTS_LISTED_OVERVIEW = "%1$d clients listed!";
public static final String MESSAGE_INVALID_CLIENT_DISPLAYED_INDEX = "The client index provided is invalid";
// ============== Service related messages ===========
public static final String MESSAGE_SERVICES_LISTED_OVERVIEW = "%1$d services listed!";
public static final String MESSAGE_INVALID_SERVICE_DISPLAYED_INDEX = "The service index provided is invalid";
public static final String MESSAGE_SERVICES_INVALID_SERVICE_DISPLAYED_INDEX = "The service index "
+ "provided is invalid";
public static final String MESSAGES_SERVICES_INVALID_DELETION = "The service you want to delete is being scheduled"
+ " today or at a future appointment, it cannot be deleted.";
public static final String MESSAGE_SERVICE_DUPLICATE_TITLE = "This service title is already used by one of the"
+ " other services";
// ============== Appointment related messages ===========
public static final String MESSAGE_APPOINTMENTS_LISTED_OVERVIEW = "%1$d appointments listed!";
public static final String MESSAGE_APPOINTMENT_ALREADY_DONE = "This appointment is already marked as done!";
public static final String MESSAGE_APPOINTMENT_ALREADY_UNDONE = "This appointment is already marked as not done!";
public static final String MESSAGE_INVALID_APPOINTMENT_DISPLAYED_INDEX = "The appointment index provided is "
+ "invalid";
// ============== Revenue related messages ===========
public static final String MESSAGE_REVENUE_LISTED_OVERVIEW = "%1$d revenue listed!";
// ============== Expense related messages ===========
public static final String MESSAGE_INVALID_EXPENSE_DISPLAYED_INDEX = "The expense index provided is invalid";
public static final String MESSAGE_EXPENSES_LISTED_OVERVIEW = "%1$d expenses listed!";
}
| 60.822222 | 119 | 0.724151 |
6f77eb09d24cbe74728bb08442a37d3e5fc5b84b | 1,312 | package com.dtstack.flinkx.interceptor;
import org.apache.flink.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogInterceptor implements Interceptor {
private static final Logger LOG = LoggerFactory.getLogger(LogInterceptor.class);
@Override
public void init(Configuration configuration) {
if (LOG.isDebugEnabled()) {
LOG.info("configuration: ");
configuration
.keySet()
.forEach(
key ->
LOG.debug(
"key : {} -> value : {}",
key,
configuration.toMap().get(key)));
}
}
@Override
public void pre(Context context) {
if (LOG.isDebugEnabled()) {
for (String key : context) {
LOG.debug("context key : {} -> value : {} ", key, context.get(key));
}
}
}
@Override
public void post(Context context) {
if (LOG.isDebugEnabled()) {
for (String key : context) {
LOG.debug("context key : {} -> value : {} ", key, context.get(key));
}
}
}
}
| 29.155556 | 84 | 0.476372 |
723e0889a6272b1260defa2216edad3f2eddd1db | 946 | package betty.socialnetwokkata.business.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@Builder
@AllArgsConstructor(access = AccessLevel.PACKAGE)
@Accessors(chain = true)
@NoArgsConstructor()
@Entity
@Table(name = "FOLLOWER")
public class Follower {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SEQUENCE")
@SequenceGenerator(name="SEQUENCE", sequenceName = "NXTNBR", initialValue = 1 ,allocationSize = 1)
private Long id;
private String follower;
private String username;
}
| 27.028571 | 102 | 0.787526 |
fde197ce2e507ef1545962d11111121872509012 | 804 | import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
switch (args[0]) {
case "M":
Map<String, Integer> m = new SimpleMap<>();
String word;
if (sc.hasNext()) {
word = sc.next();
m.put(word, sc.nextInt());
while (sc.hasNext())
m.put(sc.next(), sc.nextInt());
System.out.println(m.get(word));
}
break;
case "Q":
Queue<Integer> q = new SimpleQueue<>();
while (sc.hasNextInt())
q.enqueue(sc.nextInt());
System.out.println(q);
break;
case "S":
Set<String> s = new SimpleSet<>();
while (sc.hasNext())
s.add(sc.next());
System.out.println(s.size());
break;
default:
System.err.println("Error on input.");
sc.close();
}
}
}
| 21.72973 | 47 | 0.56592 |
a7ef982da02907df30f4ee232158e089199b8055 | 1,862 | package com.ggox.test;
import org.junit.Test;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StringUtils;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* @Author: ggox
* @Date: 2018-12-23 17:34
*/
public class MyTest {
@Test
public void test2(){
String str = "1231,12312,12312,222,,33,45,334,3,3";
String[] strings = StringUtils.tokenizeToStringArray(str, ",");
Arrays.stream(strings).forEach(System.out::println);
}
@Test
public void test3() throws ClassNotFoundException {
Class clazz = Class.forName("java.lang.String");
Object o = Array.newInstance(clazz, 0);
Class<?> aClass = o.getClass();
System.out.println(clazz);
System.out.println(aClass);
}
@Test
public void testFreezeConfiguration() {
AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(MyTest.class).getBeanDefinition();
System.out.println(beanDefinition.getClass());
DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
beanFactory.freezeConfiguration();
System.out.println(beanFactory.isConfigurationFrozen());
System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
beanFactory.registerBeanDefinition("user", beanDefinition);
System.out.println(beanFactory.isConfigurationFrozen());
System.out.println(Arrays.toString(beanFactory.getBeanDefinitionNames()));
}
@Test
public void testClassPathApplication() {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("");
classPathXmlApplicationContext.getBean("test");
}
}
| 33.854545 | 120 | 0.790011 |
cd0414f87d02754509d7400c1de6910955e89ad1 | 5,470 | package pw.cdmi.core.cache.config;
import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.transcoders.CachedData;
import org.apache.commons.lang3.ArrayUtils;
public class CacheConfig
{
private String poolName;
private String[] servers;
private int port;
private int maxConns = 500;
private int socketTimeout = 3000;
private int socketConnectTimeout = 100;
private long defaultCacheTimeout = 10 * 60 * 1000;
private String cacheKeyPrefix;
private boolean binaryProtocal = false;
private boolean aliveCheck = false;
private boolean failback = true;
private boolean failover = true;
private int socketReceiveBuffer = 64;
private int socketSendBuffer = 32;
private boolean tcpNoDelay = false;
private long sessionIdleTimeout = 5000;
// 能够存放到cache中的数据的最大值
// 默认值为1MB
private int cacheDataMaxSize = CachedData.MAX_SIZE;
private int maxQueuedNoReplyOperations = MemcachedClient.DEFAULT_MAX_QUEUED_NOPS;
private boolean needCheckTransferQueueSize = false;
private int opTimeout = 5000;
public String getPoolName()
{
return poolName;
}
public void setPoolName(String poolName)
{
this.poolName = poolName;
}
public String[] getServers()
{
if (servers == null)
{
return ArrayUtils.EMPTY_STRING_ARRAY;
}
return servers.clone();
}
public void setServers(String[] servers)
{
if (servers == null)
{
this.servers = ArrayUtils.EMPTY_STRING_ARRAY;
}
else
{
this.servers = servers.clone();
}
}
public int getPort()
{
return port;
}
public void setPort(int port)
{
this.port = port;
}
public int getMaxConns()
{
return maxConns;
}
public void setMaxConns(int maxConns)
{
this.maxConns = maxConns;
}
public int getSocketTimeout()
{
return socketTimeout;
}
public void setSocketTimeout(int socketTimeout)
{
this.socketTimeout = socketTimeout;
}
public int getSocketConnectTimeout()
{
return socketConnectTimeout;
}
public void setSocketConnectTimeout(int socketConnectTimeout)
{
this.socketConnectTimeout = socketConnectTimeout;
}
public long getDefaultCacheTimeout()
{
return defaultCacheTimeout;
}
public void setDefaultCacheTimeout(long defaultCacheTimeout)
{
this.defaultCacheTimeout = defaultCacheTimeout;
}
public String getCacheKeyPrefix()
{
return cacheKeyPrefix;
}
public void setCacheKeyPrefix(String cacheKeyPrefix)
{
this.cacheKeyPrefix = cacheKeyPrefix;
}
public boolean isBinaryProtocal()
{
return binaryProtocal;
}
public void setBinaryProtocal(boolean binaryProtocal)
{
this.binaryProtocal = binaryProtocal;
}
public boolean isAliveCheck()
{
return aliveCheck;
}
public void setAliveCheck(boolean aliveCheck)
{
this.aliveCheck = aliveCheck;
}
public boolean isFailback()
{
return failback;
}
public void setFailback(boolean failback)
{
this.failback = failback;
}
public boolean isFailover()
{
return failover;
}
public void setFailover(boolean failover)
{
this.failover = failover;
}
public int getSocketReceiveBuffer()
{
return socketReceiveBuffer;
}
public void setSocketReceiveBuffer(int socketReceiveBuffer)
{
this.socketReceiveBuffer = socketReceiveBuffer;
}
public int getSocketSendBuffer()
{
return socketSendBuffer;
}
public void setSocketSendBuffer(int socketSendBuffer)
{
this.socketSendBuffer = socketSendBuffer;
}
public boolean isTcpNoDelay()
{
return tcpNoDelay;
}
public void setTcpNoDelay(boolean tcpNoDelay)
{
this.tcpNoDelay = tcpNoDelay;
}
public long getSessionIdleTimeout()
{
return sessionIdleTimeout;
}
public void setSessionIdleTimeout(long sessionIdleTimeout)
{
this.sessionIdleTimeout = sessionIdleTimeout;
}
public int getCacheDataMaxSize()
{
return cacheDataMaxSize;
}
public void setCacheDataMaxSize(int cacheDataMaxSize)
{
this.cacheDataMaxSize = cacheDataMaxSize;
}
public int getMaxQueuedNoReplyOperations()
{
return maxQueuedNoReplyOperations;
}
public void setMaxQueuedNoReplyOperations(int maxQueuedNoReplyOperations)
{
this.maxQueuedNoReplyOperations = maxQueuedNoReplyOperations;
}
public int getOpTimeout()
{
return opTimeout;
}
public void setOpTimeout(int opTimeout)
{
this.opTimeout = opTimeout;
}
public boolean isNeedCheckTransferQueueSize()
{
return needCheckTransferQueueSize;
}
public void setNeedCheckTransferQueueSize(boolean needCheckTransferQueueSize)
{
this.needCheckTransferQueueSize = needCheckTransferQueueSize;
}
}
| 20.877863 | 85 | 0.621024 |
9c1bd6e1184e9a8272871f724e2a2d8a52cb88cf | 2,965 | package com.appblade.framework.authenticate;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.appblade.framework.AppBlade;
import com.appblade.framework.WebServiceHelper;
/**
* Activity to prompt the user to authorize themselves to use the app. <br>
* Prompts a WebView that talks to AppBlade where the user signs in with their valid credentials.<br>
* WARNING: Uses javascript. If you are using a custom endpoint make sure you trust the site you are accessing.<br>
*/
@SuppressLint("SetJavaScriptEnabled")
public class RemoteAuthorizeActivity extends Activity {
private static final String EndpointAuthNew = "/oauth/authorization/new?client_id=%s&response_type=code";
ProgressDialog progress;
AuthJavascriptInterface jsInterface;
WebView webview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
webview = new WebView(this);
setContentView(webview);
initControls();
}
/**
* Initializes the WebView and defines the WebClient behavior.
*/
private void initControls() {
String path = String.format(EndpointAuthNew, AppBlade.appInfo.Token);
final String authUrl = WebServiceHelper.getUrl(path);
Log.v(AppBlade.LogTag, "Loading URL in WebView " + authUrl);
jsInterface = new AuthJavascriptInterface(RemoteAuthorizeActivity.this);
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webview.addJavascriptInterface(jsInterface, "Android");
webview.setWebChromeClient(new WebChromeClient() {
@Override
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
setProgress(progress * 100);
}
});
webview.setWebViewClient(new WebViewClient() {
@Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(progress != null && progress.isShowing())
progress.dismiss();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if(progress == null || !progress.isShowing())
progress = ProgressDialog.show(RemoteAuthorizeActivity.this, null, "loading...");
}
});
webview.loadUrl(authUrl);
}
}
| 34.08046 | 115 | 0.718381 |
ef34813e93422ce954f1a49544074f511b82dda5 | 9,179 | package twg2.parser.jsonLite;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import twg2.parser.textParser.TextCharsParser;
import twg2.parser.textParser.TextParser;
import twg2.parser.textParserUtils.ReadIsMatching;
import twg2.parser.textParserUtils.ReadMatching;
import twg2.parser.textParserUtils.ReadWhitespace;
import twg2.text.stringUtils.StringCheck;
/**
* @author TeamworkGuy2
* @since 2014-9-2
*/
public class JsonLiteArray {
private static final char ARRAY_START = '[';
private static final char ARRAY_END = ']';
/**
* @see #parseArray(String, List)
*/
public static final List<String> parseArray(String arrayString) {
List<String> ary = new ArrayList<>();
parseArray(arrayString, ary);
return ary;
}
/**
* @see JsonLiteArray#parseArray(TextParser, boolean, List)
*/
public static final void parseArray(String arrayString, List<String> dst) {
parseArray(TextCharsParser.of(arrayString), true, dst);
}
/** Parses a JSON style array where the strings do not need to be quoted.
* Supports the following formats:<br>
* {@code [multiple words, 123, false]} parses to {@code ["multiple words", "123", "false"]}<br>
* {@code [string with "comma, separator", last]} parses to {@code ["string with "comma, separator"", "last"]}<br>
* {@code ["bilbo baggins", middle earth]} parses to {@code ["bilbo baggins", "middle earth"]}
*
* @param in the {@link TextParser} to read from
* @param readLeadingArrayWhitespace true to read leading whitespace before the array, false to not
* @param dst the destination list to store the parsed array elements in
*/
public static final void parseArray(TextParser in, boolean readLeadingArrayWhitespace, List<String> dst) {
@SuppressWarnings({ "unchecked", "rawtypes" })
List<Object> dstList = (List)dst;
parseArrayLike(in, readLeadingArrayWhitespace, true, ',', false, StringCheck.SIMPLE_WHITESPACE, true, ARRAY_START, true, ARRAY_END, false, dstList);
}
/** Read a JSON array with leading element whitespace, required '[' ']' start and end chars,
* and {@link StringCheck#SIMPLE_WHITESPACE} whitespace characters
* @see #parseArrayLike
*/
public static final void parseArrayDeep(TextParser in, boolean readLeadingArrayWhitespace, List<Object> dst) {
parseArrayLike(in, readLeadingArrayWhitespace, true, ',', false, StringCheck.SIMPLE_WHITESPACE, true, ARRAY_START, true, ARRAY_END, true, dst);
}
/** Read a JSON style array with no start mark, with leading array and element whitespace,
* no newlines inside elements, and {@link StringCheck#SIMPLE_WHITESPACE} whitespace characters
* @see #parseArrayLike
*/
public static final void parseArrayLine(TextParser in, boolean readLeadingArrayWhitespace, List<String> dst) {
parseArrayLikeLine(in, readLeadingArrayWhitespace, true, false, StringCheck.SIMPLE_WHITESPACE, dst);
}
/** Read a JSON array with leading element whitespace, required '[' ']' start and end chars,
* and {@link StringCheck#SIMPLE_WHITESPACE} whitespace characters
* @see #parseArrayLike
*/
public static final void parseArrayLineDeep(TextParser in, boolean readLeadingArrayWhitespace, boolean readLeadingElementWhitespace, List<Object> dst) {
parseArrayLike(in, readLeadingArrayWhitespace, readLeadingElementWhitespace, ',', false, StringCheck.SIMPLE_WHITESPACE, false, ARRAY_START, false, ARRAY_END, true, dst);
}
/** Read a JSON style array with no start mark that ends at the end of the current line
* @see #parseArrayLike
*/
public static final void parseArrayLikeLine(TextParser in, boolean readLeadingArrayWhitespace, boolean readLeadingElementWhitespace, boolean allowNewlineInElement,
char[] whitespace, List<String> dst) {
@SuppressWarnings({ "unchecked", "rawtypes" })
List<Object> dstList = (List)dst;
parseArrayLike(in, readLeadingArrayWhitespace, readLeadingElementWhitespace, ',', false, whitespace, false, '\0', false, '\n', false, dstList);
}
/** Read JSON like array with options to read a single line, customize the element separator char, allow newlines, etc.<br>
* For example, to read a JSON style array with leading whitespace, call:<br>
* <pre>parseArrayLike(in, true, true, ',', false, new char[] { ' ', '\t', '\n' }, true, '[', ']', dst);</pre>
*
* @param in the char source to read from
* @param readLeadingArrayWhitespace true to read leading {@code whitespace} chars before checking for the {@code startChar}
* @param readLeadingElementWhitespace true to read leading {@code whitespace} chars before reading each array element
* @param elementSeparator the char that separates array elements, does not apply if it appears inside a quoted string element
* @param allowNewlineInElement true if newlines are allowed inside element strings/text
* @param whitespace the legal whitespace characters when {@code readLeadingArrayWhitespace}
* or {@code readLeadingElementWhitespace} are true
* @param requireStartChar true if a start character is required before the first array element is read
* @param startChar the start character to read if {@code requireStartChar} is true
* @param requireEndChar true if the end character is required after the last element is read
* @param endChar the required end char to read (this character marks the end of the
* array only when it appears between elements where an {@code elementSeparator} is expected)
* @param dst the parsed element strings or nested lists of strings are added to the end of this list
*/
public static final void parseArrayLike(TextParser in, boolean readLeadingArrayWhitespace, boolean readLeadingElementWhitespace,
char elementSeparator, boolean allowNewlineInElement, char[] whitespace,
boolean requireStartChar, char startChar, boolean requireEndChar, char endChar, boolean allowNestedArrays, List<Object> dst) {
char escapeChar = '"';
char replaceChar = '\\';
char newlineChar = '\n';
StringBuilder strDst = new StringBuilder();
boolean foundEnd = false;
if(readLeadingArrayWhitespace) {
ReadWhitespace.readWhitespaceCustom(in, whitespace);
}
// require the first character to be an array start
if(requireStartChar && !in.nextIf(startChar)) {
throw new IllegalStateException("an array must start with '" + startChar + "'");
}
if(requireEndChar && !in.hasNext()) { throw new IllegalStateException("could not find end of array '" + endChar + "'"); }
for(int i = 0; in.hasNext(); i++) {
int startElemPos = in.getPosition();
if(readLeadingElementWhitespace) {
ReadWhitespace.readWhitespaceCustom(in, whitespace);
}
if((i == 0 && in.nextIf(endChar)) || (!requireEndChar && !in.hasNext())) {
foundEnd = true;
break;
}
strDst.setLength(0);
// read nested array
if(allowNestedArrays && ReadIsMatching.isNext(in, startChar)) {
ArrayList<Object> nestedDst = new ArrayList<>();
JsonLiteArray.parseArrayLike(in, readLeadingArrayWhitespace, readLeadingElementWhitespace, elementSeparator, allowNewlineInElement, whitespace,
true, startChar, true, endChar, allowNestedArrays, nestedDst);
dst.add(nestedDst);
// the nested array is required to have a closing char so can safely read trailing whitespace, for example in "[a, [b] ]"
ReadWhitespace.readWhitespaceCustom(in, whitespace);
}
// read normal array element (string or partially quoted string)
else {
JsonLiteArray.readArrayElementLike(in, replaceChar, escapeChar, elementSeparator, endChar, allowNewlineInElement, newlineChar, strDst);
dst.add(strDst.toString());
}
if(in.nextIf(endChar)) {
// leave the ending char and mark end of array reached
foundEnd = true;
break;
}
// read end char since readArrayElementLike does not read the ending char (it could be either ',' or ']')
in.unread(1);
boolean prevCharWasElemSeparator = false;
if(!(prevCharWasElemSeparator = in.nextIf(elementSeparator)) || startElemPos == in.getPosition()) {
if(!prevCharWasElemSeparator) {
in.nextChar();
}
in.nextIf(elementSeparator);
}
}
if(requireEndChar && !foundEnd) { throw new IllegalStateException("could not find end of array '" + endChar + "'"); }
}
/**
* @param in
* @param chReplace
* @param chEsc
* @param chEnd
* @param allowNewline
* @param newlineChar
* @param dst
* @return true if the read string contained a quoted section part way through it,
* false if it contained no quotes or was fully quoted
*/
public static final boolean readArrayElementLike(TextParser in, char chReplace, char chEsc, char chEnd, char chEnd2, boolean allowNewline, char newlineChar, Appendable dst) {
boolean partialQuoted = false;
try {
int readUnescaped = in.nextIfNot(chEsc, chEnd, chEnd2, 0, dst);
if(in.nextIf(chEsc)) {
partialQuoted = true;
if(readUnescaped > 0) {
dst.append(chEsc);
}
ReadMatching.readUnescape(in, chReplace, chEsc, allowNewline, newlineChar, dst);
if(readUnescaped > 0) {
dst.append(chEsc);
}
in.nextIf(chEnd);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return partialQuoted;
}
}
| 43.093897 | 175 | 0.733413 |
4f19be987f0145a9d673f888a0c3ddfeba2eda0a | 15 | public Test{
}
| 5 | 12 | 0.666667 |
07115f28cc606532fbfdbd3167d918fd9f123eae | 1,745 | /*
* (c) 2016-2021 Swirlds, Inc.
*
* This software is owned by Swirlds, Inc., which retains title to the software. This software is protected by various
* intellectual property laws throughout the world, including copyright and patent laws. This software is licensed and
* not sold. You must use this software only in accordance with the terms of the Hashgraph Open Review license at
*
* https://github.com/hashgraph/swirlds-open-review/raw/master/LICENSE.md
*
* SWIRLDS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THIS SOFTWARE, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
* OR NON-INFRINGEMENT.
*/
package com.swirlds.common.settings;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import java.io.IOException;
import java.time.Duration;
import static com.swirlds.common.settings.ParsingUtils.parseDuration;
/**
* This object is capable of parsing durations, e.g. "3 seconds", "1 day", "2.5 hours", "32ms".
* <p>
* This deserializer currently utilizes a regex for parsing, which may have superlinear time complexity
* for arbitrary input. Until that is addressed, do not use this parser on untrusted strings.
*/
public class DurationDeserializer extends StdDeserializer<Duration> {
private static final long serialVersionUID = 1;
public DurationDeserializer() {
super(Duration.class);
}
/**
* {@inheritDoc}
*/
@Override
public Duration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return parseDuration(p.readValueAs(String.class));
}
}
| 36.354167 | 118 | 0.774785 |
5682199450cab0881024c4ce5d23d0e7616550b7 | 2,330 | package cl.bhp.middleware.util;
import cl.bhp.middleware.exception.ServiceException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionFactory {
Connection conn = null;
static PropertiesUtil prop = new PropertiesUtil();
static public enum DataBaseSchema {
CLIENTE, NEGOCIO;
}
public static Connection getConnection(DataBaseSchema shema) throws ServiceException, SQLException, ClassNotFoundException {
String user = "";
String password = "";
String host = "";
String port = "";
String databaseName = "";
Properties props = new Properties();
switch (shema) {
case CLIENTE:
user = prop.getLocalProperties().getProperty("postgress.cliente.user");
password = prop.getLocalProperties().getProperty("postgress.cliente.password");
host = prop.getLocalProperties().getProperty("postgress.cliente.host");
port = prop.getLocalProperties().getProperty("postgress.cliente.port");
databaseName = prop.getLocalProperties().getProperty("postgress.cliente.databaseName");
// TODO cambiar a archivo properties valor
// props.setProperty("loginTimeout", "2000");
props.setProperty("user", user);
props.setProperty("password", password);
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/" + databaseName,props);
case NEGOCIO:
user = prop.getLocalProperties().getProperty("postgress.negocio.user");
password = prop.getLocalProperties().getProperty("postgress.negocio.password");
host = prop.getLocalProperties().getProperty("postgress.negocio.host");
port = prop.getLocalProperties().getProperty("postgress.negocio.port");
databaseName = prop.getLocalProperties().getProperty("postgress.negocio.databaseName");
// TODO cambiar a archivo properties valor
// props.setProperty("loginTimeout", "2000");
props.setProperty("user", user);
props.setProperty("password", password);
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/" + databaseName, props);
default:
return null;
}
}
public void closeConnection() {
try {
this.conn.close();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
} | 33.768116 | 125 | 0.704292 |
7e963bc6dbd628fbf166b693d172991863fdf0c1 | 266 | package headfirstdesignpatterns.singleton;
class BadSingleton {
private static BadSingleton instance;
private BadSingleton() {}
public void getInstance() {
if (instance == null) {
instance = new BadSingleton();
}
}
}
| 16.625 | 42 | 0.62406 |
7a1e8a546ea9c72cf47c4d2b3948a1c60bafc09d | 310 | package com.hs.request;
public class SaveAreaRequest {
private String area;
private Integer pid;
public String getArea() {
return area;
}
public void setArea(String area) {
this.area = area;
}
public Integer getPid() {
return pid;
}
public void setPid(Integer pid) {
this.pid = pid;
}
}
| 14.090909 | 35 | 0.680645 |
6ee9efec4b9de2fcec09e095f9763562711d1e83 | 944 | package com.xpf.imitateviewpager.widget;
import android.content.Context;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Scroller;
public class MyImageView extends AppCompatImageView {
private Scroller mScroller;
private static final String TAG = MyImageView.class.getSimpleName();
public MyImageView(Context context, AttributeSet attrs) {
super(context, attrs);
mScroller = new Scroller(context);
}
public void reset() {
mScroller.startScroll(getScrollX(), getScrollY(), -getScrollX(), -getScrollY(), 1000);
invalidate();
}
@Override
public void computeScroll() {
if (mScroller.computeScrollOffset()) {//滑动还没有完成
Log.e(TAG, "CurrX=" + mScroller.getCurrX());
scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
invalidate();
}
}
}
| 28.606061 | 94 | 0.679025 |
e2aeea4e49333651ecbfd89f12559d4842f178e5 | 1,258 | package org.aesy.musicbrainz.client;
import io.specto.hoverfly.junit.dsl.StubServiceBuilder;
import org.aesy.musicbrainz.util.MusicBrainzTest;
import org.aesy.musicbrainz.util.Resources;
import org.aesy.musicbrainz.util.Simulation;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import java.util.UUID;
import static io.specto.hoverfly.junit.dsl.ResponseCreators.success;
public class MusicBrainzJerseyClientTest
extends MusicBrainzTest {
@Test
@DisplayName("Custom user agent")
public void useragent() {
UUID mbid = UUID.randomUUID();
String userAgent = "This is a custom user agent";
MusicBrainzClient client = clientBuilder()
.userAgent(userAgent)
.build();
StubServiceBuilder request = get("artist/" + mbid)
.header(HttpHeaders.USER_AGENT, userAgent)
.willReturn(success(Resources.readString("metadata.xml"), MediaType.APPLICATION_XML));
Simulation simulation = simulate(request);
MusicBrainzResponse<?> response = client
.artist()
.withId(mbid)
.lookup();
simulation.verify();
}
}
| 28.590909 | 98 | 0.693959 |
2346f16b9909293a30386eb34dd96e829fbe523c | 406 | package com.xiangju.mapper;
import com.xiangju.domain.CommentTopic;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface CommentTopicMapper {
void addComment(CommentTopic comment);
List<CommentTopic> getTopicComments(int topic);
List<CommentTopic> getTopicCommentReplys(int replayid);
}
| 22.555556 | 59 | 0.805419 |
f3ff9a0e046c68ab3b2e714b49ad0dcc440d3b1e | 1,798 | package mysql.dao;
import mysql.entity.Position;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class PositionDAO {
private JdbcTemplate template;
private SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
public void setDataSource(DataSource dataSource){
this.template = new JdbcTemplate(dataSource);
}
public List findAll(long id){
final String FIND_ALL_SQL =
"select ID, SIM, SENDTIME, LON, LAT, DIRECTION, VELOCITY from HIS_LOCATION_"
+sdf.format(new Date())+" WHERE ID > ?";
return this.template.query(
FIND_ALL_SQL,
new Object[]{id},
new RowMapper() {
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Position position = new Position();
position.setId(resultSet.getLong("ID"));
position.setSim(resultSet.getString("SIM"));
position.setCreateTime(resultSet.getString("SENDTIME"));
position.setLongitude(0);
position.setLatitude(0);
position.setLongitudeValue(resultSet.getDouble("LON"));
position.setLatitudeValue(resultSet.getDouble("LAT"));
position.setDirection(resultSet.getDouble("DIRECTION"));
position.setSpeed(resultSet.getDouble("VELOCITY"));
return position;
}
});
}
}
| 38.255319 | 92 | 0.591212 |
e9fd8ff044a816326833af9660279847d9f414bd | 403 | package com.projects.melih.wonderandwander.ui.base;
import android.support.annotation.NonNull;
/**
* Created by Melih Gültekin on 22.04.2018
*/
public interface NavigationListener {
void onBackPressed();
void replaceFragment(@NonNull BaseFragment newFragment);
void replaceFragment(@NonNull BaseFragment newFragment, @BaseActivity.SlideAnimType int animType, boolean addToBackStack);
} | 28.785714 | 126 | 0.789082 |
25f2993aa40be947b7c7e87145b85191fc07676e | 2,045 | package com.skytala.eCommerce.domain.party.relations.person.command;
import org.apache.ofbiz.entity.Delegator;
import org.apache.ofbiz.entity.DelegatorFactory;
import org.apache.ofbiz.entity.GenericEntityException;
import org.apache.ofbiz.entity.GenericValue;
import org.apache.ofbiz.entity.GenericEntityNotFoundException;
import com.skytala.eCommerce.domain.party.relations.person.event.PersonUpdated;
import com.skytala.eCommerce.domain.party.relations.person.model.Person;
import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException;
import com.skytala.eCommerce.framework.pubsub.Broker;
import com.skytala.eCommerce.framework.pubsub.Command;
import com.skytala.eCommerce.framework.pubsub.Event;
public class UpdatePerson extends Command {
private Person elementToBeUpdated;
public UpdatePerson(Person elementToBeUpdated){
this.elementToBeUpdated = elementToBeUpdated;
}
public Person getElementToBeUpdated() {
return elementToBeUpdated;
}
public void setElementToBeUpdated(Person elementToBeUpdated){
this.elementToBeUpdated = elementToBeUpdated;
}
@Override
public Event execute() throws RecordNotFoundException{
Delegator delegator = DelegatorFactory.getDelegator("default");
boolean success;
try{
GenericValue newValue = delegator.makeValue("Person", elementToBeUpdated.mapAttributeField());
delegator.store(newValue);
if(delegator.store(newValue) == 0) {
throw new RecordNotFoundException(Person.class);
}
success = true;
} catch (GenericEntityException e) {
e.printStackTrace();
if(e.getCause().getClass().equals(GenericEntityNotFoundException.class)) {
throw new RecordNotFoundException(Person.class);
}
success = false;
}
Event resultingEvent = new PersonUpdated(success);
Broker.instance().publish(resultingEvent);
return resultingEvent;
}
}
| 36.517857 | 106 | 0.721271 |
5109841606d5f1681362bdb43f79279b3ffcc5d1 | 15,512 | package seedu.address.logic.parser;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.logic.parser.ParserUtil.MESSAGE_INVALID_INDEX;
import static seedu.address.testutil.Assert.assertThrows;
import static seedu.address.testutil.TypicalIndexes.INDEX_FIRST_PERSON;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.junit.jupiter.api.Test;
import seedu.address.logic.parser.exceptions.ParseException;
import seedu.address.model.information.Address;
import seedu.address.model.information.BlacklistStatus;
import seedu.address.model.information.Date;
import seedu.address.model.information.Email;
import seedu.address.model.information.Experience;
import seedu.address.model.information.Name;
import seedu.address.model.information.Phone;
import seedu.address.model.information.Priority;
import seedu.address.model.information.Salary;
import seedu.address.model.information.UrlLink;
import seedu.address.model.tag.Tag;
public class ParserUtilTest {
private static final String INVALID_NAME = "R@chel";
private static final String INVALID_PHONE = "+651234";
private static final String INVALID_ADDRESS = " ";
private static final String INVALID_EMAIL = "example.com";
private static final String INVALID_TAG = "#friend";
private static final String INVALID_PRIORITY = "urgent";
private static final String INVALID_EXPERIENCE = "-3";
private static final String INVALID_URL = "linkedin";
private static final String INVALID_SALARY = "-2000";
private static final String INVALID_DATE = "2 Dec 2121";
private static final String INVALID_BLACKLIST_STATUS = "no";
private static final String VALID_NAME = "Rachel Walker";
private static final String VALID_PHONE = "123456";
private static final String VALID_ADDRESS = "123 Main Street #0505";
private static final String VALID_EMAIL = "rachel@example.com";
private static final String VALID_TAG_1 = "friend";
private static final String VALID_TAG_2 = "neighbour";
private static final String VALID_PRIORITY = "high";
private static final String VALID_MODERATE_PRIORITY = "moderate";
private static final String VALID_EXPERIENCE = "3";
private static final String VALID_URL_LINK = "linkedin.com";
private static final String VALID_SALARY = "13000";
private static final String VALID_DATE = "08-08-19";
private static final String VALID_BLACKLIST_STATUS = "true";
private static final String WHITESPACE = " \t\r\n";
@Test
public void parseIndex_invalidInput_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parseIndex("10 a"));
}
@Test
public void parseIndex_outOfRangeInput_throwsParseException() {
assertThrows(ParseException.class, MESSAGE_INVALID_INDEX, ()
-> ParserUtil.parseIndex(Long.toString(Integer.MAX_VALUE + 1)));
}
@Test
public void parseIndex_validInput_success() throws Exception {
// No whitespaces
assertEquals(INDEX_FIRST_PERSON, ParserUtil.parseIndex("1"));
// Leading and trailing whitespaces
assertEquals(INDEX_FIRST_PERSON, ParserUtil.parseIndex(" 1 "));
}
@Test
public void parseName_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseName((String) null));
}
@Test
public void parseName_invalidValue_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parseName(INVALID_NAME));
}
@Test
public void parseName_validValueWithoutWhitespace_returnsName() throws Exception {
Name expectedName = new Name(VALID_NAME);
assertEquals(expectedName, ParserUtil.parseName(VALID_NAME));
}
@Test
public void parseName_validValueWithWhitespace_returnsTrimmedName() throws Exception {
String nameWithWhitespace = WHITESPACE + VALID_NAME + WHITESPACE;
Name expectedName = new Name(VALID_NAME);
assertEquals(expectedName, ParserUtil.parseName(nameWithWhitespace));
}
@Test
public void parsePhone_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parsePhone((String) null));
}
@Test
public void parsePhone_invalidValue_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parsePhone(INVALID_PHONE));
}
@Test
public void parsePhone_validValueWithoutWhitespace_returnsPhone() throws Exception {
Phone expectedPhone = new Phone(VALID_PHONE);
assertEquals(expectedPhone, ParserUtil.parsePhone(VALID_PHONE));
}
@Test
public void parsePhone_validValueWithWhitespace_returnsTrimmedPhone() throws Exception {
String phoneWithWhitespace = WHITESPACE + VALID_PHONE + WHITESPACE;
Phone expectedPhone = new Phone(VALID_PHONE);
assertEquals(expectedPhone, ParserUtil.parsePhone(phoneWithWhitespace));
}
@Test
public void parseAddress_invalidValue_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parseAddress(INVALID_ADDRESS));
}
@Test
public void parseAddress_validValueWithoutWhitespace_returnsAddress() throws Exception {
Address expectedAddress = new Address(VALID_ADDRESS);
assertEquals(expectedAddress, ParserUtil.parseAddress(VALID_ADDRESS));
}
@Test
public void parseAddress_validValueWithWhitespace_returnsTrimmedAddress() throws Exception {
String addressWithWhitespace = WHITESPACE + VALID_ADDRESS + WHITESPACE;
Address expectedAddress = new Address(VALID_ADDRESS);
assertEquals(expectedAddress, ParserUtil.parseAddress(addressWithWhitespace));
}
@Test
public void parseEmail_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseEmail((String) null));
}
@Test
public void parseEmail_invalidValue_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parseEmail(INVALID_EMAIL));
}
@Test
public void parseEmail_validValueWithoutWhitespace_returnsEmail() throws Exception {
Email expectedEmail = new Email(VALID_EMAIL);
assertEquals(expectedEmail, ParserUtil.parseEmail(VALID_EMAIL));
}
@Test
public void parseEmail_validValueWithWhitespace_returnsTrimmedEmail() throws Exception {
String emailWithWhitespace = WHITESPACE + VALID_EMAIL + WHITESPACE;
Email expectedEmail = new Email(VALID_EMAIL);
assertEquals(expectedEmail, ParserUtil.parseEmail(emailWithWhitespace));
}
@Test
public void parseTag_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseTag(null));
}
@Test
public void parseTag_invalidValue_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parseTag(INVALID_TAG));
}
@Test
public void parseTag_validValueWithoutWhitespace_returnsTag() throws Exception {
Tag expectedTag = new Tag(VALID_TAG_1);
assertEquals(expectedTag, ParserUtil.parseTag(VALID_TAG_1));
}
@Test
public void parseTag_validValueWithWhitespace_returnsTrimmedTag() throws Exception {
String tagWithWhitespace = WHITESPACE + VALID_TAG_1 + WHITESPACE;
Tag expectedTag = new Tag(VALID_TAG_1);
assertEquals(expectedTag, ParserUtil.parseTag(tagWithWhitespace));
}
@Test
public void parseTags_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseTags(null));
}
@Test
public void parseTags_collectionWithInvalidTags_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parseTags(Arrays.asList(VALID_TAG_1, INVALID_TAG)));
}
@Test
public void parseTags_emptyCollection_returnsEmptySet() throws Exception {
assertTrue(ParserUtil.parseTags(Collections.emptyList()).isEmpty());
}
@Test
public void parseTags_collectionWithValidTags_returnsTagSet() throws Exception {
Set<Tag> actualTagSet = ParserUtil.parseTags(Arrays.asList(VALID_TAG_1, VALID_TAG_2));
Set<Tag> expectedTagSet = new HashSet<Tag>(Arrays.asList(new Tag(VALID_TAG_1), new Tag(VALID_TAG_2)));
assertEquals(expectedTagSet, actualTagSet);
}
@Test
public void parsePriorityString_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parsePriorityString((String) null));
}
@Test
public void parsePriorityString_invalidValue_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parsePriorityString(INVALID_PRIORITY));
}
@Test
public void parsePriorityString_validValueWithoutWhitespace_returnsPriority() throws Exception {
Priority expectedPriority = new Priority(VALID_PRIORITY);
assertEquals(expectedPriority, ParserUtil.parsePriorityString(VALID_PRIORITY));
}
@Test
public void parsePriorityString_validValueWithWhitespace_returnsTrimmedPriority() throws Exception {
String priorityWithWhitespace = WHITESPACE + VALID_PRIORITY + WHITESPACE;
Priority expectedPriority = new Priority(VALID_PRIORITY);
assertEquals(expectedPriority, ParserUtil.parsePriorityString(priorityWithWhitespace));
}
@Test
public void parsePriority_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parsePriority(null));
}
@Test
public void parsePriority_listWithInvalidPriority_throwsParseException() {
assertThrows(ParseException.class, () -> ParserUtil.parsePriority(Arrays.asList(INVALID_PRIORITY)));
}
@Test
public void parsePriority_emptyList_returnsModeratePriority() throws Exception {
Priority expectedPriority = new Priority(VALID_MODERATE_PRIORITY);
assertEquals(expectedPriority, ParserUtil.parsePriority(Collections.emptyList()));
}
@Test
public void parsePriority_listWithValidPriority_returnsPriority() throws Exception {
Priority actualPriority = ParserUtil.parsePriority(Arrays.asList(VALID_PRIORITY));
Priority expectedPriority = new Priority(VALID_PRIORITY);
assertEquals(expectedPriority, actualPriority);
}
@Test
public void parseExperience_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseExperience((String) null));
}
@Test
public void parseExperience_invalidValue_throwsParseException() throws Exception {
assertThrows(ParseException.class, () -> ParserUtil.parseExperience(INVALID_EXPERIENCE));
}
@Test
public void parseExperience_validValueWithoutWhitespace_returnsExperience() throws Exception {
Experience expectedExperience = new Experience(VALID_EXPERIENCE);
assertEquals(expectedExperience, ParserUtil.parseExperience(VALID_EXPERIENCE));
}
@Test
public void parseExperience_validValueWithWhitespace_returnsTrimmedExperience() throws Exception {
String experienceWithWhitespace = WHITESPACE + VALID_EXPERIENCE + WHITESPACE;
Experience expectedExperience = new Experience(VALID_EXPERIENCE);
assertEquals(expectedExperience, ParserUtil.parseExperience(experienceWithWhitespace));
}
@Test
public void parseUrlLink_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseUrlLink((String) null));
}
@Test
public void parseUrlLink_invalidValue_throwsParseException() throws Exception {
assertThrows(ParseException.class, () -> ParserUtil.parseUrlLink(INVALID_URL));
}
@Test
public void parseUrlLink_validValueWithoutWhitespace_returnsExperience() throws Exception {
UrlLink expectedUrlLink = new UrlLink(VALID_URL_LINK);
assertEquals(expectedUrlLink, ParserUtil.parseUrlLink(VALID_URL_LINK));
}
@Test
public void parseUrlLink_validValueWithWhitespace_returnsTrimmedExperience() throws Exception {
String urlWithWhitespace = WHITESPACE + VALID_URL_LINK + WHITESPACE;
UrlLink expectedUrlLink = new UrlLink(VALID_URL_LINK);
assertEquals(expectedUrlLink, ParserUtil.parseUrlLink(urlWithWhitespace));
}
@Test
public void parseSalary_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseSalary(((String) null)));
}
@Test
public void parseSalary_invalidValue_throwsParseException() throws Exception {
assertThrows(ParseException.class, () -> ParserUtil.parseSalary(INVALID_SALARY));
}
@Test
public void parseSalary_validValueWithoutWhitespace_returnsExperience() throws Exception {
Salary expectedSalary = new Salary(VALID_SALARY);
assertEquals(expectedSalary, ParserUtil.parseSalary(VALID_SALARY));
}
@Test
public void parseSalary_validValueWithWhitespace_returnsTrimmedExperience() throws Exception {
String salaryWithWhitespace = WHITESPACE + VALID_SALARY + WHITESPACE;
Salary expectedSalary = new Salary(VALID_SALARY);
assertEquals(expectedSalary, ParserUtil.parseSalary(salaryWithWhitespace));
}
@Test
public void parseDate_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseDate(((String) null)));
}
@Test
public void parseDate_invalidValue_throwsParseException() throws Exception {
assertThrows(ParseException.class, () -> ParserUtil.parseDate(INVALID_DATE));
}
@Test
public void parseDate_validValueWithoutWhitespace_returnsExperience() throws Exception {
Date expectedDate = new Date(VALID_DATE);
assertEquals(expectedDate, ParserUtil.parseDate(VALID_DATE));
}
@Test
public void parseDate_validValueWithWhitespace_returnsTrimmedExperience() throws Exception {
String dateWithWhitespace = WHITESPACE + VALID_DATE + WHITESPACE;
Date expectedDate = new Date(VALID_DATE);
assertEquals(expectedDate, ParserUtil.parseDate(dateWithWhitespace));
}
@Test
public void parseBlacklistStatus_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> ParserUtil.parseBlacklistStatus(((String) null)));
}
@Test
public void parseBlacklistStatus_invalidValue_throwsParseException() throws Exception {
assertThrows(ParseException.class, () -> ParserUtil.parseBlacklistStatus(INVALID_BLACKLIST_STATUS));
}
@Test
public void parseBlacklistStatus_validValueWithoutWhitespace_returnsExperience() throws Exception {
BlacklistStatus expectedBlacklistStatus = new BlacklistStatus(VALID_BLACKLIST_STATUS);
assertEquals(expectedBlacklistStatus, ParserUtil.parseBlacklistStatus(VALID_BLACKLIST_STATUS));
}
@Test
public void parseBlacklistStatus_validValueWithWhitespace_returnsTrimmedExperience() throws Exception {
String blacklistStatusWithWhitespace = WHITESPACE + VALID_BLACKLIST_STATUS + WHITESPACE;
BlacklistStatus expectedBlacklistStatus = new BlacklistStatus(VALID_BLACKLIST_STATUS);
assertEquals(expectedBlacklistStatus, ParserUtil.parseBlacklistStatus(blacklistStatusWithWhitespace));
}
}
| 41.587131 | 112 | 0.750774 |
5e6c04e29bf6aa21fdb430421e25f4f34b8de89d | 868 | package edu.mayo.mprc.searchdb.builder;
import edu.mayo.mprc.searchdb.dao.TandemMassSpectrometrySample;
import org.joda.time.DateTime;
import java.io.File;
import java.util.Map;
/**
* Produces dummy information about mass spec files.
*
* @author Roman Zenka
*/
public class DummyMassSpecDataExtractor implements MassSpecDataExtractor {
private DateTime now;
public DummyMassSpecDataExtractor(final DateTime now) {
this.now = now;
}
@Override
public TandemMassSpectrometrySample getTandemMassSpectrometrySample(final String biologicalSampleName, final String msmsSampleName) {
return new TandemMassSpectrometrySample(
new File(msmsSampleName),
now,
0,
0,
0,
"Dummy instrument",
"Dummy #",
now,
0.0,
"",
""
);
}
@Override
public Map<String, TandemMassSpectrometrySample> getMap() {
return null;
}
}
| 20.186047 | 134 | 0.730415 |
76be264e8d27853a3bb0e8262f44918deb614eee | 1,668 | package com.zhaohengsun.learnmath.util;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.view.View;
import android.widget.ResourceCursorAdapter;
import android.widget.TextView;
import com.zhaohengsun.learnmath.R;
/**
* Created by Zhaoheng Sun on 2018/2/26.
*/
public class TaskAdapter extends ResourceCursorAdapter {
protected final static int ROW_LAYOUT = R.layout.task_list_item;
public TaskAdapter(Context context, Cursor cursor) {
super(context, ROW_LAYOUT, cursor, 0);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView isFinishedLine = (TextView) view.findViewById(R.id.isfinished_text);
TextView studentnameLine = (TextView)view.findViewById(R.id.studentname_text);
TextView timelimitLine = (TextView)view.findViewById(R.id.timelimit_text);
// TextView authorLine = (TextView) view.findViewById(android.R.id.text2);
String isfinished = cursor.getString(cursor.getColumnIndex("isfinished"));
if( isfinished.equals("true")) {
isFinishedLine.setText("Completed");
isFinishedLine.setTextColor(Color.parseColor("#32CD32"));
}
else {
isFinishedLine.setText("Not Completed");
isFinishedLine.setTextColor(Color.parseColor("#FF3030"));
}
studentnameLine.setText(cursor.getString(cursor.getColumnIndex("studentname")));
timelimitLine.setText(cursor.getLong(cursor.getColumnIndex("timelimit"))+" Min");
// String authors = cursor.getString(cursor.getColumnIndex("authors"));
}
}
| 32.076923 | 89 | 0.706235 |
c5204352303cfdce081dd7ff3f662d46cf01b59c | 11,785 | package com.hhbgk.webservice.discovery.more;
//----------------------------------------------------
//
// Generated by www.easywsdl.com
// Version: 5.0.8.0
//
// Created by Quasar Development at 04/04/2017
//
//---------------------------------------------------
import java.util.Hashtable;
import org.ksoap2.serialization.*;
public class NTCImagingSettings extends AttributeContainer implements KvmSerializable
{
public NTCBacklightCompensation BacklightCompensation;
public Float Brightness;
public Float ColorSaturation;
public Float Contrast;
public NTCExposure Exposure;
public NTCFocusConfiguration Focus;
public NTCEnums.IrCutFilterMode IrCutFilter;
public Float Sharpness;
public NTCWideDynamicRange WideDynamicRange;
public NTCWhiteBalance WhiteBalance;
public NTCImagingSettingsExtension Extension;
public NTCImagingSettings ()
{
}
public NTCImagingSettings (Object paramObj,NTCExtendedSoapSerializationEnvelope __envelope)
{
if (paramObj == null)
return;
AttributeContainer inObj=(AttributeContainer)paramObj;
if(inObj instanceof SoapObject)
{
SoapObject soapObject=(SoapObject)inObj;
int size = soapObject.getPropertyCount();
for (int i0=0;i0< size;i0++)
{
//if you have compilation error here, please use a ksoap2.jar and ExKsoap2.jar from libs folder (in the generated zip file)
PropertyInfo info=soapObject.getPropertyInfo(i0);
Object obj = info.getValue();
if (info.name.equals("BacklightCompensation"))
{
if(obj!=null)
{
Object j = obj;
this.BacklightCompensation = (NTCBacklightCompensation)__envelope.get(j,NTCBacklightCompensation.class,false);
}
continue;
}
if (info.name.equals("Brightness"))
{
if(obj!=null)
{
if (obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.Brightness = new Float(j.toString());
}
}
else if (obj instanceof Float){
this.Brightness = (Float)obj;
}
}
continue;
}
if (info.name.equals("ColorSaturation"))
{
if(obj!=null)
{
if (obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.ColorSaturation = new Float(j.toString());
}
}
else if (obj instanceof Float){
this.ColorSaturation = (Float)obj;
}
}
continue;
}
if (info.name.equals("Contrast"))
{
if(obj!=null)
{
if (obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.Contrast = new Float(j.toString());
}
}
else if (obj instanceof Float){
this.Contrast = (Float)obj;
}
}
continue;
}
if (info.name.equals("Exposure"))
{
if(obj!=null)
{
Object j = obj;
this.Exposure = (NTCExposure)__envelope.get(j,NTCExposure.class,false);
}
continue;
}
if (info.name.equals("Focus"))
{
if(obj!=null)
{
Object j = obj;
this.Focus = (NTCFocusConfiguration)__envelope.get(j,NTCFocusConfiguration.class,false);
}
continue;
}
if (info.name.equals("IrCutFilter"))
{
if(obj!=null)
{
if (obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.IrCutFilter = NTCEnums.IrCutFilterMode.fromString(j.toString());
}
}
else if (obj instanceof NTCEnums.IrCutFilterMode){
this.IrCutFilter = (NTCEnums.IrCutFilterMode)obj;
}
}
continue;
}
if (info.name.equals("Sharpness"))
{
if(obj!=null)
{
if (obj.getClass().equals(SoapPrimitive.class))
{
SoapPrimitive j =(SoapPrimitive) obj;
if(j.toString()!=null)
{
this.Sharpness = new Float(j.toString());
}
}
else if (obj instanceof Float){
this.Sharpness = (Float)obj;
}
}
continue;
}
if (info.name.equals("WideDynamicRange"))
{
if(obj!=null)
{
Object j = obj;
this.WideDynamicRange = (NTCWideDynamicRange)__envelope.get(j,NTCWideDynamicRange.class,false);
}
continue;
}
if (info.name.equals("WhiteBalance"))
{
if(obj!=null)
{
Object j = obj;
this.WhiteBalance = (NTCWhiteBalance)__envelope.get(j,NTCWhiteBalance.class,false);
}
continue;
}
if (info.name.equals("Extension"))
{
if(obj!=null)
{
Object j = obj;
this.Extension = (NTCImagingSettingsExtension)__envelope.get(j,NTCImagingSettingsExtension.class,false);
}
continue;
}
}
}
}
@Override
public Object getProperty(int propertyIndex) {
//!!!!! If you have a compilation error here then you are using old version of ksoap2 library. Please upgrade to the latest version.
//!!!!! You can find a correct version in Lib folder from generated zip file!!!!!
if(propertyIndex==0)
{
return this.BacklightCompensation!=null?this.BacklightCompensation:SoapPrimitive.NullSkip;
}
if(propertyIndex==1)
{
return this.Brightness!=null?this.Brightness:SoapPrimitive.NullSkip;
}
if(propertyIndex==2)
{
return this.ColorSaturation!=null?this.ColorSaturation:SoapPrimitive.NullSkip;
}
if(propertyIndex==3)
{
return this.Contrast!=null?this.Contrast:SoapPrimitive.NullSkip;
}
if(propertyIndex==4)
{
return this.Exposure!=null?this.Exposure:SoapPrimitive.NullSkip;
}
if(propertyIndex==5)
{
return this.Focus!=null?this.Focus:SoapPrimitive.NullSkip;
}
if(propertyIndex==6)
{
return this.IrCutFilter!=null?this.IrCutFilter.toString():SoapPrimitive.NullSkip;
}
if(propertyIndex==7)
{
return this.Sharpness!=null?this.Sharpness:SoapPrimitive.NullSkip;
}
if(propertyIndex==8)
{
return this.WideDynamicRange!=null?this.WideDynamicRange:SoapPrimitive.NullSkip;
}
if(propertyIndex==9)
{
return this.WhiteBalance!=null?this.WhiteBalance:SoapPrimitive.NullSkip;
}
if(propertyIndex==10)
{
return this.Extension!=null?this.Extension:SoapPrimitive.NullSkip;
}
return null;
}
@Override
public int getPropertyCount() {
return 11;
}
@Override
public void getPropertyInfo(int propertyIndex, @SuppressWarnings("rawtypes") Hashtable arg1, PropertyInfo info)
{
if(propertyIndex==0)
{
info.type = NTCBacklightCompensation.class;
info.name = "BacklightCompensation";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==1)
{
info.type = Float.class;
info.name = "Brightness";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==2)
{
info.type = Float.class;
info.name = "ColorSaturation";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==3)
{
info.type = Float.class;
info.name = "Contrast";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==4)
{
info.type = NTCExposure.class;
info.name = "Exposure";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==5)
{
info.type = NTCFocusConfiguration.class;
info.name = "Focus";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==6)
{
info.type = PropertyInfo.STRING_CLASS;
info.name = "IrCutFilter";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==7)
{
info.type = Float.class;
info.name = "Sharpness";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==8)
{
info.type = NTCWideDynamicRange.class;
info.name = "WideDynamicRange";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==9)
{
info.type = NTCWhiteBalance.class;
info.name = "WhiteBalance";
info.namespace= "http://www.onvif.org/ver10/schema";
}
if(propertyIndex==10)
{
info.type = NTCImagingSettingsExtension.class;
info.name = "Extension";
info.namespace= "http://www.onvif.org/ver10/schema";
}
}
@Override
public void setProperty(int arg0, Object arg1)
{
}
}
| 33.011204 | 140 | 0.450064 |
59aeafef11dad66ef243b8c459c10d322837ec27 | 3,075 | /*
* 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.knowledge;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import software.amazon.smithy.model.Model;
import software.amazon.smithy.model.shapes.OperationShape;
import software.amazon.smithy.model.shapes.Shape;
import software.amazon.smithy.model.shapes.ShapeId;
import software.amazon.smithy.model.shapes.StructureShape;
import software.amazon.smithy.model.shapes.ToShapeId;
import software.amazon.smithy.utils.ListUtils;
/**
* Index of operation IDs to their resolved input, output, and error
* structures.
*
* <p>This index performs no validation that the input, output, and
* errors actually reference valid structures.
*/
public final class OperationIndex implements KnowledgeIndex {
private final Map<ShapeId, StructureShape> inputs = new HashMap<>();
private final Map<ShapeId, StructureShape> outputs = new HashMap<>();
private final Map<ShapeId, List<StructureShape>> errors = new HashMap<>();
public OperationIndex(Model model) {
model.shapes(OperationShape.class).forEach(operation -> {
operation.getInput()
.flatMap(id -> getStructure(model, id))
.ifPresent(shape -> inputs.put(operation.getId(), shape));
operation.getOutput()
.flatMap(id -> getStructure(model, id))
.ifPresent(shape -> outputs.put(operation.getId(), shape));
errors.put(operation.getId(),
operation.getErrors()
.stream()
.map(e -> getStructure(model, e))
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toList()));
});
}
public Optional<StructureShape> getInput(ToShapeId operation) {
return Optional.ofNullable(inputs.get(operation.toShapeId()));
}
public Optional<StructureShape> getOutput(ToShapeId operation) {
return Optional.ofNullable(outputs.get(operation.toShapeId()));
}
public List<StructureShape> getErrors(ToShapeId operation) {
return errors.getOrDefault(operation.toShapeId(), ListUtils.of());
}
private Optional<StructureShape> getStructure(Model model, ToShapeId id) {
return model.getShape(id.toShapeId()).flatMap(Shape::asStructureShape);
}
}
| 39.935065 | 79 | 0.67252 |
6b24437d60fe6a6b6a27fe4a753b9c4bd1bbc5e7 | 5,121 | package de.felixbruns.jotify.media;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import de.felixbruns.jotify.util.Hex;
import de.felixbruns.jotify.util.XMLElement;
public class Media {
/**
* Identifier for this media (32-character string).
*/
protected String id;
/**
* Popularity of this media (from 0.0 to 1.0).
*/
protected float popularity;
/**
* Restrictions of this media.
*/
private List<Restriction> restrictions;
/**
* External ids of this media.
*/
private Map<String, String> externalIds;
/**
* Creates an empty {@link Media} object.
*/
protected Media(){
this.id = null;
this.popularity = Float.NaN;
this.restrictions = new ArrayList<Restriction>();
this.externalIds = new HashMap<String, String>();
}
/**
* Creates a {@link Media} object with the specified {@code id}.
*
* @param id Id of the track.
*
* @throws IllegalArgumentException If the given id is invalid.
*/
protected Media(String id){
/* Check if id string is valid. */
if(id == null || id.length() != 32 || !Hex.isHex(id)){
throw new IllegalArgumentException("Expecting a 32-character hex string.");
}
this.id = id;
this.popularity = Float.NaN;
this.restrictions = new ArrayList<Restriction>();
this.externalIds = new HashMap<String, String>();
}
/**
* Get the medias identifier.
*
* @return A 32-character identifier.
*/
public String getId(){
return this.id;
}
/**
* Set the medias identifier.
*
* @param id A 32-character identifier.
*
* @throws IllegalArgumentException If the given id is invalid.
*/
public void setId(String id){
/* Check if id string is valid. */
if(id == null || id.length() != 32 || !Hex.isHex(id)){
throw new IllegalArgumentException("Expecting a 32-character hex string.");
}
this.id = id;
}
/**
* Get the medias popularity.
*
* @return A decimal value between 0.0 and 1.0 or {@link Float.NAN} if not available.
*/
public float getPopularity(){
return this.popularity;
}
/**
* Set the medias popularity.
*
* @param popularity A decimal value between 0.0 and 1.0 or {@link Float.NAN}.
*
* @throws IllegalArgumentException If the given popularity value is invalid.
*/
public void setPopularity(float popularity){
/* Check if popularity value is valid. */
if(popularity != Float.NaN && (popularity < 0.0 || popularity > 1.0)){
throw new IllegalArgumentException("Expecting a value from 0.0 to 1.0 or Float.NAN.");
}
this.popularity = popularity;
}
/**
* Get the medias restrictions.
*
* @return A {@link List} of {@link Restriction} objects.
*/
public List<Restriction> getRestrictions(){
return this.restrictions;
}
/**
* Check if the media is restricted for the given {@code country} and {@code catalogue}.
*
* @param country A 2-letter country code.
* @param catalogue The catalogue to check.
*
* @return true if it is restricted, false otherwise.
*
* @throws IllegalArgumentException If the given 2-letter country code is invalid.
*/
public boolean isRestricted(String country, String catalogue){
if(country.length() != 2){
throw new IllegalArgumentException("Expecting a 2-letter country code!");
}
for(Restriction restriction : this.restrictions){
if(restriction.isCatalogue(catalogue) &&
(restriction.isForbidden(country) ||
!restriction.isAllowed(country))){
return true;
}
}
return false;
}
/**
* Set the medias restrictions.
*
* @param restrictions A {@link List} of {@link Restriction} objects.
*/
public void setRestrictions(List<Restriction> restrictions){
this.restrictions = restrictions;
}
/**
* Get the medias external identifiers.
*
* @return A {@link Map} of external services and their identifers for the media.
*/
public Map<String, String> getExternalIds(){
return this.externalIds;
}
/**
* Get an external identifier for the specified {@code service}.
*
* @param service The service to get the identifer for.
*
* @return An identifier or null if not available.
*/
public String getExternalId(String service){
return this.externalIds.get(service);
}
/**
* Set the medias external identifiers.
*
* @param externalIds A {@link Map} of external services and their identifers for the media.
*/
public void setExternalIds(Map<String, String> externalIds){
this.externalIds = externalIds;
}
/**
* Create a {@link Media} object from an {@link XMLElement} holding media information.
*
* @param mediaElement An {@link XMLElement} holding media information.
*
* @return A {@link Media} object.
*/
public static Media fromXMLElement(XMLElement mediaElement){
Media media = new Media();
/* Set id. */
if(mediaElement.hasChild("id")){
media.id = mediaElement.getChildText("id");
}
/* Set popularity. */
if(mediaElement.hasChild("popularity")){
media.popularity = Float.parseFloat(mediaElement.getChildText("popularity"));
}
return media;
}
}
| 24.73913 | 93 | 0.669596 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.