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
|
---|---|---|---|---|---|
0740bf3fd3f743d57a295ce8a2f0fb275650627e | 4,884 | /*
* Copyright (C) 2020 Beijing Yishu Technology Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.growingio.android.okhttp3;
import android.content.Context;
import android.util.Log;
import com.google.common.truth.Truth;
import com.growingio.android.sdk.track.http.EventResponse;
import com.growingio.android.sdk.track.http.EventUrl;
import com.growingio.android.sdk.track.modelloader.DataFetcher;
import com.growingio.android.sdk.track.modelloader.ModelLoader;
import com.growingio.android.sdk.track.modelloader.TrackerRegistry;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.RecordedRequest;
import static com.google.common.truth.Truth.assertThat;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
/**
* <p>
*
* @author cpacm 2021/6/3
*/
@RunWith(PowerMockRunner.class)
@PrepareForTest(Log.class)
@PowerMockIgnore("javax.net.ssl.*")
public class Okhttp3Test extends MockServer {
@Before
public void prepare() throws IOException {
mockStatic(Log.class);
mockEventsApiServer();
start();
}
public void mockEventsApiServer() {
Dispatcher dispatcher = new Dispatcher() {
@Override
public MockResponse dispatch(RecordedRequest request) throws InterruptedException {
String url = request.getRequestUrl().toString();
URI uri = URI.create(url);
checkPath(uri.getPath());
String json = request.getBody().readUtf8();
dispatchReceivedEvents(json);
return new MockResponse().setResponseCode(200);
}
};
setDispatcher(dispatcher);
}
@Mock
Context fakeContext;
private EventUrl initEventUrl(String host) {
long time = System.currentTimeMillis();
return new EventUrl(host, time)
.addPath("v3")
.addPath("projects")
.addPath("bfc5d6a3693a110d")
.addPath("collect")
.addHeader("name", "cpacm")
.setBodyData("cpacm".getBytes())
.addParam("stm", String.valueOf(time));
}
private void checkPath(String path) {
String expectedPath = "/v3/projects/bfc5d6a3693a110d/collect";
Truth.assertThat(path).isEqualTo(expectedPath);
}
private void dispatchReceivedEvents(String json) {
Truth.assertThat(json).isEqualTo("cpacm");
}
@Test
public void sendTest() {
OkhttpLibraryGioModule module = new OkhttpLibraryGioModule();
TrackerRegistry trackerRegistry = new TrackerRegistry();
module.registerComponents(fakeContext, trackerRegistry);
ModelLoader<EventUrl, EventResponse> modelLoader = trackerRegistry.getModelLoader(EventUrl.class, EventResponse.class);
EventUrl eventUrl = initEventUrl("http://localhost:8910/");
EventResponse response = modelLoader.buildLoadData(eventUrl).fetcher.executeData();
assertThat(response.isSucceeded()).isTrue();
Truth.assertThat(response.getStream()).isInstanceOf(InputStream.class);
Truth.assertThat(response.getUsedBytes()).isEqualTo(0L);
DataFetcher<EventResponse> dataFetcher = modelLoader.buildLoadData(eventUrl).fetcher;
Truth.assertThat(dataFetcher.getDataClass()).isAssignableTo(EventResponse.class);
dataFetcher.loadData(new DataFetcher.DataCallback<EventResponse>() {
@Override
public void onDataReady(EventResponse response) {
assertThat(response.isSucceeded()).isTrue();
Truth.assertThat(response.getStream()).isInstanceOf(InputStream.class);
Truth.assertThat(response.getUsedBytes()).isEqualTo(0L);
dataFetcher.cleanup();
dataFetcher.cancel();
}
@Override
public void onLoadFailed(Exception e) {
}
});
}
}
| 35.649635 | 127 | 0.687142 |
11306f3a04be7a70d0e943d53f0bd1455c0dcabc | 744 | package net.distortsm.api.mixin;
import org.schema.game.client.controller.GameClientController;
import org.schema.schine.network.client.ClientController;
import org.schema.schine.network.client.ClientState;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(GameClientController.class)
public abstract class DistortAPIMixin extends ClientController {
private ExampleMixin(ClientState clientState) {
super(clientState);
}
@Inject(at = @At("HEAD"), method = "initialize()V")
public void init(CallbackInfo info) {
System.out.println("Distort API Mixin Loaded!");
}
}
| 33.818182 | 67 | 0.805108 |
cf9cc6ce19e7c14e5d0b2cf04453827ffe37d6ed | 878 | /*
* 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 akh.convdimtoncdf;
/**
*
* @author akheckel
*/
class SinCell {
int nBands;
float bandSums[];
int count;
private SinCell(){
};
SinCell(int nBands) {
this.nBands = nBands;
this.bandSums = new float[nBands];
}
SinCell(float bandValues[]) {
this.nBands = bandValues.length;
this.bandSums = new float[nBands];
System.arraycopy(bandValues, 0, this.bandSums, 0, this.nBands);
count++;
}
void addValues(float bandValues[]){
for (int i=0; i<nBands; i++){
bandSums[i] += bandValues[i];
}
count++;
}
}
| 21.414634 | 80 | 0.552392 |
21983c5c5c7f23f645b919729fedd9aab2362c92 | 610 | package org.jccastro.clip.assesment.transaction.datastore;
import java.util.List;
import org.jccastro.clip.assesment.model.Transaction;
/**
* Interface for the basic transaction operations
* @author JCCastro
*
*/
public interface TransactionDataStore {
/**
*
* @param transaction
*/
public void saveTransaction(Transaction transaction);
/**
*
* @param userId
* @param transactionId
* @return
*/
public Transaction getTransaction(String userId, String transactionId);
/**
*
* @param userId
* @return
*/
public List<Transaction> getUserTransactions(String userId);
}
| 16.944444 | 72 | 0.711475 |
8918e53c77b0f9012832caa9633a39ae19664923 | 705 | package gestionprojet.controleur.actions;
import javax.swing.AbstractAction;
import gestionprojet.view.ui.Fenetre.FenetreOption;
import java.awt.event.ActionEvent;
public class ActionDerouler extends AbstractAction{
private static final long serialVersionUID = 1L;
public static final String NOM_ACTION = "Plus";
FenetreOption fenetre;
/**
* Action permettant d'afficher ou masquer le panneauBas des fenetres de creation edition
* des projets et des lots
* @param fenetre
**/
public ActionDerouler(FenetreOption fenetre){
super(NOM_ACTION);
this.fenetre = fenetre;
}
public void actionPerformed(ActionEvent e) {
fenetre.afficherMasquer();
}
}
| 24.310345 | 91 | 0.739007 |
accf8d7524956ddae27a550d6c40b9e06f0b2462 | 297 | package cz.metacentrum.perun.dispatcher.dao;
import java.util.List;
import java.util.Map;
/**
*
* @author Michal Karm Babacek JavaDoc coming soon...
*
*/
public interface RulesDao {
Map<Integer, List<String>> loadRoutingRules();
List<String> loadRoutingRulesForEngine(int clientID);
}
| 17.470588 | 54 | 0.734007 |
629344f8fffaedfc953b915ced0a95dbdc9c0c73 | 4,457 | package org.alfresco.utility.web;
import org.alfresco.utility.LogFactory;
import org.alfresco.utility.web.browser.WebBrowser;
import org.alfresco.utility.web.browser.WebBrowserFactory;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.ITestResult;
import org.testng.annotations.*;
import java.lang.reflect.Method;
import java.util.Set;
/**
* Created by Claudia Agache on 3/9/2017.
*/
public abstract class AbstractWebTest extends AbstractTestNGSpringContextTests
{
@Autowired
WebBrowserFactory browserFactory;
protected static final ThreadLocal<WebBrowser> browserThread = new ThreadLocal<WebBrowser>();
protected Logger LOG = LogFactory.getLogger();
@BeforeSuite(alwaysRun = true)
public void initializeBeans() throws Exception
{
super.springTestContextPrepareTestInstance();
}
@BeforeClass(alwaysRun = true)
public void defineBrowser() throws Exception
{
browserThread.set(browserFactory.getWebBrowser());
initializeBrowser();
}
@AfterClass(alwaysRun = true)
public void closeBrowser()
{
LOG.info("Closing WebDrone!");
if (getBrowser() != null)
{
getBrowser().quit();
}
}
@BeforeMethod(alwaysRun = true)
public void startTest(final Method method) throws Exception {
LOG.info("***************************************************************************************************");
DateTime now = new DateTime();
LOG.info("*** {} *** Starting test {}:{} ", now.toString("HH:mm:ss"), method.getDeclaringClass().getSimpleName(), method.getName());
LOG.info("***************************************************************************************************");
}
@AfterMethod(alwaysRun = true)
public void endTest(final Method method, final ITestResult result) throws Exception {
LOG.info("***************************************************************************************************");
DateTime now = new DateTime();
LOG.info("*** {} *** Ending test {}:{} {} ({} s.)", now.toString("HH:mm:ss"), method.getDeclaringClass().getSimpleName(), method.getName(),
result.isSuccess() ? "SUCCESS" : "!!! FAILURE !!!",
(result.getEndMillis() - result.getStartMillis()) / 1000);
LOG.info("***************************************************************************************************");
}
public static WebBrowser getBrowser()
{
return browserThread.get();
}
private void initializeBrowser() throws ClassNotFoundException
{
/* get all autowired annotated children of this class */
ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(true);
provider.addIncludeFilter(new AssignableTypeFilter(this.getClass()));
Set<BeanDefinition> components = provider.findCandidateComponents(getPageObjectRootPackage());
for (BeanDefinition component : components)
{
@SuppressWarnings("rawtypes")
Class pageObject = Class.forName(component.getBeanClassName());
//System.out.println("Page Object: " + pageObject.getName());
/*
* only for HtmlPage base classes
*/
if (pageObject.getClass().isInstance(HtmlPage.class))
{
try
{
@SuppressWarnings("unchecked")
Object bean = applicationContext.getBean(pageObject);
if (bean instanceof HtmlPage)
{
HtmlPage page = (HtmlPage) bean;
page.setBrowser(getBrowser());
}
}
catch (NoSuchBeanDefinitionException e)
{
continue;
}
}
}
}
public abstract String getPageObjectRootPackage();
}
| 37.453782 | 149 | 0.584474 |
f99ae6261be0c1f4b7af020ceb26b668d3003c71 | 288 | package com.bigkoo.pickerview.listener;
import android.view.View;
import com.bigkoo.pickerview.view.BasePickerView;
/**
* Created by KyuYi on 2017/3/2.
* E-Mail:[email protected]
* 功能:
*/
public interface CustomListener {
void customLayout(BasePickerView pickerView, View v);
}
| 18 | 57 | 0.743056 |
3911b8b238cc488750947f3a7c62e72e4fec6ca7 | 596 | package ocp.chap2DesignPatternsAndPrinciples;
public class LambdaExample {
@FunctionalInterface
public interface NoReturnType {
void test();
}
public static void noReturnType(NoReturnType l) {
l.test();
}
public static void main(String... args) {
// TODO
// Allowed
noReturnType(() -> System.out.println("hello"));
// Do not compile
// noReturnType( -> System.out.println());
// => If 0 parameter, parenthesis are mandatory
/* () mandatory if:
- 0 parameter
- Types are specified
{} braces mandatory if:
- return ;
- more than one line
*/
}
}
| 18.060606 | 50 | 0.65604 |
93ad15cd6ea9514db8c6bbe6583989ce1982a736 | 1,609 | package com.github.mariemmezghani.topnews.Model;
public class Source {
private String id;
private String name;
private String description;
private String url;
private String category;
private String language;
private String country;
public Source(String id, String name, String description, String url, String category, String language, String country) {
this.id = id;
this.name = name;
this.description = description;
this.url = url;
this.category = category;
this.language = language;
this.country = country;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
| 20.628205 | 125 | 0.602859 |
dc67868a13c8cc469831c36646e5b98db28803db | 88 | package packageA;
public class classA2 {
public classA1 a1;
public void foo() {}
}
| 11 | 22 | 0.693182 |
ee4b0ac5d52df48015569be9492da686626d2eac | 11,407 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package crjpa;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import crjpa.exceptions.IllegalOrphanException;
import crjpa.exceptions.NonexistentEntityException;
import crjpa.exceptions.PreexistingEntityException;
/**
*
* @author eve0014321
* @version $Revision: 1.0 $
*/
public class CuentacreditoJpaController implements Serializable {
/**
* Constructor for CuentacreditoJpaController.
*
* @param emf
* EntityManagerFactory
*/
public CuentacreditoJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
/**
* Field emf.
*/
private EntityManagerFactory emf = null;
/**
* Method getEntityManager.
*
* @return EntityManager
*/
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
/**
* Method create.
*
* @param cuentacredito
* Cuentacredito
* @throws PreexistingEntityException
* @throws Exception
*/
public void create(Cuentacredito cuentacredito) throws PreexistingEntityException, Exception {
if (cuentacredito.getPagocreditoList() == null) {
cuentacredito.setPagocreditoList(new ArrayList<Pagocredito>());
}
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cliente numeroIdentificacionCliente = cuentacredito.getNumeroIdentificacionCliente();
if (numeroIdentificacionCliente != null) {
numeroIdentificacionCliente = em.getReference(numeroIdentificacionCliente.getClass(),
numeroIdentificacionCliente.getNumeroIdentificacionCliente());
cuentacredito.setNumeroIdentificacionCliente(numeroIdentificacionCliente);
}
List<Pagocredito> attachedPagocreditoList = new ArrayList<Pagocredito>();
for (Pagocredito pagocreditoListPagocreditoToAttach : cuentacredito.getPagocreditoList()) {
pagocreditoListPagocreditoToAttach = em.getReference(pagocreditoListPagocreditoToAttach.getClass(),
pagocreditoListPagocreditoToAttach.getId());
attachedPagocreditoList.add(pagocreditoListPagocreditoToAttach);
}
cuentacredito.setPagocreditoList(attachedPagocreditoList);
em.persist(cuentacredito);
if (numeroIdentificacionCliente != null) {
numeroIdentificacionCliente.getCuentacreditoList().add(cuentacredito);
numeroIdentificacionCliente = em.merge(numeroIdentificacionCliente);
}
for (Pagocredito pagocreditoListPagocredito : cuentacredito.getPagocreditoList()) {
Cuentacredito oldIdCuentacreditoOfPagocreditoListPagocredito = pagocreditoListPagocredito
.getIdCuentacredito();
pagocreditoListPagocredito.setIdCuentacredito(cuentacredito);
pagocreditoListPagocredito = em.merge(pagocreditoListPagocredito);
if (oldIdCuentacreditoOfPagocreditoListPagocredito != null) {
oldIdCuentacreditoOfPagocreditoListPagocredito.getPagocreditoList().remove(
pagocreditoListPagocredito);
oldIdCuentacreditoOfPagocreditoListPagocredito = em
.merge(oldIdCuentacreditoOfPagocreditoListPagocredito);
}
}
em.getTransaction().commit();
} catch (Exception ex) {
if (findCuentacredito(cuentacredito.getId()) != null) {
throw new PreexistingEntityException("Cuentacredito " + cuentacredito + " already exists.", ex);
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
/**
* Method edit.
*
* @param cuentacredito
* Cuentacredito
* @throws IllegalOrphanException
* @throws NonexistentEntityException
* @throws Exception
*/
public void edit(Cuentacredito cuentacredito) throws IllegalOrphanException, NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cuentacredito persistentCuentacredito = em.find(Cuentacredito.class, cuentacredito.getId());
Cliente numeroIdentificacionClienteOld = persistentCuentacredito.getNumeroIdentificacionCliente();
Cliente numeroIdentificacionClienteNew = cuentacredito.getNumeroIdentificacionCliente();
List<Pagocredito> pagocreditoListOld = persistentCuentacredito.getPagocreditoList();
List<Pagocredito> pagocreditoListNew = cuentacredito.getPagocreditoList();
List<String> illegalOrphanMessages = null;
for (Pagocredito pagocreditoListOldPagocredito : pagocreditoListOld) {
if (!pagocreditoListNew.contains(pagocreditoListOldPagocredito)) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("You must retain Pagocredito " + pagocreditoListOldPagocredito
+ " since its idCuentacredito field is not nullable.");
}
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
if (numeroIdentificacionClienteNew != null) {
numeroIdentificacionClienteNew = em.getReference(numeroIdentificacionClienteNew.getClass(),
numeroIdentificacionClienteNew.getNumeroIdentificacionCliente());
cuentacredito.setNumeroIdentificacionCliente(numeroIdentificacionClienteNew);
}
List<Pagocredito> attachedPagocreditoListNew = new ArrayList<Pagocredito>();
for (Pagocredito pagocreditoListNewPagocreditoToAttach : pagocreditoListNew) {
pagocreditoListNewPagocreditoToAttach = em
.getReference(pagocreditoListNewPagocreditoToAttach.getClass(),
pagocreditoListNewPagocreditoToAttach.getId());
attachedPagocreditoListNew.add(pagocreditoListNewPagocreditoToAttach);
}
pagocreditoListNew = attachedPagocreditoListNew;
cuentacredito.setPagocreditoList(pagocreditoListNew);
cuentacredito = em.merge(cuentacredito);
if (numeroIdentificacionClienteOld != null
&& !numeroIdentificacionClienteOld.equals(numeroIdentificacionClienteNew)) {
numeroIdentificacionClienteOld.getCuentacreditoList().remove(cuentacredito);
numeroIdentificacionClienteOld = em.merge(numeroIdentificacionClienteOld);
}
if (numeroIdentificacionClienteNew != null
&& !numeroIdentificacionClienteNew.equals(numeroIdentificacionClienteOld)) {
numeroIdentificacionClienteNew.getCuentacreditoList().add(cuentacredito);
numeroIdentificacionClienteNew = em.merge(numeroIdentificacionClienteNew);
}
for (Pagocredito pagocreditoListNewPagocredito : pagocreditoListNew) {
if (!pagocreditoListOld.contains(pagocreditoListNewPagocredito)) {
Cuentacredito oldIdCuentacreditoOfPagocreditoListNewPagocredito = pagocreditoListNewPagocredito
.getIdCuentacredito();
pagocreditoListNewPagocredito.setIdCuentacredito(cuentacredito);
pagocreditoListNewPagocredito = em.merge(pagocreditoListNewPagocredito);
if (oldIdCuentacreditoOfPagocreditoListNewPagocredito != null
&& !oldIdCuentacreditoOfPagocreditoListNewPagocredito.equals(cuentacredito)) {
oldIdCuentacreditoOfPagocreditoListNewPagocredito.getPagocreditoList().remove(
pagocreditoListNewPagocredito);
oldIdCuentacreditoOfPagocreditoListNewPagocredito = em
.merge(oldIdCuentacreditoOfPagocreditoListNewPagocredito);
}
}
}
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Long id = cuentacredito.getId();
if (findCuentacredito(id) == null) {
throw new NonexistentEntityException("The cuentacredito with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
/**
* Method destroy.
*
* @param id
* Long
* @throws IllegalOrphanException
* @throws NonexistentEntityException
*/
public void destroy(Long id) throws IllegalOrphanException, NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cuentacredito cuentacredito;
try {
cuentacredito = em.getReference(Cuentacredito.class, id);
cuentacredito.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The cuentacredito with id " + id + " no longer exists.", enfe);
}
List<String> illegalOrphanMessages = null;
List<Pagocredito> pagocreditoListOrphanCheck = cuentacredito.getPagocreditoList();
for (Pagocredito pagocreditoListOrphanCheckPagocredito : pagocreditoListOrphanCheck) {
if (illegalOrphanMessages == null) {
illegalOrphanMessages = new ArrayList<String>();
}
illegalOrphanMessages.add("This Cuentacredito (" + cuentacredito
+ ") cannot be destroyed since the Pagocredito " + pagocreditoListOrphanCheckPagocredito
+ " in its pagocreditoList field has a non-nullable idCuentacredito field.");
}
if (illegalOrphanMessages != null) {
throw new IllegalOrphanException(illegalOrphanMessages);
}
Cliente numeroIdentificacionCliente = cuentacredito.getNumeroIdentificacionCliente();
if (numeroIdentificacionCliente != null) {
numeroIdentificacionCliente.getCuentacreditoList().remove(cuentacredito);
numeroIdentificacionCliente = em.merge(numeroIdentificacionCliente);
}
em.remove(cuentacredito);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
/**
* Method findCuentacreditoEntities.
*
* @return List<Cuentacredito>
*/
public List<Cuentacredito> findCuentacreditoEntities() {
return findCuentacreditoEntities(true, -1, -1);
}
/**
* Method findCuentacreditoEntities.
*
* @param maxResults
* int
* @param firstResult
* int
* @return List<Cuentacredito>
*/
public List<Cuentacredito> findCuentacreditoEntities(int maxResults, int firstResult) {
return findCuentacreditoEntities(false, maxResults, firstResult);
}
/**
* Method findCuentacreditoEntities.
*
* @param all
* boolean
* @param maxResults
* int
* @param firstResult
* int
* @return List<Cuentacredito>
*/
private List<Cuentacredito> findCuentacreditoEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Cuentacredito.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
/**
* Method findCuentacredito.
*
* @param id
* Long
* @return Cuentacredito
*/
public Cuentacredito findCuentacredito(Long id) {
EntityManager em = getEntityManager();
try {
return em.find(Cuentacredito.class, id);
} finally {
em.close();
}
}
/**
* Method getCuentacreditoCount.
*
* @return int
*/
public int getCuentacreditoCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Cuentacredito> rt = cq.from(Cuentacredito.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
| 34.358434 | 117 | 0.742702 |
1e74cbf8dd35da79b7d9d98cfe08fa50124ea3e1 | 2,797 | package com.github.snailycy.hybridlib.webview;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;
import android.widget.ProgressBar;
import com.github.snailycy.hybridlib.util.HybridCacheUtils;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* WebViewClient逻辑处理
*/
public class WebViewClientPresenter {
private ProgressBar mProgressBar;
/**
* 是否是白名单
*/
private boolean mIsWhiteList;
private ExecutorService mExecutorService = Executors.newFixedThreadPool(3);
private IWebViewClient mBizWebViewClient;
public WebViewClientPresenter(WrapperWebView webView) {
this.mProgressBar = webView.getProgressBar();
}
public void setBizWebViewClient(IWebViewClient bizWebViewClient) {
this.mBizWebViewClient = bizWebViewClient;
}
public void setIsWhiteList(boolean isWhiteList) {
this.mIsWhiteList = isWhiteList;
}
public void onPageStarted() {
mProgressBar.setVisibility(View.VISIBLE);
mProgressBar.setAlpha(1.0f);
}
/**
* 判断Uri是否需要拦截
*
* @param uri 网络URI
* @return 若需要拦截,返回WebResourceResponse;否则为null
*/
public WebResourceResponse shouldInterceptRequest(Uri uri) {
if (null == uri || null == uri.getPath()) {
return null;
}
// 判断请求是以下["css","js","jpg","jpeg","png","gif"]的资源,走本地缓存逻辑
if (HybridCacheUtils.mountedSDCard() && HybridCacheUtils.needCache(uri)) {
WebResourceResponse webResourceResponse = insteadOfCache(uri);
return webResourceResponse;
}
return null;
}
/**
* 检查是否有缓存,如有则读取本地缓存,否则缓存资源到本地
*
* @param uri 需要走缓存逻辑的网络请求URI
* @return 若本地有缓存,返回缓存资源;否则返回null
*/
private WebResourceResponse insteadOfCache(final Uri uri) {
if (null == uri) {
return null;
}
String uriPath = uri.getPath();
if (TextUtils.isEmpty(uriPath)) return null;
String localCachePath = HybridCacheUtils.convertUriToFilePath(uri);
// 如果缓存存在,则取缓存
if (HybridCacheUtils.checkPathExist(localCachePath)) {
try {
InputStream is = new FileInputStream(new File(localCachePath));
return new WebResourceResponse(HybridCacheUtils.getResourceType(uriPath), "UTF-8", is);
} catch (Exception e) {
e.printStackTrace();
}
} else {
// 不存在,缓存在本地
HybridCacheUtils.saveResource(uri, HybridCacheUtils.convertUriToFilePath(uri), null);
}
return null;
}
}
| 28.540816 | 103 | 0.658563 |
e550c346089d0f3eed4be7f8f8f47198dab9e275 | 732 | package me.chanjar.weixin.mp.bean.guide;
import com.google.gson.annotations.SerializedName;
import lombok.Data;
import me.chanjar.weixin.common.util.json.WxGsonBuilder;
import java.io.Serializable;
import java.util.List;
/**
* 顾问列表.
*
* @author <a href="https://github.com/binarywang">Binary Wang</a>
* @date 2020-10-07
*/
@Data
public class WxMpGuideList implements Serializable {
private static final long serialVersionUID = 144044550239346216L;
/**
* 顾问总数量
*/
@SerializedName("total_num")
private Integer totalNum;
/**
* 顾问列表
*/
private List<WxMpGuideInfo> list;
public static WxMpGuideList fromJson(String json) {
return WxGsonBuilder.create().fromJson(json, WxMpGuideList.class);
}
}
| 20.914286 | 70 | 0.726776 |
2a3e0f9973bb4d045c3af10a5de1b3575286f167 | 962 | package com.stm.login.base.view;
import com.nhn.android.naverlogin.OAuthLoginHandler;
import com.stm.common.dao.User;
/**
* Created by ㅇㅇ on 2017-06-20.
*/
public interface LoginView {
void init();
void initFacebookSdk();
void initNaverOauthLogin();
void setNaverOAuthLoginHandler(OAuthLoginHandler oAuthLoginHandler);
void setToolbarLayout();
String getNaverOAuthResponse();
void onClickBack();
void onClickLogin();
void onClickFacebookLogin();
void onClickNaverLogin();
void onClickFindPwd();
void onClickJoin();
void showToolbarTitle(String message);
void showMessage(String message);
void navigateToJoinCategoryActivity();
void navigateToJoinCategoryActivity(User user);
void setUser(User user);
User getUser();
void navigateToBack();
void navigateToOauthLoginActivity(OAuthLoginHandler oAuthLoginHandler);
void navigateToFindPasswordActivity();
}
| 17.814815 | 75 | 0.723493 |
b66410d6e39309b809259be0469338fa31d0ff48 | 2,221 | package com.belonk.lang.classes;
import com.belonk.util.Printer;
interface Action {
}
interface Size {
}
// 玩具
class Toy {
Toy() {
}
Toy(int i) {
}
}
// 益智玩具
class FancyToy extends Toy implements Action, Size {
FancyToy() {
super(1);
}
}
/**
* <p>Created by sun on 2016/1/14.
*
* @author sun
* @version 1.0
* @since 2.2.3
*/
public class TypeInfo {
//~ Static fields/initializers =====================================================================================
//~ Instance fields ================================================================================================
//~ Methods ========================================================================================================
/**
* 打印类型信息。
*
* @param aClass
*/
static void printInfo(Class aClass) {
Printer.println("Class name : " + aClass.getName() + " is interface? [" + aClass.isInterface() + "]");
Printer.println("Simple name : " + aClass.getSimpleName());
Printer.println("Canonical name : " + aClass.getCanonicalName());
}
public static void main(String[] args) {
String className = "com.belonk.lang.classes.FancyToy";
Class c = null;
try {
// 自动初始化类
c = Class.forName(className);
} catch (ClassNotFoundException e) {
Printer.println(className + " not fount.");
}
printInfo(c);
Printer.println();
for (Class aClass : c.getInterfaces()) {
printInfo(aClass);
}
Printer.println();
Class superClass = c.getSuperclass();
Object obj = null;
try {
obj = superClass.newInstance();
} catch (InstantiationException e) {
// 如果注释掉Toy的默认构造器,无法成功创建
Printer.println("Super class can not instantiate.");
System.exit(1);
} catch (IllegalAccessException e) {
Printer.println("Super class can not access.");
System.exit(1);
}
printInfo(obj.getClass());
}
}
/* Output :
Class name : FancyToy is interface? [false]
Simple name : FancyToy
Canonical name : FancyToy
Class name : Action is interface? [true]
Simple name : Action
Canonical name : Action
Class name : Size is interface? [true]
Simple name : Size
Canonical name : Size
Class name : Toy is interface? [false]
Simple name : Toy
Canonical name : Toy
*/ | 22.434343 | 117 | 0.564611 |
3a400f6932ddf9b8366eed36802fea2c1f549d1d | 1,620 | package com.wareninja.opensource.ip2location.config;
import org.yaml.snakeyaml.Yaml;
import java.io.File;
import java.io.FileInputStream;
public class FileConfiguration {
private final String parameter;
public FileConfiguration(String parameter) {
this.parameter = parameter;
}
public YamlConfiguration getFileContent() {
YamlConfiguration config = null;
try {
File ymlFile = new File(parameter);
Yaml yaml = new Yaml();
if (ymlFile.isFile()) {
FileInputStream configFile = new FileInputStream(ymlFile);
config = yaml.loadAs(configFile, YamlConfiguration.class);
}
else {
// we expect that this is just a string including yaml format
config = yaml.loadAs(parameter, YamlConfiguration.class);
}
} catch (Exception e) {
System.err.println(e.getMessage() + " | " + e.fillInStackTrace());
}
return config;
}
/*private YamlConfiguration controlAsSettings(YamlConfiguration config) {
String dIndexAs = config.getMisc().getDindex().getAs();
String cTypeAs = config.getMisc().getCtype().getAs();
if (Objects.isNull(dIndexAs))
config.getMisc().getDindex().setAs(config.getMisc().getDindex().getName());
if (Objects.isNull(cTypeAs))
config.getMisc().getCtype().setAs(config.getMisc().getCtype().getName());
if (config.getMisc().getBatch() < 200)
config.getMisc().setBatch(200);
return config;
}*/
}
| 31.764706 | 87 | 0.60679 |
9c838c0477a08103c43ca3c2a83bad3b40b614bd | 616 | package com.andcreations.ae.tex.pack.gen;
import java.io.File;
import java.util.List;
import com.andcreations.ae.tex.pack.TexPackerCfg;
/**
* @author Mikolaj Gucki
*/
public class TexPackGenCfg {
/** */
private TexPackerCfg cfg;
/** */
private List<File> dirs;
/** */
public TexPackGenCfg(TexPackerCfg cfg,List<File> dirs) {
this.cfg = cfg;
this.dirs = dirs;
}
/** */
public TexPackerCfg getTexPackerCfg() {
return cfg;
}
/** */
public List<File> getDirs() {
return dirs;
}
} | 18.666667 | 61 | 0.542208 |
b0bc9d6bdc434cb2c8e5fb1fa4984d4aae50f6b1 | 3,201 | /*******************************************************************************
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package emlab.gen.util;
import static org.junit.Assert.assertEquals;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.neo4j.template.Neo4jOperations;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
import emlab.gen.trend.TriangularTrend;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/emlab-gen-test-context.xml" })
@Transactional
public class TriangularTrendTest {
Logger logger = Logger.getLogger(GeometricTrendRegressionTest.class);
@Autowired
Neo4jOperations template;
@Test
public void testTriangularTrendGeneration() {
TriangularTrend tt = new TriangularTrend();
tt.setStart(1);
tt.setMax(1.03);
tt.setMin(1.01);
tt.setTop(1.02);
tt.persist();
double[][] triangularTrendAndForecast = new double[2][20];
for (int i = 0; i < 20; i++) {
triangularTrendAndForecast[0][i] = i;
triangularTrendAndForecast[1][i] = tt.getValue(i);
}
for (int i = 19; i >= 0; i--) {
assertEquals(triangularTrendAndForecast[1][i], tt.getValue(i), 0.0);
}
}
@Test
public void compareTrendToGeometricForecasting() {
TriangularTrend tt = new TriangularTrend();
tt.setStart(1);
tt.setMax(1.00);
tt.setMin(1.00);
tt.setTop(1.00);
tt.persist();
double[][] triangularTrendAndForecast = new double[3][50];
for (int i = 0; i < 50; i++) {
triangularTrendAndForecast[0][i] = i;
triangularTrendAndForecast[1][i] = tt.getValue(i);
}
int futureHorizon = 7;
for (int futureTime = 2 + futureHorizon; futureTime < 50; futureTime++) {
GeometricTrendRegression gtr = new GeometricTrendRegression();
for (long time = futureTime - 5; time > futureTime - 10
&& time >= 0; time = time - 1) {
gtr.addData(time, tt.getValue(time));
// logger.warn(time + "\t" + tt.getValue(time));
}
triangularTrendAndForecast[2][futureTime] = gtr.predict(futureTime);
}
for (int i = 9; i < 50; i++) {
// logger.warn(triangularTrendAndForecast[0][i] + "\t" +
// (triangularTrendAndForecast[2][i]-triangularTrendAndForecast[1][i])/triangularTrendAndForecast[1][i]);
assertEquals(triangularTrendAndForecast[2][i]
- triangularTrendAndForecast[1][i], 0.0, 0.00);
}
}
}
| 34.419355 | 108 | 0.685411 |
bcf5e013ad3b46100d3a29ec88456e6a40fa652f | 249 | package no.nav.foreldrepenger.mottak.queue;
import no.nav.foreldrepenger.no.nav.spmottak.meldinger.dokumentnotifikasjonv1.Forsendelsesinformasjon;
public interface MeldingsFordeler {
void execute(Forsendelsesinformasjon forsendelsesinfo);
}
| 24.9 | 102 | 0.843373 |
889f86a198f8e46066f3da51a06d0e6d24e477f1 | 1,979 | package com.mzr.tort.core.dto.utils;
import org.apache.commons.lang3.Validate;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.Map;
public final class TypeUtils extends org.apache.commons.lang3.reflect.TypeUtils {
private TypeUtils() {
}
public static <T extends Type> T getTypeArgument(Type aType, Class<?> aGeneric, String typeArgName) {
Map<TypeVariable<?>, Type> map = getTypeArguments(aType, aGeneric);
for (Map.Entry<TypeVariable<?>, Type> entry : map.entrySet()) {
if (aGeneric.equals(entry.getKey().getGenericDeclaration()) && entry.getKey().getName().equals(typeArgName)) {
return (T) entry.getValue();
}
}
return null;
}
public static <T extends Type> T getTypeArgument(Type aType, Class<?> aGeneric) {
Map<TypeVariable<?>, Type> map = getTypeArguments(aType, aGeneric);
for (Map.Entry<TypeVariable<?>, Type> entry : map.entrySet()) {
if (aGeneric.equals(entry.getKey().getGenericDeclaration())) {
// noinspection unchecked
return (T) entry.getValue();
}
}
return null;
}
public static Class<?> getClassArgument(Prop fieldDef, Class<?> aGeneric) {
Type typeArgument = getTypeArgument(fieldDef.getReadMethod().getGenericReturnType(), aGeneric);
if (typeArgument instanceof Class) {
return (Class<?>) typeArgument;
} else if (typeArgument instanceof TypeVariable) {
TypeVariable typeVariable = (TypeVariable) typeArgument;
return (Class<?>) Validate.notNull(getTypeArguments(fieldDef.getOwnerClass(),
(Class<?>) typeVariable.getGenericDeclaration()).get(typeVariable));
} else {
throw new IllegalArgumentException(String.format("Невозможно определить дженерик '%s' для '%s'", aGeneric,
fieldDef));
}
}
}
| 39.58 | 122 | 0.634664 |
def2f038fd6199905d388961419efdc58334d581 | 750 | package org.pcsoft.framework.jnode3d;
import org.junit.Test;
import org.pcsoft.framework.jnode3d.camera.PerspectiveLookAtCamera;
import org.pcsoft.framework.jnode3d.internal.JNode3DInternalScene;
import org.pcsoft.framework.jnode3d.node.BoxNode;
import org.pcsoft.framework.jnode3d.node.GroupNode;
import org.pcsoft.framework.jnode3d.node.PointLightNode;
public class SceneTest extends PseudoGLTest {
@Test
public void test() {
scene.setCamera(new PerspectiveLookAtCamera());
final GroupNode groupNode = new GroupNode();
groupNode.getChildren().add(new BoxNode());
groupNode.getChildren().add(new PointLightNode());
scene.setRoot(groupNode);
((JNode3DInternalScene)scene).loop();
}
}
| 30 | 67 | 0.745333 |
bbfe9f7dbbb2356d22aff2573e69d9b28271d0c7 | 14,038 | /* Copyright (C) 2005-2011 Fabio Riccardi */
package com.lightcrafts.jai.opimage;
import com.lightcrafts.media.jai.util.ImageUtil;
import com.lightcrafts.media.jai.util.JDKWorkarounds;
import com.lightcrafts.jai.LCROIShape;
import com.lightcrafts.mediax.jai.*;
import java.awt.image.*;
import java.awt.*;
import java.awt.color.ColorSpace;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: fabio
* Date: Apr 1, 2005
* Time: 9:54:39 AM
* To change this template use File | Settings | File Templates.
*/
public class BlendOpImage extends PointOpImage {
/* Source 1 band increment */
private int s1bd = 1;
/* Source 2 band increment */
private int s2bd = 1;
/* Bilevel data flag. */
private boolean areBinarySampleModels = false;
private int blendModeId;
private double opacity;
private ROI mask;
private final RenderedImage colorSelection;
public enum BlendingMode {
NORMAL ("Normal", 0),
AVERAGE ("Average", 1),
MULTIPLY ("Multiply", 2),
SCREEN ("Screen", 3),
DARKEN ("Darken", 4),
LIGHTEN ("Lighten", 5),
DIFFERENCE ("Difference", 6),
NEGATION ("Negation", 7),
EXCLUSION ("Exclusion", 8),
OVERLAY ("Overlay", 9),
HARD_LIGHT ("Hard Light", 10),
SOFT_LIGHT ("Soft Light", 11),
COLOR_DODGE ("Color Dodge", 12),
COLOR_BURN ("Color Burn", 13),
SOFT_DODGE ("Soft Dodge", 14),
SOFT_BURN ("Soft Burn", 15),
/*
SOFT_LIGHT2 ("Soft Light 2", 16),
SOFT_LIGHT3 ("Soft Light 3", 17),
SOFT_LIGHT4 ("Soft Light 4", 18),
*/
SHADOWS ("Shadows", 19),
MID_HILIGHTS("Mid+Hilights",20),
MIDTONES ("Midtones", 21);
BlendingMode(String value, int id) {
this.name = value;
this.id = id;
}
private final String name;
private final int id;
public String getName() { return name; }
}
private static Map<String, BlendingMode> modes = new HashMap<String, BlendingMode>();
static {
for (BlendingMode b : BlendingMode.values())
modes.put(b.name, b);
}
public static Set<String> availableModes() {
return modes.keySet();
}
public BlendOpImage(RenderedImage source1,
RenderedImage source2,
String blendingMode,
Double opacity,
ROI mask,
RenderedImage colorSelection,
Map config,
ImageLayout layout) {
super(source1, source2, layout, config, true);
if (source1.getSampleModel().getDataType() != DataBuffer.TYPE_USHORT
|| source2.getSampleModel().getDataType() != DataBuffer.TYPE_USHORT) {
throw new RuntimeException("Unsupported data type, only USHORT allowed.");
}
BlendingMode mode = modes.get(blendingMode);
if (mode != null) {
blendModeId = mode.id;
} else {
String className = this.getClass().getName();
throw new RuntimeException(className +
" unrecognized blending mode: " + blendingMode);
}
this.opacity = opacity.floatValue();
if(ImageUtil.isBinary(getSampleModel()) &&
ImageUtil.isBinary(source1.getSampleModel()) &&
ImageUtil.isBinary(source2.getSampleModel())) {
// Binary processing case: RasterAccessor
areBinarySampleModels = true;
} else {
// Get the source band counts.
int numBands1 = source1.getSampleModel().getNumBands();
int numBands2 = source2.getSampleModel().getNumBands();
// Handle the special case of adding a single band image to
// each band of a multi-band image.
int numBandsDst;
if(layout != null && layout.isValid(ImageLayout.SAMPLE_MODEL_MASK)) {
SampleModel sm = layout.getSampleModel(null);
numBandsDst = sm.getNumBands();
// One of the sources must be single-banded and the other must
// have at most the number of bands in the SampleModel hint.
if(numBandsDst > 1 &&
((numBands1 == 1 && numBands2 > 1) ||
(numBands2 == 1 && numBands1 > 1))) {
// Clamp the destination band count to the number of
// bands in the multi-band source.
numBandsDst = Math.min(Math.max(numBands1, numBands2),
numBandsDst);
// Create a new SampleModel if necessary.
if(numBandsDst != sampleModel.getNumBands()) {
sampleModel =
RasterFactory.createComponentSampleModel(
sm,
sampleModel.getTransferType(),
sampleModel.getWidth(),
sampleModel.getHeight(),
numBandsDst);
if(colorModel != null &&
!JDKWorkarounds.areCompatibleDataModels(sampleModel,
colorModel)) {
colorModel =
ImageUtil.getCompatibleColorModel(sampleModel,
config);
}
}
// Set the source band increments.
s1bd = numBands1 == 1 ? 0 : 1;
s2bd = numBands2 == 1 ? 0 : 1;
}
}
}
this.mask = mask;
// TODO: ensure that the geometry and tiling of the sources and that of the color selection match
this.colorSelection = colorSelection;
// Do not set flag to permit in-place operation, we dpn't produce unique tiles.
// permitInPlaceOperation();
}
// We can return source tiles directly
public boolean computesUniqueTiles() {
return false;
}
public boolean hasMask() {
return mask != null;
}
public Raster getTile(int tileX, int tileY) {
Rectangle destRect = this.getTileRect(tileX, tileY);
if (hasMask())
if (!mask.intersects(destRect)) {
if (opacity > 0)
return this.getSourceImage(1).getTile(tileX, tileY);
// Not a good idea, can come out with teh wrong number of bands
/* else if (opacity == -1)
return this.getSourceImage(0).getTile(tileX, tileY); */
}
return super.getTile(tileX, tileY);
}
ColorModel grayCm = new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_GRAY),
false, false,
Transparency.OPAQUE,
DataBuffer.TYPE_BYTE);
/**
* Adds the pixel values of two source images within a specified
* rectangle.
*
* @param sources Cobbled sources, guaranteed to provide all the
* source data necessary for computing the rectangle.
* @param dest The tile containing the rectangle to be computed.
* @param destRect The rectangle within the tile to be computed.
*/
protected void computeRect(Raster[] sources,
WritableRaster dest,
Rectangle destRect) {
if(areBinarySampleModels) {
String className = this.getClass().getName();
throw new RuntimeException(className +
" does not implement computeRect" +
" for binary data");
}
// Retrieve format tags.
RasterFormatTag[] formatTags = getFormatTags();
RasterAccessor s1 = new RasterAccessor(sources[0], destRect,
formatTags[0],
getSourceImage(0).getColorModel());
RasterAccessor s2 = new RasterAccessor(sources[1], destRect,
formatTags[1],
getSourceImage(1).getColorModel());
RasterAccessor d = new RasterAccessor(dest, destRect,
formatTags[2], getColorModel());
Raster roi = null;
if (hasMask()) {
LCROIShape lcROI = (LCROIShape) mask;
if (lcROI.intersects(destRect))
roi = lcROI.getData(destRect);
else {
if (opacity > 0) {
assert dest.getBounds().equals(sources[1].getBounds());
// dest.setRect(sources[1]);
JDKWorkarounds.setRect(dest, sources[1], 0, 0);
return;
}
// Not a good idea, can come out with teh wrong number of bands
/* else if (opacity == -1) {
assert dest.getBounds().equals(sources[0].getBounds());
// dest.setRect(sources[0]);
JDKWorkarounds.setRect(dest, sources[0], 0, 0);
return;
} */
}
}
RasterAccessor m = null;
if (roi != null) {
SampleModel roiSM = roi.getSampleModel();
int roiFormatTagID = RasterAccessor.findCompatibleTag(null, roiSM);
RasterFormatTag roiFormatTag = new RasterFormatTag(roiSM, roiFormatTagID);
m = new RasterAccessor(roi, destRect, roiFormatTag, grayCm);
}
RasterAccessor cs = null;
if (colorSelection != null) {
int tilex = sources[0].getMinX() / sources[0].getWidth();
int tiley = sources[0].getMinY() / sources[0].getHeight();
Raster csRaster = colorSelection.getTile(tilex, tiley);
if (csRaster == null) {
csRaster = colorSelection.getData(destRect);
}
SampleModel csRasterSM = csRaster.getSampleModel();
int csRasterFormatTagID = RasterAccessor.findCompatibleTag(null, csRasterSM);
RasterFormatTag csRasterFormatTag = new RasterFormatTag(csRasterSM, csRasterFormatTagID);
cs = new RasterAccessor(csRaster, destRect, csRasterFormatTag, grayCm);
}
switch (d.getDataType()) {
case DataBuffer.TYPE_USHORT:
computeRectUShort(s1, s2, m, cs, d);
break;
default:
throw new UnsupportedOperationException("Unsupported data type: " + d.getDataType());
}
if (d.needsClamping()) {
d.clampDataArrays();
}
d.copyDataToRaster();
}
// TODO: This code only works with Pixel Interleaved sources enforce it!
private void computeRectUShort(RasterAccessor src1,
RasterAccessor src2,
RasterAccessor mask,
RasterAccessor colorSelection,
RasterAccessor dst) {
int s1LineStride = src1.getScanlineStride();
int s1PixelStride = src1.getPixelStride();
int[] s1BandOffsets = src1.getBandOffsets();
short[][] s1Data = src1.getShortDataArrays();
int s2LineStride = src2.getScanlineStride();
int s2PixelStride = src2.getPixelStride();
int[] s2BandOffsets = src2.getBandOffsets();
short[][] s2Data = src2.getShortDataArrays();
int mLineStride = 0;
int mPixelStride = 0;
int mBandOffset = 0;
byte[] mData = null;
if (mask != null) {
mLineStride = mask.getScanlineStride();
mPixelStride = mask.getPixelStride();
mBandOffset = mask.getBandOffsets()[0];
mData = mask.getByteDataArrays()[0];
}
int csLineStride = 0;
int csPixelStride = 0;
int csBandOffset = 0;
byte[] csData = null;
if (colorSelection != null) {
csLineStride = colorSelection.getScanlineStride();
csPixelStride = colorSelection.getPixelStride();
csBandOffset = colorSelection.getBandOffsets()[0];
csData = colorSelection.getByteDataArrays()[0];
}
int dwidth = dst.getWidth();
int dheight = dst.getHeight();
int bands = dst.getNumBands();
int dLineStride = dst.getScanlineStride();
int dPixelStride = dst.getPixelStride();
int[] dBandOffsets = dst.getBandOffsets();
short[][] dData = dst.getShortDataArrays();
int intOpacity = (int) (0xFFFF * opacity + 0.5);
short[] s1 = s1Data[0];
short[] s2 = s2Data[0];
byte[] m = mData;
byte[] cs = csData;
short[] d = dData[0];
int s1LineOffset = s1BandOffsets[0];
int s2LineOffset = s2BandOffsets[0];
int mLineOffset = mBandOffset;
int csLineOffset = csBandOffset;
int dLineOffset = dBandOffsets[0];
PixelBlender.cUShortLoopCS(s1, s2, d, m, cs,
bands, s1bd, s2bd,
s1LineOffset, s2LineOffset, dLineOffset, mLineOffset, csLineOffset,
s1LineStride, s2LineStride, dLineStride, mLineStride, csLineStride,
s1PixelStride, s2PixelStride, dPixelStride, mPixelStride, csPixelStride,
dheight, dwidth, intOpacity, blendModeId);
}
}
| 37.736559 | 107 | 0.528423 |
15d182f9a10556d7ce4d636fa1a8a89b32559714 | 4,191 | package com.ohmybug.web;
import com.ohmybug.pojo.Grade;
import com.ohmybug.pojo.Page;
import com.ohmybug.pojo.Student;
import com.ohmybug.pojo.T_Class;
import com.ohmybug.service.GradeService;
import com.ohmybug.service.StudentService;
import com.ohmybug.service.T_ClassService;
import com.ohmybug.service.impl.GradeServiceImpl;
import com.ohmybug.service.impl.StudentServiceImpl;
import com.ohmybug.service.impl.T_ClassServiceImpl;
import com.ohmybug.utils.WebUtils;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
/**
* ClassName: StudentServlet
* Data: 2020/9/1
* author: Oh_MyBug
* version: V1.0
*/
public class StudentServlet extends BaseServlet {
private final StudentService studentService = new StudentServiceImpl();
private final GradeService gradeService = new GradeServiceImpl();
private final T_ClassService t_classService = new T_ClassServiceImpl();
protected void page(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 1);
int pageSize = WebUtils.parseInt(req.getParameter("pageSize"), Page.PAGE_SIZE);
Page<Student> page = studentService.page(pageNo, pageSize);
page.setUrl("admin/studentServlet?action=page&page=student");
req.setAttribute("page", page);
req.getRequestDispatcher("/pages/admin/student_manage.jsp").forward(req, resp);
}
protected void getSelectorList(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
List<Grade> grades = gradeService.queryGrades();
List<T_Class> t_classes = t_classService.queryT_Classs();
req.setAttribute("grades", grades);
req.setAttribute("t_classes", t_classes);
req.getRequestDispatcher("/pages/admin/student_edit.jsp").forward(req, resp);
}
protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Student student = WebUtils.copyParamToBean(req.getParameterMap(), new Student());
int addStudent = studentService.addStudent(student);
if (addStudent == -1) {
student.setId(null);
req.setAttribute("student", student);
req.getRequestDispatcher("studentServlet?action=getSelectorList").forward(req, resp);
} else {
int pageNo = WebUtils.parseInt(req.getParameter("pageNo"), 0);
pageNo += 1;
resp.sendRedirect(req.getContextPath() + "/admin/studentServlet?action=list&page=student&pageNo=" + pageNo);
}
}
protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Student student = WebUtils.copyParamToBean(req.getParameterMap(), new Student());
studentService.updateStudent(student);
resp.sendRedirect(req.getContextPath() + "/admin/studentServlet?action=page&page=student&pageNo=" + req.getParameter("pageNo"));
}
protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = WebUtils.parseInt(req.getParameter("id"), 0);
studentService.deleteStudentById(id);
resp.sendRedirect(req.getContextPath() + "/admin/studentServlet?action=page&page=student&pageNo=" + req.getParameter("pageNo"));
}
protected void getStudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int id = WebUtils.parseInt(req.getParameter("id"), 0);
Student student = studentService.queryStudentById(id);
req.setAttribute("student", student);
getSelectorList(req, resp);
}
protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
List<Student> students = studentService.queryStudents();
req.setAttribute("students", students);
req.getRequestDispatcher("/pages/admin/student_manage.jsp").forward(req, resp);
}
}
| 46.566667 | 136 | 0.724409 |
1b1b0f03261c26e3fe2d17c96f63e3072076dd18 | 18,138 | /*
See the NOTICE file distributed with this work for additional
information regarding copyright ownership.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package io.sf.carte.echosvg.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* This class represents an object which queues Runnable objects for invocation
* in a single thread.
*
* @author <a href="mailto:[email protected]">Stephane Hillion</a>
* @author For later modifications, see Git history.
* @version $Id$
*/
public class RunnableQueue implements Runnable {
/**
* Type-safe enumeration of queue states.
*/
public static final class RunnableQueueState {
private final String value;
private RunnableQueueState(String value) {
this.value = value;
}
public String getValue() {
return value;
}
@Override
public String toString() {
return "[RunnableQueueState: " + value + ']';
}
}
/**
* The queue is in the process of running tasks.
*/
public static final RunnableQueueState RUNNING = new RunnableQueueState("Running");
/**
* The queue may still be running tasks but as soon as possible will go to
* SUSPENDED state.
*/
public static final RunnableQueueState SUSPENDING = new RunnableQueueState("Suspending");
/**
* The queue is no longer running any tasks and will not run any tasks until
* resumeExecution is called.
*/
public static final RunnableQueueState SUSPENDED = new RunnableQueueState("Suspended");
/**
* The Suspension state of this thread.
*/
protected volatile RunnableQueueState state;
/**
* Object to synchronize/wait/notify for suspension issues.
*/
protected final Object stateLock = new Object();
/**
* Used to indicate if the queue was resumed while still running, so a 'resumed'
* event can be sent.
*/
protected boolean wasResumed;
/**
* The Runnable objects list, also used as synchronization point for
* pushing/poping runables.
*/
private final DoublyLinkedList list = new DoublyLinkedList();
/**
* Count of preempt entries in queue, so preempt entries can be kept properly
* ordered.
*/
protected int preemptCount;
/**
* The object which handle run events.
*/
protected RunHandler runHandler;
/**
* The current thread.
*/
protected volatile HaltingThread runnableQueueThread;
/**
* The {@link IdleRunnable} to run if the queue is empty.
*/
private IdleRunnable idleRunnable;
/**
* The time (in milliseconds) that the idle runnable should be run next.
*/
private long idleRunnableWaitTime;
/**
* Creates a new RunnableQueue started in a new thread.
*
* @return a RunnableQueue which is guaranteed to have entered its
* <code>run()</code> method.
*/
public static RunnableQueue createRunnableQueue() {
RunnableQueue result = new RunnableQueue();
synchronized (result) {
// Sync on the new object, so we can wait until the new
// thread is ready to go.
HaltingThread ht = new HaltingThread(result, "RunnableQueue-" + threadCount++);
ht.setDaemon(true);
ht.start();
while (result.getThread() == null) {
try {
result.wait();
} catch (InterruptedException ie) {
}
}
}
return result;
}
private static volatile int threadCount;
/**
* Runs this queue.
*/
@Override
public void run() {
synchronized (this) {
runnableQueueThread = (HaltingThread) Thread.currentThread();
// Wake the create method so it knows we are in
// our run and ready to go.
notify();
}
Link l;
Runnable rable;
try {
while (!HaltingThread.hasBeenHalted()) {
boolean callSuspended = false;
boolean callResumed = false;
// Mutex for suspension work.
synchronized (stateLock) {
if (state != RUNNING) {
state = SUSPENDED;
callSuspended = true;
}
}
if (callSuspended)
executionSuspended();
synchronized (stateLock) {
while (state != RUNNING) {
state = SUSPENDED;
// notify suspendExecution in case it is
// waiting til we shut down.
stateLock.notifyAll();
// Wait until resumeExecution called.
try {
stateLock.wait();
} catch (InterruptedException ie) {
}
}
if (wasResumed) {
wasResumed = false;
callResumed = true;
}
}
if (callResumed)
executionResumed();
// The following seriously stress tests the class
// for stuff happening between the two sync blocks.
//
// try {
// Thread.sleep(1);
// } catch (InterruptedException ie) { }
synchronized (list) {
if (state == SUSPENDING)
continue;
l = (Link) list.pop();
if (preemptCount != 0)
preemptCount--;
if (l == null) {
// No item to run, see if there is an idle runnable
// to run instead.
if (idleRunnable != null
&& (idleRunnableWaitTime = idleRunnable.getWaitTime()) < System.currentTimeMillis()) {
rable = idleRunnable;
} else {
// Wait for a runnable.
try {
if (idleRunnable != null && idleRunnableWaitTime != Long.MAX_VALUE) {
long t = idleRunnableWaitTime - System.currentTimeMillis();
if (t > 0) {
list.wait(t);
}
} else {
list.wait();
}
} catch (InterruptedException ie) {
// just loop again.
}
continue; // start loop over again...
}
} else {
rable = l.runnable;
}
}
try {
runnableStart(rable);
rable.run();
} catch (ThreadDeath td) {
// Let it kill us...
throw td;
} catch (Throwable t) {
// Might be nice to notify someone directly.
// But this is more or less what Swing does.
t.printStackTrace();
}
// Notify something waiting on the runnable just completed,
// if we just ran one from the queue.
if (l != null) {
l.unlock();
}
try {
runnableInvoked(rable);
} catch (ThreadDeath td) {
// Let it kill us...
throw td;
} catch (Throwable t) {
// Might be nice to notify someone directly.
// But this is more or less what Swing does.
t.printStackTrace();
}
}
} finally {
do {
// Empty the list of pending runnables and unlock them (so
// invokeAndWait will return).
// It's up to the runnables to check if the runnable actually
// ran, if that is important.
synchronized (list) {
l = (Link) list.pop();
}
if (l == null)
break;
else
l.unlock();
} while (true);
synchronized (this) {
runnableQueueThread = null;
}
}
}
/**
* Returns the thread in which the RunnableQueue is currently running.
*
* @return null if the RunnableQueue has not entered his <code>run()</code>
* method.
*/
public HaltingThread getThread() {
return runnableQueueThread;
}
/**
* Schedules the given Runnable object for a later invocation, and returns. An
* exception is thrown if the RunnableQueue was not started.
*
* @throws IllegalStateException if getThread() is null.
*/
public void invokeLater(Runnable r) {
if (runnableQueueThread == null) {
throw new IllegalStateException("RunnableQueue not started or has exited");
}
synchronized (list) {
list.push(new Link(r));
list.notify();
}
}
/**
* Waits until the given Runnable's <code>run()</code> has returned. <em>Note:
* <code>invokeAndWait()</code> must not be called from the current thread (for
* example from the <code>run()</code> method of the argument).</em>
*
* @throws IllegalStateException if getThread() is null or if the thread
* returned by getThread() is the current one.
*/
public void invokeAndWait(Runnable r) throws InterruptedException {
if (runnableQueueThread == null) {
throw new IllegalStateException("RunnableQueue not started or has exited");
}
if (runnableQueueThread == Thread.currentThread()) {
throw new IllegalStateException("Cannot be called from the RunnableQueue thread");
}
LockableLink l = new LockableLink(r);
synchronized (list) {
list.push(l);
list.notify();
}
l.lock(); // todo: the 'other side' of list may retrieve the l before it is locked...
}
/**
* Schedules the given Runnable object for a later invocation, and returns. The
* given runnable preempts any runnable that is not currently executing (ie the
* next runnable started will be the one given). An exception is thrown if the
* RunnableQueue was not started.
*
* @throws IllegalStateException if getThread() is null.
*/
public void preemptLater(Runnable r) {
if (runnableQueueThread == null) {
throw new IllegalStateException("RunnableQueue not started or has exited");
}
synchronized (list) {
list.add(preemptCount, new Link(r));
preemptCount++;
list.notify();
}
}
/**
* Waits until the given Runnable's <code>run()</code> has returned. The given
* runnable preempts any runnable that is not currently executing (ie the next
* runnable started will be the one given). <em>Note:
* <code>preemptAndWait()</code> must not be called from the current thread (for
* example from the <code>run()</code> method of the argument).</em>
*
* @throws IllegalStateException if getThread() is null or if the thread
* returned by getThread() is the current one.
*/
public void preemptAndWait(Runnable r) throws InterruptedException {
if (runnableQueueThread == null) {
throw new IllegalStateException("RunnableQueue not started or has exited");
}
if (runnableQueueThread == Thread.currentThread()) {
throw new IllegalStateException("Cannot be called from the RunnableQueue thread");
}
LockableLink l = new LockableLink(r);
synchronized (list) {
list.add(preemptCount, l);
preemptCount++;
list.notify();
}
l.lock(); // todo: the 'other side' of list may retrieve the l before it is locked...
}
public RunnableQueueState getQueueState() {
synchronized (stateLock) {
return state;
}
}
/**
* Suspends the execution of this queue after the current runnable completes.
*
* @param waitTillSuspended if true this method will not return until the queue
* has suspended (no runnable in progress or about to
* be in progress). If resumeExecution is called while
* waiting will simply return (this really indicates a
* race condition in your code). This may return before
* an associated RunHandler is notified.
* @throws IllegalStateException if getThread() is null.
*/
public void suspendExecution(boolean waitTillSuspended) {
if (runnableQueueThread == null) {
throw new IllegalStateException("RunnableQueue not started or has exited");
}
// System.err.println("Suspend Called");
synchronized (stateLock) {
wasResumed = false;
if (state == SUSPENDED) {
// already suspended, notify stateLock so an event is
// generated.
stateLock.notifyAll();
return;
}
if (state == RUNNING) {
state = SUSPENDING;
synchronized (list) {
// Wake up run thread if it is waiting for jobs,
// so we go into the suspended case (notifying
// run-handler etc...)
list.notify();
}
}
if (waitTillSuspended) {
while (state == SUSPENDING) {
try {
stateLock.wait();
} catch (InterruptedException ie) {
}
}
}
}
}
/**
* Resumes the execution of this queue.
*
* @throws IllegalStateException if getThread() is null.
*/
public void resumeExecution() {
// System.err.println("Resume Called");
if (runnableQueueThread == null) {
throw new IllegalStateException("RunnableQueue not started or has exited");
}
synchronized (stateLock) {
wasResumed = true;
if (state != RUNNING) {
state = RUNNING;
stateLock.notifyAll(); // wake it up.
}
}
}
/**
* Returns iterator lock to use to work with the iterator returned by
* iterator().
*/
public Object getIteratorLock() {
return list;
}
/**
* Returns an iterator over the runnables.
*/
public Iterator<Runnable> iterator() {
return new Iterator<Runnable>() {
Link head = (Link) list.getHead();
Link link;
@Override
public boolean hasNext() {
if (head == null) {
return false;
}
if (link == null) {
return true;
}
return link != head;
}
@Override
public Runnable next() {
if (head == null || head == link) {
throw new NoSuchElementException();
}
if (link == null) {
link = (Link) head.getNext();
return head.runnable;
}
Runnable result = link.runnable;
link = (Link) link.getNext();
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
/**
* Sets the RunHandler for this queue.
*/
public synchronized void setRunHandler(RunHandler rh) {
runHandler = rh;
}
/**
* Returns the RunHandler or null.
*/
public synchronized RunHandler getRunHandler() {
return runHandler;
}
/**
* Sets a Runnable to be run whenever the queue is empty.
*/
public void setIdleRunnable(IdleRunnable r) {
synchronized (list) {
idleRunnable = r;
idleRunnableWaitTime = 0;
list.notify();
}
}
/**
* Called when execution is being suspended. Currently just notifies runHandler
*/
protected synchronized void executionSuspended() {
// System.err.println("Suspend Sent");
if (runHandler != null) {
runHandler.executionSuspended(this);
}
}
/**
* Called when execution is being resumed. Currently just notifies runHandler
*/
protected synchronized void executionResumed() {
// System.err.println("Resumed Sent");
if (runHandler != null) {
runHandler.executionResumed(this);
}
}
/**
* Called just prior to executing a Runnable. Currently just notifies runHandler
*
* @param rable The runnable that is about to start
*/
protected synchronized void runnableStart(Runnable rable) {
if (runHandler != null) {
runHandler.runnableStart(this, rable);
}
}
/**
* Called when a Runnable completes. Currently just notifies runHandler
*
* @param rable The runnable that just completed.
*/
protected synchronized void runnableInvoked(Runnable rable) {
if (runHandler != null) {
runHandler.runnableInvoked(this, rable);
}
}
/**
* A {@link Runnable} that can also inform the caller how long it should be
* until it is run again.
*/
public interface IdleRunnable extends Runnable {
/**
* Returns the system time that can be safely waited until before this
* {@link Runnable} is run again.
*
* @return time to wait until, <code>0</code> if no waiting can be done, or
* {@link Long#MAX_VALUE} if the {@link Runnable} should not be run
* again at this time
*/
long getWaitTime();
}
/**
* This interface must be implemented by an object which wants to be notified of
* run events.
*/
public interface RunHandler {
/**
* Called just prior to invoking the runnable
*/
void runnableStart(RunnableQueue rq, Runnable r);
/**
* Called when the given Runnable has just been invoked and has returned.
*/
void runnableInvoked(RunnableQueue rq, Runnable r);
/**
* Called when the execution of the queue has been suspended.
*/
void executionSuspended(RunnableQueue rq);
/**
* Called when the execution of the queue has been resumed.
*/
void executionResumed(RunnableQueue rq);
}
/**
* This is an adapter class that implements the RunHandler interface. It simply
* does nothing in response to the calls.
*/
public static class RunHandlerAdapter implements RunHandler {
/**
* Called just prior to invoking the runnable
*/
@Override
public void runnableStart(RunnableQueue rq, Runnable r) {
}
/**
* Called when the given Runnable has just been invoked and has returned.
*/
@Override
public void runnableInvoked(RunnableQueue rq, Runnable r) {
}
/**
* Called when the execution of the queue has been suspended.
*/
@Override
public void executionSuspended(RunnableQueue rq) {
}
/**
* Called when the execution of the queue has been resumed.
*/
@Override
public void executionResumed(RunnableQueue rq) {
}
}
/**
* To store a Runnable.
*/
protected static class Link extends DoublyLinkedList.Node {
/**
* The Runnable.
*/
private final Runnable runnable;
/**
* Creates a new link.
*/
public Link(Runnable r) {
runnable = r;
}
/**
* unlock link and notify locker. Basic implementation does nothing.
*/
public void unlock() {
return;
}
}
/**
* To store a Runnable with an object waiting for him to be executed.
*/
protected static class LockableLink extends Link {
/**
* Whether this link is actually locked.
*/
private volatile boolean locked;
/**
* Creates a new link.
*/
public LockableLink(Runnable r) {
super(r);
}
/**
* Whether the link is actually locked.
*/
public boolean isLocked() {
return locked;
}
/**
* Locks this link.
*/
public synchronized void lock() throws InterruptedException {
locked = true;
notify();
wait();
}
/**
* unlocks this link.
*/
@Override
public synchronized void unlock() {
while (!locked) {
try {
wait(); // Wait until lock is called...
} catch (InterruptedException ie) {
// Loop again...
}
}
locked = false;
// Wake the locking thread...
notify();
}
}
}
| 24.880658 | 94 | 0.650513 |
ef1b7581272613a677c7f5559ca4f96b6f0f96d8 | 3,186 | package model.levelStuff;
import model.Char;
import model.Item;
import model.PlayerCharacter;
import model.enemies.Enemy;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class NewRoom {
private List<Item> inventory; //current room inventory
private List<Enemy> enemies; //enemies in room
private List<PlayerCharacter> party; //current party
private List<Char> allChars; //all characters in room, sorted by speed
private Item item; //room's item
private Boolean hasBattle; //whether room has battle
private Boolean isFinalRoom; //whether room is final one
private RoomEvent event; //room event
private int whichBoss; // can be 0 (no boss), 1 2 or 3
public NewRoom(List<Enemy> enemies, List<PlayerCharacter> party, List<Item> inventory, Item i, Boolean hb, Boolean f, int whichBoss,
RoomEvent ev) {
this.enemies = enemies;
this.event = ev;
this.party = party;
this.inventory = inventory;
this.allChars = new ArrayList<>();
this.item = i;
this.hasBattle = hb;
this.isFinalRoom = f;
this.whichBoss = whichBoss;
createAllChars();
}
//getters, setters
public RoomEvent getEvent() {
return event;
}
public int getWhichBoss() {
return whichBoss;
}
public Item getItem() {
return item;
}
public Boolean getHasBattle() {
return hasBattle;
}
public Boolean getFinalRoom() {
return isFinalRoom;
}
public List<Item> getInventory() {
return inventory;
}
public List<Enemy> getEnemies() {
return enemies;
}
public List<PlayerCharacter> getParty() {
return party;
}
public List<Char> getAllChars() {
return allChars;
}
//returns true if there is room in inventory for another item
public Boolean canPickUpItem() {
return inventory.size() < 10;
}
//sets event to null
public void useEvent() {
event = null;
}
//sets item to null
public void setItemNull() {
this.item = null;
}
//removes i from inventory
public void removeFromInventory(Item i) {
inventory.remove(i);
}
//returns true if all enemies are dead
public Boolean isBattleWon() {
for(Enemy e : enemies) {
if(!e.getDead()) {
return false;
}
}
return true;
}
//returns true if all party members are dead
public Boolean isBattleLost() {
for(PlayerCharacter e : party) {
if(!e.getDead()) {
return false;
}
}
return true;
}
//sorts all characters by speed
public void createAllChars() {
List<Char> temp = new ArrayList<>();
for(Enemy c : enemies) {
temp.add(c);
}
for(PlayerCharacter c : party) {
c.setPartyWith(party);
c.setEnemiesFighting(enemies);
temp.add(c);
}
temp.sort(Comparator.comparing(Char::getSpeed).reversed());
allChars = temp;
}
}
| 24.136364 | 136 | 0.590082 |
0f1f5e3eea66da7c0a25dffb253a35b81b22a676 | 309 | package com.thanple.little.boy.web.entity.msg;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* Created by Thanple on 2018/5/24.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class RedisPubMsg {
private Long id;
private RedisPubBean pubBean;
}
| 18.176471 | 46 | 0.770227 |
8bd5769d3ae2b31fd0125b49f182c5f5df560ec1 | 4,359 | package com.equipeRL.backend.Controllers;
import com.equipeRL.backend.Controllers.interfaces.ControllerCRUDInterface;
import com.equipeRL.backend.Controllers.propertyEditors.PermissaoPropertyEditor;
import com.equipeRL.backend.Models.Permissao;
import com.equipeRL.backend.Models.Usuario;
import com.equipeRL.backend.Services.UsuarioService;
import com.equipeRL.backend.Services.exceptions.CustomErrorType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import javax.validation.Valid;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@RestController
@RequestMapping("${spring.data.rest.base-path}/usuarios")
public class UsuariosController implements ControllerCRUDInterface<Usuario> {
@Autowired
private UsuarioService usuarioService;
@Autowired
private PermissaoPropertyEditor permissaoPropertyEditor;
@GetMapping()
public ResponseEntity<List<Usuario>> listAll() {
try {
List<Usuario> usuarios = usuarioService.getAll();
return new ResponseEntity<>(usuarios, HttpStatus.OK);
}catch (Exception e) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
@PostMapping()
public ResponseEntity<?> create(@Valid Usuario model, BindingResult result, UriComponentsBuilder ucBuilder) {
try {
//valida campos
if(result.hasErrors()) {
return new ResponseEntity(result.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
}
//verifica se já esta cadastrado
if (usuarioService.isExist(model)) {
return new ResponseEntity(new CustomErrorType("Não é possivel cadastrar o usuário com nome " +
model.getNome() + " pois já está cadastrado."), HttpStatus.CONFLICT);
}
//salva o aluno
//OBS: encriptação de senha esta sendo feito no service
usuarioService.save(model);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/api/usuarios/{id}").buildAndExpand(model.getId()).toUri());
return new ResponseEntity<>(model, headers, HttpStatus.CREATED);
} catch (Exception e) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
@PutMapping("/{id}")
public ResponseEntity<?> update(@PathVariable("id") long id, @Valid Usuario model, BindingResult result) {
try {
//valida campos
if(result.hasErrors()) {
return new ResponseEntity(result.getAllErrors(), HttpStatus.UNPROCESSABLE_ENTITY);
}
//Verifica se está cadastrado
Usuario findUsuario = usuarioService.findById(id);
if (findUsuario == null) {
return new ResponseEntity(new CustomErrorType("Item de id = " + id + " não encontrado."),
HttpStatus.NOT_FOUND);
}
//atualiza o usuario
usuarioService.update(model);
return new ResponseEntity<>(model, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
@DeleteMapping("/{id}")
public ResponseEntity<?> delete(@PathVariable("id") long id) {
try {
Usuario usuario = usuarioService.findById(id);
if (usuario == null) {
return new ResponseEntity(new CustomErrorType("Item de id = " + id + " não encontrado."),
HttpStatus.NOT_FOUND);
}
//deleta item
usuarioService.deleteById(id);
return new ResponseEntity<>(HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity(HttpStatus.BAD_REQUEST);
}
}
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.registerCustomEditor(Permissao.class, permissaoPropertyEditor);
}
}
| 30.062069 | 113 | 0.654508 |
2cd32e109b50f623b83392c55557ab4e6641e28e | 12,421 | /*
* Copyright (C) 2013 salesforce.com, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.auraframework.test.perf;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.auraframework.test.SauceUtil;
import org.auraframework.test.WebDriverTestCase.UnexpectedError;
import org.auraframework.test.perf.rdp.CPUProfilerAnalyzer;
import org.auraframework.test.perf.rdp.RDPNotification;
import org.auraframework.util.AuraTextUtil;
import org.auraframework.util.AuraUITestingUtil;
import org.auraframework.util.json.JsonReader;
import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.UnsupportedCommandException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* Utility WebDriver methods related to performance
*/
public final class PerfWebDriverUtil {
private static final Logger LOG = Logger.getLogger(PerfWebDriverUtil.class.getSimpleName());
private static final LoggingPreferences PERFORMANCE_LOGGING_PREFS;
static {
// NOTE: need to create single LoggingPreferences object to be reused as LoggingPreferences
// doesn't implement hashCode()/equals() correctly
PERFORMANCE_LOGGING_PREFS = new LoggingPreferences();
PERFORMANCE_LOGGING_PREFS.enable(LogType.PERFORMANCE, Level.INFO);
// logPrefs.enable(LogType.BROWSER, Level.ALL);
// Level.FINE for LogType.DRIVER shows all dev tools requests and responses
// logPrefs.enable(LogType.DRIVER, Level.WARNING);
// N/A in chromedriver: logPrefs.enable(LogType.PROFILER, Level.ALL);
// N/A in chromedriver: logPrefs.enable(LogType.CLIENT, Level.ALL);
// N/A in chromedriver: logPrefs.enable(LogType.SERVER, Level.ALL);
}
/**
* Adds capabilites to request collecting WebDriver performance data
*/
public static void addLoggingCapabilities(DesiredCapabilities capabilities) {
capabilities.setCapability(CapabilityType.LOGGING_PREFS, PERFORMANCE_LOGGING_PREFS);
}
/**
* Pretty-prints the data from the Resource Timing API
*/
public static void showResourceTimingData(List<Map<String, Object>> data) {
for (Map<String, Object> entry : data) {
try {
System.out.println("entry: " + new JSONObject(entry).toString(2));
} catch (JSONException e) {
throw new RuntimeException(String.valueOf(entry), e);
}
}
}
// instance:
private final WebDriver driver;
private final AuraUITestingUtil auraUITestingUtil;
public PerfWebDriverUtil(WebDriver driver, AuraUITestingUtil auraUITestingUtil) {
this.driver = driver;
this.auraUITestingUtil = auraUITestingUtil;
}
/**
* @return new RDPNotifications since the last call to this method
*/
public List<RDPNotification> getRDPNotifications() {
List<LogEntry> logEntries = getLogEntries(LogType.PERFORMANCE);
List<RDPNotification> events = Lists.newArrayList();
for (LogEntry logEntry : logEntries) {
if (LOG.isLoggable(Level.FINE)) {
LOG.fine("LOG_ENTRY: " + logEntry);
}
String message = logEntry.getMessage();
// logMessage is: {"message":{"method":"Timeline.eventRecorded","params":{...
try {
JSONObject json = new JSONObject(message);
JSONObject event = json.getJSONObject("message");
String webview = json.getString("webview");
events.add(new RDPNotification(event, webview));
} catch (JSONException e) {
LOG.log(Level.WARNING, message, e);
}
}
return events;
}
public void addTimelineTimeStamp(String label) {
((JavascriptExecutor) driver).executeScript("console.timeStamp('" + label + "')");
}
//
/**
* @param type one of the LogTypes, i.e. LogType.PERFORMANCE
* @return log entries accumulated since the last time this method was called
*/
private List<LogEntry> getLogEntries(String type) {
try {
return driver.manage().logs().get(type).getAll();
} catch (WebDriverException ignore) {
// i.e. log type 'profiler' not found
} catch (Exception e) {
LOG.log(Level.WARNING, type, e);
}
return NO_ENTRIES;
}
private static final List<LogEntry> NO_ENTRIES = ImmutableList.of();
// window.performance
/**
* @return the usedJSHeapSize from window.performance.memory
*/
public long getUsedJSHeapSize() {
return (long) ((JavascriptExecutor) driver).executeScript("return window.performance.memory.usedJSHeapSize");
}
/**
* See https://developers.google.com/chrome-developer-tools/docs/network and http://www.w3.org/TR/resource-timing
*
* @return Resource Timing API performance
*/
@SuppressWarnings("unchecked")
public List<Map<String, ?>> getResourceTimingData() {
List<Map<String, ?>> entries = (List<Map<String, ?>>) ((JavascriptExecutor) driver)
.executeScript("return window.performance.getEntries()");
return entries;
}
// UIPerfStats:
public void clearUIPerfStats() {
auraUITestingUtil.getEval("$A.Perf.removeStats()");
}
public Map<String, String> getUIPerfStats(String stage, List<String> transactionsToGather) {
Map<String, String> stats = Maps.newHashMap();
String json = auraUITestingUtil.getEval("return $A.util.json.encode($A.Perf.toJson())").toString();
json = json.substring(1, json.length() - 1);
json = json.replace("\\\"", "\"");
StringReader in = new StringReader(json);
Map<?, ?> message = (Map<?, ?>) new JsonReader().read(in);
@SuppressWarnings("unchecked")
ArrayList<HashMap<?, ?>> measures = (ArrayList<HashMap<?, ?>>) message
.get("measures");
for (HashMap<?, ?> marks : measures) {
if (!transactionsToGather.isEmpty()) {
if (!transactionsToGather.contains(marks.get("measure")) &&
// IE10 list of measures was not in the same order
// as expected in transactionsToGather so need to
// make sure measure and transactionsToGather are
// similar
!AuraTextUtil.stringsHaveSameContent(
(String) marks.get("measure"),
transactionsToGather.get(0))) {
continue;
}
}
String measureName = marks.get("measure").toString()
+ (stage != null ? ("_" + stage) : "");
stats.put(measureName, marks.get("et").toString());
}
return stats;
}
// JS heap snapshot
/**
* See https://code.google.com/p/chromedriver/issues/detail?id=519<br/>
* Note: slow, each call takes a couple of seconds
*
* @return JS heap snapshot
*/
@SuppressWarnings("unchecked")
public Map<String, ?> takeHeapSnapshot() {
if (SauceUtil.areTestsRunningOnSauce()) {
throw new UnsupportedOperationException("required 2.10 chromedriver still not available in SauceLabs");
}
long startTime = System.currentTimeMillis();
Map<String, ?> snapshot = (Map<String, ?>) ((JavascriptExecutor) driver).executeScript(":takeHeapSnapshot");
LOG.info("took heap snapshot in " + (System.currentTimeMillis() - startTime) + " ms");
return snapshot;
}
/**
* Analyzes the data in the snapshot and returns summary data
*/
@SuppressWarnings("unchecked")
public static JSONObject analyzeHeapSnapshot(Map<String, ?> data) {
Map<String, ?> metadata = (Map<String, ?>) data.get("snapshot");
int nodeCount = ((Number) metadata.get("node_count")).intValue();
// "node_fields": ["type","name","id","self_size","edge_count"]
List<Number> nodes = (List<Number>) data.get("nodes");
int totalSize = 0;
for (int i = 0; i < nodeCount; i++) {
totalSize += nodes.get(5 * i + 3).intValue();
}
JSONObject json = new JSONObject();
try {
json.put("node_count", nodeCount);
json.put("total_size", totalSize);
} catch (JSONException e) {
throw new RuntimeException(e);
}
return json;
}
// JavaScript CPU Profiler
/**
* Start JavaScript CPU profiler
*/
public void startProfile() {
if (!PerfUtil.MEASURE_JSCPU_METRICTS) {
return;
}
try {
((JavascriptExecutor) driver).executeScript(":startProfile");
} catch (UnsupportedCommandException e) {
// happens about .5% of the time
LOG.log(Level.WARNING, ":startProfile failed, retrying", e);
((JavascriptExecutor) driver).executeScript(":startProfile");
}
}
/**
* Stop JavaScript CPU profiler and return profile info
*
* See https://src.chromium.org/viewvc/chrome?revision=271803&view=revision
*/
@SuppressWarnings("unchecked")
public Map<String, ?> endProfile() {
if (!PerfUtil.MEASURE_JSCPU_METRICTS) {
return null;
}
// takes about 300ms for ui:button
Map<String, ?> retval = null;
try {
retval = (Map<String, ?>) ((JavascriptExecutor) driver).executeScript(":endProfile");
} catch (UnsupportedCommandException e) {
// happens about .5% of the time
LOG.log(Level.WARNING, ":endProfile failed, retrying", e);
retval = (Map<String, ?>) ((JavascriptExecutor) driver).executeScript(":endProfile");
}
if (retval == null) {
LOG.warning(":endProfile returned no results");
return null;
}
return (Map<String, ?>) retval.get("profile");
}
public static JSONObject analyzeCPUProfile(Map<String, ?> profile) throws JSONException {
return new CPUProfilerAnalyzer(profile).analyze();
}
/**
* @return true if the test failure is most likely an infrastructure error (i.e. SauceLabs problem)
*/
public static boolean isInfrastructureError(Throwable testFailure) {
if (testFailure instanceof UnexpectedError) {
testFailure = testFailure.getCause();
}
if (testFailure instanceof TimeoutException) {
// i.e. aura did not even load
return true;
}
if (testFailure instanceof UnsupportedCommandException) {
// org.openqa.selenium.UnsupportedCommandException: ERROR Job 2cf6026df5514bd1a859b1a82ef1c25a is not in
// progress. It may have recently finished, or experienced an error. You can learn more at
// https://saucelabs.com/jobs/2cf6026df5514bd1a859b1a82ef1c25a Command duration or timeout: 122 milliseconds
String m = testFailure.getMessage();
if (m != null && m.contains("is not in progress")) {
return true;
}
}
return false;
}
}
| 37.984709 | 120 | 0.634329 |
951fefe59fcc41385e1165ceab484ff7cd04d3d8 | 702 | package net.runelite.client.plugins.xptrackersimple;
import net.runelite.api.Skill;
import net.runelite.client.config.Config;
import net.runelite.client.config.ConfigGroup;
import net.runelite.client.config.ConfigItem;
@ConfigGroup("SimpleXpTrackerConfig")
public interface SimpleXpTrackerConfig extends Config {
@ConfigItem(
keyName="chosenSkill",
name="Skill:",
description = "",
position=1
)
default Skill chosenSkill() { return Skill.ATTACK;}
@ConfigItem(
keyName="targetLevel",
name="Target Level:",
description = "",
position=2
)
default int targetLevel() { return 0;}
}
| 25.071429 | 55 | 0.646724 |
4fcd9822d74a557cb07ac2a4ddb5bbb600370d3b | 2,565 | package com.jaxwallet.app.ui.widget.holder;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import com.jaxwallet.app.R;
import com.jaxwallet.app.ui.widget.entity.WarningData;
/**
* Created by James on 18/07/2019.
* AJ TECHNOLOGIES LTD
*/
public class WarningHolder extends BinderViewHolder<WarningData>
{
public static final int VIEW_TYPE = 1015;
private final TextView title;
private final TextView detail;
private final LinearLayout layoutBackground;
private final ImageView menuButton;
private final Button backupButton;
private final View popupAnchor;
@Override
public void bind(@Nullable WarningData data, @NonNull Bundle addition)
{
title.setText(data.title);
detail.setText(data.detail);
layoutBackground.setBackgroundTintList(ContextCompat.getColorStateList(getContext(), data.colour));
backupButton.setText(data.buttonText);
backupButton.setBackgroundColor(data.buttonColour);
backupButton.setOnClickListener(v -> { data.callback.BackupClick(data.wallet); });
menuButton.setOnClickListener(v -> {
showPopup(popupAnchor, data);
});
}
private void showPopup(View view, WarningData data) {
LayoutInflater inflater = LayoutInflater.from(getContext());
View popupView = inflater.inflate(R.layout.popup_remind_later, null);
int width = LinearLayout.LayoutParams.WRAP_CONTENT;
int height = LinearLayout.LayoutParams.WRAP_CONTENT;
final PopupWindow popupWindow = new PopupWindow(popupView, width, height, true);
popupView.setOnClickListener(v -> {
data.callback.remindMeLater(data.wallet);
popupWindow.dismiss();
});
popupWindow.showAsDropDown(view, 0, 20);
}
public WarningHolder(int res_id, ViewGroup parent)
{
super(res_id, parent);
title = findViewById(R.id.text_title);
detail = findViewById(R.id.text_detail);
layoutBackground = findViewById(R.id.layout_item_warning);
backupButton = findViewById(R.id.button_backup);
menuButton = findViewById(R.id.btn_menu);
popupAnchor = findViewById(R.id.popup_anchor);
}
}
| 36.126761 | 107 | 0.720858 |
0a73f82b11df04fa08ba21748ea0693651fb3b19 | 197 | package com.aisino.test.aop;
/**
* @author: xiajun003
* @Date: 2019/3/31 17:37
* @Description:
*/
public interface IMathCalculator {
int div(int i, int j);
int div2(int i, int j);
}
| 14.071429 | 34 | 0.624365 |
a0b8af24b9ccac05a8cf7e3b2a715a0845998cc6 | 3,128 | package com.popularmovies.vpaliy.data.mapper;
import android.util.Log;
import com.popularmovies.vpaliy.data.configuration.ImageQualityConfiguration;
import com.popularmovies.vpaliy.data.entity.Movie;
import com.popularmovies.vpaliy.domain.model.MediaCover;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import static com.popularmovies.vpaliy.data.utils.MapperUtils.convert;
import static com.popularmovies.vpaliy.data.utils.MapperUtils.convertToBackdrops;
import static com.popularmovies.vpaliy.data.utils.MapperUtils.convertToDuration;
import static com.popularmovies.vpaliy.data.utils.MapperUtils.convertToGenres;
import static com.popularmovies.vpaliy.data.utils.MapperUtils.convertToRuntime;
import static com.popularmovies.vpaliy.data.utils.MapperUtils.convertToYear;
@Singleton
public class MovieMapper extends Mapper<MediaCover,Movie> {
private final ImageQualityConfiguration qualityConfiguration;
@Inject
public MovieMapper(ImageQualityConfiguration qualityConfiguration){
this.qualityConfiguration=qualityConfiguration;
}
@Override
public MediaCover map(Movie movieEntity) {
MediaCover cover=new MediaCover();
cover.setMediaId(movieEntity.getMovieId());
cover.setPosterPath(qualityConfiguration.convertCover(movieEntity.getPosterPath()));
cover.setGenres(convert(movieEntity.getGenres()));
cover.setMovieTitle(movieEntity.getTitle());
cover.setAverageRate(movieEntity.getVoteAverage());
cover.setFavorite(movieEntity.isFavorite());
cover.setBackdrops(convert(movieEntity.getBackdropImages(),qualityConfiguration));
cover.setReleaseDate(movieEntity.getReleaseDate());
cover.setDuration(convertToDuration(movieEntity.getRuntime()));
cover.setReleaseDate(cover.getReleaseDate());
cover.setReleaseYear(convertToYear(cover.getReleaseDate()));
cover.setMustWatch(movieEntity.isMustWatch());
cover.setWatched(movieEntity.isWatched());
cover.setMainBackdrop(qualityConfiguration.convertBackdrop(movieEntity.getBackdrop_path()));
return cover;
}
@Override
public Movie reverseMap(MediaCover movieCover) {
Movie result=new Movie();
result.setMovieId(movieCover.getMediaId());
result.setPosterPath(qualityConfiguration.extractPath(movieCover.getPosterPath()));
result.setGenres(convertToGenres(movieCover.getGenres()));
result.setTitle(movieCover.getMovieTitle());
result.setVoteAverage(movieCover.getAverageVote());
result.setBackdropPath(qualityConfiguration.extractPath(movieCover.getMainBackdrop()));
result.setFavorite(movieCover.isFavorite());
result.setRuntime(convertToRuntime(movieCover.getDuration()));
result.setBackdropImages(convertToBackdrops(movieCover.getBackdrops(), qualityConfiguration));
result.setReleaseDate(movieCover.getReleaseDate());
result.setMustWatch(movieCover.isMustWatch());
result.setWatched(movieCover.isWatched());
return result;
}
}
| 46 | 102 | 0.767903 |
4f2f5f02c63a52d1b0a0e9d1149c77f7ec8381aa | 464 | package com.pgmacdesign.randomuserapitests;
/**
* Link to communicate between activity and fragments
* Created by PatrickSSD2 on 3/25/2017.
*/
public interface FragmentLink {
/**
* Set fragment to switch to
* @param whichFragment Will either be:
* {@link Constants#FRAGMENT_LIST_USERS} or
* {@link Constants#FRAGMENT_INDIVIDUAL_USER}
*/
public void setFragment(int whichFragment);
}
| 25.777778 | 70 | 0.642241 |
bd172c10b44d83099f1c7a77636e33cdf1e7002f | 2,612 | package com.TonyTiger.simplecoins.block;
import com.TonyTiger.simplecoins.Main;
import com.TonyTiger.simplecoins.TileEntity.MintTileEntity;
import com.TonyTiger.simplecoins.network.ModGuiHandler;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.InventoryHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
public class MintBlock extends Block{
public final static String modid = Main.MODID;
public MintBlock(String unlocalizedName, Material material, float hardness, float resistance){
super(material);
this.setSoundType(SoundType.METAL);
this.setUnlocalizedName(unlocalizedName);
this.setHarvestLevel("pickaxe",0);
this.setCreativeTab(CreativeTabs.MISC);
this.setResistance(resistance);
this.setHardness(hardness);
this.setRegistryName(modid, unlocalizedName);
}
public MintBlock(String unlocalizedName, float hardness, float resistance) {
this(unlocalizedName, Material.IRON, hardness, resistance);
}
public MintBlock(String unlocalizedName) {
this(unlocalizedName, 2.0f, 10.0f);
}
@Override
public boolean hasTileEntity(IBlockState state){
return true;
}
@Override
public TileEntity createTileEntity(World worldIn, IBlockState state) {
return new MintTileEntity();
}
@Override
public boolean onBlockActivated(World world, BlockPos pos, IBlockState state,
EntityPlayer player, EnumHand hand, EnumFacing side, float hitX, float hitY, float hitZ) {
if(!world.isRemote)
player.openGui(Main.instance, ModGuiHandler.MOD_TILE_ENTITY_GUI, world, pos.getX(), pos.getY(), pos.getZ());
return true;
}
@Override
public void breakBlock(World world, BlockPos pos, IBlockState blockstate){
MintTileEntity te = (MintTileEntity) world.getTileEntity(pos);
InventoryHelper.dropInventoryItems(world, pos, te);
super.breakBlock(world, pos, blockstate);
}
@Override
public void onBlockPlacedBy(World worldIn, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack) {
if (stack.hasDisplayName()) {
((MintTileEntity) worldIn.getTileEntity(pos)).setCustomName(stack.getDisplayName());
}
}
}
| 35.297297 | 120 | 0.772971 |
17be6d429542ecc6ac55f8eaf664433c0c1f0966 | 236 | /*
* Copyright (c) 1998-2021 John Caron and University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
/**
* Make an object on S3 look like a RandomAccessFile.
*/
package ucar.unidata.io.s3;
| 23.6 | 97 | 0.737288 |
3020816dcdc77cfc71a845ae4c611b5fcd166c03 | 3,238 | /*
* Copyright (C) 2004-2016 L2J DataPack
*
* This file is part of L2J DataPack.
*
* L2J DataPack is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* L2J DataPack is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package handlers.targethandlers;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.l2jserver.gameserver.handler.ITargetTypeHandler;
import com.l2jserver.gameserver.model.L2Object;
import com.l2jserver.gameserver.model.actor.L2Character;
import com.l2jserver.gameserver.model.skills.Skill;
import com.l2jserver.gameserver.model.skills.targets.L2TargetType;
import com.l2jserver.gameserver.model.zone.ZoneId;
import com.l2jserver.gameserver.network.SystemMessageId;
import com.l2jserver.gameserver.util.Util;
/**
* @author UnAfraid
*/
public class BehindArea implements ITargetTypeHandler
{
@Override
public L2Object[] getTargetList(Skill skill, L2Character activeChar, boolean onlyFirst, L2Character target)
{
List<L2Character> targetList = new ArrayList<>();
if ((target == null) || (((target == activeChar) || target.isAlikeDead()) && (skill.getCastRange() >= 0)) || (!(target.isAttackable() || target.isPlayable())))
{
activeChar.sendPacket(SystemMessageId.TARGET_IS_INCORRECT);
return EMPTY_TARGET_LIST;
}
final L2Character origin;
final boolean srcInArena = (activeChar.isInsideZone(ZoneId.PVP) && !activeChar.isInsideZone(ZoneId.SIEGE));
if (skill.getCastRange() >= 0)
{
if (!Skill.checkForAreaOffensiveSkills(activeChar, target, skill, srcInArena))
{
return EMPTY_TARGET_LIST;
}
if (onlyFirst)
{
return new L2Character[]
{
target
};
}
origin = target;
targetList.add(origin); // Add target to target list
}
else
{
origin = activeChar;
}
final Collection<L2Character> objs = activeChar.getKnownList().getKnownCharacters();
int maxTargets = skill.getAffectLimit();
for (L2Character obj : objs)
{
if (!(obj.isAttackable() || obj.isPlayable()))
{
continue;
}
if (obj == origin)
{
continue;
}
if (Util.checkIfInRange(skill.getAffectRange(), origin, obj, true))
{
if (!obj.isBehind(activeChar))
{
continue;
}
if (!Skill.checkForAreaOffensiveSkills(activeChar, obj, skill, srcInArena))
{
continue;
}
if ((maxTargets > 0) && (targetList.size() >= maxTargets))
{
break;
}
targetList.add(obj);
}
}
if (targetList.isEmpty())
{
return EMPTY_TARGET_LIST;
}
return targetList.toArray(new L2Character[targetList.size()]);
}
@Override
public Enum<L2TargetType> getTargetType()
{
return L2TargetType.BEHIND_AREA;
}
}
| 26.112903 | 161 | 0.699197 |
16149bfdc0ae444cf6bb0253a964b935cebff4b0 | 360 | package badgamesinc.hypnotic.event.events;
import badgamesinc.hypnotic.event.Event;
public class EventSendMessage extends Event {
private String message;
public EventSendMessage(String message) {
this.message = message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
| 17.142857 | 45 | 0.75 |
86f97a9a6b7f567d09986e8709978f70c2ff8df6 | 6,070 | /*
* The MIT License
*
* Copyright (c) 2018-2022, qinglangtech Ltd
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.qlangtech.tis.runtime.module.action;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.Assert;
import org.apache.commons.lang.StringUtils;
import com.alibaba.citrus.turbine.Context;
import com.qlangtech.tis.manage.biz.dal.pojo.Application;
import com.qlangtech.tis.manage.biz.dal.pojo.ApplicationCriteria;
import com.qlangtech.tis.manage.biz.dal.pojo.Department;
import com.qlangtech.tis.manage.biz.dal.pojo.UsrApplyDptRecord;
import com.qlangtech.tis.manage.biz.dal.pojo.ApplicationCriteria.Criteria;
import com.qlangtech.tis.manage.common.ANode;
import com.qlangtech.tis.manage.common.BizANode;
import com.qlangtech.tis.manage.common.UserUtils;
import com.qlangtech.tis.manage.common.apps.AppsFetcher.CriteriaSetter;
import com.qlangtech.tis.manage.common.apps.IAppsFetcher;
import com.qlangtech.tis.runtime.module.screen.Bizdomainlist;
/* *
* @author 百岁([email protected])
* @date 2019年1月17日
*/
public abstract class AppViewAction extends Bizdomainlist {
/**
*/
private static final long serialVersionUID = 1L;
public void doGet(Context context) throws Exception {
Integer bizId = this.getInt("bizid");
final List<ANode> anodelist = new ArrayList<ANode>();
if (bizId == null) {
List<Department> bizList = this.getAllBizDomain();
for (Department biz : bizList) {
anodelist.add(ANode.createBizNode(biz.getDptId(), biz.getName()));
}
} else {
// List<Application> applist = Applist
// .getApplist(context, bizId, this);
ApplicationCriteria acriteria = new ApplicationCriteria();
acriteria.createCriteria().andDptIdEqualTo(bizId);
List<Application> applist = this.getApplicationDAO().selectByExample(acriteria);
for (Application app : applist) {
anodelist.add(ANode.createAppNode(app.getAppId(), (app.getProjectName())));
}
}
context.put("anodelist", anodelist);
}
// http://l.admin.taobao.org/runtime/app_view.ajax?resulthandler=anodes&action=app_view_action&event_submit_do_query_app=y&query=search4su
/**
* @param context
* @throws Exception
*/
public void doQueryApp(Context context) throws Exception {
final String appNameFuzzy = StringUtils.trimToEmpty(this.getString("query"));
// ApplicationCriteria criteria = new ApplicationCriteria();
// criteria.createCriteria().andProjectNameLike(appNameFuzzy + "%");
final IAppsFetcher fetcher = UserUtils.getAppsFetcher(this.getRequest(), this);
// .create(this.getApplicationDAO());
final List<Application> appresult = (!StringUtils.startsWith(appNameFuzzy, "search4") ? ChangeDomainAction.empty : fetcher.getApps(new CriteriaSetter() {
@Override
public void set(Criteria criteria) {
criteria.andProjectNameLike(appNameFuzzy + "%");
}
}));
Map<Integer, BizANode> biznodes = new HashMap<Integer, BizANode>();
for (Application app : appresult) {
BizANode bizNode = biznodes.get(app.getDptId());
if (bizNode == null) {
bizNode = ANode.createExtBizNode(app.getDptId(), app.getDptName());
biznodes.put(app.getDptId(), bizNode);
}
bizNode.addAppNode(app.getAppId(), app.getProjectName());
}
context.put("anodelist", new ArrayList<BizANode>(biznodes.values()));
}
/**
* @param context
* @throws Exception
* 在应用管理列表中查询应用信息
*/
public void doQuery(Context context) throws Exception {
Application app = new Application();
String appName = this.getString("appnamesuggest");
Integer dptId = this.getInt("combDptid");
String recept = this.getString("recept");
if (appName.equals("search4") && dptId == null && StringUtils.isEmpty(recept)) {
this.addErrorMessage(context, "请输入查询条件");
return;
}
if (!appName.equals("search4")) {
app.setProjectName(this.getString("appnamesuggest"));
ApplicationCriteria criteria = new ApplicationCriteria();
criteria.createCriteria().andProjectNameEqualTo(app.getProjectName());
List<Application> appList = this.getApplicationDAO().selectByExample(criteria);
Assert.assertTrue("app num could not larger than 1", appList.size() <= 1);
UsrApplyDptRecord record = new UsrApplyDptRecord();
if (appList.size() == 0) {
this.addErrorMessage(context, "应用名(“" + app.getProjectName() + "”)不存在,请重新输入");
return;
}
}
context.put("appName", appName);
context.put("dptId", dptId);
context.put("recept", recept);
}
}
| 44.306569 | 161 | 0.672817 |
37d492b032deee80eee3d6327ddc765eb91bfedb | 2,772 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.j2ee.sun.ddloaders.multiview;
import org.netbeans.modules.xml.multiview.ItemEditorHelper;
import org.netbeans.modules.xml.multiview.XmlMultiViewDataSynchronizer;
/**
* @author pfiala,pcw
*/
public abstract class TextItemEditorModel extends ItemEditorHelper.ItemEditorModel {
protected XmlMultiViewDataSynchronizer synchronizer;
private boolean emptyAllowed;
private boolean emptyIsNull;
protected TextItemEditorModel(XmlMultiViewDataSynchronizer synchronizer, boolean emptyAllowed) {
this(synchronizer, emptyAllowed, false);
}
protected TextItemEditorModel(XmlMultiViewDataSynchronizer synchronizer, boolean emptyAllowed, boolean emptyIsNull) {
this.synchronizer = synchronizer;
this.emptyAllowed = emptyAllowed;
this.emptyIsNull = emptyIsNull;
}
protected boolean validate(String value) {
return emptyAllowed ? true : value != null && value.length() > 0;
}
protected abstract void setValue(String value);
protected abstract String getValue();
public final boolean setItemValue(String value) {
if (emptyAllowed && emptyIsNull && value != null) {
while (value.length() > 0 && value.charAt(0) == ' ') {
value = value.substring(1);
}
if (value.length() == 0) {
value = null;
}
}
if (validate(value)) {
String currentValue = getValue();
if (!(value == currentValue || value != null && value.equals(currentValue))) {
setValue(value);
synchronizer.requestUpdateData();
}
return true;
} else {
return false;
}
}
public final String getItemValue() {
String value = getValue();
return value == null ? "" : value;
}
public void documentUpdated() {
setItemValue(getEditorText());
}
}
| 33.804878 | 121 | 0.665224 |
f1a8de902b08aaffdbfb03108da99fcf4d183188 | 249 | package com.example.hades.dagger2._11_global_singleton;
public class NetworkChannel {
private static final String TAG = NetworkChannel.class.getSimpleName();
public void info() {
System.out.println(TAG + "@" + hashCode());
}
}
| 24.9 | 75 | 0.698795 |
30588f459bbef676517330e299274c58b3df9284 | 895 | package com.zhou.javakc.ccds.center.service;
import com.zhou.javakc.ccds.center.dao.CenterDao;
import com.zhou.javakc.component.data.entity.ccds.Center;
import com.zhou.javakc.component.data.jpa.base.BaseService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
/**
* @author yang
* @version v0.0.1
* @date 2019/10/24 14:59
*/
@Service
public class CenterService extends BaseService<Center, CenterDao> {
public Page<Center> findAll(Center entity)
{
/*Criteria<Card> criteria = new Criteria<>();
if(!StringUtils.isEmpty(card.getCardName()))
{
criteria.add(Restrictions.eq("cardName", card.getCardName()));
}*/
PageRequest pageable = PageRequest.of(entity.getOffset(),entity.getLimit());
return dao.findAll(pageable);
}
}
| 29.833333 | 84 | 0.709497 |
96cf444190b2f3d88e9c857ed58573f72469b6ca | 599 | package cn.qhy.common.util;
import cn.qhy.common.core.CustomException;
/**
* @author qhy
* @date 2021/12/29 16:06
*/
public class AssertUtil {
public static void isTrue(boolean flag, String tips) {
if (flag) {
throw CustomException.msg(tips);
}
}
public static void isTrue(boolean flag, int code, String tips) {
if (flag) {
throw CustomException.codeMsg(code, tips);
}
}
public static void isNull(Object obj, String tips) {
if (null == obj) {
throw CustomException.msg(tips);
}
}
}
| 19.966667 | 68 | 0.580968 |
85a12a4995801b504ac1cf7d916cc17998df3153 | 5,696 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchlib.rankingexpression.rule;
import com.yahoo.searchlib.rankingexpression.ExpressionFunction;
import com.yahoo.searchlib.rankingexpression.RankingExpression;
import com.yahoo.searchlib.rankingexpression.Reference;
import com.yahoo.searchlib.rankingexpression.evaluation.Context;
import com.yahoo.searchlib.rankingexpression.evaluation.Value;
import com.yahoo.tensor.TensorType;
import com.yahoo.tensor.evaluation.TypeContext;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Map;
/**
* A node referring either to a value in the context or to a named ranking expression function.
*
* @author bratseth
*/
public final class ReferenceNode extends CompositeNode {
private final Reference reference;
/* Parses this string into a reference */
public ReferenceNode(String name) {
this.reference = Reference.simple(name).orElseGet(() -> Reference.fromIdentifier(name));
}
public ReferenceNode(String name, List<? extends ExpressionNode> arguments, String output) {
this.reference = new Reference(name,
arguments != null ? new Arguments(arguments) : Arguments.EMPTY,
output);
}
public ReferenceNode(Reference reference) {
this.reference = reference;
}
public String getName() {
return reference.name();
}
/** Returns the arguments, never null */
public Arguments getArguments() { return reference.arguments(); }
/** Returns a copy of this where the arguments are replaced by the given arguments */
public ReferenceNode setArguments(List<ExpressionNode> arguments) {
return new ReferenceNode(reference.withArguments(new Arguments(arguments)));
}
/** Returns the specific output this references, or null if none specified */
public String getOutput() { return reference.output(); }
/** Returns a copy of this node with a modified output */
public ReferenceNode setOutput(String output) {
return new ReferenceNode(reference.withOutput(output));
}
/** Returns an empty list as this has no children */
@Override
public List<ExpressionNode> children() { return reference.arguments().expressions(); }
@Override
public StringBuilder toString(StringBuilder string, SerializationContext context, Deque<String> path, CompositeNode parent) {
// A reference to an identifier (function argument or bound variable)?
if (reference.isIdentifier() && context.getBinding(getName()) != null) {
// a bound identifier: replace by the value it is bound to
return string.append(context.getBinding(getName()));
}
// A reference to a function?
ExpressionFunction function = context.getFunction(getName());
if (function != null && function.arguments().size() == getArguments().size() && getOutput() == null) {
// a function reference: replace by the referenced function wrapped in rankingExpression
if (path == null)
path = new ArrayDeque<>();
String myPath = getName() + getArguments().expressions();
if (path.contains(myPath))
throw new IllegalStateException("Cycle in ranking expression function: " + path);
path.addLast(myPath);
String functionName = getName();
boolean needSerialization = (getArguments().size() > 0) || context.needSerialization(functionName);
if ( needSerialization ) {
ExpressionFunction.Instance instance = function.expand(context, getArguments().expressions(), path);
functionName = instance.getName();
context.addFunctionSerialization(RankingExpression.propertyName(functionName), instance.getExpressionString());
for (Map.Entry<String, TensorType> argumentType : function.argumentTypes().entrySet())
context.addArgumentTypeSerialization(functionName, argumentType.getKey(), argumentType.getValue());
if (function.returnType().isPresent())
context.addFunctionTypeSerialization(functionName, function.returnType().get());
}
path.removeLast();
return string.append("rankingExpression(").append(functionName).append(')');
}
// Not resolved in this context: output as-is
return reference.toString(string, context, path, parent);
}
/** Returns the reference of this node */
public Reference reference() { return reference; }
@Override
public TensorType type(TypeContext<Reference> context) {
TensorType type = null;
try {
type = context.getType(reference);
}
catch (IllegalArgumentException e) {
throw new IllegalArgumentException(reference + " is invalid", e);
}
if (type == null)
throw new IllegalArgumentException("Unknown feature '" + this + "'");
return type;
}
@Override
public Value evaluate(Context context) {
// TODO: Context should accept a Reference instead.
if (reference.isIdentifier())
return context.get(reference.name());
else
return context.get(getName(), getArguments(), getOutput());
}
@Override
public CompositeNode setChildren(List<ExpressionNode> newChildren) {
return setArguments(newChildren);
}
@Override
public int hashCode() {
return reference.hashCode();
}
}
| 40.112676 | 129 | 0.662921 |
b7bac9ffd39c6afad546c7fddab9a65636a91495 | 547 | package com.pascalwelsch.compositeandroid.fragment;
import android.util.Log;
public class FragmentTracking extends FragmentPlugin {
private static final String TAG = FragmentTracking.class.getSimpleName();
@Override
public void onResume() {
super.onResume();
Log.v(TAG, "#1 onResume()");
}
@Override
public void onStart() {
super.onStart();
Log.v(TAG, "#1 onStart()");
}
@Override
public void onStop() {
super.onStop();
Log.v(TAG, "#1 onStop()");
}
}
| 18.862069 | 77 | 0.605119 |
396a8210cf34641322c973aa398656b6b498754a | 1,650 | package io.arivera.oss.embedded.rabbitmq;
import io.arivera.oss.embedded.rabbitmq.util.OperatingSystem;
import org.junit.Test;
import java.net.URL;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
public class OfficialArtifactRepositoryTest {
@Test
public void downloadForWindows() throws Exception {
URL url = OfficialArtifactRepository.RABBITMQ
.getUrl(PredefinedVersion.V3_6_5, OperatingSystem.WINDOWS);
assertThat(url.toString(),
equalTo("http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.5/rabbitmq-server-windows-3.6.5.zip"));
}
@Test
public void downloadForMac() throws Exception {
URL url = OfficialArtifactRepository.RABBITMQ
.getUrl(PredefinedVersion.V3_6_5, OperatingSystem.MAC_OS);
assertThat(url.toString(),
equalTo("http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.5/rabbitmq-server-mac-standalone-3.6.5.tar.xz"));
}
@Test
public void downloadForUnix() throws Exception {
URL url = OfficialArtifactRepository.RABBITMQ
.getUrl(PredefinedVersion.V3_6_5, OperatingSystem.UNIX);
assertThat(url.toString(),
equalTo("http://www.rabbitmq.com/releases/rabbitmq-server/v3.6.5/rabbitmq-server-generic-unix-3.6.5.tar.xz"));
}
@Test
public void githubRepo() throws Exception {
URL url = OfficialArtifactRepository.GITHUB
.getUrl(PredefinedVersion.V3_6_5, OperatingSystem.MAC_OS);
assertThat(url.toString(),
equalTo("https://github.com/rabbitmq/rabbitmq-server/releases/"
+ "download/rabbitmq_v3_6_5/rabbitmq-server-mac-standalone-3.6.5.tar.xz"));
}
} | 32.352941 | 120 | 0.734545 |
b1fa5045fd7f35945dcae9b49e43fd46791058f8 | 2,622 | package com.example.wollyz.assignment;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import java.util.ArrayList;
/**
* Created by Wollyz on 25/11/2016.
*/
public class displayActivity extends Activity {
ViewPager viewPager;
SwipeAdapter adapter;
int[] imgid;
private DatabaseManager db;
ArrayList<String> landmarks = new ArrayList<>();
Cursor cursor;
int position = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
Bundle var = getIntent().getExtras();
String name = var.getString("LandmarkName");
viewPager =(ViewPager)findViewById(R.id.view_pager);
//storing the r.drawable of
switch(name){
case "China":
{
imgid = new int[]{
R.drawable.great_wall_of_china,
R.drawable.forbidden_city,
R.drawable.terracotta_army};
break;
}
case "Italy": {
imgid = new int[]{
R.drawable.colosseum,
R.drawable.sistine_chapel,
};
break;
}
case "America":
{
imgid = new int[]{
R.drawable.white_house
};
break;
}
case "France":{
imgid = new int[]{
R.drawable.eiffel_tower,
R.drawable.arc_de_triomphe
};
break;
}
case "Egypt":{
imgid = new int[]{
R.drawable.the_great_sphinx,
R.drawable.pyramids_of_giza
};
break;
}
}//end switch
db = new DatabaseManager(this);
db.open();
cursor = db.getLandmarksByCountry(name);
cursor.moveToFirst();
while(cursor.isAfterLast()==false)
{
landmarks.add(cursor.getString(1));
cursor.moveToNext();
}
Bundle b = getIntent().getExtras();
//name = b.getStringArrayList("landmarks");
adapter = new SwipeAdapter(this,imgid, landmarks);
viewPager.setAdapter(adapter);
}
}
| 26.484848 | 60 | 0.519069 |
d340b90bd59c7318faa6a8e44a0a43d68a621879 | 3,438 | package top.zhogjianhao.jmh.contrast.str;
import cn.hutool.core.util.StrUtil;
import org.junit.jupiter.api.Test;
import org.openjdk.jmh.annotations.*;
import top.zhogjianhao.StringUtils;
import java.util.concurrent.TimeUnit;
@State(Scope.Benchmark)
@Threads(1)
@Fork(1)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 5, time = 1)
@Measurement(iterations = 5, time = 1)
@BenchmarkMode(Mode.All)
public class FormatTest {
public static void main(String[] args) {
// 结果是否相等
FormatTest test = new FormatTest();
System.out.println(test.formatByHutool().equals(test.formatByZUtil()));
}
@Test
public void benchmark() throws Exception {
org.openjdk.jmh.Main.main(new String[]{FormatTest.class.getName()});
}
private static final String format = "{}爱{}";
private static final String arg1 = "我真的";
private static final String arg2 = "你啊";
@Benchmark
public String formatByHutool() {
return StrUtil.format(format, arg1, arg2);
}
@Benchmark
public String formatByZUtil() {
return StringUtils.format(format, arg1, arg2);
}
}
// Benchmark Mode Cnt Score Error Units
// FormatTest.formatByHutool thrpt 5 18.008 ± 0.223 ops/us
// FormatTest.formatByZUtil thrpt 5 19.756 ± 0.481 ops/us
// FormatTest.formatByHutool avgt 5 0.055 ± 0.002 us/op
// FormatTest.formatByZUtil avgt 5 0.052 ± 0.002 us/op
// FormatTest.formatByHutool sample 168209 0.095 ± 0.018 us/op
// FormatTest.formatByHutool:formatByHutool·p0.00 sample ≈ 0 us/op
// FormatTest.formatByHutool:formatByHutool·p0.50 sample 0.100 us/op
// FormatTest.formatByHutool:formatByHutool·p0.90 sample 0.100 us/op
// FormatTest.formatByHutool:formatByHutool·p0.95 sample 0.100 us/op
// FormatTest.formatByHutool:formatByHutool·p0.99 sample 0.200 us/op
// FormatTest.formatByHutool:formatByHutool·p0.999 sample 0.700 us/op
// FormatTest.formatByHutool:formatByHutool·p0.9999 sample 11.829 us/op
// FormatTest.formatByHutool:formatByHutool·p1.00 sample 812.032 us/op
// FormatTest.formatByZUtil sample 177572 0.087 ± 0.006 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.00 sample ≈ 0 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.50 sample 0.100 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.90 sample 0.100 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.95 sample 0.100 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.99 sample 0.200 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.999 sample 0.500 us/op
// FormatTest.formatByZUtil:formatByZUtil·p0.9999 sample 11.090 us/op
// FormatTest.formatByZUtil:formatByZUtil·p1.00 sample 247.296 us/op
// FormatTest.formatByHutool ss 5 27.680 ± 42.249 us/op
// FormatTest.formatByZUtil ss 5 12.720 ± 21.347 us/op
| 48.422535 | 93 | 0.594241 |
681822ed50a973890e45b357875f5d930b28eab2 | 2,564 | import vtk.vtkNativeLibrary;
import vtk.vtkRenderWindow;
import vtk.vtkRenderWindowInteractor;
import vtk.vtkRenderer;
import vtk.vtkNamedColors;
import vtk.vtkActorCollection;
import vtk.vtk3DSImporter;
import vtk.vtkCamera;
public class ThreeDSImporter
{
// -----------------------------------------------------------------
// Load VTK library and print which library was not properly loaded
static
{
if (!vtkNativeLibrary.LoadAllNativeLibraries())
{
for (vtkNativeLibrary lib : vtkNativeLibrary.values())
{
if (!lib.IsLoaded())
{
System.out.println(lib.GetLibraryName() + " not loaded");
}
}
}
vtkNativeLibrary.DisableOutputWindow(null);
}
// -----------------------------------------------------------------
public static void main(String args[])
{
//parse command line arguments
if (args.length != 1)
{
System.err.println("Usage: java -classpath ... Filename(.3ds) e.g iflamingo.3ds");
return;
}
String inputFilename = args[0];
vtkNamedColors Color = new vtkNamedColors();
//Renderer Background Color
double BgColor[] = new double[4];
double BgColor2[] = new double[4];
//Change Color Name to Use your own Color for Renderer Background
Color.GetColor("Gold",BgColor);
Color.GetColor("Wheat",BgColor2);
// Create the renderer, render window and interactor.
vtkRenderer ren = new vtkRenderer();
vtkRenderWindow renWin = new vtkRenderWindow();
renWin.AddRenderer(ren);
vtkRenderWindowInteractor iren = new vtkRenderWindowInteractor();
iren.SetRenderWindow(renWin);
vtk3DSImporter importer = new vtk3DSImporter();
importer.SetFileName(inputFilename);
importer.ComputeNormalsOn();
renWin.AddRenderer(ren);
ren.SetBackground2 (BgColor);
ren.SetBackground (BgColor2);
ren.GradientBackgroundOn();
importer.SetRenderWindow(renWin);
importer.Update();
vtkActorCollection actors = new vtkActorCollection();
actors = ren.GetActors();
System.out.println("There are" + " " + actors.GetNumberOfItems() + " " + "actors");
renWin.SetSize(300,300);
renWin.Render();
vtkCamera camera = new vtkCamera();
camera.SetPosition (0, -1, 0);
camera.SetFocalPoint (0, 0, 0);
camera.SetViewUp (0, 0, 1);
camera.Azimuth(150);
camera.Elevation(30);
ren.SetActiveCamera(camera);
ren.ResetCamera();
ren.ResetCameraClippingRange();
iren.Initialize();
iren.Start();
}
}
| 27.276596 | 88 | 0.631045 |
44eb97f9e1feca2be1c63994eae8c78213f239a5 | 617 | package oop;
public class BaseAdvertising {
private int ID;
private int clicks = 0;
private int views = 0;
public BaseAdvertising() {
}
public int getID() {
return this.ID;
}
public void setID(int ID) {
this.ID = ID;
}
public int getClicks() {
return this.clicks;
}
public void incClicks() {
this.clicks += 1;
}
public int getViews() {
return this.views;
}
public void incViews() {
this.views += 1;
}
public String describeMe() {
return "Class BaseAdvertising";
}
}
| 14.690476 | 39 | 0.531605 |
02b92722608aa3b506c2a80dfb6c26c34c0cdaaa | 220 | package com.payu.ratel.client;
import com.payu.ratel.context.RemoteServiceCallListener;
public interface RatelServiceCallPublisher {
void addRatelServiceCallListener(RemoteServiceCallListener listener);
}
| 24.444444 | 74 | 0.813636 |
53ce69d4d697b49b459bd4e210f84745d594a9e9 | 240 | package dhl.businessLogic.traning;
import dhl.businessLogic.leagueModel.interfaceModel.ILeagueObjectModel;
public interface ITraining {
ILeagueObjectModel updatePlayerStats(ILeagueObjectModel objLeagueObjectModel) throws Exception;
}
| 30 | 99 | 0.8625 |
bf445974f4cb9357192c103c99291310a660d053 | 557 | package com.design.statepattern;
/**
* @author Kunal Sharma at 12/10/20 10:52 PM
*/
public class GameTest {
public static void main(String[] args) {
GameContext context = new GameContext();
context.setState(new HealthyState());
context.gameAction();
System.out.println("*****");
context.setState(new SurvivalState());
context.gameAction();
System.out.println("*****");
context.setState(new DeadState());
context.gameAction();
System.out.println("*****");
}
}
| 20.62963 | 48 | 0.587074 |
93a46660a118c8053b2b923ff1e1f3af83053bfc | 4,687 | package web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.security.KeyStore;
import java.util.ArrayList;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.TrustManagerFactory;
public class WebInterfaceSSL extends WebInterface
{
private SSLServerSocketFactory sslServerSocketFactory;
private String[] sslProtocols;
public ServerSocket createSocket()
{
SSLServerSocket ss = null;
try
{
ss = (SSLServerSocket) this.sslServerSocketFactory.createServerSocket(port);
if (this.sslProtocols != null) {
ss.setEnabledProtocols(this.sslProtocols);
} else {
ss.setEnabledProtocols(ss.getSupportedProtocols());
}
ss.setUseClientMode(false);
ss.setWantClientAuth(false);
ss.setNeedClientAuth(false);
}
catch(Exception e)
{
System.out.println(e.toString());
}
return ss;
}
public WebInterfaceSSL(int port)
{
super(port);
}
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers)
{
SSLServerSocketFactory res = null;
try {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(loadedKeyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
res = ctx.getServerSocketFactory();
}
catch (Exception e)
{
System.out.println(e.toString());
//throw new IOException(e.getMessage());
}
return res;
}
/**
* Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
* loaded KeyManagerFactory. These objects must properly loaded/initialized
* by the caller.
*/
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
try {
return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
} catch (Exception e) {
System.out.println(e.toString());
//throw new IOException(e.getMessage());
}
return null;
}
/**
* Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
* certificate and passphrase
*/
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase)
{
try {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
File keystrorefile = new File(keyAndTrustStoreClasspathPath);
System.out.println(keystrorefile.getAbsolutePath());
InputStream keystoreStream = new FileInputStream(keystrorefile);//NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);
// if (keystoreStream == null)
// {
// System.out.println("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
// //throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
// return null;
// }
keystore.load(keystoreStream, passphrase);
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, passphrase);
return makeSSLSocketFactory(keystore, keyManagerFactory);
} catch (Exception e) {
System.out.println(e.toString());
//throw new IOException(e.getMessage());
}
return null;
}
public synchronized void getQueue(ArrayList<WebRequest> q)
{
q.addAll(queue);
queue.clear();
}
public synchronized void queue(WebRequest e)
{
queue.add(e);
}
public void run()
{
File f =new File("keystore.jks");
System.out.println(f.getAbsolutePath());
System.setProperty("javax.net.ssl.trustStore", f.getAbsolutePath());
sslServerSocketFactory = makeSSLSocketFactory(f.getAbsolutePath(), "csc1009".toCharArray());
try
{
final ServerSocket ss = createSocket();
while( true )
new WebRequest( this, ss.accept() );
}
catch ( IOException ioe )
{}
}
}
| 33.241135 | 145 | 0.664604 |
857f28ef9a8921179d49b23c4e4c9fbda8b65f60 | 2,306 | package utilidades;
import java.util.ArrayList;
import java.util.List;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Function;
import modelo.Elemento;
import aprendizado.RegressaoLogistica2;
import aprendizado.Regressao;
import aprendizado.RegressaoLogistica;
import entrada_saida.CategorizacaoPorFaixas;
import entrada_saida.PreenchimentoPrimeiroCampo;
import extracaoFeatures.Extrator;
import extracaoFeatures.ExtratorBinario;
import extracaoFeatures.IgualdadePrimeiroCampo;
public abstract class Constantes {
public static final double VALOR_POSITIVO = 1.0;
public static final double VALOR_NEGATIVO = 0.0;
public static final double LIMIAR_PADRAO = 0.5;
public static final double PORCENTAGEM_TESTE_PADRAO = 0.3;
public static final int REPETICOES_TESTE_CONFIANCA = 100;
public static final double TOLERANCIA_PADRAO_DESDUPLICACAO = 0.02;
public static final String STRING_IGUAIS = "IGUAIS";
public static final String STRING_DIFERENTES = "DIFERENTES";
public static final Function<Double, String> CATEGORIZACAO_PADRAO;
public static final BiFunction<Elemento, Elemento, Elemento> PREENCHIMENTO_PADRAO = new PreenchimentoPrimeiroCampo();
static {
List<Double> corte = new ArrayList<Double>();
corte.add(LIMIAR_PADRAO);
List<String> categorias = new ArrayList<String>();
categorias.add(STRING_IGUAIS);
categorias.add(STRING_DIFERENTES);
CATEGORIZACAO_PADRAO = new CategorizacaoPorFaixas(categorias, corte);
}
public static final BiPredicate<Elemento, Elemento> COMPARADOR_ELEMENTO_PADRAO = new IgualdadePrimeiroCampo();
//COnstantes relativas ao arquivo de saida
public static final String NOME_COLUNA_CERTEZA_CLASSIFICACAO = "Certeza";
public static final String TIPO_COLUNA_CERTEZA_CLASSIFICACAO = "numero";
public static final String NOME_COLUNA_CATEGORIA_CLASSIFICACAO = "Categoria";
public static final String TIPO_COLUNA_CATEGORIA_CLASSIFICACAO = "string";
public static final Extrator EXTRATOR_PADRAO = new ExtratorBinario();
public static final Regressao REGRESSAO_PADRAO = new RegressaoLogistica2();
public static final String DELIMITADOR_CAMPOS = "\";\""; //";" -> mais seguro que so usar ;
public static final String ASPAS = "\"";
}
| 41.927273 | 119 | 0.791847 |
34f03ed1f56c223d976d73e1be805f9b8bbc12b6 | 885 | /*
* Copyright (c) teris.io & Oleg Sklyar, 2017. All rights reserved
*/
package io.teris.kite.rpc.jms;
import java.util.concurrent.CompletableFuture;
import javax.annotation.Nonnull;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import io.teris.kite.rpc.ServiceExporter;
import io.teris.kite.rpc.jms.JmsServiceExporterImpl.ConfiguratorImpl;
public interface JmsServiceExporter {
@Nonnull
JmsServiceExporter export(@Nonnull ServiceExporter serviceExporter) throws JMSException;
@Nonnull
JmsServiceExporter start() throws JMSException;
@Nonnull
CompletableFuture<Void> close();
@Nonnull
static Configurator connectionFactory(@Nonnull ConnectionFactory connectionFactory) {
return new ConfiguratorImpl(connectionFactory);
}
interface Configurator {
@Nonnull
JmsServiceExporter requestTopic(String requestTopic) throws JMSException;
}
}
| 22.692308 | 89 | 0.80565 |
ef1a9453d3f92443ce2230ae288b30fdd88d1990 | 1,768 | package org.cytoscape.rest.internal.serializer;
import java.io.IOException;
import java.util.List;
import java.util.Set;
import org.cytoscape.group.CyGroup;
import org.cytoscape.model.CyEdge;
import org.cytoscape.model.CyIdentifiable;
import org.cytoscape.model.CyNode;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
public class GroupSerializer extends JsonSerializer<CyGroup> {
@Override
public Class<CyGroup> handledType() {
return CyGroup.class;
}
@Override
public void serialize(final CyGroup group, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
jgen.useDefaultPrettyPrinter();
jgen.writeStartObject();
final CyNode groupNode = group.getGroupNode();
final List<CyNode> memberNodes = group.getNodeList();
final List<CyEdge> internalEdges = group.getInternalEdgeList();
final Set<CyEdge> externalEdges = group.getExternalEdgeList();
jgen.writeNumberField(CyIdentifiable.SUID, groupNode.getSUID());
// TODO: Bug? Always false
// jgen.writeBooleanField("collapsed", group.isCollapsed(group.getRootNetwork()));
jgen.writeArrayFieldStart("nodes");
for (final CyNode node : memberNodes) {
jgen.writeNumber(node.getSUID());
}
jgen.writeEndArray();
jgen.writeArrayFieldStart("internal_edges");
for (final CyEdge edge : internalEdges) {
jgen.writeNumber(edge.getSUID());
}
jgen.writeEndArray();
jgen.writeArrayFieldStart("external_edges");
for (final CyEdge edge : externalEdges) {
jgen.writeNumber(edge.getSUID());
}
jgen.writeEndArray();
jgen.writeEndObject();
}
}
| 28.516129 | 112 | 0.769796 |
75e026dbc57ac2ccbaa838257586de0e67b7244a | 6,905 | package eu.semagrow.core.impl.optimizer;
import eu.semagrow.core.impl.plan.ops.BindJoin;
import eu.semagrow.core.impl.plan.ops.HashJoin;
import eu.semagrow.core.impl.plan.ops.MergeJoin;
import eu.semagrow.core.impl.plan.ops.SourceQuery;
import eu.semagrow.core.plan.Plan;
import org.openrdf.query.BindingSet;
import org.openrdf.query.Dataset;
import org.openrdf.query.algebra.*;
import org.openrdf.query.algebra.evaluation.QueryOptimizer;
import org.openrdf.query.algebra.helpers.QueryModelVisitorBase;
import org.openrdf.query.algebra.helpers.VarNameCollector;
import java.util.HashSet;
import java.util.Set;
/**
* A semantically-preserved optimizer that pushes down @{link Extension} nodes
* as far as possible. This optimizer can be useful when @{link Extension} contain
* custom functions that can be executed only by the remote sources.
* @author Angelos Charalambidis
*/
public class ExtensionOptimizer implements QueryOptimizer {
@Override
public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindingSet) {
tupleExpr.visit(new ExtensionFinder(tupleExpr));
}
protected static class ExtensionFinder extends QueryModelVisitorBase<RuntimeException> {
protected final TupleExpr tupleExpr;
public ExtensionFinder(TupleExpr tupleExpr) {
this.tupleExpr = tupleExpr;
}
@Override
public void meet(Extension filter) {
super.meet(filter);
if (!hasAggregates(filter))
ExtensionRelocator.relocate(filter);
}
}
private static boolean hasAggregates(Extension ext) {
for (ExtensionElem e : ext.getElements()) {
if (e.getExpr() instanceof AggregateOperator)
return true;
}
return false;
}
/*-----------------------------*
* Inner class ExtensionRelocator *
*-----------------------------*/
protected static class ExtensionRelocator extends QueryModelVisitorBase<RuntimeException> {
public static void relocate(Extension e) {
e.visit(new ExtensionRelocator(e));
}
protected final Extension extension;
protected final Set<String> vars;
public ExtensionRelocator(Extension extension) {
this.extension = extension;
vars = new HashSet<String>();
for (ExtensionElem e : extension.getElements())
vars.addAll(VarNameCollector.process(e.getExpr()));
}
@Override
protected void meetNode(QueryModelNode node) {
// By default, do not traverse
assert node instanceof TupleExpr;
relocate(extension, (TupleExpr) node);
}
@Override
public void meet(Join join) {
if (join.getLeftArg().getBindingNames().containsAll(vars)) {
// All required vars are bound by the left expr
join.getLeftArg().visit(this);
}
else if (join.getRightArg().getBindingNames().containsAll(vars)) {
// All required vars are bound by the right expr
join.getRightArg().visit(this);
}
else {
relocate(extension, join);
}
}
@Override
public void meet(LeftJoin leftJoin) {
if (leftJoin.getLeftArg().getBindingNames().containsAll(vars)) {
leftJoin.getLeftArg().visit(this);
}
else {
relocate(extension, leftJoin);
}
}
@Override
public void meet(Union union) {
Extension clone = new Extension();
clone.setElements(extension.getElements());
relocate(extension, union.getLeftArg());
relocate(clone, union.getRightArg());
ExtensionRelocator.relocate(extension);
ExtensionRelocator.relocate(clone);
}
@Override
public void meet(Difference node) {
Extension clone = new Extension();
clone.setElements(extension.getElements());
relocate(extension, node.getLeftArg());
relocate(clone, node.getRightArg());
ExtensionRelocator.relocate(extension);
ExtensionRelocator.relocate(clone);
}
@Override
public void meet(Intersection node) {
Extension clone = new Extension();
clone.setElements(extension.getElements());
relocate(extension, node.getLeftArg());
relocate(clone, node.getRightArg());
ExtensionRelocator.relocate(extension);
ExtensionRelocator.relocate(clone);
}
@Override
public void meet(Extension node) {
if (node.getArg().getBindingNames().containsAll(vars)) {
node.getArg().visit(this);
}
else {
relocate(extension, node);
}
}
@Override
public void meet(EmptySet node) {
if (extension.getParentNode() != null) {
// Remove filter from its original location
extension.replaceWith(extension.getArg());
}
}
@Override
public void meet(Filter filter) {
// Filters are commutative
filter.getArg().visit(this);
}
@Override
public void meet(Distinct node) {
node.getArg().visit(this);
}
@Override
public void meet(Order node) {
node.getArg().visit(this);
}
@Override
public void meet(QueryRoot node) {
node.getArg().visit(this);
}
@Override
public void meet(Reduced node) {
node.getArg().visit(this);
}
public void meet(SourceQuery node) { node.getArg().visit(this); }
@Override
public void meetOther(QueryModelNode node) {
if (node instanceof Plan)
((Plan) node).getArg().visit(this);
else if (node instanceof BindJoin)
meet((Join)node);
else if (node instanceof HashJoin)
meet((Join)node);
else if (node instanceof MergeJoin)
meet((Join)node);
else if (node instanceof SourceQuery)
meet((SourceQuery)node);
else
meetNode(node);
}
protected void relocate(Extension e, TupleExpr newFilterArg) {
if (e.getArg() != newFilterArg) {
if (e.getParentNode() != null) {
// Remove filter from its original location
e.replaceWith(e.getArg());
}
// Insert filter at the new location
newFilterArg.replaceWith(e);
e.setArg(newFilterArg);
}
}
}
} | 30.688889 | 95 | 0.576394 |
6f6e36f00b1dd8a57e04d0ef397f719beb85ff6c | 6,391 | package com.ngdesk.nodes;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.bson.types.ObjectId;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.ngdesk.Global;
@Component
public class GetEntries extends Node {
private final Logger log = LoggerFactory.getLogger(GetEntries.class);
@Autowired
private Global global;
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private Environment environment;
@Autowired
private SimpMessagingTemplate template;
@Override
public Map<String, Object> executeNode(Document node, Map<String, Object> inputMessage) {
Map<String, Object> resultMap = new HashMap<String, Object>();
try {
log.trace("Enter GetEntries.executeNode()");
String companyUUID = (String) inputMessage.get("COMPANY_UUID");
Document companyDocument = global.getCompanyFromUUID(companyUUID);
String companyId = companyDocument.getObjectId("_id").toString();
Document values = (Document) node.get("VALUES");
String moduleId = values.getString("MODULE");
MongoCollection<Document> modulesCollection = mongoTemplate.getCollection("modules_" + companyId);
Document moduleDocument = modulesCollection.find(Filters.eq("_id", new ObjectId(moduleId))).first();
if (moduleDocument != null) {
String moduleName = moduleDocument.getString("NAME");
String response = null;
List<Document> entriesList = new ArrayList<Document>();
JSONObject valuesJson = new JSONObject(values.toJson());
if (valuesJson.has("FIELDS")) {
JSONArray fields = valuesJson.getJSONArray("FIELDS");
JSONObject moduleJson = new JSONObject(moduleDocument.toJson());
JSONArray moduleFields = moduleJson.getJSONArray("FIELDS");
List<Bson> filters = generateFilter(fields, companyId, moduleFields, inputMessage);
MongoCollection<Document> collection = mongoTemplate.getCollection(moduleName.replaceAll("\\s+", "_") + "_" + companyId);
entriesList = collection.find(Filters.and(filters)).into(new ArrayList<Document>());
} else {
MongoCollection<Document> collection = mongoTemplate.getCollection(moduleName.replaceAll("\\s+", "_") + "_" + companyId);
entriesList = collection.find().into(new ArrayList<Document>());
}
JSONArray entriesJson = new JSONArray();
for (Document entry : entriesList) {
String entryId = entry.getObjectId("_id").toString();
entry.remove("_id");
JSONObject entryJson = new JSONObject(entry.toJson());
entry.put("DATA_ID", entryId);
entriesJson.put(entry);
}
if (entriesJson.length() > 0) {
JSONObject responseJson = new JSONObject();
responseJson.put("DATA", entriesJson);
response = responseJson.toString();
}
if (response != null) {
Map<String, Object> responseMap = new ObjectMapper().readValue(response,
new TypeReference<Map<String, Object>>() {
});
List<Map<String, Object>> moduleEntriesList = (ArrayList) responseMap.get("DATA");
Map<String, List<Map<String, Object>>> entries = new HashMap<>();
entries.put("ENTRIES", moduleEntriesList);
inputMessage.put((String) inputMessage.get("NODE_NAME"), entries);
}
ArrayList<Document> connections = (ArrayList<Document>) node.get("CONNECTIONS_TO");
if (connections.size() == 1) {
Document connection = connections.get(0);
resultMap.put("NODE_ID", connection.getString("TO_NODE"));
}
}
resultMap.put("INPUT_MESSAGE", inputMessage);
} catch (Exception e) {
e.printStackTrace();
}
log.trace("Exit GetEntries.executeNode()");
return resultMap;
}
public List<Bson> generateFilter(JSONArray nodeFields, String companyId, JSONArray moduleFields,
Map<String, Object> inputMessage) {
log.trace("Enter GetEntries.generateFilter()");
List<Bson> customFilters = new ArrayList<Bson>();
HashMap<String, String> fieldNames = new HashMap<String, String>();
for (int i = 0; i < moduleFields.length(); i++) {
JSONObject moduleField = moduleFields.getJSONObject(i);
String name = moduleField.getString("NAME");
String fieldId = moduleField.getString("FIELD_ID");
fieldNames.put(fieldId, name);
}
for (int i = 0; i < nodeFields.length(); i++) {
JSONObject field = nodeFields.getJSONObject(i);
String operator = field.getString("OPERATOR");
List<String> val = (List<String>) field.get("VALUE");
// TODO: Handle cases where its one to many and many to many
String value = val.get(0);
value = global.getValue(value, inputMessage);
String fieldId = field.getString("FIELD");
String fieldName = fieldNames.get(fieldId);
if (operator.equalsIgnoreCase("equals to") || operator.equalsIgnoreCase("is checked")) {
customFilters.add(Filters.eq(fieldName, value));
} else if (operator.equalsIgnoreCase("not equals")) {
customFilters.add(Filters.ne(fieldName, value));
} else if (operator.equalsIgnoreCase("greather than")) {
customFilters.add(Filters.gt(fieldName, value));
} else if (operator.equalsIgnoreCase("less than")) {
customFilters.add(Filters.lt(fieldName, value));
} else if (operator.equalsIgnoreCase("greater than or equals to")) {
customFilters.add(Filters.gte(fieldName, value));
} else if (operator.equalsIgnoreCase("less than or equals to")) {
customFilters.add(Filters.lte(fieldName, value));
} else if (operator.equalsIgnoreCase("contain")) {
customFilters.add(Filters.regex(fieldName, ".*" + value + ".*"));
} else if (operator.equalsIgnoreCase("does not contain")) {
customFilters.add(Filters.not(Filters.regex(fieldName, ".*" + value + ".*")));
}
}
log.trace("Exit GetEntries.generateFilter()");
return customFilters;
}
}
| 35.115385 | 126 | 0.719449 |
3063c01fb42be7987d9fa618d7843eda6f3a23f3 | 515 | package com.roy.design.visitor.store;
import com.roy.design.visitor.visitor.Human;
public class Cafe implements Store {
private static final int TOTAL_SEAT = 5;
private int usedSeat = 0;
@Override
public void accept(Human human) {
human.visit(this);
}
@Override
public void addVisitor() {
usedSeat++;
}
@Override
public int getTotalSeat() {
return TOTAL_SEAT;
}
@Override
public int getUsedSeat() {
return usedSeat;
}
}
| 17.166667 | 44 | 0.621359 |
29d9fd9e3c63167c81e2e4481f76fabd05bde60a | 330 | package com.github.jeasyrest.ioc;
import com.github.jeasyrest.ioc.util.InjectionMap;
public class Injections extends InjectionMap {
public static final Injections INSTANCE = new Injections();
private Injections(String... mapNames) {
super("META-INF/jeasyrest/injections", "jeasyrest/injections");
}
}
| 23.571429 | 71 | 0.727273 |
d1560f1fd903d123e387fa81fdb158493e0f147c | 167 | package com.withwiz.plankton.network.message2;
/**
* Message body interface
*/
public interface IMessageBody<TYPE_RAW_DATA> extends IMessagePart<TYPE_RAW_DATA> {
}
| 20.875 | 82 | 0.790419 |
817a80053a02505fec07e687776f9327007e7079 | 1,478 | package me.coley.bmf.attribute.method;
import me.coley.bmf.util.Measurable;
/**
* Local variable entry for the
* {@link me.coley.bmf.attribute.method.LocalVariableTable}.
* <ul>
* <li>{@link #start}
* <li>{@link #length}
* <li>{@link #name}
* <li>{@link #desc}
* <li>{@link #index}
* </ul>
*
* @author Matt
*/
public class Local implements Measurable {
/**
* Start index in the opcodes
*/
public int start;
/**
* Length from start local lasts in the opcodes
*/
public int length;
/**
* Constant pool pointers
*/
public int name;
public int desc;
/**
* Stack frame index. Doubles/Longs take two indices.
*/
public int index;
/**
* Creates and assigned values to the local variable entry.
*
* @param start
* {@link #start}
* @param length
* {@link #length}
* @param name
* {@link #name}
* @param desc
* {@link #desc}
* @param index
* {@link #index}
*/
public Local(int start, int length, int name, int desc, int index) {
this.start = start;
this.length = length;
this.name = name;
this.desc = desc;
this.index = index;
}
@Override
public int getLength() {
// u2: start_pc
// u2: length
// u2: name_index
// u2: descriptor_index
// u2: index
return 10;
}
} | 21.42029 | 72 | 0.523004 |
2f444f3c16db7c60b9f8bd509b5b64c5378e609c | 3,552 | /*
* Copyright 2019-2020 The Polypheny Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.polypheny.db.information;
import java.util.HashMap;
import org.junit.Assert;
import org.junit.Test;
import org.polypheny.db.information.InformationGraph.GraphData;
import org.polypheny.db.information.InformationGraph.GraphType;
public class InformationManagerTest {
private InformationManager im;
private static InformationPage p = new InformationPage( "page1", "Page 1", "Test Page 1" );
private static InformationGroup g = new InformationGroup( p, "Group 1.1" );
static {
InformationManager im = InformationManager.getInstance();
im.addPage( p );
im.addGroup( g );
Information i1 = new InformationProgress( g, "progval", 30 );
Information i2 = new InformationHtml( g, "<b>bold</b>" );
im.registerInformation( i1, i2 );
}
public InformationManagerTest() {
this.im = InformationManager.getInstance();
}
@Test
public void getPage() {
System.out.println( this.im.getPage( "page1" ).asJson() );
//Gson gson = new Gson();
//InformationPage p = gson.fromJson( this.im.getPage( "page1" ).asJson(), InformationPage.class );
}
@Test
public void getPageList() {
System.out.println( this.im.getPageList() );
}
@Test
public void informationType() {
Information i1 = new InformationHtml( "id", "group", "html" );
Assert.assertEquals( "InformationHtml", i1.type );
}
@Test(expected = RuntimeException.class)
public void graphThrowingError() {
String[] labels = { "Jan", "Feb", "März", "April", "Mail", "Juni" };
Integer[] graphData1 = { 5, 2, 7, 3, 2, 1 };
Integer[] graphData2 = { 7, 8, 2, 2, 7, 3 };
GraphData[] graphData = { new GraphData<>( "data1", graphData1 ), new GraphData<>( "data2", graphData2 ) };
Information i1 = new InformationGraph( g, GraphType.PIE, labels, graphData );
}
@Test
public void changeGraphType() {
String[] labels = { "Jan", "Feb", "März", "April", "Mail", "Juni" };
Integer[] graphData1 = { 5, 2, 7, 3, 2, 1 };
Integer[] graphData2 = { 7, 8, 2, 2, 7, 3 };
GraphData[] graphData = { new GraphData<>( "data1", graphData1 ), new GraphData<>( "data2", graphData2 ) };
InformationGraph i1 = new InformationGraph( g, GraphType.LINE, labels, graphData );
i1.updateType( GraphType.RADAR );
}
@Test
public void informationAction() {
final String[] test = { "", "" };
InformationAction action = new InformationAction( g, "btnLabel", ( params ) -> {
test[0] = "a";
test[1] = params.get( "param1" );
return "done";
} );
HashMap<String, String> params = new HashMap<>();
params.put( "param1", "b" );
action.executeAction( params );
Assert.assertEquals( test[0], "a" );
Assert.assertEquals( test[1], "b" );
}
}
| 32 | 115 | 0.623029 |
e2bb4207a7ede7f4654277e62f44899ece14dd8a | 160 | package com.jtransc.io.async.impl;
import com.jtransc.io.async.JTranscAsyncResources;
public class JTranscAsyncResourcesJVM extends JTranscAsyncResources {
}
| 22.857143 | 69 | 0.84375 |
5dd5075d18f6c18a54410a9cbfdaf339139f78a0 | 8,133 | /*
*
* * Copyright 2021 UBICUA.
* *
* * 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 ssido.model;
import androidx.annotation.NonNull;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Optional;
/**
* This class may be used to specify requirements regarding authenticator attributes.
*
* @see <a href="https://www.w3.org/TR/webauthn/#dictdef-authenticatorselectioncriteria">§5.4.4.
* Authenticator Selection Criteria (dictionary AuthenticatorSelectionCriteria)
* </a>
*/
public final class AuthenticatorSelectionCriteria {
/**
* If present, eligible authenticators are filtered to only authenticators attached with the specified <a
* href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration
* (enum AuthenticatorAttachment)</a>.
*/
@NonNull
private final Optional<AuthenticatorAttachment> authenticatorAttachment;
/**
* Describes the Relying Party's requirements regarding resident credentials. If set to <code>true</code>, the
* authenticator MUST create a <a href="https://www.w3.org/TR/webauthn/#client-side-resident-public-key-credential-source">client-side-resident
* public key credential source</a> when creating a public key credential.
*/
private final boolean requireResidentKey;
/**
* Describes the Relying Party's requirements regarding <a href="https://www.w3.org/TR/webauthn/#user-verification">user
* verification</a> for the
* <code>navigator.credentials.create()</code> operation. Eligible authenticators are filtered to only those
* capable of satisfying this requirement.
*/
@NonNull
private final UserVerificationRequirement userVerification;
@JsonCreator
private AuthenticatorSelectionCriteria(
@JsonProperty("authenticatorAttachment") AuthenticatorAttachment authenticatorAttachment,
@JsonProperty("requireResidentKey") boolean requireResidentKey,
@NonNull @JsonProperty("userVerification") UserVerificationRequirement userVerification) {
this(Optional.fromNullable(authenticatorAttachment), requireResidentKey, userVerification);
}
public static class AuthenticatorSelectionCriteriaBuilder {
private boolean requireResidentKey = false;
private UserVerificationRequirement userVerification = UserVerificationRequirement.PREFERRED;
@NonNull
private Optional<AuthenticatorAttachment> authenticatorAttachment = Optional.absent();
/**
* If present, eligible authenticators are filtered to only authenticators attached with the specified <a
* href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration
* (enum AuthenticatorAttachment)</a>.
* @param authenticatorAttachment
* @return
*/
public AuthenticatorSelectionCriteriaBuilder authenticatorAttachment(@NonNull Optional<AuthenticatorAttachment> authenticatorAttachment) {
this.authenticatorAttachment = authenticatorAttachment;
return this;
}
/**
* If present, eligible authenticators are filtered to only authenticators attached with the specified <a
* href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration
* (enum AuthenticatorAttachment)</a>.
* @param authenticatorAttachment
* @return
*/
public AuthenticatorSelectionCriteriaBuilder authenticatorAttachment(@NonNull AuthenticatorAttachment authenticatorAttachment) {
return this.authenticatorAttachment(Optional.of(authenticatorAttachment));
}
@SuppressWarnings("all")
AuthenticatorSelectionCriteriaBuilder() {
}
/**
* Describes the Relying Party's requirements regarding resident credentials. If set to <code>true</code>, the
* authenticator MUST create a <a href="https://www.w3.org/TR/webauthn/#client-side-resident-public-key-credential-source">client-side-resident
* public key credential source</a> when creating a public key credential.
*/
@SuppressWarnings("all")
public AuthenticatorSelectionCriteriaBuilder requireResidentKey(final boolean requireResidentKey) {
this.requireResidentKey = requireResidentKey;
return this;
}
/**
* Describes the Relying Party's requirements regarding <a href="https://www.w3.org/TR/webauthn/#user-verification">user
* verification</a> for the
* <code>navigator.credentials.create()</code> operation. Eligible authenticators are filtered to only those
* capable of satisfying this requirement.
*/
@SuppressWarnings("all")
public AuthenticatorSelectionCriteriaBuilder userVerification(@NonNull final UserVerificationRequirement userVerification) {
this.userVerification = userVerification;
return this;
}
public AuthenticatorSelectionCriteria build() {
boolean requireResidentKey = this.requireResidentKey;
UserVerificationRequirement userVerification = this.userVerification;
return new AuthenticatorSelectionCriteria(authenticatorAttachment, requireResidentKey, userVerification);
}
}
public static AuthenticatorSelectionCriteriaBuilder builder() {
return new AuthenticatorSelectionCriteriaBuilder();
}
public AuthenticatorSelectionCriteriaBuilder toBuilder() {
return new AuthenticatorSelectionCriteriaBuilder().authenticatorAttachment(this.authenticatorAttachment).requireResidentKey(this.requireResidentKey).userVerification(this.userVerification);
}
/**
* If present, eligible authenticators are filtered to only authenticators attached with the specified <a
* href="https://www.w3.org/TR/webauthn/#attachment">§5.4.5 Authenticator Attachment Enumeration
* (enum AuthenticatorAttachment)</a>.
*/
@NonNull
public Optional<AuthenticatorAttachment> getAuthenticatorAttachment() {
return this.authenticatorAttachment;
}
/**
* Describes the Relying Party's requirements regarding resident credentials. If set to <code>true</code>, the
* authenticator MUST create a <a href="https://www.w3.org/TR/webauthn/#client-side-resident-public-key-credential-source">client-side-resident
* public key credential source</a> when creating a public key credential.
*/
public boolean isRequireResidentKey() {
return this.requireResidentKey;
}
/**
* Describes the Relying Party's requirements regarding <a href="https://www.w3.org/TR/webauthn/#user-verification">user
* verification</a> for the
* <code>navigator.credentials.create()</code> operation. Eligible authenticators are filtered to only those
* capable of satisfying this requirement.
*/
@NonNull
public UserVerificationRequirement getUserVerification() {
return this.userVerification;
}
private AuthenticatorSelectionCriteria(
@NonNull final Optional<AuthenticatorAttachment> authenticatorAttachment,
final boolean requireResidentKey,
@NonNull final UserVerificationRequirement userVerification) {
this.authenticatorAttachment = authenticatorAttachment;
this.requireResidentKey = requireResidentKey;
this.userVerification = userVerification;
}
}
| 44.933702 | 197 | 0.718677 |
6af535ebbfeb50d779623816f3a382878ac89e24 | 3,960 | package org.auslides.security.shiro.realm;
import org.auslides.security.model.Permission;
import org.auslides.security.model.Role;
import org.auslides.security.model.User;
import org.auslides.security.repository.UserRepository;
import org.auslides.security.shiro.util.HashHelper;
import com.google.common.base.Preconditions;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.SimpleByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.LinkedHashSet;
import java.util.Set;
public class DatabaseRealm extends AuthorizingRealm {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseRealm.class.getName());
@Autowired
private UserRepository userRepository;
public DatabaseRealm() {
super(HashHelper.getCredentialsMatcher());
setAuthenticationTokenClass(UsernamePasswordToken.class);
LOGGER.debug("Creating a new instance of DatabaseRealm");
}
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthorizationInfo(principals);
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
Preconditions.checkNotNull(principals, "You can't have a null collection of principals. No really, how did you do that");
String userEmail = (String) getAvailablePrincipal(principals);
if (userEmail == null) {
throw new NullPointerException("Can't find a principal in the collection");
}
LOGGER.debug("Finding authorization info for " + userEmail + " in DB");
final User user = userRepository.findByEmailAndActive(userEmail, true);
LOGGER.debug("Found " + userEmail + " in DB");
final int totalRoles = user.getRoles().size();
final Set<String> roleNames = new LinkedHashSet<>(totalRoles);
final Set<String> permissionNames = new LinkedHashSet<>();
if (totalRoles > 0) {
for (Role role : user.getRoles()) {
roleNames.add(role.getName());
for (Permission permission : role.getPermissions()) {
permissionNames.add(permission.getName());
}
}
}
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
info.addRoles(roleNames);
info.addStringPermissions(permissionNames);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
if (token instanceof UsernamePasswordToken) {
String userEmail = ((UsernamePasswordToken) token).getUsername();
return doGetAuthenticationInfo(userEmail);
}
throw new UnsupportedOperationException("Implement another method of getting user email.");
}
private AuthenticationInfo doGetAuthenticationInfo(String email) throws AuthenticationException {
Preconditions.checkNotNull(email, "Email can't be null");
LOGGER.info("Finding authentication info for " + email + " in DB");
final User user = userRepository.findByEmailAndActive(email, true);
SimpleAccount account = new SimpleAccount(user.getEmail(), user.getPassword().toCharArray(),
new SimpleByteSource(email), getName());
final int totalRoles = user.getRoles().size();
final Set<String> roleNames = new LinkedHashSet<>(totalRoles);
final Set<String> permissionNames = new LinkedHashSet<>();
if (totalRoles > 0) {
for (Role role : user.getRoles()) {
roleNames.add(role.getName());
for (Permission permission : role.getPermissions()) {
permissionNames.add(permission.getName());
}
}
}
account.setRoles(roleNames);
account.setStringPermissions(permissionNames);
return account;
}
} | 37.714286 | 123 | 0.767929 |
90b8b0101af9a443a69a79084279638980e47700 | 2,081 | package mage.cards.a;
import mage.MageInt;
import mage.abilities.common.AttacksAloneControlledTriggeredAbility;
import mage.abilities.dynamicvalue.DynamicValue;
import mage.abilities.dynamicvalue.common.PermanentsOnBattlefieldCount;
import mage.abilities.dynamicvalue.common.StaticValue;
import mage.abilities.effects.common.continuous.BoostTargetEffect;
import mage.abilities.hint.Hint;
import mage.abilities.hint.ValueHint;
import mage.abilities.keyword.HasteAbility;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.filter.StaticFilters;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class AsariCaptain extends CardImpl {
private static final DynamicValue xValue
= new PermanentsOnBattlefieldCount(StaticFilters.FILTER_CONTROLLED_SAMURAI_OR_WARRIOR);
private static final Hint hint = new ValueHint("Samurai and Warriors you control", xValue);
public AsariCaptain(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{3}{R}{W}");
this.subtype.add(SubType.HUMAN);
this.subtype.add(SubType.SAMURAI);
this.power = new MageInt(4);
this.toughness = new MageInt(3);
// Haste
this.addAbility(HasteAbility.getInstance());
// Whenever a Samurai or Warrior you control attacks alone, it gets +1/+0 until end of turn for each Samurai or Warrior you control.
this.addAbility(new AttacksAloneControlledTriggeredAbility(
new BoostTargetEffect(xValue, StaticValue.get(0), Duration.EndOfTurn, true)
.setText("it gets +1/+0 until end of turn for each Samurai or Warrior you control"),
StaticFilters.FILTER_CONTROLLED_SAMURAI_OR_WARRIOR, true, false
).addHint(hint));
}
private AsariCaptain(final AsariCaptain card) {
super(card);
}
@Override
public AsariCaptain copy() {
return new AsariCaptain(this);
}
}
| 35.87931 | 140 | 0.730899 |
83b6c91bf02279307f9eb47bb012e86ce89ef2c0 | 2,358 | /*
* (c) Copyright 2015-2017 Micro Focus or one of its affiliates.
*
* Licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
*
* The only warranties for products and services of Micro Focus and its affiliates
* and licensors ("Micro Focus") are as may be set forth in the express warranty
* statements accompanying such products and services. Nothing herein should be
* construed as constituting an additional warranty. Micro Focus shall not be
* liable for technical or editorial errors or omissions contained herein. The
* information contained herein is subject to change without notice.
*/
package com.hp.autonomy.searchcomponents.core.config;
import java.time.Instant;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeParseException;
import java.util.Map;
import java.util.function.Function;
/**
* The different possible Idol field value types and how to convert them to {@link String}
*/
public enum FieldType {
STRING(String.class, value -> value),
DATE(ZonedDateTime.class, value -> {
try {
final long epoch = Long.parseLong(value);
return ZonedDateTime.ofInstant(Instant.ofEpochSecond(epoch), ZoneOffset.UTC);
} catch(final NumberFormatException ignore) {
try {
// HOD handles date fields inconsistently; attempt to detect this here
return ZonedDateTime.parse(value);
} catch(final DateTimeParseException ignored) {
return null;
}
}
}),
NUMBER(Number.class, Double::parseDouble),
BOOLEAN(Boolean.class, Boolean::parseBoolean),
GEOINDEX(String.class, value -> value),
// the parser won't be called - bypassed in `FieldsParserImpl` to use `RecordType`
RECORD(Map.class, value -> value);
private final Class<?> type;
@SuppressWarnings("NonSerializableFieldInSerializableClass")
private final Function<String, ?> parser;
FieldType(final Class<?> type, final Function<String, ?> parser) {
this.type = type;
this.parser = parser;
}
public Class<?> getType() {
return type;
}
public <T> T parseValue(final Class<T> type, final String stringValue) {
return type.cast(parser.apply(stringValue));
}
}
| 36.276923 | 90 | 0.690416 |
874622c81d0f5bb3628dccafedebea56f068a384 | 9,101 | package org.onetwo.common.tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.onetwo.common.utils.LangUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings("unchecked")
public class TreeBuilder<TM extends TreeModel<TM>> {
public static interface ParentNodeNotFoundAction<Node extends TreeModel<Node>> {
// DefaultTreeModel ROOT_NODE = new DefaultTreeModel("__ROOT__", "ROOT_NODE");
/***
* 返回null,则忽略
* 返回自身,则添加到根节点
* 否则,把currentNode添加到返回的父节点
* @author weishao zeng
* @param currentNode
* @return
*/
Node onParentNodeNotFound(Node currentNode);
/*default Node findParent(Map<Object, Node> nodeMap, Node node) {
return nodeMap.get(node.getId());
}*/
}
public static interface RootNodeFunc<T extends TreeModel<T>> {
// public boolean isRootNode(T node);
boolean isRootNode(T node, Map<Object, T> nodeMap);
}
public static class ReverseSortComparator<T extends TreeModel<T>> extends SortComparator<T> {
public int compare(T o1, T o2) {
return -super.compare(o1, o2);
}
}
public static class SortComparator<T extends TreeModel<T>> implements Comparator<T> {
@Override
public int compare(T o1, T o2) {
Comparable<Object> s1 = (Comparable<Object>)o1.getSort();
Comparable<Object> s2 = (Comparable<Object>)o2.getSort();
if(s1==null && s2==null){
return 0;
}else if(s1==null){
return -1;
}else if(s2==null){
return 1;
}else{
return s1.compareTo(s2);
}
}
}
public static class RootIdsFunc<T extends TreeModel<T>> implements RootNodeFunc<T> {
final private List<Object> rootIds;
public RootIdsFunc(Object... rootIds) {
super();
this.rootIds = Arrays.asList(rootIds);
}
@Override
public boolean isRootNode(T node, Map<Object, T> nodeMap) {
return rootIds.contains(node.getId()) ||
node.getParentId()==null ||
(Number.class.isInstance(node.getParentId()) && ((Number)node.getParentId()).intValue()==0);
}
}
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private Comparator<TM> comparator = new SortComparator<>();
private final ParentNodeNotFoundAction<TM> THROW_ERROR = node->{
throw new RuntimeException("build tree error: can't not find the node[" + node.getId() + ", " + node.getName() + "]'s parent node[" + node.getParentId() + "]");
};
private final ParentNodeNotFoundAction<TM> IGNORE = node->{
logger.error("build tree error: can't not find the node[" + node.getId() + ", " + node.getName() + "]'s parent node[" + node.getParentId() + "]");
return null;
};
final private Map<Object, TM> nodeMap = new LinkedHashMap<Object, TM>();
private List<TM> rootNodes = new ArrayList<TM>();
// private Comparator<Object> comparator = null;
// private List<?> rootIds;
private RootNodeFunc<TM> rootNodeFunc;
private ParentNodeNotFoundAction<TM> parentNotFoundAction = THROW_ERROR;
/*private Set<Object> notFoundParentIds = Sets.newHashSet();
public final ParentNodeNotFoundAction<TM> STORE_NOT_FOUND_PARENTS = node->{
logger.info("add node[{}]'s parent node id: {}", node, node.getParentId());
notFoundParentIds.add(node.getParentId());
return null;
};*/
public TreeBuilder(Collection<TM> datas) {
List<TM> nodes = datas.stream().filter(d -> d!=null).collect(Collectors.toList());
Collections.sort(nodes, comparator);
for(TM tm : nodes){
this.nodeMap.put(tm.getId(), tm);
}
}
public <T> TreeBuilder(Collection<T> datas, TreeModelCreator<TM, T> treeNodeCreator) {
this(datas, treeNodeCreator, null);
}
public <T> TreeBuilder(Collection<T> datas, TreeModelCreator<TM, T> treeNodeCreator, Comparator<TM> comparator) {
// Assert.notEmpty(datas);
final TreeModelCreator<TM, T> tnc = treeNodeCreator;
this.comparator = comparator != null ? comparator : this.comparator;
List<TM> tmDatas = datas.stream()
.map(e->tnc.createTreeModel(e))
.filter(e->e!=null)
.collect(Collectors.toList());
this.sortAndPutToMap(tmDatas);
}
private final void sortAndPutToMap(List<TM> datas){
Collections.sort(datas, comparator);
for(TM tm : datas){
this.nodeMap.put(tm.getId(), tm);
}
}
/*public List<?> getRootIds() {
return rootIds;
}*/
public TreeBuilder<TM> rootIds(Object...objects) {
// this.rootIds = Arrays.asList(objects);
// Collection<?> ids = CUtils.stripNull(Lists.newArrayList(objects));
if(LangUtils.isEmpty(objects))
return this;
this.rootNodeFunc = new RootIdsFunc<TM>(objects);
return this;
}
public TreeBuilder<TM> rootNodeFunc(RootNodeFunc<TM> rootNodeFunc) {
this.rootNodeFunc = rootNodeFunc;
return this;
}
public TreeBuilder<TM> ignoreParentNotFound() {
return parentNotFound(IGNORE);
}
public TreeBuilder<TM> parentNotFound(ParentNodeNotFoundAction<TM> parentNotFoundAction) {
this.parentNotFoundAction = parentNotFoundAction;
return this;
}
public List<TM> buidTree() {
return this.buidTree(parentNotFoundAction);
}
public List<TM> buidTree(ParentNodeNotFoundAction<TM> notFoundAction) {
if (nodeMap.isEmpty()) {
return Collections.EMPTY_LIST;
}
List<TM> treeModels = (List<TM>) new ArrayList<>(nodeMap.values());
// for (TM node : treeModels) {
//这个循环比较特殊,会动态修改list,所以采用这种循环方式
for (int i = 0; i < treeModels.size(); i++) {
TM node = treeModels.get(i);
/*if (node.getId().toString().contains("Politicals_DuesMgr")) {
System.out.println("test");
}*/
// 通过回调函数判断是否跟节点
if (this.rootNodeFunc!=null && this.rootNodeFunc.isRootNode(node, nodeMap)) {
addRoot(node);
continue;
}else if(node.getParentId() == null){
// 如果parentId为null,则被当做是根节点
addRoot(node);
continue;
}
// if (node.getParentId() == null || ((node.getParentId() instanceof Number) && ((Number) node.getParentId()).longValue() <= 0)) {
/*if (node.getParentId() == null) {
addRoot(node);
continue;
}*/
// 如果该节点是已存在的跟节点,则忽略
if (isExistsRootNode(node))
continue;
// TM p = nodeMap.get(node.getParentId());
TM p = findParent(nodeMap, node);
/*if (p == null) {
if (ignoreNoParentLeafe)
logger.error("build tree error: can't not find the node[" + node.getId() + ", " + node.getName() + "]'s parent node[" + node.getParentId() + "]");
else
throw new RuntimeException("build tree error: can't not find the node[" + node.getId() + ", " + node.getName() + "]'s parent node[" + node.getParentId() + "]");
} else {
p.addChild(node);
// node.setParent(p);
}*/
if (p==null) {
// 当父节点为null时,调用ParentNodeNotFoundAction回调函数查找父节点
p = notFoundAction.onParentNodeNotFound(node);
if(p==null){
// 如果返回null,则忽略处理
// addRoot(node);
} else if (p.equals(node)) {
// 返回自身,则添加到根节点
addRoot(node);
} else {
// 通过ParentNodeNotFoundAction回调查找到父节点时,把父节点也放到缓存nodeMap里
// 同时通过addChild方法把当前节点放到父节点的children列表里
nodeMap.put(p.getId(), p);
treeModels.add(p);
// 当父节点是延迟加载的时候会出现修改list的情况
p.addChild(node);
}
}else {
// 当父节点是延迟加载的时候会出现修改list的情况
p.addChild(node);
}
}
Collections.sort(rootNodes, this.comparator);
return rootNodes;
}
public List<TM> reverseRoots() {
Collections.reverse(rootNodes);
return rootNodes;
}
protected TM findParent(Map<Object, TM> nodeMap, TM node) {
return nodeMap.get(node.getParentId());
}
protected void addRoot(TM node){
rootNodes.add(node);
// this.tree.put(node.getId()!=null?node.getId():node.getName(), node);
}
protected boolean isExistsRootNode(TreeModel<?> node){
return rootNodes.contains(node);
}
public TreeModel<?> getBranch(Object rootId){
for(TreeModel<?> node : this.rootNodes){
if(rootId.equals(node.getId()))
return node;
}
return null;
}
/*public Set<Object> getNotFoundParentIds() {
return notFoundParentIds;
}*/
public List<TM> getRootNodes() {
return rootNodes;
}
public Map<Object, TM> getNodeMap() {
return nodeMap;
}
public static void main(String[] args) {
DefaultTreeModel t1 = new DefaultTreeModel(1, "t1");
DefaultTreeModel t2 = new DefaultTreeModel(2, "t2", 1);
DefaultTreeModel t3 = new DefaultTreeModel(3, "t3", 1);
DefaultTreeModel t4 = new DefaultTreeModel(4, "t4", 2);
DefaultTreeModel t5 = new DefaultTreeModel(5, "t5", 4);
List<DefaultTreeModel> list = Arrays.asList(t1, t2, t3, t4, t5);
TreeBuilder<DefaultTreeModel> tb = new TreeBuilder<DefaultTreeModel>(list, new SimpleTreeModelCreator());
tb.rootIds(1, 4);
List<DefaultTreeModel> t = tb.buidTree(tb.IGNORE);
System.out.println(t.get(0));
System.out.println(tb.getBranch(4));
}
} | 30.23588 | 166 | 0.662345 |
047bf789820cc1ca4af0fcdfbaf16516cb09da5b | 6,028 | /**
* Copyright (c) 2019-2030 panguBpm All rights reserved.
* <p>
* http://www.pangubpm.com/
* <p>
* (盘古BPM工作流平台)
*/
package com.pangubpm.bpm.model.xml.impl.type.attribute;
import com.pangubpm.bpm.model.xml.impl.type.reference.ReferenceImpl;
import com.pangubpm.bpm.model.xml.instance.ModelElementInstance;
import com.pangubpm.bpm.model.xml.type.ModelElementType;
import com.pangubpm.bpm.model.xml.type.attribute.Attribute;
import com.pangubpm.bpm.model.xml.type.reference.Reference;
import java.util.ArrayList;
import java.util.List;
/**
* <p>Base class for implementing primitive value attributes</p>
*
* @author pangubpm([email protected])
*
*/
public abstract class AttributeImpl<T> implements Attribute<T> {
/** the local name of the attribute */
private String attributeName;
/** the namespace for this attribute */
private String namespaceUri;
/** the default value for this attribute: the default value is returned
* by the {@link #getValue(ModelElementInstance)} method in case the attribute is not set on the
* domElement.
*/
private T defaultValue;
private boolean isRequired = false;
private boolean isIdAttribute = false;
private final List<Reference<?>> outgoingReferences = new ArrayList<Reference<?>>();
private final List<Reference<?>> incomingReferences = new ArrayList<Reference<?>>();
private final ModelElementType owningElementType;
AttributeImpl(ModelElementType owningElementType) {
this.owningElementType = owningElementType;
}
/**
* to be implemented by subclasses: converts the raw (String) value of the
* attribute to the type required by the model
*
* @return the converted value
*/
protected abstract T convertXmlValueToModelValue(String rawValue);
/**
* to be implemented by subclasses: converts the raw (String) value of the
* attribute to the type required by the model
*
* @return the converted value
*/
protected abstract String convertModelValueToXmlValue(T modelValue);
public ModelElementType getOwningElementType() {
return owningElementType;
}
/**
* returns the value of the attribute.
*
* @return the value of the attribute.
*/
public T getValue(ModelElementInstance modelElement) {
String value;
if(namespaceUri == null) {
value = modelElement.getAttributeValue(attributeName);
} else {
value = modelElement.getAttributeValueNs(namespaceUri, attributeName);
if(value == null) {
String alternativeNamespace = owningElementType.getModel().getAlternativeNamespace(namespaceUri);
if (alternativeNamespace != null) {
value = modelElement.getAttributeValueNs(alternativeNamespace, attributeName);
}
}
}
// default value
if (value == null && defaultValue != null) {
return defaultValue;
} else {
return convertXmlValueToModelValue(value);
}
}
/**
* sets the value of the attribute.
*
* the value of the attribute.
*/
public void setValue(ModelElementInstance modelElement, T value) {
setValue(modelElement, value, true);
}
@Override
public void setValue(ModelElementInstance modelElement, T value, boolean withReferenceUpdate) {
String xmlValue = convertModelValueToXmlValue(value);
if(namespaceUri == null) {
modelElement.setAttributeValue(attributeName, xmlValue,
isIdAttribute, withReferenceUpdate);
} else {
modelElement.setAttributeValueNs(namespaceUri, attributeName,
xmlValue, isIdAttribute, withReferenceUpdate);
}
}
public void updateIncomingReferences(ModelElementInstance modelElement, String newIdentifier, String oldIdentifier) {
if (!incomingReferences.isEmpty()) {
for (Reference<?> incomingReference : incomingReferences) {
((ReferenceImpl<?>) incomingReference).referencedElementUpdated(modelElement, oldIdentifier, newIdentifier);
}
}
}
public T getDefaultValue() {
return defaultValue;
}
public void setDefaultValue(T defaultValue) {
this.defaultValue = defaultValue;
}
public boolean isRequired() {
return isRequired;
}
/**
*/
public void setRequired(boolean required) {
this.isRequired = required;
}
/**
* @param namespaceUri the namespaceUri to set
*/
public void setNamespaceUri(String namespaceUri) {
this.namespaceUri = namespaceUri;
}
/**
* @return the namespaceUri
*/
public String getNamespaceUri() {
return namespaceUri;
}
public boolean isIdAttribute() {
return isIdAttribute;
}
/**
* Indicate whether this attribute is an Id attribute
*
*/
public void setId() {
this.isIdAttribute = true;
}
/**
* @return the attributeName
*/
public String getAttributeName() {
return attributeName;
}
/**
* @param attributeName the attributeName to set
*/
public void setAttributeName(String attributeName) {
this.attributeName = attributeName;
}
public void removeAttribute(ModelElementInstance modelElement) {
if (namespaceUri == null) {
modelElement.removeAttribute(attributeName);
}
else {
modelElement.removeAttributeNs(namespaceUri, attributeName);
}
}
public void unlinkReference(ModelElementInstance modelElement, Object referenceIdentifier) {
if (!incomingReferences.isEmpty()) {
for (Reference<?> incomingReference : incomingReferences) {
((ReferenceImpl<?>) incomingReference).referencedElementRemoved(modelElement, referenceIdentifier);
}
}
}
/**
* @return the incomingReferences
*/
public List<Reference<?>> getIncomingReferences() {
return incomingReferences;
}
/**
* @return the outgoingReferences
*/
public List<Reference<?>> getOutgoingReferences() {
return outgoingReferences;
}
public void registerOutgoingReference(Reference<?> ref) {
outgoingReferences.add(ref);
}
public void registerIncoming(Reference<?> ref) {
incomingReferences.add(ref);
}
}
| 26.438596 | 119 | 0.70355 |
808d0f26ae1af70f1062fbbea7d1f4381aca5b7f | 1,607 | import java.util.Scanner;
import java.util.*;
class Collections_Set_1
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t>0)
{
Set<Integer> s = new HashSet<Integer>() ;
int q = sc.nextInt();
while(q>0)
{
GfG g = new GfG();
char c = sc.next().charAt(0);
if(c == 'a')
{
int x = sc.nextInt();
g.insert(s,x);
}
if(c =='b')
{
g.print_contents(s);
}
if(c == 'c')
{
int x = sc.nextInt();
g.erase(s,x);
}
if(c == 'd')
{
int x = sc.nextInt();
System.out.print(g.find(s,x)+" ");
}
if(c == 'e')
System.out.print(g.size(s)+" ");
q--;
//System.out.println();
}
t--;
System.out.println();
}
}
}
/* You are required to complete below methods */
class GfG
{
/*inserts an element x to the set s */
void insert(Set<Integer> s, int x)
{
s.add(x);
}
/*prints the contents of the set s */
void print_contents(Set<Integer> s)
{
//for (final int x : s)
// System.out.format("%d ", x);
s.stream().sorted().forEachOrdered(x -> System.out.format("%d ", x));
}
/*erases an element x from the set s */
void erase(Set<Integer> s, int x)
{
s.remove(x);
}
/*returns the size of the set s */
int size(Set<Integer> s)
{
return s.size();
}
/*returns 1 if the element x is
present in set s else returns -1 */
int find(Set<Integer> s, int x)
{
return s.contains(x) ? 1 : -1;
}
}
| 18.471264 | 77 | 0.501556 |
fc6c8c13863ebc8165829cff5610ae00a7bbd0f8 | 5,175 | package com.google_ml_kit.vision;
import android.content.Context;
import android.util.Log;
import androidx.annotation.NonNull;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.pose.Pose;
import com.google.mlkit.vision.pose.PoseDetection;
import com.google.mlkit.vision.pose.PoseLandmark;
import com.google.mlkit.vision.pose.accurate.AccuratePoseDetectorOptions;
import com.google.mlkit.vision.pose.defaults.PoseDetectorOptions;
import com.google_ml_kit.ApiDetectorInterface;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
//Detector to the pose landmarks present in a image.
//Creates an abstraction over PoseDetector provided by ml kit.
public class PoseDetector implements ApiDetectorInterface {
private static final String START = "vision#startPoseDetector";
private static final String CLOSE = "vision#closePoseDetector";
private final Context context;
private com.google.mlkit.vision.pose.PoseDetector poseDetector;
public PoseDetector(Context context) {
this.context = context;
}
@Override
public List<String> getMethodsKeys() {
return new ArrayList<>(
Arrays.asList(START,
CLOSE));
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull MethodChannel.Result result) {
String method = call.method;
if (method.equals(START)) {
handleDetection(call, result);
} else if (method.equals(CLOSE)) {
closeDetector();
result.success(null);
} else {
result.notImplemented();
}
}
private void handleDetection(MethodCall call, final MethodChannel.Result result) {
Map<String, Object> imageData = (Map<String, Object>) call.argument("imageData");
InputImage inputImage = InputImageConverter.getInputImageFromData(imageData, context, result);
if (inputImage == null) return;
Map<String, Object> options = call.argument("options");
if (options == null) {
result.error("PoseDetectorError", "Invalid options", null);
return;
}
String model = (String) options.get("type");
String mode = (String) options.get("mode");
int detectorMode = PoseDetectorOptions.STREAM_MODE;
if (mode.equals("single")) {
detectorMode = PoseDetectorOptions.SINGLE_IMAGE_MODE;
}
if (model.equals("base")) {
PoseDetectorOptions detectorOptions = new PoseDetectorOptions.Builder()
.setDetectorMode(detectorMode)
.build();
poseDetector = PoseDetection.getClient(detectorOptions);
} else {
AccuratePoseDetectorOptions detectorOptions = new AccuratePoseDetectorOptions.Builder()
.setDetectorMode(detectorMode)
.build();
poseDetector = PoseDetection.getClient(detectorOptions);
}
poseDetector.process(inputImage)
.addOnSuccessListener(
new OnSuccessListener<Pose>() {
@Override
public void onSuccess(Pose pose) {
List<List<Map<String, Object>>> array = new ArrayList<>();
if (!pose.getAllPoseLandmarks().isEmpty()) {
List<Map<String, Object>> landmarks = new ArrayList<>();
for (PoseLandmark poseLandmark : pose.getAllPoseLandmarks()) {
Map<String, Object> landmarkMap = new HashMap<>();
landmarkMap.put("type", poseLandmark.getLandmarkType());
landmarkMap.put("x", poseLandmark.getPosition3D().getX());
landmarkMap.put("y", poseLandmark.getPosition3D().getY());
landmarkMap.put("z", poseLandmark.getPosition3D().getZ());
landmarkMap.put("likelihood",poseLandmark.getInFrameLikelihood());
landmarks.add(landmarkMap);
}
array.add(landmarks);
}
result.success(array);
}
})
.addOnFailureListener(
new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
result.error("PoseDetectorError", e.toString(), null);
}
});
}
private void closeDetector() {
poseDetector.close();
}
}
| 41.733871 | 106 | 0.577005 |
d38637470c9c96c3322e507117a8c425f22d3832 | 1,624 | package frictionless.frictionless.mixin;
import frictionless.frictionless.Frictionless;
import net.fabricmc.fabric.api.command.v1.CommandRegistrationCallback;
import net.minecraft.block.AbstractBlock;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemConvertible;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import frictionless.frictionless.Frictionless;
import static net.minecraft.server.command.CommandManager.literal;
@Mixin(Block.class)
public abstract class slippymixin extends AbstractBlock implements ItemConvertible {
public float slip = 1F;
//def is 0.6
public float vel = 1.05F;
public slippymixin(Settings settings) {
super(settings);
}
//def is 1
@Inject(method = "getSlipperiness", at = @At(value = "HEAD"), cancellable = true)
private void slippyFix(CallbackInfoReturnable<Float> cir) {
if(Frictionless.isSlip){
slip = 1F;
cir.setReturnValue(slip);
}else if(!Frictionless.isSlip){
slip = this.slipperiness;
}
}
@Inject(method = "getVelocityMultiplier", at = @At(value = "HEAD"), cancellable = true)
private void velFix(CallbackInfoReturnable<Float> cir) {
if(Frictionless.isSlip){
vel = 1.05F;
cir.setReturnValue(vel);
}else if(!Frictionless.isSlip){
vel = this.velocityMultiplier;
}
}
}
| 24.606061 | 91 | 0.702586 |
92403411ad2fd60bf6096e190ec5c00fafd532d3 | 5,148 | /*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.deeplearning4j.nn.modelimport.keras.layers.wrappers;
import org.deeplearning4j.nn.conf.layers.LSTM;
import org.deeplearning4j.nn.conf.layers.recurrent.Bidirectional;
import org.deeplearning4j.nn.modelimport.keras.config.Keras1LayerConfiguration;
import org.deeplearning4j.nn.modelimport.keras.config.Keras2LayerConfiguration;
import org.deeplearning4j.nn.modelimport.keras.config.KerasLayerConfiguration;
import org.deeplearning4j.nn.weights.WeightInit;
import org.junit.Test;
import org.nd4j.linalg.activations.Activation;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
/**
* @author Max Pumperla
*/
public class KerasBidirectionalTest {
private final String ACTIVATION_KERAS = "linear";
private final String ACTIVATION_DL4J = "identity";
private final String LAYER_NAME = "bidirectional_layer";
private final String INIT_KERAS = "glorot_normal";
private final WeightInit INIT_DL4J = WeightInit.XAVIER;
private final double L1_REGULARIZATION = 0.01;
private final double L2_REGULARIZATION = 0.02;
private final double DROPOUT_KERAS = 0.3;
private final double DROPOUT_DL4J = 1 - DROPOUT_KERAS;
private final int N_OUT = 13;
private final String mode = "sum";
private Integer keras1 = 1;
private Integer keras2 = 2;
private Keras1LayerConfiguration conf1 = new Keras1LayerConfiguration();
private Keras2LayerConfiguration conf2 = new Keras2LayerConfiguration();
@Test
public void testLstmLayer() throws Exception {
buildLstmLayer(conf1, keras1);
buildLstmLayer(conf2, keras2);
}
private void buildLstmLayer(KerasLayerConfiguration conf, Integer kerasVersion) throws Exception {
String innerActivation = "hard_sigmoid";
String lstmForgetBiasString = "one";
Map<String, Object> layerConfig = new HashMap<>();
layerConfig.put(conf.getLAYER_FIELD_CLASS_NAME(), conf.getLAYER_CLASS_NAME_LSTM());
Map<String, Object> lstmConfig = new HashMap<>();
lstmConfig.put(conf.getLAYER_FIELD_ACTIVATION(), ACTIVATION_KERAS); // keras linear -> dl4j identity
lstmConfig.put(conf.getLAYER_FIELD_INNER_ACTIVATION(), innerActivation); // keras linear -> dl4j identity
lstmConfig.put(conf.getLAYER_FIELD_NAME(), LAYER_NAME);
if (kerasVersion == 1) {
lstmConfig.put(conf.getLAYER_FIELD_INNER_INIT(), INIT_KERAS);
lstmConfig.put(conf.getLAYER_FIELD_INIT(), INIT_KERAS);
} else {
Map<String, Object> init = new HashMap<>();
init.put("class_name", conf.getINIT_GLOROT_NORMAL());
lstmConfig.put(conf.getLAYER_FIELD_INNER_INIT(), init);
lstmConfig.put(conf.getLAYER_FIELD_INIT(), init);
}
Map<String, Object> W_reg = new HashMap<>();
W_reg.put(conf.getREGULARIZATION_TYPE_L1(), L1_REGULARIZATION);
W_reg.put(conf.getREGULARIZATION_TYPE_L2(), L2_REGULARIZATION);
lstmConfig.put(conf.getLAYER_FIELD_W_REGULARIZER(), W_reg);
lstmConfig.put(conf.getLAYER_FIELD_RETURN_SEQUENCES(), true);
lstmConfig.put(conf.getLAYER_FIELD_DROPOUT_W(), DROPOUT_KERAS);
lstmConfig.put(conf.getLAYER_FIELD_DROPOUT_U(), 0.0);
lstmConfig.put(conf.getLAYER_FIELD_FORGET_BIAS_INIT(), lstmForgetBiasString);
lstmConfig.put(conf.getLAYER_FIELD_OUTPUT_DIM(), N_OUT);
lstmConfig.put(conf.getLAYER_FIELD_UNROLL(), true);
Map<String, Object> innerRnnConfig = new HashMap<>();
innerRnnConfig.put("class_name", "LSTM");
innerRnnConfig.put("config", lstmConfig);
Map<String, Object> innerConfig = new HashMap<>();
innerConfig.put("merge_mode", mode);
innerConfig.put("layer", innerRnnConfig);
innerConfig.put(conf.getLAYER_FIELD_NAME(), LAYER_NAME);
layerConfig.put("config", innerConfig);
layerConfig.put(conf.getLAYER_FIELD_KERAS_VERSION(), kerasVersion);
KerasBidirectional kerasBidirectional = new KerasBidirectional(layerConfig);
Bidirectional layer = kerasBidirectional.getBidirectionalLayer();
assertEquals(Bidirectional.Mode.ADD, layer.getMode());
assertEquals(Activation.HARDSIGMOID.toString().toLowerCase(),
((LSTM) kerasBidirectional.getUnderlyingRecurrentLayer()).getGateActivationFn().toString());
}
}
| 45.157895 | 113 | 0.704157 |
a0c88523e684c988120683df42b7fe86272eae40 | 1,191 | package client;
public class MapleCharacterUtil {
private MapleCharacterUtil() {
}
public static boolean canCreateChar(String name, int world) {
return isNameLegal(name) && MapleCharacter.getIdByName(name, world) < 0;
}
public static boolean isNameLegal(String name) {
if (name.length() < 3 || name.length() > 12) {
return false;
}
return java.util.regex.Pattern.compile("[a-zA-Z0-9_-]{3,12}").matcher(name).matches();
}
public static boolean hasSymbols(String name) {
String[] symbols = {"`","~","!","@","#","$","%","^","&","*","(",")","_","-","=","+","{","[","]","}","|",";",":","'",",","<",">",".","?","/"};
for (byte s = 0; s < symbols.length; s++) {
if (name.contains(symbols[s])) {
return true;
}
}
return false;
}
public static String makeMapleReadable(String in) {
String wui = in.replace('I', 'i');
wui = wui.replace('l', 'L');
wui = wui.replace("rn", "Rn");
wui = wui.replace("vv", "Vv");
wui = wui.replace("VV", "Vv");
return wui;
}
} | 32.189189 | 150 | 0.47691 |
6c5d7a517b16fd4d091c7b0ea0dc0d591ce26615 | 3,112 | /*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.i18n.shared.impl.cldr;
// DO NOT EDIT - GENERATED FROM CLDR AND ICU DATA
// cldrVersion=21.0
// number=$Revision: 6472 Google $
// type=root
// date=$Date: 2012-01-27 18:53:35 -0500 (Fri, 27 Jan 2012) $
/**
* Implementation of DateTimeFormatInfo for the "sr_Latn" locale.
*/
public class DateTimeFormatInfoImpl_sr_Latn extends DateTimeFormatInfoImpl_sr {
@Override
public String[] ampms() {
return new String[] {
"pre podne",
"popodne"
};
}
@Override
public String[] erasFull() {
return new String[] {
"Pre nove ere",
"Nove ere"
};
}
@Override
public String[] erasShort() {
return new String[] {
"p. n. e.",
"n. e"
};
}
@Override
public String formatYearMonthAbbrev() {
return "y MMM";
}
@Override
public String[] monthsFull() {
return new String[] {
"januar",
"februar",
"mart",
"april",
"maj",
"jun",
"jul",
"avgust",
"septembar",
"oktobar",
"novembar",
"decembar"
};
}
@Override
public String[] monthsNarrow() {
return new String[] {
"j",
"f",
"m",
"a",
"m",
"j",
"j",
"a",
"s",
"o",
"n",
"d"
};
}
@Override
public String[] monthsShort() {
return new String[] {
"jan",
"feb",
"mar",
"apr",
"maj",
"jun",
"jul",
"avg",
"sep",
"okt",
"nov",
"dec"
};
}
@Override
public String[] quartersFull() {
return new String[] {
"1. kvartal",
"2. kvartal",
"3. kvartal",
"4. kvartal"
};
}
@Override
public String[] quartersShort() {
return new String[] {
"Q1",
"Q2",
"Q3",
"Q4"
};
}
@Override
public String[] weekdaysFull() {
return new String[] {
"nedelja",
"ponedeljak",
"utorak",
"sreda",
"četvrtak",
"petak",
"subota"
};
}
@Override
public String[] weekdaysNarrow() {
return new String[] {
"n",
"p",
"u",
"s",
"č",
"p",
"s"
};
}
@Override
public String[] weekdaysShort() {
return new String[] {
"ned",
"pon",
"uto",
"sre",
"čet",
"pet",
"sub"
};
}
}
| 18.19883 | 80 | 0.496465 |
b65c6b3788c572057a8a7881dab95f0e3c026873 | 3,097 | package nocategoryyet;
import java.util.LinkedList;
import java.util.Queue;
public class SegmentTree {
private static class Node {
int from;
int to;
Node left;
Node right;
int total;
public Node(int from, int to) {
this.from = from;
this.to = to;
}
public String toString() {
return "[" + from + "-" + to + "]" + " sum: " + total;
}
}
private Node root;
private int size;
public SegmentTree(int[] values) {
root = constructTree(values, 0, values.length - 1);
size = values.length;
}
private Node constructTree(int[] values, int minIndex, int maxIndex) {
Node current = new Node(minIndex, maxIndex);
if (minIndex == maxIndex) {
current.total = values[minIndex];
} else {
current.left = constructTree(values, minIndex, (minIndex + maxIndex) / 2);
current.right = constructTree(values, (minIndex + maxIndex) / 2 + 1, maxIndex);
current.total = current.left.total + current.right.total;
}
return current;
}
public void set(int index, int value) {
if (index >= size || index < 0) {
throw new IndexOutOfBoundsException("Index is not within bounds");
}
root = set(index, value, root);
}
private Node set(int selectedIndex, int value, Node current) {
if (current.from == current.to && current.from == selectedIndex) {
current.total = value;
} else {
int mid = (current.from + current.to) / 2;
if (selectedIndex <= mid) {
current.left = set(selectedIndex, value, current.left);
} else {
current.right = set(selectedIndex, value, current.right);
}
current.total = current.left.total + current.right.total;
}
return current;
}
public int sumOf(int rangeFrom, int rangeTo) {
if (rangeFrom < 0 || rangeTo >= size || rangeFrom > rangeTo) {
throw new IllegalArgumentException("Range from should be: 0 <= rangeFrom <= rangeTo < size");
}
return sumOf(root, rangeFrom, rangeTo);
}
private int sumOf(Node current, int fromIndex, int toIndex) {
if (current.from == fromIndex && current.to == toIndex) {
return current.total;
}
int leftSideMaxIndex = (current.from + current.to) / 2;
if (fromIndex <= leftSideMaxIndex && toIndex > leftSideMaxIndex) {
return sumOf(current.left, fromIndex, leftSideMaxIndex) + sumOf(current.right, leftSideMaxIndex + 1, toIndex);
} else if (toIndex <= leftSideMaxIndex) {
return sumOf(current.left, fromIndex, toIndex);
} else {
return sumOf(current.right, fromIndex, toIndex);
}
}
public int size() {
return size;
}
public void levelOrder() {
Queue<Node> q = new LinkedList<>();
q.add(root);
while (!q.isEmpty()) {
Node curr = q.poll();
System.out.println(curr);
if (curr.left != null) {
q.add(curr.left);
}
if (curr.right != null) {
q.add(curr.right);
}
}
}
public static void main(String[] args) {
int[] nums = { 2, 3, 4, 1, 2, 8, 7, 4 };
SegmentTree tree = new SegmentTree(nums);
tree.levelOrder();
System.out.println(tree.sumOf(3, 7));
}
}
| 26.470085 | 114 | 0.624798 |
47a26cca239026f5a02172d7b5a9d72401665671 | 2,235 | package com.forezp.banya.Presenter;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.forezp.banya.base.BasePresenter;
import com.forezp.banya.bean.music.MusicRoot;
import com.forezp.banya.bean.music.Musics;
import com.forezp.banya.viewinterface.music.IGetMusicById;
import com.forezp.banya.viewinterface.music.IGetMusicByTagView;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
/**
* Created by forezp on 16/9/30.
*/
public class DoubanMusicPresenter extends BasePresenter {
public DoubanMusicPresenter(Context context) {
super(context);
}
/**
* @param
*/
public void searchMusicByTag(IGetMusicByTagView iGetMusicByTagView, String TAG , boolean isLoadMore){
doubanApi.searchMusicByTag(TAG)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(musicRoot -> {
disPlaySearchedMusic(iGetMusicByTagView,musicRoot,isLoadMore);
},this::loadError);
}
private void disPlaySearchedMusic(IGetMusicByTagView iGetMusicByTagView, MusicRoot musicRoot, boolean isLoadMore) {
iGetMusicByTagView.getMusicByTagSuccess(musicRoot,isLoadMore);
//if(filmLive==null){
// iGetFilmLiveView.getDataFail();
// }else {
// iGetFilmLiveView.getFilmLiveSuccess(filmLive);
Log.e("test", musicRoot.toString());
// }
}
private void loadError( Throwable throwable) {
throwable.printStackTrace();
Toast.makeText(mContext, "网络不见了", Toast.LENGTH_SHORT).show();
}
/**
* @param
*/
public void getMusicById(IGetMusicById iGetMusicById, String id ){
doubanApi.getMusicDetail(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(music -> {
displayMusic(iGetMusicById,music);
},this::loadError);
}
private void displayMusic(IGetMusicById iGetMusicById , Musics musics) {
iGetMusicById.getMusicSucess(musics);
Log.e("test", musics.toString());
}
}
| 26.927711 | 119 | 0.661745 |
a1d5f7866aa8805f2679e292427b6c03085d6747 | 220 | package edu.asupoly.ser422.t6mvc2.handler;
import java.util.Map;
import javax.servlet.http.HttpSession;
public interface ActionHandler {
public String handleIt(Map<String, String[]> params, HttpSession session);
}
| 20 | 75 | 0.786364 |
5af12e3544f5619e1eb8ed715520765cc74b5983 | 860 | /******************************************************************************
* Copyright (c) 2015 IBM Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*****************************************************************************/
package com.ibm.research.rdf.store.jena;
public class RdfStoreException extends RuntimeException {
public RdfStoreException(String msg) {
super(msg);
}
public RdfStoreException() {
super();
}
public RdfStoreException(String string, Exception e) {
super(string,e);
}
private static final long serialVersionUID = 1L;
}
| 28.666667 | 79 | 0.606977 |
1c92b4e701a3c810e9192b7b4b7a5e69fd713ac6 | 1,445 | /*
* Copyright 2018-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.core.semaphore;
import com.google.common.base.MoreObjects;
public class QueueStatus {
private int queueLength;
private int totalPermits;
public QueueStatus(int queueLength, int totalPermits) {
this.queueLength = queueLength;
this.totalPermits = totalPermits;
}
/**
* Get the count of requests waiting for permits.
*
* @return count of requests waiting for permits
*/
public int queueLength() {
return queueLength;
}
/**
* Get the sum of permits waiting for.
*
* @return sum of permits
*/
public int totalPermits() {
return totalPermits;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("queueLength", queueLength)
.add("totalPermits", totalPermits)
.toString();
}
}
| 26.272727 | 75 | 0.698962 |
ff291f2157868519c64ed15663ff835ce024febd | 2,610 | package top.auzqy._0101_0150._0122;
/**
* description: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
* createTime: 2020/8/21 15:52
* @author au
*/
public class Solution_0122 {
public int maxProfit(int[] prices) {
// return solution1_by_copy(prices, 0);
return solution2_by_copy(prices);
// return solution3_by_copy(prices);
}
/**
* description: 峰谷法
* Time Complexity: O(n)
* Space Complexity: O(1)
* createTime: 2020/8/21 21:51
* @author au
* @param prices
* @return
*/
private int solution2_by_copy(int[] prices) {
int i = 0;
int valley = prices[0];
int peak = prices[0];
int maxprofit = 0;
while (i < prices.length - 1) {
while (i < prices.length - 1 && prices[i] >= prices[i + 1]) {
i++;
}
valley = prices[i];
while (i < prices.length - 1 && prices[i] <= prices[i + 1]) {
i++;
}
peak = prices[i];
maxprofit += peak - valley;
}
return maxprofit;
}
/**
* description: 简单的一次遍历
* Time Complexity: O(n)
* Space Complexity: O(1)
* createTime: 2020/8/21 21:40
* @author au
* @param prices
* @return
*/
private int solution3_by_copy(int[] prices) {
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;
}
/**
* description: 暴力法
* Time Complexity: O(n^n)
* Space Complexity: O(n)
* createTime: 2020/8/21 15:56
* @author au
* @param prices
* @param s
* @return
*/
public int solution1_by_copy(int[] prices, int s) {
if (s >= prices.length) {
return 0;
}
int max = 0;
for (int start = s; start < prices.length; start++) {
int maxprofit = 0;
for (int i = start + 1; i < prices.length; i++) {
if (prices[start] < prices[i]) {
int profit
= solution1_by_copy(prices, i + 1)
+ prices[i]
- prices[start];
if (profit > maxprofit) {
maxprofit = profit;
}
}
}
if (maxprofit > max) {
max = maxprofit;
}
}
return max;
}
}
| 26.363636 | 85 | 0.456322 |
39f3723b6efdd704ffcc866e070d76cb2111a5ae | 6,261 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ivy.core.check;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.apache.ivy.core.module.descriptor.Artifact;
import org.apache.ivy.core.module.descriptor.DependencyDescriptor;
import org.apache.ivy.core.module.descriptor.ModuleDescriptor;
import org.apache.ivy.core.resolve.ResolveData;
import org.apache.ivy.core.resolve.ResolveEngine;
import org.apache.ivy.core.resolve.ResolveOptions;
import org.apache.ivy.core.resolve.ResolvedModuleRevision;
import org.apache.ivy.plugins.parser.ModuleDescriptorParserRegistry;
import org.apache.ivy.plugins.resolver.DependencyResolver;
import org.apache.ivy.util.Message;
public class CheckEngine {
private CheckEngineSettings settings;
private ResolveEngine resolveEngine;
public CheckEngine(CheckEngineSettings settings, ResolveEngine resolveEngine) {
this.settings = settings;
this.resolveEngine = resolveEngine;
}
/**
* Checks the given ivy file using current settings to see if all dependencies are available,
* with good confs. If a resolver name is given, it also checks that the declared publications
* are available in the corresponding resolver. Note that the check is not performed
* recursively, i.e. if a dependency has itself dependencies badly described or not available,
* this check will not discover it.
*/
public boolean check(URL ivyFile, String resolvername) {
try {
boolean result = true;
// parse ivy file
ModuleDescriptor md = ModuleDescriptorParserRegistry.getInstance().parseDescriptor(
settings, ivyFile, settings.doValidate());
// check publications if possible
if (resolvername != null) {
DependencyResolver resolver = settings.getResolver(resolvername);
String[] confs = md.getConfigurationsNames();
Set artifacts = new HashSet();
for (int i = 0; i < confs.length; i++) {
artifacts.addAll(Arrays.asList(md.getArtifacts(confs[i])));
}
for (Iterator iter = artifacts.iterator(); iter.hasNext();) {
Artifact art = (Artifact) iter.next();
if (!resolver.exists(art)) {
Message.info("declared publication not found: " + art);
result = false;
}
}
}
// check dependencies
DependencyDescriptor[] dds = md.getDependencies();
ResolveData data = new ResolveData(resolveEngine, new ResolveOptions());
for (int i = 0; i < dds.length; i++) {
// check master confs
String[] masterConfs = dds[i].getModuleConfigurations();
for (int j = 0; j < masterConfs.length; j++) {
if (!"*".equals(masterConfs[j].trim())
&& md.getConfiguration(masterConfs[j]) == null) {
Message.info("dependency required in non existing conf for " + ivyFile
+ " \n\tin " + dds[i] + ": "
+ masterConfs[j]);
result = false;
}
}
// resolve
DependencyResolver resolver =
settings.getResolver(dds[i].getDependencyRevisionId());
ResolvedModuleRevision rmr = resolver.getDependency(dds[i], data);
if (rmr == null) {
Message.info("dependency not found in " + ivyFile + ":\n\t" + dds[i]);
result = false;
} else {
String[] depConfs = dds[i].getDependencyConfigurations(md
.getConfigurationsNames());
for (int j = 0; j < depConfs.length; j++) {
if (!Arrays.asList(rmr.getDescriptor().getConfigurationsNames()).contains(
depConfs[j])) {
Message.info("dependency configuration is missing for " + ivyFile
+ "\n\tin " + dds[i] + ": "
+ depConfs[j]);
result = false;
}
Artifact[] arts = rmr.getDescriptor().getArtifacts(depConfs[j]);
for (int k = 0; k < arts.length; k++) {
if (!resolver.exists(arts[k])) {
Message.info("dependency artifact is missing for " + ivyFile
+ "\n\t in " + dds[i] + ": "
+ arts[k]);
result = false;
}
}
}
}
}
return result;
} catch (ParseException e) {
Message.info("parse problem on " + ivyFile, e);
return false;
} catch (IOException e) {
Message.info("io problem on " + ivyFile, e);
return false;
} catch (Exception e) {
Message.info("problem on " + ivyFile, e);
return false;
}
}
}
| 45.043165 | 98 | 0.558697 |
5ec2dd1492d3bd9fc4bc11cbe1bc8fe0ad05c020 | 6,548 | /*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.wso2.andes.transport.network;
import org.wso2.andes.transport.Header;
import org.wso2.andes.transport.Method;
import org.wso2.andes.transport.ProtocolDelegate;
import org.wso2.andes.transport.ProtocolError;
import org.wso2.andes.transport.ProtocolEvent;
import org.wso2.andes.transport.ProtocolHeader;
import org.wso2.andes.transport.SegmentType;
import org.wso2.andes.transport.Sender;
import org.wso2.andes.transport.Struct;
import org.wso2.andes.transport.codec.BBEncoder;
import static org.wso2.andes.transport.network.Frame.FIRST_FRAME;
import static org.wso2.andes.transport.network.Frame.FIRST_SEG;
import static org.wso2.andes.transport.network.Frame.HEADER_SIZE;
import static org.wso2.andes.transport.network.Frame.LAST_FRAME;
import static org.wso2.andes.transport.network.Frame.LAST_SEG;
import static java.lang.Math.min;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* Disassembler
*/
public final class Disassembler implements Sender<ProtocolEvent>, ProtocolDelegate<Void>
{
private final Sender<ByteBuffer> sender;
private final int maxPayload;
private final Object sendlock = new Object();
private final static ThreadLocal<BBEncoder> _encoder = new ThreadLocal<BBEncoder>()
{
public BBEncoder initialValue()
{
return new BBEncoder(4*1024);
}
};
public Disassembler(Sender<ByteBuffer> sender, int maxFrame)
{
if (maxFrame <= HEADER_SIZE || maxFrame >= 64*1024)
{
throw new IllegalArgumentException("maxFrame must be > HEADER_SIZE and < 64K: " + maxFrame);
}
this.sender = sender;
this.maxPayload = maxFrame - HEADER_SIZE;
}
public void send(ProtocolEvent event)
{
event.delegate(null, this);
}
public void flush()
{
synchronized (sendlock)
{
sender.flush();
}
}
public void close()
{
synchronized (sendlock)
{
sender.close();
}
}
private void frame(byte flags, byte type, byte track, int channel, int size, ByteBuffer buf)
{
synchronized (sendlock)
{
ByteBuffer data = ByteBuffer.allocate(size + HEADER_SIZE);
data.order(ByteOrder.BIG_ENDIAN);
data.put(0, flags);
data.put(1, type);
data.putShort(2, (short) (size + HEADER_SIZE));
data.put(5, track);
data.putShort(6, (short) channel);
data.position(HEADER_SIZE);
int limit = buf.limit();
buf.limit(buf.position() + size);
data.put(buf);
buf.limit(limit);
data.rewind();
sender.send(data);
}
}
private void fragment(byte flags, SegmentType type, ProtocolEvent event, ByteBuffer buf)
{
byte typeb = (byte) type.getValue();
byte track = event.getEncodedTrack() == Frame.L4 ? (byte) 1 : (byte) 0;
int remaining = buf.remaining();
boolean first = true;
while (true)
{
int size = min(maxPayload, remaining);
remaining -= size;
byte newflags = flags;
if (first)
{
newflags |= FIRST_FRAME;
first = false;
}
if (remaining == 0)
{
newflags |= LAST_FRAME;
}
frame(newflags, typeb, track, event.getChannel(), size, buf);
if (remaining == 0)
{
break;
}
}
}
public void init(Void v, ProtocolHeader header)
{
synchronized (sendlock)
{
sender.send(header.toByteBuffer());
sender.flush();
}
}
public void control(Void v, Method method)
{
method(method, SegmentType.CONTROL);
}
public void command(Void v, Method method)
{
method(method, SegmentType.COMMAND);
}
private void method(Method method, SegmentType type)
{
BBEncoder enc = _encoder.get();
enc.init();
enc.writeUint16(method.getEncodedType());
if (type == SegmentType.COMMAND)
{
if (method.isSync())
{
enc.writeUint16(0x0101);
}
else
{
enc.writeUint16(0x0100);
}
}
method.write(enc);
ByteBuffer methodSeg = enc.segment();
byte flags = FIRST_SEG;
boolean payload = method.hasPayload();
if (!payload)
{
flags |= LAST_SEG;
}
ByteBuffer headerSeg = null;
if (payload)
{
final Header hdr = method.getHeader();
if (hdr != null)
{
final Struct[] structs = hdr.getStructs();
for (Struct st : structs)
{
enc.writeStruct32(st);
}
}
headerSeg = enc.segment();
}
synchronized (sendlock)
{
fragment(flags, type, method, methodSeg);
if (payload)
{
ByteBuffer body = method.getBody();
fragment(body == null ? LAST_SEG : 0x0, SegmentType.HEADER, method, headerSeg);
if (body != null)
{
fragment(LAST_SEG, SegmentType.BODY, method, body);
}
}
}
}
public void error(Void v, ProtocolError error)
{
throw new IllegalArgumentException(String.valueOf(error));
}
public void setIdleTimeout(int i)
{
sender.setIdleTimeout(i);
}
}
| 27.982906 | 104 | 0.57865 |
e222a8f480083fd9f1e9d6aa6eac5917783eb9c6 | 1,315 | package info.bfly.app.protocol.service;
import info.bfly.core.annotations.ScopeType;
import info.bfly.p2p.invest.controller.InvestList;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.util.Arrays;
/**
* Created by Administrator on 2017/1/4 0004.
*/
@Scope(ScopeType.REQUEST)
@Service
public class ApiInvestListService extends InvestList {
public ApiInvestListService() {
final String[] RESTRICTIONS = { "invest.id like #{apiInvestListService.example.id}", "invest.status like #{apiInvestListService.example.status}", "invest.loan.user.id like #{apiInvestListService.example.loan.user.id}",
"invest.loan.id like #{apiInvestListService.example.loan.id}", "invest.loan.name like #{apiInvestListService.example.loan.name}", "invest.loan.type like #{apiInvestListService.example.loan.type}",
"invest.user.id = #{apiInvestListService.example.user.id}", "invest.user.username = #{apiInvestListService.example.user.username}", "invest.time >= #{apiInvestListService.searchcommitMinTime}",
"invest.status like #{apiInvestListService.example.status}", "invest.time <= #{apiInvestListService.searchcommitMaxTime}" };
setRestrictionExpressionStrings(Arrays.asList(RESTRICTIONS));
}
}
| 50.576923 | 226 | 0.74981 |
2f95602d7fcee4a6387e075ea40f853daf2e8d56 | 312 | package c.d;
public final class b {
public static final int cardview_dark_background = 2131099716;
public static final int cardview_light_background = 2131099717;
public static final int cardview_shadow_end_color = 2131099718;
public static final int cardview_shadow_start_color = 2131099719;
}
| 34.666667 | 69 | 0.791667 |
49dc49b772f8af11b0ce3aef08f2984f7269472f | 2,116 | package online.himakeit.skylark.model.gank;
import java.util.Date;
/**
* Created by:LiXueLong 李雪龙 on 2017/9/6 8:49
* <p>
* Mail : [email protected]
* <p>
* Description:
*/
public class GankMeiZhi {
public String objectId;
public String url;
public String type;
public String desc;
public String who;
public boolean used;
public Date createdAt;
public Date updateAt;
public Date publishedAt;
public int imageWidth;
public int imageHeight;
public boolean hasFadedIn = false;
public String getObjectId() {
return objectId;
}
public void setObjectId(String objectId) {
this.objectId = objectId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public boolean isUsed() {
return used;
}
public void setUsed(boolean used) {
this.used = used;
}
public Date getCreateAt() {
return createdAt;
}
public void setCreateAt(Date createAt) {
this.createdAt = createAt;
}
public Date getUpdateAt() {
return updateAt;
}
public void setUpdateAt(Date updateAt) {
this.updateAt = updateAt;
}
public Date getPublicAt() {
return publishedAt;
}
public void setPublicAt(Date publicAt) {
this.publishedAt = publicAt;
}
public int getImageWidth() {
return imageWidth;
}
public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public void setImageHeight(int imageHeight) {
this.imageHeight = imageHeight;
}
}
| 18.561404 | 49 | 0.598771 |
a385625ff744b0ed86150670998d7f3cc283f998 | 1,650 | package org.arsok.app;
import javafx.scene.image.Image;
import javafx.scene.image.PixelWriter;
import javafx.scene.image.WritableImage;
import javafx.scene.paint.Color;
import static org.arsok.app.Main.instance;
public class RayTrace {
private final WritableImage image;
private final PixelWriter writer;
public RayTrace() {
this(1000, 1000);
}
public RayTrace(int width, int height) {
this.image = new WritableImage(width, height);
this.writer = image.getPixelWriter();
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
writer.setColor(i, j, Color.BLACK);
}
}
}
public void start() {
instance.getService().submit(new RayTraceRunnable());
}
public Image getImage() {
return image;
}
private class RayTraceRunnable implements Runnable {
@Override
public void run() {
for (int i = 0; i < image.getWidth(); i++) {
for (int j = 0; j < image.getHeight(); j++) {
updatePixel(i, j);
}
}
}
private void updatePixel(int x, int y) {
//TODO: update pixel
double xDelta = (image.getWidth() / 2) - x;
double yDelta = (image.getHeight() / 2) - y;
double radius = Math.pow(xDelta, 2) + Math.pow(yDelta, 2);
if (Math.abs(xDelta) <= 100 &&
Math.abs(yDelta) <= 100 && (radius <= Math.pow(101, 2) && radius >= Math.pow(99, 2))) {
writer.setColor(x, y, Color.RED);
}
}
}
}
| 27.966102 | 107 | 0.532121 |
f61231973bb5a552a47dfdbeab5226aed5b00b33 | 2,424 | package br.com.userede.erede;
import com.google.gson.annotations.SerializedName;
public class Item {
public static final Integer PHYSICAL = 1;
public static final Integer DIGITAL = 2;
public static final Integer SERVICE = 3;
public static final Integer AIRLINE = 4;
@SerializedName("amount")
private Integer amount;
@SerializedName("description")
private String description;
@SerializedName("discount")
private Integer discount;
@SerializedName("freight")
private Integer freight;
@SerializedName("id")
private String id;
@SerializedName("quantity")
private Integer quantity;
@SerializedName("shippingType")
private String shippingType;
@SerializedName("type")
private Integer type;
public Item() {
}
public Item(String id, Integer quantity) {
this(id, quantity, Item.PHYSICAL);
}
public Item(String id, Integer quantity, Integer type) {
this.id = id;
this.quantity = quantity;
this.type = type;
}
public Integer getAmount() {
return amount;
}
public Item setAmount(Integer amount) {
this.amount = amount;
return this;
}
public String getDescription() {
return description;
}
public Item setDescription(String description) {
this.description = description;
return this;
}
public Integer getDiscount() {
return discount;
}
public Item setDiscount(Integer discount) {
this.discount = discount;
return this;
}
public Integer getFreight() {
return freight;
}
public Item setFreight(Integer freight) {
this.freight = freight;
return this;
}
public String getId() {
return id;
}
public Item setId(String id) {
this.id = id;
return this;
}
public Integer getQuantity() {
return quantity;
}
public Item setQuantity(Integer quantity) {
this.quantity = quantity;
return this;
}
public String getShippingType() {
return shippingType;
}
public Item setShippingType(String shippingType) {
this.shippingType = shippingType;
return this;
}
public Integer getType() {
return type;
}
public Item setType(Integer type) {
this.type = type;
return this;
}
}
| 20.033058 | 60 | 0.615512 |
483de1645e954ff1b83e57838c020fd0d89669fc | 2,347 | /**
* Copyright (c) 2010 Perforce Software. All rights reserved.
*/
package com.perforce.team.ui.mergequest;
import org.eclipse.osgi.util.NLS;
/**
* @author Kevin Sawicki ([email protected])
*/
public class Messages extends NLS {
private static final String BUNDLE_NAME = "com.perforce.team.ui.mergequest.messages"; //$NON-NLS-1$
/**
* BranchGraphInput_ToolTip
*/
public static String BranchGraphInput_ToolTip;
/**
* IntegrateTaskViewer_ChangelistCount
*/
public static String IntegrateTaskViewer_ChangelistCount;
/**
* IntegrateTaskViewer_OneChangelist
*/
public static String IntegrateTaskViewer_OneChangelist;
/**
* ReorderGraphDialog_DialogTitle
*/
public static String ReorderGraphDialog_DialogTitle;
/**
* ReorderGraphDialog_MoveDown
*/
public static String ReorderGraphDialog_MoveDown;
/**
* ReorderGraphDialog_MoveUp
*/
public static String ReorderGraphDialog_MoveUp;
/**
* ReorderGraphDialog_MultipleBranches
*/
public static String ReorderGraphDialog_MultipleBranches;
/**
* ReorderGraphDialog_MultipleMappings
*/
public static String ReorderGraphDialog_MultipleMappings;
/**
* ReorderGraphDialog_SingleBranch
*/
public static String ReorderGraphDialog_SingleBranch;
/**
* ReorderGraphDialog_SingleMapping
*/
public static String ReorderGraphDialog_SingleMapping;
/**
* TaskContainer_Changelist
*/
public static String TaskContainer_Changelist;
/**
* TaskContainer_CollapseAll
*/
public static String TaskContainer_CollapseAll;
/**
* TaskContainer_EarlierThan
*/
public static String TaskContainer_EarlierThan;
/**
* TaskContainer_IntegrateMapping
*/
public static String TaskContainer_IntegrateMapping;
/**
* TaskContainer_LoadingFixes
*/
public static String TaskContainer_LoadingFixes;
/**
* TaskContainer_ThisMonth
*/
public static String TaskContainer_ThisMonth;
/**
* TaskContainer_ThisYear
*/
public static String TaskContainer_ThisYear;
static {
// initialize resource bundle
NLS.initializeMessages(BUNDLE_NAME, Messages.class);
}
private Messages() {
}
}
| 21.731481 | 103 | 0.686408 |
19683f3b64773d61a9708f93edda162c9d72b2a4 | 736 | package android.support.v7.internal.widget;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
final class O
implements ViewTreeObserver.OnGlobalLayoutListener
{
O(SpinnerCompat paramSpinnerCompat)
{
}
public final void onGlobalLayout()
{
if (!SpinnerCompat.a(this.a).b())
SpinnerCompat.a(this.a).c();
ViewTreeObserver localViewTreeObserver = this.a.getViewTreeObserver();
if (localViewTreeObserver != null)
localViewTreeObserver.removeGlobalOnLayoutListener(this);
}
}
/* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar
* Qualified Name: android.support.v7.internal.widget.O
* JD-Core Version: 0.6.0
*/ | 28.307692 | 83 | 0.741848 |
2bda445a61ac1dea12bcf14f5bbcafbb9c35fc2c | 2,259 | /*
* Copyright 2011 Corpuslinguistic working group Humboldt University Berlin.
*
* 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 annis.libgui;
import java.awt.Color;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
/**
* Colors for matched nodes. The names and color values correspond to the
* CSS standard.
* @author thomas
*/
public enum MatchedNodeColors
{
Red(new Color(255, 0, 0)),
MediumVioletRed(new Color(199, 21, 133)),
LimeGreen(new Color(50, 205, 50)),
Peru(new Color(205, 133, 63)),
IndianRed(new Color(205, 92, 92)),
YellowGreen(new Color(173, 255, 47)),
DarkRed(new Color(139, 0, 0)),
OrangeRed(new Color(255, 69, 0));
private final Color color;
private MatchedNodeColors(Color color)
{
this.color = color;
}
public Color getColor()
{
return color;
}
/**
* Returns the hexadecimal RGB representation beginning with a hash-sign.
* @return the color in the format "#rrggbb"
*/
public String getHTMLColor()
{
StringBuilder result = new StringBuilder("#");
result.append(twoDigitHex(color.getRed()));
result.append(twoDigitHex(color.getGreen()));
result.append(twoDigitHex(color.getBlue()));
return result.toString();
}
private String twoDigitHex(int i)
{
String result = Integer.toHexString(i).toLowerCase(new Locale("en"));
if(result.length() > 2)
{
result = result.substring(0, 2);
}
else if(result.length() < 2)
{
result = StringUtils.leftPad(result, 2, '0');
}
return result;
}
public static String colorClassByMatch(Long match)
{
if(match == null)
{
return null;
}
long m = match;
m = Math.min(m, 8);
return "match_" + m;
}
}
| 25.382022 | 76 | 0.674192 |
70676640a33ab9b6adbc60eff1905ebbe567b3d8 | 2,131 | package skybox;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import entities.Camera;
import renderEngine.DisplayManager;
import shaders.ShaderProgram;
import toolbox.Maths;
public class SkyboxShader extends ShaderProgram{
private static final String VERTEX_FILE = "src/skybox/skyboxVertexShader.txt";
private static final String FRAGMENT_FILE = "src/skybox/skyboxFragmentShader.txt";
private static final float ROTATE_SPEED = 1f;
private int location_projectionMatrix;
private int location_viewMatrix;
private int location_fogColour;
private int location_cubeMap;
private int location_cubeMap2;
private int location_blendFactor;
private float rotation = 0;
public SkyboxShader() {
super(VERTEX_FILE, FRAGMENT_FILE);
}
public void loadProjectionMatrix(Matrix4f matrix){
super.loadMatrix(location_projectionMatrix, matrix);
}
public void loadViewMatrix(Camera camera){
Matrix4f matrix = Maths.createViewMatrix(camera);
matrix.m30 = 0.0f;
matrix.m31 = 0.0f;
matrix.m32 = 0.0f;
rotation += ROTATE_SPEED * DisplayManager.getFrameTimeSeconds();
Matrix4f.rotate((float) Math.toRadians(rotation), new Vector3f(0,1,0), matrix, matrix);
super.loadMatrix(location_viewMatrix, matrix);
}
@Override
protected void getAllUniformLocations() {
location_projectionMatrix = super.getUniformLocation("projectionMatrix");
location_viewMatrix = super.getUniformLocation("viewMatrix");
location_fogColour = super.getUniformLocation("fogColour");
location_blendFactor = super.getUniformLocation("blendFactor");
location_cubeMap = super.getUniformLocation("cubeMap");
location_cubeMap2 = super.getUniformLocation("cubeMap2");
}
@Override
protected void bindAttributes() {
super.bindAttribute(0, "position");
}
public void connectTextureUnits(){
super.loadInt(location_cubeMap, 0);
super.loadInt(location_cubeMap2, 1);
}
public void loadFogColour(float r, float g, float b){
super.loadVector(location_fogColour, new Vector3f(r,g,b));
}
public void loadBlendFactor(float blend){
super.loadFloat(location_blendFactor, blend);
}
}
| 28.413333 | 89 | 0.779446 |
aa542ce76a8763e73ae4697a2a942a7044859509 | 221 | package com.jerryjin.kit;
/**
* Author: Jerry
* Generated at: 2019/3/16 11:53 AM
* GitHub: https://github.com/JerryJin93
* Blog:
* WeChat: enGrave93
* Description:
*/
public interface ICopy {
Object copy();
}
| 15.785714 | 40 | 0.660633 |
04859a6635b028383aa61f37ed6ab53809b328c3 | 2,089 | package io.papermc.lib.environments;
import io.papermc.lib.features.asyncchunks.AsyncChunksPaper_13;
import io.papermc.lib.features.asyncchunks.AsyncChunksPaper_15;
import io.papermc.lib.features.asyncchunks.AsyncChunksPaper_9_12;
import io.papermc.lib.features.asyncteleport.AsyncTeleportPaper;
import io.papermc.lib.features.asyncteleport.AsyncTeleportPaper_13;
import io.papermc.lib.features.bedspawnlocation.BedSpawnLocationPaper;
import io.papermc.lib.features.blockstatesnapshot.BlockStateSnapshotOptionalSnapshots;
import io.papermc.lib.features.chunkisgenerated.ChunkIsGeneratedApiExists;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.HumanEntity;
public class PaperEnvironment extends SpigotEnvironment {
public PaperEnvironment() {
super();
if (isVersion(13, 1)) {
asyncChunksHandler = new AsyncChunksPaper_13();
asyncTeleportHandler = new AsyncTeleportPaper_13();
} else if (isVersion(9) && !isVersion(13)) {
asyncChunksHandler = new AsyncChunksPaper_9_12();
asyncTeleportHandler = new AsyncTeleportPaper();
}
if (isVersion(12)) {
// Paper added this API in 1.12 with same signature spigot did in 1.13
isGeneratedHandler = new ChunkIsGeneratedApiExists();
blockStateSnapshotHandler = new BlockStateSnapshotOptionalSnapshots();
}
if (isVersion(15, 2)) {
try {
// Try for new Urgent API in 1.15.2+, Teleport will automatically benefit from this
World.class.getDeclaredMethod("getChunkAtAsyncUrgently", Location.class);
asyncChunksHandler = new AsyncChunksPaper_15();
HumanEntity.class.getDeclaredMethod("getPotentialBedLocation");
bedSpawnLocationHandler = new BedSpawnLocationPaper();
} catch (NoSuchMethodException ignored) {}
}
}
@Override
public String getName() {
return "Paper";
}
@Override
public boolean isPaper() {
return true;
}
}
| 38.685185 | 99 | 0.69842 |
e8de9b368deca86adc71a39a92b04b7ca4083c98 | 1,045 | /**
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.thinkgem.jeesite.modules.cfca.dao;
import com.thinkgem.jeesite.common.persistence.CrudDao;
import com.thinkgem.jeesite.common.persistence.annotation.MyBatisDao;
import com.thinkgem.jeesite.modules.cfca.entity.CfcaElectronicChapter;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* 电子签章申请结果DAO接口
* @author xqg
* @version 2018-09-03
*/
@MyBatisDao
public interface CfcaElectronicChapterDao extends CrudDao<CfcaElectronicChapter> {
void updateChapterImage(CfcaElectronicChapter cfcaElectronicChapter);
List<CfcaElectronicChapter> findSelfList(CfcaElectronicChapter cfcaElectronicChapter);
/**
* 查询出所有未下载证书的记录
* @param cfcaElectronicChapter
* @return
*/
List<CfcaElectronicChapter> findNoDonloadList(CfcaElectronicChapter cfcaElectronicChapter);
/**
* 查询UkeyId 的个数
* @param ukeyId
* @return
*/
Integer getUkeyIdCount(@Param(value = "ukeyId") String ukeyId );
} | 26.125 | 108 | 0.779904 |
9a7d626b199bee0b26bc34603cd28e665a2966c1 | 1,617 | /*
* Copyright 2018 jd.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.yihaodian.architecture.kira.schedule.time.trigger;
interface IHashedWheelTimerAwareScheduleTarget {
/**
* Caution: Used internally only. The user should not call this method directly.
*/
long getLifeOnHashedWheelInMs();
/**
* Caution: Used internally only. The user should not call this method directly.
*/
void setLifeOnHashedWheelInMs(long lifeInMs);
/**
* Caution: Used internally only. The user should not call this method directly.
*/
int getIndexOnHashedWheel();
/**
* Caution: Used internally only. The user should not call this method directly.
*/
void setIndexOnHashedWheel(int indexOnHashedWheel);
/**
* Caution: Used internally only. The user should not call this method directly.
*/
long getRemainingRoundsOnHashedWheel();
/**
* Caution: Used internally only. The user should not call this method directly.
*/
void setRemainingRoundsOnHashedWheel(long remainingRoundsOnHashedWheel);
}
| 33 | 83 | 0.711812 |
59c63d90f1c8fa5a3a62d3ffe8e3262a80da9d97 | 532 |
package com.elusivehawk.util.math;
import com.elusivehawk.util.Dirtable;
/**
*
*
*
* @author Elusivehawk
*/
public abstract class Arithmetic extends Dirtable
{
private boolean immutable = false, sync = false;
public boolean isImmutable()
{
return this.immutable;
}
public Arithmetic setImmutable()
{
this.immutable = true;
return this;
}
public boolean isSync()
{
return this.sync;
}
public Arithmetic setSync()
{
this.sync = true;
return this;
}
public abstract int size();
}
| 12.372093 | 49 | 0.669173 |
62909cb9e4f21a8402503bf141954ba7af562647 | 5,247 | /*
* Copyright (c) 2012 M. M. Naseri <[email protected]>
*
* 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.
*/
package com.agileapes.powerpack.reflection.beans.impl;
import com.agileapes.powerpack.reflection.beans.BeanAccessorFactory;
import com.agileapes.powerpack.reflection.exceptions.NoSuchPropertyException;
import com.agileapes.powerpack.reflection.exceptions.PropertyReadAccessException;
import com.agileapes.powerpack.test.model.Book;
import com.agileapes.powerpack.test.model.RefusingBean;
import com.agileapes.powerpack.tools.collections.CollectionUtils;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.Set;
/**
* @author Mohammad Milad Naseri ([email protected])
* @since 1.0 (2012/11/15, 16:12)
*/
public class GetterBeanAccessorTest {
public static final String TITLE = "Killer UX Design";
public static final String AUTHOR = "Jodie Moule";
private final BeanAccessorFactory factory = new GetterBeanAccessorFactory();
private GetterBeanAccessor<Book> getBeanAccessor() {
final Book book = new Book();
book.setTitle(TITLE);
book.setAuthor(AUTHOR);
return (GetterBeanAccessor<Book>) factory.getBeanAccessor(book);
}
@Test
public void testGetPropertyValue() throws Exception {
final Object title = getBeanAccessor().getPropertyValue("title");
Assert.assertEquals(title, TITLE);
}
@Test
public void testGetBean() throws Exception {
Assert.assertNotNull(getBeanAccessor().getBean());
}
@Test
public void testGetProperties() throws Exception {
final Set<String> properties = CollectionUtils.asSet("title", "author", "class");
final GetterBeanAccessor<Book> descriptor = getBeanAccessor();
Assert.assertEquals(descriptor.getProperties().size(), properties.size());
for (String propertyName : descriptor.getProperties()) {
Assert.assertTrue(properties.contains(propertyName));
}
}
@Test
public void testHasProperty() throws Exception {
final Set<String> properties = CollectionUtils.asSet("title", "author", "class");
final GetterBeanAccessor<Book> beanAccessor = getBeanAccessor();
for (String property : properties) {
Assert.assertTrue(beanAccessor.hasProperty(property));
}
}
@Test
public void testGetPropertyType() throws Exception {
Assert.assertEquals(getBeanAccessor().getPropertyType("title"), String.class);
}
@Test
public void testGetBeanType() throws Exception {
Assert.assertEquals(getBeanAccessor().getBeanType(), Book.class);
}
@Test
public void testCanWrite() throws Exception {
Assert.assertTrue(getBeanAccessor().canWrite("title"));
Assert.assertTrue(getBeanAccessor().canWrite("author"));
Assert.assertFalse(getBeanAccessor().canWrite("class"));
}
@Test
public void testGetAccessMethod() throws Exception {
final PropertyAccessMethod accessMethod = getBeanAccessor().getAccessMethod("title");
Assert.assertNotNull(accessMethod);
Assert.assertEquals(accessMethod.getAccessType(), AccessType.METHOD);
Assert.assertEquals(accessMethod.getPropertyName(), "title");
Assert.assertEquals(accessMethod.getAccessorName(), "getTitle");
}
@Test(expectedExceptions = NoSuchPropertyException.class)
public void testCanWriteForNonExistentProperty() throws Exception {
final GetterBeanAccessor<Book> accessor = getBeanAccessor();
accessor.canWrite("myProperty ");
}
@Test(expectedExceptions = PropertyReadAccessException.class)
public void testReadError() throws Exception {
final GetterBeanAccessor<RefusingBean> accessor = new GetterBeanAccessor<RefusingBean>(new RefusingBean());
accessor.getPropertyValue("name");
}
@Test(expectedExceptions = NoSuchPropertyException.class)
public void testGetPropertyValueForNonExistentProperty() throws Exception {
final GetterBeanAccessor<Book> accessor = getBeanAccessor();
accessor.getPropertyValue("property");
}
@Test(expectedExceptions = NoSuchPropertyException.class)
public void testGetTypedPropertyValueForNonExistentProperty() throws Exception {
final GetterBeanAccessor<Book> accessor = getBeanAccessor();
accessor.getPropertyValue("property", Class.class);
}
@Test(expectedExceptions = NoSuchPropertyException.class)
public void testGetPropertyValueWithInvalidType() throws Exception {
final GetterBeanAccessor<Book> accessor = getBeanAccessor();
accessor.getPropertyValue("title", Class.class);
}
}
| 40.053435 | 115 | 0.725367 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.