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
|
|---|---|---|---|---|---|
c147c1f400e32b282b1c485158c7e99ad587b122
| 418
|
package com.usthe.bootshiro.dao;
import com.usthe.bootshiro.domain.bo.AuthOperationLog;
import org.springframework.dao.DataAccessException;
import java.util.List;
/* *
* @Author tomsun28
* @Description
* @Date 8:28 2018/4/22
*/
public interface AuthOperationLogMapper {
List<AuthOperationLog> selectOperationLogList();
int insertSelective(AuthOperationLog operationLog) throws DataAccessException;
}
| 22
| 82
| 0.782297
|
39719e4d1820ae77f5ad6cd4fb00b22c39f5217d
| 3,445
|
package com.laomei.sis;
import org.apache.kafka.connect.sink.SinkRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import static com.laomei.sis.Transform.SIS_TRANSFORMED_RESULT;
/**
* @author laomei on 2018/12/2 15:08
*/
public class SisPipeline implements Pipeline {
private static final Logger log = LoggerFactory.getLogger(SisPipeline.class);
private final AbstractTaskContext taskContext;
private final Reducer reducer;
private final TransformContext transformContext;
private final Executor executor;
private final AtomicBoolean isClose;
public SisPipeline(AbstractTaskContext taskContext) {
this.taskContext = taskContext;
this.transformContext = taskContext.transformContext();
this.executor = taskContext.executor();
this.reducer = taskContext.reducer();
this.isClose = new AtomicBoolean(false);
}
@Override
public void handle(Collection<SinkRecord> sinkRecords) {
if (isClose.get()) {
return;
}
List<SisRecord> sisRecords = convertToSisRecord(sinkRecords);
List<SisRecord> transedRecords = new ArrayList<>(sisRecords.size());
for (SisRecord sisRecord : sisRecords) {
String topic = sisRecord.getTopic();
Transform transform = transformContext.getTransform(topic);
SisRecord record = transform.trans(sisRecord);
if (record != null) {
transedRecords.add(record);
}
}
if (transedRecords.isEmpty()) {
return;
}
List<SisRecord> records = convertTransformResultsToSisRecords(transedRecords);
List<SisRecord> executedRecords = executor.execute(records);
if (executedRecords.isEmpty()) {
return;
}
reducer.reduce(executedRecords);
}
@Override
public void shutdown() {
if (isClose.compareAndSet(false, true)) {
if (taskContext != null) {
log.info("shutdown SisPipeline; Pipeline task name {}", taskContext.getTaskName());
taskContext.close();
}
}
}
private List<SisRecord> convertTransformResultsToSisRecords(List<SisRecord> transedRecords) {
List<SisRecord> sisRecords = new ArrayList<>();
for (SisRecord sisRecord : transedRecords) {
String topic = sisRecord.getTopic();
List<Map<String, Object>> transedResults = (List<Map<String, Object>>) sisRecord.getValue(SIS_TRANSFORMED_RESULT);
for (Map<String, Object> result : transedResults) {
if (!CollectionUtils.isEmpty(result)) {
sisRecords.add(new SisRecord(topic, result));
}
}
}
return sisRecords;
}
private List<SisRecord> convertToSisRecord(Collection<SinkRecord> sinkRecords) {
List<SisRecord> sisRecords = new ArrayList<>(sinkRecords.size());
for (SinkRecord record : sinkRecords) {
if (record == null || record.value() == null) {
continue;
}
sisRecords.add(new SisRecord(record));
}
return sisRecords;
}
}
| 33.77451
| 126
| 0.634833
|
b72dec0990c3bf2bd825886bf8b43fa9f38c673f
| 443
|
package babylisp.values;
import javax.annotation.Nonnull;
public abstract class SimpleValue extends Value {
public SimpleValue(@Nonnull ValueType type) {
super(type);
if (type.category() != ValueCategory.VC_simple)
throw new IllegalStateException();
}
@Override
public SimpleValue doCopy() {
return this;
}
@Override
public boolean immutable() {
return true;
}
}
| 20.136364
| 55
| 0.638826
|
8fca8f5677207ae544b59fdb514dceec398bb4f0
| 3,259
|
package com.comb.dataset;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.comb.dataset.beans.ActionBean;
import com.comb.dataset.beans.ItemBean;
public class InputFileDigester {
private Document doc;
private List<ActionBean> actionBeans = new ArrayList<ActionBean>();
//private SolventDataSet workingSolventDataSet;
public InputFileDigester(InputStream in) {
SAXReader reader = new SAXReader();
try {
doc = reader.read(in);
parseData();
} catch (DocumentException e) {
// log.error("Error when attmeping to parse input file", e);
}
}
public List<ActionBean> getActionBeans() {
return actionBeans;
}
/**
* @param Element <paramter> </paramter>
* @return ItemBean
*/
private ItemBean parseItems(Element element){
List vECList = new ArrayList<>() ;
List iECList = new ArrayList<>() ;
ItemBean itemBean =null;
Element elm = null;
// Element paraElement=null;
String name=null;
List<Element> itemElements;
//get action name
if (element != null) {
// paraElement =element.element("paramter");
name = element.attributeValue("name");
itemBean=new ItemBean(name);
} else{
return null;
}
itemElements=element.elements("item");//items
Iterator<Element> iterator = null;
iterator = itemElements.iterator();
while (iterator != null && iterator.hasNext()) {//parsing the items
elm = iterator.next();
if(elm.attributeValue("type").equalsIgnoreCase("vec")){ //valid EC item
vECList.add(elm.getTextTrim());
}
if(elm.attributeValue("type").equalsIgnoreCase("iec")){ //invalid EC item
iECList.add(elm.getTextTrim());
}
}
itemBean.setIECList(iECList).setVECList(vECList);
return itemBean;
}
/**
* @param Element <action> </action>
* @return ActionBean
*/
private ActionBean parseAction(Element element){
Element elm = null;
String name=null;
String comb=null;
List<Element> itemElements;
ActionBean actionBean;
//get action name
if (element != null) {
name = element.attributeValue("name");
comb = element.attributeValue("comb");
actionBean=new ActionBean(name,comb);
} else{
return null;
}
itemElements=element.elements("parameter");//Parameters
Iterator<Element> iterator = null;
List<ItemBean> itemBeans= new ArrayList<ItemBean>();
iterator = itemElements.iterator();
while (iterator != null && iterator.hasNext()) {//parsing the items
elm = iterator.next();
itemBeans.add(parseItems(elm));
}
actionBean.setItemBeans(itemBeans);
return actionBean;
}
/**
*
* @return List<ActionBean>
*/
public void parseData() {
Element rootElement = this.doc.getRootElement();
List<Element> actionsElements = rootElement.elements("action");
for(Element element:actionsElements){
ActionBean bean =parseAction(element); //one action
if(null !=bean){
actionBeans.add(bean);
}
}
}
}
| 25.460938
| 76
| 0.666769
|
5767d18cad7352da96667874fbe177aef50882c2
| 1,305
|
package leetcode;
public class DFS_100 {
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null&&q==null){
return true;
}
else if(p==null||q==null){
return false;
}
else if(p.left==null){
if(q.left==null){
if(p.val==q.val){
return isSameTree(p.right,q.right);
}
else{
return false;
}
}
else{
return false;
}
}
else if(p.right==null){
if(q.right==null){
if(p.val==q.val){
return isSameTree(p.left,q.left);
}
else{
return false;
}
}
else{
return false;
}
}
else{
if(p.val==q.val){
return isSameTree(p.left,q.left)&&isSameTree(p.right,q.right);
}
else{
return false;
}
}
}
}
}
| 26.1
| 82
| 0.30728
|
2ea13f70cc182cb6ecd31d5b7ab6314b546451ca
| 1,876
|
package au.com.centrumsystems.hudson.plugin.buildpipeline.testsupport;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.net.URL;
import static au.com.centrumsystems.hudson.plugin.buildpipeline.testsupport.TestUtils.elementIsPresent;
import static au.com.centrumsystems.hudson.plugin.buildpipeline.testsupport.TestUtils.waitForElement;
public class PipelinePage implements Page {
private static final String TRIGGER_PIPELINE_BUTTON = "trigger-pipeline-button";
private final String pipelineName;
private final WebDriver webDriver;
private final URL baseUrl;
public PipelinePage(WebDriver webDriver, String pipelineName, URL baseUrl) {
this.webDriver = webDriver;
this.pipelineName = pipelineName;
this.baseUrl = baseUrl;
}
public PipelinePage open() {
webDriver.get(baseUrl + getRelativeUrl());
return this;
}
public boolean runButtonIsPresent() {
return triggerPipelineButton() != null;
}
public boolean runButtonIsAbsent() {
waitForElement(By.xpath("//img[@alt='Pipeline History']"), webDriver);
return !elementIsPresent(By.id(TRIGGER_PIPELINE_BUTTON), webDriver);
}
public PipelinePage clickRunButton() {
triggerPipelineButton().click();
return this;
}
public void reload() throws Exception {
webDriver.navigate().refresh();
}
public BuildCardComponent buildCard(int pipelineGroup, int pipeline, int card) {
return new BuildCardComponent(webDriver, pipelineGroup, pipeline, card).waitFor();
}
private WebElement triggerPipelineButton() {
return waitForElement(By.id(TRIGGER_PIPELINE_BUTTON), webDriver);
}
@Override
public String getRelativeUrl() {
return "view/" + pipelineName;
}
}
| 30.258065
| 103
| 0.715885
|
77bf0f08673bf14a626e670de89c92cd8624a74a
| 4,929
|
package org.apache.commons.io.output;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;
public class WriterOutputStream extends OutputStream {
private static final int DEFAULT_BUFFER_SIZE = 1024;
private final CharsetDecoder decoder;
private final ByteBuffer decoderIn;
private final CharBuffer decoderOut;
private final boolean writeImmediately;
private final Writer writer;
public WriterOutputStream(Writer writer, CharsetDecoder decoder) {
this(writer, decoder, 1024, false);
}
public WriterOutputStream(Writer writer, CharsetDecoder decoder, int bufferSize, boolean writeImmediately) {
this.decoderIn = ByteBuffer.allocate(128);
checkIbmJdkWithBrokenUTF16(decoder.charset());
this.writer = writer;
this.decoder = decoder;
this.writeImmediately = writeImmediately;
this.decoderOut = CharBuffer.allocate(bufferSize);
}
public WriterOutputStream(Writer writer, Charset charset, int bufferSize, boolean writeImmediately) {
this(writer, charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE).replaceWith("?"), bufferSize, writeImmediately);
}
public WriterOutputStream(Writer writer, Charset charset) {
this(writer, charset, 1024, false);
}
public WriterOutputStream(Writer writer, String charsetName, int bufferSize, boolean writeImmediately) {
this(writer, Charset.forName(charsetName), bufferSize, writeImmediately);
}
public WriterOutputStream(Writer writer, String charsetName) {
this(writer, charsetName, 1024, false);
}
@Deprecated
public WriterOutputStream(Writer writer) {
this(writer, Charset.defaultCharset(), 1024, false);
}
public void write(byte[] b, int off, int len) throws IOException {
while (len > 0) {
int c = Math.min(len, this.decoderIn.remaining());
this.decoderIn.put(b, off, c);
processInput(false);
len -= c;
off += c;
}
if (this.writeImmediately) {
flushOutput();
}
}
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
public void write(int b) throws IOException {
write(new byte[]{(byte) b}, 0, 1);
}
public void flush() throws IOException {
flushOutput();
this.writer.flush();
}
public void close() throws IOException {
processInput(true);
flushOutput();
this.writer.close();
}
private void processInput(boolean endOfInput) throws IOException {
this.decoderIn.flip();
while (true) {
CoderResult coderResult = this.decoder.decode(this.decoderIn, this.decoderOut, endOfInput);
if (!coderResult.isOverflow()) {
break;
}
flushOutput();
}
if (coderResult.isUnderflow()) {
this.decoderIn.compact();
return;
}
throw new IOException("Unexpected coder result");
}
private void flushOutput() throws IOException {
if (this.decoderOut.position() > 0) {
this.writer.write(this.decoderOut.array(), 0, this.decoderOut.position());
this.decoderOut.rewind();
}
}
private static void checkIbmJdkWithBrokenUTF16(Charset charset) {
if ("UTF-16".equals(charset.name())) {
String TEST_STRING_2 = "vés";
byte[] bytes = "vés".getBytes(charset);
CharsetDecoder charsetDecoder2 = charset.newDecoder();
ByteBuffer bb2 = ByteBuffer.allocate(16);
CharBuffer cb2 = CharBuffer.allocate("vés".length());
int len = bytes.length;
int i = 0;
while (i < len) {
bb2.put(bytes[i]);
bb2.flip();
try {
charsetDecoder2.decode(bb2, cb2, i == len + -1);
bb2.compact();
i++;
} catch (IllegalArgumentException e) {
throw new UnsupportedOperationException("UTF-16 requested when runninng on an IBM JDK with broken UTF-16 support. Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
}
}
cb2.rewind();
if (!"vés".equals(cb2.toString())) {
throw new UnsupportedOperationException("UTF-16 requested when runninng on an IBM JDK with broken UTF-16 support. Please find a JDK that supports UTF-16 if you intend to use UF-16 with WriterOutputStream");
}
}
}
}
| 35.978102
| 226
| 0.627308
|
1832b01ea0e1be6614f69d858c6459bf31642a33
| 920
|
package com.feedzai.openml.h2o.algos.mocks;
import water.api.API;
import water.api.schemas3.ModelParametersSchemaV3;
/**
* Mocked class that extends {@link water.bindings.pojos.ModelParametersSchemaV3} having a private static field named
* {@code fields}.
*
* @author Miguel Cruz (miguel.cruz@feedzai.com)
* @since 1.0.7
*/
public class PrivateFieldsFieldParameters extends ModelParametersSchemaV3 {
/**
* Private field used for tests.
*/
private static final String[] fields = new String[]{"field_1", "field_2"}; //NOPMD
@API(
level = API.Level.critical,
direction = API.Direction.INPUT,
gridable = true,
help = "field 1"
)
public int field_1;
@API(
level = API.Level.secondary,
direction = API.Direction.INPUT,
gridable = true,
help = "field 2"
)
public int field_2;
}
| 25.555556
| 117
| 0.627174
|
e16a9d59d64820b2747189eba162962bf9c891ad
| 88,263
|
/*
* Copyright 2019 Coordinador Electrico Nacional
*
* 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 cl.coordinador.peajes;
import static cl.coordinador.peajes.PeajesConstant.NUMERO_MESES;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.ss.util.AreaReference;
import org.apache.poi.ss.util.CellReference;
import java.util.Properties;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Name;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
* @author aramos
*/
public class Lee {
public static int leeClientes(String libroEntrada, String[] TextoTemporal1, String[] Exento) {
int numClientes = 0;
Cell c2 = null;
Cell c3 = null;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("clientes");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=2) {
Row r = s.getRow(crefs[i].getRow());
c2 = r.getCell(crefs[i].getCol());
c3 = r.getCell(crefs[i+1].getCol());//Ajuste
Exento[numClientes]=c3.toString().trim();//Ajuste
TextoTemporal1[numClientes] = c2.toString().trim();// Nombre
numClientes++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numClientes;
}
public static int leeCentrales(String libroEntrada, String[] TextoTemporal,float[] Potencia, float[] MedioGene) {
int numCentrales = 0;
Cell c1 = null;
Cell c2 = null;
Cell c3 = null;
Cell c4 = null;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("centrales");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=4) {
Row r = s.getRow(crefs[i].getRow());
c1 = r.getCell(crefs[i].getCol());
c2 = r.getCell(crefs[i+1].getCol());
c3 = r.getCell(crefs[i+2].getCol());
c4 = r.getCell(crefs[i+3].getCol());
Potencia[numCentrales]= (float) c3.getNumericCellValue();
MedioGene[numCentrales]= (float) c4.getNumericCellValue();
TextoTemporal[numCentrales] = c2.toString().trim()+"#"+c1.toString().trim(); // Nombre
//System.out.println( TextoTemporal[numCentrales]);
numCentrales++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numCentrales;
}
public static int leeVATT(String libroEntrada, String[] TextoTemporal1, String[] TextoTemporal2, double[][] VATT) {
int numLineasPeajes = 0;
try {
Cell c1 = null;
int nomRangoInd;
Name nomRango;
AreaReference aref;
CellReference[] crefs;
Sheet s;
////POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
// Lectura de datos
nomRangoInd = wb.getNameIndex("lineasVATT");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i++) {
Row r = s.getRow(crefs[i].getRow());
c1 = r.getCell(crefs[i].getCol());
TextoTemporal1[i] = c1.toString().trim();
}
// Lectura de datos
nomRangoInd = wb.getNameIndex("transmisores");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i++) {
Row r = s.getRow(crefs[i].getRow());
c1 = r.getCell(crefs[i].getCol());
TextoTemporal2[i] = c1.toString().trim();
}
// Lectura de datos
nomRangoInd = wb.getNameIndex("VATT");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=NUMERO_MESES) {
Row r = s.getRow(crefs[i].getRow());
for (int j=0; j<NUMERO_MESES; j++) {
c1 = r.getCell(crefs[i + j].getCol());
VATT[numLineasPeajes][j] = c1.getNumericCellValue();
}
numLineasPeajes++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numLineasPeajes;
}
public static void leeEscribeArchivoVATT(String libroEntrada,String libroAVICOMA,int Ano) {
try {
Sheet s;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroAVICOMA ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroAVICOMA ));
s=wb.getSheet("VATT");
// Lectura de datos
int NT=s.getLastRowNum()-3;
String[] Tramo=new String[NT];
String[] Prop=new String[NT];
//String[] Comen=new String[NT];
double[][] VATT=new double[NT][NUMERO_MESES];
int aux=17+12*(Ano-2005);
//System.out.println(NT);
// Lectura de datos
for (int i=0; i<NT; i++) {
Tramo[i]= s.getRow(i+1).getCell(1).toString();
Prop[i]=s.getRow(i+1).getCell(2).toString();
for(int k=0;k<NUMERO_MESES;k++){
VATT[i][k]=s.getRow(i+1).getCell(k+aux).getNumericCellValue();
}
}
s=wb.getSheet("DatosIndex");
for (int i=0; i<NT; i++) {
//Comen[i]= s.getRow(i+1).getCell(13).toString();
}
//Escribe lo clientes en hoja clientes
//POIFSFileSystem fsEnt = new //POIFSFileSystem(new FileInputStream(libroEntrada));
XSSFWorkbook wbEnt = new XSSFWorkbook(new FileInputStream(libroEntrada));
s=wbEnt.getSheet("VATT");
String nomhoja=s.getSheetName();
Cell cellTx = null;
Cell cell= null;
Cell cellTram = null;
Cell cellDat = null;
Row row=null;
short fila = 5;
Font font = wbEnt.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Century Gothic");
CellStyle estilo = wbEnt.createCellStyle();
estilo.setFont(font);
CellStyle estilo1 = wbEnt.createCellStyle();
estilo1.setFont(font);
estilo1.setBorderRight(BorderStyle.THIN);
estilo1.setRightBorderColor(IndexedColors.PALE_BLUE.getIndex());
CellStyle estilo2 = wbEnt.createCellStyle();
estilo2.setFont(font);
estilo2.setBorderLeft(BorderStyle.THIN);
estilo2.setLeftBorderColor(IndexedColors.PALE_BLUE.getIndex());
// Datos
for(int i=0;i<NT;i++){
row = s.createRow(fila); fila++;
cellTram = row.createCell(1);
cellTram.setCellValue(Tramo[i]);
cellTram.setCellStyle(estilo);
cellTx = row.createCell(2);
cellTx.setCellValue(Prop[i]);
cellTx.setCellStyle(estilo1);
for(int k=0;k<NUMERO_MESES;k++){
cellDat = row.createCell(k+3);
cellDat.setCellValue(VATT[i][k]/12);
cellDat.setCellStyle(estilo);
}
/* cell = row.createCell(15);
cell.setCellValue(Comen[i]);
cell.setCellStyle(estilo2);
*
*/
}
// Crea nombre de rango de salida
wbEnt.removeName("lineasVATT");
Name nombreTramo = wbEnt.createName();
nombreTramo.setNameName("lineasVATT"); // Nombre del rango
CellReference cellRef2 = new CellReference(cellTram.getRowIndex(), cellTram.getColumnIndex());
String reference2 = "VATT"+"!B6:"+cellRef2.formatAsString(); // area reference
nombreTramo.setRefersToFormula(reference2);
wbEnt.removeName("transmisores");
Name nombreTx = wbEnt.createName();
nombreTx.setNameName("transmisores"); // Nombre del rango
CellReference cellRef1 = new CellReference(cellTx.getRowIndex(), cellTx.getColumnIndex());
String reference1 = "VATT"+"!C6:"+cellRef1.formatAsString(); // area reference
nombreTx.setRefersToFormula(reference1);
wbEnt.removeName("VATT");
Name nombreDatos = wbEnt.createName();
nombreDatos.setNameName("VATT"); // Nombre del rango
CellReference cellRef = new CellReference(cellDat.getRowIndex(), cellDat.getColumnIndex());
String reference = "VATT"+"!D6:"+cellRef.formatAsString(); // area reference
nombreDatos.setRefersToFormula(reference);
FileOutputStream archivoSalida = new FileOutputStream( libroEntrada );
wbEnt.write(archivoSalida);
archivoSalida.close();
System.out.println( "Acaba de extraer los VATT y asignarlos en la planilla Ent"+Ano+".xlsx" );
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void leeEscribeIndices(String libroEntrada,String libroAVICOMA,int Ano) {
Cell cell=null;
try {
Sheet s;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroAVICOMA ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroAVICOMA ));
s=wb.getSheet("Indices");
// Lectura de datos
int UltimoDato=0;
int FilaAno=5+(Ano-2004)*12;
double[] dolar=new double[NUMERO_MESES];
boolean fin=false;
for (int i=0; i<NUMERO_MESES; i++) {
if(fin==false){
cell=s.getRow(FilaAno+i).getCell(2);
//System.out.println(cell);
if(cell==null){
dolar[i]=0;
UltimoDato=i;
fin=true;
}
else
dolar[i]=cell.getNumericCellValue();
}
else
dolar[i]=0;
}
//Escribe los datos en libro de entrada
//POIFSFileSystem fsEnt = new //POIFSFileSystem(new FileInputStream(libroEntrada));
XSSFWorkbook wbEnt = new XSSFWorkbook(new FileInputStream(libroEntrada));
Sheet hoja=wbEnt.getSheet("indices");
String nhoja=hoja.getSheetName();
Cell cellDat = null;
Row row=null;
short fila = 4;
Font font = wbEnt.createFont();
font.setFontHeightInPoints((short)10);
font.setFontName("Century Gothic");
CellStyle estilo = wbEnt.createCellStyle();
estilo.setFont(font);
CellStyle estilo1 = wbEnt.createCellStyle();
estilo1.setFont(font);
estilo1.setBorderRight(BorderStyle.THIN);
estilo1.setRightBorderColor(IndexedColors.PALE_BLUE.getIndex());
CellStyle estilo2 = wbEnt.createCellStyle();
estilo2.setFont(font);
estilo2.setBorderLeft(BorderStyle.THIN);
estilo2.setLeftBorderColor(IndexedColors.PALE_BLUE.getIndex());
// Datos
for(int i=0;i<NUMERO_MESES;i++){
row = hoja.getRow(fila); fila++;
cellDat = row.createCell(2);
if(dolar[i]==0){
cellDat.setCellValue(dolar[UltimoDato-1]);
cellDat.setCellStyle(estilo);
}
else{
cellDat.setCellValue( dolar[i]);
cellDat.setCellStyle(estilo);
}
}
// Crea nombre de rango de salida
wbEnt.removeName("dolar");
Name nombreDatos = wbEnt.createName();
nombreDatos.setNameName("dolar"); // Nombre del rango
CellReference cellRef = new CellReference(cellDat.getRowIndex(), cellDat.getColumnIndex());
String reference = nhoja+"!C5:"+cellRef.formatAsString(); // area reference
nombreDatos.setRefersToFormula(reference);
FileOutputStream archivoSalida = new FileOutputStream( libroEntrada );
wbEnt.write(archivoSalida);
archivoSalida.close();
System.out.println( "Acaba de extraer el Dolar y asignarlo en la planilla Ent"+Ano+".xlsx" );
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int leeDeflin(String libroEntrada, String[] TextoTemporal1, double[][] Aux) {
int numLineas = 0;
double zBase;
double sBase = 100;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("deflin");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=12) {
Row r = s.getRow(crefs[i].getRow());
Cell c2 = null;
Cell c3 = null;
Cell c4 = null;
Cell c5 = null;
Cell c6 = null;
Cell c7 = null;
Cell c8 = null;
Cell c9 = null;
Cell c10 = null;
Cell c11 = null;
Cell c12= null;
c2 = r.getCell(crefs[i+1].getCol());
c3 = r.getCell(crefs[i+2].getCol());
c4 = r.getCell(crefs[i+3].getCol());
c5 = r.getCell(crefs[i+4].getCol());
c6 = r.getCell(crefs[i+5].getCol());
c7 = r.getCell(crefs[i+6].getCol());
c8 = r.getCell(crefs[i+7].getCol());
c9 = r.getCell(crefs[i+8].getCol());
c10 = r.getCell(crefs[i+9].getCol());
c11 = r.getCell(crefs[i+10].getCol());
c12 = r.getCell(crefs[i+11].getCol());
TextoTemporal1[numLineas]=c2.toString().trim(); //Nombre
Aux[numLineas][0] = (int) c3.getNumericCellValue() - 1; // Barra_A
Aux[numLineas][1] = (int) c4.getNumericCellValue() - 1; // Barra_B
Aux[numLineas][2] = c5.getNumericCellValue(); // V_[kV]
zBase=Aux[numLineas][2]*Aux[numLineas][2]/sBase;
Aux[numLineas][3] = c6.getNumericCellValue()/zBase; // R_[ohm]/zBase
Aux[numLineas][4] = c7.getNumericCellValue()/zBase; // X_[ohm]/zBase
Aux[numLineas][5] = (int) c8.getNumericCellValue(); //Operativa
Aux[numLineas][6] = (int) c9.getNumericCellValue(); //Troncal
Aux[numLineas][7] = (int) c10.getNumericCellValue(); //Zona
Aux[numLineas][8] = (int) c11.getNumericCellValue(); //dir
Aux[numLineas][9] = (int) c12.getNumericCellValue(); //Area
numLineas++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numLineas;
}
public static int leeLintron(String libroEntrada, String[] TextoTemporal, String[] nombreLineas,String[] nomTx, int[] intAux1, int[][] intAux2) {
int numLineasT = 0;
int numLineasT2 = 0;
int aux;
Cell c1 = null;
Cell c2 = null;
Cell c3 = null;
Cell c4 = null;
Cell c5 = null;
Cell c6 = null;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
AreaReference arefDatos;
CellReference[] crefsDatos;
AreaReference arefTx;
CellReference[] crefsTx;
int nomRangoInd = wb.getNameIndex("lintron");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
int nomRangoIndDatos = wb.getNameIndex("datosLintron");
Name nomRangoDatos = wb.getNameAt(nomRangoIndDatos);
arefDatos = new AreaReference(nomRangoDatos.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsDatos = arefDatos.getAllReferencedCells();
int nomRangoindDatosTx = wb.getNameIndex("transmisorIT");
Name nomRangoDatosTx = wb.getNameAt(nomRangoindDatosTx);
arefTx = new AreaReference(nomRangoDatosTx.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsTx = arefTx.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=2) {
Row r = s.getRow(crefs[i].getRow());
c1 = r.getCell(crefs[i].getCol());
c2 = r.getCell(crefs[i+1].getCol());
TextoTemporal[numLineasT] = c1.toString().trim();
aux=Calc.Buscar(c2.toString().trim(), nombreLineas);
if(aux==-1) {
System.out.println("La línea "+c2.toString().trim()+" en 'lintron' no se encuentra en 'lineas'");
}
intAux1[numLineasT] = aux;
numLineasT++;
}
Sheet m = wb.getSheet(crefsDatos[0].getSheetName());
for (int i=0; i<crefsDatos.length; i+=3) {
Row r = m.getRow(crefsDatos[i].getRow());
c3 = r.getCell(crefsDatos[i].getCol());
c4 = r.getCell(crefsDatos[i+1].getCol());
c5 = r.getCell(crefsDatos[i+2].getCol());
intAux2[numLineasT2][0] = (int) c3.getNumericCellValue();
intAux2[numLineasT2][1] = (int) c4.getNumericCellValue();
intAux2[numLineasT2][2] = (int) c5.getNumericCellValue();
numLineasT2++;
}
for (int i=0; i<crefsTx.length; i++) {
Row r = s.getRow(crefsTx[i].getRow());
c1=r.getCell(crefsTx[i].getCol());
nomTx[i]=c1.toString().trim();
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numLineasT;
}
public static int leeLintronIT(String libroEntrada, String[] TextoTemporal,
String[] TextoTemporal2, String[] nombreLineas, int[] intAux1,
double[][] ITE, double[][] ITP) {
int numLineasT = 0;
int iTemp1;
String TextoTmp;
double ITEAux;
double ITPAux;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
AreaReference arefTx;
CellReference[] crefsTx;
AreaReference arefITE;
CellReference[] crefsITE;
AreaReference arefITP;
CellReference[] crefsITP;
int nomRangoInd = wb.getNameIndex("lintron");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
int nomRangoIndTx = wb.getNameIndex("transmisorIT");
Name nomRangoTx = wb.getNameAt(nomRangoIndTx);
arefTx = new AreaReference(nomRangoTx.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsTx = arefTx.getAllReferencedCells();
int nomRangoIndITE = wb.getNameIndex("ITE");
Name nomRangoITE = wb.getNameAt(nomRangoIndITE);
arefITE = new AreaReference(nomRangoITE.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsITE = arefITE.getAllReferencedCells();
int nomRangoIndITP = wb.getNameIndex("ITP");
Name nomRangoITP = wb.getNameAt(nomRangoIndITP);
arefITP = new AreaReference(nomRangoITP.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsITP = arefITP.getAllReferencedCells();
for (int i=0; i<crefs.length; i+=2) {
Row r = s.getRow(crefs[i].getRow());
Cell c1 = null;
Cell c2 = null;
c1 = r.getCell(crefs[i].getCol());
c2 = r.getCell(crefs[i+1].getCol());
TextoTemporal[numLineasT] = c1.toString().trim();
intAux1[numLineasT] = Calc.Buscar(c2.toString().trim(), nombreLineas);
Cell cTx = r.getCell(crefsTx[0].getCol());
TextoTemporal2[numLineasT] = c1.toString().trim()+"#"+cTx.toString().trim();
for (int m=0; m<NUMERO_MESES; m++) {
Cell cITE = r.getCell(crefsITE[m].getCol());
ITE[numLineasT][m] = (float) cITE.getNumericCellValue();
Cell cITP = r.getCell(crefsITP[m].getCol());
ITP[numLineasT][m] = (float) cITP.getNumericCellValue();
}
if (numLineasT > 0) {
for (int k=numLineasT; k>0; k--) {
if (intAux1[k] < intAux1[k - 1]) {
TextoTmp = TextoTemporal[k];
TextoTemporal[k] = TextoTemporal[k - 1];
TextoTemporal[k - 1] = TextoTmp;
TextoTmp = TextoTemporal2[k];
TextoTemporal2[k] = TextoTemporal2[k - 1];
TextoTemporal2[k - 1] = TextoTmp;
for (int m=0; m<NUMERO_MESES; m++) {
ITEAux = ITE[k][m];
ITPAux = ITP[k][m];
ITE[k][m] = ITE[k - 1][m];
ITP[k][m] = ITP[k - 1][m];
ITE[k - 1][m] = ITEAux;
ITP[k - 1][m] = ITPAux;
}
iTemp1 = intAux1[k];
intAux1[k] = intAux1[k-1];
intAux1[k-1] = iTemp1;
}
}
}
numLineasT++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numLineasT;
}
public static int leePeajes(String libroEntrada, String[] nombreLineas, double[][] longAux) {
int numLineasT = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream(libroEntrada));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("Peajes");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i = 0; i < crefs.length; i += 12) {
Row r = s.getRow(crefs[i].getRow());
nombreLineas[numLineasT] = r.getCell(crefs[i].getCol() - 1).getStringCellValue();
for (int j = 0; j < 12; j += 1) {
longAux[numLineasT][j] = r.getCell(crefs[j].getCol()).getNumericCellValue();
}
numLineasT++;
}
} catch (java.io.FileNotFoundException e) {
System.out.println("No se puede acceder al archivo " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return numLineasT;
}
public static int leeIT(String libroEntrada, String[] nombreLineas, double[][] longAux,String NombreRango) {
int numLineasT = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream(libroEntrada));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex(NombreRango);
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i = 0; i < crefs.length; i += 12) {
Row r = s.getRow(crefs[i].getRow());
nombreLineas[numLineasT] = r.getCell(crefs[i].getCol() - 1).getStringCellValue();
for (int j = 0; j < 12; j += 1) {
longAux[numLineasT][j] = r.getCell(crefs[j].getCol()).getNumericCellValue();
}
numLineasT++;
}
} catch (java.io.FileNotFoundException e) {
System.out.println("No se se puede acceder al archivo " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return numLineasT;
}
public static int leeLintronIT2(String libroEntrada, String[] TextoTemporal,
String[] LineasT, String[] nombreLineas, int[] intAux1,
double[][] ITE,double[][] ITEG ,double[][] ITER,double[][] ITP,int[] numLineasIT) {
String[] txtTmp=new String[2500];
String[] txtTmp1=new String[2500];
int numLineasT = 0;
numLineasIT[0] = 0;
for (int i = 0; i < 2500; i++) {
txtTmp[i] = "";
}
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
AreaReference arefTx;
CellReference[] crefsTx;
AreaReference arefITE;
CellReference[] crefsITE;
AreaReference arefITEG;
CellReference[] crefsITEG;
AreaReference arefITER;
CellReference[] crefsITER;
AreaReference arefITP;
CellReference[] crefsITP;
int nomRangoInd = wb.getNameIndex("lintron");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
int nomRangoIndTx = wb.getNameIndex("transmisorIT");
Name nomRangoTx = wb.getNameAt(nomRangoIndTx);
arefTx = new AreaReference(nomRangoTx.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsTx = arefTx.getAllReferencedCells();
int nomRangoIndITE = wb.getNameIndex("ITE");
Name nomRangoITE = wb.getNameAt(nomRangoIndITE);
arefITE = new AreaReference(nomRangoITE.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsITE = arefITE.getAllReferencedCells();
int nomRangoIndITEG = wb.getNameIndex("ITEG");
Name nomRangoITEG = wb.getNameAt(nomRangoIndITEG);
arefITEG = new AreaReference(nomRangoITEG.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsITEG = arefITEG.getAllReferencedCells();
int nomRangoIndITER = wb.getNameIndex("ITER");
Name nomRangoITER = wb.getNameAt(nomRangoIndITER);
arefITER = new AreaReference(nomRangoITER.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsITER = arefITER.getAllReferencedCells();
int nomRangoIndITP = wb.getNameIndex("ITP");
Name nomRangoITP = wb.getNameAt(nomRangoIndITP);
arefITP = new AreaReference(nomRangoITP.getRefersToFormula(), wb.getSpreadsheetVersion());
crefsITP = arefITP.getAllReferencedCells();
for (int i=0; i<crefs.length; i+=2) {
Row r = s.getRow(crefs[i].getRow());
Cell c1 = null;
Cell c2 = null;
c1 = r.getCell(crefs[i].getCol());
c2 = r.getCell(crefs[i+1].getCol());
TextoTemporal[numLineasIT[0]] = c1.getStringCellValue();
intAux1[numLineasIT[0]] = Calc.Buscar(c2.toString().trim(), nombreLineas);
Cell cTx = r.getCell(crefsTx[0].getCol());
txtTmp1[numLineasIT[0]] = c1.getStringCellValue()+"#"+cTx.getStringCellValue();//Linea#Transmisor
int t = Calc.Buscar(txtTmp1[numLineasIT[0]], txtTmp);
if (t == -1) {
txtTmp[numLineasT] =txtTmp1[numLineasIT[0]];
for (int m=0; m<NUMERO_MESES; m++) {
Cell cITE = r.getCell(crefsITE[m].getCol());
ITE[numLineasT][m] = cITE.getNumericCellValue();
Cell cITEG = r.getCell(crefsITEG[m].getCol());
ITEG[numLineasT][m] = cITEG.getNumericCellValue();
Cell cITER = r.getCell(crefsITER[m].getCol());
ITER[numLineasT][m] = cITER.getNumericCellValue();
Cell cITP = r.getCell(crefsITP[m].getCol());
ITP[numLineasT][m] = cITP.getNumericCellValue();
}
numLineasT++;
}
numLineasIT[0]++;
}
for(int i=0;i<numLineasT;i++){
LineasT[i]=txtTmp[i];// registros “nicos Linea#Transmisor
//System.out.println(LineasT[i]+" "+ITE[i][0]);
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numLineasT;
}
static void leeProrratasGx(String libroEntrada, double[][][] prorrataMesGx) {
int numLineas = prorrataMesGx.length;
int numCentrales = prorrataMesGx[0].length;
int k = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("ProrrGMes");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
if(crefs.length!=numLineas*numCentrales*12)
System.out.println("Se eliminaron o agregaron Centrales, pero no se han calculado las Prorratas considerando esta modificación");
for (int i=0; i<numLineas; i++) {
for (int j=0; j<numCentrales; j++) {
Row r = s.getRow(crefs[k*NUMERO_MESES].getRow());
for (int m=0; m<NUMERO_MESES; m++) {
Cell c1 = null;
c1 = r.getCell(crefs[m].getCol());
prorrataMesGx[i][j][m] = c1.getNumericCellValue();
}
k++;
}
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
static void leeProrratasC(String libroEntrada, double[][][] prorrataMesC) {
int numLineas = prorrataMesC.length;
int numClientes = prorrataMesC[0].length;
int k = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("ProrrCMes");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
System.out.println(numLineas+" "+numClientes);
for (int i=0; i<numLineas; i++) {
for (int j=0; j<numClientes; j++) {
Row r = s.getRow(crefs[k*NUMERO_MESES].getRow());
for (int m=0; m<NUMERO_MESES; m++) {
Cell c1 = null;
c1 = r.getCell(crefs[m].getCol());
//System.out.println("líneas "+i+" cliente "+j+ " mes "+m);
prorrataMesC[i][j][m] = c1.getNumericCellValue();
}
k++;
}
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
static void leeGeneracionMes(String libroEntrada, double[][] GenMes) {//agregado para ajuste
int numCentrales = GenMes.length;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("GMes");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i=i+(NUMERO_MESES)) {
Row r = s.getRow(crefs[i].getRow());
Cell cdes = null;
for (int m=0; m<NUMERO_MESES; m++) {
cdes = r.getCell(crefs[m].getCol());
GenMes[i/NUMERO_MESES][m] = (double) cdes.getNumericCellValue();
}
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
static void leeConsumoMes(String libroEntrada, double[][] CMes, double[][][] CU) {//agregado para ajuste
int numConsumos =0;
int cuenta=0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("CMesCli");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
AreaReference aref1;
CellReference[] crefs1;
int nomRangoInd1 = wb.getNameIndex("CU");
Name nomRango1 = wb.getNameAt(nomRangoInd1);
aref1 = new AreaReference(nomRango1.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
for (int i=0; i<crefs.length; i=i+(NUMERO_MESES)) {
Row r = s.getRow(crefs[i].getRow());
for (int m=0; m<NUMERO_MESES; m++) {
Cell cdes = r.getCell(crefs[m].getCol());
CMes[numConsumos][m] =cdes.getNumericCellValue();
}
numConsumos++;
}
for (int i=0; i<crefs1.length; i+=3*NUMERO_MESES) {
Row r1 = s.getRow(crefs1[i].getRow());
for (int m=0; m<NUMERO_MESES; m++) {
Cell c1 = r1.getCell(crefs1[i+m].getCol());
Cell c2 = r1.getCell(crefs1[i+NUMERO_MESES+m].getCol());
Cell c3 = r1.getCell(crefs1[i+2*NUMERO_MESES+m].getCol());
CU[cuenta][0][m] = c1.getNumericCellValue();
CU[cuenta][1][m] = c2.getNumericCellValue();
CU[cuenta][2][m] = c3.getNumericCellValue();
}
cuenta++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
static int[] leeLineasFlujo(String libroEntrada, String nombreLineas[]) {
int[] lineas;
String Linea;
try {
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference arefFlujo = new AreaReference(wb.getNameAt(wb.getNameIndex("lineas_flujo")).getRefersToFormula(), wb.getSpreadsheetVersion());
CellReference[] crefsFlujo = arefFlujo.getAllReferencedCells();
lineas = new int[crefsFlujo.length];
Sheet s = wb.getSheet(crefsFlujo[0].getSheetName());
for (int i = 0 ; i< crefsFlujo.length;i++){
Row r = s.getRow(crefsFlujo[i].getRow());
Linea = r.getCell(crefsFlujo[i].getCol()).toString().trim();
System.out.println(Linea);
lineas[i] = Calc.Buscar(Linea,nombreLineas);
System.out.println(lineas[i]);
}
return lineas;
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return lineas = new int[1];
}
static int[] leeCentralesFlujo(String libroEntrada, String nombreLineas[], String areaNombre) {
int[] lineas;
String Linea;
try {
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference arefFlujo = new AreaReference(wb.getNameAt(wb.getNameIndex(areaNombre)).getRefersToFormula(), wb.getSpreadsheetVersion());
CellReference[] crefsFlujo = arefFlujo.getAllReferencedCells();
lineas = new int[crefsFlujo.length];
Sheet s = wb.getSheet(crefsFlujo[0].getSheetName());
for (int i = 0 ; i< crefsFlujo.length;i++){
Row r = s.getRow(crefsFlujo[i].getRow());
Linea = r.getCell(crefsFlujo[i].getCol()).toString().trim();
System.out.println(Linea);
lineas[i] = Calc.Buscar(Linea,nombreLineas);
System.out.println(lineas[i]);
}
return lineas;
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return lineas = new int[1];
}
static void leeIndices(String libroEntrada, double[] dolar, double[] interes) {
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
// dolar
AreaReference arefDolar = new AreaReference(wb.getNameAt(wb.getNameIndex("dolar")).getRefersToFormula(), wb.getSpreadsheetVersion());
CellReference[] crefsDolar = arefDolar.getAllReferencedCells();
Sheet sDolar = wb.getSheet(crefsDolar[0].getSheetName());
// inter?s
AreaReference arefInteres = new AreaReference(wb.getNameAt(wb.getNameIndex("interes")).getRefersToFormula(), wb.getSpreadsheetVersion());
CellReference[] crefsInteres = arefInteres.getAllReferencedCells();
Sheet sInteres = wb.getSheet(crefsInteres[0].getSheetName());
for (int m=0; m<NUMERO_MESES; m++) {
// dolar
Row rDolar = sDolar.getRow(crefsDolar[m].getRow());
Cell cDolar = null;
cDolar = rDolar.getCell(crefsDolar[m].getCol());
dolar[m] = cDolar.getNumericCellValue();
// inter?s
Row rInteres = sInteres.getRow(crefsInteres[m].getRow());
Cell cInteres = null;
cInteres = rInteres.getCell(crefsInteres[m].getCol());
interes[m] = cInteres.getNumericCellValue();
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int leeDefbar(String libroEntrada, String[] TextoTemporal1, int[][] intAux3) {
int numBarras = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("defbar");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=5) {
Row r = s.getRow(crefs[i].getRow());
Cell c2 = r.getCell(crefs[i+1].getCol());
Cell c3 = r.getCell(crefs[i+2].getCol());
Cell c4 = r.getCell(crefs[i+3].getCol());
Cell c5 = r.getCell(crefs[i+4].getCol());
TextoTemporal1[numBarras] = c2.toString().trim(); // Nombre
intAux3[numBarras][0] = (int) c3.getNumericCellValue(); // 1 si la barra es troncal, 0 en caso contrario
intAux3[numBarras][1] = (int) c4.getNumericCellValue(); // 0 si la barra estö en el AIC, 1 si estö en el norte y -1 si estö en el sur
intAux3[numBarras][2] = (int) c5.getNumericCellValue(); // 1 si la barra está en el SIC, -1 si la barra está en el SING
numBarras++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numBarras;
}
public static void leeConsumoxBarra(String libroEntrada, float[][] Consumos, int numBarras, int numEtapas) {
int cuenta = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("consxbarra");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
if (crefs.length/numEtapas != numBarras) {
System.out.println("Largo registro "+crefs.length+" "+" numero etapas "+numEtapas);
System.out.println("Numero barras "+numBarras);
System.out.println( "Registro de Consumos por Barra mal asignado");
System.exit(0);
}
for (int i=0; i<crefs.length; i+=numEtapas) {
Row r = s.getRow(crefs[i].getRow());
for (int j=0; j<numEtapas; j++) {
Cell c = r.getCell(crefs[i+j].getCol());
Consumos[cuenta][j] = (float) c.getNumericCellValue();
}
cuenta++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void leeEtapas(String libroEntrada, int[] duracionEtapas, int numEtapas) {
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("etapas");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
if (crefs.length != numEtapas) {
System.out.println( "Registro de Etapas mal asignado");
System.exit(0);
}
for (int i=0; i<crefs.length; i++) {
Row r = s.getRow(crefs[i].getRow());
Cell c = r.getCell(crefs[i].getCol());
duracionEtapas[i] = (int) c.getNumericCellValue();
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void leeLinman(String libroEntrada, int[][] LinMan, String[] nombreLineas, int numEtapas) {
String Linea;
int indiceLinea;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("linman");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=(numEtapas+1)) {
Row r = s.getRow(crefs[i].getRow());
Linea = r.getCell(crefs[i].getCol()).toString().trim();
indiceLinea = Calc.Buscar(Linea,nombreLineas);
//System.out.println(Linea);
if(indiceLinea==-1)System.out.println("La línea -"+Linea+"- en 'linman' no se encuentra definida en 'lineas'");
for (int j=0; j<numEtapas; j++) {
Cell c = r.getCell(crefs[i+j+1].getCol());
//System.out.println(i+j+1);
//System.out.println(c.getCellType());
//System.out.println(c.getStringCellValue());
LinMan[indiceLinea][j] = (int) c.getNumericCellValue();
}
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Llena el arreglo temporal con las centrales de plp en el archivo
* libroEntrada <b>excluyendo</> las centrales vacias. Es decir, aquellas
* centrales plp que no tienen un match en central peajes (vacio en columna
* Central Peajes)
* <br>Ademas, guarda informacion auxiliar de la barra a la que esta
* conectada la central y el indice del generador plp en el arreglo
* 'nombreCentrales'
* <br>RANGO EXCEL: plpcnfce
*
* @param libroEntrada ruta completa al archivo de entrada planilla Ent
* @param TextoTemporal1 arreglo temporal a llenar con nombres Centrales PLP
* @param infoAux arreglo bidimensional de informacion adicional donde la
* primera columna [][0] es el numero de la barra en plp y la segunda [][1]
* es el indice del generador en el arreglo nombreCentrales
* @param nombreCentrales arreglo con nombre de generadores peajes
* @return numero de centrales excluyendo las centrales "vacias" (es decir,
* aquellas que no tengan esten vacias en la columna 'Central Peajes' de la
* hoja 'centralesPLP'. Ademas, se detendra si no encuentra en arreglo
* 'nombreCentrales' cualquiera de las centrales en columna 'Central PLP' en
* el libroEntrada
*/
public static int leePlpcnfe(String libroEntrada, String[] nombresGenPLP,
int[][] infoAux, String[] nombreCentrales) {
int numGeneradores = 0;
int aux;
try {
Cell c2 = null;
Cell c3 = null;
Cell c4 = null;
Cell c5 = null;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("plpcnfce");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i = 0; i < crefs.length; i += 5) {
Row r = s.getRow(crefs[i].getRow());
c2 = r.getCell(crefs[i + 1].getCol());
c3 = r.getCell(crefs[i + 2].getCol());
c4 = r.getCell(crefs[i + 3].getCol());
c5 = r.getCell(crefs[i + 4].getCol());
nombresGenPLP[numGeneradores] = c2.toString().trim(); // Nombre
if (c3.getStringCellValue().compareTo("") != 0) {
aux = Calc.Buscar(c4.toString().trim() + "#" + c3.toString().trim(), nombreCentrales);
if (aux == -1) {
System.out.println("El generador PLP " + c2.toString().trim() + " de " + c4.toString().trim() + " en 'centralesPLP' "
+ "no posee una central de peajes asociada en 'centrales'");
}
infoAux[numGeneradores][1] = aux;
infoAux[numGeneradores][0] = (int) c5.getNumericCellValue() - 1; // barra de conexion
if (infoAux[numGeneradores][0] == -1) {
System.out.println("La barra del Generador: " + c4.toString().trim() + "#" + c3.toString().trim() + " se encuentra mal asignada");
}
numGeneradores++;
}
}
} catch (java.io.FileNotFoundException e) {
System.out.println("No se se puede acceder al archivo " + e.getMessage());
} catch (IOException e) {
e.printStackTrace(System.out);
} catch (Exception e) {
e.printStackTrace(System.out);
}
return numGeneradores;
}
/**
* Llena el arreglo temporal con las centrales de plp en el archivo
* libroEntrada <b>incluyendo</> las centrales vacias. Es decir, incluye
* todas las centrales plp
* <br>RANGO EXCEL: plpcnfce
*
* @param libroEntrada ruta completa al archivo de entrada planilla Ent
* @param TextoTemporal1 arreglo temporal a llenar con nombres Centrales PLP
* @param nombreCentrales arreglo con nombre de generadores peajes
* @return numero total de centrales plp
*/
public static int leePlpcnfe(String libroEntrada, String[] TextoTemporal1,
String[] nombreCentrales) {
int numGeneradores = 0;
int aux;
try {
Cell c2 = null;
Cell c3 = null;
Cell c4 = null;
// Cell c5 = null;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("plpcnfce");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i = 0; i < crefs.length; i += 5) {
Row r = s.getRow(crefs[i].getRow());
c2 = r.getCell(crefs[i + 1].getCol());
c3 = r.getCell(crefs[i + 2].getCol());
c4 = r.getCell(crefs[i + 3].getCol());
// c5 = r.getCell(crefs[i + 4].getCol());
TextoTemporal1[numGeneradores] = c2.toString().trim(); // Nombre
if (c3.getStringCellValue().compareTo("") != 0) {
aux = Calc.Buscar(c4.toString().trim() + "#" + c3.toString().trim(), nombreCentrales);
if (aux == -1) {
System.out.println("El generador PLP " + c2.toString().trim() + " de " + c4.toString().trim() + " en 'centralesPLP' "
+ "no posee una central de peajes asociada en 'centrales'");
}
}
numGeneradores++;
}
} catch (java.io.FileNotFoundException e) {
System.out.println("No se se puede acceder al archivo " + e.getMessage());
} catch (IOException e) {
e.printStackTrace(System.out);
} catch (Exception e) {
e.printStackTrace(System.out);
}
return numGeneradores;
}
public static int leeSumin(String libroEntrada, String[] TextoTemporal1) {
int numSumin = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("sumin");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i++) {
Row r = s.getRow(crefs[i].getRow());
Cell c = null;
c = r.getCell(crefs[i].getCol());
TextoTemporal1[numSumin] = c.toString().trim(); // Nombre
numSumin++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numSumin;
}
public static void leeOrient(String libroEntrada, int[][] orientBarTroncal, String[] nombreBarras, String[] nombreLineas) {
String Linea;
int indiceLinea;
String Barra;
int indiceBarra;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref1, aref2;
CellReference[] crefs1, crefs2;
int nomRangoInd2 = wb.getNameIndex("orientCol");
int nomRangoInd3 = wb.getNameIndex("orientFil");
Name nomRango1 = wb.getNameAt(nomRangoInd2);
Name nomRango2 = wb.getNameAt(nomRangoInd3);
aref1 = new AreaReference(nomRango1.getRefersToFormula(), wb.getSpreadsheetVersion());
aref2 = new AreaReference(nomRango2.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
crefs2 = aref2.getAllReferencedCells();
Sheet s = wb.getSheet(crefs1[0].getSheetName());
int nCol = crefs1.length;
int nFil = crefs2.length;
for (int i=0; i<nCol; i++) {
Row r1 = s.getRow(crefs1[i].getRow());
Linea = r1.getCell(crefs1[i].getCol()).toString().trim();
indiceLinea = Calc.Buscar(Linea,nombreLineas);
for (int j=0; j<nFil; j++) {
Row r2 = s.getRow(crefs2[j].getRow());
Barra = r2.getCell(crefs2[j].getCol()).toString().trim();
indiceBarra = Calc.Buscar(Barra,nombreBarras);
if(indiceBarra==-1){
System.out.println("La barra "+Barra+" en 'orient' no se encuentra en la hoja 'barras'");
System.exit(0);
}
if(indiceLinea==-1){
System.out.println("La línea "+Linea+" en 'orient' no se encuentra en la hoja 'lineas'");
System.exit(0);
}
Cell c = r2.getCell(crefs1[i].getCol());
orientBarTroncal[indiceBarra][indiceLinea] = (int) c.getNumericCellValue();
}
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
}
public static int leeBarcli(String libroEntrada, String[] TextoTemporal1, String[] TextoTemporal2,
int[][] intAux3, String[] nombreClientes, String[] nombreBarras) {
int numClaves = 0;
Row fila = null;
Cell cell = null;
Cell c2e = null;
Cell c3e = null;
Cell c4e = null;
Cell c5e = null;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("barcli");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=6) {
Row r = s.getRow(crefs[i].getRow());
Cell c2 = null;
Cell c3 = null;
Cell c4 = null;
Cell c5 = null;
Cell c6= null;
c2 = r.getCell(crefs[i+1].getCol());
c3 = r.getCell(crefs[i+2].getCol());
c4 = r.getCell(crefs[i+3].getCol());
c5 = r.getCell(crefs[i+4].getCol());
c6 = r.getCell(crefs[i+5].getCol());
TextoTemporal1[numClaves]=c2.toString().trim(); //Clave
//intAux3[numClaves][1]=Calc.Buscar(c4.toString().trim(),nombreSumin); // Suministrador
intAux3[numClaves][0]=Calc.Buscar(c5.toString().trim(),nombreBarras); // Barras
if(intAux3[numClaves][0]==-1){
System.out.println("La barra de consumo "+c5.toString().trim()+ " en 'consumos' no se encuentra en hoja 'barras'");
}
intAux3[numClaves][2]=Calc.Buscar(c3.toString().trim()+"#"+c4.toString().trim()+"#"+c5.toString().trim(),nombreClientes); // Cliente
if(intAux3[numClaves][2]==-1){
System.out.println("El consumo "+c3.toString().trim()+"#"+c4.toString().trim()+"#"+c5.toString().trim()+
" no tiene un Cliente asociado en hoja 'Clientes'");
}
intAux3[numClaves][3]= (int) c6.getNumericCellValue();
numClaves++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numClaves;
}
public static int leeConsumos(String libroEntrada, float[][] ConsumosClaves, float[][] ConsClaveMes,
int numEtapas, int[] paramEtapa, int[] duracionEta, float[][][] ECU) {
int numClaves = 0;
int cuenta1 = 0;
int cuenta2 = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("consumos");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
AreaReference aref1;
CellReference[] crefs1;
int nomRangoInd1 = wb.getNameIndex("CU");
Name nomRango1 = wb.getNameAt(nomRangoInd1);
aref1 = new AreaReference(nomRango1.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
for (int i = 0; i < crefs.length; i += numEtapas) {
Row r = s.getRow(crefs[i].getRow());
for (int j = 0; j < numEtapas; j++) {
Cell c = null;
c = r.getCell(crefs[i + j].getCol());
ConsumosClaves[numClaves][j] = (float) c.getNumericCellValue();
}
numClaves++;
}
for (int i = 0; i < crefs1.length; i += 3 * (NUMERO_MESES)) {
Row r1 = s.getRow(crefs1[i].getRow());
for (int m = 0; m < NUMERO_MESES; m++) {
Cell c1 = null;
Cell c2 = null;
Cell c3 = null;
c1 = r1.getCell(crefs1[i + m].getCol());
c2 = r1.getCell(crefs1[i + NUMERO_MESES + m].getCol());
c3 = r1.getCell(crefs1[i + 2 * NUMERO_MESES + m].getCol());
ECU[cuenta1][0][m] = (float) c1.getNumericCellValue();
ECU[cuenta1][1][m] = (float) c2.getNumericCellValue();
ECU[cuenta1][2][m] = (float) c3.getNumericCellValue();
}
cuenta1++;
}
//Calcula la energia mensual por Clave
for (int j = 0; j < numClaves; j++) {
for (int e = 0; e < numEtapas; e++) {
ConsClaveMes[j][paramEtapa[e]]
+= ConsumosClaves[j][e] * duracionEta[e];
}
}
} catch (java.io.FileNotFoundException e) {
System.out.println("No se se puede acceder al archivo " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return numClaves;
}
public static int leeConsumos2(String libroEntrada, float[][] ConsumosClaves, float[][] ConsClaveMes,
int numEtapas, int[] paramEtapa, int[] duracionEta, float[][][] ECU) {
int numClaves = 0;
int cuenta1 = 0;
int cuenta2 = 0;
String[] ClaveCli = new String[2500];
XSSFSheet hoja = null;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("consumos");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
AreaReference aref1;
CellReference[] crefs1;
int nomRangoInd1 = wb.getNameIndex("CU");
Name nomRango1 = wb.getNameAt(nomRangoInd1);
aref1 = new AreaReference(nomRango1.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
for (int i = 0; i < crefs.length; i += numEtapas) {
Row r = s.getRow(crefs[i].getRow());
for (int j = 0; j < numEtapas; j++) {
Cell c = null;
c = r.getCell(crefs[i + j].getCol());
ConsumosClaves[numClaves][j] = (float) c.getNumericCellValue();
}
numClaves++;
}
for (int i = 0; i < crefs1.length; i += 3 * (NUMERO_MESES)) {
Row r1 = s.getRow(crefs1[i].getRow());
for (int m = 0; m < NUMERO_MESES; m++) {
Cell c1 = null;
Cell c2 = null;
Cell c3 = null;
c1 = r1.getCell(crefs1[i + m].getCol());
c2 = r1.getCell(crefs1[i + NUMERO_MESES + m].getCol());
c3 = r1.getCell(crefs1[i + 2 * NUMERO_MESES + m].getCol());
ECU[cuenta1][0][m] = (float) c1.getNumericCellValue();
ECU[cuenta1][1][m] = (float) c2.getNumericCellValue();
ECU[cuenta1][2][m] = (float) c3.getNumericCellValue();
}
cuenta1++;
}
//Calcula la energia mensual por Clave
for (int j = 0; j < numClaves; j++) {
for (int e = 0; e < numEtapas; e++) {
ConsClaveMes[j][paramEtapa[e]]
+= ConsumosClaves[j][e] * duracionEta[e];
}
}
//Extrae los clientes asociados a los consumos
int nomRangoInd2 = wb.getNameIndex("barcli");
Name nomRango2 = wb.getNameAt(nomRangoInd2);
aref = new AreaReference(nomRango2.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
for (int i = 0; i < crefs.length; i += 5) {
Row r = s.getRow(crefs[i].getRow());
Cell c3 = null;
Cell c4 = null;
Cell c5 = null;
c3 = r.getCell(crefs[i + 2].getCol());
c4 = r.getCell(crefs[i + 3].getCol());
c5 = r.getCell(crefs[i + 4].getCol());
ClaveCli[cuenta2] = c3.toString().trim() + "#" + c4.toString().trim() + "#" + c5.toString().trim(); // Cliente
cuenta2++;
}
String[] TxtTemp0 = new String[numClaves];
for (int i = 0; i < numClaves; i++) {
TxtTemp0[i] = "";
}
int numCli = 0;
for (int j = 0; j < numClaves; j++) {
int l = Calc.Buscar(ClaveCli[j], TxtTemp0);
if (l == -1) {
TxtTemp0[numCli] = ClaveCli[j];
numCli++;
}
}
String[] nomCli = new String[numCli];
for (int j = 0; j < numCli; j++) {
nomCli[j] = TxtTemp0[j];
}
String[] nomCliO = new String[numCli];
int[] nc = Calc.OrdenarBurbujaStr(nomCli);
nomCliO = new String[numCli];
for (int i = 0; i < numCli; i++) {
nomCliO[i] = nomCli[nc[i]];
}
//Escribe los clientes en hoja clientes del archivo de entrada
hoja = wb.getSheet("clientes");
Cell cell = null;
Row row = null;
short fila = 5;
Font font = wb.createFont();
font.setFontHeightInPoints((short) 10);
font.setFontName("Century Gothic");
CellStyle estilo = wb.createCellStyle();
estilo.setFont(font);
CellStyle estilo1 = wb.createCellStyle();
estilo1.setFont(font);
estilo1.setAlignment(HorizontalAlignment.CENTER);
// Titulos Secundarios
for (int i = 0; i < numCli; i++) {
row = hoja.createRow(fila);
fila++;
cell = row.createCell(1);
cell.setCellValue(i + 1);
cell.setCellStyle(estilo1);
cell = row.createCell(2);
cell.setCellValue(nomCliO[i]);
cell.setCellStyle(estilo);
cell = row.createCell(3);
cell.setCellValue(-1);
cell.setCellStyle(estilo);
}
// Crea nombre de rango de salida
Name nombreCel = wb.getName("clientes");
if (nombreCel == null) {
nombreCel = wb.createName();
} else {
wb.removeName(nombreCel);
}
nombreCel.setNameName("clientes"); // Nombre del rango
CellReference cellRef = new CellReference(cell.getRowIndex(), cell.getColumnIndex());
String reference = "clientes" + "!C6:" + cellRef.formatAsString(); // area reference
nombreCel.setRefersToFormula(reference);
FileOutputStream archivoSalida = new FileOutputStream(libroEntrada);
wb.write(archivoSalida);
archivoSalida.close();
System.out.println("Acaba de extraer y escribir en la hoja 'clientes' los Clientes asociados a los consumos");
System.out.println("Recuerde indicar los clientes excentos antes de calcular los pagos");
} catch (java.io.FileNotFoundException e) {
System.out.println("No se se puede acceder al archivo " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return numClaves;
}
public static int leeCU(String libroEntrada, double[] ECU2, double[] ECU30, int[] intAux3, String[] nombreBarras) {
int numClaves = 0;
int cuenta = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(libroEntrada));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("CU");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
AreaReference aref1;
CellReference[] crefs1;
int nomRangoInd1 = wb.getNameIndex("barcli");
Name nomRango1 = wb.getNameAt(nomRangoInd1);
aref1 = new AreaReference(nomRango1.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
for (int i = 0; i < crefs1.length; i += 5) {
Row r1 = s.getRow(crefs1[i].getRow());
Cell c5 = null;
c5 = r1.getCell(crefs1[i + 4].getCol());
intAux3[numClaves] = Calc.Buscar(c5.toString().trim(), nombreBarras); // Barras
Row r = s.getRow(crefs[cuenta].getRow());
Cell c1 = null;
Cell c2 = null;
c1 = r.getCell(crefs[cuenta].getCol());
c2 = r.getCell(crefs[cuenta + 1].getCol());
ECU2[numClaves] = c1.getNumericCellValue();
ECU30[numClaves] = c2.getNumericCellValue();
cuenta = cuenta + 2;
numClaves++;
}
} catch (java.io.FileNotFoundException e) {
System.out.println("No se se puede acceder al archivo " + e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
return numClaves;
}
public static int leeLinPLP(String libroEntrada, String[] TextoTemporal1, float[][] Aux) {
int numLineasSistRed = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("linPLP");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=3) {
Row r = s.getRow(crefs[i].getRow());
Cell c2 = r.getCell(crefs[i+1].getCol());
Cell c3 = r.getCell(crefs[i+2].getCol());
TextoTemporal1[numLineasSistRed] = c2.toString().trim(); // Nombre
Aux[numLineasSistRed][0] = (float) c3.getNumericCellValue(); // Tension
numLineasSistRed++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numLineasSistRed;
}
public static int leeMeses(String libroEntrada, int[] intAux, String[] nombreMeses) {
int numSubperiodos = 0;
Cell c1 = null;
Cell c2 = null;
int numBloques;
int et = 0;
try {
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
AreaReference aref;
CellReference[] crefs;
int nomRangoInd = wb.getNameIndex("meses");
Name nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
Sheet s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=2) {
Row r = s.getRow(crefs[i].getRow());
c1 = r.getCell(crefs[i].getCol());
c2 = r.getCell(crefs[i+1].getCol());
numBloques = (int) c2.getNumericCellValue();
for (int j=0; j<numBloques; j++) {
intAux[et] = Calc.Buscar(c1.toString().trim(),nombreMeses);
et++;
}
numSubperiodos++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numSubperiodos;
}
public static int leeEfirme(String libroEntrada, String[] TextoTemporal1, double[][] Efirme) {
int numEmpre = 0;
try {
Cell c1 = null;
int nomRangoInd;
Name nomRango;
AreaReference aref;
CellReference[] crefs;
Sheet s;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
// Lectura de datos
nomRangoInd = wb.getNameIndex("EmpEfir");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i++) {
Row r = s.getRow(crefs[i].getRow());
c1 = r.getCell(crefs[i].getCol());
TextoTemporal1[i] = c1.toString().trim();
}
// Lectura de datos
nomRangoInd = wb.getNameIndex("Efirme");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (int i=0; i<crefs.length; i+=NUMERO_MESES) {
Row r = s.getRow(crefs[i].getRow());
for (int j=0; j<NUMERO_MESES; j++) {
c1 = r.getCell(crefs[i + j].getCol());
Efirme[numEmpre][j] = c1.getNumericCellValue();
}
numEmpre++;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return numEmpre;
}
public static int[] leeDistribuidoras(String libroEntrada, String[] TextoTemporal1,String[] TextoTemporal2, double[][][] Prorrata) {
int[] cuenta=new int[2];
int numDx;
int aux=0;
int numSum=0;
try {
Cell c1 = null;
Cell c2 = null;
int nomRangoInd;
Name nomRango;
AreaReference aref;
CellReference[] crefs;
AreaReference aref1;
CellReference[] crefs1;
Sheet s;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
// Lectura de datos
nomRangoInd = wb.getNameIndex("Distr");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (numDx=0; numDx<crefs.length; numDx++) {
Row r = s.getRow(crefs[numDx].getRow());
c1 = r.getCell(crefs[numDx].getCol());
TextoTemporal1[numDx] = c1.toString().trim();
}
int sum=0;
int tmp=0;
for(int i=0;i<NUMERO_MESES;i++){
tmp=i+1;
nomRangoInd = wb.getNameIndex("ProrrDx"+tmp);
nomRango = wb.getNameAt(nomRangoInd);
aref1 = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
sum=crefs1.length/numDx;
for (numSum=0; numSum<sum; numSum++) {
Row r = s.getRow(crefs1[numSum].getRow());
c2 = r.getCell(crefs1[numSum].getCol());
TextoTemporal2[numSum] = c2.toString().trim();
//System.out.println(TextoTemporal2[numSum]);
}
// Lectura de datos
aux=0;
for (int j=sum; j<crefs1.length; j+=numSum) {
Row r = s.getRow(crefs1[j].getRow());
for (int k=0; k<numSum; k++) {
c1 = r.getCell(crefs1[j + k].getCol());
//System.out.println(c1.getNumericCellValue());
Prorrata[aux][k][i] = c1.getNumericCellValue();
}
aux++;
//System.out.println(aux);
}
cuenta[0]=numDx;
cuenta[1]=numSum;
}
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return cuenta;
}
public static int leeProrrataEfirme(String libroEntrada, String[] TextoTemporal, double[][] Prorrata) {
int cuenta = 0;
int numSum;
try {
Cell c1 = null;
Cell c2 = null;
int nomRangoInd;
Name nomRango;
AreaReference aref;
CellReference[] crefs;
AreaReference aref1;
CellReference[] crefs1;
Sheet s;
//POIFSFileSystem fs = new //POIFSFileSystem(new FileInputStream( libroEntrada ));
XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream( libroEntrada ));
// Lectura de datos
nomRangoInd = wb.getNameIndex("sumRM88");
nomRango = wb.getNameAt(nomRangoInd);
aref = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs = aref.getAllReferencedCells();
s = wb.getSheet(crefs[0].getSheetName());
for (numSum=0; numSum<crefs.length; numSum++) {
Row r = s.getRow(crefs[numSum].getRow());
c1 = r.getCell(crefs[numSum].getCol());
TextoTemporal[numSum] = c1.toString().trim();
//System.out.println(TextoTemporal[numSum]);
}
nomRangoInd = wb.getNameIndex("ProrrRM88");
nomRango = wb.getNameAt(nomRangoInd);
aref1 = new AreaReference(nomRango.getRefersToFormula(), wb.getSpreadsheetVersion());
crefs1 = aref1.getAllReferencedCells();
// Lectura de datos
//System.out.println(crefs1.length);
for (int suministrador=0; suministrador<numSum; suministrador++) {
Row r = s.getRow(crefs1[suministrador*NUMERO_MESES].getRow());
for (int mes=0; mes<NUMERO_MESES; mes++) {
c1 = r.getCell(crefs1[mes + suministrador*NUMERO_MESES].getCol());
//System.out.println(c1.getNumericCellValue());
Prorrata[mes][suministrador] = c1.getNumericCellValue();
}
//System.out.println(aux);
}
cuenta =numSum;
}
catch (java.io.FileNotFoundException e) {
System.out.println( "No se se puede acceder al archivo " + e.getMessage());
}
catch (Exception e) {
e.printStackTrace();
}
return cuenta;
}
public static void leePropiedades(Properties propiedades, String ruta){
InputStream is = null;
try {
File f = new File(ruta);
is = new FileInputStream( f );
propiedades.load(is);
}
catch ( Exception e ) {
e.printStackTrace();
is = null;
}
if (is != null) {
try {
is.close();
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
}
| 45.009179
| 154
| 0.541677
|
b95b4f1447c5db3a99d15066c5af124799030c28
| 867
|
/*
* 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 edu.eci.arsw.mouseutils;
import java.math.BigInteger;
/**
*
* @author hcadavid
*/
public class MathTools {
public boolean checkIsPrime(BigInteger n) {
int count = 0;
BigInteger i=BigInteger.valueOf(2);
while (i.compareTo(n.divide(BigInteger.valueOf(2)))<=0){
if (n.mod(i).compareTo(BigInteger.ZERO)==0){
count++;
}
i=i.add(BigInteger.ONE);
}
if ( count > 0 )
{
//number is prime
return true;
}
else
{
//number is not prime
return false;
}
}
}
| 20.642857
| 79
| 0.522491
|
b0dfa5674e956373403ee86b33fa0966fb9b368e
| 3,697
|
/*
* Orika - simpler, better and faster Java bean mapping
*
* Copyright (C) 2011-2013 Orika authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ma.glasnost.orika;
import ma.glasnost.orika.metadata.Property;
import ma.glasnost.orika.metadata.Type;
public class MappingException extends RuntimeException {
private static final long serialVersionUID = -1485137975363692382L;
private Property sourceProperty;
private Property destinationProperty;
private Class<?> sourceClass;
private Type<?> sourceType;
private Type<?> destinationType;
private MappingStrategy mappingStrategy;
private String stateReport;
public MappingException(Throwable e) {
super(e);
}
public MappingException(String message) {
super(message);
}
public MappingException(String message, Throwable e) {
super(message, e);
}
public String getLocalizedMessage() {
StringBuilder message = new StringBuilder();
if (sourceClass != null) {
message.append("\nsourceClass = " + sourceClass);
}
if (sourceType != null) {
message.append("\nsourceType = " + sourceType.toFullyQualifiedString());
}
if (sourceProperty != null) {
message.append("\nsourceProperty = " + sourceProperty);
}
if (destinationType != null) {
message.append("\ndestinationType = " + destinationType.toFullyQualifiedString());
}
if (destinationProperty != null) {
message.append("\ndestinationProperty = " + destinationProperty);
}
if (mappingStrategy != null) {
message.append("\nresolvedStrategy = " + mappingStrategy);
}
if (message.length() > 0) {
message.insert(0, "While attempting the following mapping:");
message.append("\nError occurred: ");
}
message.append(super.getLocalizedMessage());
if (stateReport != null) {
message.append(stateReport);
}
return message.toString();
}
public Property getSourceProperty() {
return sourceProperty;
}
public void setSourceProperty(Property sourceProperty) {
this.sourceProperty = sourceProperty;
}
public Property getDestinationProperty() {
return destinationProperty;
}
public void setDestinationProperty(Property destinationProperty) {
this.destinationProperty = destinationProperty;
}
public Type<?> getSourceType() {
return sourceType;
}
public void setSourceType(Type<?> sourceType) {
this.sourceType = sourceType;
}
public Type<?> getDestinationType() {
return destinationType;
}
public void setDestinationType(Type<?> destinationType) {
this.destinationType = destinationType;
}
public Class<?> getSourceClass() {
return sourceClass;
}
public void setSourceClass(Class<?> sourceClass) {
this.sourceClass = sourceClass;
}
public MappingStrategy getMappingStrategy() {
return mappingStrategy;
}
public void setMappingStrategy(MappingStrategy mappingStrategy) {
this.mappingStrategy = mappingStrategy;
}
public void setStateReport(String stateReport) {
this.stateReport = stateReport;
}
public boolean containsStateReport() {
return this.stateReport != null;
}
}
| 26.407143
| 86
| 0.705166
|
eb839e4815d622d2e0a5ffe2a27afb569685da26
| 4,809
|
/*
* Copyright (C) 2019 Intel Corporation
* SPDX-License-Identifier: BSD-3-Clause
*/
package com.intel.dcsg.cpg.http;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
/**
* There isn't a query string generator or parser class in the Java APIs.
*
* <ul>
* <li>Spring framework has one:
* org.springframework.web.util.UriComponentsBuilder (380KB)
* <li>JAX-RS has one: javax.ws.rs.core.UriBuilder (120KB)
* <li>Apache HttpClient has one: org.apache.http.client.utils.URIBuilder
* (350KB)
* </ul>
*
* @author jbuhacoff
*/
public class Query {
private static final Charset UTF8 = Charset.forName("UTF-8"); // UTF-8 guaranteed to be available by java runtime, so UnsupportedEncodingException will not be thrown
protected LinkedHashMap<String,ArrayList<String>> map;
public Query() {
map = new LinkedHashMap<>();
}
public Query(Map<String,String[]> map) {
this();
for(String key : map.keySet()) {
ArrayList<String> copy = new ArrayList<>();
copy.addAll(Arrays.asList(map.get(key)));
this.map.put(key, copy);
}
}
public Set<String> keySet() {
return Collections.unmodifiableSet(map.keySet());
}
public List<String> getAll(String name) {
ArrayList<String> values = map.get(name);
if( values == null ) {
return Collections.EMPTY_LIST;
}
return Collections.unmodifiableList(values);
}
public String getFirst(String name) {
List<String> values = getAll(name);
if( values.isEmpty() ) {
return null;
}
return values.get(0);
}
@Override
public String toString() {
ArrayList<String> pairs = new ArrayList<>();
for(String key : map.keySet()) {
List<String> values = map.get(key);
if( values == null || values.isEmpty() ) { continue; }
for(String value : values) {
pairs.add(String.format("%s=%s", escape(key), escape(value)));
}
}
return StringUtils.join(pairs, "&");
}
protected String escape(String text) {
try {
return URLEncoder.encode(text, UTF8.name());
}
catch(UnsupportedEncodingException e) {
throw new RuntimeException(e); // java runtime guarantees availability of utf-8 so this will never happen
}
}
public static Map<String, List<String>> parse(URL url) {
return parse(url.getQuery());
}
/**
*
* @param query
* @return map of String to List of String
* method
*/
public static Map<String, List<String>> parse(String query) {
try {
final Map<String, List<String>> parameters = new LinkedHashMap<>();
final String[] pairs = query.split("&");
for (String pair : pairs) {
final int separator = pair.indexOf("=");
final String key = separator > 0 ? URLDecoder.decode(pair.substring(0, separator), UTF8.name()) : pair;
if (!parameters.containsKey(key)) {
parameters.put(key, new LinkedList<String>());
}
final String value = separator > 0 && pair.length() > separator + 1 ? URLDecoder.decode(pair.substring(separator + 1), UTF8.name()) : null;
parameters.get(key).add(value);
}
return parameters;
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e); // java runtime guarantees availability of utf-8 so this will never happen
}
}
/**
*
* @param query
* @return map of String to String ; if the query has multivalued
* parameters, only the first one is used
*/
public static Map<String, String> parseSinglevalued(String query) {
HashMap<String, String> singlevaluedMap = new HashMap<>();
Map<String, List<String>> multivaluedMap = parse(query);
for (Map.Entry<String, List<String>> entry : multivaluedMap.entrySet()) {
List<String> value = entry.getValue();
if (value == null || value.isEmpty()) {
singlevaluedMap.put(entry.getKey(), null);
} else {
singlevaluedMap.put(entry.getKey(), value.iterator().next());
}
}
return singlevaluedMap;
}
}
| 32.938356
| 169
| 0.599917
|
b1e6feba2f47cb3256c12941b5ee52f820591f68
| 1,156
|
package org.cloudfoundry.credhub.helper;
import org.cloudfoundry.credhub.util.CurrentTimeProvider;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.security.Security;
import java.time.Instant;
import java.util.Calendar;
import java.util.Optional;
import java.util.TimeZone;
import java.util.function.Consumer;
import static org.mockito.Mockito.when;
public class TestHelper {
public static Consumer<Long> mockOutCurrentTimeProvider(
CurrentTimeProvider mockCurrentTimeProvider) {
return (epochMillis) -> {
when(mockCurrentTimeProvider.getNow()).thenReturn(Optional.of(Instant.ofEpochMilli(epochMillis)));
when(mockCurrentTimeProvider.getInstant()).thenReturn(Instant.ofEpochMilli(epochMillis));
};
}
public static BouncyCastleProvider getBouncyCastleProvider() {
BouncyCastleProvider bouncyCastleProvider = (BouncyCastleProvider) Security
.getProvider(BouncyCastleProvider.PROVIDER_NAME);
if (bouncyCastleProvider == null) {
bouncyCastleProvider = new BouncyCastleProvider();
Security.addProvider(bouncyCastleProvider);
}
return bouncyCastleProvider;
}
}
| 30.421053
| 104
| 0.782872
|
fc7472515091d06020f0435c3c488e71cb392c7b
| 2,850
|
package org.deviceconnect.android.uiapp.utils;
import android.content.Context;
import android.content.SharedPreferences;
import org.deviceconnect.android.uiapp.R;
public final class Settings {
private SharedPreferences mPreferences;
private Context mContext;
private static Settings mInstance;
public static Settings getInstance() {
if (mInstance == null) {
mInstance = new Settings();
}
return mInstance;
}
public void load(Context context) {
mContext = context;
mPreferences = context.getSharedPreferences(context.getPackageName() + "_preferences",
Context.MODE_PRIVATE);
}
/**
* アクセストークンを取得する.
* アクセストークンがない場合にはnullを返却する。
* @return アクセストークン
*/
public String getAccessToken() {
String accessToken = mPreferences.getString(
mContext.getString(R.string.key_settings_dconn_access_token), null);
return accessToken;
}
public void setAccessToken(final String accessToken) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(mContext.getString(R.string.key_settings_dconn_access_token), accessToken);
editor.commit();
}
/**
* クライアントIDを取得する.
* @return クライアントID
*/
public String getClientId() {
String clientId = mPreferences.getString(
mContext.getString(R.string.key_settings_dconn_client_id), null);
return clientId;
}
public void setClientId(final String clientId) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(mContext.getString(R.string.key_settings_dconn_client_id), clientId);
editor.commit();
}
/**
* SSLフラグを取得する.
* @return SSLを使用する場合はtrue、それ以外はfalse
*/
public boolean isSSL() {
boolean isSSL = mPreferences.getBoolean(
mContext.getString(R.string.key_settings_dconn_ssl), false);
return isSSL;
}
/**
* ホスト名を取得する.
* @return ホスト名
*/
public String getHostName() {
String host = mPreferences.getString(
mContext.getString(R.string.key_settings_dconn_host),
mContext.getString(R.string.default_host));
return host;
}
/**
* ホートを取得する.
* @return ポート番号
*/
public int getPort() {
int port = Integer.parseInt(mPreferences.getString(
mContext.getString(R.string.key_settings_dconn_port),
mContext.getString(R.string.default_port)));
return port;
}
public String getSDKType() {
String type = mPreferences.getString(
mContext.getString(R.string.key_settings_dconn_sdk),
mContext.getString(R.string.activity_settings_sdk_entry1));
return type;
}
}
| 28.5
| 100
| 0.639298
|
1b3fe603eb3fcd98cb56ad52ac5170655319a182
| 11,926
|
package me.htrewrite.client.util;
import static org.lwjgl.opengl.GL11.*;
import me.htrewrite.client.Wrapper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.util.math.AxisAlignedBB;
import org.lwjgl.opengl.GL11;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class RenderUtils {
public static final Minecraft mc = Minecraft.getMinecraft();
/* Old Stuff*/
public static void drawBoundingBox(AxisAlignedBB bb, float width, float red, float green, float blue, float alpha)
{
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.disableDepth();
GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1);
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
glEnable(GL_LINE_SMOOTH);
glHint(GL_LINE_SMOOTH_HINT, GL_NICEST);
glLineWidth(width);
final Tessellator tessellator = Tessellator.getInstance();
final BufferBuilder bufferbuilder = tessellator.getBuffer();
bufferbuilder.begin(GL_LINE_STRIP, DefaultVertexFormats.POSITION_COLOR);
bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, 0.0F).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.maxZ).color(red, green, blue, 0.0F).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.maxZ).color(red, green, blue, 0.0F).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.minZ).color(red, green, blue, 0.0F).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, 0.0F).endVertex();
tessellator.draw();
glDisable(GL_LINE_SMOOTH);
GlStateManager.depthMask(true);
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
public static void drawBoundingBox(AxisAlignedBB bb, float width, int color)
{
final float alpha = (color >> 24 & 0xFF) / 255.0F;
final float red = (color >> 16 & 0xFF) / 255.0F;
final float green = (color >> 8 & 0xFF) / 255.0F;
final float blue = (color & 0xFF) / 255.0F;
drawBoundingBox(bb, width, red, green, blue, alpha);
}
public static void drawFilledBox(AxisAlignedBB bb, int color)
{
GlStateManager.pushMatrix();
GlStateManager.enableBlend();
GlStateManager.disableDepth();
GlStateManager.tryBlendFuncSeparate(770, 771, 0, 1);
GlStateManager.disableTexture2D();
GlStateManager.depthMask(false);
final float alpha = (color >> 24 & 0xFF) / 255.0F;
final float red = (color >> 16 & 0xFF) / 255.0F;
final float green = (color >> 8 & 0xFF) / 255.0F;
final float blue = (color & 0xFF) / 255.0F;
final Tessellator tessellator = Tessellator.getInstance();
final BufferBuilder bufferbuilder = tessellator.getBuffer();
bufferbuilder.begin(GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.maxX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.minZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.minY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.maxZ).color(red, green, blue, alpha).endVertex();
bufferbuilder.pos(bb.minX, bb.maxY, bb.minZ).color(red, green, blue, alpha).endVertex();
tessellator.draw();
GlStateManager.depthMask(true);
GlStateManager.enableDepth();
GlStateManager.enableTexture2D();
GlStateManager.disableBlend();
GlStateManager.popMatrix();
}
public static void drawSelectionBoundingBox(AxisAlignedBB boundingBox) {
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder vertexbuffer = tessellator.getBuffer();
vertexbuffer.begin(3, DefaultVertexFormats.POSITION);
vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
tessellator.draw();
vertexbuffer.begin(3, DefaultVertexFormats.POSITION);
vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
tessellator.draw();
vertexbuffer.begin(1, DefaultVertexFormats.POSITION);
vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();
vertexbuffer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();
tessellator.draw();
}
public static String DF (float value, int maxvalue) {
DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
df.setMaximumFractionDigits(maxvalue);
return df.format(value);
}
public static void drawRect(float left, float top, float right, float bottom, int color) {
float var5;
if (left < right) {
var5 = left;
left = right;
right = var5;
}
if (top < bottom) {
var5 = top;
top = bottom;
bottom = var5;
}
GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_LINE_SMOOTH);
GL11.glPushMatrix();
GLUtils.glColor(color);
GL11.glBegin(GL11.GL_QUADS);
GL11.glVertex2d(left, bottom);
GL11.glVertex2d(right, bottom);
GL11.glVertex2d(right, top);
GL11.glVertex2d(left, top);
GL11.glEnd();
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LINE_SMOOTH);
}
public static void drawBorderedRect(double x, double y, double x2, double y2, float l1, int col1, int col2) {
drawRect((int)x, (int)y, (int)x2, (int)y2, col2);
float f = (float)(col1 >> 24 & 0xFF) / 255F;
float f1 = (float)(col1 >> 16 & 0xFF) / 255F;
float f2 = (float)(col1 >> 8 & 0xFF) / 255F;
float f3 = (float)(col1 & 0xFF) / 255F;
//GL11.glEnable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
GL11.glEnable(GL11.GL_LINE_SMOOTH);
GL11.glPushMatrix();
GL11.glColor4f(f1, f2, f3, f);
GL11.glLineWidth(l1);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex2d(x, y);
GL11.glVertex2d(x, y2);
GL11.glVertex2d(x2, y2);
GL11.glVertex2d(x2, y);
GL11.glVertex2d(x, y);
GL11.glVertex2d(x2, y);
GL11.glVertex2d(x, y2);
GL11.glVertex2d(x2, y2);
GL11.glEnd();
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_TEXTURE_2D);
//GL11.glDisable(GL11.GL_BLEND);
GL11.glDisable(GL11.GL_LINE_SMOOTH);
}
public static void drawStringWithRect(String string, int x, int y, int colorString, int colorRect, int colorRect2) {
RenderUtils.drawBorderedRect(x - 2, y - 2, x + Wrapper.getMC().fontRenderer.getStringWidth(string) + 2, y + 10, 1, colorRect, colorRect2);
Wrapper.getMC().fontRenderer.drawString(string, x, y, colorString);
}
}
| 51.627706
| 146
| 0.670552
|
ae404c173eb86f42cd9e2f338f352225afd65fdb
| 4,295
|
/*
* 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.aliyuncs.ecsops.model.v20160401;
import com.aliyuncs.RpcAcsRequest;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.ecsops.Endpoint;
/**
* @author auto create
* @version
*/
public class OpsInsertOrDeleteServiceIDRequest extends RpcAcsRequest<OpsInsertOrDeleteServiceIDResponse> {
private String description;
private String effectiveOwnerType;
private String operator;
private Boolean supportTrunking;
private String operate;
private String resourceOwnerIds;
private String productName;
private String serviceId;
private String resourceTotal;
private String auditParamStr;
public OpsInsertOrDeleteServiceIDRequest() {
super("Ecsops", "2016-04-01", "OpsInsertOrDeleteServiceID", "ecs");
setMethod(MethodType.POST);
try {
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap);
com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType);
} catch (Exception e) {}
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
if(description != null){
putQueryParameter("Description", description);
}
}
public String getEffectiveOwnerType() {
return this.effectiveOwnerType;
}
public void setEffectiveOwnerType(String effectiveOwnerType) {
this.effectiveOwnerType = effectiveOwnerType;
if(effectiveOwnerType != null){
putQueryParameter("EffectiveOwnerType", effectiveOwnerType);
}
}
public String getOperator() {
return this.operator;
}
public void setOperator(String operator) {
this.operator = operator;
if(operator != null){
putQueryParameter("Operator", operator);
}
}
public Boolean getSupportTrunking() {
return this.supportTrunking;
}
public void setSupportTrunking(Boolean supportTrunking) {
this.supportTrunking = supportTrunking;
if(supportTrunking != null){
putQueryParameter("SupportTrunking", supportTrunking.toString());
}
}
public String getOperate() {
return this.operate;
}
public void setOperate(String operate) {
this.operate = operate;
if(operate != null){
putQueryParameter("Operate", operate);
}
}
public String getResourceOwnerIds() {
return this.resourceOwnerIds;
}
public void setResourceOwnerIds(String resourceOwnerIds) {
this.resourceOwnerIds = resourceOwnerIds;
if(resourceOwnerIds != null){
putQueryParameter("ResourceOwnerIds", resourceOwnerIds);
}
}
public String getProductName() {
return this.productName;
}
public void setProductName(String productName) {
this.productName = productName;
if(productName != null){
putQueryParameter("ProductName", productName);
}
}
public String getServiceId() {
return this.serviceId;
}
public void setServiceId(String serviceId) {
this.serviceId = serviceId;
if(serviceId != null){
putQueryParameter("ServiceId", serviceId);
}
}
public String getResourceTotal() {
return this.resourceTotal;
}
public void setResourceTotal(String resourceTotal) {
this.resourceTotal = resourceTotal;
if(resourceTotal != null){
putQueryParameter("ResourceTotal", resourceTotal);
}
}
public String getAuditParamStr() {
return this.auditParamStr;
}
public void setAuditParamStr(String auditParamStr) {
this.auditParamStr = auditParamStr;
if(auditParamStr != null){
putQueryParameter("AuditParamStr", auditParamStr);
}
}
@Override
public Class<OpsInsertOrDeleteServiceIDResponse> getResponseClass() {
return OpsInsertOrDeleteServiceIDResponse.class;
}
}
| 24.97093
| 118
| 0.734808
|
91a9be7b96b9144b10f6d0f12b3f556ac0b15dd5
| 143
|
package com.mapbox.services.android.navigation.v5.navigation;
public interface NavigationEventListener {
void onRunning(boolean running);
}
| 23.833333
| 61
| 0.825175
|
9d79b0f4b060bd6ad4fe8cac65ac7d8c3d83d155
| 1,293
|
package frodez.config.swagger.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 Frodez
* @date 2019-12-05
*/
@Documented
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Success {
/**
* 返回类型
* @author Frodez
* @date 2019-12-05
*/
Class<?> value();
/**
* 包装类型<br>
* <strong>不建议引入过于复杂的嵌套类型。如果需要,请使用一个特殊的类来封装嵌套类型。<br>
* 如List(List(Integer))这种类型,最好用类型Collections来封装内层的List(Integer),然后把类型变为List(Collections)。<br>
* 这样可以便于理解数据结构。 </strong>
* @author Frodez
* @date 2019-12-05
*/
Container containerType() default Container.NONE;
/**
* 包装类型<br>
* <strong>不建议引入过于复杂的嵌套类型。如果需要,请使用一个特殊的类来封装嵌套类型。<br>
* 如List(List(Integer))这种类型,最好用类型Collections来封装内层的List(Integer),然后把类型变为List(Collections)。<br>
* 这样可以便于理解数据结构。 </strong>
* @author Frodez
* @date 2019-12-05
*/
public enum Container {
/**
* 无包装
*/
NONE,
/**
* 分页封装,详情见PageData
* @see frodez.util.beans.result.PageData
*/
PAGE,
/**
* 普通list
*/
LIST,
/**
* 普通set
*/
SET;
}
}
| 19.892308
| 95
| 0.643465
|
1d3bd6eeec2ed0b22d5c9e6a1e0ae01b7c3f53b5
| 1,116
|
package com.onevgo.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Ex40CombinationSum2 {
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
// 回溯算法
Arrays.sort(candidates);
List<List<Integer>> lists = new ArrayList<>();
backtrace(lists, new ArrayList<>(), candidates, target, 0);
return lists;
}
public void backtrace(List<List<Integer>> lists, List<Integer> prev, int[] candidates, int target, int index) {
if (target == 0) {
lists.add(new ArrayList<>(prev));
return;
}
for (int i = index; i < candidates.length; i++) {
if (candidates[i] > target) {
break;
}
if (i > index && candidates[i] == candidates[i - 1]) {
continue;
}
prev.add(candidates[i]);
backtrace(lists, prev, candidates, target - candidates[i], i + 1);
prev.remove(prev.size() - 1);
}
}
public static void main(String[] args) {
}
}
| 27.9
| 115
| 0.549283
|
0916bc6704d8682638ef25ee8c42e67fff607308
| 803
|
package io.redskap.swagger.brake.report.json;
import java.util.Map;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
@Component
@RequiredArgsConstructor
public class JsonConverter {
private final ObjectMapper objectMapper;
public String convert(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
public Map<String, Object> toMap(Object obj) {
return objectMapper.convertValue(obj, new TypeReference<Map<String, Object>>() {});
}
}
| 28.678571
| 91
| 0.73599
|
f2f7bd2ab077e2683bf061fad2668bf7900cc54a
| 35,767
|
/**
* CadastrarCPFRequest.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package _59._12._54._201.WS;
public class CadastrarCPFRequest implements java.io.Serializable {
private java.lang.String autenticacao;
private java.lang.String UF;
private java.lang.String cidade;
private java.lang.String funcao;
private java.lang.String perfil;
private java.lang.String nome;
private java.lang.String controleCliente;
private java.lang.String CPF;
private java.lang.String RG;
private java.lang.String orgaoExpeditor;
private java.util.Calendar dataEmissao;
private java.util.Calendar dataNascimento;
private java.lang.String nomePai;
private java.lang.String nomeMae;
private java.lang.String endereco;
private java.lang.String numero;
private java.lang.String complemento;
private java.lang.String bairro;
private java.lang.String CEP;
private java.lang.String telefone;
private java.lang.String celular;
private java.lang.String CNHRegistro;
private java.lang.String CNH;
private java.lang.String CNHCategoria;
private java.util.Calendar CNHValidade;
private java.lang.String CNHUF;
private java.lang.String observacao;
public CadastrarCPFRequest() {
}
public CadastrarCPFRequest(
java.lang.String autenticacao,
java.lang.String UF,
java.lang.String cidade,
java.lang.String funcao,
java.lang.String perfil,
java.lang.String nome,
java.lang.String controleCliente,
java.lang.String CPF,
java.lang.String RG,
java.lang.String orgaoExpeditor,
java.util.Calendar dataEmissao,
java.util.Calendar dataNascimento,
java.lang.String nomePai,
java.lang.String nomeMae,
java.lang.String endereco,
java.lang.String numero,
java.lang.String complemento,
java.lang.String bairro,
java.lang.String CEP,
java.lang.String telefone,
java.lang.String celular,
java.lang.String CNHRegistro,
java.lang.String CNH,
java.lang.String CNHCategoria,
java.util.Calendar CNHValidade,
java.lang.String CNHUF,
java.lang.String observacao) {
this.autenticacao = autenticacao;
this.UF = UF;
this.cidade = cidade;
this.funcao = funcao;
this.perfil = perfil;
this.nome = nome;
this.controleCliente = controleCliente;
this.CPF = CPF;
this.RG = RG;
this.orgaoExpeditor = orgaoExpeditor;
this.dataEmissao = dataEmissao;
this.dataNascimento = dataNascimento;
this.nomePai = nomePai;
this.nomeMae = nomeMae;
this.endereco = endereco;
this.numero = numero;
this.complemento = complemento;
this.bairro = bairro;
this.CEP = CEP;
this.telefone = telefone;
this.celular = celular;
this.CNHRegistro = CNHRegistro;
this.CNH = CNH;
this.CNHCategoria = CNHCategoria;
this.CNHValidade = CNHValidade;
this.CNHUF = CNHUF;
this.observacao = observacao;
}
/**
* Gets the autenticacao value for this CadastrarCPFRequest.
*
* @return autenticacao
*/
public java.lang.String getAutenticacao() {
return autenticacao;
}
/**
* Sets the autenticacao value for this CadastrarCPFRequest.
*
* @param autenticacao
*/
public void setAutenticacao(java.lang.String autenticacao) {
this.autenticacao = autenticacao;
}
/**
* Gets the UF value for this CadastrarCPFRequest.
*
* @return UF
*/
public java.lang.String getUF() {
return UF;
}
/**
* Sets the UF value for this CadastrarCPFRequest.
*
* @param UF
*/
public void setUF(java.lang.String UF) {
this.UF = UF;
}
/**
* Gets the cidade value for this CadastrarCPFRequest.
*
* @return cidade
*/
public java.lang.String getCidade() {
return cidade;
}
/**
* Sets the cidade value for this CadastrarCPFRequest.
*
* @param cidade
*/
public void setCidade(java.lang.String cidade) {
this.cidade = cidade;
}
/**
* Gets the funcao value for this CadastrarCPFRequest.
*
* @return funcao
*/
public java.lang.String getFuncao() {
return funcao;
}
/**
* Sets the funcao value for this CadastrarCPFRequest.
*
* @param funcao
*/
public void setFuncao(java.lang.String funcao) {
this.funcao = funcao;
}
/**
* Gets the perfil value for this CadastrarCPFRequest.
*
* @return perfil
*/
public java.lang.String getPerfil() {
return perfil;
}
/**
* Sets the perfil value for this CadastrarCPFRequest.
*
* @param perfil
*/
public void setPerfil(java.lang.String perfil) {
this.perfil = perfil;
}
/**
* Gets the nome value for this CadastrarCPFRequest.
*
* @return nome
*/
public java.lang.String getNome() {
return nome;
}
/**
* Sets the nome value for this CadastrarCPFRequest.
*
* @param nome
*/
public void setNome(java.lang.String nome) {
this.nome = nome;
}
/**
* Gets the controleCliente value for this CadastrarCPFRequest.
*
* @return controleCliente
*/
public java.lang.String getControleCliente() {
return controleCliente;
}
/**
* Sets the controleCliente value for this CadastrarCPFRequest.
*
* @param controleCliente
*/
public void setControleCliente(java.lang.String controleCliente) {
this.controleCliente = controleCliente;
}
/**
* Gets the CPF value for this CadastrarCPFRequest.
*
* @return CPF
*/
public java.lang.String getCPF() {
return CPF;
}
/**
* Sets the CPF value for this CadastrarCPFRequest.
*
* @param CPF
*/
public void setCPF(java.lang.String CPF) {
this.CPF = CPF;
}
/**
* Gets the RG value for this CadastrarCPFRequest.
*
* @return RG
*/
public java.lang.String getRG() {
return RG;
}
/**
* Sets the RG value for this CadastrarCPFRequest.
*
* @param RG
*/
public void setRG(java.lang.String RG) {
this.RG = RG;
}
/**
* Gets the orgaoExpeditor value for this CadastrarCPFRequest.
*
* @return orgaoExpeditor
*/
public java.lang.String getOrgaoExpeditor() {
return orgaoExpeditor;
}
/**
* Sets the orgaoExpeditor value for this CadastrarCPFRequest.
*
* @param orgaoExpeditor
*/
public void setOrgaoExpeditor(java.lang.String orgaoExpeditor) {
this.orgaoExpeditor = orgaoExpeditor;
}
/**
* Gets the dataEmissao value for this CadastrarCPFRequest.
*
* @return dataEmissao
*/
public java.util.Calendar getDataEmissao() {
return dataEmissao;
}
/**
* Sets the dataEmissao value for this CadastrarCPFRequest.
*
* @param dataEmissao
*/
public void setDataEmissao(java.util.Calendar dataEmissao) {
this.dataEmissao = dataEmissao;
}
/**
* Gets the dataNascimento value for this CadastrarCPFRequest.
*
* @return dataNascimento
*/
public java.util.Calendar getDataNascimento() {
return dataNascimento;
}
/**
* Sets the dataNascimento value for this CadastrarCPFRequest.
*
* @param dataNascimento
*/
public void setDataNascimento(java.util.Calendar dataNascimento) {
this.dataNascimento = dataNascimento;
}
/**
* Gets the nomePai value for this CadastrarCPFRequest.
*
* @return nomePai
*/
public java.lang.String getNomePai() {
return nomePai;
}
/**
* Sets the nomePai value for this CadastrarCPFRequest.
*
* @param nomePai
*/
public void setNomePai(java.lang.String nomePai) {
this.nomePai = nomePai;
}
/**
* Gets the nomeMae value for this CadastrarCPFRequest.
*
* @return nomeMae
*/
public java.lang.String getNomeMae() {
return nomeMae;
}
/**
* Sets the nomeMae value for this CadastrarCPFRequest.
*
* @param nomeMae
*/
public void setNomeMae(java.lang.String nomeMae) {
this.nomeMae = nomeMae;
}
/**
* Gets the endereco value for this CadastrarCPFRequest.
*
* @return endereco
*/
public java.lang.String getEndereco() {
return endereco;
}
/**
* Sets the endereco value for this CadastrarCPFRequest.
*
* @param endereco
*/
public void setEndereco(java.lang.String endereco) {
this.endereco = endereco;
}
/**
* Gets the numero value for this CadastrarCPFRequest.
*
* @return numero
*/
public java.lang.String getNumero() {
return numero;
}
/**
* Sets the numero value for this CadastrarCPFRequest.
*
* @param numero
*/
public void setNumero(java.lang.String numero) {
this.numero = numero;
}
/**
* Gets the complemento value for this CadastrarCPFRequest.
*
* @return complemento
*/
public java.lang.String getComplemento() {
return complemento;
}
/**
* Sets the complemento value for this CadastrarCPFRequest.
*
* @param complemento
*/
public void setComplemento(java.lang.String complemento) {
this.complemento = complemento;
}
/**
* Gets the bairro value for this CadastrarCPFRequest.
*
* @return bairro
*/
public java.lang.String getBairro() {
return bairro;
}
/**
* Sets the bairro value for this CadastrarCPFRequest.
*
* @param bairro
*/
public void setBairro(java.lang.String bairro) {
this.bairro = bairro;
}
/**
* Gets the CEP value for this CadastrarCPFRequest.
*
* @return CEP
*/
public java.lang.String getCEP() {
return CEP;
}
/**
* Sets the CEP value for this CadastrarCPFRequest.
*
* @param CEP
*/
public void setCEP(java.lang.String CEP) {
this.CEP = CEP;
}
/**
* Gets the telefone value for this CadastrarCPFRequest.
*
* @return telefone
*/
public java.lang.String getTelefone() {
return telefone;
}
/**
* Sets the telefone value for this CadastrarCPFRequest.
*
* @param telefone
*/
public void setTelefone(java.lang.String telefone) {
this.telefone = telefone;
}
/**
* Gets the celular value for this CadastrarCPFRequest.
*
* @return celular
*/
public java.lang.String getCelular() {
return celular;
}
/**
* Sets the celular value for this CadastrarCPFRequest.
*
* @param celular
*/
public void setCelular(java.lang.String celular) {
this.celular = celular;
}
/**
* Gets the CNHRegistro value for this CadastrarCPFRequest.
*
* @return CNHRegistro
*/
public java.lang.String getCNHRegistro() {
return CNHRegistro;
}
/**
* Sets the CNHRegistro value for this CadastrarCPFRequest.
*
* @param CNHRegistro
*/
public void setCNHRegistro(java.lang.String CNHRegistro) {
this.CNHRegistro = CNHRegistro;
}
/**
* Gets the CNH value for this CadastrarCPFRequest.
*
* @return CNH
*/
public java.lang.String getCNH() {
return CNH;
}
/**
* Sets the CNH value for this CadastrarCPFRequest.
*
* @param CNH
*/
public void setCNH(java.lang.String CNH) {
this.CNH = CNH;
}
/**
* Gets the CNHCategoria value for this CadastrarCPFRequest.
*
* @return CNHCategoria
*/
public java.lang.String getCNHCategoria() {
return CNHCategoria;
}
/**
* Sets the CNHCategoria value for this CadastrarCPFRequest.
*
* @param CNHCategoria
*/
public void setCNHCategoria(java.lang.String CNHCategoria) {
this.CNHCategoria = CNHCategoria;
}
/**
* Gets the CNHValidade value for this CadastrarCPFRequest.
*
* @return CNHValidade
*/
public java.util.Calendar getCNHValidade() {
return CNHValidade;
}
/**
* Sets the CNHValidade value for this CadastrarCPFRequest.
*
* @param CNHValidade
*/
public void setCNHValidade(java.util.Calendar CNHValidade) {
this.CNHValidade = CNHValidade;
}
/**
* Gets the CNHUF value for this CadastrarCPFRequest.
*
* @return CNHUF
*/
public java.lang.String getCNHUF() {
return CNHUF;
}
/**
* Sets the CNHUF value for this CadastrarCPFRequest.
*
* @param CNHUF
*/
public void setCNHUF(java.lang.String CNHUF) {
this.CNHUF = CNHUF;
}
/**
* Gets the observacao value for this CadastrarCPFRequest.
*
* @return observacao
*/
public java.lang.String getObservacao() {
return observacao;
}
/**
* Sets the observacao value for this CadastrarCPFRequest.
*
* @param observacao
*/
public void setObservacao(java.lang.String observacao) {
this.observacao = observacao;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof CadastrarCPFRequest)) return false;
CadastrarCPFRequest other = (CadastrarCPFRequest) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.autenticacao==null && other.getAutenticacao()==null) ||
(this.autenticacao!=null &&
this.autenticacao.equals(other.getAutenticacao()))) &&
((this.UF==null && other.getUF()==null) ||
(this.UF!=null &&
this.UF.equals(other.getUF()))) &&
((this.cidade==null && other.getCidade()==null) ||
(this.cidade!=null &&
this.cidade.equals(other.getCidade()))) &&
((this.funcao==null && other.getFuncao()==null) ||
(this.funcao!=null &&
this.funcao.equals(other.getFuncao()))) &&
((this.perfil==null && other.getPerfil()==null) ||
(this.perfil!=null &&
this.perfil.equals(other.getPerfil()))) &&
((this.nome==null && other.getNome()==null) ||
(this.nome!=null &&
this.nome.equals(other.getNome()))) &&
((this.controleCliente==null && other.getControleCliente()==null) ||
(this.controleCliente!=null &&
this.controleCliente.equals(other.getControleCliente()))) &&
((this.CPF==null && other.getCPF()==null) ||
(this.CPF!=null &&
this.CPF.equals(other.getCPF()))) &&
((this.RG==null && other.getRG()==null) ||
(this.RG!=null &&
this.RG.equals(other.getRG()))) &&
((this.orgaoExpeditor==null && other.getOrgaoExpeditor()==null) ||
(this.orgaoExpeditor!=null &&
this.orgaoExpeditor.equals(other.getOrgaoExpeditor()))) &&
((this.dataEmissao==null && other.getDataEmissao()==null) ||
(this.dataEmissao!=null &&
this.dataEmissao.equals(other.getDataEmissao()))) &&
((this.dataNascimento==null && other.getDataNascimento()==null) ||
(this.dataNascimento!=null &&
this.dataNascimento.equals(other.getDataNascimento()))) &&
((this.nomePai==null && other.getNomePai()==null) ||
(this.nomePai!=null &&
this.nomePai.equals(other.getNomePai()))) &&
((this.nomeMae==null && other.getNomeMae()==null) ||
(this.nomeMae!=null &&
this.nomeMae.equals(other.getNomeMae()))) &&
((this.endereco==null && other.getEndereco()==null) ||
(this.endereco!=null &&
this.endereco.equals(other.getEndereco()))) &&
((this.numero==null && other.getNumero()==null) ||
(this.numero!=null &&
this.numero.equals(other.getNumero()))) &&
((this.complemento==null && other.getComplemento()==null) ||
(this.complemento!=null &&
this.complemento.equals(other.getComplemento()))) &&
((this.bairro==null && other.getBairro()==null) ||
(this.bairro!=null &&
this.bairro.equals(other.getBairro()))) &&
((this.CEP==null && other.getCEP()==null) ||
(this.CEP!=null &&
this.CEP.equals(other.getCEP()))) &&
((this.telefone==null && other.getTelefone()==null) ||
(this.telefone!=null &&
this.telefone.equals(other.getTelefone()))) &&
((this.celular==null && other.getCelular()==null) ||
(this.celular!=null &&
this.celular.equals(other.getCelular()))) &&
((this.CNHRegistro==null && other.getCNHRegistro()==null) ||
(this.CNHRegistro!=null &&
this.CNHRegistro.equals(other.getCNHRegistro()))) &&
((this.CNH==null && other.getCNH()==null) ||
(this.CNH!=null &&
this.CNH.equals(other.getCNH()))) &&
((this.CNHCategoria==null && other.getCNHCategoria()==null) ||
(this.CNHCategoria!=null &&
this.CNHCategoria.equals(other.getCNHCategoria()))) &&
((this.CNHValidade==null && other.getCNHValidade()==null) ||
(this.CNHValidade!=null &&
this.CNHValidade.equals(other.getCNHValidade()))) &&
((this.CNHUF==null && other.getCNHUF()==null) ||
(this.CNHUF!=null &&
this.CNHUF.equals(other.getCNHUF()))) &&
((this.observacao==null && other.getObservacao()==null) ||
(this.observacao!=null &&
this.observacao.equals(other.getObservacao())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getAutenticacao() != null) {
_hashCode += getAutenticacao().hashCode();
}
if (getUF() != null) {
_hashCode += getUF().hashCode();
}
if (getCidade() != null) {
_hashCode += getCidade().hashCode();
}
if (getFuncao() != null) {
_hashCode += getFuncao().hashCode();
}
if (getPerfil() != null) {
_hashCode += getPerfil().hashCode();
}
if (getNome() != null) {
_hashCode += getNome().hashCode();
}
if (getControleCliente() != null) {
_hashCode += getControleCliente().hashCode();
}
if (getCPF() != null) {
_hashCode += getCPF().hashCode();
}
if (getRG() != null) {
_hashCode += getRG().hashCode();
}
if (getOrgaoExpeditor() != null) {
_hashCode += getOrgaoExpeditor().hashCode();
}
if (getDataEmissao() != null) {
_hashCode += getDataEmissao().hashCode();
}
if (getDataNascimento() != null) {
_hashCode += getDataNascimento().hashCode();
}
if (getNomePai() != null) {
_hashCode += getNomePai().hashCode();
}
if (getNomeMae() != null) {
_hashCode += getNomeMae().hashCode();
}
if (getEndereco() != null) {
_hashCode += getEndereco().hashCode();
}
if (getNumero() != null) {
_hashCode += getNumero().hashCode();
}
if (getComplemento() != null) {
_hashCode += getComplemento().hashCode();
}
if (getBairro() != null) {
_hashCode += getBairro().hashCode();
}
if (getCEP() != null) {
_hashCode += getCEP().hashCode();
}
if (getTelefone() != null) {
_hashCode += getTelefone().hashCode();
}
if (getCelular() != null) {
_hashCode += getCelular().hashCode();
}
if (getCNHRegistro() != null) {
_hashCode += getCNHRegistro().hashCode();
}
if (getCNH() != null) {
_hashCode += getCNH().hashCode();
}
if (getCNHCategoria() != null) {
_hashCode += getCNHCategoria().hashCode();
}
if (getCNHValidade() != null) {
_hashCode += getCNHValidade().hashCode();
}
if (getCNHUF() != null) {
_hashCode += getCNHUF().hashCode();
}
if (getObservacao() != null) {
_hashCode += getObservacao().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(CadastrarCPFRequest.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CadastrarCPFRequest"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("autenticacao");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Autenticacao"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("UF");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "UF"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("cidade");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Cidade"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("funcao");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Funcao"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("perfil");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Perfil"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("nome");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Nome"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("controleCliente");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "ControleCliente"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CPF");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CPF"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("RG");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "RG"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("orgaoExpeditor");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "OrgaoExpeditor"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("dataEmissao");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "DataEmissao"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("dataNascimento");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "DataNascimento"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("nomePai");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "NomePai"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("nomeMae");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "NomeMae"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("endereco");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Endereco"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("numero");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Numero"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("complemento");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Complemento"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("bairro");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Bairro"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CEP");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CEP"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("telefone");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Telefone"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("celular");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Celular"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CNHRegistro");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CNHRegistro"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CNH");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CNH"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CNHCategoria");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CNHCategoria"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CNHValidade");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CNHValidade"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "dateTime"));
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("CNHUF");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "CNHUF"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("observacao");
elemField.setXmlName(new javax.xml.namespace.QName("http://201.54.12.59/WS", "Observacao"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| 33.117593
| 109
| 0.5828
|
27cc54a2912ec62890c1b77522cd1a89f613b551
| 1,695
|
package me.kahlil.scene;
import static com.google.common.base.Preconditions.checkArgument;
import me.kahlil.config.JavaStyle;
import me.kahlil.graphics.MutableColor;
import org.immutables.value.Value.Check;
import org.immutables.value.Value.Default;
import org.immutables.value.Value.Immutable;
/** A representation of the material of a given shape. */
@Immutable
@JavaStyle
public interface Material {
/** The color of the material. */
MutableColor getColor();
/**
* An integer between 1 (inclusive) and 511 (inclusive) indicating the "hardness" of a meterial,
* which factors into specular lighting computation.
*/
int getHardness();
/**
* The specular intensity of a material (i.e. "shiny-ness") which is specified as a double between
* 0.0 (inclusive) and 1.0 (inclusive).
*/
double getSpecularIntensity();
/**
* A parameter indicating how reflective a surface is with 1.0 being the highest and 0.0 being
* the lowest.
*/
@Default
default double getReflectiveness() {
return 0.0;
}
@Check
default void checkPreconditions() {
checkArgument(
getHardness() > 0 && getHardness() < 512,
"Hardness must be an integer between 1 (inclusive) and 511 (inclusive) but was %d",
getHardness());
checkArgument(
getSpecularIntensity() >= 0.0 && getSpecularIntensity() <= 1.0,
"Specular intensity must be between 0.0 (inclusive) and 1.0 (inclusive) but was %f",
getSpecularIntensity());
checkArgument(getReflectiveness() >= 0.0 && getReflectiveness() <= 1.0,
"Reflectiveness must be between 0.0 (inclusive) and 1.0 (inclusive) but was %f",
getReflectiveness());
}
}
| 30.818182
| 100
| 0.687906
|
79d96d0317640cd8051eca7db9340896428c17da
| 675
|
package com.destiny.cat.mq;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import java.util.List;
@Slf4j
public class MessageListener implements MessageListenerConcurrently {
@Override
public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
list.forEach(node -> {
System.out.println(node);
});
return null;
}
}
| 24.107143
| 109
| 0.805926
|
1072127de03e2beb954a68c5d9c0c66ad58160cd
| 557
|
package patterns.behavior.state.stateaction;
/**
* Context.
*
* @author Maxim Vanny
* @version 5.0
* @since 10/14/2019
*/
class Context {
/**
* field state.
*/
private State state;
/**
* Constructor.
*/
Context() {
this.state = null;
}
/**
* Getter.
*
* @return context
*/
State getContext() {
return this.state;
}
/**
* Setter.
*
* @param aState state
*/
void setContext(final State aState) {
this.state = aState;
}
}
| 13.585366
| 44
| 0.48474
|
e5329bc11b10fd45578687c11e2d9bbe6fd5ed0e
| 1,547
|
package com.goertek.commonlib.custom.widget;
import android.graphics.drawable.Drawable;
/**
* 功能列表
*
* @author: ww
* @version: 1.0.0
* @since: 2019/07/23
*/
public class WidgetOptionBean {
private static final String TAG = "WidgetOptionBean";
private String content;
private Drawable icon;
private boolean isSelected;
private String optionIndex;
private int type;
public WidgetOptionBean() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Drawable getIcon() {
return icon;
}
public void setIcon(Drawable icon) {
this.icon = icon;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public String getOptionIndex() {
return optionIndex;
}
public void setOptionIndex(String optionIndex) {
this.optionIndex = optionIndex;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
@Override
public String toString() {
return "WidgetOptionBean{" +
"content='" + content + '\'' +
", icon=" + icon +
", isSelected=" + isSelected +
", optionIndex='" + optionIndex + '\'' +
", type=" + type +
'}';
}
}
| 19.582278
| 63
| 0.548158
|
8373b381f06c20d84091ae039ff967bad193effc
| 334
|
package com.wildox.calculator;
/**
* Created by Sujay on 21/02/18.
* operates +-/*%^
*/
public abstract class Operator implements Entities {
public abstract int getPriority();
public abstract double operateOn(double operand1, double operand2);
@Override
public int occupiedLength() {
return 1;
}
}
| 17.578947
| 71
| 0.670659
|
ec72cb3aa8c5d890db57816d9d61419c58976e99
| 6,849
|
package io.catvision.appl;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import com.github.paolorotolo.appintro.AppIntro;
import com.github.paolorotolo.appintro.AppIntroFragment;
import com.google.firebase.analytics.FirebaseAnalytics;
import io.catvision.appl.intro.CustomIntroFragment;
public class IntroActivity extends AppIntro {
public static int TYPE_NONE = 0;
public static int TYPE_QR = 1;
public static int TYPE_DEEP = 2;
// Permissions
private static int CAMERA_PERMISSION = 21;
// Requests
private static int QR_CODE_REQUEST = 31;
// Variables
private FirebaseAnalytics mFirebaseAnalytics;
private AppIntroFragment firstFragment;
private AppIntroFragment lastFragment;
/**
* Does an action depending on the specified type from the fragment.
* @param type int
*/
public void click(int type) {
switch (type) {
case 1:
if (isCameraPermissionGranted())
startQRScanActivity();
break;
case 2:
Intent intent = getIntent();
intent.putExtra("type", TYPE_DEEP);
setResult(RESULT_OK, intent);
finish();
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == QR_CODE_REQUEST) {
if (resultCode == RESULT_OK) {
data.putExtra("type", TYPE_QR); // specify the event
setResult(resultCode, data);
finish();
}
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Note here that we DO NOT use setContentView();
// Add your slide fragments here.
// AppIntro will automatically generate the dots indicator and buttons.
// addSlide(firstFragment);
// Special custom fragments
// Pairing #1
Fragment customFragment1 = new CustomIntroFragment();
Bundle b1 = new Bundle();
b1.putCharSequence("title", getResources().getString(R.string.intro_third_title));
b1.putCharSequence("description", getResources().getString(R.string.intro_third_text));
b1.putInt("image", R.drawable.cat3);
b1.putInt("color", getResources().getColor(R.color.colorSlide3));
b1.putInt("type", TYPE_QR);
customFragment1.setArguments(b1);
// Pairing #2
Fragment customFragment2 = new CustomIntroFragment();
Bundle b2 = new Bundle();
b2.putCharSequence("title", getResources().getString(R.string.intro_fourth_title));
b2.putCharSequence("description", getResources().getString(R.string.intro_fourth_text));
b2.putInt("image", R.drawable.cat4);
b2.putInt("color", getResources().getColor(R.color.colorSlide4));
b2.putInt("type", TYPE_DEEP);
customFragment2.setArguments(b2);
// Instead of fragments, you can also use our default slide
// Just set a title, description, background and image. AppIntro will do the rest.
firstFragment = AppIntroFragment.newInstance(getResources().getString(R.string.intro_first_title), getResources().getString(R.string.intro_first_text), R.drawable.cat1, getResources().getColor(R.color.colorSlide1));
addSlide(firstFragment);
addSlide(AppIntroFragment.newInstance(getResources().getString(R.string.intro_second_title), getResources().getString(R.string.intro_second_text), R.drawable.cat2, getResources().getColor(R.color.colorSlide2)));
addSlide(customFragment1);
addSlide(customFragment2);
lastFragment = AppIntroFragment.newInstance(getResources().getString(R.string.intro_fifth_title), getResources().getString(R.string.intro_fifth_text), R.drawable.cat5, getResources().getColor(R.color.colorSlide5));
addSlide(lastFragment);
// setting the title
setTitle(getResources().getString(R.string.intro_title_first));
// OPTIONAL METHODS
// Override bar/separator color.
setBarColor(getResources().getColor(R.color.colorPrimary));
// setSeparatorColor(Color.parseColor("#2196F3"));
// Hide Skip/Done button.
showSkipButton(true);
setProgressButtonEnabled(true);
// Turn vibration on and set intensity.
// NOTE: you will probably need to ask VIBRATE permission in Manifest.
// setVibrate(true);
// setVibrateIntensity(30);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
@Override
public void onSkipPressed(Fragment currentFragment) {
super.onSkipPressed(currentFragment);
// Do something when users tap on Skip button.
finish();
}
@Override
public void onDonePressed(Fragment currentFragment) {
super.onDonePressed(currentFragment);
// Do something when users tap on Done button.
finish();
}
@Override
public void onSlideChanged(@Nullable Fragment oldFragment, @Nullable Fragment newFragment) {
super.onSlideChanged(oldFragment, newFragment);
// Do something when the slide changes.
try {
if (newFragment != firstFragment && newFragment != lastFragment) {
setTitle(getResources().getString(R.string.intro_title_other));
} else {
setTitle(getResources().getString(R.string.intro_title_first));
}
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Starts an activity that retrieves the QR code.
*/
public void startQRScanActivity() {
mFirebaseAnalytics.logEvent(getResources().getString(R.string.event_pair_qr), new Bundle());
Intent intent = new Intent(getApplicationContext(), QRCodeScannerActivity.class);
startActivityForResult(intent, QR_CODE_REQUEST);
}
// Permissions ---------------------------------------------------------------------------------
/**
* Checks if it is allowed to use the camera.
* @return boolean
*/
public boolean isCameraPermissionGranted() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(android.Manifest.permission.CAMERA)
== PackageManager.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.CAMERA}, CAMERA_PERMISSION);
return false;
}
} else {
return true;
}
}
/**
* Continues after the permission is obtained.
* @param requestCode int
* @param permissions @NonNull String[]
* @param grantResults @NonNull int[]
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (requestCode == CAMERA_PERMISSION) {
startQRScanActivity();
}
}
}
}
| 33.086957
| 217
| 0.739524
|
cf22929e5252a51fd8ea2150ea0cb450e9f2161f
| 129
|
package thinking.in.spring.boot.samples.spring.application.model;
public class Male {
public Male(Person person) {
}
}
| 16.125
| 65
| 0.72093
|
bdfa0ee3baa67f561a0dda3ed6f44fcd368fef78
| 7,944
|
package com.example.todoapp.tasks;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.text.TextUtils;
import android.view.View;
import android.widget.ListView;
import com.example.todoapp.Injection;
import com.example.todoapp.R;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.InstrumentationRegistry.getTargetContext;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.replaceText;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.doesNotExist;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.hasSibling;
import static android.support.test.espresso.matcher.ViewMatchers.isAssignableFrom;
import static android.support.test.espresso.matcher.ViewMatchers.isDescendantOfA;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static com.google.common.base.Preconditions.checkArgument;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.core.IsNot.not;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class TasksScreenTest {
private final static String TITLE1 = "TITLE1";
private final static String DESCRIPTION = "DESCR";
private final static String TITLE2 = "TITLE2";
@Rule
public ActivityTestRule<TasksActivity> mTasksActivityTestRule =
new ActivityTestRule<TasksActivity>(TasksActivity.class) {
@Override
protected void beforeActivityLaunched() {
super.beforeActivityLaunched();
Injection.INSTANCE.provideTasksRepository(InstrumentationRegistry.getTargetContext())
.deleteAllTasks();
}
};
private Matcher<View> withItemText(final String itemText) {
checkArgument(!TextUtils.isEmpty(itemText), "itemText cannot be null or empty");
return new TypeSafeMatcher<View>() {
@Override
public boolean matchesSafely(View item) {
return allOf(
isDescendantOfA(isAssignableFrom(ListView.class)),
withText(itemText)).matches(item);
}
@Override
public void describeTo(Description description) {
description.appendText("is isDescendantOfA LV with text " + itemText);
}
};
}
@Test
public void editTask() throws Exception {
createTask(TITLE1, DESCRIPTION);
onView(withText(TITLE1)).perform(click());
onView(withId(R.id.fabEditTask)).perform(click());
String editTaskTitle = TITLE2;
String editTaskDescription = "New Description";
onView(withId(R.id.addTaskTitle)).perform(replaceText(editTaskTitle), closeSoftKeyboard());
onView(withId(R.id.addTaskDescription)).perform(replaceText(editTaskDescription),
closeSoftKeyboard());
onView(withId(R.id.fabAddTask)).perform(click());
onView(withItemText(editTaskTitle)).check(matches(isDisplayed()));
onView(withItemText(TITLE1)).check(doesNotExist());
}
@Test
public void addTaskToTasksList() throws Exception {
createTask(TITLE1, DESCRIPTION);
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
}
@Test
public void markTaskAsComplete() {
viewAllTasks();
createTask(TITLE1, DESCRIPTION);
clickCheckBoxForTask(TITLE1);
viewAllTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
viewActiveTasks();
onView(withItemText(TITLE1)).check(matches(not(isDisplayed())));
viewCompletedTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
}
@Test
public void markTaskAsActive() {
viewAllTasks();
createTask(TITLE1, DESCRIPTION);
clickCheckBoxForTask(TITLE1);
clickCheckBoxForTask(TITLE1);
viewAllTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
viewActiveTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
viewCompletedTasks();
onView(withItemText(TITLE1)).check(matches(not(isDisplayed())));
}
@Test
public void showAllTasks() {
createTask(TITLE1, DESCRIPTION);
createTask(TITLE2, DESCRIPTION);
viewAllTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
onView(withItemText(TITLE2)).check(matches(isDisplayed()));
}
@Test
public void showActiveTasks() {
createTask(TITLE1, DESCRIPTION);
createTask(TITLE2, DESCRIPTION);
viewActiveTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
onView(withItemText(TITLE2)).check(matches(isDisplayed()));
}
@Test
public void showCompletedTasks() {
createTask(TITLE1, DESCRIPTION);
clickCheckBoxForTask(TITLE1);
createTask(TITLE2, DESCRIPTION);
clickCheckBoxForTask(TITLE2);
viewCompletedTasks();
onView(withItemText(TITLE1)).check(matches(isDisplayed()));
onView(withItemText(TITLE2)).check(matches(isDisplayed()));
}
@Test
public void clearCompletedTasks() {
viewAllTasks();
createTask(TITLE1, DESCRIPTION);
clickCheckBoxForTask(TITLE1);
createTask(TITLE2, DESCRIPTION);
clickCheckBoxForTask(TITLE2);
openActionBarOverflowOrOptionsMenu(getTargetContext());
onView(withText(R.string.menu_clear)).perform(click());
onView(withItemText(TITLE1)).check(matches(not(isDisplayed())));
onView(withItemText(TITLE2)).check(matches(not(isDisplayed())));
}
@Test
public void createOneTask_deleteTask() {
viewAllTasks();
createTask(TITLE1, DESCRIPTION);
onView(withText(TITLE1)).perform(click());
onView(withId(R.id.menu_delete)).perform(click());
viewAllTasks();
onView(withText(TITLE1)).check(matches(not(isDisplayed())));
}
private void viewAllTasks() {
onView(withId(R.id.menu_filter)).perform(click());
onView(withText(R.string.nav_all)).perform(click());
}
private void viewActiveTasks() {
onView(withId(R.id.menu_filter)).perform(click());
onView(withText(R.string.nav_active)).perform(click());
}
private void viewCompletedTasks() {
onView(withId(R.id.menu_filter)).perform(click());
onView(withText(R.string.nav_completed)).perform(click());
}
private void createTask(String title, String description) {
onView(withId(R.id.fabAddTask)).perform(click());
onView(withId(R.id.addTaskTitle)).perform(typeText(title), closeSoftKeyboard());
onView(withId(R.id.addTaskDescription)).perform(typeText(description), closeSoftKeyboard());
onView(withId(R.id.fabAddTask)).perform(click());
}
private void clickCheckBoxForTask(String title) {
onView(allOf(withId(R.id.itemComplete), hasSibling(withText(title)))).perform(click());
}
}
| 38.376812
| 105
| 0.694109
|
d40990d614b124dc8018b28f945e2bed16397ec7
| 4,429
|
/*
* Copyright (c) 2008-2021, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.cache.impl.operation;
import com.hazelcast.cache.impl.CacheDataSerializerHook;
import com.hazelcast.cache.impl.record.CacheRecord;
import com.hazelcast.internal.eviction.ExpiredKey;
import com.hazelcast.internal.nio.IOUtil;
import com.hazelcast.nio.ObjectDataInput;
import com.hazelcast.nio.ObjectDataOutput;
import com.hazelcast.spi.impl.operationservice.ExceptionAction;
import com.hazelcast.spi.exception.WrongTargetException;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
/**
* Used to transfer expired keys from owner replica to backup replicas.
*/
public class CacheExpireBatchBackupOperation extends CacheOperation {
private int primaryEntryCount;
private Collection<ExpiredKey> expiredKeys;
public CacheExpireBatchBackupOperation() {
}
public CacheExpireBatchBackupOperation(String name, Collection<ExpiredKey> expiredKeys, int primaryEntryCount) {
super(name, true);
this.expiredKeys = expiredKeys;
this.primaryEntryCount = primaryEntryCount;
}
@Override
public void run() {
if (recordStore == null) {
return;
}
for (ExpiredKey expiredKey : expiredKeys) {
evictIfSame(expiredKey);
}
equalizeEntryCountWithPrimary();
}
/**
* Equalizes backup entry count with primary in order to have identical
* memory occupancy.
*/
private void equalizeEntryCountWithPrimary() {
int diff = recordStore.size() - primaryEntryCount;
if (diff > 0) {
recordStore.sampleAndForceRemoveEntries(diff);
assert recordStore.size() == primaryEntryCount : String.format("Failed"
+ " to remove %d entries while attempting to match"
+ " primary entry count %d,"
+ " recordStore size is now %d",
diff, primaryEntryCount, recordStore.size());
}
}
@Override
public void afterRun() throws Exception {
try {
super.afterRun();
} finally {
recordStore.disposeDeferredBlocks();
}
}
@Override
public ExceptionAction onInvocationException(Throwable throwable) {
if (throwable instanceof WrongTargetException) {
if (((WrongTargetException) throwable).getTarget() == null) {
// If there isn't any address of backup replica, no need to retry this operation.
return ExceptionAction.THROW_EXCEPTION;
}
}
return super.onInvocationException(throwable);
}
protected void evictIfSame(ExpiredKey key) {
CacheRecord record = recordStore.getRecord(key.getKey());
if (record != null && record.getCreationTime() == key.getCreationTime()) {
recordStore.removeRecord(key.getKey());
}
}
@Override
public int getClassId() {
return CacheDataSerializerHook.EXPIRE_BATCH_BACKUP;
}
@Override
protected void writeInternal(ObjectDataOutput out) throws IOException {
super.writeInternal(out);
out.writeInt(expiredKeys.size());
for (ExpiredKey expiredKey : expiredKeys) {
IOUtil.writeData(out, expiredKey.getKey());
out.writeLong(expiredKey.getCreationTime());
}
out.writeInt(primaryEntryCount);
}
@Override
protected void readInternal(ObjectDataInput in) throws IOException {
super.readInternal(in);
int size = in.readInt();
expiredKeys = new LinkedList<ExpiredKey>();
for (int i = 0; i < size; i++) {
expiredKeys.add(new ExpiredKey(IOUtil.readData(in), in.readLong()));
}
primaryEntryCount = in.readInt();
}
}
| 33.052239
| 116
| 0.660646
|
878f783829e66b9baaf5e8834e71e92ccbefa0c2
| 18,655
|
/*
Copyright 2013 by Victor Jatoba
Licensed under the Academic Free License version 3.0
*/
package ec.app.aspga;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Vector;
import ec.EvolutionState;
import ec.app.aspga.bean.AspgaContext;
import ec.app.aspga.bean.Subject;
import ec.app.aspga.bean.SubjectWorkload;
import ec.util.Parameter;
import ec.vector.Gene;
/**
* The Gene that represent the individual genome. <br/>
* In this class is implemented the mutation logic,
* the creation of the initial population and the method
* used to compare two individuals.
*
* @author Victor Jatoba
* @version Apr 23 2017
*/
@SuppressWarnings("serial")
public class DayPlanGene extends Gene {
public static final int PERIOD_HOURS_LIMIT = 8; // Max 4h per period
public static final int MINIMUM_HOURS_LIMIT_DISCIPLINE = 2; // Min 1h per discipline
// Our allele is represented by the tree period of the day below.
private SubjectWorkload[] morning;
private SubjectWorkload[] afternoon;
private SubjectWorkload[] night;
private Subject[] subjects;
@Override
public void setup(final EvolutionState state, final Parameter base) {
super.setup(state, base);
this.subjects = AspgaContext.getInstance().getSubjects();
this.morning = new SubjectWorkload[0];
this.afternoon = new SubjectWorkload[0];
this.night = new SubjectWorkload[0];
}
@Override
public void reset(EvolutionState state, int thread) {
this.morning = new SubjectWorkload[0];
this.afternoon = new SubjectWorkload[0];
this.night = new SubjectWorkload[0];
// Try to schedule max 9 disciplines per day
int maxSubjectsQuantity = state.random[thread].nextInt(9);
for (int i = 0; i < maxSubjectsQuantity; i++) {
if (!insertSubjectWorkload(state, thread)) {
// insertSubjectWorkload(state, thread);
}
}
// System.out.println(printGeneToStringForHumans());
}
/**
* Verify if the array of subjectWorkloads contains the subject passed by param.
*
* @param periodOfTheDay
* period of the day that to be searched.
* @param sw
* the subjectWorkload to be found.
*
* @return <code>true</code> if found. <code>false</code> otherwise.
*/
// TODO containsAndMore... or containsOrMore.. ?
public boolean containsAndMoreThanFive(SubjectWorkload[] periodOfTheDay, SubjectWorkload sw) {
return (this.contains(periodOfTheDay, sw.getSubject()) || this.workloadExceeds(periodOfTheDay, sw.getWorkload()));
}
/**
* Verify if the period contains the specific subject.
*
* @param periodOfTheDay
* period of the day to be verified.
* @param subject
* subject to be found.
*
* @return <code>true</code> if period contains the subject. <code>false</code> otherwise.
*
*/
public boolean contains(SubjectWorkload[] periodOfTheDay, Subject subject) {
for (SubjectWorkload swActual : periodOfTheDay) {
if (swActual.getSubject().getId() == subject.getId()) {
return true;
}
}
return false;
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (!(other instanceof DayPlanGene))
return false;
if (((DayPlanGene) other).morning.length != this.morning.length)
return false;
if (((DayPlanGene) other).afternoon.length != this.afternoon.length)
return false;
if (((DayPlanGene) other).night.length != this.night.length)
return false;
for (int i = 0; i < this.morning.length; i++) {
if (this.morning[i].getSubject().getId() != ((DayPlanGene) other).morning[i].getSubject().getId())
return false;
if (this.morning[i].getWorkload() != ((DayPlanGene) other).morning[i].getWorkload())
return false;
}
for (int i = 0; i < this.afternoon.length; i++) {
if (this.afternoon[i].getSubject().getId() != ((DayPlanGene) other).afternoon[i].getSubject().getId())
return false;
if (this.afternoon[i].getWorkload() != ((DayPlanGene) other).afternoon[i].getWorkload())
return false;
}
for (int i = 0; i < this.night.length; i++) {
if (this.night[i].getSubject().getId() != ((DayPlanGene) other).night[i].getSubject().getId())
return false;
if (this.night[i].getWorkload() != ((DayPlanGene) other).night[i].getWorkload())
return false;
}
return true;
}
@Override
public void mutate(final EvolutionState state, final int thread) {
int count = 0;
while (!doMutate(state, thread) && (count < 5)) {
count++;
}
// doMutate(state, thread);
}
/**
* To make mutation in a random gene.
*
* @param state
* [description]
* @param thread
* [description]
*
* @return <code>true</code> Case the mutation was done.<br/>
* <code>false</code> otherwise.
*/
public Boolean doMutate(EvolutionState state, final int thread) {
Boolean mutated = Boolean.TRUE;
int mutationType = state.random[thread].nextInt(2); // generate random from 0 to 2
// mutationType = 4;
int vectorsLength = this.morning.length + this.afternoon.length + this.night.length;
if (mutationType == 1 && vectorsLength != 0) {
// System.out.println("---1---");
mutated = changeWorkload(state, thread);
} else if (mutationType == 2 && vectorsLength != 0) {
// System.out.println("---2---");
mutated = changeSubject(state, thread);
}
// If I don't have any SubjectWorkload, just add one.
/*
* else if(mutationType == 0) { // System.out.println("---0---"); mutated = insertSubjectWorkload(state, thread); } else if(mutationType == 3) { //
* System.out.println("---2---"); mutated = removeSubjectWorkload(state, thread); } else { System.out.println("---3---"); Boolean changeW =
* changeWorkload(state, thread); Boolean changeS = changeSubject(state, thread); mutated = (changeW || changeS); }
*/
return mutated;
}
/**
* Add a new subjectWorkload in a random period of the day.
*
* @param state
* @param thread
*
* @return <code>true</code> if the subjectWorkload was added successfully. <br/>
* <code>false</code> otherwise.
*
* @see ec.EvolutionState
* @see ec.app.aspga.bean.SubjectWorkload
*/
public boolean insertSubjectWorkload(EvolutionState state, final int thread) {
SubjectWorkload subjectWorkload = getNewSubjectWorkloadInstance(state, thread);
int periodOfTheDay = state.random[thread].nextInt(2); // random from 0 to 2
// Don't be permitted insert duplicated subjects
if (periodOfTheDay == 0 && !containsAndMoreThanFive(this.morning, subjectWorkload)) {
// System.out.println(subjectWorkload.getSubject().getName() + " inserted 1");
this.morning = addElement(this.morning, subjectWorkload);
} else if (periodOfTheDay == 1 && !containsAndMoreThanFive(this.afternoon, subjectWorkload)) {
// System.out.println(subjectWorkload.getSubject().getName() + " inserted 2");
this.afternoon = addElement(this.afternoon, subjectWorkload);
} else if (!containsAndMoreThanFive(this.night, subjectWorkload)) {
// System.out.println(subjectWorkload.getSubject().getName() + " inserted 3");
this.night = addElement(this.night, subjectWorkload);
} else {
return false;
}
return true;
}
private SubjectWorkload[] addElement(SubjectWorkload[] array, SubjectWorkload element) {
array = Arrays.copyOf(array, array.length + 1);
array[array.length - 1] = element;
return array;
}
/**
* Remove randomly one subjectWorkload from one period of the day.
*
* @return <code>true</code> if the subjectWorkload was removed successfully.<br/>
* <code>false</code> otherwise.
*/
public boolean removeSubjectWorkload(EvolutionState state, int thread) {
int periodOfTheDay = state.random[thread].nextInt(2); // random from 0 to 2
if (periodOfTheDay == 0 && !(this.morning.length == 0)) {
this.morning = removeElement(this.morning, state.random[thread].nextInt(morning.length));
} else if (periodOfTheDay == 1 && !(this.afternoon.length == 0)) {
this.afternoon = removeElement(this.afternoon, state.random[thread].nextInt(afternoon.length));
} else if (!(this.night.length == 0)) {
this.night = removeElement(this.night, state.random[thread].nextInt(night.length));
} else {
return false;
}
return true;
}
public static SubjectWorkload[] removeElement(SubjectWorkload[] input, int position) {
List result = new LinkedList();
for (int i = 0; i < input.length; i++) {
if (position != i) {
result.add(input[i]);
}
}
return (SubjectWorkload[]) result.toArray(input);
}
/**
* Responsible for change a workload from a randomly subjectWorkload.
*
* @return <code>true</code> if the workload was change successfully.<br/>
* <code>false</code> otherwise.
*/
public Boolean changeWorkload(EvolutionState state, int thread) {
SubjectWorkload[] period = null;
int periodOfTheDay = state.random[thread].nextInt(2); // random from 0 to 2
if (periodOfTheDay == 0 && (this.morning.length > 0)) {
period = this.morning;
} else if (periodOfTheDay == 1 && (this.afternoon.length > 0)) {
period = this.afternoon;
} else if (this.night.length > 0) {
period = this.night;
} else {
return false;
}
SubjectWorkload randomSubjectWorkload = period[(state.random[thread].nextInt(period.length))];
byte workloadToBeChanged = (byte) getWorkloadDifferentOf(randomSubjectWorkload.getWorkload(), state, thread);
if (!workloadExceeds(period, workloadToBeChanged)) {
randomSubjectWorkload.setWorkload(workloadToBeChanged);
// String s = randomSubjectWorkload.getSubject().getName(); s += "[M]"; randomSubjectWorkload.getSubject().setName(s);
} else {
return false;
}
return true;
}
/**
* Verify if the sum of the workload and the all workloads of the Subjects passed by param don't exceeds more than five hours.
*
* @param periodOfTheDay
* The subjects and their workloads to be verified.
* @param workload
* the workload to be verified.
*
* @return <code>true</code> if the sum don't exceeds five hours. <br/>
* <code>false</code> otherwise.
*/
public boolean workloadExceeds(SubjectWorkload[] periodOfTheDay, int workload) {
int workloadSum = 0;
for (SubjectWorkload swActual : periodOfTheDay) {
workloadSum += swActual.getWorkload();
}
if ((workloadSum + workload) > PERIOD_HOURS_LIMIT) {
return true;
}
return false;
}
/**
* Get a workload different of the workload passed by param.
*
* @param workload
* @return <code>int</code> the workload value. From 1 to 10
*/
public int getWorkloadDifferentOf(int workload, EvolutionState state, int thread) {
int workloadRandom = (state.random[thread].nextInt(PERIOD_HOURS_LIMIT) + MINIMUM_HOURS_LIMIT_DISCIPLINE);
while (workloadRandom == workload) {
// System.out.println(workload + " equals. Generating other..");
workloadRandom = (state.random[thread].nextInt(PERIOD_HOURS_LIMIT) + MINIMUM_HOURS_LIMIT_DISCIPLINE);
}
return workloadRandom;
}
/**
* Modify a random subject in a random period of the day.
*
* @return <code>true</code> if the subject was change successfully.<br/>
* <code>false</code> otherwise.
*/
public Boolean changeSubject(EvolutionState state, int thread) {
SubjectWorkload[] period = null;
Subject subjectOld = null;
Boolean mutated = Boolean.TRUE;
int periodOfTheDay = state.random[thread].nextInt(2); // random from 0 to 2
if (periodOfTheDay == 0 && (this.morning.length > 0)) {
subjectOld = this.morning[state.random[thread].nextInt(morning.length)].getSubject();
period = this.morning;
} else if (periodOfTheDay == 1 && (this.afternoon.length > 0)) {
subjectOld = this.afternoon[state.random[thread].nextInt(afternoon.length)].getSubject();
period = this.afternoon;
} else if (this.night.length > 0) {
subjectOld = this.night[state.random[thread].nextInt(night.length)].getSubject();
period = this.night;
} else {
mutated = Boolean.FALSE;
}
if (subjectOld != null) {
// System.out.println("Old: " + subjectOld.getName() + " "+ subjectOld.getId());
Subject subjectRandom = getSubjectDifferentOf(subjectOld, state, thread);
if (!contains(period, subjectRandom)) {
subjectOld.setName(new String(subjectRandom.getName()));
// String s = subjectOld.getName(); s += "[-]"; subjectOld.setName(s);
subjectOld.setId(subjectRandom.getId());
subjectOld.setDifficulty(subjectRandom.getDifficulty());
// System.out.println("OldNew: " + subjectOld.getName() + " "+ subjectOld.getId());
} else {
mutated = Boolean.FALSE;
}
}
return mutated;
}
/**
* Get a Subject different of the subject passed by param.
*
* @param subject
* @param state
* @param thread
*
* @return <code>Subject</code> the new instance.
*
* @see ec.app.aspga.bean.Subject
*/
public Subject getSubjectDifferentOf(Subject subject, EvolutionState state, int thread) {
Subject subjectNew = subjects[state.random[thread].nextInt(subjects.length)];
int idRandom = subjectNew.getId();
int idOld = subject.getId();
if (subjects.length > 1) {
while (idRandom == idOld) {
subjectNew = subjects[state.random[thread].nextInt(subjects.length)];
idRandom = subjectNew.getId();
}
}
// System.out.println("" + subject.getName() + " " + subjectNew.getName());
return getNewSubjectInstance(subjectNew);
}
/**
* Get a new instance from a subject passed by param.
*
* @param subject
* @return <code>Subject</code> the new instance from subject.
*
* @see ec.app.aspga.bean.Subject
*/
public Subject getNewSubjectInstance(Subject subject) {
Subject subjectRandom = new Subject();
subjectRandom.setName(new String(subject.getName()));
subjectRandom.setId(subject.getId());
subjectRandom.setDifficulty(subject.getDifficulty());
return subjectRandom;
}
/**
* Get a new instance from a arbitrary subjectWorkload.
*
* @param state
* @param thread
*
* @return <code>SubjectWorkload</code> the new instance from subjectWorkload.
*
* @see ec.app.aspga.bean.SubjectWorkload
* @see ec.EvolutionState
*/
public SubjectWorkload getNewSubjectWorkloadInstance(EvolutionState state, int thread) {
Subject subject = subjects[state.random[thread].nextInt(subjects.length)];
Subject subjectNew = getNewSubjectInstance(subject);
// System.out.println("id1 " + subjectNew.getId() + " id2 " + subject.getId());
byte workload = (byte) (state.random[thread].nextInt(PERIOD_HOURS_LIMIT) + MINIMUM_HOURS_LIMIT_DISCIPLINE);
SubjectWorkload subjectWorkload = new SubjectWorkload();
subjectWorkload.setSubject(subjectNew);
subjectWorkload.setWorkload(workload);
return subjectWorkload;
}
/*
* @see ec.vector.GeneVectorIndividual#hashCode()
*/
@Override
public int hashCode() {
// stolen from GPIndividual. It's a decent algorithm.
int hash = ((Object) this).getClass().hashCode();
hash = (hash << 1 | hash >>> 31);
for (int x = 0; x < morning.length; x++) {
SubjectWorkload sw = morning[x];
hash = (hash << 1 | hash >>> 31) ^ (sw.getSubject().getId() + sw.getWorkload());
}
for (int x = 0; x < afternoon.length; x++) {
SubjectWorkload sw = afternoon[x];
hash = (hash << 1 | hash >>> 31) ^ (sw.getSubject().getId() + sw.getWorkload());
}
for (int x = 0; x < night.length; x++) {
SubjectWorkload sw = night[x];
hash = (hash << 1 | hash >>> 31) ^ (sw.getSubject().getId() + sw.getWorkload());
}
return hash;
}
/**
* In reality Gene is not going to be very useful unless you at least provide a way to describe the gene when it’s printed to a log. The easiest way to do
* this is to override this method.
*/
@Override
public String printGeneToStringForHumans() {
int size = morning.length + afternoon.length + night.length;
String output = new String("");
output += "" + ("--------------------------\n" + "number of subjectWorkloads: " + size + "\n--------------------------\n");
output += "" + ("\n[Morning] \n");
for (SubjectWorkload subjectWorkload : morning) {
float workload = ((float) subjectWorkload.getWorkload()) / (float) 2;
output += "" + (subjectWorkload.getSubject().getName() + " " + workload + "\n");
}
output += "" + ("\n[Afternoon] \n");
for (SubjectWorkload subjectWorkload : afternoon) {
float workload = ((float) subjectWorkload.getWorkload()) / (float) 2;
output += "" + (subjectWorkload.getSubject().getName() + " " + workload + "\n");
}
output += "" + ("\n[Night] \n");
for (SubjectWorkload subjectWorkload : night) {
float workload = ((float) subjectWorkload.getWorkload()) / (float) 2;
output += "" + (subjectWorkload.getSubject().getName() + " " + workload + "\n");
}
return output;
}
@Override
public String toString() {
return printGeneToStringForHumans();
}
/**
* Print all the classes filled
*
* @param dayPlanGene
*/
public void printDayPlan(DayPlanGene dayPlanGene) {
int size = morning.length + afternoon.length + night.length;
System.out.println("-----------------------\nnumber of subjectWorkloads: " + size);
System.out.println("\nmorning: ");
for (SubjectWorkload subjectWorkload : dayPlanGene.morning) {
float workload = ((float) subjectWorkload.getWorkload()) / (float) 2;
System.out.println(subjectWorkload.getSubject().getName() + " " + workload);
}
System.out.println("\nafternoon: ");
for (SubjectWorkload subjectWorkload : dayPlanGene.afternoon) {
float workload = ((float) subjectWorkload.getWorkload()) / (float) 2;
System.out.println(subjectWorkload.getSubject().getName() + " " + workload);
}
System.out.println("\nnight: ");
for (SubjectWorkload subjectWorkload : dayPlanGene.night) {
float workload = ((float) subjectWorkload.getWorkload()) / (float) 2;
System.out.println(subjectWorkload.getSubject().getName() + " " + workload);
}
}
public SubjectWorkload[] getMorning() {
return this.morning;
}
public SubjectWorkload[] getAfternoon() {
return this.afternoon;
}
public SubjectWorkload[] getNight() {
return this.night;
}
public void setMorning(SubjectWorkload[] morning) {
this.morning = morning;
}
public void setAfternoon(SubjectWorkload[] afternoon) {
this.afternoon = afternoon;
}
public void setNight(SubjectWorkload[] night) {
this.night = night;
}
/**
* Print in the console the lines of the input.
*/
public void printInputLines(Vector<String> lines, String type) {
System.out.println("\n------------" + type + "---------------");
for (String lineIt : lines) {
System.out.println(lineIt);
System.out.println();
}
System.out.println("----------------Done!-------------------");
}
}
| 32.108434
| 155
| 0.676977
|
881871c885512c879acdc19328e67396da04e510
| 2,689
|
package com.bitmovin.api.sdk.model;
import java.util.Objects;
import java.util.Arrays;
import com.bitmovin.api.sdk.model.BitmovinResource;
import com.bitmovin.api.sdk.model.InputPath;
import com.bitmovin.api.sdk.model.SmpteTimecodeFlavor;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
/**
* SccCaption
*/
public class SccCaption extends BitmovinResource {
@JsonProperty("input")
private InputPath input;
@JsonProperty("smpteTimecodeFlavor")
private SmpteTimecodeFlavor smpteTimecodeFlavor;
/**
* Input location of the SCC file (required)
* @return input
*/
public InputPath getInput() {
return input;
}
/**
* Input location of the SCC file (required)
*
* @param input
* Input location of the SCC file (required)
*/
public void setInput(InputPath input) {
this.input = input;
}
/**
* Get smpteTimecodeFlavor
* @return smpteTimecodeFlavor
*/
public SmpteTimecodeFlavor getSmpteTimecodeFlavor() {
return smpteTimecodeFlavor;
}
/**
* Set smpteTimecodeFlavor
*
* @param smpteTimecodeFlavor
*/
public void setSmpteTimecodeFlavor(SmpteTimecodeFlavor smpteTimecodeFlavor) {
this.smpteTimecodeFlavor = smpteTimecodeFlavor;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
SccCaption sccCaption = (SccCaption) o;
return Objects.equals(this.input, sccCaption.input) &&
Objects.equals(this.smpteTimecodeFlavor, sccCaption.smpteTimecodeFlavor) &&
super.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(input, smpteTimecodeFlavor, super.hashCode());
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class SccCaption {\n");
sb.append(" ").append(toIndentedString(super.toString())).append("\n");
sb.append(" input: ").append(toIndentedString(input)).append("\n");
sb.append(" smpteTimecodeFlavor: ").append(toIndentedString(smpteTimecodeFlavor)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 25.130841
| 102
| 0.686872
|
f66321b1d6747f4fc3977dd177ffd35218269b6e
| 7,300
|
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) annotate safe
package androidx.work;
import androidx.work.impl.utils.futures.SettableFuture;
import kotlin.Unit;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.intrinsics.IntrinsicsKt;
import kotlin.coroutines.jvm.internal.SuspendLambda;
import kotlin.jvm.functions.Function2;
import kotlin.jvm.internal.Intrinsics;
import kotlinx.coroutines.CoroutineScope;
// Referenced classes of package androidx.work:
// CoroutineWorker
static final class CoroutineWorker$startWork$1 extends SuspendLambda
implements Function2
{
public final Continuation create(Object obj, Continuation continuation)
{
Intrinsics.checkParameterIsNotNull(((Object) (continuation)), "completion");
// 0 0:aload_2
// 1 1:ldc1 #59 <String "completion">
// 2 3:invokestatic #65 <Method void Intrinsics.checkParameterIsNotNull(Object, String)>
continuation = ((Continuation) (new CoroutineWorker$startWork$1(CoroutineWorker.this, continuation)));
// 3 6:new #2 <Class CoroutineWorker$startWork$1>
// 4 9:dup
// 5 10:aload_0
// 6 11:getfield #49 <Field CoroutineWorker this$0>
// 7 14:aload_2
// 8 15:invokespecial #67 <Method void CoroutineWorker$startWork$1(CoroutineWorker, Continuation)>
// 9 18:astore_2
continuation.p$ = (CoroutineScope)obj;
// 10 19:aload_2
// 11 20:aload_1
// 12 21:checkcast #69 <Class CoroutineScope>
// 13 24:putfield #71 <Field CoroutineScope p$>
return continuation;
// 14 27:aload_2
// 15 28:areturn
}
public final Object invoke(Object obj, Object obj1)
{
return ((CoroutineWorker$startWork$1)create(obj, (Continuation)obj1)).invokeSuspend(((Object) (Unit.INSTANCE)));
// 0 0:aload_0
// 1 1:aload_1
// 2 2:aload_2
// 3 3:checkcast #77 <Class Continuation>
// 4 6:invokevirtual #79 <Method Continuation create(Object, Continuation)>
// 5 9:checkcast #2 <Class CoroutineWorker$startWork$1>
// 6 12:getstatic #85 <Field Unit Unit.INSTANCE>
// 7 15:invokevirtual #88 <Method Object invokeSuspend(Object)>
// 8 18:areturn
}
public final Object invokeSuspend(Object obj)
{
Object obj2 = IntrinsicsKt.getCOROUTINE_SUSPENDED();
// 0 0:invokestatic #96 <Method Object IntrinsicsKt.getCOROUTINE_SUSPENDED()>
// 1 3:astore_3
label;
// 2 4:aload_0
// 3 5:getfield #98 <Field int label>
JVM INSTR tableswitch 0 1: default 32
// 0 64
// 1 42;
// 4 8:tableswitch 0 1: default 32
// 0 64
// 1 42
goto _L1 _L2 _L3
_L1:
throw new IllegalStateException("call to 'resume' before 'invoke' with coroutine");
// 5 32:new #100 <Class IllegalStateException>
// 6 35:dup
// 7 36:ldc1 #102 <String "call to 'resume' before 'invoke' with coroutine">
// 8 38:invokespecial #105 <Method void IllegalStateException(String)>
// 9 41:athrow
_L3:
if(obj instanceof kotlin.Result.Failure)
//* 10 42:aload_1
//* 11 43:instanceof #107 <Class kotlin.Result$Failure>
//* 12 46:ifne 52
//* 13 49:goto 101
{
Object obj1;
try
{
throw ((kotlin.Result.Failure)obj).exception;
// 14 52:aload_1
// 15 53:checkcast #107 <Class kotlin.Result$Failure>
// 16 56:getfield #111 <Field Throwable kotlin.Result$Failure.exception>
// 17 59:athrow
}
// Misplaced declaration of an exception variable
catch(Object obj)
//* 18 60:astore_1
//* 19 61:goto 121
//* 20 64:aload_1
//* 21 65:instanceof #107 <Class kotlin.Result$Failure>
//* 22 68:ifne 137
//* 23 71:aload_0
//* 24 72:getfield #71 <Field CoroutineScope p$>
//* 25 75:astore_1
//* 26 76:aload_0
//* 27 77:getfield #49 <Field CoroutineWorker this$0>
//* 28 80:astore_1
//* 29 81:aload_0
//* 30 82:iconst_1
//* 31 83:putfield #98 <Field int label>
//* 32 86:aload_1
//* 33 87:aload_0
//* 34 88:invokevirtual #115 <Method Object CoroutineWorker.doWork(Continuation)>
//* 35 91:astore_2
//* 36 92:aload_2
//* 37 93:astore_1
//* 38 94:aload_2
//* 39 95:aload_3
//* 40 96:if_acmpne 101
//* 41 99:aload_3
//* 42 100:areturn
//* 43 101:aload_1
//* 44 102:checkcast #117 <Class ListenableWorker$Result>
//* 45 105:astore_1
//* 46 106:aload_0
//* 47 107:getfield #49 <Field CoroutineWorker this$0>
//* 48 110:invokevirtual #121 <Method SettableFuture CoroutineWorker.getFuture$work_runtime_ktx_release()>
//* 49 113:aload_1
//* 50 114:invokevirtual #127 <Method boolean SettableFuture.set(Object)>
//* 51 117:pop
//* 52 118:goto 133
{
getFuture$work_runtime_ktx_release().setException(((Throwable) (obj)));
// 53 121:aload_0
// 54 122:getfield #49 <Field CoroutineWorker this$0>
// 55 125:invokevirtual #121 <Method SettableFuture CoroutineWorker.getFuture$work_runtime_ktx_release()>
// 56 128:aload_1
// 57 129:invokevirtual #131 <Method boolean SettableFuture.setException(Throwable)>
// 58 132:pop
}
break; /* Loop/switch isn't completed */
}
break MISSING_BLOCK_LABEL_101;
_L2:
if(obj instanceof kotlin.Result.Failure)
break MISSING_BLOCK_LABEL_137;
obj = ((Object) (p$));
obj = ((Object) (CoroutineWorker.this));
label = 1;
obj1 = ((CoroutineWorker) (obj)).doWork(((Continuation) (this)));
obj = obj1;
if(obj1 == obj2)
return obj2;
obj = ((Object) ((ListenableWorker.Result)obj));
getFuture$work_runtime_ktx_release().set(obj);
return ((Object) (Unit.INSTANCE));
// 59 133:getstatic #85 <Field Unit Unit.INSTANCE>
// 60 136:areturn
throw ((kotlin.Result.Failure)obj).exception;
// 61 137:aload_1
// 62 138:checkcast #107 <Class kotlin.Result$Failure>
// 63 141:getfield #111 <Field Throwable kotlin.Result$Failure.exception>
// 64 144:athrow
}
int label;
private CoroutineScope p$;
final CoroutineWorker this$0;
CoroutineWorker$startWork$1(CoroutineWorker coroutineworker, Continuation continuation)
{
this$0 = coroutineworker;
// 0 0:aload_0
// 1 1:aload_1
// 2 2:putfield #49 <Field CoroutineWorker this$0>
super(2, continuation);
// 3 5:aload_0
// 4 6:iconst_2
// 5 7:aload_2
// 6 8:invokespecial #52 <Method void SuspendLambda(int, Continuation)>
// 7 11:return
}
}
| 38.829787
| 114
| 0.592055
|
f426db29ad9e253aa301c5e7e379c28bb6a85c8a
| 3,884
|
package com.rzspider.project.blog.blognotice.controller;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.rzspider.project.blog.blognotice.domain.Blognotice;
import com.rzspider.project.blog.blognotice.service.IBlognoticeService;
import com.rzspider.project.system.role.service.IRoleService;
import com.rzspider.common.constant.UserConstants;
import com.rzspider.common.utils.OtherUtils;
import com.rzspider.common.utils.security.ShiroUtils;
import com.rzspider.framework.web.controller.BaseController;
import com.rzspider.framework.web.page.TableDataInfo;
import com.rzspider.framework.web.domain.Message;
/**
* 博客公告 信息操作处理
*
* @author ricozhou
* @date 2018-10-23
*/
@Controller
@RequestMapping("/blog/blognotice")
public class BlognoticeController extends BaseController {
private String prefix = "blog/blognotice";
@Autowired
private IBlognoticeService blognoticeService;
@Autowired
private IRoleService roleService;
@GetMapping()
@RequiresPermissions("blog:blognotice:view")
public String blognotice() {
return prefix + "/blognotice";
}
/**
* 查询博客公告列表
*/
@RequiresPermissions("blog:blognotice:list")
@GetMapping("/list")
@ResponseBody
public TableDataInfo list(Blognotice blognotice) {
startPage();
List<Blognotice> list = blognoticeService.selectBlognoticeList(blognotice);
return getDataTable(list);
}
/**
* 新增博客公告
*/
@RequiresPermissions("blog:blognotice:add")
@GetMapping("/add")
public String add() {
return prefix + "/add";
}
/**
* 修改博客公告
*/
@RequiresPermissions("blog:blognotice:edit")
@GetMapping("/edit/{blogNoticeId}")
public String edit(@PathVariable("blogNoticeId") Integer blogNoticeId, Model model) {
Blognotice blognotice = blognoticeService.selectBlognoticeById(blogNoticeId);
model.addAttribute("blognotice", blognotice);
return prefix + "/edit";
}
/**
* 保存博客公告
*/
@RequiresPermissions("blog:blognotice:save")
@PostMapping("/save")
@ResponseBody
public Message save(Blognotice blognotice) {
// 测试管理员禁用
if (OtherUtils.isTestManager(roleService.selectRoleKeys(ShiroUtils.getUserId()))) {
return Message.error(UserConstants.USER_MESSAGE_TEATADMIN_DISABLED_USE);
}
if (blognoticeService.saveBlognotice(blognotice) > 0) {
return Message.success();
}
return Message.error();
}
/**
* 删除博客公告
*/
@RequiresPermissions("blog:blognotice:remove")
@PostMapping("/remove/{blogNoticeId}")
@ResponseBody
public Message remove(@PathVariable("blogNoticeId") Integer blogNoticeId) {
// 测试管理员禁用
if (OtherUtils.isTestManager(roleService.selectRoleKeys(ShiroUtils.getUserId()))) {
return Message.error(UserConstants.USER_MESSAGE_TEATADMIN_DISABLED_USE);
}
if (blognoticeService.deleteBlognoticeById(blogNoticeId) > 0) {
return Message.success();
}
return Message.error();
}
/**
* 批量删除博客公告
*/
@RequiresPermissions("blog:blognotice:batchRemove")
@PostMapping("/batchRemove")
@ResponseBody
public Message remove(@RequestParam("ids[]") Integer[] blogNoticeIds) {
// 测试管理员禁用
if (OtherUtils.isTestManager(roleService.selectRoleKeys(ShiroUtils.getUserId()))) {
return Message.error(UserConstants.USER_MESSAGE_TEATADMIN_DISABLED_USE);
}
int rows = blognoticeService.batchDeleteBlognotice(blogNoticeIds);
if (rows > 0) {
return Message.success();
}
return Message.error();
}
}
| 29.648855
| 86
| 0.771885
|
3a30b0fe9457edb38d943ecc2205ebb24186b4f7
| 3,020
|
/**
* Copyright (c) 2012, Ben Fortuna
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* o Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* o Neither the name of Ben Fortuna nor the names of any other contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.fortuna.ical4j.connector.dav.method;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.xml.DomUtil;
import org.apache.jackrabbit.webdav.xml.Namespace;
import org.apache.jackrabbit.webdav.xml.XmlSerializable;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
public class PrincipalPropertySearchInfo implements XmlSerializable {
protected Element originalElement;
protected int depth;
public PrincipalPropertySearchInfo(Element reportElement, int depth) throws DavException {
this.originalElement = reportElement;
this.depth = depth;
}
public Element toXml(Document document) {
String typeLocalName = originalElement.getLocalName();
Namespace typeNamespace = DomUtil.getNamespace(originalElement);
Element reportElement = DomUtil.createElement(document, typeLocalName, typeNamespace);
reportElement.setAttribute("type", originalElement.getAttribute("type"));
reportElement.setAttribute("test", originalElement.getAttribute("test"));
for (int nodeNumber = 0; nodeNumber < originalElement.getChildNodes().getLength(); nodeNumber++) {
Node node = document.importNode(originalElement.getChildNodes().item(nodeNumber), true);
reportElement.appendChild(node);
}
return reportElement;
}
public int getDepth() {
return depth;
}
}
| 43.142857
| 106
| 0.753311
|
fb3f0720a6f322ce6bbe3955e13b00fea9d4cf4c
| 502
|
package lib.ui;
import io.appium.java_client.AppiumDriver;
import org.openqa.selenium.By;
public class NavigationUI extends MainPageObject{
private static final String
MY_LISTS_LINK = "//android.widget.FrameLayout[@content-desc='My lists']";
public NavigationUI(AppiumDriver driver)
{
super(driver);
}
public void clickMyLists()
{
this.waitForElementAndClick(By.xpath(MY_LISTS_LINK),
"Cannot find navigation button to My Lists",
20
);
}
}
| 23.904762
| 77
| 0.695219
|
bf296442c460377b51742141a5131ac1907bcf75
| 2,203
|
import com.gembox.examples.Util;
import com.gembox.spreadsheet.*;
import java.time.LocalDateTime;
import java.util.Random;
class Program {
private static final String resourcesFolder = Util.resourcesFolder();
public static void main(String[] args) throws java.io.IOException {
// If using Professional version, put your serial key below.
SpreadsheetInfo.setLicense("FREE-LIMITED-KEY");
ExcelFile ef = ExcelFile.load(resourcesFolder + "Template.xlsx");
int workingDays = 8;
LocalDateTime startDate = LocalDateTime.now().plusDays(-workingDays);
LocalDateTime endDate = LocalDateTime.now();
ExcelWorksheet ws = ef.getWorksheet(0);
// Find cells with placeholder text and set their values.
RowColumn rowColumnPosition;
if ((rowColumnPosition = ws.getCells().findText("[Company Name]", true, true)) != null)
ws.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue("ACME Corp");
if ((rowColumnPosition = ws.getCells().findText("[Company Address]", true, true)) != null)
ws.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue("240 Old Country Road, Springfield, IL");
if ((rowColumnPosition = ws.getCells().findText("[Start Date]", true, true)) != null)
ws.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue(startDate);
if ((rowColumnPosition = ws.getCells().findText("[End Date]", true, true)) != null)
ws.getCell(rowColumnPosition.getRow(), rowColumnPosition.getColumn()).setValue(endDate);
// Copy template row.
int row = 17;
ws.getRows().insertCopy(row + 1, workingDays - 1, ws.getRow(row));
// Fill inserted rows with sample data.
Random random = new Random();
for (int i = 0; i < workingDays; i++) {
ExcelRow currentRow = ws.getRow(row + i);
currentRow.getCell(1).setValue(startDate.plusDays(i));
currentRow.getCell(2).setValue(random.nextInt(11) + 1);
}
// Calculate formulas in worksheet.
ws.calculate();
ef.save("Template Use.xlsx");
}
}
| 43.196078
| 132
| 0.654562
|
77e99d7c5b840473135dd9a29bcbee62e01ba39c
| 2,569
|
package com.android.wcf.helper.typeadapters;
import android.util.Log;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
public class DateStringLongConverter implements JsonDeserializer<Long>, JsonSerializer<Long> {
private static final String ISO_8601 = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
private static final String[] DATE_FORMATS = new String[]{
ISO_8601,
"yyyy-MM-dd'T'HH:mm:ssZ",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd",
"EEE MMM dd HH:mm:ss z yyyy",
"HH:mm:ss",
"MM/dd/yyyy HH:mm:ss aaa",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSS",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS",
"yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'",
"MMM d',' yyyy H:mm:ss a"
};
@Override
public Long deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context) throws JsonParseException {
for (String format : DATE_FORMATS) {
try {
String dateString = jsonElement.getAsString();
SimpleDateFormat formatter = new SimpleDateFormat(format);
//input date is UTC. If we do not set timeZone to UTC, SimpleDateFormat parser will treat the string to represent local time
formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
return formatter.parse(dateString).getTime();
} catch (ParseException e) {
Log.e("DateParser", "error: " + e.getMessage());
}
}
throw new JsonParseException("Unparserable date: \"" + jsonElement.getAsString()
+ "\". Supported formats: \n" + Arrays.toString(DATE_FORMATS));
}
@Override
public JsonElement serialize(Long src, Type typeOfSrc, JsonSerializationContext context) {
SimpleDateFormat formatter = new SimpleDateFormat(ISO_8601, Locale.US);
//input date is local, we want to convert it to UTC.
// If we do not set timeZone to UTC, SimpleDateFormat will format it as local time
return src == null ? null : new JsonPrimitive(formatter.format(src));
}
}
| 37.779412
| 140
| 0.658622
|
4b90071e6099e5e8003651ee2686c925a92c9396
| 2,135
|
package com.ysir.yutao.product.controller;
import java.util.Arrays;
import java.util.Map;
import com.ysir.yutao.common.utils.PageUtils;
import com.ysir.yutao.common.utils.ResponseResult;
import com.ysir.yutao.product.entity.SpuInfoDescEntity;
import com.ysir.yutao.product.service.SpuInfoDescService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* spu信息介绍
*
* @author leifengyang
* @email leifengyang@gmail.com
* @date 2019-10-01 22:50:32
*/
@RestController
@RequestMapping("product/spuinfodesc")
public class SpuInfoDescController {
@Autowired
private SpuInfoDescService spuInfoDescService;
/**
* 列表
*/
@RequestMapping("/list")
public ResponseResult list(@RequestParam Map<String, Object> params){
PageUtils page = spuInfoDescService.queryPage(params);
return ResponseResult.ok().put("page", page);
}
/**
* 信息
*/
@RequestMapping("/info/{spuId}")
public ResponseResult info(@PathVariable("spuId") Long spuId){
SpuInfoDescEntity spuInfoDesc = spuInfoDescService.getById(spuId);
return ResponseResult.ok().put("spuInfoDesc", spuInfoDesc);
}
/**
* 保存
*/
@RequestMapping("/save")
public ResponseResult save(@RequestBody SpuInfoDescEntity spuInfoDesc){
spuInfoDescService.save(spuInfoDesc);
return ResponseResult.ok();
}
/**
* 修改
*/
@RequestMapping("/update")
public ResponseResult update(@RequestBody SpuInfoDescEntity spuInfoDesc){
spuInfoDescService.updateById(spuInfoDesc);
return ResponseResult.ok();
}
/**
* 删除
*/
@RequestMapping("/delete")
public ResponseResult delete(@RequestBody Long[] spuIds){
spuInfoDescService.removeByIds(Arrays.asList(spuIds));
return ResponseResult.ok();
}
}
| 25.117647
| 77
| 0.717096
|
c59f1c95576b5b818a663813217beacf67c75f6e
| 76
|
package model.commands.OtherCommands;
public class MakeUserInstruction {
}
| 15.2
| 37
| 0.828947
|
062417a33fd0abcab1440ea194d2a6f8b28e33c8
| 5,538
|
package schach.gui.menu;
import java.util.Optional;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.geometry.VPos;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.effect.ColorAdjust;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.RowConstraints;
import javafx.scene.text.Font;
import schach.common.Color;
import schach.gui.ImageHandler;
import schach.gui.settings.SwitchButton;
/**
* The MainMenuView class gets displayed when the user needs to see the main
* menu, it extends the borderPane
*
*/
public class MainMenuView extends BorderPane {
private ImageView imagePvAI = new ImageView();
private ImageView imagePvP = new ImageView();
private ImageView settingsButton = new ImageView();
private SwitchButton aiColorWhite = new SwitchButton();
private GridPane chooseGameMode = new GridPane();
private Slider aiStrength = new Slider(1, 10, 4);
private double windowSizeY;
private String style = "-fx-background:#3b3c3d;";
/**
* Constructor for the main menu view, initializes the view
*
* @param windowSizeY the windowSize of the scene needed for calculating the
* sizes of the buttons
*/
public MainMenuView(double windowSizeY) {
this.setStyle(style);
this.windowSizeY = windowSizeY;
setUpSettingsButton();
setUpChooseGameMode();
setTop(settingsButton);
setCenter(chooseGameMode);
setAlignment(chooseGameMode, Pos.CENTER);
}
public ImageView getImagePvAi() {
return imagePvAI;
}
public ImageView getSettingsButton() {
return settingsButton;
}
public ImageView getImagePvP() {
return imagePvP;
}
public SwitchButton getAiColorWhite() {
return aiColorWhite;
}
public Slider getAiStrength() {
return aiStrength;
}
/**
* Sets up the size and color of the settings button
*/
public void setUpSettingsButton() {
ColorAdjust adjust = new ColorAdjust();
adjust.setBrightness(-1);
settingsButton.setEffect(adjust);
settingsButton.setImage(ImageHandler.getIconImage(ImageHandler.Icon.SETTINGS));
settingsButton.setPickOnBounds(true);
settingsButton.setId("HomeButton");
settingsButton.setFitHeight(windowSizeY / 12);
settingsButton.setFitWidth(windowSizeY / 12);
setAlignment(settingsButton, Pos.TOP_RIGHT);
}
/**
* Sets up the two images that give the player the choice between playing
* against a computer or another human
*/
public void setUpChooseGameMode() {
RowConstraints row0 = new RowConstraints();
row0.setMinHeight(30);
chooseGameMode.getRowConstraints().add(row0);
ColorAdjust adjust = new ColorAdjust();
adjust.setBrightness(-1);
imagePvAI.setEffect(adjust);
imagePvP.setEffect(adjust);
imagePvAI.setImage(ImageHandler.getIconImage(ImageHandler.Icon.COMPUTER));
imagePvP.setImage(ImageHandler.getIconImage(ImageHandler.Icon.PLAYER));
imagePvAI.setPickOnBounds(true);
imagePvP.setPickOnBounds(true);
imagePvAI.setFitHeight(windowSizeY / 2.5);
imagePvAI.setFitWidth(windowSizeY / 2.5);
imagePvP.setFitHeight(windowSizeY / 2.5);
imagePvP.setFitWidth(windowSizeY / 2.5);
GridPane.setConstraints(imagePvP, 0, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
chooseGameMode.add(imagePvP, 0, 1);
GridPane.setConstraints(imagePvAI, 1, 0, 1, 1, HPos.CENTER, VPos.CENTER, Priority.ALWAYS, Priority.ALWAYS);
chooseGameMode.add(imagePvAI, 1, 1);
setUpAiStrength();
}
/**
* Gets called from the MainMenuController to prompt the user with choice
* between playing white or black against the computer
*
* @return Chosen color
*/
public Color playerColorPopUp() {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Choose Color");
alert.setHeaderText("With which color would you like to play?");
ButtonType buttonWhite = new ButtonType("White");
ButtonType buttonBlack = new ButtonType("Black");
ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonWhite, buttonBlack, buttonTypeCancel);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonWhite) {
return Color.WHITE;
} else if (result.get() == buttonBlack) {
return Color.BLACK;
} else {
return null;
}
}
/**
* Sets up the slider to determine the strength of the Ai
*/
private void setUpAiStrength() {
Label aiStrengthLabel = new Label("Ai Strength: ");
aiStrengthLabel.setFont(new Font("Arial", 20));
GridPane.setConstraints(aiStrengthLabel, 1, 1, 1, 1, HPos.CENTER, VPos.TOP, Priority.ALWAYS, Priority.SOMETIMES);
chooseGameMode.add(aiStrengthLabel, 1, 2);
aiStrength.setMajorTickUnit(1);
aiStrength.setMinorTickCount(0);
aiStrength.setShowTickLabels(true);
aiStrength.setShowTickMarks(true);
aiStrength.setSnapToTicks(true);
aiStrength.setMaxWidth(windowSizeY / 2);
GridPane.setConstraints(aiStrength, 1, 2, 1, 1, HPos.CENTER, VPos.TOP, Priority.ALWAYS, Priority.ALWAYS,
new Insets(10));
chooseGameMode.add(aiStrength, 1, 3);
}
}
| 33.768293
| 117
| 0.729144
|
99849e5655e30f72d8af680c373fcdf6487636fb
| 1,582
|
package udesk.udeskasr.activity;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import udesk.udeskasr.R;
public class UdeskEditActivity extends Activity {
private EditText asrText;
private String intentText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_udesk_edit);
initView();
initIntent();
}
private void initIntent() {
try {
Intent intent=getIntent();
if (intent!=null){
intentText = intent.getStringExtra(UdeskConstant.UDESK_ASR_TEXT);
asrText.setText(intentText);
asrText.setSelection(intentText.length());
}
}catch (Exception e){
e.printStackTrace();
}
}
private void initView() {
findViewById(R.id.udesk_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra(UdeskConstant.UDESK_EDIT_TEXT,asrText.getText().toString());
setResult(RESULT_OK,intent);
finish();
}
});
asrText = findViewById(R.id.udesk_edit);
}
}
| 28.763636
| 92
| 0.641593
|
b2763e1b3cf00a4273d7659bfe8f26b2c330b895
| 2,302
|
package com.rvandoosselaer.blocks;
import com.rvandoosselaer.blocks.serialize.BlockDefinition;
import com.rvandoosselaer.blocks.serialize.BlockFactory;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @author: rvandoosselaer
*/
public class BlockFactoryTest {
@Test
public void testBlockCreation() {
BlockDefinition definition = new BlockDefinition(TypeIds.GRASS, false, true, true)
.addShape(ShapeIds.CUBE)
.addShape(ShapeIds.CUBE_DOWN)
.addShapes(ShapeIds.CUBE_NORTH, ShapeIds.CUBE_EAST, ShapeIds.CUBE_SOUTH, ShapeIds.CUBE_WEST);
Collection<Block> blocks = BlockFactory.create(definition);
assertEquals(6, blocks.size());
}
@Test
public void testBlockCreationFromCollection() {
BlockDefinition cubeDefinition = new BlockDefinition(TypeIds.GRASS, false, true, true)
.addShapes(ShapeIds.CUBE, ShapeIds.CUBE_DOWN, ShapeIds.CUBE_NORTH, ShapeIds.CUBE_EAST, ShapeIds.CUBE_SOUTH, ShapeIds.CUBE_WEST);
BlockDefinition pyramidDefinition = new BlockDefinition(TypeIds.BIRCH_LOG, true, false, true)
.addShapes(ShapeIds.PYRAMID, ShapeIds.PYRAMID_DOWN, ShapeIds.PYRAMID_NORTH, ShapeIds.PYRAMID_EAST, ShapeIds.PYRAMID_SOUTH, ShapeIds.PYRAMID_WEST);
List<BlockDefinition> definitions = new ArrayList<>();
definitions.add(cubeDefinition);
definitions.add(pyramidDefinition);
Collection<Block> blocks = BlockFactory.create(definitions);
assertEquals(12, blocks.size());
}
@Test
public void testBlockCreationFromFile() {
Collection<Block> blocks = BlockFactory.create(BlockFactoryTest.class.getResourceAsStream("/blockDefinitions.yml"));
assertEquals(8, blocks.size());
}
@Test
public void testDoNotProcessNullShape() {
BlockDefinition blockDefinition = new BlockDefinition(TypeIds.BIRCH_PLANKS, true, false, false)
.addShape(null);
assertEquals(0, BlockFactory.create(blockDefinition).size());
blockDefinition.addShapes(null);
assertEquals(0, BlockFactory.create(blockDefinition).size());
}
}
| 35.415385
| 162
| 0.714596
|
b2542f32b30243f31b4788dafb28a4580ba2a07a
| 315
|
package com.andronov.subsystems;
import com.andronov.Customer;
import javax.ejb.Stateless;
@Stateless
public class CreditRatingService {
public boolean checkCustomerRating(Customer customer) {
Integer rating = 900; // Connect to external credit reference agency
return rating > 700;
}
}
| 21
| 76
| 0.736508
|
83ad3ade1f831af5a2381aaceaee66bb50920cc6
| 2,258
|
package io.vandam.dbdeploy.sql.db2_400.sql_generation;
import io.vandam.dbdeploy.databasestructure.Database;
import io.vandam.dbdeploy.databasestructure.Index;
import io.vandam.dbdeploy.databasestructure.Table;
import java.util.ArrayList;
import java.util.Collection;
import static io.vandam.dbdeploy.sql.db2_400.sql_generation.SqlIndex.getIndex;
class SqlIndexDiff {
static Collection<String> diffIndex(final Database source, final Database target) {
final Collection<String> response = new ArrayList<>();
// index changes
for (int i = 0; i < source.getTables().size(); i++) {
final Table sourceTable = source.getTables().get(i);
final Table targetTable = target.getTable(sourceTable.getSystemName());
if (null == targetTable) {
response.addAll(SqlIndex.getIndex(sourceTable.getName(), sourceTable.getIndexes()));
} else if (!sourceTable.getIndexes().isEmpty()) {
if (targetTable.getIndexes().isEmpty()) {
response.addAll(SqlIndex.getIndex(sourceTable.getName(), sourceTable.getIndexes()));
} else if (!sourceTable.getIndexes().equals(targetTable.getIndexes())) {
for (final Index index : targetTable.getIndexes()) {
response.add("DROP INDEX " + index.getName());
}
for (final Index index : sourceTable.getIndexes()) {
response.addAll(SqlIndex.getIndex(sourceTable.getName(), index));
}
}
}
}
for (int i = 0; i < target.getTables().size(); i++) {
final Table targetTable = target.getTables().get(i);
final Table sourceTable = source.getTable(targetTable.getSystemName());
if (null != sourceTable) {
if (!targetTable.getIndexes().isEmpty()) {
if (sourceTable.getIndexes().isEmpty()) {
for (final Index index : targetTable.getIndexes()) {
response.add("DROP INDEX " + index.getName());
}
}
}
}
}
return response;
}
}
| 40.321429
| 104
| 0.571302
|
4e904212521ff0962eacb5961c7fb0c8bc6f8bfd
| 2,415
|
package fr.noalegeek.pepite_dor_bot.commands;
import com.jagrosh.jdautilities.command.Command;
import com.jagrosh.jdautilities.command.CommandEvent;
import fr.noalegeek.pepite_dor_bot.enums.CommandCategories;
import fr.noalegeek.pepite_dor_bot.utils.helpers.MessageHelper;
import java.util.Locale;
public class InviteCommand extends Command {
public InviteCommand() {
this.name = "invite";
this.aliases = new String[]{"inv", "i"};
this.guildOnly = true;
this.cooldown = 10;
this.arguments = "<create/bot>";
this.help = "Crée une invitation du serveur.";
this.category = CommandCategories.MISC.category;
}
@Override
protected void execute(CommandEvent event) {
String[] args = event.getArgs().split("\\s+");
if(event.getArgs().length() == 0) {
event.replyError(MessageHelper.syntaxError(event, this)+"Les arguments disponibles sont **create** et **bot**.\n" +
"L'argument **create** crée un lien d'invitation du serveur où a été fait la commande.\n" +
"L'argument **bot** envoie le lien d'invitation du bot pour l'inviter sur n'importe quel serveur.");
return;
}
switch (args[0].toLowerCase(Locale.ROOT)) {
case "create":
event.replySuccess(MessageHelper.formattedMention(event.getAuthor()) + "Voici ton lien d'invitation du serveur " + event.getGuild().getName() +
", n'hésite pas à faire venir plein de personnes !\n" + event.getTextChannel().createInvite().complete().getUrl());
break;
case "bot":
String discordInviteURL = "https://discord.com/oauth2/authorize?client_id=%s&scope=bot&permissions=8589934591";
event.replySuccess("Voici le lien d'invitation pour inviter le bot sur ton serveur !\n"+String.format(discordInviteURL, event.getJDA().getSelfUser().getId()));
break;
default:
event.replyError(MessageHelper.syntaxError(event, this)+"Les arguments disponibles sont **create** et **bot**.\n" +
"L'argument **create** crée un lien d'invitation du serveur où a été fait la commande.\n" +
"L'argument **bot** envoie le lien d'invitation du bot pour l'inviter sur n'importe quel serveur.");
break;
}
}
}
| 50.3125
| 175
| 0.627743
|
6782590c9e8b77c9155b68ec9e84f037e3b5a496
| 2,629
|
package net.minecraft.block;
import java.util.Random;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectInstance;
import net.minecraft.potion.Effects;
import net.minecraft.util.DamageSource;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.shapes.ISelectionContext;
import net.minecraft.util.math.shapes.VoxelShape;
import net.minecraft.world.Difficulty;
import net.minecraft.world.IBlockReader;
import net.minecraft.world.World;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public class WitherRoseBlock extends FlowerBlock {
public WitherRoseBlock(Effect effectIn, Block.Properties propertiesIn) {
super(effectIn, 8, propertiesIn);
}
protected boolean isValidGround(BlockState state, IBlockReader worldIn, BlockPos pos) {
Block block = state.getBlock();
return super.isValidGround(state, worldIn, pos) || block == Blocks.NETHERRACK || block == Blocks.SOUL_SAND;
}
/**
* Called periodically clientside on blocks near the player to show effects (like furnace fire particles). Note that
* this method is unrelated to {@link randomTick} and {@link #needsRandomTick}, and will always be called regardless
* of whether the block can receive random update ticks
*/
@OnlyIn(Dist.CLIENT)
public void animateTick(BlockState stateIn, World worldIn, BlockPos pos, Random rand) {
VoxelShape voxelshape = this.getShape(stateIn, worldIn, pos, ISelectionContext.dummy());
Vec3d vec3d = voxelshape.getBoundingBox().getCenter();
double d0 = (double)pos.getX() + vec3d.x;
double d1 = (double)pos.getZ() + vec3d.z;
for(int i = 0; i < 3; ++i) {
if (rand.nextBoolean()) {
worldIn.addParticle(ParticleTypes.SMOKE, d0 + (double)(rand.nextFloat() / 5.0F), (double)pos.getY() + (0.5D - (double)rand.nextFloat()), d1 + (double)(rand.nextFloat() / 5.0F), 0.0D, 0.0D, 0.0D);
}
}
}
public void onEntityCollision(BlockState state, World worldIn, BlockPos pos, Entity entityIn) {
if (!worldIn.isRemote && worldIn.getDifficulty() != Difficulty.PEACEFUL) {
if (entityIn instanceof LivingEntity) {
LivingEntity livingentity = (LivingEntity)entityIn;
if (!livingentity.isInvulnerableTo(DamageSource.WITHER)) {
livingentity.addPotionEffect(new EffectInstance(Effects.WITHER, 40));
}
}
}
}
}
| 42.403226
| 207
| 0.715862
|
99238c0d3212f5732aa0794ea680aa98f1a9a0af
| 5,333
|
/*
* Copyright 2020 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.trusty.service;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import org.eclipse.microprofile.config.inject.ConfigProperty;
import org.kie.kogito.explainability.api.ExplainabilityRequestDto;
import org.kie.kogito.persistence.api.Storage;
import org.kie.kogito.persistence.api.query.AttributeFilter;
import org.kie.kogito.persistence.api.query.QueryFilterFactory;
import org.kie.kogito.trusty.service.messaging.incoming.ModelIdCreator;
import org.kie.kogito.trusty.service.messaging.outgoing.ExplainabilityRequestProducer;
import org.kie.kogito.trusty.storage.api.TrustyStorageService;
import org.kie.kogito.trusty.storage.api.model.Decision;
import org.kie.kogito.trusty.storage.api.model.Execution;
import org.kie.kogito.trusty.storage.api.model.ExplainabilityResult;
@ApplicationScoped
public class TrustyServiceImpl implements TrustyService {
@ConfigProperty(name = "trusty.explainability.enabled")
Boolean isExplainabilityEnabled;
@Inject
ExplainabilityRequestProducer explainabilityRequestProducer;
@Inject
TrustyStorageService storageService;
TrustyServiceImpl() {
// dummy constructor needed
}
public TrustyServiceImpl(TrustyStorageService storageService) {
this.storageService = storageService;
}
@Override
public List<Execution> getExecutionHeaders(OffsetDateTime from, OffsetDateTime to, int limit, int offset, String prefix) {
Storage<String, Decision> storage = storageService.getDecisionsStorage();
List<AttributeFilter<?>> filters = new ArrayList<>();
filters.add(QueryFilterFactory.like(Execution.EXECUTION_ID_FIELD, prefix + "*"));
filters.add(QueryFilterFactory.greaterThanEqual(Execution.EXECUTION_TIMESTAMP_FIELD, from.toInstant().toEpochMilli()));
filters.add(QueryFilterFactory.lessThanEqual(Execution.EXECUTION_TIMESTAMP_FIELD, to.toInstant().toEpochMilli()));
return new ArrayList<>(storage.query().limit(limit).offset(offset).filter(filters).execute());
}
@Override
public Decision getDecisionById(String executionId) {
Storage<String, Decision> storage = storageService.getDecisionsStorage();
if (!storage.containsKey(executionId)) {
throw new IllegalArgumentException(String.format("A decision with ID %s does not exist in the storage.", executionId));
}
return storage.get(executionId);
}
@Override
public void storeDecision(String executionId, Decision decision) {
Storage<String, Decision> storage = storageService.getDecisionsStorage();
if (storage.containsKey(executionId)) {
throw new IllegalArgumentException(String.format("A decision with ID %s is already present in the storage.", executionId));
}
storage.put(executionId, decision);
}
@Override
public void updateDecision(String executionId, Decision decision) {
storageService.getDecisionsStorage().put(executionId, decision);
}
@Override
public void processDecision(String executionId, Decision decision) {
storeDecision(executionId, decision);
// TODO: Create a proper ExplainabilityRequestDto when all the properties will be defined and available. https://issues.redhat.com/browse/KOGITO-2944
if (Boolean.TRUE.equals(isExplainabilityEnabled)) {
explainabilityRequestProducer.sendEvent(new ExplainabilityRequestDto(executionId));
}
}
@Override
public void storeExplainability(String executionId, ExplainabilityResult result) {
// TODO: Store it https://issues.redhat.com/browse/KOGITO-2945
}
@Override
public void storeModel(String groupId, String artifactId, String version, String name, String namespace, String definition) {
final String identifier = ModelIdCreator.makeIdentifier(groupId, artifactId, version, name, namespace);
final Storage<String, String> storage = storageService.getModelStorage();
if (storage.containsKey(identifier)) {
throw new IllegalArgumentException(String.format("A model with ID %s is already present in the storage.", identifier));
}
storage.put(identifier, definition);
}
@Override
public String getModelById(String modelId) {
final Storage<String, String> storage = storageService.getModelStorage();
if (!storage.containsKey(modelId)) {
throw new IllegalArgumentException(String.format("A model with ID %s does not exist in the storage.", modelId));
}
return storage.get(modelId);
}
}
| 43.008065
| 157
| 0.739546
|
c8385b59f59644b79ede540eecc5794581d27a2a
| 6,085
|
package io.openems.edge.meter.virtual.symmetric.add;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.osgi.service.component.ComponentContext;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Deactivate;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventConstants;
import org.osgi.service.event.EventHandler;
import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.openems.common.channel.AccessMode;
import io.openems.common.exceptions.OpenemsError.OpenemsNamedException;
import io.openems.edge.common.channel.calculate.CalculateAverage;
import io.openems.edge.common.channel.calculate.CalculateIntegerSum;
import io.openems.edge.common.channel.calculate.CalculateLongSum;
import io.openems.edge.common.component.AbstractOpenemsComponent;
import io.openems.edge.common.component.ComponentManager;
import io.openems.edge.common.component.OpenemsComponent;
import io.openems.edge.common.event.EdgeEventConstants;
import io.openems.edge.common.modbusslave.ModbusSlave;
import io.openems.edge.common.modbusslave.ModbusSlaveTable;
import io.openems.edge.meter.api.MeterType;
import io.openems.edge.meter.api.SymmetricMeter;
import io.openems.edge.meter.api.VirtualMeter;
@Designate(ocd = Config.class, factory = true)
@Component(name = "Meter.Virtual.Symmetric.Add", //
immediate = true, //
configurationPolicy = ConfigurationPolicy.REQUIRE, //
property = EventConstants.EVENT_TOPIC + "=" + EdgeEventConstants.TOPIC_CYCLE_BEFORE_PROCESS_IMAGE//
) //
public class VirtualAdd extends AbstractOpenemsComponent
implements VirtualMeter, SymmetricMeter, OpenemsComponent, EventHandler, ModbusSlave {
private final Logger log = LoggerFactory.getLogger(VirtualAdd.class);
private MeterType meterType = MeterType.PRODUCTION;
@Reference
protected ComponentManager componentManager;
private Config config;
@Reference(policy = ReferencePolicy.DYNAMIC, policyOption = ReferencePolicyOption.GREEDY, cardinality = ReferenceCardinality.MULTIPLE)
private volatile List<SymmetricMeter> symmetricMeter = new CopyOnWriteArrayList<>();
public VirtualAdd() {
super(//
OpenemsComponent.ChannelId.values(), //
SymmetricMeter.ChannelId.values() //
);
}
@Activate
void activate(ComponentContext context, Config config) throws OpenemsNamedException {
super.activate(context, config.id(), config.alias(), config.enabled());
this.config = config;
this.meterType = config.type();
}
@Deactivate
protected void deactivate() {
super.deactivate();
}
@Override
public void handleEvent(Event event) {
if (!this.isEnabled()) {
return;
}
switch (event.getTopic()) {
case EdgeEventConstants.TOPIC_CYCLE_BEFORE_PROCESS_IMAGE:
this.calculateChannelValues();
}
}
private void calculateChannelValues() {
// Find all configured SymmetricMeters
List<SymmetricMeter> meters = new ArrayList<SymmetricMeter>();
try {
for (String meterId : this.config.meterIds()) {
SymmetricMeter mts = this.componentManager.getComponent(meterId);
meters.add(mts);
}
} catch (Exception e) {
this.logError(this.log, e.getClass().getSimpleName() + ": " + e.getMessage());
}
final CalculateAverage meterFrequency = new CalculateAverage();
final CalculateIntegerSum meterMinActivePower = new CalculateIntegerSum();
final CalculateIntegerSum meterMaxActivePower = new CalculateIntegerSum();
final CalculateIntegerSum meterActivePower = new CalculateIntegerSum();
final CalculateIntegerSum meterReactivePower = new CalculateIntegerSum();
final CalculateLongSum meterActiveProductionEnergy = new CalculateLongSum();
final CalculateLongSum meterActiveConsumptionEnergy = new CalculateLongSum();
final CalculateAverage meterVoltage = new CalculateAverage();
final CalculateIntegerSum meterCurrent = new CalculateIntegerSum();
for (SymmetricMeter meter : meters) {
meterFrequency.addValue(meter.getFrequency());
meterMinActivePower.addValue(meter.getMinActivePower());
meterMaxActivePower.addValue(meter.getMaxActivePower());
meterActivePower.addValue(meter.getActivePower());
meterReactivePower.addValue(meter.getReactivePower());
meterActiveConsumptionEnergy.addValue(getActiveConsumptionEnergy());
meterActiveProductionEnergy.addValue(meter.getActiveProductionEnergy());
meterVoltage.addValue(meter.getVoltage());
meterCurrent.addValue(meter.getCurrent());
}
this.getFrequency().setNextValue(meterFrequency.calculate());
this.getMinActivePower().setNextValue(meterMinActivePower.calculate());
this.getMaxActivePower().setNextValue(meterMaxActivePower.calculate());
this.getActivePower().setNextValue(meterActivePower.calculate());
this.getReactivePower().setNextValue(meterReactivePower.calculate());
this.getActiveConsumptionEnergy().setNextValue(meterActiveConsumptionEnergy.calculate());
this.getActiveProductionEnergy().setNextValue(meterActiveProductionEnergy.calculate());
this.getVoltage().setNextValue(meterVoltage.calculate());
this.getCurrent().setNextValue(meterCurrent.calculate());
}
@Override
public MeterType getMeterType() {
return this.meterType;
}
@Override
public String debugLog() {
return "L:" + this.getActivePower().value().asString();
}
@Override
public boolean addToSum() {
return this.config.addToSum();
}
@Override
public ModbusSlaveTable getModbusSlaveTable(AccessMode accessMode) {
return new ModbusSlaveTable( //
OpenemsComponent.getModbusSlaveNatureTable(accessMode), //
SymmetricMeter.getModbusSlaveNatureTable(accessMode) //
);
}
}
| 38.757962
| 135
| 0.798192
|
b11afb2ce8939fd9b83d1fc8dca9e652cb700c9e
| 5,928
|
/*
* This file is generated by jOOQ.
*/
package org.blackdread.sqltojava.jooq.tables;
import javax.annotation.Generated;
import org.blackdread.sqltojava.jooq.InformationSchema;
import org.blackdread.sqltojava.jooq.tables.records.InnodbTablesRecord;
import org.jooq.Field;
import org.jooq.ForeignKey;
import org.jooq.Name;
import org.jooq.Record;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.impl.DSL;
import org.jooq.impl.TableImpl;
import org.jooq.types.UInteger;
import org.jooq.types.ULong;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.11.11"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class InnodbTables extends TableImpl<InnodbTablesRecord> {
private static final long serialVersionUID = 1686197983;
/**
* The reference instance of <code>information_schema.INNODB_TABLES</code>
*/
public static final InnodbTables INNODB_TABLES = new InnodbTables();
/**
* The class holding records for this type
*/
@Override
public Class<InnodbTablesRecord> getRecordType() {
return InnodbTablesRecord.class;
}
/**
* The column <code>information_schema.INNODB_TABLES.TABLE_ID</code>.
*/
public final TableField<InnodbTablesRecord, ULong> TABLE_ID = createField("TABLE_ID", org.jooq.impl.SQLDataType.BIGINTUNSIGNED.nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.BIGINTUNSIGNED)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.NAME</code>.
*/
public final TableField<InnodbTablesRecord, String> NAME = createField("NAME", org.jooq.impl.SQLDataType.VARCHAR(218).nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.VARCHAR)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.FLAG</code>.
*/
public final TableField<InnodbTablesRecord, Integer> FLAG = createField("FLAG", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.INTEGER)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.N_COLS</code>.
*/
public final TableField<InnodbTablesRecord, Integer> N_COLS = createField("N_COLS", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.INTEGER)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.SPACE</code>.
*/
public final TableField<InnodbTablesRecord, Long> SPACE = createField("SPACE", org.jooq.impl.SQLDataType.BIGINT.nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.BIGINT)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.ROW_FORMAT</code>.
*/
public final TableField<InnodbTablesRecord, String> ROW_FORMAT = createField("ROW_FORMAT", org.jooq.impl.SQLDataType.VARCHAR(4).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.VARCHAR)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.ZIP_PAGE_SIZE</code>.
*/
public final TableField<InnodbTablesRecord, UInteger> ZIP_PAGE_SIZE = createField("ZIP_PAGE_SIZE", org.jooq.impl.SQLDataType.INTEGERUNSIGNED.nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.INTEGERUNSIGNED)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.SPACE_TYPE</code>.
*/
public final TableField<InnodbTablesRecord, String> SPACE_TYPE = createField("SPACE_TYPE", org.jooq.impl.SQLDataType.VARCHAR(3).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.VARCHAR)), this, "");
/**
* The column <code>information_schema.INNODB_TABLES.INSTANT_COLS</code>.
*/
public final TableField<InnodbTablesRecord, Integer> INSTANT_COLS = createField("INSTANT_COLS", org.jooq.impl.SQLDataType.INTEGER.nullable(false).defaultValue(org.jooq.impl.DSL.inline("", org.jooq.impl.SQLDataType.INTEGER)), this, "");
/**
* Create a <code>information_schema.INNODB_TABLES</code> table reference
*/
public InnodbTables() {
this(DSL.name("INNODB_TABLES"), null);
}
/**
* Create an aliased <code>information_schema.INNODB_TABLES</code> table reference
*/
public InnodbTables(String alias) {
this(DSL.name(alias), INNODB_TABLES);
}
/**
* Create an aliased <code>information_schema.INNODB_TABLES</code> table reference
*/
public InnodbTables(Name alias) {
this(alias, INNODB_TABLES);
}
private InnodbTables(Name alias, Table<InnodbTablesRecord> aliased) {
this(alias, aliased, null);
}
private InnodbTables(Name alias, Table<InnodbTablesRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""));
}
public <O extends Record> InnodbTables(Table<O> child, ForeignKey<O, InnodbTablesRecord> key) {
super(child, key, INNODB_TABLES);
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return InformationSchema.INFORMATION_SCHEMA;
}
/**
* {@inheritDoc}
*/
@Override
public InnodbTables as(String alias) {
return new InnodbTables(DSL.name(alias), this);
}
/**
* {@inheritDoc}
*/
@Override
public InnodbTables as(Name alias) {
return new InnodbTables(alias, this);
}
/**
* Rename this table
*/
@Override
public InnodbTables rename(String name) {
return new InnodbTables(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public InnodbTables rename(Name name) {
return new InnodbTables(name, null);
}
}
| 34.870588
| 258
| 0.691464
|
3bce675cd50c9e4c5c6de010a3a2e3d1e713b5ca
| 155
|
package br.com.megasena.co;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class CoIndex {
public String inicializa() {
return "";
}
}
| 10.333333
| 36
| 0.709677
|
9aee28231f0f71a402298b9a2d14510f170d0bef
| 1,626
|
package com.bytehonor.sdk.intent.human.model;
import java.util.HashSet;
import java.util.Set;
public class IntentRequest {
private long ts;
private String query;
private String uuid;
private String app;
private Set<String> words;
private IntentSession session;
public IntentRequest() {
this.ts = System.currentTimeMillis();
this.session = new IntentSession();
}
public static IntentRequest create(String query, String uuid, String app) {
IntentRequest request = new IntentRequest();
request.setQuery(query);
request.setUuid(uuid);
request.setApp(app);
request.setWords(new HashSet<String>());
request.getSession().setUuid(uuid);
request.getSession().setApp(app);
return request;
}
public long getTs() {
return ts;
}
public void setTs(long ts) {
this.ts = ts;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getQuery() {
return query;
}
public void setQuery(String query) {
this.query = query;
}
public Set<String> getWords() {
return words;
}
public void setWords(Set<String> words) {
this.words = words;
}
public IntentSession getSession() {
return session;
}
public void setSession(IntentSession session) {
this.session = session;
}
}
| 19.129412
| 79
| 0.597786
|
6670b27303b3a3e2a71136ac865144747a29293f
| 186
|
package com.base.lib.interfaces;
import android.content.res.Configuration;
public interface ConfigChangedListener {
public void onConfigurationChanged(Configuration newConfig);
}
| 20.666667
| 64
| 0.822581
|
15578cfb2c7a0241ca8a76d9c988e7d89d133bd2
| 1,003
|
package com.example.security;
import com.example.entity.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {
// 1.返回json数据
String result = new ObjectMapper().writeValueAsString(Result.error(401, "用户未认证!"));
// 2.处理编码方式,防止中文乱码的情况
httpServletResponse.setContentType("text/json;charset=utf-8");
// 3.使用HttpServletResponse中返回给前台
httpServletResponse.getWriter().write(result);
}
}
| 40.12
| 152
| 0.79661
|
cb5e351981cfa8990b77e48f07ecafaad2987299
| 841
|
package io.yooseongc.kma;
import org.gdal.gdal.Dataset;
import org.gdal.gdal.gdal;
public class GdalRegisterTest {
private static final String path = "C:/Users/user/data/";
public static void main(String[] args) {
gdal.AllRegister();
System.out.println(gdal.VersionInfo());
//Dataset data = gdal.Open(path + "g512_v070_ergl_pres_h000.2018060500.gb2");
Dataset data2 = gdal.Open(path + "g512_v070_ergl_unis_h000.2018060500.gb2");
String info = gdal.GDALInfo(data2, null);
System.out.println(info);
}
}
/*
* RUN ENV ...
*
* VM args : -Djava.library.path="C:\release-1911-x64-gdal-2-3-0-mapserver-7-0-7\bin\gdal\java;${env_var:PATH}"
*
* ENV :
* 1) PATH : C:\Program Files\GDAL
* 2) GDAL_DATA : C:\Program Files\GDAL\gdal-data
* 3) GDAL_DRIVER : C:\Program Files\GDAL\gdal\gdalplugins
*
*/
| 22.131579
| 111
| 0.678954
|
a670a0f111ee127379ee210dabef372dbfac9bbe
| 2,428
|
//Chapter6 - Exercise P6.2
//http://math.hws.edu/eck/cs124/javanotes4/c5/s3.html
public class Card
{
private String card1;
private String card2;
public Card (String letterCard1, String letterCard2)
{
card1 = letterCard1;
card2 = letterCard2;
}
public String getDescription1()
{
String c = " ";
if (card1.equalsIgnoreCase("A"))
c = "Ace";
else if (card1.equalsIgnoreCase("2"))
c = "Two";
else if (card1.equalsIgnoreCase("3"))
c = "Three";
else if (card1.equalsIgnoreCase("4"))
c = "Four";
else if (card1.equalsIgnoreCase("5"))
c = "Five";
else if (card1.equalsIgnoreCase("6"))
c = "Six";
else if (card1.equalsIgnoreCase("7"))
c = "Seven";
else if (card1.equalsIgnoreCase("8"))
c = "Eight";
else if (card1.equalsIgnoreCase("9"))
c = "Nine";
else if (card1.equalsIgnoreCase("10"))
c = "Ten";
else if (card1.equalsIgnoreCase("J"))
c = "Jack";
else if (card1.equalsIgnoreCase("Q"))
c = "Queen";
else if (card1.equalsIgnoreCase("K"))
c = "King";
else if (card1.equalsIgnoreCase("D"))
c = "Diamond";
else if (card1.equalsIgnoreCase("H"))
c = "Heart";
else if (card1.equalsIgnoreCase("S"))
c = "Spade";
else if (card1.equalsIgnoreCase("C"))
c = "Clubs";
else
{
System.out.println ("Invalid letter for card!");
}
return c;
}
public String getDescription2()
{
String c = " ";
if (card2.equalsIgnoreCase("A"))
c = "Ace";
else if (card2.equalsIgnoreCase("2"))
c = "Two";
else if (card2.equalsIgnoreCase("3"))
c = "Three";
else if (card2.equalsIgnoreCase("4"))
c = "Four";
else if (card2.equalsIgnoreCase("5"))
c = "Five";
else if (card2.equalsIgnoreCase("6"))
c = "Six";
else if (card2.equalsIgnoreCase("7"))
c = "Seven";
else if (card2.equalsIgnoreCase("8"))
c = "Eight";
else if (card2.equalsIgnoreCase("9"))
c = "Nine";
else if (card2.equalsIgnoreCase("10"))
c = "Ten";
else if (card2.equalsIgnoreCase("J"))
c = "Jack";
else if (card2.equalsIgnoreCase("Q"))
c = "Queen";
else if (card2.equalsIgnoreCase("K"))
c = "King";
else if (card2.equalsIgnoreCase("D"))
c = "Diamond";
else if (card2.equalsIgnoreCase("H"))
c = "Heart";
else if (card2.equalsIgnoreCase("S"))
c = "Spade";
else if (card2.equalsIgnoreCase("C"))
c = "Clubs";
else
{
System.out.println ("Invalid letter for card!");
}
return c;
}
public String toString()
{
return getDescription1() + " of " + getDescription2();
}
}
| 22.072727
| 58
| 0.631796
|
7f5ae8bb74e661fbfb06e3506e362157609cd017
| 1,992
|
package com.alibaba.csp.ahas.sentinel.cluster;
import java.util.List;
import com.alibaba.csp.ahas.sentinel.cluster.entity.ClusterGroupEntity;
import com.alibaba.csp.ahas.sentinel.util.MachineUtils;
import com.alibaba.csp.sentinel.cluster.server.config.ClusterServerConfigManager;
import com.alibaba.csp.sentinel.cluster.server.config.ServerFlowConfig;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.acm.DataAcmFormat;
import com.alibaba.csp.sentinel.log.RecordLog;
import com.taobao.csp.third.com.alibaba.fastjson.JSON;
import com.taobao.csp.third.com.alibaba.fastjson.TypeReference;
/**
* @author Eric Zhao
*/
public class ClusterServerFlowConfigParser implements Converter<String, ServerFlowConfig> {
@Override
public ServerFlowConfig convert(String source) {
if (source == null) {
return null;
}
String data = new DataAcmFormat(source).getData();
RecordLog.info("[ClusterServerFlowConfigParser] Get data: " + data);
List<ClusterGroupEntity> groupList = JSON.parseObject(data, new TypeReference<List<ClusterGroupEntity>>() {});
if (groupList == null || groupList.isEmpty()) {
return null;
}
return extractServerFlowConfig(groupList);
}
private ServerFlowConfig extractServerFlowConfig(List<ClusterGroupEntity> groupList) {
for (ClusterGroupEntity group : groupList) {
if (MachineUtils.isCurrentMachineEqual(group)) {
return new ServerFlowConfig()
.setExceedCount(ClusterServerConfigManager.getExceedCount())
.setIntervalMs(ClusterServerConfigManager.getIntervalMs())
.setMaxAllowedQps(group.getMaxAllowedQps())
.setMaxOccupyRatio(ClusterServerConfigManager.getMaxOccupyRatio())
.setSampleCount(ClusterServerConfigManager.getSampleCount());
}
}
return null;
}
}
| 41.5
| 118
| 0.705823
|
5748bd5a96bf62b77326b72f7d9ba77d742c4ff6
| 1,743
|
package heavenchess.ai;
import java.util.Iterator;
import heavenchess.movement.*;
import heavenchess.board.Chessboard;
import heavenchess.board.ChessboardState;
// todo: add the filter to exclude attackable moves
public class AllPossibleMoveProvider implements MoveProvider, Iterator<Move> {
private final MoveEnumerator enumerator;
private final Iterator<Point> pointsOfThisSide;
private Iterator<Move> validMoveIter;
private Move nextMove;
private Point currentPoint;
public AllPossibleMoveProvider(Chessboard chessboard, ChessboardState side) {
this.pointsOfThisSide = chessboard.getSlotsOfState(side).iterator();
this.enumerator = new MoveEnumerator(chessboard);
this.currentPoint = null;
}
public Move next() {
if (nextMove == null) {
throw new IllegalAccessError("Must make sure hasNext() returns true before calling next()");
}
Move ret = nextMove;
nextMove = null;
return ret;
}
public boolean hasNext() {
if (nextMove != null)
return true;
while (true) {
if (currentPoint == null) {
if (pointsOfThisSide.hasNext()) {
currentPoint = pointsOfThisSide.next();
} else {
return false;
}
}
if (validMoveIter == null) {
validMoveIter = enumerator.allValidMoves(currentPoint).iterator();
}
if (validMoveIter.hasNext()) {
nextMove = validMoveIter.next();
return true;
} else {
validMoveIter = null;
currentPoint = null;
}
}
}
}
| 30.578947
| 104
| 0.591509
|
4a02eff9411018a9680681b7fc18d4408711c4b2
| 2,701
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.stream.app.twitter.sentiment.processor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author Christian Tzolov
*/
public class WordVocabulary implements AutoCloseable {
/**
* This contains the word vocabulary used to train the TensorFlow model.
*/
private final ConcurrentHashMap<String, Integer> vocabulary;
public WordVocabulary(InputStream vocabularyInputStream) throws IOException {
vocabulary = buildVocabulary(vocabularyInputStream);
}
public int[][] vectorizeSentence(String sentence) {
int[][] vectorizedText = new int[1][128];
String[] words = clearText(sentence).split(" ");
for (int i = 0; i < words.length; i++) {
Integer v = vocabulary.get(words[i]);
vectorizedText[0][i] = (v != null)? v : 0;
}
return vectorizedText;
}
private ConcurrentHashMap<String, Integer> buildVocabulary(InputStream input) throws IOException {
ConcurrentHashMap<String, Integer> vocabulary = new ConcurrentHashMap<>();
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
String l = buffer.readLine();
while (l != null ) {
String p[] = l.split(",");
if (p[1].length() > 1) {
vocabulary.put(p[0], Integer.valueOf(p[1]));
}
l = buffer.readLine();
}
}
return vocabulary;
}
private String clearText(String sentence) {
return sentence
.trim()
.replaceAll("[^A-Za-z0-9(),!?\\'\\`]", " ")
.replaceAll("(.)\\1+", "\\1\\1")
.replaceAll("\\'s", " \\'s")
.replaceAll("\\'ve", " \\'ve")
.replaceAll("n\\'t", " n\\'t")
.replaceAll("\\'re", " \\'re")
.replaceAll("\\'d", " \\'d")
.replaceAll("\\'ll", " \\'ll")
.replaceAll(",", " , ")
.replaceAll("!", " ! ")
.replaceAll("\\(", " \\( ")
.replaceAll("\\)", " \\) ")
.replaceAll("\\?", " \\? ")
.replaceAll("\\s{2,}", " ")
.toLowerCase();
}
@Override
public void close() throws Exception {
vocabulary.clear();
}
}
| 29.043011
| 99
| 0.652351
|
8a58dc9ba343abf81a3fc2041f2690dbddff1888
| 4,200
|
package com.airbnb.epoxy;
import com.squareup.javapoet.ClassName;
import java.util.List;
import javax.lang.model.element.Element;
import javax.lang.model.element.PackageElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
class DataBindingModuleLookup {
private final Elements elements;
private final Types types;
private final ErrorLogger errorLogger;
private final ResourceProcessor resourceProcessor;
DataBindingModuleLookup(Elements elements, Types types, ErrorLogger errorLogger,
ResourceProcessor resourceProcessor) {
this.elements = elements;
this.types = types;
this.errorLogger = errorLogger;
this.resourceProcessor = resourceProcessor;
}
String getModuleName(Element element) {
PackageElement packageOf = elements.getPackageOf(element);
String packageName = packageOf.getQualifiedName().toString();
// First we try to get the module name by looking at what R classes were found when processing
// layout annotations. This may find nothing if no layouts were given as annotation params
String moduleName = getModuleNameViaResources(packageName);
if (moduleName == null) {
// If the first approach fails, we try to guess at the R class for the module and look up
// the class to see if it exists. This can fail if this model's package name does not
// include the module name as a prefix (convention makes this unlikely.)
moduleName = getModuleNameViaGuessing(packageName);
}
if (moduleName == null) {
errorLogger.logError("Could not find module name for DataBinding BR class.");
// Fallback to using the package name so we can at least try to generate and compile something
moduleName = packageName;
}
return moduleName;
}
/**
* Attempts to get the module name of the given package. We can do this because the package name
* of an R class is the module. Generally only one R class is used and we can just use that module
* name, but it is possible to have multiple R classes. In that case we compare the package names
* to find what is the most similar.
* <p>
* We need to get the module name to know the path of the BR class for data binding.
*/
private String getModuleNameViaResources(String packageName) {
List<ClassName> rClasses = resourceProcessor.getRClassNames();
if (rClasses.isEmpty()) {
return packageName;
}
if (rClasses.size() == 1) {
// Common case
return rClasses.get(0).packageName();
}
// Generally the only R class used should be the app's. It is possible to use other R classes
// though, like Android's. In that case we figure out the most likely match by comparing the
// package name.
// For example we might have "com.airbnb.epoxy.R" and "android.R"
String[] packageNames = packageName.split("\\.");
ClassName bestMatch = null;
int bestNumMatches = -1;
for (ClassName rClass : rClasses) {
String[] rModuleNames = rClass.packageName().split("\\.");
int numNameMatches = 0;
for (int i = 0; i < Math.min(packageNames.length, rModuleNames.length); i++) {
if (packageNames[i].equals(rModuleNames[i])) {
numNameMatches++;
} else {
break;
}
}
if (numNameMatches > bestNumMatches) {
bestMatch = rClass;
}
}
return bestMatch.packageName();
}
/**
* Attempts to get the android module that is currently being processed.. We can do this because
* the package name of an R class is the module name. So, we take any element in the module,
* <p>
* We need to get the module name to know the path of the BR class for data binding.
*/
private String getModuleNameViaGuessing(String packageName) {
String[] packageNameParts = packageName.split("\\.");
String moduleName = "";
for (int i = 0; i < packageNameParts.length; i++) {
moduleName += packageNameParts[i];
Element rClass = Utils.getElementByName(moduleName + ".R", elements, types);
if (rClass != null) {
return moduleName;
} else {
moduleName += ".";
}
}
return null;
}
}
| 34.146341
| 100
| 0.684048
|
721efe33772d4f3b46f1d4a85c6912bbdf42fd81
| 327
|
package com.wbm.plugin.util.data.json;
import java.io.Serializable;
public interface JsonDataMember extends Serializable {
// 데이터 주기: 각 메소드에서 Gson으로 String을 원하는 데이터 타입으로 변환시켜서 사용해야 함
public Object getData();
// 데이터 받아오기
public void distributeData(String jsonString);
// 확장자까지 .json 붙이기
public String getFileName();
}
| 21.8
| 60
| 0.75841
|
e3a155f3c82aad799a8633ee5cc7a0720b8a2563
| 3,090
|
package io.debezium.connector.postgresql.snapshot.partial.filters.handlers;
import io.debezium.connector.postgresql.snapshot.partial.filters.FilterHandler;
import io.debezium.connector.postgresql.snapshot.partial.filters.threaded.SnapshotFilterManager;
import io.debezium.connector.postgresql.snapshot.partial.filters.threaded.message.PoisonPillMessage;
import io.debezium.connector.postgresql.snapshot.partial.filters.threaded.message.ShouldSnapshotFilterMessage;
import io.debezium.connector.postgresql.snapshot.partial.filters.threaded.message.SnapshotFilterMessage;
import io.debezium.relational.TableId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
public class ThreadedSnapshotFilter implements FilterHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ThreadedSnapshotFilter.class);
private static final int MAX_RESPONSE_POLLING_ATTEMPTS = 30;
private static final int ONE_SECOND = 1;
private final LinkedBlockingQueue<SnapshotFilterMessage> requestQueue;
private final FilterHandler filterHandler;
public ThreadedSnapshotFilter(FilterHandler filterHandler) {
this.requestQueue = new LinkedBlockingQueue<>();
this.filterHandler = filterHandler;
Thread queryWorker = new Thread(new SnapshotFilterManager(requestQueue));
LOGGER.debug("Starting snapshot filter manager thread");
queryWorker.start();
}
@Override
public boolean shouldSnapshot(TableId tableId) {
ArrayBlockingQueue<Boolean> responseQueue = new ArrayBlockingQueue<>(1);
SnapshotFilterMessage message = new ShouldSnapshotFilterMessage(tableId, responseQueue, filterHandler);
try {
requestQueue.put(message);
for (int i = 0; i < MAX_RESPONSE_POLLING_ATTEMPTS; i++) {
Boolean response = responseQueue.poll(ONE_SECOND, TimeUnit.SECONDS);
if (response != null) {
return response;
}
LOGGER.info("Response from snapshot filter manager thread timed out for {}. Retrying", tableId);
}
LOGGER.warn("Failed to get response whether to snapshot or not for {}", tableId);
}
catch (InterruptedException e) {
LOGGER.error("Interrupted while communicating with the snapshot filter manager for {}", tableId, e);
}
LOGGER.warn("Failed to determine whether to not snapshot {}. Performing snapshot by default.", tableId);
return true;
}
@Override
public void close() {
LOGGER.info("Sending a request to close the snapshot filter.");
try {
SnapshotFilterMessage poisonPill = new PoisonPillMessage(filterHandler);
requestQueue.put(poisonPill);
}
catch (InterruptedException e) {
LOGGER.error("Interrupted while closing snapshot filter. External resources may not have closed.", e);
}
}
}
| 41.756757
| 114
| 0.718447
|
1504922919f536be18509025509c39fd0d908790
| 4,933
|
/*
* Copyright (C) 2007 The Guava Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.common.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.util.List;
/**
* Tester for equals() and hashCode() methods of a class.
*
* <p>The simplest use case is:
*
* <pre>
* new EqualsTester().addEqualityGroup(foo).testEquals();
* </pre>
*
* <p>This tests {@code foo.equals(foo)}, {@code foo.equals(null)}, and a few
* other operations.
*
* <p>For more extensive testing, add multiple equality groups. Each group
* should contain objects that are equal to each other but unequal to the
* objects in any other group. For example:
* <pre>
* new EqualsTester()
* .addEqualityGroup(new User("page"), new User("page"))
* .addEqualityGroup(new User("sergey"))
* .testEquals();
* </pre>
* <p>This tests:
* <ul>
* <li>comparing each object against itself returns true
* <li>comparing each object against null returns false
* <li>comparing each object against an instance of an incompatible class
* returns false
* <li>comparing each pair of objects within the same equality group returns
* true
* <li>comparing each pair of objects from different equality groups returns
* false
* <li>the hash codes of any two equal objects are equal
* </ul>
*
* <p>When a test fails, the error message labels the objects involved in
* the failed comparison as follows:
* <ul>
* <li>"{@code [group }<i>i</i>{@code , item }<i>j</i>{@code ]}" refers to the
* <i>j</i><sup>th</sup> item in the <i>i</i><sup>th</sup> equality group,
* where both equality groups and the items within equality groups are
* numbered starting from 1. When either a constructor argument or an
* equal object is provided, that becomes group 1.
* </ul>
*
* @author Jim McMaster
* @author Jige Yu
* @since 10.0
*/
@Beta
@GwtCompatible
public final class EqualsTester {
private static final int REPETITIONS = 3;
private final List<List<Object>> equalityGroups = Lists.newArrayList();
private final RelationshipTester.ItemReporter itemReporter;
/**
* Constructs an empty EqualsTester instance
*/
public EqualsTester() {
this(new RelationshipTester.ItemReporter());
}
EqualsTester(RelationshipTester.ItemReporter itemReporter) {
this.itemReporter = checkNotNull(itemReporter);
}
/**
* Adds {@code equalityGroup} with objects that are supposed to be equal to
* each other and not equal to any other equality groups added to this tester.
*/
public EqualsTester addEqualityGroup(Object... equalityGroup) {
checkNotNull(equalityGroup);
equalityGroups.add(ImmutableList.copyOf(equalityGroup));
return this;
}
/**
* Run tests on equals method, throwing a failure on an invalid test
*/
public EqualsTester testEquals() {
RelationshipTester<Object> delegate =
new RelationshipTester<>(
Equivalence.equals(), "Object#equals", "Object#hashCode", itemReporter);
for (List<Object> group : equalityGroups) {
delegate.addRelatedGroup(group);
}
for (int run = 0; run < REPETITIONS; run++) {
testItems();
delegate.test();
}
return this;
}
private void testItems() {
for (Object item : Iterables.concat(equalityGroups)) {
assertTrue(item + " must not be Object#equals to null", !item.equals(null));
assertTrue(item + " must not be Object#equals to an arbitrary object of another class",
!item.equals(NotAnInstance.EQUAL_TO_NOTHING));
assertEquals(item + " must be Object#equals to itself", item, item);
assertEquals("the Object#hashCode of " + item + " must be consistent",
item.hashCode(), item.hashCode());
}
}
/**
* Class used to test whether equals() correctly handles an instance
* of an incompatible class. Since it is a private inner class, the
* invoker can never pass in an instance to the tester
*/
private enum NotAnInstance {
EQUAL_TO_NOTHING;
}
}
| 34.02069
| 93
| 0.702615
|
e356fd8d17cd532a8a68b1d48fbf870071eca916
| 710
|
package me.hypherionmc.storagedrawers.util;
import net.minecraft.item.ItemStack;
import javax.annotation.Nonnull;
public class ItemStackMatcher
{
public static ItemStackMatcher EMPTY = new ItemStackMatcher(ItemStack.EMPTY);
@Nonnull
protected ItemStack stack;
public ItemStackMatcher (@Nonnull ItemStack stack) {
this.stack = stack;
}
public boolean matches (@Nonnull ItemStack stack) {
return areItemsEqual(this.stack, stack);
}
public static boolean areItemsEqual (@Nonnull ItemStack stack1, @Nonnull ItemStack stack2) {
if (!stack1.isItemEqual(stack2))
return false;
return ItemStack.areItemsEqual(stack1, stack2);
}
}
| 24.482759
| 96
| 0.708451
|
c152b04856fabefaaa2ec2eff27e96aabb78e7dd
| 1,990
|
package org.leo.im.store.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import org.leo.im.model.File;
import org.leo.im.store.connection.ConnectionProvider;
import org.leo.im.store.dao.BaseDAO;
import org.leo.im.store.dao.FileDAO;
import org.leo.im.store.exception.DAOException;
import org.leo.im.store.util.DbUtils;
/**
* 文件dao jdbc实现类
*
* @author Leo
* @date 2018/6/13
*/
public class JdbcFileDAOImpl implements BaseDAO, FileDAO {
private final static String FILE_TABLE = "im_file";
/**
* 添加文件
* @param file
* @return
*/
@Override
public String save(File file) {
Connection conn = ConnectionProvider.getConnection();
if (conn == null) {
throw new DAOException(CONNECTION_NOT_FOUND_EXCEPTION);
}
StringBuilder sql = new StringBuilder(256);
sql.append("INSERT INTO ").append(FILE_TABLE).append("(id,name,extension,size,mime_typ,width,height,path,thumb_width,thumb_height) ");
sql.append("VALUES(?,?,?,?,?,?,?,?,?,?)");
PreparedStatement stmt = null;
try {
stmt = conn.prepareStatement(sql.toString());
String fileId = createId();
stmt.setString(1, fileId);
stmt.setString(2, file.getName());
stmt.setString(3, file.getExtension());
stmt.setInt(4, file.getSize());
stmt.setString(5,file.getMimeType());
stmt.setInt(6, file.getWidth());
stmt.setInt(7, file.getHeight());
stmt.setString(8, file.getPath());
stmt.setShort(9, file.getThumbWidth());
stmt.setShort(10, file.getThumbHeight());
if(stmt.executeUpdate() > 0) {
return fileId;
}
return null;
} catch (SQLException e) {
throw new DAOException(e);
} finally {
DbUtils.closeStatement(stmt);
}
}
}
| 30.615385
| 142
| 0.6
|
622f81f3bf275b790af66c8890b3687711cb52d6
| 1,906
|
package engine.components;
import java.awt.Color;
import java.awt.Graphics;
import java.util.ArrayList;
import javax.swing.JComponent;
import engine.pieces.Piece;
public class Square extends JComponent {
private int y; // this will be which row the square is in
private int x; // this will be which column the square is in
private int squareSize;
private boolean displayPiece; // will be used to see if the piece is currently being dragged.
private Piece piece; // will be N, K, Q, Etc.
private Color color;
private MoveHandler mh;
public Square(int x, int y, int squareSize, Color color, MoveHandler mh) {
/**
* @param y - row of square
* @param x - col of square
* @param color - a memory reference to a Color object that is stored in the Board class
* **/
this.y = y;
this.x = x;
this.mh = mh;
this.squareSize = squareSize;
this.displayPiece = false;
this.piece = null; // empty square
this.color = color;
}
public MoveHandler getMoveHandler() {
return this.mh;
}
public int[] getPosition() {
return new int[] {x, y};
}
public void setPiece(Piece pt) {
/**
* @param pt - Piece class of piece.
* */
displayPiece = true;
this.piece = pt; // reassign new piece.
}
public void setDisplayPiece(boolean has) {
this.displayPiece = has;
}
public Piece getPiece() {
/**
* Will just return the piece type
* */
return this.piece;
}
public Square clone(MoveHandler newHandler) {
return new Square(x, y, squareSize, color, newHandler);
}
@Override
public void paintComponent(Graphics g) {
/**
* This method draws the color of the square
* */
super.paintComponent(g);
g.setColor(this.color);
g.fillRect(x*squareSize, y*squareSize, squareSize, squareSize);
if(displayPiece && this.piece != null) { // if there's a piece in there, then draw it.
piece.draw(g, x*squareSize, y*squareSize);
}
}
}
| 23.825
| 94
| 0.677859
|
acd370d609eb62145d18fce4b869b35709b2aab3
| 4,116
|
/*
* The MIT License
*
* Copyright 2021 Thomas Lehmann.
*
* 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 magic.system.hyperion.components.tasks;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import java.io.File;
import java.net.URISyntaxException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
* Testing of class {@link DockerImageTask}.
*
* @author Thomas Lehmann
*/
@DisplayName("Testing DockerImage class")
@SuppressWarnings("checkstyle:multiplestringliterals")
@TestMethodOrder(value = MethodOrderer.Random.class)
public class DockerImageTaskTest {
/**
* Testing Docker image creation with embedded Dockerfile content.
*/
@Test
public void testEmbeddedCode() {
final var strCode = "FROM centos:latest\n"
+ "COPY target/test-classes/scripts/say-hello-world.sh .\n"
+ "RUN chmod +x /say-hello-world.sh";
final var dockerImageTask = new DockerImageTask("test", strCode);
dockerImageTask.setRepositoryTag("image-test:latest");
var result = dockerImageTask.run(TaskTestsTools.getDefaultTaskParameters());
assertTrue(result.isSuccess());
final var dockerContainerTask = new DockerContainerTask("test", "/say-hello-world.sh");
dockerContainerTask.setImageName("image-test");
result = dockerContainerTask.run(TaskTestsTools.getDefaultTaskParameters());
assertEquals("hello world!", result.getVariable().getValue().strip());
}
/**
* Testing Docker image creation with code referencing a path and file.
*/
@Test
public void testFromFile() throws URISyntaxException {
final var scriptUrl = getClass().getResource("/dockerfiles/SimpleDockerfile");
final var file = new File(scriptUrl.toURI());
final var dockerImageTask = new DockerImageTask("test", file.getAbsolutePath());
dockerImageTask.setRepositoryTag("image-test:latest");
var result = dockerImageTask.run(TaskTestsTools.getDefaultTaskParameters());
assertTrue(result.isSuccess());
final var dockerContainerTask = new DockerContainerTask("test", "/say-hello-world.sh");
dockerContainerTask.setImageName("image-test");
result = dockerContainerTask.run(TaskTestsTools.getDefaultTaskParameters());
assertEquals("hello world!", result.getVariable().getValue().strip());
}
/**
* Testing copying of task.
*/
@Test
public void testCopy() {
final var strCode = "FROM centos:latest\n"
+ "COPY target/test-classes/scripts/say-hello-world.sh .\n"
+ "RUN chmod +x /say-hello-world.sh";
final var dockerImageTask = new DockerImageTask("test", strCode);
assertEquals(dockerImageTask, dockerImageTask.copy());
}
}
| 42.43299
| 96
| 0.697279
|
ce02b5733dd31453e08f34b74a904458b20f766d
| 19,097
|
/*
* Copyright 2019-2020 Jeff Hain
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.jolikit.bwd.impl.utils.gprim;
import net.jolikit.bwd.api.graphics.GRect;
import net.jolikit.lang.Dbg;
import net.jolikit.lang.LangUtils;
import net.jolikit.lang.NbrsUtils;
public class DefaultLineDrawer implements InterfaceLineDrawer {
/*
* TODO upgrade If ever want to do anti-aliased bresenhams
* (for lines, ovals, etc.):
* http://members.chello.at/~easyfilter/bresenham.html
*/
//--------------------------------------------------------------------------
// CONFIGURATION
//--------------------------------------------------------------------------
private static final boolean DEBUG = false;
//--------------------------------------------------------------------------
// FIELDS
//--------------------------------------------------------------------------
/*
* TODO jdk Can use Math.nextAfter(...) from JDK 6+.
*
* 1+-one_ulp is not enough to guard against computing coordinates
* that round out of clip, at least not for values of magnitude
* above about 500_000_000.
*/
private static final double ONE_MINUS_2_ULPS = 0.9999999999999998;
private static final double ONE_PLUS_2_ULPS = 1.0000000000000004;
private final InterfaceClippedLineDrawer clippedLineDrawer;
//--------------------------------------------------------------------------
// PUBLIC METHODS
//--------------------------------------------------------------------------
/**
* Uses a default clipped line drawer, using the specified
* clipped point drawer.
*/
public DefaultLineDrawer(InterfaceClippedPointDrawer clippedPointDrawer) {
this.clippedLineDrawer = new DefaultClippedLineDrawer(clippedPointDrawer);
}
public DefaultLineDrawer(InterfaceClippedLineDrawer clippedLineDrawer) {
this.clippedLineDrawer = LangUtils.requireNonNull(clippedLineDrawer);
}
/*
* Instance methods.
*/
@Override
public void drawLine(
GRect clip,
int x1, int y1, int x2, int y2) {
drawLine(
clip,
x1, y1, x2, y2,
this.clippedLineDrawer);
}
@Override
public int drawLine(
GRect clip,
int x1, int y1, int x2, int y2,
int factor, short pattern, int pixelNum) {
return drawLine(
clip,
x1, y1, x2, y2,
factor, pattern, pixelNum,
this.clippedLineDrawer);
}
/*
* Static methods.
*/
public static void drawLine(
GRect clip,
int x1, int y1, int x2, int y2,
InterfaceClippedLineDrawer clippedLineDrawer) {
drawLine(
clip,
x1, y1, x2, y2,
1, GprimUtils.PLAIN_PATTERN, 0,
clippedLineDrawer);
}
public static int drawLine(
GRect clip,
int x1, int y1, int x2, int y2,
int factor, short pattern, int pixelNum,
InterfaceClippedLineDrawer clippedLineDrawer) {
final int trueX1 = x1;
final int trueY1 = y1;
final int trueX2 = x2;
final int trueY2 = y2;
// First, making sure x1 <= x2.
final boolean p1p2Swap = (x1 > x2);
if (p1p2Swap) {
int tmp = x1;
x1 = x2;
x2 = tmp;
tmp = y1;
y1 = y2;
y2 = tmp;
}
// NB: Positive slope... goes down on screen, since y points downward.
final boolean hadPositiveSlopeAfterSwap = (y1 < y2);
int yMin;
int yMax;
if (hadPositiveSlopeAfterSwap) {
yMin = y1;
yMax = y2;
} else {
yMin = y2;
yMax = y1;
}
final boolean mustComputePixelNum =
GprimUtils.mustComputePixelNum(pattern);
// Fast check.
if ((x2 < clip.x())
|| (yMax < clip.y())
|| (x1 > clip.xMax())
|| (yMin > clip.yMax())
|| clip.isEmpty()) {
// Line outside clip (not all cases,
// except for horizontal/vertical lines),
// or empty clip.
if (DEBUG) {
Dbg.log("OUT (obvious)");
}
if (mustComputePixelNum) {
pixelNum = GprimUtils.pixelNumPlusSegmentPixelLengthNormalized(
x1, y1, x2, y2,
factor,
pixelNum);
}
return pixelNum;
}
// Horizontal case first (should be the most used,
// for cache-friendly fillings).
if (y1 == y2) {
if (mustComputePixelNum) {
pixelNum = pixelNumPlusDistToClip_horizontal(
clip,
trueX1,
factor,
pixelNum);
}
x1 = Math.max(x1, clip.x());
x2 = Math.min(x2, clip.xMax());
if (p1p2Swap) {
int tmp = x1;
x1 = x2;
x2 = tmp;
}
// Horizontal line, now clipped.
if (DEBUG) {
Dbg.log("IN CLIP (horizontal)");
}
pixelNum = clippedLineDrawer.drawHorizontalLineInClip(
x1, x2, y1,
factor, pattern, pixelNum);
if (mustComputePixelNum) {
pixelNum = pixelNumPlusDistToClip_horizontal(
clip,
trueX2,
factor,
pixelNum);
}
return pixelNum;
}
if (x1 == x2) {
if (mustComputePixelNum) {
pixelNum = pixelNumPlusDistToClip_vertical(
clip,
trueY1,
factor,
pixelNum);
}
yMin = Math.max(yMin, clip.y());
yMax = Math.min(yMax, clip.yMax());
if (hadPositiveSlopeAfterSwap) {
y1 = yMin;
y2 = yMax;
} else {
y2 = yMin;
y1 = yMax;
}
if (p1p2Swap) {
int tmp = y1;
y1 = y2;
y2 = tmp;
}
// Vertical line, now clipped.
if (DEBUG) {
Dbg.log("IN CLIP (vertical)");
}
pixelNum = clippedLineDrawer.drawVerticalLineInClip(
x1, y1, y2,
factor, pattern, pixelNum);
if (mustComputePixelNum) {
pixelNum = pixelNumPlusDistToClip_vertical(
clip,
trueY2,
factor,
pixelNum);
}
return pixelNum;
}
return clipLine_withSlope(
clip,
x1, y1, x2, y2,
factor, pattern, pixelNum,
p1p2Swap,
hadPositiveSlopeAfterSwap,
clippedLineDrawer);
}
//--------------------------------------------------------------------------
// PRIVATE METHODS
//--------------------------------------------------------------------------
private static int pixelNumPlusDistToClip_horizontal(
GRect clip,
int x,
int factor,
int pixelNum) {
final long pixelDist = computePixelDistToClip_horizontal(
clip,
x);
if (DEBUG) {
Dbg.log("dist from x = " + x + " to clip = " + pixelDist);
}
pixelNum = GprimUtils.pixelNumPlusLongAmountNormalized(factor, pixelNum, pixelDist);
return pixelNum;
}
private static int pixelNumPlusDistToClip_vertical(
GRect clip,
int y,
int factor,
int pixelNum) {
final long pixelDist = computePixelDistToClip_vertical(
clip,
y);
if (DEBUG) {
Dbg.log("dist from y = " + y + " to clip = " + pixelDist);
}
pixelNum = GprimUtils.pixelNumPlusLongAmountNormalized(factor, pixelNum, pixelDist);
return pixelNum;
}
private static long computePixelDistToClip_horizontal(
GRect clip,
int x) {
final long skippedAmount;
if (x < clip.x()) {
skippedAmount = (clip.x() - (long) x);
} else if (x > clip.xMax()) {
skippedAmount = (x - (long) clip.xMax());
} else {
skippedAmount = 0;
}
return skippedAmount;
}
private static long computePixelDistToClip_vertical(
GRect clip,
int y) {
final long skippedAmount;
if (y < clip.y()) {
skippedAmount = (clip.y() - (long) y);
} else if (y > clip.yMax()) {
skippedAmount = (y - (long) clip.yMax());
} else {
skippedAmount = 0;
}
return skippedAmount;
}
/*
*
*/
/**
* Must have x1 <= x2,
* and clip not empty.
*/
private static int clipLine_withSlope(
final GRect clip,
int x1,
int y1,
int x2,
int y2,
final int factor,
final short pattern,
int pixelNum,
final boolean p1p2Swap,
final boolean positiveSlope,
InterfaceClippedLineDrawer clippedLineDrawer) {
if (DEBUG) {
Dbg.log("clipLine_withSlope(" + clip
+ ", " + x1 + ", " + y1 + ", " + x2 + ", " + y2
+ ", " + factor + ", " + pattern + ", " + pixelNum
+ ", " + p1p2Swap + ", " + positiveSlope + ",)");
}
double x1d = x1;
double y1d = y1;
double x2d = x2;
double y2d = y2;
/*
* Intersecting line with clip borders, if needed,
* to draw only the relevant part.
* While doing this, if we find out the line is outside clip,
* we return.
* Taking care to compute with doubles, to avoid integer overflow
* and preserve line slope despite clipping.
*/
/*
* We actually consider the clip corresponding to input clip
* enlarged by 0.5, with border excluded (to make sure resulting
* coordinates always round into the clip).
* This makes sure that clipping doesn't suppress pixels
* that would be paint in clip area if there was no clipping.
*
* While doing this, we ensure not to simply add 0.5 to actual
* coordinates, since due to rounding errors it could allow for
* coordinates that don't round into the clip.
*/
final double h = 0.5;
// Rounds to clipX.
final double clipXExtended = (clip.x() - h) * (clip.x() <= 0 ? ONE_MINUS_2_ULPS : ONE_PLUS_2_ULPS);
// Rounds to clipY.
final double clipYExtended = (clip.y() - h) * (clip.y() <= 0 ? ONE_MINUS_2_ULPS : ONE_PLUS_2_ULPS);
// Rounds to clipXMax.
final double clipXMaxExtended = (clip.xMax() + h) * (clip.xMax() < 0 ? ONE_PLUS_2_ULPS : ONE_MINUS_2_ULPS);
// Rounds to clipYMax.
final double clipYMaxExtended = (clip.yMax() + h) * (clip.yMax() < 0 ? ONE_PLUS_2_ULPS : ONE_MINUS_2_ULPS);
if (DEBUG) {
Dbg.log("clipXExtended = " + clipXExtended);
Dbg.log("clipYExtended = " + clipYExtended);
Dbg.log("clipXMaxExtended = " + clipXMaxExtended);
Dbg.log("clipYMaxExtended = " + clipYMaxExtended);
}
final boolean mustComputePixelNum =
GprimUtils.mustComputePixelNum(pattern);
/*
* Getting x coordinates back in range, if needed.
*/
final boolean x1Out = (x1d < clipXExtended);
final boolean x2Out = (x2d > clipXMaxExtended);
if (DEBUG) {
Dbg.log("x1Out = " + x1Out);
Dbg.log("x2Out = " + x2Out);
}
final boolean someXOut = (x1Out || x2Out);
double a = Double.NaN;
double b = Double.NaN;
boolean equationComputed = false;
if (someXOut) {
// y1 = a * x1 + b
// y2 = a * x2 + b
// a = (y2 - y1) / (x2 - x1)
// b = y - a * x
final double denomInv = 1.0 / (x2d - x1d);
a = (y2d - y1d) * denomInv;
b = y1d - a * x1d;
if (DEBUG) {
Dbg.log("a (act,clip1) = " + a);
Dbg.log("b (act,clip1) = " + b);
}
equationComputed = true;
// First, getting x coordinates in range.
// No problem if computed y's are out of range, we will
// take care of them later.
if (x1Out) {
x1d = clipXExtended;
// Typically no longer a mathematical integer.
y1d = a * x1d + b;
}
if (x2Out) {
x2d = clipXMaxExtended;
// Typically no longer a mathematical integer.
y2d = a * x2d + b;
}
if (DEBUG) {
Dbg.log("x1d (1) = " + NbrsUtils.toStringNoCSN(x1d));
Dbg.log("y1d (1) = " + NbrsUtils.toStringNoCSN(y1d));
Dbg.log("x2d (1) = " + NbrsUtils.toStringNoCSN(x2d));
Dbg.log("y2d (1) = " + NbrsUtils.toStringNoCSN(y2d));
}
if (Math.max(y1d,y2d) < clipYExtended) {
// Line above clip (all cases).
if (DEBUG) {
Dbg.log("OUT : line above (all cases)");
}
if (mustComputePixelNum) {
pixelNum = GprimUtils.pixelNumPlusSegmentPixelLengthNormalized(
x1, y1, x2, y2,
factor,
pixelNum);
}
return pixelNum;
}
if (Math.min(y1d,y2d) > clipYMaxExtended) {
// Line below clip (all cases).
if (DEBUG) {
Dbg.log("OUT : line below (all cases)");
}
if (mustComputePixelNum) {
pixelNum = GprimUtils.pixelNumPlusSegmentPixelLengthNormalized(
x1, y1, x2, y2,
factor,
pixelNum);
}
return pixelNum;
}
}
/*
* Getting y coordinates back in range, if needed.
*
* Mathematically we would only need to test against
* lower or upper bound, depending on whether slope
* is positive or negative, but we test against both
* to guard against possible inaccuracies.
*/
final boolean y1Out = (y1d < clipYExtended) || (y1d > clipYMaxExtended);
final boolean y2Out = (y2d < clipYExtended) || (y2d > clipYMaxExtended);
if (DEBUG) {
Dbg.log("y1Out = " + y1Out);
Dbg.log("y2Out = " + y2Out);
}
final boolean someYOut = (y1Out || y2Out);
if (someYOut) {
if (!equationComputed) {
final double denomInv = 1.0 / (x2d - x1d);
a = (y2d - y1d) * denomInv;
b = y1d - a * x1d;
if (DEBUG) {
Dbg.log("a (act,clip2) = " + a);
Dbg.log("b (act,clip2) = " + b);
}
}
final double aInv = 1.0 / a;
final double bDivA = b * aInv;
// x = 1/a * y - b/a
if (y1Out) {
y1d = (positiveSlope ? clipYExtended : clipYMaxExtended);
// Typically no longer a mathematical integer.
x1d = aInv * y1d - bDivA;
// x1 was already in clip, so since we get y1 back in clip range,
// x1 should now be well in clip, so no need to ensure it's in
// to guard against eventual rounding errors.
}
if (y2Out) {
y2d = (positiveSlope ? clipYMaxExtended : clipYExtended);
// Typically no longer a mathematical integer.
x2d = aInv * y2d - bDivA;
// x2 was already in clip, so since we get y2 back in clip range,
// x2 should now be well in clip, so no need to ensure it's in
// to guard against eventual rounding errors.
}
}
/*
* Ensuring initial p1/p2 order.
*/
if (p1p2Swap) {
{
double tmp = x1d;
x1d = x2d;
x2d = tmp;
tmp = y1d;
y1d = y2d;
y2d = tmp;
}
{
int tmp = x1;
x1 = x2;
x2 = tmp;
tmp = y1;
y1 = y2;
y2 = tmp;
}
}
/*
*
*/
if (someXOut || someYOut) {
if (DEBUG) {
Dbg.log("CLIPPED (general)");
Dbg.log("x1d (2) = " + NbrsUtils.toStringNoCSN(x1d));
Dbg.log("y1d (2) = " + NbrsUtils.toStringNoCSN(y1d));
Dbg.log("x2d (2) = " + NbrsUtils.toStringNoCSN(x2d));
Dbg.log("y2d (2) = " + NbrsUtils.toStringNoCSN(y2d));
}
pixelNum = clippedLineDrawer.drawGeneralLineClipped(
clip,
x1, y1, x2, y2,
x1d, y1d, x2d, y2d,
factor, pattern, pixelNum);
return pixelNum;
} else {
if (DEBUG) {
Dbg.log("IN CLIP");
}
return clippedLineDrawer.drawGeneralLineInClip(
x1, y1, x2, y2,
factor, pattern, pixelNum);
}
}
}
| 33.56239
| 115
| 0.455831
|
64d8bdf4b984d78c245862bbd0365aba99324b3c
| 3,260
|
// FCMOD
package net.minecraft.src;
public class FCEntityWitch extends EntityWitch
{
private static final int[] m_itemDrops = new int[] {
FCBetterThanWolves.fcItemWitchWart.itemID,
Item.glassBottle.itemID,
Item.stick.itemID };
public FCEntityWitch( World world )
{
super( world );
tasks.RemoveAllTasksOfClass( EntityAIWander.class );
tasks.addTask( 2, new FCEntityAIWanderSimple( this, moveSpeed ) );
}
@Override
protected void dropFewItems( boolean bKilledByPlayer, int iLootingModifier )
{
int iNumDrops = rand.nextInt( 3 ) + 1;
for ( int iTempCount = 0; iTempCount < iNumDrops; ++iTempCount )
{
int iItemID = m_itemDrops[rand.nextInt( m_itemDrops.length )];
int iNumItems = rand.nextInt( 3 );
if ( iLootingModifier > 0 )
{
iNumItems += rand.nextInt( iLootingModifier + 1 );
}
for ( ; iNumItems > 0; iNumItems-- )
{
dropItem( iItemID, 1 );
}
}
}
@Override
public boolean getCanSpawnHere()
{
// limit witch spawns to above and around sea level
if ( (int)posY >= worldObj.provider.getAverageGroundLevel() - 5 )
{
return super.getCanSpawnHere();
}
return false;
}
@Override
public void CheckForScrollDrop()
{
if ( rand.nextInt( 1000 ) == 0 )
{
ItemStack itemstack = new ItemStack( FCBetterThanWolves.fcItemArcaneScroll, 1, Enchantment.aquaAffinity.effectId );
entityDropItem(itemstack, 0.0F);
}
}
@Override
public void playLivingSound()
{
String var1 = "mob.ghast.affectionate scream";
if (var1 != null)
{
playSound(var1, this.getSoundVolume() * 0.25F, 0.5F + rand.nextFloat() * 0.25F );
}
}
@Override
public void attackEntityWithRangedAttack( EntityLiving target, float fDamageModifier )
{
if ( !IsConsumingPotion() )
{
super.attackEntityWithRangedAttack( target, fDamageModifier );
worldObj.playSoundAtEntity( this, "mob.wither.shoot", 0.5F, 0.4F / (rand.nextFloat() * 0.4F + 0.8F));
}
}
/**
* This method is misnamed in that it actually sets whether the witch is in the process of
* consuming a potion, and has nothing to do with agression.
*/
@Override
public void setAggressive( boolean bIsConsumingPotion )
{
super.setAggressive( bIsConsumingPotion );
if ( bIsConsumingPotion )
{
// sound when witch starts drinking a potion
worldObj.playSoundAtEntity( this, "mob.wither.shoot", 0.5F,
0.4F / ( rand.nextFloat() * 0.4F + 0.8F ) );
}
}
//------------- Class Specific Methods ------------//
/**
* getAgressive() is misnamed in the parent. This function for clarity
*/
public boolean IsConsumingPotion()
{
return getAggressive();
}
}
| 27.863248
| 128
| 0.546626
|
3a918fbf96083ce79deffffbf00855b5df9235f4
| 2,297
|
package urender.demo.editor;
import java.awt.image.BufferedImage;
import javax.swing.ImageIcon;
import urender.api.UTextureFormat;
import urender.api.UTextureSwizzleChannel;
import urender.api.UTextureType;
import urender.engine.UTexture;
import urender.engine.UTexture2D;
import urender.g3dio.generic.IIOTextureLoader;
public class TextureEditHandle implements IEditHandle<UTexture> {
public final UTexture tex;
public ImageIcon icon;
public TextureEditHandle(UTexture texture) {
this.tex = texture;
if (texture.getTextureType() == UTextureType.TEX2D) {
BufferedImage image = decodeTex((UTexture2D) tex);
if (image != null) {
icon = new ImageIcon(image);
}
}
}
private static BufferedImage decodeTex(UTexture2D tex) {
int bpp = 0;
switch (tex.format) {
case R8:
bpp = 1;
break;
case RG8:
bpp = 2;
break;
case RGB8:
bpp = 3;
break;
case RGBA8:
bpp = 4;
break;
default:
return null;
}
int width = tex.getWidth();
int height = tex.getHeight();
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
int stride = IIOTextureLoader.calcRowStride(width, bpp);
byte[] temp = new byte[bpp];
for (int y = 0; y < height; y++) {
tex.data.position(y * stride);
for (int x = 0; x < width; x++) {
tex.data.get(temp);
int r = getUnswizzledComponent(temp, tex.swizzleMask.r);
int g = getUnswizzledComponent(temp, tex.swizzleMask.g);
int b = getUnswizzledComponent(temp, tex.swizzleMask.b);
int a = getUnswizzledComponent(temp, tex.swizzleMask.a);
img.setRGB(x, height - y - 1, (a << 24) | (r << 16) | (g << 8) | (b << 0));
}
}
return img;
}
private static int getUnswizzledComponent(byte[] rawData, UTextureSwizzleChannel swizzle) {
switch (swizzle) {
case ONE:
return 255;
case ZERO:
return 0;
case R:
return rawData[0] & 255;
case G:
return rawData.length > 1 ? rawData[1] & 255 : 0;
case B:
return rawData.length > 2 ? rawData[2] & 255 : 0;
case A:
return rawData.length > 3 ? rawData[3] & 255 : 0;
}
return 0;
}
@Override
public String toString() {
return tex.getName();
}
@Override
public void save() {
}
@Override
public UTexture getContent() {
return tex;
}
}
| 22.519608
| 92
| 0.659121
|
4f24a9c904707792c987982c0a1ec37c97c1ace0
| 3,901
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See License.txt in the repository root.
package com.microsoft.tfs.client.common.ui.framework.validation;
import org.eclipse.jface.util.Geometry;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.PlatformUI;
import com.microsoft.tfs.client.common.ui.framework.layout.GridDataBuilder;
import com.microsoft.tfs.util.valid.AbstractValidatorBinding;
import com.microsoft.tfs.util.valid.IValidationMessage;
import com.microsoft.tfs.util.valid.IValidity;
import com.microsoft.tfs.util.valid.Severity;
import com.microsoft.tfs.util.valid.ValidatorBinding;
public class ErrorLabel extends Composite {
private final Label label;
private final Image errorImage;
private final Image warningImage;
private final ValidatorBinding validatorBinding;
private Point computedSize;
public ErrorLabel(final Composite parent, final int style) {
super(parent, style);
label = new Label(this, SWT.NONE);
GridDataBuilder.newInstance().hHint(16).wHint(16).applyTo(label);
errorImage = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_ERROR_TSK);
warningImage = PlatformUI.getWorkbench().getSharedImages().getImage(ISharedImages.IMG_OBJS_WARN_TSK);
validatorBinding = new AbstractValidatorBinding() {
@Override
protected void update(final IValidity validity) {
if (validity.getSeverity() == Severity.OK) {
clearErrorState();
} else {
final IValidationMessage validationMessage = validity.getFirstMessage();
if (validationMessage == null) {
setErrorState(validity.getSeverity(), null);
} else {
setErrorState(validationMessage.getSeverity(), validationMessage.getMessage());
}
}
}
};
addControlListener(new ControlAdapter() {
@Override
public void controlResized(final ControlEvent e) {
ErrorLabel.this.controlResized(e);
}
});
}
public ValidatorBinding getValidatorBinding() {
return validatorBinding;
}
public void clearErrorState() {
setErrorState(Severity.OK, null);
}
public void setErrorState(final Severity severity, final String message) {
if (severity == Severity.ERROR) {
label.setVisible(true);
label.setImage(errorImage);
if (message != null) {
label.setToolTipText(message);
} else {
label.setToolTipText(null);
}
} else if (severity == Severity.WARNING) {
label.setVisible(true);
label.setImage(warningImage);
if (message != null) {
label.setToolTipText(message);
} else {
label.setToolTipText(null);
}
} else {
label.setVisible(false);
label.setToolTipText(null);
}
}
@Override
public Point computeSize(final int wHint, final int hHint, final boolean changed) {
if (computedSize == null) {
final Rectangle r = errorImage.getBounds().union(warningImage.getBounds());
computedSize = Geometry.getSize(r);
}
return computedSize;
}
private void controlResized(final ControlEvent e) {
label.setBounds(getClientArea());
}
}
| 34.522124
| 109
| 0.642143
|
64026a2c00cda1005814b3602b990a63fc92bf9f
| 10,581
|
/***********************************************************************************************************************
* Copyright (C) 2010-2014 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.test.runtime;
import eu.stratosphere.configuration.Configuration;
import eu.stratosphere.core.io.IOReadableWritable;
import eu.stratosphere.nephele.jobgraph.DistributionPattern;
import eu.stratosphere.nephele.jobgraph.JobGenericInputVertex;
import eu.stratosphere.nephele.jobgraph.JobGraph;
import eu.stratosphere.nephele.jobgraph.JobGraphDefinitionException;
import eu.stratosphere.nephele.jobgraph.JobInputVertex;
import eu.stratosphere.nephele.jobgraph.JobOutputVertex;
import eu.stratosphere.nephele.jobgraph.JobTaskVertex;
import eu.stratosphere.nephele.template.AbstractGenericInputTask;
import eu.stratosphere.nephele.template.AbstractOutputTask;
import eu.stratosphere.nephele.template.AbstractTask;
import eu.stratosphere.runtime.io.api.RecordReader;
import eu.stratosphere.runtime.io.api.RecordWriter;
import eu.stratosphere.runtime.io.channels.ChannelType;
import eu.stratosphere.test.util.RecordAPITestBase;
import eu.stratosphere.util.LogUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@RunWith(Parameterized.class)
public class NetworkStackNepheleITCase extends RecordAPITestBase {
private static final Log LOG = LogFactory.getLog(NetworkStackNepheleITCase.class);
private static final String DATA_VOLUME_GB_CONFIG_KEY = "data.volume.gb";
private static final String USE_FORWARDER_CONFIG_KEY = "use.forwarder";
private static final String NUM_SUBTASKS_CONFIG_KEY = "num.subtasks";
private static final String NUM_SUBTASKS_PER_INSTANCE_CONFIG_KEY = "num.subtasks.instance";
private static final String IS_SLOW_SENDER_CONFIG_KEY = "is.slow.sender";
private static final String IS_SLOW_RECEIVER_CONFIG_KEY = "is.slow.receiver";
private static final int IS_SLOW_SLEEP_MS = 10;
private static final int IS_SLOW_EVERY_NUM_RECORDS = (2 * 32 * 1024) / SpeedTestRecord.RECORD_SIZE;
// ------------------------------------------------------------------------
public NetworkStackNepheleITCase(Configuration config) {
super(config);
setNumTaskManager(2);
LogUtils.initializeDefaultConsoleLogger();
}
@Parameters
public static Collection<Object[]> getConfigurations() {
Object[][] configParams = new Object[][]{
new Object[]{1, false, false, false, 4, 2},
new Object[]{1, true, false, false, 4, 2},
new Object[]{1, true, true, false, 4, 2},
new Object[]{1, true, false, true, 4, 2},
new Object[]{2, true, false, false, 4, 2},
new Object[]{4, true, false, false, 4, 2},
new Object[]{4, true, false, false, 8, 4},
new Object[]{4, true, false, false, 16, 8},
};
List<Configuration> configs = new ArrayList<Configuration>(configParams.length);
for (Object[] p : configParams) {
Configuration config = new Configuration();
config.setInteger(DATA_VOLUME_GB_CONFIG_KEY, (Integer) p[0]);
config.setBoolean(USE_FORWARDER_CONFIG_KEY, (Boolean) p[1]);
config.setBoolean(IS_SLOW_SENDER_CONFIG_KEY, (Boolean) p[2]);
config.setBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, (Boolean) p[3]);
config.setInteger(NUM_SUBTASKS_CONFIG_KEY, (Integer) p[4]);
config.setInteger(NUM_SUBTASKS_PER_INSTANCE_CONFIG_KEY, (Integer) p[5]);
configs.add(config);
}
return toParameterList(configs);
}
// ------------------------------------------------------------------------
@Override
protected JobGraph getJobGraph() throws Exception {
int dataVolumeGb = this.config.getInteger(DATA_VOLUME_GB_CONFIG_KEY, 1);
boolean useForwarder = this.config.getBoolean(USE_FORWARDER_CONFIG_KEY, true);
boolean isSlowSender = this.config.getBoolean(IS_SLOW_SENDER_CONFIG_KEY, false);
boolean isSlowReceiver = this.config.getBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, false);
int numSubtasks = this.config.getInteger(NUM_SUBTASKS_CONFIG_KEY, 1);
int numSubtasksPerInstance = this.config.getInteger(NUM_SUBTASKS_PER_INSTANCE_CONFIG_KEY, 1);
return createJobGraph(dataVolumeGb, useForwarder, isSlowSender, isSlowReceiver, numSubtasks, numSubtasksPerInstance);
}
@After
public void calculateThroughput() {
if (getJobExecutionResult() != null) {
int dataVolumeGb = this.config.getInteger(DATA_VOLUME_GB_CONFIG_KEY, 1);
double dataVolumeMbit = dataVolumeGb * 8192.0;
double runtimeSecs = getJobExecutionResult().getNetRuntime() / 1000.0;
int mbitPerSecond = (int) Math.round(dataVolumeMbit / runtimeSecs);
LOG.info(String.format("Test finished with throughput of %d MBit/s (" +
"runtime [secs]: %.2f, data volume [mbits]: %.2f)", mbitPerSecond, runtimeSecs, dataVolumeMbit));
}
}
private JobGraph createJobGraph(int dataVolumeGb, boolean useForwarder, boolean isSlowSender, boolean isSlowReceiver,
int numSubtasks, int numSubtasksPerInstance) throws JobGraphDefinitionException {
JobGraph jobGraph = new JobGraph("Speed Test");
JobInputVertex producer = new JobGenericInputVertex("Speed Test Producer", jobGraph);
producer.setInputClass(SpeedTestProducer.class);
producer.setNumberOfSubtasks(numSubtasks);
producer.setNumberOfSubtasksPerInstance(numSubtasksPerInstance);
producer.getConfiguration().setInteger(DATA_VOLUME_GB_CONFIG_KEY, dataVolumeGb);
producer.getConfiguration().setBoolean(IS_SLOW_SENDER_CONFIG_KEY, isSlowSender);
JobTaskVertex forwarder = null;
if (useForwarder) {
forwarder = new JobTaskVertex("Speed Test Forwarder", jobGraph);
forwarder.setTaskClass(SpeedTestForwarder.class);
forwarder.setNumberOfSubtasks(numSubtasks);
forwarder.setNumberOfSubtasksPerInstance(numSubtasksPerInstance);
}
JobOutputVertex consumer = new JobOutputVertex("Speed Test Consumer", jobGraph);
consumer.setOutputClass(SpeedTestConsumer.class);
consumer.setNumberOfSubtasks(numSubtasks);
consumer.setNumberOfSubtasksPerInstance(numSubtasksPerInstance);
consumer.getConfiguration().setBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, isSlowReceiver);
if (useForwarder) {
producer.connectTo(forwarder, ChannelType.NETWORK, DistributionPattern.BIPARTITE);
forwarder.connectTo(consumer, ChannelType.NETWORK, DistributionPattern.BIPARTITE);
forwarder.setVertexToShareInstancesWith(producer);
consumer.setVertexToShareInstancesWith(producer);
}
else {
producer.connectTo(consumer, ChannelType.NETWORK, DistributionPattern.BIPARTITE);
producer.setVertexToShareInstancesWith(consumer);
}
return jobGraph;
}
// ------------------------------------------------------------------------
public static class SpeedTestProducer extends AbstractGenericInputTask {
private RecordWriter<SpeedTestRecord> writer;
@Override
public void registerInputOutput() {
this.writer = new RecordWriter<SpeedTestRecord>(this);
}
@Override
public void invoke() throws Exception {
this.writer.initializeSerializers();
// Determine the amount of data to send per subtask
int dataVolumeGb = getTaskConfiguration().getInteger(NetworkStackNepheleITCase.DATA_VOLUME_GB_CONFIG_KEY, 1);
long dataMbPerSubtask = (dataVolumeGb * 1024) / getCurrentNumberOfSubtasks();
long numRecordsToEmit = (dataMbPerSubtask * 1024 * 1024) / SpeedTestRecord.RECORD_SIZE;
LOG.info(String.format("%d/%d: Producing %d records (each record: %d bytes, total: %.2f GB)",
getIndexInSubtaskGroup() + 1, getCurrentNumberOfSubtasks(), numRecordsToEmit,
SpeedTestRecord.RECORD_SIZE, dataMbPerSubtask / 1024.0));
boolean isSlow = getTaskConfiguration().getBoolean(IS_SLOW_SENDER_CONFIG_KEY, false);
int numRecords = 0;
SpeedTestRecord record = new SpeedTestRecord();
for (long i = 0; i < numRecordsToEmit; i++) {
if (isSlow && (numRecords++ % IS_SLOW_EVERY_NUM_RECORDS) == 0) {
Thread.sleep(IS_SLOW_SLEEP_MS);
}
this.writer.emit(record);
}
this.writer.flush();
}
}
public static class SpeedTestForwarder extends AbstractTask {
private RecordReader<SpeedTestRecord> reader;
private RecordWriter<SpeedTestRecord> writer;
@Override
public void registerInputOutput() {
this.reader = new RecordReader<SpeedTestRecord>(this, SpeedTestRecord.class);
this.writer = new RecordWriter<SpeedTestRecord>(this);
}
@Override
public void invoke() throws Exception {
this.writer.initializeSerializers();
SpeedTestRecord record;
while ((record = this.reader.next()) != null) {
this.writer.emit(record);
}
this.writer.flush();
}
}
public static class SpeedTestConsumer extends AbstractOutputTask {
private RecordReader<SpeedTestRecord> reader;
@Override
public void registerInputOutput() {
this.reader = new RecordReader<SpeedTestRecord>(this, SpeedTestRecord.class);
}
@Override
public void invoke() throws Exception {
boolean isSlow = getTaskConfiguration().getBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, false);
int numRecords = 0;
while (this.reader.next() != null) {
if (isSlow && (numRecords++ % IS_SLOW_EVERY_NUM_RECORDS) == 0) {
Thread.sleep(IS_SLOW_SLEEP_MS);
}
}
}
}
public static class SpeedTestRecord implements IOReadableWritable {
private static final int RECORD_SIZE = 128;
private final byte[] buf = new byte[RECORD_SIZE];
public SpeedTestRecord() {
for (int i = 0; i < RECORD_SIZE; ++i) {
this.buf[i] = (byte) (i % 128);
}
}
@Override
public void write(DataOutput out) throws IOException {
out.write(this.buf);
}
@Override
public void read(DataInput in) throws IOException {
in.readFully(this.buf);
}
}
}
| 36.867596
| 120
| 0.733296
|
64a467132f74c8631eb854cc038e8ca8d9fcfe36
| 93
|
package cz.epptec.decision.model;
public class ExampleRuleOutput {
private int price;
}
| 15.5
| 33
| 0.763441
|
f8cbc9d7057a095f2d2daa36b7d153a9a8b43ec7
| 2,081
|
package com.lothrazar.cyclic.util;
import com.lothrazar.cyclic.capability.wrappers.SpongeBlockWrapper;
import net.minecraft.block.Block;
import net.minecraft.block.BlockState;
import net.minecraft.block.IBucketPickupHandler;
import net.minecraft.block.SpongeBlock;
import net.minecraft.block.WetSpongeBlock;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.Direction;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.common.util.LazyOptional;
import net.minecraftforge.fluids.IFluidBlock;
import net.minecraftforge.fluids.capability.CapabilityFluidHandler;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.wrappers.BucketPickupHandlerWrapper;
import net.minecraftforge.fluids.capability.wrappers.FluidBlockWrapper;
public final class UtilFluidHandler {
private UtilFluidHandler() {
}
public static IFluidHandler get(final World world, final BlockPos blockPos, final Direction side) {
return getOptCap(world, blockPos, side).resolve().orElse(null);
}
public static LazyOptional<IFluidHandler> getOptCap(final World world, final BlockPos blockPos, final Direction side) {
final TileEntity tileEntity = world.getTileEntity(blockPos);
if (tileEntity != null) {
return tileEntity.getCapability(CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, side);
}
return LazyOptional.empty();
}
public static IFluidHandler getFromBlock(final World world, final BlockPos blockPos) {
final BlockState blockState = world.getBlockState(blockPos);
final Block block = blockState.getBlock();
if (block instanceof IBucketPickupHandler) {
return new BucketPickupHandlerWrapper((IBucketPickupHandler) block, world, blockPos);
}
if (block instanceof IFluidBlock) {
return new FluidBlockWrapper((IFluidBlock) block, world, blockPos);
}
if (block instanceof SpongeBlock || block instanceof WetSpongeBlock) {
return new SpongeBlockWrapper(block, world, blockPos);
}
return null;
}
}
| 40.803922
| 121
| 0.791446
|
e02c5367db7e606c74caaba37259650fb86c05fe
| 472
|
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
class SolutionTest {
@Test
void sample() {
assertEquals(0, CountingDuplicates.duplicateCount("abcde"));
assertEquals(1, CountingDuplicates.duplicateCount("abcdea"));
assertEquals(1, CountingDuplicates.duplicateCount("indivisibility"));
assertEquals(3, CountingDuplicates.duplicateCount("dA" + "c".repeat(10) + "b".repeat(100) + "a".repeat(1000)));
}
}
| 33.714286
| 115
| 0.737288
|
466a025ff777fad2574afdcc06293672ead5196f
| 4,110
|
package com.idata.mq.base.properties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AmpMdmProperties {
@Value("${mdm.device.online.queue.name}")
private String deviceOnlineQueueName;
@Value("${mdm.device.online.routing.key}")
private String deviceOnlineRoutingKey;
@Value("${mdm.device.offline.queue.name}")
private String deviceOfflineQueueName;
@Value("${mdm.device.offline.routing.key}")
private String deviceOfflineRoutingKey;
@Value("${mdm.device.message.result.queue.name}")
private String deviceMessageResultQueueName;
@Value("${mdm.device.message.result.routing.key}")
private String deviceMessageResultRoutingKey;
@Value("${mdm.service.confirm.queue.name}")
private String confirmQueueName;
@Value("${mdm.service.confirm.routing.key}")
private String confirmRoutingKey;
@Value("${mdm.service.status.queue.name}")
private String serviceStatusQueueName;
@Value("${mdm.service.status.routing.key}")
private String serviceStatusRoutingKey;
@Value("${mdm.service.msg.fail.queue.name}")
private String failMsgQueueName;
@Value("${mdm.service.msg.fail.routing.key}")
private String failMsgRoutingKey;
public String getDeviceOnlineQueueName() {
return deviceOnlineQueueName;
}
public void setDeviceOnlineQueueName(String deviceOnlineQueueName) {
this.deviceOnlineQueueName = deviceOnlineQueueName;
}
public String getDeviceOnlineRoutingKey() {
return deviceOnlineRoutingKey;
}
public void setDeviceOnlineRoutingKey(String deviceOnlineRoutingKey) {
this.deviceOnlineRoutingKey = deviceOnlineRoutingKey;
}
public String getDeviceOfflineQueueName() {
return deviceOfflineQueueName;
}
public void setDeviceOfflineQueueName(String deviceOfflineQueueName) {
this.deviceOfflineQueueName = deviceOfflineQueueName;
}
public String getDeviceOfflineRoutingKey() {
return deviceOfflineRoutingKey;
}
public void setDeviceOfflineRoutingKey(String deviceOfflineRoutingKey) {
this.deviceOfflineRoutingKey = deviceOfflineRoutingKey;
}
public String getDeviceMessageResultQueueName() {
return deviceMessageResultQueueName;
}
public void setDeviceMessageResultQueueName(String deviceMessageResultQueueName) {
this.deviceMessageResultQueueName = deviceMessageResultQueueName;
}
public String getDeviceMessageResultRoutingKey() {
return deviceMessageResultRoutingKey;
}
public void setDeviceMessageResultRoutingKey(String deviceMessageResultRoutingKey) {
this.deviceMessageResultRoutingKey = deviceMessageResultRoutingKey;
}
public String getConfirmQueueName() {
return confirmQueueName;
}
public void setConfirmQueueName(String confirmQueueName) {
this.confirmQueueName = confirmQueueName;
}
public String getConfirmRoutingKey() {
return confirmRoutingKey;
}
public void setConfirmRoutingKey(String confirmRoutingKey) {
this.confirmRoutingKey = confirmRoutingKey;
}
public String getServiceStatusQueueName() {
return serviceStatusQueueName;
}
public void setServiceStatusQueueName(String serviceStatusQueueName) {
this.serviceStatusQueueName = serviceStatusQueueName;
}
public String getServiceStatusRoutingKey() {
return serviceStatusRoutingKey;
}
public void setServiceStatusRoutingKey(String serviceStatusRoutingKey) {
this.serviceStatusRoutingKey = serviceStatusRoutingKey;
}
public String getFailMsgQueueName() {
return failMsgQueueName;
}
public void setFailMsgQueueName(String failMsgQueueName) {
this.failMsgQueueName = failMsgQueueName;
}
public String getFailMsgRoutingKey() {
return failMsgRoutingKey;
}
public void setFailMsgRoutingKey(String failMsgRoutingKey) {
this.failMsgRoutingKey = failMsgRoutingKey;
}
}
| 28.943662
| 88
| 0.734063
|
e6a59db436f52a2e27e0cc4a796de11e45b8302b
| 765
|
package sqlchart;
public class DataSource {
public final String name;
public final String url;
public final int poolSize;
public volatile boolean alive;
public volatile Table[] tables;
public final KeyDesc[] keyDescs = null;
public final Descriptor[] descriptors = null;
public final ChartSeries[] chartSeriess = null;
public transient volatile SqlConnectionPool connectionPool;
public DataSource(String name, String url, int poolSize) {
this.name = name;
this.url = url;
this.poolSize = poolSize;
}
static Table findTable(Table[] tabs, String name) {
Table[] volatileTmp = tabs;
if (volatileTmp != null) {
for (Table t : volatileTmp)
if (t.table.equals(name))
return t;
}
return null;
}
}
| 23.90625
| 61
| 0.688889
|
255d63346af371fb06d870c903f49717ca33c5d6
| 754
|
package priv.jesse.mall.service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.query.Param;
import priv.jesse.mall.entity.Aboutus;
import priv.jesse.mall.entity.Product;
import priv.jesse.mall.entity.SmsRecord;
import java.util.List;
public interface SmsRecordService {
/**
* 分页查询所有
*
* @param pageable
* @return
*/
Page<SmsRecord> findAll(Pageable pageable);
/**
* 创建
*
* @param smsRecord
* @return
*/
int create(SmsRecord smsRecord);
/**
* 根据发送记录查询
* @param smsRecord
* @return
*/
int findBySmsRecord(@Param("smsRecord") SmsRecord smsRecord);
}
| 16.755556
| 65
| 0.649867
|
f895a90821ba16e07594766b1c2382374c1a023b
| 1,154
|
package com.sarinsa.starvingtotem.common.core.registry;
import com.sarinsa.starvingtotem.common.core.StarvingTotem;
import com.sarinsa.starvingtotem.common.effect.BitterCurseEffect;
import com.sarinsa.starvingtotem.common.effect.SweetBlessingEffect;
import net.minecraft.potion.Effect;
import net.minecraft.potion.EffectType;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import java.util.function.Supplier;
public class STEffects {
public static final DeferredRegister<Effect> EFFECTS = DeferredRegister.create(ForgeRegistries.POTIONS, StarvingTotem.MODID);
public static final RegistryObject<Effect> BITTER_CURSE = register("bitter_curse", () -> new BitterCurseEffect(EffectType.NEUTRAL, 0x467773));
public static final RegistryObject<Effect> SWEET_BLESSING = register("sweet_blessing", () -> new SweetBlessingEffect(EffectType.BENEFICIAL, 0x467773));
private static <T extends Effect> RegistryObject<T> register(String name, Supplier<T> effectSupplier) {
return EFFECTS.register(name, effectSupplier);
}
}
| 42.740741
| 155
| 0.811092
|
0fde127f6345db8753d9b91685dec75e8ce62553
| 1,188
|
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.sql.querydsl.container;
import java.util.Objects;
import org.elasticsearch.xpack.sql.expression.Attribute;
public class AttributeSort extends Sort {
private final Attribute attribute;
public AttributeSort(Attribute attribute, Direction direction) {
super(direction);
this.attribute = attribute;
}
public Attribute attribute() {
return attribute;
}
@Override
public int hashCode() {
return Objects.hash(attribute, direction());
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
AttributeSort other = (AttributeSort) obj;
return Objects.equals(direction(), other.direction())
&& Objects.equals(attribute, other.attribute);
}
}
| 26.4
| 79
| 0.643098
|
c3755b28464ce242f468f2227e56f7af5340dbdf
| 25,235
|
package net.sanmuyao.core.util;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang.StringUtils;
/**
* 日期时间操作类
* @author 杜庆明 [duqingming@qq.com]
* @version 1.0
*/
public class DateUtil {
/**
* 取系统默认时区的当前时间
* @return
*/
public static Date getDate() {
// Etc/GMT 是格林威治标准时间,得到的时间和默认时区是一样的
// Etc/GMT+8 比林威治标准时间慢8小时,
// Etc/GMT-8 东八区,我们比那快8小时所以减8
// PRC 设置中国时区
// Calendar.getInstance(TimeZone.getTimeZone("GMT-8:00")).getTime();
Calendar cal = Calendar.getInstance(java.util.Locale.CHINA);
return cal.getTime();
}
/**
* 取系统默认时区的当前时间毫秒数
* @return
*/
public static long getTime() {
return getDate().getTime();
}
// =================== start 将日期转成字符串 start =================== //
/**
* 将指定时间转换成指定格式的字符串
* 应尽量避免使用此方法,建议使用方法:getStrDateTime(Date date, DateTimeFormat dateTimePattern)
* @param date
* @param format
* @return
*/
public static String getStrDateTime(Date date, String format) {
if (date == null)
return "";
DateFormat sdf = new SimpleDateFormat(format);
String tsStr = sdf.format(date);
return tsStr;
}
/**
* 将指定long类型的时间戳转换成指定格式的字符串
* 应尽量避免使用此方法,建议使用方法:getStrDateTime(Date date, DateTimeFormat dateTimePattern)
* @param date
* @param format
* @return
*/
public static String getStrDateTime(long timeInMillis, String format) {
if (timeInMillis <= 0)
return null;
Calendar c = Calendar.getInstance(Locale.CHINA);
c.setTimeInMillis(timeInMillis);
DateFormat sdf = new SimpleDateFormat(format);
return sdf.format(c.getTime());
}
/**
* 将指定时间转换成指定格式的字符串
* @param date
* @param dateTimePattern
* @return
*/
public static String getStrDateTime(Date date, DateTimePattern dateTimePattern) {
return getStrDateTime(date, dateTimePattern.getCode());
}
/**
* 取当指定时间格式化形式的字符串,日期格式为:yyyy-MM-dd HH:mm:ss
* @param date
* @return
*/
public static String getStrDateTime(Date date) {
return getStrDateTime(date, DateTimePattern.shortDateTimePattern);
}
/**
* 将long类型的时间戳转换成指定格式的字符串,日期格式为:yyyy-MM-dd HH:mm:ss
* @param timeInMillis
* @return
*/
public static String getStrDateTime(long timeInMillis) {
return getStrDateTime(timeInMillis, "yyyy-MM-dd HH:mm:ss");
}
/**
* 取指定时间的日期格式化字符串,日期格式为:yyyy-MM-dd
* @param date
* @return
*/
public static String getStrDate(Date date) {
return getStrDateTime(date, DateTimePattern.shortDatePattern);
}
/**
* 取指定时间的时间格式化字符串,时间格式为:HH:mm:ss
* @param date
* @return
*/
public static String getStrTime(Date date) {
return getStrDateTime(date, DateTimePattern.shortTimePattern);
}
/**
* 取当前时间的日期格式化字符串,日期格式为:yyyy-MM-dd
* @param date
* @return
*/
public static String getStrDate() {
return getStrDateTime(DateUtil.getDate(), DateTimePattern.shortDatePattern);
}
/**
* 取当前时间的时间格式化字符串,时间格式为:HH:mm:ss
* @param date
* @return
*/
public static String getStrTime() {
return getStrDateTime(DateUtil.getDate(), DateTimePattern.shortTimePattern);
}
/**
* 取格式化的系统当前时间,格式为:yyyy-MM-dd HH:mm:ss
* @return
*/
public static String getStrDateTime() {
return getStrDateTime(DateUtil.getDate());
}
// =================== end 将日期转成字符串 end =================== //
// =================== start 取时间 start =================== //
/**
* 将字符串格式的时间转换成时间对象
* 不建议直接使用此方法,请使用方法:getDate(String dateString, DateTimeFormat dateTimePattern)
* @param dateString
* @param dateFormat
* @return
*/
public static Date getDate(String dateString, String dateFormat) {
if (StringUtils.isEmpty(dateString)) return null;
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
Date date;
try {
date = sdf.parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
return null;
}
return date;
}
/**
* 将字符串格式的时间转换成时间对象
* @param dateString 字符串格式的时间
* @param dateTimePattern 时间的格式
* @return
*/
public static Date getDate(String dateString, DateTimePattern dateTimePattern) {
return getDate(dateString, dateTimePattern.getCode());
}
/**
* 将字符串格式的时间转换成时间对象,时间格式必需为:yyyy-MM-dd
* @param dateString
* @return
*/
public static Date getDate(String dateString) {
return getDate(dateString, DateTimePattern.shortDatePattern);
}
/**
* 将字符串类型日期转换成日期(格式:yyyy-MM-dd hh:mm:ss)
*
* @param dateString
* @return
*/
public static Date getDatetime(String dateString) {
return getDate(dateString, DateTimePattern.shortDateTimePattern);
}
/**
* 将Object类型日期转换成日期
* @param dateObject
* @return
*/
public static Date getDateTime(Object dateObject) {
if (dateObject == null) {
return null;
} else if(dateObject instanceof Date) {
return (Date)dateObject;
} else if(dateObject instanceof Long) {
return new Date((Long)dateObject);
} else if(dateObject instanceof String) {
return getDatetime(String.valueOf(dateObject));
}
return null;
}
// =================== end 取时间 end =================== //
/**
* 将Timestamp类型日期转换成long
* @param timestamp
* @return
*/
public static long getLong(Timestamp timestamp) {
if (timestamp == null)
return 0;
return timestamp.getTime();
}
/**
* 将日期往后推
* 设置日期后会将时、分设置为0
* @param days 要往后推的天数,如果往前推请传入负数
* @return
*/
public static Date getAfterDate(int days) {
Calendar cal = Calendar.getInstance(java.util.Locale.CHINA);
cal.add(Calendar.DATE, -days);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
return cal.getTime();
}
/**
* 取系统默认时区的当前年
*/
public static int getYear() {
// Etc/GMT 是格林威治标准时间,得到的时间和默认时区是一样的
// Etc/GMT+8 比林威治标准时间慢8小时,
// Etc/GMT-8 东八区,我们比那快8小时所以减8
// PRC 设置中国时区
// Calendar.getInstance(TimeZone.getTimeZone("GMT-8:00")).getTime();
Calendar cal = Calendar.getInstance(java.util.Locale.CHINA);
int year = cal.get(Calendar.YEAR); //Calendar.MONTH
return year;
}
/**
* 取系统默认时区的当前月
*/
public static int getMonth() {
// Etc/GMT 是格林威治标准时间,得到的时间和默认时区是一样的
// Etc/GMT+8 比林威治标准时间慢8小时,
// Etc/GMT-8 东八区,我们比那快8小时所以减8
// PRC 设置中国时区
// Calendar.getInstance(TimeZone.getTimeZone("GMT-8:00")).getTime();
Calendar cal = Calendar.getInstance(java.util.Locale.CHINA);
int month = cal.get(Calendar.MONTH) + 1; //Calendar.MONTH
return month;
}
/**
* 取系统默认时区的当前日
* @return
*/
public static int getDay() {
// Etc/GMT 是格林威治标准时间,得到的时间和默认时区是一样的
// Etc/GMT+8 比林威治标准时间慢8小时,
// Etc/GMT-8 东八区,我们比那快8小时所以减8
// PRC 设置中国时区
// Calendar.getInstance(TimeZone.getTimeZone("GMT-8:00")).getTime();
Calendar cal = Calendar.getInstance(java.util.Locale.CHINA);
int date = cal.get(Calendar.DATE); //Calendar.DATE
return date;
}
/**
* 获取传入时间月份的第一天
* @param date
* @return
*/
public static String getMonthFirstDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(firstDate);
}
/**
* 获取传入时间月份的最后一天
* @param date
* @return
*/
public static String getMonthLastDate(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date lastDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(lastDate);
}
/**
* 获取传入时间下个月第一天
* @param dt
* @return
*/
public static String getNextMonthFirstDate(Date dt) {
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.MONTH, 1);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date lastDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(lastDate);
}
/**
* 获取传入时间下一个年份第一天
* @param dt
* @return
*/
public static String getNextYearFirstDate(Date dt) {
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.add(Calendar.YEAR, 1);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(firstDate);
}
/**
* 获取传入时间当前年份第一天
* @param dt
* @return
*/
public static String getYearFirstDate(Date dt) {
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date firstDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(firstDate);
}
/**
* 时间类型的对象转换成字符串类型的时间格式 yyyy-MM-dd HH:mm:ss
*
* @param date
* @return
*/
public static String toString(Date date) {
if (date == null) {
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
/**
* 时间类型的对象转换成字符串类型的时间格式 yyyy-MM-dd HH:mm:ss
*
* @param timestamp
* @return
*/
public static Object toString(Timestamp timestamp) {
if (timestamp == null) {
return "";
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(timestamp);
}
/**
* 两个时间相差距离多少天多少小时多少分多少秒
*
* @param str1
* 时间参数 1 格式:1990-01-01 12:00:00
* @param str2
* 时间参数 2 格式:2009-01-01 12:00:00
* @return long[] 返回值为:{天, 时, 分, 秒}
*/
public static long[] getDistanceTimes(String str1, String str2) {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date one;
Date two;
long day = 0;
long hour = 0;
long min = 0;
long sec = 0;
try {
one = df.parse(str1);
two = df.parse(str2);
long time1 = one.getTime();
long time2 = two.getTime();
long diff;
if (time1 < time2) {
diff = time2 - time1;
} else {
diff = time1 - time2;
}
day = diff / (24 * 60 * 60 * 1000);
hour = (diff / (60 * 60 * 1000) - day * 24);
min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60);
sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
} catch (ParseException e) {
e.printStackTrace();
}
long[] times = { day, hour, min, sec };
return times;
}
/**
* 获得当前输入年月的所有日期
*
* @param year_month
* @author 罗静
* @return
*/
public static List<Object> getAllDate(String year_month) {
List<Object> list = new ArrayList<Object>();
Calendar rightNow = Calendar.getInstance();
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM");
try {
rightNow.setTime(simpleDate.parse(year_month));
} catch (ParseException e) {
e.printStackTrace();
}
int days = rightNow.getActualMaximum(Calendar.DAY_OF_MONTH);
String date = "";
for (int i = 1; i <= days; i++) {
if (i < 10) {
date = year_month + "-0" + i;
} else {
date = year_month + "-" + i;
}
list.add(date);
}
return list;
}
/**
* 获取当前传入日期(yyyy-MM-dd)是星期几
* 修改信息:Miaoshun,2014年12月10日,周日返回7
* @param datetime
* @author 罗静
* @return
*/
public static int getWeekdayOfDateTime(Date datetime) {
Calendar c = Calendar.getInstance();
try {
c.setTime(datetime);
} catch (Exception e) {
e.printStackTrace();
}
int weekday = c.get(Calendar.DAY_OF_WEEK) - 1;
// 星期天
if (weekday == 0) {
weekday = 7;
}
return weekday;
}
/**
* 获取星期天数
* @return
*/
public static int getWeekday() {
Calendar c = Calendar.getInstance();
int weekday = c.get(Calendar.DAY_OF_WEEK) - 1;
// 星期天
if (weekday == 0) {
weekday = 7;
}
return weekday;
}
/**
* 获取传入日期所在周期,星期一的时间
* @param dt
* @return
*/
public static String getWeek1day(Date dt){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK,2);
Date firstDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(firstDate);
}
/**
* 获取传入时间,下一个周一的日期
* @param dt
* @return
*/
public static String getNextWeek1day(Date dt){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK,2);
cal.add(Calendar.DAY_OF_MONTH,7);
Date firstDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(firstDate);
}
/**
* 获取传入日期所在周期,星期日的时间
* @param dt
* @return
*/
public static String getWeek0day(Date dt){
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
cal.set(Calendar.DAY_OF_WEEK,1);
Date firstDate = cal.getTime();
SimpleDateFormat sf = new SimpleDateFormat("YYYY-MM-dd");
return sf.format(firstDate);
}
/**
* 获取当前传入日期的前n天日期集合
*
* @param datetime
* ,n
* @author 罗静
* @return
*/
public static List<String> getDateBefore(Date date, int n) {
List<String> dateList = new ArrayList<String>();
Calendar now = Calendar.getInstance();
for (int i = n; i > 0; i--) {
now.setTime(date);
now.set(Calendar.DATE, now.get(Calendar.DATE) - i);
Date beforeDate = now.getTime();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
dateList.add(format.format(beforeDate));
}
return dateList;
}
/**
* 获取当前传入日期的周一、周日两天的日期集合
*
* @param datetime
* @author 罗静
* @return
*/
public static List<String> getWeekDate(String datetime) {
List<String> list = new ArrayList<String>();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
try {
cal.setTime(df.parse(datetime));
} catch (ParseException e) {
e.printStackTrace();
}
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 获取本周一的日期
list.add(df.format(cal.getTime()));
// 这种输出的是上个星期周日的日期,因为老外那边把周日当成第一天
cal.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
// 增加一个星期,才是我们中国人理解的本周日的日期
cal.add(Calendar.WEEK_OF_YEAR, 1);
list.add(df.format(cal.getTime()));
return list;
}
/**
* 以当前时间为基准,按天进行偏移
* @param day 需要偏移的天数,负值为往后偏移,正值为往前偏移
* @return
*/
public static Date offsetByDay(int day) {
Date dt = DateUtil.getDate();
Calendar date = Calendar.getInstance();
date.setTime(dt);
date.add(Calendar.DAY_OF_MONTH, day);
return date.getTime();
}
/**
* 取时间的按天进行偏移之后的时间
* @param dt 基准时间
* @param day 偏移的天数
* @return
*/
public static Date offsetByDay(Date dt , int day) {
Calendar date = Calendar.getInstance();
date.setTime(dt);
date.add(Calendar.DAY_OF_MONTH, day);
return date.getTime();
}
/**
* 取时间的按天进行偏移之后的时间
* @param date 基准时间
* @param day 偏移的天数
* @return
*/
public static Date offsetByDay(String date , int day) {
return offsetByDay(getDate(date), day);
}
/**
* 获取当前传入的日期、星期几、最近的上一个星期几来获取最近的上一个星期几所对应的日期
*
* @param datetime
* @param weekname1
* 时间参数格式:1 表示星期一
* @param weekname2
* 时间参数格式:2 表示最近的上一个星期二
* @author 牛逢路
* @return
*/
public static String getDateByWeekName(String datetime, int weekname1,
int weekname2) {
String lastDate = "";
SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = dateFmt.parse(datetime);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
if (weekname2 < weekname1) {
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)
- (weekname1 - weekname2));
} else {
cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)
- (7 - (weekname2 - weekname1)));
}
lastDate = dateFmt.format(cal.getTime());
return lastDate;
}
/**
* 将UTC(Sun Jan 09 2011 00:00:00 GMT 0800)格式时间转换成yyyy-MM-dd
*
* @param utctime
* utc格式的时间
* @return String yyyy-MM-dd格式时间
* @author 罗静
*/
public static String formatUTCToDate(String utctime) {
String fmtDate = "";
if (utctime == null || utctime.trim().length() == 0) {
return fmtDate;
}
// 把utc的年取出来
String year = "";
SimpleDateFormat smtReturn = new SimpleDateFormat("MM-dd");
;
SimpleDateFormat sfmTurn = null;
if (utctime.length() > 4) {
if (utctime.indexOf("UTC") >= 0) {
year = utctime.substring(utctime.length() - 4);
sfmTurn = new SimpleDateFormat("EEE MMM dd HH:mm:ss", Locale.US);
} else if (utctime.indexOf("GMT") >= 0) {
year = utctime.substring(11, 15);
sfmTurn = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss",
Locale.US);
} else {
return utctime;
}
}
// 先将utc时间转换成mm-dd
try {
Date date = sfmTurn.parse(utctime);
String md = smtReturn.format(date);
fmtDate = year + "-" + md;
} catch (ParseException e) {
e.printStackTrace();
}
return fmtDate;
}
/**
* 获取当前传入日期的前1天日期
*
* @param strdate
* @author 罗静
* @return
*/
public static String getBeforeDay(String strdate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String reStr = "";
try {
Date dt = sdf.parse(strdate);
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(dt);
rightNow.add(Calendar.DAY_OF_YEAR, -1);// 日期减1天
Date dt1 = rightNow.getTime();
reStr = sdf.format(dt1);// 昨天
} catch (ParseException e) {
e.printStackTrace();
}
return reStr;
}
/**
* 获取当前传入日期的前一个月的日期
*
* @param datetime
* @author 罗静
* @return
*/
public static String getBeforeMonth(String strdate) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String reStr = "";
try {
Date dt = sdf.parse(strdate);
Calendar rightNow = Calendar.getInstance();
rightNow.setTime(dt);
rightNow.add(Calendar.MONTH, -1);// 日期减1个月
Date dt1 = rightNow.getTime();
reStr = sdf.format(dt1);// 昨天
} catch (ParseException e) {
e.printStackTrace();
}
return reStr;
}
/**
* 获取当前日期下一天
* @return
*/
public static String getAfterDate() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date date = calendar.getTime();
return sdf.format(date);
}
/**
* 日期推算
*
* @param year 将日期加上指定的年数
* @param month 将日期加上指定的月数
* @param day 将日期加上指定的天数
* @return
*/
public static Date getAfterDate(Date date, int year, int month, int day) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
if(year != 0) calendar.add(Calendar.YEAR, year);
if(month != 0) calendar.add(Calendar.MONTH, month);
if(day != 0) calendar.add(Calendar.DAY_OF_YEAR, day);
return calendar.getTime();
}
/**
* 时间推算
* @param date
* @param year
* @param month
* @param day
* @param hour
* @param minute
* @param second
* @return
*/
public static Date getAfterDateTime(Date date, int year, int month, int day, int hour, int minute, int second) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.YEAR, year);
calendar.add(Calendar.MONTH, month);
calendar.add(Calendar.DAY_OF_YEAR, day);
// 时分秒
calendar.add(Calendar.HOUR_OF_DAY, hour);
calendar.add(Calendar.MINUTE, minute);
calendar.add(Calendar.SECOND, second);
return calendar.getTime();
}
/**
* 取日期时间对象
* @param year
* @param month
* @param date
* @return
*/
public static Date getDate(Integer year, Integer month, Integer date) {
if(year == null) {
year = 1970;
}
if(month == null) {
month = 1;
}
if(date == null) {
date = 1;
}
Calendar calendar = Calendar.getInstance();
calendar.set(year, month-1, date, 0, 0, 0);
return calendar.getTime();
}
/**
* 取今天开始时 yyyy-MM-dd 00:00:00
* @return
*/
public static String getTodayStart() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
return sdf.format(new Date());
}
/**
* 取今天结束时 yyyy-MM-dd 23:59:59
* @return
*/
public static String getTodayEnd() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
return sdf.format(new Date());
}
/**
* 比较两个时间的大小,若DATE1>=DATE2则true,否则false,
* @param DATE1
* @param DATE2
* @return
*/
public static boolean compareDate(Date date1, Date date2) {
Calendar calendar= Calendar.getInstance(); //初始化日历对象
calendar.setTime(date1);
long timeOne= calendar.getTimeInMillis();
calendar.setTime(date2);
long timeTwo= calendar.getTimeInMillis();
if(timeOne >= timeTwo){
return true;
}
return false;
}
/**
* 比较两个日期时间的大小
*
* @param date1
* @param date2
* @return
*/
public static int compareByDate(Date date1, Date date2) {
String str1 = getStrDateTime(date1, "yyyy-MM-dd HH:mm:ss");
String str2 = getStrDateTime(date2, "yyyy-MM-dd HH:mm:ss");
return str1.compareTo(str2);
}
/**
* 比较两个日期的大小
*
* @param date1
* @param date2
* @return
*/
public static int compareByDay(Date date1, Date date2) {
String str1 = getStrDateTime(date1, "yyyy-MM-dd");
String str2 = getStrDateTime(date2, "yyyy-MM-dd");
return str1.compareTo(str2);
}
/**
* 把某日期时间加上一些时分秒。现应用于跨日统计时间
* @param date
* @param hhMMss 格式 08:30:00
* @return
*/
public static Date addHHMMSS(Date date, String hhMMss) {
if(hhMMss==null) return date;
int delay_hour=0;
int delay_minute=0;
int delay_second=0;
if(hhMMss!=null){
try{
String[] hms=hhMMss.split(":");
delay_hour=Integer.parseInt(hms[0]);
delay_minute=Integer.parseInt(hms[1]);
delay_second=Integer.parseInt(hms[2]);
}catch(Exception e){}
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR_OF_DAY, delay_hour);
calendar.add(Calendar.MINUTE, delay_minute);
calendar.add(Calendar.SECOND, delay_second);
return calendar.getTime();
}
/**
* 获取指定时间段内相差的年数
* @param date1
* @param date2
* @return
*/
public static int diffInYears(Date date1, Date date2) {
if(date1==null) {
date1 = new Date();
}
if(date2==null) {
date2 = date1;
}
Calendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date2);
int c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR));
return c;
}
/**
* 获取指定时间段内相差的月份数
* @param date1
* @param date2
* @return
*/
public static int diffInMonths(Date date1, Date date2) {
if(date1==null) {
date1 = new Date();
}
if(date2==null) {
date2 = date1;
}
Calendar cal1 = new GregorianCalendar();
cal1.setTime(date1);
Calendar cal2 = new GregorianCalendar();
cal2.setTime(date2);
int c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH);
return c;
}
/**
* 获取指定时间段内相差的天数
* @param date1
* @param date2
* @return
* @throws Exception
*/
public static long diffInDays(Date date1, Date date2) {
if(date1==null) {
date1 = new Date();
}
if(date2==null) {
date2 = date1;
}
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String str1 = getStrDateTime(date1, "yyyy-MM-dd");
String str2 = getStrDateTime(date2, "yyyy-MM-dd");
long to = 0;
long from = 0;
try {
to = df.parse(str1).getTime();
from = df.parse(str2).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
long diff = (to - from) / (1000 * 60 * 60 * 24);
return diff;
}
/**
* 获取两个时间段内的秒数
* date1 - date2
* @param date1
* @param date2
* @return
*/
public static long diffInSeconds(Date date1, Date date2) {
if(date1==null) {
date1 = new Date();
}
if(date2==null) {
date2 = date1;
}
long d1 = date1 == null ? 0 : date1.getTime();
long d2 = date2 == null ? 0 : date2.getTime();
return (long) Math.ceil((d1 - d2) / (double) 1000);
}
/**
* 获取两个时间段内的分钟数
* @param date1
* @param date2
* @return
*/
public static long diffInMinutes(Date date1, Date date2) {
long d1 = date1 == null ? 0 : date1.getTime();
long d2 = date2 == null ? 0 : date2.getTime();
return (long) Math.ceil((d1 - d2) / (double) 60000);
}
/**
* 取某年某月的最后一天的日期
* @param year
* @param month
* @return
*/
public static Date getMonthLastDate(int year, int month) {
Calendar cal = Calendar.getInstance();
// 不加下面2行,就是取当前时间前一个月的第一天及最后一天
cal.set(Calendar.YEAR, year);
cal.set(Calendar.MONTH, month);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DAY_OF_MONTH, -1);
Date lastDate = cal.getTime();
return lastDate;
}
/**
* 根据年、月获取对应月份天数
* @param year
* @param month
* @return
*/
public static int getDaysByYearMonth(int year, int month) {
Calendar a = Calendar.getInstance();
a.set(Calendar.YEAR, year);
a.set(Calendar.MONTH, month - 1);
a.set(Calendar.DATE, 1);
a.roll(Calendar.DATE, -1);
int maxDate = a.get(Calendar.DATE);
return maxDate;
}
/**
* 取时间类型
* @param start_time hh:MM:ss
* @return
*/
public static Date getTime(String start_time) {
String str = "1970-01-01 " + start_time;
return DateUtil.getDatetime(str);
}
}
| 23.606174
| 127
| 0.641569
|
4405375b8e3fafc360483711ac93882e7bd891a8
| 2,424
|
package xyz.zpayh.ageraView.click;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.view.View;
import com.google.android.agera.Observable;
import com.google.android.agera.Updatable;
import java.util.concurrent.Executor;
import static com.google.android.agera.Preconditions.checkNotNull;
import static com.google.android.agera.Preconditions.checkState;
/**
* Created by Administrator on 2016/10/24.
*/
public final class ClickCompiler implements
ClickCompilerStates.RClickView,
ClickCompilerStates.RFrequency,
ClickCompilerStates.RFlow,
ClickCompilerStates.RConfig{
private static final ThreadLocal<ClickCompiler> compilers = new ThreadLocal<>();
@NonNull
public static ClickCompilerStates.RClickView compiler(){
checkState(Looper.myLooper() != null, "Can only be compiler on a Looper thread");
ClickCompiler compiler = compilers.get();
if (compiler == null){
compiler = new ClickCompiler();
} else {
compilers.set(null);
}
return compiler;
}
private static void recycle(@NonNull final ClickCompiler compiler){
compilers.set(compiler);
}
private ClickCompiler(){
this.view = null;
this.frequency = 0;
this.executor = null;
}
private int frequency;
private View view;
private Executor executor;
@NonNull
@Override
public ClickCompiler click(@NonNull View view) {
this.view = checkNotNull(view);
return this;
}
@NonNull
@Override
public ClickCompiler goTo(@NonNull Executor executor) {
this.executor = checkNotNull(executor);
return this;
}
@NonNull
@Override
public ClickCompiler onUpdatesPer(int millis) {
frequency = Math.max(0,millis);
return this;
}
@NonNull
@Override
public Observable compile() {
Observable observable = compileObservableAndReset();
recycle(this);
return observable;
}
@Override
public void addUpdatable(@NonNull Updatable updatable) {
Observable observable = compile();
observable.addUpdatable(updatable);
}
private Observable compileObservableAndReset() {
Observable observable = new ClickObservable(view,executor,frequency);
view = null;
frequency = 0;
return observable;
}
}
| 24.989691
| 89
| 0.67038
|
0644896647953e3c8ecd4d9c28743d72e7e1bae6
| 2,511
|
package ca.quadrilateral.jobsmarts.mail;
import java.util.Collection;
import java.util.stream.Collectors;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import javax.mail.MessagingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.stringtemplate.v4.ST;
import org.stringtemplate.v4.STGroup;
import org.stringtemplate.v4.STGroupString;
import ca.quadrilateral.jobsmarts.api.Job;
import ca.quadrilateral.jobsmarts.data.api.IUserDataService;
public class NewJobMailHandler {
private static final Logger logger = LoggerFactory.getLogger(NewJobMailHandler.class);
private static final String templateText =
"subject(job) ::= \"New Job Posted: $job.jobSummary.jobTitle$ - $job.jobSummary.companyName$\" " +
"message(job) ::= \"<html><head></head><body>" +
"<table border='1'>" +
" <tr><td>Job Title</td><td>$job.jobSummary.jobTitle$</td></tr>" +
" <tr><td>Date Posted</td><td>$job.jobDetails.datePosted$</td></tr>" +
" $job.jobDetails.fields.keys:{k | <tr><td>$k$</td><td>$job.jobDetails.fields.(k)$</td></tr>}$" +
"</table>" +
"$job.jobDetails.descriptionHtml$" +
"</body></html>\" ";
;
private static final STGroup stGroup = new STGroupString("<string", templateText, '$', '$');
@Inject
private IUserDataService userDataService;
@Inject
private MailSender mailSender;
public void handleNewJob(@Observes final Job newJob) {
final ST messageSubjectTemplate = stGroup.getInstanceOf("subject");
final ST messageBodyTemplate = stGroup.getInstanceOf("message");
messageSubjectTemplate.add("job", newJob);
messageBodyTemplate.add("job", newJob);
final String messageSubject = messageSubjectTemplate.render();
final String messageBody = messageBodyTemplate.render();
try {
mailSender.sendMailMessage(getEmailAddressesToSendTo(), messageSubject, messageBody);
} catch (final MessagingException e) {
logger.warn("Error sending new job mail message with subject: {}", messageSubject, e);
}
}
private Collection<String> getEmailAddressesToSendTo() {
return userDataService
.getAllUsers()
.stream()
.map(user -> user.getEmail())
.collect(Collectors.toList());
}
}
| 36.926471
| 112
| 0.637196
|
2c7cd939e1aa876cd152ffeeeea12421e4024e51
| 750
|
class Solution {
public String[] findRestaurant(String[] list1, String[] list2) {
String[] temp = new String[1005];
Map<String, Integer> pos = new HashMap<>();
int Min = 2000, sz = 0;
for (int i = 0; i < list1.length; i++) {
pos.put(list1[i], i);
}
for (int i = 0; i < list2.length; i++) {
if(pos.get(list2[i]) != null){
int cur = pos.get(list2[i]) + i;
if(cur < Min){
Min = cur;
sz = 0;
temp[sz++] = list2[i];
} else if(cur == Min){
temp[sz++] = list2[i];
}
}
}
return Arrays.copyOf(temp, sz);
}
}
| 32.608696
| 68
| 0.393333
|
31b2d03a5bc357bccc877f6909571ba35309fdaf
| 16,629
|
package datawave.query.jexl;
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import datawave.query.attributes.ValueTuple;
import datawave.query.jexl.nodes.TreeHashNode;
import datawave.query.jexl.visitors.TreeHashVisitor;
import org.apache.commons.jexl2.Interpreter;
import org.apache.commons.jexl2.JexlContext;
import org.apache.commons.jexl2.JexlEngine;
import org.apache.commons.jexl2.JexlException;
import org.apache.commons.jexl2.parser.ASTAndNode;
import org.apache.commons.jexl2.parser.ASTEQNode;
import org.apache.commons.jexl2.parser.ASTERNode;
import org.apache.commons.jexl2.parser.ASTFunctionNode;
import org.apache.commons.jexl2.parser.ASTGENode;
import org.apache.commons.jexl2.parser.ASTGTNode;
import org.apache.commons.jexl2.parser.ASTIdentifier;
import org.apache.commons.jexl2.parser.ASTLENode;
import org.apache.commons.jexl2.parser.ASTLTNode;
import org.apache.commons.jexl2.parser.ASTMethodNode;
import org.apache.commons.jexl2.parser.ASTOrNode;
import org.apache.commons.jexl2.parser.ASTReference;
import org.apache.commons.jexl2.parser.ASTReferenceExpression;
import org.apache.commons.jexl2.parser.ASTSizeMethod;
import org.apache.commons.jexl2.parser.JexlNode;
import org.apache.log4j.Logger;
import com.google.common.collect.Maps;
import datawave.query.collections.FunctionalSet;
import datawave.query.jexl.functions.QueryFunctions;
/**
* Extended so that calls to a function node, which can return a collection of 'hits' instead of a Boolean, can be evaluated as true/false based on the size of
* the hit collection. Also, if the member 'arithmetic' has been set to a HitListArithmetic, then the returned hits will be added to the hitSet of the
* arithmetic.
*
* Also added in the ability to count attributes pulled from the ValueTuples which contribute to the positive evaluation.
*/
public class DatawaveInterpreter extends Interpreter {
protected Map<TreeHashNode,Object> resultMap;
private static final Logger log = Logger.getLogger(DatawaveInterpreter.class);
public DatawaveInterpreter(JexlEngine jexl, JexlContext aContext, boolean strictFlag, boolean silentFlag) {
super(jexl, aContext, strictFlag, silentFlag);
resultMap = Maps.newHashMap();
}
/**
* This convenience method can be used to interpret the result of the script.execute() result which calls the interpret method below.
*
* @param scriptExecuteResult
* @return true if we matched, false otherwise.
*/
public static boolean isMatched(Object scriptExecuteResult) {
boolean matched = false;
if (scriptExecuteResult != null && Boolean.class.isAssignableFrom(scriptExecuteResult.getClass())) {
matched = (Boolean) scriptExecuteResult;
} else if (scriptExecuteResult != null && Collection.class.isAssignableFrom(scriptExecuteResult.getClass())) {
// if the function returns a collection of matches, return true/false
// based on the number of matches
Collection<?> matches = (Collection<?>) scriptExecuteResult;
matched = (!matches.isEmpty());
} else {
if (log.isDebugEnabled()) {
log.debug("Unable to process non-Boolean result from JEXL evaluation '" + scriptExecuteResult);
}
}
return matched;
}
@Override
public Object visit(ASTFunctionNode node, Object data) {
TreeHashNode hash = TreeHashVisitor.getNodeHash(node);
Object result = resultMap.get(hash);
if (null != result) {
return result;
}
result = super.visit(node, data);
if (this.arithmetic instanceof HitListArithmetic) {
HitListArithmetic hitListArithmetic = (HitListArithmetic) arithmetic;
Set<String> hitSet = hitListArithmetic.getHitSet();
if (hitSet != null && result instanceof Collection<?>) {
for (Object o : ((Collection<?>) result)) {
if (o instanceof ValueTuple) {
hitListArithmetic.add((ValueTuple) o);
}
}
}
}
// if the function stands alone, then it needs to return ag boolean
// if the function is paired with a method that is called on its results (like 'size') then the
// actual results must be returned.
if (hasSiblings(node)) {
resultMap.put(hash, result);
return result;
}
resultMap.put(hash, result instanceof Collection ? !((Collection) result).isEmpty() : result);
return result instanceof Collection ? !((Collection) result).isEmpty() : result;
}
/**
* Triggered when variable can not be resolved.
*
* @param xjexl
* the JexlException ("undefined variable " + variable)
* @return throws JexlException if strict, null otherwise
*/
@Override
protected Object unknownVariable(JexlException xjexl) {
if (strict) {
throw xjexl;
}
// do not warn
return null;
}
@Override
public Object visit(ASTEQNode node, Object data) {
TreeHashNode hash = TreeHashVisitor.getNodeHash(node);
Object result = resultMap.get(hash);
if (null != result)
return result;
result = super.visit(node, data);
resultMap.put(hash, result);
return result;
}
@Override
public Object visit(ASTERNode node, Object data) {
TreeHashNode hash = TreeHashVisitor.getNodeHash(node);
Object result = resultMap.get(hash);
if (null != result)
return result;
result = super.visit(node, data);
resultMap.put(hash, result);
return result;
}
/**
* unused because hasSiblings should cover every case with the size method, plus other methods
*
* @param node
* @return
*/
private boolean hasSizeMethodSibling(ASTFunctionNode node) {
JexlNode parent = node.jjtGetParent();
for (int i = 0; i < parent.jjtGetNumChildren(); i++) {
JexlNode kid = parent.jjtGetChild(i);
if (kid instanceof ASTSizeMethod) {
return true;
}
}
return false;
}
public Object visit(ASTMethodNode node, Object data) {
if (data == null) {
data = new FunctionalSet(); // an empty set
}
return super.visit(node, data);
}
public Object visit(ASTOrNode node, Object data) {
FunctionalSet leftFunctionalSet = null;
FunctionalSet rightFunctionalSet = null;
Object left = node.jjtGetChild(0).jjtAccept(this, data);
if (left == null)
left = FunctionalSet.empty();
if (left instanceof Collection == false) {
try {
boolean leftValue = arithmetic.toBoolean(left);
if (leftValue) {
return Boolean.TRUE;
}
} catch (ArithmeticException xrt) {
throw new JexlException(node.jjtGetChild(0), "boolean coercion error", xrt);
}
} else {
if (leftFunctionalSet == null)
leftFunctionalSet = new FunctionalSet();
leftFunctionalSet.addAll((Collection) left);
}
Object right = node.jjtGetChild(1).jjtAccept(this, data);
if (right == null)
right = FunctionalSet.empty();
if (right instanceof Collection == false) {
try {
boolean rightValue = arithmetic.toBoolean(right);
if (rightValue) {
return Boolean.TRUE;
}
} catch (ArithmeticException xrt) {
throw new JexlException(node.jjtGetChild(1), "boolean coercion error", xrt);
}
} else {
if (rightFunctionalSet == null)
rightFunctionalSet = new FunctionalSet();
rightFunctionalSet.addAll((Collection) right);
}
// when an identifier is expanded by the data model within a Function node, the results of the matches
// for both (all?) fields must be gathered into a single collection to be returned.
if (leftFunctionalSet != null && rightFunctionalSet != null) { // add left and right
FunctionalSet functionalSet = new FunctionalSet(leftFunctionalSet);
functionalSet.addAll(rightFunctionalSet);
return functionalSet;
} else if (leftFunctionalSet != null) {
return leftFunctionalSet;
} else if (rightFunctionalSet != null) {
return rightFunctionalSet;
} else {
return getBooleanOr(left, right);
}
}
private JexlNode dereference(JexlNode node) {
while (node.jjtGetNumChildren() == 1 && (node instanceof ASTReferenceExpression || node instanceof ASTReference)) {
node = node.jjtGetChild(0);
}
return node;
}
/**
* * This will determine if this ANDNode contains a range, and will invoke the appropriate range function instead of evaluating the LT/LE and GT/GE nodes *
* independently as that does not work when there are sets of values in the context. * * @param node * @return a collection of hits (or empty set) if we
* evaluated a range. null otherwise.
*/
private Collection<?> evaluateRange(ASTAndNode node) {
Collection<?> evaluation = null;
JexlNode left = node.jjtGetChild(0);
JexlNode right = node.jjtGetChild(1);
if (left instanceof ASTLENode || left instanceof ASTLTNode) {
JexlNode temp = left;
left = right;
right = temp;
}
if ((left instanceof ASTGENode || left instanceof ASTGTNode) && (right instanceof ASTLENode || right instanceof ASTLTNode)) {
JexlNode leftIdentifier = dereference(left.jjtGetChild(0));
JexlNode rightIdentifier = dereference(right.jjtGetChild(0));
if (leftIdentifier instanceof ASTIdentifier && rightIdentifier instanceof ASTIdentifier) {
String fieldName = leftIdentifier.image;
if (fieldName.equals(rightIdentifier.image)) {
Object fieldValue = leftIdentifier.jjtAccept(this, null);
Object leftValue = left.jjtGetChild(1).jjtAccept(this, null);
boolean leftInclusive = left instanceof ASTGENode;
Object rightValue = right.jjtGetChild(1).jjtAccept(this, null);
boolean rightInclusive = right instanceof ASTLENode;
if (leftValue instanceof Number && rightValue instanceof Number) {
if (fieldValue instanceof Collection) {
evaluation = QueryFunctions.between((Collection) fieldValue, ((Number) leftValue).floatValue(), leftInclusive,
((Number) rightValue).floatValue(), rightInclusive);
} else {
evaluation = QueryFunctions.between(fieldValue, ((Number) leftValue).floatValue(), leftInclusive,
((Number) rightValue).floatValue(), rightInclusive);
}
} else {
if (fieldValue instanceof Collection) {
evaluation = QueryFunctions.between((Collection) fieldValue, String.valueOf(leftValue), leftInclusive, String.valueOf(rightValue),
rightInclusive);
} else {
evaluation = QueryFunctions.between(fieldValue, String.valueOf(leftValue), leftInclusive, String.valueOf(rightValue),
rightInclusive);
}
}
if (this.arithmetic instanceof HitListArithmetic) {
HitListArithmetic hitListArithmetic = (HitListArithmetic) arithmetic;
Set<String> hitSet = hitListArithmetic.getHitSet();
if (hitSet != null) {
hitSet.addAll((Collection<String>) evaluation);
}
}
}
}
}
return evaluation;
}
public Object visit(ASTAndNode node, Object data) {
// check for the special case of a range (conjunction of a G/GE and a L/LE node) and reinterpret as a function
Object evaluation = evaluateRange(node);
if (evaluation != null) {
return evaluation;
}
FunctionalSet leftFunctionalSet = null;
FunctionalSet rightFunctionalSet = null;
Object left = node.jjtGetChild(0).jjtAccept(this, data);
if (left == null)
left = FunctionalSet.empty();
if (left instanceof Collection == false) {
try {
boolean leftValue = arithmetic.toBoolean(left);
if (!leftValue) {
return Boolean.FALSE;
}
} catch (RuntimeException xrt) {
throw new JexlException(node.jjtGetChild(0), "boolean coercion error", xrt);
}
} else {
if (leftFunctionalSet == null)
leftFunctionalSet = new FunctionalSet();
leftFunctionalSet.addAll((Collection) left);
}
Object right = node.jjtGetChild(1).jjtAccept(this, data);
if (right == null)
right = FunctionalSet.empty();
if (right instanceof Collection == false) {
try {
boolean rightValue = arithmetic.toBoolean(right);
if (!rightValue) {
return Boolean.FALSE;
}
} catch (ArithmeticException xrt) {
throw new JexlException(node.jjtGetChild(1), "boolean coercion error", xrt);
}
} else {
if (rightFunctionalSet == null)
rightFunctionalSet = new FunctionalSet();
rightFunctionalSet.addAll((Collection) right);
}
// return union of left and right iff they are both non-null & non-empty
if (leftFunctionalSet != null && rightFunctionalSet != null) {
if (!leftFunctionalSet.isEmpty() && !rightFunctionalSet.isEmpty()) {
FunctionalSet functionalSet = new FunctionalSet(leftFunctionalSet);
functionalSet.addAll(rightFunctionalSet);
return functionalSet;
} else {
return Boolean.FALSE;
}
} else {
return getBooleanAnd(left, right);
}
}
/** {@inheritDoc} */
public Object visit(ASTSizeMethod node, Object data) {
if (data != null) {
return super.visit(node, data);
} else {
return 0;
}
}
// this handles the case where one side is a boolean and the other is a collection
private boolean getBooleanAnd(Object left, Object right) {
if (left instanceof Collection) {
left = ((Collection) left).isEmpty() == false;
}
if (right instanceof Collection) {
right = ((Collection) right).isEmpty() == false;
}
return arithmetic.toBoolean(left) && arithmetic.toBoolean(right);
}
private boolean getBooleanOr(Object left, Object right) {
if (left instanceof Collection) {
left = ((Collection) left).isEmpty() == false;
}
if (right instanceof Collection) {
right = ((Collection) right).isEmpty() == false;
}
return arithmetic.toBoolean(left) || arithmetic.toBoolean(right);
}
/**
* a function node that has siblings has a method paired with it, like the size method in includeRegex(foo,bar).size() It must return its collection of
* results for the other method to use, instead of a boolean indicating that there were results
*
* @param node
* @return
*/
private boolean hasSiblings(ASTFunctionNode node) {
JexlNode parent = node.jjtGetParent();
if (parent.jjtGetNumChildren() > 1) {
return true;
}
JexlNode grandparent = parent.jjtGetParent();
if (grandparent instanceof ASTMethodNode) {
return true;
}
return false;
}
}
| 41.88665
| 159
| 0.598773
|
a14828f74adb8faa10b19d7c2be006ef860c14f3
| 1,042
|
package polsl.pblserverapp.model;
import lombok.Data;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.List;
@Data
public class Task
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long taskId;
private String creationDate;
private String creationHour;
private Shape shape;
private String ownerUsername;
private Long ownerId;
private String selectedQueueName;
private List<String> argsValues;
@Override
public String toString() {
return "Task{" +
"taskId=" + taskId +
", creationDate='" + creationDate + '\'' +
", creationHour='" + creationHour + '\'' +
", shape=" + shape +
", ownerUsername='" + ownerUsername + '\'' +
", ownerId=" + ownerId +
", selectedQueueName='" + selectedQueueName + '\'' +
", argsValues=" + argsValues +
'}';
}
}
| 27.421053
| 68
| 0.586372
|
6df1cbe515486f268bc795ed8d8f806c7ed32edf
| 535
|
/*
* 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.
*/
import javax.swing.*;
import java.awt.*;
/**
*
* @author kuda
*/
public class ImageBackgroundPanel extends JPanel{
private ImageIcon bgImage;
public ImageBackgroundPanel(ImageIcon bgImage) {
this.bgImage = bgImage;
}
public void paintComponent(Graphics g) {
g.drawImage(bgImage.getImage(), 0, 0 ,this);
}
}
| 25.47619
| 80
| 0.685981
|
c66041888ed9a63857405d9da47170868165fac4
| 772
|
package com.mowen.designpattern.proxy;
import java.rmi.Naming;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
/**
* Created by mowen on 4/10/16.
*/
public class GumballMachineTestDrive {
public static void main(String[] args) {
try {
LocateRegistry.createRegistry(8888);
GumballMachineRemote gumballMachine = new com.mowen.designpattern.proxy.state.GumballMachine("NewYork", 3);
Naming.bind("rmi://localhost:8888/NYGM", gumballMachine);
gumballMachine = new com.mowen.designpattern.proxy.state.GumballMachine("Chicago", 2);
Naming.bind("rmi://localhost:8888/CGGM", gumballMachine);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 28.592593
| 119
| 0.665803
|
d6127aa3ada9b87a34f9846d926b10dfe80d0813
| 1,404
|
package com.dexburger.configurations;
import java.util.Collections;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.google.common.base.Predicates;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Tag;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = { SwaggerConfiguration.BASE_PACKAGE })
public class SwaggerConfiguration {
public static final String BASE_PACKAGE = "com.dexburger";
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.basePackage(BASE_PACKAGE)).paths(PathSelectors.any())
.paths(Predicates.not(PathSelectors.regex("/error.*"))).build()
.apiInfo(apiInfo()).tags(new Tag("Cardapio", ""), new Tag("Pedidos", ""));
}
private ApiInfo apiInfo() {
return new ApiInfo("DexBurgerAPI", "DexBurgerAPI", "1.0", "", ApiInfo.DEFAULT_CONTACT,
"MIT License", "https://mit-license.org", Collections.emptyList());
}
}
| 35.1
| 88
| 0.794872
|
a00a40908709358bd324e8b5da9a409a754db4df
| 2,401
|
package com.xt.leetcode;
import java.util.*;
/**
* 5.最长回文子串
* 给你一个字符串 s,找到 s 中最长的回文子串。
* done
* 时间复杂度O(n*log(n))
*/
public class Solution5 {
HashMap<Integer, List<Integer>> indexMap = new HashMap<>();
String reverseStr = "";
String str = "";
public String longestPalindrome(String s) {
char[] chars = s.toCharArray();
str = s;
//循环一遍,得出每个字符的位置
StringBuilder builder = new StringBuilder();
for (int i = 0; i < chars.length; i++) {
int aChar = chars[i];
List<Integer> integers = indexMap.computeIfAbsent(aChar, k -> new ArrayList<>());
integers.add(i);
builder.insert(0, (char) aChar);
}
reverseStr = builder.toString();
int maxLength = 0;
String maxStr = "";
String currentStr = "";
for (int i = 0; i < chars.length; i++) {
int aChar = chars[i];
List<Integer> integers = indexMap.get(aChar);
if (integers.size() == 1) {
currentStr = s.substring(integers.get(0), integers.get(0) + 1);
if (currentStr.length() > maxLength) {
maxLength = currentStr.length();
maxStr = currentStr;
}
continue;
}
for (int k = integers.size() - 1; k >= 0; k--) {
Integer end = integers.get(k);
if (i >= end) {
break;
}
boolean paindrome = isPaindrome(str, reverseStr, i, end);
if (paindrome) {
currentStr = str.substring(i, end + 1);
if (currentStr.length() > maxLength) {
maxLength = currentStr.length();
maxStr = currentStr;
}
break;
}
}
}
return maxStr;
}
/**
* 判断是否回文子串
*
* @param str 当前字符串
* @param startIndex
* @param endIndex
* @return
*/
public boolean isPaindrome(String str, String reverseStr, int startIndex, int endIndex) {
String substring1 = str.substring(startIndex, endIndex + 1);
String substring2 = reverseStr.substring(str.length() - endIndex - 1, str.length() - startIndex - 1 + 1);
return substring1.equals(substring2);
}
}
| 31.592105
| 113
| 0.491045
|
67c4bca5e35eb3d96928c12a3386cdd57296dd25
| 34,706
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|llap
operator|.
name|cli
operator|.
name|service
package|;
end_package
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|base
operator|.
name|Preconditions
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|collect
operator|.
name|ImmutableSet
import|;
end_import
begin_import
import|import
name|jline
operator|.
name|TerminalFactory
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Arrays
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Properties
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Set
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|CommandLine
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|GnuParser
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|HelpFormatter
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|Option
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|OptionBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|Options
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|commons
operator|.
name|cli
operator|.
name|ParseException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|conf
operator|.
name|HiveConf
operator|.
name|ConfVars
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|hive
operator|.
name|llap
operator|.
name|log
operator|.
name|LogHelpers
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|Logger
import|;
end_import
begin_import
import|import
name|org
operator|.
name|slf4j
operator|.
name|LoggerFactory
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|util
operator|.
name|StringUtils
operator|.
name|TraditionalBinaryPrefix
import|;
end_import
begin_class
annotation|@
name|SuppressWarnings
argument_list|(
literal|"static-access"
argument_list|)
class|class
name|LlapServiceCommandLine
block|{
specifier|private
specifier|static
specifier|final
name|Logger
name|LOG
init|=
name|LoggerFactory
operator|.
name|getLogger
argument_list|(
name|LlapServiceCommandLine
operator|.
name|class
operator|.
name|getName
argument_list|()
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|DIRECTORY
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"directory"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Temp directory for jars etc."
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"directory"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'d'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|NAME
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"name"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Cluster name for YARN registry"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"name"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'n'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|EXECUTORS
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"executors"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"executor per instance"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"executors"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'e'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|IO_THREADS
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"iothreads"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"iothreads per instance"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"iothreads"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'t'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|CACHE
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"cache"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"cache size per instance"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"cache"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'c'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|SIZE
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"size"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"cache size per instance"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"size"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'s'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|XMX
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"xmx"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"working memory size"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"xmx"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'w'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|AUXJARS
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"auxjars"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"additional jars to package (by default, JSON SerDe jar is packaged if available)"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"auxjars"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'j'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|AUXHBASE
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"auxhbase"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"whether to package the HBase jars (true by default)"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"auxhbase"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'h'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|HIVECONF
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"hiveconf"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Use value for given property. Overridden by explicit parameters"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"property=value"
argument_list|)
operator|.
name|hasArgs
argument_list|(
literal|2
argument_list|)
operator|.
name|withValueSeparator
argument_list|()
operator|.
name|create
argument_list|()
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|JAVAHOME
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"javaHome"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Path to the JRE/JDK. This should be installed at the same location on all cluster nodes "
operator|+
literal|"($JAVA_HOME, java.home by default)"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"javaHome"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|QUEUE
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"queue"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"The queue within which LLAP will be started"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"queue"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'q'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Set
argument_list|<
name|String
argument_list|>
name|VALID_LOGGERS
init|=
name|ImmutableSet
operator|.
name|of
argument_list|(
name|LogHelpers
operator|.
name|LLAP_LOGGER_NAME_RFA
operator|.
name|toLowerCase
argument_list|()
argument_list|,
name|LogHelpers
operator|.
name|LLAP_LOGGER_NAME_QUERY_ROUTING
operator|.
name|toLowerCase
argument_list|()
argument_list|,
name|LogHelpers
operator|.
name|LLAP_LOGGER_NAME_CONSOLE
operator|.
name|toLowerCase
argument_list|()
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|LOGGER
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"logger"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"logger for llap instance (["
operator|+
name|VALID_LOGGERS
operator|+
literal|"]"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"logger"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|START
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"startImmediately"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"immediately start the cluster"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"startImmediately"
argument_list|)
operator|.
name|hasArg
argument_list|(
literal|false
argument_list|)
operator|.
name|create
argument_list|(
literal|'z'
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|OUTPUT
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"output"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Output directory for the generated scripts"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"output"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|AUXHIVE
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"auxhive"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"whether to package the Hive aux jars (true by default)"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"auxhive"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|"auxhive"
argument_list|)
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Option
name|HELP
init|=
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
literal|"help"
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Print help information"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"help"
argument_list|)
operator|.
name|hasArg
argument_list|(
literal|false
argument_list|)
operator|.
name|create
argument_list|(
literal|'H'
argument_list|)
decl_stmt|;
comment|// Options for the python script that are here because our option parser cannot ignore the unknown ones
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_INSTANCES
init|=
literal|"instances"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_ARGS
init|=
literal|"args"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_LOGLEVEL
init|=
literal|"loglevel"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_KEYTAB_DIR
init|=
literal|"service-keytab-dir"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_KEYTAB
init|=
literal|"service-keytab"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_PRINCIPAL
init|=
literal|"service-principal"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_PLACEMENT
init|=
literal|"service-placement"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_DEFAULT_KEYTAB
init|=
literal|"service-default-keytab"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_HEALTH_PERCENT
init|=
literal|"health-percent"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_HEALTH_TIME_WINDOW_SECS
init|=
literal|"health-time-window-secs"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_HEALTH_INIT_DELAY_SECS
init|=
literal|"health-init-delay-secs"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_AM_CONTAINER_MB
init|=
literal|"service-am-container-mb"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|String
name|OPTION_SERVICE_APPCONFIG_GLOBAL
init|=
literal|"service-appconfig-global"
decl_stmt|;
specifier|private
specifier|static
specifier|final
name|Options
name|OPTIONS
init|=
operator|new
name|Options
argument_list|()
decl_stmt|;
static|static
block|{
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|DIRECTORY
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|NAME
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|EXECUTORS
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|IO_THREADS
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|CACHE
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|SIZE
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|XMX
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|AUXJARS
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|AUXHBASE
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|HIVECONF
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|JAVAHOME
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|QUEUE
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|LOGGER
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|START
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OUTPUT
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|AUXHIVE
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|HELP
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_INSTANCES
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Specify the number of instances to run this on"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_INSTANCES
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'i'
argument_list|)
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_ARGS
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"java arguments to the llap instance"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_ARGS
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'a'
argument_list|)
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_LOGLEVEL
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"log levels for the llap instance"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_LOGLEVEL
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'l'
argument_list|)
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_KEYTAB_DIR
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Service AM keytab directory on HDFS (where the headless user keytab is stored by Service "
operator|+
literal|"keytab installation, e.g. .yarn/keytabs/llap)"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_SERVICE_KEYTAB_DIR
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_KEYTAB
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Service AM keytab file name inside "
operator|+
name|OPTION_SERVICE_KEYTAB_DIR
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_SERVICE_KEYTAB
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_PRINCIPAL
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Service AM principal; should be the user running the cluster, e.g. hive@EXAMPLE.COM"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_SERVICE_PRINCIPAL
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_PLACEMENT
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Service placement policy; see YARN documentation at "
operator|+
literal|"https://issues.apache.org/jira/browse/YARN-1042. This is unnecessary if LLAP is going to take more than "
operator|+
literal|"half of the YARN capacity of a node."
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_SERVICE_PLACEMENT
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_DEFAULT_KEYTAB
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"try to set default settings for Service AM keytab; mostly for dev testing"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_SERVICE_DEFAULT_KEYTAB
argument_list|)
operator|.
name|hasArg
argument_list|(
literal|false
argument_list|)
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_HEALTH_PERCENT
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Percentage of running containers after which LLAP application is considered healthy"
operator|+
literal|" (Default: 80)"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_HEALTH_PERCENT
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_HEALTH_TIME_WINDOW_SECS
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Time window in seconds (after initial delay) for which LLAP application is allowed to be "
operator|+
literal|"in unhealthy state before being killed (Default: 300)"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_HEALTH_TIME_WINDOW_SECS
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_HEALTH_INIT_DELAY_SECS
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Delay in seconds after which health percentage is monitored (Default: 400)"
argument_list|)
operator|.
name|withArgName
argument_list|(
name|OPTION_HEALTH_INIT_DELAY_SECS
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_AM_CONTAINER_MB
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"The size of the service AppMaster container in MB"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"b"
argument_list|)
operator|.
name|hasArg
argument_list|()
operator|.
name|create
argument_list|(
literal|'b'
argument_list|)
argument_list|)
expr_stmt|;
name|OPTIONS
operator|.
name|addOption
argument_list|(
name|OptionBuilder
operator|.
name|withLongOpt
argument_list|(
name|OPTION_SERVICE_APPCONFIG_GLOBAL
argument_list|)
operator|.
name|withDescription
argument_list|(
literal|"Property (key=value) to be set in the global section of the Service appConfig"
argument_list|)
operator|.
name|withArgName
argument_list|(
literal|"property=value"
argument_list|)
operator|.
name|hasArgs
argument_list|(
literal|2
argument_list|)
operator|.
name|withValueSeparator
argument_list|()
operator|.
name|create
argument_list|()
argument_list|)
expr_stmt|;
block|}
specifier|private
name|String
index|[]
name|args
decl_stmt|;
specifier|private
name|String
name|directory
decl_stmt|;
specifier|private
name|String
name|name
decl_stmt|;
specifier|private
name|int
name|executors
decl_stmt|;
specifier|private
name|int
name|ioThreads
decl_stmt|;
specifier|private
name|long
name|cache
decl_stmt|;
specifier|private
name|long
name|size
decl_stmt|;
specifier|private
name|long
name|xmx
decl_stmt|;
specifier|private
name|String
name|jars
decl_stmt|;
specifier|private
name|boolean
name|isHbase
decl_stmt|;
specifier|private
name|Properties
name|conf
init|=
operator|new
name|Properties
argument_list|()
decl_stmt|;
specifier|private
name|String
name|javaPath
init|=
literal|null
decl_stmt|;
specifier|private
name|String
name|llapQueueName
decl_stmt|;
specifier|private
name|String
name|logger
init|=
literal|null
decl_stmt|;
specifier|private
name|boolean
name|isStarting
decl_stmt|;
specifier|private
name|String
name|output
decl_stmt|;
specifier|private
name|boolean
name|isHiveAux
decl_stmt|;
specifier|private
name|boolean
name|isHelp
decl_stmt|;
specifier|static
name|LlapServiceCommandLine
name|parseArguments
parameter_list|(
name|String
index|[]
name|args
parameter_list|)
block|{
name|LlapServiceCommandLine
name|cl
init|=
literal|null
decl_stmt|;
try|try
block|{
name|cl
operator|=
operator|new
name|LlapServiceCommandLine
argument_list|(
name|args
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Exception
name|e
parameter_list|)
block|{
name|LOG
operator|.
name|error
argument_list|(
literal|"Parsing the command line arguments failed"
argument_list|,
name|e
argument_list|)
expr_stmt|;
name|printUsage
argument_list|()
expr_stmt|;
name|System
operator|.
name|exit
argument_list|(
literal|1
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|cl
operator|.
name|isHelp
condition|)
block|{
name|printUsage
argument_list|()
expr_stmt|;
name|System
operator|.
name|exit
argument_list|(
literal|0
argument_list|)
expr_stmt|;
block|}
return|return
name|cl
return|;
block|}
name|LlapServiceCommandLine
parameter_list|(
name|String
index|[]
name|args
parameter_list|)
throws|throws
name|ParseException
block|{
name|LOG
operator|.
name|info
argument_list|(
literal|"LLAP invoked with arguments = {}"
argument_list|,
name|Arrays
operator|.
name|toString
argument_list|(
name|args
argument_list|)
argument_list|)
expr_stmt|;
name|this
operator|.
name|args
operator|=
name|args
expr_stmt|;
name|parseCommandLine
argument_list|(
name|args
argument_list|)
expr_stmt|;
block|}
specifier|private
name|void
name|parseCommandLine
parameter_list|(
name|String
index|[]
name|args
parameter_list|)
throws|throws
name|ParseException
block|{
name|CommandLine
name|cl
init|=
operator|new
name|GnuParser
argument_list|()
operator|.
name|parse
argument_list|(
name|OPTIONS
argument_list|,
name|args
argument_list|)
decl_stmt|;
if|if
condition|(
name|cl
operator|.
name|hasOption
argument_list|(
name|HELP
operator|.
name|getOpt
argument_list|()
argument_list|)
condition|)
block|{
name|isHelp
operator|=
literal|true
expr_stmt|;
return|return;
block|}
if|if
condition|(
operator|!
name|cl
operator|.
name|hasOption
argument_list|(
name|OPTION_INSTANCES
argument_list|)
condition|)
block|{
name|printUsage
argument_list|()
expr_stmt|;
throw|throw
operator|new
name|ParseException
argument_list|(
literal|"instance must be set"
argument_list|)
throw|;
block|}
name|int
name|instances
init|=
name|Integer
operator|.
name|parseInt
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|OPTION_INSTANCES
argument_list|)
argument_list|)
decl_stmt|;
if|if
condition|(
name|instances
operator|<=
literal|0
condition|)
block|{
throw|throw
operator|new
name|ParseException
argument_list|(
literal|"Invalid configuration: "
operator|+
name|instances
operator|+
literal|" (should be greater than 0)"
argument_list|)
throw|;
block|}
name|directory
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|DIRECTORY
operator|.
name|getOpt
argument_list|()
argument_list|)
expr_stmt|;
name|name
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|NAME
operator|.
name|getOpt
argument_list|()
argument_list|)
expr_stmt|;
name|executors
operator|=
name|Integer
operator|.
name|parseInt
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|EXECUTORS
operator|.
name|getOpt
argument_list|()
argument_list|,
literal|"-1"
argument_list|)
argument_list|)
expr_stmt|;
name|ioThreads
operator|=
name|Integer
operator|.
name|parseInt
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|IO_THREADS
operator|.
name|getOpt
argument_list|()
argument_list|,
name|Integer
operator|.
name|toString
argument_list|(
name|executors
argument_list|)
argument_list|)
argument_list|)
expr_stmt|;
name|cache
operator|=
name|TraditionalBinaryPrefix
operator|.
name|string2long
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|CACHE
operator|.
name|getOpt
argument_list|()
argument_list|,
literal|"-1"
argument_list|)
argument_list|)
expr_stmt|;
name|size
operator|=
name|TraditionalBinaryPrefix
operator|.
name|string2long
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|SIZE
operator|.
name|getOpt
argument_list|()
argument_list|,
literal|"-1"
argument_list|)
argument_list|)
expr_stmt|;
name|xmx
operator|=
name|TraditionalBinaryPrefix
operator|.
name|string2long
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|XMX
operator|.
name|getOpt
argument_list|()
argument_list|,
literal|"-1"
argument_list|)
argument_list|)
expr_stmt|;
name|jars
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|AUXJARS
operator|.
name|getOpt
argument_list|()
argument_list|)
expr_stmt|;
name|isHbase
operator|=
name|Boolean
operator|.
name|parseBoolean
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|AUXHBASE
operator|.
name|getOpt
argument_list|()
argument_list|,
literal|"true"
argument_list|)
argument_list|)
expr_stmt|;
if|if
condition|(
name|cl
operator|.
name|hasOption
argument_list|(
name|HIVECONF
operator|.
name|getLongOpt
argument_list|()
argument_list|)
condition|)
block|{
name|conf
operator|=
name|cl
operator|.
name|getOptionProperties
argument_list|(
name|HIVECONF
operator|.
name|getLongOpt
argument_list|()
argument_list|)
expr_stmt|;
block|}
if|if
condition|(
name|cl
operator|.
name|hasOption
argument_list|(
name|JAVAHOME
operator|.
name|getLongOpt
argument_list|()
argument_list|)
condition|)
block|{
name|javaPath
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|JAVAHOME
operator|.
name|getLongOpt
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|llapQueueName
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|QUEUE
operator|.
name|getOpt
argument_list|()
argument_list|,
name|ConfVars
operator|.
name|LLAP_DAEMON_QUEUE_NAME
operator|.
name|getDefaultValue
argument_list|()
argument_list|)
expr_stmt|;
if|if
condition|(
name|cl
operator|.
name|hasOption
argument_list|(
name|LOGGER
operator|.
name|getLongOpt
argument_list|()
argument_list|)
condition|)
block|{
name|logger
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|LOGGER
operator|.
name|getLongOpt
argument_list|()
argument_list|)
expr_stmt|;
name|Preconditions
operator|.
name|checkArgument
argument_list|(
name|VALID_LOGGERS
operator|.
name|contains
argument_list|(
name|logger
operator|.
name|toLowerCase
argument_list|()
argument_list|)
argument_list|)
expr_stmt|;
block|}
name|isStarting
operator|=
name|cl
operator|.
name|hasOption
argument_list|(
name|START
operator|.
name|getOpt
argument_list|()
argument_list|)
expr_stmt|;
name|output
operator|=
name|cl
operator|.
name|getOptionValue
argument_list|(
name|OUTPUT
operator|.
name|getLongOpt
argument_list|()
argument_list|)
expr_stmt|;
name|isHiveAux
operator|=
name|Boolean
operator|.
name|parseBoolean
argument_list|(
name|cl
operator|.
name|getOptionValue
argument_list|(
name|AUXHIVE
operator|.
name|getOpt
argument_list|()
argument_list|,
literal|"true"
argument_list|)
argument_list|)
expr_stmt|;
block|}
specifier|private
specifier|static
name|void
name|printUsage
parameter_list|()
block|{
name|HelpFormatter
name|hf
init|=
operator|new
name|HelpFormatter
argument_list|()
decl_stmt|;
try|try
block|{
name|int
name|width
init|=
name|hf
operator|.
name|getWidth
argument_list|()
decl_stmt|;
name|int
name|jlineWidth
init|=
name|TerminalFactory
operator|.
name|get
argument_list|()
operator|.
name|getWidth
argument_list|()
decl_stmt|;
name|width
operator|=
name|Math
operator|.
name|min
argument_list|(
literal|160
argument_list|,
name|Math
operator|.
name|max
argument_list|(
name|jlineWidth
argument_list|,
name|width
argument_list|)
argument_list|)
expr_stmt|;
name|hf
operator|.
name|setWidth
argument_list|(
name|width
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|Throwable
name|t
parameter_list|)
block|{
comment|// Ignore
block|}
name|hf
operator|.
name|printHelp
argument_list|(
literal|"llap"
argument_list|,
name|OPTIONS
argument_list|)
expr_stmt|;
block|}
name|String
index|[]
name|getArgs
parameter_list|()
block|{
return|return
name|args
return|;
block|}
name|String
name|getDirectory
parameter_list|()
block|{
return|return
name|directory
return|;
block|}
name|String
name|getName
parameter_list|()
block|{
return|return
name|name
return|;
block|}
name|int
name|getExecutors
parameter_list|()
block|{
return|return
name|executors
return|;
block|}
name|int
name|getIoThreads
parameter_list|()
block|{
return|return
name|ioThreads
return|;
block|}
name|long
name|getCache
parameter_list|()
block|{
return|return
name|cache
return|;
block|}
name|long
name|getSize
parameter_list|()
block|{
return|return
name|size
return|;
block|}
name|long
name|getXmx
parameter_list|()
block|{
return|return
name|xmx
return|;
block|}
name|String
name|getAuxJars
parameter_list|()
block|{
return|return
name|jars
return|;
block|}
name|boolean
name|getIsHBase
parameter_list|()
block|{
return|return
name|isHbase
return|;
block|}
name|boolean
name|getIsHiveAux
parameter_list|()
block|{
return|return
name|isHiveAux
return|;
block|}
name|Properties
name|getConfig
parameter_list|()
block|{
return|return
name|conf
return|;
block|}
name|String
name|getJavaPath
parameter_list|()
block|{
return|return
name|javaPath
return|;
block|}
name|String
name|getLlapQueueName
parameter_list|()
block|{
return|return
name|llapQueueName
return|;
block|}
name|String
name|getLogger
parameter_list|()
block|{
return|return
name|logger
return|;
block|}
name|boolean
name|isStarting
parameter_list|()
block|{
return|return
name|isStarting
return|;
block|}
name|String
name|getOutput
parameter_list|()
block|{
return|return
name|output
return|;
block|}
block|}
end_class
end_unit
| 15.063368
| 813
| 0.809053
|
cbf3625bc22f6c4d8a79f2623f73cc9a3238d57e
| 2,199
|
package com.github.mickroll.maven.dependency_duplicator_plugin.it;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
public class MavenWrapper {
private static final String BASE_DIR = "target/maven-projects/";
private static final String MVN_COMMAND;
static {
if (System.getProperty("os.name").toLowerCase().contains("win")) {
MVN_COMMAND = "mvn.cmd";
} else {
MVN_COMMAND = "mvn";
}
}
private final File runDir;
public MavenWrapper(final String subdir) {
this.runDir = new File(BASE_DIR, subdir).getAbsoluteFile();
}
public List<String> run(final String goal, final int expectedExitValue) throws IOException, InterruptedException {
final Process process = new ProcessBuilder(Arrays.asList(MVN_COMMAND, goal))
.directory(runDir)
.redirectErrorStream(true)
.start();
final List<String> stdoutLines = new ArrayList<>();
Executors.newSingleThreadExecutor()
.submit(() -> new BufferedReader(new InputStreamReader(process.getInputStream())).lines().forEach(stdoutLines::add));
process.waitFor(1, TimeUnit.MINUTES);
FileUtils.writeLines(new File(runDir, "build.log"), stdoutLines);
if (process.exitValue() != expectedExitValue) {
System.out.println(formatLines("> ", stdoutLines));
}
assertThat(process.exitValue()).as("exit value").isEqualTo(expectedExitValue);
return stdoutLines;
}
public static String formatLines(final String prefix, final List<String> lines) {
final StringBuilder result = new StringBuilder();
for (final String line : lines) {
result.append(prefix).append(line).append("\n");
}
return result.toString();
}
}
| 34.904762
| 126
| 0.655298
|
09ba68219e5a410233e1ec07beb14f4fc6b202dc
| 3,660
|
/*
* Anserini: A Lucene toolkit for replicable information retrieval research
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.anserini.ltr.feature.base;
import io.anserini.index.IndexArgs;
import io.anserini.ltr.feature.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* This feature extractor will compute BM25 score as according to Lucene 5.3 documentation
* The formula is the same, but the computation of docSize is slightly different,
* Lucene uses the norm value encoded in the index, we are calculating it as is
* also we do not have any boosting, the field norm is also not available
*/
public class BM25 implements FeatureExtractor {
private static final Logger LOG = LogManager.getLogger(BM25.class);
// Default values, could be changed
private double k1 = 0.9;
private double b = 0.4;
private String field;
private String qfield;
public BM25() {
this.field = IndexArgs.CONTENTS;
this.qfield = "analyzed";
}
public BM25(double k, double b) {
this.k1 = k;
this.b = b;
this.field = IndexArgs.CONTENTS;
this.qfield = "analyzed";
}
public BM25(double k, double b, String field, String qfield) {
this.k1 = k;
this.b = b;
this.field = field;
this.qfield = qfield;
}
/**
* We will implement this according to the Lucene specification
* the formula used:
* sum ( IDF(qi) * (df(qi,D) * (k+1)) / (df(qi,D) + k * (1-b + b*|D| / avgFL))
* IDF and avgFL computation are described above.
*/
@Override
public float extract(DocumentContext documentContext, QueryContext queryContext) {
DocumentFieldContext context = documentContext.fieldContexts.get(field);
QueryFieldContext qcontext = queryContext.fieldContexts.get(qfield);
long numDocs = context.numDocs;
long docSize = context.docSize;
long totalTermFreq = context.totalTermFreq;
double avgFL = (double)totalTermFreq/numDocs;
float score = 0;
for (String queryToken : qcontext.queryTokens) {
int docFreq = context.getDocFreq(queryToken);
long termFreq = context.getTermFreq(queryToken);
double numerator = (this.k1 + 1) * termFreq;
double docLengthFactor = this.b * (docSize / avgFL);
double denominator = termFreq + (this.k1) * (1 - this.b + docLengthFactor);
double idf = Math.log(1 + (numDocs - docFreq + 0.5d) / (docFreq + 0.5d));
score += idf * numerator / denominator;
}
return score;
}
@Override
public float postEdit(DocumentContext context, QueryContext queryContext) {
QueryFieldContext qcontext = queryContext.fieldContexts.get(qfield);
return qcontext.getSelfLog(context.docId, getName());
}
@Override
public String getName() {
return String.format("%s_%s_BM25_k1_%.2f_b_%.2f",field, qfield, k1, b);
}
@Override
public String getField() {
return field;
}
@Override
public String getQField(){return qfield;}
public double getK1() {
return k1;
}
public double getB() {
return b;
}
@Override
public FeatureExtractor clone() {
return new BM25(k1, b, field, qfield);
}
}
| 31.016949
| 90
| 0.694536
|
a2b3e710816615ba6549879658dcd967226454fb
| 9,914
|
/*
* 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 com.gemstone.gemfire.rest.internal.web.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.gemstone.gemfire.cache.LowMemoryException;
import com.gemstone.gemfire.cache.Region;
import com.gemstone.gemfire.cache.execute.Execution;
import com.gemstone.gemfire.cache.execute.FunctionException;
import com.gemstone.gemfire.cache.execute.FunctionService;
import com.gemstone.gemfire.cache.execute.ResultCollector;
import com.gemstone.gemfire.internal.cache.GemFireCacheImpl;
import com.gemstone.gemfire.internal.logging.LogService;
import com.gemstone.gemfire.internal.util.ArrayUtils;
import com.gemstone.gemfire.rest.internal.web.controllers.support.RestServersResultCollector;
import com.gemstone.gemfire.rest.internal.web.exception.GemfireRestException;
import com.gemstone.gemfire.rest.internal.web.util.JSONUtils;
import org.json.JSONException;
import com.wordnik.swagger.annotations.ApiOperation;
import com.wordnik.swagger.annotations.ApiResponse;
import com.wordnik.swagger.annotations.ApiResponses;
/**
* The CommonCrudController serves REST Requests related to listing regions,
* listing keys in region, delete keys or delete all data in region.
* <p/>
* @author Nilkanth Patel, john blum
* @since 8.0
*/
@SuppressWarnings("unused")
public abstract class CommonCrudController extends AbstractBaseController {
private static final Logger logger = LogService.getLogger();
/**
* list all available resources (Regions) in the GemFire cluster
* @return JSON document containing result
*/
@RequestMapping(method = RequestMethod.GET, produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_JSON_VALUE })
@ApiOperation(
value = "list all resources (Regions)",
notes = "List all available resources (Regions) in the GemFire cluster",
response = void.class
)
@ApiResponses( {
@ApiResponse( code = 200, message = "OK." ),
@ApiResponse( code = 500, message = "GemFire throws an error or exception." )
} )
public ResponseEntity<?> regions() {
if(logger.isDebugEnabled()){
logger.debug("Listing all resources (Regions) in GemFire...");
}
final Set<Region<?, ?>> regions = getCache().rootRegions();
String listRegionsAsJson = JSONUtils.formulateJsonForListRegions(regions, "regions");
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(toUri());
return new ResponseEntity<String>(listRegionsAsJson, headers, HttpStatus.OK);
}
/**
* List all keys for the given region in the GemFire cluster
* @param region gemfire region
* @return JSON document containing result
*/
@RequestMapping(method = RequestMethod.GET, value = "/{region}/keys",
produces = { MediaType.APPLICATION_JSON_VALUE } )
@ApiOperation(
value = "list all keys",
notes = "List all keys in region",
response = void.class
)
@ApiResponses( {
@ApiResponse( code = 200, message = "OK" ),
@ApiResponse( code = 404, message = "Region does not exist" ),
@ApiResponse( code = 500, message = "GemFire throws an error or exception" )
} )
public ResponseEntity<?> keys(@PathVariable("region") String region){
if(logger.isDebugEnabled()){
logger.debug("Reading all Keys in Region ({})...", region);
}
region = decode(region);
Object[] keys = getKeys(region, null);
String listKeysAsJson = JSONUtils.formulateJsonForListKeys(keys, "keys");
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(toUri(region, "keys"));
return new ResponseEntity<String>(listKeysAsJson, headers, HttpStatus.OK);
}
/**
* Delete data for single key or specific keys in region
* @param region gemfire region
* @param keys for which data is requested
* @return JSON document containing result
*/
@RequestMapping(method = RequestMethod.DELETE, value = "/{region}/{keys}",
produces = { MediaType.APPLICATION_JSON_VALUE } )
@ApiOperation(
value = "delete data for key(s)",
notes = "Delete data for single key or specific keys in region",
response = void.class
)
@ApiResponses( {
@ApiResponse( code = 200, message = "OK" ),
@ApiResponse( code = 404, message = "Region or key(s) does not exist" ),
@ApiResponse( code = 500, message = "GemFire throws an error or exception" )
} )
public ResponseEntity<?> delete(@PathVariable("region") String region,
@PathVariable("keys") final String[] keys){
if(logger.isDebugEnabled()){
logger.debug("Delete data for key {} on region {}", ArrayUtils.toString((Object[])keys), region);
}
region = decode(region);
deleteValues(region, (Object[])keys);
return new ResponseEntity<Object>(HttpStatus.OK);
}
/**
* Delete all data in region
* @param region gemfire region
* @return JSON document containing result
*/
@RequestMapping(method = RequestMethod.DELETE, value = "/{region}")
@ApiOperation(
value = "delete all data",
notes = "Delete all data in the region",
response = void.class
)
@ApiResponses( {
@ApiResponse( code = 200, message = "OK" ),
@ApiResponse( code = 404, message = "Region does not exist" ),
@ApiResponse( code = 500, message = "if GemFire throws an error or exception" )
} )
public ResponseEntity<?> delete(@PathVariable("region") String region) {
if(logger.isDebugEnabled()){
logger.debug("Deleting all data in Region ({})...", region);
}
region = decode(region);
deleteValues(region);
return new ResponseEntity<Object>(HttpStatus.OK);
}
@RequestMapping(method = { RequestMethod.GET, RequestMethod.HEAD }, value = "/ping")
@ApiOperation(
value = "Check Rest service status ",
notes = "Check whether gemfire REST service is up and running!",
response = void.class
)
@ApiResponses( {
@ApiResponse( code = 200, message = "OK" ),
@ApiResponse( code = 500, message = "if GemFire throws an error or exception" )
} )
public ResponseEntity<?> ping() {
return new ResponseEntity<Object>(HttpStatus.OK);
}
@RequestMapping(method = { RequestMethod.GET }, value = "/servers")
@ApiOperation(
value = "fetch all REST enabled servers in the DS",
notes = "Find all gemfire node where developer REST service is up and running!",
response = void.class
)
@ApiResponses( {
@ApiResponse( code = 200, message = "OK" ),
@ApiResponse( code = 500, message = "if GemFire throws an error or exception" )
} )
public ResponseEntity<?> servers() {
Execution function = null;
if(logger.isDebugEnabled()){
logger.debug("Executing function to get REST enabled gemfire nodes in the DS!");
}
try {
function = FunctionService.onMembers(getAllMembersInDS());
} catch(FunctionException fe) {
throw new GemfireRestException("Disributed system does not contain any valid data node that can host REST service!", fe);
}
try {
final ResultCollector<?, ?> results = function.withCollector(new RestServersResultCollector()).execute(GemFireCacheImpl.FIND_REST_ENABLED_SERVERS_FUNCTION_ID);
Object functionResult = results.getResult();
if(functionResult instanceof List<?>) {
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(toUri("servers"));
try {
String functionResultAsJson = JSONUtils.convertCollectionToJson((ArrayList<Object>)functionResult);
return new ResponseEntity<String>(functionResultAsJson, headers, HttpStatus.OK);
} catch (JSONException e) {
throw new GemfireRestException("Could not convert function results into Restful (JSON) format!", e);
}
}else {
throw new GemfireRestException("Function has returned results that could not be converted into Restful (JSON) format!");
}
} catch(ClassCastException cce){
throw new GemfireRestException("Key is of an inappropriate type for this region!", cce);
} catch(NullPointerException npe){
throw new GemfireRestException("Specified key is null and this region does not permit null keys!", npe);
} catch(LowMemoryException lme){
throw new GemfireRestException("Server has encountered low memory condition!", lme);
} catch (IllegalArgumentException ie) {
throw new GemfireRestException("Input parameter is null! ", ie);
}catch (FunctionException fe){
throw new GemfireRestException("Server has encountered error while executing the function!", fe);
}
}
}
| 39.656
| 165
| 0.700525
|
203748dad461b7147fb76f25834399ff131ff86e
| 2,485
|
package edu.mit.mitmobile2;
import java.util.HashMap;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
public abstract class CategoryNewModuleActivity extends NewModuleActivity implements OnMITMenuItemListener {
MITPopupSecondaryTitleBar mSecondaryTitleBar;
HashMap<String, ScreenInterface> mScreenInterfaces = new HashMap<String, ScreenInterface>();
HashMap<String, View> mViews = new HashMap<String, View>();
HashMap<String, String> mTitles = new HashMap<String, String>();
ScreenInterface mCurrentScreenInterface = null;
@Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
mSecondaryTitleBar = new MITPopupSecondaryTitleBar(this);
mSecondaryTitleBar.setOnPopupMenuItemListener(this);
initContentView();
getTitleBar().addSecondaryBar(mSecondaryTitleBar);
}
@Override
protected void onResume() {
super.onResume();
if (mCurrentScreenInterface != null) {
mCurrentScreenInterface.updateView();
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
if (null != mSecondaryTitleBar) {
mSecondaryTitleBar.notifyScreenRotated();
}
}
protected MITPopupSecondaryTitleBar getSecondaryBar() {
return mSecondaryTitleBar;
}
protected void addCategory(ScreenInterface screenInterface, String menuId, String title) {
mSecondaryTitleBar.addPopupMenuItem(new MITMenuItem(menuId, title));
mScreenInterfaces.put(menuId, screenInterface);
mTitles.put(menuId, title);
if (mCurrentScreenInterface == null) {
onOptionItemSelected(menuId);
}
}
private void loadScreen(String menuId) {
View view;
String title = mTitles.get(menuId);
ScreenInterface screenInterface = mScreenInterfaces.get(menuId);
if (mViews.containsKey(menuId)) {
view = mViews.get(menuId);
} else {
view = screenInterface.getView();
mViews.put(menuId, view);
}
mSecondaryTitleBar.setTitle(title);
mCurrentScreenInterface = screenInterface;
setContentView(view, false);
}
protected ScreenInterface getCategory(String optionId) {
return mScreenInterfaces.get(optionId);
}
protected ScreenInterface getCurrentCategory() {
return mCurrentScreenInterface;
}
@Override
public void onOptionItemSelected(String optionId) {
loadScreen(optionId);
mCurrentScreenInterface.updateView();
mCurrentScreenInterface.onSelected();
}
}
| 27.921348
| 108
| 0.772233
|
4fa7db89ee209e03d16753d401c0a0654ed8f684
| 4,350
|
package net.runelite.client.plugins.templetrekking;
import com.google.inject.Provides;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.inject.Inject;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.Client;
import net.runelite.api.Tile;
import net.runelite.api.TileObject;
import net.runelite.api.events.DecorativeObjectChanged;
import net.runelite.api.events.DecorativeObjectDespawned;
import net.runelite.api.events.DecorativeObjectSpawned;
import net.runelite.api.events.GameObjectChanged;
import net.runelite.api.events.GameObjectDespawned;
import net.runelite.api.events.GameObjectSpawned;
import net.runelite.api.events.GroundObjectChanged;
import net.runelite.api.events.GroundObjectDespawned;
import net.runelite.api.events.GroundObjectSpawned;
import net.runelite.api.events.WallObjectChanged;
import net.runelite.api.events.WallObjectDespawned;
import net.runelite.api.events.WallObjectSpawned;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.ui.overlay.OverlayManager;
@PluginDescriptor(
name = "Temple Trekking",
description = "Highlights walkable tiles for the bog encounter in the Temple Trekking minigame",
tags = {"bog", "temple", "trekking", "ritzlite"},
enabledByDefault = false
)
@Slf4j
public class BogPlugin extends Plugin
{
private static final int WALKABLE_BOG_TILE_ID = 13838;
@Getter
private final List<TileObject> walkableBogTiles = new ArrayList<>();
@Inject
private OverlayManager overlayManager;
@Inject
private BogOverlay bogOverlay;
@Inject
private Client client;
@Override
protected void startUp() throws Exception
{
overlayManager.add(bogOverlay);
}
@Override
protected void shutDown() throws Exception
{
overlayManager.remove(bogOverlay);
}
@Subscribe
public void onGameObjectSpawned(GameObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getGameObject());
}
@Subscribe
public void onGameObjectChanged(GameObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getGameObject());
}
@Subscribe
public void onGameObjectDespawned(GameObjectDespawned event)
{
onTileObject(event.getTile(), event.getGameObject(), null);
}
@Subscribe
public void onGroundObjectSpawned(GroundObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getGroundObject());
}
@Subscribe
public void onGroundObjectChanged(GroundObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getGroundObject());
}
@Subscribe
public void onGroundObjectDespawned(GroundObjectDespawned event)
{
onTileObject(event.getTile(), event.getGroundObject(), null);
}
@Subscribe
public void onWallObjectSpawned(WallObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getWallObject());
}
@Subscribe
public void onWallObjectChanged(WallObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getWallObject());
}
@Subscribe
public void onWallObjectDespawned(WallObjectDespawned event)
{
onTileObject(event.getTile(), event.getWallObject(), null);
}
@Subscribe
public void onDecorativeObjectSpawned(DecorativeObjectSpawned event)
{
onTileObject(event.getTile(), null, event.getDecorativeObject());
}
@Subscribe
public void onDecorativeObjectChanged(DecorativeObjectChanged event)
{
onTileObject(event.getTile(), event.getPrevious(), event.getDecorativeObject());
}
@Subscribe
public void onDecorativeObjectDespawned(DecorativeObjectDespawned event)
{
onTileObject(event.getTile(), event.getDecorativeObject(), null);
}
private void onTileObject(Tile tile, TileObject oldObject, TileObject newObject)
{
walkableBogTiles.remove(oldObject);
if (newObject != null && newObject.getId() == WALKABLE_BOG_TILE_ID) {
walkableBogTiles.add(newObject);
}
}
}
| 29.591837
| 104
| 0.729425
|
e31c7094cac8937f574962e26461767cda8cdf7c
| 1,909
|
/**
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* 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.hadoop.ozone.freon;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.lang3.RandomStringUtils;
/**
* Utility class to write random keys from a limited buffer.
*/
public class ContentGenerator {
/**
* Size of the destination object (key or file).
*/
private int keySize;
/**
* Buffer for the pre-allocated content (will be reused if less than the
* keySize).
*/
private int bufferSize;
private final byte[] buffer;
ContentGenerator(int keySize, int bufferSize) {
this.keySize = keySize;
this.bufferSize = bufferSize;
buffer = RandomStringUtils.randomAscii(bufferSize)
.getBytes(StandardCharsets.UTF_8);
}
/**
* Write the required bytes to the output stream.
*/
public void write(OutputStream outputStream) throws IOException {
for (long nrRemaining = keySize;
nrRemaining > 0; nrRemaining -= bufferSize) {
int curSize = (int) Math.min(bufferSize, nrRemaining);
outputStream.write(buffer, 0, curSize);
}
}
}
| 30.301587
| 80
| 0.72132
|
6182d075f9fe4f60691cd125c2483f4fe0a10333
| 2,841
|
/*
* Copyright 2014 KonradOliwer.
*
* 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 pwr.om.geneticai.chromosome;
import pwr.om.battlesystem.actor.Actor;
import pwr.om.battlesystem.actor.State;
/**
*
* @author KonradOliwer
*/
public class BasicInfoAddChromosome extends Chromosome {
final static int INDEXES_PER_ACION = 9;
final static int BASE_ACTION_PRIORITY_INDEX = 0;
final static int SELF_HP_LOWER_BORDER_INDEX = 1;
final static int SELF_HP_UPPER_BORDER_INDEX = 2;
final static int SELF_AP_LOWER_BORDER_INDEX = 3;
final static int SELF_AP_UPPER_BORDER_INDEX = 4;
final static int ENEMY_HP_LOWER_BORDER_INDEX = 5;
final static int ENEMY_HP_UPPER_BORDER_INDEX = 6;
final static int ENEMY_AP_LOWER_BORDER_INDEX = 7;
final static int ENEMY_AP_UPPER_BORDER_INDEX = 8;
public BasicInfoAddChromosome(Actor self) {
super(self, INDEXES_PER_ACION);
}
public BasicInfoAddChromosome(Actor self, int[] arrayReprezentation) {
this(self);
this.copyArrayReprezentation(arrayReprezentation);
}
@Override
public int getActionPriority(Actor self, Actor enemy, int actionId) {
int actionIndex = -1;
for (int i = 0; i < actionIds.length; i++) {
if (actionIds[i] == actionId) {
actionIndex = i;
break;
}
}
State s = self.getState();
State e = enemy.getState();
int startIndexOfAction = actionIndex * INDEXES_PER_ACION;
return (int) (chromosome[startIndexOfAction + BASE_ACTION_PRIORITY_INDEX]
+ between(SELF_HP_LOWER_BORDER_INDEX, SELF_HP_UPPER_BORDER_INDEX, startIndexOfAction, s.hp)
+ between(SELF_AP_LOWER_BORDER_INDEX, SELF_AP_UPPER_BORDER_INDEX, startIndexOfAction, s.ap)
+ between(ENEMY_HP_LOWER_BORDER_INDEX, ENEMY_HP_UPPER_BORDER_INDEX, startIndexOfAction, e.hp)
+ between(ENEMY_AP_LOWER_BORDER_INDEX, ENEMY_AP_UPPER_BORDER_INDEX, startIndexOfAction, e.ap)
);
}
private double between(int lowerIndex, int upperIndex, int offset, int value) {
return (chromosome[offset + lowerIndex] <= value && chromosome[offset + upperIndex] >= value) ? 1 : 0;
}
}
| 40.014085
| 111
| 0.680746
|
76b8cd005e8b8309acf549d57a9f48637b08110b
| 5,887
|
/*
* Copyright (c) 2009 Haefelinger IT
*
* 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 it.haefelinger.flaka;
import it.haefelinger.flaka.util.HttpUpload;
import it.haefelinger.flaka.util.Static;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.types.FileSet;
/**
*
* @author merzedes
* @since 1.0
*/
public class HttpUploadTask extends Task {
protected File rcfile;
protected HttpUpload uploader;
protected List filesets;
protected File logdir;
protected String acceptpat;
protected String errorpat;
public HttpUploadTask() {
this.uploader = new HttpUpload();
this.filesets = new ArrayList();
this.logdir = null;
}
public void setAcceptIf(String s) {
this.acceptpat = Static.trim2(s, this.acceptpat);
}
public void setErrorIf(String s) {
this.errorpat = Static.trim2(s, this.errorpat);
}
public void setLogdir(File logdir) {
this.logdir = logdir;
}
public void setEndpoint(String S) {
String s = Static.trim2(S, null);
if (s != null)
this.uploader.set("endpoint", s);
}
public void setTest(boolean b) {
this.uploader.set("testonly", b ? "true" : "false");
}
public void setCategory(String S) {
String s = Static.trim2(S, null);
if (s != null)
this.uploader.set("category", s);
}
public void setRcFile(File file) {
this.rcfile = file;
}
public void setDebug(boolean b) {
this.uploader.setDebug(b);
}
public void addFileset(FileSet set) {
if (set != null) {
this.filesets.add(set);
}
}
public boolean isTest() {
return this.uploader.get("testonly", "").matches("\\s*true\\s*");
}
public String[] eval(FileSet fs) throws BuildException {
DirectoryScanner ds;
File dir;
String[] files;
if (fs == null)
return null;
ds = fs.getDirectoryScanner(getProject());
dir = fs.getDir(getProject());
files = ds.getIncludedFiles();
for (int i = 0; i < files.length; ++i) {
String s;
s = files[i];
files[i] = new File(dir, s).getAbsolutePath();
}
return files;
}
// The method executing the task
public void execute() throws BuildException {
String s;
if (this.debug) {
/* enable debug output */
// HttpUpload.debug(true);
}
if (this.filesets == null) {
throwbx("this task must be used with at least on <fileset>.");
}
/* read username and password from a hidden RC loc */
if (this.rcfile != null) {
String[] words;
s = this.rcfile.getAbsolutePath();
if (!this.rcfile.exists()) {
throwbx("loc `" + s + "' does not exist.");
}
/* read username and password from this loc */
s = Static.readlines(this.rcfile);
if (s == null) {
throwbx("unable to read from loc `" + s + "'.");
return;
}
/* split into words */
words = s.split("\\s+");
if (words == null || words.length < 2) {
throwbx("syntax error while parsing loc `" + s + "' - too few words.");
return;
}
/* format: username password */
this.uploader.set("user", words[0]);
this.uploader.set("passwd", words[1]);
}
boolean errorseen = false;
/* TODO: not used right now .. */
this.uploader.set("accept-if", this.acceptpat);
for (int i = 0; i < this.filesets.size(); ++i) {
String[] files;
files = eval((FileSet) this.filesets.get(i));
if (files == null)
continue;
for (int j = 0; j < files.length; ++j) {
File f;
boolean rc;
f = new File(files[j]);
this.uploader.set("filepath", f.getPath());
rc = this.uploader.upload();
if (this.logdir != null) {
String buf;
String name = f.getPath().replaceAll("/|\\.\\.|\\\\|:|\\.", "_");
buf = this.uploader.get("xmlbuf", null);
savebuf(buf, "upload-" + name + ".xml");
buf = this.uploader.get("resbuf", null);
savebuf(buf, "upload-" + name + ".txt");
}
if (!rc) {
String errmsg;
errorseen = true;
errmsg = this.uploader.getError();
if (isTest())
info(errmsg);
else
throwbx(errmsg);
} else {
info("loc `" + this.uploader.get("filepath", "") + "' uploaded.");
}
}
}
if (errorseen) {
throwbx("error(s) seen while uploading files.");
}
}
/**
* Save content of buffer buf into logdir using filename fname.
*
* @param buf
* @param fname
* @return true if no error occured
*/
private boolean savebuf(String buf, String fname) {
boolean good = true;
FileOutputStream fo = null;
File u;
if (this.logdir != null && buf != null && fname != null) {
u = new File(this.logdir, fname);
this.debug("writing upload log report: " + u.getAbsolutePath());
try {
fo = new FileOutputStream(u);
fo.write(buf.getBytes());
} catch (Exception e) {
good = false;
this.error("unable to write upload log report: ", e);
} finally {
Static.close(fo);
}
}
return good;
}
}
| 24.839662
| 80
| 0.588415
|
bef8043d60544c2e0ad0e083f213180145d29830
| 2,000
|
package com.chason.base.relearning.jmh;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.results.RunResult;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 1)
@Measurement(iterations = 1)
@State(Scope.Benchmark)
public class CalcculatorBenchmark {
@Param({"10000", "100000", "1000000"})
private int length;
private int[] numbers;
private Calculator singleCalculator;
private Calculator multiCalculator;
@Benchmark
public long singleCalculator() {
return singleCalculator.sum(numbers);
}
@Benchmark
public long multiCalculator() {
return multiCalculator.sum(numbers);
}
@Setup
public void prepare() {
numbers = IntStream.rangeClosed(1, length).toArray();
singleCalculator = new SingleCalculator();
multiCalculator = new MultiCalculator(Runtime.getRuntime().availableProcessors());
}
@TearDown
public void shutdown() {
singleCalculator.shutdown();
multiCalculator.shutdown();
}
public static void main(String[] args) throws RunnerException {
// numbers = IntStream.rangeClosed(1,1000000).toArray();
// singleCalculator = new SingleCalculator();
// multiCalculator = new MultiCalculator(Runtime.getRuntime().availableProcessors());
// System.out.println(singleCalculator.sum(numbers));
// System.out.println(multiCalculator.sum(numbers));
Options options = new OptionsBuilder()
.include(CalcculatorBenchmark.class.getSimpleName())
.forks(1)
.build();
Collection<RunResult> results = new Runner(options).run();
}
}
| 29.850746
| 92
| 0.6975
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.