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
|
|---|---|---|---|---|---|
bd3589222337e04174e55c931f3e06600f128b8a
| 1,883
|
package com.roomate.service.impl;
import com.roomate.domain.Customer;
import com.roomate.domain.Loan;
import com.roomate.repository.LoanRepository;
import com.roomate.request.LoanRequest;
import com.roomate.service.LoanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
/**
* Created by dogukan.ozturkan on 28.11.2016.
*/
@Service
@Transactional
public class LoanServiceImpl implements LoanService {
@Autowired
private LoanRepository loanRepository;
@Override
@Transactional
public void saveApply(LoanRequest loanRequest, Customer customer) {
Loan loan = new Loan();
loan.setAmount(loanRequest.getAmount());
loan.setTerm(loanRequest.getTerm());
BigDecimal customerMonthlySalary = BigDecimal.TEN.divide(BigDecimal.valueOf(24.0), 3, RoundingMode.CEILING);
BigDecimal customerMonthlyPayment = loanRequest.getAmount().divide(BigDecimal.valueOf(loanRequest.getTerm()), 3, BigDecimal.ROUND_CEILING);
if (customerMonthlySalary.compareTo(customerMonthlyPayment) > 0) {
loan.setCreditStatus(Loan.CreditStatus.APPROVED);
} else {
loan.setCreditStatus(Loan.CreditStatus.REJECTED);
}
loan.setIpAddress(loanRequest.getIpAddress());
loan.setCustomer(customer);
loanRepository.save(loan);
}
@Override
public List<Loan> getLoanApplyByCustomerId(long customerId) {
return loanRepository.findByCustomerId(customerId);
}
@Override
public List<Loan> findByIpAddressAndCustomerId(String ipAddress, long customerId) {
return loanRepository.findByIpAddressAndCustomerId(ipAddress, customerId);
}
}
| 30.868852
| 147
| 0.744557
|
fd73c1cab342891e182deb2d43ad36eef5948118
| 1,050
|
package employees.domain;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.annotation.JsonNaming;
@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)
public class Employee {
String id;
String employeeName;
String employeeSalary;
String employeeAge;
String profileImage;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
public String getEmployeeSalary() {
return employeeSalary;
}
public void setEmployeeSalary(String employeeSalary) {
this.employeeSalary = employeeSalary;
}
public String getEmployeeAge() {
return employeeAge;
}
public void setEmployeeAge(String employeeAge) {
this.employeeAge = employeeAge;
}
public String getProfileImage() {
return profileImage;
}
public void setProfileImage(String profileImage) {
this.profileImage = profileImage;
}
}
| 22.340426
| 61
| 0.771429
|
6fff968bf424739a645367b8b0bbeb9fdc5fe5db
| 405
|
package yanagishima.module;
import com.google.inject.servlet.ServletModule;
import yanagishima.servlet.*;
public class ElasticsearchServletModule extends ServletModule {
@Override
protected void configureServlets() {
bind(ElasticsearchServlet.class);
serve("/elasticsearch").with(ElasticsearchServlet.class);
serve("/elasticsearchQueryStatus").with(ElasticsearchQueryStatusServlet.class);
}
}
| 27
| 81
| 0.812346
|
d400a77c03e9c756c5aeb74b035dee877456a631
| 955
|
package com.mes.msgboard.json;
import java.io.Serializable;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@ApiModel(value="CommentRequest",description="Request object for creating a new comment")
public class CommentRequest implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1262703006369194855L;
@ApiModelProperty(dataType = "Object", required = true, name = "comment", value = "comment")
@NotNull(groups=Default.class)
private CommentData comment;
public CommentRequest(CommentData commentData) {
super();
this.comment = commentData;
}
public CommentRequest() {
super();
// TODO Auto-generated constructor stub
}
public CommentData getCommentData() {
return comment;
}
public void setCommentData(CommentData commentData) {
this.comment= commentData;
}
}
| 22.738095
| 93
| 0.763351
|
73f16d3cf6c7c9f0130ce7a3f10e1249d3b95a80
| 1,738
|
package view;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Labeled;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import main.Main;
public class Controller implements Initializable {
@FXML
Labeled label1, label2;
@FXML
Button button1;
@FXML
TextField IP, port;
boolean cnt = true;
@Override
public void initialize(URL location, ResourceBundle resources) {
System.out.println("View is now loaded!");
}
private static Controller instance;
public Controller() {
instance = this;
}
public void button1Pressod() throws IOException {
if (cnt) {
button1.setText("disconnect");
Main.getInstance().connect(IP.getText(), port.getText());
IP.setDisable(true);
port.setDisable(true);
} else {
button1.setText(" connect ");
Main.getInstance().disconnect();
IP.setDisable(false);
port.setDisable(false);
}
cnt = !cnt;
}
public void mouseHandler(MouseEvent mouseEvent) {
label1.setText(mouseEvent.getEventType() + " " + mouseEvent.getButton()
+ " " + "(X,Y)=(" + mouseEvent.getX() + "," + mouseEvent.getY()
+ ") ");
if (!cnt)
Main.getInstance().sendSignal(
mouseEvent.getEventType() + " " + mouseEvent.getButton()
+ " " + "(X,Y)=(" + mouseEvent.getX() + ","
+ mouseEvent.getY() + ") ");
}
public void keyboardHandler(KeyEvent keyEvent) {
label2.setText(keyEvent.getEventType() + " " + keyEvent.getText());
if (!cnt)
Main.getInstance().sendSignal(
keyEvent.getEventType() + " " + keyEvent.getText());
}
}
| 21.725
| 73
| 0.681818
|
ad55fd414efe856fc5a51c9a0f0af76159567be9
| 9,809
|
/*
Copyright (c) 2000-2019 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
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
STANFORD UNIVERSITY 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.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.protocol;
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.annotation.*;
import org.lockss.app.LockssApp;
import org.lockss.app.LockssDaemon;
import org.lockss.plugin.AuUtil;
import org.lockss.util.*;
import org.lockss.state.*;
import org.lockss.util.os.PlatformUtil;
public class PersistentPeerIdSetImpl implements PersistentPeerIdSet {
private static Logger log = Logger.getLogger();
// Static constants
protected static final String TEMP_EXTENSION = ".temp";
// Internal variables
protected String auid;
@JsonIgnore
protected Set<PeerIdentity> peerSet = new HashSet<>();
protected Set<String> rawSet = new HashSet<>();
@JsonIgnore
protected IdentityManager m_identityManager;
@JsonIgnore
protected boolean m_changed = false;
public PersistentPeerIdSetImpl(IdentityManager identityManager) {
m_identityManager = identityManager;
}
/**
* Constructor.
*
* @param auid
* A String with the Archival Unit identifier.
* @param identityManager
* An {@link IdentityManager} to translate {@link String}s to
* {@link PeerIdentity} instances.
*/
public PersistentPeerIdSetImpl(String auid, IdentityManager identityManager) {
this.auid = auid;
m_identityManager = identityManager;
}
/**
* Creates and provides a new instance.
*
* @param auid
* A String with the Archival Unit identifier.
* @param idMgr
* An {@link IdentityManager} to translate {@link String}s to
* {@link PeerIdentity} instances.
* @return a PersistentPeerIdSetImpl with the newly created object.
*/
public static PersistentPeerIdSetImpl make(String auid,
IdentityManager idMgr) {
PersistentPeerIdSetImpl ppisi = new PersistentPeerIdSetImpl(auid, idMgr);
return ppisi;
}
/**
* Factory method for json/Jackson. This creates a "bean" instance which
* is used only as a source from which to copy data, then it is
* discarded. Hence, idMgr is not needed.
* @param auid The AUID
*/
@JsonCreator
public static PersistentPeerIdSetImpl make(@JsonProperty("auid") String auid) {
PersistentPeerIdSetImpl res = new PersistentPeerIdSetImpl(auid, null);
return res;
}
/** Store the set and retain in memory
*/
public void store() throws IOException {
throw new UnsupportedOperationException("Storing PersistentPeerIdSet is currently only implemented for DatedPeerIdSet");
}
protected StateManager getStateMgr() {
return LockssDaemon.getManagerByTypeStatic(StateManager.class);
}
/** Release resources without saving */
public void release() {
}
public boolean add(PeerIdentity pi) {
boolean result;
result = peerSet.add(pi);
m_changed |= result;
return result;
}
public boolean addAll(Collection<? extends PeerIdentity> cpi) {
boolean result;
result = peerSet.addAll(cpi);
m_changed |= result;
return result;
}
public void clear() {
if (!peerSet.isEmpty()) {
peerSet.clear();
m_changed = true;
}
}
public boolean contains(Object o) {
return peerSet.contains(o);
}
public boolean containsAll(Collection<?> co) {
return peerSet.containsAll(co);
}
// Using class.equals() because this has a subclass
public boolean equals(Object o) {
if (getClass().equals(o.getClass())) {
PersistentPeerIdSetImpl ppis = (PersistentPeerIdSetImpl) o;
return peerSet.equals(ppis.peerSet);
} else {
return false;
}
}
/* A hash code must always return a value; it cannot throw an IOException. */
public int hashCode() {
return peerSet.hashCode();
}
public boolean isEmpty() {
return peerSet.isEmpty();
}
public Iterator<PeerIdentity> iterator() {
return peerSet.iterator();
}
public boolean remove(Object o) {
boolean result;
result = peerSet.remove(o);
m_changed |= result;
return result;
}
public boolean removeAll(Collection<?> c) {
boolean result;
result = peerSet.removeAll(c);
m_changed |= result;
return result;
}
public boolean retainAll(Collection<?> c) {
boolean result;
result = peerSet.retainAll(c);
m_changed |= result;
return result;
}
public int size() {
return peerSet.size();
}
public Object[] toArray() {
return peerSet.toArray();
}
/**
* Provides the AUID.
*
* @return A String with the AUID.
*/
public String getAuid() {
return auid;
}
/**
* Provides a serialized version of this entire object as a JSON string.
*
* @return a String with this object serialized as a JSON string.
* @throws IOException
* if any problem occurred during the serialization.
*/
@Override
public String toJson() throws IOException {
return toJson((Set<PeerIdentity>)null);
}
/**
* Provides a serialized version of this object with the named peers as a JSON
* string.
*
* @param peers
* A Set<PeerIdentity> with the peers to be included.
*
* @return a String with this object serialized as a JSON string.
* @throws IOException
* if any problem occurred during the serialization.
*/
@Override
public synchronized String toJson(Set<PeerIdentity> peers)
throws IOException {
return AuUtil.jsonFromPersistentPeerIdSetImpl(makeBean(peers));
}
/** Return a set of Strings of the keys of the pids in our peerSet that
* are contained in filterPeers */
protected Set<String> makeRawSet(Set<PeerIdentity> filterPeers) {
Set<String> res = new HashSet<>();
for (PeerIdentity pid : peerSet) {
if (filterPeers == null || filterPeers.contains(pid)) {
res.add(pid.getKey());
}
}
return res;
}
/**
* Creates and provides a new instance with the named peers.
*
* @param peers
* A Set<PeerIdentity> with the peers to be included.
* @return a PersistentPeerIdSetImpl with the newly created object.
*/
PersistentPeerIdSetImpl makeBean(Set<PeerIdentity> peers) {
PersistentPeerIdSetImpl res =
new PersistentPeerIdSetImpl(auid, m_identityManager);
res.rawSet = makeRawSet(peers);
return res;
}
/** Return a set of PeerIdentity created from the supplied id strings */
protected Set<PeerIdentity> internPeerIdSet(IdentityManager idMgr,
Set<String> ids) {
Set<PeerIdentity> res = new HashSet<>();
for (String s : ids) {
try {
res.add(idMgr.findPeerIdentity(s));
} catch (IdentityManager.MalformedIdentityKeyException e) {
throw new IllegalArgumentException("Illegal pid " + s +
" in " + ids, e);
}
}
return res;
}
/**
* Provides the PeerIdentitys that are present in a serialized JSON string.
*
* @param json
* A String with the JSON text.
* @param app
* A LockssApp with the LOCKSS context.
* @return a Set<PeerIdentity> that was updated from the JSON source.
* @throws IOException
* if any problem occurred during the deserialization.
*/
public synchronized Set<PeerIdentity> updateFromJson(String json,
LockssApp app)
throws IOException {
// Deserialize the JSON text into a new, scratch instance.
PersistentPeerIdSetImpl srcSet =
AuUtil.persistentPeerIdSetImplFromJson(json);
// Get the peer identities.
peerSet = internPeerIdSet(m_identityManager, srcSet.rawSet);
postUnmarshal(app);
return peerSet;
}
/**
* Deserializes a JSON string into a new PersistentPeerIdSetImpl object.
*
* @param key
* A String with the Archival Unit identifier.
* @param json
* A String with the JSON text.
* @param daemon
* A LockssDaemon with the LOCKSS daemon.
* @return a PersistentPeerIdSetImpl with the newly created object.
* @throws IOException
* if any problem occurred during the deserialization.
*/
public static PersistentPeerIdSetImpl fromJson(String key, String json,
LockssDaemon daemon)
throws IOException {
PersistentPeerIdSetImpl res =
PersistentPeerIdSetImpl.make(key, daemon.getIdentityManager());
res.updateFromJson(json, daemon);
return res;
}
/**
* Avoids duplicating common strings.
*/
protected void postUnmarshal(LockssApp lockssContext) {
auid = StringPool.AUIDS.intern(auid);
}
}
| 27.47619
| 124
| 0.690488
|
c2ae995a8d097edee9fcfd8570b62f39d3f44379
| 1,854
|
/**
* Copyright 2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sf.katta.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import net.sf.katta.AbstractTest;
import org.junit.Test;
public class ZkConfigurationTest extends AbstractTest {
@Test
public void testSystemProperty() {
try {
System.clearProperty(ZkConfiguration.KATTA_PROPERTY_NAME);
ZkConfiguration conf1 = new ZkConfiguration();
System.setProperty(ZkConfiguration.KATTA_PROPERTY_NAME, "/katta.zk.properties_alt_root");
ZkConfiguration conf2 = new ZkConfiguration();
//
assertEquals("/katta", conf1.getZkRootPath());
assertEquals("/test/katta20090510153800", conf2.getZkRootPath());
//
try {
System.setProperty(ZkConfiguration.KATTA_PROPERTY_NAME, "/not-found");
new ZkConfiguration();
fail("Should have failed");
} catch (RuntimeException e) {
// Good.
}
} finally {
System.clearProperty(ZkConfiguration.KATTA_PROPERTY_NAME);
}
}
@Test
public void testZkParent() {
assertEquals("/katta", ZkConfiguration.getZkParent("/katta/abc"));
assertEquals("/", ZkConfiguration.getZkParent("/katta"));
assertEquals(null, ZkConfiguration.getZkParent("/"));
}
}
| 32.526316
| 95
| 0.709817
|
b3c61bb4ed0e3af20825c2146620fac77ba73050
| 5,694
|
package com.sequenceiq.cloudbreak.service.upgrade.sync;
import static com.sequenceiq.cloudbreak.api.endpoint.v4.common.Status.UPDATE_IN_PROGRESS;
import static com.sequenceiq.cloudbreak.cloud.model.catalog.ImagePackageVersion.CM;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_CM_MIXED_PACKAGE_VERSIONS_FAILED;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_CM_MIXED_PACKAGE_VERSIONS_FAILED_MULTIPLE;
import static com.sequenceiq.cloudbreak.event.ResourceEvent.STACK_CM_MIXED_PACKAGE_VERSIONS_FAILED_NO_CANDIDATE;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.sequenceiq.cloudbreak.cloud.model.catalog.Image;
import com.sequenceiq.cloudbreak.event.ResourceEvent;
import com.sequenceiq.cloudbreak.service.parcel.ClouderaManagerProductTransformer;
import com.sequenceiq.cloudbreak.service.upgrade.sync.common.ParcelInfo;
import com.sequenceiq.cloudbreak.structuredevent.event.CloudbreakEventService;
@Service
public class CandidateImageAwareMixedPackageVersionService {
private static final Logger LOGGER = LoggerFactory.getLogger(CandidateImageAwareMixedPackageVersionService.class);
@Inject
private CloudbreakEventService eventService;
@Inject
private MixedPackageMessageProvider mixedPackageMessageProvider;
@Inject
private MixedPackageVersionComparator mixedPackageVersionComparator;
@Inject
private ClouderaManagerProductTransformer clouderaManagerProductTransformer;
public void examinePackageVersionsWithAllCandidateImages(Long stackId, Set<Image> candidateImages, String currentCmVersion, Set<ParcelInfo> activeParcels,
String imageCatalogUrl) {
LOGGER.debug("Target image not found for cluster therefore comparing package versions with other candidate images.");
if (areComponentVersionsMatchWithAnyImage(activeParcels, currentCmVersion, candidateImages)) {
LOGGER.debug("The combination of the cluster package versions are compatible.");
} else {
Set<Image> imagesWithSameCmVersion = getImageByCurrentCmVersion(currentCmVersion, candidateImages);
String activeParcelsMessage = createActiveParcelsMessage(activeParcels);
if (imagesWithSameCmVersion.isEmpty()) {
LOGGER.debug("There is no other image in the catalog with the same {} CM version.", currentCmVersion);
sendNotification(stackId, STACK_CM_MIXED_PACKAGE_VERSIONS_FAILED_NO_CANDIDATE, List.of(currentCmVersion, activeParcelsMessage));
} else if (imagesWithSameCmVersion.size() > 1) {
LOGGER.debug("Multiple image is available with the same CM version {}", imagesWithSameCmVersion);
Image latestImage = getLatestImage(imagesWithSameCmVersion);
String suggestedVersionsMessage = createSuggestedVersionsMessage(latestImage, activeParcels);
sendNotification(stackId, STACK_CM_MIXED_PACKAGE_VERSIONS_FAILED_MULTIPLE,
List.of(currentCmVersion, activeParcelsMessage, suggestedVersionsMessage, imageCatalogUrl));
} else {
LOGGER.debug("There is only one image with the same CM version.");
String suggestedVersions = createSuggestedVersionsMessage(imagesWithSameCmVersion.iterator().next(), activeParcels);
sendNotification(stackId, STACK_CM_MIXED_PACKAGE_VERSIONS_FAILED, List.of(currentCmVersion, activeParcelsMessage, suggestedVersions));
}
}
}
private boolean areComponentVersionsMatchWithAnyImage(Set<ParcelInfo> activeParcels, String cmVersion, Set<Image> images) {
return images.stream().anyMatch(image -> cmVersion.equals(getCmVersion(image.getPackageVersions())) && matchParcelVersions(activeParcels, image));
}
private String getCmVersion(Map<String, String> packageVersions) {
return packageVersions.get(CM.getKey());
}
private boolean matchParcelVersions(Set<ParcelInfo> activeParcels, Image image) {
return mixedPackageVersionComparator.matchParcelVersions(activeParcels, getProductsFromImage(image));
}
private Map<String, String> getProductsFromImage(Image image) {
return clouderaManagerProductTransformer.transformToMap(image, true, true);
}
private Set<Image> getImageByCurrentCmVersion(String currentCmVersion, Set<Image> candidateImages) {
return candidateImages.stream()
.filter(image -> currentCmVersion.equals(getCmVersion(image.getPackageVersions())))
.collect(Collectors.toSet());
}
private String createActiveParcelsMessage(Set<ParcelInfo> activeParcels) {
return mixedPackageMessageProvider.createActiveParcelsMessage(activeParcels);
}
private com.sequenceiq.cloudbreak.cloud.model.catalog.Image getLatestImage(Set<Image> images) {
return images.stream()
.max(Comparator.comparing(Image::getCreated))
.orElse(images.iterator().next());
}
private String createSuggestedVersionsMessage(Image image, Set<ParcelInfo> activeParcels) {
return mixedPackageMessageProvider.createSuggestedVersionsMessage(getProductsFromImage(image), activeParcels, getCmVersion(image.getPackageVersions()));
}
private void sendNotification(Long stackId, ResourceEvent resourceEvent, List<String> args) {
eventService.fireCloudbreakEvent(stackId, UPDATE_IN_PROGRESS.name(), resourceEvent, args);
}
}
| 52.238532
| 160
| 0.766772
|
42270bef81cf563fd4b9cf660b653790f37cff87
| 2,126
|
/*
* Copyright 2015 Nokia Solutions and Networks
* Licensed under the Apache License, Version 2.0,
* see license.txt file for details.
*/
package org.robotframework.ide.eclipse.main.plugin.project;
public class RobotProjectConfigEvents {
public static final String ROBOT_CONFIG_MARKER_CHANGED = "robot/redxml/marker/changed";
public static final String ROBOT_CONFIG_ENV_LOADING_STARTED = "robot/redxml/env/loading_started";
public static final String ROBOT_CONFIG_ENV_LOADED = "robot/redxml/env/loaded";
public static final String ROBOT_CONFIG_VAR_MAP_CHANGED = "robot/redxml/detail/varmap/changed";
public static final String ROBOT_CONFIG_VAR_MAP_STRUCTURE_CHANGED = "robot/redxml/structural/varmap/changed";
public static final String ROBOT_CONFIG_VAR_FILE_CHANGED = "robot/redxml/detail/varfile/changed";
public static final String ROBOT_CONFIG_VAR_FILE_STRUCTURE_CHANGED = "robot/redxml/structural/varfile/changed";
public static final String ROBOT_CONFIG_LIBRARY_ADDED_REMOVED = "robot/redxml/structural/libs/added_removed";
public static final String ROBOT_CONFIG_LIBRARY_MODE_CHANGED = "robot/redxml/detail/libs/changed";
public static final String ROBOT_CONFIG_LIBRARIES_ARGUMENTS_ADDED = "robot/redxml/structural/libs/args/added";
public static final String ROBOT_CONFIG_LIBRARIES_ARGUMENTS_REMOVED = "robot/redxml/structural/libs/args/removed";
public static final String ROBOT_CONFIG_LIBRARIES_ARGUMENTS_CHANGED = "robot/redxml/detail/libs/args/changed";
public static final String ROBOT_CONFIG_PYTHONPATH_CHANGED = "robot/redxml/detail/pythonpath/changed";
public static final String ROBOT_CONFIG_PYTHONPATH_STRUCTURE_CHANGED = "robot/redxml/structural/pythonpath/changed";
public static final String ROBOT_CONFIG_CLASSPATH_CHANGED = "robot/redxml/detail/classpath/changed";
public static final String ROBOT_CONFIG_CLASSPATH_STRUCTURE_CHANGED = "robot/redxml/structural/classpath/changed";
public static final String ROBOT_CONFIG_VALIDATION_EXCLUSIONS_STRUCTURE_CHANGED = "robot/redxml/structural/validationexclusions/changed";
}
| 55.947368
| 141
| 0.816557
|
d810031d4ebd21450444f3e198b3b2348796004d
| 9,305
|
/*
* The MIT License
*
* Copyright 2013 Jesse Glick.
*
* 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.jenkinsci.plugins.build_token_root;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.Extension;
import hudson.model.Cause;
import hudson.model.CauseAction;
import hudson.model.Job;
import hudson.model.ParameterDefinition;
import hudson.model.ParameterValue;
import hudson.model.ParametersAction;
import hudson.model.ParametersDefinitionProperty;
import hudson.model.Queue;
import hudson.model.UnprotectedRootAction;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.security.csrf.CrumbExclusion;
import hudson.triggers.SCMTrigger;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static javax.servlet.http.HttpServletResponse.SC_CREATED;
import jenkins.model.Jenkins;
import jenkins.model.ParameterizedJobMixIn;
import jenkins.triggers.SCMTriggerItem;
import jenkins.util.TimeDuration;
import org.kohsuke.stapler.HttpResponses;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
@Extension
public class BuildRootAction implements UnprotectedRootAction {
private static final Logger LOGGER = Logger.getLogger(BuildRootAction.class.getName());
public static final String URLNAME = "buildByToken";
@Override public String getUrlName() {
return URLNAME;
}
@Override public String getIconFileName() {
return null;
}
@Override public String getDisplayName() {
return null;
}
public void doBuild(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job, @QueryParameter TimeDuration delay) throws IOException, ServletException {
LOGGER.log(Level.FINE, "build on {0}", job);
ParameterizedJobMixIn.ParameterizedJob<?, ?> p = project(job, req, rsp);
if (delay == null) {
delay = new TimeDuration(p.getQuietPeriod());
}
ParametersDefinitionProperty pp = ((Job<?,?>) p).getProperty(ParametersDefinitionProperty.class);
if (pp == null) {
LOGGER.fine("wrong kind");
throw HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "Use /buildByToken/buildWithParameters for this job since it takes parameters");
}
Queue.Item item = Jenkins.get().getQueue().schedule(p, delay.getTimeInSeconds(), getBuildCause(req));
if (item != null) {
rsp.sendRedirect(SC_CREATED, req.getContextPath() + '/' + item.getUrl());
} else {
rsp.sendRedirect(".");
}
}
public void doBuildWithParameters(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job, @QueryParameter TimeDuration delay) throws IOException, ServletException {
LOGGER.log(Level.FINE, "buildWithParameters on {0}", job);
ParameterizedJobMixIn.ParameterizedJob<?, ?> p = project(job, req, rsp);
if (delay == null) {
delay = new TimeDuration(p.getQuietPeriod());
}
ParametersDefinitionProperty pp = ((Job<?,?>) p).getProperty(ParametersDefinitionProperty.class);
if (pp == null) {
LOGGER.fine("wrong kind");
throw HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, "Use /buildByToken/build for this job since it takes no parameters");
}
List<ParameterValue> values = new ArrayList<>();
for (ParameterDefinition d : pp.getParameterDefinitions()) {
ParameterValue value = d.createValue(req);
if (value != null) {
values.add(value);
}
}
Queue.Item item = Jenkins.get().getQueue().schedule(p, delay.getTimeInSeconds(), new ParametersAction(values), getBuildCause(req));
if (item != null) {
rsp.sendRedirect(SC_CREATED, req.getContextPath() + '/' + item.getUrl());
} else {
rsp.sendRedirect(".");
}
}
public void doPolling(StaplerRequest req, StaplerResponse rsp, @QueryParameter String job) throws IOException, ServletException {
LOGGER.log(Level.FINE, "polling on {0}", job);
ParameterizedJobMixIn.ParameterizedJob<?, ?> p = project(job, req, rsp);
// AbstractProject.schedulePolling only adds one thing here: check for isDisabled. But in that case, !isBuildable, so we would not have gotten here anyway.
SCMTriggerItem scmp = SCMTriggerItem.SCMTriggerItems.asSCMTriggerItem(p);
if (scmp == null) {
LOGGER.log(Level.FINE, "{0} is not a SCMTriggerItem", p);
throw HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, new IOException(job + " is not a SCMTriggerItem"));
}
SCMTrigger trigger = scmp.getSCMTrigger();
if (trigger == null) {
LOGGER.log(Level.FINE, "{0} is not configured to poll", p);
throw HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, new IOException(job + " is not configured to poll"));
}
trigger.run();
ok(rsp);
}
@SuppressWarnings("deprecation")
private ParameterizedJobMixIn.ParameterizedJob<?, ?> project(String job, StaplerRequest req, StaplerResponse rsp) throws IOException, HttpResponses.HttpResponseException {
Job<?,?> j;
try (ACLContext c = ACL.as(ACL.SYSTEM)) {
j = Jenkins.get().getItemByFullName(job, Job.class);
}
if (j == null) {
LOGGER.log(Level.FINE, "no such job {0}", job);
throw HttpResponses.notFound();
}
if (!(j instanceof ParameterizedJobMixIn.ParameterizedJob)) {
LOGGER.log(Level.FINE, "{0} is not a ParameterizedJob", j);
throw HttpResponses.notFound();
}
ParameterizedJobMixIn.ParameterizedJob<?, ?> p = (ParameterizedJobMixIn.ParameterizedJob) j;
hudson.model.BuildAuthorizationToken authToken = p.getAuthToken();
if (authToken == null || authToken.getToken() == null) {
// For jobs without tokens, prefer not to leak information about their existence.
// (We assume anonymous lacks DISCOVER.)
LOGGER.log(Level.FINE, "no authToken on {0}", job);
throw HttpResponses.notFound();
}
try {
hudson.model.BuildAuthorizationToken.checkPermission((Job) p, authToken, req, rsp);
} catch (RuntimeException x) { // e.g., AccessDeniedException
LOGGER.log(Level.FINE, "on {0} was denied: {1}", new Object[] {job, x.getMessage()});
throw x;
}
if (!j.isBuildable()) {
LOGGER.log(Level.FINE, "{0} is not buildable", job);
throw HttpResponses.error(HttpServletResponse.SC_BAD_REQUEST, new IOException(job + " is not buildable"));
}
LOGGER.log(Level.FINE, "found {0}", p);
return p;
}
private CauseAction getBuildCause(StaplerRequest req) {
return new CauseAction(new Cause.RemoteCause(req.getRemoteAddr(), req.getParameter("cause")));
}
@SuppressFBWarnings(value = "RCN_REDUNDANT_NULLCHECK_WOULD_HAVE_BEEN_A_NPE", justification = "https://github.com/spotbugs/spotbugs/issues/756")
private void ok(StaplerResponse rsp) throws IOException {
rsp.setContentType("text/html");
try (PrintWriter w = rsp.getWriter()) {
w.write("Scheduled.\n");
}
}
@Extension
public static class BuildRootActionCrumbExclusion extends CrumbExclusion {
@Override
public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException {
String pathInfo = req.getPathInfo();
if (pathInfo != null && pathInfo.startsWith(getExclusionPath())) {
chain.doFilter(req, resp);
return true;
}
return false;
}
public String getExclusionPath() {
return "/" + URLNAME + "/";
}
}
}
| 44.521531
| 181
| 0.679527
|
a0320f6fb5b23440716317ead335200ace11ca8e
| 6,508
|
/*
* Copyright 2015-2016 Patrick Jungermann
*
* 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.github.pjungermann.config.types.json;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.pjungermann.config.Config;
import com.github.pjungermann.config.KeyBuilder;
import com.github.pjungermann.config.types.ConfigConversionException;
import com.github.pjungermann.config.types.ConfigConverter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.io.IOException;
import java.util.*;
import static java.util.Collections.synchronizedMap;
/**
* Converter from JSON to {@link Config} and vise versa.
*
* @author Patrick Jungermann
*/
@Component
@Singleton
public class JsonConverter implements ConfigConverter<ObjectNode> {
private static final Logger LOGGER = LoggerFactory.getLogger(JsonConverter.class);
static final ObjectMapper MAPPER;
static {
MAPPER = new ObjectMapper();
MAPPER.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
}
private KeyBuilder keyBuilder;
@Inject
public void setKeyBuilder(@NotNull final KeyBuilder keyBuilder) {
this.keyBuilder = keyBuilder;
}
@NotNull
@Override
public Config from(@NotNull final ObjectNode convertible) {
final Config config = new Config();
putAll(synchronizedMap(config), convertible, "");
return config;
}
@SuppressWarnings("unchecked")
protected void putAll(@NotNull final Map<String, Object> config,
@NotNull final ObjectNode convertible,
@NotNull final String keyPrefix) {
final Iterator<Map.Entry<String, JsonNode>> fields = convertible.fields();
while (fields.hasNext()) {
final Map.Entry<String, JsonNode> entry = fields.next();
put(config, keyPrefix + entry.getKey(), entry.getValue());
}
}
@SuppressWarnings("unchecked")
protected void put(@NotNull final Map<String, Object> config,
@NotNull final String key,
@NotNull JsonNode node) {
if (node instanceof ObjectNode) {
putAll(config, (ObjectNode) node, keyBuilder.toPrefix(key));
return;
}
config.put(key, extractValue(node));
}
@Nullable
protected Object extractValue(@NotNull final JsonNode node) {
if (node.isNull()) {
return null;
}
if (node.isBoolean()) {
return node.booleanValue();
}
if (node.isNumber()) {
return node.numberValue();
}
if (node.isTextual()) {
return node.textValue();
}
if (node.isBinary()) {
try {
return node.binaryValue();
} catch (IOException e) {
LOGGER.error(String.format(
"failed to read binary value from node %s of type %s",
node, node.getClass()
), e);
}
}
if (node instanceof ArrayNode) {
return prepareEntries((ArrayNode) node);
}
throw new UnsupportedOperationException(String.format(
"node %s of type %s is not supported",
node, node.getClass()
));
}
@NotNull
@SuppressWarnings("unchecked")
protected ArrayList prepareEntries(@NotNull final ArrayNode valueList) {
final ArrayList list = new ArrayList(valueList.size());
for (JsonNode entry : valueList) {
if (entry instanceof ObjectNode) {
list.add(from((ObjectNode) entry));
} else {
list.add(extractValue(entry));
}
}
return list;
}
@NotNull
@Override
@SuppressWarnings("unchecked")
public ObjectNode to(@NotNull final Config config) throws ConfigConversionException {
final HashMap<String, Object> map = new HashMap<>(config.size());
new HashSet<>(config.keySet())
.stream()
.forEach(key -> addHierarchicalEntry(map, (String) key, config.get(key)));
try {
final String jsonString = MAPPER.writeValueAsString(map);
return (ObjectNode) MAPPER.readTree(jsonString);
} catch (JsonProcessingException e) {
throw new ConfigConversionException(
"failed to serialize the config as json " +
"and deserialize it into a JsonNode",
e);
} catch (IOException e) {
// unlikely to happen, but part of the interface
throw new ConfigConversionException(
"failed to read from the content", e);
}
}
@SuppressWarnings("unchecked")
protected void addHierarchicalEntry(@NotNull final Map<String, Object> map,
@NotNull final String key,
final Object value) {
final int index = key.indexOf(keyBuilder.getSeparator());
if (index == -1) {
map.put(key, value);
return;
}
final String rootKey = key.substring(0, index);
if (!map.containsKey(rootKey)) {
map.putIfAbsent(rootKey, new HashMap<>());
}
addHierarchicalEntry(
(Map<String, Object>) map.get(rootKey),
key.substring(index + 1),
value);
}
}
| 31.746341
| 90
| 0.614014
|
cece3b338e7d5d89fffa5864b59d46432a2bf2a1
| 14,072
|
package qin.javaee8.testing;
import org.junit.Test;
import qin.javaee8.core.SessionBasic;
import qin.tinyshop8.domain.Goods;
import qin.tinyshop8.utils.ShopBaseSupport;
import java.util.ArrayList;
import java.util.List;
public class SaveGoodsInfo implements ShopBaseSupport,
SessionBasic
{
@Test
public void save() throws Exception
{
Goods goods0 = new Goods();
goods0.setGoodsName("【原封正品 移动4G公开版特价】Apple/苹果 iPhone 5S 苹果5S手机");
goods0.setGoodsProNo("AG0012320_1");
goods0.setGoodsNo("AG0012320");
goods0.setGoodsStoreNums(36);
goods0.setGoodsWeight("300");
goods0.setGoodsSellPrice(Double.valueOf("4898.0"));
goods0.setGoodsMarketPrice(Double.valueOf("5000.0"));
goods0.setGoodsCostPrice(Double.valueOf("4700.0"));
List<String> goodsImages0 = new ArrayList<>();
goodsImages0.add(basePath + "data/uploads/2014/04/29/870c43499b99862429287c2d4119fef6.jpg");
goods0.setGoodsImgs(goodsImages0);
Goods goods1 = new Goods();
goods1.setGoodsName("小米手机3国内性价比最强机");
goods1.setGoodsProNo("X20140120567_1");
goods1.setGoodsNo("X20140120567");
goods1.setGoodsStoreNums(36);
goods1.setGoodsWeight("300");
goods1.setGoodsSellPrice(Double.valueOf("1799.0"));
goods1.setGoodsMarketPrice(Double.valueOf("1999.0"));
goods1.setGoodsCostPrice(Double.valueOf("1799.0"));
List<String> goodsImages1 = new ArrayList<>();
goodsImages1.add(basePath + "data/uploads/2014/04/29/bee3fc7f0746b54f51fc5f1a2e7a38e3.jpg");
goods1.setGoodsImgs(goodsImages1);
Goods goods2 = new Goods();
goods2.setGoodsName("MacBook Air");
goods2.setGoodsProNo("M20140102654_1");
goods2.setGoodsNo("M20140102654");
goods2.setGoodsStoreNums(24);
goods2.setGoodsWeight("1080");
goods2.setGoodsSellPrice(Double.valueOf("6288.0"));
goods2.setGoodsMarketPrice(Double.valueOf("6388.0"));
goods2.setGoodsCostPrice(Double.valueOf("6200.0"));
List<String> goodsImages2 = new ArrayList<>();
goodsImages2.add(basePath + "data/uploads/2014/04/29/6b33dafad4bb8752240cf2d3ab066be8.jpg");
goods2.setGoodsImgs(goodsImages2);
Goods goods3 = new Goods();
goods3.setGoodsName("Samsung GALAXY S5 4G 联通定制版 G9006V");
goods3.setGoodsProNo("SX201401023465_1");
goods3.setGoodsNo("SX201401023465");
goods3.setGoodsStoreNums(24);
goods3.setGoodsWeight("300");
goods3.setGoodsSellPrice(Double.valueOf("5299.0"));
goods3.setGoodsMarketPrice(Double.valueOf("5399.0"));
goods3.setGoodsCostPrice(Double.valueOf("5200.0"));
List<String> goodsImages3 = new ArrayList<>();
goodsImages3.add(basePath + "data/uploads/2014/04/29/d6e93371fdcfae0890fe519fdeb50129.jpg");
goods3.setGoodsImgs(goodsImages3);
Goods goods4 = new Goods();
goods4.setGoodsName("联想 ThinkPad X1 Carbon X1 Carbon 3443-1N1 i7 4G 笔记本");
goods4.setGoodsProNo("L20140203432");
goods4.setGoodsNo("L20140203432");
goods4.setGoodsStoreNums(23);
goods4.setGoodsWeight("3405");
goods4.setGoodsSellPrice(Double.valueOf("16699.0"));
goods4.setGoodsMarketPrice(Double.valueOf("16799.0"));
goods4.setGoodsCostPrice(Double.valueOf("16000.0"));
List<String> goodsImages4 = new ArrayList<>();
goodsImages4.add(basePath + "data/uploads/2014/04/29/8f551833e1ab9568186641fe4b5b0101.jpg");
goods4.setGoodsImgs(goodsImages4);
Goods goods5 = new Goods();
goods5.setGoodsName("Apple/苹果 配备 Retina 显示屏的 MacBook Pro ME865CH/A笔电脑 1");
goods5.setGoodsProNo("AP20140101787_1");
goods5.setGoodsNo("AP20140101787");
goods5.setGoodsStoreNums(24);
goods5.setGoodsWeight("1570");
goods5.setGoodsSellPrice(Double.valueOf("9288.0"));
goods5.setGoodsMarketPrice(Double.valueOf("9298.0"));
goods5.setGoodsCostPrice(Double.valueOf("9200.0"));
List<String> goodsImages5 = new ArrayList<>();
goodsImages5.add(basePath + "data/uploads/2014/04/30/b8f4125b967911e08f7115f8d2b3f684.jpg");
goods5.setGoodsImgs(goodsImages5);
Goods goods6 = new Goods();
goods6.setGoodsName("Apple/苹果 iPhone 5C电信版 苹果5c 正品行货");
goods6.setGoodsProNo("AP20140101788_1");
goods6.setGoodsNo("AP20140101788");
goods6.setGoodsStoreNums(72);
goods6.setGoodsWeight("300");
goods6.setGoodsSellPrice(Double.valueOf("3367.0"));
goods6.setGoodsMarketPrice(Double.valueOf("3899.0"));
goods6.setGoodsCostPrice(Double.valueOf("3367.0"));
List<String> goodsImages6 = new ArrayList<>();
goodsImages6.add(basePath + "data/uploads/2014/04/30/62527b26f1afbe204f247b72d1f20c2d.jpg");
goods6.setGoodsImgs(goodsImages6);
Goods goods7 = new Goods();
goods7.setGoodsName(" Apple/苹果 iPhone 4s 8G 苹果4S手机");
goods7.setGoodsProNo("AP20140101786_1");
goods7.setGoodsNo("AP20140101786");
goods7.setGoodsStoreNums(24);
goods7.setGoodsWeight("400");
goods7.setGoodsSellPrice(Double.valueOf("2479.0"));
goods7.setGoodsMarketPrice(Double.valueOf("3488.0"));
goods7.setGoodsCostPrice(Double.valueOf("2479.0"));
List<String> goodsImages7 = new ArrayList<>();
goodsImages7.add(basePath + "data/uploads/2014/04/30/f31a00b4e0f6617378095a8c1bfb00c9.jpg");
goods7.setGoodsImgs(goodsImages7);
Goods goods8 = new Goods();
goods8.setGoodsName("小米手机2S");
goods8.setGoodsProNo("X20140120566_1");
goods8.setGoodsNo("X20140120566");
goods8.setGoodsStoreNums(60);
goods8.setGoodsWeight("400");
goods8.setGoodsSellPrice(Double.valueOf("1299.0"));
goods8.setGoodsMarketPrice(Double.valueOf("1499.0"));
goods8.setGoodsCostPrice(Double.valueOf("1299.0"));
List<String> goodsImages8 = new ArrayList<>();
goodsImages8.add(basePath + "data/uploads/2014/04/30/f3ccdd27d2000e3f9255a7e3e2c48800.jpg");
goods8.setGoodsImgs(goodsImages8);
Goods goods9 = new Goods();
goods9.setGoodsName("Apple/苹果 ipad air WIFI iPad Air平板黑预售白现货");
goods9.setGoodsProNo("AP20140101785_1");
goods9.setGoodsNo("AP20140101785");
goods9.setGoodsStoreNums(48);
goods9.setGoodsWeight("700");
goods9.setGoodsSellPrice(Double.valueOf("3399.0"));
goods9.setGoodsMarketPrice(Double.valueOf("4900.0"));
goods9.setGoodsCostPrice(Double.valueOf("3999.0"));
List<String> goodsImages9 = new ArrayList<>();
goodsImages9.add(basePath + "data/uploads/2014/04/30/95fc43a276b4706c1eb6be35a460dcc9.jpg");
goods9.setGoodsImgs(goodsImages9);
Goods goods10 = new Goods();
goods10.setGoodsName("BRIOSO格子衬衫 女 长袖2014春装新款女装修身韩版大码百搭衬衣潮");
goods10.setGoodsProNo("NS20140504123_1");
goods10.setGoodsNo("NS20140504123");
goods10.setGoodsStoreNums(191);
goods10.setGoodsWeight("200");
goods10.setGoodsSellPrice(Double.valueOf("49.0"));
goods10.setGoodsMarketPrice(Double.valueOf("199.0"));
goods10.setGoodsCostPrice(Double.valueOf("40.0"));
List<String> goodsImages10 = new ArrayList<>();
goodsImages10.add(basePath + "data/uploads/2014/05/04/6a63f7365e4430b5d07791fd32c66500.jpg");
goods10.setGoodsImgs(goodsImages10);
Goods goods11 = new Goods();
goods11.setGoodsName("白衬衫女短袖2014新款夏装女衬衣大码工作服工装韩版女士衬衫职业");
goods11.setGoodsProNo("NS20140504121_1");
goods11.setGoodsNo("NS20140504121");
goods11.setGoodsStoreNums(219);
goods11.setGoodsWeight("200");
goods11.setGoodsSellPrice(Double.valueOf("55.0"));
goods11.setGoodsMarketPrice(Double.valueOf("110.0"));
goods11.setGoodsCostPrice(Double.valueOf("50.0"));
List<String> goodsImages11 = new ArrayList<>();
goodsImages11.add(basePath + "data/uploads/2014/05/04/f81d28ad7c32504c0af3a8c44eec681e.jpg");
goods11.setGoodsImgs(goodsImages11);
Goods goods12 = new Goods();
goods12.setGoodsName("春夏装新款2014长袖白衬衫女短袖雪纺韩版大码女装打底衫职业衬衣");
goods12.setGoodsProNo("NS20140504122_1");
goods12.setGoodsNo("NS20140504122");
goods12.setGoodsStoreNums(616);
goods12.setGoodsWeight("200");
goods12.setGoodsSellPrice(Double.valueOf("79.0"));
goods12.setGoodsMarketPrice(Double.valueOf("238.0"));
goods12.setGoodsCostPrice(Double.valueOf("70.0"));
List<String> goodsImages12 = new ArrayList<>();
goodsImages12.add(basePath + "data/uploads/2014/05/04/fb84a52b8da8869e478a236ed10172b8.jpg");
goods12.setGoodsImgs(goodsImages12);
Goods goods13 = new Goods();
goods13.setGoodsName("夏天职业衬衫女装正装短袖衬衫工装女寸衫韩版白领工作服白衬衣女");
goods13.setGoodsProNo("NS20140504120_1");
goods13.setGoodsNo("NS20140504120");
goods13.setGoodsStoreNums(264);
goods13.setGoodsWeight("200");
goods13.setGoodsSellPrice(Double.valueOf("49.0"));
goods13.setGoodsMarketPrice(Double.valueOf("108.0"));
goods13.setGoodsCostPrice(Double.valueOf("40.0"));
List<String> goodsImages13 = new ArrayList<>();
goodsImages13.add(basePath + "data/uploads/2014/05/04/da175403c79047247a25e76ec8c4913a.jpg");
goods13.setGoodsImgs(goodsImages13);
Goods goods14 = new Goods();
goods14.setGoodsName("职业女装纯棉内搭白色寸衫水钻领子带钻翻领衬衫搭配小西装打底衫");
goods14.setGoodsProNo("NS20140504124_1");
goods14.setGoodsNo("NS20140504124");
goods14.setGoodsStoreNums(88);
goods14.setGoodsWeight("200");
goods14.setGoodsSellPrice(Double.valueOf("45.0"));
goods14.setGoodsMarketPrice(Double.valueOf("68.0"));
goods14.setGoodsCostPrice(Double.valueOf("40.0"));
List<String> goodsImages14 = new ArrayList<>();
goodsImages14.add(basePath + "data/uploads/2014/05/04/b1dcd910f2d270c11d91668ecfbf7302.jpg");
goods14.setGoodsImgs(goodsImages14);
Goods goods15 = new Goods();
goods15.setGoodsName("时尚潮流 牛仔衬衫 男 长袖韩版时尚复古磨白衬衫男春夏外套包邮");
goods15.setGoodsProNo("MS20140504120_1");
goods15.setGoodsNo("MS20140504120");
goods15.setGoodsStoreNums(110);
goods15.setGoodsWeight("200");
goods15.setGoodsSellPrice(Double.valueOf("58.0"));
goods15.setGoodsMarketPrice(Double.valueOf("199.0"));
goods15.setGoodsCostPrice(Double.valueOf("50.0"));
List<String> goodsImages15 = new ArrayList<>();
goodsImages15.add(basePath + "data/uploads/2014/05/04/19579466f48282ec37548040b0c69bb3.jpg");
goods15.setGoodsImgs(goodsImages15);
Goods goods16 = new Goods();
goods16.setGoodsName("2014夏装长袖男士格子衬衣拼接波点修身休闲衬衫衫青春百搭潮热卖");
goods16.setGoodsProNo("MS20140504121_1");
goods16.setGoodsNo("MS20140504121");
goods16.setGoodsStoreNums(264);
goods16.setGoodsWeight("200");
goods16.setGoodsSellPrice(Double.valueOf("78.0"));
goods16.setGoodsMarketPrice(Double.valueOf("278.0"));
goods16.setGoodsCostPrice(Double.valueOf("70.0"));
List<String> goodsImages16 = new ArrayList<>();
goodsImages16.add(basePath + "data/uploads/2014/05/04/a56ab48abdf9aefdef5fd16abb44d02c.jpg");
goods16.setGoodsImgs(goodsImages16);
Goods goods17 = new Goods();
goods17.setGoodsName("2014春装新款长袖衬衫男 韩版修身灯芯绒波点衬衫男士衬衫上衣潮");
goods17.setGoodsProNo("MS20140504122_1");
goods17.setGoodsNo("MS20140504122");
goods17.setGoodsStoreNums(66);
goods17.setGoodsWeight("200");
goods17.setGoodsSellPrice(Double.valueOf("65.0"));
goods17.setGoodsMarketPrice(Double.valueOf("198.0"));
goods17.setGoodsCostPrice(Double.valueOf("60.0"));
List<String> goodsImages17 = new ArrayList<>();
goodsImages17.add(basePath + "data/uploads/2014/05/04/16615175a6eff3846c20d4e68100ed70.jpg");
goods17.setGoodsImgs(goodsImages17);
Goods goods18 = new Goods();
goods18.setGoodsName("2014春装男款格子长袖男衬衫 休闲衬衣潮");
goods18.setGoodsProNo("MS20140504123_1");
goods18.setGoodsNo("MS20140504123");
goods18.setGoodsStoreNums(220);
goods18.setGoodsWeight("200");
goods18.setGoodsSellPrice(Double.valueOf("35.0"));
goods18.setGoodsMarketPrice(Double.valueOf("75.0"));
goods18.setGoodsCostPrice(Double.valueOf("30.0"));
List<String> goodsImages18 = new ArrayList<>();
goodsImages18.add(basePath + "data/uploads/2014/05/04/9bd757b51fc75afd17475b667a042599.jpg");
goods18.setGoodsImgs(goodsImages18);
Goods goods19 = new Goods();
goods19.setGoodsName("复古风唐装男士长袖衬衫 韩版修身灯芯绒盘扣莲花秀男式休闲衬衣");
goods19.setGoodsProNo("MS20140504124_1");
goods19.setGoodsNo("MS20140504124");
goods19.setGoodsStoreNums(96);
goods19.setGoodsWeight("200");
goods19.setGoodsSellPrice(Double.valueOf("76.0"));
goods19.setGoodsMarketPrice(Double.valueOf("126.0"));
goods19.setGoodsCostPrice(Double.valueOf("70.0"));
List<String> goodsImages19 = new ArrayList<>();
goodsImages19.add(basePath + "data/uploads/2014/05/04/451b95af03616fd150e78fdc84a22378.jpg");
goods19.setGoodsImgs(goodsImages19);
session.save(goods0);
session.save(goods1);
session.save(goods2);
session.save(goods3);
session.save(goods4);
session.save(goods5);
session.save(goods6);
session.save(goods7);
session.save(goods8);
session.save(goods9);
session.save(goods10);
session.save(goods11);
session.save(goods12);
session.save(goods13);
session.save(goods14);
session.save(goods15);
session.save(goods16);
session.save(goods17);
session.save(goods18);
session.save(goods19);
transaction.commit();
}
}
| 50.257143
| 101
| 0.678653
|
89d4c84a11463cff8d2383c4668616c2e13e1ddf
| 7,800
|
/*
* Copyright: (c) 2004-2011 Mayo Foundation for Medical Education and
* Research (MFMER). All rights reserved. MAYO, MAYO CLINIC, and the
* triple-shield Mayo logo are trademarks and service marks of MFMER.
*
* Except as contained in the copyright notice above, or as used to identify
* MFMER as the author of this software, the trade names, trademarks, service
* marks, or product names of the copyright holder shall not be used in
* advertising, promotion or otherwise in connection with this software without
* prior written authorization of the copyright holder.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package edu.mayo.cts2.framework.filter.directory;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import edu.mayo.cts2.framework.filter.match.ResolvableMatchAlgorithmReference;
import edu.mayo.cts2.framework.model.command.ResolvedFilter;
import edu.mayo.cts2.framework.model.core.MatchAlgorithmReference;
import edu.mayo.cts2.framework.model.directory.DirectoryResult;
import edu.mayo.cts2.framework.model.exception.ExceptionFactory;
/**
* The Class AbstractCallbackDirectoryBuilder.
*
* @param <T> the generic type
* @author <a href="mailto:kevin.peterson@mayo.edu">Kevin Peterson</a>
*/
public abstract class AbstractCallbackDirectoryBuilder<T> extends AbstractNonLazyDirectoryBuilder<T> {
/** The match algorithm references. */
private Set<MatchAlgorithmReference> matchAlgorithmReferences =
new HashSet<MatchAlgorithmReference>();
private Callback<T> callback;
private List<T> resultBuffer;
/**
* Instantiates a new abstract callback directory builder.
*
* @param callback the callback
*/
public AbstractCallbackDirectoryBuilder(Callback<T> callback){
this(callback, null);
}
/**
* Instantiates a new abstract callback directory builder.
*
* @param callback the callback
* @param matchAlgorithmReferences the match algorithm references
*/
public AbstractCallbackDirectoryBuilder(
Callback<T> callback,
Set<MatchAlgorithmReference> matchAlgorithmReferences
){
super();
this.callback = callback;
this.matchAlgorithmReferences = matchAlgorithmReferences;
}
/**
* Adds the supported model attribute reference.
*
* @param reference the reference
* @return the directory builder
*/
public DirectoryBuilder<T> addSupportedModelAttributeReference(
ResolvableMatchAlgorithmReference reference){
this.matchAlgorithmReferences.add(reference);
return this;
}
/*
* (non-Javadoc)
*
* @see
* org.cts2.internal.model.uri.restrict.ListBasedResolvingRestrictionHandler
* #restrict(java.util.List, org.cts2.core.Filter)
*/
public DirectoryResult<T> resolve() {
boolean atEnd = true;
if(CollectionUtils.isEmpty(this.getFilterComponents())){
return this.callback.execute(this.getStart(), this.getMaxToReturn());
}
if(this.getFilterComponents().size() == 1){
ResolvedFilter filterComponent = this.getFilterComponents().iterator().next();
return this.callback.execute(
filterComponent,
DEFAULT_SCORE_THRESHOLD,
this.getStart(),
this.getMaxToReturn());
}
for (final ResolvedFilter filter : this.getFilterComponents()) {
if (this.resultBuffer == null) {
this.resultBuffer = new ArrayList<T>();
DirectoryResult<T> result = doRestrict(
filter,
DEFAULT_SCORE_THRESHOLD);
atEnd &= result.isAtEnd();
this.resultBuffer.addAll(result.getEntries());
} else {
DirectoryResult<T> result = doRestrict(
filter,
DEFAULT_SCORE_THRESHOLD);
atEnd &= result.isAtEnd();
this.resultBuffer.addAll(result.getEntries());
}
}
return new DirectoryResult<T>(this.resultBuffer, atEnd);
}
/* (non-Javadoc)
* @see edu.mayo.cts2.framework.filter.directory.DirectoryBuilder#count()
*/
public int count() {
if(CollectionUtils.isEmpty(this.getFilterComponents())){
return this.callback.executeCount();
}
if(this.getFilterComponents().size() == 1){
ResolvedFilter filterComponent = this.getFilterComponents().iterator().next();
return this.callback.executeCount(filterComponent, DEFAULT_SCORE_THRESHOLD);
}
for (final ResolvedFilter filter : this.getFilterComponents()) {
if (this.resultBuffer == null) {
this.resultBuffer = new ArrayList<T>();
DirectoryResult<T> result = doRestrict(
filter,
DEFAULT_SCORE_THRESHOLD);
this.resultBuffer.addAll(result.getEntries());
} else {
DirectoryResult<T> result = doRestrict(
filter,
DEFAULT_SCORE_THRESHOLD);
this.resultBuffer.addAll(result.getEntries());
}
}
return resultBuffer.size();
}
/**
* Do restrict.
*
* @param filterComponent the filter component
* @param minScore the min score
* @return the directory result
*/
protected DirectoryResult<T> doRestrict(ResolvedFilter filterComponent, float minScore){
return this.callback.execute(
filterComponent,
minScore,
this.getStart(),
this.getMaxToReturn());
}
/**
* Gets the match algorithm.
*
* @param reference the reference
* @return the match algorithm
*/
protected MatchAlgorithmReference getMatchAlgorithm(MatchAlgorithmReference reference){
for(MatchAlgorithmReference matchAlgorithm : this.matchAlgorithmReferences){
if(StringUtils.equals(matchAlgorithm.getContent(), reference.getContent())){
return matchAlgorithm;
}
if(StringUtils.equals(matchAlgorithm.getUri(),reference.getUri())){
return matchAlgorithm;
}
}
throw ExceptionFactory.createUnsupportedMatchAlgorithm(
reference.getContent(),
this.matchAlgorithmReferences);
}
/**
* The Interface Callback.
*
* @param <T> the generic type
* @author <a href="mailto:kevin.peterson@mayo.edu">Kevin Peterson</a>
*/
public static interface Callback<T> {
/**
* Execute.
*
* @param filterComponent the filter component
* @param matchAlgorithm the match algorithm
* @param minScore the min score
* @param start the start
* @param maxResults the max results
* @return the directory result
*/
public DirectoryResult<T> execute(
ResolvedFilter filterComponent,
float minScore,
int start,
int maxResults);
/**
* Execute count.
*
* @param filterComponent the filter component
* @param matchAlgorithm the match algorithm
* @param minScore the min score
* @return the int
*/
public int executeCount(
ResolvedFilter filterComponent,
float minScore);
/**
* Execute.
*
* @param start the start
* @param maxResults the max results
* @return the directory result
*/
public DirectoryResult<T> execute(
int start,
int maxResults);
/**
* Execute count.
*
* @return the int
*/
public int executeCount();
}
}
| 28.158845
| 103
| 0.688846
|
9d9c4cc15a838f15e74a935c4cb9840f8f9efc9a
| 719
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package ficha7.exercicio2;
/**
*
* @author joaog
*/
public class MinhaThread extends Thread{
Counter c;
boolean soma;
public MinhaThread(boolean soma){
this.soma = soma;
c = new Counter();
this.start();
}
@Override
public void run(){
if(!soma){
for(int i = 0; i < 20; i++){
c.decrement();
}
}
else{
for(int i = 0; i < 20; i++){
c.increment();
}
}
}
}
| 17.975
| 79
| 0.500695
|
637483c8bd246ed496ed938e098ac91694e85471
| 5,819
|
package in.ac.iitm.shaili.ImageProcessing;
import android.graphics.Bitmap;
import android.graphics.Color;
/**
* Created by Awanish Raj on 24/06/15.
*/
public class BinarizeAdaptiveOld {
private static final String LOG_TAG = "BinarizeAdaptive";
private static final int WINDOW_FACTOR = 8;
// private static final float THRESH_DARKBG = 1.55f;
private static final float THRESH_LIGHTBG = 0.85f;
/**
* Image binarization using Bradley's algorithm
*
* @param original
* @return
*/
public static Bitmap thresh(Bitmap original) {
final int width = original.getWidth();
final int height = original.getHeight();
int integralImg[] = new int[width * height];
// int grayMatrix[][] = new int[width][height];
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
int sum, index, count;
/**
* First pass for computing the integral image.
*/
for (int i = 0; i < width; i++) {
sum = 0;
for (int j = 0; j < height; j++) {
// int grayPixel = (grayMatrix[i][j] - minGray) * 255 / (maxGray - minGray);
int grayPixel = gray(original.getPixel(i, j));
// grayMatrix[i][j] = grayPixel;
sum += grayPixel;
index = j * width + i;
integralImg[index] = sum + ((i != 0) ? integralImg[index - 1] : 0);
}
}
float thresholdFactor = THRESH_LIGHTBG;
/**
* For high value of bgLightness, we need <1f
* For bgLightness = 0.5f, we need 1f;
* For lower value of bgLightness, we need >1f
*/
int x1, y1, x2, y2;
int s2 = (width / WINDOW_FACTOR) / 2;
/**
* Second pass to perform thresholding
*/
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
/**
* Calculating corner positions for S X S box
*/
x1 = i - s2;
x2 = i + s2;
y1 = j - s2;
y2 = j + s2;
/**
* Truncating border values
*/
if (x1 < 0) x1 = 0;
if (x2 >= width) x2 = width - 1;
if (y1 < 0) y1 = 0;
if (y2 >= height) y2 = height - 1;
/**
* Total number of pixels in the box after truncation
*/
count = (x2 - x1) * (y2 - y1);
/**
* Calculating sum over the box using integral image
*/
sum = integralImg[y2 * width + x2]
- integralImg[y1 * width + x2]
- integralImg[y2 * width + x1]
+ integralImg[y1 * width + x1];
x1 = i - 30;
x2 = i + 30;
y1 = j - 30;
y2 = j + 30;
// /**
// * Truncating border values
// */
// if (x1 < 0) x1 = 0;
// if (x2 >= width) x2 = width - 1;
// if (y1 < 0) y1 = 0;
// if (y2 >= height) y2 = height - 1;
//
// /**
// * Total number of pixels in the box after truncation
// */
// int biggerCount = (x2 - x1) * (y2 - y1);
//
// /**
// * Calculating sum over the box using integral image
// */
// int biggerSum = integralImg[y2 * width + x2]
// - integralImg[y1 * width + x2]
// - integralImg[y2 * width + x1]
// + integralImg[y1 * width + x1];
/**
* Binarizing the image based on threshold for the box
*/
// int gray = grayMatrix[i][j];
// output.setPixel(i, j, Color.rgb(gray, gray, gray));
// if ((grayMatrix[i][j] * count) <= (long) (sum * thresholdFactor)) {
// float localLightness = (biggerSum / (255f * biggerCount));
// long mainThresh = (long) ((localLightness > 0.5f) ? sum * THRESH_LIGHTBG : sum * THRESH_DARKBG);
// if ((grayMatrix[i][j] * count) <= mainThresh) {
// if ((grayMatrix[i][j] * count) <= (long) (sum * thresholdFactor)) {
// if ((scaledPixel) <= (long) (scaledAverage2 * thresholdFactor)) {
if ((gray(original.getPixel(i, j)) * count) <= (long) (sum * thresholdFactor)) {
output.setPixel(i, j, Color.BLACK);
// output.setPixel(i, j, (localLightness > 0.5f) ? Color.BLACK : Color.WHITE);
// output.setPixel(i, j, Color.BLACK);
} else {
output.setPixel(i, j, Color.WHITE);
// output.setPixel(i, j, (localLightness > 0.5f) ? Color.WHITE : Color.BLACK);
// output.setPixel(i, j, Color.WHITE);
}
}
}
return output;
}
/**
* Method to obtain gray pixel
*
* @param pixel
* @return
*/
private static int gray(int pixel) {
/**
* RGB average
*/
// return ((Color.red(pixel) + Color.green(pixel) + Color.blue(pixel)) / 3);
/**
* Standard luminance calculation
*/
return (int) (0.2126 * Color.red(pixel) + 0.7152 * Color.green(pixel) + 0.0722 * Color.blue(pixel));
/**
* Perceived luminance calculation
*/
// return (int) (0.299 * Color.red(pixel) + 0.587 * Color.green(pixel) + 0.114 * Color.blue(pixel));
}
}
| 32.691011
| 114
| 0.450077
|
74842b862165cc6a9d10cab24404f818e5eda241
| 5,960
|
package org.egov.cpt.models;
import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import org.egov.cpt.models.calculation.Calculation;
import org.springframework.validation.annotation.Validated;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.ApiModel;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
/**
* A Object holds the basic data for a Property
*/
@ApiModel(description = "A Object holds the basic data for a Property")
@Validated
@javax.annotation.Generated(value = "org.egov.codegen.SpringBootCodegen", date = "2018-09-18T17:06:11.263+05:30")
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
@Builder
public class Property {
@JsonProperty("id")
private String id;
@JsonProperty("transitNumber")
private String transitNumber;
@JsonProperty("tenantId")
private String tenantId;
@JsonProperty("colony")
private String colony;
@JsonProperty("masterDataState")
private String masterDataState;
@JsonProperty("masterDataAction")
private String masterDataAction;
@JsonProperty("assignee")
@Builder.Default
private List<String> assignee = null;
@Size(max = 128)
@JsonProperty("comment")
private String comment;
@JsonProperty("auditDetails")
private AuditDetails auditDetails;
@JsonProperty("propertyDetails")
private PropertyDetails propertyDetails;
@Valid
@JsonProperty("owners")
private List<Owner> owners;
@Valid
@JsonProperty
private List<DuplicateCopy> duplicateCopys;
@Valid
@JsonProperty
private List<PropertyImages> propertyImages;
@Valid
@JsonProperty
private List<NoticeGeneration> notices;
@Valid
@JsonProperty
private List<MortgageApprovedGrantDetails> grantDetails;
@Valid
@JsonProperty
private List<RentDemand> demands;
@Valid
@JsonProperty
private List<RentDemand> inActiveDemands;
@Valid
@JsonProperty
private List<RentPayment> payments;
@Valid
@JsonProperty
private List<RentPayment> inActivePayments;
@Valid
@JsonProperty
private List<RentCollection> rentCollections;
@Valid
@JsonProperty
private RentAccount rentAccount;
@Valid
@JsonProperty
private RentSummary rentSummary;
@Valid
@JsonProperty
private Calculation calculation;
public Property addDocumentItem(DuplicateCopy newDuplicateCopyItem) {
if (this.duplicateCopys == null) {
this.duplicateCopys = new ArrayList<>();
}
for (DuplicateCopy duplicateCopy : duplicateCopys) {
if (duplicateCopy.getId().equalsIgnoreCase(newDuplicateCopyItem.getId())) {
return this;
}
}
this.duplicateCopys.add(newDuplicateCopyItem);
return this;
}
public Property addOwnerItem(Owner newOwnerItem) {
if (this.owners == null) {
this.owners = new ArrayList<>();
}
for (Owner owner : owners) {
if (owner.getId().equalsIgnoreCase(newOwnerItem.getId())) {
return this;
}
}
this.owners.add(newOwnerItem);
return this;
}
public Property addPropertyImagesItem(PropertyImages newPropertyImagesItem) {
if (this.propertyImages == null) {
this.propertyImages = new ArrayList<>();
}
for (PropertyImages propertyImage : propertyImages) {
if (propertyImage.getId().equalsIgnoreCase(newPropertyImagesItem.getId())) {
return this;
}
}
this.propertyImages.add(newPropertyImagesItem);
return this;
}
public Property addNoticeItem(NoticeGeneration newNoticeItem) {
if (this.notices == null) {
this.notices = new ArrayList<>();
}
for (NoticeGeneration notice : notices) {
if (notice.getId().equalsIgnoreCase(newNoticeItem.getId())) {
return this;
}
}
this.notices.add(newNoticeItem);
return this;
}
public Property addGrantDetailItem(MortgageApprovedGrantDetails newGrantDetailItem) {
if (this.grantDetails == null) {
this.grantDetails = new ArrayList<>();
}
for (MortgageApprovedGrantDetails grantDetail : grantDetails) {
if (grantDetail.getId().equalsIgnoreCase(newGrantDetailItem.getId())) {
return this;
}
}
this.grantDetails.add(newGrantDetailItem);
return this;
}
public Property addDemandItem(RentDemand newDemandItem) {
if (this.demands == null) {
this.demands = new ArrayList<>();
}
for (RentDemand grantDetail : demands) {
if (grantDetail.getId().equalsIgnoreCase(newDemandItem.getId())) {
return this;
}
}
this.demands.add(newDemandItem);
return this;
}
public Property addPaymentItem(RentPayment newPaymentItem) {
if (this.payments == null) {
this.payments = new ArrayList<>();
}
for (RentPayment grantDetail : payments) {
if (grantDetail.getId().equalsIgnoreCase(newPaymentItem.getId())) {
return this;
}
}
this.payments.add(newPaymentItem);
return this;
}
public Property addCollectionItem(RentCollection newCollectionItem) {
if (this.rentCollections == null) {
this.rentCollections = new ArrayList<>();
}
for (RentCollection rentCollection : rentCollections) {
if (rentCollection.getId().equalsIgnoreCase(newCollectionItem.getId())) {
return this;
}
}
this.rentCollections.add(newCollectionItem);
return this;
}
@JsonProperty("pincode")
private String pincode;
@JsonProperty("area")
private String area;
/**
* Amount to be paid
*/
@JsonProperty("paymentAmount")
private Double paymentAmount;
/**
* Pending consumer code. This needs to be saved in the database for online
* payments.
*/
@JsonProperty("rentPaymentConsumerCode")
private String rentPaymentConsumerCode;
@JsonProperty("transactionId")
private String transactionId;
@JsonProperty("bankName")
private String bankName;
}
| 23.84
| 114
| 0.714094
|
99b203cd70e10715a13a106d5348b3dd76000302
| 610
|
package com.ovh.mls.serving.runtime.core;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Interval {
private final Double lowerBound;
private final Double upperBound;
@JsonCreator
public Interval(@JsonProperty("lower_bound") Double lowerBound, @JsonProperty("upper_bound") Double upperBound) {
this.lowerBound = lowerBound;
this.upperBound = upperBound;
}
public Double getLowerBound() {
return lowerBound;
}
public Double getUpperBound() {
return upperBound;
}
}
| 24.4
| 117
| 0.713115
|
6dd99356e4707a49b648abf05c44e9369d6f8e77
| 2,649
|
/*
* Copyright 2019-present HiveMQ GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hivemq.logging;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.turbo.TurboFilter;
import ch.qos.logback.core.spi.FilterReply;
import com.google.common.annotations.VisibleForTesting;
import jetbrains.exodus.ExodusException;
import jetbrains.exodus.env.EnvironmentImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.Marker;
/**
* This Log Level Modificator is used to modify the log level of Xodus logs.
*
* @author Dominik Obermaier
*/
public class XodusEnvironmentImplLogLevelModificator extends TurboFilter {
@VisibleForTesting
final static Logger environmentalLogger = LoggerFactory.getLogger(EnvironmentImpl.class);
@Override
public FilterReply decide(final Marker marker, final ch.qos.logback.classic.Logger logger, final Level level,
final String format, final Object[] params, final Throwable t) {
if (level.isGreaterOrEqual(Level.INFO)) {
if (logger.getName().equals(environmentalLogger.getName())) {
if (format != null) {
if (format.contains("transaction(s) not finished")) {
logger.trace(marker, format, params);
return FilterReply.DENY;
} else if (format.contains("Transactions stack traces are not available")) {
logger.trace(marker, format, params);
return FilterReply.DENY;
}
}
}
}
if (level.isGreaterOrEqual(Level.ERROR) && t != null && t.getMessage() != null && t instanceof ExodusException) {
if (t.getMessage().contains("cleanFile") || t.getMessage().contains("There is no file by address")) {
logger.trace(marker, "Xodus background job unable to cleanup stale data just now, trying again later");
return FilterReply.DENY;
}
}
// Let other filters decide
return FilterReply.NEUTRAL;
}
}
| 36.791667
| 121
| 0.658739
|
22a54647c3caf659dc63a0f1d0f7d735704b5541
| 2,100
|
package edu.anadolu.cmdline;
import edu.anadolu.analysis.Analyzers;
import edu.anadolu.analysis.Tag;
import edu.anadolu.datasets.CollectionFactory;
import edu.anadolu.datasets.DataSet;
import edu.anadolu.stats.DocLengthStats;
import org.clueweb09.InfoNeed;
import org.clueweb09.tracks.Track;
import org.kohsuke.args4j.Option;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
/**
* A Tool That Computes Document Length Statistics
*/
public final class DoclenTool extends CmdLineTool {
@Option(name = "-collection", required = true, usage = "Collection")
private edu.anadolu.datasets.Collection collection;
@Override
public String getHelp() {
return "Following properties must be defined in config.properties for " + CLI.CMD + " " + getName() + " tfd.home";
}
@Override
public String getShortDescription() {
return "Computes Document Length Statistics";
}
@Override
public void run(Properties props) throws Exception {
if (parseArguments(props) == -1) return;
String tfd_home = props.getProperty("tfd.home");
if (tfd_home == null) {
System.out.println("tfd.home is mandatory for query statistics!");
return;
}
DataSet dataset = CollectionFactory.dataset(collection, tfd_home);
List<InfoNeed> needs = new ArrayList<>();
for (Track track : dataset.tracks())
needs.addAll(track.getTopics());
final String[] fields = props.getProperty("freq.fields", "description,keywords,title,contents").split(",");
for (final Path indexPath : discoverIndexes(dataset)) {
Tag t = Tag.tag(indexPath.getFileName().toString());
Set<String> words = distinctTerms(needs, Analyzers.analyzer(t));
for (String field : fields)
try (DocLengthStats docLengthStats = new DocLengthStats(dataset.collectionPath(), indexPath, field)) {
docLengthStats.process(words);
}
}
}
}
| 31.343284
| 122
| 0.667143
|
4792a232d8b048f6c15d5867d340edc91bdf42c3
| 1,113
|
package org.jesperancinha.std.flash511.actuator;
import org.jesperancinha.console.consolerizer.console.ConsolerizerComposer;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringFlash511Launcher implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringFlash511Launcher.class, args);
}
@Override
public void run(String... args) throws Exception {
ConsolerizerComposer.outSpace()
.bgRed("It is important to note that the sessions endpoint does not come out of the box in Spring")
.green("It has to be manually implemented!");
ConsolerizerComposer.outSpace()
.none()
.blue("http://localhost:8081/actuator/sessions").green("for sessions")
.newLine()
.blue("http://localhost:8081/actuator").green("for actuators")
.newLine()
.reset();
}
}
| 38.37931
| 115
| 0.681042
|
ac56032f49e26a773b77c9ca3795ca342dfe0b40
| 3,685
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.thespheres.betula.gpuntis.impl;
import java.awt.Component;
import java.awt.Cursor;
import org.thespheres.betula.xmlimport.utilities.SourceTargetLinksAccess;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import javax.swing.SwingUtilities;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import org.openide.WizardDescriptor;
import org.openide.util.RequestProcessor;
import org.thespheres.betula.gpuntis.UntisImportConfiguration;
import org.thespheres.betula.gpuntis.UntisImportData;
import org.thespheres.betula.ui.util.JAXBUtil;
import org.thespheres.betula.xmlimport.uiutil.AbstractFileImportAction;
/**
*
* @author boris.heithecker
*/
public class UntisSourceTargetAccess extends SourceTargetLinksAccess<UntisSourceTargetLinks, UntisImportConfiguration> implements PropertyChangeListener {
private final UntisImportData wizard;
private final RequestProcessor.Task[] LOAD_TASK = new RequestProcessor.Task[]{null};
private final WizardDescriptor.Iterator<?> iterator;
public UntisSourceTargetAccess(final UntisImportData wiz, final WizardDescriptor.Iterator<?> iterator) {
super(UntisSourceTargetLinks.class, "Untis-Assoziationen");
wizard = wiz;
this.iterator = iterator;
init();
}
@Override
protected JAXBContext getJAXB(UntisImportConfiguration config) throws IOException {
if (ctx2 == null) {
final Class[] tl = JAXBUtil.lookupJAXBTypes("UntisSourceTargetAccess", UntisSourceTargetLinks.class, UntisTargetLink.class);
try {
ctx2 = JAXBContext.newInstance(tl);
} catch (JAXBException ex) {
throw new IOException(ex);
}
}
return ctx2;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(AbstractFileImportAction.IMPORT_TARGET)) {
init();
}
}
private synchronized void init() {
final UntisImportConfiguration cfg = (UntisImportConfiguration) wizard.getProperty(AbstractFileImportAction.IMPORT_TARGET);
if (cfg != null) {
if (LOAD_TASK[0] != null) {
LOAD_TASK[0].cancel();
}
LOAD_TASK[0] = RP.post(() -> run(cfg));
}
}
void waitLoadingFinished() {
synchronized (LOAD_TASK) {
if (LOAD_TASK[0] != null) {
final Component cmp = iterator.current() != null ? iterator.current().getComponent() : null;
if (SwingUtilities.isEventDispatchThread() && cmp != null) {
final Cursor c = cmp.getCursor();
cmp.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
LOAD_TASK[0].waitFinished();
cmp.setCursor(c);
} else {
LOAD_TASK[0].waitFinished();
}
}
}
}
@Override
protected UntisSourceTargetLinks loadSourceTargetLinks(UntisImportConfiguration config) throws IOException {
UntisSourceTargetLinks res = super.loadSourceTargetLinks(config);
wizard.putProperty(AbstractFileImportAction.SOURCE_TARGET_LINKS, res);
return res;
}
@Override
protected boolean overrideSourceTargetLinks(UntisSourceTargetLinks assoziationen, UntisImportConfiguration config) {
return !assoziationen.isEmpty();
}
}
| 37.222222
| 154
| 0.679783
|
1e59298766010c73d1f51aaab0c613ca08e2f159
| 472
|
package model.adt;
import model.exceptions.InterpreterException;
import model.values.IValue;
import java.util.Map;
public interface IHeap {
void add(Integer key, IValue value);
void update(Integer key, IValue value) throws InterpreterException;
IValue search(Integer key) throws InterpreterException;
void remove(Integer key);
void setContent(Map<Integer, IValue> other);
Map<Integer, IValue> getContent();
boolean isDefined(Integer key);
}
| 27.764706
| 71
| 0.754237
|
09800320da3c2e45b11bd6f446b72819f4bfe5e7
| 4,788
|
package cn.com.warlock.emitter.bytes;
import static cn.com.warlock.emitter.bytes.IDBuilder.parseGeneratorId;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import org.apache.commons.codec.binary.Hex;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
public class IDBuilderTest {
@Test
public void buildZero() {
final byte[] result = IDBuilder.build(new Blueprint(0, 0, 0, 0));
final byte[] zero = new byte[8];
assertThat(result, CoreMatchers.is(zero));
}
@Test
public void buildMostlyOnes() {
final byte[] result = IDBuilder.build(new Blueprint(Blueprint.MAX_TIMESTAMP,
Blueprint.MAX_SEQUENCE_COUNTER, Blueprint.MAX_GENERATOR_ID, Blueprint.MAX_CLUSTER_ID));
final String expected = "ffffffffffff0fff";
assertThat(Hex.encodeHexString(result), CoreMatchers.is(expected));
}
@Test
public void buildTimestampOnly() {
final long TEST_TS_A = 143062936275L;
final String TEST_A_REVERSED = "cb54ecf284000000";
final byte[] result_a = IDBuilder.build(new Blueprint(TEST_TS_A, 0, 0, 0));
assertThat(Hex.encodeHexString(result_a).toLowerCase(), CoreMatchers.is(TEST_A_REVERSED));
final long TEST_TS_B = 0x3FFFFFFFDL;
final String TEST_B_REVERSED = "bfffffffc0000000";
final byte[] result_b = IDBuilder.build(new Blueprint(TEST_TS_B, 0, 0, 0));
assertThat(Hex.encodeHexString(result_b).toLowerCase(), CoreMatchers.is(TEST_B_REVERSED));
}
@Test
public void buildSequenceCounterOnly() {
final byte[] result = IDBuilder.build(new Blueprint(0, 0x22, 0, 0));
final byte[] sixthByte = new byte[] { result[5] };
final String expected = "22";
assertThat(Hex.encodeHexString(sixthByte), CoreMatchers.is(expected));
}
@Test
public void buildGeneratorIdOnly() {
final byte[] result = IDBuilder.build(new Blueprint(0, 0, 0x27, 0));
final byte[] lastTwoBytes = new byte[] { result[6], result[7] };
final String expected = "0270";
assertThat(Hex.encodeHexString(lastTwoBytes), CoreMatchers.is(expected));
}
@Test
public void buildClusterIdOnly() {
final byte[] result = IDBuilder.build(new Blueprint(0, 0, 0, 5));
final byte[] lastTwoBytes = new byte[] { result[6], result[7] };
final String expected = "0005";
assertThat(Hex.encodeHexString(lastTwoBytes), CoreMatchers.is(expected));
}
@Test
public void parseBytes() {
final long TEST_TS = 143062936275L;
final byte[] resultOne = IDBuilder.build(new Blueprint(TEST_TS, 10, 1, 5));
assertThat(IDBuilder.parseGeneratorId(resultOne), is(1));
assertThat(IDBuilder.parseClusterId(resultOne), is(5));
assertThat(IDBuilder.parseSequenceId(resultOne), is(10));
assertThat(IDBuilder.parseTimestamp(resultOne), is(TEST_TS));
Blueprint blueprint = IDBuilder.parse(resultOne);
final byte[] result_two = IDBuilder.build(blueprint);
assertThat(resultOne, CoreMatchers.is(result_two));
}
@Test
public void blueprint() {
final long TEST_TS = 143062936275L;
final byte[] resultOne = IDBuilder.build(new Blueprint(TEST_TS, 10, 1, 5));
final Blueprint blueprintOne = IDBuilder.parse(resultOne);
final byte[] resultOneAgain = IDBuilder.build(blueprintOne);
assertThat(resultOne, CoreMatchers.is(resultOneAgain));
final byte[] resultZeros = IDBuilder.build(new Blueprint(0, 0, 0, 0));
final Blueprint blueprintZeros = IDBuilder.parse(resultZeros);
final byte[] resultZerosAgain = IDBuilder.build(blueprintZeros);
assertThat(resultZeros, CoreMatchers.is(resultZerosAgain));
final byte[] resultMostlyOnes = IDBuilder.build(new Blueprint(Blueprint.MAX_TIMESTAMP,
Blueprint.MAX_SEQUENCE_COUNTER, Blueprint.MAX_GENERATOR_ID, Blueprint.MAX_CLUSTER_ID));
final Blueprint blueprintMostlyOnes = IDBuilder.parse(resultMostlyOnes);
final byte[] resultMostlyOnesAgain = IDBuilder.build(blueprintMostlyOnes);
assertThat(resultMostlyOnes, CoreMatchers.is(resultMostlyOnesAgain));
}
@Test
public void parseGeneratorIdTest() {
byte[] id = new byte[8];
id[6] = 0x0f;
id[7] = (byte) (0x0f << 4);
byte[] clone = id.clone();
assertThat(parseGeneratorId(id), is(255));
assertThat(id, is(clone));
}
@Test(expected = IllegalArgumentException.class)
public void parseIllegalArgument() {
IDBuilder.parse(new byte[0]);
}
@Test(expected = IllegalArgumentException.class)
public void parseIllegalArgumentNull() {
IDBuilder.parse(null);
}
}
| 37.700787
| 99
| 0.676692
|
fed14813f2e696caabefc4eadbc58c8a34d5fa39
| 3,306
|
/*
* Copyright (c) 2013-2016, EMC Corporation.
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* + Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* + Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* + The name of EMC Corporation may not be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.emc.atmos.mgmt.jersey;
import com.emc.acdp.AcdpException;
import com.emc.atmos.api.jersey.ErrorFilter;
import com.emc.atmos.mgmt.AbstractMgmtConfig;
import com.emc.util.SslUtil;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class JerseyUtil {
public static Client createClient(AbstractMgmtConfig config) {
try {
ClientConfig clientConfig = new DefaultClientConfig();
// register an open trust manager to allow SSL connections to servers with self-signed certificates
if ( config.isDisableSslValidation() ) {
clientConfig.getProperties().put( HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
new HTTPSProperties( SslUtil.gullibleVerifier,
SslUtil.createGullibleSslContext() ) );
}
Client client = Client.create( clientConfig );
configureClient( client, config );
return client;
} catch ( Exception e ) {
throw new AcdpException( "Error configuring REST client", e );
}
}
/**
* Note that this method cannot disable SSL validation, so that configuration option is ignored here. You are
* responsible for configuring the client with any proxy, ssl or other options prior to calling this constructor.
*/
public static void configureClient(Client client, AbstractMgmtConfig config) {
client.addFilter( new ErrorFilter() );
client.addFilter( new AuthFilter( config ) );
}
private JerseyUtil() {
}
}
| 46.56338
| 117
| 0.708106
|
96edbc693cb8fcd55bcdb1667b0d95d6278f7621
| 62,936
|
/*
* Copyright <2021> 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://www.apache.org/licenses/LICENSE-2.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.documentdb.jdbc;
import org.bson.BsonDateTime;
import org.bson.BsonDocument;
import org.bson.BsonNull;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import software.amazon.documentdb.jdbc.common.test.DocumentDbTestEnvironment;
import java.sql.Connection;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.Month;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.format.TextStyle;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.function.Function;
public class DocumentDbStatementDateTimeTest extends DocumentDbStatementTest {
/**
* Tests TIMESTAMPADD() and TIMESTAMPDIFF() for intervals that can be converted to ms.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests TIMESTAMPADD() and TIMESTAMPDIFF() with different intervals.")
@ParameterizedTest(name = "testQueryTimestampAddDiff - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testQueryTimestampAddDiff(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testTimestampAddDiff";
final long dateTime = Instant.parse("2020-02-22T00:00:00.00Z").toEpochMilli();
final long weekAfterDateTime = Instant.parse("2020-02-29T00:00:00.00Z").toEpochMilli();
final long dayAfterDateTime = Instant.parse("2020-02-23T00:00:00.00Z").toEpochMilli();
final long hourAfterDateTime = Instant.parse("2020-02-22T01:00:00.00Z").toEpochMilli();
final long minuteAfterDateTime = Instant.parse("2020-02-22T00:01:00.00Z").toEpochMilli();
final long secondAfterDateTime = Instant.parse("2020-02-22T00:00:01.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
doc1.append("fieldWeekAfter", new BsonDateTime(weekAfterDateTime));
doc1.append("fieldDayAfter", new BsonDateTime(dayAfterDateTime));
doc1.append("fieldHourAfter", new BsonDateTime(hourAfterDateTime));
doc1.append("fieldMinuteAfter", new BsonDateTime(minuteAfterDateTime));
doc1.append("fieldSecondAfter", new BsonDateTime(secondAfterDateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Add 1 day to a date column.
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT TIMESTAMPADD(WEEK"
+ ", 1, \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(new Timestamp(weekAfterDateTime), resultSet.getTimestamp(1));
Assertions.assertFalse(resultSet.next());
// Add 1 day to a date column.
final ResultSet resultSet1 = statement.executeQuery(
String.format("SELECT TIMESTAMPADD(DAY"
+ ", 1, \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet1);
Assertions.assertTrue(resultSet1.next());
Assertions.assertEquals(new Timestamp(dayAfterDateTime), resultSet1.getTimestamp(1));
Assertions.assertFalse(resultSet1.next());
// Add 1 hour to a date column.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT TIMESTAMPADD(HOUR"
+ ", 1, \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet2);
Assertions.assertTrue(resultSet2.next());
Assertions.assertEquals(new Timestamp(hourAfterDateTime), resultSet2.getTimestamp(1));
Assertions.assertFalse(resultSet2.next());
// Add 1 minute to a date column.
final ResultSet resultSet3 = statement.executeQuery(
String.format("SELECT TIMESTAMPADD(MINUTE"
+ ", 1, \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet3);
Assertions.assertTrue(resultSet3.next());
Assertions.assertEquals(new Timestamp(minuteAfterDateTime), resultSet3.getTimestamp(1));
Assertions.assertFalse(resultSet3.next());
// Add 1 second to a date column.
final ResultSet resultSet4 = statement.executeQuery(
String.format("SELECT TIMESTAMPADD(SECOND"
+ ", 1, \"field\") FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet4);
Assertions.assertTrue(resultSet4.next());
Assertions.assertEquals(new Timestamp(secondAfterDateTime), resultSet4.getTimestamp(1));
Assertions.assertFalse(resultSet4.next());
// Add 1 day to a date literal.
final ResultSet resultSet5 = statement.executeQuery(
String.format("SELECT TIMESTAMPADD(DAY"
+ ", 1, TIMESTAMP '2020-02-22 00:00:00' ) FROM \"%s\".\"%s\"",
getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet5);
Assertions.assertTrue(resultSet5.next());
Assertions.assertEquals(new Timestamp(dayAfterDateTime), resultSet5.getTimestamp(1));
Assertions.assertFalse(resultSet5.next());
// Add 1 day to the date and extract the day of the month from result.
final ResultSet resultSet6 = statement.executeQuery(
String.format("SELECT DAYOFMONTH(TIMESTAMPADD(DAY"
+ ", 1, \"field\")) FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet6);
Assertions.assertTrue(resultSet6.next());
Assertions.assertEquals(23, resultSet6.getInt(1));
Assertions.assertFalse(resultSet6.next());
// Difference of DAY
final ResultSet resultSet7 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(DAY, \"field\", \"fieldDayAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet7);
Assertions.assertTrue(resultSet7.next());
Assertions.assertEquals(1, resultSet7.getLong(1));
Assertions.assertFalse(resultSet7.next());
// Difference of WEEK
final ResultSet resultSet8 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(WEEK, \"field\", \"fieldWeekAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet8);
Assertions.assertTrue(resultSet8.next());
Assertions.assertEquals(1, resultSet8.getLong(1));
Assertions.assertFalse(resultSet8.next());
// Difference of HOUR
final ResultSet resultSet9 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(HOUR, \"field\", \"fieldHourAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet9);
Assertions.assertTrue(resultSet9.next());
Assertions.assertEquals(1, resultSet9.getLong(1));
Assertions.assertFalse(resultSet9.next());
// Difference of MINUTE
final ResultSet resultSet10 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(MINUTE, \"field\", \"fieldMinuteAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet10);
Assertions.assertTrue(resultSet10.next());
Assertions.assertEquals(1, resultSet10.getLong(1));
Assertions.assertFalse(resultSet10.next());
// Difference of SECOND
final ResultSet resultSet11 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(SECOND, \"field\", \"fieldSecondAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet11);
Assertions.assertTrue(resultSet11.next());
Assertions.assertEquals(1, resultSet11.getLong(1));
Assertions.assertFalse(resultSet11.next());
// Difference of MINUTE in SECOND
final ResultSet resultSet12 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(SECOND, \"field\", \"fieldMinuteAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet12);
Assertions.assertTrue(resultSet12.next());
Assertions.assertEquals(60, resultSet12.getLong(1));
Assertions.assertFalse(resultSet12.next());
// Difference of HOUR in SECOND
final ResultSet resultSet13 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(SECOND, \"field\", \"fieldHourAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet13);
Assertions.assertTrue(resultSet13.next());
Assertions.assertEquals(3600, resultSet13.getLong(1));
Assertions.assertFalse(resultSet13.next());
// Difference of DAY in SECOND
final ResultSet resultSet14 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(SECOND, \"field\", \"fieldDayAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet14);
Assertions.assertTrue(resultSet14.next());
Assertions.assertEquals(86400, resultSet14.getLong(1));
Assertions.assertFalse(resultSet14.next());
// Difference of WEEK in SECOND
final ResultSet resultSet15 = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(SECOND, \"field\", \"fieldWeekAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet15);
Assertions.assertTrue(resultSet15.next());
Assertions.assertEquals(604800, resultSet15.getLong(1));
Assertions.assertFalse(resultSet15.next());
// Difference of SECOND in MICROSECOND
final ResultSet resultSet16 = statement.executeQuery(
String.format(
"SELECT TIMESTAMPDIFF(MICROSECOND, \"field\", \"fieldSecondAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet16);
Assertions.assertTrue(resultSet16.next());
Assertions.assertEquals(1000000, resultSet16.getLong(1));
Assertions.assertFalse(resultSet16.next());
}
}
/**
* Tests TIMESTAMPDIFF() for YEAR.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests TIMESTAMPDIFF() for YEAR.")
@ParameterizedTest(name = "testQueryTimestampDiffYear - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testQueryTimestampDiffYear(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testTimestampDiffYear";
final long dateTime = Instant.parse("2020-02-22T00:00:00.00Z").toEpochMilli();
final long yearAfterDateTime = Instant.parse("2021-02-22T00:00:00.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
doc1.append("fieldYearAfter", new BsonDateTime(yearAfterDateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Difference of 12 months in YEAR
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(YEAR, \"field\", \"fieldYearAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(1, resultSet.getLong(1));
Assertions.assertFalse(resultSet.next());
}
}
/**
* Tests TIMESTAMPADD() for QUARTER.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests TIMESTAMPDIFF() for QUARTER.")
@ParameterizedTest(name = "testQueryTimestampDiffQuarter - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testQueryTimestampDiffQuarter(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testTimestampDiffQuarter";
final long dateTime = Instant.parse("2020-02-22T00:00:00.00Z").toEpochMilli();
final long yearAfterDateTime = Instant.parse("2021-02-22T00:00:00.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
doc1.append("fieldYearAfter", new BsonDateTime(yearAfterDateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Difference of 12 months in QUARTER
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(QUARTER, \"field\", \"fieldYearAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(4, resultSet.getLong(1));
Assertions.assertFalse(resultSet.next());
}
}
/**
* Tests TIMESTAMPADD() for MONTH.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests TIMESTAMPDIFF() for MONTH.")
@ParameterizedTest(name = "testQueryTimestampDiffMonth - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testQueryTimestampDiffMonth(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testTimestampDiffMonth";
final long dateTime = Instant.parse("2020-02-22T00:00:00.00Z").toEpochMilli();
final long yearAfterDateTime = Instant.parse("2021-02-22T00:00:00.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
doc1.append("fieldYearAfter", new BsonDateTime(yearAfterDateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Difference of 12 months in MONTH
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT TIMESTAMPDIFF(MONTH, \"field\", \"fieldYearAfter\")"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(12, resultSet.getLong(1));
Assertions.assertFalse(resultSet.next());
}
}
/**
* Tests that EXTRACT works for different time units.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests EXTRACT() for different time units.")
@ParameterizedTest(name = "testQueryExtract - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testQueryExtract(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testExtract";
final long dateTime = Instant.parse("2020-02-03T04:05:06.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102}");
doc2.append("field", new BsonDateTime(dateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get date parts and use group by to remove any duplicate rows.
final Locale originalLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.SIMPLIFIED_CHINESE);
// Get date parts.
final ResultSet resultSet = statement.executeQuery(String.format(
"SELECT %n"
+ "YEAR(\"field\"),%n"
+ "MONTH(\"field\"),%n"
+ "WEEK(\"field\"),%n"
+ "DAYOFMONTH(\"field\"),%n"
+ "DAYOFWEEK(\"field\"),%n"
+ "DAYOFYEAR(\"field\"),%n"
+ "HOUR(\"field\"),%n"
+ "MINUTE(\"field\"),%n"
+ "SECOND(\"field\"),%n"
+ "QUARTER(\"field\"),%n"
+ "DAYNAME(\"field\"),%n"
+ "MONTHNAME(\"field\")%n"
+ "FROM \"%s\".\"%s\" %n"
+ "GROUP BY %n"
+ "YEAR(\"field\"),%n"
+ "MONTH(\"field\"),%n"
+ "WEEK(\"field\"),%n"
+ "DAYOFMONTH(\"field\"),%n"
+ "DAYOFWEEK(\"field\"),%n"
+ "DAYOFYEAR(\"field\"),%n"
+ "HOUR(\"field\"),%n"
+ "MINUTE(\"field\"),%n"
+ "SECOND(\"field\"),%n"
+ "QUARTER(\"field\"),%n"
+ "DAYNAME(\"field\"),%n"
+ "MONTHNAME(\"field\")",
getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
// Year is 2020.
Assertions.assertEquals(2020, resultSet.getInt(1));
// Month is 2 (Feb).
Assertions.assertEquals(2, resultSet.getInt(2));
// Week in year is 5.
Assertions.assertEquals(5, resultSet.getInt(3));
// Day of month is 3.
Assertions.assertEquals(3, resultSet.getInt(4));
// Day of week is 2 (Monday).
Assertions.assertEquals(2, resultSet.getInt(5));
// Day of year is 34.
Assertions.assertEquals(34, resultSet.getInt(6));
// Hour is 4.
Assertions.assertEquals(4, resultSet.getInt(7));
// Minute is 5.
Assertions.assertEquals(5, resultSet.getInt(8));
// Seconds is 6.
Assertions.assertEquals(6, resultSet.getInt(9));
// Quarter is 1.
Assertions.assertEquals(1, resultSet.getInt(10));
// Day name is Monday
Assertions.assertEquals("星期一", resultSet.getString(11));
// Month name is February
Assertions.assertEquals("二月", resultSet.getString(12));
Assertions.assertFalse(resultSet.next());
// Use extract in CASE.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT "
+ "CASE WHEN DAYOFMONTH(\"field\") < 5 "
+ "THEN 'A' "
+ "ELSE 'B' "
+ "END "
+ "FROM \"%s\".\"%s\" ", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet2);
Assertions.assertTrue(resultSet2.next());
Assertions.assertEquals("A", resultSet2.getString(1));
Assertions.assertTrue(resultSet2.next());
Assertions.assertEquals("A", resultSet2.getString(1));
Assertions.assertFalse(resultSet2.next());
} finally {
Locale.setDefault(originalLocale);
}
}
}
@DisplayName("Tests DAYNAME")
@ParameterizedTest(name = "testDayName - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testDayName(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testDayName";
final List<BsonDocument> docs = new ArrayList<>();
final Instant startingDateTime = Instant.parse("2020-02-02T04:05:06.00Z");
for (int i = 0; i < 8; i++) {
docs.add(new BsonDocument(
"field",
new BsonDateTime(startingDateTime.plus(i, ChronoUnit.DAYS).toEpochMilli())));
}
insertBsonDocuments(tableName, docs.toArray(new BsonDocument[0]));
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
final Locale originalLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.SIMPLIFIED_CHINESE);
// Get date parts.
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT "
+ "DAYNAME(\"field\"), \"field\""
+ "FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
new Timestamp(startingDateTime.plus(0, ChronoUnit.DAYS).toEpochMilli()),
resultSet.getTimestamp(2));
Assertions.assertEquals(
DayOfWeek.SUNDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.MONDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.TUESDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.WEDNESDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.THURSDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.FRIDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.SATURDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
DayOfWeek.SUNDAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertFalse(resultSet.next());
} finally {
Locale.setDefault(originalLocale);
}
}
}
@DisplayName("Tests MONTHNAME")
@ParameterizedTest(name = "testMonthName - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testMonthName(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testMonthName";
final List<BsonDocument> docs = new ArrayList<>();
final OffsetDateTime startingDateTime = Instant.parse("2020-01-02T04:05:06.00Z").atOffset(ZoneOffset.UTC);
for (int i = 0; i < 13; i++) {
docs.add(new BsonDocument(
"field",
new BsonDateTime(startingDateTime.plusMonths(i).toInstant().toEpochMilli())));
}
docs.add(new BsonDocument(
"field",
new BsonNull()));
insertBsonDocuments(tableName, docs.toArray(new BsonDocument[0]));
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
final Locale originalLocale = Locale.getDefault();
try {
Locale.setDefault(Locale.SIMPLIFIED_CHINESE);
// Get date parts.
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT "
+ "MONTHNAME(\"field\"), \"field\""
+ "FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
new Timestamp(startingDateTime.toInstant().toEpochMilli()),
resultSet.getTimestamp(2));
Assertions.assertEquals(
Month.JANUARY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.FEBRUARY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.MARCH.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.APRIL.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.MAY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.JUNE.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.JULY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.AUGUST.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.SEPTEMBER.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.OCTOBER.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.NOVEMBER.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.DECEMBER.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
Month.JANUARY.getDisplayName(TextStyle.FULL, Locale.getDefault()),
resultSet.getString(1));
Assertions.assertTrue(resultSet.next());
Assertions.assertNull(resultSet.getString(1));
Assertions.assertFalse(resultSet.next());
} finally {
Locale.setDefault(originalLocale);
}
}
}
@DisplayName("Tests MONTHNAME for NULL")
@ParameterizedTest(name = "testMonthNameForNull - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testMonthNameForNull(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testMonthNameForNull";
final List<BsonDocument> docs = new ArrayList<>();
docs.add(new BsonDocument(
"field",
new BsonNull()));
insertBsonDocuments(tableName, docs.toArray(new BsonDocument[0]));
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get month name.
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT %n"
+ " MONTHNAME(CAST(NULL AS TIMESTAMP))%n"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertNull(resultSet.getString(1));
Assertions.assertFalse(resultSet.next());
// Get date parts.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT %n"
+ " MONTHNAME(NULL)%n"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet2);
Assertions.assertTrue(resultSet2.next());
Assertions.assertNull(resultSet2.getString(1));
Assertions.assertFalse(resultSet2.next());
final ResultSet resultSet3 = statement.executeQuery(
String.format("SELECT %n"
+ " MONTHNAME(CAST(\"field\" AS TIMESTAMP))%n"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet3);
Assertions.assertTrue(resultSet3.next());
Assertions.assertNull(resultSet3.getTimestamp(1));
Assertions.assertFalse(resultSet3.next());
}
}
@DisplayName("Tests DAYNAME for NULL")
@ParameterizedTest(name = "testDayNameForNull - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testDayNameForNull(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testDayNameForNull";
final List<BsonDocument> docs = new ArrayList<>();
docs.add(new BsonDocument(
"field",
new BsonNull()));
insertBsonDocuments(tableName, docs.toArray(new BsonDocument[0]));
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get month name.
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT %n"
+ " DAYNAME(CAST(NULL AS TIMESTAMP))%n"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertNull(resultSet.getString(1));
Assertions.assertFalse(resultSet.next());
// Get date parts.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT %n"
+ " DAYNAME(NULL)%n"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet2);
Assertions.assertTrue(resultSet2.next());
Assertions.assertNull(resultSet2.getString(1));
Assertions.assertFalse(resultSet2.next());
final ResultSet resultSet3 = statement.executeQuery(
String.format("SELECT %n"
+ " DAYNAME(CAST(\"field\" AS TIMESTAMP))%n"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet3);
Assertions.assertTrue(resultSet3.next());
Assertions.assertNull(resultSet3.getTimestamp(1));
Assertions.assertFalse(resultSet3.next());
}
}
/**
* Tests CURRENT_TIMESTAMP.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests CURRENT_TIMESTAMP.")
@ParameterizedTest(name = "testCurrentTimestamp - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testCurrentTimestamp(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testCurrentTimestamp";
final long dateTime = Instant.parse("2020-02-03T04:05:06.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get current date.
final ResultSet resultSet1 = statement.executeQuery(
String.format("SELECT CURRENT_TIMESTAMP"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
final Function<ResultSet, SQLException> validateResultSet = (testResultSet) -> {
try {
Assertions.assertNotNull(testResultSet);
Assertions.assertTrue(testResultSet.next());
Assertions.assertEquals(Types.TIMESTAMP,
testResultSet.getMetaData().getColumnType(1));
final Timestamp timestamp = testResultSet.getTimestamp(1);
Assertions.assertNotNull(timestamp);
final OffsetDateTime actualDateTime = timestamp.toInstant()
.atOffset(ZoneOffset.UTC);
final OffsetDateTime currentDateTime = Instant.now().atOffset(ZoneOffset.UTC);
final long diffInMilliSeconds = actualDateTime
.until(currentDateTime, ChronoUnit.MILLIS);
Assertions.assertTrue(diffInMilliSeconds >= 0);
Assertions.assertTrue(diffInMilliSeconds < 1000);
Assertions.assertFalse(testResultSet.next());
return null;
} catch (SQLException e) {
return e;
}
};
SQLException e = validateResultSet.apply(resultSet1);
if (e != null) {
throw e;
}
// Get current date as alias column name.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT CURRENT_TIMESTAMP AS \"cts\""
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
e = validateResultSet.apply(resultSet2);
if (e != null) {
throw e;
}
// Where clause use.
final ResultSet resultSet3 = statement.executeQuery(
String.format("SELECT \"field\" "
+ " FROM \"%s\".\"%s\""
+ " WHERE \"field\" < CURRENT_TIMESTAMP", getDatabaseName(),
tableName));
Assertions.assertNotNull(resultSet3);
Assertions.assertTrue(resultSet3.next());
Assertions.assertEquals(dateTime, resultSet3.getTimestamp(1).getTime());
Assertions.assertFalse(resultSet3.next());
final ResultSet resultSet4 = statement.executeQuery(
String.format("SELECT \"field\" "
+ " FROM \"%s\".\"%s\""
+ " WHERE \"field\" > CURRENT_TIMESTAMP", getDatabaseName(),
tableName));
Assertions.assertNotNull(resultSet4);
Assertions.assertFalse(resultSet4.next());
}
}
/**
* Tests CURRENT_DATE.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests CURRENT_DATE.")
@ParameterizedTest(name = "testCurrentDate - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testCurrentDate(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testCurrentDate";
final long dateTime = Instant.parse("2020-02-03T04:05:06.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get current date.
final ResultSet resultSet1 = statement.executeQuery(
String.format("SELECT CURRENT_DATE"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
final Function<ResultSet, SQLException> validateResultSet = (testResultSet) -> {
try {
Assertions.assertNotNull(testResultSet);
Assertions.assertTrue(testResultSet.next());
Assertions.assertEquals(Types.DATE,
testResultSet.getMetaData().getColumnType(1));
final Date actualDate = testResultSet.getDate(1);
Assertions.assertNotNull(actualDate);
final Date currentDate = new Date(Instant.now().toEpochMilli());
Assertions.assertEquals(currentDate.toString(), actualDate.toString());
Assertions.assertFalse(testResultSet.next());
return null;
} catch (SQLException e) {
return e;
}
};
SQLException e = validateResultSet.apply(resultSet1);
if (e != null) {
throw e;
}
// Get current date as alias column name.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT CURRENT_DATE AS \"cts\""
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
e = validateResultSet.apply(resultSet2);
if (e != null) {
throw e;
}
// Where clause use.
final ResultSet resultSet3 = statement.executeQuery(
String.format("SELECT \"field\" "
+ " FROM \"%s\".\"%s\""
+ " WHERE \"field\" < CURRENT_DATE", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet3);
Assertions.assertTrue(resultSet3.next());
Assertions.assertEquals(dateTime, resultSet3.getDate(1).getTime());
Assertions.assertFalse(resultSet3.next());
final ResultSet resultSet4 = statement.executeQuery(
String.format("SELECT \"field\" "
+ " FROM \"%s\".\"%s\""
+ " WHERE \"field\" > CURRENT_DATE", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet4);
Assertions.assertFalse(resultSet4.next());
}
}
/**
* Tests CURRENT_TIME.
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests CURRENT_TIME.")
@ParameterizedTest(name = "testCurrentTime - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testCurrentTime(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testCurrentTime";
final long dateTime = Instant.parse("2020-02-03T04:05:06.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get current date.
final ResultSet resultSet1 = statement.executeQuery(
String.format("SELECT CURRENT_TIME"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
final Function<ResultSet, SQLException> validateResultSet = (testResultSet) -> {
try {
Assertions.assertNotNull(testResultSet);
Assertions.assertTrue(testResultSet.next());
Assertions.assertEquals(Types.TIME,
testResultSet.getMetaData().getColumnType(1));
final Time actualDate = testResultSet.getTime(1);
Assertions.assertNotNull(actualDate);
final Time currentTime = new Time(Instant.now().toEpochMilli());
final long timeDiff = actualDate.toLocalTime()
.until(currentTime.toLocalTime(), ChronoUnit.MILLIS);
Assertions.assertTrue(timeDiff < 2000);
Assertions.assertFalse(testResultSet.next());
return null;
} catch (SQLException e) {
return e;
}
};
SQLException e = validateResultSet.apply(resultSet1);
if (e != null) {
throw e;
}
// Get current date as alias column name.
final ResultSet resultSet2 = statement.executeQuery(
String.format("SELECT CURRENT_TIME AS \"cts\""
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
e = validateResultSet.apply(resultSet2);
if (e != null) {
throw e;
}
// Where clause use - must cast to TIME to make it comparable.
final ResultSet resultSet3 = statement.executeQuery(
String.format("SELECT \"field\""
+ " FROM \"%s\".\"%s\""
+ " WHERE CAST(\"field\" AS TIME) < CURRENT_TIME", getDatabaseName(),
tableName));
Assertions.assertNotNull(resultSet3);
Assertions.assertTrue(resultSet3.next());
Assertions.assertEquals(dateTime, resultSet3.getDate(1).getTime());
Assertions.assertFalse(resultSet3.next());
final ResultSet resultSet4 = statement.executeQuery(
String.format("SELECT \"field\""
+ " FROM \"%s\".\"%s\""
+ " WHERE CAST(\"field\" AS TIME) > CURRENT_TIME", getDatabaseName(),
tableName));
Assertions.assertNotNull(resultSet4);
Assertions.assertFalse(resultSet4.next());
}
}
/**
* Tests for queries FLOOR(... TO ...) in select clause.
*
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests for queries FLOOR(... TO ...) in select clause.")
@ParameterizedTest(name = "testQuerySelectFloorForDate - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testQuerySelectFloorForDate(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testQuerySelectFloorForDate";
final Instant dateTime = Instant.parse("2020-02-03T12:34:56.78Z");
final OffsetDateTime offsetDateTime = dateTime.atOffset(ZoneOffset.UTC);
final Instant epochDateTime = Instant.EPOCH;
final OffsetDateTime offsetEpochDateTime = epochDateTime.atOffset(ZoneOffset.UTC);
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime.toEpochMilli()));
doc1.append("fieldEpoch", new BsonDateTime(epochDateTime.toEpochMilli()));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
final ResultSet resultSet = statement.executeQuery(
String.format("SELECT"
+ " FLOOR(\"field\" TO YEAR),"
+ " FLOOR(\"field\" TO MONTH),"
+ " FLOOR(\"field\" TO QUARTER),"
+ " FLOOR(\"field\" TO DAY),"
+ " FLOOR(\"field\" TO HOUR),"
+ " FLOOR(\"field\" TO MINUTE),"
+ " FLOOR(\"field\" TO SECOND),"
+ " FLOOR(\"field\" TO MILLISECOND),"
+ " FLOOR(\"fieldEpoch\" TO YEAR),"
+ " FLOOR(\"fieldEpoch\" TO MONTH),"
+ " FLOOR(\"fieldEpoch\" TO QUARTER),"
+ " FLOOR(\"fieldEpoch\" TO DAY),"
+ " FLOOR(\"fieldEpoch\" TO HOUR),"
+ " FLOOR(\"fieldEpoch\" TO MINUTE),"
+ " FLOOR(\"fieldEpoch\" TO SECOND),"
+ " FLOOR(\"fieldEpoch\" TO MILLISECOND),"
+ " FLOOR(NULL TO MILLISECOND)"
+ " FROM \"%s\".\"%s\"",
getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet);
Assertions.assertTrue(resultSet.next());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, 1),
resultSet.getTimestamp(1).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, offsetDateTime.getMonthValue()),
resultSet.getTimestamp(2).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, 1),
resultSet.getTimestamp(3).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet.getTimestamp(4).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.HOURS),
resultSet.getTimestamp(5).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.MINUTES),
resultSet.getTimestamp(6).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.SECONDS),
resultSet.getTimestamp(7).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.MILLIS),
resultSet.getTimestamp(8).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetEpochDateTime, 1),
resultSet.getTimestamp(9).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetEpochDateTime, offsetEpochDateTime.getMonthValue()),
resultSet.getTimestamp(10).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetEpochDateTime, 1),
resultSet.getTimestamp(11).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(epochDateTime, ChronoUnit.DAYS),
resultSet.getTimestamp(12).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(epochDateTime, ChronoUnit.HOURS),
resultSet.getTimestamp(13).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(epochDateTime, ChronoUnit.MINUTES),
resultSet.getTimestamp(14).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(epochDateTime, ChronoUnit.SECONDS),
resultSet.getTimestamp(15).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(epochDateTime, ChronoUnit.MILLIS),
resultSet.getTimestamp(16).getTime());
Assertions.assertNull(resultSet.getTimestamp(17));
Assertions.assertFalse(resultSet.next());
// Test WEEK (to Monday) truncation
final ResultSet resultSet1 = statement.executeQuery(String.format(
"SELECT"
+ " FLOOR(\"field\" TO WEEK)," // Monday
+ " FLOOR(TIMESTAMPADD(DAY, 1, \"field\") TO WEEK)," // Tuesday
+ " FLOOR(TIMESTAMPADD(DAY, 2, \"field\") TO WEEK)," // Wednesday
+ " FLOOR(TIMESTAMPADD(DAY, 3, \"field\") TO WEEK)," // Thursday
+ " FLOOR(TIMESTAMPADD(DAY, 4, \"field\") TO WEEK)," // Friday
+ " FLOOR(TIMESTAMPADD(DAY, 5, \"field\") TO WEEK)," // Saturday
+ " FLOOR(TIMESTAMPADD(DAY, 6, \"field\") TO WEEK)," // Sunday
+ " FLOOR(TIMESTAMPADD(DAY, 7, \"field\") TO WEEK)," // Next week
+ " FLOOR(NULL TO WEEK)" // NULL
+ " FROM \"%s\".\"%s\"",
getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet1);
Assertions.assertTrue(resultSet1.next());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(1).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(2).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(3).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(4).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(5).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(6).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(dateTime, ChronoUnit.DAYS),
resultSet1.getTimestamp(7).getTime());
// Next week
Assertions.assertEquals(
getTruncatedTimestamp(
dateTime
.atOffset(ZoneOffset.UTC)
.plus(1, ChronoUnit.WEEKS)
.toInstant(), ChronoUnit.DAYS),
resultSet1.getTimestamp(8).getTime());
Assertions.assertNull(resultSet1.getTimestamp(9));
Assertions.assertFalse(resultSet1.next());
// Test QUARTER truncation
final ResultSet resultSet2 = statement.executeQuery(String.format(
"SELECT %n"
+ " FLOOR(\"field\" TO QUARTER), %n"
+ " FLOOR(TIMESTAMPADD(DAY, 100, \"field\") TO QUARTER), %n"
+ " FLOOR(TIMESTAMPADD(DAY, 200, \"field\") TO QUARTER), %n"
+ " FLOOR(TIMESTAMPADD(DAY, 300, \"field\") TO QUARTER), %n"
+ " FLOOR(NULL TO QUARTER) %n"
+ " FROM \"%s\".\"%s\"",
getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet2);
Assertions.assertTrue(resultSet2.next());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, 1), // Jan. 01
resultSet2.getTimestamp(1).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, 4), // Apr. 01
resultSet2.getTimestamp(2).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, 7), // Jul. 01
resultSet2.getTimestamp(3).getTime());
Assertions.assertEquals(
getTruncatedTimestamp(offsetDateTime, 10), // Oct. 01
resultSet2.getTimestamp(4).getTime());
Assertions.assertNull(resultSet2.getTimestamp(5)); // NULL
Assertions.assertFalse(resultSet2.next());
// Don't support FLOOR for numeric, yet.
final String errorMessage = Assertions.assertThrows(
SQLException.class,
() -> statement.executeQuery(
String.format("SELECT FLOOR(12.34) FROM \"%s\".\"%s\"",
getDatabaseName(), tableName))).getMessage();
Assertions.assertTrue(
errorMessage.startsWith(String.format(
"Unable to parse SQL 'SELECT FLOOR(12.34) FROM \"%s\".\"testQuerySelectFloorForDate\"'.",
getDatabaseName()))
&& errorMessage.endsWith(
"Additional info: 'Translation of FLOOR(12.34:DECIMAL(4, 2)) is not supported by DocumentDbRules''"));
}
}
/**
* Tests CURRENT_TIMESTAMP, CURRENT_TIME and CURRENT_DATE for multiple instances are the same value.
*
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests CURRENT_TIMESTAMP, CURRENT_TIME and CURRENT_DATE for multiple instances are the same value.")
@ParameterizedTest(name = "testCurrentTimestampMultipleInstances - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testCurrentTimestampMultipleInstances(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testCurrentTimestampMultipleInstances";
final long dateTime = Instant.parse("2020-02-03T04:05:06.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
insertBsonDocuments(tableName, new BsonDocument[]{doc1});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Get current date.
final ResultSet resultSet1 = statement.executeQuery(
String.format(
"SELECT CURRENT_TIMESTAMP AS ts, CURRENT_TIME AS t, CURRENT_DATE AS d"
+ " FROM \"%s\".\"%s\"", getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet1);
Assertions.assertTrue(resultSet1.next());
Assertions.assertEquals(Types.TIMESTAMP,
resultSet1.getMetaData().getColumnType(1));
Assertions.assertEquals(Types.TIME,
resultSet1.getMetaData().getColumnType(2));
Assertions.assertEquals(Types.DATE,
resultSet1.getMetaData().getColumnType(3));
final Timestamp timestamp = resultSet1.getTimestamp(1);
final Timestamp time = resultSet1.getTimestamp(2);
final Timestamp date = resultSet1.getTimestamp(3);
Assertions.assertNotNull(timestamp);
Assertions.assertNotNull(time);
Assertions.assertNotNull(date);
Assertions.assertEquals(timestamp, time);
Assertions.assertEquals(timestamp, date);
Assertions.assertFalse(resultSet1.next());
}
}
/**
* Tests select dates with AND condition.
*
* @throws SQLException occurs if query fails.
*/
@DisplayName("Tests select dates with AND condition.")
@ParameterizedTest(name = "testSelectDateWithAnd - [{index}] - {arguments}")
@MethodSource({"getTestEnvironments"})
void testSelectDateWithAnd(final DocumentDbTestEnvironment testEnvironment) throws SQLException {
setTestEnvironment(testEnvironment);
final String tableName = "testSelectDateWithAnd";
final long dateTime = Instant.parse("2020-02-03T04:05:06.00Z").toEpochMilli();
final BsonDocument doc1 = BsonDocument.parse("{\"_id\": 101}");
doc1.append("field", new BsonDateTime(dateTime));
final BsonDocument doc2 = BsonDocument.parse("{\"_id\": 102}");
doc2.append("field", new BsonNull());
insertBsonDocuments(tableName, new BsonDocument[]{doc1, doc2});
try (Connection connection = getConnection()) {
final Statement statement = getDocumentDbStatement(connection);
// Find condition that doesn't exist.
final ResultSet resultSet1 = statement.executeQuery(
String.format(
"SELECT \"field\" > '2021-01-01' AND \"field\" < '2020-02-01' FROM \"%s\".\"%s\"",
getDatabaseName(), tableName));
Assertions.assertNotNull(resultSet1);
Assertions.assertTrue(resultSet1.next());
// Non-NULL result
Assertions.assertEquals(Types.BOOLEAN, resultSet1.getMetaData().getColumnType(1));
final Boolean aBoolean = resultSet1.getBoolean(1);
Assertions.assertFalse(resultSet1.wasNull());
Assertions.assertNotNull(aBoolean);
Assertions.assertFalse(aBoolean);
// NULL result
Assertions.assertTrue(resultSet1.next());
Assertions.assertNull(resultSet1.getObject(1));
resultSet1.getBoolean(1);
Assertions.assertTrue(resultSet1.wasNull());
Assertions.assertFalse(resultSet1.next());
}
}
private long getTruncatedTimestamp(final OffsetDateTime offsetDateTime, final int monthValue) {
return OffsetDateTime.of(
offsetDateTime.getYear(), monthValue, 1,
0, 0, 0, 0,
ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
}
private long getTruncatedTimestamp(final Instant dateTime, final ChronoUnit chronoUnit) {
return dateTime
.atOffset(ZoneOffset.UTC)
.truncatedTo(chronoUnit)
.toInstant()
.toEpochMilli();
}
}
| 51.799177
| 130
| 0.568212
|
93a0adac285bdeb31e0ea80d42b48a6658e88d29
| 11,821
|
package com.hartwig.hmftools.patientdb.matchers;
import static com.hartwig.hmftools.patientdb.data.TestDatamodelFactory.biopsyBuilder;
import static com.hartwig.hmftools.patientdb.data.TestDatamodelFactory.sampleBuilder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.Collections;
import java.util.List;
import com.google.common.collect.Lists;
import com.hartwig.hmftools.patientdb.data.BiopsyData;
import com.hartwig.hmftools.patientdb.data.SampleData;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.junit.Test;
public class BiopsyMatcherTest {
private final static LocalDate JAN2015 = LocalDate.parse("2015-01-01");
private final static LocalDate FEB2015 = LocalDate.parse("2015-02-01");
private final static LocalDate MAR2015 = LocalDate.parse("2015-03-01");
private final static LocalDate JUL2015 = LocalDate.parse("2015-07-01");
private final static LocalDate AUG2015 = LocalDate.parse("2015-08-01");
private final static LocalDate SEP2015 = LocalDate.parse("2015-09-01");
private final static LocalDate NOV2015 = LocalDate.parse("2015-11-01");
private final static SampleData SEQUENCED_BIOPSY_JUL = sampleBuilder(JUL2015).build();
private final static SampleData SEQUENCED_BIOPSY_AUG = sampleBuilder(AUG2015).build();
private final static SampleData SEQUENCED_BIOPSY_SEP = sampleBuilder(SEP2015).build();
private final static SampleData SEQUENCED_BIOPSY_NOV = sampleBuilder(NOV2015).build();
private final static SampleData SEQUENCED_BIOPSY_ARRIVED_NOV_SAMPLED_MAR = sampleBuilder(NOV2015).samplingDate(MAR2015).build();
private final static BiopsyData CLINICAL_BIOPSY_JAN = biopsyBuilder().date(JAN2015).build();
private final static BiopsyData CLINICAL_BIOPSY_FEB = biopsyBuilder().date(FEB2015).build();
private final static BiopsyData CLINICAL_BIOPSY_MAR = biopsyBuilder().date(MAR2015).build();
private final static BiopsyData CLINICAL_BIOPSY_MAR_NOT_EVALUABLE = biopsyBuilder().date(MAR2015).biopsyEvaluable("no").build();
private final static BiopsyData CLINICAL_BIOPSY_JUL = biopsyBuilder().date(JUL2015).build();
private final static BiopsyData CLINICAL_BIOPSY_SEP = biopsyBuilder().date(SEP2015).build();
private final static BiopsyData CLINICAL_BIOPSY_NULL = biopsyBuilder().build();
// MIVO: ---biopsy(jul)/sample(jul)---
@Test
public void biopsyAndSampleSameDateYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_JUL);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, SEQUENCED_BIOPSY_JUL.sampleId());
}
// MIVO: ---biopsy(mar)-x-x-x-sample(jul)---
@Test
public void biopsyBeforeSampleWithinThresholdYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_MAR);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, SEQUENCED_BIOPSY_JUL.sampleId());
}
// MIVO: ---biopsy(jan)-x-x-x-x-x-sample(jul)---
@Test
public void biopsyBeforeSampleOutsideThresholdYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_JAN);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null);
}
// MIVO: ---sample(aug)-biopsy(sep)---
@Test
public void biopsyTakenAfterSampleArrivedYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_AUG);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_SEP);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null);
}
// MIVO: ---biopsy(feb)-biopsy(mar)-x-x-x-sample(jul)---
@Test
public void twoBiopsiesBeforeSampleWithinThresholdYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_FEB, CLINICAL_BIOPSY_MAR);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, null);
}
// MIVO: ---biopsy(feb)-x-x-null(?)-x-sample(jul)---
@Test
public void twoBiopsiesSecondNullBeforeSampleWithinThresholdYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_FEB, CLINICAL_BIOPSY_NULL);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, null);
}
// MIVO: ---null(?)-biopsy(feb)-x-x-x-x-sample(jul)---
@Test
public void twoBiopsiesFirstNullBeforeSampleWithinThresholdYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_NULL, CLINICAL_BIOPSY_FEB);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, null);
}
// MIVO: ---biopsy(jan)-x-biopsy(mar)-x-x-x-sample(jul)---
@Test
public void twoBiopsiesBeforeSampleOneWithinThresholdYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_JAN, CLINICAL_BIOPSY_MAR);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, SEQUENCED_BIOPSY_JUL.sampleId());
}
// MIVO: ---biopsy(jan)-x-biopsy(mar)-x-x-x-sample(jul)---
@Test
public void twoBiopsiesBeforeSample1WithinThresholdOutOfOrderYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_MAR, CLINICAL_BIOPSY_JAN);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, SEQUENCED_BIOPSY_JUL.sampleId());
}
// MIVO: ---biopsy(jan)-biopsy(feb)-x-x-x-x-x-x-sample(sep)---
@Test
public void twoBiopsiesBeforeSampleOutsideThresholdYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_SEP);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_JAN, CLINICAL_BIOPSY_FEB);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, null);
}
// MIVO: ---biopsy(feb)-x-x-x-x-sample(jul)-sample(aug)---
@Test
public void biopsyBefore2SamplesWithinThresholdYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL, SEQUENCED_BIOPSY_AUG);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_FEB);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, SEQUENCED_BIOPSY_JUL.sampleId());
}
// MIVO: ---biopsy(mar)-x-x-x-sample(jul)-x-biopsy(sep)---
@Test
public void oneSampleBetween2BiopsiesWithinThresholdYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_MAR, CLINICAL_BIOPSY_SEP);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, SEQUENCED_BIOPSY_JUL.sampleId(), null);
}
// MIVO: ---biopsy(feb)-biopsy(mar)-x-x-x-x-sample(aug)-sample(sep)---
@Test
public void twoSamplesAfterTwoBiopsiesYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_SEP, SEQUENCED_BIOPSY_NOV);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_FEB, CLINICAL_BIOPSY_MAR);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, null);
}
// MIVO: ---biopsy(mar)-x-x-x-x-sample(aug)-biopsy(sep)-x-sample(nov)---
@Test
public void twoSamplesBetweenTwoBiopsiesWithinThresholdYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_AUG, SEQUENCED_BIOPSY_NOV);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_MAR, CLINICAL_BIOPSY_SEP);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, SEQUENCED_BIOPSY_AUG.sampleId(), SEQUENCED_BIOPSY_NOV.sampleId());
}
// MIVO: ---biopsy(jan)-x-x-x-x-x-x-sample(aug)-biopsy(sep)-x-sample(nov)---
@Test
public void twoSamplesBetweenTwoBiopsiesOneOutsideThresholdYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_AUG, SEQUENCED_BIOPSY_NOV);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_JAN, CLINICAL_BIOPSY_SEP);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null, SEQUENCED_BIOPSY_NOV.sampleId());
}
// KODU: --biopsy(mar)-x-x-x-x-sample(nov)--
@Test
public void biopsyArrivedInNovButSamplingDateKnownYieldsMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_ARRIVED_NOV_SAMPLED_MAR);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_MAR);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, SEQUENCED_BIOPSY_ARRIVED_NOV_SAMPLED_MAR.sampleId());
}
// KODU: --biopsy(jan)-x-sample(mar)-x-x-sample_arrived(nov)--
@Test
public void biopsyFromJanArrivedInNovButSamplingDateInMarYieldsNoMatch() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_ARRIVED_NOV_SAMPLED_MAR);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_JAN);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null);
}
@Test
public void noMatchWhenBiopsyIsNotEvaluable() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList(CLINICAL_BIOPSY_MAR_NOT_EVALUABLE);
runMatcherAndVerify(sequencedBiopsies, clinicalBiopsies, null);
}
@Test
public void createFindingWhenNotEnoughClinicalBiopsies() {
final List<SampleData> sequencedBiopsies = Lists.newArrayList(SEQUENCED_BIOPSY_JUL);
final List<BiopsyData> clinicalBiopsies = Lists.newArrayList();
MatchResult<BiopsyData> matchedBiopsies = BiopsyMatcher.matchBiopsiesToTumorSamples("patient", sequencedBiopsies, clinicalBiopsies);
assertEquals(2, matchedBiopsies.findings().size());
assertTrue(matchedBiopsies.findings().get(0).message().toLowerCase().contains("not enough clinical biopsy forms to match"));
}
private static void runMatcherAndVerify(@NotNull List<SampleData> sequencedBiopsies, @NotNull List<BiopsyData> clinicalBiopsies,
@Nullable String... expectedSampleIds) {
final List<BiopsyData> matchedBiopsies =
BiopsyMatcher.matchBiopsiesToTumorSamples("patient", sequencedBiopsies, clinicalBiopsies).values();
assertTrue(clinicalBiopsies.size() == matchedBiopsies.size());
if (expectedSampleIds == null) {
assertEquals(null, matchedBiopsies.get(0).sampleId());
} else {
Collections.sort(matchedBiopsies);
for (int i = 0; i < expectedSampleIds.length; i++) {
assertTrue(matchedBiopsies.size() >= i);
assertEquals(expectedSampleIds[i], matchedBiopsies.get(i).sampleId());
}
}
}
}
| 50.302128
| 140
| 0.747145
|
5eb87591e19bb5cde5f5fa2c468fbc30dc167148
| 9,581
|
/*
* Tencent is pleased to support the open source community by making Angel available.
*
* Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
*
* https://opensource.org/licenses/BSD-3-Clause
*
* 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.tencent.angel.master;
import com.google.protobuf.ServiceException;
import com.tencent.angel.client.AngelClient;
import com.tencent.angel.client.AngelClientFactory;
import com.tencent.angel.conf.AngelConf;
import com.tencent.angel.conf.MatrixConf;
import com.tencent.angel.exception.AngelException;
import com.tencent.angel.localcluster.LocalClusterContext;
import com.tencent.angel.master.task.AMTask;
import com.tencent.angel.master.task.AMTaskManager;
import com.tencent.angel.master.worker.WorkerManager;
import com.tencent.angel.master.worker.attempt.WorkerAttempt;
import com.tencent.angel.master.worker.worker.AMWorker;
import com.tencent.angel.master.worker.workergroup.AMWorkerGroup;
import com.tencent.angel.ml.matrix.MatrixContext;
import com.tencent.angel.ml.matrix.MatrixMetaManager;
import com.tencent.angel.ml.matrix.RowType;
import com.tencent.angel.psagent.PSAgent;
import com.tencent.angel.psagent.client.MasterClient;
import com.tencent.angel.psagent.matrix.PSAgentMatrixMetaManager;
import com.tencent.angel.worker.Worker;
import com.tencent.angel.worker.WorkerAttemptId;
import com.tencent.angel.worker.WorkerGroupId;
import com.tencent.angel.worker.WorkerId;
import com.tencent.angel.worker.task.TaskId;
import it.unimi.dsi.fastutil.ints.Int2IntOpenHashMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.mapreduce.lib.input.CombineTextInputFormat;
import org.apache.log4j.PropertyConfigurator;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class TaskManagerTest {
private static final Log LOG = LogFactory.getLog(TaskManagerTest.class);
private static final String LOCAL_FS = LocalFileSystem.DEFAULT_FS;
private static final String TMP_PATH = System.getProperty("java.io.tmpdir", "/tmp");
private static AngelClient angelClient;
private static WorkerGroupId group0Id;
private static WorkerId worker0Id;
private static WorkerAttemptId worker0Attempt0Id;
private static TaskId task0Id;
private static TaskId task1Id;
static {
PropertyConfigurator.configure("../conf/log4j.properties");
}
@BeforeClass
public static void setup() throws Exception {
try {
// set basic configuration keys
Configuration conf = new Configuration();
conf.setBoolean("mapred.mapper.new-api", true);
conf.setBoolean(AngelConf.ANGEL_JOB_OUTPUT_PATH_DELETEONEXIST, true);
conf.set(AngelConf.ANGEL_TASK_USER_TASKCLASS, DummyTask.class.getName());
// use local deploy mode and dummy dataspliter
conf.set(AngelConf.ANGEL_DEPLOY_MODE, "LOCAL");
conf.setBoolean(AngelConf.ANGEL_AM_USE_DUMMY_DATASPLITER, true);
conf.set(AngelConf.ANGEL_INPUTFORMAT_CLASS, CombineTextInputFormat.class.getName());
conf.set(AngelConf.ANGEL_SAVE_MODEL_PATH, LOCAL_FS + TMP_PATH + "/out");
conf.set(AngelConf.ANGEL_TRAIN_DATA_PATH, LOCAL_FS + TMP_PATH + "/in");
conf.set(AngelConf.ANGEL_LOG_PATH, LOCAL_FS + TMP_PATH + "/log");
conf.setInt(AngelConf.ANGEL_WORKERGROUP_NUMBER, 1);
conf.setInt(AngelConf.ANGEL_PS_NUMBER, 1);
conf.setInt(AngelConf.ANGEL_WORKER_TASK_NUMBER, 2);
// get a angel client
angelClient = AngelClientFactory.get(conf);
// add matrix
MatrixContext mMatrix = new MatrixContext();
mMatrix.setName("w1");
mMatrix.setRowNum(1);
mMatrix.setColNum(100000);
mMatrix.setMaxRowNumInBlock(1);
mMatrix.setMaxColNumInBlock(50000);
mMatrix.setRowType(RowType.T_INT_DENSE);
mMatrix.set(MatrixConf.MATRIX_OPLOG_ENABLEFILTER, "false");
mMatrix.set(MatrixConf.MATRIX_HOGWILD, "true");
mMatrix.set(MatrixConf.MATRIX_AVERAGE, "false");
mMatrix.set(MatrixConf.MATRIX_OPLOG_TYPE, "DENSE_INT");
angelClient.addMatrix(mMatrix);
MatrixContext mMatrix2 = new MatrixContext();
mMatrix2.setName("w2");
mMatrix2.setRowNum(1);
mMatrix2.setColNum(100000);
mMatrix2.setMaxRowNumInBlock(1);
mMatrix2.setMaxColNumInBlock(50000);
mMatrix2.setRowType(RowType.T_DOUBLE_DENSE);
mMatrix2.set(MatrixConf.MATRIX_OPLOG_ENABLEFILTER, "false");
mMatrix2.set(MatrixConf.MATRIX_HOGWILD, "false");
mMatrix2.set(MatrixConf.MATRIX_AVERAGE, "false");
mMatrix2.set(MatrixConf.MATRIX_OPLOG_TYPE, "DENSE_DOUBLE");
angelClient.addMatrix(mMatrix2);
angelClient.startPSServer();
angelClient.run();
Thread.sleep(5000);
group0Id = new WorkerGroupId(0);
worker0Id = new WorkerId(group0Id, 0);
worker0Attempt0Id = new WorkerAttemptId(worker0Id, 0);
task0Id = new TaskId(0);
task1Id = new TaskId(1);
} catch (Exception x) {
LOG.error("setup failed ", x);
throw x;
}
}
@Test
public void testTaskIteration() throws Exception {
try {
LOG.info("===========================testTaskIteration===============================");
AngelApplicationMaster angelAppMaster = LocalClusterContext.get().getMaster().getAppMaster();
assertTrue(angelAppMaster != null);
AMTaskManager taskManager = angelAppMaster.getAppContext().getTaskManager();
WorkerManager workerManager = angelAppMaster.getAppContext().getWorkerManager();
assertTrue(workerManager != null);
AMWorkerGroup workerGroup0 = workerManager.getWorkGroup(worker0Id);
AMWorker worker0 = workerGroup0.getWorker(worker0Id);
WorkerAttempt worker0Attempt0 = worker0.getWorkerAttempt(worker0Attempt0Id);
Worker worker = LocalClusterContext.get().getWorker(worker0Attempt0Id).getWorker();
MasterClient masterClient = worker.getPSAgent().getMasterClient();
masterClient.taskIteration(task0Id.getIndex(), 1);
AMTask task0 = taskManager.getTask(task0Id);
AMTask task1 = taskManager.getTask(task1Id);
assertEquals(task0.getIteration(), 1);
assertEquals(task1.getIteration(), 0);
assertEquals(worker0Attempt0.getMinIteration(), 0);
assertEquals(worker0.getMinIteration(), 0);
assertEquals(workerGroup0.getMinIteration(), 0);
masterClient.taskIteration(task1Id.getIndex(), 1);
assertEquals(task0.getIteration(), 1);
assertEquals(task1.getIteration(), 1);
assertEquals(worker0Attempt0.getMinIteration(), 1);
assertEquals(worker0.getMinIteration(), 1);
assertEquals(workerGroup0.getMinIteration(), 1);
} catch (Exception x){
LOG.error("run testTaskIteration failed ", x);
throw x;
}
}
@Test
public void testTaskMatrixClock() throws ServiceException {
try {
LOG.info("===========================testTaskMatrixClock===============================");
AngelApplicationMaster angelAppMaster = LocalClusterContext.get().getMaster().getAppMaster();
assertTrue(angelAppMaster != null);
AMTaskManager taskManager = angelAppMaster.getAppContext().getTaskManager();
Worker worker = LocalClusterContext.get().getWorker(worker0Attempt0Id).getWorker();
PSAgentMatrixMetaManager matrixMetaManager = worker.getPSAgent().getMatrixMetaManager();
int w1Id = matrixMetaManager.getMatrixId("w1");
int w2Id = matrixMetaManager.getMatrixId("w2");
MasterClient masterClient = worker.getPSAgent().getMasterClient();
AMTask task0 = taskManager.getTask(task0Id);
AMTask task1 = taskManager.getTask(task1Id);
masterClient.updateClock(task0Id.getIndex(), w1Id, 1);
masterClient.updateClock(task0Id.getIndex(), w2Id, 1);
Int2IntOpenHashMap matrixClocks = task0.getMatrixClocks();
assertEquals(matrixClocks.size(), 2);
assertEquals(matrixClocks.get(w1Id), 1);
assertEquals(matrixClocks.get(w2Id), 1);
masterClient.updateClock(task0Id.getIndex(), w1Id, 2);
assertEquals(task0.getMatrixClock(w1Id), 2);
assertEquals(task0.getMatrixClock(w2Id), 1);
masterClient.updateClock(task1Id.getIndex(), w1Id, 1);
masterClient.updateClock(task1Id.getIndex(), w2Id, 1);
matrixClocks = task1.getMatrixClocks();
assertEquals(matrixClocks.size(), 2);
assertEquals(matrixClocks.get(w1Id), 1);
assertEquals(matrixClocks.get(w2Id), 1);
masterClient.updateClock(task1Id.getIndex(), w1Id, 2);
assertEquals(task1.getMatrixClock(w1Id), 2);
assertEquals(task1.getMatrixClock(w2Id), 1);
} catch (Exception x) {
LOG.error("run testTaskMatrixClock failed ", x);
throw x;
}
}
@AfterClass
public static void stop() throws AngelException {
try {
LOG.info("stop local cluster");
angelClient.stop();
} catch (Exception x) {
LOG.error("stop failed ", x);
throw x;
}
}
}
| 42.772321
| 100
| 0.728212
|
0c7b3392f745acf76ee389487f2c2eb08a588578
| 789
|
package com.app.qunadai.bean.base;
/**
* Created by wayne on 2017/9/5.
*/
public class BaseBean<T> {
// 接口请求返回带状态码
private String code;
// 服务器返回的提示信息
private String msg;
private String detail;
//data数据
private T content;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail;
}
public T getContent() {
return content;
}
public void setContent(T content) {
this.content = content;
}
}
| 16.4375
| 42
| 0.569075
|
b5fd6abe447747606a998e378c0dc55a1695de44
| 4,381
|
/*
* Copyright 2002-2004 Jeremias Maerki.
*
* 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.krysalis.barcode4j.impl.int2of5;
import org.krysalis.barcode4j.ChecksumMode;
import org.krysalis.barcode4j.impl.MockClassicBarcodeLogicHandler;
import org.krysalis.barcode4j.impl.int2of5.Interleaved2Of5LogicImpl;
import junit.framework.TestCase;
/**
* Test class for the Interleaved 2 of 5 implementation.
*
* @author Jeremias Maerki
* @version $Id: Interleaved2Of5Test.java,v 1.1 2009-02-19 10:14:54 jmaerki Exp $
*/
public class Interleaved2Of5Test extends TestCase {
public Interleaved2Of5Test(String name) {
super(name);
}
public void testChecksum() throws Exception {
//Check with default specification (ITF-14, EAN-14, SSC-14, DUN14 and USPS)
assertEquals('5', Interleaved2Of5LogicImpl.calcChecksum("123456789"));
assertTrue(Interleaved2Of5LogicImpl.validateChecksum("1234567895"));
assertFalse(Interleaved2Of5LogicImpl.validateChecksum("1234567896"));
//Check with German Post Identcode and Leitcode specification
assertEquals('6', Interleaved2Of5LogicImpl.calcChecksum("12345678901", 4, 9));
}
public void testLogic() throws Exception {
StringBuffer sb = new StringBuffer();
Interleaved2Of5LogicImpl logic;
String expected;
logic = new Interleaved2Of5LogicImpl(ChecksumMode.CP_AUTO, false);
logic.generateBarcodeLogic(new MockClassicBarcodeLogicHandler(sb), "12345670");
expected = "<BC><SBG:start-char:null>B1W1B1W1</SBG>"
+ "<SBG:msg-char:12>B2W1B1W2B1W1B1W1B2W2</SBG>"
+ "<SBG:msg-char:34>B2W1B2W1B1W2B1W1B1W2</SBG>"
+ "<SBG:msg-char:56>B2W1B1W2B2W2B1W1B1W1</SBG>"
+ "<SBG:msg-char:70>B1W1B1W1B1W2B2W2B2W1</SBG>"
+ "<SBG:stop-char:null>B2W1B1</SBG>"
+ "</BC>";
//System.out.println(expected);
//System.out.println(sb.toString());
assertEquals(expected, sb.toString());
sb.setLength(0);
logic = new Interleaved2Of5LogicImpl(ChecksumMode.CP_ADD, false);
logic.generateBarcodeLogic(new MockClassicBarcodeLogicHandler(sb), "12345670");
expected = "<BC><SBG:start-char:null>B1W1B1W1</SBG>"
+ "<SBG:msg-char:01>B1W2B1W1B2W1B2W1B1W2</SBG>"
+ "<SBG:msg-char:23>B1W2B2W2B1W1B1W1B2W1</SBG>"
+ "<SBG:msg-char:45>B1W2B1W1B2W2B1W1B2W1</SBG>"
+ "<SBG:msg-char:67>B1W1B2W1B2W1B1W2B1W2</SBG>"
+ "<SBG:msg-char:00>B1W1B1W1B2W2B2W2B1W1</SBG>"
+ "<SBG:stop-char:null>B2W1B1</SBG>"
+ "</BC>";
//System.out.println(expected);
//System.out.println(sb.toString());
assertEquals(expected, sb.toString());
sb.setLength(0);
logic = new Interleaved2Of5LogicImpl(ChecksumMode.CP_CHECK, false);
logic.generateBarcodeLogic(new MockClassicBarcodeLogicHandler(sb), "123456700");
//Variable expected stays the same for this test!!!!!
//System.out.println(expected);
//System.out.println(sb.toString());
assertEquals(expected, sb.toString());
sb.setLength(0);
logic = new Interleaved2Of5LogicImpl(ChecksumMode.CP_CHECK, false);
try {
logic.generateBarcodeLogic(new MockClassicBarcodeLogicHandler(sb), "123456706");
fail("Expected logic implementation to fail because wrong checksum is supplied");
} catch (IllegalArgumentException iae) {
//must fail
}
}
}
| 43.376238
| 93
| 0.625656
|
4d74c17c5ccc72b4f1745bb202fa685870ff2bd4
| 2,490
|
/*
* Copyright 2018 Felipe Joglar Santos
*
* 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.fjoglar.lyricly.data.source.local.preferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
/**
* Helper class to make simple the use of SharedPreferences.
*/
public class PreferencesRepository implements PreferencesDataSource {
private static volatile PreferencesRepository INSTANCE;
private final SharedPreferences preferences;
// Prevent direct instantiation.
private PreferencesRepository(Context context) {
preferences = PreferenceManager.getDefaultSharedPreferences(context);
}
/**
* Returns the single instance of this class, creating it if necessary.
*
* @param context Context object
*/
public static PreferencesRepository getInstance(Context context) {
if (INSTANCE == null) {
synchronized (PreferencesRepository.class) {
if (INSTANCE == null) {
INSTANCE = new PreferencesRepository(context.getApplicationContext());
}
}
}
return INSTANCE;
}
/**
* Used to force {@link #getInstance(Context)} to create a new instance next
* time it's called.
*/
public static void destroyInstance() {
INSTANCE = null;
}
@Override
public long getLastUpdatedTimeInMillis() {
return preferences.getLong(LAST_UPDATED_TIME_KEY, 0);
}
@Override
public void setLastUpdatedTimeInMillis() {
preferences.edit().putLong(LAST_UPDATED_TIME_KEY, System.currentTimeMillis()).apply();
}
@Override
public boolean hasOnBoardingBeenShown() {
return preferences.getBoolean(IS_ON_BOARDING_SHOWN_KEY, false);
}
@Override
public void setHasOnBoardingBeenShown() {
preferences.edit().putBoolean(IS_ON_BOARDING_SHOWN_KEY, true).apply();
}
}
| 30.365854
| 94
| 0.694378
|
dd5c603faded00b71583b84b6d7e58fc51cc93d3
| 3,998
|
package de.charite.compbio.jannovar.vardbs.dbsnp;
import de.charite.compbio.jannovar.vardbs.base.DBAnnotationOptions;
import de.charite.compbio.jannovar.vardbs.base.VCFHeaderExtender;
import htsjdk.variant.vcf.VCFHeader;
import htsjdk.variant.vcf.VCFHeaderLineCount;
import htsjdk.variant.vcf.VCFHeaderLineType;
import htsjdk.variant.vcf.VCFInfoHeaderLine;
/**
* Helper class for extending {@link VCFHeader}s for DBSNP annotations.
*
* @author <a href="mailto:manuel.holtgrewe@bihealth.de">Manuel Holtgrewe</a>
*/
public class DBSNPVCFHeaderExtender extends VCFHeaderExtender {
public DBSNPVCFHeaderExtender(DBAnnotationOptions options) {
super(options);
}
@Override
public String getDefaultPrefix() {
return "DBSNP_";
}
@Override
public void addHeaders(VCFHeader header, String prefix) {
addHeadersInfixes(header, prefix, "", "");
if (options.isReportOverlapping() && !options.isReportOverlappingAsMatching())
addHeadersInfixes(header, prefix, "OVL_", " (requiring no genotype match, only position overlap)");
}
public void addHeadersInfixes(VCFHeader header, String prefix, String infix, String note) {
VCFInfoHeaderLine infoDBSNPCommon = new VCFInfoHeaderLine(prefix + infix + "COMMON", VCFHeaderLineCount.A,
VCFHeaderLineType.Integer,
"Flagged as common in dbSNP" + note + ". Original description: RS is a common SNP. A common SNP is "
+ "one that has at least one 1000Genomes population with a minor allele "
+ "of frequency >= 1% and for which 2 or more founders contribute to that minor allele "
+ "frequency.");
header.addMetaDataLine(infoDBSNPCommon);
VCFInfoHeaderLine infoDBSNPFreqs = new VCFInfoHeaderLine(prefix + infix + "CAF", VCFHeaderLineCount.R,
VCFHeaderLineType.Float,
"Allele frequencies from dbSNP" + note + ". Original description: An ordered, comma delimited list "
+ "of allele frequencies based on 1000Genomes, starting with the reference allele "
+ "followed by alternate alleles as ordered in the ALT column. Where a 1000Genomes "
+ "alternate allele is not in the dbSNPs alternate allele set, the allele is added "
+ "to the ALT column. The minor allele is the second largest value in the list, "
+ "and was previuosly reported in VCF as the GMAF. This is the GMAF reported on "
+ "the RefSNP and EntrezSNP pages and VariationReporter");
header.addMetaDataLine(infoDBSNPFreqs);
VCFInfoHeaderLine infoG5 = new VCFInfoHeaderLine(prefix + infix + "G5", VCFHeaderLineCount.A,
VCFHeaderLineType.Integer, "Allele frequency >5% in all populations from dbSNP (yes: 1, no: 0)" + note
+ ". Original description: >5% minor allele frequency in 1+ populations");
header.addMetaDataLine(infoG5);
VCFInfoHeaderLine infoG5A = new VCFInfoHeaderLine(prefix + infix + "G5A", VCFHeaderLineCount.A,
VCFHeaderLineType.Integer, "Allele frequency >5% in all populations from dbSNP (yes: 1, no: 0)" + note
+ ". Original description: >5% minor allele frequency in each and all populations");
header.addMetaDataLine(infoG5A);
if ("OVL_".equals(infix)) {
VCFInfoHeaderLine overlappingRS = new VCFInfoHeaderLine(prefix + "OVL_IDS", VCFHeaderLineCount.A,
VCFHeaderLineType.String, "dbSNP cluster identifiers with overlapping alternative positions, "
+ "not necessarily matching alleles, for each alternative allele, separated '|'");
header.addMetaDataLine(overlappingRS);
} else {
VCFInfoHeaderLine matchingRS = new VCFInfoHeaderLine(prefix + "IDS", VCFHeaderLineCount.A,
VCFHeaderLineType.String,
"dbSNP cluster identifiers with matching alternative positions and alleles, for each "
+ "alternative alleles, separated by '|'");
header.addMetaDataLine(matchingRS);
}
VCFInfoHeaderLine infoOrigin = new VCFInfoHeaderLine(prefix + infix + "SAO", VCFHeaderLineCount.A,
VCFHeaderLineType.String, "Variant allele origin (UNSPECIFIED, GERMLINE, SOMATIC, BOTH)");
header.addMetaDataLine(infoOrigin);
}
}
| 48.756098
| 108
| 0.748374
|
d80e9478be7da402033954351b23d219406b1270
| 2,180
|
package io.github.jspinak.brobot.actions.methods.sikuliWrappers.find;
import io.github.jspinak.brobot.actions.BrobotSettings;
import io.github.jspinak.brobot.actions.actionOptions.ActionOptions;
import io.github.jspinak.brobot.datatypes.primitives.image.Image;
import io.github.jspinak.brobot.datatypes.primitives.image.ImagePatterns;
import io.github.jspinak.brobot.datatypes.primitives.match.Matches;
import io.github.jspinak.brobot.datatypes.primitives.region.Region;
import io.github.jspinak.brobot.datatypes.state.stateObject.stateImageObject.StateImageObject;
import io.github.jspinak.brobot.mock.Mock;
import org.sikuli.script.Pattern;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* Finds all Matches for all Patterns in the Brobot Image.
* Used by Find.ALL and Find.BEST.
* The Find.BEST option finds all Matches and picks the best Match from these Matches.
*/
@Component
public class FindAllPatterns implements FindPatternInterface {
private final ImagePatterns imagePatterns;
private final Mock mock;
private final FindPattern findPattern;
public FindAllPatterns(ImagePatterns imagePatterns, Mock mock, FindPattern findPattern) {
this.imagePatterns = imagePatterns;
this.mock = mock;
this.findPattern = findPattern;
}
@Override
public Matches find(Region region, StateImageObject stateImageObject, Image image,
ActionOptions actionOptions) {
if (BrobotSettings.mock && BrobotSettings.screenshot.isEmpty())
return mock.getMatches(stateImageObject, region, actionOptions);
List<Pattern> patterns = imagePatterns.getPatterns(image, actionOptions);
Matches matches = new Matches();
for (Pattern pattern : patterns) {
matches.addAll(findPattern.findAll(region, pattern, stateImageObject, actionOptions));
}
/*
* Store Snapshots before adjusting the Match. This makes it easier to reuse.
* A failed operation will be stored here without a Match.
*/
matches.getDanglingSnapshots().addAllMatches(actionOptions, matches);
return matches;
}
}
| 41.132075
| 98
| 0.744954
|
0142105e596c595b62d69ee4ff91d72aa373cdea
| 1,763
|
package week9;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.EnumSet;
public class WritableFileChannelExample {
public static void main(String[] args) {
Path file = Paths.get(System.getProperty("user.dir")).resolve("randomnums.txt");
System.out.println("Will write file to: " + file);
// this is just like an array that you don't need to size
java.util.List<String> numbers = new ArrayList<>();
for (int i = 0; i < 100; i++) {
// casting to string from int, casting to int from double!
numbers.add("" + (int)Math.floor((Math.random() * 1000*1000) + 1000*1000));
}
// temporary buffer, for each iteration.
ByteBuffer buf = null;
try {
/***
* Why use a fileChannel over other methods?
*
* https://dzone.com/articles/java-nio-vs-io
*
* NIO vs IO
*
* NIO uses buffers
* IO uses streams
*
* Read about the differences, however you may not understand them until you understand what a "Thread" is.
*
*
* FileChannels are NIO.
*
* InputStream / OutputStream ar IO.
*
*
* Streams are byte by byte, buffers work in blocks of bytes.
*
*
*/
// the file channel
WritableByteChannel channel =
Files.newByteChannel(file, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE));
for (String num : numbers) {
buf = ByteBuffer.wrap((num + "\n").getBytes());
channel.write(buf);
}
System.out.println("File written.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 24.830986
| 110
| 0.655701
|
e311face11aa2733e1cd7519649e623e08575f5a
| 2,529
|
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.digitaltwins.v2020_12_01;
import rx.Observable;
import com.microsoft.azure.management.digitaltwins.v2020_12_01.DigitalTwinsDescription;
import rx.Completable;
/**
* Type representing DigitalTwins.
*/
public interface DigitalTwins {
/**
* Begins definition for a new DigitalTwinsInstance resource.
* @param name resource name.
* @return the first stage of the new DigitalTwinsInstance definition.
*/
DigitalTwinsDescription.DefinitionStages.Blank defineDigitalTwinsInstance(String name);
/**
* Get DigitalTwinsInstances resource.
*
* @param resourceGroupName resource group name
* @param name resource name
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<DigitalTwinsDescription> getByResourceGroupAsync(String resourceGroupName, String name);
/**
* Get all the DigitalTwinsInstances in a resource group.
*
* @param resourceGroupName resource group name
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<DigitalTwinsDescription> listByResourceGroupAsync(String resourceGroupName);
/**
* Get all the DigitalTwinsInstances in a subscription.
*
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<DigitalTwinsDescription> listAsync();
/**
* Delete a DigitalTwinsInstance.
*
* @param resourceGroupName resource group name
* @param name resource name
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Completable deleteAsync(String resourceGroupName, String name);
/**
* Check if a DigitalTwinsInstance name is available.
*
* @param location Location of DigitalTwinsInstance.
* @param name Resource name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<CheckNameResult> checkNameAvailabilityAsync(String location, String name);
}
| 34.175676
| 103
| 0.730724
|
4039fd285cb02c7c181ba2496c4b26d5af9f33ef
| 229
|
package DiscUtils.Nfs;
import java.io.Closeable;
public interface IRpcClient extends Closeable {
RpcCredentials getCredentials();
IRpcTransport getTransport(int program, int version);
int nextTransactionId();
}
| 16.357143
| 57
| 0.759825
|
c480fba961fc177dbc6f2864b31b5bf90f3516ba
| 91
|
package Chatr.Helper.Enums;
public enum MessageType {
TEXT, GIF, IMAGE, EMOJI, STICKER
}
| 15.166667
| 33
| 0.747253
|
ed33c20ec5567b28819236dbbe9a7fff44807d9e
| 8,395
|
package org.beifengtz.jvmm.core.conf;
import com.google.gson.Gson;
import org.beifengtz.jvmm.common.util.StringUtil;
import java.util.Map;
/**
* <p>
* Description: TODO
* </p>
* <p>
* Created in 16:48 2021/5/22
*
* @author beifengtz
*/
public final class Configuration {
private final String name;
private final int port;
private final boolean autoIncrease;
private final int httpMaxChunkSize;
private final boolean securityEnable;
private final String securityAccount;
private final String securityPassword;
private final String logLevel;
private final boolean logUseJvmm;
private final int workThread;
/**
* 是否是从agent加载
*/
private final boolean fromAgent;
private Configuration(Builder builder) {
this.name = builder.name;
this.port = builder.port;
this.autoIncrease = builder.autoIncrease;
this.httpMaxChunkSize = builder.httpMaxChunkSize;
this.securityEnable = builder.securityEnable;
this.securityAccount = builder.securityAccount;
this.securityPassword = builder.securityPassword;
this.logLevel = builder.logLevel;
this.logUseJvmm = builder.logUseJvmm;
this.workThread = builder.workThread;
this.fromAgent = builder.fromAgent;
}
public static Builder newBuilder() {
return new Builder();
}
public static Configuration defaultInstance() {
return new Builder().build();
}
@Override
public String toString() {
return new Gson().toJson(this);
}
public String argFormat() {
StringBuilder sb = new StringBuilder();
sb.append("name=").append(name).append(";");
sb.append("port.bind=").append(port).append(";");
sb.append("port.autoIncrease=").append(autoIncrease).append(";");
sb.append("http.maxChunkSize=").append(httpMaxChunkSize).append(";");
sb.append("security.account=").append(securityAccount).append(";");
sb.append("security.password=").append(securityPassword).append(";");
sb.append("security.enable=").append(securityEnable).append(";");
sb.append("log.level=").append(logLevel).append(";");
sb.append("log.useJvmm=").append(logUseJvmm).append(";");
sb.append("workThread=").append(workThread).append(";");
sb.append("fromAgent=").append(fromAgent).append(";");
return sb.toString();
}
public static class Builder {
private String name = "jvmm_server";
private int port = 5010;
private boolean autoIncrease = true;
private int httpMaxChunkSize = 52428800; // 50MB
private boolean securityEnable = false;
private String securityAccount = "";
private String securityPassword = "";
private String logLevel = "info";
private boolean logUseJvmm = false;
private int workThread = 1;
private boolean fromAgent = false;
public Configuration build() {
return new Configuration(this);
}
public int getPort() {
return port;
}
public Builder setPort(int port) {
this.port = port;
return this;
}
public boolean isAutoIncrease() {
return autoIncrease;
}
public Builder setAutoIncrease(boolean autoIncrease) {
this.autoIncrease = autoIncrease;
return this;
}
public String getName() {
return name;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public int getHttpMaxChunkSize() {
return httpMaxChunkSize;
}
public Builder setHttpMaxChunkSize(int httpMaxChunkSize) {
this.httpMaxChunkSize = httpMaxChunkSize;
return this;
}
public boolean isSecurityEnable() {
return securityEnable;
}
public Builder setSecurityEnable(boolean securityEnable) {
this.securityEnable = securityEnable;
return this;
}
public String getSecurityAccount() {
return securityAccount;
}
public Builder setSecurityAccount(String securityAccount) {
this.securityAccount = securityAccount;
return this;
}
public String getSecurityPassword() {
return securityPassword;
}
public Builder setSecurityPassword(String securityPassword) {
this.securityPassword = securityPassword;
return this;
}
public String getLogLevel() {
return logLevel;
}
public Builder setLogLevel(String logLevel) {
this.logLevel = logLevel;
return this;
}
public int getWorkThread() {
return workThread;
}
public Builder setWorkThread(int workThread) {
this.workThread = workThread;
return this;
}
public boolean isFromAgent() {
return fromAgent;
}
public void setFromAgent(boolean fromAgent) {
this.fromAgent = fromAgent;
}
public boolean isLogUseJvmm() {
return logUseJvmm;
}
public Builder setLogUseJvmm(boolean logUseJvmm) {
this.logUseJvmm = logUseJvmm;
return this;
}
public void mergeFromProperties(Map<String, String> argMap) {
String name = argMap.get("name");
if (StringUtil.nonEmpty(name)) {
setName(name);
}
String portBind = argMap.get("port.bind");
if (StringUtil.nonEmpty(portBind)) {
setPort(Integer.parseInt(portBind));
}
String portAutoIncrease = argMap.get("port.autoIncrease");
if (StringUtil.nonEmpty(portAutoIncrease)) {
setAutoIncrease(Boolean.parseBoolean(portAutoIncrease));
}
String httpMaxChunkSize = argMap.get("http.maxChunkSize");
if (StringUtil.nonEmpty(httpMaxChunkSize)) {
setHttpMaxChunkSize(Integer.parseInt(httpMaxChunkSize));
}
String securityEnable = argMap.get("security.enable");
if (StringUtil.nonEmpty(securityEnable)) {
setSecurityEnable(Boolean.parseBoolean(securityEnable));
}
String securityAccount = argMap.get("security.account");
if (StringUtil.nonEmpty(securityAccount)) {
setSecurityAccount(securityAccount);
}
String securityPassword = argMap.get("security.password");
if (StringUtil.nonEmpty(securityPassword)) {
setSecurityPassword(securityPassword);
}
String logLevel = argMap.get("log.level");
if (StringUtil.nonEmpty(logLevel)) {
setLogLevel(logLevel);
}
String logUseJvmm = argMap.get("log.useJvmm");
if (StringUtil.nonEmpty(logUseJvmm)) {
setLogUseJvmm(Boolean.parseBoolean(logUseJvmm));
}
String workThread = argMap.get("workThread");
if (StringUtil.nonEmpty(workThread)) {
setWorkThread(Math.max(Integer.parseInt(workThread), 1));
}
String fromAgent = argMap.get("fromAgent");
if (StringUtil.nonEmpty(fromAgent)) {
setFromAgent(Boolean.parseBoolean(fromAgent));
}
}
}
public int getPort() {
return port;
}
public boolean isAutoIncrease() {
return autoIncrease;
}
public String getName() {
return name;
}
public int getHttpMaxChunkSize() {
return httpMaxChunkSize;
}
public boolean isSecurityEnable() {
return securityEnable;
}
public String getSecurityAccount() {
return securityAccount;
}
public String getSecurityPassword() {
return securityPassword;
}
public String getLogLevel() {
return logLevel;
}
public int getWorkThread() {
return workThread;
}
public boolean isFromAgent() {
return fromAgent;
}
public boolean isLogUseJvmm() {
return logUseJvmm;
}
}
| 28.076923
| 77
| 0.591185
|
fb00c977977e93cb17769ff64e408e947b4a7142
| 1,692
|
package com.smartdevicelink.proxy.rpc;
import android.support.annotation.NonNull;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.proxy.RPCRequest;
import com.smartdevicelink.proxy.rpc.enums.ModuleType;
import java.util.Hashtable;
public class ReleaseInteriorVehicleDataModule extends RPCRequest {
public static final String KEY_MODULE_TYPE = "moduleType";
public static final String KEY_MODULE_ID = "moduleId";
public ReleaseInteriorVehicleDataModule() {
super(FunctionID.RELEASE_INTERIOR_VEHICLE_MODULE.toString());
}
public ReleaseInteriorVehicleDataModule(Hashtable<String, Object> hash) {
super(hash);
}
/**
* @param moduleType Sets the Module Type for this class
*/
public ReleaseInteriorVehicleDataModule(@NonNull ModuleType moduleType){
this();
setModuleType(moduleType);
}
/**
* Sets the Module Type for this class
* @param type the Module Type to be set
*/
public void setModuleType(@NonNull ModuleType type) {
setParameters(KEY_MODULE_TYPE, type);
}
/**
* Gets the Module Type of this class
* @return the Module Type of this class
*/
public ModuleType getModuleType() {
return (ModuleType) getObject(ModuleType.class, KEY_MODULE_TYPE);
}
/**
* Sets the Module Ids for this class
* @param id the ids to be set
*/
public void setModuleId(String id) {
setParameters(KEY_MODULE_ID, id);
}
/**
* Gets the Module Id of this class
* @return the Module Ids
*/
public String getModuleId() {
return getString(KEY_MODULE_ID);
}
}
| 26.857143
| 77
| 0.682033
|
7e17ef60ff7c7f04f65f532e65e972f58c019d7d
| 6,897
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dadoco.admin.model;
import com.dadoco.common.annotations.GreaterZero;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* @author dfcalderio
*/
@Entity
@Table(name = "contribucion_especial")
@NamedQueries({
@NamedQuery(name = "ContribucionEspecial.findAll", query = "SELECT c FROM ContribucionEspecial c WHERE c.estado = 0 ORDER BY c.id")
, @NamedQuery(name = "ContribucionEspecial.findById", query = "SELECT c FROM ContribucionEspecial c WHERE c.id = :id")
, @NamedQuery(name = "ContribucionEspecial.findByNombre", query = "SELECT c FROM ContribucionEspecial c WHERE c.nombre = :nombre")
, @NamedQuery(name = "ContribucionEspecial.findByEstado", query = "SELECT c FROM ContribucionEspecial c WHERE c.estado = :estado")
, @NamedQuery(name = "ContribucionEspecial.findByPresupuesto", query = "SELECT c FROM ContribucionEspecial c WHERE c.presupuesto = :presupuesto")
, @NamedQuery(name = "ContribucionEspecial.findByCosto", query = "SELECT c FROM ContribucionEspecial c WHERE c.costo = :costo")
, @NamedQuery(name = "ContribucionEspecial.findByFechaCreacion", query = "SELECT c FROM ContribucionEspecial c WHERE c.fechaCreacion = :fechaCreacion")
, @NamedQuery(name = "ContribucionEspecial.findByFechaTerminacion", query = "SELECT c FROM ContribucionEspecial c WHERE c.fechaTerminacion = :fechaTerminacion")
, @NamedQuery(name = "ContribucionEspecial.findByFechaInicioCobro", query = "SELECT c FROM ContribucionEspecial c WHERE c.fechaInicioCobro = :fechaInicioCobro")
, @NamedQuery(name = "ContribucionEspecial.findByFechaFinalCobro", query = "SELECT c FROM ContribucionEspecial c WHERE c.fechaFinalCobro = :fechaFinalCobro")
, @NamedQuery(name = "ContribucionEspecial.findByDescripcion", query = "SELECT c FROM ContribucionEspecial c WHERE c.descripcion = :descripcion")
, @NamedQuery(name = "ContribucionEspecial.findByObservaciones", query = "SELECT c FROM ContribucionEspecial c WHERE c.observaciones = :observaciones")})
public class ContribucionEspecial implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 200)
@Column(name = "nombre")
private String nombre;
@Basic(optional = false)
@NotNull
@Column(name = "estado")
private short estado;
@Basic(optional = false)
@NotNull
@GreaterZero
@Column(name = "presupuesto")
private Double presupuesto;
@Column(name = "costo")
private double costo;
@Column(name = "fecha_creacion")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaCreacion;
@Column(name = "fecha_terminacion")
@Temporal(TemporalType.TIMESTAMP)
private Date fechaTerminacion;
@Column(name = "fecha_inicio_cobro")
@Temporal(TemporalType.DATE)
@Basic(optional = false)
@NotNull
private Date fechaInicioCobro;
@Column(name = "fecha_final_cobro")
@Temporal(TemporalType.DATE)
@Basic(optional = false)
@NotNull
private Date fechaFinalCobro;
@Size(max = 2147483647)
@Column(name = "descripcion")
private String descripcion;
@Size(max = 2147483647)
@Column(name = "observaciones")
private String observaciones;
public ContribucionEspecial() {
}
public ContribucionEspecial(Integer id) {
this.id = id;
}
public ContribucionEspecial(Integer id, String nombre, short estado) {
this.id = id;
this.nombre = nombre;
this.estado = estado;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public short getEstado() {
return estado;
}
public void setEstado(short estado) {
this.estado = estado;
}
public Double getPresupuesto() {
return presupuesto;
}
public void setPresupuesto(Double presupuesto) {
this.presupuesto = presupuesto;
}
public double getCosto() {
return costo;
}
public void setCosto(double costo) {
this.costo = costo;
}
public Date getFechaCreacion() {
return fechaCreacion;
}
public void setFechaCreacion(Date fechaCreacion) {
this.fechaCreacion = fechaCreacion;
}
public Date getFechaTerminacion() {
return fechaTerminacion;
}
public void setFechaTerminacion(Date fechaTerminacion) {
this.fechaTerminacion = fechaTerminacion;
}
public Date getFechaInicioCobro() {
return fechaInicioCobro;
}
public void setFechaInicioCobro(Date fechaInicioCobro) {
this.fechaInicioCobro = fechaInicioCobro;
}
public Date getFechaFinalCobro() {
return fechaFinalCobro;
}
public void setFechaFinalCobro(Date fechaFinalCobro) {
this.fechaFinalCobro = fechaFinalCobro;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public String getObservaciones() {
return observaciones;
}
public void setObservaciones(String observaciones) {
this.observaciones = observaciones;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof ContribucionEspecial)) {
return false;
}
ContribucionEspecial other = (ContribucionEspecial) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.dadoco.ren.model.ContribucionEspecial[ id=" + id + " ]";
}
}
| 31.637615
| 164
| 0.68624
|
3a251d56e5905eff49402bfc8f4bcd857594586d
| 1,839
|
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (almaslvl@gmail.com).
* See LICENSE for details.
*/
package s03entities;
import com.almasb.fxgl.app.FXGL;
import com.almasb.fxgl.app.GameApplication;
import com.almasb.fxgl.entity.component.Component;
import com.almasb.fxgl.entity.Entities;
import com.almasb.fxgl.settings.GameSettings;
import com.almasb.fxgl.time.LocalTimer;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;
/**
* This samples shows how to create timer based controls for entities.
*
* @author Almas Baimagambetov (AlmasB) (almaslvl@gmail.com)
*/
public class TimerControlSample extends GameApplication {
@Override
protected void initSettings(GameSettings settings) {
settings.setWidth(800);
settings.setHeight(600);
settings.setTitle("TimerControlSample");
settings.setVersion("0.2");
}
@Override
protected void initGame() {
Entities.builder()
.at(100, 100)
.viewFromNode(new Rectangle(40, 40))
.with(new LiftControl())
.buildAndAttach(getGameWorld());
}
private class LiftControl extends Component {
private LocalTimer timer = FXGL.newLocalTimer();
private boolean goingUp = false;
@Override
public void onUpdate(double tpf) {
// 1. check if timer elapsed
if (timer.elapsed(Duration.seconds(2))) {
// 2. perform logic
goingUp = !goingUp;
// 3. capture time so that timer is reset
timer.capture();
}
double speed = tpf * 60;
entity.translateY(goingUp ? -speed : speed);
}
}
public static void main(String[] args) {
launch(args);
}
}
| 25.191781
| 70
| 0.621533
|
2c74c496d42d97769eb1885c475ef53351ac758f
| 910
|
package com.autohome.frostmourne.spi.starter.api;
import java.util.List;
import com.autohome.frostmourne.core.contract.Protocol;
import com.autohome.frostmourne.spi.starter.model.AlarmMessage;
import com.autohome.frostmourne.spi.starter.model.MessageResult;
import com.autohome.frostmourne.spi.starter.model.Team;
import com.autohome.frostmourne.spi.starter.model.AccountInfo;
import feign.Headers;
import feign.Param;
import feign.RequestLine;
public interface IFrostmourneSpiApi {
@RequestLine("POST /message/send?_appId={_appId}")
@Headers("Content-Type: application/json")
Protocol<List<MessageResult>> send(AlarmMessage alarmMessage, @Param("_appId") String _appId);
@RequestLine("GET /shorten/link?_appId={_appId}&longUrl={longUrl}")
@Headers("Content-Type: application/json")
Protocol<String> shortenLink(@Param("_appId") String _appId, @Param("longUrl") String longUrl);
}
| 37.916667
| 99
| 0.783516
|
9cfb12c7c6f20cdf638cf1455c7259fc755c0c9d
| 849
|
package com.itzmeds.adfs.client.request;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.Root;
@Root(name = "AppliesTo")
public class AppliesTo {
@Element(name = "a:EndpointReference", required = true)
protected EndpointReference endpointReference;
/**
* Gets the value of the endpointReference property.
*
* @return
* possible object is
* {@link EndpointReference }
*
*/
public EndpointReference getEndpointReference() {
return endpointReference;
}
/**
* Sets the value of the endpointReference property.
*
* @param value
* allowed object is
* {@link EndpointReference }
*
*/
public void setEndpointReference(EndpointReference value) {
this.endpointReference = value;
}
}
| 22.342105
| 63
| 0.632509
|
526f99cf9b3df83c4abea8573d6b409d5ef6dbac
| 1,946
|
package algorithms.searching_sorting.model;
public class SortGrade {
public Grade[] mergeSort(Grade[] grades, int begin, int end) {
order(grades, begin, end);
return grades;
}
public void order(Grade[] grades, int begin, int end) {
int numberOfElements = end - begin;
if (numberOfElements > 1){
int middle = (begin + end) / 2;
//System.out.println(begin+" "+middle+" "+end); // Validate orders/mergers
order(grades, begin, middle); // order first middle (recursive)
order(grades, middle, end); // order second middle (recursive)
merge(grades, begin, middle, end); // merge two parts already ordered
}
}
public void merge(Grade[] grades, int begin, int middle, int end) {
Grade[] result = new Grade[end - begin];
int current1 = begin;
int current2 = middle; // from middle
int currentPointer = 0;
while (current1 < middle && current2 < end) {
Grade grade1 = grades[current1];
Grade grade2 = grades[current2];
if (grade1.getValue() < grade2.getValue()){
result[currentPointer] = grade1;
current1++;
} else {
result[currentPointer] = grade2;
current2++;
}
currentPointer++;
}
// first part of the array chosen to the middle
while (current1 < middle){
result[currentPointer] = grades[current1];
currentPointer++;
current1++;
}
// the middle to the end
while (current2 < end){
result[currentPointer] = grades[current2];
currentPointer++;
current2++;
}
// rest of itens for add
for (int count = 0; count < currentPointer; count++){
grades[begin + count] = result[count];
}
}
}
| 30.888889
| 86
| 0.538541
|
15dd19f7718137dd3a2a127e71c2aa7f09e46368
| 1,896
|
package com.example.swagger.apigateway.impl;
import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.cloudapi.model.v20160714.CreateApiGroupRequest;
import com.aliyuncs.cloudapi.model.v20160714.CreateApiGroupResponse;
import com.aliyuncs.cloudapi.model.v20160714.ImportSwaggerRequest;
import com.aliyuncs.cloudapi.model.v20160714.ImportSwaggerResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.example.swagger.apigateway.ApiGateway;
/**
* @author lenny
* @since 2020/4/24 5:18 PM
*/
public class ApiGatewayImpl implements ApiGateway {
private IAcsClient client;
public ApiGatewayImpl() {
DefaultProfile profile = DefaultProfile.getProfile(
"cn-hangzhou",
"<<您的阿里云 key id>>",
"<<您的阿里云 key secret>>");
client = new DefaultAcsClient(profile);
}
@Override
public String createGroup(String groupName) throws ClientException {
CreateApiGroupRequest request = new CreateApiGroupRequest();
request.setGroupName(groupName);
CreateApiGroupResponse response = client.getAcsResponse(request);
System.out.println(">> GroupID << === >> " + response.getGroupId() + " <<");
return response.getGroupId();
}
@Override
public void importSwagger(String groupId, String swaggerData, String globalCondition) throws ClientException {
ImportSwaggerRequest request = new ImportSwaggerRequest();
request.setGroupId(groupId);
request.setDataFormat("json");
request.setData(swaggerData);
request.setGlobalCondition(globalCondition);
request.setbOverwrite(true);
ImportSwaggerResponse response = client.getAcsResponse(request);
System.out.println(JSON.toJSONString(response));
}
}
| 36.461538
| 114
| 0.723101
|
d4bc523ec872b16bf72769f7d855f93c59d9ba9e
| 318
|
package com.caucho.hessian.io;
public abstract class AbstractSerializerFactory {
public AbstractSerializerFactory() {
}
public abstract Serializer getSerializer(Class var1) throws HessianProtocolException;
public abstract Deserializer getDeserializer(Class var1) throws HessianProtocolException;
}
| 26.5
| 93
| 0.805031
|
56c6a01512531a08891d5939e6f2d67eec8077fc
| 4,839
|
package jc.sudoku.solver.logical.strategies;
import static jc.sudoku.view.SudokuViewConsts.*;
import static jc.sudoku.puzzle.Constraint.UnitType.*;
import static jc.sudoku.solver.logical.hinting.HintRefType.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jc.sudoku.solver.logical.Result;
import jc.sudoku.solver.logical.Strategy;
import jc.sudoku.solver.logical.hinting.HintBuilder;
import jc.sudoku.solver.logical.streams.StreamUtil;
import jc.sudoku.puzzle.Constraint;
import jc.sudoku.puzzle.Puzzle;
import jc.sudoku.puzzle.action.Action;
import jc.sudoku.puzzle.action.impl.CandidateRemovedAction;
import jc.sudoku.puzzle.Hit;
// This strategy looks for locked/hidden pairs or triples - units that have only
// 2 or 3 remaining possible cells for a candidate. For all other units that also
// contain both/all these cells, the candidate can be removed from the other cells
// in that unit.
//
// If the first unit is a row or a column, then the second unit must be a box and
// this is called box/line reduction. If the first unit is a box, then this is
// called a pointing pair/triple.
//
// In terms of the set cover representation, this is c1, c2 distinct columns such
// that c1 is a strict subset of c2, then rows in c2 - c1 can be removed. Selecting
// any of these rows would not cover c1, and would remove all possible rows that
// could cover it.
//
public class LockedSetsStrategy implements Strategy {
private static Logger LOG = LoggerFactory.getLogger(LockedSetsStrategy.class);
@Override
public Optional<Result> findResult(Puzzle puzzle) {
LOG.info("Trying LockedSetsStrategy");
for (Constraint c1 = puzzle.getRootConstraint().getNext();
c1 != puzzle.getRootConstraint();
c1 = c1.getNext()) {
for (Constraint c2 = c1.getNext();
c2 != puzzle.getRootConstraint();
c2 = c2.getNext()) {
// one constraint's hits must be a strict subset of the other's
if (c1.getLength() == c2.getLength()) continue;
// set up cMin to be the smaller constraint, cMax the larger
Constraint cMin, cMax;
if (c1.getLength() > c2.getLength()) {
cMin = c2; cMax = c1;
} else {
cMin = c1; cMax = c2;
}
if (cMin.isStrictSubsetOf(cMax)) {
LOG.info("Found locked set in constraints {} and {}",
cMin.getName(), cMax.getName());
List<Hit> base = StreamUtil.collectConstraintHits(cMin);
List<Hit> diff = cMax.minus(cMin);
HintBuilder hints = new HintBuilder();
List<Action> actions = new ArrayList<>();
String ruleType; // just for logging
if (cMin.getType() == ROW || cMin.getType() == COLUMN) {
hints.addText("There is a Box/Line Reduction ...").newHint();
ruleType = "Box/line reduction";
}
else {
hints.addText(String.format("There is a Pointing %s ...",
cMin.getLength() == 2 ? "Pair"
: (cMin.getLength() == 3 ? "Triple"
: Integer.toString(cMin.getLength()) + "-tuple"))).newHint();
ruleType = String.format("Pointing %s",
cMin.getLength() == 2 ? "Pair"
: (cMin.getLength() == 3 ? "Triple"
: Integer.toString(cMin.getLength()) + "-tuple"));
}
hints.addText("Check out the cells ")
.addHintRefs(CELL_NAME, base, HIGHLIGHT_GREEN)
.addText(" ...")
.newHint()
.addText("Cells ")
.addHintRefs(CELL_NAME, base, HIGHLIGHT_GREEN)
.addText(String.format(" are the only possibilities for a %d in ",
base.get(0).getCandidate().getDigit()))
.addHintRef(UNIT_TYPE_AND_NAME, base.get(0), HIGHLIGHT_GREEN)
.addText(String.format(". They %s occur in ",
cMin.getLength() == 2 ? "both" : "all"))
.addHintRef(UNIT_TYPE_AND_NAME, diff.get(0), HIGHLIGHT_YELLOW)
.addText(String.format(", so any other candidates %d in ",
base.get(0).getCandidate().getDigit()))
.addHintRef(UNIT_TYPE_AND_NAME, diff.get(0), HIGHLIGHT_YELLOW)
.addText(", namely ")
.addHintRefs(CANDIDATE_NAME, diff, HIGHLIGHT_YELLOW)
.addText(" can be removed.");
// setup the actions
for (Hit h : diff) {
String name = String.format(
"%s of candidate %d in %s %s removed from %s %s",
ruleType,
h.getCandidate().getDigit(),
cMin.getType().getName(),
cMin.getUnitName(),
cMax.getType().getName(),
cMax.getUnitName()
);
actions.add(new CandidateRemovedAction(puzzle, h, name));
}
return Optional.of(new Result(hints.getHints(), hints.getMarkups(), actions));
}
}
}
return Optional.empty();
}
}
| 38.404762
| 84
| 0.640835
|
911c6c77c88144e631487239879f57f00089c024
| 12,455
|
package com.mopchik.mopchik;
import android.app.Activity;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import com.dropbox.core.android.Auth;
import com.mopchik.mopchik.MusicService.MusicBinder;
import android.widget.MediaController.MediaPlayerControl;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MusicFragment extends Fragment implements View.OnClickListener/*MediaPlayerControl*/{
private ArrayList<Song> songList;
private ListView songView;
public View view;
public Activity activity;
public Context context;
RelativeLayout rel;
LayoutInflater inflater;
public static MusicService musicSrv;
public static Intent playIntent;
private boolean musicBound=false;
SongAdapter songAdt;
private boolean playbackPaused = false;
ImageButton play;
ImageButton pause;
TextView name;
TextView author;
View view1;
RelativeLayout activity_music;
public void onAttach(Context context) {
super.onAttach(context);
Log.e("onClick","onAttach");
this.context = context;
Model.instance().setContext(context);
if (context instanceof Activity){
activity=(Activity) context;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflater=inflater;
view = inflater.inflate(R.layout.activity_music, container, false);
activity_music = (RelativeLayout)view.findViewById(R.id.activity_music);
Model.instance().setRel(activity_music);
view1 = inflater.inflate(R.layout.rel,activity_music,false);
Model.instance().setView(view1);
name = (TextView)view1.findViewById(R.id.name);
author = (TextView)view1.findViewById(R.id.author);
Model.instance().setTextName(name);
Model.instance().setTextAuthor(author);
pause = (ImageButton)view1.findViewById(R.id.pause);
play = (ImageButton)view1.findViewById(R.id.play);
if(Model.instance().getPlayed()){
RelativeLayout.LayoutParams lp= (RelativeLayout.LayoutParams) view1.getLayoutParams();
lp.bottomMargin=0;
name.setText(Model.instance().getName());
author.setText(Model.instance().getAuthor());
pause.setOnClickListener(MusicFragment.this);
play.setOnClickListener(MusicFragment.this);
activity_music.addView(view1);
Model.instance().setAdded(view1);
}
//rel=(RelativeLayout)view.findViewById(R.id.rel);
//if(musicSrv==null) rel.setVisibility(View.GONE);
/*name=(TextView)view.findViewById(R.id.name);
author=(TextView)view.findViewById(R.id.author);
play = (ImageButton)view.findViewById(R.id.play);
pause=(ImageButton)view.findViewById(R.id.pause);
play.setVisibility(View.GONE);
play.setOnClickListener(this);
pause.setOnClickListener(this);*/
//ctr = new Controller(activity);
/*songView = (ListView)view.findViewById(R.id.song_list);
songList = new ArrayList<Song>();*/
init();
getSongList(songList);
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
Model.instance().setSongList(songList);
songAdt = new SongAdapter(context, songList, songView);
songView.setAdapter(songAdt);
//setController();
return view;
}
private void init() {
songList = new ArrayList<>();
songView = (ListView) view.findViewById(R.id.song_list);
// Sets each song with a functionality.
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Sets the respective song in the Service, and then plays it.
//name.setText(songList.get(position).getTitle());
//author.setText(songList.get(position).getArtist());
//rel.setVisibility(View.VISIBLE);
//MainActivity m = new MainActivity();
//m.setRelVisible();
if (position != musicSrv.getNumber()) {
if (!Model.instance().getPlayed()) {
view1 = inflater.inflate(R.layout.rel, activity_music, false);
RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) view1.getLayoutParams();
lp.bottomMargin = 0;
activity_music.addView(view1);
Model.instance().setAdded(view1);
Model.instance().setPlayed(true);
}
name = (TextView) view1.findViewById(R.id.name);
author = (TextView) view1.findViewById(R.id.author);
pause = (ImageButton) view1.findViewById(R.id.pause);
play = (ImageButton) view1.findViewById(R.id.play);
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Model.instance().setPause(false);
name.setText(songList.get(position).getTitle());
author.setText(songList.get(position).getArtist());
pause.setOnClickListener(MusicFragment.this);
play.setOnClickListener(MusicFragment.this);
Model.instance().setName(songList.get(position).getTitle());
Model.instance().setAuthor(songList.get(position).getArtist());
musicSrv.setSong(position);
musicSrv.playSong();
// Sets the flag to false for the controller's duration and position purposes.
if (playbackPaused) playbackPaused = false;
}else{
Intent intent = new Intent(context,ControllerActivity.class);
startActivity(intent);
}
}
});
}
public void getSongList(ArrayList<Song> songList) {
//retrieve song info
ContentResolver musicResolver = activity.getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
musicSrv.go();
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Model.instance().setPause(false);
break;
case R.id.pause:
musicSrv.pausePlayer();
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
Model.instance().setPause(true);
break;
}
}
private ServiceConnection musicConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
//Model.instance().setMusicSrv(musicSrv);
musicBound = true;
Model.instance().setmusicBound(musicBound);
}
@Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
Model.instance().setmusicBound(musicBound);
}
};
@Override
public void onStart() {
super.onStart();
if(musicSrv==null){
playIntent = new Intent(activity, MusicService.class);
Log.e("oncClick","увы-увы");
context.bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
context.startService(playIntent);
}
if(Model.instance().getPause()) pause.setVisibility(View.GONE);
else play.setVisibility(View.GONE);
}
@Override
public void onDestroy() {
super.onDestroy();
}
/*public static void showController() {
controller.show(0);
}
@Override
public void onStop() {
controller.chetkiy_hide();
Model.instance().setPaused(true);
super.onStop();
}
public void setController(){
controller = new MusicController(context);
controller.setPrevNextListeners(new View.OnClickListener() {
@Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
@Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(songView);
controller.setEnabled(true);
}
//play next
private void playNext(){
musicSrv.playNext();
Model.instance().setplaybackPaused(false);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
Model.instance().setplaybackPaused(false);
}
//implement methods
@Override
public void start() {
musicSrv.go();
}
@Override
public void pause() {
musicSrv.pausePlayer();
playbackPaused=true;
}
@Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else if(playbackPaused) return musicSrv.getDur();
else return 0;
}
@Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else if(playbackPaused) return musicSrv.getPosn();
else return 0;
}
@Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
@Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getAudioSessionId() {
return 0;
}
*/
}
| 29.375
| 111
| 0.604496
|
7cdb422087c47e5e63f9691d36376c472d3e011c
| 5,970
|
package com.example.demo.test.SerializerFeaturePackage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.util.*;
/**
* SerializerFeature
*/
public class SerializerFeatureClass {
private static Word word;
private static void init() {
word = new Word();
word.setA("a");
word.setB(2);
word.setC(true);
word.setD("d");
word.setE("");
word.setF(null);
word.setDate(new Date());
List<User> list = new ArrayList<User>();
User user1 = new User();
user1.setId(1);
user1.setOld("11");
user1.setName("用户1");
user1.setAdd("北京");
User user2 = new User();
user2.setId(2);
user2.setOld("22");
user2.setName("用户2");
user2.setAdd("上海");
User user3 = new User();
user3.setId(3);
user3.setOld("33");
user3.setName("用户3");
user3.setAdd("广州");
list.add(user3);
list.add(user2);
list.add(null);
list.add(user1);
word.setList(list);
Map<String, Object> map = new HashMap<>();
map.put("mapa", "mapa");
map.put("mapo", "mapo");
map.put("mapz", "mapz");
map.put("user1", user1);
map.put("user3", user3);
map.put("user4", null);
map.put("list", list);
word.setMap(map);
}
/**
* 9、自定义
* 格式化输出
* 显示值为null的字段
* 将为null的字段值显示为""
* DisableCircularReferenceDetect:消除循环引用
*/
private static void showJsonBySelf() {
init();
System.out.println(JSON.toJSONString(word, true));
System.out.println(JSON.toJSONString(word, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.DisableCircularReferenceDetect, SerializerFeature.PrettyFormat, SerializerFeature.WriteNullListAsEmpty));
}
/**
* 将bean转为array
*/
private static void beanToArray() {
init();
/*word.setMap(null);
word.setList(null);*/
System.out.println(JSON.toJSONString(word, true));
System.out.println(JSON.toJSONString(word, SerializerFeature.BeanToArray, SerializerFeature.PrettyFormat));
}
/**
* 6:
* PrettyFormat
*/
private static void prettyFormat() {
word.setMap(null);
word.setList(null);
System.out.println(JSON.toJSONString(word));
System.out.println(JSON.toJSONString(word, SerializerFeature.PrettyFormat));
}
/**
* SortField:按字段名称排序后输出。默认为false
* 这里使用的是fastjson:为了更好使用sort field martch优化算法提升parser的性能,fastjson序列化的时候,
* 缺省把SerializerFeature.SortField特性打开了。
* 反序列化的时候也缺省把SortFeidFastMatch的选项打开了。
* 这样,如果你用fastjson序列化的文本,输出的结果是按照fieldName排序输出的,parser时也能利用这个顺序进行优化读取。
* 这种情况下,parser能够获得非常好的性能。
*/
private static void sortField() {
System.out.println(JSON.toJSONString(word));
System.out.println(JSON.toJSONString(word, SerializerFeature.SortField));
}
/**
* 4:
* WriteNullListAsEmpty:List字段如果为null,输出为[],而非null
* 需要配合WriteMapNullValue使用,现将null输出
*/
private static void writeNullListAsEmpty() {
init();
word.setList(null);
System.out.println(JSONObject.toJSONString(word));
System.out.println("设置WriteNullListAsEmpty后:");
System.out.println(JSONObject.toJSONString(word, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty));
}
/**
* 3:
* UseISO8601DateFormat:Date使用ISO8601格式输出,默认为false
*/
private static void useISO8601DateFormat() {
init();
System.out.println(JSONObject.toJSONString(word, true));
System.out.println("设置UseISO8601DateFormat后:");
System.out.println(JSONObject.toJSONString(word, SerializerFeature.UseISO8601DateFormat, SerializerFeature.PrettyFormat));
}
/**
* 2:
* WriteMapNullValue:是否输出值为null的字段,默认为false
*/
private static void writeMapNullValue() {
System.out.println(JSONObject.toJSONString(word));
System.out.println("设置WriteMapNullValue后:");
System.out.println(JSONObject.toJSONString(word, SerializerFeature.WriteMapNullValue));
}
/**
* 1:
* UseSingleQuotes:使用单引号而不是双引号,默认为false
*/
private static void useSingleQuotes() {
System.out.println(JSONObject.toJSONString(word));
System.out.println("设置useSingleQuotes后:");
System.out.println(JSONObject.toJSONString(word, SerializerFeature.UseSingleQuotes));
}
public static void main(String[] args) {
//showJsonBySelf();
//beanToArray();
//writeNullListAsEmpty();
useISO8601DateFormat();
}
}
/**
* SerializerFeature属性
* QuoteFieldNames 输出key时是否使用双引用,默认为true
* UseSingleQuotes 使用单引号而不是双引号,默认为false
* WriteMapNullValue 是否输出值为null的字段,默认为false
* WriteEnumUsingToString Enum输出name()或者orgninal,默认为false
* UseISO8601DateFor Date使用ISO8601格式输出,默认为false
* WriteNullListAsEmpty List字段如果为null,输出[],而非null
* WriteNullStringAsEmpty 字符类型字段如果为null,输出为"",而非null
* WriteNullNumberAsZero 数值字段如果为null,输出为0,而非null
* WriteNullBooleanAsFalse Boolean字段如果为null,输出为false,而非null
* BeanToArray 将对象转为array输出
* SkipTransientField 如果是true,类中的Get方法对应的Field是transient,序列化时将会被忽略。默认为true
* SortField 按字段名称排序后输出。默认为false
* WriteTabAsSpecial 把\t做转义输出,默认为false 不推荐
* PrettyFormat 结果是否格式化,默认为false
* WriteClassName 序列化时写入类型信息,默认为false。反序列化是需用到
* DisableCircularReferenceDetect 消除对同一对象循环引用的问题,默认为false
* WriteSlashAsSpecial 对斜杠’/’进行转义
* BrowserCompatible 将中文都会序列化为格式,字节数会多一些,但是能兼容IE 6,默认为false
* WriteDateUseDateFormat 全局修改日期格式,默认为false。JSON.DEFFAULT_DATE_FORMAT = “yyyy-MM-dd”;JSON.toJSONString(obj, SerializerFeature.WriteDateUseDateFormat);
* DisableCheckSpecialChar 一个对象的字符串属性中如果有特殊字符如双引号,将会在转成json时带有反斜杠转移符。如果不需要转义,可以使用这个属性。默认为false
*/
| 27.897196
| 253
| 0.671357
|
65957a286dc02965f356d7c1947c2deff363148c
| 3,614
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.client.cli;
import org.apache.flink.client.deployment.executors.LocalExecutor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.configuration.PipelineOptions;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.time.Duration;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
/**
* Integration tests for {@link CliFrontend}.
*/
public class CliFrontendITCase {
private PrintStream originalPrintStream;
private ByteArrayOutputStream testOutputStream;
@Before
public void before() {
originalPrintStream = System.out;
testOutputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(testOutputStream));
}
@After
public void finalize() {
System.setOut(originalPrintStream);
}
private String getStdoutString() {
return testOutputStream.toString();
}
@Test
public void configurationIsForwarded() throws Exception {
Configuration config = new Configuration();
CustomCommandLine commandLine = new DefaultCLI();
config.set(PipelineOptions.AUTO_WATERMARK_INTERVAL, Duration.ofMillis(42L));
CliFrontend cliFrontend = new CliFrontend(config, Collections.singletonList(commandLine));
cliFrontend.parseAndRun(new String[]{"run", "-c", TestingJob.class.getName(), CliFrontendTestUtils.getTestJarPath()});
assertThat(getStdoutString(), containsString("Watermark interval is 42"));
}
@Test
public void commandlineOverridesConfiguration() throws Exception {
Configuration config = new Configuration();
// we use GenericCli because it allows specifying arbitrary options via "-Dfoo=bar" syntax
CustomCommandLine commandLine = new GenericCLI(config, "/dev/null");
config.set(PipelineOptions.AUTO_WATERMARK_INTERVAL, Duration.ofMillis(42L));
CliFrontend cliFrontend = new CliFrontend(config, Collections.singletonList(commandLine));
cliFrontend.parseAndRun(new String[]{
"run",
"-t", LocalExecutor.NAME,
"-c", TestingJob.class.getName(),
"-D" + PipelineOptions.AUTO_WATERMARK_INTERVAL.key() + "=142",
CliFrontendTestUtils.getTestJarPath()});
assertThat(getStdoutString(), containsString("Watermark interval is 142"));
}
/**
* Testing job that the watermark interval from the {@link org.apache.flink.api.common.ExecutionConfig}.
*/
public static class TestingJob {
public static void main(String[] args) {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
System.out.println(
"Watermark interval is " + env.getConfig().getAutoWatermarkInterval());
}
}
}
| 33.155963
| 120
| 0.770061
|
1c435b71fa4891ff814dbae706c2c5f6fd2d3725
| 25,742
|
/**
* Sencha GXT 4.0.1 - Sencha for GWT
* Copyright (c) 2006-2016, Sencha Inc.
*
* licensing@sencha.com
* http://www.sencha.com/products/gxt/license/
*
* ================================================================================
* Evaluation/Trial License
* ================================================================================
* This version of Sencha GXT is licensed commercially for a limited period for
* evaluation purposes only. Production use or use beyond the applicable evaluation
* period is prohibited under this license.
*
* Please see the Sencha GXT Licensing page at:
* http://www.sencha.com/products/gxt/license/
*
* For clarification or additional options, please contact:
* licensing@sencha.com
* ================================================================================
*
*
*
*
*
*
*
* ================================================================================
* Disclaimer
* ================================================================================
* THIS SOFTWARE IS DISTRIBUTED "AS-IS" WITHOUT ANY WARRANTIES, CONDITIONS AND
* REPRESENTATIONS WHETHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
* IMPLIED WARRANTIES AND CONDITIONS OF MERCHANTABILITY, MERCHANTABLE QUALITY,
* FITNESS FOR A PARTICULAR PURPOSE, DURABILITY, NON-INFRINGEMENT, PERFORMANCE AND
* THOSE ARISING BY STATUTE OR FROM CUSTOM OR USAGE OF TRADE OR COURSE OF DEALING.
* ================================================================================
*/
package com.sencha.gxt.explorer.client.grid;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.RepeatingCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Overflow;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.ScrollEvent;
import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.user.client.Random;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.cell.core.client.form.TextAreaInputCell.TextAreaAppearance;
import com.sencha.gxt.core.client.ValueProvider;
import com.sencha.gxt.core.client.dom.XElement;
import com.sencha.gxt.core.client.util.Margins;
import com.sencha.gxt.core.client.util.Util;
import com.sencha.gxt.data.shared.ListStore;
import com.sencha.gxt.data.shared.ModelKeyProvider;
import com.sencha.gxt.examples.resources.client.TestData;
import com.sencha.gxt.explorer.client.app.ui.ExampleContainer;
import com.sencha.gxt.explorer.client.app.ui.ExplorerShell.Theme;
import com.sencha.gxt.explorer.client.model.Example.Detail;
import com.sencha.gxt.widget.core.client.ContentPanel;
import com.sencha.gxt.widget.core.client.Window;
import com.sencha.gxt.widget.core.client.button.TextButton;
import com.sencha.gxt.widget.core.client.button.ToggleButton;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer;
import com.sencha.gxt.widget.core.client.container.VerticalLayoutContainer.VerticalLayoutData;
import com.sencha.gxt.widget.core.client.event.SelectEvent;
import com.sencha.gxt.widget.core.client.event.SelectEvent.SelectHandler;
import com.sencha.gxt.widget.core.client.event.StartEditEvent;
import com.sencha.gxt.widget.core.client.event.StartEditEvent.StartEditHandler;
import com.sencha.gxt.widget.core.client.event.ViewReadyEvent;
import com.sencha.gxt.widget.core.client.event.ViewReadyEvent.ViewReadyHandler;
import com.sencha.gxt.widget.core.client.form.Field;
import com.sencha.gxt.widget.core.client.form.FieldLabel;
import com.sencha.gxt.widget.core.client.form.IntegerSpinnerField;
import com.sencha.gxt.widget.core.client.form.TextArea;
import com.sencha.gxt.widget.core.client.grid.ColumnConfig;
import com.sencha.gxt.widget.core.client.grid.ColumnModel;
import com.sencha.gxt.widget.core.client.grid.Grid;
import com.sencha.gxt.widget.core.client.grid.Grid.GridCell;
import com.sencha.gxt.widget.core.client.grid.GridView;
import com.sencha.gxt.widget.core.client.grid.editing.ClicksToEdit;
import com.sencha.gxt.widget.core.client.grid.editing.GridInlineEditing;
import com.sencha.gxt.widget.core.client.info.Info;
import com.sencha.gxt.widget.core.client.menu.CheckMenuItem;
import com.sencha.gxt.widget.core.client.menu.Menu;
import com.sencha.gxt.widget.core.client.menu.MenuItem;
/**
* An example that illustrates a way to implement word wrap in {@link Grid} column headers and cells.
* <p />
* This class demonstrates many capabilities of word wrap in grids, including setting heading text, setting cell text,
* setting column width, setting header height, getting header height and toggling force fit. Most applications will not
* have need for all of these functions. The basic word wrap column header support can be found in
* {@link WordWrapColumnHeader}.
* <p />
* This class generally uses the term <i>heading</i> to refer to the text of a column heading and the term <i>header</i>
* to refer to the visual elements that display the heading. In some cases, this terminology is relaxed to make the
* example more usable.
*/
@Detail(
name = "Word Wrap Grid",
category = "Grid",
icon = "basicgrid",
classes = WordWrapColumnHeader.class,
maxHeight = WordWrapGridExample.MAX_HEIGHT,
maxWidth = WordWrapGridExample.MAX_WIDTH,
minHeight = WordWrapGridExample.MIN_HEIGHT,
minWidth = WordWrapGridExample.MIN_WIDTH
)
public class WordWrapGridExample implements IsWidget, EntryPoint {
/**
* A value provider that supports a spreadsheet-like table with an arbitrary number of columns.
*/
public static class ColumnValueProvider implements ValueProvider<Row, String> {
private static int nextId;
private final int columnIndex;
private final String path = "Column" + Integer.toString(nextId++);
public ColumnValueProvider(int columnIndex) {
this.columnIndex = columnIndex;
}
@Override
public String getPath() {
return path;
}
@Override
public String getValue(Row row) {
return row.getColumn(columnIndex);
}
@Override
public void setValue(Row row, String value) {
row.setValue(columnIndex, value);
}
}
/**
* An array of column widths that can be used with {@link GridView#setForceFit(boolean)} to save column widths before
* invoking <code>setForceFit(true)</code> and restore them after invoking <code>setForceFit(false)</code>.
*/
public class ColumnWidths {
private int[] columnWidths;
public void restore(Grid<Row> grid) {
ColumnModel<Row> columnModel = grid.getColumnModel();
for (int columnIndex = 0; columnIndex < columnWidths.length; columnIndex++) {
columnModel.setColumnWidth(columnIndex, columnWidths[columnIndex]);
}
}
public void save(Grid<Row> grid) {
ColumnModel<Row> columnModel = grid.getColumnModel();
int columnCount = columnModel.getColumnCount();
columnWidths = new int[columnCount];
for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {
ColumnConfig<Row, Object> columnConfig = columnModel.getColumn(columnIndex);
columnWidths[columnIndex] = columnConfig.getWidth();
}
}
}
/**
* A data model that supports a spreadsheet-like table with an arbitrary number of rows and columns.
*/
public static class Row {
private static int nextId;
private final String[] columns;
private final String key = "Row" + Integer.toString(nextId++);
public Row(int columnCount) {
columns = new String[columnCount];
}
public String getColumn(int columnIndex) {
return columns[columnIndex];
}
public String getKey() {
return key;
}
public void setValue(int columnIndex, String value) {
columns[columnIndex] = value;
}
}
/**
* A model key provider that supports a spreadsheet-like table with an arbitrary number of rows.
*/
public class RowKeyProvider implements ModelKeyProvider<Row> {
@Override
public String getKey(Row row) {
return row.getKey();
}
}
/**
* A value provider that supports a spreadsheet-like table with an arbitrary number of rows.
*/
public class RowValueProvider {
public ValueProvider<Row, String> getColumnValueProvider(int columnIndex) {
return new ColumnValueProvider(columnIndex);
}
}
/**
* A grid view that limits the width of the items in the column header menu's column sub-menu. Strictly speaking, this
* is not required for a word wrap grid header because the sub-menu resizes itself to the width of the longest column
* heading, but this does improve the usability by limiting the sub-menu width.
*/
public static class WordWrapGridView extends GridView<Row> {
@Override
protected Menu createContextMenu(int colIndex) {
Menu contextMenu = super.createContextMenu(colIndex);
int lastItem = contextMenu.getWidgetCount() - 1;
if (lastItem >= 0) {
Widget widget = contextMenu.getWidget(lastItem);
if (widget instanceof MenuItem) {
MenuItem columns = (MenuItem) widget;
Menu columnMenu = columns.getSubMenu();
if (columnMenu != null) {
int cols = columnMenu.getWidgetCount();
for (int i = 0; i < cols; i++) {
widget = columnMenu.getWidget(i);
if (widget instanceof CheckMenuItem) {
CheckMenuItem menuItem = (CheckMenuItem) widget;
menuItem.setWidth(200);
}
}
}
}
}
return contextMenu;
}
}
protected static final int MAX_HEIGHT = 600;
protected static final int MAX_WIDTH = 800;
protected static final int MIN_HEIGHT = 480;
protected static final int MIN_WIDTH = 675;
private static final int ROW_COUNT = 15;
private static final int COLUMN_COUNT = 5;
private static final Margins M1 = new Margins(5, 5, 0, 5);
private static final Margins M2 = new Margins(5, 5, 5, 5);
private static final String[] SENTENCES = TestData.DUMMY_TEXT_LONG.replaceAll("\\<[^>]*>", "").split("\\. ");
private ContentPanel panel;
private RowValueProvider rvp = new RowValueProvider();
private ColumnWidths columnWidths = new ColumnWidths();
@Override
public Widget asWidget() {
if (panel == null) {
List<ColumnConfig<Row, ?>> columns = new LinkedList<ColumnConfig<Row, ?>>();
Set<String> columnHeaders = new HashSet<String>(COLUMN_COUNT);
for (int i = 0; i < COLUMN_COUNT; i++) {
ValueProvider<Row, String> cvp = rvp.getColumnValueProvider(i);
String headerText = createDummyHeaderText(columnHeaders);
columnHeaders.add(headerText);
SafeHtml sh = wrapString(headerText);
ColumnConfig<Row, String> cc = new ColumnConfig<Row, String>(cvp, 200, sh);
// Use a custom cell renderer to support word wrap in the grid's cells
cc.setCell(new AbstractCell<String>() {
@Override
public void render(Context context, String value, SafeHtmlBuilder sb) {
if (value == null || value.isEmpty()) {
sb.append(Util.NBSP_SAFE_HTML);
} else {
sb.append(wrapString(value));
}
}
});
columns.add(cc);
}
final ColumnModel<Row> cm = new ColumnModel<Row>(columns);
final ListStore<Row> ls = new ListStore<Row>(new RowKeyProvider());
ls.setAutoCommit(true);
int columnCount = columns.size();
for (int i = 0; i < ROW_COUNT; i++) {
Row row = new Row(columnCount);
for (int j = 0; j < columnCount; j++) {
row.setValue(j, createDummyText());
}
ls.add(row);
}
final Grid<Row> grid = new Grid<Row>(ls, cm, new WordWrapGridView());
grid.getView().setColumnHeader(new WordWrapColumnHeader<Row>(grid, cm));
grid.getView().setColumnLines(true);
final GridInlineEditing<Row> editing = new GridInlineEditing<Row>(grid) {
protected void onScroll(ScrollEvent event) {
// Suppress default action, which may result in canceling edit
}
};
editing.setClicksToEdit(ClicksToEdit.TWO);
editing.addStartEditHandler(new StartEditHandler<Row>() {
@Override
public void onStartEdit(StartEditEvent<Row> event) {
GridCell cell = event.getEditCell();
ColumnConfig<Row, ?> cc = cm.getColumn(cell.getCol());
Field<Object> editor = (Field<Object>) editing.getEditor(cc);
Element rowElement = grid.getView().getRow(cell.getRow());
// Resize the inline editor to the height of the row and style it to match the text
int height = rowElement.getOffsetHeight() - 1;
editor.setHeight(height);
XElement cellElement = grid.getView().getCell(cell.getRow(), cell.getCol()).cast();
Style style = ((TextAreaAppearance) editor.getCell().getAppearance()).getInputElement(editor.getElement()).getStyle();
String fontSize = cellElement.getComputedStyle("fontSize");
if (fontSize != null) {
style.setProperty("fontSize", fontSize);
}
String fontFamily = cellElement.getComputedStyle("fontFamily");
if (fontFamily != null) {
style.setProperty("fontFamily", fontFamily);
}
style.setOverflow(Overflow.HIDDEN);
}
});
for (ColumnConfig<Row, ?> cc : columns) {
@SuppressWarnings("unchecked")
ColumnConfig<Row, String> scc = (ColumnConfig<Row, String>) cc;
final TextArea ta = new TextArea();
ta.setPreventScrollbars(true);
ta.addKeyDownHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
// Allow the enter key to end grid inline editing
if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
Scheduler.get().scheduleFinally(new RepeatingCommand() {
@Override
public boolean execute() {
editing.completeEditing();
ta.clear();
return false;
}
});
}
}
});
editing.addEditor(scc, ta);
}
grid.addViewReadyHandler(new ViewReadyHandler() {
@Override
public void onViewReady(ViewReadyEvent event) {
Info.display("onViewReady", "heading width=" + grid.getView().getHeader().getOffsetWidth() + ", height=" + grid.getView().getHeader().getOffsetHeight());
grid.getView().getHeader().addResizeHandler(new ResizeHandler() {
@Override
public void onResize(ResizeEvent event) {
Info.display("onResize", "heading width=" + event.getWidth() + ", height=" + event.getHeight());
}
});
}
});
panel = new ContentPanel();
panel.setHeading("Word Wrap Grid");
panel.add(grid);
panel.addButton(new TextButton("Set Heading Text", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
final Window w = new Window();
w.setHeading("Set Heading Text");
w.setPixelSize(300, Theme.TRITON.isActive() ? 240 : 200);
w.setResizable(false);
w.setModal(true);
VerticalLayoutContainer vlc = new VerticalLayoutContainer();
w.setWidget(vlc);
final IntegerSpinnerField index = new IntegerSpinnerField();
index.setMinValue(0);
index.setMaxValue(COLUMN_COUNT - 1);
index.setValue(0);
index.setAllowBlank(false);
index.setSelectOnFocus(true);
vlc.add(new FieldLabel(index, "Column Index"), new VerticalLayoutData(1, -1, M1));
final TextArea text = new TextArea();
vlc.add(new FieldLabel(text, "Heading Text"), new VerticalLayoutData(1, 1, M2));
w.addButton(new TextButton("Cancel", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
w.hide();
}
}));
w.addButton(new TextButton("OK", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
if (index.validate()) {
w.hide();
SafeHtml newHeading = SafeHtmlUtils.EMPTY_SAFE_HTML;
String newText = text.getValue();
if (newText == null || newText.isEmpty()) {
newHeading = Util.NBSP_SAFE_HTML;
} else {
newHeading = wrapString(newText);
}
ColumnModel<Row> columnModel = grid.getColumnModel();
columnModel.setColumnHeader(index.getValue(), newHeading);
}
}
}));
w.show();
w.setFocusWidget(index);
}
}));
panel.addButton(new TextButton("Set Cell Text", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
final Window w = new Window();
w.setHeading("Set Cell Text");
w.setPixelSize(300, Theme.TRITON.isActive() ? 285 : 200);
w.setResizable(false);
w.setModal(true);
VerticalLayoutContainer vlc = new VerticalLayoutContainer();
w.setWidget(vlc);
final IntegerSpinnerField rowIndex = new IntegerSpinnerField();
rowIndex.setMinValue(0);
rowIndex.setMaxValue(ROW_COUNT - 1);
rowIndex.setValue(0);
rowIndex.setAllowBlank(false);
rowIndex.setSelectOnFocus(true);
vlc.add(new FieldLabel(rowIndex, "Row Index"), new VerticalLayoutData(1, -1, M1));
final IntegerSpinnerField columnIndex = new IntegerSpinnerField();
columnIndex.setMinValue(0);
columnIndex.setMaxValue(COLUMN_COUNT - 1);
columnIndex.setValue(0);
columnIndex.setAllowBlank(false);
columnIndex.setSelectOnFocus(true);
vlc.add(new FieldLabel(columnIndex, "Column Index"), new VerticalLayoutData(1, -1, M1));
final TextArea text = new TextArea();
vlc.add(new FieldLabel(text, "Cell Text"), new VerticalLayoutData(1, 1, M2));
w.addButton(new TextButton("Cancel", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
w.hide();
}
}));
w.addButton(new TextButton("OK", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
if (rowIndex.validate() && columnIndex.validate()) {
w.hide();
String newText = text.getValue();
if (newText == null) {
newText = "";
}
Row row = ls.get(rowIndex.getValue());
row.setValue(columnIndex.getValue(), newText);
ls.update(row);
}
}
}));
w.show();
w.setFocusWidget(rowIndex);
}
}));
panel.addButton(new TextButton("Set Column Width", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
final Window w = new Window();
w.setHeading("Set Column Width");
w.setPixelSize(300, Theme.TRITON.isActive() ? 190 : 150);
w.setResizable(false);
w.setModal(true);
VerticalLayoutContainer vlc = new VerticalLayoutContainer();
w.setWidget(vlc);
final IntegerSpinnerField columnIndex = new IntegerSpinnerField();
columnIndex.setMinValue(0);
columnIndex.setMaxValue(COLUMN_COUNT - 1);
columnIndex.setValue(0);
columnIndex.setAllowBlank(false);
columnIndex.setSelectOnFocus(true);
vlc.add(new FieldLabel(columnIndex, "Column Index"), new VerticalLayoutData(1, -1, M1));
final IntegerSpinnerField width = new IntegerSpinnerField();
width.setMinValue(0);
width.setValue(50);
width.setAllowBlank(false);
width.setSelectOnFocus(true);
vlc.add(new FieldLabel(width, "Column Width"), new VerticalLayoutData(1, -1, M2));
w.addButton(new TextButton("Cancel", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
w.hide();
}
}));
w.addButton(new TextButton("OK", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
if (columnIndex.validate() && width.validate()) {
w.hide();
grid.getColumnModel().setColumnWidth(columnIndex.getValue(), width.getValue());
}
}
}));
w.show();
w.setFocusWidget(columnIndex);
}
}));
panel.addButton(new TextButton("Set Heading Height", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
final Window w = new Window();
w.setHeading("Set Heading Height");
w.setPixelSize(300, 300);
w.setResizable(false);
w.setModal(true);
VerticalLayoutContainer vlc = new VerticalLayoutContainer();
w.setWidget(vlc);
vlc.add(new HTML("<span style='font: 12px tahoma,arial,verdana,sans-serif;'>Sets the size of the heading to a fixed height. If this height is less than the height of the heading text, the heading text will be truncated.<br><br>To restore automatic sizing, specify a value of -1.<br><br></span>"), new VerticalLayoutData(1, -1, M1));
final IntegerSpinnerField height = new IntegerSpinnerField();
height.setMinValue(-1);
height.setValue(50);
height.setAllowBlank(false);
height.setSelectOnFocus(true);
vlc.add(new FieldLabel(height, "Heading Height"), new VerticalLayoutData(1, -1, M2));
w.addButton(new TextButton("Cancel", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
w.hide();
}
}));
w.addButton(new TextButton("OK", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
if (height.validate()) {
w.hide();
grid.getView().getHeader().setHeight(height.getValue());
}
}
}));
w.show();
w.setFocusWidget(height);
}
}));
panel.addButton(new TextButton("Get Heading Height", new SelectHandler() {
@Override
public void onSelect(SelectEvent event) {
int headerHeight = grid.getView().getHeader().getOffsetHeight();
Info.display("getHeight", "height=" + headerHeight);
}
}));
final ToggleButton fftb = new ToggleButton("Force Fit");
fftb.setValue(true);
fftb.addValueChangeHandler(new ValueChangeHandler<Boolean>() {
@Override
public void onValueChange(ValueChangeEvent<Boolean> event) {
if (fftb.getValue()) {
columnWidths.save(grid);
grid.getView().setForceFit(true);
} else {
grid.getView().setForceFit(false);
columnWidths.restore(grid);
}
grid.getView().layout();
}
});
panel.addButton(fftb);
panel.show();
// save column state and force fit by default
Scheduler.get().scheduleFinally(new Scheduler.ScheduledCommand() {
@Override
public void execute() {
columnWidths.save(grid);
grid.getView().setForceFit(true);
grid.getView().layout();
}
});
}
return panel;
}
@Override
public void onModuleLoad() {
new ExampleContainer(this)
.setMaxHeight(MAX_HEIGHT)
.setMaxWidth(MAX_WIDTH)
.setMinHeight(MIN_HEIGHT)
.setMinWidth(MIN_WIDTH)
.doStandalone();
}
private String createDummyHeaderText(Set<String> existingHeaders) {
String sentence = null;
while ((sentence = SENTENCES[Random.nextInt(SENTENCES.length)]) != null) {
if (sentence.length() < 50 && !existingHeaders.contains(sentence)) {
break;
}
}
return sentence;
}
private String createDummyText() {
int sentenceCount = 1 + Random.nextInt(5);
StringBuilder s = new StringBuilder();
for (int i = 0; i < sentenceCount; i++) {
s.append(SENTENCES[Random.nextInt(SENTENCES.length)]);
s.append(". ");
}
return s.toString();
}
private SafeHtml wrapString(String untrustedString) {
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<span style='white-space: normal;'>");
sb.appendEscaped(untrustedString);
sb.appendHtmlConstant("</span>");
return sb.toSafeHtml();
}
}
| 39.786708
| 342
| 0.633478
|
a3411385794813dc2aeba93ea155f68315c54aa4
| 16,291
|
package internal.org.springframework.content.commons.repository.events;
import static com.github.paulcwarren.ginkgo4j.Ginkgo4jDSL.*;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.hamcrest.MockitoHamcrest.argThat;
import java.io.Serializable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.springframework.content.commons.repository.StoreEvent;
import org.springframework.content.commons.repository.ContentStore;
import org.springframework.content.commons.repository.events.AbstractStoreEventListener;
import org.springframework.content.commons.repository.events.AfterAssociateEvent;
import org.springframework.content.commons.repository.events.AfterGetContentEvent;
import org.springframework.content.commons.repository.events.AfterGetResourceEvent;
import org.springframework.content.commons.repository.events.AfterSetContentEvent;
import org.springframework.content.commons.repository.events.AfterUnassociateEvent;
import org.springframework.content.commons.repository.events.AfterUnsetContentEvent;
import org.springframework.content.commons.repository.events.BeforeAssociateEvent;
import org.springframework.content.commons.repository.events.BeforeGetContentEvent;
import org.springframework.content.commons.repository.events.BeforeGetResourceEvent;
import org.springframework.content.commons.repository.events.BeforeSetContentEvent;
import org.springframework.content.commons.repository.events.BeforeUnassociateEvent;
import org.springframework.content.commons.repository.events.BeforeUnsetContentEvent;
import com.github.paulcwarren.ginkgo4j.Ginkgo4jConfiguration;
import com.github.paulcwarren.ginkgo4j.Ginkgo4jRunner;
@SuppressWarnings("unchecked")
@RunWith(Ginkgo4jRunner.class)
@Ginkgo4jConfiguration(threads = 1)
public class AbstractStoreEventListenerTest {
private AbstractStoreEventListener<Object> listener;
private StoreEvent event;
// mocks
private TestContentEventConsumer consumer;
private ContentStore<Object, Serializable> store;
{
Describe("#onApplicationEvent", () -> {
Context("given a content event listener", () -> {
BeforeEach(() -> {
consumer = mock(TestContentEventConsumer.class);
store = (ContentStore<Object, Serializable>) mock(ContentStore.class);
listener = new TestContentEventListener(consumer);
});
JustBeforeEach(() -> {
listener.onApplicationEvent(event);
});
Context("given a before get resource event", () -> {
BeforeEach(() -> {
event = new BeforeGetResourceEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<BeforeGetResourceEvent> argumentCaptor = ArgumentCaptor
.forClass(BeforeGetResourceEvent.class);
verify(consumer).onBeforeGetResource(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onBeforeGetResource(argThat(is(event.getSource())));
});
});
Context("given an after get resource event", () -> {
BeforeEach(() -> {
event = new AfterGetResourceEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<AfterGetResourceEvent> argumentCaptor = ArgumentCaptor
.forClass(AfterGetResourceEvent.class);
verify(consumer).onAfterGetResource(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onAfterGetResource(argThat(is(event.getSource())));
});
});
Context("given a before associate event", () -> {
BeforeEach(() -> {
event = new BeforeAssociateEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<BeforeAssociateEvent> argumentCaptor = ArgumentCaptor
.forClass(BeforeAssociateEvent.class);
verify(consumer).onBeforeAssociate(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onBeforeAssociate(argThat(is(event.getSource())));
});
});
Context("given an after associate event", () -> {
BeforeEach(() -> {
event = new AfterAssociateEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<AfterAssociateEvent> argumentCaptor = ArgumentCaptor
.forClass(AfterAssociateEvent.class);
verify(consumer).onAfterAssociate(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onAfterAssociate(argThat(is(event.getSource())));
});
});
Context("given a before unassociate event", () -> {
BeforeEach(() -> {
event = new BeforeUnassociateEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<BeforeUnassociateEvent> argumentCaptor = ArgumentCaptor
.forClass(BeforeUnassociateEvent.class);
verify(consumer).onBeforeUnassociate(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onBeforeUnassociate(argThat(is(event.getSource())));
});
});
Context("given an after unassociate event", () -> {
BeforeEach(() -> {
event = new AfterUnassociateEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<AfterUnassociateEvent> argumentCaptor = ArgumentCaptor
.forClass(AfterUnassociateEvent.class);
verify(consumer).onAfterUnassociate(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onAfterUnassociate(argThat(is(event.getSource())));
});
});
Context("given a before get content event", () -> {
BeforeEach(() -> {
event = new BeforeGetContentEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<BeforeGetContentEvent> argumentCaptor = ArgumentCaptor
.forClass(BeforeGetContentEvent.class);
verify(consumer).onBeforeGetContent(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onBeforeGetContent(argThat(is(event.getSource())));
});
});
Context("given an after get content event", () -> {
BeforeEach(() -> {
event = new AfterGetContentEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<AfterGetContentEvent> argumentCaptor = ArgumentCaptor
.forClass(AfterGetContentEvent.class);
verify(consumer).onAfterGetContent(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onAfterGetContent(argThat(is(event.getSource())));
});
});
Context("given a before set content event", () -> {
BeforeEach(() -> {
event = new BeforeSetContentEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<BeforeSetContentEvent> argumentCaptor = ArgumentCaptor
.forClass(BeforeSetContentEvent.class);
verify(consumer).onBeforeSetContent(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onBeforeSetContent(argThat(is(event.getSource())));
});
});
Context("given a after set content event", () -> {
BeforeEach(() -> {
event = new AfterSetContentEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<AfterSetContentEvent> argumentCaptor = ArgumentCaptor
.forClass(AfterSetContentEvent.class);
verify(consumer).onAfterSetContent(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onAfterSetContent(argThat(is(event.getSource())));
});
});
Context("given a before unset content event", () -> {
BeforeEach(() -> {
event = new BeforeUnsetContentEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<BeforeUnsetContentEvent> argumentCaptor = ArgumentCaptor
.forClass(BeforeUnsetContentEvent.class);
verify(consumer).onBeforeUnsetContent(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onBeforeUnsetContent(argThat(is(event.getSource())));
});
});
Context("given a after unset content event", () -> {
BeforeEach(() -> {
event = new AfterUnsetContentEvent(new EventSource(), store);
});
It("should call the event consumer", () -> {
ArgumentCaptor<AfterUnsetContentEvent> argumentCaptor = ArgumentCaptor
.forClass(AfterUnsetContentEvent.class);
verify(consumer).onAfterUnsetContent(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), is(event));
assertThat(argumentCaptor.getValue().getSource(),
is(event.getSource()));
assertThat(argumentCaptor.getValue().getStore(), is(store));
});
It("should call the event source consumer", () -> {
verify(consumer)
.onAfterUnsetContent(argThat(is(event.getSource())));
});
});
});
});
}
@Test
public void noop() {
}
public static class TestContentEventListener
extends AbstractStoreEventListener<Object> {
private TestContentEventConsumer consumer;
public TestContentEventListener(TestContentEventConsumer consumer) {
super();
this.consumer = consumer;
}
@Override
protected void onBeforeGetResource(BeforeGetResourceEvent event) {
consumer.onBeforeGetResource(event);
}
@Override
protected void onBeforeGetResource(Object entity) {
consumer.onBeforeGetResource(entity);
}
@Override
protected void onAfterGetResource(AfterGetResourceEvent event) {
consumer.onAfterGetResource(event);
}
@Override
protected void onAfterGetResource(Object entity) {
consumer.onAfterGetResource(entity);
}
@Override
protected void onBeforeAssociate(BeforeAssociateEvent event) {
consumer.onBeforeAssociate(event);
}
@Override
protected void onBeforeAssociate(Object entity) {
consumer.onBeforeAssociate(entity);
}
@Override
protected void onAfterAssociate(AfterAssociateEvent event) {
consumer.onAfterAssociate(event);
}
@Override
protected void onAfterAssociate(Object entity) {
consumer.onAfterAssociate(entity);
}
@Override
protected void onBeforeUnassociate(BeforeUnassociateEvent event) {
consumer.onBeforeUnassociate(event);
}
@Override
protected void onBeforeUnassociate(Object entity) {
consumer.onBeforeUnassociate(entity);
}
@Override
protected void onAfterUnassociate(AfterUnassociateEvent event) {
consumer.onAfterUnassociate(event);
}
@Override
protected void onAfterUnassociate(Object entity) {
consumer.onAfterUnassociate(entity);
}
@Override
protected void onBeforeGetContent(BeforeGetContentEvent event) {
consumer.onBeforeGetContent(event);
}
@Override
protected void onBeforeGetContent(Object entity) {
consumer.onBeforeGetContent(entity);
}
@Override
protected void onAfterGetContent(AfterGetContentEvent event) {
consumer.onAfterGetContent(event);
}
@Override
protected void onAfterGetContent(Object entity) {
consumer.onAfterGetContent(entity);
}
@Override
protected void onBeforeSetContent(BeforeSetContentEvent event) {
consumer.onBeforeSetContent(event);
}
@Override
protected void onBeforeSetContent(Object entity) {
consumer.onBeforeSetContent(entity);
}
@Override
protected void onAfterSetContent(AfterSetContentEvent event) {
consumer.onAfterSetContent(event);
}
@Override
protected void onAfterSetContent(Object entity) {
consumer.onAfterSetContent(entity);
}
@Override
protected void onBeforeUnsetContent(BeforeUnsetContentEvent event) {
consumer.onBeforeUnsetContent(event);
}
@Override
protected void onBeforeUnsetContent(Object entity) {
consumer.onBeforeUnsetContent(entity);
}
@Override
protected void onAfterUnsetContent(AfterUnsetContentEvent event) {
consumer.onAfterUnsetContent(event);
}
@Override
protected void onAfterUnsetContent(Object entity) {
consumer.onAfterUnsetContent(entity);
}
}
public interface TestContentEventConsumer {
void onBeforeGetResource(BeforeGetResourceEvent event);
void onBeforeGetResource(Object entity);
void onAfterGetResource(AfterGetResourceEvent event);
void onAfterGetResource(Object entity);
void onBeforeAssociate(BeforeAssociateEvent event);
void onBeforeAssociate(Object entity);
void onAfterAssociate(AfterAssociateEvent event);
void onAfterAssociate(Object entity);
void onBeforeUnassociate(BeforeUnassociateEvent event);
void onBeforeUnassociate(Object entity);
void onAfterUnassociate(AfterUnassociateEvent event);
void onAfterUnassociate(Object entity);
void onBeforeGetContent(BeforeGetContentEvent event);
void onBeforeGetContent(Object entity);
void onAfterGetContent(AfterGetContentEvent event);
void onAfterGetContent(Object entity);
void onBeforeSetContent(BeforeSetContentEvent event);
void onBeforeSetContent(Object argThat);
void onAfterSetContent(AfterSetContentEvent event);
void onAfterSetContent(Object argThat);
void onBeforeUnsetContent(BeforeUnsetContentEvent event);
void onBeforeUnsetContent(Object argThat);
void onAfterUnsetContent(AfterUnsetContentEvent event);
void onAfterUnsetContent(Object argThat);
}
public static class EventSource {
}
}
| 35.109914
| 88
| 0.712172
|
b292ea9de9c1aab9d938db4764ae4cf6313000da
| 2,708
|
package de.jollyday.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.time.LocalDate;
import java.util.Set;
import org.junit.Test;
import de.jollyday.Holiday;
import de.jollyday.HolidayCalendar;
import de.jollyday.HolidayManager;
import de.jollyday.ManagerParameters;
import de.jollyday.tests.base.AbstractCountryTestBase;
import de.jollyday.util.CalendarUtil;
public class HolidayEGTest extends AbstractCountryTestBase {
private static final int YEAR = 2019;
private CalendarUtil calendarUtil = new CalendarUtil();
@Test
public void testNumberOfHolidays() throws Exception {
HolidayManager holidayManager = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.EGYPT));
Set<Holiday> holidays = holidayManager.getHolidays(YEAR);
assertEquals(17, holidays.size());
}
@Test
public void testEasterMonday2019() throws Exception {
LocalDate expected = calendarUtil.create(YEAR, 4, 29);
HolidayManager holidayManager = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.EGYPT));
Set<Holiday> holidays = holidayManager.getHolidays(YEAR);
assertEquals(17, holidays.size());
assertTrue("Wrong / missing holiday for Easter Monday",
holidays.stream().filter(holiday -> holiday.getPropertiesKey().equals("christian.EASTER_MONDAY")
&& holiday.getDate().equals(expected)).count() == 1);
}
@Test
public void testEidFitr2019() throws Exception {
LocalDate expected = calendarUtil.create(YEAR, 6, 4);
HolidayManager holidayManager = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.EGYPT));
Set<Holiday> holidays = holidayManager.getHolidays(YEAR);
assertEquals(17, holidays.size());
assertTrue("Wrong / missing holiday for Eid Fitr",
holidays.stream().filter(holiday -> holiday.getPropertiesKey().equals("islamic.ID_AL_FITR")
&& holiday.getDate().equals(expected)).count() == 1);
}
@Test
public void testArafaat2019() throws Exception {
LocalDate expected = calendarUtil.create(YEAR, 8, 10);
HolidayManager holidayManager = HolidayManager.getInstance(ManagerParameters.create(HolidayCalendar.EGYPT));
Set<Holiday> holidays = holidayManager.getHolidays(YEAR);
assertEquals(17, holidays.size());
assertTrue("Wrong / missing holiday for Arafaat", holidays.stream().filter(
holiday -> holiday.getPropertiesKey().equals("islamic.ARAFAAT") && holiday.getDate().equals(expected))
.count() == 1);
}
}
| 41.661538
| 118
| 0.706056
|
46bb58a9eef817f0da0021d8c1829e4882a6a07d
| 2,110
|
// 数组
// java语言支持长度不变的数组。
// java语言以标准库ArrayList来实现动态数组。
// 如果数组的元素可比较,那么数组可以直接用==比较
import java.util.ArrayList;
import java.util.Comparator;
class Array {
public static void printArray(int []array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
System.out.println();
}
public static void printVector(ArrayList<Integer> vec) {
for (int i = 0; i < vec.size(); i++) {
System.out.print(vec.get(i) + " ");
}
System.out.println();
}
public static void main(String[] args) {
// 数组初始化
// 长度为10,默认初始化为0
int []array = new int[10];
int []array2 = new int[10];
if (array == array2) {
System.out.println("We are equal.");
}
// 索引与赋值
array[1] = 3;
System.out.println(array.length);
Array.printArray(array);
ArrayList<Integer> vec = new ArrayList<>(); // 动态数组
for (int i = 0; i < 5; i++) {
vec.add(i); // append
}
System.out.println(vec.get(0)); // 索引
vec.add(2, 100); // insert at index 2, value 100
System.out.println(vec.indexOf(100)); // index of 100
if (vec.contains(100)) { // contains
System.out.println("vec has 100");
}
vec.remove(0); // removeFirst
vec.remove(vec.size()-1); // removeLast
ArrayList<Integer> vec2 = new ArrayList<Integer>(5);
vec2.add(3);
vec2.add(4);
vec2.add(5);
vec.addAll(vec2); // 数组加法
Array.printVector(vec);
vec.sort(new Comparator<Integer>() { // sort by function
@Override
public int compare(Integer a, Integer b) {
return a - b;
}
});
// empty
if (vec.isEmpty()) {
System.out.println("vec is empty");
}
// capacity and size
System.out.println("cap: " + vec.size());
System.out.println("len: " + vec.size());
// clear
vec.clear();
Array.printVector(vec);
}
}
| 30.142857
| 64
| 0.508531
|
8f70df7f3998ebd53ee1a86d4a7ef19d14ae0f43
| 5,672
|
package org.janelia.jacs2.asyncservice.common;
import com.beust.jcommander.Parameter;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.janelia.jacs2.asyncservice.common.mdc.MdcContext;
import org.janelia.jacs2.cdi.qualifier.PropertyValue;
import org.janelia.jacs2.dataservice.persistence.JacsServiceDataPersistence;
import org.janelia.model.service.JacsServiceData;
import org.janelia.model.service.ServiceMetaData;
import org.slf4j.Logger;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* This is a generic async service wrapper which can be used to wrap other service processing.
* This service is not available in the service registry, therefore it cannot be invoked from the outside.
*/
@MdcContext
public class GenericAsyncServiceProcessor extends AbstractServiceProcessor<Void> {
static class ProcessingArgs extends ServiceArgs {
@Parameter(names = "-serviceName", description = "Service name")
String serviceName;
@Parameter(names = "-serviceArgs", description = "Service arguments", splitter = ServiceArgs.ServiceArgSplitter.class)
List<String> serviceArgs = new ArrayList<>();
}
@Inject
public GenericAsyncServiceProcessor(ServiceComputationFactory computationFactory,
JacsServiceDataPersistence jacsServiceDataPersistence,
@PropertyValue(name = "service.DefaultWorkingDir") String defaultWorkingDir,
Logger logger) {
super(computationFactory, jacsServiceDataPersistence, defaultWorkingDir, logger);
}
@Override
public ServiceMetaData getMetadata() {
return ServiceArgs.createMetadata("genericAsyncService", new ProcessingArgs());
}
@Override
public JacsServiceData createServiceData(ServiceExecutionContext executionContext, List<ServiceArg> args) {
Pair<String, List<String>> serviceWithArgs = args.stream()
.reduce(ImmutablePair.of(null, Arrays.asList()),
(Pair<String, List<String>> sa, ServiceArg a) -> {
if ("-serviceName".equals(a.getFlag())) {
return ImmutablePair.of(a.getValues().stream().findFirst().orElse(sa.getLeft()), sa.getRight());
} else if ("-serviceArgs".equals(a.getFlag())) {
return ImmutablePair.of(
sa.getLeft(),
Stream.concat(
sa.getRight().stream(),
a.getValues().stream()
.flatMap(av -> new ServiceArgs.ServiceArgSplitter().split(av).stream()))
.collect(Collectors.toList()));
} else {
return ImmutablePair.of(sa.getLeft(), Stream.concat(sa.getRight().stream(), Arrays.stream(a.toStringArray())).collect(Collectors.toList()));
}
},
(sa1, sa2) -> ImmutablePair.of(StringUtils.defaultIfBlank(sa2.getLeft(), sa1.getLeft()),
Stream.concat(sa1.getRight().stream(), sa2.getRight().stream()).collect(Collectors.toList())));
return createServiceData(serviceWithArgs.getLeft(), executionContext, serviceWithArgs.getRight());
}
@Override
public ServiceComputation<JacsServiceResult<Void>> process(JacsServiceData jacsServiceData) {
JacsServiceData submittedService = submit(jacsServiceData);
PeriodicallyCheckableState<JacsServiceData> submittedServiceStateCheck = new PeriodicallyCheckableState<>(submittedService, ProcessorHelper.getSoftJobDurationLimitInSeconds(submittedService.getResources()) / 100);
return computationFactory.newCompletedComputation(submittedServiceStateCheck)
.thenSuspendUntil((PeriodicallyCheckableState<JacsServiceData> sdState) -> new ContinuationCond.Cond<>(sdState, sdState.updateCheckTime() && isDone(sdState)))
.thenApply((PeriodicallyCheckableState<JacsServiceData> sdState) -> getResult(sdState))
;
}
private JacsServiceData submit(JacsServiceData jacsServiceData) {
return jacsServiceDataPersistence.createServiceIfNotFound(jacsServiceData);
}
private boolean isDone(PeriodicallyCheckableState<JacsServiceData> jacsServiceDataState) {
JacsServiceData refreshServiceData = jacsServiceDataPersistence.findById(jacsServiceDataState.getState().getId());
return refreshServiceData.hasCompleted();
}
private JacsServiceResult<Void> getResult(PeriodicallyCheckableState<JacsServiceData> jacsServiceDataState) {
JacsServiceData refreshServiceData = jacsServiceDataPersistence.findById(jacsServiceDataState.getState().getId());
if (refreshServiceData.hasCompletedSuccessfully()) {
return new JacsServiceResult<>(refreshServiceData);
} else {
throw new ComputationException(refreshServiceData, "Service " + refreshServiceData.toString() + " completed unsuccessfully");
}
}
private ProcessingArgs getArgs(JacsServiceData jacsServiceData) {
return ServiceArgs.parse(getJacsServiceArgsArray(jacsServiceData), new ProcessingArgs());
}
}
| 54.538462
| 221
| 0.666432
|
7a4795869ef90b63aee3ae5f466078340ef547fb
| 5,823
|
package br.senai.hm.controller;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import application.Main;
import br.senai.hm.dao.ConferenciaDAO;
import br.senai.hm.modelo.Ambiente;
import br.senai.hm.modelo.Conferencia;
import br.senai.hm.modelo.Patrimonio;
import br.senai.hm.util.Mensagens;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.DatePicker;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.effect.Effect;
import javafx.scene.effect.Glow;
import javafx.scene.image.Image;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Callback;
public class ConferenciaController implements Initializable {
private static final Effect Glow = new Glow(1.0);
private static final Effect Glow1 = new Glow(0.0);
private static Conferencia c;
private ConferenciaDAO daoc;
@FXML
private Pane ap;
@FXML
private RadioButton radioSim, radioNao, radioTodas;
@FXML
private ToggleGroup grupo = new ToggleGroup();
@FXML
private TextField dtpAtual;
@FXML
private TableView<Conferencia> tbConferencia;
@FXML
private TableColumn<Conferencia, Long> columnId;
@FXML
private TableColumn<Conferencia, String> columnDtAgendamento;
@FXML
private TableColumn<Conferencia, String> columnAmbiente;
@FXML
private TableColumn<Conferencia, String> columnInconsistencias;
@FXML
private TableColumn<Conferencia, String> columnStatus;
private static ObservableList<Conferencia> listItens;
@FXML
private Button btnDetalhar;
@FXML
private Button btnSair;
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
daoc = new ConferenciaDAO();
popularTabela();
radioSim.setToggleGroup(grupo);
radioNao.setToggleGroup(grupo);
radioTodas.setToggleGroup(grupo);
}
Date dtAtual = new Date(System.currentTimeMillis());
String dtf = "dd/MM/yyyy";
SimpleDateFormat formatas = new SimpleDateFormat(dtf);
String data = formatas.format(dtAtual);
private void popularTabela() {
dtpAtual.setText(data);
listItens = FXCollections.observableArrayList(daoc.buscarTodos());
tbConferencia.getItems().clear();
columnId.setCellValueFactory(new PropertyValueFactory<>("Id"));
columnDtAgendamento.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Conferencia, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Conferencia, String> param) {
return new SimpleStringProperty(param.getValue().getAgendamento().getDataFormatada());
}
});
columnAmbiente.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Conferencia, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Conferencia, String> param) {
return new SimpleStringProperty(param.getValue().getAgendamento().getAmbiente().getDescricao());
}
});
columnInconsistencias.setCellValueFactory(new PropertyValueFactory<>("Inconsistencia"));
columnStatus.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<Conferencia, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Conferencia, String> param) {
if (param.getValue().getData() != null) {
return new SimpleStringProperty("Realizada");
} else {
return new SimpleStringProperty("Pendente");
}
}
});
tbConferencia.setItems(listItens);
}
public void detalhar(ActionEvent event) {
if (tbConferencia.getSelectionModel().isEmpty()) {
Mensagens.mostrarMsg6();
} else if (c != null && c.getData() != null ) {
try {
Stage stage = new Stage();
Parent root = FXMLLoader.load(getClass().getResource("/views/Detalhe_Conferencia.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.setTitle("Detalhe de Conferencia");
stage.getIcons().add(new Image("resource/imagens/hm.png"));
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
} else {
Mensagens.mostrarMsg18();
}
}
public void buscarSim() {
ObservableList<Conferencia> itensEncontrados = FXCollections.observableArrayList();
for (Conferencia c : listItens) {
if (c.getData() != null) {
itensEncontrados.add(c);
}
}
if (radioSim.isSelected()) {
tbConferencia.setItems(itensEncontrados);
}
}
public void buscarNao() {
ObservableList<Conferencia> itensEncontrados = FXCollections.observableArrayList();
for (Conferencia c : listItens) {
if (c.getData() == null) {
itensEncontrados.add(c);
}
}
if (radioNao.isSelected()) {
tbConferencia.setItems(itensEncontrados);
}
}
public void buscarTodas(ActionEvent e) {
popularTabela();
}
public void selectItem(MouseEvent event) {
if (tbConferencia.getFocusModel().getFocusedItem() != null) {
c = tbConferencia.getFocusModel().getFocusedItem();
}
}
public static Conferencia getConferencia() {
return c;
}
public void sair(ActionEvent event) {
ap.getScene().getWindow().hide();
}
}
| 27.597156
| 102
| 0.751503
|
6a86b6dbb9e99122018e2714477292231a545524
| 2,792
|
/*
* 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.geektimes.commons.reflect.util;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import java.util.function.Predicate;
import static org.geektimes.commons.function.Predicates.and;
import static org.geektimes.commons.reflect.util.ClassUtils.isFinal;
import static org.geektimes.commons.reflect.util.ClassUtils.*;
import static org.geektimes.commons.reflect.util.ConstructorUtils.hasNonPrivateConstructorWithoutParameters;
import static org.geektimes.commons.reflect.util.MemberUtils.*;
import static org.geektimes.commons.reflect.util.MethodUtils.OBJECT_METHOD_PREDICATE;
import static org.geektimes.commons.reflect.util.MethodUtils.getAllDeclaredMethods;
/**
* The utilities class for {@link Proxy Proxy}
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 1.0.0
*/
public abstract class ProxyUtils {
/**
* <ul>
* <li>class has a non-private constructor with no parameters</li>
* <li>class is not declared final</li>
* <li>class does not have non-static, final methods with public, protected or default visibility</li>
* <li>class is not primitive type</li>
* <li>class is not array type</li>
* </ul>
*
* @param type
* @return
*/
public static boolean isProxyable(Class<?> type) {
if (isArray(type)) {
return false;
}
if (isPrimitive(type)) {
return false;
}
if (isFinal(type)) {
return false;
}
if (!hasNonPrivateConstructorWithoutParameters(type)) {
return false;
}
Predicate<Method> predicate = and(NON_STATIC_METHOD_PREDICATE, FINAL_METHOD_PREDICATE,
NON_PRIVATE_METHOD_PREDICATE, OBJECT_METHOD_PREDICATE.negate());
Set<Method> methods = getAllDeclaredMethods(type, predicate);
if (!methods.isEmpty()) {
return false;
}
return true;
}
}
| 34.469136
| 110
| 0.694842
|
2ae6885f8de719f3deb5752d3315d3a6a8e92354
| 4,282
|
/*
* Power BI Client
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: v1.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package cl.cc.powerbi.client.model;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* A Power BI datasource connection details
*/
@ApiModel(description = "A Power BI datasource connection details")
@JsonPropertyOrder({ DatasourceConnectionDetails.JSON_PROPERTY_SERVER,
DatasourceConnectionDetails.JSON_PROPERTY_DATABASE, DatasourceConnectionDetails.JSON_PROPERTY_URL })
public class DatasourceConnectionDetails {
public static final String JSON_PROPERTY_SERVER = "server";
private String server;
public static final String JSON_PROPERTY_DATABASE = "database";
private String database;
public static final String JSON_PROPERTY_URL = "url";
private String url;
public DatasourceConnectionDetails server(String server) {
this.server = server;
return this;
}
/**
* The connection server
*
* @return server
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The connection server")
@JsonProperty(JSON_PROPERTY_SERVER)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getServer() {
return server;
}
public void setServer(String server) {
this.server = server;
}
public DatasourceConnectionDetails database(String database) {
this.database = database;
return this;
}
/**
* The connection database
*
* @return database
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The connection database")
@JsonProperty(JSON_PROPERTY_DATABASE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
public DatasourceConnectionDetails url(String url) {
this.url = url;
return this;
}
/**
* The connection url
*
* @return url
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The connection url")
@JsonProperty(JSON_PROPERTY_URL)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DatasourceConnectionDetails datasourceConnectionDetails = (DatasourceConnectionDetails) o;
return Objects.equals(this.server, datasourceConnectionDetails.server)
&& Objects.equals(this.database, datasourceConnectionDetails.database)
&& Objects.equals(this.url, datasourceConnectionDetails.url);
}
@Override
public int hashCode() {
return Objects.hash(server, database, url);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DatasourceConnectionDetails {\n");
sb.append(" server: ").append(toIndentedString(server)).append("\n");
sb.append(" database: ").append(toIndentedString(database)).append("\n");
sb.append(" url: ").append(toIndentedString(url)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 27.625806
| 109
| 0.659271
|
0abe06f5cbc0be78befb0ac18b0c8773f01a6d30
| 1,355
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.apex.malhar.contrib.couchbase;
import net.spy.memcached.internal.OperationFuture;
/**
* AbstractCouchBaseSetOperator which extends AbstractCouchBaseOutputOperator and implements set functionality of couchbase.
*
* @since 2.0.0
*/
public abstract class AbstractCouchBaseSetOperator<T> extends AbstractCouchBaseOutputOperator<T>
{
@Override
public OperationFuture<Boolean> processKeyValue(String key, Object value)
{
OperationFuture<Boolean> future = store.getInstance().set(key, value);
return future;
}
}
| 36.621622
| 124
| 0.765314
|
1056a375b775c0717308b1064e53e4e059b4f3f3
| 1,212
|
package cn.dsc.mapstruct.mapper;
import cn.dsc.mapstruct.consts.GenderEnum;
import cn.dsc.mapstruct.dto.SchoolDTO;
import cn.dsc.mapstruct.entity.School;
import cn.dsc.mapstruct.entity.User;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import org.junit.Test;
import java.math.BigDecimal;
import static org.junit.Assert.*;
/**
* @author dingshichen
*/
public class SchoolMapperTest {
@Test
public void schoolToSchoolDTO() {
User user1 = new User();
user1.setId(10);
user1.setName("dingshichen");
user1.setBalance(new BigDecimal("100"));
user1.setGender(GenderEnum.MAN);
user1.setGmtCreated(DateUtil.parse("2020-10-10"));
User user2 = new User();
user2.setId(15);
user2.setName("qiuping");
user2.setBalance(new BigDecimal("50"));
user2.setGender(GenderEnum.WOMAN);
user2.setGmtCreated(DateUtil.parse("2020-11-05"));
School school = new School();
school.setName("zhonghua");
school.setUsers(CollUtil.newArrayList(user1, user2));
SchoolDTO dto = SchoolMapper.INSTANCE.schoolToSchoolDTO(school);
System.out.println(dto);
}
}
| 28.186047
| 72
| 0.675743
|
abdc11b403a9e249b6923c7628dd75722c757b3b
| 2,909
|
/**
* 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 hello.controller;
import javax.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.stereotype.Controller;
import hello.model.Greeting;
import hello.model.HelloMessage;
import hello.model.Scoring;
@Controller
public class GreetingController {
private static final Logger log = LoggerFactory.getLogger(GreetingController.class);
@Autowired
private JmsTemplate jmsSender;
@Autowired
private SimpMessageSendingOperations simpSender;
@MessageMapping("/hello")
public Greeting greeting(HelloMessage message) {
final Greeting greeting = new Greeting("Hello, " + message.getName() + "!");
jmsSender.convertAndSend("request", greeting);
return greeting;
}
@MessageMapping("/score")
public Scoring scoring(HelloMessage message, SimpMessageHeaderAccessor accessor) {
final Scoring scoring = new Scoring(accessor.getSessionId(), "Score, " + message.getName() + "!");
jmsSender.convertAndSend("requestScore", scoring);
return scoring;
}
@JmsListener(destination = "response")
public void greeting(@Valid Greeting greeting) {
log.info("Received greeting {}", greeting.getContent());
simpSender.convertAndSend("/topic/greetings", new Greeting(greeting.getContent()));
}
private MessageHeaders createHeaders(String sessionId) {
SimpMessageHeaderAccessor headerAccessor = SimpMessageHeaderAccessor.create(SimpMessageType.MESSAGE);
headerAccessor.setSessionId(sessionId);
headerAccessor.setLeaveMutable(true);
return headerAccessor.getMessageHeaders();
}
@JmsListener(destination = "responseScore")
public void scoring(@Valid Scoring scoring) {
log.info("Received scoring {}", scoring.getContent());
simpSender.convertAndSendToUser(scoring.getSessionId(), "/topic/scoring", new Greeting(scoring.getContent()),
createHeaders(scoring.getSessionId()));
}
}
| 37.294872
| 111
| 0.789618
|
a6f189ac623430c6fe066330f83e26a8a4f2f49b
| 1,617
|
/*
* Copyright 2010-2016 Grzegorz Slowikowski
*
* 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.code.play.selenium.step;
import com.thoughtworks.selenium.CommandProcessor;
import com.google.code.play.selenium.StoredVars;
public abstract class AbstractSeleniumCommand
{
protected StoredVars storedVars;
protected CommandProcessor commandProcessor;
protected String command;
protected String param1;
protected String param2;
public AbstractSeleniumCommand( StoredVars storedVars, CommandProcessor commandProcessor, String command,
String param1 )
{
this.storedVars = storedVars;
this.commandProcessor = commandProcessor;
this.command = command;
this.param1 = param1;
this.param2 = "";
}
public AbstractSeleniumCommand( StoredVars storedVars, CommandProcessor commandProcessor, String command,
String param1, String param2 )
{
this( storedVars, commandProcessor, command, param1 );
this.param2 = param2;
}
}
| 29.944444
| 109
| 0.703154
|
ce9f6e0e0b9604d8adc9a1223555c16f4fdad486
| 2,209
|
/*
* =============================================================================
*
* Copyright (c) 2011-2018, The THYMELEAF team (http://www.thymeleaf.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* =============================================================================
*/
package org.thymeleaf.templateresolver;
import java.util.Map;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.templateresource.ITemplateResource;
import org.thymeleaf.templateresource.WebApplicationTemplateResource;
import org.thymeleaf.util.Validate;
import org.thymeleaf.web.IWebApplication;
/**
* <p>
* Implementation of {@link ITemplateResolver} that extends {@link AbstractConfigurableTemplateResolver}
* and creates {@link WebApplicationTemplateResource} instances for template resources.
* </p>
*
* @author Daniel Fernández
*
* @since 3.1.0
*
*/
public class WebApplicationTemplateResolver extends AbstractConfigurableTemplateResolver {
private final IWebApplication webApplication;
public WebApplicationTemplateResolver(final IWebApplication webApplication) {
super();
Validate.notNull(webApplication, "Web Application object cannot be null");
this.webApplication = webApplication;
}
@Override
protected ITemplateResource computeTemplateResource(
final IEngineConfiguration configuration, final String ownerTemplate, final String template, final String resourceName, final String characterEncoding, final Map<String, Object> templateResolutionAttributes) {
return new WebApplicationTemplateResource(this.webApplication, resourceName, characterEncoding);
}
}
| 35.629032
| 221
| 0.703033
|
a0ea45374cd724b26e62b48b2d087eda20384812
| 767
|
package ru.linachan.nemesis;
import org.json.simple.JSONObject;
public class NemesisApproval {
private NemesisApprovalType type;
private String description;
private Integer value;
public NemesisApproval(JSONObject approvalData) {
type = NemesisApprovalType.getApprovalType((String) approvalData.get("type"));
description = (String) approvalData.get("description");
value = Integer.valueOf((String) approvalData.get("value"));
}
public NemesisApprovalType getType() {
return type;
}
public String getDescription() {
return description;
}
public Integer getValue() {
return value;
}
public String toString() {
return type.toString() + ": " + value;
}
}
| 23.242424
| 86
| 0.659713
|
77c3d8fe6e338252ddd6a8319e76d93a7ced9911
| 460
|
package com.okx.domain.market;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
/**
* Market orderbook.
*/
@NoArgsConstructor
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class OrderBook {
private List<Order> asks;
private List<Order> bids;
@JsonProperty("ts")
private Long time;
}
| 19.166667
| 61
| 0.765217
|
c60b1cf5986b937e50d7a749b2da1810d854ff86
| 511
|
/**
*
*/
package org.wertx.path;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import io.vertx.core.http.HttpMethod;
@Retention(RUNTIME)
@Target(ElementType.METHOD)
/**
* @author 瞿建军 Email: jianjun.qu@istuary.com
* 2017年2月10日
*/
public @interface Path {
HttpMethod method();
String path();
boolean auth() default true;
String permit() default "";
}
| 15.484848
| 59
| 0.720157
|
2addd8f915c1c5df2b50aafc93081f16a2f3fc89
| 1,728
|
package com.example.jokeviewer;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.example.jokeviewer.util.Constants;
public class JokeActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_joke);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("Jokes");
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
}
Intent intent = getIntent();
if (intent != null) {
String jokeDescription = intent.getStringExtra(Constants.EXTRA_JOKE_DESCRIPTION);
String jokeCategory = intent.getStringExtra(Constants.EXTRA_JOKE_CATEGORY);
showJoke(jokeCategory, jokeDescription);
} else {
Toast.makeText(this, R.string.msg_no_joke_found, Toast.LENGTH_SHORT).show();
finish();
}
}
private void showJoke(String jokeCategory, String jokeDescription) {
((TextView) findViewById(R.id.text_joke_category)).setText(getString(R.string.joke_category, jokeCategory));
((TextView) findViewById(R.id.text_joke)).setText(jokeDescription);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
| 33.882353
| 116
| 0.689236
|
66b7be6e48d3552870a311ee412c9158e6b36b95
| 2,200
|
package org.haiku.haikudepotserver.dataobjects.auto;
import java.util.Map;
import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.QueryResult;
import org.apache.cayenne.query.MappedExec;
/**
* This class was generated by Cayenne.
* It is probably a good idea to avoid changing this class manually,
* since it may be overwritten next time code is regenerated.
* If you need to make any customizations, please use subclass.
*/
public class _HaikuDepot {
public static final String PKG_VERSION_LOCALIZATION_RESOLUTION_QUERYNAME = "PkgVersionLocalizationResolution";
public static final String ALL_PKG_ICONS_QUERYNAME = "AllPkgIcons";
public static final String ALL_PKG_SCREENSHOTS_QUERYNAME = "AllPkgScreenshots";
public static final String PKG_NAMES_FOR_REPOSITORY_SOURCE_QUERYNAME = "PkgNamesForRepositorySource";
public static final String SEARCH_PKG_VERSIONS_QUERYNAME = "SearchPkgVersions";
public QueryResult<?> performPkgVersionLocalizationResolution(ObjectContext context, Map<String, ?> parameters) {
MappedExec query = MappedExec.query(PKG_VERSION_LOCALIZATION_RESOLUTION_QUERYNAME).params(parameters);
return query.execute(context);
}
public QueryResult<?> performAllPkgIcons(ObjectContext context, Map<String, ?> parameters) {
MappedExec query = MappedExec.query(ALL_PKG_ICONS_QUERYNAME).params(parameters);
return query.execute(context);
}
public QueryResult<?> performAllPkgScreenshots(ObjectContext context, Map<String, ?> parameters) {
MappedExec query = MappedExec.query(ALL_PKG_SCREENSHOTS_QUERYNAME).params(parameters);
return query.execute(context);
}
public QueryResult<?> performPkgNamesForRepositorySource(ObjectContext context, Map<String, ?> parameters) {
MappedExec query = MappedExec.query(PKG_NAMES_FOR_REPOSITORY_SOURCE_QUERYNAME).params(parameters);
return query.execute(context);
}
public QueryResult<?> performSearchPkgVersions(ObjectContext context, Map<String, ?> parameters) {
MappedExec query = MappedExec.query(SEARCH_PKG_VERSIONS_QUERYNAME).params(parameters);
return query.execute(context);
}
}
| 43.137255
| 117
| 0.771364
|
1266078627f814801b61d3d6c1b836c1c6f2db62
| 7,251
|
package org.jtrim2.executor;
import java.util.Objects;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import org.jtrim2.cancel.Cancellation;
import org.jtrim2.cancel.CancellationToken;
import org.jtrim2.concurrent.AsyncTasks;
/**
* Executes tasks at some time in the future. This interface defines a more
* robust way to execute tasks than {@code java.util.concurrent.Executor}.
* That is, this interface defines a simpler way for canceling tasks and allows
* to continue after the completion of the submitted task via a {@link CompletionStage}.
* It is possible to continue execution regardless how the submitted task completed
* (success, failure or canceled).
* For more control over the life of a {@code TaskExecutor}, see the extending
* {@link TaskExecutorService} interface.
*
* <h2>Thread safety</h2>
* Implementations of this interface are required to be safely accessible from
* multiple threads concurrently.
*
* <h3>Synchronization transparency</h3>
* The methods of this interface are not required to be
* <I>synchronization transparent</I> because they may execute tasks, handlers added
* to {@code CompletionStage}, etc.
*
* @see CancelableTask
* @see TaskExecutorService
* @see TaskExecutors#upgradeToStoppable(TaskExecutor)
*/
public interface TaskExecutor extends Executor {
/**
* Executes the function at some time in the future. When and on
* what thread, the function is to be executed is completely implementation
* dependent. Implementations may choose to execute tasks later on a
* separate thread or synchronously in the calling thread at the discretion
* of the implementation.
*
* @param <V> the type of the result of the submitted function
* @param cancelToken the {@code CancellationToken} which is to be checked
* if the submitted task is to be canceled. If this
* {@code CancellationToken} signals a cancellation request, this
* {@code TaskExecutor} may choose to not even attempt to execute the
* submitted task. This argument may not be {@code null}. When the task cannot be
* canceled, use the static {@link org.jtrim2.cancel.Cancellation#UNCANCELABLE_TOKEN}
* for this argument (even in this case, the {@code TaskExecutor} may be able to
* cancel the task, if it was not submitted for execution).
* @param function the function to be executed by this {@code TaskExecutor}. This
* argument cannot be {@code null}.
* @return the {@code CompletionStage} which can be used to execute tasks
* after the completion of the submitted function and process the result of
* the submitted function. This method never returns {@code null}.
*
* @throws NullPointerException thrown if the {@code CancellationToken}
* or the task is {@code null}
*
* @see org.jtrim2.cancel.Cancellation#createCancellationSource()
* @see org.jtrim2.cancel.Cancellation#UNCANCELABLE_TOKEN
*/
public <V> CompletionStage<V> executeFunction(
CancellationToken cancelToken,
CancelableFunction<? extends V> function);
/**
* Executes the task at some time in the future. When and on what thread, the task is
* to be executed is completely implementation dependent. Implementations may
* choose to execute tasks later on a separate thread or synchronously in the
* calling thread at the discretion of the implementation.
*
* @param cancelToken the {@code CancellationToken} which is to be checked
* if the submitted task is to be canceled. If this
* {@code CancellationToken} signals a cancellation request, this
* {@code TaskExecutor} may choose to not even attempt to execute the
* submitted task. This argument may not be {@code null}. When the task cannot be
* canceled, use the static {@link org.jtrim2.cancel.Cancellation#UNCANCELABLE_TOKEN}
* for this argument (even in this case, the {@code TaskExecutor} may be able to
* cancel the task, if it was not submitted for execution).
* @param task the task to be executed by this {@code TaskExecutor}. This
* argument cannot be {@code null}.
* @return the {@code CompletionStage} which can be used to execute tasks
* after the completion of the submitted task. This method never returns {@code null}.
*
* @throws NullPointerException thrown if the {@code CancellationToken}
* or the task is {@code null}
*
* @see org.jtrim2.cancel.Cancellation#createCancellationSource()
* @see org.jtrim2.cancel.Cancellation#UNCANCELABLE_TOKEN
*/
public default CompletionStage<Void> execute(CancellationToken cancelToken, CancelableTask task) {
Objects.requireNonNull(task, "task");
return executeFunction(cancelToken, (taskCancelToken) -> {
task.execute(taskCancelToken);
return null;
});
}
/**
* Executes an non-cancelable task at some time in the future. When and on what thread,
* the task is to be executed is completely implementation dependent. Implementations may
* choose to execute tasks later on a separate thread or synchronously in the
* calling thread at the discretion of the implementation.
* <P>
* Note that although the task itself is not cancelable explicitly, the executor might cancel
* it by not executing the submitted task. For example, due to a call to the
* {@link TaskExecutorService#shutdownAndCancel() shutdownAndCancel} method of
* {@link TaskExecutorService}.
* <P>
* The default implementation delegates the call to
* {@link #execute(CancellationToken, CancelableTask) execute(CancellationToken, CancelableTask)}.
*
* @param task the task to be executed by this {@code TaskExecutor}. This
* argument cannot be {@code null}.
* @return the {@code CompletionStage} which can be used to execute tasks
* after the completion of the submitted task. This method never returns {@code null}.
*
* @throws NullPointerException thrown if the task is {@code null}
*
* @see org.jtrim2.cancel.Cancellation#createCancellationSource()
* @see org.jtrim2.cancel.Cancellation#UNCANCELABLE_TOKEN
*/
public default CompletionStage<Void> executeStaged(Runnable task) {
Objects.requireNonNull(task, "command");
return execute(Cancellation.UNCANCELABLE_TOKEN, (cancelToken) -> task.run());
}
/**
* {@inheritDoc }
* <P>
* Note that although the task itself is not cancelable explicitly, the executor might cancel
* it by not executing the submitted task. For example, due to a call to the
* {@link TaskExecutorService#shutdownAndCancel() shutdownAndCancel} method of
* {@link TaskExecutorService}.
* <P>
* The default implementation delegates the call to {@link #executeStaged(Runnable) executeStaged} and
* logs uncaught errors thrown by the submitted task.
*/
@Override
public default void execute(Runnable command) {
Objects.requireNonNull(command, "command");
executeStaged(command).exceptionally(AsyncTasks::expectNoError);
}
}
| 50.006897
| 106
| 0.710523
|
6d390ecf5d349373e75d0291bd4df6a052a18827
| 105
|
package com.eyft.server.model;
public enum PropOrderStatus {
ORDERED,
ACCEPTED,
DELIVERED
}
| 13.125
| 30
| 0.704762
|
13c5b70ab92435bd5059ef3e804de99c4d15b20a
| 269
|
package uk.gov.hmcts.reform.bulkscan.payment.processor.service.servicebus.exceptions;
public class UnknownMessageProcessingResultException extends RuntimeException {
public UnknownMessageProcessingResultException(String message) {
super(message);
}
}
| 29.888889
| 85
| 0.806691
|
316b46892d78685439716ea9b29872ab0eaf5059
| 11,523
|
package com.moemoe.lalala.presenter;
import android.text.TextUtils;
import com.moemoe.lalala.app.AppSetting;
import com.moemoe.lalala.greendao.gen.AuthorInfoDao;
import com.moemoe.lalala.model.api.ApiService;
import com.moemoe.lalala.model.api.NetResultSubscriber;
import com.moemoe.lalala.model.api.NetSimpleResultSubscriber;
import com.moemoe.lalala.model.entity.AuthorInfo;
import com.moemoe.lalala.model.entity.CodeEntity;
import com.moemoe.lalala.model.entity.CommentDetailEntity;
import com.moemoe.lalala.model.entity.CommentDetailRqEntity;
import com.moemoe.lalala.model.entity.LoginEntity;
import com.moemoe.lalala.model.entity.LoginResultEntity;
import com.moemoe.lalala.model.entity.SplashEntity;
import com.moemoe.lalala.model.entity.ThirdLoginEntity;
import com.moemoe.lalala.utils.GreenDaoManager;
import com.moemoe.lalala.utils.PreferenceUtils;
import com.moemoe.lalala.utils.StringUtils;
import com.moemoe.lalala.utils.retrofit.RetrofitUrlManager;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import javax.inject.Inject;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.HttpUrl;
/**
*
* Created by yi on 2016/11/29.
*/
public class SimplePresenter implements SimpleContract.Presenter {
private SimpleContract.View view;
private ApiService apiService;
@Inject
public SimplePresenter(SimpleContract.View view, ApiService apiService) {
this.view = view;
this.apiService = apiService;
}
@Override
public void doRequest(final Object data, int type) {
if (type == 0){//find pwd
CodeEntity entity = new CodeEntity();
entity.mobile = (String) data;
apiService.requestCode4ResetPwd(entity)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NetSimpleResultSubscriber() {
@Override
public void onSuccess() {
if(view != null) view.onSuccess(null);
}
@Override
public void onFail(int code,String msg) {
if(view != null) view.onFailure(code,msg);
}
});
}else if(type == 1){//register
CodeEntity entity = new CodeEntity();
entity.mobile = (String) data;
apiService.requestRegisterCode(entity)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NetSimpleResultSubscriber() {
@Override
public void onSuccess() {
if(view != null) view.onSuccess(null);
}
@Override
public void onFail(int code,String msg) {
if(view != null) view.onFailure(code,msg);
}
});
}else if(type == 4){
AuthorInfoDao dao = GreenDaoManager.getInstance().getSession().getAuthorInfoDao();
AuthorInfo info = dao.load((long) 1);
if(info == null) {
info = new AuthorInfo();
}else {
PreferenceUtils.setAuthorInfo(info);
}
if(StringUtils.isThirdParty(info.getPlatform())){
//三方登录
ThirdLoginEntity bean = new ThirdLoginEntity(info.getUserName(),info.getOpenId(),StringUtils.convertPlatform(info.getPlatform()), (String) data);
final AuthorInfo finalInfo1 = info;
apiService.loginThird(bean)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NetResultSubscriber<LoginResultEntity>() {
@Override
public void onSuccess(LoginResultEntity entity) {
finalInfo1.setToken(entity.getToken());
finalInfo1.setUserId(entity.getUserId());
finalInfo1.setCoin(entity.getCoin());
finalInfo1.setUserName(entity.getUserName());
finalInfo1.setRcToken(entity.getRcToken());
finalInfo1.setLevel(entity.getLevel());
finalInfo1.setOpenBag(entity.isOpenBag());
if(!TextUtils.isEmpty(entity.getVipTime())){
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date date = format.parse(entity.getVipTime());
Date now = new Date();
if(date.before(now)){
finalInfo1.setVipTime("");
}else {
finalInfo1.setVipTime(entity.getVipTime());
}
} catch (ParseException e) {
e.printStackTrace();
}
}else {
finalInfo1.setVipTime("");
}
finalInfo1.setInspector(entity.isInspector());
finalInfo1.setInviteNum(entity.getInviteNum());
finalInfo1.setDeskMateEntities(entity.getDeskMateList());
PreferenceUtils.setAuthorInfo(finalInfo1);
if(view != null) view.onSuccess(entity);
}
@Override
public void onFail(int code,String msg) {
PreferenceUtils.clearAuthorInfo();
if(view != null) view.onFailure(code,msg);
}
});
}else {
//自有登录
LoginEntity bean = new LoginEntity(info.getPhone(),info.getPassword(), (String) data);
final AuthorInfo finalInfo = info;
apiService.login(bean)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NetResultSubscriber<LoginResultEntity>() {
@Override
public void onSuccess(LoginResultEntity entity) {
finalInfo.setToken(entity.getToken());
finalInfo.setUserId(entity.getUserId());
finalInfo.setCoin(entity.getCoin());
finalInfo.setUserName(entity.getUserName());
finalInfo.setRcToken(entity.getRcToken());
finalInfo.setLevel(entity.getLevel());
finalInfo.setOpenBag(entity.isOpenBag());
if(!TextUtils.isEmpty(entity.getVipTime())){
try {
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
Date date = format.parse(entity.getVipTime());
Date now = new Date();
if(date.before(now)){
finalInfo.setVipTime("");
}else {
finalInfo.setVipTime(entity.getVipTime());
}
} catch (ParseException e) {
e.printStackTrace();
}
}else {
finalInfo.setVipTime("");
}
finalInfo.setInspector(entity.isInspector());
finalInfo.setInviteNum(entity.getInviteNum());
finalInfo.setDeskMateEntities(entity.getDeskMateList());
PreferenceUtils.setAuthorInfo(finalInfo);
if(view != null) view.onSuccess(entity);
}
@Override
public void onFail(int code,String msg) {
PreferenceUtils.clearAuthorInfo();
if(view != null) view.onFailure(code,msg);
}
});
}
}else if(type == 8){
apiService.getCommentDetail((CommentDetailRqEntity) data)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NetResultSubscriber<CommentDetailEntity>() {
@Override
public void onSuccess(CommentDetailEntity commentDetailEntity) {
if(view != null) view.onSuccess(commentDetailEntity);
}
@Override
public void onFail(int code, String msg) {
if(view != null) view.onFailure(code,msg);
}
});
}else if(type == 9){
apiService.saveLive2d((String) data)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new NetSimpleResultSubscriber() {
@Override
public void onSuccess() {
}
@Override
public void onFail(int code, String msg) {
}
});
}else if(type == 10){
apiService.checkTxbb()
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(new NetResultSubscriber<Boolean>() {
@Override
public void onSuccess(Boolean aBoolean) {
AppSetting.TXBB = aBoolean;
// if(!aBoolean){
// RetrofitUrlManager.getInstance().setGlobalDomain("http://pgbb.moemoe.la/");
// }else {
// RetrofitUrlManager.getInstance().setGlobalDomain("http://2333.moemoe.la/");
// }
}
@Override
public void onFail(int code, String msg) {
}
});
}
}
@Override
public void release() {
view = null;
}
}
| 46.277108
| 161
| 0.467239
|
88326590a4f1d9fd203b8328f8e12a82359a72ed
| 1,894
|
package com.burakyildiz.springboot.business.mapping;
import com.burakyildiz.springboot.entities.concretes.User;
import com.burakyildiz.springboot.entities.dtos.UserDto;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.processing.Generated;
@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2021-12-21T14:58:52+0300",
comments = "version: 1.4.2.Final, compiler: javac, environment: Java 17.0.1 (Oracle Corporation)"
)
public class UserMapperImpl implements UserMapper {
@Override
public List<UserDto> convertAllUserListToUserDtoList(List<User> userList) {
if ( userList == null ) {
return null;
}
List<UserDto> list = new ArrayList<UserDto>( userList.size() );
for ( User user : userList ) {
list.add( convertUserToUserDto( user ) );
}
return list;
}
@Override
public User convertUserDtoToUser(UserDto userDto) {
if ( userDto == null ) {
return null;
}
User user = new User();
user.setPhoneNumber( userDto.getPhoneNumber() );
user.setEmail( userDto.getEmail() );
user.setId( userDto.getId() );
user.setFirstName( userDto.getFirstName() );
user.setLastName( userDto.getLastName() );
user.setUserName( userDto.getUserName() );
return user;
}
@Override
public UserDto convertUserToUserDto(User user) {
if ( user == null ) {
return null;
}
UserDto userDto = new UserDto();
userDto.setPhoneNumber( user.getPhoneNumber() );
userDto.setEmail( user.getEmail() );
userDto.setId( user.getId() );
userDto.setFirstName( user.getFirstName() );
userDto.setLastName( user.getLastName() );
userDto.setUserName( user.getUserName() );
return userDto;
}
}
| 28.69697
| 101
| 0.63094
|
6b4d0815b22e26c795844bc78bc84e2342b8a606
| 4,240
|
package org.jointheleague.graphical.robot.curves;
import org.jointheleague.graphical.robot.Robot;
import java.awt.*;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
/**
* A Path that is followed by a Robot. Only the part of the path from
* the path's start to the robot's current position is drawn.
*/
final public class DynamicPath implements Drawable {
private Segment currentSegment;
private Path2D currentPath = new Path2D.Float();
private float time = 0F;
private final PathIterator pathIterator;
private Robot.Pos startingPoint;
private final int lineSize;
private final Color color;
private final Robot robot;
private final boolean fill;
/**
* Constructor
*
* @param pathIterator a PathIterator describing the path
* @param lineSize the line width used to draw the path.
* @param color the color used to draw the path
* @param robot a Robot that moves along the path
* @param fill if set to true, fill path else draw the outline
*/
public DynamicPath(PathIterator pathIterator, int lineSize, Color color, Robot robot, boolean fill) {
this.pathIterator = pathIterator;
this.lineSize = lineSize;
this.color = color;
this.robot = robot;
this.fill = fill;
currentSegment = getCurrentSegment();
assert currentSegment != null;
double startAngle = currentSegment.getStartAngle();
if (!Double.isNaN(startAngle)) robot.turnTo(Math.toDegrees(startAngle));
}
private Segment getCurrentSegment() {
assert !pathIterator.isDone();
float[] coordinates = new float[6];
float x = robot.getX();
float y = robot.getY();
int type = pathIterator.currentSegment(coordinates);
switch (type) {
case PathIterator.SEG_MOVETO:
startingPoint = new Robot.Pos(coordinates[0], coordinates[1]);
return new Move(x, y, coordinates);
case PathIterator.SEG_LINETO:
return new Line(x, y, coordinates, 0, null);
case PathIterator.SEG_QUADTO:
return new Quad(x, y, coordinates, 0, null);
case PathIterator.SEG_CUBICTO:
return new Cubic(x, y, coordinates, 0, null);
case PathIterator.SEG_CLOSE:
coordinates[0] = startingPoint.getX();
coordinates[1] = startingPoint.getY();
return new Close(x, y, coordinates, 0, null);
default:
return null;
}
}
/**
* Moves the robot forward on the path by an increment that
* is proportional to the speed.
*
* @param speed a double value that specifies the increment
*/
public void incrementTime(double speed) {
time += speed / currentSegment.getSize();
Robot.Pos pos = currentSegment.getPos(time);
robot.setPos(pos.getX(), pos.getY());
double angle = currentSegment.getAngle(time);
if (!Double.isNaN(angle)) robot.setAngle(Math.toDegrees(angle));
if (time >= 1F) {
currentSegment.addTo(currentPath);
pathIterator.next();
if (!pathIterator.isDone()) {
currentSegment = getCurrentSegment();
assert currentSegment != null;
double startAngle = currentSegment.getStartAngle();
if (!Double.isNaN(startAngle)) robot.turnTo(Math.toDegrees(startAngle));
time = 0F;
}
}
}
/**
* @return true if the robot has reached the end of the path.
*/
public boolean isComplete() {
return pathIterator.isDone();
}
private Path2D getPath2D() {
if (0.0 < time && time < 1.0) {
Path2D path = new Path2D.Float(currentPath);
return currentSegment.addTo(path, time);
} else {
return currentPath;
}
}
@Override
public void draw(Graphics2D g2) {
g2.setStroke(new BasicStroke(lineSize));
g2.setColor(color);
if (fill) {
g2.fill(getPath2D());
} else {
g2.draw(getPath2D());
}
}
}
| 34.471545
| 105
| 0.599764
|
0a72d0f1b5475c252853e82e0ed4241e1b43616a
| 2,883
|
/**
* SqlJetIndexedColumn.java
* Copyright (C) 2009-2010 TMate Software Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package org.tmatesoft.sqljet.core.internal.schema;
import org.antlr.runtime.tree.CommonTree;
import org.tmatesoft.sqljet.core.schema.ISqlJetColumnDef;
import org.tmatesoft.sqljet.core.schema.ISqlJetIndexedColumn;
import org.tmatesoft.sqljet.core.schema.SqlJetSortingOrder;
/**
* @author TMate Software Ltd.
* @author Dmitry Stadnik (dtrace@seznam.cz)
*/
public class SqlJetIndexedColumn implements ISqlJetIndexedColumn {
private final String name;
private final String collation;
private final SqlJetSortingOrder sortingOrder;
private ISqlJetColumnDef tableColumn;
public SqlJetIndexedColumn(CommonTree ast) {
name = ast.getText();
String collation = null;
SqlJetSortingOrder sortingOrder = null;
for (int i = 0; i < ast.getChildCount(); i++) {
CommonTree child = (CommonTree) ast.getChild(i);
if ("collate".equalsIgnoreCase(child.getText())) {
collation = child.getChild(0).getText();
} else if ("asc".equalsIgnoreCase(child.getText())) {
sortingOrder = SqlJetSortingOrder.ASC;
} else if ("desc".equalsIgnoreCase(child.getText())) {
sortingOrder = SqlJetSortingOrder.DESC;
} else {
assert false;
}
}
this.collation = collation;
this.sortingOrder = sortingOrder;
}
public String getName() {
return name;
}
public String getCollation() {
return collation;
}
public SqlJetSortingOrder getSortingOrder() {
return sortingOrder;
}
@Override
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getName());
if (getCollation() != null) {
buffer.append(" COLLATE ");
buffer.append(getCollation());
}
if (getSortingOrder() != null) {
buffer.append(' ');
buffer.append(getSortingOrder());
}
return buffer.toString();
}
/**
* @param tableColumn the tableColumn to set
*/
public void setTableColumn(ISqlJetColumnDef tableColumn) {
this.tableColumn = tableColumn;
}
/**
* @return the tableColumn
*/
public ISqlJetColumnDef getTableColumn() {
return tableColumn;
}
}
| 30.670213
| 71
| 0.642386
|
6131a337696a9b098bae87546804d33104b48878
| 2,486
|
package org.motechproject.tasks.domain;
import org.apache.commons.lang.ArrayUtils;
import org.codehaus.jackson.annotate.JsonValue;
import static org.apache.commons.lang.StringUtils.isNotBlank;
/**
* Defines the type of various manipulations used in a task for both triggers and data sources.
*/
public enum ManipulationType {
TOLOWER("toLower", ManipulationTarget.STRING),
TOUPPER("toUpper", ManipulationTarget.STRING),
CAPITALIZE("capitalize", ManipulationTarget.STRING),
JOIN("join", ManipulationTarget.STRING),
FORMAT("format", ManipulationTarget.STRING),
SUBSTRING("substring", ManipulationTarget.STRING),
SPLIT("split", ManipulationTarget.STRING),
DATETIME("dateTime", ManipulationTarget.DATE, ManipulationTarget.DATE),
PLUSDAYS("plusDays", ManipulationTarget.DATE),
UNKNOWN("unknown", ManipulationTarget.ALL);
private final String value;
private final ManipulationTarget target;
private ManipulationTarget[] forbiddenResultTypes;
public Object parse(String value) {
return value;
}
@JsonValue
public String getValue() {
return value;
}
@JsonValue
public ManipulationTarget getTarget() {
return target;
}
private ManipulationType(String value, ManipulationTarget target, ManipulationTarget ... forbiddenResultTypes) {
this.value = value;
this.target = target;
this.forbiddenResultTypes = forbiddenResultTypes;
}
private ManipulationType(String value, ManipulationTarget target) {
this.value = value;
this.target = target;
this.forbiddenResultTypes = new ManipulationTarget[0];
}
public static ManipulationType fromString(String string) {
ManipulationType result = null;
if (isNotBlank(string)) {
for (ManipulationType level : ManipulationType.values()) {
if (level.getValue().equalsIgnoreCase(string)) {
result = level;
break;
}
}
}
if (result == null) {
result = ManipulationType.UNKNOWN;
}
return result;
}
public boolean allowResultType(ManipulationTarget resultType) {
if (ArrayUtils.contains(forbiddenResultTypes, ManipulationTarget.ALL)) {
return false;
}
if (ArrayUtils.contains(forbiddenResultTypes, resultType)) {
return false;
}
return true;
}
}
| 29.951807
| 116
| 0.663315
|
f0ceb57b97d0f3e38d6ef78b8bfcdfefb42b53b1
| 1,108
|
package de.metas.inoutcandidate.api;
import javax.annotation.Nullable;
import org.adempiere.util.lang.IContextAware;
import de.metas.inout.model.I_M_InOutLine;
import de.metas.inoutcandidate.api.impl.ReceiptScheduleAllocBuilder;
import de.metas.inoutcandidate.model.I_M_ReceiptSchedule;
import de.metas.inoutcandidate.model.I_M_ReceiptSchedule_Alloc;
import de.metas.quantity.StockQtyAndUOMQty;
public interface IReceiptScheduleAllocBuilder
{
I_M_ReceiptSchedule_Alloc build();
I_M_ReceiptSchedule_Alloc buildAndSave();
ReceiptScheduleAllocBuilder setContext(IContextAware context);
IReceiptScheduleAllocBuilder setM_ReceiptSchedule(I_M_ReceiptSchedule receiptSchedule);
IReceiptScheduleAllocBuilder setQtyToAllocate(StockQtyAndUOMQty qtyToAllocate);
ReceiptScheduleAllocBuilder setQtyWithIssues(StockQtyAndUOMQty qtyWithIssues);
/**
* @param receiptLine can be {@code null} because M_ReceiptSchedule_Alloc are also used to allocate a HU to a receipt schedule even *before* there is any inOutLine.
*/
IReceiptScheduleAllocBuilder setM_InOutLine(@Nullable I_M_InOutLine receiptLine);
}
| 33.575758
| 165
| 0.850181
|
2c4871a3021ab3dd403e6109189649a7fe27cc86
| 741
|
package com.something.spring.integration.service.impl;
import com.something.spring.integration.pojo.User;
import com.something.spring.integration.service.ReserviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
/**
* @author cWww
* @Title
* @Description
* @date: 2018/9/6 17:27
*/
@Service("reserviceServiceImpl")
public class ReserviceServiceImpl implements ReserviceService {
private static final Logger LOGGER = LoggerFactory.getLogger(ReserviceServiceImpl.class);
@Override
public String sayHello(User user) {
LOGGER.info("user,{},{}",user.getUsername(),user.getPassword());
return user.getUsername()+":"+user.getPassword();
}
}
| 27.444444
| 93
| 0.746289
|
fc5f24302fffe85242d2cd764c92666fa31c3737
| 439
|
package de.lemona.android.guice.providers.system;
import com.google.inject.Inject;
import android.content.Context;
import android.os.PowerManager;
import de.lemona.android.guice.ContextSingleton;
@ContextSingleton
public class PowerManagerProvider extends AbstractServiceProvider<PowerManager> {
@Inject
public PowerManagerProvider(Context context) {
super(Context.POWER_SERVICE, PowerManager.class, context);
}
}
| 24.388889
| 81
| 0.794989
|
8c71f9a3153634cab449f483c3f2c9f13054914d
| 1,927
|
package io.github.henryssondaniel.teacup.protocol.http.server;
import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.Filter;
import io.github.henryssondaniel.teacup.core.logging.Factory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
class ContextImpl implements ContextSetter {
private static final Logger LOGGER = Factory.getLogger(ContextImpl.class);
private final Map<String, Object> attributes = new HashMap<>(0);
private final Collection<Filter> filters = new LinkedList<>();
private final String path;
private final Response response;
private Authenticator authenticator;
ContextImpl(String path, Response response) {
this.path = path;
this.response = response;
}
@Override
public Map<String, Object> getAttributes() {
LOGGER.log(Level.FINE, "Returns the attributes");
return new HashMap<>(attributes);
}
@Override
public Authenticator getAuthenticator() {
return authenticator;
}
@Override
public List<Filter> getFilters() {
LOGGER.log(Level.FINE, "Returns the filters");
return new ArrayList<>(filters);
}
@Override
public String getPath() {
return path;
}
@Override
public Response getResponse() {
return response;
}
@Override
public void setAttributes(Map<String, Object> attributes) {
LOGGER.log(Level.FINE, "Setting the attributes");
this.attributes.clear();
this.attributes.putAll(attributes);
}
@Override
public void setAuthenticator(Authenticator authenticator) {
this.authenticator = authenticator;
}
@Override
public void setFilters(List<? extends Filter> filters) {
LOGGER.log(Level.FINE, "Setting the filters");
this.filters.clear();
this.filters.addAll(filters);
}
}
| 24.705128
| 76
| 0.732226
|
65a561aea8c5e58e750fe2e9c6ad9d648a30cc5c
| 5,051
|
package com.voxelgameslib.voxelgameslib.components.elo;
import javax.annotation.Nonnull;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import jskills.Rating;
@Entity
@Table(name = "rating")
public class RatingWrapper {
@Id
@GeneratedValue
private int id;
private double conservativeStandardDeviationMultiplier;
private double mean;
private double standardDeviation;
private double conservativeRating;
public RatingWrapper(double conservativeStandardDeviationMultiplier, double mean, double standardDeviation, double conservativeRating) {
this.conservativeStandardDeviationMultiplier = conservativeStandardDeviationMultiplier;
this.mean = mean;
this.standardDeviation = standardDeviation;
this.conservativeRating = conservativeRating;
}
protected RatingWrapper() {
//JPA
}
public RatingWrapper(@Nonnull Rating rating) {
this(rating.getConservativeStandardDeviationMultiplier(), rating.getMean(), rating.getStandardDeviation(), rating.getConservativeRating());
}
@java.beans.ConstructorProperties({"id", "conservativeStandardDeviationMultiplier", "mean", "standardDeviation", "conservativeRating"})
public RatingWrapper(int id, double conservativeStandardDeviationMultiplier, double mean, double standardDeviation, double conservativeRating) {
this.id = id;
this.conservativeStandardDeviationMultiplier = conservativeStandardDeviationMultiplier;
this.mean = mean;
this.standardDeviation = standardDeviation;
this.conservativeRating = conservativeRating;
}
@Nonnull
public Rating toRating() {
return new Rating(getMean(), getStandardDeviation(), getConservativeStandardDeviationMultiplier());
}
public int getId() {
return this.id;
}
public double getConservativeStandardDeviationMultiplier() {
return this.conservativeStandardDeviationMultiplier;
}
public double getMean() {
return this.mean;
}
public double getStandardDeviation() {
return this.standardDeviation;
}
public double getConservativeRating() {
return this.conservativeRating;
}
public void setId(int id) {
this.id = id;
}
public void setConservativeStandardDeviationMultiplier(double conservativeStandardDeviationMultiplier) {
this.conservativeStandardDeviationMultiplier = conservativeStandardDeviationMultiplier;
}
public void setMean(double mean) {
this.mean = mean;
}
public void setStandardDeviation(double standardDeviation) {
this.standardDeviation = standardDeviation;
}
public void setConservativeRating(double conservativeRating) {
this.conservativeRating = conservativeRating;
}
public boolean equals(Object o) {
if (o == this) return true;
if (!(o instanceof RatingWrapper)) return false;
final RatingWrapper other = (RatingWrapper) o;
if (!other.canEqual((Object) this)) return false;
if (this.getId() != other.getId()) return false;
if (Double.compare(this.getConservativeStandardDeviationMultiplier(), other.getConservativeStandardDeviationMultiplier()) != 0)
return false;
if (Double.compare(this.getMean(), other.getMean()) != 0) return false;
if (Double.compare(this.getStandardDeviation(), other.getStandardDeviation()) != 0) return false;
if (Double.compare(this.getConservativeRating(), other.getConservativeRating()) != 0) return false;
return true;
}
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getId();
final long $conservativeStandardDeviationMultiplier = Double.doubleToLongBits(this.getConservativeStandardDeviationMultiplier());
result = result * PRIME + (int) ($conservativeStandardDeviationMultiplier >>> 32 ^ $conservativeStandardDeviationMultiplier);
final long $mean = Double.doubleToLongBits(this.getMean());
result = result * PRIME + (int) ($mean >>> 32 ^ $mean);
final long $standardDeviation = Double.doubleToLongBits(this.getStandardDeviation());
result = result * PRIME + (int) ($standardDeviation >>> 32 ^ $standardDeviation);
final long $conservativeRating = Double.doubleToLongBits(this.getConservativeRating());
result = result * PRIME + (int) ($conservativeRating >>> 32 ^ $conservativeRating);
return result;
}
protected boolean canEqual(Object other) {
return other instanceof RatingWrapper;
}
public String toString() {
return "RatingWrapper(id=" + this.getId() + ", conservativeStandardDeviationMultiplier=" + this.getConservativeStandardDeviationMultiplier() + ", mean=" + this.getMean() + ", standardDeviation=" + this.getStandardDeviation() + ", conservativeRating=" + this.getConservativeRating() + ")";
}
}
| 38.853846
| 296
| 0.709364
|
d351032d4e7b66a17f3f7db2fd865deb81f2c652
| 1,526
|
package com.gempukku.swccgo.logic.effects;
import com.gempukku.swccgo.game.PhysicalCard;
import com.gempukku.swccgo.game.SwccgGame;
import com.gempukku.swccgo.logic.GameUtils;
import com.gempukku.swccgo.logic.timing.AbstractSuccessfulEffect;
import com.gempukku.swccgo.logic.timing.Action;
import java.util.Collection;
/**
* This effect records the specified card(s) as being 'blown away' for the purposes of the game keeping track of which cards
* have been 'blown away' during the game.
*/
class RecordCardsBlownAwayEffect extends AbstractSuccessfulEffect {
private Collection<PhysicalCard> _cardsBlownAway;
/**
* Creates an effect that records the specified card(s) as being 'blown away' for the purposes of the game keeping track of which cards
* have been 'blown away' during the game.
* @param action the action performing this effect
* @param cardsBlownAway the cards 'blown away'
*/
public RecordCardsBlownAwayEffect(Action action, Collection<PhysicalCard> cardsBlownAway) {
super(action);
_cardsBlownAway = cardsBlownAway;
}
@Override
public void doPlayEffect(SwccgGame game) {
// Send message for cards 'blown away'
game.getGameState().sendMessage(GameUtils.getAppendedNames(_cardsBlownAway) + " " + GameUtils.be(_cardsBlownAway) + " 'blown away'");
// Remember cards that were 'blown away'
for (PhysicalCard card : _cardsBlownAway) {
game.getModifiersQuerying().blownAway(card);
}
}
}
| 38.15
| 141
| 0.726737
|
b2ba40a3e6d5dd23e25ed611077349d1b16442b3
| 5,256
|
/*
* Copyright (c) 2019-2020 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.testing.story.buckets;
import java.io.File;
import java.io.IOException;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.schema.statistics.ActivityStatisticsUtil;
import com.evolveum.midpoint.schema.util.task.ActivityPath;
import com.evolveum.midpoint.schema.util.task.TaskOperationStatsUtil;
import com.evolveum.midpoint.util.exception.CommonException;
import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.testng.annotations.Test;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.test.TestResource;
import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.testing.story.AbstractStoryTest;
/**
* Tests performance of bucketed tasks.
* To be run manually.
*/
@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" })
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
public class TestBucketsPerformance extends AbstractStoryTest {
protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "buckets");
protected static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml");
private static final TestResource<RoleType> ROLE_SLOW = new TestResource<>(TEST_DIR, "role-slow.xml", "4c9f44cc-9cbd-454f-b346-a3a66242ec3d");
private static final TestResource<TaskType> TASK_RECOMPUTE_16_04 = new TestResource<>(TEST_DIR, "task-recompute-16-04.xml", "0f19ae56-050f-4a6d-b407-25a6cf49297d");
private static final TestResource<TaskType> TASK_RECOMPUTE_256_30 = new TestResource<>(TEST_DIR, "task-recompute-256-30.xml", "a2060e8f-1675-41a0-a1ae-1781f14c034f");
private static final int NUMBER_OF_USERS = 1000;
@Override
public void initSystem(Task initTask, OperationResult initResult) throws Exception {
super.initSystem(initTask, initResult);
addObject(ROLE_SLOW, initTask, initResult);
createUsers(initResult);
}
private void createUsers(OperationResult result) throws SchemaException, EncryptionException, ObjectAlreadyExistsException {
for (int i = 0; i < NUMBER_OF_USERS; i++) {
UserType user = new UserType(prismContext)
.name(String.format("user-%06d", i))
.beginAssignment()
.targetRef(ROLE_SLOW.oid, RoleType.COMPLEX_TYPE)
.end();
repoAddObject(user.asPrismObject(), result);
}
display("Users created: " + NUMBER_OF_USERS);
}
/** We want minimalistic logging here. */
@Override
protected boolean isAvoidLoggingChange() {
return false;
}
@Override
protected File getSystemConfigurationFile() {
return SYSTEM_CONFIGURATION_FILE;
}
@Test
public void test100RecomputeUsers_16_buckets_4_threads() throws Exception {
executeRecomputation(TASK_RECOMPUTE_16_04);
}
@Test
public void test110RecomputeUsers_256_buckets_30_threads() throws Exception {
executeRecomputation(TASK_RECOMPUTE_256_30);
}
@Test
public void test120RecomputeUsers_16_buckets_4_threads_again() throws Exception {
executeRecomputation(TASK_RECOMPUTE_16_04);
}
@Test
public void test130RecomputeUsers_256_buckets_30_threads_again() throws Exception {
executeRecomputation(TASK_RECOMPUTE_256_30);
}
private void executeRecomputation(TestResource<TaskType> recomputationTask) throws IOException, CommonException {
given();
Task task = getTestTask();
OperationResult result = task.getResult();
when();
addTask(recomputationTask, result);
waitForTaskFinish(recomputationTask.oid, false);
then();
var tree = assertTaskTree(recomputationTask.oid, "after")
.display()
.subtask(0)
.display()
.end()
.getObject().asObjectable();
var operationStats = TaskOperationStatsUtil.getOperationStatsFromTree(tree, prismContext);
displayValue("Operation statistics", TaskOperationStatsUtil.format(operationStats));
var activityStats = ActivityStatisticsUtil.getActivityStatsFromTree(tree, ActivityPath.empty());
displayValue("Activity statistics", ActivityStatisticsUtil.format(activityStats));
var performanceInformation =
activityManager.getPerformanceInformation(recomputationTask.oid, result);
displayDumpable("Performance information", performanceInformation);
taskManager.deleteTaskTree(recomputationTask.oid, result);
}
}
| 40.122137
| 170
| 0.734779
|
b012c2e5c951361479c02139041ded6d5276f48a
| 4,305
|
/*
* Copyright (C) 2019 Juraj Antal
*
* Originally created in G-Watch App
*
* 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 sk.trupici.gwatch.wear.receivers;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import sk.trupici.gwatch.wear.BuildConfig;
import sk.trupici.gwatch.wear.GWatchApplication;
import sk.trupici.gwatch.wear.common.data.GlucosePacket;
import sk.trupici.gwatch.wear.common.data.Packet;
import sk.trupici.gwatch.wear.common.util.BgUtils;
/**
* description from LibreHack:
*
* Bundle bundle = new Bundle();
* bundle.putString("data", data.json);
* Intent intent = new Intent("com.outshineiot.diabox.BgEstimate");
* intent.putExtras(bundle);
* sendBroadcast(intent)
* *
* data:
* {
* "realTimeGlucose": {
* "timestamp": 1599077082859, // start of the sensor
* "index": 20060,
* "raw": 53
* },
* "historicGlucose": [{
* "timestamp": 1600252482859,
* "index": 19590,
* "raw": 45
* }, {
* "timestamp": 1600253382859,
* "index": 19605,
* "raw": 32
* }]
* }
*/
public class DiaboxReceiver extends BGReceiver {
private final static String SRC_LABEL = "DiaBox";
private final static String PREFERENCE_KEY = "pref_data_source_diabox";
private final static String ACTION = "com.outshineiot.diabox.BgEstimate";
private final static String EXTRA_DATA = "data";
private final static String EXTRA_REALTIME = "realTimeGlucose";
private final static String EXTRA_HISTORICAL = "historicGlucose";
private final static String DATA_TIMESTAMP = "timestamp";
private final static String DATA_GLUCOSE = "raw";
@Override
public String getPreferenceKey() {
return PREFERENCE_KEY;
}
@Override
public String getSourceLabel() {
return SRC_LABEL;
}
@Override
public String getAction() {
return ACTION;
}
@Override
protected Packet processIntent(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String data = extras.getString(EXTRA_DATA);
if (data != null) {
try {
JSONObject dataObj = new JSONObject(data);
if (dataObj != null) {
JSONObject realtimeObj = dataObj.optJSONObject(EXTRA_REALTIME);
if (realtimeObj != null) {
long now = System.currentTimeMillis();
long timestamp = realtimeObj.optLong(DATA_TIMESTAMP, 0L);
int glucoseValue = realtimeObj.optInt(DATA_GLUCOSE, 0);
if (BuildConfig.DEBUG) {
Log.w(GWatchApplication.LOG_TAG, "Glucose: " + glucoseValue + " mg/dl / " + BgUtils.convertGlucoseToMmolL(glucoseValue) + " mmol/l");
Log.w(GWatchApplication.LOG_TAG, "Timestamp: " + timestamp + " -> " + now);
}
short glucose = (short)Math.round(glucoseValue);
if (glucose > 0) {
// since the timestamp in realtime glucose is a timestamp when sensor was started we need to use current time here...
return new GlucosePacket(glucose, now, (byte) 0, null, null, getSourceLabel());
}
}
}
} catch (JSONException e) {
Log.e(GWatchApplication.LOG_TAG, "Error while parsing Diabox data", e);
}
}
}
return null;
}
}
| 35.578512
| 165
| 0.60302
|
5fa68beda7b1545aa6df37f0a515483fb853c948
| 769
|
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.ui.laf;
import com.intellij.ide.ui.UITheme;
import com.intellij.ide.ui.laf.darcula.DarculaLaf;
import javax.swing.*;
/**
* @author Konstantin Bulenkov
*/
public class UIThemeBasedLookAndFeelInfo extends UIManager.LookAndFeelInfo {
private final UITheme myTheme;
public UIThemeBasedLookAndFeelInfo(UITheme theme) {
super(theme.getName(), theme.isDark() ? DarculaLaf.class.getName() : IntelliJLaf.class.getName());
myTheme = theme;
}
public UITheme getTheme() {
return myTheme;
}
public void installTheme(UIDefaults defaults) {
myTheme.applyProperties(defaults);
}
}
| 27.464286
| 140
| 0.746424
|
d0013654df108bcfb5e5c7fe49051b3d8429f1a8
| 1,463
|
package com.sequenceiq.freeipa.api.v1.dns.doc;
public final class DnsOperationDescriptions {
public static final String ADD_DNS_ZONE_FOR_SUBNETS = "Creates reverse DNS Zone entry for subnets in CIDR format";
public static final String ADD_DNS_ZONE_FOR_SUBNET_IDS = "Creates reverse DNS Zone entry for subnet IDs";
public static final String LIST_DNS_ZONES = "List DNS zones available in FreeIPA";
public static final String DELETE_DNS_ZONE_BY_SUBNET = "Deletes reverse DNS Zone entry by subnet CIDR";
public static final String DELETE_DNS_ZONE_BY_SUBNET_ID = "Deletes reverse DNS Zone entry by subnet ID";
public static final String DELETE_DNS_RECORD_BY_FQDN = "Deletes all related A and PTR DNS record";
public static final String ADD_DNS_CNAME_RECORD = "Creates a DNS CNAME record with the value in the defined zone if zone exists. "
+ "If zone not specified default zone will be used.";
public static final String ADD_DNS_A_RECORD = "Creates a DNS A record with the value in the defined zone if zone exists. If zone not specified "
+ "default zone will be used. Reverse pointer is created if requested and reverse zone exists.";
public static final String DELETE_DNS_A_RECORD = "Deletes the A record in DNS Zone and tries to delete PTR if exists.";
public static final String DELETE_DNS_CNAME_RECORD = "Deletes the CNAME record in DNS Zone.";
private DnsOperationDescriptions() {
}
}
| 66.5
| 148
| 0.764183
|
a46403d5ab9f2b40601c9e4e4da542375b31c89a
| 1,713
|
package com.jcloisterzone.reducers;
import com.jcloisterzone.board.pointer.FeaturePointer;
import com.jcloisterzone.event.MeepleDeployed;
import com.jcloisterzone.event.PlayEvent.PlayEventMeta;
import com.jcloisterzone.feature.Structure;
import com.jcloisterzone.figure.DeploymentCheckResult;
import com.jcloisterzone.figure.Follower;
import com.jcloisterzone.figure.Meeple;
import com.jcloisterzone.game.state.GameState;
import io.vavr.collection.LinkedHashMap;
public class DeployMeeple extends AbstractUndeploy {
private final Meeple meeple;
private final FeaturePointer fp;
public DeployMeeple(Meeple meeple, FeaturePointer fp) {
this.meeple = meeple;
this.fp = fp;
}
@Override
public GameState apply(GameState state) {
Structure feature = state.getStructure(fp);
if (feature == null) {
throw new IllegalArgumentException("There is no feature on " + fp);
}
DeploymentCheckResult check = meeple.isDeploymentAllowed(state, fp, feature);
if (!check.result) {
throw new IllegalArgumentException(check.error);
}
LinkedHashMap<Meeple, FeaturePointer> deployedMeeples = state.getDeployedMeeples();
FeaturePointer movedFrom = deployedMeeples.get(meeple).getOrNull();
state = state.setDeployedMeeples(deployedMeeples.put(meeple, fp));
state = state.appendEvent(
new MeepleDeployed(PlayEventMeta.createWithActivePlayer(state), meeple, fp, movedFrom)
);
if (movedFrom != null && (meeple instanceof Follower)) {
state = undeployLonelySpecials(state, (Follower) meeple, movedFrom, true);
}
return state;
}
}
| 34.26
| 98
| 0.709866
|
bdac13453dabc72122662af280c75d10eeb0b1b5
| 2,151
|
package home.gabe.tvword.controllers;
import home.gabe.tvword.model.AuditEvent;
import home.gabe.tvword.model.web.PasswordCommand;
import home.gabe.tvword.services.AdminService;
import home.gabe.tvword.services.AuditService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.security.Principal;
@Slf4j
@Controller
public class AdminController {
private AdminService adminService;
private AuditService auditService;
public AdminController(AdminService adminService, AuditService auditService) {
this.adminService = adminService;
this.auditService = auditService;
}
@GetMapping("/admin/changepwd")
public String getChangePasswordForm(Principal principal, Model model, @RequestParam(name = "success", required = false, defaultValue = "false") String success) {
UserPrincipalWrapper wrapper = new UserPrincipalWrapper(principal);
log.info("{}: AC: getChangePasswordForm(success={})", wrapper, success);
Boolean bool = Boolean.parseBoolean(success);
PasswordCommand command = new PasswordCommand();
command.setUsername(wrapper.getUser().getName());
model.addAttribute("pwdCommand", command);
model.addAttribute("success", bool);
return "admin/changepwd";
}
@PostMapping("/admin/changepwd_process")
public String processChangePassword(Principal principal, @ModelAttribute("pwdCommand") PasswordCommand command) {
UserPrincipalWrapper wrapper = new UserPrincipalWrapper(principal);
log.info("{}: AC: processChangePassword()", wrapper); //not logging password fields
adminService.changePassword(wrapper.getUser(), command);
auditService.logEvent(wrapper.getUser().getName(), AuditEvent.AE_CHANGE_PASSWORD);
return "redirect:/admin/changepwd?success=true";
}
}
| 38.410714
| 165
| 0.754533
|
37cccc4f66d9a6b84a92ccd54ba78b8afcb7fd1c
| 7,018
|
/*
* Copyright (C) 2018 Velocity Contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.velocitypowered.proxy.command;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import com.google.common.collect.ImmutableList;
import com.mojang.brigadier.builder.LiteralArgumentBuilder;
import com.velocitypowered.api.command.BrigadierCommand;
import com.velocitypowered.api.command.CommandSource;
import com.velocitypowered.api.command.RawCommand;
import com.velocitypowered.api.command.SimpleCommand;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import org.junit.jupiter.api.Test;
public class CommandManagerTests extends CommandTestSuite {
// Registration
@Test
void testRegisterWithMeta() {
final var meta = manager.metaBuilder("hello").build();
manager.register(meta, DummyCommand.INSTANCE);
assertTrue(manager.hasCommand("hello"));
assertRegisteredAliases("hello");
assertEquals(meta, manager.getCommandMeta("hello"));
}
@Test
void testRegisterWithMetaContainingMultipleAliases() {
final var meta = manager.metaBuilder("foo")
.aliases("bar")
.aliases("baz", "qux")
.build();
manager.register(meta, DummyCommand.INSTANCE);
assertTrue(manager.hasCommand("foo"));
assertTrue(manager.hasCommand("bar"));
assertTrue(manager.hasCommand("baz"));
assertTrue(manager.hasCommand("qux"));
assertRegisteredAliases("foo", "bar", "baz", "qux");
assertEquals(meta, manager.getCommandMeta("foo"));
assertEquals(meta, manager.getCommandMeta("bar"));
assertEquals(meta, manager.getCommandMeta("baz"));
assertEquals(meta, manager.getCommandMeta("qux"));
}
@Test
void testRegisterAliasesAreCaseInsensitive() {
final var meta = manager.metaBuilder("Foo")
.aliases("Bar")
.build();
manager.register(meta, DummyCommand.INSTANCE);
assertTrue(manager.hasCommand("foo"));
assertTrue(manager.hasCommand("bar"));
assertRegisteredAliases("foo", "bar");
}
@Test
void testRegisterBrigadierCommand() {
final var node = LiteralArgumentBuilder
.<CommandSource>literal("hello")
.build();
manager.register(new BrigadierCommand(node));
assertTrue(manager.hasCommand("hello"));
assertRegisteredAliases("hello");
}
@Test
void testRegisterOverridesPreviousCommand() {
final var called = new AtomicBoolean();
final var oldMeta = manager.metaBuilder("foo").build();
manager.register(oldMeta, DummyCommand.INSTANCE); // fails on execution
assertEquals(oldMeta, manager.getCommandMeta("foo"));
final var newMeta = manager.metaBuilder("foo").build();
manager.register(newMeta, (RawCommand) invocation -> called.set(true));
assertEquals(newMeta, manager.getCommandMeta("foo"));
manager.executeAsync(MockCommandSource.INSTANCE, "foo").join();
assertTrue(called.get());
}
@Test
void testAddingExecutableHintToMetaThrows() {
final var hintNode = LiteralArgumentBuilder
.<CommandSource>literal("hint")
.executes(context -> fail())
.build();
assertThrows(IllegalArgumentException.class, () -> {
manager.metaBuilder("hello").hint(hintNode);
});
}
@Test
void testAddingHintWithRedirectToMetaThrows() {
final var targetNode = LiteralArgumentBuilder
.<CommandSource>literal("target")
.build();
final var hintNode = LiteralArgumentBuilder
.<CommandSource>literal("origin")
.redirect(targetNode)
.build();
assertThrows(IllegalArgumentException.class, () -> {
manager.metaBuilder("hello").hint(hintNode);
});
}
// Un-registration
@Test
void testUnregisterUnregisteredAliasIsIgnored() {
manager.unregister("hello");
assertFalse(manager.hasCommand("hello"));
assertRegisteredAliases();
}
@Test
void testUnregisterRegisteredAlias() {
manager.register("hello", DummyCommand.INSTANCE);
manager.unregister("hello");
assertFalse(manager.hasCommand("hello"));
assertRegisteredAliases();
}
@Test
void testUnregisterSecondaryAlias() {
final var meta = manager.metaBuilder("foo")
.aliases("bar")
.build();
manager.register(meta, DummyCommand.INSTANCE);
manager.unregister("bar");
assertFalse(manager.hasCommand("bar"));
assertTrue(manager.hasCommand("foo"));
assertEquals(meta, manager.getCommandMeta("foo"));
assertRegisteredAliases("foo");
}
@Test
void testUnregisterAllAliases() {
final var meta = manager.metaBuilder("foo")
.aliases("bar")
.build();
manager.register(meta, DummyCommand.INSTANCE);
manager.unregister(meta);
assertFalse(manager.hasCommand("bar"));
assertFalse(manager.hasCommand("foo"));
}
@Test
void testUnregisterAliasOverlap() {
final var meta1 = manager.metaBuilder("foo")
.aliases("bar")
.build();
manager.register(meta1, DummyCommand.INSTANCE);
final var meta2 = manager.metaBuilder("bar")
.build();
manager.register(meta2, DummyCommand.INSTANCE);
assertEquals(meta1, manager.getCommandMeta("foo"));
assertEquals(meta2, manager.getCommandMeta("bar"));
manager.unregister(meta1);
assertNull(manager.getCommandMeta("foo"));
assertEquals(meta2, manager.getCommandMeta("bar"));
}
// Execution
@Test
void testExecuteUnknownAliasIsForwarded() {
assertForwarded("");
assertForwarded("hello");
}
// Suggestions
@Test
void testEmptyManagerSuggestNoAliases() {
assertSuggestions("");
}
static final class DummyCommand implements SimpleCommand {
static final DummyCommand INSTANCE = new DummyCommand();
private DummyCommand() {}
@Override
public void execute(final Invocation invocation) {
fail();
}
@Override
public List<String> suggest(final Invocation invocation) {
return fail();
}
@Override
public boolean hasPermission(final Invocation invocation) {
return fail();
}
}
}
| 29.86383
| 75
| 0.699202
|
4cb8410fb6e5cfc9fe9be9b4b0c201f32a5f6843
| 5,147
|
/*
Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com)
This file is part of the Semantic Discovery Toolkit.
The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The Semantic Discovery Toolkit is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with The Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sd.util;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* JUnit Tests for the LookAheadIterator class.
* <p>
* @author Spence Koehler
*/
public class TestLookAheadIterator extends TestCase {
public TestLookAheadIterator(String name) {
super(name);
}
public void testBasicIteration() {
final List<String> list = Arrays.asList(new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i"});
final LookAheadIterator iter = new LookAheadIterator<String>(list.iterator());
final Iterator<String> expected = list.iterator();
while (iter.hasNext()) {
assertTrue(expected.hasNext());
final String expectedNext = expected.next();
assertEquals(expectedNext, iter.next());
assertEquals(expectedNext, iter.lookAhead(0));
assertEquals(null, iter.lookAhead(-1));
}
assertFalse(expected.hasNext());
}
public void testLookAheadIterationFromFarToNear() {
final String[] strings = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
final List<String> list = Arrays.asList(strings);
final LookAheadIterator<String> iter = new LookAheadIterator<String>(list.iterator());
final Iterator<String> expected = list.iterator();
int index = 0;
while (iter.hasNext()) {
assertTrue(expected.hasNext());
final String expectedNext = expected.next();
final String next = iter.next();
assertEquals(expectedNext, next);
assertEquals(expectedNext, iter.lookAhead(0));
assertEquals(null, iter.lookAhead(-1));
for (int numAhead = strings.length; numAhead >= 0; --numAhead) {
final String expectedAhead = (index + numAhead) >= strings.length ? null : strings[index + numAhead];
assertEquals("index=" + index + " numAhead=" + numAhead, expectedAhead, iter.lookAhead(numAhead));
}
++index;
}
assertFalse(expected.hasNext());
}
public void testLookAheadIterationFromNearToFar() {
final String[] strings = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
final List<String> list = Arrays.asList(strings);
final LookAheadIterator<String> iter = new LookAheadIterator<String>(list.iterator());
final Iterator<String> expected = list.iterator();
int index = 0;
while (iter.hasNext()) {
assertTrue(expected.hasNext());
final String expectedNext = expected.next();
final String next = iter.next();
assertEquals(expectedNext, next);
assertEquals(expectedNext, iter.lookAhead(0));
assertEquals(null, iter.lookAhead(-1));
for (int numAhead = 0; numAhead < strings.length; ++numAhead) {
final String expectedAhead = (index + numAhead) >= strings.length ? null : strings[index + numAhead];
assertEquals("index=" + index + " numAhead=" + numAhead, expectedAhead, iter.lookAhead(numAhead));
}
++index;
}
assertFalse(expected.hasNext());
}
public void testLookBothWaysIteration() {
final String[] strings = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i"};
final List<String> list = Arrays.asList(strings);
final LookAheadIterator<String> iter = new LookAheadIterator<String>(list.iterator(), true);
final Iterator<String> expected = list.iterator();
int index = 0;
while (iter.hasNext()) {
assertTrue(expected.hasNext());
final String expectedNext = expected.next();
final String next = iter.next();
assertEquals(expectedNext, next);
assertEquals(expectedNext, iter.lookAhead(0));
for (int numAhead = -strings.length; numAhead < strings.length; ++numAhead) {
final String expectedAhead = (index + numAhead) >= strings.length ? null : (index + numAhead) < 0 ? null : strings[index + numAhead];
assertEquals("index=" + index + " numAhead=" + numAhead, expectedAhead, iter.lookAhead(numAhead));
}
++index;
}
assertFalse(expected.hasNext());
}
public static Test suite() {
TestSuite suite = new TestSuite(TestLookAheadIterator.class);
return suite;
}
public static void main(String[] args) {
junit.textui.TestRunner.run(suite());
}
}
| 33.422078
| 141
| 0.667768
|
57bbad0651a15fe48f884166e78e8e7ceac0ec1b
| 180
|
package com.monsanto.data.goldengate.config.factory;
import com.monsanto.data.goldengate.config.Conf;
public interface ConfigurationFactory {
Conf load(String filePath);
}
| 18
| 52
| 0.794444
|
7886e66beb81e8655cb6ad62c856b6efeac85008
| 21,393
|
package ch.yannick.context.datamanagement;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import ch.yannick.context.RootApplication;
import ch.yannick.intern.action_talent.Action;
import ch.yannick.intern.action_talent.ActionData;
import ch.yannick.intern.action_talent.Talent;
import ch.yannick.intern.items.Clothe;
import ch.yannick.intern.items.Item;
import ch.yannick.intern.personnage.Attribute;
import ch.yannick.intern.personnage.Character;
import ch.yannick.intern.personnage.HitZone;
import ch.yannick.intern.personnage.Race;
import ch.yannick.intern.usables.Weapon;
import ch.yannick.intern.usables.UsableInterface;
import ch.yannick.intern.usables.UsableType;
public class SQLDBManager extends SQLiteOpenHelper {
private static final String LOG="SQLManager";
// All Static variables related to db
// Database Version
private static final int DATABASE_VERSION = 12;
// Database Name
private static final String DATABASE_NAME = "SSE";
// table names
private static final String
TABLE_CHARACTER = "character", TABLE_ATTRIBUTE = "attribute", TABLE_TALENT = "talent", TABLE_STATE = "state",
TABLE_ITEM= "item", TABLE_USABLE = "usable", TABLE_CLOTHE ="clothe", TABLE_SPELL ="spell", TABLE_MANA_COUNT = "mana_count",
TABLE_ATTRIBUTE_ACTION ="attribute_action";
//Table columns for all tables
private static final String KEY_NAME = "name", KEY_DESCRIPTION = "description",
KEY_ID="id", KEY_SERVER_ID = "server_id",
KEY_VALUE = "value";
// Foreign Keys
private static final String KEY_CHARACTER_ID = "character_id",KEY_ITEM_ID = "item_id",KEY_STATE_ID = "state_id";
// Character Table Columns names
private static final String KEY_RACE = "race",
KEY_CLASS = "class";
// attirbute and talent Table columns
//NONe
//item TABLE columsn
private static final String KEY_WEIGHT = "weight";
// usable Table Columns names
private static final String KEY_TYPE= "type";
// clothes table columns
private static final String KEY_WHEATER_PROTECTION = "wheater_protection",
KEY_PROTECTION = "protection",
KEY_BODYPART ="bodypart";
// mana count table columns
private static final String KEY_MANA = "mana";
// action Table Columns
private static final String KEY_ATTRIBUTES="attributes",
KEY_FATIGUE="fatigue", KEY_MODIFIER = "modifier", KEY_TICKS ="ticks",
KEY_RESULT="resultValue", KEY_SKILL_ENHANCER = "enhancer";
// state table colums
private static final String KEY_LIFE_MAX = "life_max", KEY_LIFE_NOW ="life_now",
KEY_STAMINA_MAX ="stamina_max", KEY_STAMINA_NOW = "stamina_now",
KEY_PERIOD_STAMINA_MAX = "period_stamina_max", KEY_PERIOD_STAMINA_NOW= "period_stamina_now", KEY_PERIOD_STAMINA_USED = "period_stamina_used",
KEY_MENTALSTATE_X = "mentalstate_x", KEY_MENTALSTATE_Y = "mentalstate_y", KEY_MENTALSTATE = "mentalstate";
private SQLiteDatabase db;
public SQLDBManager(RootApplication context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CHARACTER_TABLE = "CREATE TABLE " + TABLE_CHARACTER + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_SERVER_ID + " LONG,"
+ KEY_RACE + " STRING,"
+ KEY_CLASS + " STRING"
+ ");";
String CREATE_ATTRIBUTE_TABLE = "CREATE TABLE " + TABLE_ATTRIBUTE + "("
+ KEY_CHARACTER_ID + " INTEGER,"
+ KEY_NAME + " VARCHAR,"
+ KEY_VALUE + " INTEGER,"
+ " FOREIGN KEY ("+KEY_CHARACTER_ID+") REFERENCES "+TABLE_CHARACTER+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_TALENT_TABLE=" CREATE TABLE "+ TABLE_TALENT+"("
+ KEY_CHARACTER_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " VARCHAR,"
+ KEY_VALUE + " INTEGER,"
+ " FOREIGN KEY ("+KEY_CHARACTER_ID+") REFERENCES "+TABLE_CHARACTER+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_STATE_TABLE = "CREATE TABLE "+ TABLE_STATE +"("
+ KEY_CHARACTER_ID + " INTEGER PRIMARY KEY,"
+ KEY_LIFE_MAX + " INTEGER,"
+ KEY_LIFE_NOW + " INTEGER,"
+ KEY_STAMINA_MAX + " INTEGER,"
+ KEY_STAMINA_NOW + " INTEGER,"
+ KEY_PERIOD_STAMINA_MAX + " INTEGER,"
+ KEY_PERIOD_STAMINA_NOW+ " INTEGER,"
+ KEY_PERIOD_STAMINA_USED + " INTEGER,"
+ KEY_MENTALSTATE + " VARCHAR(255),"
+ KEY_MENTALSTATE_X + " INTEGER,"
+ KEY_MENTALSTATE_Y+ " INTEGER,"
+ " FOREIGN KEY ("+KEY_CHARACTER_ID+") REFERENCES "+TABLE_CHARACTER+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_TABLE_ITEM = " CREATE TABLE "+ TABLE_ITEM +"("
+KEY_ID + " INTEGER PRIMARY KEY,"
+KEY_NAME + " STRING,"
+KEY_SERVER_ID + " LONG,"
+KEY_CHARACTER_ID+ " INTEGER,"
+KEY_DESCRIPTION + " TEXT,"
+KEY_WEIGHT + " INTEGER,"
+ " FOREIGN KEY ("+KEY_CHARACTER_ID+") REFERENCES "+TABLE_CHARACTER+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_USABLE_TABLE=" CREATE TABLE "+ TABLE_USABLE +"("
+ KEY_ITEM_ID + " INTEGER,"
+ KEY_TYPE +" STRING,"
+ " FOREIGN KEY ("+KEY_ITEM_ID+") REFERENCES "+TABLE_ITEM+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_TABLE_CLOTHE = "CREATE TABLE "+ TABLE_CLOTHE+"("
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_ITEM_ID + " INTEGER,"
+ KEY_BODYPART + " VARCHAR(255),"
+ KEY_WHEATER_PROTECTION +" INTEGER,"
+ KEY_PROTECTION +" INTEGER,"
+ " FOREIGN KEY ("+KEY_ITEM_ID+") REFERENCES "+TABLE_ITEM+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_TABLE_SPELL = "CREATE TABLE " + TABLE_SPELL +"("
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_CHARACTER_ID + " INTEGER,"
+ " FOREIGN KEY ("+KEY_CHARACTER_ID+") REFERENCES "+TABLE_CHARACTER+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_TABLE_MANA_COUNT = "CREATE TABLE "+ TABLE_MANA_COUNT + "("
+ KEY_ITEM_ID + " INTEGER,"
+ KEY_STATE_ID + " INTEGER,"
+ KEY_MANA + " INTEGER,"
+ " FOREIGN KEY ("+KEY_ITEM_ID+") REFERENCES "+TABLE_ITEM+" ("+KEY_ID+") ON DELETE CASCADE"
+ " FOREIGN KEY ("+KEY_STATE_ID+") REFERENCES "+TABLE_STATE+" ("+KEY_ID+") ON DELETE CASCADE);";
String CREATE_TABLE_ACTION = "CREATE TABLE "+ TABLE_ATTRIBUTE_ACTION +"("
+ KEY_ITEM_ID + " INTEGER,"
+ KEY_ID + " INTEGER PRIMARY KEY, "
+ KEY_NAME + " STRING,"
+ KEY_ATTRIBUTES +" VARCHAR,"
+ KEY_FATIGUE + " INTEGER,"
+ KEY_TICKS + " INTEGER,"
+ KEY_SKILL_ENHANCER + " INTEGER,"
+ KEY_MODIFIER + " INTEGER,"
+ KEY_RESULT +" VARCHAR,"
+ " FOREIGN KEY ("+KEY_ITEM_ID+") REFERENCES "+TABLE_ITEM+" ("+KEY_ID+") ON DELETE CASCADE);";
db.execSQL(CREATE_CHARACTER_TABLE);
db.execSQL(CREATE_ATTRIBUTE_TABLE);
db.execSQL(CREATE_STATE_TABLE);
db.execSQL(CREATE_TABLE_ACTION);
db.execSQL(CREATE_TABLE_CLOTHE);
db.execSQL(CREATE_TABLE_MANA_COUNT);
db.execSQL(CREATE_TALENT_TABLE);
db.execSQL(CREATE_USABLE_TABLE);
db.execSQL(CREATE_TABLE_ITEM);
db.execSQL(CREATE_TABLE_SPELL);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTRIBUTE_ACTION);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ATTRIBUTE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MANA_COUNT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ITEM);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SPELL);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CHARACTER);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CLOTHE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_STATE);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_TALENT);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USABLE);
// Create tables again
onCreate(db);
}
//////////// PERSONAGES //////////////////////////////////
public synchronized Long pushCharacter(Character p){ // add or update personnage
ContentValues c = new ContentValues();
c.put(KEY_NAME, p.toString());
c.put(KEY_RACE, p.getRasse().name());
c.put(KEY_SERVER_ID, p.getServerId());
c.put(KEY_CLASS, p.getJob());
long id = pushData(TABLE_CHARACTER,p.getId(),c);
Log.d(LOG," Character pushed and id is "+id);
p.setId(id);
deleteEntry(TABLE_TALENT,KEY_CHARACTER_ID,id);
for(Talent tl:p.getTalents().keySet()){
Log.d(LOG,"pushing talent "+ tl.getName());
c = new ContentValues();
c.put(KEY_CHARACTER_ID,id);
c.put(KEY_NAME,tl.getName());
c.put(KEY_VALUE,p.getTalents().get(tl));
pushData(TABLE_TALENT,null,c);
}
deleteEntry(TABLE_ATTRIBUTE,KEY_CHARACTER_ID,id);
for(Attribute attribute:p.getAttributes()){
Log.d(LOG,"pushing attribute "+attribute.name());
c = new ContentValues();
c.put(KEY_CHARACTER_ID,id);
c.put(KEY_NAME,attribute.name());
c.put(KEY_VALUE,p.getAttr(attribute));
pushData(TABLE_ATTRIBUTE,null,c);
}
return id;
}
public synchronized Character getCharacter(Long id) throws Exception{
db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CHARACTER, new String[]{ KEY_ID, KEY_NAME, KEY_RACE}, KEY_ID + "=?",
new String[]{String.valueOf(id) }, null,null,null,null);
if(cursor.moveToFirst()){
Log.d(LOG, "adding Pers to list with id:" + cursor.getLong(0) + " Name:" + cursor.getString(1));
Character p = new Character(cursor.getString(1),cursor.getLong(0));
p.setRasse(Race.valueOf(getString(cursor, KEY_RACE)));
cursor.close();
// Attributes
cursor = db.query(TABLE_ATTRIBUTE, new String[]{KEY_CHARACTER_ID,KEY_NAME,KEY_VALUE},
KEY_CHARACTER_ID + "=?",new String[]{String.valueOf(id) }, null,null,null,null);
if(cursor.moveToFirst()){
do{
Log.d(LOG, "Adding attribute " + getString(cursor,KEY_NAME));
p.setAttr(Attribute.valueOf(getString(cursor, KEY_NAME)), get(cursor, KEY_VALUE));
}while(cursor.moveToNext());
}
cursor.close();
// Talents
cursor = db.query(TABLE_TALENT, new String[]{KEY_CHARACTER_ID,KEY_NAME,KEY_VALUE},
KEY_CHARACTER_ID + "=?",new String[]{String.valueOf(id) }, null,null,null,null);
if(cursor.moveToFirst()){
do{
Log.d(LOG, "Adding talent " + getString(cursor,KEY_NAME));
p.setTalent(Talent.getTalent(getString(cursor, KEY_NAME)),get(cursor,KEY_VALUE));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return p;
}else{
cursor.close();
db.close();
throw(new Exception("Personnage not in the DataBase"));
}
}
public synchronized ArrayList<Character> getAllCharacter(){
ArrayList<Character> list= new ArrayList<>();
db = getReadableDatabase();
Cursor cursor = db.query(TABLE_CHARACTER,new String[]{KEY_NAME,KEY_ID},null,null,null,null,null);
if(cursor.moveToFirst()){
do{
Log.d(LOG,"adding character with id " + cursor.getLong(1));
list.add(new Character(cursor.getString(0),cursor.getLong(1)));
}while(cursor.moveToNext());
}
db.close();
cursor.close();
return list;
}
public synchronized void delete(Character p){
deleteEntry(SQLDBManager.TABLE_CHARACTER, p.getId());
}
//////////// ITEMS //////////////////////////////////
public synchronized Long pushItem(Item w){
ContentValues c = new ContentValues();
delete(w);
c.put(KEY_NAME,w.getName());
c.put(KEY_SERVER_ID,w.getServerId());
c.put(KEY_CHARACTER_ID,w.getOwner());
c.put(KEY_DESCRIPTION,w.getDescription());
c.put(KEY_WEIGHT,w.getWeight());
Long id = pushData(TABLE_ITEM,w.getId(),c); // in case it is first time
if(w instanceof UsableInterface){
ActionData data;
for(Action action:((UsableInterface) w).getActions()) {
Log.d(LOG,"" +action);
data = ((UsableInterface) w).getData(action);
Log.d(LOG,"" +data);
if(!data.isRemake) {
c = new ContentValues();
c.put(KEY_ITEM_ID, id);
c.put(KEY_NAME, action.getName());
c.put(KEY_ATTRIBUTES, data.getAttributesString());
c.put(KEY_FATIGUE, data.fatigue);
c.put(KEY_TICKS,data.ticks);
c.put(KEY_SKILL_ENHANCER, data.enhancer);
c.put(KEY_RESULT, data.getResult());
pushData(TABLE_ATTRIBUTE_ACTION, null, c);
}
}
}
if(w instanceof Weapon){
c = new ContentValues();
c.put(KEY_ITEM_ID,id);
c.put(KEY_TYPE,((Weapon) w).getTyp().name());
pushData(TABLE_USABLE,null,c);
}
if(w instanceof Clothe){
c = new ContentValues();
c.put(KEY_ITEM_ID,id);
c.put(KEY_BODYPART,((Clothe) w).getPart().name());
c.put(KEY_WHEATER_PROTECTION,((Clothe) w).getWeatherProtection());
c.put(KEY_PROTECTION,((Clothe) w).getProtection());
pushData(TABLE_CLOTHE,null,c);
}
return id;
}
public synchronized ArrayList<Item> getAllItem(Long ownerId) {
ArrayList<Item> list= new ArrayList<>();
db = getReadableDatabase();
Cursor cursor = db.query(TABLE_ITEM, new String[]{KEY_ID, KEY_NAME, KEY_SERVER_ID, KEY_CHARACTER_ID, KEY_DESCRIPTION, KEY_WEIGHT},
null,null, null, null, null, null);
Item item;
Cursor cSub;
if(cursor.moveToFirst()){
do{
Log.d(LOG,"adding item to list with id:"+cursor.getLong(0)+" Name:"+cursor.getString(1));
item = new Item(getLong(cursor,KEY_ID),getLong(cursor,KEY_SERVER_ID),getLong(cursor,KEY_CHARACTER_ID),getString(cursor,KEY_NAME),
getString(cursor,KEY_DESCRIPTION),get(cursor,KEY_WEIGHT));
cSub = db.query(TABLE_USABLE, new String[]{KEY_TYPE,KEY_ITEM_ID},KEY_ITEM_ID +"=?",
new String[]{String.valueOf(getLong(cursor,KEY_ID))},null,null,null,null);
if(cSub.moveToFirst())
item = new Weapon(item,UsableType.valueOf(getString(cSub, KEY_TYPE)));
cSub.close();
cSub = db.query(TABLE_CLOTHE, new String[]{KEY_ITEM_ID, KEY_WHEATER_PROTECTION, KEY_PROTECTION, KEY_BODYPART}, KEY_ITEM_ID +"=?",
new String[]{String.valueOf(getLong(cursor,KEY_ID))},null,null,null,null);
if(cSub.moveToFirst())
item = new Clothe(item, HitZone.valueOf(getString(cSub, KEY_BODYPART)),get(cSub,KEY_PROTECTION),get(cSub,KEY_WHEATER_PROTECTION));
cSub.close();
if(item instanceof Weapon){
cSub = db.query(TABLE_ATTRIBUTE_ACTION,new String[]{KEY_ITEM_ID,KEY_NAME,KEY_ATTRIBUTES,KEY_FATIGUE,KEY_TICKS,KEY_SKILL_ENHANCER,KEY_MODIFIER,KEY_RESULT},
KEY_ITEM_ID+"=?",new String[]{String.valueOf(getLong(cursor,KEY_ID))},null,null,null,null);
if(cSub.moveToFirst()){
do{
((Weapon) item).addData(Action.valueOf(getString(cSub, KEY_NAME)),
new ActionData(Action.valueOf(getString(cSub, KEY_NAME)),get(cSub, KEY_FATIGUE), get(cSub, KEY_SKILL_ENHANCER), get(cSub, KEY_MODIFIER), get(cSub, KEY_TICKS),getString(cSub,KEY_ATTRIBUTES), getString(cSub, KEY_RESULT)));
}while (cSub.moveToNext());
}
}
list.add(item);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return list;
}
public synchronized Item getItem(Long id) {
db = getReadableDatabase();
Cursor cursor;
if(id != null)
cursor = db.query(TABLE_ITEM, new String[]{KEY_ID, KEY_NAME, KEY_SERVER_ID, KEY_CHARACTER_ID, KEY_DESCRIPTION, KEY_WEIGHT},
KEY_ID +"=?",new String[]{String.valueOf(id)}, null, null, null, null);
else
cursor = db.query(TABLE_ITEM, new String[]{KEY_ID, KEY_NAME, KEY_SERVER_ID, KEY_CHARACTER_ID, KEY_DESCRIPTION, KEY_WEIGHT},
null,null, null, null, null, null);
Item item = null;
Cursor cSub;
if(cursor.moveToFirst()){
Log.d(LOG,"adding item to list with id:"+cursor.getLong(0)+" Name:"+cursor.getString(1));
item = new Item(getLong(cursor,KEY_ID),getLong(cursor,KEY_SERVER_ID),getLong(cursor,KEY_CHARACTER_ID),getString(cursor,KEY_NAME),
getString(cursor,KEY_DESCRIPTION),get(cursor,KEY_WEIGHT));
cSub = db.query(TABLE_USABLE, new String[]{KEY_TYPE,KEY_ITEM_ID},KEY_ITEM_ID +"=?",
new String[]{String.valueOf(getLong(cursor,KEY_ID))},null,null,null,null);
if(cSub.moveToFirst())
item = new Weapon(item,UsableType.valueOf(getString(cSub, KEY_TYPE)));
cSub.close();
cSub = db.query(TABLE_CLOTHE, new String[]{KEY_ITEM_ID, KEY_WHEATER_PROTECTION, KEY_PROTECTION, KEY_BODYPART}, KEY_ITEM_ID +"=?",
new String[]{String.valueOf(getLong(cursor,KEY_ID))},null,null,null,null);
if(cSub.moveToFirst())
item = new Clothe(item, HitZone.valueOf(getString(cSub, KEY_BODYPART)),get(cSub,KEY_PROTECTION),get(cSub,KEY_WHEATER_PROTECTION));
cSub.close();
if(item instanceof Weapon){
cSub = db.query(TABLE_ATTRIBUTE_ACTION,new String[]{KEY_ITEM_ID,KEY_NAME,KEY_ATTRIBUTES,KEY_FATIGUE,KEY_TICKS,KEY_SKILL_ENHANCER,KEY_MODIFIER,KEY_RESULT},
KEY_ITEM_ID+"=?",new String[]{String.valueOf(getLong(cursor,KEY_ID))},null,null,null,null);
if(cSub.moveToFirst()){
do{
((Weapon) item).addData(Action.valueOf(getString(cSub, KEY_NAME)),
new ActionData(Action.valueOf(getString(cSub, KEY_NAME)),get(cSub,KEY_FATIGUE), get(cSub,KEY_SKILL_ENHANCER),get(cSub,KEY_MODIFIER), get(cSub,KEY_TICKS),getString(cSub,KEY_ATTRIBUTES),getString(cSub,KEY_RESULT)));
}while (cSub.moveToNext());
}
}
}
cursor.close();
db.close();
return item;
}
public synchronized void delete(Item item) {
deleteEntry(TABLE_ITEM, item.getId());
deleteEntry(TABLE_USABLE, KEY_ITEM_ID, item.getId());
deleteEntry(TABLE_SPELL,KEY_ITEM_ID, item.getId());
deleteEntry(TABLE_CLOTHE,KEY_ITEM_ID, item.getId());
deleteEntry(TABLE_ATTRIBUTE_ACTION,KEY_ITEM_ID, item.getId());
}
// State
//TODO
// Help methods
private int get(Cursor c,String key){
return c.getInt(c.getColumnIndexOrThrow(key));
}
private boolean getBool(Cursor c, String key) {
return c.getInt(c.getColumnIndex(key))==1;
}
private long getLong(Cursor c, String key) {
return c.getLong(c.getColumnIndexOrThrow(key));
}
private String getString(Cursor c,String key){
return c.getString(c.getColumnIndexOrThrow(key));
}
private long pushData(String table,Long id, ContentValues values){
db = getWritableDatabase();
if(id == null){
Log.d(LOG,"inserting ");
id=db.insert(table, null,values);
}else{
Log.d(LOG,"updating ");
db.update(table, values, KEY_ID+" = ?", new String[]{String.valueOf(id)});
}
db.close();
return id;
}
private void deleteEntry(String table,Long id){
deleteEntry(table,KEY_ID,id);
}
private void deleteEntry(String table,String key_column,Long id){
if(id != null)
getWritableDatabase().delete(table,key_column + " = ?",
new String[]{String.valueOf(id)});
}
}
| 43.218182
| 256
| 0.597018
|
d905b82ea9b86318fb6da663904a474e6a141877
| 322
|
package io.rx_cache2;
/**
* Exception thrown by RxCache when some error happens.
*/
public final class RxCacheException extends RuntimeException {
public RxCacheException(String message) {
super(message);
}
public RxCacheException(String message, Throwable exception) {
super(message, exception);
}
}
| 20.125
| 64
| 0.73913
|
034088de630aceb76fcecf5b83af6fab6c461b76
| 46,829
|
package com.intellij.lang.javascript.linter.jscs.config;
import com.intellij.json.psi.JsonArray;
import com.intellij.json.psi.JsonBooleanLiteral;
import com.intellij.json.psi.JsonStringLiteral;
import com.intellij.json.psi.JsonValue;
import com.intellij.lang.javascript.linter.jscs.JscsPreset;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.ObjectUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.intellij.lang.javascript.linter.jscs.config.JscsOptionDescriptor.ValueDescription.NO_VALIDATION;
import static com.intellij.lang.javascript.linter.jscs.config.ValueType.*;
/**
* @author Irina.Chernushina on 4/30/2015.
*/
public enum JscsOption {
requireCurlyBraces (boolOrKeywordsArray()),
requireSpaceAfterKeywords (boolOrKeywordsArray()),
disallowSpaceAfterKeywords (boolOrKeywordsArray()),
requireSpaceBeforeBlockStatements (descr().canBool().canInteger()),
disallowSpaceBeforeBlockStatements (descr().canBool()),
requireParenthesesAroundIIFE (descr().canBool()),
requireSpacesInConditionalExpression (ternary()),
disallowSpacesInConditionalExpression (ternary()),
requireSpacesInFunctionExpression (beforeBraces()),
disallowSpacesInFunctionExpression (beforeBraces()),
requireSpacesInAnonymousFunctionExpression (descr().addType(obj, new JscsOptionDescriptor.ValuesObject((o) -> {
o.addBoolFields("beforeOpeningRoundBrace", "beforeOpeningCurlyBrace");
o.addField("allExcept").addType(array, new JscsOptionDescriptor.CustomValidation((value) -> {
final JsonArray array = ObjectUtils.tryCast(value, JsonArray.class);
final String expected = "Expected values: true or \"shorthand\"";
if (array != null) {
// null is not gonna happen, it is checked in annotator
final List<JsonValue> list = array.getValueList();
if (list.size() > 1) return "Expected one-element array";
if (list.isEmpty()) return null;
final JsonValue arrayValue = list.get(0);
if (arrayValue instanceof JsonBooleanLiteral) {
if ("true".equals(arrayValue.getText())) return null;
} else if (arrayValue instanceof JsonStringLiteral) {
if ("shorthand".equals(StringUtil.unquoteString(arrayValue.getText()))) return null;
}
return expected;
}
return null;
}));
}))),
disallowSpacesInAnonymousFunctionExpression (beforeBraces()),
requireSpacesInNamedFunctionExpression (beforeBraces()),
disallowSpacesInNamedFunctionExpression (beforeBraces()),
requireSpacesInFunctionDeclaration (beforeBraces()),
disallowSpacesInFunctionDeclaration (beforeBraces()),
requireSpacesInFunction (beforeBraces()),
disallowSpacesInFunction (beforeBraces()),
disallowMultipleVarDecl (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("strict").canBool();
o.addField("allExcept").canStringArray("undefined", "required");
}))),
requireMultipleVarDecl (descr().canBool().addType(str, new JscsOptionDescriptor.ValuesCollection("onevar"))),
requireBlocksOnNewline (descr().canBool().canInteger().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("includeComments").canBool();
o.addField("minLines").canInteger();
}))),
requirePaddingNewlinesInBlocks (descr().canBool().canInteger().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("open").canTrueOrFalse();
o.addField("close").canTrueOrFalse();
}))),
disallowPaddingNewlinesInBlocks (descr().canBool()),
disallowSpacesInsideObjectBrackets (descr().canBool().addType(str, new JscsOptionDescriptor.ValuesCollection("all", "nested"))
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("}", ")", "{", "(")))),
disallowSpacesInsideArrayBrackets (descr().canBool().addType(str, new JscsOptionDescriptor.ValuesCollection("all", "nested"))
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("}", "]", "{", "[")))),
disallowSpacesInsideParentheses (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("only").canStringArray("{", "}", "(", ")")))),
requireSpacesInsideObjectBrackets (descr().addType(str, new JscsOptionDescriptor.ValuesCollection("all", "allButNested"))
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("}", ")", "{", "(")))),
requireSpacesInsideArrayBrackets (descr().addType(str, new JscsOptionDescriptor.ValuesCollection("all", "allButNested"))
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("}", "]", "{", "[")))),
requireSpacesInsideParentheses (descr().addType(str, new JscsOptionDescriptor.ValuesCollection("all", "allButNested"))
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("all").canBool();
o.addField("except").canStringArray("}", ")", "{", "(");
}))),
disallowQuotedKeysInObjects (descr().canBool().canString("allButReserved")),
disallowDanglingUnderscores (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").addType(array, NO_VALIDATION)))),
disallowSpaceAfterObjectKeys (descr().canBool().canString("ignoreSingleLine", "ignoreMultiLine")
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("singleline", "multiline", "aligned")))),
requireSpaceAfterObjectKeys (descr().canBool()),
disallowSpaceBeforeObjectValues (descr().canBool()),
requireSpaceBeforeObjectValues (descr().canBool()),
disallowCommaBeforeLineBreak (descr().canBool(). addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("function")))),
requireCommaBeforeLineBreak (descr().canBool()),
requireAlignedObjectValues (descr().canString("all", "ignoreFunction", "ignoreLineBreak")),
requireOperatorBeforeLineBreak (descr().canBool().canOperatorsArray()),
disallowSpaceAfterPrefixUnaryOperators (descr().canBool().canStringArray(Constants.unaryOperators)),
requireSpaceAfterPrefixUnaryOperators (descr().canBool().canStringArray(Constants.unaryOperators)),
disallowSpaceBeforePostfixUnaryOperators (descr().canBool().canStringArray(Constants.unaryOperators)),
requireSpaceBeforePostfixUnaryOperators (descr().canBool().canStringArray(Constants.unaryOperators)),
disallowSpaceBeforeBinaryOperators (descr().canBool().canBinaryOperatorsArray()),
requireSpaceBeforeBinaryOperators (descr().canBool().canBinaryOperatorsArray()),
disallowSpaceAfterBinaryOperators (descr().canBool().canBinaryOperatorsArray()),
requireSpaceAfterBinaryOperators (descr().canBool().canBinaryOperatorsArray()),
disallowSpaceBeforeComma (descr().canBool()),
requireSpaceBeforeComma (descr().canBool()),
disallowSpaceBeforeSemicolon (descr().canBool()),
disallowParenthesesAroundArrowParam (descr().canBool()),
requireParenthesesAroundArrowParam (descr().canBool()),
disallowObjectKeysOnNewLine (descr().canBool()),
requireObjectKeysOnNewLine (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("sameLine")))),
disallowImplicitTypeConversion (descr().canStringArray("numeric", "boolean", "binary", "string")),
requireCamelCaseOrUpperCaseIdentifiers (descr().canBool().canString("ignoreProperties")),
disallowKeywords (descr().canKeywordsArray()),
disallowMultipleLineStrings (descr().canBool()),
disallowMultipleLineBreaks (descr().canBool()),
disallowMixedSpacesAndTabs (descr().canBool().canString("smart")),
disallowTrailingWhitespace (descr().canBool().canString("ignoreEmptyLines")),
disallowTrailingComma (descr().canBool()),
requireTrailingComma (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject(o-> o.addBoolFields("ignoreSingleValue", "ignoreSingleLine")))),
disallowKeywordsOnNewLine (descr().canKeywordsArray()),
requireKeywordsOnNewLine (descr().canKeywordsArray()),
requireLineFeedAtFileEnd (descr().canBool()),
maximumLineLength (descr().canInteger().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("value").canInteger();
o.addField("tabSize").canInteger();
o.addField("allExcept").canStringArray("regex", "comments", "urlComments", "functionSignature", "require");
o.addBoolFields("allowComments", "allowUrlComments", "allowRegex");
}).mandatory("value"))),
requireCapitalizedConstructors (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").addType(array, NO_VALIDATION)))),
requireDotNotation (descr().canBool().canString("except_snake_case")),
requireYodaConditions (descr().canBool().canStringArray(Constants.conditionalOperators)),
disallowYodaConditions (descr().canBool().canStringArray(Constants.conditionalOperators)),
requireSpaceAfterLineComment (descr().canBool().canString("allowSlash").addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").addType(array, NO_VALIDATION)))),
disallowSpaceAfterLineComment (descr().canBool()),
disallowAnonymousFunctions (descr().canBool()),
requireAnonymousFunctions (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("declarations")))),
disallowNewlineBeforeBlockStatements (descr().canBool().canStringArray(Constants.blockStatementKeywords)),
requireNewlineBeforeBlockStatements (descr().canBool().canStringArray(Constants.blockStatementKeywords)),
validateLineBreaks (descr().canString("CR", "LF", "CRLF")),
validateQuoteMarks (descr().canBool().canString("\"", "'")
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addBoolFields("escape");
o.addField("mark").canString("\"", "'");
}))),
validateIndentation (descr().canInteger().addType(str, new JscsOptionDescriptor.ValuesCollection("\t").doNotTrimValues())
.addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("value").canInteger().addType(str, new JscsOptionDescriptor.ValuesCollection("\t").doNotTrimValues());
o.addBoolFields("includeEmptyLines");
o.addField("allExcept").canStringArray("comments", "emptyLines");
}).mandatory("value"))),
validateParameterSeparator (descr().addType(str, new JscsOptionDescriptor.ValuesCollection(", ", " ,", " , ").doNotTrimValues())),
jsDoc (descr().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("checkAnnotations").canBool().canString("closurecompiler", "jsdoc3", "jsduck5")
.addType(obj, new JscsOptionDescriptor.ValuesObject((i)-> {
i.addField("preset").canString("closurecompiler", "jsdoc3", "jsduck5");
i.addField("extra").addType(obj, NO_VALIDATION);
}))
.withDescription("Ensures tag names are valid");
o.addField("checkParamExistence").canBool()
.withDescription("Checks all parameters are documented");
o.addField("checkParamNames").canBool()
.withDescription("Ensures param names in jsdoc and in function declaration are equal");
o.addField("requireParamTypes").canBool()
.withDescription("Ensures params in jsdoc contains type");
o.addField("checkRedundantParams").canBool()
.withDescription("Reports redundant params in jsdoc");
o.addField("checkReturnTypes").canBool()
.withDescription("Reports discrepancies between the claimed in jsdoc and actual typ");
o.addField("checkRedundantReturns").canBool()
.withDescription("Report statements for functions with no return");
o.addField("requireReturnTypes").canBool()
.withDescription("Ensures returns in jsdoc contains type");
o.addField("checkTypes").canBool().canString("strictNativeCase", "capitalizedNativeCase")
.withDescription("Reports invalid types for bunch of tags");
o.addField("checkRedundantAccess").canBool().canString("enforceLeadingUnderscore", "enforceTrailingUnderscore")
.withDescription("Reports redundant access declarations");
o.addField("leadingUnderscoreAccess").canBool().canString("private", "protected")
.withDescription("Ensures access declaration is set for _underscored function names");
o.addField("enforceExistence").canBool().canString("exceptExports")
.withDescription("Ensures jsdoc block exist");
o.addField("requireHyphenBeforeDescription").canBool()
.withDescription("Ensures a param description has a hyphen before it (checks for -)");
o.addField("requireNewlineAfterDescription").canBool()
.withDescription("Ensures a doc comment description has padding newline");
o.addField("disallowNewlineAfterDescription").canBool()
.withDescription("Ensures a doc comment description has no padding newlines");
o.addField("requireDescriptionCompleteSentence").canBool()
.withDescription("Ensures a doc comment description is a complete sentence.");
o.addField("requireParamDescription").canBool()
.withDescription("Ensures a param description exists.");
o.addField("requireReturnDescription").canBool()
.withDescription("Checks a return description exists");
}))),
safeContextKeyword (descr().addType(str, NO_VALIDATION)
.addType(array, NO_VALIDATION)),
disallowPaddingNewlinesBeforeKeywords (descr().canBool().canKeywordsArray()),
disallowMultipleSpaces (descr().canBool()),
disallowKeywordsInComments (descr().canBool().addType(str, new JscsOptionDescriptor.StringVerifier((text) -> {
if (! text.startsWith("\\b(") || ! text.endsWith(")\\b")) {
return "String should be defined in format '\\b(word1|word2)\\b'";
}
return null;
}))
.addType(array, NO_VALIDATION)),
requireCapitalizedComments (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").addType(array, NO_VALIDATION)))),
disallowSpaceBeforeKeywords (descr().canBool().canKeywordsArray()),
requirePaddingNewLinesBeforeLineComments (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canString("firstAfterCurly")))),
requireDollarBeforejQueryAssignment (descr().canBool().canString("ignoreProperties")),
disallowFunctionDeclarations (descr().canBool()),
requireSpaceBeforeKeywords (descr().canBool().canKeywordsArray()),
disallowCapitalizedComments (descr().canBool()),
disallowSpaceBetweenArguments (descr().canBool()),
disallowSpacesInForStatement (descr().canBool()),
requirePaddingNewLinesAfterBlocks (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("inCallExpressions", "inNewExpressions", "inArrayExpressions", "inProperties")))),
requirePaddingNewlinesBeforeKeywords (descr().canBool().canKeywordsArray()),
disallowPaddingNewLinesBeforeLineComments (descr().canBool()),
requireLineBreakAfterVariableAssignment (descr().canBool()),
disallowCurlyBraces (descr().canBool().canKeywordsArray()),
disallowOperatorBeforeLineBreak (descr().canBool().canOperatorsArray()),
disallowPaddingNewLinesAfterBlocks (descr().canBool()),
disallowSemicolons (descr().canBool()),
requireSemicolons (descr().canBool()),
requireSpaceBetweenArguments (descr().canBool()),
disallowSpacesInCallExpression (descr().canBool()),
disallowIdentifierNames (descr().addType(array, NO_VALIDATION)),
requirePaddingNewLineAfterVariableDeclaration (descr().canBool()),
requirePaddingNewLinesInObjects (descr().canBool()),
disallowPaddingNewLinesInObjects (descr().canBool()),
requireSpacesInForStatement (descr().canBool()),
disallowSpacesInsideBrackets (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("[", "]", "{", "}")))),
requireSpacesInCallExpression (descr().canBool()),
requireQuotedKeysInObjects (descr().canBool()),
requireFunctionDeclarations (descr().canBool()),
requireSpacesInsideBrackets (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("[", "]", "{", "}")))),
disallowNamedUnassignedFunctions (descr().canBool()),
disallowNotOperatorsInConditionals (descr().canBool()),
disallowPaddingNewLinesAfterUseStrict (descr().canBool()),
disallowPaddingNewLinesBeforeExport (descr().canBool()),
maximumNumberOfLines (descr().canInteger()),
requireNamedUnassignedFunctions (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").addType(array, NO_VALIDATION)))),
requirePaddingNewLinesBeforeExport (descr().canBool()),
requireVarDeclFirst (descr().canBool()),
requireMatchingFunctionName (descr().canBool()),
requireTemplateStrings (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("stringConcatenation")))),
requireSpread (descr().canBool()),
requireShorthandArrowFunctions (descr().canBool()),
requireArrowFunctions (descr().canBool()),
disallowNodeTypes (descr().canExpandableStringArray()),
requireNumericLiterals (descr().canBool()),
validateAlignedFunctionParameters (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addBoolFields("lineBreakAfterOpeningBraces", "lineBreakBeforeClosingBraces")))),
validateNewlineAfterArrayElements (descr().canBool().canInteger().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("maximum").canInteger();
o.addBoolFields("ignoreBrackets");
}))),
disallowShorthandArrowFunctions (descr().canBool()),
disallowArrowFunctions (descr().canBool()),
validateOrderInObjectKeys (descr().canBool().canString("asc", "asc-insensitive", "asc-natural",
"desc", "desc-insensitive", "desc-natural")),
disallowEmptyBlocks (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("comments")))),
requirePaddingNewLinesAfterUseStrict (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("require")))),
// 02/2016
disallowIdenticalDestructuringNames (descr().canBool()),
disallowMultiLineTernary (descr().canBool()),
disallowNestedTernaries (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("maxLevel").canInteger()))),
disallowSpaceAfterComma (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("sparseArrays")))),
disallowSpacesInGenerator (spacesInGenerator()),
disallowSpacesInsideParenthesizedExpression (spacesInParenthesizedExpression()),
disallowSpacesInsideTemplateStringPlaceholders (descr().canBool()),
disallowTabs (descr().canBool()),
disallowUnusedParams (descr().canBool()),
disallowVar (descr().canBool()),
requireAlignedMultilineParams (descr().canBool().canInteger().canString("firstParam")),
requireArrayDestructuring (descr().canBool()),
requireCapitalizedConstructorsNew (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canExpandableStringArray()))),
requireEarlyReturn (descr().canBool()),
requireEnhancedObjectLiterals (descr().canBool()),
requireImportAlphabetized (descr().canBool()),
requireMultiLineTernary (descr().canBool()),
requireObjectDestructuring (descr().canBool()),
requireSpaceAfterComma (descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("trailing")))),
requireSpacesInGenerator (spacesInGenerator()),
requireSpacesInsideParenthesizedExpression (spacesInParenthesizedExpression()),
validateCommentPosition (descr().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("position").canString("above", "beside");
o.addField("allExcept").canExpandableStringArray();
}))),
disallowArrayDestructuringReturn (descr().canBool()),
disallowSpacesInsideImportedObjectBraces (descr().canBool()),
disallowUnusedVariables (descr().canBool()),
requireNewlineBeforeSingleStatementsInIf (descr().canBool()),
requireSpaceBeforeDestructuredValues (descr().canBool()),
requireSpacesInsideImportedObjectBraces (descr().canBool()),
requireUseStrict (descr().canBool()),
// options, not rules below
additionalRules (descr().addType(array, NO_VALIDATION)),
preset (descr().canString(JscsPreset.stringValues())),
excludeFiles (descr().addType(array, NO_VALIDATION)),
fileExtensions (descr().addType(str, new JscsOptionDescriptor.StringVerifier((text) -> {
final String trim = text.trim();
if ("*".equals(trim)) return null;
return "Expected array of file extensions, beginning with '.', or \"*\"";
})).
addType(array, new JscsOptionDescriptor.StringVerifier((text -> {
final String trim = text.trim();
if (trim.startsWith(".")) return null;
return "File extension should begin with '.'";
})))),
extract (descr().canBool().canExpandableStringArray()),
maxErrors (descr().canInteger()),
es3 (descr().canBool()),
errorFilter (descr().addType(str, NO_VALIDATION)),
plugins (descr().addType(array, NO_VALIDATION));
private static JscsOptionDescriptor spacesInParenthesizedExpression() {
return descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addField("allExcept").canStringArray("{", "}", "function")));
}
private static JscsOptionDescriptor spacesInGenerator() {
return descr().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> {
o.addField("beforeStar").canBool();
o.addField("afterStar").canBool();
o.mustNotBeEmpty();
}));
}
static {
disallowAnonymousFunctions.setDescription("Requires that a function expression be named.");
disallowCapitalizedComments.setDescription("Requires the first alphabetical character of a comment to be lowercase.");
disallowCommaBeforeLineBreak.setDescription("Disallows commas as last token on a line in lists.");
disallowCurlyBraces.setDescription("Disallows curly braces after statements.");
disallowDanglingUnderscores.setDescription("Disallows identifiers that start or end in _. Some popular identifiers are automatically listed as exceptions:");
disallowEmptyBlocks.setDescription("Disallows empty blocks (except for catch blocks).");
disallowFunctionDeclarations.setDescription("Disallows function declarations.");
disallowIdentifierNames.setDescription("Disallows a specified set of identifier names.");
disallowImplicitTypeConversion.setDescription("Disallows implicit type conversion.");
disallowKeywordsInComments.setDescription("Disallows keywords in your comments, such as TODO or FIXME");
disallowKeywordsOnNewLine.setDescription("Disallows placing keywords on a new line.");
disallowKeywords.setDescription("Disallows usage of specified keywords.");
disallowMixedSpacesAndTabs.setDescription("Requires lines to not contain both spaces and tabs consecutively, or spaces after tabs only for alignment if \"smart\"");
disallowMultipleLineBreaks.setDescription("Disallows multiple blank lines in a row.");
disallowMultipleLineStrings.setDescription("Disallows strings that span multiple lines without using concatenation.");
disallowMultipleSpaces.setDescription("Disallows multiple indentation characters (tabs or spaces) between identifiers, keywords, and any other token");
disallowMultipleVarDecl.setDescription("Disallows multiple var declaration (except for-loop).");
disallowNamedUnassignedFunctions.setDescription("Disallows unassigned functions to be named inline");
disallowNewlineBeforeBlockStatements.setDescription("Disallows newline before opening curly brace of all block statements.");
disallowNotOperatorsInConditionals.setDescription("Disallows the not, not equals, and strict not equals operators in conditionals.");
disallowOperatorBeforeLineBreak.setDescription("Requires putting certain operators on the next line rather than on the current line before a line break.");
disallowPaddingNewLinesAfterBlocks.setDescription("Disallow a newline after blocks");
disallowPaddingNewLinesAfterUseStrict.setDescription("Disallow a blank line after 'use strict'; statements");
disallowPaddingNewLinesBeforeExport.setDescription("Disallows newline before module.exports");
disallowPaddingNewlinesBeforeKeywords.setDescription("Disallow an empty line above the specified keywords.");
disallowPaddingNewLinesBeforeLineComments.setDescription("Disallows newline before line comments");
disallowPaddingNewlinesInBlocks.setDescription("Disallows blocks from beginning or ending with 2 newlines.");
disallowPaddingNewLinesInObjects.setDescription("Disallows newline inside curly braces of all objects.");
disallowQuotedKeysInObjects.setDescription("Disallows quoted keys in object if possible.");
disallowSemicolons.setDescription("Disallows lines from ending in a semicolon.");
disallowSpaceAfterBinaryOperators.setDescription("Requires sticking binary operators to the right.");
disallowSpaceAfterKeywords.setDescription("Disallows space after keyword.");
disallowSpaceAfterLineComment.setDescription("Requires that a line comment (//) not be followed by a space.");
disallowSpaceAfterObjectKeys.setDescription("Disallows space after object keys.");
disallowSpaceAfterPrefixUnaryOperators.setDescription("Requires sticking unary operators to the right.");
disallowSpaceBeforeBinaryOperators.setDescription("Requires sticking binary operators to the left.");
disallowSpaceBeforeBlockStatements.setDescription("Disallows space before block statements (for loops, control structures).");
disallowSpaceBeforeKeywords.setDescription("Disallows space before keyword.");
disallowSpaceBeforeObjectValues.setDescription("Disallows space after object keys.");
disallowSpaceBeforePostfixUnaryOperators.setDescription("Requires sticking unary operators to the left.");
disallowSpaceBetweenArguments.setDescription("Ensure there are no spaces after argument separators in call expressions.");
disallowSpacesInAnonymousFunctionExpression.setDescription("Disallows space before () or {} in anonymous function expressions.");
disallowSpacesInCallExpression.setDescription("Disallows space before () in call expressions.");
disallowSpacesInConditionalExpression.setDescription("Disallows space before and/or after ? or : in conditional expressions.");
disallowSpacesInForStatement.setDescription("Disallow spaces in between for statement.");
disallowSpacesInFunctionDeclaration.setDescription("Disallows space before () or {} in function declarations.");
disallowSpacesInFunctionExpression.setDescription("Disallows space before () or {} in function expressions (both named and anonymous).");
disallowSpacesInFunction.setDescription("Expression");
disallowSpacesInNamedFunctionExpression.setDescription("Disallows space before () or {} in named function expressions.");
disallowSpacesInsideArrayBrackets.setDescription("Disallows space after opening array square bracket and before closing.");
disallowSpacesInsideBrackets.setDescription("Disallows space after opening square bracket and before closing.");
disallowSpacesInsideObjectBrackets.setDescription("Disallows space after opening object curly brace and before closing.");
disallowSpacesInsideParentheses.setDescription("Disallows space after opening round bracket and before closing.");
disallowSpaceBeforeComma.setDescription("Disallows spaces before comma");
requireSpaceBeforeComma.setDescription("Requires space before comma");
disallowSpaceBeforeSemicolon.setDescription("Disallows spaces before semicolons");
disallowParenthesesAroundArrowParam.setDescription("Disallows parentheses around arrow function expressions with a single parameter");
requireParenthesesAroundArrowParam.setDescription("Requires parentheses around arrow function expressions with a single parameter");
disallowObjectKeysOnNewLine.setDescription("Disallows placing object keys on new line");
requireObjectKeysOnNewLine.setDescription("Requires placing object keys on new line");
disallowTrailingComma.setDescription("Disallows an extra comma following the final element of an array or object literal.");
disallowTrailingWhitespace.setDescription("Requires all lines to end on a non-whitespace character");
disallowYodaConditions.setDescription("Requires the variable to be the left hand operator when doing a boolean comparison");
maximumLineLength.setDescription("Requires all lines to be at most the number of characters specified");
maximumNumberOfLines.setDescription("Requires the file to be at most the number of lines specified");
requireAlignedObjectValues.setDescription("Requires proper alignment in object literals.");
requireAnonymousFunctions.setDescription("Requires that a function expression be anonymous.");
requireBlocksOnNewline.setDescription("Requires blocks to begin and end with a newline");
requireCamelCaseOrUpperCaseIdentifiers.setDescription("Requires identifiers to be camelCased or UPPERCASE_WITH_UNDERSCORES");
requireCapitalizedComments.setDescription("Requires the first alphabetical character of a comment to be uppercase, unless it is part of a multi-line textblock.");
requireCapitalizedConstructors.setDescription("Requires constructors to be capitalized (except for this)");
requireCommaBeforeLineBreak.setDescription("Requires commas as last token on a line in lists.");
requireCurlyBraces.setDescription("Requires curly braces after statements.");
requireDollarBeforejQueryAssignment.setDescription("Require a $ before variable names that are jquery assignments.");
requireDotNotation.setDescription("Requires member expressions to use dot notation when possible");
requireFunctionDeclarations.setDescription("Requires function declarations by disallowing assignment of functions expressions to variables. Function expressions are allowed in all other contexts, including when passed as function arguments or immediately invoked.");
requireKeywordsOnNewLine.setDescription("Requires placing keywords on a new line.");
requireLineBreakAfterVariableAssignment.setDescription("Requires placing line feed after assigning a variable.");
requireLineFeedAtFileEnd.setDescription("Requires placing line feed at file end.");
requireMultipleVarDecl.setDescription("Requires multiple var declaration.");
requireNamedUnassignedFunctions.setDescription("Require unassigned functions to be named inline");
requireNewlineBeforeBlockStatements.setDescription("Requires newline before opening curly brace of all block statements.");
requireOperatorBeforeLineBreak.setDescription("Requires operators to appear before line breaks and not after.");
requirePaddingNewLineAfterVariableDeclaration.setDescription("Requires an extra blank newline after var declarations, as long as it is not the last expression in the current block.");
requirePaddingNewLinesAfterBlocks.setDescription("Requires newline after blocks");
requirePaddingNewLinesAfterUseStrict.setDescription("Requires a blank line after 'use strict'; statements");
requirePaddingNewLinesBeforeExport.setDescription("Requires newline before module.exports");
requirePaddingNewlinesBeforeKeywords.setDescription("Requires an empty line above the specified keywords unless the keyword is the first expression in a block.");
requirePaddingNewLinesBeforeLineComments.setDescription("Requires newline before line comments");
requirePaddingNewlinesInBlocks.setDescription("Requires blocks to begin and end with 2 newlines");
requirePaddingNewLinesInObjects.setDescription("Requires newline inside curly braces of all objects.");
requireParenthesesAroundIIFE.setDescription("Requires parentheses around immediately invoked function expressions.");
requireQuotedKeysInObjects.setDescription("Requires quoted keys in objects.");
requireSemicolons.setDescription("Requires semicolon after:");
requireSpaceAfterBinaryOperators.setDescription("Disallows sticking binary operators to the right.");
requireSpaceAfterKeywords.setDescription("Requires space after keyword.");
requireSpaceAfterLineComment.setDescription("Requires that a line comment (//) be followed by a space.");
requireSpaceAfterObjectKeys.setDescription("Requires space after object keys.");
requireSpaceAfterPrefixUnaryOperators.setDescription("Disallows sticking unary operators to the right.");
requireSpaceBeforeBinaryOperators.setDescription("Disallows sticking binary operators to the left.");
requireSpaceBeforeBlockStatements.setDescription("Requires space(s) before block statements (for loops, control structures).");
requireSpaceBeforeKeywords.setDescription("Requires space before keyword.");
requireSpaceBeforeObjectValues.setDescription("Requires space after object keys.");
requireSpaceBeforePostfixUnaryOperators.setDescription("Disallows sticking unary operators to the left.");
requireSpaceBetweenArguments.setDescription("Ensure there are spaces after argument separators in call expressions.");
requireSpacesInAnonymousFunctionExpression.setDescription("Requires space before () or {} in anonymous function expressions.");
requireSpacesInCallExpression.setDescription("Requires space before () in call expressions.");
requireSpacesInConditionalExpression.setDescription("Requires space before and/or after ? or : in conditional expressions.");
requireSpacesInForStatement.setDescription("Requires spaces inbetween for statement.");
requireSpacesInFunctionDeclaration.setDescription("Requires space before () or {} in function declarations.");
requireSpacesInFunctionExpression.setDescription("Requires space before () or {} in function expressions (both named and anonymous).");
requireSpacesInFunction.setDescription("Expression");
requireSpacesInNamedFunctionExpression.setDescription("Requires space before () or {} in named function expressions.");
requireSpacesInsideArrayBrackets.setDescription("Requires space after opening array square bracket and before closing.");
requireSpacesInsideBrackets.setDescription("Requires space after opening square bracket and before closing.");
requireSpacesInsideObjectBrackets.setDescription("Requires space after opening object curly brace and before closing.");
requireSpacesInsideParentheses.setDescription("Requires space after opening round bracket and before closing.");
requireTrailingComma.setDescription("Requires an extra comma following the final element of an array or object literal.");
requireYodaConditions.setDescription("Requires the variable to be the right hand operator when doing a boolean comparison");
requireVarDeclFirst.setDescription("Requires var declaration to be on the top of an enclosing scope");
requireMatchingFunctionName.setDescription("Requires function names to match member and property names");
requireTemplateStrings.setDescription("Requires the use of template strings instead of string concatenation");
requireSpread.setDescription("Disallows using .apply in favor of the spread operator");
requireShorthandArrowFunctions.setDescription("Require arrow functions to use an expression body when returning a single statement (no block statement, implicit return)");
requireArrowFunctions.setDescription("Requires that arrow functions are used instead of anonymous function expressions in callbacks");
disallowNodeTypes.setDescription("Disallow use of certain node types (from Esprima/ESTree). Esprima node types");
requireNumericLiterals.setDescription("Requires use of binary, hexadecimal, and octal literals instead of parseInt");
safeContextKeyword.setDescription("Option to check var that = this expressions");
validateAlignedFunctionParameters.setDescription("Validates proper alignment of function parameters.");
validateIndentation.setDescription("Validates indentation for switch statements and block statements");
validateLineBreaks.setDescription("Option to check line break characters");
validateNewlineAfterArrayElements.setDescription("Requires each element in array on a single line when array length is more than passed maximum number or array fills more than one line. Set ignoreBrackets to true to allow elements on the same line with brackets.");
validateParameterSeparator.setDescription("Enable validation of separators between function parameters. Will ignore newlines.");
validateQuoteMarks.setDescription("Requires all quote marks to be either the supplied value, or consistent if true");
jsDoc.setDescription("Validate jsdoc comments");
disallowShorthandArrowFunctions.setDescription("Require arrow functions to use a block statement (explicit return)");
disallowArrowFunctions.setDescription("Disallows arrow functions");
validateOrderInObjectKeys.setDescription("Validates the order in object keys");
disallowEmptyBlocks.setDescription("Disallows empty blocks (except for catch blocks)");
//02/2016
disallowNestedTernaries.setDescription("Disallows nested ternaries");
disallowMultiLineTernary.setDescription("Disallows the test, consequent and alternate to be on separate lines when using the ternary operator");
disallowIdenticalDestructuringNames.setDescription("Disallows identical destructuring names for the key and value in favor of using shorthand destructuring");
disallowSpaceAfterComma.setDescription("Disallows spaces after commas");
disallowSpacesInGenerator.setDescription("Disallow space before or after * in generator functions");
disallowSpacesInsideParenthesizedExpression.setDescription("Disallows space after opening and before closing grouping parentheses.");
disallowSpacesInsideTemplateStringPlaceholders.setDescription("Disallows spaces before and after curly brace inside template string placeholders.");
disallowTabs.setDescription("Disallows tabs everywhere.");
disallowUnusedParams.setDescription("Disallows unused params in function expression and function declaration.");
disallowVar.setDescription("Disallows declaring variables with var.");
requireAlignedMultilineParams.setDescription("Enforces indentation of parameters in multiline functions");
requireArrayDestructuring.setDescription("Requires that variable assignment from array values are * destructured.");
requireCapitalizedConstructorsNew.setDescription("Requires capitalized constructors to to use the new keyword");
requireEarlyReturn.setDescription("Requires to return early in a function.");
requireEnhancedObjectLiterals.setDescription("Requires declaring objects via ES6 enhanced object literals");
requireImportAlphabetized.setDescription("Requires imports to be alphabetised");
requireMultiLineTernary.setDescription("Requires the test, consequent and alternate to be on separate lines when using the ternary operator.");
requireObjectDestructuring.setDescription("Requires variable declarations from objects via destructuring");
requireSpaceAfterComma.setDescription("Requires space after comma");
requireSpacesInGenerator.setDescription("Requires space before and after * in generator functions");
requireSpacesInsideParenthesizedExpression.setDescription("Requires space after opening and before closing grouping parentheses.");
validateCommentPosition.setDescription("This rule is for validating the positioning of line comments. Block comments are ignored.");
disallowArrayDestructuringReturn.setDescription("Requires object destructuring for multiple return values, not array destructuring.");
disallowSpacesInsideImportedObjectBraces.setDescription("Disallow space after opening object curly brace and before closing in import statements.");
disallowUnusedVariables.setDescription("Disallows unused variables defined with var, let or const.");
requireNewlineBeforeSingleStatementsInIf.setDescription("Requires newline before single if statements.");
requireSpaceBeforeDestructuredValues.setDescription("Require space after colon in object destructuring.");
requireSpacesInsideImportedObjectBraces.setDescription("Requires space after opening object curly brace and before closing in import statements.");
requireUseStrict.setDescription("Requires 'use strict'; statements.");
additionalRules.setDescription("Path to load additional rules");
preset.setDescription("Extends defined rules with preset rules.");
excludeFiles.setDescription("Disables style checking for specified paths.");
fileExtensions.setDescription("Changes the set of file extensions that will be processed.");
extract.setDescription("Set list of glob patterns for files which embedded JavaScript should be checked");
maxErrors.setDescription("Set the maximum number of errors to report");
es3.setDescription("Use ES3 reserved words");
errorFilter.setDescription("A filter function that determines whether or not to report an error. This will be called for every found error.");
plugins.setDescription("Paths to load plugins. See the wiki page for more details about the Plugin API");
}
private static JscsOptionDescriptor beforeBraces() {
return descr().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addBoolFields("beforeOpeningRoundBrace", "beforeOpeningCurlyBrace")));
}
private static JscsOptionDescriptor ternary() {
return descr().canBool().addType(obj, new JscsOptionDescriptor.ValuesObject((o)-> o.addBoolFields("afterTest", "beforeConsequent", "afterConsequent", "beforeAlternate")));
}
private static JscsOptionDescriptor boolOrKeywordsArray() {
return descr().canBool().canKeywordsArray();
}
private static JscsOptionDescriptor descr() {
return new JscsOptionDescriptor();
}
@Nullable
public static JscsOption safeValueOf(@NotNull final String name) {
try {
return valueOf(name);
}
catch (IllegalArgumentException e) {
return null;
}
}
private final JscsOptionDescriptor myDescriptor;
private String myDescription;
private final List<ValueType> myTypesList;
JscsOption(JscsOptionDescriptor descriptor) {
myDescriptor = descriptor;
myTypesList = new ArrayList<>(myDescriptor.getTypes().keySet());
Collections.sort(myTypesList);
}
public JscsOptionDescriptor getDescriptor() {
return myDescriptor;
}
public String getDescription() {
return myDescription;
}
public void setDescription(String description) {
myDescription = description;
}
public boolean canBe(ValueType type) {
return myDescriptor.getTypes().containsKey(type);
}
public List<ValueType> getTypesList() {
return myTypesList;
}
@NotNull
public List<ValueType> otherTypes(@Nullable ValueType type) {
if (type == null) return Collections.unmodifiableList(myTypesList);
if (myTypesList.size() == 1) return Collections.emptyList();
final List<ValueType> list = new ArrayList<>(myTypesList);
list.remove(type);
return list;
}
}
| 79.103041
| 270
| 0.722586
|
96d27e48843688298ca504bbddf2ac98cf850deb
| 9,055
|
//package group.rober.dataform.service;
//
//import com.fasterxml.jackson.databind.ObjectMapper;
//import com.fasterxml.jackson.databind.ObjectReader;
//import group.rober.base.dict.model.DictEntry;
//import group.rober.base.dict.service.DictService;
//import group.rober.dataform.autoconfigure.DataFormProperties;
//import group.rober.dataform.model.DataForm;
//import group.rober.dataform.service.impl.DataFormAdminServiceDBImpl;
//import group.rober.runtime.kit.JSONKit;
//import org.apache.commons.io.FileUtils;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Service;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.io.*;
//import java.nio.file.*;
//import java.nio.file.attribute.BasicFileAttributes;
//import java.util.ArrayList;
//import java.util.Collections;
//import java.util.EnumSet;
//import java.util.List;
//
//@Service
//public class JsonDBTransService {
//
// private final static Logger LOGGER = LoggerFactory.getLogger(JsonDBTransService.class);
//
// @Autowired
// DataFormProperties dataFormProperties;
//
// @Autowired
// DataFormAdminServiceDBImpl dataFormAdminService;
//
// @Autowired
// DictService dictService;
//
// @Autowired
// ObjectMapper objectMapper;
//
// private volatile Dirs exportDirs;
// private volatile Dirs importDirs;
//
// private final static String DEFAULT_JSON_PATH = "src/main/resources/dbjson";
//
// private Path getExportDir(String contextPath) {
// String path = dataFormProperties.getExportDir();
// if (null != path && !path.isEmpty()) return Paths.get(path);
// return Paths.get(System.getProperty("user.dir"), contextPath, DEFAULT_JSON_PATH);
// }
//
// private Path getImportDir(String contextPath) {
// return getExportDir(contextPath);
// }
//
// public void export2Json(String contextPath) throws IOException {
// Path path = getExportDir(contextPath);
// if (null == exportDirs)
// exportDirs = prepareExportDir(path);
// else
// prepareExportDir(path);
//
// List<DataForm> dataForms = dataFormAdminService.getCompleteDataForms();
// if (null != dataForms && !dataForms.isEmpty()) {
// String dfDir = exportDirs.dataformDir.toString();
// dataForms.forEach(dataForm -> {
// if (null == dataForm.getId() || dataForm.getId().isEmpty())
// return;
// try {
// Path dfPath = Files.createFile(Paths.get(dfDir, dataForm.getId() + ".json"));
// writeJsonFile(dfPath, dataForm);
// } catch (IOException ex) {
// LOGGER.warn(ex.getMessage());
// }
// });
// }
//
// List<DictEntry> dictEntries = dictService.getDictList();
// if (null != dictEntries && !dictEntries.isEmpty()) {
// String dicDir = exportDirs.dictionaryDir.toString();
// dictEntries.forEach(dictEntry -> {
// if (null == dictEntry.getCode() || dictEntry.getCode().isEmpty())
// return;
// try {
// Path dicPath = Files.createFile(Paths.get(dicDir, dictEntry.getCode() + ".json"));
// writeJsonFile(dicPath, dictEntry);
// } catch (IOException ex) {
// LOGGER.warn(ex.getMessage());
// }
// });
// }
// }
//
// private void writeJsonFile(Path file, Object obj) throws IOException{
// try(OutputStream outputStream = new BufferedOutputStream(
// Files.newOutputStream(file, StandardOpenOption.CREATE))) {
// objectMapper.writer().writeValue(outputStream, obj);
// outputStream.close();
// }
// }
//
// private Path ensureDirExist(Path path) throws IOException{
// try {
// return Files.createDirectories(path);
// } catch (FileAlreadyExistsException ex) {
// LOGGER.info(ex.getMessage());
// return path;
// }
// }
//
// private Dirs prepareExportDir(Path path) throws IOException{
// if (Files.notExists(path)) {
// path = ensureDirExist(path);
// Path dicDir = ensureDirExist(Paths.get(path.toString(), dataFormProperties.getDictionaryDir()));
// Path dataformDir = ensureDirExist(Paths.get(path.toString(), dataFormProperties.getDataformDir()));
// return new Dirs(dicDir, dataformDir);
// } else {
// Path dicDir = Paths.get(path.toString(), dataFormProperties.getDictionaryDir());
// Path dataformDir = Paths.get(path.toString(), dataFormProperties.getDataformDir());
// if (Files.notExists(dicDir))
// ensureDirExist(dicDir);
// else
// FileUtils.cleanDirectory(dicDir.toFile());
// if (Files.notExists(dataformDir))
// ensureDirExist(dataformDir);
// else
// FileUtils.cleanDirectory(dataformDir.toFile());
//
// return new Dirs(dicDir, dataformDir);
// }
// }
//
// @Transactional
// public void import2DB(String contextPath) throws IOException{
// if (null == importDirs) {
// Path path = getImportDir(contextPath);
// importDirs = new Dirs(Paths.get(path.toString(), dataFormProperties.getDictionaryDir()),
// Paths.get(path.toString(), dataFormProperties.getDataformDir()));
// }
// JsonFileVisitor<DataForm> dataFormJsonFileVisitor = new JsonFileVisitor<>(objectMapper.reader(),
// DataForm.class, Collections.synchronizedList(
// new ArrayList<>((int)Files.list(importDirs.dataformDir).count())));
// Files.walkFileTree(importDirs.dataformDir, EnumSet.noneOf(FileVisitOption.class), 1, dataFormJsonFileVisitor);
// if (null != dataFormJsonFileVisitor.objects && !dataFormJsonFileVisitor.objects.isEmpty()) {
// dataFormAdminService.deleteAll();
// dataFormJsonFileVisitor.objects.forEach(dataForm -> {
// try {
// dataFormAdminService.saveDataForm(dataForm, null);
// } catch (Exception ex) {
// System.err.println(JSONKit.toJsonString(dataForm));
// throw ex;
// }
// });
// }
//
// JsonFileVisitor<DictEntry> dictEntryJsonFileVisitor = new JsonFileVisitor<>(objectMapper.reader(),
// DictEntry.class, Collections.synchronizedList(
// new ArrayList<>((int)Files.list(importDirs.dictionaryDir).count())));
// Files.walkFileTree(importDirs.dictionaryDir, EnumSet.noneOf(FileVisitOption.class), 1, dictEntryJsonFileVisitor);
// if (null != dictEntryJsonFileVisitor.objects && !dictEntryJsonFileVisitor.objects.isEmpty()) {
// dictService.deleteAll();
// dictEntryJsonFileVisitor.objects.forEach(dictEntry -> dictService.save(dictEntry));
// }
// }
//
// private static class JsonFileVisitor<T> implements FileVisitor<Path> {
//
// protected final ObjectReader objectReader;
// protected final List<T> objects;
//
// JsonFileVisitor(ObjectReader objectReader, Class<T> tClass, List<T> objects) {
// this.objectReader = objectReader.forType(tClass);
// this.objects = objects;
// }
//
// @Override
// public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// String filePath = file.toString();
// if (!filePath.endsWith(".json")) return FileVisitResult.CONTINUE;
// try(InputStream inputStream = new BufferedInputStream(Files.newInputStream(file, StandardOpenOption.READ))) {
// objects.add(objectReader.readValue(inputStream));
// return FileVisitResult.CONTINUE;
// }
// }
//
// @Override
// public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
// LOGGER.warn(exc.getMessage());
// return FileVisitResult.CONTINUE;
// }
//
// @Override
// public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
// return FileVisitResult.CONTINUE;
// }
// }
//
//
//
// private static class Dirs {
// public final Path dictionaryDir;
// public final Path dataformDir;
//
// public Dirs(Path dictionaryDir, Path dataformDir) {
// this.dictionaryDir = dictionaryDir;
// this.dataformDir = dataformDir;
// }
// }
//
//}
| 41.536697
| 123
| 0.614246
|
0de825f01d93adaeae345da6df8b66fbd153e001
| 2,771
|
/*
* Copyright (c) 2021 yizzuide All rights Reserved.
* 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 com.github.yizzuide.milkomeda.pulsar;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* PulsarFlow
* 该注解应用于@RequestMapping注解的方法上,能通过DeferredResult技术延迟返回结果,让数据的返回更灵活,
* 使用场景如:长轮询、耗时请求fast-timeout等
*
* 注意:使用该注解的方法返回必需为 Object。(由于 SpringMVC 内部会对类型进行校验的机制,使用 Object 并不会影响实际处理结果)
*
* @author yizzuide
* @since 0.1.0
* @version 1.5.0
* Create at 2019/03/29 10:22
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface PulsarFlow {
/**
* 可选标注实际返回类型,只是让代码看起来更直观
* @return 实际返回的Class
*/
Class<?> returnClass() default Object.class;
/**
* 功能和returnClass一样
* @return 实际返回的Class
*/
Class<?> value() default Object.class;
/**
* 支持使用DeferredResult方式,推迟响应返回
* 使用方法:
* ``` @PulsarFlow(useDeferredResult=true)
* public Object method(..., PulsarDeferredResult deferredResult) {
* ...
* // 设置唯一标识符
* deferredResult.setDeferredResultID("235495954");
* // 返回任意数据,但内部不会获取这个值,在其它类中通过<code>PulsarHolder.getPulsar().getDeferredResult("唯一序列号").setResult(...)</code>返回
* return null;
* }
* ```
*
* @return 如果指定为 true,则使用DeferredResult,默认使用WebAsyncTask
*/
boolean useDeferredResult() default false;
/**
* 设置DeferredResult的ID标识,用于在返回时查找
* 1. 支持Spring EL表达式,如:#id
* 2. 支持HTTP Header获取表达式(内建支持),如:@token
* @return 如果有设置,则需要不在方法上添加PulsarDeferredResult参数来设置ID
*/
String id() default "";
}
| 34.209877
| 125
| 0.699747
|
540632d54333984c7ee4248e6abeb2b52fc3d6a1
| 2,200
|
package org.cat.eye.test.bundle.simple;
import org.cat.eye.engine.model.annotation.*;
import org.cat.eye.test.bundle.model.impl.FileCounterStoreImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Kotov on 30.09.2017.
*/
@IsComputable
public class FileCounterComputer implements Serializable {
private final static Logger LOGGER = LoggerFactory.getLogger(FileCounterComputer.class);
@Id
private final String path;
private List<FileCounterComputer> computers = new ArrayList<>();
private int numberLocalFiles;
public FileCounterComputer(String path) {
this.path = path;
}
public String getPath() {
return path;
}
@Compute
public List<FileCounterComputer> getDirectoriesAndFileCounter() throws Exception {
FileCounterStoreImpl store = new FileCounterStoreImpl();
int fileCount = 0;
File directory = new File(path);
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
computers.add(new FileCounterComputer(file.getAbsolutePath()));
LOGGER.info("getDirectoriesAndFileCounter - " +
"STEP-1: Computation with path [{}} was created.", file.getAbsolutePath());
} else {
fileCount++;
}
}
}
}
// write result
numberLocalFiles = fileCount;
if (fileCount != 0) {
store.putFileNumber(path, fileCount);
}
return computers;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FileCounterComputer)) return false;
FileCounterComputer that = (FileCounterComputer) o;
return path.equals(that.path);
}
@Override
public int hashCode() {
return path.hashCode();
}
}
| 25.882353
| 107
| 0.599091
|
d284dce30493d39483e3ffd582231378f409642e
| 507
|
package net.acomputerdog.securitycheckup.test.step;
import net.acomputerdog.securitycheckup.test.TestEnvironment;
public abstract class PassthroughStep<T> implements Step<T> {
private final Step<T> passthrough;
protected PassthroughStep(Step<T> passthrough) {
this.passthrough = passthrough;
}
@Override
public T run(TestEnvironment environment) {
return passthrough.run(environment);
}
public Step<T> getPassthrough() {
return passthrough;
}
}
| 23.045455
| 61
| 0.712032
|
ed7e76e6a7b01cd1418f15c8b90710822ae1d4b8
| 1,450
|
package com.example.reveallayout;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import butterknife.BindView;
import butterknife.ButterKnife;
/**
* @author Hendra Anggrian (hendraanggrian@gmail.com)
*/
public class MainActivity2 extends AppCompatActivity {
@BindView(R.id.button) FloatingActionButton button;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity2.this, SecondActivity2.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra(SecondActivity2.EXTRA_RECT, createRect(button));
startActivity(intent);
}
});
}
private Rect createRect(View view) {
Rect rect = new Rect();
view.getDrawingRect(rect);
((ViewGroup) view.getParent()).offsetDescendantRectToMyCoords(view, rect);
return rect;
}
}
| 32.954545
| 86
| 0.702759
|
84b4e19ff70f95ffc00d2291286d4886b9cec2ee
| 151
|
package com.example.faisal.ayat_syafiq;
/**
* Created by faisal on 1/20/18.
*/
public interface BackPressedListener {
void onBackPressed();
}
| 13.727273
| 39
| 0.708609
|
a50145ddac9e8c30bf8c6855929f58e4da73cdce
| 898
|
/*
* */
package com.synectiks.process.common.plugins.sidecar.rest.models;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.auto.value.AutoValue;
import com.synectiks.process.common.plugins.sidecar.rest.requests.ConfigurationAssignment;
import java.util.List;
@AutoValue
@JsonAutoDetect
public abstract class NodeConfiguration {
@JsonProperty
public abstract String nodeId();
@JsonProperty
public abstract List<ConfigurationAssignment> assignments();
@JsonCreator
public static NodeConfiguration create(@JsonProperty("node_id") String nodeId,
@JsonProperty("assignments") List<ConfigurationAssignment> assignments) {
return new AutoValue_NodeConfiguration(nodeId, assignments);
}
}
| 32.071429
| 116
| 0.758352
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.