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
|
|---|---|---|---|---|---|
08abc4b4515f78bf4d88494596b36de54ab5a4ce
| 212
|
package com.yang.firework;
/**
* Created by qinfeng on 16/8/4.
*/
class BlendFunc {
int src;
int dst;
public BlendFunc(int src, int dst) {
this.src = src;
this.dst = dst;
}
}
| 13.25
| 40
| 0.551887
|
b1e00bdaf7cb933a6da76b3801c6d4cb5bdad489
| 19,519
|
package org.lantern;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.concurrent.atomic.AtomicReference;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.TrustManagerFactory;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.lantern.event.Events;
import org.lantern.event.PeerCertEvent;
import org.lastbamboo.common.offer.answer.IceConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Charsets;
import com.google.inject.Inject;
import com.google.inject.Singleton;
/**
* This class manages the local trust store of external entities we trust
* for creating SSL connections. This includes both hard coded certificates
* for a small number of services we use as well as dynamically added
* certificates for peers. Peer certificates must be discovered and added
* through a trusted channel such as one of the hard coded trusted authorities
* (aka Google Talk with its equifax certificate as of this writing).
*/
@Singleton
public class LanternTrustStore {
private final static Logger LOGGER =
LoggerFactory.getLogger(LanternTrustStore.class);
private static final String CIPHER_SUITE_LOW_BIT =
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA";
private final AtomicReference<SSLContext> sslContextRef =
new AtomicReference<SSLContext>();
private final LanternKeyStoreManager ksm;
private final KeyStore trustStore;
private TrustManagerFactory tmf;
static {
try {
configureCipherSuites();
} catch (Throwable t) {
LOGGER.error("Unable to configure cipher suites: {}", t.getMessage(), t);
}
}
private static void configureCipherSuites() {
Security.addProvider(new BouncyCastleProvider());
IceConfig.setCipherSuites(new String[] {
CIPHER_SUITE_LOW_BIT
});
}
@Inject
public LanternTrustStore(final LanternKeyStoreManager ksm) {
this.ksm = ksm;
this.trustStore = blankTrustStore();
this.tmf = initTrustManagerFactory();
}
/**
* Every time the trust store changes, we need to recreate particularly
* our SSL context because we now trust different servers. We reload only
* on trust store changes as an optimization to avoid loading the whole
* SSL context from scratch for each new outgoing socket.
*/
private void onTrustStoreChanged() {
this.tmf = initTrustManagerFactory();
this.sslContextRef.set(provideSslContext());
}
private TrustManagerFactory initTrustManagerFactory() {
try {
final TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(
TrustManagerFactory.getDefaultAlgorithm());
// We create the trust manager factory with the latest trust store.
trustManagerFactory.init(this.trustStore);
return trustManagerFactory;
} catch (final NoSuchAlgorithmException e) {
LOGGER.error("Could not load algorithm?", e);
throw new Error("Could not load algorithm", e);
} catch (final KeyStoreException e) {
LOGGER.error("Could not load keystore?", e);
throw new Error("Could not load keystore for tmf", e);
}
}
private KeyStore blankTrustStore() {
try {
final KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null);
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
addCert(ks, cf, "littleproxy", LITTLEPROXY);
addCert(ks, cf, "digicerthighassurancerootca", DIGICERT);
addCert(ks, cf, "equifaxsecureca", EQUIFAX);
addCert(ks, cf, "equifaxsecureca2", EQUIFAX2);
return ks;
} catch (final KeyStoreException e) {
LOGGER.error("Could not load keystore?", e);
throw new Error("Could not load blank trust store", e);
} catch (final NoSuchAlgorithmException e) {
LOGGER.error("No such algo?", e);
throw new Error("Could not load blank trust store", e);
} catch (final CertificateException e) {
LOGGER.error("Bad cert?", e);
throw new Error("Could not load blank trust store", e);
} catch (final IOException e) {
LOGGER.error("Could not load?", e);
throw new Error("Could not load blank trust store", e);
}
}
private void addCert(final KeyStore ks, final CertificateFactory cf,
final String alias, final String pemCert)
throws CertificateException, KeyStoreException {
final InputStream bis =
new ByteArrayInputStream(pemCert.getBytes(Charsets.UTF_8));
final Certificate cert = cf.generateCertificate(bis);
ks.setCertificateEntry(alias, cert);
}
public void addCert(String pemCert) {
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
InputStream bis
= new ByteArrayInputStream(pemCert.getBytes(Charsets.UTF_8));
X509Certificate cert
= (X509Certificate)cf.generateCertificate(bis);
String alias = getCertAlias(cert);
this.trustStore.setCertificateEntry(alias, cert);
onTrustStoreChanged();
} catch (CertificateException e) {
LOGGER.error("Couldn't create certificate", e);
} catch (KeyStoreException e) {
LOGGER.error("Could not load cert into keystore", e);
}
}
public void addCert(final String alias, final String pemCert)
throws CertificateException, KeyStoreException {
final CertificateFactory cf = CertificateFactory.getInstance("X.509");
addCert(this.trustStore, cf, alias, pemCert);
onTrustStoreChanged();
}
public void addCert(URI jid, Certificate cert) {
LOGGER.debug("Adding cert for {} to trust store", jid);
Events.asyncEventBus().post(new PeerCertEvent(jid, cert));
try {
this.trustStore.setCertificateEntry(jid.toASCIIString(), cert);
} catch (KeyStoreException e) {
LOGGER.error("Could not load cert into keystore?", e);
}
onTrustStoreChanged();
}
/**
* Accessor for the SSL context. This is regenerated whenever
* we receive new certificates.
*
* @return The SSL context.
*/
public synchronized SSLContext getSslContext() {
if (this.sslContextRef.get() == null) {
this.sslContextRef.set(provideSslContext());
}
final SSLContext context = sslContextRef.get();
LOGGER.debug("Returning context: {}", context);
return context;
}
/**
* Return an new/unused {@link SSLEngine} reflecting our {@link SSLContext}.
* For performance, these are created eagerly ahead of time.
*/
public SSLEngine newSSLEngine() {
LOGGER.debug("Creating a new SSL engine...");
final SSLEngine engine = getSslContext().createSSLEngine();
// Make sure only TLS is enabled to get around SSLv3 attacks such as
// poodle. See:
// http://www.oracle.com/technetwork/java/javase/documentation/cve-2014-3566-2342133.html
engine.setEnabledProtocols(new String[] {"TLSv1"});
return engine;
}
private SSLContext provideSslContext() {
try {
final SSLContext context = SSLContext.getInstance("TLS");
// Create the context with the latest trust manager factory.
context.init(this.ksm.getKeyManagerFactory().getKeyManagers(),
this.tmf.getTrustManagers(), null);
return context;
} catch (final Exception e) {
LOGGER.error("Failed to initialize the client-side SSLContext", e);
throw new Error(
"Failed to initialize the client-side SSLContext", e);
}
}
public void deleteCert(final String alias) {
try {
this.trustStore.deleteEntry(alias);
onTrustStoreChanged();
} catch (final KeyStoreException e) {
LOGGER.debug("Error removing entry -- doesn't exist?", e);
}
}
/**
* Checks if the trust store contains exactly this certificate. This
* doesn't worry about certificate chaining or anything like that --
* this trust store must instead contain the actual certificate.
*
* @param cert The certificate to check.
* @return <code>true</code> if the trust store contains the certificate,
* otherwise <code>false</code>.
*/
public boolean containsCertificate(final X509Certificate cert) {
LOGGER.debug("Loading trust store...");
// We could use KeyStore.getCertificateAlias here, but that will
// iterate through everything, potentially causing issues when there
// are a lot of certs.
final String alias = getCertAlias(cert);
LOGGER.debug("Looking for alias {}", alias);
try {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("All aliases");
Enumeration<String> aliases = this.trustStore.aliases();
while (aliases.hasMoreElements()) {
LOGGER.debug(aliases.nextElement());
}
}
final Certificate existingCert = this.trustStore.getCertificate(alias);
LOGGER.trace("Existing certificate: {}", (existingCert));
return existingCert != null && existingCert.equals(cert);
} catch (final KeyStoreException e) {
LOGGER.warn("Exception accessing keystore", e);
return false;
}
}
private String getCertAlias(X509Certificate cert) {
return cert.getIssuerDN().getName().substring(3).toLowerCase();
}
private void listEntries(final KeyStore ks) {
try {
final Enumeration<String> aliases = ks.aliases();
while (aliases.hasMoreElements()) {
final String alias = aliases.nextElement();
//System.err.println(alias+": "+ks.getCertificate(alias));
System.err.println(alias);
LOGGER.debug(alias);
}
} catch (final KeyStoreException e) {
LOGGER.warn("KeyStore error", e);
}
}
public void listEntries() {
listEntries(trustStore);
}
private static final String EQUIFAX =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDIDCCAomgAwIBAgIENd70zzANBgkqhkiG9w0BAQUFADBOMQswCQYDVQQGEwJV\n"
+ "UzEQMA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2Vy\n"
+ "dGlmaWNhdGUgQXV0aG9yaXR5MB4XDTk4MDgyMjE2NDE1MVoXDTE4MDgyMjE2NDE1\n"
+ "MVowTjELMAkGA1UEBhMCVVMxEDAOBgNVBAoTB0VxdWlmYXgxLTArBgNVBAsTJEVx\n"
+ "dWlmYXggU2VjdXJlIENlcnRpZmljYXRlIEF1dGhvcml0eTCBnzANBgkqhkiG9w0B\n"
+ "AQEFAAOBjQAwgYkCgYEAwV2xWGcIYu6gmi0fCG2RFGiYCh7+2gRvE4RiIcPRfM6f\n"
+ "BeC4AfBONOziipUEZKzxa1NfBbPLZ4C/QgKO/t0BCezhABRP/PvwDN1Dulsr4R+A\n"
+ "cJkVV5MW8Q+XarfCaCMczE1ZMKxRHjuvK9buY0V7xdlfUNLjUA86iOe/FP3gx7kC\n"
+ "AwEAAaOCAQkwggEFMHAGA1UdHwRpMGcwZaBjoGGkXzBdMQswCQYDVQQGEwJVUzEQ\n"
+ "MA4GA1UEChMHRXF1aWZheDEtMCsGA1UECxMkRXF1aWZheCBTZWN1cmUgQ2VydGlm\n"
+ "aWNhdGUgQXV0aG9yaXR5MQ0wCwYDVQQDEwRDUkwxMBoGA1UdEAQTMBGBDzIwMTgw\n"
+ "ODIyMTY0MTUxWjALBgNVHQ8EBAMCAQYwHwYDVR0jBBgwFoAUSOZo+SvSspXXR9gj\n"
+ "IBBPM5iQn9QwHQYDVR0OBBYEFEjmaPkr0rKV10fYIyAQTzOYkJ/UMAwGA1UdEwQF\n"
+ "MAMBAf8wGgYJKoZIhvZ9B0EABA0wCxsFVjMuMGMDAgbAMA0GCSqGSIb3DQEBBQUA\n"
+ "A4GBAFjOKer89961zgK5F7WF0bnj4JXMJTENAKaSbn+2kmOeUJXRmm/kEd5jhW6Y\n"
+ "7qj/WsjTVbJmcVfewCHrPSqnI0kBBIZCe/zuf6IWUrVnZ9NA2zsmWLIodz2uFHdh\n"
+ "1voqZiegDfqnc1zqcPGUIWVEX/r87yloqaKHee9570+sB3c4\n"
+ "-----END CERTIFICATE-----";
private static final String EQUIFAX2 =
//i:/C=US/O=Equifax/OU=Equifax Secure Certificate Authority
"-----BEGIN CERTIFICATE-----\n"
+ "MIIDfTCCAuagAwIBAgIDErvmMA0GCSqGSIb3DQEBBQUAME4xCzAJBgNVBAYTAlVT\n"
+ "MRAwDgYDVQQKEwdFcXVpZmF4MS0wKwYDVQQLEyRFcXVpZmF4IFNlY3VyZSBDZXJ0\n"
+ "aWZpY2F0ZSBBdXRob3JpdHkwHhcNMDIwNTIxMDQwMDAwWhcNMTgwODIxMDQwMDAw\n"
+ "WjBCMQswCQYDVQQGEwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UE\n"
+ "AxMSR2VvVHJ1c3QgR2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\n"
+ "CgKCAQEA2swYYzD99BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9m\n"
+ "OSm9BXiLnTjoBbdqfnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIu\n"
+ "T8rxh0PBFpVXLVDviS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6c\n"
+ "JmTM386DGXHKTubU1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmR\n"
+ "Cw7+OC7RHQWa9k0+bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5asz\n"
+ "PeE4uwc2hGKceeoWMPRfwCvocWvk+QIDAQABo4HwMIHtMB8GA1UdIwQYMBaAFEjm\n"
+ "aPkr0rKV10fYIyAQTzOYkJ/UMB0GA1UdDgQWBBTAephojYn7qwVkDBF9qn1luMrM\n"
+ "TjAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjA6BgNVHR8EMzAxMC+g\n"
+ "LaArhilodHRwOi8vY3JsLmdlb3RydXN0LmNvbS9jcmxzL3NlY3VyZWNhLmNybDBO\n"
+ "BgNVHSAERzBFMEMGBFUdIAAwOzA5BggrBgEFBQcCARYtaHR0cHM6Ly93d3cuZ2Vv\n"
+ "dHJ1c3QuY29tL3Jlc291cmNlcy9yZXBvc2l0b3J5MA0GCSqGSIb3DQEBBQUAA4GB\n"
+ "AHbhEm5OSxYShjAGsoEIz/AIx8dxfmbuwu3UOx//8PDITtZDOLC5MH0Y0FWDomrL\n"
+ "NhGc6Ehmo21/uBPUR/6LWlxz/K7ZGzIZOKuXNBSqltLroxwUCEm2u+WR74M26x1W\n"
+ "b8ravHNjkOR/ez4iyz0H7V84dJzjA1BOoa+Y7mHyhD8S\n"
+ "-----END CERTIFICATE-----";
private static final String DIGICERT =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIGWDCCBUCgAwIBAgIQCl8RTQNbF5EX0u/UA4w/OzANBgkqhkiG9w0BAQUFADBs\n"
+ "MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n"
+ "d3cuZGlnaWNlcnQuY29tMSswKQYDVQQDEyJEaWdpQ2VydCBIaWdoIEFzc3VyYW5j\n"
+ "ZSBFViBSb290IENBMB4XDTA4MDQwMjEyMDAwMFoXDTIyMDQwMzAwMDAwMFowZjEL\n"
+ "MAkGA1UEBhMCVVMxFTATBgNVBAoTDERpZ2lDZXJ0IEluYzEZMBcGA1UECxMQd3d3\n"
+ "LmRpZ2ljZXJ0LmNvbTElMCMGA1UEAxMcRGlnaUNlcnQgSGlnaCBBc3N1cmFuY2Ug\n"
+ "Q0EtMzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL9hCikQH17+NDdR\n"
+ "CPge+yLtYb4LDXBMUGMmdRW5QYiXtvCgFbsIYOBC6AUpEIc2iihlqO8xB3RtNpcv\n"
+ "KEZmBMcqeSZ6mdWOw21PoF6tvD2Rwll7XjZswFPPAAgyPhBkWBATaccM7pxCUQD5\n"
+ "BUTuJM56H+2MEb0SqPMV9Bx6MWkBG6fmXcCabH4JnudSREoQOiPkm7YDr6ictFuf\n"
+ "1EutkozOtREqqjcYjbTCuNhcBoz4/yO9NV7UfD5+gw6RlgWYw7If48hl66l7XaAs\n"
+ "zPw82W3tzPpLQ4zJ1LilYRyyQLYoEt+5+F/+07LJ7z20Hkt8HEyZNp496+ynaF4d\n"
+ "32duXvsCAwEAAaOCAvowggL2MA4GA1UdDwEB/wQEAwIBhjCCAcYGA1UdIASCAb0w\n"
+ "ggG5MIIBtQYLYIZIAYb9bAEDAAIwggGkMDoGCCsGAQUFBwIBFi5odHRwOi8vd3d3\n"
+ "LmRpZ2ljZXJ0LmNvbS9zc2wtY3BzLXJlcG9zaXRvcnkuaHRtMIIBZAYIKwYBBQUH\n"
+ "AgIwggFWHoIBUgBBAG4AeQAgAHUAcwBlACAAbwBmACAAdABoAGkAcwAgAEMAZQBy\n"
+ "AHQAaQBmAGkAYwBhAHQAZQAgAGMAbwBuAHMAdABpAHQAdQB0AGUAcwAgAGEAYwBj\n"
+ "AGUAcAB0AGEAbgBjAGUAIABvAGYAIAB0AGgAZQAgAEQAaQBnAGkAQwBlAHIAdAAg\n"
+ "AEMAUAAvAEMAUABTACAAYQBuAGQAIAB0AGgAZQAgAFIAZQBsAHkAaQBuAGcAIABQ\n"
+ "AGEAcgB0AHkAIABBAGcAcgBlAGUAbQBlAG4AdAAgAHcAaABpAGMAaAAgAGwAaQBt\n"
+ "AGkAdAAgAGwAaQBhAGIAaQBsAGkAdAB5ACAAYQBuAGQAIABhAHIAZQAgAGkAbgBj\n"
+ "AG8AcgBwAG8AcgBhAHQAZQBkACAAaABlAHIAZQBpAG4AIABiAHkAIAByAGUAZgBl\n"
+ "AHIAZQBuAGMAZQAuMBIGA1UdEwEB/wQIMAYBAf8CAQAwNAYIKwYBBQUHAQEEKDAm\n"
+ "MCQGCCsGAQUFBzABhhhodHRwOi8vb2NzcC5kaWdpY2VydC5jb20wgY8GA1UdHwSB\n"
+ "hzCBhDBAoD6gPIY6aHR0cDovL2NybDMuZGlnaWNlcnQuY29tL0RpZ2lDZXJ0SGln\n"
+ "aEFzc3VyYW5jZUVWUm9vdENBLmNybDBAoD6gPIY6aHR0cDovL2NybDQuZGlnaWNl\n"
+ "cnQuY29tL0RpZ2lDZXJ0SGlnaEFzc3VyYW5jZUVWUm9vdENBLmNybDAfBgNVHSME\n"
+ "GDAWgBSxPsNpA/i/RwHUmCYaCALvY2QrwzAdBgNVHQ4EFgQUUOpzidsp+xCPnuUB\n"
+ "INTeeZlIg/cwDQYJKoZIhvcNAQEFBQADggEBAB7ipUiebNtTOA/vphoqrOIDQ+2a\n"
+ "vD6OdRvw/S4iWawTwGHi5/rpmc2HCXVUKL9GYNy+USyS8xuRfDEIcOI3ucFbqL2j\n"
+ "CwD7GhX9A61YasXHJJlIR0YxHpLvtF9ONMeQvzHB+LGEhtCcAarfilYGzjrpDq6X\n"
+ "dF3XcZpCdF/ejUN83ulV7WkAywXgemFhM9EZTfkI7qA5xSU1tyvED7Ld8aW3DiTE\n"
+ "JiiNeXf1L/BXunwH1OH8zVowV36GEEfdMR/X/KLCvzB8XSSq6PmuX2p0ws5rs0bY\n"
+ "Ib4p1I5eFdZCSucyb6Sxa1GDWL4/bcf72gMhy2oWGU4K8K2Eyl2Us1p292E=\n"
+ "-----END CERTIFICATE-----";
private static final String LITTLEPROXY =
"-----BEGIN CERTIFICATE-----\n"
+ "MIIEqjCCApKgAwIBAgIETSOp+zANBgkqhkiG9w0BAQUFADAWMRQwEgYDVQQDEwts\n"
+ "aXR0bGVwcm94eTAgFw0xMTAxMDQyMzE1MDdaGA8yMTEwMTIxMTIzMTUwN1owFjEU\n"
+ "MBIGA1UEAxMLbGl0dGxlcHJveHkwggIiMA0GCSqGSIb3DQEBAQUAA4ICDwAwggIK\n"
+ "AoICAQCm4Ulsi69ZqgeSf+aVDFlVMkMWzYKomTcDFCX9rpys+nKiLpKbzXKruBUM\n"
+ "Ud9BSG1I3eiJ9jJP77f5DpW0z2bptOHSRi0a9GOpx6I8AjKBvKH2CtV8cnGsopN8\n"
+ "JMMop6tZ7hVRo3M0BmGh9SgAQaX46nVIwcA3oUSLQKEqAsw8WVmbYJhwNWpPAl5M\n"
+ "0BT/ElEKG2LPaB0ha+8mFeT3haq4Jeuxeb5MfnpuEnLQ4FTre27f7bO3r/QaxVpu\n"
+ "UHF6MyMjoQCcjUO99Fo6a0poo6XX7ys9jnPEl44Pt36ygced2S3U4ZtchWWf634B\n"
+ "Wh5jmHtrcdOo94emzHGdah+XnTJI5BYUyNgNeI/8D3OyTlVWxUDU4f/9XqxVtc1F\n"
+ "KjMe33eT6kL2s5GWaT+1R9dJ4TCFizPQrWrwu2IDbyDj2sJGdSrjj+w2kHQ/V17q\n"
+ "AD2TmDlMmIvrqRc1lptBhcSpdTp5EoZEvgwTyRM7jpwDj5rAUXV8eu/93NcImJY2\n"
+ "QkGxAamB2vFWwxxYShKUqyG1zxyIF1cvWnAywgZuE4t5TGiZ9AIor5XkNDcaE0pj\n"
+ "6yJtblOFhSKiJgSUR49dl0D39fzy++gkkWmjgUuRTMglx0wAFPxFa/TGhfK0Ukze\n"
+ "WpJxoWHR06+EPN0kj/nagk5q4Ovz8EOZratTwToCEi9Doe5N8wIDAQABMA0GCSqG\n"
+ "SIb3DQEBBQUAA4ICAQBiLlzTzBfFsvtfz6ll8mU8jptS6A3YV7Zldon25I/xQlik\n"
+ "72hS25+s2U3mzcIz1kkdSYhyTa8B1JhXygnUYkJV+AShP5+tlcYXWq1YMx9GrKC2\n"
+ "SEOrsmt2tHLJS03oyCZfYcKdoJMRoTXnKe8WDs7M4iFSXGeaFn1SePbdjNMGHCVT\n"
+ "Cr58PhCxigXushNAVy5GZFh0gcFeMIYJIUqJADbw4IyicXpcUdQJHs7DkvXxquXZ\n"
+ "rNv2NKWlqQI2iwn2Aow8V0c7mud/kGdzLFM18NZVfZQsWWBWXP3CxUPGGrfaxiCH\n"
+ "aLo1i9KnD6yEw9x/0mcajy3VN4y8QdJpgPhGDQXMMvqDWIEouy05sES4V0GVTksQ\n"
+ "42SscqVWyT0HNRgmvOQHEc9Oh9mkCuspEzSA+LH1CGYc+dSTUTZUO+MmcfMDYpj4\n"
+ "NkLH/AgVwKPiFyD5MUYi7isLJnfpkmZcgJOL/FXtGmLeD8nt8eRPRS4YZMLDtd/9\n"
+ "FVo6KC1mlaiosLys7wUBuu15HdyJrkD+k4ZNrkx/oMlcLOgPdz2Qkue3Rqa9DRuX\n"
+ "jwwv90xVufuOJ5mYcQ2VA80x8YT+XTq194BGSqYAAU8Rq1/5fAMg5cwhg4BDjmY2\n"
+ "ok2U3fCl58xbiwp6owpamVoPblrq7Zl4ylyF33H6ewM+f5XA+L1iC5KWs9q8Kw==\n"
+ "-----END CERTIFICATE-----";
}
| 48.554726
| 97
| 0.685588
|
24a70dd5b06371ed906e57a43d3df90188ad6309
| 8,852
|
/*
* Copyright 2018 Murat Artim (muratartim@gmail.com).
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package equinox.task;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.jfree.data.xy.XYDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import equinox.Equinox;
import equinox.controller.ExternalPlotViewPanel;
import equinox.controller.InputPanel;
import equinox.controller.ViewPanel;
import equinox.data.EmbeddedTask;
import equinox.data.ExecutionMode;
import equinox.data.SeriesKey;
import equinox.data.fileType.ExternalFlight;
import equinox.data.fileType.ExternalStressSequence;
import equinox.data.input.ExternalFlightPlotInput;
import equinox.serverUtilities.Permission;
import equinox.task.InternalEquinoxTask.ShortRunningTask;
import equinox.task.automation.AutomaticTaskOwner;
import equinox.task.automation.MultipleInputTask;
/**
* Class for plot external typical flights task.
*
* @author Murat Artim
* @date Mar 15, 2015
* @time 5:10:42 PM
*/
public class PlotExternalTypicalFlights extends InternalEquinoxTask<XYDataset> implements ShortRunningTask, MultipleInputTask<ExternalFlight>, AutomaticTaskOwner<XYDataset> {
/** Automatic inputs. */
private final List<ExternalFlight> flights_;
/** Plot input. */
private final ExternalFlightPlotInput input_;
/** Input threshold. Once the threshold is reached, this task will be executed. */
private volatile int inputThreshold_ = 0;
/** Automatic tasks. */
private HashMap<String, EmbeddedTask<XYDataset>> automaticTasks_ = null;
/**
* Creates plot STH flights task.
*
* @param input
* Plot input.
*/
public PlotExternalTypicalFlights(ExternalFlightPlotInput input) {
input_ = input;
flights_ = Collections.synchronizedList(new ArrayList<>());
}
/**
* Adds typical flight.
*
* @param flight
* Typical flight to add.
*/
public void addTypicalFlight(ExternalFlight flight) {
flights_.add(flight);
}
@Override
synchronized public void setInputThreshold(int inputThreshold) {
inputThreshold_ = inputThreshold;
}
@Override
synchronized public void addAutomaticInput(AutomaticTaskOwner<ExternalFlight> task, ExternalFlight input, ExecutionMode mode) {
automaticInputAdded(task, input, mode, flights_, inputThreshold_);
}
@Override
synchronized public void inputFailed(AutomaticTaskOwner<ExternalFlight> task, ExecutionMode mode) {
inputThreshold_ = automaticInputFailed(task, mode, flights_, inputThreshold_);
}
@Override
public void addAutomaticTask(String taskID, EmbeddedTask<XYDataset> task) {
if (automaticTasks_ == null) {
automaticTasks_ = new HashMap<>();
}
automaticTasks_.put(taskID, task);
}
@Override
public HashMap<String, EmbeddedTask<XYDataset>> getAutomaticTasks() {
return automaticTasks_;
}
@Override
public String getTaskTitle() {
return "Plot external typical flights";
}
@Override
public boolean canBeCancelled() {
return false;
}
@Override
protected XYDataset call() throws Exception {
// check permission
checkPermission(Permission.PLOT_TYPICAL_FLIGHT);
// update progress info
updateTitle("Plotting external typical flights...");
// create dataset
XYSeriesCollection dataset = new XYSeriesCollection();
// get database connection
try (Connection connection = Equinox.DBC_POOL.getConnection()) {
// plot stresses
plot(connection, dataset);
}
// return dataset
return dataset;
}
@Override
protected void succeeded() {
// call ancestor
super.succeeded();
// set chart data
try {
// get chart data
XYDataset dataset = get();
// user initiated task
if (automaticTasks_ == null) {
// get spectrum view panel
ExternalPlotViewPanel panel = (ExternalPlotViewPanel) taskPanel_.getOwner().getOwner().getViewPanel().getSubPanel(ViewPanel.EXTERNAL_PLOT_VIEW);
// set data
panel.plottingCompleted(dataset);
// show spectrum plot panel
taskPanel_.getOwner().getOwner().getViewPanel().showSubPanel(ViewPanel.EXTERNAL_PLOT_VIEW);
taskPanel_.getOwner().getOwner().getInputPanel().showSubPanel(InputPanel.PLOT_EXTERNAL_FLIGHTS_PANEL);
}
// automatic task
else {
automaticTaskOwnerSucceeded(dataset, automaticTasks_, taskPanel_);
}
}
// exception occurred
catch (InterruptedException | ExecutionException e) {
handleResultRetrievalException(e);
}
}
@Override
protected void failed() {
// call ancestor
super.failed();
// manage automatic tasks
automaticTaskOwnerFailed(automaticTasks_);
}
@Override
protected void cancelled() {
// call ancestor
super.cancelled();
// manage automatic tasks
automaticTaskOwnerFailed(automaticTasks_);
}
/**
* Plots input flights on the given chart.
*
* @param connection
* Database connection.
* @param dataset
* Dataset.
* @throws Exception
* If exception occurs during process.
*/
private void plot(Connection connection, XYSeriesCollection dataset) throws Exception {
// get flight IDs
updateMessage("Plotting stresses...");
// create statement
try (Statement statement = connection.createStatement()) {
// prepare statement to get file id
String sql = "select file_id from ext_sth_flights where flight_id = ?";
try (PreparedStatement getFileId = connection.prepareStatement(sql)) {
// loop over flights
for (ExternalFlight flight : flights_) {
// update info
updateMessage("Getting peaks for flight '" + flight.getName() + "' from database...");
// create series name
String name = getFlightName(flight);
// create series
XYSeries series = new XYSeries(new SeriesKey(checkName(name, dataset), flight.getID()));
// get file id
int fileId = -1;
getFileId.setInt(1, flight.getID());
try (ResultSet resultSet = getFileId.executeQuery()) {
if (resultSet.next()) {
fileId = resultSet.getInt("file_id");
}
}
// create query
sql = "select peak_num, peak_val from ext_sth_peaks_" + fileId + " where flight_id = " + flight.getID() + " order by peak_num";
// add chart data to series
try (ResultSet resultSet = statement.executeQuery(sql)) {
// loop over peaks
while (resultSet.next()) {
// get peak number
int peakNum = resultSet.getInt("peak_num");
// get stress
double stress = resultSet.getDouble("peak_val");
// add to data
series.add(peakNum, stress);
}
}
// add series to dataset
dataset.addSeries(series);
}
}
}
}
/**
* Returns flight name.
*
* @param flight
* Flight.
* @return Flight name.
*/
private String getFlightName(ExternalFlight flight) {
// initialize name
String name = "";
// get naming options
boolean[] options = input_.getNamingOptions();
// include stress sequence name
if (options[0]) {
name += flight.getParentItem().getParentItem().getName() + ", ";
}
// include EID
if (options[1]) {
name += ExternalStressSequence.getEID(flight.getParentItem().getParentItem().getName()) + ", ";
}
// include flight name
if (options[2]) {
name += flight.getName() + ", ";
}
// include A/C program
if (options[3]) {
name += flight.getParentItem().getParentItem().getProgram() + ", ";
}
// include A/C section
if (options[4]) {
name += flight.getParentItem().getParentItem().getSection() + ", ";
}
// include fatigue mission
if (options[5]) {
name += flight.getParentItem().getParentItem().getMission() + ", ";
}
// return name
return name.substring(0, name.lastIndexOf(", "));
}
/**
* Checks given series name for uniqueness.
*
* @param name
* Series name.
* @param dataset
* Dataset.
* @return Modified name.
* @throws Exception
* If exception occurs during process.
*/
private String checkName(String name, XYSeriesCollection dataset) throws Exception {
if (dataset.indexOf(name) == -1)
return name;
return checkName(name + " ", dataset);
}
}
| 25.732558
| 174
| 0.701197
|
608b3314c8b0f702ac321622ef6c4caab9ff455c
| 17,716
|
package com.lzhpo.deliver.service.impl;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.lzhpo.deliver.entity.*;
import com.lzhpo.deliver.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.lzhpo.common.init.CacheUtils;
import com.lzhpo.deliver.mapper.DispatchMapper;
import com.lzhpo.stock.entity.LineTakeout;
import com.lzhpo.stock.entity.QuickTakeout;
import com.lzhpo.stock.entity.Takeout;
import com.lzhpo.stock.service.ILineTakeoutService;
import com.lzhpo.stock.service.IQuickTakeoutService;
import com.lzhpo.stock.service.ITakeoutService;
import com.lzhpo.sys.service.IGenerateNoService;
/**
* <p>
* 服务实现类
* </p>
*
* @author xdm
* @since 2020-09-03
*/
@Service
public class DispatchServiceImpl extends ServiceImpl<DispatchMapper, Dispatch> implements IDispatchService {
@Autowired
private IGenerateNoService generateNoService;
@Autowired
private IDispactAddressService dispactAddressService;
@Autowired
private IExpressBillService expressBillService;
@Autowired
private ITakeoutService takeoutService;
@Autowired
private ILineTakeoutService lineTakeoutService;
@Autowired
private IVehicleContractMainService vehicleContractMainService;
@Autowired
private IVehicleContractMainDetailService vehicleContractMainDetailService ;
@Autowired
private IDispatchCostService dispatchCostService;
@Autowired
private IQuickTakeoutService quickTakeoutService;
@Autowired
private IAddressService addressService;
@Override
public long getDispatchCount(String name) {
QueryWrapper<Dispatch> wrapper = new QueryWrapper<>();
// 下行编辑条件
wrapper.eq("del_flag", false);
// wrapper.eq("name",name);
return baseMapper.selectCount(wrapper);
}
/*
* (non-Javadoc)
*
* @see
* com.lzhpo.deliver.service.IDispatchService#saveDispatch(com.lzhpo.deliver
* .entity.Dispatch)
*/
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = "Dispatchs", allEntries = true)
public Dispatch saveDispatch(Dispatch dispatch) {
//未排单
Integer scheduling_status_no = CacheUtils.keyDict.get("scheduling_status_no").getValue();
dispatch.setDispatchStatus(scheduling_status_no);
dispatch.setCode(generateNoService.nextCode("YSJH"));
// 待确认
Integer modify_status_await = CacheUtils.keyDict.get("modify_status_await").getValue();
dispatch.setStatus(modify_status_await);
baseMapper.insert(dispatch);
Set<DispactAddress> detaliSet = dispatch.getDetailSet();
saveDetail(dispatch, detaliSet);
return dispatch;
}
private String saveDetail(Dispatch dispatch, Set<DispactAddress> detaliSet) {
// 已排单
Integer scheduling_status_yes = CacheUtils.keyDict.get("scheduling_status_yes").getValue();
// 锁定
Integer modify_status_lock = CacheUtils.keyDict.get("modify_status_lock").getValue();
StringBuffer bf = new StringBuffer();
if(detaliSet!=null){
for (DispactAddress dispactAddress : detaliSet) {
//这里处理单据id为空的单据
//跳过dispatchId不为空的单据
if(StringUtils.isNotEmpty(dispactAddress.getDispacthId())){
continue;
}
long count = dispactAddressService.getCountByCodeAndIDispacthId(dispactAddress.getCode(), dispactAddress.getDispacthId());
if(count>0){//已经绑定过
bf.append(dispactAddress.getCode() + "该单已排过 ");
continue;
}
dispactAddress.setDispacthId(dispatch.getId());
// 原表更改它得配送状态
switch (dispactAddress.getType()) {
case 1:// 快速发单 得表 把其配送状态改为已排单
ExpressBill expressBill = expressBillService.getById(dispactAddress.getTableId());
expressBill.setSchedulingStatus(scheduling_status_yes);
// 锁定单据
expressBill.setStatus(modify_status_lock);
expressBillService.updateById(expressBill);
dispactAddress.setId(null);
dispactAddressService.save(dispactAddress);
break;
case 2:// 库存发单 得表 把其配送状态改为已排单
Takeout takeout = takeoutService.getById(dispactAddress.getTableId());
takeout.setSchedulingStatus(scheduling_status_yes);
takeout.setStatus(modify_status_lock);
// 锁定单据
takeoutService.updateById(takeout);
dispactAddress.setId(null);
dispactAddressService.save(dispactAddress);
break;
case 3:// 快速发单得拆单
ExpressBill expressBillSpilt = expressBillService.getById(dispactAddress.getTableId());
expressBillSpilt.setSchedulingStatus(scheduling_status_yes);
// 锁定单据
expressBillSpilt.setStatus(modify_status_lock);
expressBillService.updateById(expressBillSpilt);
dispactAddressService.updateById(dispactAddress);
break;
case 4: // 出库单 得拆单
Takeout takeoutSpilt = takeoutService.getById(dispactAddress.getTableId());
takeoutSpilt.setSchedulingStatus(scheduling_status_yes);
takeoutSpilt.setStatus(modify_status_lock);
// 锁定单据
takeoutService.updateById(takeoutSpilt);
dispactAddressService.updateById(dispactAddress); // 拆单后已经有该条记录,分配给dispactId便可
case 5:// 线路发单 得表 把其配送状态改为已排单
LineTakeout linetakeout = lineTakeoutService.getById(dispactAddress.getTableId());
linetakeout.setSchedulingStatus(scheduling_status_yes);
linetakeout.setStatus(modify_status_lock);
// 锁定单据
lineTakeoutService.updateById(linetakeout);
dispactAddress.setId(null);
dispactAddressService.save(dispactAddress);
break;
case 6: // 线路发单 得拆单
LineTakeout linetakeoutSplit = lineTakeoutService.getById(dispactAddress.getTableId());
linetakeoutSplit.setSchedulingStatus(scheduling_status_yes);
linetakeoutSplit.setStatus(modify_status_lock);
// 锁定单据
lineTakeoutService.updateById(linetakeoutSplit);
dispactAddressService.updateById(dispactAddress); // 拆单后已经有该条记录,分配给dispactId便可
case 7:// 线路发单 得表 把其配送状态改为已排单
QuickTakeout quicktakeout = quickTakeoutService.getById(dispactAddress.getTableId());
quicktakeout.setSchedulingStatus(scheduling_status_yes);
quicktakeout.setStatus(modify_status_lock);
// 锁定单据
quickTakeoutService.updateById(quicktakeout);
dispactAddress.setId(null);
dispactAddressService.save(dispactAddress);
break;
case 8: // 线路发单 得拆单
QuickTakeout quicktakeoutSplit = quickTakeoutService.getById(dispactAddress.getTableId());
quicktakeoutSplit.setSchedulingStatus(scheduling_status_yes);
quicktakeoutSplit.setStatus(modify_status_lock);
// 锁定单据
quickTakeoutService.updateById(quicktakeoutSplit);
dispactAddressService.updateById(dispactAddress); // 拆单后已经有该条记录,分配给dispactId便可
default:
break;
}
}
}
return bf.toString();
}
@Override
public Dispatch getDispatchById(String id) {
return baseMapper.selectById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = "Dispatchs", allEntries = true)
public void updateDispatch(Dispatch dispatch) {
// 可撤销
Integer modify_status_revocation = CacheUtils.keyDict.get("modify_status_revocation").getValue();
try {
mathSegnVehicelCost(dispatch);
}catch (RuntimeJsonMappingException e) {
throw new RuntimeJsonMappingException(e.getMessage());
}
dispatch.setStatus(modify_status_revocation);
baseMapper.updateById(dispatch);
}
private void mathSegnVehicelCost(Dispatch dispatch) {
//市内
Integer deliver_type_in = CacheUtils.keyDict.get("deliver_type_in").getValue();
//外埠
Integer deliver_type_out = CacheUtils.keyDict.get("deliver_type_out").getValue();
//外埠经销商
Integer point_type_distributor_out = CacheUtils.keyDict.get("point_type_distributor_out").getValue();
//市内经销商
Integer point_type_distributor_in = CacheUtils.keyDict.get("point_type_distributor_in").getValue();
//现在要看子表是啥类型了
List<DispactAddress> detailList = dispactAddressService.getListByDispatchId(dispatch.getId());
//看是不是都是一种类型
//为空也抛出去异常
Integer deliverType = null;
// 这个看是什么值 不是混装就是单独某种
Integer fixFlag = null;
// 是否混装
Boolean fix = false;
if(detailList.isEmpty()){
throw new RuntimeJsonMappingException("该运输计划中无内容,请仔细核对");
}else{
//这里找对应是配送什么得是不是都是一种类型(前端虽然过滤过了,在这里多写一步过滤)
boolean flag = true;
// 这个循环是判断是不是 外埠和市内混装(不允许) 经销商和超市混装(允许,但是哪个合同价高生成对应的费用)
for (DispactAddress dispactAddress : detailList) {
if(flag){//第一次赋值以后和此值进行对比
deliverType = dispactAddress.getDeliverType();
fixFlag = getAddressType(dispactAddress.getAddressId()); // 这个值在目前可能为空,为了避免可能的问题 在下面多判断一次
flag = false;
}else{
if(deliverType!=null&&!deliverType.equals( dispactAddress.getDeliverType())){
//如果不为空也有相同值变抛出异常
throw new RuntimeJsonMappingException("该运输计划不可同时包含市内和外埠得订单");
}
if(fixFlag !=null &&!fixFlag.equals( getAddressType(dispactAddress.getAddressId()))){
fix = true ; //代表混装了
}else{
fixFlag = getAddressType(dispactAddress.getAddressId());
}
}
}
}
//获得他的子表,去生成单车的运费 支出费用
VehicleContractMain main = null;
// 这个是经销商合同 这两者是 有一个必不能是空
VehicleContractMain distributorContractMain = null;
List<DispactAddress> list = new ArrayList<>();
List<DispactAddress> distributorList = new ArrayList<>();
//上面已經確保不是空值
int pointNum =1;
// 超市
Integer area_type_supermarket = CacheUtils.keyDict.get("area_type_supermarket").getValue();
// 经销商
Integer area_type_dealer = CacheUtils.keyDict.get("area_type_dealer").getValue();
// 在有市内超市 或者 外埠超市的时候 才需要取以下的值
boolean supermarketFlag = (!fix && fixFlag!=null && area_type_supermarket.equals(fixFlag)) || fix ;
boolean dealerFlag = (!fix && fixFlag!=null && area_type_dealer.equals(fixFlag)) || fix ;
if(supermarketFlag && deliver_type_in.equals(deliverType)){//市内
list = dispactAddressService.countNumDetailSendAreaByDispatchId(dispatch.getId());
main = vehicleContractMainService.getByVehicleId(dispatch.getVehicleId(),deliver_type_in);
pointNum = (int) dispactAddressService.countNumDetailSendPlaceByDispatchId(dispatch.getId());//这个是市内得
}
if(supermarketFlag && deliver_type_out.equals(deliverType)){//外埠
list = dispactAddressService.countNumDetailSendCityByDispatchId(dispatch.getId());
main = vehicleContractMainService.getByVehicleId(dispatch.getVehicleId(),deliver_type_out);
pointNum = list.size();
}
// 在有市内经销商 或者 外埠经销商的时候 才需要取以下的值 经销商 不关心 点费 只关系最远距离
if(dealerFlag && deliver_type_in.equals(deliverType)){//市内经销商
distributorList = dispactAddressService.countNumDetailSendAreaByDispatchId(dispatch.getId());
distributorContractMain = vehicleContractMainService.getByVehicleId(dispatch.getVehicleId(),point_type_distributor_in);
}
if(dealerFlag && deliver_type_out.equals(deliverType)){//外埠经销商
distributorList = dispactAddressService.countNumDetailSendCityByDispatchId(dispatch.getId());
distributorContractMain = vehicleContractMainService.getByVehicleId(dispatch.getVehicleId(),point_type_distributor_out);
}
DispatchCost cost = new DispatchCost();
DispatchCost distributorCost = new DispatchCost();
// 这里 抛出去异常要具体情况具体分析
// 如果不是混装
if(!fix){
// 超市的
if(fixFlag!=null && area_type_supermarket.equals(fixFlag)){
//找到这个车辆得合同
if(main==null){
// 根据市内 和 外埠的不同 可以细分
if(deliver_type_in.equals(deliverType)){
throw new RuntimeJsonMappingException("该车辆未找到对应市内超市合同");
}else {
throw new RuntimeJsonMappingException("该车辆未找到对应外埠超市合同");
}
}
}else { // 经销商的
if(distributorContractMain==null){
// 根据市内 和 外埠的不同 可以细分
if(deliver_type_in.equals(deliverType)){
throw new RuntimeJsonMappingException("该车辆未找到对应市内经销商合同");
}else {
throw new RuntimeJsonMappingException("该车辆未找到对应外埠经销商合同");
}
}
}
}else { //混装的 那两个合同都不能为null
if(main==null || distributorContractMain==null){
if(deliver_type_in.equals(deliverType)){
throw new RuntimeJsonMappingException("该单为市内经销商和超市混合配送单,但该车辆未找到对应市内合同");
}else {
throw new RuntimeJsonMappingException("该单为外埠经销商和超市混合配送单,但该车辆未找到对应外埠合同");
}
}
}
// 那么这里就确保了两个合同必定有个是不是空的
if(main != null){
//找到他的点数
List<BigDecimal> moneyList = new ArrayList<BigDecimal>();
// 那么一切照旧
cost.setPointNum(pointNum);
//难点费暂且不算
cost.setMinPoint(main.getMinPoint());
cost.setPointPrice(main.getPointPrice());
cost.setDispatchId(dispatch.getId());
for (DispactAddress dispactAddress : list) {
VehicleContractMainDetail detail = null;
if(deliver_type_in.equals(deliverType)){//市内
detail = vehicleContractMainDetailService.selectDetailMoneyByInfoNoRange(main.getId(), dispactAddress.getProvinceId(), dispactAddress.getCityId(), dispactAddress.getCountiesId());
}
if(deliver_type_out.equals(deliverType)){//外埠
detail = vehicleContractMainDetailService.selectDetailCityMoneyByInfoNoRange(main.getId(), dispactAddress.getProvinceId(), dispactAddress.getCityId());
}
if(detail!=null){
moneyList.add(detail.getMoney());
}
}
//从List中找到最大值
BigDecimal money = Collections.max(moneyList);
//区域收费 然后看点数到没有
if(money==null){
money = new BigDecimal(0);
}
if(pointNum>=main.getMinPoint()){//5 4
//大于等于起送量 也就是从这个开始计费
Integer num = pointNum-main.getMinPoint()+1;//2
//支出等于基础运费加上额外点数*点费
cost.setMoeny(money.add(main.getPointPrice().multiply(new BigDecimal(num))));
}else{
cost.setMoeny(money);
}
}
// 以上的话如果 超市的合同存在的话 其中已经存了一次钱
if(distributorContractMain != null){
//找到他的点数
List<BigDecimal> moneyList = new ArrayList<BigDecimal>();
distributorCost.setDispatchId(dispatch.getId());
for (DispactAddress dispactAddress : distributorList) {
VehicleContractMainDetail detail = null;
BigDecimal money = new BigDecimal(0);
if(deliver_type_in.equals(deliverType)) {//市内
money = vehicleContractMainDetailService.selectDetailMoneyByInfo(distributorContractMain.getId(), dispactAddress.getProvinceId(), dispactAddress.getCityId(),dispactAddress.getCountiesId(),dispatch.getDispatchVolume(),false);
}else {
money = vehicleContractMainDetailService.selectDetailMoneyByInfo(distributorContractMain.getId(), dispactAddress.getProvinceId(), dispactAddress.getCityId(),dispactAddress.getCountiesId(),dispatch.getDispatchVolume(),true);
}
moneyList.add(money);
}
//从List中找到最大值
BigDecimal money = Collections.max(moneyList);
distributorCost.setMoeny(money);
}
// 这个时候还是有可能钱是空值的 说明这一种类的合同 但是没有对应地区的合同 找不对报价
if(cost.getMoeny() == null && distributorCost.getMoeny() == null){
throw new RuntimeJsonMappingException("该车型有对应合同,但是无目前装载方数对应的报价");
}
// 这个钱和 cost 的钱做对比
if(cost.getMoeny() == null){
distributorCost.setRemarks("此单为经销商单独配送单");
dispatchCostService.save(distributorCost);
return;
}
if(distributorCost.getMoeny() == null){
cost.setRemarks("此单为超市单独配送单");
dispatchCostService.save(cost);
return;
}
// 都有值比个大小
if(distributorCost.getMoeny().compareTo(cost.getMoeny())==-1){
cost.setRemarks("此单为混合单据,综合费用以超市计算更高");
dispatchCostService.save(cost);
return;
}else{
distributorCost.setRemarks("此单为混合单据,综合费用以经销商计算更高");
dispatchCostService.save(distributorCost);
return;
}
}
private Integer getAddressType(String addressId) {
if(addressId != null){
Address address = addressService.getById(addressId);
if(address!=null){
// 其实只是要获取 配送地址的类型是不是经销商或者超市
return address.getAddressType();
}
}
return null;
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = "Dispatchs", allEntries = true)
public void deleteDispatch(Dispatch dispatch) {
dispatch.setDelFlag(true);
dispatchCostService.deleteByDispatchId(dispatch.getId());
List<DispactAddress> detailList = dispactAddressService.getListByDispatchId(dispatch.getId());
//删除时,子表理应全部解绑
for (DispactAddress dispactAddress : detailList) {
dispactAddressService.changeBindingStatus(dispactAddress.getId());
}
baseMapper.updateById(dispatch);
}
@Override
@Cacheable("Dispatchs")
public List<Dispatch> selectAll() {
QueryWrapper<Dispatch> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag", false);
return baseMapper.selectList(wrapper);
}
@Override
public Dispatch backDispatch(String id) {
// 待确认
Integer modify_status_await = CacheUtils.keyDict.get("modify_status_await").getValue();
Dispatch entity = getById(id);
entity.setStatus(modify_status_await);
dispatchCostService.deleteByDispatchId(id);//撤回得时候也删除支出 删除得时候做一个双重保险
baseMapper.updateById(entity);
return entity;
}
@Override
public int backDispatchByWaybillId(String wayBillId) {
QueryWrapper<Dispatch> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag", false);
wrapper.eq("way_bill_id", wayBillId);
Dispatch entity = new Dispatch();
entity.setWayBillId("");
//未排单
Integer scheduling_status_no = CacheUtils.keyDict.get("scheduling_status_no").getValue();
entity.setDispatchStatus(scheduling_status_no);
baseMapper.update(entity, wrapper);
return 0;
}
@Override
public List<Dispatch> selectByWayBillId(String wayBillId) {
QueryWrapper<Dispatch> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag", false);
wrapper.eq("way_bill_id", wayBillId);
return baseMapper.selectList(wrapper);
}
@Override
public List<Dispatch> selectByCode(String code) {
QueryWrapper<Dispatch> wrapper = new QueryWrapper<>();
wrapper.eq("del_flag", false);
wrapper.like("code", code);
return baseMapper.selectList(wrapper);
}
}
| 35.290837
| 229
| 0.754064
|
7a8ca97af72da85e38ca86281e9f3cd171caf02a
| 20
|
module Seminar_4 {
}
| 10
| 18
| 0.75
|
2d0a72bf3447d5f9834062e7a969da0ce80e22be
| 80
|
package com.warmup.reflection;
public interface Say {
public String say();
}
| 11.428571
| 30
| 0.7375
|
5b98a1c2cecd5c59da7d3a42b56957c98f1b232f
| 543
|
/**
*
*/
package com.ibenben.util.page;
import java.util.List;
import com.github.pagehelper.PageInfo;
/**
* @author sszheng
*
* Created on 2016年7月27日 下午3:17:03
* @param <T>
*/
public class PageInfoExt<T> extends PageInfo<T> {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param list
*/
public PageInfoExt(List<T> list) {
super(list);
}
private String result = "ok";
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
}
| 12.627907
| 49
| 0.635359
|
8e6a03f60886817141b33f6b601e13b88a114901
| 2,583
|
package org.agoncal.fascicle.jpa.puttingtogether;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import java.util.ArrayList;
import java.util.List;
/**
* @author Antonio Goncalves
* http://www.antoniogoncalves.org
* --
*/
// @formatter:off
// tag::adocSnippet[]
@Entity
public class Author {
@Id
@GeneratedValue
private Long id;
@Column(name = "first_name", length = 50)
private String firstName;
@Column(name = "last_name", nullable = false)
private String lastName;
@Column(length = 2000)
private String bio;
private String email;
@ManyToMany(mappedBy = "authors")
private List<Book> books = new ArrayList<>();
// Constructors, getters, setters
// tag::adocSkip[]
// @formatter:on
// ======================================
// = Getters & Setters =
// ======================================
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Author firstName(String firstName) {
this.firstName = firstName;
return this;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Author lastName(String lastName) {
this.lastName = lastName;
return this;
}
public String getBio() {
return bio;
}
public void setBio(String bio) {
this.bio = bio;
}
public Author bio(String bio) {
this.bio = bio;
return this;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Author email(String email) {
this.email = email;
return this;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
public Author book(Book book) {
this.books.add(book);
return this;
}
// ======================================
// = hash, equals, toString =
// ======================================
@Override
public String toString() {
return "Author{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", bio='" + bio + '\'' +
", email='" + email + '\'' +
'}';
}
// end::adocSkip[]
}
// end::adocSnippet[]
| 19.276119
| 49
| 0.581107
|
c23c68f6fb115c13c32cbe1aec2fa5be4b4833bf
| 566
|
package com.xuxd.kafka.console.beans.dto;
import com.xuxd.kafka.console.beans.AclEntry;
import lombok.Data;
import org.apache.kafka.common.resource.ResourceType;
/**
* kafka-console-ui.
*
* @author xuxd
* @date 2021-08-30 16:28:23
**/
@Data
public class ProducerAuthDTO {
private String topic;
private String username;
public AclEntry toEntry() {
AclEntry entry = new AclEntry();
entry.setPrincipal(username);
entry.setName(topic);
entry.setResourceType(ResourceType.TOPIC.name());
return entry;
}
}
| 20.214286
| 57
| 0.678445
|
9381b8436f742ebb72c27b5675a5ef86cbe540a6
| 16,444
|
/*
* Copyright 2016 Miroslav Janíček
*
* 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.sandius.rembulan;
import java.util.Comparator;
/**
* A representation of an ordering on values, allowing the comparison of values
* of the same type (in the type parameter {@code T}).
*
* <p>In Lua, only strings and numbers have such an ordering. This class serves the
* purpose of a bridge between the concrete representation of Lua numbers
* (as {@link java.lang.Number}) and the raw comparison operations provided by
* {@link LuaMathOperators}, and the concrete representation of Lua strings
* (as {@link java.lang.String}) and the comparison operations defined on them.</p>
*
* <p>Consequently, there are two concrete implementations of this class:
* {@link #NUMERIC} for the numeric ordering and {@link #STRING} for the string
* ordering. These instances may be used directly for comparing objects of known,
* conforming types; for unknown objects, the method {@link #of(Object, Object)}
* returns an ordering that accepts {@link java.lang.Object}, and uses one of
* the two ordering instances, or {@code null} if the arguments
* are not directly comparable in Lua.</p>
*
* <p>The comparison methods of this class return unboxed booleans.</p>
*
* <p>This class implements the {@link Comparator} interface by imposing a total
* order on the accepted values. For numbers, this total ordering is <i>different</i>
* from the one imposed by this class. See the documentation of {@link NumericOrdering}
* for more details.</p>
*
* <p><b>Example:</b> Given two objects {@code a}, and {@code b}, attempt to
* evaluate the Lua expression {@code (a <= b)}:</p>
*
* <pre>
* // Object a, b
* final boolean result;
* Ordering<Object> cmp = Ordering.of(a, b);
* if (cmp != null) {
* // a and b are comparable in cmp
* result = cmp.le(a, b);
* }
* else {
* throw new RuntimeException("a and b not comparable");
* }
* </pre>
*
* @param <T> the type of values comparable in the ordering
*/
public abstract class Ordering<T> implements Comparator<T> {
private Ordering() {
// not to be instantiated by the outside world
}
/**
* A static instance of the numeric ordering.
*/
public static final NumericOrdering NUMERIC = new NumericOrdering();
/**
* A static instance of the string ordering.
*/
public static final StringOrdering STRING = new StringOrdering();
/**
* Returns {@code true} if {@code a} is equal to {@code b} in this ordering.
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return {@code true} iff {@code a} is equal to {@code b} in this ordering
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
public abstract boolean eq(T a, T b);
/**
* Returns {@code true} if {@code a} is lesser than {@code b} in this ordering.
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return {@code true} iff {@code a} is lesser than {@code b} in this ordering
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
public abstract boolean lt(T a, T b);
/**
* Returns {@code true} if {@code a} is lesser than or equal to {@code b} in this ordering.
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return {@code true} iff {@code a} is lesser than or equal to equal to {@code b}
* in this ordering
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
public abstract boolean le(T a, T b);
/**
* Returns {@code true} iff the object {@code a} is raw-equal to {@code b} following
* the Lua equality rules.
*
* <p>Excerpt from the Lua Reference Manual (§3.4.4):</p>
*
* <blockquote>
* <p>Equality (==) first compares the type of its operands. If the types are different,
* then the result is false. Otherwise, the values of the operands are compared.
* Strings are compared in the obvious way. Numbers are equal if they denote the
* same mathematical value.</p>
*
* <p>Tables, userdata, and threads are compared by reference: two objects are considered
* equal only if they are the same object. Every time you create a new object (a table,
* userdata, or thread), this new object is different from any previously existing
* object. Closures with the same reference are always equal. Closures with any
* detectable difference (different behavior, different definition) are always
* different.</p>
* </blockquote>
*
* <p><b>Note:</b> Rembulan uses {@link Object#equals(Object)} to compare all non-nil,
* non-string, and non-numeric values for equality, effectively shifting the
* responsibility of adhering to the rules of Lua raw-equality for tables, userdata
* and threads to their implementations.</p>
*
* @param a an object, may be {@code null}
* @param b another object, may be {@code null}
* @return {@code true} iff {@code a} is raw-equal to {@code b}
*/
public static boolean isRawEqual(Object a, Object b) {
if (a == null && b == null) {
// two nils
return true;
}
else if (a == null) {
// b is definitely not nil; also ensures that neither a nor b is null in the tests below
return false;
}
else if (a instanceof Number && b instanceof Number) {
return Ordering.NUMERIC.eq((Number) a, (Number) b);
}
else if (LuaType.isString(a) && LuaType.isString(b)) {
return Ordering.STRING.eq(toByteString(a), toByteString(b));
}
else {
return a.equals(b);
}
}
/**
* Numeric ordering.
*
* <p>Numbers are compared using the comparison methods provided by {@link LuaMathOperators},
* defining the ordering as one based on the ordering of the mathematical values
* of the numbers in question.</p>
*
* <p>This class implements the {@link Comparator} interface by imposing a total order
* on numbers that differs from the ordering defined by the methods
* {@link #eq(Number, Number)}, {@link #lt(Number, Number)}
* and {@link #le(Number, Number)}:</p>
*
* <ul>
* <li><i>NaN</i> is treated as equal to itself and greater than any other
* number, while {@code eq(a, b) == false} and {@code lt(a, b) == false}
* when {@code a} or {@code b} is <i>NaN</i>;
* <li>{@code -0.0} is considered to be lesser than {@code 0.0},
* while {@code eq(-0.0, 0.0) == true} and {@code lt(-0.0, 0.0) == false}.</li>
* </ul>
*
* <p>Note that the total ordering imposed by the {@link #compare(Number, Number)}
* is <i>inconsistent with equals</i>.</p>
*
* <p>For proper treatment of <i>NaN</i>s and (float) zero values, use the
* {@code Ordering} methods directly.</p>
*
*/
public static final class NumericOrdering extends Ordering<Number> {
private NumericOrdering() {
// not to be instantiated by the outside world
}
/**
* Returns {@code true} iff {@code a} denotes the same mathematical value
* as {@code b}.
*
* <p>Note that since <i>NaN</i> does not denote any mathematical value,
* this method returns {@code false} whenever any of its arguments is <i>NaN</i>.</p>
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return {@code true} iff {@code a} and {@code b} denote the same mathematical
* value
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
@Override
public boolean eq(Number a, Number b) {
boolean isflt_a = a instanceof Double || a instanceof Float;
boolean isflt_b = b instanceof Double || b instanceof Float;
if (isflt_a) {
return isflt_b
? LuaMathOperators.eq(a.doubleValue(), b.doubleValue())
: LuaMathOperators.eq(a.doubleValue(), b.longValue());
}
else {
return isflt_b
? LuaMathOperators.eq(a.longValue(), b.doubleValue())
: LuaMathOperators.eq(a.longValue(), b.longValue());
}
}
/**
* Returns {@code true} iff the mathematical value denoted by {@code a}
* is lesser than the mathematical value denoted by {@code b}.
*
* <p>Note that since <i>NaN</i> does not denote any mathematical value,
* this method returns {@code false} whenever any of its arguments is <i>NaN</i>.</p>
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return {@code true} iff the mathematical value denoted by {@code a}
* is lesser than the mathematical value denoted by {@code b}
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
@Override
public boolean lt(Number a, Number b) {
boolean isflt_a = a instanceof Double || a instanceof Float;
boolean isflt_b = b instanceof Double || b instanceof Float;
if (isflt_a) {
return isflt_b
? LuaMathOperators.lt(a.doubleValue(), b.doubleValue())
: LuaMathOperators.lt(a.doubleValue(), b.longValue());
}
else {
return isflt_b
? LuaMathOperators.lt(a.longValue(), b.doubleValue())
: LuaMathOperators.lt(a.longValue(), b.longValue());
}
}
/**
* Returns {@code true} iff the mathematical value denoted by {@code a}
* is lesser than or equal to the mathematical value denoted by {@code b}.
*
* <p>Note that since <i>NaN</i> does not denote any mathematical value,
* this method returns {@code false} whenever any of its arguments is <i>NaN</i>.</p>
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return {@code true} iff the mathematical value denoted by {@code a}
* is lesser than or equal to the mathematical value denoted
* by {@code b}
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
@Override
public boolean le(Number a, Number b) {
boolean isflt_a = a instanceof Double || a instanceof Float;
boolean isflt_b = b instanceof Double || b instanceof Float;
if (isflt_a) {
return isflt_b
? LuaMathOperators.le(a.doubleValue(), b.doubleValue())
: LuaMathOperators.le(a.doubleValue(), b.longValue());
}
else {
return isflt_b
? LuaMathOperators.le(a.longValue(), b.doubleValue())
: LuaMathOperators.le(a.longValue(), b.longValue());
}
}
/**
* Compare the numbers {@code a} and {@code b}, yielding an integer that
* is negative, zero or positive if {@code a} is lesser than, equal to, or greater
* than {@code b}.
*
* <p>The ordering imposed by this method differs from the one defined
* by the methods {@link #eq(Number, Number)}, {@link #lt(Number, Number)}
* and {@link #le(Number, Number)} in the treatment of <i>NaN</i>s
* and float zeros:</p>
*
* <ul>
* <li><i>NaN</i> is treated as equal to itself and greater than any other
* number, while {@code eq(a, b) == false} and {@code lt(a, b) == false}
* when {@code a} or {@code b} is <i>NaN</i>;
* <li>{@code -0.0} is considered to be lesser than {@code 0.0},
* while {@code eq(-0.0, 0.0) == true} and {@code lt(-0.0, 0.0) == false}.</li>
* </ul>
*
* <p>The total ordering of {@code Number} objects imposed by this method
* is <i>inconsistent with equals</i>.</p>
*
* @param a first argument, must not be {@code null}
* @param b second argument, must not be {@code null}
* @return a negative, zero or positive integer if the number {@code a} is lesser
* than, equal to, or greater than the number {@code b}
*
* @throws NullPointerException if {@code a} or {@code b} is {@code null}
*/
@Override
public int compare(Number a, Number b) {
if (lt(a, b)) {
return -1;
}
else if (lt(b, a)) {
return 1;
}
else {
// treat NaN as equal to itself and greater than any other number,
// and -0.0 as lesser than 0.0
return Double.compare(a.doubleValue(), b.doubleValue());
}
}
}
/**
* String ordering.
*
* <p>This is the (total) lexicographical ordering imposed by the method
* {@link String#compareTo(String)}.</p>
*/
public static final class StringOrdering extends Ordering<ByteString> {
private StringOrdering() {
// not to be instantiated by the outside world
}
@Override
public boolean eq(ByteString a, ByteString b) {
return a.compareTo(b) == 0;
}
@Override
public boolean lt(ByteString a, ByteString b) {
return a.compareTo(b) < 0;
}
@Override
public boolean le(ByteString a, ByteString b) {
return a.compareTo(b) <= 0;
}
@Override
public int compare(ByteString a, ByteString b) {
return a.compareTo(b);
}
}
private static final NumericObjectOrdering NUMERIC_OBJECT = new NumericObjectOrdering();
private static final StringObjectOrdering STRING_OBJECT = new StringObjectOrdering();
private static class NumericObjectOrdering extends Ordering<Object> {
@Override
public boolean eq(Object a, Object b) {
return NUMERIC.eq((Number) a, (Number) b);
}
@Override
public boolean lt(Object a, Object b) {
return NUMERIC.lt((Number) a, (Number) b);
}
@Override
public boolean le(Object a, Object b) {
return NUMERIC.le((Number) a, (Number) b);
}
@Override
public int compare(Object a, Object b) {
return NUMERIC.compare((Number) a, (Number) b);
}
}
private static ByteString toByteString(Object o) throws ClassCastException {
if (o instanceof ByteString) return (ByteString) o;
else return ByteString.of((String) o); // may throw a ClassCastException
}
private static class StringObjectOrdering extends Ordering<Object> {
@Override
public boolean eq(Object a, Object b) {
return STRING.eq(toByteString(a), toByteString(b));
}
@Override
public boolean lt(Object a, Object b) {
return STRING.lt(toByteString(a), toByteString(b));
}
@Override
public boolean le(Object a, Object b) {
return STRING.le(toByteString(a), toByteString(b));
}
@Override
public int compare(Object a, Object b) {
return STRING.compare(toByteString(a), toByteString(b));
}
}
/**
* Based on the actual types of the arguments {@code a} and {@code b}, returns
* the ordering in which {@code a} and {@code b} can be compared, or {@code null}
* if they are not comparable.
*
* <p>More specifically, if {@code a} and {@code b} are both numbers, returns
* an ordering that uses (but is distinct from) {@link #NUMERIC}; if {@code a} and
* {@code b} are both strings, returns an ordering that uses (but is distinct from)
* {@link #STRING}; otherwise, returns {@code null}.</p>
*
* <p>Note that when the result is non-{@code null}, it is guaranteed that
* 1) neither {@code a} nor {@code b} is {@code null}; and 2)
* both {@code a} and {@code b} are of types accepted by the underlying ordering.
* Caution must be observed when using the ordering with another object {@code c}
* (i.e., other than {@code a} or {@code b}): the returned ordering will throw
* a {@link ClassCastException} if {@code c} is of an incompatible type, or
* a {@link NullPointerException} if {@code c} is {@code null}.</p>
*
* @param a an object, may be {@code null}
* @param b another object, may be {@code null}
* @return an ordering based on {@link #NUMERIC} if both {@code a} and {@code b} are numbers;
* an ordering based on {@link #STRING} if both {@code a} and {@code b} are strings;
* {@code null} otherwise
*/
public static Ordering<Object> of(Object a, Object b) {
if (a instanceof Number && b instanceof Number) {
return NUMERIC_OBJECT;
}
else if (LuaType.isString(a) && LuaType.isString(b)) {
return STRING_OBJECT;
}
else {
return null;
}
}
}
| 35.593074
| 95
| 0.655741
|
3beacdaba8cef9305f23a65ed945c73c93e23b76
| 1,109
|
package com.github.tingyugetc520.bytedance.lark.bean.authentication.v1;
import com.github.tingyugetc520.bytedance.lark.util.json.FsGsonBuilder;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
/**
* 用oauth2获取用户信息的结果类
*/
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class FsOauth2UserInfo implements Serializable {
private static final long serialVersionUID = 3786309563951035110L;
private String name;
private String openId;
private String unionId;
private String email;
private String userId;
private String mobile;
private String accessToken;
private Integer expiresIn;
private String refreshToken;
private Integer refreshExpiresId;
private String tokenType;
private String tenantKey;
public static FsOauth2UserInfo fromJson(String json) {
return FsGsonBuilder.create().fromJson(json, FsOauth2UserInfo.class);
}
public String toJson() {
return FsGsonBuilder.create().toJson(this);
}
}
| 23.595745
| 73
| 0.791704
|
6bf5052789f7b503787b157a5e00dece4b3d6160
| 1,422
|
package fuellogg.model.view;
import java.math.BigDecimal;
import java.time.LocalDate;
public class DetailsViewOnExpenses {
private LocalDate date;
private Integer odometer;
private BigDecimal price;
private String description;
private String type;
private Long vehicleId;
public Long getVehicleId() {
return vehicleId;
}
public DetailsViewOnExpenses setVehicleId(Long vehicleId) {
this.vehicleId = vehicleId;
return this;
}
public LocalDate getDate() {
return date;
}
public DetailsViewOnExpenses setDate(LocalDate date) {
this.date = date;
return this;
}
public Integer getOdometer() {
return odometer;
}
public DetailsViewOnExpenses setOdometer(Integer odometer) {
this.odometer = odometer;
return this;
}
public BigDecimal getPrice() {
return price;
}
public DetailsViewOnExpenses setPrice(BigDecimal price) {
this.price = price;
return this;
}
public String getDescription() {
return description;
}
public DetailsViewOnExpenses setDescription(String description) {
this.description = description;
return this;
}
public String getType() {
return type;
}
public DetailsViewOnExpenses setType(String type) {
this.type = type;
return this;
}
}
| 20.911765
| 69
| 0.64135
|
7e9f5488d615d46ad57e592644606f6a7477e3d7
| 1,030
|
package com.ruoyi.system.domain.senselink;
import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.BaseEntity;
/**
* 设备与人员组关联信息
*
* @author zl
*/
public class SlDeviceGroupsRel extends BaseEntity {
/** 设备与人员组关联id */
@Excel(name = "设备与人员组关联id")
private Long id;
/** 人员组id */
@Excel(name = "人员组id")
private Long groupid;
/** 设备id */
@Excel(name = "设备id")
private Long deviceid;
/**设备与人员组关联重复数量**/
private int count;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getGroupid() {
return groupid;
}
public void setGroupid(Long groupid) {
this.groupid = groupid;
}
public Long getDeviceid() {
return deviceid;
}
public void setDeviceid(Long deviceid) {
this.deviceid = deviceid;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
| 17.166667
| 51
| 0.58835
|
8e6296a2ba5ab3a0f82e5eafa8c8f07eb6582b54
| 1,281
|
package me.limeglass.skungee.bungeecord.utils;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import net.md_5.bungee.api.plugin.Plugin;
public class BungeeReflectionUtil {
public static Set<Class<?>> getClasses(JarFile jar, String... packages) {
Set<Class<?>> classes = new HashSet<>();
try {
for (Enumeration<JarEntry> jarEntry = jar.entries(); jarEntry.hasMoreElements();) {
String name = jarEntry.nextElement().getName().replace("/", ".");
if (name.length() >= 6) {
String className = name.substring(0, name.length() - 6);
className = className.replace('/', '.');
for (String packageName : packages) {
if (!name.startsWith(packageName) || !name.endsWith(".class"))
continue;
classes.add(Class.forName(className));
}
}
}
jar.close();
} catch (IOException | ClassNotFoundException e1) {
e1.printStackTrace();
}
return classes;
}
public static Set<Class<?>> getClasses(Plugin instance, String... packages) {
try {
JarFile jar = new JarFile(instance.getFile());
return getClasses(jar, packages);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 27.255319
| 86
| 0.672131
|
d967d266b8c911e6e0104877f202bda4abfb408b
| 292
|
package io.javaoperatorsdk.admissioncontroller;
import io.fabric8.kubernetes.api.model.admission.v1.AdmissionRequest;
import io.fabric8.kubernetes.api.model.admission.v1.AdmissionResponse;
public interface RequestHandler {
AdmissionResponse handle(AdmissionRequest admissionRequest);
}
| 26.545455
| 70
| 0.849315
|
ac7e3f16ab2b346b25501cf0c9efe42e07a970dd
| 3,329
|
/*
* Copyright (c) 2005-2013 Clark & Parsia, LLC. <http://www.clarkparsia.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.complexible.common.openrdf.query;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import org.openrdf.query.QueryResultHandlerException;
import org.openrdf.query.resultio.QueryResultFormat;
import org.openrdf.query.resultio.QueryResultWriter;
import org.openrdf.rio.RioSetting;
import org.openrdf.rio.WriterConfig;
/**
* <p>More useful base for creating custom {@link QueryResultWriter} implementations.
* Provides no-op methods for the new parts of the API so existing implementations don't
* have boilerplate no-op methods to ignore the stuff that should not be in the API.</p>
*
* @author Michael Grove
* @since 1.0
* @version 1.0
*/
public abstract class AbstractQueryResultWriter implements QueryResultWriter {
private final QueryResultFormat mFormat;
private WriterConfig mWriterConfig = new WriterConfig();
protected AbstractQueryResultWriter(final QueryResultFormat theFormat) {
mFormat = theFormat;
}
/**
* @inheritDoc
*/
@Override
public final QueryResultFormat getQueryResultFormat() {
return mFormat;
}
/**
* @inheritDoc
*/
@Override
public void handleStylesheet(final String s) throws QueryResultHandlerException {
// no-op
}
/**
* @inheritDoc
*/
@Override
public void setWriterConfig(WriterConfig config) {
this.mWriterConfig = config;
}
/**
* @inheritDoc
*/
@Override
public WriterConfig getWriterConfig() {
return this.mWriterConfig;
}
/**
* @inheritDoc
*/
@Override
public Collection<RioSetting<?>> getSupportedSettings() {
return Collections.emptyList();
}
/**
* @inheritDoc
*/
@Override
public void handleLinks(final List<String> theStrings) throws QueryResultHandlerException {
// no-op
}
/**
* @inheritDoc
*/
@Override
public void startHeader() throws QueryResultHandlerException {
// no-op
}
/**
* @inheritDoc
*/
@Override
public void startDocument() throws QueryResultHandlerException {
// no-op
}
/**
* @inheritDoc
*/
@Override
public void handleNamespace(final String s, final String s2) throws QueryResultHandlerException {
// no-op
}
/**
* @inheritDoc
*/
@Override
public void endHeader() throws QueryResultHandlerException {
// no-op
}
/**
* @inheritDoc
*/
@Override
public void handleBoolean(final boolean b) throws QueryResultHandlerException {
throw new UnsupportedOperationException();
}
}
| 24.659259
| 101
| 0.668669
|
a41b01fce17e5050df418c4eb601cd56a3d1c74f
| 398
|
package com.guigu.gulimall.order.dao;
import com.guigu.gulimall.order.entity.PaymentInfoEntity;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
* 支付信息表
*
* @author mylovehaveadream
* @email mylovehaveadream@gmail.com
* @date 2020-08-26 19:11:15
*/
@Mapper
public interface PaymentInfoDao extends BaseMapper<PaymentInfoEntity> {
}
| 22.111111
| 71
| 0.778894
|
53aeb900d70a2dd37b45b02ee5c0e2c74fb8af10
| 1,169
|
import java.lang.Object;
import java.lang.Override;
/**
* A simple class with Javadoc.
*
* @since 1.0.0
*/
public class Javadoc {
private final String name;
private final int count;
public Javadoc(String name, int count) {
this.name = name;
this.count = count;
}
/**
* Returns the name.
*
* @return the name.
*/
public String getName() {
return name;
}
/**
* Returns the count.
*
* @return the count.
*/
public int getCount() {
return count;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + (name == null ? 0 : name.hashCode());
result = prime * result + count;
return result;
}
@Override
public boolean equals(Object other) {
if (other == this)
return true;
else if (other == null || getClass() != other.getClass())
return false;
Javadoc that = (Javadoc) other;
return equals(name, that.name)
&& count == that.count;
}
private boolean equals(Object left, Object right) {
if (left == null)
return right == null;
else
return left.equals(right);
}
}
| 18.265625
| 67
| 0.579983
|
41ff2c9543b7b914149efc98a0b90e7b734ff6f9
| 543
|
package com.aojiaoo.admin;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
import org.springframework.scheduling.annotation.EnableAsync;
/**
* @author puremdq
*/
@ConfigurationPropertiesScan
@EnableAsync
@SpringBootApplication
public class CommonAdminApplication {
public static void main(String[] args) {
SpringApplication.run(CommonAdminApplication.class, args);
}
}
| 25.857143
| 79
| 0.813996
|
4a3f01fa1dbed3d771067e08651732501338b018
| 865
|
package me.wuwenbin.noteblogv4.model.entity;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import static java.lang.Boolean.TRUE;
/**
* created by Wuwenbin on 2018/7/15 at 11:57
* @author wuwenbin
*/
@Data
@Entity
@Table(name = "nb_keyword")
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class NBKeyword implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false, length = 11)
private Long id;
@Column(nullable = false)
@NotEmpty
private String words;
@Column(nullable = false, length = 1, columnDefinition = "tinyint(1)")
@Builder.Default
private Boolean enable = TRUE;
}
| 22.179487
| 74
| 0.74104
|
43ca4ba8542c22503ba4aa8b2367de089febbd22
| 778
|
/*
* Copyright (c) 2017. The Hyve and respective contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* See the file LICENSE in the root of this repository.
*
*/
package nl.thehyve.podium.service.mapper;
import nl.thehyve.podium.common.service.dto.AuditEventRepresentation;
import org.mapstruct.Mapper;
import org.springframework.boot.actuate.audit.AuditEvent;
import java.util.List;
@Mapper(componentModel = "spring", uses = { })
public interface AuditEventMapper {
AuditEventRepresentation auditEventToAuditEventRepresentation(AuditEvent auditEvent);
List<AuditEventRepresentation> auditEventsToAuditEventRepresentations(List<AuditEvent> auditEventList);
}
| 29.923077
| 107
| 0.785347
|
fd6628bb994aea3497ba098e8abce568446b47a1
| 2,094
|
package com.esfm.modules.lpa.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
/**
* 分层审核-审核员(LpaAuditor)表实体类
* @author yaoxin
* @since 2020-08-21 11:08:02
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class LpaAuditor extends Model<LpaAuditor> {
private String id;
//工号 索引
@Excel(name = "工号 索引", width = 20)
private String userId;
//层级
@Excel(name = "层级", width = 20)
private Integer layer;
//父级Id
@Excel(name = "父级Id", width = 20)
private String pid;
//是否冻结
@Excel(name = "是否冻结", width = 20)
private Boolean freeze;
//创造时间
@TableField(fill = FieldFill.INSERT)
@Excel(name = "创造时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
//更新时间
@TableField(fill = FieldFill.INSERT_UPDATE)
@Excel(name = "更新时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
//删除时间
@Excel(name = "删除时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date deleteTime;
//冗余姓名
@Excel(name = "冗余姓名", width = 20)
private String userName;
//创造着
@TableField(fill = FieldFill.INSERT)
@Excel(name = "创造着", width = 20)
private String createBy;
/**
* 获取主键值
* @return 主键值
*/
@Override
public Serializable pkVal() {
return this.id;
}
}
| 29.914286
| 69
| 0.663324
|
5932d318a94d0792657b7759f397d6af2bbd5107
| 3,076
|
/*
* Copyright 2002-2012 Drew Noakes
*
* 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.
*
* More information about this project is available at:
*
* http://drewnoakes.com/code/exif/
* http://code.google.com/p/metadata-extractor/
*/
package com.drew.metadata;
import com.drew.imaging.jpeg.JpegProcessingException;
import com.drew.imaging.jpeg.JpegSegmentData;
import com.drew.imaging.jpeg.JpegSegmentReader;
import java.io.File;
import java.io.IOException;
/**
* @author Drew Noakes http://drewnoakes.com
*/
public class ExtractMetadataToFileUtility
{
public static void main(String[] args) throws IOException, JpegProcessingException
{
if (args.length != 1) {
System.err.println("Expects a single argument of the file path to process.");
System.exit(1);
}
String filePath = args[0];
String outputFilePath = filePath + ".metadata";
JpegSegmentData segmentData = new JpegSegmentReader(new File(filePath)).getSegmentData();
segmentData.removeSegment(JpegSegmentReader.SEGMENT_DHT);
segmentData.removeSegment(JpegSegmentReader.SEGMENT_DQT);
segmentData.removeSegment(JpegSegmentReader.SEGMENT_SOF0);
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 1));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 2));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 3)); // No 4
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 5));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 6));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 7));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 8));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 9));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 10));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 11)); // No 12
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 13));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 14));
segmentData.removeSegment((byte)(JpegSegmentReader.SEGMENT_SOF0 + 15));
segmentData.removeSegment(JpegSegmentReader.SEGMENT_SOI);
System.out.println("Writing output to: " + outputFilePath);
JpegSegmentData.toFile(new File(outputFilePath), segmentData);
}
}
| 45.235294
| 98
| 0.703511
|
fd2910104b1a8ab7df4341e1eee82090d89fe109
| 1,172
|
package com.java110.fee.dao;
import com.java110.utils.exception.DAOException;
import com.java110.entity.merchant.BoMerchant;
import com.java110.entity.merchant.BoMerchantAttr;
import com.java110.entity.merchant.Merchant;
import com.java110.entity.merchant.MerchantAttr;
import java.util.List;
import java.util.Map;
/**
* 催缴单组件内部之间使用,没有给外围系统提供服务能力
* 催缴单服务接口类,要求全部以字符串传输,方便微服务化
* 新建客户,修改客户,删除客户,查询客户等功能
*
* Created by wuxw on 2016/12/27.
*/
public interface IFeeCollectionOrderServiceDao {
/**
* 保存 催缴单信息
* @param info
* @throws DAOException DAO异常
*/
void saveFeeCollectionOrderInfo(Map info) throws DAOException;
/**
* 查询催缴单信息(instance过程)
* 根据bId 查询催缴单信息
* @param info bId 信息
* @return 催缴单信息
* @throws DAOException DAO异常
*/
List<Map> getFeeCollectionOrderInfo(Map info) throws DAOException;
/**
* 修改催缴单信息
* @param info 修改信息
* @throws DAOException DAO异常
*/
void updateFeeCollectionOrderInfo(Map info) throws DAOException;
/**
* 查询催缴单总数
*
* @param info 催缴单信息
* @return 催缴单数量
*/
int queryFeeCollectionOrdersCount(Map info);
}
| 18.903226
| 70
| 0.680034
|
bfbab70fe00f1af9ecfd29df5d9db26d33470cf4
| 1,899
|
package com.github.cumtfc.srs.service.course;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.cumtfc.srs.dao.CourseRepository;
import com.github.cumtfc.srs.po.course.Course;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* @author 冯楚
* @date 2018/6/8-19:12
*/
@Service
public class CourseServiceImpl implements CourseService {
@Autowired
private CourseRepository courseRepository;
@Override
public String findAllInJson() {
List<Course> courses = courseRepository.findAll();
ObjectMapper mapper = new ObjectMapper();
ArrayNode arrayNode = mapper.createArrayNode();
for (Course course : courses) {
arrayNode.add(course.toJson());
}
return arrayNode.toString();
}
@Override
@Transactional(rollbackFor = Exception.class)
public Course saveOne(Course course) {
// for (int i = 0; i < course.getPrevCourses().size(); i++) {
//
// Optional<Course> coursePo = courseRepository.findById(course.getPrevCourses().get(i).getId());
// if (coursePo.isPresent()) {
// course.getPrevCourses().set(i, coursePo.get());
// }
// }
return courseRepository.save(course);
}
@Override
public List<Course> saveAll(List<Course> courses) {
return courseRepository.saveAll(courses);
}
@Override
public boolean deleteOne(Course course) {
courseRepository.delete(course);
return true;
}
@Override
public boolean deleteOne(Integer id) {
courseRepository.deleteById(id);
return true;
}
}
| 27.926471
| 108
| 0.676145
|
6c2ccefdd3f2f73c6437d9435a0d86df19cc5553
| 1,177
|
package mahjong.mode;
/**
* Created by pengyi
* Date : 16-6-12.
*/
public enum ScoreType {
BA_GANG("扒杠", 1),
AN_GANG("暗杠", 2),
DIAN_GANG("点杠", 3),
PING_HU("平胡", 4),
ZIMO_HU("自摸", 5),
MENQING_HU("门清", 6),
PENGPENG_HU("碰碰胡", 7),
HUNYISE_HU("混一色", 8),
QINGYISE_HU("清一色", 9),
QIXIAODUI_HU("七小对", 10),
HUNYAOJIU_HU("混幺九", 11),
HAOHUAQIXIAODUI_HU("豪华七小对", 12),
SHISANYAO_HU("十三幺", 13),
TIAN_HU("天胡", 14),
DI_HU("地胡", 15),
QUANYAOJIU_HU("全幺九", 16),
QUANFAN_HU("全番", 17),
SHUANGHAOHUAQIXIAODUI_HU("双豪华七小对", 18),
SANHAOHUAQIXIAODUI_HU("三豪华七小对", 19),
SHIBALUOHAN("十八罗汉", 20),
HAIDI("海底", 21),
GANGBAO("杠爆", 22),
ZHUANGYING("庄硬", 23),
FEI("飞", 24);
private String name;
private Integer values;
ScoreType(String name, Integer values) {
this.name = name;
this.values = values;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getValues() {
return values;
}
public void setValues(Integer values) {
this.values = values;
}
}
| 20.293103
| 44
| 0.563297
|
5a7c04f65ff81a5660aa79304dfe38537b41977f
| 5,023
|
package cn.kgc.controller;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import cn.kgc.pojo.Approval;
import cn.kgc.pojo.Block;
import cn.kgc.pojo.Notice;
import cn.kgc.pojo.Project;
import cn.kgc.pojo.User;
import cn.kgc.pojo.UserBlock;
import cn.kgc.service.ApprovalService;
import cn.kgc.service.BlockService;
import cn.kgc.service.NoticeService;
import cn.kgc.service.ProjectService;
import cn.kgc.service.UserBlockService;
@Controller
@RequestMapping(value="/page/door")
public class DoorController {
@Resource
private ApprovalService approvalService;//审批业务对象
@Resource
private NoticeService noticeService;//公告业务对象
@Resource
private ProjectService projectService;//工程业务对象
@Resource
private BlockService blockService;//任务业务对象
@Resource
private UserBlockService userBlockService;//用户-任务关联业务对象
@RequiresPermissions("door:getUserInfo")
@ResponseBody
@RequestMapping(value="/getUserInfo.do",
method=RequestMethod.POST)
public String getUserInfo() {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
return JSON.toJSONString(user);
}
/**
* 获取我的审批表格数据
* @return
*/
@RequiresPermissions("door:getMyApprovalTable")
@ResponseBody
@RequestMapping(value="/getMyApprovalTable.do")
public String getMyApprovalTable() {
//获取当前操作用户
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
//获取当前用户提交的审批集合
List<Approval> approvals = approvalService.getApprovalsBySubmitUserId(user.getUsername());
List<Map<String, String>> result = new ArrayList<>();
int index = 0;
for (Approval approval : approvals) {
if(index > 3)
break;
Map<String, String> map = new HashMap<>();
map.put("id", approval.getId());
map.put("title", approval.getTitle());
int status = approval.getStatus();
if(status == 0) {
map.put("status", "<small class=\"label label-warning\">待审批</small>");
}
else if(status == 1) {
map.put("status", "<small class=\"label label-success\">已同意</small>");
}else if(status == 2) {
map.put("status", "<small class=\"label label-danger\">已拒绝</small>");
}
result.add(map);
index++;
}
return JSONArray.toJSONString(result);
}
/**
* 获取我的公告集合
* @return
*/
@RequiresPermissions("door:getMyNotices")
@ResponseBody
@RequestMapping(value="/getMyNotices.do",
method=RequestMethod.POST)
public String getMyNotices() {
//获取当前操作用户
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
//根据发布者获取公告集合
List<Notice> notices = noticeService.getNoticesBySubmitUserId(user.getUsername());
int size = notices.size()>3 ? 3 : notices.size();
List<Map<String, String>> result = new ArrayList<>();
for(int i=0; i<size; i++) {
Map<String, String> map = new HashMap<>();
map.put("title", notices.get(i).getTitle());
int status = notices.get(i).getStatus();
if(status == 1) {
map.put("status", "<small class=\"label label-danger\">紧急</small>");
}
else if(status == 2) {
map.put("status", "<small class=\"label label-warning\">一般</small>");
}
result.add(map);
}
return JSONArray.toJSONString(result);
}
/**
* 获取今日任务表格数据
* @return
*/
@RequiresPermissions("door:getTodayBlocksTable")
@ResponseBody
@RequestMapping(value="/getTodayBlocksTable.do")
public String getTodayBlocksTable() {
//获取当前操作用户
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getPrincipal();
List<Map<String, String>> result = new ArrayList<>();//结果集
int index = 0;
//获取当前用户参与的任务集合
List<UserBlock> userBlocks = userBlockService.getUserBlockByUserId(user.getUsername());
for (UserBlock userBlock : userBlocks) {
if(index > 3)
break;
Map<String, String> map = new HashMap<>();//表格的每一行数据
Block block = blockService.getBlockById(userBlock.getBlockId());
//任务描述
map.put("description", block.getDescription());
//所属工程
Project project = projectService.getProjectById(block.getProjectId());
map.put("projectName", project.getName());
//任务组长
User leader = block.getLeader();
map.put("blockLeader", leader.getUsername() + "-" + leader.getName());
result.add(map);
index++;
}
return JSONArray.toJSONString(result);
}
}
| 30.077844
| 93
| 0.692614
|
c253d94faaae632a4a532df5454d735ce853f6bb
| 822
|
/**
*
*/
package org.gds.creator;
import org.gds.product.BusinessCustomVM;
import org.gds.product.BusinessStandardVM;
import org.gds.product.VirtualMachine;
/**
* A concrete Creator subclass of the Factory Method Design Pattern
*/
public class BusinessVMCreator extends VirtualMachineCreator {
/*
* (non-Javadoc)
*
* @see org.gds.creator.VirtualMachineCreator#createVirtualMachine()
*/
VirtualMachine createVirtualMachine(String type) throws UnknownVMException {
if (type.equals(VMTypes.CUSTOM.toString())) {
return new BusinessCustomVM();
}
else if (type.equals(VMTypes.STANDARD.toString())) {
return new BusinessStandardVM();
}
else {
throw new UnknownVMException("Unknown VM Type");
}
}
}
| 24.909091
| 80
| 0.654501
|
9915226b05239f780b1307d15792dc11fd603e03
| 105
|
package com.ppdai.platform.das.console.common.validates.group.member;
public interface UpdateMember {
}
| 21
| 69
| 0.819048
|
85678ac7142192f49f508f2b0c795b4b7bfcaaf4
| 748
|
package mo.boids;
public class Constants {
/**
* Conversion between the model time and real time.
*/
public static double stepTime = 0.1;
/**
* The "fly towards center" factor.
*/
public static double holdFlockCenter = 0.001;
public static double avoidNeibourthood = 0.01;
/**
* The number of boids in the flock.
*/
public static int count = 8;
/**
* The keep away zone around boids
*/
public static double keepAwayDistance = 50;
/**
* Minimal speed (accelerate if slower).
*/
public static double minSpeed = 2;
/**
* Max speed (slow down if faster).
*/
public static double maxSpeed = minSpeed * 5;
/**
* The acceleration for speed adjustment.
*/
public static double speedAdjust = 0.001;
}
| 16.26087
| 52
| 0.659091
|
8df72e3fc58a74054e47ca942eb607d1baff3009
| 270
|
package com.flickhunter.model;
public class Document {
public int docId;
public double tw;
public Document(int did, double tw) {
this.docId = did;
this.tw = tw;
}
public String toString() {
String docIdString = docId + ":" + tw;
return docIdString;
}
}
| 15.882353
| 40
| 0.674074
|
c5bea1ef0e66f5227b893cbe39b4015c978b7f29
| 2,286
|
package com.ipincloud.iotbj.srv.domain;
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Time;
import java.sql.Date;
import java.sql.Timestamp;
import com.alibaba.fastjson.annotation.JSONField;
//(AlgorithmAccess)算法接入
//generate by redcloud,2020-07-24 19:59:20
public class AlgorithmAccess implements Serializable {
private static final long serialVersionUID = 4L;
// 自增ID
private Long id ;
// 算法名称
private String title ;
// 算法描述
private String describion ;
// 请求地址
private String address ;
// 算法接入
private String accessmode ;
// 预警等级
private String grade ;
// 是否关联人脸识别
private String relationface ;
// 算法标识
private String ucode ;
// 创建时间
private Long created ;
// 修改时间
private Long updated ;
public Long getId() {
return id ;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title ;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescribion() {
return describion ;
}
public void setDescribion(String describion) {
this.describion = describion;
}
public String getAddress() {
return address ;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccessmode() {
return accessmode ;
}
public void setAccessmode(String accessmode) {
this.accessmode = accessmode;
}
public String getGrade() {
return grade ;
}
public void setGrade(String grade) {
this.grade = grade;
}
public String getRelationface() {
return relationface ;
}
public void setRelationface(String relationface) {
this.relationface = relationface;
}
public String getUcode() {
return ucode ;
}
public void setUcode(String ucode) {
this.ucode = ucode;
}
public Long getCreated() {
return created ;
}
public void setCreated(Long created) {
this.created = created;
}
public Long getUpdated() {
return updated ;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
}
| 19.538462
| 54
| 0.614611
|
cecc3e6491b0afab577036a4e06d8757de266e02
| 624
|
package dto;
public class Cliente {
public String Cliente;
public String CNPJ;
public String Setor;
public Cliente (String Cliente, String CNPJ, String Setor) {
this.Cliente = Cliente;
this.CNPJ = CNPJ;
this.Setor = Setor;
}
public String getCliente() {
return Cliente;
}
public void setCliente(String cliente) {
Cliente = cliente;
}
public String getCNPJ() {
return CNPJ;
}
public void setCNPJ(String cNPJ) {
CNPJ = cNPJ;
}
public String getSetor() {
return Setor;
}
public void setSetor(String setor) {
Setor = setor;
}
}
| 14.181818
| 62
| 0.620192
|
ff56ee3f07e907bc56f511e24061d191ee985a71
| 8,579
|
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.plan.a;
import java.util.HashMap;
import java.util.Map;
public class NoSemiColonTest extends ScriptTestCase {
public void testIfStatement() {
assertEquals(1, exec("int x = 5 if (x == 5) return 1 return 0"));
assertEquals(0, exec("int x = 4 if (x == 5) return 1 else return 0"));
assertEquals(2, exec("int x = 4 if (x == 5) return 1 else if (x == 4) return 2 else return 0"));
assertEquals(1, exec("int x = 4 if (x == 5) return 1 else if (x == 4) return 1 else return 0"));
assertEquals(3, exec(
"int x = 5\n" +
"if (x == 5) {\n" +
" int y = 2\n" +
" \n" +
" if (y == 2) {\n" +
" x = 3\n" +
" }\n" +
" \n" +
"}\n" +
"\n" +
"return x\n"));
}
public void testWhileStatement() {
assertEquals("aaaaaa", exec("String c = \"a\" int x while (x < 5) { c ..= \"a\" ++x } return c"));
Object value = exec(
" byte[][] b = new byte[5][5] \n" +
" byte x = 0, y \n" +
" \n" +
" while (x < 5) { \n" +
" y = 0 \n" +
" \n" +
" while (y < 5) { \n" +
" b[x][y] = (byte)(x*y) \n" +
" ++y \n" +
" } \n" +
" \n" +
" ++x \n" +
" } \n" +
" \n" +
" return b \n");
byte[][] b = (byte[][])value;
for (byte x = 0; x < 5; ++x) {
for (byte y = 0; y < 5; ++y) {
assertEquals(x*y, b[x][y]);
}
}
}
public void testDoWhileStatement() {
assertEquals("aaaaaa", exec("String c = \"a\" int x do { c ..= \"a\" ++x } while (x < 5) return c"));
Object value = exec(
" long[][] l = new long[5][5] \n" +
" long x = 0, y \n" +
" \n" +
" do { \n" +
" y = 0 \n" +
" \n" +
" do { \n" +
" l[(int)x][(int)y] = x*y \n" +
" ++y \n" +
" } while (y < 5) \n" +
" \n" +
" ++x \n" +
" } while (x < 5) \n" +
" \n" +
" return l \n");
long[][] l = (long[][])value;
for (long x = 0; x < 5; ++x) {
for (long y = 0; y < 5; ++y) {
assertEquals(x*y, l[(int)x][(int)y]);
}
}
}
public void testForStatement() {
assertEquals("aaaaaa", exec("String c = \"a\" for (int x = 0; x < 5; ++x) c ..= \"a\" return c"));
Object value = exec(
" int[][] i = new int[5][5] \n" +
" for (int x = 0; x < 5; ++x) { \n" +
" for (int y = 0; y < 5; ++y) { \n" +
" i[x][y] = x*y \n" +
" } \n" +
" } \n" +
" \n" +
" return i \n");
int[][] i = (int[][])value;
for (int x = 0; x < 5; ++x) {
for (int y = 0; y < 5; ++y) {
assertEquals(x*y, i[x][y]);
}
}
}
public void testDeclarationStatement() {
assertEquals((byte)2, exec("byte a = 2 return a"));
assertEquals((short)2, exec("short a = 2 return a"));
assertEquals((char)2, exec("char a = 2 return a"));
assertEquals(2, exec("int a = 2 return a"));
assertEquals(2L, exec("long a = 2 return a"));
assertEquals(2F, exec("float a = 2 return a"));
assertEquals(2.0, exec("double a = 2 return a"));
assertEquals(false, exec("boolean a = false return a"));
assertEquals("string", exec("String a = \"string\" return a"));
assertEquals(HashMap.class, exec("Map<String, Object> a = new HashMap<String, Object>() return a").getClass());
assertEquals(byte[].class, exec("byte[] a = new byte[1] return a").getClass());
assertEquals(short[].class, exec("short[] a = new short[1] return a").getClass());
assertEquals(char[].class, exec("char[] a = new char[1] return a").getClass());
assertEquals(int[].class, exec("int[] a = new int[1] return a").getClass());
assertEquals(long[].class, exec("long[] a = new long[1] return a").getClass());
assertEquals(float[].class, exec("float[] a = new float[1] return a").getClass());
assertEquals(double[].class, exec("double[] a = new double[1] return a").getClass());
assertEquals(boolean[].class, exec("boolean[] a = new boolean[1] return a").getClass());
assertEquals(String[].class, exec("String[] a = new String[1] return a").getClass());
assertEquals(Map[].class, exec("Map<String,Object>[] a = new Map<String,Object>[1] return a").getClass());
assertEquals(byte[][].class, exec("byte[][] a = new byte[1][2] return a").getClass());
assertEquals(short[][][].class, exec("short[][][] a = new short[1][2][3] return a").getClass());
assertEquals(char[][][][].class, exec("char[][][][] a = new char[1][2][3][4] return a").getClass());
assertEquals(int[][][][][].class, exec("int[][][][][] a = new int[1][2][3][4][5] return a").getClass());
assertEquals(long[][].class, exec("long[][] a = new long[1][2] return a").getClass());
assertEquals(float[][][].class, exec("float[][][] a = new float[1][2][3] return a").getClass());
assertEquals(double[][][][].class, exec("double[][][][] a = new double[1][2][3][4] return a").getClass());
assertEquals(boolean[][][][][].class, exec("boolean[][][][][] a = new boolean[1][2][3][4][5] return a").getClass());
assertEquals(String[][].class, exec("String[][] a = new String[1][2] return a").getClass());
assertEquals(Map[][][].class, exec("Map<String,Object>[][][] a = new Map<String,Object>[1][2][3] return a").getClass());
}
public void testContinueStatement() {
assertEquals(9, exec("int x = 0, y = 0 while (x < 10) { ++x if (x == 1) continue ++y } return y"));
}
public void testBreakStatement() {
assertEquals(4, exec("int x = 0, y = 0 while (x < 10) { ++x if (x == 5) break ++y } return y"));
}
public void testReturnStatement() {
assertEquals(10, exec("return 10"));
assertEquals(5, exec("int x = 5 return x"));
assertEquals(4, exec("int[] x = new int[2] x[1] = 4 return x[1]"));
assertEquals(5, ((short[])exec("short[] s = new short[3] s[1] = 5 return s"))[1]);
assertEquals(10, ((Map)exec("Map<String,Object> s = new HashMap< String,Object>() s.put(\"x\", 10) return s")).get("x"));
}
}
| 47.927374
| 129
| 0.425691
|
f73ce5501df17373b76c74c454dbf9a11c327855
| 488
|
package fr.free.nrw.commons.contributions;
import fr.free.nrw.commons.BasePresenter;
/**
* The contract for Contributions View & Presenter
*/
public class ContributionsContract {
public interface View {
void showMessage(String localizedMessage);
}
public interface UserActionListener extends BasePresenter<ContributionsContract.View> {
Contribution getContributionsWithTitle(String uri);
void deleteUpload(Contribution contribution);
}
}
| 21.217391
| 91
| 0.743852
|
9cfe7d565c917b00b9a65805f2c256f6df9877da
| 280
|
package com.alianza.sip.sdp.version0;
import com.alianza.sip.sdp.SdpDecoder;
import com.alianza.sip.sdp.SessionDescription;
public class SdpDecoderVersion0 implements SdpDecoder {
@Override
public SessionDescription decode(String content) {
return null;
}
}
| 23.333333
| 55
| 0.760714
|
d62219107912bf0762bdaf236f6d5814460c5a08
| 720
|
package com.euroscripting.facades;
import com.euroscripting.assemblers.CurrencyAssembler;
import com.euroscripting.daos.CurrencyDAO;
import com.euroscripting.dtos.CurrencyDTO;
import com.euroscripting.entities.SxCurrencies;
import java.util.ArrayList;
import java.util.List;
public class CurrencyFacade {
public List<CurrencyDTO> getAll() {
CurrencyDAO dao = new CurrencyDAO();
List<CurrencyDTO> dtoList = new ArrayList<CurrencyDTO>();
CurrencyDTO dto = null;
List<SxCurrencies> entityList = dao.getAll();
if(!entityList.isEmpty()){
for(SxCurrencies entity : entityList){
dto = CurrencyAssembler.getDTOFromEntity(entity);
dtoList.add(dto);
}
}
return dtoList;
}
}
| 21.176471
| 59
| 0.738889
|
94029ef5e9e0dd459187f3b1ca7937af4933daaf
| 2,229
|
package edu.fiuba.algo3.loaders;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.google.gson.Gson;
import edu.fiuba.algo3.constants.QuestionType;
import edu.fiuba.algo3.engine.questions.GroupChoiceQuestion;
import edu.fiuba.algo3.exceptions.QuestionsNotLoadedException;
import edu.fiuba.algo3.model.GameOption;
import edu.fiuba.algo3.model.OptionGroup;
import edu.fiuba.algo3.model.Question;
import edu.fiuba.algo3.resources.ResourceLoader;
public class QuestionLoader {
private static final String TYPE = "type";
private static final String CORRECT_OPTIONS = "correctOptions";
private static final Gson gson = new Gson();
private QuestionLoader() {}
@SuppressWarnings("unchecked")
public static List<Question> loadQuestions(String questionsPath) throws QuestionsNotLoadedException{
String questionJson;
List<Question> questions = new ArrayList<>();
try {
questionJson = ResourceLoader.loadTextFile(questionsPath);
questions = parseToList(new Gson().fromJson(questionJson, List.class));
} catch (Exception ex) {
throw new QuestionsNotLoadedException(ex.getMessage());
}
if(questions.isEmpty()) {
throw new QuestionsNotLoadedException("Questions couldn't be loaded");
}
return questions;
}
@SuppressWarnings("unchecked")
private static List<Question> parseToList(List<Map<String, Object>> list){
List<Question> questionList = new ArrayList<>();
list.stream().forEach(element -> {
String type = element.get(TYPE).toString();
Question question = (Question) gson.fromJson(gson.toJson(element), QuestionType.valueOf(type).getQuestionClass());
if(question instanceof GroupChoiceQuestion) {
loadGroupChoiceQuestion(element, (GroupChoiceQuestion) question);
}
questionList.add(question);
});
return questionList;
}
private static void loadGroupChoiceQuestion(Map<String, Object> element, GroupChoiceQuestion question) {
List correctOptionsList = (List) element.get(CORRECT_OPTIONS);
List<GameOption> groupList = new ArrayList<>();
for(Object correctOption : correctOptionsList) {
groupList.add(gson.fromJson(gson.toJson(correctOption), OptionGroup.class));
}
question.setCorrectOptions(groupList);
}
}
| 34.828125
| 117
| 0.767609
|
ca0d052d8d2be805a28ae17aff2c5c3db2ab6663
| 992
|
package com.beauty.message.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* description
*
* @author yufengwen
* @date 2021/8/24 1:09 下午
*/
@RestController
public class Sender {
@Autowired
private JavaMailSender javaMailSender;
@Value("${spring.mail.username}")
private String username;
/**
* 测试outlook发送邮件,已成功
* */
@RequestMapping("/send")
public String send()
{
SimpleMailMessage m=new SimpleMailMessage();
m.setFrom(username);
m.setTo("yufengwen@baijia.com");
m.setText("test");
m.setSubject("subject");//主题
javaMailSender.send(m);
return "success";
}
}
| 25.435897
| 62
| 0.702621
|
6c26b99ec3f034e8b0a942b28ea3d899323978d3
| 4,390
|
/*
* Thumbnailator - a thumbnail generation library
*
* Copyright (c) 2008-2020 Chris Kroells
*
* 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 net.coobird.thumbnailator.tasks;
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.ThumbnailParameter;
import net.coobird.thumbnailator.tasks.io.ImageSink;
import net.coobird.thumbnailator.tasks.io.ImageSource;
/**
* A {@link ThumbnailTask} which holds an {@link ImageSource} from which the
* image is read or retrieved, and an {@link ImageSink} to which the thumbnail
* is stored or written.
* <p>
* This class will take care of handing off information from the
* {@link ImageSource} to the {@link ImageSink}. For example, the output format
* that should be used by the {@link ImageSink} will be handed off if the
* {@link ThumbnailParameter#ORIGINAL_FORMAT} parameter is set.
*
* @author coobird
*
* @param <S> The source class from which the source image is retrieved
* or read.
* @param <D> The destination class to which the thumbnail is stored
* or written.
*/
public class SourceSinkThumbnailTask<S, D> extends ThumbnailTask<S, D> {
/**
* The source from which the image is retrieved or read.
*/
private final ImageSource<S> source;
/**
* The destination to which the thumbnail is stored or written.
*/
private final ImageSink<D> destination;
/**
* Creates a {@link ThumbnailTask} in which an image is retrived from the
* specified {@link ImageSource} and written to the specified
* {@link ImageSink}, using the parameters provided in the specified
* {@link ThumbnailParameter}.
*
* @param param The parameters to use to create the thumbnail.
* @param source The source from which the image is retrieved
* or read from.
* @param destination The destination to which the thumbnail is
* stored or written to.
* @throws NullPointerException If either the parameter,
* {@link ImageSource} or {@link ImageSink}
* is {@code null}.
*/
public SourceSinkThumbnailTask(ThumbnailParameter param, ImageSource<S> source, ImageSink<D> destination) {
super(param);
if (source == null) {
throw new NullPointerException("ImageSource cannot be null.");
}
if (destination == null) {
throw new NullPointerException("ImageSink cannot be null.");
}
source.setThumbnailParameter(param);
this.source = source;
destination.setThumbnailParameter(param);
this.destination = destination;
}
@Override
public BufferedImage read() throws IOException {
BufferedImage img = source.read();
inputFormatName = source.getInputFormatName();
return img;
}
@Override
public void write(BufferedImage img) throws IOException {
String paramOutputFormat = param.getOutputFormat();
String formatName = null;
if (ThumbnailParameter.DETERMINE_FORMAT.equals(paramOutputFormat)) {
paramOutputFormat = destination.preferredOutputFormatName();
}
if (paramOutputFormat == ThumbnailParameter.ORIGINAL_FORMAT) {
formatName = inputFormatName;
} else {
formatName = paramOutputFormat;
}
destination.setOutputFormatName(formatName);
destination.write(img);
}
@Override
public S getSource() {
return source.getSource();
}
@Override
public D getDestination() {
return destination.getSink();
}
}
| 33.769231
| 108
| 0.73303
|
5da6a90916b047cb629ba7d219cdd80a87464b2d
| 2,931
|
// Copyright (c) 2003, 2008 Per M.A. Bothner.
// This is free software; for terms and warranty disclaimer see ./COPYING.
package gnu.kawa.xml;
import gnu.lists.*;
import gnu.xml.*;
/** Manages a sequence of node references in document order without duplicates.
* All elements are POSITION_PAIR_FOLLOWS elements, which makes operations
* simple and efficient. The most recently added element is just before
* the gap. Optimized for the data being in order, or at least having good
* locality (a node being "near" the previously-entered node). */
public class SortedNodes extends Nodes
{
int nesting = 0;
int compareIndex(int index, AbstractSequence seq2, int ipos2)
{
int datum = data[index];
if (datum != POSITION_PAIR_FOLLOWS)
throw new RuntimeException("invalid kind of value to compare");
AbstractSequence seq = (AbstractSequence) objects[getIntN(index+1)];
return AbstractSequence.compare(seq, getIntN(index+3),
seq2, ipos2);
}
/** Find index where to put position (seq, ipos).
* Require {@code index>=start && index<end},
* where {@code end==start+POS_SIZE*count}.
* Require all position before index are "less than" (seq, ipos),
* and all positions after are "greater than" (seq, ipos).
* If there is no such index (because it is "same as"), return -1.
*/
int find (int start, int count, AbstractSequence seq, int ipos)
{
int lo = 0;
int hi = count;
// We use binary search, though the arraycopy operations in writePosition
// limit the value - a sequence of writePosition calls is still quadratic
// in the worst case (but linear if locality is good).
while (lo < hi)
{
int mid = (lo + hi) >>> 1;
int cmp = compareIndex(start + POS_SIZE * mid, seq, ipos);
if (cmp == 0)
return -1;
if (cmp > 0)
hi = mid;
else
lo = mid + 1;
}
return start + POS_SIZE * lo;
}
public void writePosition(AbstractSequence seq, int ipos)
{
if (count > 0)
{
int lastIndex = gapStart - POS_SIZE;
int cmp = compareIndex(lastIndex, seq, ipos);
if (cmp < 0)
{
// The new node is after all nodes up to gapStart.
int i = gapEnd;
int end = data.length;
// Note that if the incoming nodes are already sorted (a common
// case in path expressions), then find will immediately return i.
i = find (i, (end - i) / POS_SIZE, seq, ipos);
if (i < 0)
return;
int delta = i - gapEnd;
if (delta > 0)
{
System.arraycopy(data, gapEnd, data, gapStart, delta);
gapEnd = i;
gapStart += delta;
}
}
else if (cmp == 0)
return;
else
{
int i = find (0, lastIndex / POS_SIZE, seq, ipos);
if (i < 0)
return;
int delta = gapStart - i;
if (delta > 0)
{
System.arraycopy(data, i, data, gapEnd - delta, delta);
gapStart = i;
gapEnd -= delta;
}
}
}
super.writePosition(seq, ipos);
}
}
| 29.31
| 79
| 0.634937
|
f28b99794e1898245176fdacf9e9f79cef4f0fef
| 1,598
|
package com.alexstyl.specialdates.events;
import android.content.SharedPreferences;
import android.content.res.Resources;
import com.alexstyl.specialdates.EasyPreferences;
import com.alexstyl.specialdates.EventsUpdateTrigger;
import java.util.ArrayList;
import java.util.List;
public final class PreferenceChangedEventsUpdateTrigger implements EventsUpdateTrigger {
private final EasyPreferences preferences;
private final List<String> keys;
private SharedPreferences.OnSharedPreferenceChangeListener listener;
public PreferenceChangedEventsUpdateTrigger(EasyPreferences preferences, Resources strings, int firstKeys, int... keys) {
this.preferences = preferences;
this.keys = new ArrayList<>(keys.length + 1);
this.keys.add(strings.getString(firstKeys));
for (int key : keys) {
this.keys.add(strings.getString(key));
}
}
@Override
public void startObserving(final Callback callback) {
listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (isAKeyIcareAbout(key)) {
callback.onMonitorTriggered();
}
}
};
preferences.addOnPreferenceChangedListener(listener);
}
private boolean isAKeyIcareAbout(String key) {
return keys.contains(key);
}
@Override
public void stopObserving() {
preferences.removeOnPreferenceChagnedListener(listener);
}
}
| 31.333333
| 125
| 0.703379
|
c668a5cc609de3cbb8ba0517882047eafa0d5de1
| 887
|
package com.arkhn.hapi.loader;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "spring.redis")
@Configuration
@EnableConfigurationProperties
public class RedisCounterProperties {
private String host;
private Integer port;
private Integer db_index;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Integer getDb_index() {
return db_index;
}
public void setDb_index(Integer db_index) {
this.db_index = db_index;
}
}
| 22.74359
| 81
| 0.704622
|
4bc4fa0ef6bd6680272cd57b173600ce90089331
| 5,945
|
package org.jruby.ir.targets.simple;
import org.jruby.Ruby;
import org.jruby.RubyArray;
import org.jruby.RubyHash;
import org.jruby.RubyRegexp;
import org.jruby.RubyString;
import org.jruby.compiler.NotCompilableException;
import org.jruby.compiler.impl.SkinnyMethodAdapter;
import org.jruby.ir.runtime.IRRuntimeHelpers;
import org.jruby.ir.targets.ClassData;
import org.jruby.ir.targets.DynamicValueCompiler;
import org.jruby.ir.targets.IRBytecodeAdapter;
import org.jruby.ir.targets.JVM;
import org.jruby.ir.targets.indy.DRegexpObjectSite;
import org.jruby.runtime.ThreadContext;
import org.jruby.runtime.builtin.IRubyObject;
import org.jruby.specialized.RubyArraySpecialized;
import org.jruby.util.CodegenUtils;
import org.jruby.util.RegexpOptions;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import static org.jruby.util.CodegenUtils.ci;
import static org.jruby.util.CodegenUtils.p;
import static org.jruby.util.CodegenUtils.params;
import static org.jruby.util.CodegenUtils.sig;
public class NormalDynamicValueCompiler implements DynamicValueCompiler {
private final IRBytecodeAdapter compiler;
public NormalDynamicValueCompiler(IRBytecodeAdapter compiler) {
this.compiler = compiler;
}
public void pushDRegexp(Runnable callback, RegexpOptions options, int arity) {
if (arity > IRBytecodeAdapter.MAX_ARGUMENTS)
throw new NotCompilableException("dynamic regexp has more than " + IRBytecodeAdapter.MAX_ARGUMENTS + " elements");
String cacheField = null;
Label done = null;
if (options.isOnce()) {
// need to cache result forever
cacheField = "dregexp" + compiler.getClassData().cacheFieldCount.getAndIncrement();
done = new Label();
compiler.adapter.getClassVisitor().visitField(Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC, cacheField, ci(RubyRegexp.class), null, null).visitEnd();
compiler.adapter.getstatic(compiler.getClassData().clsName, cacheField, ci(RubyRegexp.class));
compiler.adapter.dup();
compiler.adapter.ifnonnull(done);
compiler.adapter.pop();
}
// We may evaluate these operands multiple times or the upstream instrs that created them, which is a bug (jruby/jruby#2798).
// However, only one dregexp will ever come out of the indy call.
callback.run();
compiler.adapter.invokedynamic("dregexp", sig(RubyRegexp.class, params(ThreadContext.class, RubyString.class, arity)), DRegexpObjectSite.BOOTSTRAP, options.toEmbeddedOptions());
if (done != null) {
compiler.adapter.dup();
compiler.adapter.putstatic(compiler.getClassData().clsName, cacheField, ci(RubyRegexp.class));
compiler.adapter.label(done);
}
}
public void array(int length) {
if (length > IRBytecodeAdapter.MAX_ARGUMENTS) throw new NotCompilableException("literal array has more than " + IRBytecodeAdapter.MAX_ARGUMENTS + " elements");
// use utility method for supported sizes
if (length <= RubyArraySpecialized.MAX_PACKED_SIZE) {
compiler.invokeIRHelper("newArray", sig(RubyArray.class, params(ThreadContext.class, IRubyObject.class, length)));
return;
}
SkinnyMethodAdapter adapter2;
String incomingSig = CodegenUtils.sig(JVM.OBJECT, params(ThreadContext.class, JVM.OBJECT, length));
final String methodName = "array:" + length;
final ClassData classData = compiler.getClassData();
if (!classData.arrayMethodsDefined.containsKey(length)) {
adapter2 = new SkinnyMethodAdapter(
compiler.adapter.getClassVisitor(),
Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC,
methodName,
incomingSig,
null,
null);
adapter2.aload(0);
adapter2.getfield(p(ThreadContext.class), "runtime", ci(Ruby.class));
IRBytecodeAdapter.buildArrayFromLocals(adapter2, 1, length);
adapter2.invokevirtual(p(Ruby.class), "newArrayNoCopy", sig(RubyArray.class, IRubyObject[].class));
adapter2.areturn();
adapter2.end();
classData.arrayMethodsDefined.put(length, null);
}
// now call it
compiler.adapter.invokestatic(classData.clsName, methodName, incomingSig);
}
public void hash(int length) {
if (length > IRBytecodeAdapter.MAX_ARGUMENTS / 2) throw new NotCompilableException("literal hash has more than " + (IRBytecodeAdapter.MAX_ARGUMENTS / 2) + " pairs");
SkinnyMethodAdapter adapter2;
String incomingSig = sig(JVM.OBJECT, params(ThreadContext.class, boolean.class, JVM.OBJECT, length * 2));
final String methodName = "hash:" + length;
final ClassData classData = compiler.getClassData();
if (!classData.hashMethodsDefined.containsKey(length)) {
adapter2 = new SkinnyMethodAdapter(
compiler.adapter.getClassVisitor(),
Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_SYNTHETIC,
methodName,
incomingSig,
null,
null);
adapter2.aload(0);
adapter2.getfield(p(ThreadContext.class), "runtime", ci(Ruby.class));
adapter2.iload(1);
IRBytecodeAdapter.buildArrayFromLocals(adapter2, 2, length * 2);
adapter2.invokestatic(p(IRRuntimeHelpers.class), "constructHashFromArray", sig(RubyHash.class, Ruby.class, boolean.class, IRubyObject[].class));
adapter2.areturn();
adapter2.end();
classData.hashMethodsDefined.put(length, null);
}
// now call it
compiler.adapter.invokestatic(classData.clsName, methodName, incomingSig);
}
}
| 42.769784
| 185
| 0.675189
|
ea99f8410aee08b5e757acf3f3abead2a5dd1ec6
| 4,243
|
package com.bazl.dna.lims.model.po;
import java.io.Serializable;
import java.util.Date;
public class AmTrainRecord implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String id;
private String personalId;
private Date trainStartDatetime;
private Date trainEndDatetime;
private String trainAddress;
private String trainContent;
private String trainSpeaker;
private String trainLevel;
private Date createDatetime;
private String createPerson;
private Date updateDatetime;
private String updatePerson;
private String deleteFlag;
private Date deleteDatetime;
private String deletePerson;
private String trainingSubject;
private String trainingParty;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id == null ? null : id.trim();
}
public String getPersonalId() {
return personalId;
}
public void setPersonalId(String personalId) {
this.personalId = personalId == null ? null : personalId.trim();
}
public Date getTrainStartDatetime() {
return trainStartDatetime;
}
public void setTrainStartDatetime(Date trainStartDatetime) {
this.trainStartDatetime = trainStartDatetime;
}
public Date getTrainEndDatetime() {
return trainEndDatetime;
}
public void setTrainEndDatetime(Date trainEndDatetime) {
this.trainEndDatetime = trainEndDatetime;
}
public String getTrainAddress() {
return trainAddress;
}
public void setTrainAddress(String trainAddress) {
this.trainAddress = trainAddress == null ? null : trainAddress.trim();
}
public String getTrainContent() {
return trainContent;
}
public void setTrainContent(String trainContent) {
this.trainContent = trainContent == null ? null : trainContent.trim();
}
public String getTrainSpeaker() {
return trainSpeaker;
}
public void setTrainSpeaker(String trainSpeaker) {
this.trainSpeaker = trainSpeaker == null ? null : trainSpeaker.trim();
}
public String getTrainLevel() {
return trainLevel;
}
public void setTrainLevel(String trainLevel) {
this.trainLevel = trainLevel == null ? null : trainLevel.trim();
}
public Date getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Date createDatetime) {
this.createDatetime = createDatetime;
}
public String getCreatePerson() {
return createPerson;
}
public void setCreatePerson(String createPerson) {
this.createPerson = createPerson == null ? null : createPerson.trim();
}
public Date getUpdateDatetime() {
return updateDatetime;
}
public void setUpdateDatetime(Date updateDatetime) {
this.updateDatetime = updateDatetime;
}
public String getUpdatePerson() {
return updatePerson;
}
public void setUpdatePerson(String updatePerson) {
this.updatePerson = updatePerson == null ? null : updatePerson.trim();
}
public String getDeleteFlag() {
return deleteFlag;
}
public void setDeleteFlag(String deleteFlag) {
this.deleteFlag = deleteFlag == null ? null : deleteFlag.trim();
}
public Date getDeleteDatetime() {
return deleteDatetime;
}
public void setDeleteDatetime(Date deleteDatetime) {
this.deleteDatetime = deleteDatetime;
}
public String getDeletePerson() {
return deletePerson;
}
public void setDeletePerson(String deletePerson) {
this.deletePerson = deletePerson == null ? null : deletePerson.trim();
}
public String getTrainingSubject() {
return trainingSubject;
}
public void setTrainingSubject(String trainingSubject) {
this.trainingSubject = trainingSubject == null ? null : trainingSubject.trim();
}
public String getTrainingParty() {
return trainingParty;
}
public void setTrainingParty(String trainingParty) {
this.trainingParty = trainingParty == null ? null : trainingParty.trim();
}
}
| 23.441989
| 87
| 0.666274
|
3d29507565e4966b75bc88fe3d8acfbc6a36498d
| 5,312
|
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0 (For details, see https://github.com/awsdocs/amazon-s3-developer-guide/blob/master/LICENSE-SAMPLECODE.)
import java.io.IOException;
import java.util.Arrays;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration;
import com.amazonaws.services.s3.model.BucketLifecycleConfiguration.Transition;
import com.amazonaws.services.s3.model.StorageClass;
import com.amazonaws.services.s3.model.Tag;
import com.amazonaws.services.s3.model.lifecycle.LifecycleAndOperator;
import com.amazonaws.services.s3.model.lifecycle.LifecycleFilter;
import com.amazonaws.services.s3.model.lifecycle.LifecyclePrefixPredicate;
import com.amazonaws.services.s3.model.lifecycle.LifecycleTagPredicate;
public class LifecycleConfiguration {
public static void main(String[] args) throws IOException {
String clientRegion = "*** Client region ***";
String bucketName = "*** Bucket name ***";
// Create a rule to archive objects with the "glacierobjects/" prefix to Glacier immediately.
BucketLifecycleConfiguration.Rule rule1 = new BucketLifecycleConfiguration.Rule()
.withId("Archive immediately rule")
.withFilter(new LifecycleFilter(new LifecyclePrefixPredicate("glacierobjects/")))
.addTransition(new Transition().withDays(0).withStorageClass(StorageClass.Glacier))
.withStatus(BucketLifecycleConfiguration.ENABLED);
// Create a rule to transition objects to the Standard-Infrequent Access storage class
// after 30 days, then to Glacier after 365 days. Amazon S3 will delete the objects after 3650 days.
// The rule applies to all objects with the tag "archive" set to "true".
BucketLifecycleConfiguration.Rule rule2 = new BucketLifecycleConfiguration.Rule()
.withId("Archive and then delete rule")
.withFilter(new LifecycleFilter(new LifecycleTagPredicate(new Tag("archive", "true"))))
.addTransition(new Transition().withDays(30).withStorageClass(StorageClass.StandardInfrequentAccess))
.addTransition(new Transition().withDays(365).withStorageClass(StorageClass.Glacier))
.withExpirationInDays(3650)
.withStatus(BucketLifecycleConfiguration.ENABLED);
// Add the rules to a new BucketLifecycleConfiguration.
BucketLifecycleConfiguration configuration = new BucketLifecycleConfiguration()
.withRules(Arrays.asList(rule1, rule2));
try {
AmazonS3 s3Client = AmazonS3ClientBuilder.standard()
.withCredentials(new ProfileCredentialsProvider())
.withRegion(clientRegion)
.build();
// Save the configuration.
s3Client.setBucketLifecycleConfiguration(bucketName, configuration);
// Retrieve the configuration.
configuration = s3Client.getBucketLifecycleConfiguration(bucketName);
// Add a new rule with both a prefix predicate and a tag predicate.
configuration.getRules().add(new BucketLifecycleConfiguration.Rule().withId("NewRule")
.withFilter(new LifecycleFilter(new LifecycleAndOperator(
Arrays.asList(new LifecyclePrefixPredicate("YearlyDocuments/"),
new LifecycleTagPredicate(new Tag("expire_after", "ten_years"))))))
.withExpirationInDays(3650)
.withStatus(BucketLifecycleConfiguration.ENABLED));
// Save the configuration.
s3Client.setBucketLifecycleConfiguration(bucketName, configuration);
// Retrieve the configuration.
configuration = s3Client.getBucketLifecycleConfiguration(bucketName);
// Verify that the configuration now has three rules.
configuration = s3Client.getBucketLifecycleConfiguration(bucketName);
System.out.println("Expected # of rules = 3; found: " + configuration.getRules().size());
// Delete the configuration.
s3Client.deleteBucketLifecycleConfiguration(bucketName);
// Verify that the configuration has been deleted by attempting to retrieve it.
configuration = s3Client.getBucketLifecycleConfiguration(bucketName);
String s = (configuration == null) ? "No configuration found." : "Configuration found.";
System.out.println(s);
}
catch(AmazonServiceException e) {
// The call was transmitted successfully, but Amazon S3 couldn't process
// it, so it returned an error response.
e.printStackTrace();
}
catch(SdkClientException e) {
// Amazon S3 couldn't be contacted for a response, or the client
// couldn't parse the response from Amazon S3.
e.printStackTrace();
}
}
}
| 54.204082
| 137
| 0.683358
|
7f9bdd04162cbcaf40c0b787a3b651e9cae16f94
| 2,486
|
package com.daviancorp.android.ui.adapter;
import android.content.Context;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.daviancorp.android.data.classes.Weapon;
import com.daviancorp.android.mh4udatabase.R;
import com.daviancorp.android.ui.general.WeaponListEntry;
/**
* Created by Mark on 3/3/2015.
*/
public class WeaponExpandableListBowgunAdapter extends WeaponExpandableListGeneralAdapter {
public WeaponExpandableListBowgunAdapter(Context context, View.OnLongClickListener listener) {
super(context, listener);
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v;
RecyclerView.ViewHolder viewHolder;
int resource = R.layout.fragment_weapon_tree_item_bowgun;
v = LayoutInflater.from(parent.getContext())
.inflate(resource, parent, false);
viewHolder = new WeaponBowgunViewHolder(v);
v.setOnLongClickListener(mListener);
return viewHolder;
}
private static class WeaponBowgunViewHolder extends WeaponViewHolder {
// Gunner
TextView recoiltv;
TextView steadytv;
TextView reloadtv;
public WeaponBowgunViewHolder(View weaponView) {
super(weaponView);
//
// Bowgun views
//
reloadtv = (TextView) weaponView.findViewById(R.id.reload_text);
recoiltv = (TextView) weaponView.findViewById(R.id.recoil_text);
steadytv = (TextView) weaponView.findViewById(R.id.deviation_text);
}
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
super.onBindViewHolder(viewHolder, position);
WeaponBowgunViewHolder holder = (WeaponBowgunViewHolder) viewHolder;
Weapon weapon = ((WeaponListEntry) getItemAt(position)).weapon;
String reload = weapon.getReloadSpeed();
String recoil = weapon.getRecoil();
String steady = weapon.getDeviation();
if (steady.startsWith("Left/Right")) {
String[] tempSteady = steady.split(":");
steady = "L/R:" + tempSteady[1];
}
holder.reloadtv.setText("REL: " + reload);
holder.recoiltv.setText("REC: " + recoil);
holder.steadytv.setText("DEV: " + steady);
}
}
| 30.691358
| 98
| 0.679002
|
65e1de98b8abd7244c624a22b978379be6247ba1
| 9,816
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package android.support.v4.app;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.widget.RemoteViews;
// Referenced classes of package android.support.v4.app:
// NotificationBuilderWithBuilderAccessor, NotificationCompat
public static class NotificationCompat$NotificationCompatBaseImpl$BuilderBase
implements NotificationBuilderWithBuilderAccessor
{
public Notification build()
{
return mBuilder.getNotification();
// 0 0:aload_0
// 1 1:getfield #151 <Field android.app.Notification$Builder mBuilder>
// 2 4:invokevirtual #157 <Method Notification android.app.Notification$Builder.getNotification()>
// 3 7:areturn
}
public android.app.Notification.Builder getBuilder()
{
return mBuilder;
// 0 0:aload_0
// 1 1:getfield #151 <Field android.app.Notification$Builder mBuilder>
// 2 4:areturn
}
private android.app.Notification.Builder mBuilder;
NotificationCompat$NotificationCompatBaseImpl$BuilderBase(Context context, Notification notification, CharSequence charsequence, CharSequence charsequence1, CharSequence charsequence2, RemoteViews remoteviews, int i,
PendingIntent pendingintent, PendingIntent pendingintent1, Bitmap bitmap, int j, int k, boolean flag)
{
// 0 0:aload_0
// 1 1:invokespecial #19 <Method void Object()>
context = ((Context) ((new android.app.Notification.Builder(context)).setWhen(notification.when).setSmallIcon(notification.icon, notification.iconLevel).setContent(notification.contentView).setTicker(notification.tickerText, remoteviews).setSound(notification.sound, notification.audioStreamType).setVibrate(notification.vibrate).setLights(notification.ledARGB, notification.ledOnMS, notification.ledOffMS)));
// 2 4:new #21 <Class android.app.Notification$Builder>
// 3 7:dup
// 4 8:aload_1
// 5 9:invokespecial #24 <Method void android.app.Notification$Builder(Context)>
// 6 12:aload_2
// 7 13:getfield #30 <Field long Notification.when>
// 8 16:invokevirtual #34 <Method android.app.Notification$Builder android.app.Notification$Builder.setWhen(long)>
// 9 19:aload_2
// 10 20:getfield #38 <Field int Notification.icon>
// 11 23:aload_2
// 12 24:getfield #41 <Field int Notification.iconLevel>
// 13 27:invokevirtual #45 <Method android.app.Notification$Builder android.app.Notification$Builder.setSmallIcon(int, int)>
// 14 30:aload_2
// 15 31:getfield #49 <Field RemoteViews Notification.contentView>
// 16 34:invokevirtual #53 <Method android.app.Notification$Builder android.app.Notification$Builder.setContent(RemoteViews)>
// 17 37:aload_2
// 18 38:getfield #57 <Field CharSequence Notification.tickerText>
// 19 41:aload 6
// 20 43:invokevirtual #61 <Method android.app.Notification$Builder android.app.Notification$Builder.setTicker(CharSequence, RemoteViews)>
// 21 46:aload_2
// 22 47:getfield #65 <Field android.net.Uri Notification.sound>
// 23 50:aload_2
// 24 51:getfield #68 <Field int Notification.audioStreamType>
// 25 54:invokevirtual #72 <Method android.app.Notification$Builder android.app.Notification$Builder.setSound(android.net.Uri, int)>
// 26 57:aload_2
// 27 58:getfield #76 <Field long[] Notification.vibrate>
// 28 61:invokevirtual #80 <Method android.app.Notification$Builder android.app.Notification$Builder.setVibrate(long[])>
// 29 64:aload_2
// 30 65:getfield #83 <Field int Notification.ledARGB>
// 31 68:aload_2
// 32 69:getfield #86 <Field int Notification.ledOnMS>
// 33 72:aload_2
// 34 73:getfield #89 <Field int Notification.ledOffMS>
// 35 76:invokevirtual #93 <Method android.app.Notification$Builder android.app.Notification$Builder.setLights(int, int, int)>
// 36 79:astore_1
int l = notification.flags;
// 37 80:aload_2
// 38 81:getfield #96 <Field int Notification.flags>
// 39 84:istore 14
boolean flag2 = false;
// 40 86:iconst_0
// 41 87:istore 16
boolean flag1;
if((l & 2) != 0)
//* 42 89:iload 14
//* 43 91:iconst_2
//* 44 92:iand
//* 45 93:ifeq 102
flag1 = true;
// 46 96:iconst_1
// 47 97:istore 15
else
//* 48 99:goto 105
flag1 = false;
// 49 102:iconst_0
// 50 103:istore 15
context = ((Context) (((android.app.Notification.Builder) (context)).setOngoing(flag1)));
// 51 105:aload_1
// 52 106:iload 15
// 53 108:invokevirtual #100 <Method android.app.Notification$Builder android.app.Notification$Builder.setOngoing(boolean)>
// 54 111:astore_1
if((notification.flags & 8) != 0)
//* 55 112:aload_2
//* 56 113:getfield #96 <Field int Notification.flags>
//* 57 116:bipush 8
//* 58 118:iand
//* 59 119:ifeq 128
flag1 = true;
// 60 122:iconst_1
// 61 123:istore 15
else
//* 62 125:goto 131
flag1 = false;
// 63 128:iconst_0
// 64 129:istore 15
context = ((Context) (((android.app.Notification.Builder) (context)).setOnlyAlertOnce(flag1)));
// 65 131:aload_1
// 66 132:iload 15
// 67 134:invokevirtual #103 <Method android.app.Notification$Builder android.app.Notification$Builder.setOnlyAlertOnce(boolean)>
// 68 137:astore_1
if((notification.flags & 0x10) != 0)
//* 69 138:aload_2
//* 70 139:getfield #96 <Field int Notification.flags>
//* 71 142:bipush 16
//* 72 144:iand
//* 73 145:ifeq 154
flag1 = true;
// 74 148:iconst_1
// 75 149:istore 15
else
//* 76 151:goto 157
flag1 = false;
// 77 154:iconst_0
// 78 155:istore 15
context = ((Context) (((android.app.Notification.Builder) (context)).setAutoCancel(flag1).setDefaults(notification.defaults).setContentTitle(charsequence).setContentText(charsequence1).setContentInfo(charsequence2).setContentIntent(pendingintent).setDeleteIntent(notification.deleteIntent)));
// 79 157:aload_1
// 80 158:iload 15
// 81 160:invokevirtual #106 <Method android.app.Notification$Builder android.app.Notification$Builder.setAutoCancel(boolean)>
// 82 163:aload_2
// 83 164:getfield #109 <Field int Notification.defaults>
// 84 167:invokevirtual #113 <Method android.app.Notification$Builder android.app.Notification$Builder.setDefaults(int)>
// 85 170:aload_3
// 86 171:invokevirtual #117 <Method android.app.Notification$Builder android.app.Notification$Builder.setContentTitle(CharSequence)>
// 87 174:aload 4
// 88 176:invokevirtual #120 <Method android.app.Notification$Builder android.app.Notification$Builder.setContentText(CharSequence)>
// 89 179:aload 5
// 90 181:invokevirtual #123 <Method android.app.Notification$Builder android.app.Notification$Builder.setContentInfo(CharSequence)>
// 91 184:aload 8
// 92 186:invokevirtual #127 <Method android.app.Notification$Builder android.app.Notification$Builder.setContentIntent(PendingIntent)>
// 93 189:aload_2
// 94 190:getfield #131 <Field PendingIntent Notification.deleteIntent>
// 95 193:invokevirtual #134 <Method android.app.Notification$Builder android.app.Notification$Builder.setDeleteIntent(PendingIntent)>
// 96 196:astore_1
if((notification.flags & 0x80) != 0)
//* 97 197:aload_2
//* 98 198:getfield #96 <Field int Notification.flags>
//* 99 201:sipush 128
//* 100 204:iand
//* 101 205:ifeq 214
flag1 = true;
// 102 208:iconst_1
// 103 209:istore 15
else
//* 104 211:goto 218
flag1 = flag2;
// 105 214:iload 16
// 106 216:istore 15
mBuilder = ((android.app.Notification.Builder) (context)).setFullScreenIntent(pendingintent1, flag1).setLargeIcon(bitmap).setNumber(i).setProgress(j, k, flag);
// 107 218:aload_0
// 108 219:aload_1
// 109 220:aload 9
// 110 222:iload 15
// 111 224:invokevirtual #138 <Method android.app.Notification$Builder android.app.Notification$Builder.setFullScreenIntent(PendingIntent, boolean)>
// 112 227:aload 10
// 113 229:invokevirtual #142 <Method android.app.Notification$Builder android.app.Notification$Builder.setLargeIcon(Bitmap)>
// 114 232:iload 7
// 115 234:invokevirtual #145 <Method android.app.Notification$Builder android.app.Notification$Builder.setNumber(int)>
// 116 237:iload 11
// 117 239:iload 12
// 118 241:iload 13
// 119 243:invokevirtual #149 <Method android.app.Notification$Builder android.app.Notification$Builder.setProgress(int, int, boolean)>
// 120 246:putfield #151 <Field android.app.Notification$Builder mBuilder>
// 121 249:return
}
}
| 51.663158
| 411
| 0.639364
|
476ccdffef66b7646310a209d59290859d5f312f
| 3,453
|
// =================================================================================================
// Copyright 2011 Twitter, Inc.
// -------------------------------------------------------------------------------------------------
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this work except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file, or 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.twitter.common.checkstyle;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Utilities needed by custom checkstyle rules.
*
* @author Utkarsh Srivastava
*/
public final class CheckStyleUtils {
private CheckStyleUtils() {
// utility
}
/**
* Returns the message bundle to use for a custom rule. All built-in rules in checkstyle have
* a message bundle in the same package as that rule. This method returns the path to that
* bundle.
*
* @param parentBuiltInCheckClass The class of the built-in checkstyle rule that the custom rule
* ultimately derives from.
* @return Path to message bundle.
*/
public static String getMessageBundle(final Class<? extends Check> parentBuiltInCheckClass) {
String parentBuiltInCheckClassName = parentBuiltInCheckClass.getName();
// This code is copied from com.puppycrawl.tools.checkstyle.api.
// AbstractViolationReporter.java::getMessageBundle(String s)
// If that method were protected (and not package private) we could
// just invoke it
final int endIndex = parentBuiltInCheckClassName.lastIndexOf('.');
final String messages = "messages";
if (endIndex < 0) {
return messages;
}
final String packageName = parentBuiltInCheckClassName.substring(0, endIndex);
return packageName + "." + messages;
}
/**
* Checks to see if a method has the "@Override" annotation.
*
* @param aAST The AST to check.
* @return Whether the AST represents a method that has the annotation.
*/
public static boolean isOverrideMethod(DetailAST aAST) {
// Need it to be a method, cannot have an override on anything else.
// Must also have MODIFIERS token to hold the @Override
if ((TokenTypes.METHOD_DEF != aAST.getType())
|| (TokenTypes.MODIFIERS != aAST.getFirstChild().getType())) {
return false;
}
// Now loop over all nodes while they are annotations looking for
// an "@Override".
DetailAST node = aAST.getFirstChild().getFirstChild();
while ((null != node) && (TokenTypes.ANNOTATION == node.getType())) {
if ((node.getFirstChild().getType() == TokenTypes.AT)
&& (node.getFirstChild().getNextSibling().getType() == TokenTypes.IDENT)
&& ("Override".equals(node.getFirstChild().getNextSibling().getText()))) {
return true;
}
node = node.getNextSibling();
}
return false;
}
}
| 40.151163
| 100
| 0.640892
|
d74e71a251a34f9513980e2e92047829699ecd78
| 2,020
|
/*
* 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 co.edu.uniandes.csw.monitoria.resources;
import co.edu.uniandes.csw.monitoria.dtos.PagoDTO;
import co.edu.uniandes.csw.monitoria.ejb.PagoLogic;
import co.edu.uniandes.csw.monitoria.entities.PagoEntity;
import co.edu.uniandes.csw.monitoria.exceptions.BusinessLogicException;
import java.util.ArrayList;
import javax.ws.rs.GET;
import java.util.List;
import java.util.logging.Level;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
/**
*
* @author mf.mena
*/
@Path("pagos")
@Produces("application/json")
@Consumes("application/json")
@Stateless
public class PagoResource {
@Inject
PagoLogic pagoLogic; // Variable para acceder a la lógica de la aplicación. Es una inyección de dependencias.
/**
* GET para todos los pagos.
* @return la lista de todos los monitores en objetos json DTO.
*/
@GET
public List<PagoDTO> getPago() {
return listEntity2DetailDTO(pagoLogic.getPagos());
}
private List<PagoDTO> listEntity2DetailDTO(List<PagoEntity> entityList) {
List<PagoDTO> list = new ArrayList<>();
for (PagoEntity entity : entityList) {
list.add(new PagoDTO(entity));
}
return list;
}
@PUT
@Path("{id: \\d+}")
public PagoDTO updatePago(@PathParam("id") Long id, PagoDTO pago) throws BusinessLogicException{
return new PagoDTO(pagoLogic.updatePago(id, pago.toEntity()));
}
@DELETE
@Path("{id: \\d+}")
public void deletePago(@PathParam("id") Long id)throws BusinessLogicException {
pagoLogic.deletePago(id);
}
}
| 30.149254
| 114
| 0.669802
|
f25e1d4904202a7cb76be520d8735afb36d597b8
| 464
|
package cz.seky.backend.objects;
/**
* "infectedByRegion": [
* {
* "name": "Hlavní město Praha",
* "value": 816
* },
* */
public class ApiRegion {
String name,value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
| 16.571429
| 40
| 0.534483
|
f0a18c2cb0a188cda188d6ef3f66c0aa2a4ebbcf
| 109
|
package edu.uoc.geopocket.common.calculation;
public interface Describable {
String getDescription();
}
| 18.166667
| 45
| 0.779817
|
4c951068eaf14921e00aafcbf052749afbd242ac
| 2,167
|
package com.baeldung.lambda.shipping;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import java.util.Comparator;
import java.util.UUID;
public class ShippingService {
private SessionFactory sessionFactory;
private ShippingDao shippingDao;
public ShippingService(SessionFactory sessionFactory, ShippingDao shippingDao) {
this.sessionFactory = sessionFactory;
this.shippingDao = shippingDao;
}
public String createConsignment(Consignment consignment) {
try (Session session = sessionFactory.openSession()) {
consignment.setDelivered(false);
consignment.setId(UUID.randomUUID().toString());
shippingDao.save(session, consignment);
return consignment.getId();
}
}
public void addItem(String consignmentId, Item item) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> addItem(session, consignment, item));
}
}
private void addItem(Session session, Consignment consignment, Item item) {
consignment.getItems()
.add(item);
shippingDao.save(session, consignment);
}
public void checkIn(String consignmentId, Checkin checkin) {
try (Session session = sessionFactory.openSession()) {
shippingDao.find(session, consignmentId)
.ifPresent(consignment -> checkIn(session, consignment, checkin));
}
}
private void checkIn(Session session, Consignment consignment, Checkin checkin) {
consignment.getCheckins().add(checkin);
consignment.getCheckins().sort(Comparator.comparing(Checkin::getTimeStamp));
if (checkin.getLocation().equals(consignment.getDestination())) {
consignment.setDelivered(true);
}
shippingDao.save(session, consignment);
}
public Consignment view(String consignmentId) {
try (Session session = sessionFactory.openSession()) {
return shippingDao.find(session, consignmentId)
.orElseGet(Consignment::new);
}
}
}
| 34.396825
| 85
| 0.671435
|
00fdc16de45eae541ad00320ddbc6a1199a58756
| 139
|
package cn.wildfirechat.remote;
public interface GeneralCallback2 {
void onSuccess(String result);
void onFail(int errorCode);
}
| 17.375
| 35
| 0.755396
|
b6e58ef10d4bc3bfe9ac4cdb244a9b8f7a7b093c
| 421
|
package cn.az.project.rpc.remote.transport;
import cn.az.project.rpc.extension.SPI;
import cn.az.project.rpc.remote.dto.RpcRequest;
/**
* @author az
* @since 12/09/20 22:53
*/
@SPI
public interface RpcRequestTransport {
/**
* send rpc request to server and get result
*
* @param rpcRequest message body
* @return data from server
*/
Object sendRpcRequest(RpcRequest rpcRequest);
}
| 19.136364
| 49
| 0.68171
|
b21ef64862b17ba875d0ada210cc0ff33cae3165
| 269
|
package com.boxiaoyun.cms.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.hysj.cms.client.model.entity.Category;
import org.springframework.stereotype.Repository;
@Repository
public interface CategoryMapper extends BaseMapper<Category> {
}
| 26.9
| 62
| 0.836431
|
4b9afd0647e40efd739483e6b707a70de2ca07ad
| 2,369
|
/*******************************************************************************
* Copyright 2013 Marco Balduini, Emanuele Della Valle
*
* 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.
*
* Acknowledgements:
*
* This work was partially supported by the European project LarKC (FP7-215535)
* and by the European project MODAClouds (FP7-318484)
******************************************************************************/
package polimi.deib.rsp_services_csparql.knowledge_base;
import java.io.IOException;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import polimi.deib.rsp_services_csparql.commons.Csparql_Engine;
import com.google.gson.Gson;
public class Update extends ServerResource {
private Logger logger = LoggerFactory.getLogger(Update.class.getName());
@Post
public void execUpdateQuery(Representation rep){
Gson gson = new Gson();
try {
Csparql_Engine engine = (Csparql_Engine) getContext().getAttributes().get("csparqlengine");
String queryBody;
queryBody = rep.getText();
engine.execUpdateQueryOverDatasource(queryBody);
this.getResponse().setStatus(Status.SUCCESS_OK,"Update operation succeded.");
this.getResponse().setEntity(gson.toJson("Update operation succeded."), MediaType.APPLICATION_JSON);
} catch (IOException e) {
logger.error("Problem during query Operation");
this.getResponse().setStatus(Status.SERVER_ERROR_INTERNAL,"Problem during query Operation");
this.getResponse().setEntity(gson.toJson("Problem during query Operation"), MediaType.APPLICATION_JSON);
} finally {
this.getResponse().commit();
this.commit();
this.release();
}
}
}
| 32.902778
| 107
| 0.705783
|
6fec304779356d17ee9707ffff4d8a8be997187a
| 901
|
package com.armageddon.android.flickrdroid.common;
/**
* Helps to create user logo in different sizes
*/
public interface LogoIcon {
String mini_48px = "_d"; // 48 x 48
String small_60px = "_s"; // 60 x 60
String normal_100px = "_m"; // 100 x 100
String big_150px = "_l"; // 150 x 150
String huge_300px = "_r"; // 300 x 300
//188864276@N07
// Request Example
//https://farm66.staticflickr.com/65535/buddyicons/188349986@N07_m.jpg
default String getUrl (String iconFarm, String iconServer, String nsid, String size) {
StringBuilder sb = new StringBuilder();
sb.append("https://farm");
sb.append(iconFarm);
sb.append(".staticflickr.com/");
sb.append(iconServer);
sb.append("/buddyicons/");
sb.append(nsid);
sb.append(size);
sb.append(".jpg");
return sb.toString();
}
}
| 27.30303
| 90
| 0.612653
|
1f95b490227ddea262f84fde1107439e83145c8b
| 14,995
|
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common
* Development and Distribution License("CDDL") (collectively, the
* "License"). You may not use this file except in compliance with the
* License. You can obtain a copy of the License at
* http://www.netbeans.org/cddl-gplv2.html
* or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
* specific language governing permissions and limitations under the
* License. When distributing the software, include this License Header
* Notice in each file and include the License file at
* nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the
* License Header, with the fields enclosed by brackets [] replaced by
* your own identifying information:
* "Portions Copyrighted [year] [name of copyright owner]"
*
* Contributor(s):
*
* The Original Software is NetBeans. The Initial Developer of the Original
* Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
* Microsystems, Inc. All Rights Reserved.
*
* If you wish your version of this file to be governed by only the CDDL
* or only the GPL Version 2, indicate your decision by adding
* "[Contributor] elects to include this software in this distribution
* under the [CDDL or GPL Version 2] license." If you do not indicate a
* single choice of license, a recipient has the option to distribute
* your version of this file under either the CDDL, the GPL Version 2 or
* to extend the choice of license to its licensees as provided above.
* However, if you add GPL Version 2 code and therefore, elected the GPL
* Version 2 license, then the option applies only if the new code is
* made subject to such option by the copyright holder.
*/
package org.netbeans.modules.form;
import java.beans.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Takes care of registration and finding property editors used by the Form Editor.
*
* @author Ian Formanek, Tomas Pavek
*/
final public class FormPropertyEditorManager {
/**
* Maps property type to property editor class. There are 2 maps - one for
* findings of the standard PropertyEditorManager, one for our specific
* search path (org.netbeans.modules.form.editors2 etc).
*/
private static Map<String, Map<Class, Class>> editorClassCache;
/**
* Maps property type to list of property editor classes. For externally
* registered editors (like i18n).
*/
private static Map<Class, List<Class>> expliciteEditors;
private static final String[] DEFAULT_EDITOR_SEARCH_PATH = {
"org.netbeans.modules.form.editors2", // this needs to be first // NOI18N
"org.netbeans.beaninfo.editors", // NOI18N
"org.netbeans.modules.swingapp" // NOI18N
};
// -------
public static synchronized PropertyEditor findEditor(FormProperty property) {
Class type = property.getValueType();
FormModel form = property.getPropertyContext().getFormModel();
List<PropertyEditor> list = findEditors(type, form, false);
return list.isEmpty() ? null : list.get(0);
}
public static synchronized PropertyEditor[] getAllEditors(FormProperty property) {
Class type = property.getValueType();
FormModel form = property.getPropertyContext().getFormModel();
List<PropertyEditor> list = findEditors(type, form, true);
return list.toArray(new PropertyEditor[list.size()]);
}
public static synchronized void registerEditor(Class propertyType, Class editorClass) {
List<Class> classList;
if (expliciteEditors != null) {
classList = expliciteEditors.get(propertyType);
} else {
classList = null;
expliciteEditors = new HashMap<Class, List<Class>>();
}
if (classList == null) {
classList = new LinkedList<Class>();
classList.add(editorClass);
expliciteEditors.put(propertyType, classList);
} else if (!classList.contains(editorClass)) {
classList.add(editorClass);
}
}
private static List<Class> getRegisteredEditorClasses(Class propertyType) {
List<Class> classList = expliciteEditors != null ? expliciteEditors.get(propertyType) : null;
return classList != null ? classList : Collections.EMPTY_LIST;
}
/**
* Finds a low-level property editor from a set of known editors suitable
* for the GUI builder. It's here for ResourceWrapperEditor implementations
* to find the basic editor they wrap.
* @param type the type of the property
* @return newly created instance of found PropertyEditor, or null if not found
*/
public static PropertyEditor findBasicEditor(Class type) {
return findPrimaryEditor(type, false);
}
private static List<PropertyEditor> findEditors(Class type, FormModel targetForm, boolean all) {
List<PropertyEditor> editorList = new ArrayList<PropertyEditor>(5);
// 1st look for primary editor among known editors
PropertyEditor prEd = findPrimaryEditor(type, true);
if (prEd != null) {
editorList.add(prEd);
if (!all) {
return editorList;
}
}
// 2nd search custom search path (theoretically there can be a package
// from a JAR that is on user project's classpath)
if (isEditorInCache(type, "2")) { // NOI18N
prEd = createEditorFromCache(type, "2"); // NOI18N
} else {
prEd = null;
String typeName = type.getSimpleName();
if (!typeName.contains("[")) { // not an array type // NOI18N
Class editorClass = null;
List<String> defaultSearchPath = Arrays.asList(DEFAULT_EDITOR_SEARCH_PATH);
for (String path : FormLoaderSettings.getInstance().getEditorSearchPath()) {
if (path != null && path.length() > 0 && !defaultSearchPath.contains(path)) {
String name = path + "." + typeName + "Editor"; // NOI18N
try {
editorClass = FormUtils.loadClass(name, targetForm);
prEd = createEditorInstance(editorClass);
if (prEd != null) {
break;
} // otherwise failed instantiating, continue
}
catch (Exception e) {} // silently ignore
editorClass = null;
}
}
addEditorClassToCache(type, editorClass, "2"); // also cache nonexistence // NOI18N
} // ignore array types
}
if (prEd != null) {
editorList.add(prEd);
if (!all) {
return editorList;
}
}
// 3rd additional specialized editors registered using registerEditor(...)
for (Class cls : getRegisteredEditorClasses(type)) {
prEd = createEditorInstance(cls);
if (prEd != null) {
editorList.add(prEd);
if (!all) {
return editorList;
}
}
}
// 4th general ComponentChooserEditor
if (editorList.isEmpty() && isComponentType(type)) {
editorList.add(new ComponentChooserEditor(new Class[] { type }));
if (!all) {
return editorList;
}
}
// 5th general editors for connection and custom code
// A
//editorList.add(new RADConnectionPropertyEditor(type, RADConnectionPropertyEditor.Type.FormConnection));
//editorList.add(new RADConnectionPropertyEditor(type, RADConnectionPropertyEditor.Type.CustomCode));
return editorList;
}
/**
* Finds a property editor in a known set of property editors provided by
* form module and NB platform. It guarantees that the known editors needed
* for the GUI builder are found first, java.beans.PropertyEditorManager is
* consulted only secondarily.
* @param type the type of the property
* @param wrapperAllowed true if the PE may wrap another PE, false to find
* only the basic editor
* @return newly created instance of found PropertyEditor, or null if not found
*/
private static PropertyEditor findPrimaryEditor(Class type, boolean wrapperAllowed) {
// look at the known search path first
PropertyEditor prEd = null;
String cacheKey = wrapperAllowed ? "1a" : "1b"; // NOI18N
if (isEditorInCache(type, cacheKey)) {
prEd = createEditorFromCache(type, cacheKey);
} else {
String typeName = type.getSimpleName();
if (!typeName.contains("[") // not an array type // NOI18N
&& !type.equals(Object.class)) { // Issue 204469
Class editorClass = null;
for (String path : DEFAULT_EDITOR_SEARCH_PATH) {
String name = path + "." + typeName + "Editor"; // NOI18N
try {
editorClass = FormUtils.loadSystemClass(name);
if (wrapperAllowed /*|| !ResourceWrapperEditor.class.isAssignableFrom(editorClass)*/) { // A
prEd = createEditorInstance(editorClass);
if (prEd != null) {
break;
} // otherwise failed instantiating, continue
}
}
catch (Exception e) {} // silently ignore
editorClass = null;
}
addEditorClassToCache(type, editorClass, cacheKey); // also cache nonexistence
} // ignore array types
}
if (prEd == null) {
// if not found on NB search path, try java.beans.PropertyEditorManager
cacheKey = "1c"; // NOI18N
if (isEditorInCache(type, cacheKey)) {
prEd = createEditorFromCache(type, cacheKey);
} else {
prEd = (type != Object.class) ? PropertyEditorManager.findEditor(type) : null;
addEditorToCache(type, prEd, cacheKey); // also cache nonexistence
}
}
return prEd;
}
private static boolean isEditorInCache(Class propertyType, String key) {
return getEditorClassCache(key).containsKey(propertyType);
// the cache may also hold the information that there is no property editor for given type
}
private static PropertyEditor createEditorFromCache(Class propertyType, String key) {
Class editorClass = getEditorClassCache(key).get(propertyType);
return editorClass != null ? createEditorInstance(editorClass) : null;
}
private static void addEditorToCache(Class propertyType, PropertyEditor editor, String key) {
if (editor == null) {
addEditorClassToCache(propertyType, null, key);
} else {
// Caching the class for editor instance is a bit tricky - the instance
// is created by PropertyEditorManager, but we may not be able to re-create
// it just from a class. We assume it is possible if the class has a no-arg
// public constructor. Otherwise we don't cache the property editor class.
Class editorClass = editor.getClass();
try {
Constructor ctor = editorClass.getConstructor();
if (ctor != null && (ctor.getModifiers() & Modifier.PUBLIC) == Modifier.PUBLIC) {
addEditorClassToCache(propertyType, editorClass, key);
}
} catch (NoSuchMethodException ex) {} // ignore
}
}
private static void addEditorClassToCache(Class propertyType, Class editorClass, String key) {
getEditorClassCache(key).put(propertyType, editorClass);
}
private static Map<Class,Class> getEditorClassCache(String key) {
if (editorClassCache == null) {
editorClassCache = new HashMap();
}
Map<Class, Class> classCache = editorClassCache.get(key);
if (classCache == null) {
classCache = new WeakHashMap<Class,Class>();
// the weakness of the map is for classes from user projects
// (property types which we remember we have no property editor for)
editorClassCache.put(key, classCache);
}
return classCache;
}
// /**
// * Returns true if given type has a specific property editor wrapping the
// * default one - so the default searching mechanism is not used to find
// * such an editor. Used for subclasses of ResourceWrapperEditor.
// */
// private static boolean hasWrappingEditor(Class type) {
// return type == String.class
// || type == java.awt.Font.class
// || type == java.awt.Color.class
// || type == javax.swing.Icon.class;
// }
/**
* Returns true if given type can be considered as "component type" - i.e.
* can expect components of this type in the form, so it makes sense to
* have ComponentChooserEditor as one of the property editors for this type.
*/
private static boolean isComponentType(Class type) {
return !type.equals(Object.class) && !type.equals(String.class)
&& !type.isEnum() && !type.isPrimitive()
&& !Number.class.isAssignableFrom(type);
}
private static PropertyEditor createEditorInstance(Class cls) {
try {
return (PropertyEditor) cls.newInstance();
} catch (Exception ex) {
log(ex, "Error instantiating property editor: "+cls.getName()); // NOI18N
}
return null;
}
private static Logger logger;
private static void log(Throwable ex, String msg) {
if (logger == null) {
logger = Logger.getLogger(FormPropertyEditorManager.class.getName());
}
logger.log(Level.INFO, msg, ex);
}
}
| 43.33815
| 116
| 0.624942
|
bdeb67aee6cdf508f81111e0ae4768b65c5fef6e
| 39
|
enum Luz{
Vermelho, Ambar, Verde
}
| 9.75
| 26
| 0.641026
|
be2a95c89cd625546e73ab19dad4858403813f33
| 4,053
|
/**
* Copyright (c) 2010 Martin Geisse
*
* This file is distributed under the terms of the MIT license.
*/
package name.martingeisse.miner.startmenu;
import name.martingeisse.common.javascript.analyze.JsonAnalyzer;
import name.martingeisse.miner.Main;
import name.martingeisse.miner.common.Faction;
import name.martingeisse.miner.ingame.IngameHandler;
import name.martingeisse.stackd.client.gui.Gui;
import name.martingeisse.stackd.client.gui.GuiElement;
import name.martingeisse.stackd.client.gui.control.MessageBox;
import name.martingeisse.stackd.client.gui.element.FillColor;
import name.martingeisse.stackd.client.gui.element.Margin;
import name.martingeisse.stackd.client.gui.element.OverlayStack;
import name.martingeisse.stackd.client.gui.element.Sizer;
import name.martingeisse.stackd.client.gui.element.Spacer;
import name.martingeisse.stackd.client.gui.element.TextParagraph;
import name.martingeisse.stackd.client.gui.element.ThinBorder;
import name.martingeisse.stackd.client.gui.element.VerticalLayout;
import name.martingeisse.stackd.client.gui.util.Color;
import name.martingeisse.stackd.client.util.MouseUtil;
/**
* The "character details" menu page.
*/
public class PlayerDetailsPage extends AbstractStartmenuPage {
/**
* the playerId
*/
private final long playerId;
/**
* the faction
*/
private final Faction faction;
/**
* the name
*/
private final String name;
/**
* the coins
*/
private final int coins;
/**
* Constructor.
* @param playerId the player ID
*/
public PlayerDetailsPage(long playerId) {
// fetch player data
this.playerId = playerId;
JsonAnalyzer json = AccountApiClient.getInstance().fetchPlayerDetails(playerId);
this.faction = Faction.values()[json.analyzeMapElement("faction").expectInteger()];
this.name = json.analyzeMapElement("name").expectString();
this.coins = json.analyzeMapElement("coins").expectInteger();
// build the layout
final VerticalLayout menu = new VerticalLayout();
menu.addElement(buildInfoBox());
menu.addElement(new Spacer(2 * Gui.GRID));
menu.addElement(new Sizer(new StartmenuButton("Play!") {
@Override
protected void onClick() {
play();
}
}, -1, 10 * Gui.GRID));
menu.addElement(new Spacer(2 * Gui.GRID));
menu.addElement(new StartmenuButton("Delete Character") {
@Override
protected void onClick() {
new MessageBox("Really delete this character?", MessageBox.YES_NO) {
@Override
protected void onClose(int buttonIndex) {
if (buttonIndex == 0) {
AccountApiClient.getInstance().deletePlayer(PlayerDetailsPage.this.playerId);
getGui().setRootElement(new ChooseCharacterPage());
}
};
}.show(PlayerDetailsPage.this);
}
});
menu.addElement(new Spacer(2 * Gui.GRID));
menu.addElement(new Sizer(new StartmenuButton("Back") {
@Override
protected void onClick() {
getGui().setRootElement(new ChooseCharacterPage());
}
}, -1, 5 * Gui.GRID));
initializeStartmenuPage(menu);
}
/**
*
*/
private GuiElement buildInfoBox() {
VerticalLayout verticalLayout = new VerticalLayout();
verticalLayout.addElement(new TextParagraph().setText("--- " + name + " ---"));
verticalLayout.addElement(new Spacer(Gui.GRID));
verticalLayout.addElement(new TextParagraph().setText("Faction: " + faction.getDisplayName()));
verticalLayout.addElement(new TextParagraph().setText("Coins: " + coins));
OverlayStack stack = new OverlayStack();
stack.addElement(new FillColor(new Color(128, 128, 128, 255)));
stack.addElement(new Margin(verticalLayout, Gui.GRID));
return new ThinBorder(stack).setColor(new Color(192, 192, 192, 255));
}
/**
*
*/
private void play() {
AccountApiClient.getInstance().accessPlayer(playerId);
getGui().addFollowupOpenglAction(new Runnable() {
@Override
public void run() {
try {
Main.frameLoop.getRootHandler().setWrappedHandler(new IngameHandler());
MouseUtil.grab();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
});
}
}
| 30.022222
| 97
| 0.723168
|
9d574f802b90d215a555a51cbaba8a0555d79733
| 42,877
|
/*******************************************************************************
* Copyright 2013 Mojave Innovations 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.
*
* Contributors:
* Mojave Innovations GmbH - initial API and implementation
******************************************************************************/
package org.entirej.applicationframework.tmt.renderers.blocks;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnViewerToolTipSupport;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.rap.rwt.RWT;
import org.eclipse.rap.rwt.template.Cell;
import org.eclipse.rap.rwt.template.ImageCell;
import org.eclipse.rap.rwt.template.ImageCell.ScaleMode;
import org.eclipse.rap.rwt.template.Template;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusEvent;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.entirej.applicationframework.tmt.layout.EJTMTEntireJGridPane;
import org.entirej.applicationframework.tmt.renderer.interfaces.EJTMTAppBlockRenderer;
import org.entirej.applicationframework.tmt.renderer.interfaces.EJTMTAppItemRenderer;
import org.entirej.applicationframework.tmt.renderers.blocks.definition.interfaces.EJTMTMultiRecordBlockDefinitionProperties;
import org.entirej.applicationframework.tmt.renderers.blocks.definition.interfaces.EJTMTSingleRecordBlockDefinitionProperties;
import org.entirej.applicationframework.tmt.renderers.blocks.definition.interfaces.EJTMTTreeBlockDefinitionProperties;
import org.entirej.applicationframework.tmt.renderers.screen.EJTMTInsertScreenRenderer;
import org.entirej.applicationframework.tmt.renderers.screen.EJTMTQueryScreenRenderer;
import org.entirej.applicationframework.tmt.renderers.screen.EJTMTUpdateScreenRenderer;
import org.entirej.applicationframework.tmt.table.EJTMTAbstractFilteredTable;
import org.entirej.applicationframework.tmt.table.EJTMTAbstractFilteredTable.FilteredContentProvider;
import org.entirej.applicationframework.tmt.table.EJTMTTableViewerColumnFactory;
import org.entirej.framework.core.EJMessage;
import org.entirej.framework.core.data.EJDataRecord;
import org.entirej.framework.core.data.controllers.EJEditableBlockController;
import org.entirej.framework.core.enumerations.EJManagedBlockProperty;
import org.entirej.framework.core.enumerations.EJManagedScreenProperty;
import org.entirej.framework.core.enumerations.EJScreenType;
import org.entirej.framework.core.interfaces.EJScreenItemController;
import org.entirej.framework.core.internal.EJInternalEditableBlock;
import org.entirej.framework.core.properties.EJCoreMainScreenItemProperties;
import org.entirej.framework.core.properties.EJCoreProperties;
import org.entirej.framework.core.properties.EJCoreVisualAttributeProperties;
import org.entirej.framework.core.properties.definitions.interfaces.EJFrameworkExtensionProperties;
import org.entirej.framework.core.properties.interfaces.EJBlockProperties;
import org.entirej.framework.core.properties.interfaces.EJItemGroupProperties;
import org.entirej.framework.core.properties.interfaces.EJMainScreenProperties;
import org.entirej.framework.core.properties.interfaces.EJScreenItemProperties;
import org.entirej.framework.core.renderers.EJManagedItemRendererWrapper;
import org.entirej.framework.core.renderers.interfaces.EJInsertScreenRenderer;
import org.entirej.framework.core.renderers.interfaces.EJQueryScreenRenderer;
import org.entirej.framework.core.renderers.interfaces.EJUpdateScreenRenderer;
import com.eclipsesource.tabris.device.ClientDevice;
import com.eclipsesource.tabris.device.ClientDevice.Platform;
import com.eclipsesource.tabris.widgets.ClientDialog;
import com.eclipsesource.tabris.widgets.ClientDialog.ButtonType;
import com.eclipsesource.tabris.widgets.RefreshComposite;
import com.eclipsesource.tabris.widgets.RefreshListener;
public class EJTMTMultiRecordBlockRenderer implements EJTMTAppBlockRenderer, KeyListener
{
private boolean _isFocused = false;
private EJEditableBlockController _block;
private EJTMTEntireJGridPane _mainPane;
private TableViewer _tableViewer;
private EJTMTQueryScreenRenderer _queryScreenRenderer;
private EJTMTInsertScreenRenderer _insertScreenRenderer;
private EJTMTUpdateScreenRenderer _updateScreenRenderer;
private FilteredContentProvider _filteredContentProvider;
private List<EJDataRecord> _tableBaseRecords = new ArrayList<EJDataRecord>();
protected void clearFilter()
{
if (_filteredContentProvider != null)
{
_filteredContentProvider.setFilter(null);
}
}
@Override
public void refreshBlockProperty(EJManagedBlockProperty managedBlockPropertyType)
{
}
@Override
public void refreshBlockRendererProperty(String propertyName)
{
}
@Override
public void executingQuery()
{
// no impl
}
@Override
public void refreshItemProperty(String itemName, EJManagedScreenProperty managedItemPropertyType, EJDataRecord record)
{
if (EJManagedScreenProperty.ITEM_INSTANCE_VISUAL_ATTRIBUTE.equals(managedItemPropertyType))
{
EJScreenItemController item = _block.getScreenItem(EJScreenType.MAIN, itemName);
if (item != null)
{
if (record == null || _tableViewer == null)
{
return;
}
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
_tableViewer.refresh(record);
}
}
}
else if (EJManagedScreenProperty.ITEM_INSTANCE_HINT_TEXT.equals(managedItemPropertyType))
{
EJScreenItemController item = _block.getScreenItem(EJScreenType.MAIN, itemName);
if (item != null)
{
if (record == null)
{
return;
}
}
}
else if (EJManagedScreenProperty.SCREEN_ITEM_VISUAL_ATTRIBUTE.equals(managedItemPropertyType))
{
EJScreenItemController item = _block.getScreenItem(EJScreenType.MAIN, itemName);
if (item != null)
{
item.getManagedItemRenderer().getUnmanagedRenderer().setVisualAttribute(item.getProperties().getVisualAttributeProperties());
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
_tableViewer.setInput(new Object());
}
}
}
}
@Override
public void refreshItemRendererProperty(String itemName, String propertyName)
{
}
@Override
public Composite getGuiComponent()
{
return _mainPane;
}
@Override
public EJQueryScreenRenderer getQueryScreenRenderer()
{
return _queryScreenRenderer;
}
@Override
public EJInsertScreenRenderer getInsertScreenRenderer()
{
return _insertScreenRenderer;
}
@Override
public EJUpdateScreenRenderer getUpdateScreenRenderer()
{
return _updateScreenRenderer;
}
@Override
public void initialiseRenderer(EJEditableBlockController block)
{
_block = block;
_queryScreenRenderer = new EJTMTQueryScreenRenderer();
_insertScreenRenderer = new EJTMTInsertScreenRenderer();
_updateScreenRenderer = new EJTMTUpdateScreenRenderer();
}
@Override
public void blockCleared()
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
clearFilter();
_tableViewer.setInput(new Object());
}
notifyStatus();
}
@Override
public void synchronize()
{
}
protected void notifyStatus()
{
// TODO
}
@Override
public void detailBlocksCleared()
{
}
@Override
public boolean hasFocus()
{
return _isFocused;
}
public boolean isInsertMode()
{
return false;
}
public boolean isUpdateMode()
{
return false;
}
@Override
public boolean isCurrentRecordDirty()
{
return false;
}
@Override
public void enterInsert(EJDataRecord record)
{
if (_block.getInsertScreenRenderer() == null)
{
EJMessage message = new EJMessage("Please define an Insert Screen Renderer for this form before an insert operation can be performed.");
_block.getForm().getMessenger().handleMessage(message);
}
else
{
_block.getInsertScreenRenderer().open(record);
}
}
@Override
public void enterQuery(EJDataRecord queryRecord)
{
if (_block.getQueryScreenRenderer() == null)
{
EJMessage message = new EJMessage("Please define a Query Screen Renderer for this form before a query operation can be performed.");
_block.getForm().getMessenger().handleMessage(message);
}
else
{
_block.getQueryScreenRenderer().open(queryRecord);
}
}
@Override
public void enterUpdate(EJDataRecord recordToUpdate)
{
if (_block.getUpdateScreenRenderer() == null)
{
EJMessage message = new EJMessage("Please define an Update Screen Renderer for this form before an update operation can be performed.");
_block.getForm().getMessenger().handleMessage(message);
}
else
{
_block.getUpdateScreenRenderer().open(recordToUpdate);
}
}
@Override
public void queryExecuted()
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
clearFilter();
_tableViewer.setInput(new Object());
}
selectRow(0);
}
public void pageRetrieved()
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
clearFilter();
_tableViewer.setInput(new Object());
}
selectRow(0);
}
@Override
public void recordDeleted(int dataBlockRecordNumber)
{
EJDataRecord recordAt = getRecordAt(dataBlockRecordNumber > 1 ? dataBlockRecordNumber - 2 : 0);
if (recordAt == null)
{
recordAt = getLastRecord();
}
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
clearFilter();
_tableViewer.setInput(new Object());
}
if (recordAt != null)
{
recordSelected(recordAt);
}
}
@Override
public void recordInserted(EJDataRecord record)
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
clearFilter();
_tableViewer.setInput(new Object());
}
recordSelected(record);
}
@Override
public void refreshAfterChange(EJDataRecord record)
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
_tableViewer.refresh(record);
}
}
@Override
public void recordSelected(EJDataRecord record)
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
if(record != null )
{
_tableViewer.setSelection( new StructuredSelection(record), true);
}
else
{
selectRow(0);//select default row
}
}
notifyStatus();
}
@Override
public void setHasFocus(boolean focus)
{
_isFocused = focus;
if (_isFocused)
{
showFocusedBorder(true);
_block.focusGained();
}
else
{
showFocusedBorder(false);
_block.focusLost();
}
notifyStatus();
}
/**
* Enables a blue border around this controller. This will indicate that the
* container held by this controller has cursor focus.
*
* @param focused
* If <code>true</code> is passed then the border will be
* displayed, if <code>false</code> is passed then no border will
* be shown.
*/
protected void showFocusedBorder(boolean focused)
{
}
@Override
public void setFocusToItem(EJScreenItemController item)
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
_tableViewer.getTable().forceFocus();
}
}
@Override
public void gainFocus()
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
_tableViewer.getTable().forceFocus();
}
setHasFocus(true);
}
@Override
public EJDataRecord getFocusedRecord()
{
EJDataRecord _focusedRecord = null;
if (_tableViewer != null && !_tableViewer.getTable().isDisposed())
{
ISelection selection = _tableViewer.getSelection();
if (selection instanceof IStructuredSelection)
{
IStructuredSelection structuredSelection = (IStructuredSelection) selection;
Object firstElement = structuredSelection.getFirstElement();
if(firstElement==null )
{
selectRow(0);
structuredSelection = (IStructuredSelection)_tableViewer.getSelection();
firstElement = structuredSelection.getFirstElement();
}
if (firstElement instanceof EJDataRecord)
{
_focusedRecord = (EJDataRecord) firstElement;
}
}
}
return _focusedRecord;
}
@Override
public int getDisplayedRecordNumber(EJDataRecord record)
{
if (record == null)
{
return -1;
}
return _tableBaseRecords.indexOf(record);
}
@Override
public int getDisplayedRecordCount()
{
// Indicates the number of records that are available within the View.
// the number depends on the filters set on the table!
return _tableBaseRecords.size();
}
@Override
public EJDataRecord getFirstRecord()
{
return getRecordAt(0);
}
@Override
public EJDataRecord getLastRecord()
{
return getRecordAt(getDisplayedRecordCount() - 1);
}
@Override
public EJDataRecord getRecordAt(int displayedRecordNumber)
{
if (displayedRecordNumber > -1 && displayedRecordNumber < getDisplayedRecordCount())
{
return _tableBaseRecords.get(displayedRecordNumber);
}
return null;
}
@Override
public EJDataRecord getRecordAfter(EJDataRecord record)
{
int viewIndex = getDisplayedRecordNumber(record);
if (-1 < viewIndex)
{
return getRecordAt(viewIndex + 1);
}
return null;
}
@Override
public EJDataRecord getRecordBefore(EJDataRecord record)
{
int viewIndex = getDisplayedRecordNumber(record);
if (-1 < viewIndex)
{
return getRecordAt(viewIndex - 1);
}
return null;
}
public void selectRow(int selectedRow)
{
if (_tableViewer != null && !_tableViewer.getTable().isDisposed() && getDisplayedRecordCount() > selectedRow)
{
_tableViewer.setSelection(new StructuredSelection(getRecordAt(selectedRow)), true);
}
notifyStatus();
}
public final EJInternalEditableBlock getBlock()
{
return _block.getBlock();
}
@Override
public void buildGuiComponent(EJTMTEntireJGridPane blockCanvas)
{
EJBlockProperties blockProperties = _block.getProperties();
EJMainScreenProperties mainScreenProperties = blockProperties.getMainScreenProperties();
GridData gridData = new GridData(GridData.FILL_BOTH);
gridData.widthHint = mainScreenProperties.getWidth();
gridData.heightHint = mainScreenProperties.getHeight();
gridData.horizontalSpan = mainScreenProperties.getHorizontalSpan();
gridData.verticalSpan = mainScreenProperties.getVerticalSpan();
gridData.grabExcessHorizontalSpace = mainScreenProperties.canExpandHorizontally();
gridData.grabExcessVerticalSpace = mainScreenProperties.canExpandVertically();
if (gridData.grabExcessHorizontalSpace)
{
gridData.minimumWidth = mainScreenProperties.getWidth();
}
if (gridData.grabExcessVerticalSpace)
{
gridData.minimumHeight = mainScreenProperties.getHeight();
}
EJFrameworkExtensionProperties rendererProp = blockProperties.getBlockRendererProperties();
blockCanvas.setLayoutData(gridData);
EJFrameworkExtensionProperties sectionProperties = null;
if (rendererProp != null)
{
sectionProperties = rendererProp.getPropertyGroup(EJTMTSingleRecordBlockDefinitionProperties.ITEM_GROUP_TITLE_BAR);
}
if (mainScreenProperties.getDisplayFrame())
{
Group group = new Group(blockCanvas, SWT.NONE);
group.setLayout(new FillLayout());
group.setLayoutData(gridData);
String frameTitle = mainScreenProperties.getFrameTitle();
if (frameTitle != null && frameTitle.length() > 0)
{
group.setText(frameTitle);
}
_mainPane = new EJTMTEntireJGridPane(group, 1);
}
else
{
_mainPane = new EJTMTEntireJGridPane(blockCanvas, 1);
_mainPane.setLayoutData(gridData);
}
_mainPane.cleanLayout();
Composite tableParent = _mainPane;
final String pullRefreshAction = rendererProp.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.PULL_REFRESH_ACTION);
ClientDevice service = RWT.getClient().getService(ClientDevice.class);
if(pullRefreshAction!=null && pullRefreshAction.length()>0 && service!=null && service.getPlatform() !=Platform.WEB)
{
final RefreshComposite composite = new RefreshComposite( _mainPane, SWT.NONE );
GridLayout layout = new GridLayout(1, false);
layout.marginWidth = 0;
layout.marginLeft = 0;
layout.marginRight = 0;
layout.marginHeight = 0;
layout.marginBottom = 0;
layout.marginTop = 0;
composite.setLayout(layout);
String refreshMsg = rendererProp.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.PULL_REFRESH_MESSAGE);
if(pullRefreshAction!=null && pullRefreshAction.length()>0)
{
composite.setMessage( refreshMsg);
}
else
{
composite.setMessage( "Refreshing..." );
}
composite.addRefreshListener( new RefreshListener() {
@Override
public void refresh() {
EJDataRecord rec = getFocusedRecord();
if(rec!=null)
{
_block.executeActionCommand(pullRefreshAction, EJScreenType.MAIN);
}
composite.done();
}
} );
composite.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
tableParent= composite;
}
int style = SWT.VIRTUAL | SWT.H_SCROLL | SWT.V_SCROLL;
if (rendererProp.getBooleanProperty(EJTMTMultiRecordBlockDefinitionProperties.ROW_SELECTION, true))
{
style = style | SWT.FULL_SELECTION;
}
Collection<EJItemGroupProperties> allItemGroupProperties = _block.getProperties().getScreenItemGroupContainer(EJScreenType.MAIN)
.getAllItemGroupProperties();
final Table table;
final EJTMTAbstractFilteredTable filterTree;
if (rendererProp.getBooleanProperty(EJTMTTreeBlockDefinitionProperties.FILTER, false))
{
if (allItemGroupProperties.size() > 0)
{
EJItemGroupProperties displayProperties = allItemGroupProperties.iterator().next();
if (displayProperties.dispayGroupFrame())
{
Group group = new Group(tableParent, SWT.NONE);
group.setLayout(new FillLayout());
if (displayProperties.getFrameTitle() != null && displayProperties.getFrameTitle().length() > 0)
{
group.setText(displayProperties.getFrameTitle());
}
group.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
filterTree = new EJTMTAbstractFilteredTable(group, style)
{
@Override
public void filter(String filter)
{
if (_filteredContentProvider != null
&& (filter == null && _filteredContentProvider.getFilter() != null || !filter.equals(_filteredContentProvider.getFilter())))
{
_filteredContentProvider.setFilter(filter);
getViewer().setInput(filter);
notifyStatus();
}
}
@Override
protected TableViewer doCreateTableViewer(Composite parent, int style)
{
return _tableViewer = new TableViewer(parent, style);
}
};
}
else
{
filterTree = new EJTMTAbstractFilteredTable(tableParent, style)
{
@Override
public void filter(String filter)
{
if (_filteredContentProvider != null
&& (filter == null && _filteredContentProvider.getFilter() != null || !filter.equals(_filteredContentProvider.getFilter())))
{
_filteredContentProvider.setFilter(filter);
getViewer().setInput(filter);
notifyStatus();
}
}
@Override
protected TableViewer doCreateTableViewer(Composite parent, int style)
{
return _tableViewer = new TableViewer(parent, style);
}
};
filterTree.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
}
}
else
{
filterTree = new EJTMTAbstractFilteredTable(tableParent, style)
{
@Override
public void filter(String filter)
{
if (_filteredContentProvider != null
&& (filter == null && _filteredContentProvider.getFilter() != null || !filter.equals(_filteredContentProvider.getFilter())))
{
_filteredContentProvider.setFilter(filter);
getViewer().setInput(filter);
notifyStatus();
}
}
@Override
protected TableViewer doCreateTableViewer(Composite parent, int style)
{
return _tableViewer = new TableViewer(parent, style);
}
};
filterTree.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
}
table = (_tableViewer = filterTree.getViewer()).getTable();
}
else
{
filterTree = null;
if (allItemGroupProperties.size() > 0)
{
EJItemGroupProperties displayProperties = allItemGroupProperties.iterator().next();
if (displayProperties.dispayGroupFrame())
{
Group group = new Group(tableParent, SWT.NONE);
group.setLayout(new FillLayout());
if (displayProperties.getFrameTitle() != null && displayProperties.getFrameTitle().length() > 0)
{
group.setText(displayProperties.getFrameTitle());
}
group.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
table = new Table(group, style);
}
else
{
table = new Table(tableParent, style);
table.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
}
}
else
{
table = new Table(tableParent, style);
table.setLayoutData(new GridData(GridData.FILL_BOTH | GridData.GRAB_HORIZONTAL | GridData.GRAB_VERTICAL));
}
_tableViewer = new TableViewer(table);
}
table.setLinesVisible(true);
EJTMTTableViewerColumnFactory factory = new EJTMTTableViewerColumnFactory(_tableViewer);
ColumnViewerToolTipSupport.enableFor(_tableViewer);
final List<ColumnLabelProvider> nodeTextProviders = new ArrayList<ColumnLabelProvider>();
Template template = new Template();
int colIndex = 0;
for (EJItemGroupProperties groupProperties : allItemGroupProperties)
{
Collection<EJScreenItemProperties> itemProperties = groupProperties.getAllItemProperties();
for (EJScreenItemProperties screenItemProperties : itemProperties)
{
EJCoreMainScreenItemProperties mainScreenItemProperties = (EJCoreMainScreenItemProperties) screenItemProperties;
ColumnLabelProvider screenItem = createScreenItem(factory, mainScreenItemProperties, template, colIndex);
if (screenItem != null)
{
nodeTextProviders.add(screenItem);
colIndex++;
}
}
}
int rowheight = rendererProp.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.ROW_HEIGHT, 60);
if (rowheight > 0)
{
table.setData(RWT.CUSTOM_ITEM_HEIGHT, rowheight);
}
table.setData(RWT.ROW_TEMPLATE, template);
table.addSelectionListener(new SelectionAdapter()
{
@Override
public void widgetSelected(SelectionEvent e)
{
if (e.text != null)
{
_block.executeActionCommand(e.text, EJScreenType.MAIN);
}
}
});
table.addFocusListener(new FocusListener()
{
@Override
public void focusLost(FocusEvent arg0)
{
setHasFocus(false);
}
@Override
public void focusGained(FocusEvent arg0)
{
setHasFocus(true);
}
});
_mainPane.addMouseListener(new MouseAdapter()
{
@Override
public void mouseDown(MouseEvent arg0)
{
if (!_block.hasFocus())
{
setHasFocus(true);
}
}
});
table.addMouseListener(new MouseAdapter()
{
@Override
public void mouseDown(MouseEvent arg0)
{
if (!_block.hasFocus())
{
setHasFocus(true);
}
}
});
_tableViewer.setContentProvider(_filteredContentProvider = new FilteredContentProvider()
{
boolean matchItem(EJDataRecord rec)
{
if (filter != null && filter.trim().length() > 0)
{
for (ColumnLabelProvider filterTextProvider : nodeTextProviders)
{
String text = filterTextProvider.getText(rec);
if (text != null && text.toLowerCase().contains(filter.toLowerCase()))
{
return true;
}
}
}
return false;
}
@Override
public void inputChanged(Viewer arg0, Object arg1, Object arg2)
{
_tableBaseRecords.clear();
if (arg2 != null && arg2.equals(filter) && filter.trim().length() > 0)
{
// filter
for (EJDataRecord record : _block.getBlock().getRecords())
{
if (matchItem(record))
{
_tableBaseRecords.add(record);
}
}
}
else
{
filter = null;
if (filterTree != null)
{
filterTree.clearText();
}
_tableBaseRecords.addAll(_block.getBlock().getRecords());
}
}
@Override
public void dispose()
{
}
@Override
public Object[] getElements(Object arg0)
{
return _tableBaseRecords.toArray();
}
});
_tableViewer.setInput(new Object());
_tableViewer.addSelectionChangedListener(new ISelectionChangedListener()
{
@Override
public void selectionChanged(SelectionChangedEvent arg0)
{
EJDataRecord focusedRecord = getFocusedRecord();
if (focusedRecord != null)
{
_block.newRecordInstance(focusedRecord);
}
notifyStatus();
}
});
final String selectionAction = rendererProp.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.ROW_SELECTION_ACTION);
if(selectionAction!=null && selectionAction.trim().length()>0)
{
_tableViewer.getTable().addMouseListener(new MouseAdapter()
{
@Override
public void mouseUp(MouseEvent e)
{
EJDataRecord rec = getFocusedRecord();
if(rec!=null)
{
_block.executeActionCommand(selectionAction, EJScreenType.MAIN);
}
}
});
}
}
public ColumnLabelProvider createScreenItem(EJTMTTableViewerColumnFactory factory, EJCoreMainScreenItemProperties itemProps, Template template, int col)
{
if (itemProps.isSpacerItem())
{
return null;
}
EJScreenItemController item = _block.getScreenItem(EJScreenType.MAIN, itemProps.getReferencedItemName());
EJManagedItemRendererWrapper renderer = item.getManagedItemRenderer();
if (renderer != null)
{
EJFrameworkExtensionProperties blockProperties = itemProps.getBlockRendererRequiredProperties();
EJTMTAppItemRenderer itemRenderer = (EJTMTAppItemRenderer) renderer.getUnmanagedRenderer();
ColumnLabelProvider labelProvider = itemRenderer.createColumnLabelProvider(itemProps, item);
if (labelProvider != null)
{
Cell<? extends Cell<?>> columnCell = itemRenderer.createColumnCell(itemProps, item, template);
if (columnCell == null)
{
return null;
}
columnCell.setBindingIndex(col);
int width = blockProperties.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.WIDTH_PROPERTY, 0);
int height = blockProperties.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.HEIGHT_PROPERTY, 0);
int top = blockProperties.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_TOP, -1);
int left = blockProperties.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_LEFT, -1);
int right = blockProperties.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_RIGHT, -1);
int bottom = blockProperties.getIntProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_BOTTOM, -1);
String visualAttribute = blockProperties.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.VISUAL_ATTRIBUTE_PROPERTY);
if (visualAttribute != null)
{
EJCoreVisualAttributeProperties va = EJCoreProperties.getInstance().getVisualAttributesContainer()
.getVisualAttributeProperties(visualAttribute);
if (va != null)
{
itemRenderer.setInitialVisualAttribute(va);
}
}
// create dummy column
TableViewerColumn viewerColumn = factory.createColumn(itemProps.getLabel(), 5, labelProvider, SWT.LEFT);
TableColumn column = viewerColumn.getColumn();
column.setData("KEY", itemProps.getReferencedItemName());
column.setToolTipText(itemProps.getHint());
if(columnCell instanceof ImageCell)
{
if(width>0 & height>0)
{
((ImageCell)columnCell).setScaleMode(ScaleMode.FILL);
}
}
if(width>0)
{
if((left==-1 && right!=-1) || EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_RIGHT.equals(blockProperties
.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_H_ALIGNMENT)))
{
left = -1;
if(right==-1)
{
right =0;
}
}
else
{
right = -1;
if(left==-1)
{
left =0;
}
}
}
if(height>0)
{
if((top==-1 && bottom!=-1) || EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_BOTTOM.equals(blockProperties
.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_V_ALIGNMENT)))
{
top = -1;
if(bottom==-1)
{
bottom =0;
}
}
else
{
bottom = -1;
if(top==-1)
{
top =0;
}
}
}
if (top > -1)
{
columnCell.setTop(top);
}
if (left > -1)
{
columnCell.setLeft(left);
}
if (right > -1)
{
columnCell.setRight(right);
}
if (bottom > -1)
{
columnCell.setBottom(bottom);
}
if (left <= -1 && right <= -1)
{
if(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_RIGHT.equals(blockProperties
.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_H_ALIGNMENT)))
{
columnCell.setRight(0);
}
else
{
columnCell.setLeft(0);
}
}
if (top <= -1 && bottom <= -1)
{
if(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_BOTTOM.equals(blockProperties
.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_V_ALIGNMENT)))
{
columnCell.setBottom(0);
}
else
{
columnCell.setTop(0);
}
}
if (left <= -1 || right <= -1)
{
if (width != 0)
{
columnCell.setWidth(width);
}
else
{
columnCell.setWidth(20);
}
}
if (top <= -1 || bottom <= -1)
{
if (height != 0)
{
columnCell.setHeight(height);
}
else
{
columnCell.setHeight(20);
}
}
columnCell.setHorizontalAlignment(getComponentStyle(blockProperties
.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_H_ALIGNMENT)));
columnCell
.setVerticalAlignment(getComponentStyle(blockProperties.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_V_ALIGNMENT)));
final String action = blockProperties.getStringProperty(EJTMTMultiRecordBlockDefinitionProperties.CELL_ACTION_COMMAND);
if (action != null && action.length() > 0)
{
columnCell.setName(action);
columnCell.setSelectable(true);
}
return labelProvider;
}
}
return null;
}
@Override
public void keyPressed(KeyEvent arg0)
{
// ignore
}
@Override
public void keyReleased(KeyEvent arg0)
{
}
protected int getComponentStyle(String alignmentProperty)
{
if (alignmentProperty != null && alignmentProperty.trim().length() > 0)
{
if (alignmentProperty.equals(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_LEFT))
{
return SWT.LEFT;
}
if (alignmentProperty.equals(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_RIGHT))
{
return SWT.RIGHT;
}
if (alignmentProperty.equals(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_CENTER))
{
return SWT.CENTER;
}
if (alignmentProperty.equals(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_TOP))
{
return SWT.TOP;
}
if (alignmentProperty.equals(EJTMTMultiRecordBlockDefinitionProperties.COLUMN_ALLIGN_BOTTOM))
{
return SWT.BOTTOM;
}
}
return SWT.NONE;
}
@Override
public void askToDeleteRecord(final EJDataRecord recordToDelete, String msg)
{
if (msg == null)
{
msg = "Are you sure you want to delete the current record?";
}
ClientDialog hintDialog = new ClientDialog();
hintDialog.setTitle("Delete");
hintDialog.setMessage(msg);
hintDialog.setButton(ButtonType.OK, "Yes", new Listener()
{
@Override
public void handleEvent(Event event)
{
_block.getBlock().deleteRecord(recordToDelete);
_block.setRendererFocus(true);
}
});
hintDialog.setButton(ButtonType.CANCEL, "No");
hintDialog.open();
}
}
| 35.318781
| 160
| 0.566201
|
146cb78f0dfe56befc7d357d63d3016616a5ad7e
| 5,120
|
package org.drools.compiler.compiler;
import org.drools.compiler.builder.impl.KnowledgeBuilderConfigurationImpl;
import org.drools.core.base.ClassTypeResolver;
import org.drools.core.base.TypeResolver;
import org.drools.core.definitions.InternalKnowledgePackage;
import org.drools.core.definitions.rule.impl.RuleImpl;
import org.drools.core.util.ClassUtils;
import org.drools.core.factmodel.traits.TraitRegistry;
import org.drools.compiler.lang.descr.ImportDescr;
import org.drools.core.rule.DialectRuntimeRegistry;
import org.drools.core.rule.ImportDeclaration;
import org.drools.core.spi.Consequence;
import org.kie.api.io.Resource;
import java.util.HashSet;
import java.util.Map;
public class PackageRegistry {
private static final String[] implicitImports = new String[] {
"org.kie.api.definition.rule.*",
"org.kie.api.definition.type.*",
"org.drools.core.factmodel.traits.Alias",
"org.drools.core.factmodel.traits.Trait",
"org.drools.core.factmodel.traits.Traitable",
"org.drools.core.beliefsystem.abductive.Abductive",
"org.drools.core.beliefsystem.abductive.Abducible" };
private final InternalKnowledgePackage pkg;
private String dialect;
private final DialectRuntimeRegistry dialectRuntimeRegistry;
private final DialectCompiletimeRegistry dialectCompiletimeRegistry;
private final TypeResolver typeResolver;
public PackageRegistry(ClassLoader rootClassLoader, KnowledgeBuilderConfigurationImpl pkgConf, InternalKnowledgePackage pkg) {
this.pkg = pkg;
this.dialectCompiletimeRegistry = pkgConf.buildDialectRegistry(rootClassLoader, pkgConf, this, pkg);
this.dialectRuntimeRegistry = pkg.getDialectRuntimeRegistry();
this.typeResolver = new ClassTypeResolver( new HashSet<String>( this.pkg.getImports().keySet() ),
rootClassLoader,
this.pkg.getName() );
this.typeResolver.addImport( pkg.getName() + ".*" );
for (String implicitImport : implicitImports) {
this.typeResolver.addImplicitImport( implicitImport );
}
pkg.setTypeResolver(typeResolver);
}
private PackageRegistry(InternalKnowledgePackage pkg, DialectRuntimeRegistry runtimeRegistry, DialectCompiletimeRegistry compiletimeRegistry, TypeResolver typeResolver) {
this.pkg = pkg;
this.dialectRuntimeRegistry = runtimeRegistry;
this.dialectCompiletimeRegistry = compiletimeRegistry;
this.typeResolver = typeResolver;
}
PackageRegistry clonePackage(ClassLoader classLoader) {
InternalKnowledgePackage clonedPkg = ClassUtils.deepClone(pkg, classLoader);
clonedPkg.setDialectRuntimeRegistry(pkg.getDialectRuntimeRegistry());
for (org.kie.api.definition.rule.Rule rule : pkg.getRules()) {
RuleImpl clonedRule = clonedPkg.getRule(rule.getName());
clonedRule.setConsequence(((RuleImpl)rule).getConsequence());
if (((RuleImpl)rule).hasNamedConsequences()) {
for (Map.Entry<String, Consequence> namedConsequence : ((RuleImpl)rule).getNamedConsequences().entrySet()) {
clonedRule.addNamedConsequence(namedConsequence.getKey(), namedConsequence.getValue());
}
}
}
PackageRegistry clone = new PackageRegistry(clonedPkg, dialectRuntimeRegistry, dialectCompiletimeRegistry, typeResolver);
clone.setDialect(dialect);
return clone;
}
public String getDialect() {
return dialect;
}
public void setDialect(String dialect) {
this.dialect = dialect;
}
public InternalKnowledgePackage getPackage() {
return pkg;
}
public ClassLoader getPackageClassLoader() {
return getPackage().getPackageClassLoader();
}
public DialectRuntimeRegistry getDialectRuntimeRegistry() {
return dialectRuntimeRegistry;
}
public DialectCompiletimeRegistry getDialectCompiletimeRegistry() {
return dialectCompiletimeRegistry;
}
public void addImport(ImportDescr importDescr) {
registerImport( importDescr.getTarget() );
this.dialectCompiletimeRegistry.addImport( importDescr );
}
public void registerImport(String importEntry) {
this.pkg.addImport( new ImportDeclaration( importEntry ) );
this.typeResolver.addImport( importEntry );
}
public void addStaticImport(ImportDescr importDescr) {
this.dialectCompiletimeRegistry.addStaticImport( importDescr );
}
public TypeResolver getTypeResolver() {
return this.typeResolver;
}
public void compileAll() {
this.dialectCompiletimeRegistry.compileAll();
}
public boolean removeObjectsGeneratedFromResource(Resource resource) {
return pkg.removeObjectsGeneratedFromResource(resource);
}
public TraitRegistry getTraitRegistry() {
return pkg.getTraitRegistry();
}
}
| 38.208955
| 174
| 0.698828
|
20081417797502d348b37f1ec4a9fcaadc09d805
| 1,251
|
/**
* [1968] - [2020] Centros Culturales de Mexico A.C / Universidad Panamericana
* All Rights Reserved.
*/
package up.edu.isgc.raytracer.lights;
import up.edu.isgc.raytracer.Intersection;
import up.edu.isgc.raytracer.Materials.Material;
import up.edu.isgc.raytracer.Vector3D;
import java.awt.*;
/**
* @author Asael Fernandez
* @coauthor Jafet Rodríguez
*/
public class DirectionalLight extends Light {
private Vector3D direction;
/** Getters, setters and constructors of the class
*/
public DirectionalLight(Vector3D position, Vector3D direction, Material material, double intensity){
super(position, material, intensity);
setDirection(Vector3D.normalize(direction));
}
public Vector3D getDirection() {
return direction;
}
public void setDirection(Vector3D direction) {
this.direction = direction;
}
/**
* calculate de dot product for the light diffuse
* @param intersection
* @return
*/
@Override
public float getNDotL(Intersection intersection) {
return (float)Math.max(Vector3D.dotProduct(intersection.getNormal(), Vector3D.scalarMultiplication(getDirection(), -1.0)), 0.0);
}
}
| 28.431818
| 137
| 0.673062
|
193285330f412046e90d9c4c403ea7902fbe0e6d
| 1,114
|
package com.github.mforoni.jbasic;
import java.lang.reflect.Array;
import java.util.Collection;
import javax.annotation.Nonnull;
import com.google.common.annotations.Beta;
/**
* Provides {@code static} utility methods for manipulating {@link Collection} objects.
*
* @author Foroni Marco
* @see Collection
*/
@Beta
public final class JCollections {
// Suppresses default constructor, ensuring non-instantiability.
private JCollections() {
throw new AssertionError();
}
/**
* Convert the specified collection to a new array.
*
* @param collection a {@link Collection}
* @param type the generic type
* @return a new array having the same elements of the specified collection
*/
@Beta
@Nonnull
public static <T> T[] toArray(@Nonnull final Collection<T> collection,
@Nonnull final Class<T> type) {
// Use Array native method to create array of a type only known at run time
@SuppressWarnings("unchecked")
final T[] array = (T[]) Array.newInstance(type, collection.size());
return collection.toArray(array);
}
}
| 29.315789
| 88
| 0.686715
|
8248843421274e53598527a75d58c5906932ae88
| 1,515
|
package me.moodcat.backend.rooms;
import me.moodcat.database.controllers.UserDAO;
import me.moodcat.database.entities.ChatMessage;
import me.moodcat.database.entities.Room;
import me.moodcat.database.entities.User;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.Transactional;
/**
* ChatMessageFactory.
*/
public class ChatMessageFactory {
private final Provider<UserDAO> userDAOProvider;
@Inject
public ChatMessageFactory(final Provider<UserDAO> userDAOProvider) {
this.userDAOProvider = userDAOProvider;
}
/**
* Create a ChatMessage entity according to the ChatMessage instance
* provided by the backend.
*
* @param room
* The room the chat message was posted in.
* @param chatMessageInstance
* The ChatMessage.
* @return The ChatMessage entity to store in the database.
*/
@Transactional
public ChatMessage create(final Room room, final ChatMessageInstance chatMessageInstance) {
final ChatMessage chatMessage = new ChatMessage();
final User user = userDAOProvider.get().findById(
chatMessageInstance.getUserId());
chatMessage.setUser(user);
chatMessage.setMessage(chatMessageInstance.getMessage());
chatMessage.setTimestamp(chatMessageInstance.getTimestamp());
chatMessage.setId(chatMessageInstance.getId());
chatMessage.setRoom(room);
return chatMessage;
}
}
| 31.5625
| 95
| 0.708251
|
306e3911749117432031c901693be1c3030849fd
| 158
|
package com.raoulvdberge.refinedstorage.item.info;
import net.minecraft.util.ResourceLocation;
public interface IItemInfo {
ResourceLocation getId();
}
| 19.75
| 50
| 0.803797
|
17593bf96d6d3ac6d9e49b3649e8f75354d0d3d6
| 3,888
|
package com.bsmoot.service;
import com.bsmoot.constants.Constants;
import com.fasterxml.jackson.annotation.*;
import java.util.HashMap;
import java.util.Map;
/**
* Represent the ReCaptcha response object
* @author Nadav Bismuth
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder({
Constants.SUCCESS_PARAM_NAME,
Constants.CHALLENGE_PARAM_NAME,
Constants.HOSTNAME_PARAM_NAME,
Constants.ERRORS_PARAM_NAME
})
public class ReCaptchaResponse {
@JsonProperty(Constants.SUCCESS_PARAM_NAME)
private boolean success;
@JsonProperty(Constants.CHALLENGE_PARAM_NAME)
private String challengeTs;
@JsonProperty(Constants.HOSTNAME_PARAM_NAME)
private String hostname;
@JsonProperty(Constants.ERRORS_PARAM_NAME)
private ErrorCode[] errorCodes;
public ReCaptchaResponse() {
}
public ReCaptchaResponse(boolean success, ErrorCode[] errorCodes) {
this.success = success;
this.errorCodes = errorCodes;
}
@JsonIgnore
public boolean hasClientError() {
ErrorCode[] errors = getErrorCodes();
if(errors == null) {
return false;
}
for(ErrorCode error : errors) {
switch(error) {
case InvalidResponse:
case MissingResponse:
case TimeoutOrDuplicate:
return true;
}
}
return false;
}
@JsonIgnore
public boolean hasServerError() {
ErrorCode[] errors = getErrorCodes();
if(errors == null ) {
return false;
}
for(ErrorCode error : errors) {
switch(error) {
case InvalidSecret:
case MissingSecret:
case BedRequest:
case GeneralError:
return true;
}
}
return false;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getChallengeTs() {
return challengeTs;
}
public void setChallengeTs(String challengeTs) {
this.challengeTs = challengeTs;
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public ErrorCode[] getErrorCodes() {
return errorCodes;
}
public void setErrorCodes(ErrorCode[] errorCodes) {
this.errorCodes = errorCodes;
}
public enum ErrorCode {
MissingSecret,
InvalidSecret,
MissingResponse,
InvalidResponse,
BedRequest,
TimeoutOrDuplicate,
GeneralError;
private static Map<String, ErrorCode> errorsMap = new HashMap<String, ErrorCode>(6);
static {
errorsMap.put(Constants.ERROR_MISSING_SECRET, MissingSecret);
errorsMap.put(Constants.ERROR_INVALID_SECRET, InvalidSecret);
errorsMap.put(Constants.ERROR_MISSING_RESPONSE, MissingResponse);
errorsMap.put(Constants.ERROR_INVALID_RESPONSE, InvalidResponse);
errorsMap.put(Constants.ERROR_BED_REQUEST, BedRequest);
errorsMap.put(Constants.ERROR_TIMEOUT_OR_DUPLICATE, TimeoutOrDuplicate);
errorsMap.put(Constants.ERROR_GENERAL, GeneralError);
}
public String getErrorCodeKey(){
return errorsMap
.entrySet()
.stream().filter(entry -> entry.getValue() == this)
.map(Map.Entry::getKey)
.findFirst()
.orElse(null);
}
@JsonCreator
public static ErrorCode forValue(String value) {
return errorsMap.get(value.toLowerCase());
}
}
}
| 26.44898
| 92
| 0.608539
|
96427413fc9cd43a0db7d2dc3ceb0f281cd62213
| 74
|
package pageObjects.modules;
public class StudentDemographicDataPage {
}
| 14.8
| 41
| 0.837838
|
0170ed22ac59644d8a26881295844500d638c31c
| 5,263
|
package com.vaadin.componentfactory;
/*
* #%L
* Vaadin Component Factory Toggle Button Component for Vaadin 14
* %%
* Copyright (C) 2017 - 2019 Vaadin Ltd
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import com.vaadin.flow.component.AbstractField;
import com.vaadin.flow.component.AbstractSinglePropertyField;
import com.vaadin.flow.component.ClickNotifier;
import com.vaadin.flow.component.ComponentEvent;
import com.vaadin.flow.component.ComponentEventListener;
import com.vaadin.flow.component.DomEvent;
import com.vaadin.flow.component.Focusable;
import com.vaadin.flow.component.HasSize;
import com.vaadin.flow.component.HasStyle;
import com.vaadin.flow.component.Tag;
import com.vaadin.flow.component.dependency.JsModule;
import com.vaadin.flow.component.dependency.NpmPackage;
import com.vaadin.flow.shared.Registration;
/**
* Server-side component for the <code>vcf-toggle-button</code> element.
*
* @author Vaadin Ltd
*/
@Tag("vcf-toggle-button")
@NpmPackage(value = "@vaadin-component-factory/vcf-toggle-button", version = "1.0.3")
@JsModule("@vaadin-component-factory/vcf-toggle-button")
@SuppressWarnings("serial")
public class ToggleButton extends
AbstractSinglePropertyField<ToggleButton, Boolean> implements HasStyle,
HasSize, Focusable<ToggleButton>, ClickNotifier<ToggleButton> {
/**
* Default constructor.
*/
public ToggleButton() {
super("checked", false, false);
}
/**
* Constructs a toggle button with the initial label text.
*
* @param labelText
* the label text to set
* @see #setLabel(String)
*/
public ToggleButton(String labelText) {
this();
setLabel(labelText);
}
/**
* Constructs a toggle button with the initial value.
*
* @param initialValue
* the initial value
* @see AbstractField#setValue(Object)
*/
public ToggleButton(boolean initialValue) {
this();
setValue(initialValue);
}
/**
* Constructs a toggle button with the initial value.
*
* @param labelText
* the label text to set
* @param initialValue
* the initial value
* @see #setLabel(String)
* @see AbstractField#setValue(Object)
*/
public ToggleButton(String labelText, boolean initialValue) {
this(labelText);
setValue(initialValue);
}
/**
* Constructs a toggle button with the initial label text and value change
* listener.
*
* @param label
* the label text to set
* @param listener
* the value change listener to add
* @see #setLabel(String)
* @see #addValueChangeListener(ValueChangeListener)
*/
public ToggleButton(String label,
ValueChangeListener<ComponentValueChangeEvent<ToggleButton, Boolean>> listener) {
this(label);
addValueChangeListener(listener);
}
/**
* Get the current label text.
*
* @return the current label text
*/
public String getLabel() {
return getElement().getProperty("label");
}
/**
* Sets label of toggle button
*
* @param label
* the label text to set
*/
public void setLabel(String label) {
getElement().setProperty("label", label);
}
/**
* If true, the user cannot interact with this element.
* <p>
* This property is not synchronized automatically from the client side, so
* the returned value may not be the same as in client side.
* </p>
*
* @return the {@code disabled} property from the webcomponent
*/
protected boolean isDisabled() {
return getElement().getProperty("disabled", false);
}
/**
* Disables the toggle button.
*
* @param disabled
* the boolean value to set
*/
public void setDisabled(boolean disabled) {
getElement().setProperty("disabled", disabled);
}
@DomEvent("change")
public static class ChangeEvent extends ComponentEvent<ToggleButton> {
public ChangeEvent(ToggleButton source, boolean fromClient) {
super(source, fromClient);
}
}
/**
* Adds a listener for {@code change} events fired by the webcomponent.
*
* @param listener
* the listener
* @return a {@link Registration} for removing the event listener
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Registration addChangeListener(
ComponentEventListener<ChangeEvent> listener) {
return addListener(ChangeEvent.class,
(ComponentEventListener) listener);
}
}
| 29.567416
| 93
| 0.65096
|
833b8fb44ac175db1350524f4666d575ce18debb
| 5,799
|
package com.stream.hstream.fragments;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.stream.dao.Favorite;
import com.stream.hstream.HStreamDB;
import com.stream.hstream.R;
import com.stream.hstream.adapter.SimpleHolder;
import com.stream.scene.ToolBarFragment;
import com.stream.util.DrawableManager;
import com.stream.util.LoadImageHelper;
import com.stream.videoplayerlibrary.common.VideoUtils;
import com.stream.videoplayerlibrary.tv.TuMediaPlayerManager;
import com.stream.videoplayerlibrary.tv.TuVideoPlayer;
import com.stream.widget.view.ViewTransition;
import java.util.List;
/**
* Created by Fuzm on 2017/4/27 0027.
*/
public class VideoFavoriteFragment extends ToolBarFragment {
private ListView mListView;
private FavoriteListAdapter mAdapter;
private ViewTransition mViewTransition;
private List<Favorite> mData;
@Nullable
@Override
public View onCreateView2(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_favorite_main, container, false);
mListView = (ListView) view.findViewById(R.id.list_favorites);
TextView tip = (TextView) view.findViewById(R.id.tip);
mData = HStreamDB.queryAllFavorite();
mAdapter = new FavoriteListAdapter(LayoutInflater.from(getContext()), getContext());
mListView.setAdapter(mAdapter);
Drawable drawable = DrawableManager.getDrawable(getContext(), R.drawable.ic_big_favorite);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
tip.setCompoundDrawables(null, drawable, null, null);
mViewTransition = new ViewTransition(mListView, tip);
updateView();
return view;
}
public void updateView() {
if(mData != null && mData.size() > 0) {
mViewTransition.showView(0, true);
} else {
mViewTransition.showView(1, true);
}
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setTitle(getResources().getString(R.string.menu_favorite));
setNavigationIcon(R.drawable.v_arrow_left_dark_x24);
}
@Override
public void onDestroy() {
super.onDestroy();
mListView = null;
mViewTransition = null;
mData = null;
TuMediaPlayerManager.releaseManager();
}
@Override
public int getNavCheckedItem() {
return R.id.nav_favorite;
}
@Override
public void onNavigationClick() {
onBackPressed();
}
private class FavoriteListAdapter extends com.stream.hstream.adapter.SimpleAdapter<VideoHolder> {
private final LayoutInflater mInflater;
private final Context mContext;
public FavoriteListAdapter(@NonNull LayoutInflater inflater, Context context) {
mContext = context;
mInflater = inflater;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Object getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public VideoHolder onCreateViewHolder(ViewGroup parent) {
return new VideoHolder(mInflater.inflate(R.layout.item_favorite_video_list, parent, false));
}
@Override
public void onBindViewHolder(VideoHolder holder, int position) {
Favorite favorite = mData.get(position);
holder.mVideoPlayer.setUp(favorite.getVideo_url(), favorite.getTitle(), TuVideoPlayer.MODE_NORMAL_SCREEN);
if(favorite.getThumb().startsWith("http://") || favorite.getThumb().startsWith("https://")) {
holder.setThumb(mContext, favorite.getToken(), favorite.getThumb());
} else {
holder.mVideoPlayer.setThumb(VideoUtils.getDrawableFromPath(mContext, favorite.getThumb()));
}
}
}
private class VideoHolder extends SimpleHolder implements View.OnClickListener{
private View mItemView;
private TuVideoPlayer mVideoPlayer;
private LoadImageHelper mImageHelper;
private Button mDelete;
public VideoHolder(View itemView) {
super(itemView);
mItemView = itemView;
mVideoPlayer = (TuVideoPlayer) itemView.findViewById(R.id.list_favorite_video);
mDelete = (Button) itemView.findViewById(R.id.delete);
mDelete.setOnClickListener(this);
}
public void setThumb(Context context, String token, String thumb) {
mImageHelper = LoadImageHelper.with(context)
.load(token, thumb)
.into(mVideoPlayer.getThumb());
}
@Override
public void onClick(View v) {
int index = mListView.getPositionForView(mItemView);
if(index == -1) {
return;
}
if(v == mDelete) {
Favorite favorite = mData.get(index);
HStreamDB.removeFavorite(favorite.getToken());
mVideoPlayer.suspend();
mData.remove(index);
mAdapter.notifyDataSetChanged();
}
}
}
}
| 32.038674
| 124
| 0.660976
|
d5cb91b0c579f3a88e3ed5de588f6c4959b22abd
| 1,737
|
package com.marekhakala.mynomadlifeapp.UI;
import android.app.Application;
import android.content.Context;
import com.marekhakala.mynomadlifeapp.Repository.IMyNomadLifeRepository;
import com.marekhakala.mynomadlifeapp.UI.Loader.CitiesLoader;
import com.marekhakala.mynomadlifeapp.UI.Loader.ExchangeRatesLoader;
import com.marekhakala.mynomadlifeapp.UI.Loader.OfflineModeCitiesLoader;
import com.marekhakala.mynomadlifeapp.UI.Loader.OfflinePlacesToWorkLoader;
import com.marekhakala.mynomadlifeapp.UI.Loader.PlacesToWorkLoader;
import dagger.Module;
import dagger.Provides;
@Module
public class UiModule {
@Provides
public Context providesApplicationContext(Application application) {
return application.getApplicationContext();
}
@Provides
public CitiesLoader providesCitiesLoader(Context context, IMyNomadLifeRepository repository) {
return new CitiesLoader(context, repository);
}
@Provides
public OfflineModeCitiesLoader providesOfflineModeCitiesLoader(Context context, IMyNomadLifeRepository repository) {
return new OfflineModeCitiesLoader(context, repository);
}
@Provides
public PlacesToWorkLoader providesPlacesToWorkLoader(Context context, IMyNomadLifeRepository repository) {
return new PlacesToWorkLoader(context, repository);
}
@Provides
public OfflinePlacesToWorkLoader providesOfflinePlacesToWorkLoader(Context context, IMyNomadLifeRepository repository) {
return new OfflinePlacesToWorkLoader(context, repository);
}
@Provides
public ExchangeRatesLoader providesExchangeRatesLoader(Context context, IMyNomadLifeRepository repository) {
return new ExchangeRatesLoader(context, repository);
}
}
| 36.1875
| 124
| 0.803109
|
5a63959f2eb775b9aadb01a2171aae19e9061dbb
| 689
|
/*
*/
package networthcalculator.utilities;
import javafx.event.EventHandler;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
/**
*
* @author MP
*/
public class EventHandlerMaker {
public static EventHandler<KeyEvent> maxLength() {
return new EventHandler<KeyEvent>() {
@Override
public void handle(KeyEvent arg0) {
int length = 8; // Max length of amount
TextField tx = (TextField) arg0.getSource();
if (tx.getText().length() >= length) {
arg0.consume();
}
}
};
}
}
| 21.53125
| 60
| 0.525399
|
7c6e93fe3a4a0e1fc3a5a617825949eac48aed85
| 9,460
|
package uk.ac.ebi.atlas.experimentpage.cellplot;
import com.google.common.collect.ImmutableMap;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.test.context.web.WebAppConfiguration;
import uk.ac.ebi.atlas.configuration.TestConfig;
import uk.ac.ebi.atlas.testutils.JdbcUtils;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Stream;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatNullPointerException;
import static uk.ac.ebi.atlas.testutils.RandomDataTestUtils.generateRandomEnsemblGeneId;
import static uk.ac.ebi.atlas.testutils.RandomDataTestUtils.generateRandomExperimentAccession;
@ExtendWith(SpringExtension.class)
@WebAppConfiguration
@ContextConfiguration(classes = TestConfig.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class CellPlotDaoIT {
private static final Random RNG = ThreadLocalRandom.current();
@Inject
private DataSource dataSource;
@Inject
private JdbcUtils jdbcTestUtils;
@Inject
private CellPlotDao subject;
public ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
@BeforeAll
void populateDatabaseTables() {
populator.setScripts(
new ClassPathResource("fixtures/202108/experiment.sql"),
new ClassPathResource("fixtures/202108/scxa_analytics.sql"),
new ClassPathResource("fixtures/202108/scxa_coords.sql"),
new ClassPathResource("fixtures/202108/scxa_cell_group.sql"),
new ClassPathResource("fixtures/202108/scxa_cell_group_membership.sql"));
populator.execute(dataSource);
}
@AfterAll
void cleanDatabaseTables() {
populator.setScripts(
new ClassPathResource("fixtures/202108/scxa_cell_group_marker_gene_stats-delete.sql"),
new ClassPathResource("fixtures/202108/scxa_cell_group_marker_genes-delete.sql"),
new ClassPathResource("fixtures/202108/scxa_cell_group_membership-delete.sql"),
new ClassPathResource("fixtures/202108/scxa_cell_group-delete.sql"),
new ClassPathResource("fixtures/202108/scxa_coords-delete.sql"),
new ClassPathResource("fixtures/202108/scxa_analytics-delete.sql"),
new ClassPathResource("fixtures/202108/experiment-delete.sql"));
populator.execute(dataSource);
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithKProvider")
void fetchCellPlotWithK(String experimentAccession,
int k,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(subject.fetchCellPlotWithK(experimentAccession, k, plotMethod, parameterisation))
.isNotEmpty()
.doesNotHaveDuplicates();
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithKProvider")
void fetchCellPlotWithKWithInvalidExperimentAccessionReturnsEmpty(String experimentAccession,
int k,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(
subject.fetchCellPlotWithK(
generateRandomExperimentAccession(),
k,
plotMethod,
parameterisation))
.isEmpty();
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithKProvider")
void fetchCellPlotWithKWithInvalidPlotMethodReturnsEmpty(String experimentAccession,
int k,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(subject.fetchCellPlotWithK(experimentAccession, k, randomAlphabetic(4), parameterisation))
.isEmpty();
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithKProvider")
void fetchCellPlotWithKWithInvalidParameterisationReturnsEmpty(String experimentAccession,
int k,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(
subject.fetchCellPlotWithK(
experimentAccession,
k,
randomAlphabetic(4),
ImmutableMap.of(randomAlphabetic(10), RNG.nextInt())))
.isEmpty();
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithKProvider")
void throwsIfInvalidKIsRequested(String experimentAccession,
int k,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThatNullPointerException().isThrownBy(
() -> subject.fetchCellPlotWithK(experimentAccession, RNG.nextInt(), plotMethod, parameterisation));
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithKProvider")
void fetchCellPlot(String experimentAccession,
// We can reuse the same provider but we must have a place for the unused parameter
int k,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(subject.fetchCellPlot(experimentAccession, plotMethod, parameterisation))
.isNotEmpty()
.doesNotHaveDuplicates();
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithGeneIdProvider")
void fetchExpressionPlot(String experimentAccession,
// We can reuse the same provider but we must have a place for the unused parameter
String geneId,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(subject.fetchCellPlotWithExpression(experimentAccession, geneId, plotMethod, parameterisation))
.isNotEmpty()
.doesNotHaveDuplicates();
}
@ParameterizedTest
@MethodSource("randomExperimentAccessionPlotWithGeneIdProvider")
void fetchExpressionPlotWithInvalidGeneIdHasNoExpression(String experimentAccession,
String geneId,
String plotMethod,
Map<String, Integer> parameterisation) {
assertThat(
subject.fetchCellPlotWithExpression(
experimentAccession,
generateRandomEnsemblGeneId(),
plotMethod,
parameterisation))
.allSatisfy(dto -> assertThat(dto).hasFieldOrPropertyWithValue("expressionLevel", 0.0));
}
private Stream<Arguments> randomExperimentAccessionPlotWithKProvider() {
var experimentAccession = jdbcTestUtils.fetchRandomExperimentAccession();
var k = 0;
while (k == 0) {
try {
k = Integer.parseInt(jdbcTestUtils.fetchRandomVariableAndValue(experimentAccession).getLeft());
} catch (NumberFormatException e) {
// Keep trying until we have a valid k, remember we could get inferred cell type as variable
}
}
var plotMethod = jdbcTestUtils.fetchRandomPlotMethod(experimentAccession);
var parameterisation = jdbcTestUtils.fetchRandomParameterisation(experimentAccession, plotMethod);
return Stream.of(Arguments.of(experimentAccession, k, plotMethod, parameterisation));
}
private Stream<Arguments> randomExperimentAccessionPlotWithGeneIdProvider() {
var experimentAccession = jdbcTestUtils.fetchRandomExperimentAccession();
var geneId = jdbcTestUtils.fetchRandomGeneFromSingleCellExperiment(experimentAccession);
var plotMethod = jdbcTestUtils.fetchRandomPlotMethod(experimentAccession);
var parameterisation = jdbcTestUtils.fetchRandomParameterisation(experimentAccession, plotMethod);
return Stream.of(Arguments.of(experimentAccession, geneId, plotMethod, parameterisation));
}
}
| 48.020305
| 116
| 0.642495
|
105f6324dafd5b3942f5b38800578b1e38efccbc
| 8,290
|
package com.vaguehope.onosendai.model;
import android.database.Cursor;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.vaguehope.onosendai.R;
import com.vaguehope.onosendai.images.ImageLoadRequest;
import com.vaguehope.onosendai.images.ImageLoader;
import com.vaguehope.onosendai.model.LinkedTweetLoader.TweetLoadRequest;
import com.vaguehope.onosendai.model.TweetRowView.QuotingTweetRowView;
import com.vaguehope.onosendai.storage.TweetCursorReader;
import com.vaguehope.onosendai.widget.ClickToExpand;
import com.vaguehope.onosendai.widget.PendingImage;
public enum TweetLayout {
MAIN(0, R.layout.tweetlistrow) {
@Override
public TweetRowView makeRowView (final View view, final TweetListViewState tweetListViewState) {
return new TweetRowView(
(ImageView) view.findViewById(R.id.imgMain),
(TextView) view.findViewById(R.id.txtTweet),
(TextView) view.findViewById(R.id.txtName)
);
}
@Override
public void applyTweetTo (final Tweet item, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
if (item.isFiltered()) {
rowView.getTweet().setText(R.string.tweet_filtered);
}
else {
rowView.getTweet().setText(item.getBody());
}
final String usernameWithSubtitle = item.getUsernameWithSubtitle();
rowView.getName().setText(usernameWithSubtitle != null ? usernameWithSubtitle : item.getFullnameWithSubtitle());
final String avatarUrl = item.getAvatarUrl();
if (avatarUrl != null) {
imageLoader.loadImage(new ImageLoadRequest(avatarUrl, rowView.getAvatar()));
}
else {
rowView.getAvatar().setImageResource(R.drawable.question_blue);
}
}
@Override
public void applyCursorTo (final Cursor c, final TweetCursorReader cursorReader, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
final String name;
final String username = cursorReader.readUsernameWithSubtitle(c);
if (username != null) {
name = username;
}
else {
name = cursorReader.readFullnameWithSubtitle(c);
}
rowView.getName().setText(name);
if (cursorReader.readFiltered(c)) {
rowView.getTweet().setText(R.string.tweet_filtered);
}
else {
rowView.getTweet().setText(cursorReader.readBody(c));
}
final String avatarUrl = cursorReader.readAvatar(c);
if (avatarUrl != null) {
imageLoader.loadImage(new ImageLoadRequest(avatarUrl, rowView.getAvatar()));
}
else {
rowView.getAvatar().setImageResource(R.drawable.question_blue);
}
}
},
INLINE_MEDIA(1, R.layout.tweetlistinlinemediarow) {
@Override
public TweetRowView makeRowView (final View view, final TweetListViewState tweetListViewState) {
final PendingImage pendingImage = (PendingImage) view.findViewById(R.id.imgMedia);
pendingImage.setExpandedTracker(tweetListViewState.getExpandedImagesTracker());
return new TweetRowView(
(ImageView) view.findViewById(R.id.imgMain),
(TextView) view.findViewById(R.id.txtTweet),
(TextView) view.findViewById(R.id.txtName),
pendingImage
);
}
@Override
public void applyTweetTo (final Tweet item, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
MAIN.applyTweetTo(item, rowView, imageLoader, reqWidth, tweetLoader);
setImage(item.getInlineMediaUrl(), rowView, imageLoader, reqWidth);
}
@Override
public void applyCursorTo (final Cursor c, final TweetCursorReader cursorReader, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
MAIN.applyCursorTo(c, cursorReader, rowView, imageLoader, reqWidth, tweetLoader);
setImage(cursorReader.readInlineMedia(c), rowView, imageLoader, reqWidth);
}
},
QUOTED(2, R.layout.tweetlistquoterow) {
@Override
public TweetRowView makeRowView (final View view, final TweetListViewState tweetListViewState) {
final View t = view.findViewById(R.id.tweet);
final View qt = view.findViewById(R.id.quotedTweet);
final PendingImage pendingImage = (PendingImage) t.findViewById(R.id.imgMedia);
pendingImage.setExpandedTracker(tweetListViewState.getExpandedImagesTracker());
final PendingImage qPendingImage = (PendingImage) qt.findViewById(R.id.imgMedia);
qPendingImage.setExpandedTracker(tweetListViewState.getExpandedImagesTracker());
return new QuotingTweetRowView(
(ImageView) t.findViewById(R.id.imgMain),
(TextView) t.findViewById(R.id.txtTweet),
(TextView) t.findViewById(R.id.txtName),
pendingImage,
(ClickToExpand) view.findViewById(R.id.quotedClickToExpand),
(ImageView) qt.findViewById(R.id.imgMain),
(TextView) qt.findViewById(R.id.txtTweet),
(TextView) qt.findViewById(R.id.txtName),
qPendingImage
);
}
@Override
public void applyTweetTo (final Tweet item, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
MAIN.applyTweetTo(item, rowView, imageLoader, reqWidth, tweetLoader);
final String inlineMediaUrl = item.getInlineMediaUrl();
if (inlineMediaUrl != null) {
setImage(inlineMediaUrl, rowView, imageLoader, reqWidth);
}
else {
rowView.showInlineMedia(false);
}
tweetLoader.loadTweet(new TweetLoadRequest(item.getSid(), item.getQuotedSid(), (QuotingTweetRowView) rowView, imageLoader, reqWidth));
}
@Override
public void applyCursorTo (final Cursor c, final TweetCursorReader cursorReader, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
MAIN.applyCursorTo(c, cursorReader, rowView, imageLoader, reqWidth, tweetLoader);
final String inlineMediaUrl = cursorReader.readInlineMedia(c);
if (inlineMediaUrl != null) {
setImage(inlineMediaUrl, rowView, imageLoader, reqWidth);
}
else {
rowView.showInlineMedia(false);
}
tweetLoader.loadTweet(new TweetLoadRequest(cursorReader.readSid(c), cursorReader.readQuotedSid(c), (QuotingTweetRowView) rowView, imageLoader, reqWidth));
}
},
SEAMLESS_MEDIA(3, R.layout.tweetlistseamlessmediarow) {
@Override
public TweetRowView makeRowView (final View view, final TweetListViewState tweetListViewState) {
final PendingImage pendingImage = (PendingImage) view.findViewById(R.id.imgMedia);
pendingImage.setExpandedTracker(tweetListViewState.getExpandedImagesTracker());
return new TweetRowView(pendingImage);
}
@Override
public void applyTweetTo (final Tweet item, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
setImage(item.getInlineMediaUrl(), rowView, imageLoader, reqWidth);
}
@Override
public void applyCursorTo (final Cursor c, final TweetCursorReader cursorReader, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth, final LinkedTweetLoader tweetLoader) {
setImage(cursorReader.readInlineMedia(c), rowView, imageLoader, reqWidth);
}
};
protected static void setImage (final String inlineMediaUrl, final TweetRowView rowView, final ImageLoader imageLoader, final int reqWidth) {
final ImageView imageView = rowView.getInlineMedia();
rowView.showInlineMedia(true);
if (inlineMediaUrl != null) {
imageLoader.loadImage(new ImageLoadRequest(inlineMediaUrl, imageView, reqWidth, rowView.getInlineMediaLoadListener()));
}
else {
imageView.setImageResource(R.drawable.question_blue);
}
}
private final int index;
private final int layout;
private TweetLayout (final int index, final int layout) {
this.index = index;
this.layout = layout;
}
public int getIndex () {
return this.index;
}
public int getLayout () {
return this.layout;
}
public abstract TweetRowView makeRowView (final View view, final TweetListViewState tweetListViewState);
public abstract void applyTweetTo (Tweet item, TweetRowView rowView, ImageLoader imageLoader, int reqWidth, LinkedTweetLoader tweetLoader);
public abstract void applyCursorTo (Cursor c, TweetCursorReader cursorReader, TweetRowView rowView, ImageLoader imageLoader, int reqWidth, LinkedTweetLoader tweetLoader);
}
| 40.048309
| 200
| 0.768275
|
8404ca34c60ff7c03e1b764b123601bafa66e726
| 2,194
|
package les.pathfiles.j7;
import java.io.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.DosFileAttributes;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Path path = Paths.get("C:\\Users\\ikudryashov.EATMEAT\\IdeaProjects\\Java_Lessons\\Lessons\\temp.txt").toAbsolutePath();
Files.walkFileTree(Paths.get("."),/* new HashSet<FileVisitOption>(), 1,*/ new MyFileVisitor());
}
static class MyFileVisitor extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
System.out.println(file.getFileName());
return FileVisitResult.CONTINUE;
}
}
// https://goo.gl/cXea6T Вывод ВСЕХ файлов
// https://goo.gl/km1Qx1 Можно пробежать по-директории
/*{
Path path= Paths.get("C:\\Users\\ikudryashov.EATMEAT\\IdeaProjects\\Java_Lessons\\Lessons\\temp.txt").toAbsolutePath();
// List<String> list = Files.readAllLines(Paths.get("C:\\Users\\ikudryashov.EATMEAT\\IdeaProjects\\Java_Lessons\\Lessons\\temp.txt"));
// for (String s : list){
// System.out.println(s); }
// List<String> list1 = new ArrayList<String>();
// list1.add("new");
// list1.add("bla");
// Files.write(path, list1);
InputStream inputStream = Files.newInputStream(path);
OutputStream outputStream = Files.newOutputStream(path);
Reader reader = Files.newBufferedReader(path);
Writer writer = Files.newBufferedWriter(path);
}*/
}
// https://goo.gl/SeURbC Можно брать стримы и сохранять их в файлы
// https://goo.gl/eXmgfS Можно записать БЕЗ Writer
// https://goo.gl/fhX97y Чтение файла построчно
// https://goo.gl/7htwkz Запись массива байт
// https://goo.gl/f6mChA Чтение в массив
// https://goo.gl/hNqfJk FileAttributes
// https://goo.gl/ETvhmH Основной функционал Files
// https://goo.gl/Pj26Ks path.get
// https://goo.gl/3i72dd Первая реализация работы с файлами
// at 24.01.2018 (14:49)
| 35.387097
| 139
| 0.67639
|
e869044c16df9036e8fb4d41dba2c2c848068bcf
| 4,543
|
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.genomics.model;
/**
* The read group set export request.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Genomics API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class ExportReadGroupSetRequest extends com.google.api.client.json.GenericJson {
/**
* Required. A Google Cloud Storage URI for the exported BAM file. The currently authenticated
* user must have write access to the new file. An error will be returned if the URI already
* contains data.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String exportUri;
/**
* Required. The Google Cloud project ID that owns this export. The caller must have WRITE access
* to this project.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String projectId;
/**
* The reference names to export. If this is not specified, all reference sequences, including
* unmapped reads, are exported. Use `*` to export only unmapped reads.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.List<java.lang.String> referenceNames;
/**
* Required. A Google Cloud Storage URI for the exported BAM file. The currently authenticated
* user must have write access to the new file. An error will be returned if the URI already
* contains data.
* @return value or {@code null} for none
*/
public java.lang.String getExportUri() {
return exportUri;
}
/**
* Required. A Google Cloud Storage URI for the exported BAM file. The currently authenticated
* user must have write access to the new file. An error will be returned if the URI already
* contains data.
* @param exportUri exportUri or {@code null} for none
*/
public ExportReadGroupSetRequest setExportUri(java.lang.String exportUri) {
this.exportUri = exportUri;
return this;
}
/**
* Required. The Google Cloud project ID that owns this export. The caller must have WRITE access
* to this project.
* @return value or {@code null} for none
*/
public java.lang.String getProjectId() {
return projectId;
}
/**
* Required. The Google Cloud project ID that owns this export. The caller must have WRITE access
* to this project.
* @param projectId projectId or {@code null} for none
*/
public ExportReadGroupSetRequest setProjectId(java.lang.String projectId) {
this.projectId = projectId;
return this;
}
/**
* The reference names to export. If this is not specified, all reference sequences, including
* unmapped reads, are exported. Use `*` to export only unmapped reads.
* @return value or {@code null} for none
*/
public java.util.List<java.lang.String> getReferenceNames() {
return referenceNames;
}
/**
* The reference names to export. If this is not specified, all reference sequences, including
* unmapped reads, are exported. Use `*` to export only unmapped reads.
* @param referenceNames referenceNames or {@code null} for none
*/
public ExportReadGroupSetRequest setReferenceNames(java.util.List<java.lang.String> referenceNames) {
this.referenceNames = referenceNames;
return this;
}
@Override
public ExportReadGroupSetRequest set(String fieldName, Object value) {
return (ExportReadGroupSetRequest) super.set(fieldName, value);
}
@Override
public ExportReadGroupSetRequest clone() {
return (ExportReadGroupSetRequest) super.clone();
}
}
| 35.771654
| 182
| 0.720009
|
9f675c071460ef41b42fe2b34731fcb5aee0b714
| 544
|
package P10_Tuple;
public class Tuple<T, E> {
private T item1;
private E item2;
public Tuple(T item1, E item2) {
this.item1 = item1;
this.item2 = item2;
}
public T getItem1() {
return item1;
}
public void setItem1(T item1) {
this.item1 = item1;
}
public E getItem2() {
return item2;
}
public void setItem2(E item2) {
this.item2 = item2;
}
@Override
public String toString() {
return this.item1 + " -> " + this.item2;
}
}
| 16.484848
| 48
| 0.534926
|
ac9f33aa715a573ca2c3dccbe2e467f4cf598716
| 1,834
|
//| Copyright - The University of Edinburgh 2017 |
//| |
//| 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 uk.ac.ed.epcc.webapp.tags;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.Tag;
import javax.servlet.jsp.tagext.TagSupport;
/** Tag to mark page as containing a form that may requie additional
* JS support
* @author spb
*
*/
public class WebappFormPage extends TagSupport implements Tag {
/**
*
*/
public WebappFormPage() {
}
/* (non-Javadoc)
* @see javax.servlet.jsp.tagext.TagSupport#doStartTag()
*/
@Override
public int doStartTag() throws JspException {
PageContext page = pageContext;
HttpServletRequest request = (HttpServletRequest) page.getRequest();
WebappHeadTag.markAsFormPage(request);
return EVAL_PAGE;
}
}
| 37.428571
| 78
| 0.561069
|
b575994f64adee2ea83fb06016ef427fdc9edf73
| 1,593
|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.ballerina.core.runtime.dispatching.uri;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
/**
* Query parameter related operations.
*/
public class QueryParamProcessor {
public static final String ENCODING = "UTF-8";
public static Map<String, String> processQueryParams(String queryStr) throws UnsupportedEncodingException {
Map<String, String> queryParams = new HashMap<>();
String[] entries = queryStr.split("&");
for (String entry : entries) {
int index = entry.indexOf('=');
if (index != -1) {
String name = entry.substring(0, index);
String value = URLDecoder.decode(entry.substring(index + 1),
ENCODING);
queryParams.put(name, value);
}
}
return queryParams;
}
}
| 33.1875
| 111
| 0.666667
|
c88b89d0c428a5407f9f93a1bc9cecfe151f2b47
| 428
|
package structural.flyweight;
public final class Bullet {
private final String bulletSize;
private final String bulletWeight;
public Bullet(String bulletSize, String bulletWeight) {
this.bulletSize = bulletSize;
this.bulletWeight = bulletWeight;
}
public String getBulletSize() {
return bulletSize;
}
public String getBulletWeight() {
return bulletWeight;
}
}
| 21.4
| 59
| 0.67757
|
a5b88341762cfae2fcf8e26e6ae928f35b890b8b
| 8,749
|
package jp.nayutaya.geodelta;
import static jp.nayutaya.geodelta.Assert.assertArrayArrayEquals;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import java.util.Random;
import org.junit.Test;
public class GeoDeltaTest
{
@Test
public void getDeltaIds()
{
assertArrayEquals(new byte[] {0}, GeoDelta.getDeltaIds(+45.0, +0.0, 1));
assertArrayEquals(new byte[] {1}, GeoDelta.getDeltaIds(+45.0, +90.0, 1));
assertArrayEquals(new byte[] {2}, GeoDelta.getDeltaIds(+45.0, +180.0, 1));
assertArrayEquals(new byte[] {3}, GeoDelta.getDeltaIds(+45.0, -90.0, 1));
assertArrayEquals(new byte[] {2}, GeoDelta.getDeltaIds(+45.0, -180.0, 1));
assertArrayEquals(new byte[] {4}, GeoDelta.getDeltaIds(-45.0, +0.0, 1));
assertArrayEquals(new byte[] {5}, GeoDelta.getDeltaIds(-45.0, +90.0, 1));
assertArrayEquals(new byte[] {6}, GeoDelta.getDeltaIds(-45.0, +180.0, 1));
assertArrayEquals(new byte[] {7}, GeoDelta.getDeltaIds(-45.0, -90.0, 1));
assertArrayEquals(new byte[] {6}, GeoDelta.getDeltaIds(-45.0, -180.0, 1));
assertArrayEquals(new byte[] {0}, GeoDelta.getDeltaIds(+0.0, +0.0, 1));
assertArrayEquals(new byte[] {0, 1}, GeoDelta.getDeltaIds(+0.0, +0.0, 2));
assertArrayEquals(new byte[] {0, 1, 1}, GeoDelta.getDeltaIds(+0.0, +0.0, 3));
assertArrayEquals(new byte[] {0, 1, 1, 1}, GeoDelta.getDeltaIds(+0.0, +0.0, 4));
}
@Test
public void getDeltaCode()
{
assertEquals("Z", GeoDelta.getDeltaCode(+45.0, +0.0, 1));
assertEquals("Y", GeoDelta.getDeltaCode(+45.0, +90.0, 1));
assertEquals("X", GeoDelta.getDeltaCode(+45.0, +180.0, 1));
assertEquals("W", GeoDelta.getDeltaCode(+45.0, -90.0, 1));
assertEquals("X", GeoDelta.getDeltaCode(+45.0, -180.0, 1));
assertEquals("V", GeoDelta.getDeltaCode(-45.0, +0.0, 1));
assertEquals("T", GeoDelta.getDeltaCode(-45.0, +90.0, 1));
assertEquals("S", GeoDelta.getDeltaCode(-45.0, +180.0, 1));
assertEquals("R", GeoDelta.getDeltaCode(-45.0, -90.0, 1));
assertEquals("S", GeoDelta.getDeltaCode(-45.0, -180.0, 1));
assertEquals("Z", GeoDelta.getDeltaCode(+0.0, +0.0, 1));
assertEquals("ZM", GeoDelta.getDeltaCode(+0.0, +0.0, 2));
assertEquals("Z7", GeoDelta.getDeltaCode(+0.0, +0.0, 3));
assertEquals("Z7M", GeoDelta.getDeltaCode(+0.0, +0.0, 4));
}
@Test
public void getCenter_ids()
{
assertArrayEquals(new double[] {+71.480, +0.000}, GeoDelta.getCenter(new byte[] {0}), 1E-3);
assertArrayEquals(new double[] {+46.024, +90.000}, GeoDelta.getCenter(new byte[] {1}), 1E-3);
assertArrayEquals(new double[] {+71.480, -180.000}, GeoDelta.getCenter(new byte[] {2}), 1E-3);
assertArrayEquals(new double[] {+46.024, -90.000}, GeoDelta.getCenter(new byte[] {3}), 1E-3);
assertArrayEquals(new double[] {-71.480, +0.000}, GeoDelta.getCenter(new byte[] {4}), 1E-3);
assertArrayEquals(new double[] {-46.024, +90.000}, GeoDelta.getCenter(new byte[] {5}), 1E-3);
assertArrayEquals(new double[] {-71.480, -180.000}, GeoDelta.getCenter(new byte[] {6}), 1E-3);
assertArrayEquals(new double[] {-46.024, -90.000}, GeoDelta.getCenter(new byte[] {7}), 1E-3);
assertArrayEquals(new double[] {+71.480, +0.000}, GeoDelta.getCenter(new byte[] {0, 0}), 1E-3);
assertArrayEquals(new double[] {+71.480, +0.000}, GeoDelta.getCenter(new byte[] {0, 0, 0}), 1E-3);
}
@Test
public void getCenter_code()
{
assertArrayEquals(new double[] {+71.480, +0.000}, GeoDelta.getCenter("Z"), 1E-3);
assertArrayEquals(new double[] {+46.024, +90.000}, GeoDelta.getCenter("Y"), 1E-3);
assertArrayEquals(new double[] {+71.480, -180.000}, GeoDelta.getCenter("X"), 1E-3);
assertArrayEquals(new double[] {+46.024, -90.000}, GeoDelta.getCenter("W"), 1E-3);
assertArrayEquals(new double[] {-71.480, +0.000}, GeoDelta.getCenter("V"), 1E-3);
assertArrayEquals(new double[] {-46.024, +90.000}, GeoDelta.getCenter("T"), 1E-3);
assertArrayEquals(new double[] {-71.480, -180.000}, GeoDelta.getCenter("S"), 1E-3);
assertArrayEquals(new double[] {-46.024, -90.000}, GeoDelta.getCenter("R"), 1E-3);
assertArrayEquals(new double[] {+71.480, +0.000}, GeoDelta.getCenter("ZK"), 1E-3);
assertArrayEquals(new double[] {+71.480, +0.000}, GeoDelta.getCenter("Z2"), 1E-3);
}
@Test
public void getCoordinates_ids1()
{
{
// @formatter:off
final double[][] expecteds = {
{+71.480, +0.000},
{ +0.000, +0.000},
{+82.467, -90.000},
{+82.467, +90.000},
};
// @formatter:on
assertArrayArrayEquals(expecteds, GeoDelta.getCoordinates(new byte[] {0}), 1E-3);
}
{
// @formatter:off
final double[][] expecteds = {
{-71.480, +0.000},
{ +0.000, +0.000},
{-82.467, +90.000},
{-82.467, -90.000},
};
// @formatter:on
assertArrayArrayEquals(expecteds, GeoDelta.getCoordinates(new byte[] {4}), 1E-3);
}
}
@Test
public void getCoordinates_ids2()
{
final double[][][] delta = new double[8][][];
for ( int id = 0; id < 8; id++ )
{
delta[id] = GeoDelta.getCoordinates(new byte[] {(byte)id});
}
assertArrayEquals(delta[0][1], delta[1][3], 1E-15);
assertArrayEquals(delta[0][1], delta[3][2], 1E-15);
assertArrayEquals(delta[0][1], delta[4][1], 1E-15);
assertArrayEquals(delta[0][1], delta[5][2], 1E-15);
assertArrayEquals(delta[0][1], delta[7][3], 1E-15);
assertArrayEquals(delta[0][2], delta[2][3], 1E-15);
assertArrayEquals(delta[0][2], delta[3][1], 1E-15);
assertArrayEquals(delta[0][3], delta[1][1], 1E-15);
assertArrayEquals(delta[0][3], delta[2][2], 1E-15);
assertArrayEquals(delta[1][2], delta[2][1], 1E-15);
assertArrayEquals(delta[1][2], delta[3][3], 1E-15);
assertArrayEquals(delta[1][2], delta[5][3], 1E-15);
assertArrayEquals(delta[1][2], delta[6][1], 1E-15);
assertArrayEquals(delta[1][2], delta[7][2], 1E-15);
assertArrayEquals(delta[4][3], delta[6][2], 1E-15);
assertArrayEquals(delta[4][3], delta[7][1], 1E-15);
assertArrayEquals(delta[4][2], delta[5][1], 1E-15);
assertArrayEquals(delta[4][2], delta[6][3], 1E-15);
}
@Test
public void getCoordinates_ids3()
{
final double[][][] delta = new double[4][][];
for ( int id = 0; id < 4; id++ )
{
delta[id] = GeoDelta.getCoordinates(new byte[] {0, (byte)id});
}
assertArrayEquals(delta[0][1], delta[2][3], 1E-15);
assertArrayEquals(delta[0][1], delta[3][2], 1E-15);
assertArrayEquals(delta[0][2], delta[1][3], 1E-15);
assertArrayEquals(delta[0][2], delta[3][1], 1E-15);
assertArrayEquals(delta[0][3], delta[1][2], 1E-15);
assertArrayEquals(delta[0][3], delta[2][1], 1E-15);
}
@Test
public void getCoordinates_code()
{
{
final double[][] expecteds = GeoDelta.getCoordinates(new byte[] {0});
assertArrayArrayEquals(expecteds, GeoDelta.getCoordinates("Z"), 1E-15);
}
{
final double[][] expecteds = GeoDelta.getCoordinates(new byte[] {0, 1, 2});
assertArrayArrayEquals(expecteds, GeoDelta.getCoordinates("Z8"), 1E-15);
}
}
@Test
public void randomGetDeltaCodeAndGetCenter()
{
final double latMax = Projector.nyToLat(+12.0);
final double lngMax = 180.0;
final Random r = new Random();
for ( int i = 0; i < 1000; i++ )
{
final double lat1 = r.nextDouble() * latMax * 2 - latMax;
final double lng1 = r.nextDouble() * lngMax * 2 - lngMax;
final int level = r.nextInt(30) + 1;
final String code1 = GeoDelta.getDeltaCode(lat1, lng1, level);
final double[] latlng2 = GeoDelta.getCenter(code1);
final String code2 = GeoDelta.getDeltaCode(latlng2[0], latlng2[1], level);
final double[] latlng3 = GeoDelta.getCenter(code2);
assertEquals(code1, code2);
assertArrayEquals(latlng2, latlng3, 1E-15);
}
}
}
| 45.806283
| 107
| 0.564522
|
77e92f9ca7689e631ac206a6b7b5b420fc5a525f
| 676
|
//package com.carty.code;
//
//import org.springframework.stereotype.Component;
//import org.springframework.web.context.request.ServletWebRequest;
//
//import com.carty.security.core.validate.code.ImageCode;
//import com.carty.security.core.validate.code.ValidateCodeGenerator;
//
///**
// * 更高级的图形验证码实现,覆盖了core中默认的图形验证码生成器
// * @author Administrator
// *
// */
//@Component("imageCodeGenerator")
//public class DemoImageCodeGenerator implements ValidateCodeGenerator {
//
// @Override
// public ImageCode generate(ServletWebRequest request) {
// // TODO Auto-generated method stub
// System.out.println("更高级的图形验证码实现");
// return null;
// }
//
//}
| 27.04
| 73
| 0.717456
|
8a8449f5a6a6335c658c3e95dd2f6f1a5eccce79
| 290
|
package com.txt.video.base;
/**
* Created by JustinWjq
* @date 2019-12-23.
* description:
*/
public interface IBaseView {
/**
* 加载中
*/
void onLoading();
/**
* 加载错误回调
*/
void onLoadFailed();
/**
* 加载完成
*/
void onLoadSuccess();
}
| 11.6
| 28
| 0.503448
|
660430f0b28242170217f5de35dbc67e96da1276
| 2,951
|
package org.horx.wdf.sys.service;
import org.horx.wdf.common.entity.PaginationQuery;
import org.horx.wdf.common.entity.PaginationResult;
import org.horx.wdf.sys.dto.DictDTO;
import org.horx.wdf.sys.dto.DictItemDTO;
import org.horx.wdf.sys.dto.dataauth.DictDataAuthDTO;
import org.horx.wdf.sys.dto.dataauth.DictItemAuthDTO;
import org.horx.wdf.sys.dto.query.DictItemQueryDTO;
import org.horx.wdf.sys.dto.query.DictQueryDTO;
import org.horx.wdf.sys.dto.wrapper.BatchWithDictAuthDTO;
import org.horx.wdf.sys.dto.wrapper.DictWithAuthDTO;
import org.horx.wdf.sys.springcloud.SpringcloudConsumerContextInterceptor;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
/**
* 字典Service。
* 用于SpringCloud Feign Client。
* @since 1.0
*/
@RequestMapping("/sys/dict")
@Component
@FeignClient(value = "horx-wdf-springcloud-provider", configuration = SpringcloudConsumerContextInterceptor.class)
public interface DictService {
@GetMapping("/getById")
DictDTO getById(@RequestParam Long id);
@PostMapping("/getByIdAuthorized")
DictDTO getByIdAuthorized(@RequestParam Long id, @RequestBody DictDataAuthDTO dictDataAuth);
@GetMapping("/getByCode")
DictDTO getByCode(@RequestParam String code);
@PostMapping("/paginationQuery")
PaginationResult<DictDTO> paginationQuery(@RequestBody PaginationQuery<DictQueryDTO> paginationQuery);
@PostMapping("/create")
Long create(@RequestBody DictWithAuthDTO dictWithAuthDTO);
@PostMapping("/modify")
void modify(@RequestBody DictWithAuthDTO dictWithAuthDTO);
@PostMapping("/remove")
void remove(@RequestBody BatchWithDictAuthDTO batchWithDictAuthDTO);
@GetMapping("/getItemById")
DictItemDTO getItemById(@RequestParam Long id);
@PostMapping("/paginationQueryItem")
PaginationResult<DictItemDTO> paginationQueryItem(@RequestBody PaginationQuery<DictItemQueryDTO> paginationQuery);
@PostMapping("/createItem")
Long createItem(@RequestBody DictItemDTO dictItem);
@PostMapping("/modifyItem")
void modifyItem(@RequestBody DictItemDTO dictItem);
@PostMapping("/removeItem")
void removeItem(@RequestParam Long[] ids);
@GetMapping("/queryEnabledItemList")
List<DictItemDTO> queryEnabledItemList(@RequestParam String dictCode);
@GetMapping("/queryEnabledItemListByDictId")
List<DictItemDTO> queryEnabledItemListByDictId(@RequestParam Long dictId);
@PostMapping("/queryEnabledItemListAuthorized")
List<DictItemDTO> queryEnabledItemListAuthorized(@RequestParam String dictCode, @RequestBody DictItemAuthDTO dictItemAuth);
}
| 37.35443
| 127
| 0.79329
|
6ff237250a35d403124c10337c0870b375fb08ae
| 4,699
|
package com.dmsvo.offlinealchemy.classes.views;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.dmsvo.offlinealchemy.R;
import com.dmsvo.offlinealchemy.classes.base.Article;
import com.dmsvo.offlinealchemy.classes.base.Comment;
import com.dmsvo.offlinealchemy.classes.base.CompleteArticle;
import com.dmsvo.offlinealchemy.classes.db.Converters;
import java.util.List;
/**
* Created by DmSVo on 08.01.2018.
*/
public class ArticleAdapter extends BaseAdapter {
Activity context;
List<CompleteArticle> data;
private static LayoutInflater inflater = null;
private int currentSelection = -1;
public ArticleAdapter(Activity context, List<CompleteArticle> articles)
{
this.context = context;
this.data = articles;
inflater = (LayoutInflater) context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
public void setItems(List<CompleteArticle> newData) {
data = newData;
notifyDataSetChanged();
}
public void addItems(List<CompleteArticle> additional)
{
data.addAll(additional);
notifyDataSetChanged();
}
public interface OnSelectionChangedListener {
void OnSelectionChanged();
}
private OnSelectionChangedListener onSelectionChangedListener;
public void setOnSelectionChangedListener(OnSelectionChangedListener listener) {
onSelectionChangedListener = listener;
}
protected void onSelectionChanged() {
if (onSelectionChangedListener != null) {
onSelectionChangedListener.OnSelectionChanged();
}
}
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public void setItem(int i, CompleteArticle cart)
{
data.set(i,cart);
notifyDataSetChanged();
}
public int getSelection() { return currentSelection; }
public void setSelection(int pos) {
currentSelection = pos;
notifyDataSetChanged();
onSelectionChanged();
}
@Override
public View getView(int position, View view, ViewGroup viewGroup) {
View vi = view;
if (vi == null)
vi = inflater.inflate(R.layout.article_view, null);
if (position == currentSelection) {
vi.setBackgroundResource(R.color.accentedDark);
} else {
vi.setBackgroundResource(R.color.transparent);
}
CompleteArticle cart = data.get(position);
Article article = cart.article;
TextView header = (TextView) vi.findViewById(R.id.header);
header.setText(article.getName());
boolean wasRead = article.getWasRead() == 1;
boolean loaded = article.getLoaded() == 1;
if (!wasRead && !loaded) {
header.setTypeface(null, Typeface.BOLD_ITALIC);
} else if (!wasRead) {
header.setTypeface(null, Typeface.BOLD);
} else if (!loaded) {
header.setTypeface(null, Typeface.ITALIC);
} else {
header.setTypeface(null, Typeface.NORMAL);
}
boolean fav = article.getFavorite() == 1;
if (fav) {
header.setBackgroundColor(context.getResources().getColor(R.color.accentedDark));
} else {
header.setBackgroundColor(context.getResources().getColor(R.color.transparent));
}
TextView date = (TextView) vi.findViewById(R.id.article_date);
date.setText(article.getDate().toString());
TextView commentsView = (TextView) vi.findViewById(R.id.article_comments);
if (cart.comments != null) {
commentsView.setText("Комментариев: " + cart.comments.size());
} else {
commentsView.setText("Комментариев ~ " + cart.article.getCommentCount());
}
// TODO: сделать в виде списка кнопок?
TextView tagsView = vi.findViewById(R.id.article_tags);
List<String> tags = cart.article.getTags();
String combined = "";
for (String tag : tags)
{
combined += tag + " ";
}
if (!combined.equals("")) {
tagsView.setText(combined);
} else {
tagsView.setVisibility(View.GONE);
}
return vi;
}
}
| 29.553459
| 93
| 0.644818
|
49c32b19b4e45c2a68f8a4b3d9bb281e3ebf9abb
| 1,846
|
package com.cjburkey.mc2d.chunk;
import org.joml.Vector2i;
import org.joml.Vector3f;
import com.cjburkey.mc2d.block.ABlock;
import com.cjburkey.mc2d.block.BlockState;
import com.cjburkey.mc2d.world.World;
public final class ChunkData {
public static final float scale = 5.0f;
public static final int chunkSize = 16;
public static final float scaleAndSize = scale * chunkSize;
public static final float chunkZ = -0.05f;
private BlockState[][] blocks;
private final Vector2i chunkPos;
public ChunkData(int cx, int cy) {
blocks = new BlockState[chunkSize][chunkSize];
chunkPos = new Vector2i(cx, cy);
}
public void setBlock(int x, int y, ABlock block) {
if(inChunk(x, y)) {
if(block == null) {
blocks[x][y] = null;
} else {
blocks[x][y] = new BlockState(this, block, getWorldCoordsForBlock(x, y));
}
}
}
public void refresh(World world) {
world.reRenderChunk(chunkPos.x, chunkPos.y);
}
public void removeBlock(int x, int y) {
setBlock(x, y, null);
}
public boolean inChunk(int x, int y) {
return ((x >= 0) && (x < chunkSize) && (y >= 0) && (y < chunkSize));
}
public BlockState getBlockState(int x, int y) {
if(inChunk(x, y)) {
return blocks[x][y];
}
return null;
}
public ABlock getBlock(int x, int y) {
BlockState at = getBlockState(x, y);
if(at != null) {
return at.getBlock();
}
return null;
}
public Vector2i getChunkCoords() {
return new Vector2i(chunkPos);
}
public Vector3f getWorldCoords() {
return new Vector3f(chunkPos.x * scaleAndSize, chunkPos.y * scaleAndSize, chunkZ);
}
public Vector2i getChunkWorldCoords() {
return new Vector2i(chunkPos.x * chunkSize, chunkPos.y * chunkSize);
}
public Vector2i getWorldCoordsForBlock(int x, int y) {
return new Vector2i(chunkPos.x * chunkSize + x, chunkPos.y * chunkSize + y);
}
}
| 23.974026
| 84
| 0.679848
|
1a9d13c7d803f3479967c2a0058f9b60f3e567e6
| 18,761
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.base;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import android.os.Bundle;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import org.chromium.base.annotations.MainDex;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Provides information about the current activity's status, and a way
* to register / unregister listeners for state changes.
*/
@JNINamespace("base::android")
@MainDex
public class ApplicationStatus {
private static class ActivityInfo {
private int mStatus = ActivityState.DESTROYED;
private ObserverList<ActivityStateListener> mListeners = new ObserverList<>();
/**
* @return The current {@link ActivityState} of the activity.
*/
@ActivityState
public int getStatus() {
return mStatus;
}
/**
* @param status The new {@link ActivityState} of the activity.
*/
public void setStatus(@ActivityState int status) {
mStatus = status;
}
/**
* @return A list of {@link ActivityStateListener}s listening to this activity.
*/
public ObserverList<ActivityStateListener> getListeners() {
return mListeners;
}
}
private static final Object sCachedApplicationStateLock = new Object();
@ApplicationState
private static Integer sCachedApplicationState;
/** Last activity that was shown (or null if none or it was destroyed). */
@SuppressLint("StaticFieldLeak")
private static Activity sActivity;
/** A lazily initialized listener that forwards application state changes to native. */
private static ApplicationStateListener sNativeApplicationStateListener;
/**
* A map of which observers listen to state changes from which {@link Activity}.
*/
private static final Map<Activity, ActivityInfo> sActivityInfo = new ConcurrentHashMap<>();
/**
* A list of observers to be notified when any {@link Activity} has a state change.
*/
private static final ObserverList<ActivityStateListener> sGeneralActivityStateListeners =
new ObserverList<>();
/**
* A list of observers to be notified when the visibility state of this {@link Application}
* changes. See {@link #getStateForApplication()}.
*/
private static final ObserverList<ApplicationStateListener> sApplicationStateListeners =
new ObserverList<>();
/**
* Interface to be implemented by listeners.
*/
public interface ApplicationStateListener {
/**
* Called when the application's state changes.
* @param newState The application state.
*/
void onApplicationStateChange(@ApplicationState int newState);
}
/**
* Interface to be implemented by listeners.
*/
public interface ActivityStateListener {
/**
* Called when the activity's state changes.
* @param activity The activity that had a state change.
* @param newState New activity state.
*/
void onActivityStateChange(Activity activity, @ActivityState int newState);
}
private ApplicationStatus() {}
/**
* Initializes the activity status for a specified application.
*
* @param application The application whose status you wish to monitor.
*/
public static void initialize(BaseChromiumApplication application) {
application.registerWindowFocusChangedListener(
new BaseChromiumApplication.WindowFocusChangedListener() {
@Override
public void onWindowFocusChanged(Activity activity, boolean hasFocus) {
if (!hasFocus || activity == sActivity) return;
int state = getStateForActivity(activity);
if (state != ActivityState.DESTROYED && state != ActivityState.STOPPED) {
sActivity = activity;
}
// TODO(dtrainor): Notify of active activity change?
}
});
application.registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(final Activity activity, Bundle savedInstanceState) {
onStateChange(activity, ActivityState.CREATED);
}
@Override
public void onActivityDestroyed(Activity activity) {
onStateChange(activity, ActivityState.DESTROYED);
}
@Override
public void onActivityPaused(Activity activity) {
onStateChange(activity, ActivityState.PAUSED);
}
@Override
public void onActivityResumed(Activity activity) {
onStateChange(activity, ActivityState.RESUMED);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}
@Override
public void onActivityStarted(Activity activity) {
onStateChange(activity, ActivityState.STARTED);
}
@Override
public void onActivityStopped(Activity activity) {
onStateChange(activity, ActivityState.STOPPED);
}
});
}
/**
* Must be called by the main activity when it changes state.
*
* @param activity Current activity.
* @param newState New state value.
*/
private static void onStateChange(Activity activity, @ActivityState int newState) {
if (activity == null) throw new IllegalArgumentException("null activity is not supported");
if (sActivity == null
|| newState == ActivityState.CREATED
|| newState == ActivityState.RESUMED
|| newState == ActivityState.STARTED) {
sActivity = activity;
}
int oldApplicationState = getStateForApplication();
if (newState == ActivityState.CREATED) {
// TODO(tedchoc): crbug/691100. The timing of application callback lifecycles were
// changed in O and the activity info may have been lazily created
// on first access to avoid a crash on startup. This should be removed
// once the new lifecycle APIs are available.
if (!BuildInfo.isAtLeastO()) {
assert !sActivityInfo.containsKey(activity);
}
sActivityInfo.put(activity, new ActivityInfo());
}
// Invalidate the cached application state.
synchronized (sCachedApplicationStateLock) {
sCachedApplicationState = null;
}
ActivityInfo info = sActivityInfo.get(activity);
info.setStatus(newState);
// Remove before calling listeners so that isEveryActivityDestroyed() returns false when
// this was the last activity.
if (newState == ActivityState.DESTROYED) {
sActivityInfo.remove(activity);
if (activity == sActivity) sActivity = null;
}
// Notify all state observers that are specifically listening to this activity.
for (ActivityStateListener listener : info.getListeners()) {
listener.onActivityStateChange(activity, newState);
}
// Notify all state observers that are listening globally for all activity state
// changes.
for (ActivityStateListener listener : sGeneralActivityStateListeners) {
listener.onActivityStateChange(activity, newState);
}
int applicationState = getStateForApplication();
if (applicationState != oldApplicationState) {
for (ApplicationStateListener listener : sApplicationStateListeners) {
listener.onApplicationStateChange(applicationState);
}
}
}
/**
* Testing method to update the state of the specified activity.
*/
@VisibleForTesting
public static void onStateChangeForTesting(Activity activity, int newState) {
onStateChange(activity, newState);
}
/**
* @return The most recent focused {@link Activity} tracked by this class. Being focused means
* out of all the activities tracked here, it has most recently gained window focus.
*/
public static Activity getLastTrackedFocusedActivity() {
return sActivity;
}
/**
* @return A {@link List} of all non-destroyed {@link Activity}s.
*/
public static List<WeakReference<Activity>> getRunningActivities() {
List<WeakReference<Activity>> activities = new ArrayList<>();
for (Activity activity : sActivityInfo.keySet()) {
activities.add(new WeakReference<>(activity));
}
return activities;
}
/**
* Query the state for a given activity. If the activity is not being tracked, this will
* return {@link ActivityState#DESTROYED}.
*
* <p>
* Please note that Chrome can have multiple activities running simultaneously. Please also
* look at {@link #getStateForApplication()} for more details.
*
* <p>
* When relying on this method, be familiar with the expected life cycle state
* transitions:
* <a href="http://developer.android.com/guide/components/activities.html#Lifecycle">
* Activity Lifecycle
* </a>
*
* <p>
* During activity transitions (activity B launching in front of activity A), A will completely
* paused before the creation of activity B begins.
*
* <p>
* A basic flow for activity A starting, followed by activity B being opened and then closed:
* <ul>
* <li> -- Starting Activity A --
* <li> Activity A - ActivityState.CREATED
* <li> Activity A - ActivityState.STARTED
* <li> Activity A - ActivityState.RESUMED
* <li> -- Starting Activity B --
* <li> Activity A - ActivityState.PAUSED
* <li> Activity B - ActivityState.CREATED
* <li> Activity B - ActivityState.STARTED
* <li> Activity B - ActivityState.RESUMED
* <li> Activity A - ActivityState.STOPPED
* <li> -- Closing Activity B, Activity A regaining focus --
* <li> Activity B - ActivityState.PAUSED
* <li> Activity A - ActivityState.STARTED
* <li> Activity A - ActivityState.RESUMED
* <li> Activity B - ActivityState.STOPPED
* <li> Activity B - ActivityState.DESTROYED
* </ul>
*
* @param activity The activity whose state is to be returned.
* @return The state of the specified activity (see {@link ActivityState}).
*/
@ActivityState
public static int getStateForActivity(Activity activity) {
ActivityInfo info = sActivityInfo.get(activity);
return info != null ? info.getStatus() : ActivityState.DESTROYED;
}
/**
* @return The state of the application (see {@link ApplicationState}).
*/
@ApplicationState
@CalledByNative
public static int getStateForApplication() {
synchronized (sCachedApplicationStateLock) {
if (sCachedApplicationState == null) {
sCachedApplicationState = determineApplicationState();
}
return sCachedApplicationState;
}
}
/**
* Checks whether or not any Activity in this Application is visible to the user. Note that
* this includes the PAUSED state, which can happen when the Activity is temporarily covered
* by another Activity's Fragment (e.g.).
* @return Whether any Activity under this Application is visible.
*/
public static boolean hasVisibleActivities() {
int state = getStateForApplication();
return state == ApplicationState.HAS_RUNNING_ACTIVITIES
|| state == ApplicationState.HAS_PAUSED_ACTIVITIES;
}
/**
* Checks to see if there are any active Activity instances being watched by ApplicationStatus.
* @return True if all Activities have been destroyed.
*/
public static boolean isEveryActivityDestroyed() {
return sActivityInfo.isEmpty();
}
/**
* Registers the given listener to receive state changes for all activities.
* @param listener Listener to receive state changes.
*/
public static void registerStateListenerForAllActivities(ActivityStateListener listener) {
sGeneralActivityStateListeners.addObserver(listener);
}
/**
* Registers the given listener to receive state changes for {@code activity}. After a call to
* {@link ActivityStateListener#onActivityStateChange(Activity, int)} with
* {@link ActivityState#DESTROYED} all listeners associated with that particular
* {@link Activity} are removed.
* @param listener Listener to receive state changes.
* @param activity Activity to track or {@code null} to track all activities.
*/
@SuppressLint("NewApi")
public static void registerStateListenerForActivity(ActivityStateListener listener,
Activity activity) {
assert activity != null;
ActivityInfo info = sActivityInfo.get(activity);
// TODO(tedchoc): crbug/691100. The timing of application callback lifecycles were changed
// in O and the activity info may need to be lazily created if the onCreate
// event has not yet been received.
if (BuildInfo.isAtLeastO() && info == null && !activity.isDestroyed()) {
info = new ActivityInfo();
sActivityInfo.put(activity, info);
}
assert info != null && info.getStatus() != ActivityState.DESTROYED;
info.getListeners().addObserver(listener);
}
/**
* Unregisters the given listener from receiving activity state changes.
* @param listener Listener that doesn't want to receive state changes.
*/
public static void unregisterActivityStateListener(ActivityStateListener listener) {
sGeneralActivityStateListeners.removeObserver(listener);
// Loop through all observer lists for all activities and remove the listener.
for (ActivityInfo info : sActivityInfo.values()) {
info.getListeners().removeObserver(listener);
}
}
/**
* Registers the given listener to receive state changes for the application.
* @param listener Listener to receive state state changes.
*/
public static void registerApplicationStateListener(ApplicationStateListener listener) {
sApplicationStateListeners.addObserver(listener);
}
/**
* Unregisters the given listener from receiving state changes.
* @param listener Listener that doesn't want to receive state changes.
*/
public static void unregisterApplicationStateListener(ApplicationStateListener listener) {
sApplicationStateListeners.removeObserver(listener);
}
/**
* Robolectric JUnit tests create a new application between each test, while all the context
* in static classes isn't reset. This function allows to reset the application status to avoid
* being in a dirty state.
*/
public static void destroyForJUnitTests() {
sApplicationStateListeners.clear();
sGeneralActivityStateListeners.clear();
sActivityInfo.clear();
synchronized (sCachedApplicationStateLock) {
sCachedApplicationState = null;
}
sActivity = null;
sNativeApplicationStateListener = null;
}
/**
* Registers the single thread-safe native activity status listener.
* This handles the case where the caller is not on the main thread.
* Note that this is used by a leaky singleton object from the native
* side, hence lifecycle management is greatly simplified.
*/
@CalledByNative
private static void registerThreadSafeNativeApplicationStateListener() {
ThreadUtils.runOnUiThread(new Runnable() {
@Override
public void run() {
if (sNativeApplicationStateListener != null) return;
sNativeApplicationStateListener = new ApplicationStateListener() {
@Override
public void onApplicationStateChange(int newState) {
nativeOnApplicationStateChange(newState);
}
};
registerApplicationStateListener(sNativeApplicationStateListener);
}
});
}
/**
* Determines the current application state as defined by {@link ApplicationState}. This will
* loop over all the activities and check their state to determine what the general application
* state should be.
* @return HAS_RUNNING_ACTIVITIES if any activity is not paused, stopped, or destroyed.
* HAS_PAUSED_ACTIVITIES if none are running and one is paused.
* HAS_STOPPED_ACTIVITIES if none are running/paused and one is stopped.
* HAS_DESTROYED_ACTIVITIES if none are running/paused/stopped.
*/
@ApplicationState
private static int determineApplicationState() {
boolean hasPausedActivity = false;
boolean hasStoppedActivity = false;
for (ActivityInfo info : sActivityInfo.values()) {
int state = info.getStatus();
if (state != ActivityState.PAUSED
&& state != ActivityState.STOPPED
&& state != ActivityState.DESTROYED) {
return ApplicationState.HAS_RUNNING_ACTIVITIES;
} else if (state == ActivityState.PAUSED) {
hasPausedActivity = true;
} else if (state == ActivityState.STOPPED) {
hasStoppedActivity = true;
}
}
if (hasPausedActivity) return ApplicationState.HAS_PAUSED_ACTIVITIES;
if (hasStoppedActivity) return ApplicationState.HAS_STOPPED_ACTIVITIES;
return ApplicationState.HAS_DESTROYED_ACTIVITIES;
}
// Called to notify the native side of state changes.
// IMPORTANT: This is always called on the main thread!
private static native void nativeOnApplicationStateChange(@ApplicationState int newState);
}
| 39.085417
| 99
| 0.649006
|
af639ab91396547f501ce476b02229cd52f9f7ec
| 6,503
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package com.facebook.login.widget;
// Referenced classes of package com.facebook.login.widget:
// LoginButton
public static final class LoginButton$ToolTipMode extends Enum
{
public static LoginButton$ToolTipMode fromInt(int i)
{
LoginButton$ToolTipMode aloginbutton$tooltipmode[] = values();
// 0 0:invokestatic #59 <Method LoginButton$ToolTipMode[] values()>
// 1 3:astore_3
int k = aloginbutton$tooltipmode.length;
// 2 4:aload_3
// 3 5:arraylength
// 4 6:istore_2
for(int j = 0; j < k; j++)
//* 5 7:iconst_0
//* 6 8:istore_1
//* 7 9:iload_1
//* 8 10:iload_2
//* 9 11:icmpge 38
{
LoginButton$ToolTipMode loginbutton$tooltipmode = aloginbutton$tooltipmode[j];
// 10 14:aload_3
// 11 15:iload_1
// 12 16:aaload
// 13 17:astore 4
if(loginbutton$tooltipmode.getValue() == i)
//* 14 19:aload 4
//* 15 21:invokevirtual #63 <Method int getValue()>
//* 16 24:iload_0
//* 17 25:icmpne 31
return loginbutton$tooltipmode;
// 18 28:aload 4
// 19 30:areturn
}
// 20 31:iload_1
// 21 32:iconst_1
// 22 33:iadd
// 23 34:istore_1
//* 24 35:goto 9
return null;
// 25 38:aconst_null
// 26 39:areturn
}
public static LoginButton$ToolTipMode valueOf(String s)
{
return (LoginButton$ToolTipMode)Enum.valueOf(com/facebook/login/widget/LoginButton$ToolTipMode, s);
// 0 0:ldc1 #2 <Class LoginButton$ToolTipMode>
// 1 2:aload_0
// 2 3:invokestatic #68 <Method Enum Enum.valueOf(Class, String)>
// 3 6:checkcast #2 <Class LoginButton$ToolTipMode>
// 4 9:areturn
}
public static LoginButton$ToolTipMode[] values()
{
return (LoginButton$ToolTipMode[])((LoginButton$ToolTipMode []) ($VALUES)).clone();
// 0 0:getstatic #42 <Field LoginButton$ToolTipMode[] $VALUES>
// 1 3:invokevirtual #73 <Method Object _5B_Lcom.facebook.login.widget.LoginButton$ToolTipMode_3B_.clone()>
// 2 6:checkcast #69 <Class LoginButton$ToolTipMode[]>
// 3 9:areturn
}
public int getValue()
{
return intValue;
// 0 0:aload_0
// 1 1:getfield #52 <Field int intValue>
// 2 4:ireturn
}
public String toString()
{
return stringValue;
// 0 0:aload_0
// 1 1:getfield #50 <Field String stringValue>
// 2 4:areturn
}
private static final LoginButton$ToolTipMode $VALUES[];
public static final LoginButton$ToolTipMode AUTOMATIC;
public static LoginButton$ToolTipMode DEFAULT;
public static final LoginButton$ToolTipMode DISPLAY_ALWAYS;
public static final LoginButton$ToolTipMode NEVER_DISPLAY;
private int intValue;
private String stringValue;
static
{
AUTOMATIC = new LoginButton$ToolTipMode("AUTOMATIC", 0, "automatic", 0);
// 0 0:new #2 <Class LoginButton$ToolTipMode>
// 1 3:dup
// 2 4:ldc1 #22 <String "AUTOMATIC">
// 3 6:iconst_0
// 4 7:ldc1 #24 <String "automatic">
// 5 9:iconst_0
// 6 10:invokespecial #28 <Method void LoginButton$ToolTipMode(String, int, String, int)>
// 7 13:putstatic #30 <Field LoginButton$ToolTipMode AUTOMATIC>
DISPLAY_ALWAYS = new LoginButton$ToolTipMode("DISPLAY_ALWAYS", 1, "display_always", 1);
// 8 16:new #2 <Class LoginButton$ToolTipMode>
// 9 19:dup
// 10 20:ldc1 #31 <String "DISPLAY_ALWAYS">
// 11 22:iconst_1
// 12 23:ldc1 #33 <String "display_always">
// 13 25:iconst_1
// 14 26:invokespecial #28 <Method void LoginButton$ToolTipMode(String, int, String, int)>
// 15 29:putstatic #35 <Field LoginButton$ToolTipMode DISPLAY_ALWAYS>
NEVER_DISPLAY = new LoginButton$ToolTipMode("NEVER_DISPLAY", 2, "never_display", 2);
// 16 32:new #2 <Class LoginButton$ToolTipMode>
// 17 35:dup
// 18 36:ldc1 #36 <String "NEVER_DISPLAY">
// 19 38:iconst_2
// 20 39:ldc1 #38 <String "never_display">
// 21 41:iconst_2
// 22 42:invokespecial #28 <Method void LoginButton$ToolTipMode(String, int, String, int)>
// 23 45:putstatic #40 <Field LoginButton$ToolTipMode NEVER_DISPLAY>
LoginButton$ToolTipMode loginbutton$tooltipmode = AUTOMATIC;
// 24 48:getstatic #30 <Field LoginButton$ToolTipMode AUTOMATIC>
// 25 51:astore_0
$VALUES = (new LoginButton$ToolTipMode[] {
loginbutton$tooltipmode, DISPLAY_ALWAYS, NEVER_DISPLAY
});
// 26 52:iconst_3
// 27 53:anewarray LoginButton$ToolTipMode[]
// 28 56:dup
// 29 57:iconst_0
// 30 58:aload_0
// 31 59:aastore
// 32 60:dup
// 33 61:iconst_1
// 34 62:getstatic #35 <Field LoginButton$ToolTipMode DISPLAY_ALWAYS>
// 35 65:aastore
// 36 66:dup
// 37 67:iconst_2
// 38 68:getstatic #40 <Field LoginButton$ToolTipMode NEVER_DISPLAY>
// 39 71:aastore
// 40 72:putstatic #42 <Field LoginButton$ToolTipMode[] $VALUES>
DEFAULT = loginbutton$tooltipmode;
// 41 75:aload_0
// 42 76:putstatic #44 <Field LoginButton$ToolTipMode DEFAULT>
//* 43 79:return
}
private LoginButton$ToolTipMode(String s, int i, String s1, int j)
{
super(s, i);
// 0 0:aload_0
// 1 1:aload_1
// 2 2:iload_2
// 3 3:invokespecial #48 <Method void Enum(String, int)>
stringValue = s1;
// 4 6:aload_0
// 5 7:aload_3
// 6 8:putfield #50 <Field String stringValue>
intValue = j;
// 7 11:aload_0
// 8 12:iload 4
// 9 14:putfield #52 <Field int intValue>
// 10 17:return
}
}
| 37.80814
| 117
| 0.564816
|
f549c586de6a021b69c85fb47aa666293cf4867c
| 1,544
|
/**
* Tencent is pleased to support the open source community by making Tars available.
*
* Copyright (C) 2016 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.qq.tars.tars2java.parse.ast;
import org.antlr.runtime.CommonToken;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.Tree;
public class TarsConst extends CommonTree {
private final String constName;
private final String constValue;
private TarsPrimitiveType constType;
public TarsConst(int tokenType, String constName, String constValue) {
super(new CommonToken(tokenType));
this.constName = constName;
this.constValue = constValue;
}
@Override
public void addChild(Tree child) {
super.addChild(child);
if (child instanceof TarsPrimitiveType) {
constType = (TarsPrimitiveType) child;
}
}
public TarsPrimitiveType constType() {
return constType;
}
public String constName() {
return constName;
}
public String constValue() {
return constValue;
}
}
| 27.571429
| 92
| 0.755181
|
87bbba1d51706deaa591fb32d071da87a24b29fc
| 444
|
/*
* 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.addteq.confluence.plugin.excellentable.attachment;
import com.google.gson.JsonObject;
/**
*
* @author Vikash Kumar <vikash.kumar@addteq.com>
*/
public interface AttachmentService {
public JsonObject parseAttachment(long attachmentId);
}
| 24.666667
| 79
| 0.759009
|
43503bf5a9f3df7ee67b13da81b0edf0337db560
| 873
|
package com.global.labs.utils;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
import com.global.labs.R;
public class LogoutDialog extends Dialog {
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
super.setContentView(R.layout.layout_snackbar);
TextView tv = (TextView) findViewById(R.id.textView);
tv.setText(message);
// Button btn = (Button) findViewById(R.id.button1);
// btn.setOnClickListener(new View.OnClickListener() {
//
// @Override
// public void onClick(View v) {
//
// dismiss();
// }
// });
}
String message = "";
public LogoutDialog(Context context, String Message) {
super(context);
this.message = Message;
show();
}
}
| 20.785714
| 55
| 0.726231
|
a9a233cc6f8128a680329d0c2ba3ff220c9d272c
| 19,126
|
/*
* Copyright 2011 Unicommerce (P) Limited . All Rights Reserved.
* UNICOMMERCE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
* @version 1.0, Nov 27, 2011
* @author singla
*/
package com.unilearntech.unilearntech.utils.string;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.core.convert.support.DefaultConversionService;
public class StringUtils {
private static final String GMAIL_EMAIL_SUFFIX = "@gmail.com";
private static final int GMAIL_EMAIL_SUFFIX_LENGTH = GMAIL_EMAIL_SUFFIX.length();
public static final String EMPTY_STRING = "";
public static final char CHAR_NEW_LINE = '\n';
public static final char CHAR_NULL = '\0';
private static DefaultConversionService conversionService = new DefaultConversionService();
public static String getRandom(int length) {
String randomString = getRandom();
return randomString.substring(randomString.length() - length);
}
public static String trimString(String str) {
if (isNotBlank(str)) {
return str.trim();
}
return str;
}
public static String getRandomAlphaNumeric(int length) {
String aplhaNumberic = getRandom().toLowerCase().replaceAll("[^\\da-z]", "");
return aplhaNumberic.substring(aplhaNumberic.length() - length);
}
public static String getRandomAlphaNumeric() {
return getRandom().toLowerCase().replaceAll("[^\\da-z]", "");
}
public static String getRandomNumeric(int length) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length; i++) {
builder.append((int) (Math.random() * 10));
}
return builder.toString();
}
public static String getRandom() {
return UUID.randomUUID().toString();
}
public static boolean isEmpty(String str) {
return str == null ? true : "".equals(str.trim());
}
public static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
public static boolean isBlank(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return false;
}
}
return true;
}
public static boolean isNumeric(String str) {
return !isBlank(str) && str.matches("^\\d+$");
}
public static boolean isStrictlyAlphaNumeric(String str) {
return !isBlank(str) && str.matches("^(?=.*[a-z])(?=.*[0-9])[a-z0-9]+$");
}
public static boolean isAlphaNumeric(String str){
return !isBlank(str) && str.matches("^[a-zA-Z0-9]+$");
}
public static boolean isNotBlank(String str) {
return !isBlank(str);
}
public static String getAccessorNameForField(String name) {
return new StringBuilder("get").append(name.substring(0, 1).toUpperCase()).append(name.substring(1)).toString();
}
public static String getModifierNameForField(String name) {
return new StringBuilder("set").append(name.substring(0, 1).toUpperCase()).append(name.substring(1)).toString();
}
public static String getNotNullValue(String value) {
return value != null ? value : "";
}
public static String join(char sep, Collection<String> strings) {
if (strings == null || strings.size() == 0) {
return EMPTY_STRING;
}
StringBuilder builder = new StringBuilder();
for (String s : strings) {
builder.append(s).append(sep);
}
return builder.deleteCharAt(builder.length() - 1).toString();
}
public static String join(Collection<String> strings) {
return join(',', strings);
}
public static String extractBetweenDelimiters(String input, String startDelimiter, String endDelimiter) {
int startIndex = input.indexOf(startDelimiter);
if (startIndex != -1) {
int endIndex = input.indexOf(endDelimiter, startIndex + startDelimiter.length());
if (endIndex != -1) {
return input.substring(startIndex + startDelimiter.length(), endIndex);
}
}
return null;
}
public static String normalizeEmail(String email) {
if (email.toLowerCase().endsWith(GMAIL_EMAIL_SUFFIX)) {
return email.substring(0, email.length() - GMAIL_EMAIL_SUFFIX_LENGTH).split("\\+")[0].replaceAll("\\.", "") + GMAIL_EMAIL_SUFFIX;
} else {
return email;
}
}
public static String getEmailDomain(String email) {
return email.substring(email.lastIndexOf('@') + 1);
}
public static String getLocalPartFromEmail(String emailAdd) {
return emailAdd.substring(0, emailAdd.lastIndexOf('@'));
}
public static List<String> split(String input, String regex) {
return new ArrayList<>(Arrays.asList(input.split(regex)));
}
public static List<String> split(String input) {
return split(input, ",");
}
public static String capitalizeString(String string) {
char[] chars = string.toLowerCase().toCharArray();
boolean found = false;
for (int i = 0; i < chars.length; i++) {
if (!found && Character.isLetter(chars[i])) {
chars[i] = Character.toUpperCase(chars[i]);
found = true;
} else if (Character.isWhitespace(chars[i]) || chars[i] == '.' || chars[i] == '\'') { // You can add other chars here
found = false;
}
}
return String.valueOf(chars);
}
public static Double parsePrice(String number) {
number = number.replaceAll("[^\\.\\d,-]", "");
DecimalFormat df = new DecimalFormat("#,##,###.##");
Number n;
try {
n = df.parse(number);
} catch (ParseException e) {
return 0.0;
}
return n.doubleValue();
}
public static <T> boolean equalsAny(T input, T... values) {
for (T value : values) {
if (input.equals(value)) {
return true;
} else if(!input.getClass().equals(value.getClass())) {
// checking type of input and values as well, as of now, we can pass input & values of different types
// because compiler do not restrict it which make issue with code logic if someone mistakenly put input of other type and some/all items of values of different type
throw new RuntimeException("Wrong type parameter passed for " + value + " of type " + value.getClass() + " while input type is " + input.getClass());
}
}
return false;
}
public static boolean compareStrings(String s1, String s2) {
if (s1 == null)
return s2 == null;
return s1.equals(s2);
}
public static boolean equalsIngoreCaseAny(String input, String... strings) {
for (String string : strings) {
if (input.equalsIgnoreCase(string)) {
return true;
}
}
return false;
}
private static final int INT = 0;
private static final int FRAC = 1;
private static final int EXP = 2;
/**
* Parse a number from a string. Finds the first recognizable base-10 number (integer or floating point) in the
* string and returns it as a Number. Uses American English conventions (i.e., '.' as decimal point and ',' as
* <<<<<<< HEAD thousands separator).
*
* @param s String to parse ======= thousands separator). <<<<<<< Updated upstream
* @param
* @param s String to parse >>>>>>> Stashed changes >>>>>>> cc5957b9e5f35a418b4f5af14be6805a0dc6a56a
* @return first recognizable number
* @throws NumberFormatException if no recognizable number is found
*/
public static Number parseNumber(String s) throws NumberFormatException {
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
int start = i;
int end = ++i;
int state = INT;
if (start > 0 && s.charAt(start - 1) == '.') {
--start;
state = FRAC;
}
if (start > 0 && s.charAt(start - 1) == '-') {
--start;
}
foundEnd: while (i < s.length()) {
switch (s.charAt(i)) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
end = ++i;
break;
case '.':
if (state != INT) {
break foundEnd;
}
state = FRAC;
++i;
break;
case ',': // ignore commas
++i;
break;
case 'e':
case 'E':
state = EXP;
++i;
if (i < s.length() && ((c = s.charAt(i)) == '+' || c == '-')) {
++i;
}
break;
default:
break foundEnd;
}
}
String num = s.substring(start, end);
num = replace(num, ",", "");
try {
if (state == INT) {
return Long.valueOf(num);
} else {
return new Float(num);
}
} catch (NumberFormatException e) {
throw new RuntimeException("internal error: " + e);
}
}
}
throw new NumberFormatException(s);
}
/**
* Replace all occurences of a string.
*
* @param subject String in which to search
* @param original String to search for in subject
* @param replacement String to substitute
* @return subject with all occurences of original replaced by replacement
*/
public static String replace(String subject, String original, String replacement) {
StringBuilder output = new StringBuilder();
int p = 0;
int i;
while ((i = subject.indexOf(original, p)) != -1) {
output.append(subject.substring(p, i));
output.append(replacement);
p = i + original.length();
}
if (p < subject.length()) {
output.append(subject.substring(p));
}
return output.toString();
}
/**
* Escapes metacharacters in a string.
*
* @param subject String in which metacharacters are to be escaped
* @param escapeChar the escape character (e.g., \)
* @param metachars the metacharacters that should be escaped
* @return subject with escapeChar inserted before every character found in metachars
*/
public static String escape(String subject, char escapeChar, String metachars) {
return escape(subject, metachars, escapeChar, metachars);
}
/**
* Escapes characters in a string.
*
* @param subject String in which metacharacters are to be escaped
* @param chars Characters that need to be escaped (e.g. "\b\t\r\n\\")
* @param escapeChar the escape character (e.g., '\\')
* @param metachars escape code letters corresponding to each letter in chars (e.g. "btrn\\") <B>Must have
* metachars.length () == chars.length().</B>
* @return subject where every occurence of c in chars is replaced by escapeChar followed the character
* corresponding to c in metachars.
*/
public static String escape(String subject, String chars, char escapeChar, String metachars) {
StringBuilder output = new StringBuilder();
int p = 0;
int i;
while ((i = indexOfAnyChar(subject, chars, p)) != -1) {
output.append(subject.substring(p, i));
char c = subject.charAt(i); // character that needs escaping
int k = chars.indexOf(c);
char metac = metachars.charAt(k); // its corresponding metachar
output.append(escapeChar);
output.append(metac);
p = i + 1;
}
if (p < subject.length()) {
output.append(subject.substring(p));
}
return output.toString();
}
/**
* Translate escape sequences (e.g. \r, \n) to characters.
*
* @param subject String in which metacharacters are to be escaped
* @param escapeChar the escape character (e.g., \)
* @param metachars letters representing escape codes (typically "btrn\\")
* @param chars characters corresponding to metachars (typically "\b\t\r\n\\"). <B>Must have chars.length () ==
* metachars.length().</B>
* @param keepUntranslatedEscapes Controls behavior on unknown escape sequences (see below).
* @return subject where every escapeChar followed by c in metachars is replaced by the character corresponding to c
* in chars. If an escape sequence is untranslatable (because escapeChar is followed by some character c not
* in metachars), then the escapeChar is kept if keepUntranslatedEscapes is true, otherwise the escapeChar
* is deleted. (The character c is always kept.)
*/
public static String unescape(String subject, char escapeChar, String metachars, String chars, boolean keepUntranslatedEscapes) {
StringBuilder output = new StringBuilder();
int p = 0;
int i;
int len = subject.length();
while ((i = subject.indexOf(escapeChar, p)) != -1) {
output.append(subject.substring(p, i));
if (i + 1 == len) {
break;
}
char metac = subject.charAt(i + 1); // metachar to replace
int k = metachars.indexOf(metac);
if (k == -1) {
// untranslatable sequence
if (keepUntranslatedEscapes) {
output.append(escapeChar);
}
output.append(metac);
} else {
output.append(chars.charAt(k)); // its corresponding true char
}
p = i + 2; // skip over both escapeChar & metac
}
if (p < len) {
output.append(subject.substring(p));
}
return output.toString();
}
/**
* Find first occurrence of any of a set of characters.
*
* @param subject String in which to search
* @param chars Characters to search for
* @return index of first occurrence in subject of a character from chars, or -1 if no match.
*/
public static int indexOfAnyChar(String subject, String chars) {
return indexOfAnyChar(subject, chars, 0);
}
/**
* Find first occurrence of any of a set of characters, starting at a specified index.
*
* @param subject String in which to search
* @param chars Characters to search for
* @param start Starting offset to search from
* @return index of first occurrence (after start) in subject of a character from chars, or -1 if no match.
*/
public static int indexOfAnyChar(String subject, String chars, int start) {
for (int i = start; i < subject.length(); ++i) {
if (chars.indexOf(subject.charAt(i)) != -1) {
return i;
}
}
return -1;
}
/**
* removes all characters which are not letter or digit (removes whitespaces as well!)
*
* @param input input string
* @return string with all non-word chars removed
*/
public static String removeNonWordChars(String input) {
StringBuilder output = new StringBuilder();
char[] cinput = input.toCharArray();
for (char element : cinput) {
if (Character.isLetterOrDigit(element)) {
output.append(element);
}
}
return output.toString();
}
/**
* @param input boolean string
* @return true if input is "yes" or "1" or "true"
*/
public static boolean parseBoolean(String input) {
input = input == null ? null : input.trim();
return ((input != null) && (input.equalsIgnoreCase("true") || input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("1")));
}
public static String pad(String input, int length, char c) {
input = getNotNullValue(input);
if (input.length() >= length) {
return input;
} else {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < length - input.length(); i++) {
builder.append(c);
}
builder.append(input);
return builder.toString();
}
}
public static String underscorify(String input) {
return input.replaceAll("[\\s\\W]", "_").replaceAll("[_]+", "_");
}
public static String escapeSql(String input) {
if (input == null) {
return "NULL";
} else {
return new StringBuilder().append('\'').append(
input.replaceAll("\\\\", "\\\\\\\\").replaceAll("\t", "\\\\t").replaceAll("\n", "\\\\n").replaceAll("\r", "\\\\r").replaceAll("\"", "\\\\\"").replaceAll("'",
"\\\\'")).append('\'').toString();
}
}
public static String normalizeCacheKey(String input) {
if (input == null) {
return StringUtils.EMPTY_STRING;
}
return StringUtils.removeNonWordChars(input).toLowerCase();
}
public static <T> T convert(Object source, Class<T> targetType) {
return conversionService.convert(source, targetType);
}
/**
* Providing string formatting to a pattern
*/
public static String format(String pattern, Object... args) {
return String.format(pattern, args);
}
public static String replaceByRegex(String input, String regexString, String replacementString) {
Pattern pattern = Pattern.compile(regexString);
return pattern.matcher(input).replaceAll(replacementString);
}
}
| 36.639847
| 180
| 0.550403
|
a071823210adac098396393650d8bae347225e43
| 679
|
package com.gbourquet.yaph.client.mvp.place;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceTokenizer;
import com.google.gwt.place.shared.Prefix;
public class LogoutPlace extends Place {
private String token;
public LogoutPlace(String token) {
this.token = token;
}
public String getToken() {
return token;
}
@Prefix(value = "logout")
public static class Tokenizer implements PlaceTokenizer<LogoutPlace> {
@Override
public String getToken(LogoutPlace place) {
return place.getToken();
}
@Override
public LogoutPlace getPlace(String token) {
return new LogoutPlace(token);
}
}
}
| 21.903226
| 72
| 0.712813
|
3fc15cbd4824007a55cb5e08bcda6763b047773d
| 784
|
package io.github.dzikowski.storm;
import java.util.Map;
import backtype.storm.task.OutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.tuple.Tuple;
@SuppressWarnings("serial")
public class PrintlnBolt extends BaseRichBolt {
private OutputCollector _collector;
@Override
@SuppressWarnings("rawtypes")
public void prepare(Map conf, TopologyContext context, OutputCollector collector) {
_collector = collector;
}
@Override
public void execute(Tuple input) {
System.out.println(">>> " + input);
_collector.ack(input);
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
}
| 25.290323
| 85
| 0.760204
|
a50add4f134c739511275e128eba39f3ef84b67d
| 239
|
public class ContarPares {
public static void contar(int[] a){
int pares = 0;
for(int x: a){
if(x%2==0){
pares++;
}
}
System.out.println(pares);
}
}
| 17.071429
| 39
| 0.401674
|
eebcd919e0dbf85794b34d159f186d877186f321
| 1,210
|
/*
* 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 dk.statsbiblioteket.summa.support.harmonise.hub;
import dk.statsbiblioteket.summa.support.harmonise.hub.core.ComponentCallable;
import org.apache.solr.common.params.SolrParams;
import java.util.List;
/**
* Modifies incoming requests.
*/
public interface RequestAdjuster {
/**
* @param params original parameters for the calling HubComposite.
* @param components the components that will be called, including component-specific parameters.
* @return the adjusted component list.
*/
List<ComponentCallable> adjustRequests(
SolrParams params, List<ComponentCallable> components);
}
| 35.588235
| 101
| 0.738017
|
7e3fe7e3db160aeb53ea923bcc89f2d91d5df7bd
| 1,786
|
package com.twocheckout.model;
import java.math.BigDecimal;
public class Billing {
private BigDecimal amount;
private String bill_method;
private Long billing_id;
private BigDecimal customer_amount;
private Long customer_id;
private String date_deposited;
private String date_end;
private String date_fail;
private String date_next;
private String date_pending;
private String date_start;
private Long lineitem_id;
private String recurring_status;
private String status;
private BigDecimal usd_amount;
private BigDecimal vendor_amount;
public BigDecimal getAmount() {
return amount;
}
public String getBillMethod() {
return bill_method;
}
public Long getBillingId() {
return billing_id;
}
public BigDecimal getCustomerAmount() {
return customer_amount;
}
public Long getCustomerId() {
return customer_id;
}
public String getDateDeposited() {
return date_deposited;
}
public String getDateEnd() {
return date_end;
}
public String getDateFail() {
return date_fail;
}
public String getDateNext() {
return date_next;
}
public String getDatePending() {
return date_pending;
}
public String getDateStart() {
return date_start;
}
public Long getLineitemId() {
return lineitem_id;
}
public String getRecurringStatus() {
return recurring_status;
}
public String getStatus() {
return status;
}
public BigDecimal getUsdAmount() {
return usd_amount;
}
public BigDecimal getVendorAmount() {
return vendor_amount;
}
}
| 21.518072
| 43
| 0.633259
|
14260b359576f05029abeb281e4ae67eda44d6bb
| 2,501
|
package org.infinispan.persistence.remote.configuration;
import static org.infinispan.persistence.remote.configuration.KeyStoreConfiguration.KEYSTORE_CERTIFICATE_PASSWORD;
import static org.infinispan.persistence.remote.configuration.KeyStoreConfiguration.KEYSTORE_FILENAME;
import static org.infinispan.persistence.remote.configuration.KeyStoreConfiguration.KEYSTORE_PASSWORD;
import static org.infinispan.persistence.remote.configuration.KeyStoreConfiguration.KEYSTORE_TYPE;
import static org.infinispan.persistence.remote.configuration.KeyStoreConfiguration.KEY_ALIAS;
import org.infinispan.client.hotrod.logging.Log;
import org.infinispan.client.hotrod.logging.LogFactory;
import org.infinispan.commons.configuration.Builder;
import org.infinispan.commons.configuration.attributes.AttributeSet;
/**
* @since 10.0
*/
public class KeyStoreConfigurationBuilder extends AbstractSecurityConfigurationChildBuilder implements Builder<KeyStoreConfiguration> {
private static final Log log = LogFactory.getLog(KeyStoreConfigurationBuilder.class);
protected KeyStoreConfigurationBuilder(SecurityConfigurationBuilder builder) {
super(builder, KeyStoreConfiguration.attributeDefinitionSet());
}
public AttributeSet attributes() {
return attributes;
}
public KeyStoreConfigurationBuilder keyStoreFileName(String keyStoreFileName) {
this.attributes.attribute(KEYSTORE_FILENAME).set(keyStoreFileName);
return this;
}
public KeyStoreConfigurationBuilder keyStoreType(String keyStoreType) {
this.attributes.attribute(KEYSTORE_TYPE).set(keyStoreType);
return this;
}
public KeyStoreConfigurationBuilder keyStorePassword(char[] keyStorePassword) {
this.attributes.attribute(KEYSTORE_PASSWORD).set(new String(keyStorePassword));
return this;
}
public KeyStoreConfigurationBuilder keyStoreCertificatePassword(char[] keyStoreCertificatePassword) {
this.attributes.attribute(KEYSTORE_CERTIFICATE_PASSWORD).set(new String(keyStoreCertificatePassword));
return this;
}
public KeyStoreConfigurationBuilder keyAlias(String keyAlias) {
this.attributes.attribute(KEY_ALIAS).set(keyAlias);
return this;
}
@Override
public KeyStoreConfiguration create() {
return new KeyStoreConfiguration(attributes.protect());
}
@Override
public KeyStoreConfigurationBuilder read(KeyStoreConfiguration template) {
this.attributes.read(template.attributes());
return this;
}
}
| 39.078125
| 135
| 0.804878
|
743caa6b335a8dd89ff692b9d0e4c01db2465790
| 4,259
|
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.incfs.install.adb.ddmlib;
import com.android.annotations.NonNull;
import com.android.ddmlib.AdbCommandRejectedException;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.TimeoutException;
import com.android.incfs.install.IDeviceConnection;
import com.android.incfs.install.IncrementalInstallSession;
import com.android.utils.ILogger;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Channel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.concurrent.Executor;
/**
* Represents a connection to a device through ADB for use with {@link
* IncrementalInstallSession.Builder#execute(Executor, IDeviceConnection.Factory, ILogger)}.
*/
public class DeviceConnection implements IDeviceConnection {
/**
* Creates a factory for creating a connection to the device.
*
* @param deviceSerialNumber the serial of the device to talk to.
*/
public static Factory getFactory(@NonNull String deviceSerialNumber) throws IOException {
final AndroidDebugBridge adb = AndroidDebugBridge.getBridge();
if (adb == null) {
throw new IOException("Unable to connect to adb");
}
for (final IDevice device : adb.getDevices()) {
if (deviceSerialNumber.equals(device.getSerialNumber())) {
return new Factory(device);
}
}
throw new IOException("Failed to find device with serial \"" + deviceSerialNumber + "\"");
}
public static class Factory implements IDeviceConnection.Factory {
private final IDevice mDevice;
private Factory(@NonNull IDevice device) {
mDevice = device;
}
@Override
public IDeviceConnection connectToService(
@NonNull String service, @NonNull String[] parameters) throws IOException {
final SocketChannel channel;
try {
channel = mDevice.rawBinder(service, parameters);
} catch (AdbCommandRejectedException | TimeoutException e) {
throw new IOException(
String.format(
"Failed invoking binder command \"%s %s\"",
service, String.join(" ", parameters)),
e);
}
channel.configureBlocking(false);
return new DeviceConnection(channel);
}
}
@NonNull private final SocketChannel mChannel;
@NonNull private final Selector mReadSelector;
@NonNull private final Selector mWriteSelector;
private DeviceConnection(@NonNull SocketChannel channel) throws IOException {
mChannel = channel;
mChannel.configureBlocking(false);
mReadSelector = Selector.open();
mChannel.register(mReadSelector, SelectionKey.OP_READ);
mWriteSelector = Selector.open();
mChannel.register(mWriteSelector, SelectionKey.OP_WRITE);
}
@Override
public int read(@NonNull ByteBuffer dst, long timeoutMs) throws IOException {
mReadSelector.select(timeoutMs);
return mChannel.read(dst);
}
@Override
public int write(@NonNull ByteBuffer src, long timeoutMs) throws IOException {
mWriteSelector.select(timeoutMs);
return mChannel.write(src);
}
@Override
public void close() throws Exception {
try (Channel c = mChannel;
Selector r = mReadSelector;
Selector w = mWriteSelector) {}
}
}
| 37.034783
| 98
| 0.675041
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.