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 |
|---|---|---|---|---|---|
645cb0aa0700ca8685ea611c9a8233405f0b1dc7 | 605 | package com.hribol.bromium.common.replay;
import com.hribol.bromium.replay.ReplayingState;
import com.hribol.bromium.replay.filters.StateConditionsUpdater;
/**
* Updates a condition by setting it to satisfied and signalizes if the current
* synchronization event that we are waiting for is satisfied
*/
public class SignalizingStateConditionsUpdater implements StateConditionsUpdater {
@Override
public void update(ReplayingState replayingState, String event) {
replayingState.setConditionSatisfied(event);
replayingState.signalizeIfSynchronizationEventIsSatisfied();
}
}
| 35.588235 | 82 | 0.798347 |
7b4aad10bb168edab88979f609ffee8669ea0060 | 3,594 | /*
* Copyright (C) 2006-2020 Talend Inc. - www.talend.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 org.talend.components.azure.runtime.converters;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.talend.components.azure.runtime.input.SchemaUtils;
import org.talend.sdk.component.api.record.Record;
import org.talend.sdk.component.api.record.Schema;
import org.talend.sdk.component.api.service.record.RecordBuilderFactory;
public class HTMLConverter implements RecordConverter<Element> {
public static HTMLConverter of(RecordBuilderFactory recordBuilderFactory) {
return new HTMLConverter(recordBuilderFactory);
}
private RecordBuilderFactory recordBuilderFactory;
private Schema columns;
private HTMLConverter(RecordBuilderFactory recordBuilderFactory) {
this.recordBuilderFactory = recordBuilderFactory;
}
@Override
public Schema inferSchema(Element record) {
if (columns == null) {
List<String> columnNames = inferSchemaInfo(record, !isHeaderRecord(record));
Schema.Builder schemaBuilder = recordBuilderFactory.newSchemaBuilder(Schema.Type.RECORD);
columnNames.forEach(column -> schemaBuilder
.withEntry(recordBuilderFactory.newEntryBuilder().withName(column).withType(Schema.Type.STRING).build()));
columns = schemaBuilder.build();
}
return columns;
}
@Override
public Record toRecord(Element record) {
if (columns == null) {
columns = inferSchema(record);
}
Record.Builder builder = recordBuilderFactory.newRecordBuilder();
Elements rowColumns = record.getAllElements();
for (int i = 1; i < rowColumns.size(); i++) {
builder.withString(columns.getEntries().get(i - 1).getName(), rowColumns.get(i).text());
}
return builder.build();
}
@Override
public Element fromRecord(Record record) {
throw new UnsupportedOperationException("HTML Output are not supported");
}
private List<String> inferSchemaInfo(Element row, boolean useDefaultFieldName) {
List<String> result = new ArrayList<>();
Set<String> existNames = new HashSet<>();
int index = 0;
Elements columns = row.getAllElements();
for (int i = 1; i < columns.size(); i++) { // skip first element since it would be the whole row
String fieldName = columns.get(i).ownText();
if (useDefaultFieldName || StringUtils.isEmpty(fieldName)) {
fieldName = "field" + (i - 1);
}
String finalName = SchemaUtils.correct(fieldName, index++, existNames);
existNames.add(finalName);
result.add(finalName);
}
return result;
}
private boolean isHeaderRecord(Element record) {
return record.getElementsByTag("th").size() > 0;
}
}
| 37.4375 | 126 | 0.685031 |
0e72e1e6d8819a4d282baa28e6c0c9515b5fe9a7 | 2,171 | package net.obvj.confectory;
import java.util.Optional;
/**
* A base interface for objects that retrieve configuration data.
*
* @param <T> the source type which configuration data is to be retrieved
*
* @author oswaldo.bapvic.jr (Oswaldo Junior)
* @since 0.1.0
*/
public interface ConfigurationDataRetriever<T>
{
/**
* Returns the source configuration object used by this helper object, typically for
* manual handling and/or troubleshooting purposes.
*
* @return an {@link Optional}, possibly containing the source configuration object
*/
Optional<T> getBean();
/**
* Returns the {@code boolean} value associated with the specified {@code key}.
*
* @param key the property key
* @return the {@code boolean} value associated with the specified {@code key}
*/
boolean getBooleanProperty(String key);
/**
* Returns the {@code int} value associated with the specified {@code key}.
*
* @param key the property key
* @return the {@code int} value associated with the specified {@code key}
* @throws NumberFormatException if the value is not a parsable {@code int}.
*/
int getIntProperty(String key);
/**
* Returns the {@code long} value associated with the specified {@code key}.
*
* @param key the property key
* @return the {@code long} value associated with the specified {@code key}
* @throws NumberFormatException if the value is not a parsable {@code long}.
*/
long getLongProperty(String key);
/**
* Returns the {@code double} value associated with the specified {@code key}.
*
* @param key the property key
* @return the {@code double} value associated with the specified {@code key}
* @throws NumberFormatException if the value is not a parsable {@code double}.
*/
double getDoubleProperty(String key);
/**
* Returns the {@code String} value associated with the specified {@code key}.
*
* @param key the property key
* @return the {@code String} value associated with the specified {@code key}
*/
String getStringProperty(String key);
}
| 31.926471 | 88 | 0.662828 |
1a18ad2b256ea082f3b49e2ce7add48bbf15e0ec | 626 | package com.atguigu.gmall.item.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.*;
/**
* @author saberlin
* @create 2021/12/16 11:17
*/
@Configuration
public class ThreadPoolConfig {
@Bean
public ExecutorService executorService(){
return new ThreadPoolExecutor(40,200,600, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(1000), Executors.defaultThreadFactory(),
(Runnable r, ThreadPoolExecutor executor)->{
System.out.println("异步任务失败");
});
}
}
| 27.217391 | 81 | 0.683706 |
830b3078a5d8bf03424cf37f0feb74e6470c4220 | 451 | package fwcd.whiteboard.protocol.request;
import fwcd.whiteboard.protocol.dispatch.WhiteboardServer;
public class GetAllItemsRequest extends Request {
protected GetAllItemsRequest() {}
public GetAllItemsRequest(long senderId) {
super(senderId, RequestName.GET_ALL_ITEMS);
}
@Override
public void sendTo(WhiteboardServer server) {
server.getAllItems(this);
}
@Override
public String toString() {
return "GetAllItemsRequest";
}
}
| 20.5 | 58 | 0.776053 |
114c5291d9cde2334da9525e85123a036dd9c1fe | 1,287 | /*
* 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 uk.ac.sanger.phenodigm2.model;
/**
*
* @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk>
*/
public class DiseaseIdentifier extends ExternalIdentifier implements Comparable<DiseaseIdentifier> {
public DiseaseIdentifier(String compoundIdentifier) {
super(compoundIdentifier);
}
public DiseaseIdentifier(String databaseCode, String databaseAcc) {
super(databaseCode, databaseAcc);
}
/**
* Sorts the ExternalIdentifier by databaseCode and then by databaseIdentifier
* @param other
* @return
*/
@Override
public int compareTo(DiseaseIdentifier other) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;
if (this == other) {
return EQUAL;
}
if (this.getDatabaseCode().equals(other.getDatabaseCode())) {
return (this.getDatabaseAcc().compareTo(other.getDatabaseAcc()));
}
return this.getDatabaseCode().compareTo(other.getDatabaseCode());
}
}
| 28.6 | 101 | 0.626263 |
5290deab0c75037d12ccc84458030406c66bd12e | 1,335 | package com.musicallcommunity.musicallback.repository.impl;
import com.musicallcommunity.musicallback.model.Conversation;
import com.musicallcommunity.musicallback.repository.ConversationRepository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;
abstract class ConversationRepositoryImpl implements ConversationRepository {
@PersistenceContext
EntityManager entityManager;
@Override
public List getByUserId(Long userId) {
Query query = entityManager.createNativeQuery("SELECT c.* FROM conversation as c " +
"WHERE c.user_id = ?", Conversation.class);
query.setParameter(1, userId );
return query.getResultList();
}
/*@Override
public List getByIdAndSenderId(Long id, Long sender_id) {
Query query = entityManager.createNativeQuery(
"SELECT c.* FROM conversation as c " + "WHERE c.user_id IN " +
"(SELECT m.sender_id FROM ? as m " + "WHERE m.sender_id = ?) " +
"AND c.id = ?"
, Conversation.class);
query.setParameter(1, Message.class);
query.setParameter(1, sender_id );
query.setParameter(3, id );
return query.getResultList();
}*/
}
| 29.021739 | 92 | 0.669663 |
65f2fc1355c1eeb8da5b4b4fea7aab734daa380a | 618 | package de.chrissx.fixe4j;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class Fixe {
public static byte[] keyFromStr(String str)
{
return str.getBytes(StandardCharsets.US_ASCII);
}
public static byte[] keyFromInt(int i)
{
return ByteBuffer.allocate(4).putInt(i).array();
}
public static byte[] keyFromLong(long i)
{
return ByteBuffer.allocate(8).putLong(i).array();
}
public static void fixe(byte[] key, byte[] in, byte[] out)
{
assert in.length <= out.length;
for(int i = 0; i < in.length; i++)
{
out[i] = (byte) (in[i] ^ key[i % key.length]);
}
}
}
| 19.3125 | 59 | 0.669903 |
26f8c15f27c077b9f81effa3634e6e3302aa5caa | 3,396 | /**
* Copyright © 2006-2016 Web Cohesion (info@webcohesion.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.webcohesion.enunciate.util.freemarker;
import com.webcohesion.enunciate.metadata.ClientName;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.Configuration;
import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import java.util.Iterator;
import java.util.List;
/**
* Gets the client-side component type for the specified classname.
*
* @author Ryan Heaton
*/
public class SimpleNameWithParamsMethod implements TemplateMethodModelEx {
private final ClientClassnameForMethod typeConversion;
public SimpleNameWithParamsMethod(ClientClassnameForMethod typeConversion) {
this.typeConversion = typeConversion;
}
/**
* Gets the client-side package for the type, type declaration, package, or their string values.
*
* @param list The arguments.
* @return The string value of the client-side package.
*/
public Object exec(List list) throws TemplateModelException {
if (list.size() < 1) {
throw new TemplateModelException("The convertPackage method must have the class or package as a parameter.");
}
TemplateModel from = (TemplateModel) list.get(0);
Object unwrapped = FreemarkerUtil.unwrap(from);
boolean noParams = list.size() > 1 && Boolean.FALSE.equals(FreemarkerUtil.unwrap((TemplateModel) list.get(1)));
return simpleNameFor(unwrapped, noParams);
}
public String simpleNameFor(Object unwrapped, boolean noParams) throws TemplateModelException {
if (!(unwrapped instanceof TypeElement)) {
throw new TemplateModelException("A type element must be provided.");
}
TypeElement declaration = (TypeElement) unwrapped;
String simpleNameWithParams = declaration.getAnnotation(ClientName.class) != null ? declaration.getAnnotation(ClientName.class).value() : declaration.getSimpleName().toString();
if (!noParams) {
simpleNameWithParams += convertTypeParams(declaration);
}
return simpleNameWithParams;
}
protected String convertTypeParams(TypeElement declaration) throws TemplateModelException {
String typeParams = "";
if (declaration.getTypeParameters() != null && !declaration.getTypeParameters().isEmpty()) {
typeParams += "<";
Iterator<? extends TypeParameterElement> paramIt = declaration.getTypeParameters().iterator();
while (paramIt.hasNext()) {
typeParams += this.typeConversion.convert(paramIt.next());
if (paramIt.hasNext()) {
typeParams += ", ";
}
}
typeParams += ">";
}
return typeParams;
}
} | 37.318681 | 181 | 0.739988 |
a0eb410db7405bf1430649d601606350c1c9e460 | 5,422 | /*
* Copyright 2005 David M Johnson (For RSS and Atom In Action)
*
* 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.apache.roller.weblogger.webservices.adminprotocol;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Writer;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
import org.jdom.output.Format;
import org.apache.roller.weblogger.webservices.adminprotocol.sdk.EntrySet;
/**
* Atom Admin Servlet implements the Atom Admin endpoint.
* This servlet simply delegates work to a particular handler object.
*
* @author jtb
* @web.servlet name="AdminServlet"
* @web.servlet-mapping url-pattern="/roller-services/rap/*"
*/
public class AdminServlet extends HttpServlet {
private static Log logger = LogFactory.getFactory().getInstance(AdminServlet.class);
/**
* Handles an Atom GET by calling handler and writing results to response.
*/
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Handler handler = Handler.getHandler(req);
String userName = handler.getUserName();
EntrySet c = handler.processGet();
res.setStatus(HttpServletResponse.SC_OK);
res.setContentType("application/xml; charset=utf-8");
String s = c.toString();
Writer writer = res.getWriter();
writer.write(s);
writer.close();
} catch (HandlerException he) {
res.sendError(he.getStatus(), he.getMessage());
he.printStackTrace(res.getWriter());
logger.error(he);
}
}
/**
* Handles an Atom POST by calling handler to identify URI, reading/parsing
* data, calling handler and writing results to response.
*/
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Handler handler = Handler.getHandler(req);
String userName = handler.getUserName();
EntrySet c = handler.processPost(new InputStreamReader(req.getInputStream()));
res.setStatus(HttpServletResponse.SC_CREATED);
res.setContentType("application/xml; charset=utf-8");
String s = c.toString();
Writer writer = res.getWriter();
writer.write(s);
writer.close();
} catch (HandlerException he) {
res.sendError(he.getStatus(), he.getMessage());
he.printStackTrace(res.getWriter());
logger.error(he);
}
}
/**
* Handles an Atom PUT by calling handler to identify URI, reading/parsing
* data, calling handler and writing results to response.
*/
protected void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Handler handler = Handler.getHandler(req);
String userName = handler.getUserName();
EntrySet c = handler.processPut(new InputStreamReader(req.getInputStream()));
res.setStatus(HttpServletResponse.SC_OK);
res.setContentType("application/xml; charset=utf-8");
String s = c.toString();
Writer writer = res.getWriter();
writer.write(s);
writer.close();
} catch (HandlerException he) {
res.sendError(he.getStatus(), he.getMessage());
he.printStackTrace(res.getWriter());
logger.error(he);
}
}
/**
* Handle Atom Admin DELETE by calling appropriate handler.
*/
protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try {
Handler handler = Handler.getHandler(req);
String userName = handler.getUserName();
EntrySet es = handler.processDelete();
res.setStatus(HttpServletResponse.SC_OK);
res.setContentType("application/xml; charset=utf-8");
String s = es.toString();
Writer writer = res.getWriter();
writer.write(s);
writer.close();
} catch (HandlerException he) {
res.sendError(he.getStatus(), he.getMessage());
he.printStackTrace(res.getWriter());
logger.error(he);
}
}
}
| 39.289855 | 115 | 0.620804 |
ffb9fcd6801516267d4142663bf38cc66c91304d | 2,078 | /*
* Copyright Ningbo Qishan 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.mds.group.purchase.logistics.result;
import com.mds.group.purchase.logistics.model.Community;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* The type Community can pick.
*
* @author pavawi
*/
@Data
@EqualsAndHashCode(callSuper = true)
public class CommunityCanPick extends Community implements Comparable<CommunityCanPick> {
@ApiModelProperty("用户与小区的距离")
private Double distance;
/**
* Instantiates a new Community can pick.
*
* @param c the c
*/
public CommunityCanPick(Community c) {
setAppmodelId(c.getAppmodelId());
setCommunityId(c.getCommunityId());
setCommunityName(c.getCommunityName());
setPcaAdr(c.getPcaAdr());
setStreetName(c.getStreetName());
setAreaId(c.getAreaId());
setAreaName(c.getAreaName());
setCityId(c.getCityId());
setLocation(c.getLocation());
setProvinceId(c.getProvinceId());
setStreetId(c.getStreetId());
}
/**
* Instantiates a new Community can pick.
*/
public CommunityCanPick() {
}
@Override
public int compareTo(CommunityCanPick o) {
if (o == null) {
return 0;
}
if (Double.valueOf(this.getDistance()) != null && Double.valueOf(o.getDistance()) != null) {
return (int) (this.getDistance() - o.getDistance());
}
return 0;
}
}
| 28.465753 | 100 | 0.664581 |
8f2a31e884cb7da1866cdd3b4f239d5e5cd91e8b | 216 | package com.pushcart.repository;
import com.pushcart.model.Basket;
import org.springframework.data.jpa.repository.JpaRepository;
public interface BasketRepository extends JpaRepository<Basket, Long> {
}
| 21.6 | 72 | 0.791667 |
063a5dfa06bbe0491bb927086bdeedf386c5d1b1 | 3,850 | package com.g13.pdt.servicios;
import java.util.Date;
import java.util.List;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.TypedQuery;
import javax.validation.ConstraintViolationException;
import com.g13.pdt.entidades.Propietario;
import com.g13.pdt.excepciones.DatosInvalidosException;
import com.g13.pdt.excepciones.NoExisteElementoException;
import com.g13.pdt.interfaces.IPropietarios;
import com.g13.pdt.util.CadenasUtil;
@Stateless
@Remote
public class PropietariosBeanRemote implements IPropietarios {
@PersistenceContext
private EntityManager em;
public PropietariosBeanRemote() {
}
@Override
public Propietario altaPropietario(Propietario propietario) throws DatosInvalidosException {
try {
propietario.setActivo(true);
propietario.setDesde(new Date());
this.em.persist(propietario);
this.em.flush();
}
catch (ConstraintViolationException e) {
DatosInvalidosException ee = CadenasUtil.crearException(e);
throw ee;
}
catch (PersistenceException e) {
DatosInvalidosException pe = CadenasUtil.crearException(e);
throw pe;
}
return propietario;
}
@Override
public Propietario editarPropietario(Propietario propietario) throws DatosInvalidosException, NoExisteElementoException {
this.obtenerPorId(propietario.getId()); //Si no existe tira NoExisteElementoException
try {
this.em.merge(propietario);
this.em.flush();
}
catch (ConstraintViolationException e) {
DatosInvalidosException ee = CadenasUtil.crearException(e);
throw ee;
}
catch (PersistenceException e) {
DatosInvalidosException pe = CadenasUtil.crearException(e);
throw pe;
}
return propietario;
}
@Override
public Propietario desactivarPropietario(Propietario propietario) throws DatosInvalidosException, NoExisteElementoException {
// this.em.merge(propietario);
propietario = this.obtenerPorId(propietario.getId()); //Si no existe tira NoExisteElementoException;
try {
propietario.setActivo(false);
propietario.setHasta(new Date());
this.em.flush();
}
catch (ConstraintViolationException e) {
DatosInvalidosException ee = CadenasUtil.crearException(e);
throw ee;
}
catch (PersistenceException e) {
DatosInvalidosException pe = CadenasUtil.crearException(e);
throw pe;
}
return propietario;
}
@Override
public List<Propietario> obtenerListaTodos() {
TypedQuery<Propietario> query = this.em.createQuery("SELECT p FROM Propietario p",Propietario.class);
List<Propietario> resultado = query.getResultList();
// resultado.size();
return resultado;
}
@Override
public Propietario activarPropietario(Propietario propietario) throws DatosInvalidosException, NoExisteElementoException {
propietario = this.obtenerPorId(propietario.getId()); //Si no existe tira NoExisteElementoException;
try {
propietario.setActivo(true);
propietario.setDesde(new Date());
this.em.flush();
}
catch (ConstraintViolationException e) {
DatosInvalidosException ee = CadenasUtil.crearException(e);
throw ee;
}
catch (PersistenceException e) {
DatosInvalidosException pe = CadenasUtil.crearException(e);
System.out.println("DIO PERSISTENCE EXCEPTION");
throw pe;
}
catch (NullPointerException e) {
DatosInvalidosException pe = CadenasUtil.crearException(e);
throw pe;
}
return propietario;
}
@Override
public Propietario obtenerPorId(Integer id) throws NoExisteElementoException {
Propietario entidadBD = this.em.find(Propietario.class, id);
if (entidadBD == null) {
throw new NoExisteElementoException("No existe un Propietario con id " + id);
}
return entidadBD;
}
}
| 28.947368 | 126 | 0.756623 |
ce5eb81540e2b8943ae8ee1454f6e08631e148c8 | 169 | package com.intellij.execution;
import java.util.concurrent.Future;
/**
* @author traff
*/
public interface TaskExecutor {
Future<?> executeTask(Runnable task);
}
| 15.363636 | 39 | 0.733728 |
6ff8cb469fef1736cdfd8fa18d7df6ed5156c093 | 1,247 | /*
* #%L
* wcm.io
* %%
* Copyright (C) 2015 wcm.io
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.wcm.caravan.jaxrs.publisher;
import org.osgi.annotation.versioning.ConsumerType;
/**
* Marker interface that is implemented by all JAX-RS services and providers
* that are also OSGi components.
*/
//CHECKSTYLE:OFF
@ConsumerType
public interface JaxRsComponent {
//CHECKSTYLE:ON
/**
* OSGi property name that marks JaxRS components to be registered globally to all JAX-RS applications.
* The property value has to be set to "true".
* Such components have to be marked as "serviceFactory" as well to ensure bundle scope.
*/
String PROPERTY_GLOBAL_COMPONENT = "caravan.jaxrs.global";
}
| 30.414634 | 105 | 0.727346 |
3fe7a54fbf6b4b26b5b3346280230dbd3d5401ca | 355 | package org.springframework.autobuilds.jpetstore.dao;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.autobuilds.jpetstore.domain.Category;
public interface CategoryDao {
List getCategoryList() throws DataAccessException;
Category getCategory(String categoryId) throws DataAccessException;
}
| 23.666667 | 69 | 0.839437 |
9d94a455a4c08f9cef9e113a83fa14584ee12f37 | 4,393 | /**
* Copyright (c) 2000-2018 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
package com.liferay.faces.osgi.weaver.internal;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.Version;
/**
* @author Kyle Stiemann
*/
public class BundleMockImpl implements Bundle {
@Override
public <A> A adapt(Class<A> type) {
throw new UnsupportedOperationException("");
}
@Override
public int compareTo(Bundle o) {
throw new UnsupportedOperationException("");
}
@Override
public Enumeration<URL> findEntries(String path, String filePattern, boolean recurse) {
throw new UnsupportedOperationException("");
}
@Override
public BundleContext getBundleContext() {
throw new UnsupportedOperationException("");
}
@Override
public long getBundleId() {
throw new UnsupportedOperationException("");
}
@Override
public File getDataFile(String filename) {
throw new UnsupportedOperationException("");
}
@Override
public URL getEntry(String path) {
throw new UnsupportedOperationException("");
}
@Override
public Enumeration<String> getEntryPaths(String path) {
throw new UnsupportedOperationException("");
}
@Override
public Dictionary<String, String> getHeaders() {
throw new UnsupportedOperationException("");
}
@Override
public Dictionary<String, String> getHeaders(String locale) {
throw new UnsupportedOperationException("");
}
@Override
public long getLastModified() {
throw new UnsupportedOperationException("");
}
@Override
public String getLocation() {
throw new UnsupportedOperationException("");
}
@Override
public ServiceReference<?>[] getRegisteredServices() {
throw new UnsupportedOperationException("");
}
@Override
public URL getResource(String name) {
throw new UnsupportedOperationException("");
}
@Override
public Enumeration<URL> getResources(String name) throws IOException {
throw new UnsupportedOperationException("");
}
@Override
public ServiceReference<?>[] getServicesInUse() {
throw new UnsupportedOperationException("");
}
@Override
public Map<X509Certificate, List<X509Certificate>> getSignerCertificates(int signersType) {
throw new UnsupportedOperationException("");
}
@Override
public int getState() {
throw new UnsupportedOperationException("");
}
@Override
public String getSymbolicName() {
return "test.bundle.symbolic.name";
}
@Override
public Version getVersion() {
throw new UnsupportedOperationException("");
}
@Override
public boolean hasPermission(Object permission) {
throw new UnsupportedOperationException("");
}
@Override
public Class<?> loadClass(String name) throws ClassNotFoundException {
throw new UnsupportedOperationException("");
}
@Override
public void start() throws BundleException {
throw new UnsupportedOperationException("");
}
@Override
public void start(int options) throws BundleException {
throw new UnsupportedOperationException("");
}
@Override
public void stop() throws BundleException {
throw new UnsupportedOperationException("");
}
@Override
public void stop(int options) throws BundleException {
throw new UnsupportedOperationException("");
}
@Override
public void uninstall() throws BundleException {
throw new UnsupportedOperationException("");
}
@Override
public void update() throws BundleException {
throw new UnsupportedOperationException("");
}
@Override
public void update(InputStream input) throws BundleException {
throw new UnsupportedOperationException("");
}
}
| 23.875 | 92 | 0.757796 |
785e4a879d11d48f7a940ddf474476ea77912715 | 921 | package com.inputstick.apps.kp2aplugin.remote;
import android.content.SharedPreferences;
import com.inputstick.api.layout.KeyboardLayout;
import com.inputstick.api.utils.remote.RemotePreferences;
import com.inputstick.apps.kp2aplugin.PreferencesHelper;
public class KP2ARemotePreferences extends RemotePreferences {
@Override
public void reload(SharedPreferences sharedPref) {
String code = PreferencesHelper.getRemoteLayoutCode(sharedPref);
layout = KeyboardLayout.getLayout(code);
typingSpeed = PreferencesHelper.getTypingSpeed(sharedPref);
showModifiers = true;
showMouse = true;
touchScreenMode = !PreferencesHelper.isRemoteInMouseMode(sharedPref);
ratio = 0;
tapToClick = true;
mouseSensitivity = PreferencesHelper.getRemoteMouseSensitivity(sharedPref);
scrollSensitivity = PreferencesHelper.getRemoteScrollSensitivity(sharedPref);
proximityThreshold = 0;
tapInterval = 500;
}
}
| 31.758621 | 79 | 0.813246 |
3d1f6c3aca0da039e250c786e0c3135d5f60824c | 116 | package ro.lau.app.assetresizer.business;
/**
* Created by lau on 15.02.2017.
*/
public class ImageProcessor {
}
| 14.5 | 41 | 0.706897 |
20bdcc53833072470418f4affdae2653d67022e7 | 2,375 | package ca.bc.gov.hlth.hnsecure.message;
import java.util.HashMap;
import java.util.Map;
public class MessageUtil {
public static final Map<String, String> mTypeCollection = new HashMap<String, String>();
static {
mTypeCollection.put("R15", "RAICHK-BNF-CVST");
mTypeCollection.put("R33", "RAICMPL-PR-INFO");
mTypeCollection.put("E45", "RAIELG-CNFRM");
mTypeCollection.put("R35", "RAIEND-PYR-RL");
mTypeCollection.put("R36", "RAIEND-PYR-RLDP");
mTypeCollection.put("R30", "RAIEST-PYR-RL");
mTypeCollection.put("R31", "RAIEST-PYR-RLDP");
mTypeCollection.put("R37", "RAIGT-ACCT-ADDR");
mTypeCollection.put("R16", "RAIGT-BNF-CVPRD");
mTypeCollection.put("R32", "RAIGT-CNT-PRDS");
mTypeCollection.put("R22", "RAIGT-DCMNT-DTL");
mTypeCollection.put("R21", "RAIGT-DCMNT-SMY");
mTypeCollection.put("R03", "RAIGT-PRSN-DMGR");
mTypeCollection.put("R41", "RAINW-PYR-INQRY");
mTypeCollection.put("R42", "RAIPHN-LOOKUP");
mTypeCollection.put("R09", "RAIPRSN-NM-SRCH");
mTypeCollection.put("R20", "RAIRCRD-DCMNT");
mTypeCollection.put("R08", "RAIRCRD-DTH-VNT");
mTypeCollection.put("R01", "RAIRCRD-NW-BRN");
mTypeCollection.put("R02", "RAIRCRD-NW-PRSN");
mTypeCollection.put("R38", "RAIUP-ACCT-ADDR");
mTypeCollection.put("R39", "RAIUP-ACCT-PHON");
mTypeCollection.put("R34", "RAINW-PYR-INQRY");
mTypeCollection.put("R07", "RAIUPDT-PR-ADDR");
mTypeCollection.put("R06", "RAIUPDT-PR-DEMO");
mTypeCollection.put("R05", "RAIVLDT-ADDR");
mTypeCollection.put("R70", "PHCGT-REGDATA");
mTypeCollection.put("R71", "PHCADD-REG");
mTypeCollection.put("R72", "PHCDE-REG");
mTypeCollection.put("R73", "PHCCHG-REG");
mTypeCollection.put("R74", "PHCGT-PENDATA");
mTypeCollection.put("R75", "PHCPEND-OVRD");
mTypeCollection.put("R76", "PHCQRY-REPORT");
mTypeCollection.put("R49", "RAICOVPART-ENQ");
mTypeCollection.put("R43", "RAIRNST-OA-DEP");
mTypeCollection.put("R44", "RAIRNST-CNCL");
mTypeCollection.put("R45", "RAIRNW-CNCL");
mTypeCollection.put("R46", "RAIUPT-PREMCOV");
mTypeCollection.put("R50", "RAIENROL-EMP");
mTypeCollection.put("R51", "RAIEXTEND-VISA");
mTypeCollection.put("R52", "RAIENROL-DEP");
mTypeCollection.put("R53", "RAIEMP-FIND");
mTypeCollection.put("R54", "RAIEXT-VISA-DEP");
mTypeCollection.put("R55", "RAIEMP-LIST");
mTypeCollection.put("*", "PNP");
}
}
| 35.447761 | 89 | 0.690105 |
b8f891594ba16c09881d899e4a49e7badf001b0b | 2,298 | package com.wayne.algo.sort;
public class ShellSort {
private int length;
private int max;
private int array[];
public ShellSort() {
}
public ShellSort(int length, int max) {
init(length, max);
}
private void init(int length, int max) {
this.length = length;
this.max = max;
array = DataUtils.generateIntArray(length, max);
DataUtils.displayIntArray(array, "The original array is: ");
}
/**
* gap : h = 3*h + 1
*/
public void shellSortBasic() {
// get the max step as start point
int step = 1;
int factor = 3;
while (step <= this.max / factor) {
// [1,4,13,...]
step = step * factor + 1;
}
sortByStep(step, factor);
}
/**
* in the original shell sort algo, 2 is used as factor to get each steps, but it not efficient cause it may do repeat comparing & insert
* use Prime number as each step would be best as every time of insert by step, no cross repeat will occur
*/
public void shellSortPrimeNumber() {
double factor = 2.2;
int max_step = (int) Math.ceil(this.length / factor);
this.sortByStep(max_step, factor);
}
private void sortByStep(int step, double factor) {
// sort array by each step from max to 1
while (step > 0) {
System.out.println("each step: " + step);
// sort by index gap = step, using insert sort algorithm
for (int outter = step; outter < this.length; outter++) {
int temp = array[outter];
int inner = outter;
// find where to insert the temp
// move to right_index if it's bigger than temp
while ( inner > step -1 && array[inner-step] > temp) {
array[inner] = array[inner-step];
inner -= step;
}
array[inner] = temp;
}
step = (int) Math.ceil((step -1) / factor);
}
}
public static void main(String[] args) {
ShellSort ss = new ShellSort(20, 30);
ss.shellSortPrimeNumber();
System.out.println();
DataUtils.displayIntArray(ss.array, "sorted result: ");
}
}
| 27.686747 | 141 | 0.54047 |
ab2233deb5fd2e6448e465eb4147d526c3add0bc | 1,400 | package com.gabia.internproject.util.ObjectMaping.MapStruct;
import com.gabia.internproject.data.entity.PlaceType;
import com.gabia.internproject.data.entity.Role;
import com.gabia.internproject.dto.response.PlaceTypeResponseDTO;
import com.gabia.internproject.dto.response.RoleResponseDTO;
import org.mapstruct.Mapper;
import java.util.Collection;
import java.util.List;
@Mapper
public abstract class PlaceTypeMapper implements MapStructMapper {
abstract PlaceTypeResponseDTO convertToDTO(PlaceType entity);
abstract PlaceType convertToEntity(PlaceTypeResponseDTO dto);
abstract List<PlaceTypeResponseDTO> convertToDTO(Collection<PlaceType> entityList);
abstract List<PlaceType> convertToEntity(Collection<PlaceTypeResponseDTO> dtoList);
public <D, T> D convertToDTO(T entity,Class<D> dtoClass){
return (D)this.convertToDTO((PlaceType) entity);
};
public <D, T> D convertToEntity(T dto,Class<D> entityClass){
return (D)this.convertToEntity((PlaceTypeResponseDTO) dto);
};
public <D, T> List<D> convertToDTO(Collection<T> entityList, Class<D> dtoClass){
return (List<D>) this.convertToDTO( (Collection<PlaceType>) entityList);
}
public <D, T> List<D> convertToEntity(Collection<T> dtoList, Class<D> entityClass){
return (List<D>) this.convertToEntity( (Collection<PlaceTypeResponseDTO>) dtoList);
};
}
| 30.434783 | 91 | 0.755714 |
d0a95a8f92d347dcc4fdb5f8964a0068f746e60f | 956 | package org.nanotek.beans.entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.validation.Valid;
import org.nanotek.entities.AreaBeginDateEntity;
import org.nanotek.entities.MutableBeginDayEntity;
import org.nanotek.entities.MutableBeginMonthEntity;
import org.nanotek.entities.MutableBeginYearEntity;
@Valid
@Entity
@DiscriminatorValue("AreaBeginDate")
public class AreaBeginDate<K extends AreaBeginDate<K>> extends BeginDateBase<K> implements
AreaBeginDateEntity<K>,
MutableBeginYearEntity<Integer>,
MutableBeginMonthEntity<Integer>,
MutableBeginDayEntity<Integer>{
private static final long serialVersionUID = 4640549011512215583L;
public AreaBeginDate() {
}
public AreaBeginDate(Integer year) {
super(year);
}
public AreaBeginDate(Integer year, Integer month) {
super(year, month);
}
public AreaBeginDate(Integer year, Integer month, Integer day) {
super(year, month, day);
}
}
| 23.9 | 92 | 0.805439 |
89eec02dc735a5078dfe57ab533352ac4ffb4eec | 866 | package frc.robot.utils;
import edu.wpi.first.wpilibj.Compressor;
import org.montclairrobotics.sprocket.loop.Priority;
import org.montclairrobotics.sprocket.loop.Updatable;
import org.montclairrobotics.sprocket.loop.Updater;
import org.montclairrobotics.sprocket.utils.Togglable;
public class PressureRegulator implements Togglable, Updatable {
Compressor c;
private boolean enabled;
public PressureRegulator(Compressor c){
this.c = c;
Updater.add(this, Priority.CONTROL);
}
@Override
public void update() {
if(!c.getPressureSwitchValue() && enabled){
c.setClosedLoopControl(true);
}else{
c.setClosedLoopControl(false);
}
}
@Override
public void enable() {
enabled = true;
}
@Override
public void disable() {
enabled = false;
}
} | 24.742857 | 64 | 0.669746 |
2d344c0d6da19318b6c7850887acf9458887225e | 6,709 | package net.exploitables.slashlib.context;
import discord4j.core.event.domain.interaction.MessageInteractionEvent;
import discord4j.core.object.entity.Guild;
import discord4j.core.object.entity.Member;
import discord4j.core.object.entity.Message;
import discord4j.core.object.entity.User;
import discord4j.core.object.entity.channel.GuildChannel;
import discord4j.core.object.entity.channel.MessageChannel;
import discord4j.core.object.entity.channel.TopLevelGuildChannel;
import reactor.core.publisher.Mono;
/**
* A builder class provided to user commands before the command logic is called.
*/
public class MessageInteractionContextBuilder extends ContextBuilder {
final MessageInteractionEvent event;
Guild guild;
MessageChannel messageChannel;
TopLevelGuildChannel guildChannel;
Message targetMessage;
User messageAuthor;
Member messageAuthorAsMember;
User callingUser;
Member callingUserAsMember;
public MessageInteractionContextBuilder(MessageInteractionEvent event) {
this.event = event;
this.guild = null;
this.messageChannel = null;
this.guildChannel = null;
this.targetMessage = null;
this.messageAuthor = null;
this.messageAuthorAsMember = null;
this.callingUser = null;
this.callingUserAsMember = null;
}
public MessageInteractionContext build() {
return new MessageInteractionContext(this);
}
/**
* Mark that the guild is required for command execution.
* This method will collect the:
* guild
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireGuild() {
requiredMonoList.add(event.getInteraction().getGuild()
.doOnNext(guild -> this.guild = guild)
.map(guild -> 1));
return this;
}
/**
* Mark that the {@link MessageChannel} the command was called in is required for command execution.
* This method will collect the:
* messageChannel
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireMessageChannel() {
requiredMonoList.add(event.getInteraction().getChannel()
.doOnNext(channel -> this.messageChannel = channel)
.map(channel -> 1));
return this;
}
/**
* Mark that the {@link GuildChannel} the command was called in is required for command execution.
* This method will collect the:
* messageChannel
* guildChannel
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireGuildChannel() {
requiredMonoList.add(event.getInteraction().getChannel()
.doOnNext(channel -> this.messageChannel = channel)
.ofType(TopLevelGuildChannel.class)
.doOnNext(channel -> this.guildChannel = channel)
.map(channel -> 1));
return this;
}
/**
* Mark that the {@link Message} the command was called on is required for command execution.
* This method will collect the:
* message
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireMessage() {
requiredMonoList.add(event.getTargetMessage()
.doOnNext(message -> this.targetMessage = message)
.map(member -> 1));
return this;
}
/**
* Mark that the {@link Member} who authored the message this command
* was called on is required for command execution.
* This method will collect the:
* message
* messageAuthor
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireMessageAuthor() {
requiredMonoList.add(event.getTargetMessage()
.doOnNext(message -> this.targetMessage = message)
.flatMap(message -> Mono.justOrEmpty(message.getAuthor()))
.doOnNext(user -> this.messageAuthor = user)
.map(member -> 1));
return this;
}
/**
* Mark that the {@link Member} who authored the message this command
* was called on is required for command execution.
* This method will collect the:
* guild
* message
* messageAuthor
* messageAuthorAsMember
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireMessageAuthorAsMember() {
// As of D4J v3.2.0 message#getAuthorAsMember() will get the guild
requiredMonoList.add(event.getTargetMessage()
.doOnNext(message -> this.targetMessage = message)
.flatMap(message -> message.getGuild()
.doOnNext(guild -> this.guild = guild)
.flatMap(guild -> Mono.justOrEmpty(message.getAuthor())
.doOnNext(author -> this.messageAuthor = author)
.flatMap(author -> guild.getMemberById(author.getId()))
.doOnNext(member -> this.messageAuthorAsMember = member)))
.map(member -> 1));
return this;
}
/**
* Mark that the {@link User} the command was called by is required for command execution.
* This method will collect the:
* callingUser
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireCallingUser() {
requiredMonoList.add(Mono.justOrEmpty(event.getInteraction().getUser())
.doOnNext(user -> this.callingUser = user)
.map(member -> 1));
return this;
}
/**
* Mark that the {@link Member} the command was called by is required for command execution.
* This method will collect the:
* callingUserAsMember
*
* If the data cannot be collected then a {@link DataMissingException} will be thrown.
* @return this instance
*/
public MessageInteractionContextBuilder requireCallingMember() {
requiredMonoList.add(Mono.justOrEmpty(event.getInteraction().getMember())
.doOnNext(member -> this.callingUserAsMember = member)
.map(member -> 1));
return this;
}
}
| 36.661202 | 104 | 0.661201 |
292567339dcea42cc569b1528af9b141f052b3bf | 2,716 | /*
* Copyright (c) 2021 Raffael Herzog
*
* 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 ch.raffael.meldioc.idea.inspections;
import ch.raffael.meldioc.idea.AbstractMeldInspection;
import ch.raffael.meldioc.idea.Context;
import ch.raffael.meldioc.idea.MeldQuickFix;
import ch.raffael.meldioc.model.SrcElement;
import ch.raffael.meldioc.model.config.ModelAnnotationType;
import ch.raffael.meldioc.model.messages.Message;
import com.intellij.codeInsight.intention.AddAnnotationFix;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiType;
import io.vavr.collection.Traversable;
import io.vavr.control.Option;
public final class ConflictingOverrideInspection extends AbstractMeldInspection {
@Override
protected Traversable<Option<? extends LocalQuickFix>> quickFixes(PsiElement element, Message<PsiElement, PsiType> msg, Context inspectionContext) {
return msg.conflicts()
.flatMap(SrcElement::configs)
.distinct()
.map(cnf -> MeldQuickFix.forAnyModifierOwner("Annotate with " + cnf.displayName(), element, msg.element(),
ctx -> {
String[] removable = ModelAnnotationType.all()
.filter(ModelAnnotationType::role)
.map(c -> c.annotationType().getCanonicalName())
.toJavaArray(String[]::new);
new AddAnnotationFix(cnf.type().annotationType().getCanonicalName(), ctx.psi(),
Annotations.annotationFromConfig(cnf, ctx.psi()).getParameterList().getAttributes(), removable)
.invoke(ctx.psi().getProject(), null, null);
}));
}
}
| 46.827586 | 150 | 0.730118 |
9924905bd23c18bf1fe585151f81a42400823a22 | 5,860 | package com.suncreate.pressuresensor.fragment.me;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import com.google.gson.reflect.TypeToken;
import com.suncreate.pressuresensor.AppContext;
import com.suncreate.pressuresensor.R;
import com.suncreate.pressuresensor.base.BaseDetailFragment;
import com.suncreate.pressuresensor.bean.base.ResultBean;
import com.suncreate.pressuresensor.bean.user.Pay;
import com.loopj.android.http.TextHttpResponseHandler;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import butterknife.Bind;
import cz.msebera.android.httpclient.Header;
/**
* 收支明细详情页
*/
public class MyFinancialCenterPaymentDetailDetailFragment extends BaseDetailFragment<Pay> {
//公共部分
@Bind(R.id.tv_in_out_amount)
TextView tv_in_out_amount;
@Bind(R.id.tv_amount)
TextView tv_amount;
@Bind(R.id.tv_type_level_1)
TextView tv_type_level_1;
@Bind(R.id.tv_time)
TextView tv_time;
@Bind(R.id.tv_ord_num)
TextView tv_ord_num;
@Bind(R.id.tv_type_level_2)
TextView tv_type_level_2;
//特殊部分,充值,提现 才显示
// @Bind(R.id.status_box)
// RelativeLayout status_box;
// @Bind(R.id.tv_status)
// TextView tv_status;
// @Bind(R.id.tv_status_text)
// TextView tv_status_text;
// @Bind(R.id.account_box)
// RelativeLayout account_box;
// @Bind(R.id.tv_account)
// TextView tv_account;
// @Bind(R.id.tv_account_text)
// TextView tv_account_text;
//消费标识(0支出 1收入,默认全部)
String mConsumeCost;
//消费编号[订单:order,提现:cash,充值:rech]
String mConsumeSn;
//明细类型(0充值,1提现,2退款,3服务订单费,4工位订单费,5配件订单费,6管理员充值)
String payType;
String amount;
String mAddtime;
@Override
public void initView(View view) {
super.initView(view);
Bundle args = getArguments();
if (args != null) {
mConsumeCost = args.getString("consumeCost");
mConsumeSn = args.getString("consumeSn");
payType = args.getString("payType");
amount = args.getString("amount");
mAddtime = args.getString("addtime");
}
initCommonView();
}
@Override
protected int getLayoutId() {
return R.layout.fragment_my_financial_center_in_out_detail_detail;
}
@Override
protected String getCacheKey() {
return mId + "financialDetailDetail";
}
@Override
protected void sendRequestDataForNet() {
//根据消费编号请求不一样的消费编号[订单:order,提现:cash,充值:rech]
//明细类型(0充值,1提现,2退款,3服务订单费,4工位订单费,5配件订单费,6管理员充值)
// if (mConsumeSn.contains("order")) {
//
// } else if (mConsumeSn.contains("cash")) {
// MonkeyApi.viewWithdrawRecord(mConsumeSn, cashHandler);
// } else if (mConsumeSn.contains("rech")) {
// MonkeyApi.viewRechargeRecord(mConsumeSn, rechHandler);
// }
}
protected TextHttpResponseHandler cashHandler = new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
try {
ResultBean<Pay> resultBean = AppContext.createGson().fromJson(responseString, getType());
if (resultBean != null && resultBean.getCode() == 1) {
Pay mPay = resultBean.getResult();
initWidthdrawDetailView(mPay);
} else {
executeOnLoadDataError();
}
} catch (Exception e) {
onFailure(statusCode, headers, responseString, e);
}
}
};
protected TextHttpResponseHandler rechHandler = new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
}
};
private void initWidthdrawDetailView(Pay mPay) {
if (mPay != null) {
}
}
private void initCommonView() {
if (("1").equals(mConsumeCost)) {
tv_in_out_amount.setText("入账金额");
tv_type_level_1.setText("收入");
} else if (mConsumeCost.equals("0")) {
tv_in_out_amount.setText("出账金额");
tv_type_level_1.setText("支出");
}
if (amount != null) {
tv_amount.setText(amount);
}
if (mAddtime != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long demand_addtimeL = Long.valueOf(mAddtime);
String dateTime = sdf.format(new Date(demand_addtimeL));
tv_time.setText(dateTime);
}
if (mConsumeSn != null) {
tv_ord_num.setText(mConsumeSn);
}
//明细类型(0充值,1提现,2退款,3服务订单费,4工位订单费,5配件订单费)
if (payType != null) {
switch (payType) {
case "0":
tv_type_level_2.setText("充值");
break;
case "1":
tv_type_level_2.setText("提现");
break;
case "2":
tv_type_level_2.setText("退款");
break;
case "3":
tv_type_level_2.setText("服务订单费");
break;
case "4":
tv_type_level_2.setText("工位订单费");
break;
case "5":
tv_type_level_2.setText("配件订单费");
break;
}
}
}
@Override
protected Type getType() {
return new TypeToken<ResultBean<Pay>>() {
}.getType();
}
}
| 30.051282 | 109 | 0.594881 |
28d02fddcc2d19d8c0c09f790867d5cae55318f5 | 11,930 | package opencrypto.test;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Security;
import java.util.Arrays;
import java.util.Random;
import javacard.framework.ISO7816;
import javax.smartcardio.ResponseAPDU;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.interfaces.ECPublicKey;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECParameterSpec;
import org.bouncycastle.math.ec.ECCurve;
import org.bouncycastle.math.ec.ECPoint;
/**
*
* @author Vasilios Mavroudis and Petr Svenda
*/
public class Util {
public static String toHex(byte[] bytes) {
return toHex(bytes, 0, bytes.length);
}
public static String toHex(byte[] bytes, int offset, int len) {
// StringBuilder buff = new StringBuilder();
String result = "";
for (int i = offset; i < offset + len; i++) {
result += String.format("%02X", bytes[i]);
}
return result;
}
public static String bytesToHex(byte[] bytes) {
char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
/* Utils */
public static short getShort(byte[] buffer, int offset) {
return ByteBuffer.wrap(buffer, offset, 2).order(ByteOrder.BIG_ENDIAN).getShort();
}
public static short readShort(byte[] data, int offset) {
return (short) (((data[offset] << 8)) | ((data[offset + 1] & 0xff)));
}
public static byte[] shortToByteArray(int s) {
return new byte[]{(byte) ((s & 0xFF00) >> 8), (byte) (s & 0x00FF)};
}
public static byte[] joinArray(byte[]... arrays) {
int length = 0;
for (byte[] array : arrays) {
length += array.length;
}
final byte[] result = new byte[length];
int offset = 0;
for (byte[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
public static byte[] trimLeadingZeroes(byte[] array) {
short startOffset = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != 0) {
break;
} else {
// still zero
startOffset++;
}
}
byte[] result = new byte[array.length - startOffset];
System.arraycopy(array, startOffset, result, 0, array.length - startOffset);
return result;
}
public static byte[] concat(byte[] a, byte[] b) {
int aLen = a.length;
int bLen = b.length;
byte[] c = new byte[aLen + bLen];
System.arraycopy(a, 0, c, 0, aLen);
System.arraycopy(b, 0, c, aLen, bLen);
return c;
}
public static byte[] concat(byte[] a, byte[] b, byte[] c) {
byte[] tmp_conc = concat(a, b);
return concat(tmp_conc, c);
}
public static ECPoint randECPoint() throws Exception {
Security.addProvider(new BouncyCastleProvider());
ECParameterSpec ecSpec_named = ECNamedCurveTable.getParameterSpec("secp256r1"); // NIST P-256
KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECDSA", "BC");
kpg.initialize(ecSpec_named);
KeyPair apair = kpg.generateKeyPair();
ECPublicKey apub = (ECPublicKey) apair.getPublic();
return apub.getQ();
}
public static byte[] IntToBytes(int val) {
byte[] data = new byte[5];
if (val < 0) {
data[0] = 0x01;
} else {
data[0] = 0x00;
}
int unsigned = Math.abs(val);
data[1] = (byte) (unsigned >>> 24);
data[2] = (byte) (unsigned >>> 16);
data[3] = (byte) (unsigned >>> 8);
data[4] = (byte) unsigned;
return data;
}
public static int BytesToInt(byte[] data) {
int val = (data[1] << 24)
| ((data[2] & 0xFF) << 16)
| ((data[3] & 0xFF) << 8)
| (data[4] & 0xFF);
if (data[0] == 0x01) {
val = val * -1;
}
return val;
}
private static boolean checkSW(ResponseAPDU response) {
if (response.getSW() != (ISO7816.SW_NO_ERROR & 0xffff)) {
System.err.printf("Received error status: %02X.\n",
response.getSW());
return false;
}
return true;
}
public static byte[] hexStringToByteArray(String s) {
String sanitized = s.replace(" ", "");
byte[] b = new byte[sanitized.length() / 2];
for (int i = 0; i < b.length; i++) {
int index = i * 2;
int v = Integer.parseInt(sanitized.substring(index, index + 2), 16);
b[i] = (byte) v;
}
return b;
}
/**
* *Math Stuff**
*/
public static BigInteger randomBigNat(int maxNumBitLength) {
Random rnd = new Random();
BigInteger aRandomBigInt;
while (true) {
do {
aRandomBigInt = new BigInteger(maxNumBitLength, rnd);
} while (aRandomBigInt.compareTo(new BigInteger("1")) < 1);
if ((Util.trimLeadingZeroes(aRandomBigInt.toByteArray()).length != maxNumBitLength / 8) || (aRandomBigInt.toByteArray()).length != maxNumBitLength / 8) {
// After serialization, number is longer or shorter - generate new one
} else {
// We have proper number
return aRandomBigInt;
}
}
}
public static byte[] SerializeBigInteger(BigInteger BigInt) {
int bnlen = BigInt.bitLength() / 8;
byte[] large_int_b = new byte[bnlen];
Arrays.fill(large_int_b, (byte) 0);
int int_len = BigInt.toByteArray().length;
if (int_len == bnlen) {
large_int_b = BigInt.toByteArray();
} else if (int_len > bnlen) {
large_int_b = Arrays.copyOfRange(BigInt.toByteArray(), int_len
- bnlen, int_len);
} else if (int_len < bnlen) {
System.arraycopy(BigInt.toByteArray(), 0, large_int_b,
large_int_b.length - int_len, int_len);
}
return large_int_b;
}
public static long pow_mod(long x, long n, long p) {
if (n == 0) {
return 1;
}
if ((n & 1) == 1) {
return (pow_mod(x, n - 1, p) * x) % p;
}
x = pow_mod(x, n / 2, p);
return (x * x) % p;
}
/* Takes as input an odd prime p and n < p and returns r
* such that r * r = n [mod p]. */
public static BigInteger tonelli_shanks(BigInteger n, BigInteger p) {
//1. By factoring out powers of 2, find Q and S such that p-1=Q2^S p-1=Q*2^S and Q is odd
BigInteger p_1 = p.subtract(BigInteger.ONE);
BigInteger S = BigInteger.ZERO;
BigInteger Q = p_1;
BigInteger two = BigInteger.valueOf(2);
while (Q.mod(two).compareTo(BigInteger.ONE) != 0) { //while Q is not odd
Q = Q.divide(two);
//Q = p_1.divide(two.modPow(S, p));
S = S.add(BigInteger.ONE);
}
//2. Find the first quadratic non-residue z by brute-force search
BigInteger z = BigInteger.ONE;
while (z.modPow(p_1.divide(BigInteger.valueOf(2)), p).compareTo(p_1) != 0) {
z = z.add(BigInteger.ONE);
}
System.out.println("n (y^2) : " + Util.bytesToHex(n.toByteArray()));
System.out.println("Q : " + Util.bytesToHex(Q.toByteArray()));
System.out.println("S : " + Util.bytesToHex(S.toByteArray()));
BigInteger R = n.modPow(Q.add(BigInteger.ONE).divide(BigInteger.valueOf(2)), p);
BigInteger c = z.modPow(Q, p);
BigInteger t = n.modPow(Q, p);
BigInteger M = S;
while (t.compareTo(BigInteger.ONE) != 0) {
BigInteger tt = t;
BigInteger i = BigInteger.ZERO;
while (tt.compareTo(BigInteger.ONE) != 0) {
System.out.println("t : " + tt.toString());
tt = tt.multiply(tt).mod(p);
i = i.add(BigInteger.ONE);
//if (i.compareTo(m)==0) return BigInteger.ZERO;
}
BigInteger M_i_1 = M.subtract(i).subtract(BigInteger.ONE);
System.out.println("M : " + M.toString());
System.out.println("i : " + i.toString());
System.out.println("M_i_1: " + M_i_1.toString());
System.out.println("===================");
BigInteger b = c.modPow(two.modPow(M_i_1, p_1), p);
BigInteger b2 = b.multiply(b).mod(p);
R = R.multiply(b).mod(p);
c = b2;
t = t.multiply(b2).mod(p);
M = i;
}
if (R.multiply(R).mod(p).compareTo(n) == 0) {
return R;
} else {
return BigInteger.ZERO;
}
}
/* Takes as input an odd prime p and n < p and returns r
* such that r * r = n [mod p]. */
public static BigInteger tonellishanks(BigInteger n, BigInteger p) {
//1. By factoring out powers of 2, find Q and S such that p-1=Q2^S p-1=Q*2^S and Q is odd
BigInteger p_1 = p.subtract(BigInteger.ONE);
BigInteger S = BigInteger.ZERO;
BigInteger Q = p_1;
BigInteger two = BigInteger.valueOf(2);
System.out.println("p : " + Util.bytesToHex(p.toByteArray()));
System.out.println("p is prime: " + p.isProbablePrime(10));
System.out.println("n : " + Util.bytesToHex(n.toByteArray()));
System.out.println("Q : " + Util.bytesToHex(Q.toByteArray()));
System.out.println("S : " + Util.bytesToHex(S.toByteArray()));
while (Q.mod(two).compareTo(BigInteger.ONE) != 0) { //while Q is not odd
Q = p_1.divide(two.modPow(S, p));
S = S.add(BigInteger.ONE);
//System.out.println("Iter n: " + bytesToHex(n.toByteArray()));
//System.out.println("Iter Q: " + bytesToHex(Q.toByteArray()));
//System.out.println("Iter S: " + bytesToHex(S.toByteArray()));
}
//System.out.println("n: " + bytesToHex(n.toByteArray()));
//System.out.println("Q: " + bytesToHex(Q.toByteArray()));
//System.out.println("S: " + bytesToHex(S.toByteArray()));
return n;
}
private static ECPoint ECPointDeSerialization(byte[] serialized_point,
int offset, int pointLength, ECCurve curve) {
byte[] x_b = new byte[pointLength / 2];
byte[] y_b = new byte[pointLength / 2];
// System.out.println("Serialized Point: " + toHex(serialized_point));
// src -- This is the source array.
// srcPos -- This is the starting position in the source array.
// dest -- This is the destination array.
// destPos -- This is the starting position in the destination data.
// length -- This is the number of array elements to be copied.
System.arraycopy(serialized_point, offset + 1, x_b, 0, pointLength / 2);
BigInteger x = new BigInteger(bytesToHex(x_b), 16);
// System.out.println("X:" + toHex(x_b));
System.arraycopy(serialized_point, offset + (pointLength / 2 + 1), y_b, 0, pointLength / 2);
BigInteger y = new BigInteger(bytesToHex(y_b), 16);
// System.out.println("Y:" + toHex(y_b));
ECPoint point = curve.createPoint(x, y);
return point;
}
}
| 34.183381 | 165 | 0.549288 |
c5c9bbdd30f0b152ece56f13a086c5468c695ae3 | 289 | package scratch.UCERF3.logicTree;
import java.util.List;
public class LogicalOrTrimmer extends LogicalAndOrTrimmer {
public LogicalOrTrimmer(List<TreeTrimmer> trimmers) {
super(false, trimmers);
}
public LogicalOrTrimmer(TreeTrimmer... trimmers) {
super(false, trimmers);
}
}
| 18.0625 | 59 | 0.768166 |
164f62b2a652e40e720005e2c56ce1d50178a344 | 2,990 | package idv.const_x.tools.coder.generator.view.field;
import java.util.HashMap;
import java.util.Map;
import idv.const_x.file.PlaceHodler;
import idv.const_x.tools.coder.generator.Field;
import idv.const_x.tools.coder.generator.view.ViewContext;
public class RichTextFieldGenerator extends AbsFieldGenerator{
@Override
public void init(ViewContext context, Field field) {
StringBuilder create = new StringBuilder();
create.append(" <div style='padding:0 10px;'>\n <p style='-webkit-margin-before: 2px;'>\n <label style='width:90px;text-align:right;vertical-align:top;display:inline-block;'>").append(field.getAlias()).append(":</label>\n");
create.append(" <textarea style='margin:0px;height:290px;width:630px;border-radius:4px 4px 4px 4px;border:1px solid #ddd;' name=\"").append(field.getName()).append("\" id=\"").append(field.getName()).append("\" ></textarea>\n");
if(!field.isNullable()){
create.append(" <span class='starL'></span>\n");
}
create.append(" </p>\n </div>\n");
this.createFieldElements = create.toString();
create = new StringBuilder();
String entry = context.getBaseContext().getEntity().toLowerCase();
create.append(" <div style='padding:0 10px;'>\n <p style='-webkit-margin-before: 2px;'>\n <label style='width:90px;text-align:right;vertical-align:top;display:inline-block;'>").append(field.getAlias()).append(":</label>\n");
create.append(" <textarea style='margin:0px;height:290px;width:630px;border-radius:4px 4px 4px 4px;border:1px solid #ddd;' name=\"").append(field.getName()).append("\" id=\"").append(field.getName()).append("\" \n");
create.append(" >${").append(entry).append(".").append(field.getName()).append("}</textarea>\n");
if(!field.isNullable()){
create.append(" <span class='starL'></span>\n");
}
create.append(" </p>\n </div>\n");
this.updateFieldElements = create.toString();
StringBuilder scripts = new StringBuilder();
String temp = "xheditor.tmp";
PlaceHodler hodler = new PlaceHodler();
Map<String, String> properties = new HashMap<String, String>();
properties.put("module", context.getBaseContext().getModule().toLowerCase());
properties.put("field",field.getName());
scripts.append(hodler.hodle(context.getTempBase() + temp,properties)).append("\n");
super.createExpandScripts = scripts.toString();
super.updateExpandScripts = createExpandScripts;
if(!field.isNullable()){
StringBuilder validate = new StringBuilder();
validate.append(" if(!($(\"#").append(field.getName()).append("\").val())){\n");
validate.append(" $.messager.alert('错误', '").append(field.getAlias()).append("不能为空', 'error');\n");
validate.append(" return false;\n");
validate.append(" }\n");
super.createValdiatesBeforeSubmit = validate.toString();
super.updateValdiatesBeforeSubmit = validate.toString();
}
}
}
| 48.225806 | 240 | 0.66388 |
054e2ca6d7d95eebc1320be92f5d0401ac01c397 | 359 | package com.milchstrabe.rainbow.tcp.service;
import com.milchstrabe.rainbow.exception.AuthException;
import com.milchstrabe.rainbow.server.domain.ClientType;
import com.milchstrabe.rainbow.tcp.typ3.netty.session.Session;
public interface ISignInService {
void signIn(String token, String cid, ClientType cType, Session session) throws AuthException;
}
| 32.636364 | 98 | 0.824513 |
5afbf4f3bb7a6731a933db38e2d1a5f8a7c4cc5c | 454 | package cn.gson.oasys.mapper;
import cn.gson.oasys.mappers.DiscussListPOMapper;
import lombok.extern.slf4j.Slf4j;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
@SpringBootTest
@RunWith(SpringRunner.class)
@Slf4j
public class SortTest {
@Resource
private DiscussListPOMapper discussListPOMapper;
}
| 21.619048 | 60 | 0.819383 |
02df542b52bed52bcfa858e69d072afeae7ac3f1 | 8,571 | package com.storycraft.core.player.home;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import com.storycraft.StoryPlugin;
import com.storycraft.command.ICommand;
import com.storycraft.config.json.JsonConfigEntry;
import com.storycraft.config.json.JsonConfigFile;
import com.storycraft.StoryMiniPlugin;
import com.storycraft.core.rank.ServerRank;
import com.storycraft.util.MessageUtil;
import org.bukkit.Location;
import org.bukkit.OfflinePlayer;
import org.bukkit.block.data.type.Bed;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
public class HomeManager extends StoryMiniPlugin implements Listener {
private JsonConfigFile homeConfigFile;
@Override
public void onLoad(StoryPlugin plugin) {
try {
plugin.getConfigManager().addConfigFile("home.json", homeConfigFile = new JsonConfigFile()).getSync();
} catch (Throwable e) {
e.printStackTrace();
}
plugin.getCommandManager().addCommand(new HomeCommand());
plugin.getCommandManager().addCommand(new SetHomeCommand());
}
@Override
public void onEnable() {
getPlugin().getServer().getPluginManager().registerEvents(this, getPlugin());
}
public void setPlayerHome(Player player, Location location) {
setRespawnLocation(player, location);
player.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.SUCCESS, "HomeManager", "집 위치가 " + location.getWorld().getName() + " " + (Math.floor(location.getX() * 10) / 10) + " " + (Math.floor(location.getY() * 10) / 10) + " " + (Math.floor(location.getZ() * 10) / 10) + " 로 지정되었습니다."));
}
public int getTeleportCoolTime() {
JsonConfigEntry entry = getOptionEntry();
try {
return entry.get("cooltime").getAsInt();
} catch (Exception e) {
setTeleportCoolTime(60000);
return 60000;
}
}
public void setTeleportCoolTime(int coolTime) {
JsonConfigEntry entry = getOptionEntry();
entry.set("cooltime", coolTime);
}
@EventHandler
public void onRespawn(PlayerRespawnEvent e) {
Location respawnLocation = getRespawnLocation(e.getPlayer());
if (respawnLocation != null)
e.setRespawnLocation(respawnLocation);
}
public Location getRespawnLocation(OfflinePlayer p) {
JsonConfigEntry entry;
if (!homeConfigFile.contains(p.getUniqueId().toString()) || (entry = homeConfigFile.getObject(p.getUniqueId().toString())) == null)
return null;
try {
return new Location(getPlugin().getServer().getWorld(entry.get("world").getAsString()), entry.get("x").getAsDouble(), entry.get("y").getAsDouble(), entry.get("z").getAsDouble(), entry.get("yaw").getAsFloat(), entry.get("pitch").getAsFloat());
} catch (Exception e) {
return null;
}
}
public void setRespawnLocation(Player p, Location location) {
p.setBedSpawnLocation(location);
JsonConfigEntry entry = new JsonConfigEntry();
entry.set("world", location.getWorld().getName());
entry.set("x", location.getX());
entry.set("y", location.getY());
entry.set("z", location.getZ());
entry.set("yaw", location.getYaw());
entry.set("pitch", location.getPitch());
homeConfigFile.set(p.getUniqueId().toString(), entry);
}
public JsonConfigEntry getOptionEntry() {
JsonConfigEntry entry = homeConfigFile.getObject("options");
if (entry == null) {
homeConfigFile.set("options", entry = homeConfigFile.createEntry());
}
return entry;
}
public class HomeCommand implements ICommand {
private Map<UUID, Long> timeMap;
public HomeCommand() {
this.timeMap = new HashMap<>();
}
@Override
public String[] getAliases() {
return new String[]{ "home" };
}
@Override
public void onCommand(CommandSender sender, String[] args) {
Player p = (Player) sender;
if (getPlugin().getCoreManager().getRankManager().hasPermission(p, ServerRank.MOD) && args.length > 0){
String targetPlayer = args[0];
OfflinePlayer pl = getPlugin().getServer().getOfflinePlayer(targetPlayer);
if (pl == null) {
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.FAIL, "HomeManager", "플레이어 " + targetPlayer + " 을(를) 찾을 수 없습니다"));
}
else {
Location location = getRespawnLocation(pl);
if (location == null) {
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.FAIL, "HomeManager", "플레이어 " + targetPlayer + " 의 집이 설정되어있지 않습니다"));
return;
}
p.teleport(location);
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.SUCCESS, "HomeManager", targetPlayer + " 의 집으로 이동되었습니다"));
}
}
else {
Location location = getRespawnLocation(p);
if (location == null) {
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.FAIL, "HomeManager", "집 위치가 지정되어 있지 않습니다. /sethome을 사용해 지정후 사용해 주세요"));
return;
}
if (isCoolTimeDone(p) || getPlugin().getCoreManager().getRankManager().hasPermission(p, ServerRank.MOD)) {
p.teleport(location);
timeMap.put(p.getUniqueId(), System.currentTimeMillis());
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.SUCCESS, "HomeManager", "집으로 이동되었습니다"));
}
else {
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.FAIL, "HomeManager", "다음 커맨드 사용까지 " + Math.ceil((getTeleportCoolTime() - (System.currentTimeMillis() - getLastTeleport(p))) / 1000) + " 초 더 기다려야 합니다"));
}
}
}
protected void updateLastTeleport(Player p) {
if (timeMap.containsKey(p.getUniqueId()))
timeMap.replace(p.getUniqueId(), System.currentTimeMillis());
else
timeMap.put(p.getUniqueId(), System.currentTimeMillis());
}
protected long getLastTeleport(Player p) {
if (!timeMap.containsKey(p.getUniqueId()))
return 0;
else
return timeMap.get(p.getUniqueId());
}
protected boolean isCoolTimeDone(Player p) {
return System.currentTimeMillis() - getLastTeleport(p) >= getTeleportCoolTime();
}
@Override
public boolean availableOnConsole() {
return false;
}
@Override
public boolean availableOnCommandBlock() {
return false;
}
@Override
public boolean isPermissionRequired() {
return true;
}
@Override
public String getPermissionRequired() {
return "server.command.home";
}
}
public class SetHomeCommand implements ICommand {
@Override
public String[] getAliases() {
return new String[]{ "sethome" };
}
@Override
public void onCommand(CommandSender sender, String[] args) {
Player p = (Player) sender;
Location location = p.getLocation();
if (args.length > 0) {
p.sendMessage(MessageUtil.getPluginMessage(MessageUtil.MessageType.FAIL, "HomeManager", "집은 한개만 설정가능합니다"));
return;
}
setPlayerHome(p, location);
}
@Override
public boolean availableOnConsole() {
return false;
}
@Override
public boolean availableOnCommandBlock() {
return false;
}
@Override
public boolean isPermissionRequired() {
return true;
}
@Override
public String getPermissionRequired() {
return "server.command.sethome";
}
}
}
| 34.011905 | 307 | 0.601447 |
56a7d005ec62aa0ce04b3e86aa357aab1468eecc | 4,905 | package net.minecraft.util;
import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.security.*;
import org.apache.logging.log4j.*;
public class CryptManager
{
private static final Logger LOGGER;
public static SecretKey createNewSharedKey() {
try {
final KeyGenerator keygenerator = KeyGenerator.getInstance("AES");
keygenerator.init(128);
return keygenerator.generateKey();
}
catch (NoSuchAlgorithmException nosuchalgorithmexception) {
throw new Error(nosuchalgorithmexception);
}
}
public static KeyPair generateKeyPair() {
try {
final KeyPairGenerator keypairgenerator = KeyPairGenerator.getInstance("RSA");
keypairgenerator.initialize(1024);
return keypairgenerator.generateKeyPair();
}
catch (NoSuchAlgorithmException nosuchalgorithmexception) {
nosuchalgorithmexception.printStackTrace();
CryptManager.LOGGER.error("Key pair generation failed!");
return null;
}
}
public static byte[] getServerIdHash(final String serverId, final PublicKey publicKey, final SecretKey secretKey) {
try {
return digestOperation("SHA-1", new byte[][] { serverId.getBytes("ISO_8859_1"), secretKey.getEncoded(), publicKey.getEncoded() });
}
catch (UnsupportedEncodingException unsupportedencodingexception) {
unsupportedencodingexception.printStackTrace();
return null;
}
}
private static byte[] digestOperation(final String algorithm, final byte[]... data) {
try {
final MessageDigest messagedigest = MessageDigest.getInstance(algorithm);
for (final byte[] abyte : data) {
messagedigest.update(abyte);
}
return messagedigest.digest();
}
catch (NoSuchAlgorithmException nosuchalgorithmexception) {
nosuchalgorithmexception.printStackTrace();
return null;
}
}
public static PublicKey decodePublicKey(final byte[] encodedKey) {
try {
final EncodedKeySpec encodedkeyspec = new X509EncodedKeySpec(encodedKey);
final KeyFactory keyfactory = KeyFactory.getInstance("RSA");
return keyfactory.generatePublic(encodedkeyspec);
}
catch (NoSuchAlgorithmException ex) {}
catch (InvalidKeySpecException ex2) {}
CryptManager.LOGGER.error("Public key reconstitute failed!");
return null;
}
public static SecretKey decryptSharedKey(final PrivateKey key, final byte[] secretKeyEncrypted) {
return new SecretKeySpec(decryptData(key, secretKeyEncrypted), "AES");
}
public static byte[] encryptData(final Key key, final byte[] data) {
return cipherOperation(1, key, data);
}
public static byte[] decryptData(final Key key, final byte[] data) {
return cipherOperation(2, key, data);
}
private static byte[] cipherOperation(final int opMode, final Key key, final byte[] data) {
try {
return createTheCipherInstance(opMode, key.getAlgorithm(), key).doFinal(data);
}
catch (IllegalBlockSizeException illegalblocksizeexception) {
illegalblocksizeexception.printStackTrace();
}
catch (BadPaddingException badpaddingexception) {
badpaddingexception.printStackTrace();
}
CryptManager.LOGGER.error("Cipher data failed!");
return null;
}
private static Cipher createTheCipherInstance(final int opMode, final String transformation, final Key key) {
try {
final Cipher cipher = Cipher.getInstance(transformation);
cipher.init(opMode, key);
return cipher;
}
catch (InvalidKeyException invalidkeyexception) {
invalidkeyexception.printStackTrace();
}
catch (NoSuchAlgorithmException nosuchalgorithmexception) {
nosuchalgorithmexception.printStackTrace();
}
catch (NoSuchPaddingException nosuchpaddingexception) {
nosuchpaddingexception.printStackTrace();
}
CryptManager.LOGGER.error("Cipher creation failed!");
return null;
}
public static Cipher createNetCipherInstance(final int opMode, final Key key) {
try {
final Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding");
cipher.init(opMode, key, new IvParameterSpec(key.getEncoded()));
return cipher;
}
catch (GeneralSecurityException generalsecurityexception) {
throw new RuntimeException(generalsecurityexception);
}
}
static {
LOGGER = LogManager.getLogger();
}
}
| 36.604478 | 142 | 0.641998 |
caa80005b5d66239c6ac040f7be9ae251415ecff | 1,845 | /*
* Copyright 2019 ConsenSys AG.
*
* 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 tech.pegasys.pantheon.ethereum.graphql.internal.methods;
import tech.pegasys.pantheon.ethereum.core.Address;
import tech.pegasys.pantheon.ethereum.core.Wei;
import tech.pegasys.pantheon.ethereum.graphql.internal.queries.BlockchainQueries;
import tech.pegasys.pantheon.ethereum.graphql.internal.results.Account;
import tech.pegasys.pantheon.util.bytes.BytesValue;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
public class BlockMinerFetcher implements DataFetcher<Account> {
private final BlockchainQueries blockchain;
public BlockMinerFetcher(final BlockchainQueries blockchain) {
this.blockchain = blockchain;
}
@Override
public Account get(final DataFetchingEnvironment environment) throws Exception {
long blockNumber = environment.getArgument("block");
Address address =
blockchain
.getBlockHeaderByNumber(blockNumber)
.map(header -> header.getCoinbase())
.orElse(null);
return new Account(
address,
blockchain.accountBalance(address, blockNumber).map(balance -> balance).orElse(Wei.ZERO),
blockchain.accountNonce(address, blockNumber).map(count -> count.longValue()).orElse(0L),
BytesValue.EMPTY);
}
}
| 39.255319 | 118 | 0.757182 |
44394df01a229f18ea2aa6ae21fd03ce15ba877b | 216 | package com.rpa.rpaplatform;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class RpaplatformApplicationTests {
@Test
void contextLoads() {
}
}
| 15.428571 | 60 | 0.791667 |
7e381de61cea6d93721e8271f407f30d46fe5ef0 | 5,627 | /*
* 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.kaishustory.id.random.plan.cache;
import com.kaishustory.id.common.constants.IdConstants;
import com.kaishustory.id.common.model.ISegment;
import com.kaishustory.id.common.service.ILoadSegment;
import com.kaishustory.id.random.plan.model.Plan;
import com.kaishustory.id.random.plan.utils.PlanAlgorithm;
import com.kaishustory.id.sequence.segment.cache.SegmentCache;
import com.kaishustory.id.sequence.segment.model.SegmentDefine;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 随机规划ID缓存管理
*
* @author liguoyang
* @create 2019-05-16 10:45
**/
@Component
public class PlanCache extends SegmentCache {
/**
* Redis
*/
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 规划算法全局锁
*/
private final String PLAN_LOCK = "ID:PLAN:LOCK:{TAG}";
/**
* 规划算法本地锁
*/
private Lock planLocalLock = new ReentrantLock();
/**
* 加载ID分片
* @param tag 业务标签
* @return
*/
@Override
public void loadSegment(String tag){
// 加载分片ID
loadSegment(IdConstants.TYPE_PLAN, tag, new ILoadSegment() {
/**
* 初始化
* @param tag 业务标签
*/
@Override
public void init(String tag) {
// 获得全局锁
planLock(tag);
}
/**
* 保存默认ID定义
* @param tag ID定义
* @return
*/
@Override
public SegmentDefine saveDefaultDefine(String tag) {
SegmentDefine define = new SegmentDefine();
define.setTag(tag);
define.setType(IdConstants.TYPE_PLAN);
define.setStep(1000);
define.setMaxNum(100000000L*5);
define.setDayReset(false);
saveDefine(define);
return define;
}
/**
* 获得最大ID
* @param define ID定义
* @param date 日期
* @return 最大ID
*/
@Override
public Long getMaxId(SegmentDefine define, String date) {
return define.getMaxId();
}
/**
* 创建新分片
* @param define ID定义
* @param date 日期
* @param maxId 最大ID
* @return 新分片
*/
@Override
public ISegment createSegment(SegmentDefine define, String date, Long maxId) {
Plan plan = new Plan();
// 生成ID列表
plan.getCurr().addAll(genID(define.getMaxNum(), define.getMaxId(), define.getStep()));
// 设置有效日期
plan.setEffectiveTime(date);
return plan;
}
/**
* 更新ID定义
* @param define ID定义
* @param segment 新生村分片
* @return ID定义
*/
@Override
public SegmentDefine updateDefine(SegmentDefine define, ISegment segment) {
// 更新最大主键
define.setMaxId(segment.getMax());
// 更新时间
define.setUpdateTime(new Date());
return define;
}
/**
* 销毁
* @param tag 业务标签
*/
@Override
public void destroy(String tag) {
// 解除全局锁
planUnlock(tag);
}
});
}
/**
* 生成ID列表
* @param maxNum 最大数量
* @param maxId 当前最大ID
* @param num 生成ID数量
* @return 新生成ID列表
*/
private List<Long> genID(Long maxNum, Long maxId, int num){
PlanAlgorithm planAlgorithm = new PlanAlgorithm(maxNum);
List<Long> ids = new ArrayList<>();
Long last = maxId;
for (int i = 0; i < num; i++) {
last = planAlgorithm.get(last);
ids.add(last);
}
return ids;
}
/**
* 获得规划算法全局锁
* @param tag 业务标签
*/
private void planLock(String tag) {
// 获得本地锁
planLocalLock.lock();
// 尝试全局锁
while (redisTemplate.opsForValue().increment(PLAN_LOCK.replace("{TAG}", tag),1) != 1) {
try {
// 获得锁失败时,等待150毫秒后重试
Thread.sleep(150);
}catch (Exception e) {
e.printStackTrace();
}
}
// 设置锁时间1分钟
redisTemplate.expire(PLAN_LOCK.replace("{TAG}", tag), 1, TimeUnit.MINUTES);
}
/**
* 解除规划算法全局锁
* @param tag 业务标签
*/
private void planUnlock(String tag) {
// 解除全局锁
redisTemplate.delete(PLAN_LOCK.replace("{TAG}", tag));
// 解除本地锁
planLocalLock.unlock();
}
}
| 27.052885 | 102 | 0.54203 |
2459cea5257e0a3c45c1abbbdd5adf546ca19ec6 | 8,245 | /*
Copyright (c) 2000-2015 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.
*/
package org.lockss.plugin.metapress;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lockss.config.ConfigManager;
import org.lockss.config.Configuration;
import org.lockss.extractor.ArticleMetadataExtractor;
import org.lockss.extractor.FileMetadataExtractor;
import org.lockss.extractor.MetadataTarget;
import org.lockss.plugin.*;
import org.lockss.plugin.simulated.SimulatedArchivalUnit;
import org.lockss.plugin.simulated.SimulatedContentGenerator;
import org.lockss.test.*;
import org.lockss.util.*;
public class TestMetapressArticleIteratorFactory extends ArticleIteratorTestCase {
private SimulatedArchivalUnit sau; // Simulated AU to generate content
private final String PLUGIN_NAME = "org.lockss.plugin.metapress.ClockssMetaPressPlugin";
private final String BASE_URL = "http://uksg.metapress.com/";
private static final int DEFAULT_FILESIZE = 3000;
private final String EXPECTED_PDF_URL = "http://uksg.metapress.com/content/823xp7lgublqah49/fulltext.pdf";
private final String EXPECTED_FULL_TEXT_HTML_URL = "http://uksg.metapress.com/content/823xp7lgublqah49/fulltext.html";
private final String EXPECTED_CITATION_RIS_URL = "http://uksg.metapress.com/export.mpx?code=823XP7LGUBLQAH49&mode=ris";
private final String EXPECTED_FULL_TEXT_URL = EXPECTED_PDF_URL;
protected String cuRole = null;
ArticleMetadataExtractor.Emitter emitter;
protected boolean emitDefaultIfNone = false;
FileMetadataExtractor me = null;
MetadataTarget target;
@Override
public void setUp() throws Exception {
super.setUp();
String tempDirPath = setUpDiskSpace();
au = createAu();
sau = PluginTestUtil.createAndStartSimAu(simAuConfig(tempDirPath));
}
@Override
public void tearDown() throws Exception {
sau.deleteContentTree();
super.tearDown();
}
protected ArchivalUnit createAu() throws ArchivalUnit.ConfigurationException {
return
PluginTestUtil.createAndStartAu(PLUGIN_NAME,
ConfigurationUtil.fromArgs("base_url",
"http://uksg.metapress.com/",
"volume_name", "5",
"journal_issn", "0953-0460"));
}
Configuration simAuConfig(String rootPath) {
Configuration conf = ConfigManager.newConfiguration();
conf.put("root", rootPath);
conf.put("base_url", "http://uksg.metapress.com/");
conf.put("depth", "1");
conf.put("branch", "4");
conf.put("numFiles", "7");
conf.put("fileTypes",
"" + (SimulatedContentGenerator.FILE_TYPE_PDF)
+ (SimulatedContentGenerator.FILE_TYPE_HTML)
+ (SimulatedContentGenerator.FILE_TYPE_TXT) );
conf.put("binFileSize", "" + DEFAULT_FILESIZE);
return conf;
}
Configuration metapressAuConfig() {
return ConfigurationUtil.fromArgs("base_url",
"http://uksg.metapress.com/",
"volume_name", "5",
"journal_issn", "0953-0460");
}
public void testRoots() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
assertEquals(ListUtil.list("http://uksg.metapress.com/content"),
getRootUrls(artIter));
}
public void testUrlsWithPrefixes() throws Exception {
SubTreeArticleIterator artIter = createSubTreeIter();
Pattern pat = getPattern(artIter);
assertNotMatchesRE(pat, "http://uksg.metapress.com/contentt/823xp7lgublqah49/j0143.pdfwrong");
assertNotMatchesRE(pat, "http://uksg.metapress.com/contentt/volume/823xp7lgublqah49/j0143.pdfwrong");
assertMatchesRE(pat, "http://uksg.metapress.com/content/823xp7lgublqah49/fulltext.pdf");
assertNotMatchesRE(pat, "http://www.example.com/content/");
assertNotMatchesRE(pat, "http://www.example.com/content/j");
assertNotMatchesRE(pat, "http://www.example.com/content/j0123/j383.pdfwrong");
}
public void testCitationRis() throws Exception {
Pattern PATTERN = Pattern.compile("/content/([a-z0-9]{16})/fulltext\\.pdf$", Pattern.CASE_INSENSITIVE);
String pdfUrl = "http://uksg.metapress.com/content/823xp7lgublqah49/fulltext.pdf";
Matcher mat = PATTERN.matcher(pdfUrl);
assertTrue(mat.find());
// convert 'code' tp upper case.
// citation ris: http://uksg.metapress.com/export.mpx?code=823XP7LGUBLQAH49&mode=ris";
String citStr = mat.replaceFirst(String.format("/export.mpx?code=%s&mode=ris", mat.group(1).toUpperCase()));
log.info("citStr: " + citStr);
assertEquals(EXPECTED_CITATION_RIS_URL, citStr);
}
public void testCreateArticleFiles() throws Exception {
PluginTestUtil.crawlSimAu(sau);
// create urls to store in UrlCacher
String[] urls = { BASE_URL + "content/823xp7lgublqah49/fulltext.pdf",
BASE_URL + "content/823xp7lgublqah49/fulltext.html",
BASE_URL + "export.mpx?code=823XP7LGUBLQAH49&mode=ris" };
// get cached url content type and properties from simulated contents
// for UrclCacher.storeContent()
CachedUrl cuPdf = null;
CachedUrl cuHtml = null;
for (CachedUrl cu : AuUtil.getCuIterable(sau)) {
if (cuPdf == null
&& cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_PDF)) {
//log.info("pdf contenttype: " + cu.getContentType());
cuPdf = cu;
} else if (cuHtml == null
&& cu.getContentType().toLowerCase().startsWith(Constants.MIME_TYPE_HTML)) {
//log.info("html contenttype: " + cu.getContentType());
cuHtml = cu;
}
if (cuPdf != null && cuHtml != null) {
break;
}
}
// store content using cached url content type and properties
for (String url : urls) {
//log.info("url: " + url);
if (url.contains("full")) {
storeContent(cuHtml.getUnfilteredInputStream(),
cuHtml.getProperties(), url);
} else if (url.contains("pdf")) {
storeContent(cuPdf.getUnfilteredInputStream(),
cuPdf.getProperties(), url);
}
}
// get article iterator, get article files and the appropriate urls according
// to their roles.
String [] expectedUrls = { EXPECTED_PDF_URL,
EXPECTED_FULL_TEXT_URL,
EXPECTED_FULL_TEXT_HTML_URL };
for (SubTreeArticleIterator artIter = createSubTreeIter(); artIter.hasNext(); ) {
ArticleFiles af = artIter.next();
String[] actualUrls = { af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_PDF),
af.getFullTextUrl(),
af.getRoleUrl(ArticleFiles.ROLE_FULL_TEXT_HTML), };
//log.info("actualUrls: " + actualUrls.length);
for (int i = 0;i< actualUrls.length; i++) {
//log.info("expected url: " + expectedUrls[i]);
//log.info(" actual url: " + actualUrls[i]);
assertEquals(expectedUrls[i], actualUrls[i]);
}
}
}
}
| 41.432161 | 121 | 0.69812 |
8ecf03ed48fdf648f1b69b84f6c7eec480f427ce | 164 | import java.util.List;
public class SingleCommand {
String cmd;
List<String> args;
public SingleCommand(String c, List<String> ar){
cmd = c;
args = ar;
}
} | 16.4 | 49 | 0.689024 |
073f2f41e8081f92c622f4419cc5bc3023519796 | 1,130 | /*
* Copyright 2015-16, Yahoo! Inc.
* Licensed under the terms of the Apache License 2.0. See LICENSE file at the project root for terms.
*/
package com.yahoo.sketches;
import com.yahoo.memory.Memory;
/**
* Base class for serializing and deserializing custom types.
* @param <T> Type of item
*
* @author Alexander Saydakov
*/
public abstract class ArrayOfItemsSerDe<T> {
/**
* Serialize an array of items to byte array.
* The size of the array doesn't need to be serialized.
* This method is called by the sketch serialization process.
*
* @param items array of items to be serialized
* @return serialized representation of the given array of items
*/
public abstract byte[] serializeToByteArray(T[] items);
/**
* Deserialize an array of items from a given Memory object.
* This method is called by the sketch deserialization process.
*
* @param mem Memory containing a serialized array of items
* @param numItems number of items in the serialized array
* @return deserialized array of items
*/
public abstract T[] deserializeFromMemory(Memory mem, int numItems);
}
| 28.974359 | 102 | 0.716814 |
b632213f487015b2298ea28e8acae8e17381fe12 | 1,083 | package controller;
import dao.getTableNamesDAO;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.List;
/**
* Controller for tableHandler
* this class generates a JSON Array of all tables in the targetdatabase
*/
public class TableJsonCreator {
/**
* declaration of the DAO class which handles getting tablenames from the target database
*/
getTableNamesDAO gtdao = new getTableNamesDAO();
/**
* method that generates a JSON Array which contains all tablenames
*
* @return JSONArray of all tables
*/
public String convertToJSON(){
//initialization
String baseString ="";
List<String> tables =gtdao.getTableNames();
//can only iterate 1 thing so an extra iterator to keep track
try{
for (String t: tables){
baseString += t + ";";
}}
catch (Exception exc){
}
baseString = baseString.substring(0,baseString.length()-1);
return baseString;
}
}
| 22.102041 | 93 | 0.626039 |
759f19e84ab62383ba90c9b5dc78e59145c383bf | 871 | package ru.job4j.dao;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* @author Hincu Andrei (andreih1981@gmail.com)on 16.03.2018.
* @version $Id$.
* @since 0.1.
*/
public class HibernateService {
//
// private static final SessionFactory SESSION_FACTORY;
// static {
// try {
// Configuration configuration = new Configuration();
// configuration.configure();
//
// SESSION_FACTORY = configuration.buildSessionFactory();
// } catch (Throwable ex) {
// throw new ExceptionInInitializerError(ex);
// }
// }
// public static SessionFactory getSessionFactory() throws HibernateException {
// return SESSION_FACTORY;
// }
// public static void closeFactory() {
// SESSION_FACTORY.close();
// }
} | 28.096774 | 82 | 0.647532 |
25b6f9d4e2e334fddbfef9d93cb3cf68c7d20726 | 1,628 | package com.github.polyang.istudy.framework.starter.session.manager.impl;
import com.github.polyang.istudy.framework.starter.session.generator.MicroSessionIdGenerator;
import com.github.polyang.istudy.framework.starter.session.generator.impl.GeneralMicroSessionIdGenerator;
import com.github.polyang.istudy.framework.starter.session.manager.MicroSessionManager;
import com.github.polyang.istudy.framework.starter.session.repository.MicroSessionRepository;
/**
* @Description: session管理抽象实现
* @Author: polyang
* @Date: 2021/6/19 14:51
*/
public abstract class BaseMicroSessionManagerImpl implements MicroSessionManager {
private long maxInactiveIntervalInSeconds = 1800L;
private MicroSessionIdGenerator microSessionIdGenerator = new GeneralMicroSessionIdGenerator();
private MicroSessionRepository sessionRepository;
public long getMaxInactiveIntervalInSeconds() {
return maxInactiveIntervalInSeconds;
}
public void setMaxInactiveIntervalInSeconds(long maxInactiveIntervalInSeconds) {
this.maxInactiveIntervalInSeconds = maxInactiveIntervalInSeconds;
}
public MicroSessionIdGenerator getMicroSessionIdGenerator() {
return microSessionIdGenerator;
}
public void setMicroSessionIdGenerator(MicroSessionIdGenerator microSessionIdGenerator) {
this.microSessionIdGenerator = microSessionIdGenerator;
}
public MicroSessionRepository getSessionRepository() {
return sessionRepository;
}
public void setSessionRepository(MicroSessionRepository sessionRepository) {
this.sessionRepository = sessionRepository;
}
}
| 36.177778 | 105 | 0.801597 |
61797b832707a10e15624d236f30c7ba5fefb575 | 221 | package com.longluo.android.wxapi;
import com.umeng.socialize.weixin.view.WXCallbackActivity;
/**
微信登录回调(请注意这个 Activity 放置的包名要和当前项目的包名保持一致,否则将不能正常回调)
*/
public final class WXEntryActivity extends WXCallbackActivity {} | 27.625 | 64 | 0.823529 |
cc74950c531294c6a8032546929ed39eed159428 | 2,229 | package comp1110.ass2;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;
import static org.junit.Assert.assertTrue;
public class IsPiecePlacementWellFormedTest {
@Rule
public Timeout globalTimeout = Timeout.millis(1000);
private void test(String piecePlacement, Boolean expected) {
boolean out = Metro.isPiecePlacementWellFormed(piecePlacement);
assertTrue("expected " + expected + " for piece placement: " + piecePlacement +
", but got " + out, out == expected);
}
@Test
public void testWellFormed() {
testTrivial();
for (int i = 0; i < Utilities.COMPLETE_BOARDSTRINGS.length; i++) {
String boardString = Utilities.COMPLETE_BOARDSTRINGS[i];
for (int j = 0; j < Utilities.COMPLETE_BOARDSTRINGS[i].length() / 6; j++) {
String piece = boardString.substring(j * 6, j * 6 + 6);
test(piece, true);
}
}
}
@Test
public void testBadTile() {
testTrivial();
String boardString = Utilities.COMPLETE_BOARDSTRINGS[0];
String replace = boardString.replace('b', 'p');
replace = replace.replace('a', 'o');
for (int i = 0; i < 8; i++) {
test(replace.substring(i * 6, i * 6 + 6), false);
}
}
@Test
public void testBadLocation() {
testTrivial();
String boardString = Utilities.COMPLETE_BOARDSTRINGS[0];
String replace = boardString.replace('0', '9');
replace = replace.replace('7', '8');
replace = replace.replace('6', '9');
for (int i = 0; i < 13; i++) {
test(replace.substring(i * 6, i * 6 + 6), false);
}
}
@Test
public void testBadLength() {
testTrivial();
String boardString = Utilities.COMPLETE_BOARDSTRINGS[0];
for (int i = 0; i < boardString.length() / 6; i++) {
String piece = boardString.substring(i * 6, i * 6 + 6) + 'a';
test(piece, false);
}
}
private void testTrivial() {
test("aaaa00", true);
test("zzzz99", false);
}
} | 29.72 | 88 | 0.548677 |
54a0fd57467d3f92bbe6a471447829df5ae13c26 | 379 | package dev.vality.hooker.dao;
import dev.vality.hooker.model.EventType;
import lombok.*;
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class WebhookAdditionalFilter {
private EventType eventType;
private String shopId;
private String invoiceStatus;
private String invoicePaymentStatus;
private String invoicePaymentRefundStatus;
}
| 21.055556 | 46 | 0.796834 |
594da03456fd32ad8b2002d03be17d83e4a01269 | 1,673 | package me.zhengjie.modules.business.creditCard.domain;
import lombok.Data;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import javax.persistence.*;
import java.math.BigDecimal;
import java.io.Serializable;
import java.util.Date;
/**
* @author leo
* @date 2019-12-25
*/
@Entity
@Data
@Table(name="credit_card")
public class CreditCard implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
// 信用卡名称
@Column(name = "card_name")
private String cardName;
// 信用卡号
@Column(name = "card_number")
private String cardNumber;
// 到期时间
@Column(name = "card_exp")
private String cardExp;
// 过期时间
@Column(name = "card_exp_date")
private Date cardExpDate;
// 校验码
@Column(name = "card_cvv")
private String cardCvv;
// 当前金额
@Column(name = "current_amount")
private BigDecimal currentAmount;
// 币种
@Column(name = "currency")
private String currency;
// Label
@Column(name = "card_label")
private String cardLabel;
// 过期时间
@Column(name = "close_date")
private Date closeDate;
// 信用卡状态:0-不可用,1-可用
@Column(name = "card_status")
private Integer cardStatus;
// 数据状态:0-无效,1-有效
@Column(name = "data_status")
private Integer dataStatus;
// 创建人
@Column(name = "created_by")
private String createdBy;
// 创建时间
@Column(name = "created_date")
private Date createdDate;
public void copy(CreditCard source){
BeanUtil.copyProperties(source,this, CopyOptions.create().setIgnoreNullValue(true));
}
} | 20.9125 | 92 | 0.661686 |
76d3def1c6c58ed8a2b719505c312a220f6611fd | 9,758 | /*
* 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.accumulo.start;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.accumulo.start.classloader.AccumuloClassLoader;
import org.apache.accumulo.start.spi.KeywordExecutable;
import org.apache.accumulo.start.spi.KeywordExecutable.UsageGroup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private static ClassLoader classLoader;
private static Class<?> vfsClassLoader;
private static Map<String,KeywordExecutable> servicesMap;
public static void main(final String[] args) {
try {
// Preload classes that cause a deadlock between the ServiceLoader and the DFSClient when
// using
// the VFSClassLoader with jars in HDFS.
ClassLoader loader = getClassLoader();
Class<?> confClass = null;
try {
confClass =
AccumuloClassLoader.getClassLoader().loadClass("org.apache.hadoop.conf.Configuration");
} catch (ClassNotFoundException e) {
log.error("Unable to find Hadoop Configuration class on classpath, check configuration.",
e);
System.exit(1);
}
Object conf = null;
try {
conf = confClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
log.error("Error creating new instance of Hadoop Configuration", e);
System.exit(1);
}
try {
Method getClassByNameOrNullMethod =
conf.getClass().getMethod("getClassByNameOrNull", String.class);
getClassByNameOrNullMethod.invoke(conf, "org.apache.hadoop.mapred.JobConf");
getClassByNameOrNullMethod.invoke(conf, "org.apache.hadoop.mapred.JobConfigurable");
} catch (Exception e) {
log.error("Error pre-loading JobConf and JobConfigurable classes, VFS classloader with "
+ "system classes in HDFS may not work correctly", e);
System.exit(1);
}
if (args.length == 0) {
printUsage();
System.exit(1);
}
if (args[0].equals("-h") || args[0].equals("-help") || args[0].equals("--help")) {
printUsage();
System.exit(1);
}
// determine whether a keyword was used or a class name, and execute it with the remaining
// args
String keywordOrClassName = args[0];
KeywordExecutable keywordExec = getExecutables(loader).get(keywordOrClassName);
if (keywordExec != null) {
execKeyword(keywordExec, stripArgs(args, 1));
} else {
execMainClassName(keywordOrClassName, stripArgs(args, 1));
}
} catch (Throwable t) {
log.error("Uncaught exception", t);
System.exit(1);
}
}
public static synchronized ClassLoader getClassLoader() {
if (classLoader == null) {
try {
classLoader = (ClassLoader) getVFSClassLoader().getMethod("getClassLoader").invoke(null);
Thread.currentThread().setContextClassLoader(classLoader);
} catch (IOException | IllegalArgumentException | ReflectiveOperationException
| SecurityException e) {
log.error("Problem initializing the class loader", e);
System.exit(1);
}
}
return classLoader;
}
public static synchronized Class<?> getVFSClassLoader()
throws IOException, ClassNotFoundException {
if (vfsClassLoader == null) {
Thread.currentThread().setContextClassLoader(AccumuloClassLoader.getClassLoader());
vfsClassLoader = AccumuloClassLoader.getClassLoader()
.loadClass("org.apache.accumulo.start.classloader.vfs.AccumuloVFSClassLoader");
}
return vfsClassLoader;
}
private static void execKeyword(final KeywordExecutable keywordExec, final String[] args) {
Runnable r = () -> {
try {
keywordExec.execute(args);
} catch (Exception e) {
die(e);
}
};
startThread(r, keywordExec.keyword());
}
private static void execMainClassName(final String className, final String[] args) {
Class<?> classWithMain = null;
try {
classWithMain = getClassLoader().loadClass(className);
} catch (ClassNotFoundException cnfe) {
System.out.println("Invalid argument: Java <main class> '" + className
+ "' was not found. Please use the wholly qualified package name.");
printUsage();
System.exit(1);
}
execMainClass(classWithMain, args);
}
public static void execMainClass(final Class<?> classWithMain, final String[] args) {
Method main = null;
try {
main = classWithMain.getMethod("main", args.getClass());
} catch (Throwable t) {
log.error("Could not run main method on '" + classWithMain.getName() + "'.", t);
}
if (main == null || !Modifier.isPublic(main.getModifiers())
|| !Modifier.isStatic(main.getModifiers())) {
System.out.println(classWithMain.getName()
+ " must implement a public static void main(String args[]) method");
System.exit(1);
}
final Method finalMain = main;
Runnable r = () -> {
try {
finalMain.invoke(null, (Object) args);
} catch (InvocationTargetException e) {
if (e.getCause() != null) {
die(e.getCause());
} else {
// Should never happen, but check anyway.
die(e);
}
} catch (Exception e) {
die(e);
}
};
startThread(r, classWithMain.getName());
}
public static String[] stripArgs(final String[] originalArgs, int numToStrip) {
int newSize = originalArgs.length - numToStrip;
String[] newArgs = new String[newSize];
System.arraycopy(originalArgs, numToStrip, newArgs, 0, newSize);
return newArgs;
}
private static void startThread(final Runnable r, final String name) {
Thread t = new Thread(r, name);
t.setContextClassLoader(getClassLoader());
t.start();
}
/**
* Print a stack trace to stderr and exit with a non-zero status.
*
* @param t
* The {@link Throwable} containing a stack trace to print.
*/
private static void die(final Throwable t) {
log.error("Thread '" + Thread.currentThread().getName() + "' died.", t);
System.exit(1);
}
public static void printCommands(TreeSet<KeywordExecutable> set, UsageGroup group) {
set.stream().filter(e -> e.usageGroup() == group)
.forEach(ke -> System.out.printf(" %-30s %s\n", ke.usage(), ke.description()));
}
public static void printUsage() {
TreeSet<KeywordExecutable> executables =
new TreeSet<>(Comparator.comparing(KeywordExecutable::keyword));
executables.addAll(getExecutables(getClassLoader()).values());
System.out.println("\nUsage: accumulo <command> [--help] (<argument> ...)\n\n"
+ " --help Prints usage for specified command");
System.out.println("\nCore Commands:");
printCommands(executables, UsageGroup.CORE);
System.out.println(" classpath Prints Accumulo classpath\n"
+ " <main class> args Runs Java <main class> located on Accumulo classpath");
System.out.println("\nProcess Commands:");
printCommands(executables, UsageGroup.PROCESS);
System.out.println("\nOther Commands:");
printCommands(executables, UsageGroup.OTHER);
System.out.println();
}
public static synchronized Map<String,KeywordExecutable> getExecutables(final ClassLoader cl) {
if (servicesMap == null) {
servicesMap = checkDuplicates(ServiceLoader.load(KeywordExecutable.class, cl));
}
return servicesMap;
}
public static Map<String,KeywordExecutable>
checkDuplicates(final Iterable<? extends KeywordExecutable> services) {
TreeSet<String> blacklist = new TreeSet<>();
TreeMap<String,KeywordExecutable> results = new TreeMap<>();
for (KeywordExecutable service : services) {
String keyword = service.keyword();
if (blacklist.contains(keyword)) {
// subsequent times a duplicate is found, just warn and exclude it
warnDuplicate(service);
} else if (results.containsKey(keyword)) {
// the first time a duplicate is found, blacklist it and warn
blacklist.add(keyword);
warnDuplicate(results.remove(keyword));
warnDuplicate(service);
} else {
// first observance of this keyword, so just add it to the list
results.put(service.keyword(), service);
}
}
return Collections.unmodifiableSortedMap(results);
}
private static void warnDuplicate(final KeywordExecutable service) {
log.warn("Ambiguous duplicate binding for keyword '{}' found: {}", service.keyword(),
service.getClass().getName());
}
}
| 36.546816 | 99 | 0.668477 |
1028620fdbf316a0619e0ff3ba0dbebfc35bdabf | 1,621 | package net.codejava.Controller;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.util.Properties;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import net.codejava.Model.Weather;
import net.codejava.View.WeatherService;
@Service
public class WeatherServiceImpl implements WeatherService {
@Value("${app.id}")
private String AppID;
private final JsonWeatherParser parser = new JsonWeatherParser();
@Override
public Weather getCurrentWeather(String city)
throws IOException, ParseException, JSONException, org.json.simple.parser.ParseException {
return getWeatherFromJson(getJsonFromServer(city));
}
private Weather getWeatherFromJson(String json)
throws ParseException, org.json.simple.parser.ParseException, JSONException {
parser.setJsonToParsing(json);
return parser.getWeather();
}
private String getJsonFromServer(String city) throws IOException {
String result = "";
URL url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=" + city + "&APPID=" + AppID + "&units=metric");
URLConnection urlConnection = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result += result.concat(inputLine);
}
in.close();
return result;
}
}
| 28.946429 | 102 | 0.775447 |
71e83785125a34a7b6acc200fb7bacbbe4ece120 | 7,153 | package org.nem.core.node;
import org.hamcrest.MatcherAssert;
import org.hamcrest.core.*;
import org.junit.*;
import org.nem.core.serialization.*;
import org.nem.core.test.*;
import java.util.*;
public class NodeTest {
private static final NodeIdentity DEFAULT_IDENTITY = new WeakNodeIdentity("bob");
private static final NodeEndpoint DEFAULT_ENDPOINT = new NodeEndpoint("ftp", "10.8.8.2", 12);
private static final NodeMetaData DEFAULT_META_DATA = new NodeMetaData(null, null);
// region construction
@Test
public void canCreateNewNodeWithoutMetaData() {
// Arrange:
final NodeIdentity identity = new WeakNodeIdentity("alice");
final NodeEndpoint endpoint = new NodeEndpoint("http", "localhost", 8080);
// Act:
final Node node = new Node(identity, endpoint);
// Assert:
MatcherAssert.assertThat(node.getIdentity(), IsSame.sameInstance(identity));
MatcherAssert.assertThat(node.getEndpoint(), IsSame.sameInstance(endpoint));
MatcherAssert.assertThat(node.getMetaData(), IsEqual.equalTo(new NodeMetaData(null, null)));
}
@Test
public void canCreateNewNodeWithMetaData() {
// Arrange:
final NodeIdentity identity = new WeakNodeIdentity("alice");
final NodeEndpoint endpoint = new NodeEndpoint("http", "localhost", 8080);
final NodeMetaData metaData = new NodeMetaData("p", "a");
// Act:
final Node node = new Node(identity, endpoint, metaData);
// Assert:
MatcherAssert.assertThat(node.getIdentity(), IsSame.sameInstance(identity));
MatcherAssert.assertThat(node.getEndpoint(), IsSame.sameInstance(endpoint));
MatcherAssert.assertThat(node.getMetaData(), IsSame.sameInstance(metaData));
}
@Test
public void nodeCanBeRoundTripped() {
// Arrange:
final NodeIdentity identity = new WeakNodeIdentity("alice");
final NodeEndpoint endpoint = new NodeEndpoint("http", "localhost", 8080);
final NodeMetaData metaData = new NodeMetaData("p", "a");
final Node originalNode = new Node(identity, endpoint, metaData);
// Act:
final Node node = new Node(Utils.roundtripSerializableEntity(originalNode, null));
// Assert:
MatcherAssert.assertThat(node.getIdentity(), IsEqual.equalTo(identity));
MatcherAssert.assertThat(node.getEndpoint(), IsEqual.equalTo(endpoint));
MatcherAssert.assertThat(node.getMetaData(), IsEqual.equalTo(metaData));
}
@Test
public void nodeCanBeDeserializedWithoutMetaData() {
// Arrange:
final NodeIdentity identity = new WeakNodeIdentity("alice");
final NodeEndpoint endpoint = new NodeEndpoint("http", "localhost", 8080);
final Node originalNode = new Node(identity, endpoint);
final JsonSerializer serializer = new JsonSerializer(true);
originalNode.serialize(serializer);
serializer.getObject().remove("metaData");
// Act:
final Node node = new Node(new JsonDeserializer(serializer.getObject(), null));
// Assert:
MatcherAssert.assertThat(node.getIdentity(), IsEqual.equalTo(identity));
MatcherAssert.assertThat(node.getEndpoint(), IsEqual.equalTo(endpoint));
MatcherAssert.assertThat(node.getMetaData(), IsEqual.equalTo(new NodeMetaData(null, null)));
}
@Test
public void identityCannotBeNull() {
// Act:
ExceptionAssert.assertThrows(v -> new Node(null, DEFAULT_ENDPOINT), IllegalArgumentException.class);
ExceptionAssert.assertThrows(v -> new Node(null, DEFAULT_ENDPOINT, DEFAULT_META_DATA), IllegalArgumentException.class);
}
@Test
public void endpointCannotBeNull() {
// Act:
ExceptionAssert.assertThrows(v -> new Node(DEFAULT_IDENTITY, null), IllegalArgumentException.class);
ExceptionAssert.assertThrows(v -> new Node(DEFAULT_IDENTITY, null, DEFAULT_META_DATA), IllegalArgumentException.class);
}
// endregion
// region setters
@Test
public void canChangeEndpoint() {
// Arrange:
final Node node = new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT);
final NodeEndpoint endpoint = NodeEndpoint.fromHost("10.0.0.2");
// Act:
node.setEndpoint(endpoint);
// Assert:
MatcherAssert.assertThat(node.getEndpoint(), IsSame.sameInstance(endpoint));
}
@Test(expected = IllegalArgumentException.class)
public void cannotChangeEndpointToNull() {
// Act:
new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT).setEndpoint(null);
}
@Test
public void canChangeMetaData() {
// Arrange:
final Node node = new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT);
final NodeMetaData metaData = new NodeMetaData("aaa", "ppp");
// Act:
node.setMetaData(metaData);
// Assert:
MatcherAssert.assertThat(node.getMetaData(), IsSame.sameInstance(metaData));
}
@Test(expected = IllegalArgumentException.class)
public void cannotChangeMetaDataToNull() {
// Act:
new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT).setMetaData(null);
}
// endregion
// region equals / hashCode
@SuppressWarnings("serial")
private static final Map<String, Node> DESC_TO_NODE_MAP = new HashMap<String, Node>() {
{
this.put("default", new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT, DEFAULT_META_DATA));
this.put("diff-identity", new Node(new WeakNodeIdentity("alice"), DEFAULT_ENDPOINT, DEFAULT_META_DATA));
this.put("diff-endpoint", new Node(DEFAULT_IDENTITY, new NodeEndpoint("http", "localhost", 8080), DEFAULT_META_DATA));
this.put("diff-meta-data", new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT, new NodeMetaData("p", "a")));
}
};
@Test
public void equalsOnlyReturnsTrueForEquivalentObjects() {
// Arrange:
final Node node = new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT, DEFAULT_META_DATA);
// Assert:
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("default"), IsEqual.equalTo(node));
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("diff-identity"), IsNot.not(IsEqual.equalTo(node)));
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("diff-endpoint"), IsEqual.equalTo(node));
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("diff-meta-data"), IsEqual.equalTo(node));
MatcherAssert.assertThat(null, IsNot.not(IsEqual.equalTo(node)));
MatcherAssert.assertThat(DEFAULT_IDENTITY, IsNot.not(IsEqual.equalTo((Object) node)));
}
@Test
public void hashCodesAreEqualForEquivalentObjects() {
// Arrange:
final Node node = new Node(DEFAULT_IDENTITY, DEFAULT_ENDPOINT, DEFAULT_META_DATA);
final int hashCode = node.hashCode();
// Assert:
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("default").hashCode(), IsEqual.equalTo(hashCode));
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("diff-identity").hashCode(), IsNot.not(IsEqual.equalTo(hashCode)));
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("diff-endpoint").hashCode(), IsEqual.equalTo(hashCode));
MatcherAssert.assertThat(DESC_TO_NODE_MAP.get("diff-meta-data").hashCode(), IsEqual.equalTo(hashCode));
}
// endregion
// region toString
@Test
public void toStringReturnsAppropriateRepresentation() {
// Arrange:
final NodeIdentity identity = new WeakNodeIdentity("alice");
final NodeEndpoint endpoint = new NodeEndpoint("http", "localhost", 8080);
final NodeMetaData metaData = new NodeMetaData("p", "a");
final Node node = new Node(identity, endpoint, metaData);
// Assert:
MatcherAssert.assertThat(node.toString(), IsEqual.equalTo("Node [(Weak Id) alice] @ [localhost]"));
}
// endregion
}
| 35.410891 | 121 | 0.752691 |
ed065b4ad1e91980b324cad23428c0ad5bef1aba | 11,330 | /*
* ============LICENSE_START==========================================
* ONAP Portal SDK
* ===================================================================
* Copyright © 2017 AT&T Intellectual Property. All rights reserved.
* ===================================================================
*
* Unless otherwise specified, all software contained herein is licensed
* under the Apache License, Version 2.0 (the "License");
* you may not use this software 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.
*
* Unless otherwise specified, all documentation contained herein is licensed
* under the Creative Commons License, Attribution 4.0 Intl. (the "License");
* you may not use this documentation except in compliance with the License.
* You may obtain a copy of the License at
*
* https://creativecommons.org/licenses/by/4.0/
*
* Unless required by applicable law or agreed to in writing, documentation
* 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.
*
* ============LICENSE_END============================================
*
* ECOMP is a trademark and service mark of AT&T Intellectual Property.
*/
package org.onap.portalsdk.core.domain.support;
import java.util.List;
import java.util.Map;
import org.onap.portalsdk.core.logging.logic.EELFLoggerDelegate;
public class Container {
private static final EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(Container.class);
String id;
String name;
Size size;
Position p;
Map<String, Container> containerRowCol;
Map<String, Element> elementRowCol;
int numOfRows;
int numOfCols;
double sum = 0;
double interEleWd;
double interEleH;
double interEleToContainerWd;
double interEleToContainerH;
double interEleToInnerContainerWd;
double interEleToInnerContainerH;
double top;
double left;
double height;
double width;
String visibilityType;
List<Container> innerCList;
List<Element> elementList;
public Container() {
}
public Container(String id, String name, int numOfRows, int numOfCols, double interEleWd, double interEleH,
double interEleToContainerWd, double interEleToContainerH, double interEleToInnerContainerWd,
double interEleToInnerContainerH) {
this.id = id;
this.name = name;
this.numOfRows = numOfRows;
this.numOfCols = numOfCols;
this.interEleWd = interEleWd;
this.interEleH = interEleH;
this.interEleToContainerWd = interEleToContainerWd;
this.interEleToContainerH = interEleToContainerH;
this.interEleToInnerContainerWd = interEleToInnerContainerWd;
this.interEleToInnerContainerH = interEleToInnerContainerH;
}
public Map<String, Container> getContainerRowCol() {
return containerRowCol;
}
public Map<String, Element> getElementRowCol() {
return elementRowCol;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setInnerContainer(Map<String, Container> innerCon) {
containerRowCol = innerCon;
}
public void setElements(Map<String, Element> innerE) {
elementRowCol = innerE;
}
public Position getP() {
return p;
}
public void setP(Position p) {
this.p = p;
}
public void setTop(double top) {
this.top = top;
}
public void setLeft(double left) {
this.left = left;
}
public void setHeight(double height) {
this.height = height;
}
public void setWidth(double width) {
this.width = width;
}
public void setInnerCList(List<Container> innerCList) {
this.innerCList = innerCList;
}
public void setElementList(List<Element> elementList) {
this.elementList = elementList;
}
public void setVisibilityType(String visibilityType) {
this.visibilityType = visibilityType;
}
public Size computeSize() {
logger.debug("computeSize: name is {}", getName());
Size size = new Size();
double width = 0;
double height = 0;
for (int i = 0; i < numOfRows; i++) {
if ((containerRowCol != null && containerRowCol.containsKey(i + String.valueOf(numOfCols - 1)))
|| (elementRowCol != null && elementRowCol.containsKey(i + String.valueOf(numOfCols - 1)))) {
for (int j = 0; j < numOfCols; j++) {
if (containerRowCol != null && containerRowCol.containsKey(i + String.valueOf(j))) {
width += containerRowCol.get(i + String.valueOf(j)).computeSize().getWidth();
} else if (elementRowCol != null && elementRowCol.containsKey(i + String.valueOf(j)))
width += elementRowCol.get(i + String.valueOf(j)).computeSize().getWidth();
}
break;
}
}
if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
|| this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider")
|| this.getName().equals("Neo") || this.getName().equals("Support")) {
width += (numOfCols - 1) * interEleWd + 2 * interEleToInnerContainerWd;
} else {
width += (numOfCols - 1) * interEleWd + 2 * interEleToContainerWd;
}
size.setWidth(width);
for (int j = 0; j < numOfCols; j++) {
if ((containerRowCol != null && containerRowCol.containsKey(String.valueOf(numOfRows - 1) + j))
|| (elementRowCol != null && elementRowCol.containsKey(String.valueOf(numOfRows - 1) + j))) {
for (int i = 0; i < numOfRows; i++) {
if (containerRowCol != null && containerRowCol.containsKey(i + String.valueOf(j))) {
height += containerRowCol.get(i + String.valueOf(j)).computeSize().getHeight();
} else if (elementRowCol != null && elementRowCol.containsKey(i + String.valueOf(j)))
height += elementRowCol.get(String.valueOf(i) + String.valueOf(j)).computeSize().getHeight();
}
break;
}
}
if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
|| this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider")
|| this.getName().equals("Neo") || this.getName().equals("Support")) {
height += (numOfRows - 1) * interEleH + 2 * interEleToInnerContainerH + 0.1;
} else {
if (this.getName().equals("VoLTE UE") || this.getName().equals("3G UE") || this.getName().equals("HC UE-A")
|| this.getName().equals("HC UE-B") || this.getName().equals("VNI UE")
|| this.getName().equals("PSTN")) {
height += (numOfRows - 1) * interEleH + interEleToContainerH / 2;
} else
height += (numOfRows - 1) * interEleH + 2 * interEleToContainerH;
}
size.setHeight(height);
return size;
}
public void computeElementPositions() {
double xsum = 0;
double ysum = 0;
for (int i = 0; i < numOfRows; i++) {
for (int j = 0; j < numOfCols; j++) {
if (containerRowCol != null && containerRowCol.containsKey(String.valueOf(i) + String.valueOf(j))) {
Container c = containerRowCol.get(String.valueOf(i) + String.valueOf(j));
Position p = new Position();
p.x = j * interEleWd + xsum + this.getP().getX() + interEleToContainerWd;
ysum = 0;
for (int k = 0; k < i; k++) {
if (containerRowCol.containsKey(String.valueOf(k) + String.valueOf(j)))
ysum += containerRowCol.get(String.valueOf(k) + String.valueOf(j)).computeSize()
.getHeight();
else if (elementRowCol.containsKey(String.valueOf(k) + String.valueOf(j)))
ysum += elementRowCol.get(String.valueOf(k) + String.valueOf(j)).computeSize().getHeight();
}
p.y = i * interEleH + ysum + this.getP().getY() + interEleToContainerH;
// containerCoord.add(c,p);
xsum += c.computeSize().getWidth();
c.setP(p);
} else if (elementRowCol != null && elementRowCol.containsKey(String.valueOf(i) + String.valueOf(j))) {
Element e = elementRowCol.get(String.valueOf(i) + String.valueOf(j));
Position p = new Position();
if (j == numOfCols - 1) {
for (int t = 0; t < i; t++) {
if (containerRowCol != null
&& containerRowCol.containsKey(String.valueOf(t) + String.valueOf(j - 1))) {
if (!elementRowCol.containsKey(String.valueOf(i) + String.valueOf(j - 1))
&& !containerRowCol.containsKey(String.valueOf(i) + String.valueOf(j - 1))) {
xsum += containerRowCol.get(String.valueOf(t) + String.valueOf(j - 1)).computeSize()
.getWidth();
break;
}
}
}
}
if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
|| this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider")
|| this.getName().equals("Neo") || this.getName().equals("Support")) {
p.x = j * interEleWd + xsum + this.getP().getX() + interEleToInnerContainerWd;
} else if (this.getName().equals("VNI UE") || this.getName().equals("PSTN")
|| this.getName().equals("3G UE") || this.getName().equals("HC UE-A")
|| this.getName().equals("HC UE-B")) {
p.x = j * interEleWd + xsum + this.getP().getX() + interEleToContainerWd - 0.8;
} else {
p.x = j * interEleWd + xsum + this.getP().getX() + interEleToContainerWd;
}
ysum = 0;
for (int k = 0; k < i; k++) {
if (containerRowCol != null
&& containerRowCol.containsKey(String.valueOf(k) + String.valueOf(j)))
ysum += containerRowCol.get(String.valueOf(k) + String.valueOf(j)).computeSize()
.getHeight();
else if (elementRowCol != null
&& elementRowCol.containsKey(String.valueOf(k) + String.valueOf(j)))
ysum += elementRowCol.get(String.valueOf(k) + String.valueOf(j)).computeSize().getHeight();
else if (containerRowCol != null) {
for (int chk = j; chk > 0; chk--) {
if (containerRowCol.containsKey(String.valueOf(k) + String.valueOf(chk - 1))) {
if (containerRowCol.get(String.valueOf(k) + String.valueOf(chk - 1)).computeSize()
.getWidth()
+ containerRowCol.get(String.valueOf(k) + String.valueOf(chk - 1)).getP()
.getX() > p.x) {
ysum += containerRowCol.get(String.valueOf(k) + String.valueOf(chk - 1))
.computeSize().getHeight();
break;
}
}
}
}
}
if (this.getName().equals("Broadworks complex") || this.getName().equals("Application Servers")
|| this.getName().equals("Call Session Control") || this.getName().equals("GMLC Provider")
|| this.getName().equals("Neo") || this.getName().equals("Support")) {
p.y = this.getP().getY() + ysum + i * interEleH + interEleToInnerContainerH + 1;
} else {
if (e.getName().equals("")) {
p.y = this.getP().getY() + ysum + i * interEleH + (interEleToContainerH);
} else
p.y = this.getP().getY() + ysum + i * interEleH + interEleToContainerH;
}
xsum += e.computeSize().getWidth();
e.setP(p);
}
}
xsum = 0;
}
}
}
| 35.29595 | 110 | 0.645984 |
01160dc41260ba9e5f613a84b76d27ebb65aff75 | 4,432 | package com.neconico.neconico.config.security.oauth;
import com.neconico.neconico.dto.users.UserJoinDto;
import lombok.Builder;
import lombok.Getter;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.UUID;
@Getter
public class OAuthAttributes {
private Map<String, Object> attributes;
private String registrationId;
private String nameAttributeKey;
private String name;
private String email;
private String phoneNumber;
private String gender;
private String picture;
private String uniqueId; //NAVER 이용 시 해당 유저 고유식별 ID
@Builder
public OAuthAttributes(Map<String, Object> attributes, String nameAttributeKey,
String registrationId, String name, String email, String phoneNumber,
String gender, String picture, String uniqueId) {
this.attributes = attributes;
this.registrationId = registrationId;
this.nameAttributeKey = nameAttributeKey;
this.name = name;
this.email = email;
this.phoneNumber = phoneNumber;
this.gender = gender;
this.picture = picture;
this.uniqueId = uniqueId;
}
public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes) {
if(registrationId.equals("naver")) {
return ofNaver(registrationId, "id", attributes);
}
return ofGoogle(registrationId, userNameAttributeName, attributes);
}
public UserJoinDto createUserJoinDto() {
String accountId = "";
if(registrationId.equals("naver")) {
accountId = extractAccountId(email) + "N";
}else {
accountId = extractAccountId(email) + "G";
}
UserJoinDto userJoinDto = new UserJoinDto();
userJoinDto.setAccountId(accountId);
userJoinDto.setAccountPw(email + UUID.randomUUID());
userJoinDto.setAccountName(name);
userJoinDto.setGender(gender);
userJoinDto.setBirthdate("OAUTH");
userJoinDto.setEmail(email);
userJoinDto.setPhoneNumber(phoneNumber);
userJoinDto.setZipNo("OAUTH");
userJoinDto.setAddress("OAUTH");
userJoinDto.setInfoAgreement("check");
userJoinDto.setCreateDate(LocalDateTime.now());
userJoinDto.setModifiedDate(LocalDateTime.now());
userJoinDto.setAuthority("ROLE_USER");
return userJoinDto;
}
private static OAuthAttributes ofNaver(String registrationId, String userNameAttributeName, Map<String, Object> attributes) {
Map<String, Object> response = (Map<String, Object>) attributes.get("response");
return OAuthAttributes.builder()
.name((String) response.get("name"))
.email((String) response.get("email"))
.picture((String) response.get("profile_image"))
.gender((String) response.get("gender"))
.attributes(response)
.phoneNumber((String) response.get("mobile"))
.uniqueId((String) response.get("id"))
.registrationId(registrationId)
.nameAttributeKey(userNameAttributeName)
.build();
}
public static OAuthAttributes ofGoogle(String registrationId, String userNameAttributeName, Map<String, Object> attributes) {
return OAuthAttributes.builder()
.name((String) attributes.get("name"))
.email((String) attributes.get("email"))
.picture((String) attributes.get("picture"))
.gender("U")
.attributes(attributes)
.phoneNumber(null)
.uniqueId(null)
.registrationId(registrationId)
.nameAttributeKey(userNameAttributeName)
.build();
}
private String extractAccountId(String email) {
int index = email.indexOf("@");
return email.substring(0, index);
}
public void changeName(String name) {
this.name = name;
}
public void changeEmail(String email) {
this.email = email;
}
public void changePhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void changeGender(String gender) {
this.gender = gender;
}
public void changePicture(String picture) {
this.picture = picture;
}
}
| 34.092308 | 129 | 0.633123 |
1526c9fc1be3ed86eaa18d7ebc716a2138c13eee | 3,679 | package com.lrk.xk.xk.model;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
/**
* @author lrk
* @date 2019/4/27 上午9:14
*/
@Entity
public class Teacher {
private int id;
private String tno;
private String password;
private String name;
private byte gender;
private String notes;
private byte isAdmin;
private int deptId;
@Id
@Column(name = "id",
nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "tno",
nullable = false,
length = 45)
public String getTno() {
return tno;
}
public void setTno(String tno) {
this.tno = tno;
}
@Basic
@Column(name = "password",
nullable = false,
length = 32)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Basic
@Column(name = "name",
nullable = false,
length = 45)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Basic
@Column(name = "gender",
nullable = false)
public byte getGender() {
return gender;
}
public void setGender(byte gender) {
this.gender = gender;
}
@Basic
@Column(name = "notes",
nullable = true,
length = 255)
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
@Basic
@Column(name = "is_admin",
nullable = false)
public byte getIsAdmin() {
return isAdmin;
}
public void setIsAdmin(byte isAdmin) {
this.isAdmin = isAdmin;
}
@Basic
@Column(name = "dept_id",
nullable = false)
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Teacher teacher = (Teacher) o;
if (id != teacher.id) {
return false;
}
if (gender != teacher.gender) {
return false;
}
if (isAdmin != teacher.isAdmin) {
return false;
}
if (deptId != teacher.deptId) {
return false;
}
if (tno != null ? !tno.equals(teacher.tno) : teacher.tno != null) {
return false;
}
if (password != null ? !password.equals(teacher.password) : teacher.password != null) {
return false;
}
if (name != null ? !name.equals(teacher.name) : teacher.name != null) {
return false;
}
if (notes != null ? !notes.equals(teacher.notes) : teacher.notes != null) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (tno != null ? tno.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (int) gender;
result = 31 * result + (notes != null ? notes.hashCode() : 0);
result = 31 * result + (int) isAdmin;
result = 31 * result + deptId;
return result;
}
}
| 22.02994 | 95 | 0.525686 |
24df967fdf2c3c4859d5451e33a1b96370c940f8 | 5,935 | package com.github.simondan.svl.app.communication;
import android.content.Context;
import com.github.simondan.svl.app.communication.config.*;
import com.github.simondan.svl.app.communication.exceptions.*;
import de.adito.ojcms.rest.auth.api.AuthenticationRequest;
import okhttp3.*;
import javax.net.ssl.*;
import java.security.SecureRandom;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import static de.adito.ojcms.rest.auth.util.OJGsonSerializer.GSON_INSTANCE;
/**
* @author Simon Danner, 16.11.2019
*/
class RestBuilder<RESULT>
{
private static final MediaType TEXT_MEDIA_TYPE = MediaType.parse("text/plain; charset=utf-8");
private static final MediaType JSON_MEDIA_TYPE = MediaType.parse("application/json; charset=utf-8");
private final ICredentialsStore credentialsStore;
private final Class<RESULT> resultType;
private String path;
private EMethod method;
private RequestBody param;
private TimeoutConfig timeoutConfig = DefaultConfig.TIMEOUT_CONFIG;
public static <RESULT> RestBuilder<RESULT> buildCall(Context pContext, Class<RESULT> pResultType)
{
return new RestBuilder<>(pContext, pResultType);
}
public static RestBuilder<Void> buildNoResultCall(Context pContext)
{
return new RestBuilder<>(pContext, Void.class);
}
private RestBuilder(Context pContext, Class<RESULT> pResultType)
{
credentialsStore = ICredentialsStore.createForContext(pContext);
resultType = pResultType;
}
RestBuilder<RESULT> path(String pPath)
{
path = pPath;
return this;
}
RestBuilder<RESULT> method(EMethod pMethod)
{
method = pMethod;
return this;
}
RestBuilder<RESULT> textParam(String pParam)
{
param = RequestBody.create(TEXT_MEDIA_TYPE, pParam);
return this;
}
RestBuilder<RESULT> jsonParam(Object pParam, Class<?> pParamType)
{
param = RequestBody.create(JSON_MEDIA_TYPE, GSON_INSTANCE.toJson(pParam, pParamType));
return this;
}
RestBuilder<RESULT> timeout(TimeUnit pTimeUnit, long pValue)
{
timeoutConfig = new TimeoutConfig(pTimeUnit, pValue);
return this;
}
RESULT executeCall() throws RequestTimeoutException, AuthenticationImpossibleException, RequestFailedException
{
return _createRestCall().callRestInterface();
}
RESULT executeCallNoAuthentication() throws RequestTimeoutException, RequestFailedException
{
return _createRestCall().callRestInterfaceNoAuth();
}
private RestCall<RESULT> _createRestCall()
{
return new RestCall<>(timeoutConfig, credentialsStore, new _CallConfig());
}
private class _CallConfig implements IRestCallConfig<RESULT>
{
_CallConfig()
{
Objects.requireNonNull(resultType, "No result type provided!");
Objects.requireNonNull(path, "No path provided!");
Objects.requireNonNull(method, "No method provided!");
}
@Override
public Class<RESULT> getResultType()
{
return resultType;
}
@Override
public Request.Builder prepareRequest()
{
return _initRequest(path);
}
@Override
public Call buildCall(Request.Builder pBuilder)
{
final Request request;
switch (method)
{
case GET:
request = pBuilder.get().build();
break;
case POST:
request = pBuilder.post(param).build();
break;
case PUT:
request = pBuilder.put(param).build();
break;
case DELETE:
request = pBuilder.delete().build();
break;
default:
throw new RuntimeException("Method " + method + " not supported!");
}
return _createCall(request);
}
@Override
public Call createAuthenticationCall()
{
final AuthenticationRequest authRequest = credentialsStore.buildAuthenticationRequest();
return _createCall(_initRequest(DefaultConfig.AUTH_PATH)
.post(RequestBody.create(JSON_MEDIA_TYPE, GSON_INSTANCE.toJson(authRequest, AuthenticationRequest.class)))
.build());
}
private Call _createCall(Request pRequest)
{
return createUnsafeOkHttpClientBuilder()
.callTimeout(timeoutConfig.getTimeout(), timeoutConfig.getTimeUnit())
.readTimeout(timeoutConfig.getTimeout(), timeoutConfig.getTimeUnit())
.writeTimeout(timeoutConfig.getTimeout(), timeoutConfig.getTimeUnit())
.build()
.newCall(pRequest);
}
private Request.Builder _initRequest(String pPath)
{
return new Request.Builder()
.url(DefaultConfig.createServerUrlFromDefaults() + "/" + pPath);
}
}
private static OkHttpClient.Builder createUnsafeOkHttpClientBuilder() //TODO
{
try
{
final TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager()
{
@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType)
{
}
@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType)
{
}
@Override
public java.security.cert.X509Certificate[] getAcceptedIssuers()
{
return new java.security.cert.X509Certificate[]{};
}
}
};
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, trustAllCerts, new SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
return new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0])
.hostnameVerifier((hostname, session) -> true);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
| 28.95122 | 116 | 0.683235 |
35a267acbd4c24d3b916e2944536724c711b4e58 | 1,100 | /*
* 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 launcher;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import view.local.JPanelMenuPrincipal;
import view.local.fenetrePrincipale;
/**
*
* @author Anis
*/
public class Launcher {
public static void main(String[] args) {
JFrame frame = new fenetrePrincipale();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setLocation(600, 10);
frame.setResizable(true);
JPanelMenuPrincipal menu = new JPanelMenuPrincipal();
frame.setContentPane(menu);
frame.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width / 2 - frame.getSize().width / 2, dim.height / 2 - frame.getSize().height / 2);
frame.setVisible(true);
}
}
| 26.829268 | 114 | 0.673636 |
59b0a662664b92823fd3db29bdbd51578fefd665 | 508 | package Inter_threadCommunication.pipeStream.pipeReaderWrite;
import java.io.PipedWriter;
/**
* Created by xianpeng.xia
* on 2019-06-09 21:32
*/
public class ThreadWrite extends Thread {
private WriteData writeData;
private PipedWriter pipedWriter;
public ThreadWrite(WriteData writeData, PipedWriter pipedWriter) {
this.writeData = writeData;
this.pipedWriter = pipedWriter;
}
@Override
public void run() {
writeData.writeMethod(pipedWriter);
}
}
| 21.166667 | 70 | 0.708661 |
718522f874ecdb36184cd559113f07dd8366617e | 5,228 | /*
* 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.openjpa.persistence;
import org.apache.openjpa.enhance.FieldConsumer;
import org.apache.openjpa.enhance.FieldSupplier;
import org.apache.openjpa.enhance.PCEnhancer;
import org.apache.openjpa.enhance.PCRegistry;
import org.apache.openjpa.enhance.PersistenceCapable;
import org.apache.openjpa.enhance.StateManager;
/**
* This Object is here for the sole purpose of testing pcGetEnhancementContractVersion. This object isn't a tested
* PersistenceCapable implementation so it shouldn't be used unless you are fully aware of what you are doing.
*/
public class DummyPersistenceCapeable implements PersistenceCapable {
private static int pcInheritedFieldCount;
private static String pcFieldNames[] = {};
private static Class pcFieldTypes[];
private static byte pcFieldFlags[] = {};
private static Class pcPCSuperclass;
protected transient boolean pcVersionInit;
protected transient StateManager pcStateManager;
private transient Object pcDetachedState;
static {
Class aclass[] = new Class[0];
pcFieldTypes = aclass;
PCRegistry.register(DummyPersistenceCapeable.class, pcFieldNames, pcFieldTypes, pcFieldFlags, pcPCSuperclass,
"DummyPersistenceCapeable", new DummyPersistenceCapeable());
}
public int pcGetEnhancementContractVersion() {
return PCEnhancer.ENHANCER_VERSION - 1;
}
public PersistenceCapable pcNewInstance(StateManager sm, boolean clear) {
return new DummyPersistenceCapeable();
}
public void pcCopyFields(Object fromObject, int[] fields) {
// TODO Auto-generated method stub
}
public void pcCopyKeyFieldsFromObjectId(FieldConsumer consumer, Object obj) {
// TODO Auto-generated method stub
}
public void pcCopyKeyFieldsToObjectId(FieldSupplier supplier, Object obj) {
// TODO Auto-generated method stub
}
public void pcCopyKeyFieldsToObjectId(Object obj) {
// TODO Auto-generated method stub
}
public void pcDirty(String fieldName) {
// TODO Auto-generated method stub
}
public Object pcFetchObjectId() {
// TODO Auto-generated method stub
return null;
}
public Object pcGetDetachedState() {
// TODO Auto-generated method stub
return null;
}
public Object pcGetGenericContext() {
// TODO Auto-generated method stub
return null;
}
public StateManager pcGetStateManager() {
// TODO Auto-generated method stub
return null;
}
public Object pcGetVersion() {
// TODO Auto-generated method stub
return null;
}
public boolean pcIsDeleted() {
// TODO Auto-generated method stub
return false;
}
public Boolean pcIsDetached() {
// TODO Auto-generated method stub
return null;
}
public boolean pcIsDirty() {
// TODO Auto-generated method stub
return false;
}
public boolean pcIsNew() {
// TODO Auto-generated method stub
return false;
}
public boolean pcIsPersistent() {
// TODO Auto-generated method stub
return false;
}
public boolean pcIsTransactional() {
// TODO Auto-generated method stub
return false;
}
public PersistenceCapable pcNewInstance(StateManager sm, Object obj, boolean clear) {
// TODO Auto-generated method stub
return null;
}
public Object pcNewObjectIdInstance() {
// TODO Auto-generated method stub
return null;
}
public Object pcNewObjectIdInstance(Object obj) {
// TODO Auto-generated method stub
return null;
}
public void pcProvideField(int fieldIndex) {
// TODO Auto-generated method stub
}
public void pcProvideFields(int[] fieldIndices) {
// TODO Auto-generated method stub
}
public void pcReplaceField(int fieldIndex) {
// TODO Auto-generated method stub
}
public void pcReplaceFields(int[] fieldIndex) {
// TODO Auto-generated method stub
}
public void pcReplaceStateManager(StateManager sm) {
// TODO Auto-generated method stub
}
public void pcSetDetachedState(Object state) {
// TODO Auto-generated method stub
}
public DummyPersistenceCapeable() {
// TODO Auto-generated constructor stub
}
}
| 28.107527 | 117 | 0.686878 |
99a3ccbfdc672a626b2cdaea98957dfe5c040f43 | 277 | package com.taller2dam.taller.repository;
import com.taller2dam.taller.dao.Servicio;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ServicioRepository extends JpaRepository<Servicio, Long> {
//Optional<Servicio> findByName(String name);
}
| 30.777778 | 75 | 0.819495 |
a4230c103a4398fdb426e1e22e7044a21c16f606 | 347 | package org.dbhaskaran.studentdal.service;
import java.util.List;
import org.dbhaskaran.studentdal.entities.Student;
public interface IStudentService {
Student saveStudent(Student student);
Student updateStudent(Student student);
void deleteStudent(Student student);
Student getStudentbyId(long id);
List<Student> getAllStudents();
}
| 18.263158 | 50 | 0.801153 |
5a4868ce3397226769941300fce6be6540c4f36d | 1,516 | class Solution {
public List<Integer> countSmaller(int[] nums) {
int n = nums.length;
Pair[] pairs = new Pair[n];
for(int i=0; i<n; i++) {
pairs[i] = new Pair(nums[i], i);
}
int[] count = new int[n];
mergeSort(count, pairs, 0, n-1);
List<Integer> result = new ArrayList<>();
for(int c: count) result.add(c);
return result;
}
private void mergeSort(int[] count, Pair[] pairs, int left, int right) {
if (left >= right) return;
int mid = left + (right-left)/2;
mergeSort(count, pairs, left, mid);
mergeSort(count, pairs, mid+1, right);
merge(count, pairs, left, mid, right);
}
private void merge(int[] count, Pair[] pairs, int left, int mid, int right) {
Pair[] temp = new Pair[right-left+1];
int i=left, j=mid+1, k=0;
while(i <= mid && j<= right) {
if (pairs[i].val <= pairs[j].val) {
temp[k++] = pairs[j++];
} else {
count[pairs[i].pos] += right - j + 1;
temp[k++] = pairs[i++];
}
}
while(i <= mid) {
temp[k++] = pairs[i++];
}
while(j <= right) {
temp[k++] = pairs[j++];
}
for(i=left; i<= right; i++) {
pairs[i] = temp[i-left];
}
}
}
class Pair {
int val;
int pos;
public Pair(int val, int pos) {
this.val = val;
this.pos = pos;
}
} | 27.563636 | 81 | 0.455805 |
1b0f039e47ad67e6b534d05a16b447cb3d435083 | 1,219 | import org.junit.Test;
/**
* @author Politeness Chen
* @create 2019--05--13 22:28
*/
public class _07_Reverse {
public int reverse(int x) {
char[] chars = Long.toString(x).toCharArray();
if (chars[0] != '-') {
int i = 0;
int j = chars.length - 1;
while (i < j) {
swap(chars,i++,j--);
}
try{
return Integer.parseInt(String.valueOf(chars));
} catch (Exception e) {
return 0;
}
} else {
int i = 1;
int j = chars.length - 1;
while (i < j) {
swap(chars,i++,j--);
}
try{
return Integer.parseInt(String.valueOf(chars));
} catch (Exception e) {
return 0;
}
}
}
public static void swap(char[] chars,int a,int b){
char temp = chars[a];
chars[a] = chars[b];
chars[b] = temp;
}
@Test
public void t(){
int a = reverse(-1234567);
System.out.println(a);
}
@Test
public void t1(){
int a = reverse(1234567);
System.out.println(a);
}
}
| 22.574074 | 63 | 0.42904 |
4e51f4be95152ee1c6845b430e178b6843f044aa | 314 | package qowyn.ark.tools.data;
import qowyn.ark.ArkSavegame;
import qowyn.ark.GameObjectContainer;
import qowyn.ark.tools.LatLonCalculator;
public interface DataContext {
public LatLonCalculator getLatLonCalculator();
public GameObjectContainer getObjectContainer();
public ArkSavegame getSavegame();
}
| 19.625 | 50 | 0.812102 |
136c4f862a7c57a34b2ccd0b0493afe44e4ddbe5 | 3,986 | /*
// <editor-fold desc="The MIT License" defaultstate="collapsed">
* The MIT License
*
* Copyright 2022 Studio 42 GmbH (https://www.s42m.de).
*
* 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.
*/
//</editor-fold>
package de.s42.base.collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
*
* @author Benjamin Schiller
* @param <KeyType>
* @param <DataType>
*/
public class MappedList<KeyType, DataType>
{
protected final List<DataType> list = new ArrayList<>();
protected final Set<DataType> set = new HashSet<>();
protected final Map<KeyType, DataType> map = new HashMap<>();
public MappedList()
{
}
public int size()
{
return list.size();
}
public boolean isEmpty()
{
return list.isEmpty();
}
public void clear()
{
list.clear();
set.clear();
map.clear();
}
public void addAll(MappedList<KeyType, DataType> other)
{
for (Map.Entry<KeyType, DataType> entry : other.map().entrySet()) {
add(entry.getKey(), entry.getValue());
}
}
public void add(KeyType key, DataType value)
{
assert key != null;
assert value != null;
DataType oldValue = map.put(key, value);
if (oldValue != null) {
list.remove(oldValue);
}
list.add(value);
set.add(value);
}
public boolean remove(KeyType key)
{
assert key != null;
DataType value = map.remove(key);
if (value != null) {
list.remove(value);
set.remove(value);
return true;
}
return false;
}
public boolean removeByData(DataType value)
{
assert value != null;
Set<Map.Entry<KeyType, DataType>> entries = map.entrySet();
for (Map.Entry<KeyType, DataType> entry : entries) {
if (value.equals(entry.getValue())) {
entries.remove(entry);
list.remove(value);
set.remove(value);
return true;
}
}
return false;
}
public Optional<DataType> get(KeyType key)
{
assert key != null;
return Optional.ofNullable(map.get(key));
}
public DataType get(int index)
{
assert index >= 0;
assert index < list.size();
return list.get(index);
}
public boolean contains(KeyType key)
{
assert key != null;
return map.containsKey(key);
}
public boolean containsData(DataType data)
{
assert data != null;
return map.containsValue(data);
}
public Object[] toArray()
{
return list.toArray();
}
public Set<KeyType> keys()
{
return Collections.unmodifiableSet(map.keySet());
}
public Set<DataType> values()
{
return Collections.unmodifiableSet(set);
}
public List<DataType> list()
{
return Collections.unmodifiableList(list);
}
public Map<KeyType, DataType> map()
{
return Collections.unmodifiableMap(map);
}
}
| 22.647727 | 81 | 0.666332 |
7aab3190ff8354dbd8121345d1b63d1476fbff54 | 1,979 | /*
* Copyright 2016 Heng Yuan
*
* 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.yuanheng.cookjson;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.stream.JsonParser;
import javax.json.stream.JsonParserFactory;
/**
* @author Heng Yuan
*/
class JsonParserFactoryImpl implements JsonParserFactory
{
private final Map<String, ?> m_config;
private final ConfigHandler m_handler;
public JsonParserFactoryImpl (Map<String, ?> config, ConfigHandler handler)
{
m_config = config;
m_handler = handler;
}
@Override
public JsonParser createParser (Reader reader)
{
return m_handler.createParser (m_config, reader);
}
@Override
public JsonParser createParser (InputStream is)
{
return m_handler.createParser (m_config, is);
}
@Override
public JsonParser createParser (InputStream is, Charset charset)
{
return m_handler.createParser (m_config, is, charset);
}
@Override
public JsonParser createParser (JsonObject obj)
{
return new JsonStructureParser (obj);
}
@Override
public JsonParser createParser (JsonArray array)
{
return new JsonStructureParser (array);
}
@Override
public Map<String, ?> getConfigInUse ()
{
return Collections.unmodifiableMap (m_config);
}
}
| 25.050633 | 77 | 0.725114 |
366c0e3cdcc4f18410244f8b31b89b51e0eb95a7 | 119 | package swarm.shared.json;
public interface I_ReadsJson
{
void readJson(I_JsonObject json, A_JsonFactory factory);
}
| 17 | 57 | 0.806723 |
7248d05a5920468df1ee150f44cd1346ecb95db2 | 2,439 | package org.pro.ygcms.core.domain.channel;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import org.pro.ygcms.core.domain.CmsAbstractEntity;
/**
* 栏目实体类
* 作者:郭凯
* 时间:2015年7月1日
*/
@Entity
@Table(name = "cms_channel")
public class CmsChannel extends CmsAbstractEntity {
/**
*
*/
private static final long serialVersionUID = 1657136730350104784L;
@Column(name = "channel_path")
private String channelPath;
@Column(name = "has_content")
private int hasContent;
@Column(name = "is_display")
private int isDisplay;
@Column(name = "lft")
private int lft;
@Column(name = "model_id")
private String modelId;
@Column(name = "parent_id")
private String parentId;
@Column(name = "priority")
private int priority;
@Column(name = "rgt")
private int rgt;
@Column(name = "site_id")
private String siteId;
@Column(name = "channel_name")
private String channelName;
public String getChannelName() {
return channelName;
}
public void setChannelName(String channelName) {
this.channelName = channelName;
}
public String getChannelPath() {
return channelPath;
}
public void setChannelPath(String channelPath) {
this.channelPath = channelPath;
}
public int getHasContent() {
return hasContent;
}
public void setHasContent(int hasContent) {
this.hasContent = hasContent;
}
public int getIsDisplay() {
return isDisplay;
}
public void setIsDisplay(int isDisplay) {
this.isDisplay = isDisplay;
}
public int getLft() {
return lft;
}
public void setLft(int lft) {
this.lft = lft;
}
public String getModelId() {
return modelId;
}
public void setModelId(String modelId) {
this.modelId = modelId;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public int getPriority() {
return priority;
}
public void setPriority(int priority) {
this.priority = priority;
}
public int getRgt() {
return rgt;
}
public void setRgt(int rgt) {
this.rgt = rgt;
}
public String getSiteId() {
return siteId;
}
public void setSiteId(String siteId) {
this.siteId = siteId;
}
@Override
public String[] businessKeys() {
// TODO Auto-generated method stub
return null;
}
} | 17.297872 | 68 | 0.664207 |
bf5af3829e270c93f02f69689c3779e78f2ba2e3 | 391 | package com.training.core.mybatis;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Created by ZhenWeiLai on 2016/11/22.
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface DataSourceSwitch {
String targetDataSource() default "";
}
| 24.4375 | 44 | 0.790281 |
40851dc898b91e03b0742a0ba729c368dd21cb67 | 1,146 | package mx.volcanolabs.urmovie.entities;
import java.util.List;
public class MovieDetail {
private Movie movie;
private List<MovieVideo> movieVideos;
private List<MovieReview> movieReviews;
private MovieFavorite movieFavorite;
public MovieDetail() {}
public MovieDetail(Movie movie, MovieFavorite movieFavorite) {
this.movie = movie;
this.movieFavorite = movieFavorite;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public List<MovieVideo> getMovieVideos() {
return movieVideos;
}
public void setMovieVideos(List<MovieVideo> movieVideos) {
this.movieVideos = movieVideos;
}
public List<MovieReview> getMovieReviews() {
return movieReviews;
}
public void setMovieReviews(List<MovieReview> movieReviews) {
this.movieReviews = movieReviews;
}
public MovieFavorite getMovieFavorite() {
return movieFavorite;
}
public void setMovieFavorite(MovieFavorite movieFavorite) {
this.movieFavorite = movieFavorite;
}
}
| 22.92 | 66 | 0.67452 |
f956e413dd7f382e29a9c055a80de53de3770e33 | 19,724 | /*
* Copyright (c) 2009 - 2020 CaspersBox Web Services
*
* 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.cws.esolutions.core.processors.dto;
/*
* Project: eSolutionsCore
* Package: com.cws.esolutions.core.processors.dto
* File: Application.java
*
* History
*
* Author Date Comments
* ----------------------------------------------------------------------------
* cws-khuntly 11/23/2008 22:39:20 Created.
*/
import java.io.File;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import java.io.Serializable;
import java.lang.reflect.Field;
import org.slf4j.LoggerFactory;
import com.cws.esolutions.core.CoreServicesConstants;
import com.cws.esolutions.core.processors.enums.DeploymentType;
/**
* @author cws-khuntly
* @version 1.0
* @see java.io.Serializable
*/
public class Application implements Serializable
{
private double score = 0.0;
private String name = null;
private String guid = null;
private double version = 1.0;
private String scmPath = null;
private String jvmName = null;
private Date onlineDate = null;
private String basePath = null;
private String platform = null;
private String logsPath = null;
private Date offlineDate = null;
private String clusterName = null;
private String installPath = null;
private String pidDirectory = null;
private String logsDirectory = null;
private boolean isScmEnabled = false;
private String applicationGuid = null;
private String applicationName = null;
private File applicationBinary = null;
private String packageLocation = null;
private String packageInstaller = null;
private String installerOptions = null;
private List<Service> platforms = null;
private DeploymentType deploymentType = null;
private static final String CNAME = Application.class.getName();
private static final long serialVersionUID = -7939041322590386615L;
private static final Logger DEBUGGER = LoggerFactory.getLogger(CoreServicesConstants.DEBUGGER);
private static final boolean DEBUG = DEBUGGER.isDebugEnabled();
private static final Logger ERROR_RECORDER = LoggerFactory.getLogger(CoreServicesConstants.ERROR_LOGGER);
public final void setApplicationGuid(final String value)
{
final String methodName = Application.CNAME + "#setApplicationGuid(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.applicationGuid = value;
}
public final void setApplicationName(final String value)
{
final String methodName = Application.CNAME + "#setApplicationName(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.applicationName = value;
}
public final void setPlatform(final String value)
{
final String methodName = Application.CNAME + "#setPlatform(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.platform = value;
}
public final void setApplicationBinary(final File value)
{
final String methodName = Application.CNAME + "#setApplicationBinary(final File value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.applicationBinary = value;
}
public final void setClusterName(final String value)
{
final String methodName = Application.CNAME + "#setClusterName(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.clusterName = value;
}
public final void setBasePath(final String value)
{
final String methodName = Application.CNAME + "#setBasePath(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.basePath = value;
}
public final void setLogsPath(final String value)
{
final String methodName = Application.CNAME + "#setLogsPath(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.logsPath = value;
}
public final void setPidDirectory(final String value)
{
final String methodName = Application.CNAME + "#setPidDirectory(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.pidDirectory = value;
}
public final void setScmPath(final String value)
{
final String methodName = Application.CNAME + "#setScmPath(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.scmPath = value;
}
public final void setJvmName(final String value)
{
final String methodName = Application.CNAME + "#setJvmName(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.jvmName = value;
}
public final void setDeploymentType(final DeploymentType value)
{
final String methodName = Application.CNAME + "#setDeploymentType(final DeploymentType value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.deploymentType = value;
}
public final void setIsScmEnabled(final boolean value)
{
final String methodName = Application.CNAME + "#setIsScmEnabled(final boolean value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.isScmEnabled = value;
}
public final void setScore(final double value)
{
final String methodName = Application.CNAME + "#setScore(final double value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.score = value;
}
public final void setGuid(final String value)
{
final String methodName = Application.CNAME + "#setGuid(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.guid = value;
}
public final void setName(final String value)
{
final String methodName = Application.CNAME + "#setName(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.name = value;
}
public final void setVersion(final double value)
{
final String methodName = Application.CNAME + "#setVersion(final double value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.version = value;
}
public final void setInstallPath(final String value)
{
final String methodName = Application.CNAME + "#setInstallPath(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.installPath = value;
}
public final void setPackageLocation(final String value)
{
final String methodName = Application.CNAME + "#setPackageLocation(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.packageLocation = value;
}
public final void setPackageInstaller(final String value)
{
final String methodName = Application.CNAME + "#setPackageInstaller(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.packageInstaller = value;
}
public final void setInstallerOptions(final String value)
{
final String methodName = Application.CNAME + "#setInstallerOptions(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.installerOptions = value;
}
public final void setLogsDirectory(final String value)
{
final String methodName = Application.CNAME + "#setLogsDirectory(final String value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.logsDirectory = value;
}
public final void setPlatforms(final List<Service> value)
{
final String methodName = Application.CNAME + "#setPlatforms(final List<Service> value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.platforms = value;
}
public final void setOnlineDate(final Date value)
{
final String methodName = Application.CNAME + "#setOnlineDate(final Date value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.onlineDate = value;
}
public final void setOfflineDate(final Date value)
{
final String methodName = Application.CNAME + "#setOfflineDate(final Date value)";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", value);
}
this.offlineDate = value;
}
public final double getScore()
{
final String methodName = Application.CNAME + "#getScore()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.score);
}
return this.score;
}
public final String getGuid()
{
final String methodName = Application.CNAME + "#getGuid()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.guid);
}
return this.guid;
}
public final String getName()
{
final String methodName = Application.CNAME + "#getName()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.name);
}
return this.name;
}
public final String getPackageLocation()
{
final String methodName = Application.CNAME + "#getPackageLocation()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.packageLocation);
}
return this.packageLocation;
}
public final String getPackageInstaller()
{
final String methodName = Application.CNAME + "#getPackageInstaller()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.packageInstaller);
}
return this.packageInstaller;
}
public final String getInstallerOptions()
{
final String methodName = Application.CNAME + "#getInstallerOptions()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.installerOptions);
}
return this.installerOptions;
}
public final String getLogsDirectory()
{
final String methodName = Application.CNAME + "#getLogsDirectory()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.logsDirectory);
}
return this.logsDirectory;
}
public final List<Service> getPlatforms()
{
final String methodName = Application.CNAME + "#getPlatforms()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.platforms);
}
return this.platforms;
}
public final Date getOnlineDate()
{
final String methodName = Application.CNAME + "#getOnlineDate()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.onlineDate);
}
return this.onlineDate;
}
public final Date getOfflineDate()
{
final String methodName = Application.CNAME + "#getOfflineDate()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.offlineDate);
}
return this.offlineDate;
}
public final String getApplicationGuid()
{
final String methodName = Application.CNAME + "#getApplicationGuid()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.applicationGuid);
}
return this.applicationGuid;
}
public final String getApplicationName()
{
final String methodName = Application.CNAME + "#getApplicationName()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.applicationName);
}
return this.applicationName;
}
public final String getPlatform()
{
final String methodName = Application.CNAME + "#getPlatform()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.platform);
}
return this.platform;
}
public final File getApplicationBinary()
{
final String methodName = Application.CNAME + "#getApplicationBinary()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.applicationBinary);
}
return this.applicationBinary;
}
public final double getVersion()
{
final String methodName = Application.CNAME + "#getVersion()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.version);
}
return this.version;
}
public final String getClusterName()
{
final String methodName = Application.CNAME + "#getClusterName()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.clusterName);
}
return this.clusterName;
}
public final String getBasePath()
{
final String methodName = Application.CNAME + "#getBasePath()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.basePath);
}
return this.basePath;
}
public final String getLogsPath()
{
final String methodName = Application.CNAME + "#getLogsPath()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.logsPath);
}
return this.logsPath;
}
public final String getInstallPath()
{
final String methodName = Application.CNAME + "#getInstallPath()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.installPath);
}
return this.installPath;
}
public final String getPidDirectory()
{
final String methodName = Application.CNAME + "#getPidDirectory()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.pidDirectory);
}
return this.pidDirectory;
}
public final String getScmPath()
{
final String methodName = Application.CNAME + "#getScmPath()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.scmPath);
}
return this.scmPath;
}
public final String getJvmName()
{
final String methodName = Application.CNAME + "#getJvmName()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.jvmName);
}
return this.jvmName;
}
public final DeploymentType getDeploymentType()
{
final String methodName = Application.CNAME + "#getDeploymentType()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.deploymentType);
}
return this.deploymentType;
}
public final boolean getIsScmEnabled()
{
final String methodName = Application.CNAME + "#getIsScmEnabled()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.isScmEnabled);
}
return this.isScmEnabled;
}
public final boolean isScmEnabled()
{
final String methodName = Application.CNAME + "#isScmEnabled()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
DEBUGGER.debug("Value: {}", this.isScmEnabled);
}
return this.isScmEnabled;
}
@Override
public final String toString()
{
final String methodName = Application.CNAME + "#toString()";
if (DEBUG)
{
DEBUGGER.debug(methodName);
}
StringBuilder sBuilder = new StringBuilder()
.append("[" + this.getClass().getName() + "]" + CoreServicesConstants.LINE_BREAK + "{" + CoreServicesConstants.LINE_BREAK);
for (Field field : this.getClass().getDeclaredFields())
{
if (DEBUG)
{
DEBUGGER.debug("field: {}", field);
}
if (!(field.getName().equals("methodName")) &&
(!(field.getName().equals("CNAME"))) &&
(!(field.getName().equals("DEBUGGER"))) &&
(!(field.getName().equals("DEBUG"))) &&
(!(field.getName().equals("ERROR_RECORDER"))) &&
(!(field.getName().equals("serialVersionUID"))))
{
try
{
if (field.get(this) != null)
{
sBuilder.append("\t" + field.getName() + " --> " + field.get(this) + CoreServicesConstants.LINE_BREAK);
}
}
catch (IllegalAccessException iax)
{
ERROR_RECORDER.error(iax.getMessage(), iax);
}
}
}
sBuilder.append('}');
if (DEBUG)
{
DEBUGGER.debug("sBuilder: {}", sBuilder);
}
return sBuilder.toString();
}
}
| 25.783007 | 135 | 0.569256 |
6f7f345a8622a94b39cfbd9d4bf8e2cc878502f8 | 2,135 | /*
* (C) Copyright IBM Corp. 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
package com.ibm.watson.assistant.v2.model;
import static org.testng.Assert.*;
import com.ibm.cloud.sdk.core.service.model.FileWithMetadata;
import com.ibm.watson.assistant.v2.utils.TestUtilities;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import org.testng.annotations.Test;
/** Unit test class for the MessageInputOptionsSpelling model. */
public class MessageInputOptionsSpellingTest {
final HashMap<String, InputStream> mockStreamMap = TestUtilities.createMockStreamMap();
final List<FileWithMetadata> mockListFileWithMetadata =
TestUtilities.creatMockListFileWithMetadata();
@Test
public void testMessageInputOptionsSpelling() throws Throwable {
MessageInputOptionsSpelling messageInputOptionsSpellingModel =
new MessageInputOptionsSpelling.Builder().suggestions(true).autoCorrect(true).build();
assertEquals(messageInputOptionsSpellingModel.suggestions(), Boolean.valueOf(true));
assertEquals(messageInputOptionsSpellingModel.autoCorrect(), Boolean.valueOf(true));
String json = TestUtilities.serialize(messageInputOptionsSpellingModel);
MessageInputOptionsSpelling messageInputOptionsSpellingModelNew =
TestUtilities.deserialize(json, MessageInputOptionsSpelling.class);
assertTrue(messageInputOptionsSpellingModelNew instanceof MessageInputOptionsSpelling);
assertEquals(messageInputOptionsSpellingModelNew.suggestions(), Boolean.valueOf(true));
assertEquals(messageInputOptionsSpellingModelNew.autoCorrect(), Boolean.valueOf(true));
}
}
| 45.425532 | 118 | 0.798595 |
0877011f70d20e738b4c808c58a30bf5a34affc6 | 2,470 | package dev.cheerfun.pixivic.biz.web.admin.po;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import dev.cheerfun.pixivic.biz.web.admin.util.JpaConverterJson;
import dev.cheerfun.pixivic.biz.web.collection.po.CollectionTag;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.List;
/**
* @author OysterQAQ
* @version 1.0
* @date 2020/7/29 1:30 下午
* @description Discussion
*/
@Data
@Entity(name = "discussions")
@NoArgsConstructor
@AllArgsConstructor
public class DiscussionPO {
@Id
@Column(name = "discussion_id")
private Integer id;
@Column(name = "section_id")
private Integer sectionId;
private String title;
private String content;
@Column(name = "user_id")
private Integer userId;
private String username;
@Column(name = "total_up")
private Integer totalUp;
@Column(name = "total_down")
private Integer totalDown;
@Column(name = "total_view")
private Integer totalView;
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@Column(name = "create_time")
private LocalDateTime createTime;
@JsonSerialize(using = LocalDateTimeSerializer.class)
@JsonDeserialize(using = LocalDateTimeDeserializer.class)
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
@Column(name = "update_time")
private LocalDateTime updateTime;
@Column(name = "comment_count")
private Integer commentCount;
@Transient
private Integer option;
@Column(name = "tag_list")
@Convert(converter = JpaConverterJson.class)
private List<CollectionTag> tagList;
public DiscussionPO(Integer sectionId, String title, String content, Integer userId, String username, List<CollectionTag> tagList, LocalDateTime now) {
this.sectionId = sectionId;
this.title = title;
this.content = content;
this.userId = userId;
this.username = username;
this.tagList = tagList;
this.createTime = now;
}
}
| 33.378378 | 155 | 0.733603 |
38d68d7a8ec760f9a3e0df9132e386d07e1eefa2 | 3,876 | package org.lyj.ext.html.web.grabber.html;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.lyj.commons.util.StringUtils;
import org.lyj.ext.html.utils.HtmlParserUtil;
import org.lyj.ext.html.web.grabber.CrawlerSettings;
import org.lyj.ext.html.web.grabber.DocItem;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Set;
import java.util.concurrent.Callable;
public class HtmlGrabberTask
implements Callable<DocItem> {
// ------------------------------------------------------------------------
// c o n s t
// ------------------------------------------------------------------------
private static final int TIMEOUT = 60000; // one minute
// ------------------------------------------------------------------------
// f i e l d s
// ------------------------------------------------------------------------
private final CrawlerSettings _settings;
private final DocItem _doc;
// ------------------------------------------------------------------------
// c o n s t r u c t o r
// ------------------------------------------------------------------------
public HtmlGrabberTask(final CrawlerSettings settings,
final URL url,
final int depth) {
_settings = settings;
_doc = new DocItem(url, depth);
}
@Override
public DocItem call() throws Exception {
this.init();
return _doc;
}
// ------------------------------------------------------------------------
// p u b l i c
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// p r i v a t e
// ------------------------------------------------------------------------
private void init() throws Exception {
this.initDocument(Jsoup.parse(_doc.url(), TIMEOUT));
}
private void initDocument(final Document document) {
if (null != document) {
// get links from document
_doc.links().addAll(HtmlParserUtil.getLinks(document, _doc.url()));
_doc.content(HtmlParserUtil.getText(document, _settings.document().autodetectContentThreashold()));
_doc.html(document.outerHtml());
_doc.text(document.text());
final HtmlParserUtil.Microdata microdata = HtmlParserUtil.getMicrodata(document);
_doc.title(microdata.title);
_doc.description(microdata.description);
_doc.image(microdata.image);
if (!StringUtils.hasText(_doc.title())) {
_doc.title(HtmlParserUtil.getTitle(document));
}
if (!StringUtils.hasText(_doc.description())) {
_doc.description(StringUtils.leftStr(_doc.content(), 255, true));
}
if (!StringUtils.hasText(_doc.image())) {
final Set<URL> images = HtmlParserUtil.getImages(document, _doc.url());
if (!images.isEmpty()) {
_doc.image(images.iterator().next().toString());
}
}
}
}
private void processLinks(final Elements links) {
for (Element link : links) {
final String href = link.attr("href");
if (!StringUtils.hasText(href)
|| href.startsWith("#")) {
continue;
}
try {
final URL nextUrl = new URL(_doc.url(), href);
_doc.links().add(nextUrl);
} catch (MalformedURLException ignored) { // ignore bad urls
}
}
}
}
| 34 | 111 | 0.449948 |
e302d676bd2d3111f2900903bb51683ad0104adc | 323 | package xyz.erupt.mybatis.annotation;
import com.baomidou.mybatisplus.core.mapper.Mapper;
import java.lang.annotation.*;
/**
* @author YuePeng
* date 2021/3/12 16:38
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface BindMapper {
Class<? extends Mapper<?>> value();
}
| 17.944444 | 51 | 0.736842 |
aff604845367fe8f332b5538895a4e60806ff128 | 896 | package com.woowle.eggwithtomato.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 集群定时任务配置注解
* @author yuanlong.huang.o
*
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TaskClusterRedisConfig {
/**redis存储对应的key*/
String key() ;
/**key对应的value值*/
String value() default "1";
/**
* 选用第一个redis库存储该key
* spring操作reids不支持切换数据库,
* 如果用的是spring操作reids,该配置不生效
* */
String index() default "0";
/**
* 该key的过期时间,单位秒,过期时间不能超过定时任务的时间间隔
* 过期时间只要大于各个集群节点redis执行setnx的时间和
* 一般可以设置为定时任务的时间间隔减去定时任务的一个时间单位
* 例如:@Scheduled(cron = "0/20 * * * * ?") timeout可以设置为19
* */
int timeout() ;
/**是否允许多节点并发运行 */
boolean isConcurrent() default false;
}
| 20.363636 | 57 | 0.728795 |
5cac499f1ececca21f79a27ae627d767d48c31c2 | 11,830 | package org.mobeho.calendar;
import java.time.LocalDate;
/// <Description>
/// Author: Michael Maimon
/// Copyright (C) Mobeho. All rights reserved.
/// </Description>
public class Christian
{
private int dayOfWeak;
private int dayInMonth;
private int month;
private int dayInYear;
private int year;
private int startYearDayOfWeak;
private int daysFromStart;
private boolean gregorianAge;
static final int DAYS_FROM_BERESHIT_TO_1900 = 2067023;
public Christian(boolean from19000101)
{
if (from19000101)
reset(DAYS_FROM_BERESHIT_TO_1900);
else
reset(0);
}
protected boolean reset(int daysFromStart)
{
if (daysFromStart >= this.daysFromStart && this.daysFromStart > 0)
return false;
if (daysFromStart >= DAYS_FROM_BERESHIT_TO_1900)
{
this.dayInYear = 1;
this.dayInMonth = 1;
this.month = 1;
this.year = 1900;
this.dayOfWeak = 2;
this.startYearDayOfWeak = 2;
this.daysFromStart = 2067023;
this.gregorianAge = true;
}
else
{
this.dayInYear = 280;
this.dayInMonth = 7;
this.month = 10;
this.year = -3761;
this.dayOfWeak = 2;
this.startYearDayOfWeak = 2;
this.daysFromStart = 0;
this.gregorianAge = false;
}
return true;
}
public boolean set(int year, int month, int day)
{
if (month < 1 || month > 12 || day < 1 || day > 31)
return false;
if (!getIfLeapYear(year) && month == 2 && day > 28)
return false;
if (year < getYear() || (year == getYear() && month < getMonth()) || (year == getYear() && month == getMonth() && day < getDay()))
{
if (year >= 1900 && month >= 1)
reset(DAYS_FROM_BERESHIT_TO_1900);
else
reset(0);
}
while (getDay() != 1 && getYear() < year) addDays(1);
while (getMonth() != 1 && getYear() < year) addMonths(1);
while (getYear() < year) addYears(1);
while (getMonth() < month && getMonth() < getNumberOfMonths()) addMonths(1);
if (day > getNumberDaysInMonth())
return false;
while (getDay() < day && getDay() < getNumberDaysInMonth()) addDays(1);
return true;
}
public boolean isLeapYear()
{
return getIfLeapYear(this.year);
}
public boolean getIfLeapYear(int someYear)
{
if (!this.gregorianAge)
{
return someYear != 0 && someYear % 4 == 0;
}
else
{
// Every year divisible by 4 is a leap year.
// But every year divisible by 100 is NOT a leap year
// Unless the year is also divisible by 400, then it is still a leap year.
return someYear % 4 == 0 && (someYear % 100 != 0 || someYear % 400 == 0);
}
}
public boolean isGregorianAge()
{
if (this.year > 1582) return true;
else if (this.year < 1582) return false;
// in year 1582
if (this.month > 10) return true;
else if (this.month < 10) return false;
// in month 10
if (this.dayInMonth > 4) return true;
else if (this.dayInMonth < 4) return false;
return false;
}
private void setGregorianAge()
{
if (!this.gregorianAge && isGregorianAge())
{
// Just once
this.gregorianAge = true;
if (this.year == 1582 && this.month == 10 && (this.dayInMonth > 4 && this.dayInMonth < 15))
{
adv(10);
this.dayInYear = adv(this.dayInYear, getNumberOfMonths(), 10);
}
else
{
this.daysFromStart -= 10;
this.dayOfWeak = adv(this.dayOfWeak, 7, -10);
}
}
}
private int getFebruaryLength()
{
if (isLeapYear())
return 29;
else
return 28;
}
private int shift(int val, int bas, int add)
{
return ((val + --add) / bas);
}
private int adv(int val, int bas, int add)
{
val = ((val + --add) % bas + 1);
if (val == 0)
{
if (add < -1) val = bas;
else if (add > -1) val = 1;
}
return val;
}
public void addDays(int days)
{
int daysFromStart = this.daysFromStart;
if (reset(this.daysFromStart + days))
days += daysFromStart - this.daysFromStart;
if (days < 0)
return;
// max days in _year
while (days > 366)
{
days += this.daysFromStart;
addYears(1);
days -= this.daysFromStart;
}
// max days in _month
while (days > 31)
{
days += this.daysFromStart;
addMonths(1);
days -= this.daysFromStart;
}
// prevent from across two months
if ((days + this.dayInMonth) / getNumberDaysInMonth() > 1 && days > 28)
{
days -= 28;
this.daysFromStart += 28;
this.dayInYear = adv(this.dayInYear, getNumberDaysInYear(), 28);
this.dayInYear = ((this.dayInYear + 28) % getNumberDaysInYear());
adv(28);
}
//The next lines order is important
this.daysFromStart += days;
this.dayInYear = adv(this.dayInYear, getNumberDaysInYear(), days);
this.dayOfWeak = adv(this.dayOfWeak, 7, days);
this.startYearDayOfWeak = (this.dayOfWeak);
adv(days);
setGregorianAge();
if (this.dayInMonth > getNumberDaysInMonth())
adv(0);
}
public void addMonths(int months)
{
if (months <= 0)
return;
while (months > getNumberOfMonths())
{
months -= getNumberOfMonths();
addYears(1);
}
while (months-- > 0)
{
this.daysFromStart += getNumberDaysInMonth();
this.dayInYear = adv(this.dayInYear, getNumberDaysInYear(), getNumberDaysInMonth());
this.dayOfWeak = adv(this.dayOfWeak, 7, getNumberDaysInMonth());
this.startYearDayOfWeak = this.dayOfWeak;
int shift = shift(this.month, getNumberOfMonths(), 1);
this.month = adv(this.month, getNumberOfMonths(), 1);
this.year = adv(this.year, 100000, shift);
setGregorianAge();
}
if (this.dayInMonth > getNumberDaysInMonth())
adv(0);
}
public void addYears(int years)
{
if (years <= 0)
return;
for (; years > 0; years--)
{
int numbersDaysToAdd = getNumberDaysInYear() + addMonthTuning(getIfLeapYear(this.year), getIfLeapYear(this.year + 1));
this.daysFromStart += numbersDaysToAdd;
this.dayInYear = adv(this.dayInYear, getNumberDaysInYear(), numbersDaysToAdd);
this.dayOfWeak = adv(this.dayOfWeak, 7, numbersDaysToAdd);
this.startYearDayOfWeak = this.dayOfWeak;
this.year = adv(this.year, 100000, 1);
setGregorianAge();
}
if (this.dayInMonth > getNumberDaysInMonth())
adv(0);
}
private void adv(int adding)
{
int shiftMonth = shift(this.dayInMonth, getNumberDaysInMonth(), adding);
this.dayInMonth = adv(this.dayInMonth, getNumberDaysInMonth(), adding);
int shiftYear = shift(this.month, getNumberOfMonths(), shiftMonth);
this.month = adv(this.month, getNumberOfMonths(), shiftMonth);
this.year = adv(this.year, 100000, shiftYear);
}
/// 1 2 3 4 5 6 7 8 9 10 11 12
/// N 31 28 31 30 31 30 31 31 30 31 30 31 365
/// P 31 29 31 30 31 30 31 31 30 31 30 31 366
///
/// n->p
/// 1 31 28 31 30 31 30 31 31 30 31 30 31 365 0
/// 2 28 31 30 31 30 31 31 30 31 30 31 31 365 0
/// 3 31 30 31 30 31 31 30 31 30 31 31 29 366 +1
/// 4 30 31 30 31 31 30 31 30 31 31 29 31 366 +1
/// 5 31 30 31 31 30 31 30 31 31 29 31 30 366 +1
/// 6 30 31 31 30 31 30 31 31 29 31 30 31 366 +1
/// 7 31 31 30 31 30 31 31 29 31 30 31 30 366 +1
///
/// 1 2 3 4 5 6 7 8 9 10 11 12
/// P 31 29 31 30 31 30 31 31 30 31 30 31 366
/// N 31 28 31 30 31 30 31 31 30 31 30 31 365
///
/// p->n
/// 1 31 29 31 30 31 30 31 31 30 31 30 31 366 0
/// 2 29 31 30 31 30 31 31 30 31 30 31 31 366 0
/// 3 31 30 31 30 31 31 30 31 30 31 31 28 365 -1
/// 4 30 31 30 31 31 30 31 30 31 31 28 31 365 -1
/// 5 31 30 31 31 30 31 30 31 31 28 31 30 365 -1
/// 6 30 31 31 30 31 30 31 31 28 31 30 31 365 -1
/// 7 31 31 30 31 30 31 31 28 31 30 31 30 365 -1
private int addMonthTuning(boolean fromYear, boolean toYear)
{
if (!fromYear)
{
if (toYear)
{
if (this.month >= 3) return +1;
}
}
else
{
if (!toYear)
{
if (this.month >= 3) return -1;
}
}
return 0;
}
String[] weakDayStrings = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
String[] monthStrings = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
int getNumberDaysInMonth()
{
switch (this.month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 12:
return 31;
case 2:
return getFebruaryLength();
case 4:
case 6:
case 9:
case 11:
return 30;
case 10:
if (this.year == 1582)
return 21;
else
return 31;
}
return -1;
}
String[] getDaysOfMonthString()
{
String[] days = new String[getNumberDaysInMonth()];
for (int index = 1; index <= getNumberDaysInMonth(); index++)
days[index - 1] = String.valueOf(index);
return days;
}
public LocalDate getLocalDate()
{
if (this.year < 1)
return null;
return LocalDate.of(this.year, this.month, this.dayInMonth);
}
//Properties
public int getDay()
{
return this.dayInMonth;
}
public String getDayString()
{
return String.valueOf(this.dayInMonth);
}
public int getDayOfWeak()
{
return this.dayOfWeak;
}
public String getDayOfWeakString()
{
return weakDayStrings[this.dayOfWeak - 1];
}
public int getMonth()
{
return this.month;
}
public String getMonthString()
{
return monthStrings[this.month - 1];
}
public int getYear()
{
return this.year;
}
int getNumberOfMonths()
{
return 12;
}
private int getNumberDaysInYear()
{
return getFebruaryLength() + 4 * 30 + 7 * 31;
}
int getDaysInYear()
{
return getFebruaryLength() + 4 * 30 + 7 * 31-((this.year==1582)?10:0);
}
public int getChrisNumberOfWeeks()
{
return (getStartYearDayOfYear() + getNumberDaysInYear()) / 7;
}
public int getDaysFromStart()
{
return this.daysFromStart;
}
public int getDayInYear()
{
return this.dayInYear;
}
public int getStartYearDayOfYear()
{
return this.startYearDayOfWeak;
}
public String toString() {
return String.format("%02d/%02d/%04d", this.dayInMonth, this.month, this.year);
}
}
| 27.835294 | 138 | 0.52071 |
718d640d7095c72a87181a83b4a15d6dcf75e177 | 7,715 | package bluetooth.servidor;
import java.io.DataInputStream;
import java.io.IOException;
import java.util.Vector;
import javax.bluetooth.RemoteDevice;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import org.bouncycastle.util.encoders.Base64;
/**
* contem metodos de recepcao de dados, execucao de mensagens de protocolo
* escuta e tratamento de ligacoes.
*/
public class Servidor {
/**
* UUID do servido oferecido
*/
private String UUID_SERVICO = "9856";
/**
* o nome do servidor
*/
private String NOME_SERVIDOR = "bluetooth_at_ispgaya";
/**
* para aceitar ligacoes ao servidor e ao servido oferecido
*/
private StreamConnectionNotifier service;
/**
* Vector que contem objectos do tipo Cliente.
* cada entrada corresponde a um cliente ligado...
*/
private Vector<Cliente> listaClientes = new Vector<Cliente>();
private LDAP ldap = new LDAP();
/**
* inicia o servidor
* @throws java.io.IOException se ocorrer algum erro na criacao do servidor.
* talvez nao haja nenhum dispositivo bluetooth ligado...
*/
public void iniciar() throws IOException {
ldap.ligar();
service = (StreamConnectionNotifier)Connector.open("btspp://localhost:" + UUID_SERVICO + ";name=" + NOME_SERVIDOR);
new Thread() {
public void run() {
escutarLigacoes();
}
}.start();
}
/**
* desliga o servidor
*/
public void terminar() {
try {
service.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* fica a espera de ligacoes ao servidor
*/
private void escutarLigacoes() {
StreamConnection conn;
while(true) {
try {
System.out.println("# a escutar...");
conn = service.acceptAndOpen();
ligacaoRecebida(conn);
}catch(IOException ex) {
ex.printStackTrace();
break;
}
}
}
/**
* quando e recebida uma ligacao temos que adicionar o cliente que se ligou
* ao Vector e abrir os streams de comunicacao
* @param sc o stream onde foi recebida a ligacao
*/
private void ligacaoRecebida(StreamConnection sc) {
try {
RemoteDevice rd = RemoteDevice.getRemoteDevice(sc);
Cliente cliente = new Cliente();
// o meu dispositivo
cliente.setDispRemoto(rd);
// stream para recepcao de dados do dispositivo
cliente.setInputStream(sc.openDataInputStream());
// stream para envio de dados para o dispositivo
cliente.setOutputStream(sc.openDataOutputStream());
// o endereco bluetooth do dispositivo
cliente.setEnderecoBluetooth(rd.getBluetoothAddress());
// o nome do dispositivo
cliente.setNomeBluetooth(rd.getFriendlyName(false));
// stream
cliente.setStream(sc);
listaClientes.add(cliente);
System.out.println("# " + cliente.getNomeBluetooth() + "[" + cliente.getEnderecoBluetooth() + "], ligou-se ao servidor...");
// iniciar a recepcao de dados para o cliente que acabou de entrar
new Thread() {
public void run() {
receberDados(listaClientes.elementAt(listaClientes.size() - 1));
}
}.start();
} catch(IOException ex) {
ex.printStackTrace();
}
}
/**
* receber dados de um cliente no seu DataInputStream
* @param cliente o cliente do qual recebemos os dados
*/
private void receberDados(Cliente cliente){
DataInputStream inputStream = cliente.getInputStream();
String msg;
try {
while((msg = inputStream.readUTF()) != null) {
msg = Seguranca.desencriptar(msg, cliente.getKey());
if(msg.length() == 2 && Integer.parseInt(msg) == Protocolo.OP_LOGOUT) {
break;
} else {
executarAccao(Protocolo.getAccao(msg), msg, cliente);
}
}
} catch(IOException ex) {
//ex.printStackTrace();
}
desligarCliente(cliente);
}
/**
* desliga um cliente do servidor e remove-o do Vector de Clientes
* @param cliente o cliente a desligar
*/
private void desligarCliente(Cliente cliente) {
System.out.println("# " + cliente.getNomeBluetooth() + ", terminou a ligacao ao servidor...");
cliente.desligar();
listaClientes.removeElement(cliente);
}
/**
* executa uma determinada accao de protocolo.
*
* as unicas mensagens que o cliente pode enviar para o servidor sao:
* # Protocolo.OP_AUTENTICACAO - autenticar
* # Protocolo.OP_BUSCAR_MAIL - buscar o mail da inbox
* # Protocolo.OP_ENVIAR_MAIL - enviar um email
* # Protocolo.OP_LOGOUT - terminar a ligacao com o servidor
* @param accao a accao a realizar
* @param msg a mensagem de protocolo recebida
* @param cliente o cliente que executou a accao
*/
private void executarAccao(int accao, String msg, Cliente cliente) {
System.out.println("$ " + cliente.getNomeBluetooth() + ", quer: " + Protocolo.getNomeAccao(accao));
if(accao == Protocolo.OP_AUTENTICACAO) {
String username = Protocolo.getNomeUtilizador(msg);
String password = Protocolo.getPassword(msg);
int ret = ldap.autenticar(username, password);
if(ret == Protocolo.OK_AUTENTICACAO_OK) {
cliente.setPassword(password);
cliente.setNomeUtilizador(username);
cliente.setNomeMail(username + Mail.MAIL_DOMINIO);
}
// na mensagem de autenticacao tambem vai incluido a classe do
// dispositivo que e filtrada aqui
try {
int len = msg.length();
int tipo = Integer.parseInt(msg.substring(len - 3));
cliente.setClasseDispositivo(tipo);
} catch(NumberFormatException ex) {
}
cliente.enviarDados(String.valueOf(ret));
} else if(accao == Protocolo.OP_BUSCAR_MAIL) {
String mails = Mail.buscarMail(cliente.getNomeUtilizador(), cliente.getPassword(), Protocolo.getData(msg));
System.out.println();
if(mails.length() == 0) {
cliente.enviarDados(String.valueOf(Protocolo.ERRO_NAO_TEM_MAILS_NOVOS));
} else {
cliente.enviarDados(String.valueOf(Protocolo.OK_RECEBER_MAIL) + mails);
}
} else if(accao == Protocolo.OP_ENVIAR_MAIL) {
String por = cliente.getNomeMail();
String para = Protocolo.getMailPara(msg);
String assunto = Protocolo.getAssunto(msg);
String texto = Protocolo.getTexto(msg);
int ret = Mail.enviarMail(por, para, assunto, texto);
cliente.enviarDados(String.valueOf(ret));
}
}
} | 34.596413 | 136 | 0.560207 |
13a219921deb11cc572cad2a726eb8ccd3768fa9 | 8,511 | /*
* Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available.
*
* Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
*
* BK-BASE 蓝鲸基础平台 is licensed under the MIT License.
*
* License for BK-BASE 蓝鲸基础平台:
* --------------------------------------------------------------------
* 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.tencent.bk.base.dataflow.flink.streaming.topology;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.tencent.bk.base.dataflow.flink.streaming.topology.FlinkStreamingTopology.FlinkStreamingBuilder;
import java.util.Map;
import org.junit.Test;
public class TestFlinkStreamingTopology {
@Test
public void testIsFileSystemState() {
assertFalse(getFlinkStreamingTopology().isFileSystemState());
assertEquals("Asia/Shanghai", getFlinkStreamingTopology().getTimeZone());
assertNull(getFlinkStreamingTopology().getGeogAreaCode());
}
/**
* 获取测试需要使用的 {@link FlinkStreamingTopology}
*
* @return {@link FlinkStreamingTopology}的测试实例
*/
public static FlinkStreamingTopology getFlinkStreamingTopology() {
Map<String, Object> parameters = ImmutableMap.<String, Object>builder()
.put("job_id", "test_job_id")
.put("job_name", "test_job_name")
.put("job_type", "flink")
.put("run_mode", "product")
.put("time_zone", "Asia/Shanghai")
.put("chain", "enable")
.put("metric", ImmutableMap.<String, String>builder()
.put("metric_kafka_server", "metric kafka server")
.put("metric_kafka_topic", "metric kafka topic")
.build())
.put("checkpoint", ImmutableMap.<String, Object>builder()
.put("checkpoint_redis_sentinel_port", 0)
.put("checkpoint_redis_port", 50000)
.put("state_backend", "rocksdb")
.put("checkpoint_redis_host", "redis host")
.put("manager", "redis")
.put("start_position", "continue")
.put("state_checkpoints_dir", "checkpoint dir")
.put("checkpoint_redis_password", "redis password")
.put("checkpoint_interval", 600000)
.build())
.put("nodes", ImmutableMap.<String, Object>builder()
.put("source", generateSourceNodeInfo())
.put("transform", generateTransformNodeInfo())
.build())
.build();
return new FlinkStreamingBuilder(parameters).build();
}
private static Map<String, Object> generateTransformNodeInfo() {
return ImmutableMap.<String, Object>builder()
.put("1_test_join_transform", ImmutableMap.<String, Object>builder()
.put("id", "1_test_join_transform")
.put("name", "test_join_transform")
.put("processor", ImmutableMap.of("processor_type", "join_transform",
"processor_args", "{\"first\":\"1_first\",\"second\":\"1_second\","
+ "\"type\":\"right\",\"join_keys\":"
+ "[{\"first\":\"first_key\",\"second\":\"second_key\"}]}"))
.put("parents", ImmutableList.of("1_first", "1_second"))
.put("window", ImmutableMap.of("count_freq", 60,
"allowed_lateness", false, "type", "tumbling"))
.put("fields", ImmutableList.<Map<String, Object>>builder()
.add(ImmutableMap.of("field", "dtEventTime", "type", "string",
"origin", "", "description", "event time"))
.add(ImmutableMap.of("field", "_startTime_", "type", "string",
"origin", "", "description", "event time"))
.add(ImmutableMap.of("field", "_endTime_", "type", "string",
"origin", "", "description", "event time"))
.add(ImmutableMap.of("field", "a", "type", "string",
"origin", "1_first:a", "description", "a"))
.add(ImmutableMap.of("field", "b", "type", "string",
"origin", "1_second:b", "description", "b"))
.build())
.build())
.build();
}
private static Map<String, Object> generateSourceNodeInfo() {
return ImmutableMap.<String, Object>builder()
.put("1_first", ImmutableMap.<String, Object>builder()
.put("id", "1_first")
.put("name", "first")
.put("input", ImmutableMap.of("type", "kafka", "cluster_port", 9092,
"cluster_domain", "domain"))
.put("fields", ImmutableList.<Map<String, Object>>builder()
.add(ImmutableMap.of("field", "dtEventTime", "type", "string",
"origin", "", "description", "event time"))
.add(ImmutableMap.of("field", "bkdata_par_offset", "type", "string",
"origin", "", "description", "bkdata_par_offset"))
.add(ImmutableMap.of("field", "first_key", "type", "string",
"origin", "", "description", "first key"))
.add(ImmutableMap.of("field", "a", "type", "string",
"origin", "", "description", "a"))
.build())
.build())
.put("1_second", ImmutableMap.<String, Object>builder()
.put("id", "1_second")
.put("name", "second")
.put("input", ImmutableMap.of("type", "kafka", "cluster_port", 9092,
"cluster_domain", "domain"))
.put("fields", ImmutableList.<Map<String, Object>>builder()
.add(ImmutableMap.of("field", "dtEventTime", "type", "string",
"origin", "", "description", "event time"))
.add(ImmutableMap.of("field", "bkdata_par_offset", "type", "string",
"origin", "", "description", "bkdata_par_offset"))
.add(ImmutableMap.of("field", "second_key", "type", "string",
"origin", "", "description", "second key"))
.add(ImmutableMap.of("field", "b", "type", "string",
"origin", "", "description", "b"))
.build())
.build())
.build();
}
}
| 57.897959 | 114 | 0.513453 |
f9e875d4d646bbe288a636c9a2337939d5f608a9 | 3,792 | package com.google.android.gms.games.achievement;
import android.database.CharArrayBuffer;
import android.net.Uri;
import android.os.Parcel;
import com.google.android.gms.common.data.C0705d;
import com.google.android.gms.common.data.DataHolder;
import com.google.android.gms.games.Player;
import com.google.android.gms.games.PlayerRef;
import com.google.android.gms.internal.C1742je;
import com.google.android.gms.plus.PlusShare;
public final class AchievementRef extends C0705d implements Achievement {
AchievementRef(DataHolder dataHolder, int i) {
super(dataHolder, i);
}
public int describeContents() {
return 0;
}
public Achievement freeze() {
return new AchievementEntity(this);
}
public String getAchievementId() {
return getString("external_achievement_id");
}
public int getCurrentSteps() {
boolean z = true;
if (getType() != 1) {
z = false;
}
C1742je.m5152K(z);
return getInteger("current_steps");
}
public String getDescription() {
return getString(PlusShare.KEY_CONTENT_DEEP_LINK_METADATA_DESCRIPTION);
}
public void getDescription(CharArrayBuffer charArrayBuffer) {
mo11079a(PlusShare.KEY_CONTENT_DEEP_LINK_METADATA_DESCRIPTION, charArrayBuffer);
}
public String getFormattedCurrentSteps() {
boolean z = true;
if (getType() != 1) {
z = false;
}
C1742je.m5152K(z);
return getString("formatted_current_steps");
}
public void getFormattedCurrentSteps(CharArrayBuffer charArrayBuffer) {
boolean z = true;
if (getType() != 1) {
z = false;
}
C1742je.m5152K(z);
mo11079a("formatted_current_steps", charArrayBuffer);
}
public String getFormattedTotalSteps() {
boolean z = true;
if (getType() != 1) {
z = false;
}
C1742je.m5152K(z);
return getString("formatted_total_steps");
}
public void getFormattedTotalSteps(CharArrayBuffer charArrayBuffer) {
boolean z = true;
if (getType() != 1) {
z = false;
}
C1742je.m5152K(z);
mo11079a("formatted_total_steps", charArrayBuffer);
}
public long getLastUpdatedTimestamp() {
return getLong("last_updated_timestamp");
}
public String getName() {
return getString("name");
}
public void getName(CharArrayBuffer charArrayBuffer) {
mo11079a("name", charArrayBuffer);
}
public Player getPlayer() {
return new PlayerRef(this.f790JG, this.f791KZ);
}
public Uri getRevealedImageUri() {
return mo11081aR("revealed_icon_image_uri");
}
public String getRevealedImageUrl() {
return getString("revealed_icon_image_url");
}
public int getState() {
return getInteger("state");
}
public int getTotalSteps() {
boolean z = true;
if (getType() != 1) {
z = false;
}
C1742je.m5152K(z);
return getInteger("total_steps");
}
public int getType() {
return getInteger("type");
}
public Uri getUnlockedImageUri() {
return mo11081aR("unlocked_icon_image_uri");
}
public String getUnlockedImageUrl() {
return getString("unlocked_icon_image_url");
}
public long getXpValue() {
return getLong((!mo11080aQ("instance_xp_value") || mo11082aS("instance_xp_value")) ? "definition_xp_value" : "instance_xp_value");
}
public String toString() {
return AchievementEntity.m2076b(this);
}
public void writeToParcel(Parcel parcel, int i) {
((AchievementEntity) freeze()).writeToParcel(parcel, i);
}
}
| 26.333333 | 138 | 0.632648 |
58eb4357610274c4b0d16a511536d4c67d608cf6 | 892 | package LabExercise11;
import java.util.ArrayList;
import java.util.Scanner;
public class RemoveDuplicate {
public static void removeDuplicate(ArrayList list) {
for (int i = 0; i < list.size(); i++) {
for (int j = i + 1; j < list.size(); j++) {
if (list.get(i).equals(list.get(j))) {
list.remove(j);
}
}
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
System.out.print("Enter 10 integers: ");
for (int i = 0; i < 10; i++) {
list.add(input.next());
}
removeDuplicate(list);
System.out.print("The distinct integers are ");
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i) + " ");
}
}
}
| 28.774194 | 56 | 0.503363 |
8d4faad9ebf6ebcd3c8b8dd800a997c1f43acd08 | 214 | package org.streetjava.lesson.helloworld;
/**
*
* @author dungld
*/
public class Teacher implements Test{
@Override
public void testLanguage(Sayable sayable) {
sayable.sayHello();
}
}
| 14.266667 | 47 | 0.649533 |
c9209ee54571f600dc14668dcdb91f13a63a1e8f | 17,903 | // $Id: SHA1.java,v 1.1 2002/09/05 19:27:06 baford Exp $
//
// $Log: SHA1.java,v $
// Revision 1.1 2002/09/05 19:27:06 baford
// Put together the on-line source code and examples page for the thesis.
//
// Revision 1.1 2002/09/02 20:14:03 baford
// Copied test suite from ICFP paper directory
//
// Revision 1.1 2002/07/25 18:30:31 baford
// Added more files from cryptix32-20001002-r3.2.0/src
// to increase the size of the test suite a bit
//
// Revision 1.7 1999/07/13 18:13:22 edwin
// Fixed cloning.
// This is a fix to: http://130.89.235.121/root/cryptix/old/cryptix/FAQ.html#bj_blockmessagedigest_clone
//
// Revision 1.6 1998/01/05 01:33:59 iang
// BUG: missing the engineUpdate() method.
//
// Revision 1.5 1997/12/19 05:44:13 hopwood
// + Committed changes below.
//
// Revision 1.4.1 1997/12/19 hopwood
// + Added URL for FIPS 180-1.
//
// Revision 1.4 1997/12/16 21:58:25 iang
// + MD5, SHA{01} debugged, got working, internal self_tests ok.
// + BlockMessageDigest.bitcount() made long, was int, check calling
// where it is assumed by digest algorithms to be a long.
//
// Revision 1.3 1997/12/07 07:25:29 hopwood
// + Committed changes below.
//
// Revision 1.2.1 1997/11/30 hopwood
// + Added references in documentation.
//
// Revision 1.2 1997/11/20 19:36:30 hopwood
// + cryptix.util.* name changes.
//
// Revision 1.1.1.1 1997/11/03 22:36:56 hopwood
// + Imported to CVS (tagged as 'start').
//
// Revision 0.3.0.0 1997/08/15 David Hopwood
// + Renamed to SHA1 (from SHA), and moved to cryptix.provider.md
// package.
// + This class is now a pure JCA MessageDigest.
//
// Revision 0.2.5.1 1997/03/15 Jill Baker
// + Moved this file here from old namespace.
//
// Revision 0.2.5.0 1997/02/24 Original Author not stated
// + Original version.
//
// $Endlog$
/*
* Copyright (c) 1995-1997 Systemics Ltd
* on behalf of the Cryptix Development Team. All rights reserved.
*/
package cryptix.provider.md;
import java.io.PrintWriter;
import java.security.MessageDigest;
import cryptix.util.core.Debug;
import cryptix.util.core.Hex;
/**
* This class implements the SHA-1 message digest algorithm.
* <p>
* <b>BUG</b>: The update method is missing.
* <p>
* <b>References:</b>
* <ol>
* <li> Bruce Schneier,
* "Section 18.7 Secure Hash Algorithm (SHA),"
* <cite>Applied Cryptography, 2nd edition</cite>,
* John Wiley & Sons, 1996
* <p>
* <li> NIST FIPS PUB 180-1,
* "Secure Hash Standard",
* U.S. Department of Commerce, May 1993.<br>
* <a href="http://www.itl.nist.gov/div897/pubs/fip180-1.htm">
* http://www.itl.nist.gov/div897/pubs/fip180-1.htm</a>
* </ol>
* <p>
* <b>Copyright</b> © 1995-1997
* <a href="http://www.systemics.com/">Systemics Ltd</a> on behalf of the
* <a href="http://www.systemics.com/docs/cryptix/">Cryptix Development Team</a>.
* <br>All rights reserved.
* <p>
* <b>$Revision: 1.1 $</b>
* @author Systemics Ltd
* @author David Hopwood
* @since Cryptix 2.2.2
*/
public final class SHA1
extends BlockMessageDigest
implements Cloneable
{
// Debugging methods and vars.
//...........................................................................
private static final boolean DEBUG = Debug.GLOBAL_DEBUG;
private static final boolean DEBUG_SLOW = Debug.GLOBAL_DEBUG_SLOW;
private static final int debuglevel = DEBUG ? Debug.getLevel("SHA-1") : 0;
private static final PrintWriter err = DEBUG ? Debug.getOutput() : null;
private static void debug(String s) { err.println("SHA-1: " + s); }
// SHA-1 constants and variables
//...........................................................................
/**
* Length of the final hash (in bytes).
*/
private static final int HASH_LENGTH = 20;
/**
* Length of a block (i.e. the number of bytes hashed in every transform).
*/
private static final int DATA_LENGTH = 64;
private int[] data;
private int[] digest;
private byte[] tmp;
private int[] w;
/**
* Returns the length of the hash (in bytes).
*/
protected int engineGetDigestLength() {
return HASH_LENGTH;
}
/**
* Returns the length of the data (in bytes) hashed in every transform.
*/
protected int engineGetDataLength()
{
return DATA_LENGTH;
}
/**
* Constructs a SHA-1 message digest.
*/
public SHA1()
{
super("SHA-1");
java_init();
reset();
}
private void java_init()
{
digest = new int[HASH_LENGTH/4];
data = new int[DATA_LENGTH/4];
tmp = new byte[DATA_LENGTH];
w = new int[80];
}
/**
* This constructor is here to implement cloneability of this class.
*/
private SHA1 (SHA1 md) {
this();
data = (int[])md.data.clone();
digest = (int[])md.digest.clone();
tmp = (byte[])md.tmp.clone();
w = (int[])md.w.clone();
}
/**
* Returns a copy of this MD object.
*/
public Object clone() { return new SHA1(this); }
/**
* Initializes (resets) the message digest.
*/
protected void engineReset()
{
super.engineReset();
java_reset();
}
private void java_reset()
{
digest[0] = 0x67452301;
digest[1] = 0xefcdab89;
digest[2] = 0x98badcfe;
digest[3] = 0x10325476;
digest[4] = 0xc3d2e1f0;
}
/**
* Adds data to the message digest.
*
* @param data The data to be added.
* @param offset The start of the data in the array.
* @param length The amount of data to add.
*/
protected void engineTransform(byte[] in)
{
java_transform(in);
}
private void java_transform(byte[] in)
{
byte2int(in, 0, data, 0, DATA_LENGTH/4);
transform(data);
}
/**
* Returns the digest of the data added and resets the digest.
* @return the digest of all the data added to the message digest as a byte array.
*/
protected byte[] engineDigest(byte[] in, int length)
{
byte b[] = java_digest(in, length);
engineReset();
return b;
}
private byte[] java_digest(byte[] in, int pos)
{
if (pos != 0) System.arraycopy(in, 0, tmp, 0, pos);
tmp[pos++] = (byte)0x80;
if (pos > DATA_LENGTH - 8)
{
while (pos < DATA_LENGTH)
tmp[pos++] = 0;
byte2int(tmp, 0, data, 0, DATA_LENGTH/4);
transform(data);
pos = 0;
}
while (pos < DATA_LENGTH - 8)
tmp[pos++] = 0;
byte2int(tmp, 0, data, 0, (DATA_LENGTH/4)-2);
// Big endian
// WARNING: int>>>32 != 0 !!!
// bitcount() used to return a long, now it's an int.
long bc = bitcount();
data[14] = (int) (bc>>>32);
data[15] = (int) bc;
transform(data);
byte buf[] = new byte[HASH_LENGTH];
// Big endian
int off = 0;
for (int i = 0; i < HASH_LENGTH/4; ++i) {
int d = digest[i];
buf[off++] = (byte) (d>>>24);
buf[off++] = (byte) (d>>>16);
buf[off++] = (byte) (d>>>8);
buf[off++] = (byte) d;
}
return buf;
}
// SHA-1 transform routines
//...........................................................................
private static int f1(int a, int b, int c) { return (c^(a&(b^c))) + 0x5A827999; }
private static int f2(int a, int b, int c) { return (a^b^c) + 0x6ED9EBA1; }
private static int f3(int a, int b, int c) { return ((a&b)|(c&(a|b))) + 0x8F1BBCDC; }
private static int f4(int a, int b, int c) { return (a^b^c) + 0xCA62C1D6; }
private void transform (int[] X)
{
int A = digest[0];
int B = digest[1];
int C = digest[2];
int D = digest[3];
int E = digest[4];
if (DEBUG && debuglevel > 5) debug("A="+A+" B="+B+" C="+C+" D="+D+" E="+E);
int W[] = w;
for (int i=0; i<16; i++)
{
W[i] = X[i];
if (DEBUG && debuglevel > 8) debug(" " + i + "=" + X[i]);
}
for (int i=16; i<80; i++)
{
int j = W[i-16] ^ W[i-14] ^ W[i-8] ^ W[i-3];
W[i] = j;
W[i] = (j << 1) | (j >>> -1);
}
E += ((A << 5)|(A >>> -5)) + f1(B, C, D) + W[0]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f1(A, B, C) + W[1]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f1(E, A, B) + W[2]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f1(D, E, A) + W[3]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f1(C, D, E) + W[4]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f1(B, C, D) + W[5]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f1(A, B, C) + W[6]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f1(E, A, B) + W[7]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f1(D, E, A) + W[8]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f1(C, D, E) + W[9]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f1(B, C, D) + W[10]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f1(A, B, C) + W[11]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f1(E, A, B) + W[12]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f1(D, E, A) + W[13]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f1(C, D, E) + W[14]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f1(B, C, D) + W[15]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f1(A, B, C) + W[16]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f1(E, A, B) + W[17]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f1(D, E, A) + W[18]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f1(C, D, E) + W[19]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f2(B, C, D) + W[20]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f2(A, B, C) + W[21]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f2(E, A, B) + W[22]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f2(D, E, A) + W[23]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f2(C, D, E) + W[24]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f2(B, C, D) + W[25]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f2(A, B, C) + W[26]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f2(E, A, B) + W[27]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f2(D, E, A) + W[28]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f2(C, D, E) + W[29]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f2(B, C, D) + W[30]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f2(A, B, C) + W[31]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f2(E, A, B) + W[32]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f2(D, E, A) + W[33]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f2(C, D, E) + W[34]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f2(B, C, D) + W[35]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f2(A, B, C) + W[36]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f2(E, A, B) + W[37]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f2(D, E, A) + W[38]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f2(C, D, E) + W[39]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f3(B, C, D) + W[40]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f3(A, B, C) + W[41]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f3(E, A, B) + W[42]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f3(D, E, A) + W[43]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f3(C, D, E) + W[44]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f3(B, C, D) + W[45]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f3(A, B, C) + W[46]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f3(E, A, B) + W[47]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f3(D, E, A) + W[48]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f3(C, D, E) + W[49]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f3(B, C, D) + W[50]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f3(A, B, C) + W[51]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f3(E, A, B) + W[52]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f3(D, E, A) + W[53]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f3(C, D, E) + W[54]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f3(B, C, D) + W[55]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f3(A, B, C) + W[56]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f3(E, A, B) + W[57]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f3(D, E, A) + W[58]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f3(C, D, E) + W[59]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f4(B, C, D) + W[60]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f4(A, B, C) + W[61]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f4(E, A, B) + W[62]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f4(D, E, A) + W[63]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f4(C, D, E) + W[64]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f4(B, C, D) + W[65]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f4(A, B, C) + W[66]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f4(E, A, B) + W[67]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f4(D, E, A) + W[68]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f4(C, D, E) + W[69]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f4(B, C, D) + W[70]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f4(A, B, C) + W[71]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f4(E, A, B) + W[72]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f4(D, E, A) + W[73]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f4(C, D, E) + W[74]; C =((C << 30)|(C >>> -30));
E += ((A << 5)|(A >>> -5)) + f4(B, C, D) + W[75]; B =((B << 30)|(B >>> -30));
D += ((E << 5)|(E >>> -5)) + f4(A, B, C) + W[76]; A =((A << 30)|(A >>> -30));
C += ((D << 5)|(D >>> -5)) + f4(E, A, B) + W[77]; E =((E << 30)|(E >>> -30));
B += ((C << 5)|(C >>> -5)) + f4(D, E, A) + W[78]; D =((D << 30)|(D >>> -30));
A += ((B << 5)|(B >>> -5)) + f4(C, D, E) + W[79]; C =((C << 30)|(C >>> -30));
digest[0] += A;
digest[1] += B;
digest[2] += C;
digest[3] += D;
digest[4] += E;
if (DEBUG && debuglevel > 5) debug("d1="+digest[0]+" d1="+digest[1]+" d2="+digest[2]+" d3="+digest[3]+" d4="+digest[4]);
}
// why was this public?
// Note: parameter order changed to be consistent with System.arraycopy.
private static void byte2int(byte[] src, int srcOffset,
int[] dst, int dstOffset, int length)
{
while (length-- > 0)
{
// Big endian
dst[dstOffset++] = (src[srcOffset++] << 24) |
((src[srcOffset++] & 0xFF) << 16) |
((src[srcOffset++] & 0xFF) << 8) |
(src[srcOffset++] & 0xFF);
}
}
// // // // // // // // // // // // T E S T // // // // // // // //
/**
* Entry point for <code>self_test</code>.
*/
public static final void
main(String argv[])
{
try { self_test(); }
catch(Throwable t) { t.printStackTrace(); System.exit(1);}
}
//
// Only two known sets of data!
// Using Hex format 0xAB results in needing casts.
//
private static String[] texts =
{
"abc", // t 1
"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", // t 2
"", // empty, added
};
private static byte[][] hashs =
{
{-87,-103,62,54,71,6,-127,106,-70,62,37,113,120,80,-62,108,-100,-48,-40,-99,},
{-124,-104,62,68,28,59,-46,110,-70,-82,74,-95,-7,81,41,-27,-27,70,112,-15,},
{-38,57,-93,-18,94,107,75,13,50,85,-65,-17,-107,96,24,-112,-81,-40,7,9,},
};
/**
* Do some basic tests.
* Three of the known/validation data are included only, no output,
* success or exception.
* If you want more, write a test program!
* @see cryptix.test.TestSHA1
*/
public static final void
self_test()
throws Exception
{
int length = hashs[0].length;
for (int i = 0; i < texts.length; i++)
{
SHA1 hash = new SHA1();
byte[] text = texts[i].getBytes();
for (int j = 0; j < texts[i].length(); j++)
hash.engineUpdate(text[j]);
if (notEquals(hash.engineDigest(), hashs[i]))
throw new Exception("hash #"+ i +" failed");
}
}
private static final boolean
notEquals(byte[] a, byte[] b)
{
for (int i = 0; i < a.length; i++)
{
if (a[i] != b[i])
return true;
// if (a[i] == -81) // force a trip up
// return true;
}
return false;
}
}
| 37.611345 | 120 | 0.417695 |
3bcc2db39b74ba54292c7cf35066c3b3dbcc767d | 801 | package ru.job4j.list.linkedlist.stack;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class SimpleStackTest {
@Test
public void pushSomeElementToOurStack() {
SimpleStack<Integer> simpleStack = new SimpleStack<>();
simpleStack.push(4);
simpleStack.push(5);
assertThat(simpleStack.getLinkedStore().get(1), is(5));
}
@Test
public void pollMethodTestingFromSimpleStack() {
SimpleStack<Integer> simpleStack = new SimpleStack<>();
simpleStack.push(1);
simpleStack.push(2);
simpleStack.push(3);
assertThat(simpleStack.poll(), is(3));
assertThat(simpleStack.poll(), is(2));
assertThat(simpleStack.poll(), is(1));
}
} | 29.666667 | 63 | 0.665418 |
174766ac210e0e4c51303b3193ed00e0f9b6b59c | 2,563 | package it.polimi.ingsw.client.view.cli.middle;
import it.polimi.ingsw.client.view.cli.CLIBuilder;
import it.polimi.ingsw.client.view.cli.CLIelem.body.PersonalBoardBody;
import it.polimi.ingsw.client.view.cli.layout.ResChoiceRowCLI;
import it.polimi.ingsw.client.view.cli.layout.SizedBox;
import it.polimi.ingsw.client.view.cli.layout.recursivelist.Row;
import it.polimi.ingsw.client.view.abstractview.ProductionViewBuilder;
import it.polimi.ingsw.network.simplemodel.SimpleCardCells;
import it.polimi.ingsw.network.simplemodel.SimpleProductions.SimpleProduction;
import java.util.Objects;
import java.util.stream.Stream;
public class MiddleProductionViewCLI extends ProductionViewBuilder implements CLIBuilder {
/**
* This method starts the view, asking the player to terminate or choose a production
*/
@Override
public void run() {
PersonalBoardBody board = new PersonalBoardBody(getThisPlayerCache(), PersonalBoardBody.Mode.CHOOSE_PRODUCTION);
board.initializeFaithTrack();
board.initializeBuyOrChoosePos();
SimpleCardCells simpleCardCells = Objects.requireNonNull(getThisPlayerCache()).getElem(SimpleCardCells.class).orElseThrow();
Row prodsRow = board.productionsBuilder(simpleCardCells);
board.setProductions(prodsRow);
board.setMessage("Select a production or press ENTER to produce");
getCLIView().setBody(board);
getCLIView().show();
}
/**
* This method is called after selecting a selectable production
*/
@Override
public void choosingResForProduction() {
PersonalBoardBody board = new PersonalBoardBody(getThisPlayerCache(), PersonalBoardBody.Mode.SELECT_RES_FOR_PROD);
SimpleCardCells simpleCardCells = Objects.requireNonNull(getThisPlayerCache()).getElem(SimpleCardCells.class).orElseThrow();
SimpleProduction lastSelectedProduction = simpleCardCells.getSimpleProductions().lastSelectedProduction().orElseThrow();
ResChoiceRowCLI choices = new ResChoiceRowCLI(0,lastSelectedProduction.getUnrolledInputs(),lastSelectedProduction.getUnrolledOutputs());
Row top = new Row(Stream.of(new SizedBox(1,0),choices.getGridElem()));
board.setTop(top);
Row prodsRow = board.productionsBuilder(simpleCardCells);
board.setProductions(prodsRow);
board.setResChoiceRow(choices);
board.initializeBuyOrChoosePos();
board.setMessage("Select the resources for the production");
getCLIView().setBody(board);
getCLIView().show();
}
}
| 45.767857 | 144 | 0.753024 |
059c3496bb64a07dc3beb3abd37d727a1fc48383 | 1,494 | package org.togglz.core.util;
import java.util.Set;
import org.togglz.core.Feature;
import org.togglz.core.context.FeatureContext;
import org.togglz.core.manager.FeatureManager;
/**
* An untyped feature can be used if the name of a feature is known but not the correct type of the feature enum. The real type
* of the feature will be resolved lazily by asking the {@link FeatureManager} for the features it is responsible for. If the
* name of the untyped feature doesn't correspond to one of these features, a runtime exception will be thrown.
*
* @author Christian Kaltepoth
*
* @deprecated Use {@link NamedFeature} instead.
*/
@Deprecated
public class UntypedFeature implements Feature {
private final String name;
public UntypedFeature(String name) {
Validate.notBlank(name, "name is required");
this.name = name;
}
@Override
public String name() {
return getTypedFeature().name();
}
private Feature _feature;
private Feature getTypedFeature() {
if (_feature == null) {
Set<Feature> features = FeatureContext.getFeatureManager().getFeatures();
for (Feature f : features) {
if (f.name().equals(name)) {
_feature = f;
}
}
if (_feature == null) {
throw new IllegalArgumentException("FeatureManager doesn't know about feature: " + name);
}
}
return _feature;
}
}
| 29.294118 | 127 | 0.64257 |
802c11fa998cd7ed5d3903a46ce2f873abedaa52 | 997 | package selim.rifts.items;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.ResourceLocation;
import net.minecraft.world.World;
import selim.rifts.EnderRifts;
import selim.rifts.ModInfo;
import selim.rifts.gui.GuiHandler;
public class ItemRiftEye extends Item {
public ItemRiftEye() {
this.setRegistryName(new ResourceLocation(ModInfo.ID, "rift_eye"));
this.setUnlocalizedName(ModInfo.ID + ":rift_eye");
this.setCreativeTab(EnderRifts.mainTab);
this.maxStackSize = 1;
}
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand) {
if (world.isRemote)
player.openGui(EnderRifts.instance, GuiHandler.RIFT_EYE, world, 0, 0, 0);
return ActionResult.newResult(EnumActionResult.PASS, player.getHeldItem(hand));
}
}
| 31.15625 | 99 | 0.796389 |
4785f4957ef42d3dfb043259285d8879c9a9b0db | 168 | package lmr.randomizer.randomization;
/**
* Created by thezerothcat on 8/19/2017.
*/
public enum ShopRandomizationEnum {
NONE,
CATEGORIZED,
EVERYTHING
}
| 15.272727 | 40 | 0.708333 |
131fed53c6b5d52b60253ba3ce8f8f127069d460 | 555 | package com.liuhuan.study.springcloud.alibaba.service;
import com.liuhuan.study.springcloud.entities.CommonResult;
import com.liuhuan.study.springcloud.entities.Payment;
import org.springframework.stereotype.Component;
/**
* @author LiuHuan
* @create 2020-02-25 18:30
*/
@Component
public class PaymentFallbackService implements PaymentService {
@Override
public CommonResult<Payment> paymentSQL(Long id) {
return new CommonResult<>(44444, "服务降级返回,---PaymentFallbackService", new Payment(id, "errorSerial"));
}
}
| 30.833333 | 110 | 0.742342 |
7766aec5e0c13563308945dd526eff0ca7b51924 | 3,220 | package com.lakeel.altla.sample.weather.viewhelper;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.Toolbar;
import java.util.Objects;
public final class AppCompatHelper {
private AppCompatHelper() {
}
public static void back(@NonNull Fragment fragment) {
FragmentActivity activity = fragment.getActivity();
Objects.requireNonNull(activity);
back(activity);
}
public static void back(@NonNull FragmentActivity activity) {
if (0 < activity.getSupportFragmentManager().getBackStackEntryCount()) {
activity.getSupportFragmentManager().popBackStack();
} else {
NavUtils.navigateUpFromSameTask(activity);
}
}
public static void setToolbarAsSupportActionBar(@NonNull AppCompatActivity activity, @IdRes int toolbarId) {
Toolbar toolbar = activity.findViewById(toolbarId);
Objects.requireNonNull(toolbar);
activity.setSupportActionBar(toolbar);
}
@NonNull
public static ActionBar getRequiredSupportActionBar(@NonNull Fragment fragment) {
return getRequiredSupportActionBar(getAppCompatActivity(fragment));
}
@NonNull
public static ActionBar getRequiredSupportActionBar(@NonNull AppCompatActivity activity) {
return getRequiredSupportActionBar(activity.getDelegate());
}
@NonNull
public static ActionBar getRequiredSupportActionBar(@NonNull AppCompatDelegate delegate) {
ActionBar actionBar = delegate.getSupportActionBar();
if (actionBar == null) {
throw new IllegalStateException("No action bar is supported.");
}
return actionBar;
}
@NonNull
private static AppCompatActivity getAppCompatActivity(@NonNull Fragment fragment) {
FragmentActivity activity = fragment.getActivity();
if (activity instanceof AppCompatActivity) {
return (AppCompatActivity) activity;
} else {
throw new IllegalStateException("'fragment.activity' isn't an instance of the AppCompatActivity class.");
}
}
public static void replaceFragment(@NonNull AppCompatActivity activity,
@IdRes int containerViewId, @NonNull Fragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.replace(containerViewId, fragment, fragment.getClass().getName())
.commit();
}
public static void replaceFragmentAndAddToBackStack(@NonNull AppCompatActivity activity,
@IdRes int containerViewId, @NonNull Fragment fragment) {
activity.getSupportFragmentManager().beginTransaction()
.addToBackStack(fragment.getClass().getName())
.replace(containerViewId, fragment, fragment.getClass().getName())
.commit();
}
}
| 37.882353 | 117 | 0.692857 |
83284558ea3cb6117f8bf4092bb0a3979f55fe6a | 1,485 | /**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE and NOTICE files at the root of the source
* tree and available online at
*
* http://www.dspace.org/license/
*/
package org.dspace.app.rest.model;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnore;
/**
* The Browse Entry REST Resource
*
* @author Andrea Bollini (andrea.bollini at 4science.it)
*
*/
public class BrowseEntryRest implements RestModel {
private static final long serialVersionUID = -3415049466402327251L;
public static final String NAME = "browseEntry";
private String authority;
private String value;
private String valueLang;
private long count;
@JsonIgnore
private BrowseIndexRest browseIndex;
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getValueLang() {
return valueLang;
}
public void setValueLang(String valueLang) {
this.valueLang = valueLang;
}
public long getCount() {
return count;
}
public void setCount(long count) {
this.count = count;
}
public BrowseIndexRest getBrowseIndex() {
return browseIndex;
}
public void setBrowseIndex(BrowseIndexRest browseIndex) {
this.browseIndex = browseIndex;
}
@Override
public String getType() {
return NAME;
}
}
| 19.539474 | 69 | 0.734007 |
d2115df35b6b47e5d64cbeb3d38f5d1d2cdf990b | 789 | package com.frost_fox.jenkins.job_addon.description;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BuildStatusTest {
@Test
public void returnsRunningStatusIfIsBuildingIsTrue() {
BuildStatus status = BuildStatus.from(true, true);
assertThat(status).isEqualTo(BuildStatus.Running);
}
@Test
public void returnsSuccessStatusIfIsBuildingIsFalseAndSuccessIsTrue() {
BuildStatus status = BuildStatus.from(true, false);
assertThat(status).isEqualTo(BuildStatus.Success);
}
@Test
public void returnsFailStatusIfIsBuildingIsFalseAndSuccessIsFalse() {
BuildStatus status = BuildStatus.from(false, false);
assertThat(status).isEqualTo(BuildStatus.Fail);
}
} | 24.65625 | 75 | 0.730038 |
2e9863f87b83daa399f08ed931991404f9807451 | 78,592 | /*
* BytecodeTypeAnalysis.java
* Copyright 2008, 2009, 2010, 2011, 2012, 2013 Fiji Systems Inc.
* This file is part of the FIJI VM Software licensed under the FIJI PUBLIC
* LICENSE Version 3 or any later version. A copy of the FIJI PUBLIC LICENSE is
* available at fivm/LEGAL and can also be found at
* http://www.fiji-systems.com/FPL3.txt
*
* By installing, reproducing, distributing, and/or using the FIJI VM Software
* you agree to the terms of the FIJI PUBLIC LICENSE. You may exercise the
* rights granted under the FIJI PUBLIC LICENSE subject to the conditions and
* restrictions stated therein. Among other conditions and restrictions, the
* FIJI PUBLIC LICENSE states that:
*
* a. You may only make non-commercial use of the FIJI VM Software.
*
* b. Any adaptation you make must be licensed under the same terms
* of the FIJI PUBLIC LICENSE.
*
* c. You must include a copy of the FIJI PUBLIC LICENSE in every copy of any
* file, adaptation or output code that you distribute and cause the output code
* to provide a notice of the FIJI PUBLIC LICENSE.
*
* d. You must not impose any additional conditions.
*
* e. You must not assert or imply any connection, sponsorship or endorsement by
* the author of the FIJI VM Software
*
* f. You must take no derogatory action in relation to the FIJI VM Software
* which would be prejudicial to the FIJI VM Software author's honor or
* reputation.
*
*
* The FIJI VM Software is provided as-is. FIJI SYSTEMS INC does not make any
* representation and provides no warranty of any kind concerning the software.
*
* The FIJI PUBLIC LICENSE and any rights granted therein terminate
* automatically upon any breach by you of the terms of the FIJI PUBLIC LICENSE.
*/
package com.fiji.fivm.codegen;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeMap;
import com.fiji.asm.Label;
import com.fiji.asm.Opcodes;
import com.fiji.asm.UTF8Sequence;
import com.fiji.fivm.Constants;
import com.fiji.fivm.TypeParsing;
import com.fiji.fivm.r1.Inline;
import com.fiji.fivm.r1.NoInline;
import com.fiji.fivm.r1.NoReturn;
/**
* The bytecode forward-flow type-inference abstract interpreter. This analysis
* is intended to give you the bare minimum of information that you need to
* reason about the types in bytecode. Currently it's just used for building GC
* maps.
* <p>
* This analysis started out being very simple; it had exactly the bare minimum
* of functionality necessary to infer GC references. For simplicity, it's based
* on ASM. For speed, it uses ASM's visitor API and performs only one linear
* pass over the bytecode. This pass is used for constraint generation; thse
* constraints are optimized for memory compactness and speed. The constraints
* are then solved; most of the solving involves comparing integers.
* <p>
* Almost enough power is included to reason about Pointer and Pointer[] types,
* but this hasn't been fully implemented. Currently the 'types' are just
* JVM bytecode descriptors with some magic (see ExtendedTypes). This magic is
* already powerful enough to reason about Pointer and Pointer[] (the only
* missing piece is that this analysis doesn't fully leverage that functionality),
* and almost powerful enough to reason about the JVM execution type-system.
* <p>
* This analysis runs on the critical path of the baseline JIT. Thus, it's
* crucial that no features are added unless a high-performance implementation
* can be done. The general benchmark is that for a ~5k bytecode method, this
* should take less than 4ms on a decently-fast Intel laptop. And remember: no
* crazy object orientation! This code will be compiled with -A open and usually
* --opt-size, and sometimes with -G hf, and yet still needs to be fast!
*/
public final class BytecodeTypeAnalysis {
MethodBytecodeExtractor mbe;
int verbosity;
// NOTE: this code is at least slightly duplicating what's in ASM ... the point is that
// we *do not* want to rewrite the bytecode just to get frame info. 'cause that just
// seems retarded.
private static int[] EMPTY_PUSHED=new int[0];
private static BB[] EMPTY_SUCC=new BB[0];
@Inline
int nStack() {
return mbe.nStack();
}
@Inline
int nLocals() {
return mbe.nLocals();
}
class EdgeState {
boolean complete;
int[] locals;
int[] stack;
EdgeState() {
locals=new int[nLocals()];
}
public String toString() {
String result="[EdgeState: ";
if (!complete) {
result+="(INCOMPLETE) ";
}
result+="Locals("+typesToString(locals)+") Stack(";
if (stack!=null) {
result+=typesToString(stack);
}
return result+")]";
}
void assertComplete() {
if (!complete) {
throw new CodeGenException("Incomplete edge state after fixpoint");
}
}
void assign(int local,int type) {
if (complete) {
throw new CodeGenException(
"cannot make manual changes to EdgeState after it is complete");
}
if (!ExtendedTypes.isExplicitType(type)) {
throw new CodeGenException("cannot set local with unknown type");
}
locals[local]=type;
}
void push(int type) {
if (complete) {
throw new CodeGenException(
"cannot make manual changes to EdgeState after it is complete");
}
if (!ExtendedTypes.isExplicitType(type)) {
throw new CodeGenException("cannot set local with unknown type");
}
if (stack==null) {
stack=new int[1];
stack[0]=type;
} else {
int[] newStack=new int[stack.length+1];
System.arraycopy(
stack,0,
newStack,0,
stack.length);
newStack[stack.length]=type;
stack=newStack;
}
}
boolean forceComplete() {
if (complete) {
return false;
} else {
if (stack==null) {
stack=EMPTY_PUSHED;
}
complete=true;
return true;
}
}
boolean mergeFrom(EdgeState prev) {
if (prev.complete) {
boolean result=false;
for (int i=0;i<locals.length;++i) {
int newLocal=ExtendedTypes.lub(locals[i],prev.locals[i]);
if (newLocal!=locals[i]) {
result=true;
locals[i]=newLocal;
}
}
if (stack==null) {
stack=new int[prev.stack.length];
System.arraycopy(prev.stack,0,
stack,0,
stack.length);
result=true;
} else {
if (stack.length!=prev.stack.length) {
throw new CodeGenException("Stack heights don't match up; target has "+stack.length+" while source has "+prev.stack.length);
}
for (int i=0;i<stack.length;++i) {
int newStack=ExtendedTypes.lub(stack[i],prev.stack[i]);
if (newStack!=stack[i]) {
stack[i]=newStack;
result=true;
}
}
}
complete=true;
return result;
} else {
return false;
}
}
boolean mergeFrom(EdgeState atHead,BlockState body) {
if (atHead.complete) {
boolean result=false;
// locals. they used to be easy but then I made them hard.
for (int i=0;i<locals.length;++i) {
int newLocal=body.getState(atHead,body.locals[i]);
if (newLocal!=locals[i]) {
result=true;
locals[i]=newLocal;
}
}
// the stack. it's weird.
if (stack==null) {
int height=atHead.stack.length-body.nPopped+body.nPushed;
if (height<0) {
throw new CodeGenException("Negative stack height: previous height = "+atHead.stack.length+", number popped = "+body.nPopped+", number pushed = "+body.nPushed);
}
stack=new int[height];
}
for (int i=0;i<atHead.stack.length-body.nPopped;++i) {
int newStack=ExtendedTypes.lub(stack[i],atHead.stack[i]);
if (newStack!=stack[i]) {
result=true;
stack[i]=newStack;
}
}
for (int i=0;i<body.nPushed;++i) {
int newStack=body.getState(atHead,body.pushed[i]);
if (newStack!=stack[atHead.stack.length-body.nPopped+i]) {
result=true;
stack[atHead.stack.length-body.nPopped+i]=newStack;
}
}
complete=true;
return result;
} else {
return false;
}
}
boolean mergeFrom(ThrowState throu) {
if (throu.complete) {
boolean result=false;
if (complete) {
if (stack.length!=1) {
throw new CodeGenException(
"Exception handler may sometimes be jumped to with a stack that "+
"is not exactly one-cell high.");
}
if (stack[0]!='L') {
throw new CodeGenException(
"Exception handler may sometimes be jumped to with a stack that "+
"does not contain exactly one heap reference.");
}
} else {
result=true;
push('L');
}
for (int i=0;i<locals.length;++i) {
int newLocal=ExtendedTypes.lub(locals[i],throu.locals[i]);
if (newLocal!=locals[i]) {
result=true;
locals[i]=newLocal;
}
}
complete=true;
return result;
} else {
return false;
}
}
}
class ThrowState {
boolean complete;
boolean mayThrow;
int[] locals;
ThrowState() {
}
void assertComplete() {
if (!complete) {
throw new CodeGenException("Incomplete throw state after fixpoint");
}
}
boolean mergeFrom(EdgeState atHead,BlockState body) {
if (!body.mayThrow) {
if (complete) {
return false;
} else {
complete=true;
return true;
}
} else {
if (atHead.complete) {
boolean result=false;
mayThrow=true;
if (locals==null) {
locals=new int[nLocals()];
result=true;
}
for (int i=0;i<locals.length;++i) {
int[] excLocals;
if (body.excLocals==null) {
excLocals=null;
} else {
excLocals=body.excLocals[i];
}
int newLocal;
if (excLocals==null) {
newLocal=body.getState(atHead,body.excLocalsSimple[i]);
} else {
newLocal=ExtendedTypes.lub(
body.getState(atHead,body.excLocalsSimple[i]),
body.getState(atHead,excLocals));
}
newLocal=ExtendedTypes.lub(atHead.locals[i],newLocal);
if (newLocal!=locals[i]) {
result=true;
locals[i]=newLocal;
}
}
complete=true;
return result;
} else {
return false;
}
}
}
}
class BlockState {
int nPopped;
int nPushed;
int[] pushed;
int[] locals;
int[] excLocalsSimple;
int[][] excLocals;
boolean mayThrow;
BlockState() {
pushed=EMPTY_PUSHED;
int nLocals=nLocals();
locals=new int[nLocals];
excLocalsSimple=new int[nLocals];
for (int i=0;i<nLocals;++i) {
locals[i]=ExtendedTypes.newLocalRef(i);
}
}
public String toString() {
StringBuilder buf=new StringBuilder();
buf.append("[BlockState: nPopped("+nPopped+") nPushed("+nPushed+") ");
buf.append("pushed("+typesToString(pushed)+")");
buf.append(" locals("+typesToString(locals)+")");
buf.append(" excLocalsSimple("+typesToString(excLocalsSimple)+")");
buf.append(" excLocals(");
if (excLocals==null) {
buf.append("null");
} else {
for (int[] el : excLocals) {
buf.append("["+typesToString(el)+"]");
}
}
buf.append(")]");
return buf.toString();
}
int getState(EdgeState atHead,int code) {
if (code==0) {
throw new CodeGenException("code cannot be 0");
}
switch (ExtendedTypes.codeKind(code)) {
case ExtendedTypes.EXPLICIT_TYPE:
case ExtendedTypes.PTR_TYPE:
case ExtendedTypes.SYMB_TYPE:
return code;
case ExtendedTypes.LOCAL_REFERENCE:
return ExtendedTypes.validateNonStateRef(
atHead.locals[ExtendedTypes.getPayload(code)]);
case ExtendedTypes.STACK_REFERENCE:
return ExtendedTypes.validateNonStateRef(
atHead.stack[atHead.stack.length-ExtendedTypes.getPayload(code)-1]);
default:
throw new CodeGenException("bad code kind: "+code);
}
}
int getState(EdgeState atHead,int[] codes) {
int result=0;
for (int code : codes) {
result=ExtendedTypes.lub(result,getState(atHead,code));
}
return result;
}
@Inline
void pop() {
if (nPushed==0) {
nPopped++;
} else {
nPushed--;
}
}
@Inline
void pop(int n) {
nPushed-=n;
if (nPushed<0) {
nPopped-=nPushed;
nPushed=0;
}
}
@NoInline
private void reallocStack() {
int[] newPushed=new int[(pushed.length+1)<<1];
System.arraycopy(pushed,0,
newPushed,0,
nPushed);
pushed=newPushed;
}
@Inline
void push(int type) {
if (pushed.length==nPushed) {
reallocStack();
}
pushed[nPushed++]=type;
}
@NoInline
@NoReturn
private void popOverflow() {
throw new CodeGenException("Pop overflow");
}
@Inline
int popValue() {
if (nPushed==0) {
int idx=nPopped++;
if (idx>65535 || idx<0) {
popOverflow();
return 0; // make javac happy
}
return ExtendedTypes.newStackRef(idx);
} else {
return pushed[--nPushed];
}
}
void assign(int local,int type) {
locals[local]=type;
}
int load(int local) {
return locals[local];
}
void mayThrow() {
for (int i=0;i<locals.length;++i) {
int curLocal=locals[i];
int result=ExtendedTypes.tryLub(curLocal,excLocalsSimple[i]);
if (result<0) {
if (excLocals==null) {
if (verbosity>=1) {
System.err.println("Inflating excLocals in "+this);
}
excLocals=new int[locals.length][];
}
int[] lubs=excLocals[i];
if (lubs==null) {
if (verbosity>=1) {
System.err.println("Inflating excLocal["+i+"] in "+this+
" because of "+curLocal+" (simple = "+excLocalsSimple[i]+")");
}
excLocals[i]=new int[]{curLocal};
} else {
boolean found=false;
for (int j=0;j<lubs.length;++j) {
result=ExtendedTypes.tryLub(curLocal,lubs[j]);
if (result>=0) {
lubs[j]=result;
found=true;
break;
}
}
if (!found) {
if (verbosity>=1) {
System.err.println(
"Extending inflation excLocal["+i+"] in "+this+
" because of "+curLocal+" (simple = "+excLocalsSimple[i]+")");
}
int[] newLubs=new int[lubs.length+1];
System.arraycopy(lubs,0,
newLubs,0,
lubs.length);
newLubs[lubs.length]=curLocal;
excLocals[i]=newLubs;
}
}
} else {
excLocalsSimple[i]=result;
}
}
mayThrow=true;
}
}
class BB {
int bcOffset;
EdgeState atHead;
EdgeState atTail;
BlockState body;
ThrowState throu;
BB[] normalSuccessors;
int nNormalSuccessors;
BB[] excSuccessors;
int nExcSuccessors;
BB(int bcOffset) {
this.bcOffset=bcOffset;
atHead=new EdgeState();
atTail=new EdgeState();
body=new BlockState();
throu=new ThrowState();
normalSuccessors=EMPTY_SUCC;
excSuccessors=EMPTY_SUCC;
}
public String toString() {
StringBuilder buf=new StringBuilder();
buf.append("[BB: ");
buf.append(bcOffset);
buf.append(" Succ(");
for (int i=0;i<nNormalSuccessors;++i) {
if (i!=0) {
buf.append(", ");
}
buf.append(normalSuccessors[i].bcOffset);
}
buf.append("), ExcSucc(");
for (int i=0;i<nExcSuccessors;++i) {
if (i!=0) {
buf.append(", ");
}
buf.append(excSuccessors[i].bcOffset);
}
buf.append("), ");
buf.append(body.toString());
buf.append("]");
return buf.toString();
}
void addNormalSuccessor(BB succ) {
if (verbosity>=1) {
System.err.println("Edge: "+bcOffset+" -> "+succ.bcOffset);
}
if (nNormalSuccessors==normalSuccessors.length) {
BB[] newSucc=new BB[(nNormalSuccessors+1)<<1];
System.arraycopy(normalSuccessors,0,
newSucc,0,
nNormalSuccessors);
normalSuccessors=newSucc;
}
normalSuccessors[nNormalSuccessors++]=succ;
if (verbosity>=1) {
System.err.println(this);
}
}
void addExcSuccessor(BB succ) {
if (verbosity>=1) {
System.err.println("Exc edge: "+bcOffset+" -> "+succ.bcOffset);
}
if (nExcSuccessors==excSuccessors.length) {
BB[] newSucc=new BB[(nExcSuccessors+1)<<1];
System.arraycopy(excSuccessors,0,
newSucc,0,
nExcSuccessors);
excSuccessors=newSucc;
}
excSuccessors[nExcSuccessors++]=succ;
if (verbosity>=1) {
System.err.println(this);
}
}
boolean propagate() {
try {
boolean result=false;
result|=atTail.mergeFrom(atHead,body);
result|=throu.mergeFrom(atHead,body);
if (verbosity>=1) {
System.err.println(this);
System.err.println("atHead("+bcOffset+"): "+atHead);
System.err.println("atTail("+bcOffset+"): "+atTail);
}
if (atTail.complete) {
if (verbosity>=1 && nNormalSuccessors==0) {
System.err.println("not propagating from "+bcOffset+" because it has no successors");
}
for (int i=0;i<nNormalSuccessors;++i) {
if (verbosity>=1) {
System.err.println("propagating along "+bcOffset+" -> "+
normalSuccessors[i].bcOffset);
}
try {
result|=normalSuccessors[i].atHead.mergeFrom(atTail);
} catch (CodeGenException e) {
throw new CodeGenException(
"Failed to propagate from "+bcOffset+" to "+
normalSuccessors[i].bcOffset,e);
}
}
} else {
if (verbosity>=1) {
System.err.println("not propagating from "+bcOffset+" due to incompleteness");
}
}
if (throu.mayThrow) {
if (verbosity>=1 && nExcSuccessors==0) {
System.err.println("not exception-propagating from "+bcOffset+" because it has no exception-successors");
}
for (int i=0;i<nExcSuccessors;++i) {
if (verbosity>=1) {
System.err.println("propagating exceptional flow along "+bcOffset+
" -> "+excSuccessors[i].bcOffset);
}
try {
result|=excSuccessors[i].atHead.mergeFrom(throu);
} catch (CodeGenException e) {
throw new CodeGenException(
"Failed to propagate exceptional flow from "+bcOffset+" to "+
excSuccessors[i].bcOffset,e);
}
}
} else {
if (verbosity>=1) {
System.err.println("not exception-propagating from "+bcOffset+" because it doesn't throw");
}
}
return result;
} catch (VirtualMachineError e) {
throw e;
} catch (Throwable e) {
throw new CodeGenException(
"Failed to propagate at bcOffset = "+bcOffset,e);
}
}
void assertComplete() {
try {
atHead.assertComplete();
atTail.assertComplete();
throu.assertComplete();
} catch (VirtualMachineError e) {
throw e;
} catch (Throwable e) {
throw new CodeGenException(
"Failed to assert completeness at bcOffset = "+bcOffset,e);
}
}
}
static class TryCatch {
int start;
int end;
int target;
boolean terminal;
TryCatch(int start,
int end,
int target,
boolean terminal) {
this.start=start;
this.end=end;
this.target=target;
this.terminal=terminal;
}
}
TreeMap< Integer, BB > blocks=new TreeMap< Integer, BB >();
ArrayList< BB > blocksArray;
ArrayList< TryCatch > handlers=new ArrayList< TryCatch >();
boolean finished=false;
int bytecodeSize;
BB blockFor(int bcOffset) {
BB result=blocks.get(bcOffset);
if (result==null) {
if (finished) {
throw new CodeGenException("Could not find basic block at "+bcOffset);
} else {
if (verbosity>=1) {
System.err.println("Allocating BB("+bcOffset+")");
}
blocks.put(bcOffset,result=new BB(bcOffset));
if (verbosity>=1) {
System.err.println("blocks["+bcOffset+"] = "+blocks.get(bcOffset));
}
}
}
return result;
}
BB blockFor(Label label) {
return blockFor(label.getOffsetWorks());
}
boolean propForward() {
if (verbosity>=1) {
System.err.println(" Propagating forward...");
}
boolean changed=false;
for (BB bb : blocksArray) {
changed|=bb.propagate();
}
return changed;
}
boolean propBackward() {
if (verbosity>=1) {
System.err.println(" Propagating backward...");
}
boolean changed=false;
for (int i=blocksArray.size();i-->0;) {
changed|=blocksArray.get(i).propagate();
}
return changed;
}
public BytecodeTypeAnalysis(MethodBytecodeExtractor mbe) {
this(mbe,0);
}
public BytecodeTypeAnalysis(MethodBytecodeExtractor mbe,
int verbosity_) {
this.mbe=mbe;
this.verbosity=verbosity_;
try {
if (verbosity>=1) {
System.err.println("Beginning bytecode type analysis...");
System.err.println("nLocals = "+nLocals()+", nStack = "+nStack());
}
mbe.extract(
new EmptyMethodVisitor() {
BB currentBB;
BlockState current;
boolean terminal;
boolean justJumped;
int lastOffset;
boolean endSeen;
{
currentBB=blockFor(0);
current=currentBB.body;
terminal=false;
}
// FIXME: if we see a branch then we need to terminate the previous
// block and fire off a new one at the succeeding instruction!!
// i.e. need a flag that we set whenever we add a successor, and
// visitBCOffset needs to Do The Right thing when that flag is
// set...
void makeNewBlock(int offset) {
BB newBB=blockFor(offset);
if (newBB!=currentBB) {
if (!terminal) {
currentBB.addNormalSuccessor(newBB);
}
currentBB=newBB;
current=currentBB.body;
terminal=false;
}
}
public void visitBCOffset(int offset) {
if (false && verbosity>=1) {
System.err.println("at bcOffset = "+offset);
}
if (justJumped) {
makeNewBlock(offset);
justJumped=false;
}
lastOffset=offset;
}
public void visitLabel(Label l) {
if (false && verbosity>=1) {
System.err.println("visiting label with bcOffset = "+l.getOffsetWorks());
}
makeNewBlock(l.getOffsetWorks());
}
public void visitEnd() {
if (endSeen) {
throw new Error("Seeing end twice!");
}
// if a method ends in a jump then we'll stupidly insert a
// basic block at the tail. here we kill it if it exists.
if (verbosity>=1) {
System.err.println("Removing "+lastOffset);
}
blocks.remove(lastOffset);
bytecodeSize=lastOffset;
endSeen=true;
}
public void visitTryCatchBlock(Label start,
Label end,
Label handler,
UTF8Sequence type) {
// NOTE: because this analysis doubles as a light-weight verification,
// we don't want to mark a catch block as terminal just because it
// catches Throwable. It turns out that javac/ecj will emit code
// that is unreachable in this way, presumably because they don't
// have accurate information about which bytecode instructions may
// or may not throw. But perhaps this is something that we'll have to
// look into...
handlers.add(
new TryCatch(
start.getOffsetWorks(),
end.getOffsetWorks(),
handler.getOffsetWorks(),
type==null/* || type.equals(UTF8Sequence.java_lang_Throwable)*/));
}
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.NOP:
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
break;
case Opcodes.ACONST_NULL:
current.push('L');
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
current.push('I');
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
current.push('F');
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
current.push('J');
current.push('-');
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
current.push('D');
current.push('-');
break;
case Opcodes.IALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
case Opcodes.IDIV:
case Opcodes.IREM:
current.mayThrow();
current.pop(2);
current.push('I');
break;
case Opcodes.LALOAD:
current.mayThrow();
current.pop(2);
current.push('J');
current.push('-');
break;
case Opcodes.FALOAD:
case Opcodes.FDIV:
case Opcodes.FREM:
current.mayThrow();
current.pop(2);
current.push('F');
break;
case Opcodes.DALOAD:
current.mayThrow();
current.pop(2);
current.push('D');
current.push('-');
break;
case Opcodes.AALOAD:
current.mayThrow();
current.pop(2);
current.push('L');
break;
case Opcodes.IASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
current.mayThrow();
current.pop(3);
break;
case Opcodes.DASTORE:
case Opcodes.LASTORE:
current.mayThrow();
current.pop(4);
break;
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
case Opcodes.IADD:
case Opcodes.ISUB:
case Opcodes.IMUL:
current.pop(2);
current.push('I');
break;
case Opcodes.FADD:
case Opcodes.FSUB:
case Opcodes.FMUL:
current.pop(2);
current.push('F');
break;
case Opcodes.POP:
current.pop(1);
break;
case Opcodes.POP2:
current.pop(2);
break;
case Opcodes.DUP: {
int val=current.popValue();
current.push(val);
current.push(val);
break;
}
case Opcodes.DUP_X1: {
int val1=current.popValue();
int val2=current.popValue();
current.push(val1);
current.push(val2);
current.push(val1);
break;
}
case Opcodes.DUP_X2: {
int val1=current.popValue();
int val2=current.popValue();
int val3=current.popValue();
current.push(val1);
current.push(val3);
current.push(val2);
current.push(val1);
break;
}
case Opcodes.DUP2: {
int val1=current.popValue();
int val2=current.popValue();
current.push(val2);
current.push(val1);
current.push(val2);
current.push(val1);
break;
}
case Opcodes.DUP2_X1: {
int val1=current.popValue();
int val2=current.popValue();
int val3=current.popValue();
current.push(val2);
current.push(val1);
current.push(val3);
current.push(val2);
current.push(val1);
break;
}
case Opcodes.DUP2_X2: {
int val1=current.popValue();
int val2=current.popValue();
int val3=current.popValue();
int val4=current.popValue();
current.push(val2);
current.push(val1);
current.push(val4);
current.push(val3);
current.push(val2);
current.push(val1);
break;
}
case Opcodes.SWAP: {
int val1=current.popValue();
int val2=current.popValue();
current.push(val1);
current.push(val2);
break;
}
case Opcodes.LDIV:
case Opcodes.LREM:
current.mayThrow();
current.pop(4);
current.push('J');
current.push('-');
break;
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
case Opcodes.LADD:
case Opcodes.LSUB:
case Opcodes.LMUL:
current.pop(4);
current.push('J');
current.push('-');
break;
case Opcodes.DDIV:
case Opcodes.DREM:
current.mayThrow();
current.pop(4);
current.push('D');
current.push('-');
break;
case Opcodes.DADD:
case Opcodes.DSUB:
case Opcodes.DMUL:
current.pop(4);
current.push('D');
current.push('-');
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
current.pop();
break;
case Opcodes.I2L:
case Opcodes.F2L:
current.pop();
current.push('J');
current.push('-');
break;
case Opcodes.I2F:
current.pop();
current.push('F');
break;
case Opcodes.I2D:
case Opcodes.F2D:
current.pop();
current.push('D');
current.push('-');
break;
case Opcodes.L2I:
case Opcodes.D2I:
current.pop(2);
current.push('I');
break;
case Opcodes.L2F:
case Opcodes.D2F:
current.pop(2);
current.push('F');
break;
case Opcodes.L2D:
current.pop(2);
current.push('D');
current.push('-');
break;
case Opcodes.F2I:
current.pop();
current.push('I');
break;
case Opcodes.D2L:
current.pop(2);
current.push('J');
current.push('-');
break;
case Opcodes.LCMP:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
current.pop(4);
current.push('I');
break;
case Opcodes.FCMPL:
case Opcodes.FCMPG:
current.pop(2);
current.push('I');
break;
case Opcodes.IRETURN:
case Opcodes.LRETURN:
case Opcodes.FRETURN:
case Opcodes.DRETURN:
case Opcodes.ARETURN:
case Opcodes.RETURN:
terminal=true;
break;
case Opcodes.ARRAYLENGTH:
current.pop();
current.push('I');
break;
case Opcodes.ATHROW:
current.mayThrow();
current.pop();
terminal=true;
break;
case Opcodes.MONITORENTER:
current.mayThrow();
current.pop();
break;
case Opcodes.MONITOREXIT:
current.mayThrow();
current.pop();
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitFieldInsn(int opcode,
UTF8Sequence owner,
UTF8Sequence name,
UTF8Sequence desc) {
char type=Types.toExec((char)desc.byteAt(0));
current.mayThrow();
switch (opcode) {
case Opcodes.GETSTATIC:
current.push(type);
if (Types.cells(type)==2) {
current.push('-');
}
break;
case Opcodes.PUTSTATIC:
current.pop(Types.cells(type));
break;
case Opcodes.GETFIELD:
current.pop();
current.push(type);
if (Types.cells(type)==2) {
current.push('-');
}
break;
case Opcodes.PUTFIELD:
current.pop(1+Types.cells(type));
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitMethodInsn(int opcode,
UTF8Sequence owner,
UTF8Sequence name,
UTF8Sequence desc) {
TypeParsing.MethodSigSeqs sigs=TypeParsing.splitMethodSig(desc);
char retType=(char)sigs.result().byteAt(0);
if (retType!='V') {
retType=Types.toExec(retType);
}
int paramCells=0;
for (UTF8Sequence sig : sigs.params()) {
paramCells+=Types.cells(Types.toExec((char)sig.byteAt(0)));
}
current.mayThrow();
switch (opcode) {
case Opcodes.INVOKEVIRTUAL:
case Opcodes.INVOKESPECIAL:
case Opcodes.INVOKEINTERFACE:
paramCells++;
break;
case Opcodes.INVOKESTATIC:
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
current.pop(paramCells);
if (retType!='V') {
current.push(retType);
if (Types.cells(retType)==2) {
current.push('-');
}
}
}
public void visitIincInsn(int var,int increment) {
current.assign(var,'I');
}
public void visitIntInsn(int opcode,int operand) {
switch (opcode) {
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
current.push('I');
break;
case Opcodes.NEWARRAY:
current.mayThrow();
current.pop();
current.push('L');
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitJumpInsn(int opcode,Label label) {
switch (opcode) {
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
current.pop(2);
currentBB.addNormalSuccessor(blockFor(label));
justJumped=true;
break;
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
current.pop(1);
currentBB.addNormalSuccessor(blockFor(label));
justJumped=true;
break;
case Opcodes.GOTO:
currentBB.addNormalSuccessor(blockFor(label));
justJumped=true;
terminal=true; // bad terminology but I can't bring myself to care
break;
case Opcodes.JSR:
throw new CodeGenException("saw unexpected JSR: "+opcode);
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitLdcInsn(Object cst) {
if (cst instanceof Integer) {
current.push('I');
} else if (cst instanceof Float) {
current.push('F');
} else if (cst instanceof Long) {
current.push('J');
current.push('-');
} else if (cst instanceof Double) {
current.push('D');
current.push('-');
} else if (cst instanceof String || cst instanceof com.fiji.asm.Type) {
current.push('R');
} else {
throw new CodeGenException("unexpected kind of LDC: "+cst);
}
}
public void visitLookupSwitchInsn(Label dflt,int[] keys,Label[] labels) {
current.pop();
currentBB.addNormalSuccessor(blockFor(dflt));
for (Label l : labels) {
currentBB.addNormalSuccessor(blockFor(l));
}
terminal=true;
}
public void visitMultiANewArrayInsn(UTF8Sequence desc,int dims) {
current.mayThrow();
current.pop(dims);
current.push('R');
}
public void visitTableSwitchInsn(int min,int max,Label dflt,Label[] labels) {
current.pop();
currentBB.addNormalSuccessor(blockFor(dflt));
for (Label l : labels) {
currentBB.addNormalSuccessor(blockFor(l));
}
terminal=true;
}
public void visitTypeInsn(int opcode,UTF8Sequence type) {
switch (opcode) {
case Opcodes.NEW:
current.mayThrow();
current.push('R');
break;
case Opcodes.ANEWARRAY:
current.mayThrow();
current.pop();
current.push('R');
break;
case Opcodes.CHECKCAST:
current.mayThrow();
break;
case Opcodes.INSTANCEOF:
current.pop();
current.push('I');
break;
default:
throw new CodeGenException("unexpected opcode: "+opcode);
}
}
public void visitVarInsn(int opcode,int var) {
switch (opcode) {
case Opcodes.ILOAD:
current.push('I');
break;
case Opcodes.LLOAD:
current.push('J');
current.push('-');
break;
case Opcodes.FLOAD:
current.push('F');
break;
case Opcodes.DLOAD:
current.push('D');
current.push('-');
break;
case Opcodes.ALOAD:
current.push(current.load(var));
break;
case Opcodes.ISTORE:
current.assign(var,'I');
current.pop();
break;
case Opcodes.LSTORE:
current.assign(var,'J');
current.pop(2);
break;
case Opcodes.FSTORE:
current.assign(var,'F');
current.pop();
break;
case Opcodes.DSTORE:
current.assign(var,'D');
current.pop(2);
break;
case Opcodes.ASTORE:
current.assign(var,current.popValue());
break;
case Opcodes.RET:
throw new CodeGenException("unexpected RET");
default:
throw new CodeGenException("unexpected opcode: "+opcode);
}
}
});
if (verbosity>=1) {
System.err.println("Parsed code.");
}
// set up root block
BB root=blockFor(0);
TypeParsing.MethodSigSeqs mss=TypeParsing.splitMethodSig(mbe.descriptor());
int offset=0;
if ((mbe.flags()&Constants.BF_STATIC)==0) {
root.atHead.assign(offset,'R');
offset++;
}
for (int i=0;i<mss.nParams();++i) {
root.atHead.assign(offset,Types.toExec(mss.param(i).charAt(0)));
offset+=Types.cells(mss.param(i).charAt(0));
}
for (int i=offset;i<nLocals();++i) {
root.atHead.assign(i,'.');
}
root.atHead.forceComplete();
// indicate that no new blocks should be created
finished=true;
blocksArray=new ArrayList< BB >(blocks.values());
if (verbosity>=1) {
System.err.println("Linking try-catch blocks...");
}
// link try-catch blocks
for (BB bb : blocks.values()) {
loopOverHandlers:
for (TryCatch tc : handlers) {
if (bb.bcOffset >= tc.start && bb.bcOffset < tc.end) {
bb.addExcSuccessor(blockFor(tc.target));
if (tc.terminal) {
break loopOverHandlers;
}
}
}
}
if (verbosity>=1) {
System.err.println("Performing fixpoint...");
}
// perform fixpoint
for (int cnt=1;;cnt++) {
if (verbosity>=1) {
System.err.println(" Fixpoint iteration #"+cnt);
}
if (!propForward()) break;
if (!propBackward()) break;
if (!propForward()) break;
}
if (verbosity>=1) {
System.err.println("Fixpoint done; asserting completeness...");
}
// assert that everyone is complete
for (BB bb : blocksArray) {
bb.assertComplete();
}
if (verbosity>=1) {
System.err.println("Analysis done.");
}
} catch (VirtualMachineError e) {
throw e;
} catch (Throwable e) {
throw new CodeGenException("Failed to analyze "+mbe,e);
}
}
public class ForwardHeavyCalc extends EmptyMethodVisitor {
int[] stack;
int[] locals;
int nPushed;
boolean justJumped;
public ForwardHeavyCalc() {
stack=new int[nStack()];
locals=new int[nLocals()];
reset(0);
}
void reset(int bcOffset) {
if (bcOffset!=bytecodeSize) {
BB bb=blockFor(bcOffset);
System.arraycopy(bb.atHead.stack,0,
stack,0,
bb.atHead.stack.length);
System.arraycopy(bb.atHead.locals,0,
locals,0,
locals.length);
nPushed=bb.atHead.stack.length;
}
}
void assign(int local,int type) {
locals[local]=type;
}
public void push(int type) {
stack[nPushed++]=type;
}
public int popValue() {
return stack[--nPushed];
}
public void pop() {
nPushed--;
}
public void pop(int amount) {
nPushed-=amount;
}
// INEFFICIENT! do not use except for debugging!
public int[] stack() {
int[] result=new int[nPushed];
System.arraycopy(stack,0,
result,0,
nPushed);
return result;
}
public int[] locals() {
return locals;
}
public int stackHeight() {
return nPushed;
}
public int stackAtAbsolute(int height) {
int result=stack[height];
if (ExtendedTypes.isStateRef(result)) {
throw new CodeGenException("cannot have state references anymore: "+result+" at abs height "+height);
}
return result;
}
public int stackAt(int offset) {
int result=stack[nPushed-offset-1];
if (ExtendedTypes.isStateRef(result)) {
throw new CodeGenException("cannot have state references anymore: "+result+" at height "+offset);
}
return result;
}
// useful for situations where you know that the stack offset is invalid,
// but in which case you still want something returned because you intend
// to ignore it anyway.
public int tryStackAt(int offset) {
int idx=nPushed-offset-1;
if (idx<0 || idx>=stack.length) {
return 0;
}
return stackAt(offset);
}
public boolean stackAtIsRef(int offset) {
return ExtendedTypes.isRef(stackAt(offset));
}
public boolean stackAtIsNonNull(int offset) {
return ExtendedTypes.isNonNull(stackAt(offset));
}
public int localAt(int local) {
int result=locals[local];
if (ExtendedTypes.isStateRef(result)) {
throw new CodeGenException("cannot have state references anymore: "+result+" at local "+local);
}
return result;
}
public boolean localAtIsRef(int local) {
return ExtendedTypes.isRef(localAt(local));
}
public boolean localAtIsNonNull(int local) {
return ExtendedTypes.isNonNull(localAt(local));
}
public void visitBCOffset(int bcOffset) {
if (justJumped) {
reset(bcOffset);
justJumped=false;
}
}
public void visitLabel(Label l) {
if ((l.getStatus()&Label.DEBUG)==0) {
reset(l.getOffsetWorks());
}
}
public void visitInsn(int opcode) {
switch (opcode) {
case Opcodes.NOP:
case Opcodes.INEG:
case Opcodes.LNEG:
case Opcodes.FNEG:
case Opcodes.DNEG:
case Opcodes.I2B:
case Opcodes.I2C:
case Opcodes.I2S:
break;
case Opcodes.ACONST_NULL:
push('L');
break;
case Opcodes.ICONST_M1:
case Opcodes.ICONST_0:
case Opcodes.ICONST_1:
case Opcodes.ICONST_2:
case Opcodes.ICONST_3:
case Opcodes.ICONST_4:
case Opcodes.ICONST_5:
push('I');
break;
case Opcodes.FCONST_0:
case Opcodes.FCONST_1:
case Opcodes.FCONST_2:
push('F');
break;
case Opcodes.LCONST_0:
case Opcodes.LCONST_1:
push('J');
push('-');
break;
case Opcodes.DCONST_0:
case Opcodes.DCONST_1:
push('D');
push('-');
break;
case Opcodes.IALOAD:
case Opcodes.BALOAD:
case Opcodes.CALOAD:
case Opcodes.SALOAD:
case Opcodes.IDIV:
case Opcodes.IREM:
pop(2);
push('I');
break;
case Opcodes.LALOAD:
pop(2);
push('J');
push('-');
break;
case Opcodes.FALOAD:
case Opcodes.FDIV:
case Opcodes.FREM:
pop(2);
push('F');
break;
case Opcodes.DALOAD:
pop(2);
push('D');
push('-');
break;
case Opcodes.AALOAD:
pop(2);
push('L');
break;
case Opcodes.IASTORE:
case Opcodes.FASTORE:
case Opcodes.AASTORE:
case Opcodes.BASTORE:
case Opcodes.CASTORE:
case Opcodes.SASTORE:
pop(3);
break;
case Opcodes.DASTORE:
case Opcodes.LASTORE:
pop(4);
break;
case Opcodes.ISHL:
case Opcodes.ISHR:
case Opcodes.IUSHR:
case Opcodes.IAND:
case Opcodes.IOR:
case Opcodes.IXOR:
case Opcodes.IADD:
case Opcodes.ISUB:
case Opcodes.IMUL:
pop(2);
push('I');
break;
case Opcodes.FADD:
case Opcodes.FSUB:
case Opcodes.FMUL:
pop(2);
push('F');
break;
case Opcodes.POP:
pop(1);
break;
case Opcodes.POP2:
pop(2);
break;
case Opcodes.DUP: {
int val=popValue();
push(val);
push(val);
break;
}
case Opcodes.DUP_X1: {
int val1=popValue();
int val2=popValue();
push(val1);
push(val2);
push(val1);
break;
}
case Opcodes.DUP_X2: {
int val1=popValue();
int val2=popValue();
int val3=popValue();
push(val1);
push(val3);
push(val2);
push(val1);
break;
}
case Opcodes.DUP2: {
int val1=popValue();
int val2=popValue();
push(val2);
push(val1);
push(val2);
push(val1);
break;
}
case Opcodes.DUP2_X1: {
int val1=popValue();
int val2=popValue();
int val3=popValue();
push(val2);
push(val1);
push(val3);
push(val2);
push(val1);
break;
}
case Opcodes.DUP2_X2: {
int val1=popValue();
int val2=popValue();
int val3=popValue();
int val4=popValue();
push(val2);
push(val1);
push(val4);
push(val3);
push(val2);
push(val1);
break;
}
case Opcodes.SWAP: {
int val1=popValue();
int val2=popValue();
push(val1);
push(val2);
break;
}
case Opcodes.LDIV:
case Opcodes.LREM:
pop(4);
push('J');
push('-');
break;
case Opcodes.LAND:
case Opcodes.LOR:
case Opcodes.LXOR:
case Opcodes.LADD:
case Opcodes.LSUB:
case Opcodes.LMUL:
pop(4);
push('J');
push('-');
break;
case Opcodes.DDIV:
case Opcodes.DREM:
pop(4);
push('D');
push('-');
break;
case Opcodes.DADD:
case Opcodes.DSUB:
case Opcodes.DMUL:
pop(4);
push('D');
push('-');
break;
case Opcodes.LSHL:
case Opcodes.LSHR:
case Opcodes.LUSHR:
pop();
break;
case Opcodes.I2L:
case Opcodes.F2L:
pop();
push('J');
push('-');
break;
case Opcodes.I2F:
pop();
push('F');
break;
case Opcodes.I2D:
case Opcodes.F2D:
pop();
push('D');
push('-');
break;
case Opcodes.L2I:
case Opcodes.D2I:
pop(2);
push('I');
break;
case Opcodes.L2F:
case Opcodes.D2F:
pop(2);
push('F');
break;
case Opcodes.L2D:
pop(2);
push('D');
push('-');
break;
case Opcodes.F2I:
pop();
push('I');
break;
case Opcodes.D2L:
pop(2);
push('J');
push('-');
break;
case Opcodes.LCMP:
case Opcodes.DCMPL:
case Opcodes.DCMPG:
pop(4);
push('I');
break;
case Opcodes.FCMPL:
case Opcodes.FCMPG:
pop(2);
push('I');
break;
case Opcodes.IRETURN:
case Opcodes.LRETURN:
case Opcodes.FRETURN:
case Opcodes.DRETURN:
case Opcodes.ARETURN:
case Opcodes.RETURN:
break;
case Opcodes.ARRAYLENGTH:
pop();
push('I');
break;
case Opcodes.ATHROW:
pop();
break;
case Opcodes.MONITORENTER:
pop();
break;
case Opcodes.MONITOREXIT:
pop();
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitFieldInsn(int opcode,
UTF8Sequence owner,
UTF8Sequence name,
UTF8Sequence desc) {
char type=Types.toExec((char)desc.byteAt(0));
switch (opcode) {
case Opcodes.GETSTATIC:
push(type);
if (Types.cells(type)==2) {
push('-');
}
break;
case Opcodes.PUTSTATIC:
pop(Types.cells(type));
break;
case Opcodes.GETFIELD:
pop();
push(type);
if (Types.cells(type)==2) {
push('-');
}
break;
case Opcodes.PUTFIELD:
pop(1+Types.cells(type));
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitMethodInsn(int opcode,
UTF8Sequence owner,
UTF8Sequence name,
UTF8Sequence desc) {
TypeParsing.MethodSigSeqs sigs=TypeParsing.splitMethodSig(desc);
char retType=Types.toExec((char)sigs.result().byteAt(0));
int paramCells=0;
for (UTF8Sequence sig : sigs.params()) {
paramCells+=Types.cells(Types.toExec((char)sig.byteAt(0)));
}
if (Protocols.isInstance(opcode)) {
paramCells++;
}
pop(paramCells);
if (retType!='V') {
push(retType);
if (Types.cells(retType)==2) {
push('-');
}
}
}
public void visitIincInsn(int var,int increment) {
assign(var,'I');
}
public void visitIntInsn(int opcode,int operand) {
switch (opcode) {
case Opcodes.BIPUSH:
case Opcodes.SIPUSH:
push('I');
break;
case Opcodes.NEWARRAY:
pop();
push('R');
break;
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitJumpInsn(int opcode,Label label) {
switch (opcode) {
case Opcodes.IF_ACMPEQ:
case Opcodes.IF_ACMPNE:
case Opcodes.IF_ICMPEQ:
case Opcodes.IF_ICMPNE:
case Opcodes.IF_ICMPLT:
case Opcodes.IF_ICMPGE:
case Opcodes.IF_ICMPGT:
case Opcodes.IF_ICMPLE:
pop(2);
justJumped=true;
break;
case Opcodes.IFEQ:
case Opcodes.IFNE:
case Opcodes.IFLT:
case Opcodes.IFGE:
case Opcodes.IFGT:
case Opcodes.IFLE:
case Opcodes.IFNULL:
case Opcodes.IFNONNULL:
pop(1);
justJumped=true;
break;
case Opcodes.GOTO:
justJumped=true;
break;
case Opcodes.JSR:
throw new CodeGenException("saw unexpected JSR: "+opcode);
default:
throw new CodeGenException("unrecognized opcode: "+opcode);
}
}
public void visitLdcInsn(Object cst) {
if (cst instanceof Integer) {
push('I');
} else if (cst instanceof Float) {
push('F');
} else if (cst instanceof Long) {
push('J');
push('-');
} else if (cst instanceof Double) {
push('D');
push('-');
} else if (cst instanceof String || cst instanceof com.fiji.asm.Type) {
push('R');
} else {
throw new CodeGenException("unexpected kind of LDC: "+cst);
}
}
public void visitLookupSwitchInsn(Label dflt,int[] keys,Label[] labels) {
pop();
justJumped=true;
}
public void visitMultiANewArrayInsn(UTF8Sequence desc,int dims) {
pop(dims);
push('R');
}
public void visitTableSwitchInsn(int min,int max,Label dflt,Label[] labels) {
pop();
justJumped=true;
}
public void visitTypeInsn(int opcode,UTF8Sequence type) {
switch (opcode) {
case Opcodes.NEW:
push('R');
break;
case Opcodes.ANEWARRAY:
pop();
push('R');
break;
case Opcodes.CHECKCAST:
break;
case Opcodes.INSTANCEOF:
pop();
push('I');
break;
default:
throw new CodeGenException("unexpected opcode: "+opcode);
}
}
public void visitVarInsn(int opcode,int var) {
switch (opcode) {
case Opcodes.ILOAD:
push('I');
break;
case Opcodes.LLOAD:
push('J');
push('-');
break;
case Opcodes.FLOAD:
push('F');
break;
case Opcodes.DLOAD:
push('D');
push('-');
break;
case Opcodes.ALOAD:
push(localAt(var));
break;
case Opcodes.ISTORE:
assign(var,'I');
pop();
break;
case Opcodes.LSTORE:
assign(var,'J');
pop(2);
break;
case Opcodes.FSTORE:
assign(var,'F');
pop();
break;
case Opcodes.DSTORE:
assign(var,'D');
pop(2);
break;
case Opcodes.ASTORE:
assign(var,popValue());
break;
case Opcodes.RET:
throw new CodeGenException("unexpected RET");
default:
throw new CodeGenException("unexpected opcode: "+opcode);
}
}
}
public int[] localsAt(int bcOffset) {
BB bb=blocks.get(bcOffset);
if (bb==null) {
throw new CodeGenException("Do not know about bytecode offset "+bcOffset);
}
return bb.atHead.locals;
}
public int[] stackAt(int bcOffset) {
BB bb=blocks.get(bcOffset);
if (bb==null) {
throw new CodeGenException("Do not know about bytecode offset "+bcOffset);
}
return bb.atHead.stack;
}
public static String typesToString(int[] types) {
if (types==null) {
return "null";
}
StringBuilder buf=new StringBuilder();
for (int code : types) {
switch (ExtendedTypes.codeKind(code)) {
case ExtendedTypes.EXPLICIT_TYPE:
if (code==0) {
buf.append('_');
} else {
buf.append((char)code);
}
break;
case ExtendedTypes.LOCAL_REFERENCE:
buf.append("(local: "+ExtendedTypes.getPayload(code)+")");
break;
case ExtendedTypes.STACK_REFERENCE:
buf.append("(stack: "+ExtendedTypes.getPayload(code)+")");
break;
case ExtendedTypes.PTR_TYPE:
buf.append("(pointer");
for (int n=ExtendedTypes.getPayload(code);n-->0;) {
buf.append("[]");
}
buf.append(")");
break;
case ExtendedTypes.SYMB_TYPE:
buf.append("(symbolic: "+ExtendedTypes.getPayload(code)+")");
break;
default:
throw new CodeGenException("unrecognized code: "+code);
}
}
return buf.toString();
}
public Set< Integer > knownPoints() {
return blocks.keySet();
}
}
| 37.001883 | 184 | 0.399379 |
6c0163f435e01c5ba90d1362b1365c84903e3e2f | 5,061 | /*
* Copyright 2013-present Facebook, 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.facebook.buck.testutil;
import static java.nio.file.StandardOpenOption.CREATE;
import static java.nio.file.StandardOpenOption.WRITE;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.io.MorePaths;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Set;
/**
* An abstraction for dealing with Zip files. Use it within a try-with-resources block for maximum
* fun and profit. This differs from {@link java.util.zip.ZipFile} by providing a mechanism to add
* content to the zip and by not providing a way of extracting individual entries (just the names
* of the entries).
*/
public class Zip implements AutoCloseable {
// Java 7 introduced an abstraction for modeling file systems. One of the implementations that
// ships with the JRE is one that handles Zip files. This allows us to work on zip files directly
// without needing to write the contents to an intermediate directory.
// See: http://docs.oracle.com/javase/7/docs/technotes/guides/io/fsp/zipfilesystemprovider.html
private final FileSystem fs;
private final Path root;
/**
* Open the zip file for reading and/or writing. Note that this constructor will create
* {@code zip} if {@code forWriting} is true and the file does not exist.
*
* @param zip The zip file to operate on. The name must end with ".zip" or ".jar".
* @param forWriting Whether the zip file should be opened for writing or not.
* @throws IOException Should something terrible occur.
*/
public Zip(Path zip, boolean forWriting) throws IOException {
String extension = MorePaths.getFileExtension(zip);
assertTrue(
"zip name must end with .zip for file type detection to work",
"zip".equals(extension) || "jar".equals(extension));
URI uri = URI.create("jar:" + zip.toUri());
fs = FileSystems.newFileSystem(
uri, ImmutableMap.of("create", String.valueOf(forWriting)));
root = Iterables.getFirst(fs.getRootDirectories(), null);
assertNotNull("Unable to determine root of file system: " + fs, root);
}
public void add(String fileName, byte[] contents) throws IOException {
Path zipPath = fs.getPath(root.toString(), fileName);
if (Files.notExists(zipPath.getParent())) {
Files.createDirectories(zipPath.getParent());
}
Files.write(zipPath, contents, CREATE, WRITE);
}
public void add(String fileName, String contents) throws IOException {
add(fileName, contents.getBytes(StandardCharsets.UTF_8));
}
public void addDir(String dirName) throws IOException {
Path zipPath = fs.getPath(root.toString(), dirName);
if (Files.notExists(zipPath)) {
Files.createDirectories(zipPath);
}
}
public Set<String> getDirNames() throws IOException {
final ImmutableSet.Builder<String> contents = ImmutableSet.builder();
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
throws IOException {
// Skip the leading "/" from the path.
contents.add(dir.toString().substring(1));
return FileVisitResult.CONTINUE;
}
});
return contents.build();
}
public Set<String> getFileNames() throws IOException {
final ImmutableSet.Builder<String> contents = ImmutableSet.builder();
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
// Skip the leading "/" from the path.
contents.add(file.toString().substring(1));
return FileVisitResult.CONTINUE;
}
});
return contents.build();
}
public byte[] readFully(String fileName) throws IOException {
Path resolved = root.resolve(fileName);
return Files.readAllBytes(resolved);
}
@Override
public void close() throws IOException {
fs.close();
}
}
| 37.488889 | 99 | 0.721597 |
4a86c757ae84a5dad07526101bde7f4585cc5e7e | 1,860 | package mcjty.meecreeps.api;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import org.apache.commons.lang3.tuple.Pair;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.List;
/**
* A factory for actions
*/
public interface IActionFactory {
/**
* Return true if this action is possible given the targetted block and
* surroundings
*/
boolean isPossible(World world, BlockPos pos, EnumFacing side);
/**
* Return true if this action is possible given the targetted block
* but maybe not with surroundings. i.e. it is possible to do this but
* some items may be missing or some circumstances may be less ideal for this
* task
*/
boolean isPossibleSecondary(World world, BlockPos pos, EnumFacing side);
/**
* Optionally return a heading for further questions. If this returns null then
* there are no further questions. This is called client-side!
*/
@Nullable
default String getFurtherQuestionHeading(World world, BlockPos pos, EnumFacing side) { return null; }
/**
* Return a list of possible further questions. If there are no further questions this will
* return an empty list. The array should be a pair of Id and question. The question will be
* asked to the user and the id is what will be given to the action when it is finally executed
* This is called client-side!
*/
@Nonnull
default List<Pair<String, String>> getFurtherQuestions(World world, BlockPos pos, EnumFacing side) { return Collections.emptyList(); }
/**
* Actually create the action. If this is a 'question' factory then
* this will return null
*/
IActionWorker createWorker(@Nonnull IWorkerHelper helper);
}
| 34.444444 | 138 | 0.714516 |
80b25f4e726a7b2f455847de4d3b88cfbc9c67e6 | 419 | package com.groupdocs.ui.viewer.cache.mixin;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.groupdocs.viewer.FileType;
import com.groupdocs.viewer.results.Page;
import java.util.List;
public abstract class OutlookViewInfoMixIn {
OutlookViewInfoMixIn(@JsonProperty("fileType") FileType fileType, @JsonProperty("pages") List<Page> pages, @JsonProperty("folders") List<String> folders) {
}
}
| 29.928571 | 159 | 0.787589 |
0ac6d05d6bf5cca428ed9f69f53b0f51c1abf748 | 4,731 | /*
* Copyright 2018 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.template.soy.passes.htmlmatcher;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
import com.google.template.soy.base.SourceLocation;
import com.google.template.soy.base.internal.IncrementingIdGenerator;
import com.google.template.soy.error.ErrorReporter;
import com.google.template.soy.exprtree.ExprNode;
import com.google.template.soy.passes.htmlmatcher.HtmlMatcherTagNode.TagKind;
import com.google.template.soy.soyparse.SoyFileParser;
import com.google.template.soy.soytree.HtmlCloseTagNode;
import com.google.template.soy.soytree.HtmlOpenTagNode;
import com.google.template.soy.soytree.HtmlTagNode.TagExistence;
import com.google.template.soy.soytree.IfCondNode;
import com.google.template.soy.soytree.IfNode;
import com.google.template.soy.soytree.RawTextNode;
import com.google.template.soy.soytree.SoyNode;
import com.google.template.soy.soytree.SoyNode.Kind;
import com.google.template.soy.soytree.SwitchCaseNode;
/** Utility functions for HTML Matcher Graph tests. */
public final class TestUtils {
private static final IncrementingIdGenerator idGenerator = new IncrementingIdGenerator();
public static HtmlOpenTagNode soyHtmlOpenTagNode() {
return new HtmlOpenTagNode(
idGenerator.genId(),
new RawTextNode(idGenerator.genId(), "div", SourceLocation.UNKNOWN),
SourceLocation.UNKNOWN,
/** selfClosing */
false,
TagExistence.IN_TEMPLATE);
}
public static HtmlCloseTagNode soyHtmlCloseTagNode() {
return new HtmlCloseTagNode(
idGenerator.genId(),
new RawTextNode(idGenerator.genId(), "div", SourceLocation.UNKNOWN),
SourceLocation.UNKNOWN,
TagExistence.IN_TEMPLATE);
}
public static HtmlMatcherTagNode htmlMatcherOpenTagNode(HtmlOpenTagNode soyNode) {
return new HtmlMatcherTagNode(soyNode);
}
public static HtmlMatcherTagNode htmlMatcherCloseTagNode(HtmlCloseTagNode soyNode) {
return new HtmlMatcherTagNode(soyNode);
}
public static ExprNode soyExprNode(String exprText) {
return SoyFileParser.parseExpression(
exprText,
ErrorReporter.exploding());
}
public static IfCondNode soyIfCondNode(String exprText) {
IfCondNode soyNode =
new IfCondNode(idGenerator.genId(), SourceLocation.UNKNOWN, "if", soyExprNode(exprText));
IfNode parentIfNode = new IfNode(idGenerator.genId(), SourceLocation.UNKNOWN);
parentIfNode.addChild(soyNode);
return soyNode;
}
public static IfCondNode soyIfElseCondNode(String exprText) {
IfCondNode soyNode =
new IfCondNode(
idGenerator.genId(), SourceLocation.UNKNOWN, "elseif", soyExprNode(exprText));
IfNode parentIfNode = new IfNode(idGenerator.genId(), SourceLocation.UNKNOWN);
parentIfNode.addChild(soyNode);
return soyNode;
}
public static SwitchCaseNode soySwitchCaseNode(String exprText) {
SwitchCaseNode soyNode =
new SwitchCaseNode(
idGenerator.genId(), SourceLocation.UNKNOWN, ImmutableList.of(soyExprNode(exprText)));
IfNode parentIfNode = new IfNode(idGenerator.genId(), SourceLocation.UNKNOWN);
parentIfNode.addChild(soyNode);
return soyNode;
}
public static void assertNodeIsOpenTagWithName(HtmlMatcherGraphNode node, String tagName) {
assertThat(node).isInstanceOf(HtmlMatcherTagNode.class);
assertThat(((HtmlMatcherTagNode) node).getTagKind()).isEqualTo(TagKind.OPEN_TAG);
SoyNode soyNode = node.getSoyNode().get();
assertThat(soyNode.getKind()).isEqualTo(Kind.HTML_OPEN_TAG_NODE);
assertThat(((HtmlOpenTagNode) soyNode).getTagName().toString()).isEqualTo(tagName);
}
public static void assertNodeIsCloseTagWithName(HtmlMatcherGraphNode node, String tagName) {
assertThat(node).isInstanceOf(HtmlMatcherTagNode.class);
assertThat(((HtmlMatcherTagNode) node).getTagKind()).isEqualTo(TagKind.CLOSE_TAG);
SoyNode soyNode = node.getSoyNode().get();
assertThat(soyNode.getKind()).isEqualTo(Kind.HTML_CLOSE_TAG_NODE);
assertThat(((HtmlCloseTagNode) soyNode).getTagName().toString()).isEqualTo(tagName);
}
}
| 39.425 | 98 | 0.760727 |
d6a9fb7be216147b83cc4b977c129ce611057b7a | 2,559 | package net.blay09.mods.hardcorerevival.network;
import net.blay09.mods.hardcorerevival.HardcoreRevival;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.network.NetworkDirection;
import net.minecraftforge.fml.network.NetworkEvent;
import net.minecraftforge.fml.network.NetworkRegistry;
import net.minecraftforge.fml.network.PacketDistributor;
import net.minecraftforge.fml.network.simple.SimpleChannel;
public class NetworkHandler {
public static final String NETWORK_VERSION = "6";
public static final SimpleChannel channel = NetworkRegistry.newSimpleChannel(new ResourceLocation(HardcoreRevival.MOD_ID, "network"), () -> NETWORK_VERSION, NETWORK_VERSION::equals, NETWORK_VERSION::equals);
public static void init() {
channel.registerMessage(0, HardcoreRevivalDataMessage.class, HardcoreRevivalDataMessage::encode, HardcoreRevivalDataMessage::decode, HardcoreRevivalDataMessage::handle);
channel.registerMessage(1, RevivalSuccessMessage.class, RevivalSuccessMessage::encode, RevivalSuccessMessage::decode, RevivalSuccessMessage::handle);
channel.registerMessage(2, RescueMessage.class, RescueMessage::encode, RescueMessage::decode, RescueMessage::handle);
channel.registerMessage(3, RevivalProgressMessage.class, RevivalProgressMessage::encode, RevivalProgressMessage::decode, RevivalProgressMessage::handle);
channel.registerMessage(4, AcceptFateMessage.class, (message, buf) -> {}, it -> new AcceptFateMessage(), AcceptFateMessage::handle);
channel.registerMessage(5, HardcoreRevivalConfigMessage.class, HardcoreRevivalConfigMessage::encode, HardcoreRevivalConfigMessage::decode, HardcoreRevivalConfigMessage::handle);
}
public static void sendToPlayer(PlayerEntity player, Object message) {
NetworkHandler.channel.send(PacketDistributor.PLAYER.with(() -> (ServerPlayerEntity) player), message);
}
public static void ensureServerSide(NetworkEvent.Context context) {
if (context.getDirection() != NetworkDirection.PLAY_TO_SERVER) {
throw new UnsupportedOperationException("Expected packet side does not match; expected client");
}
}
public static void ensureClientSide(NetworkEvent.Context context) {
if (context.getDirection() != NetworkDirection.PLAY_TO_CLIENT) {
throw new UnsupportedOperationException("Expected packet side does not match; expected client");
}
}
}
| 60.928571 | 211 | 0.785854 |
646e3fc874a5a91a320b816af2b5c3a15dedd965 | 627 | /**
* @author David Manouchehri
* Created on 7/17/15 at 4:53 PM.
* All content is under the MIT License unless otherwise specified.
* See LICENSE.txt for details.
*
* Page 307, Question P6.6
*/
public class AlternatingSum {
public static void main(String[] args) {
int[] sample = {1, 4, 9, 16, 9, 7, 4, 9, 11};
System.out.println(altSum(sample));
}
public static int altSum(int[] input) {
int holder = 0;
int flip = 1;
for(int i = 0; i < input.length; i++, flip*=-1)
holder += input[i]*flip;
return holder;
}
}
| 27.26087 | 75 | 0.545455 |
4b56182dbdbf61266e8763b4a79097a770226126 | 365 | import org.junit.Test;
import static org.junit.Assert.*;
public class KataIsquaTest {
private double precision = 0.0000000000001;
@Test
public void sampleTestCases() {
// assertEquals(0.0, KataIsqua.findUniq(new double[]{0, 1, 0,}), precision);
assertEquals(2.0, KataIsqua.findUniq(new double[]{1, 1, 1, 2, 1, 1}), precision);
}
}
| 26.071429 | 89 | 0.657534 |
440c2628dca82af49e566f04d596f50771cced60 | 209 | package de.novatec.hawtio;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class HawtioApplicationTests {
@Test
void contextLoads() {
}
}
| 14.928571 | 60 | 0.784689 |
d24e554fc0a02b1827df96653b4b9b92dc1b1878 | 237 | package edu.mit.mitmobile2;
import android.content.Context;
public class LibraryLoanActionRow extends TwoLineActionRow {
public LibraryLoanActionRow(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
}
| 19.75 | 60 | 0.793249 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.