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
4fe68c34c48ee2168eacee25a937cd4619f8c039
7,471
/* * Copyright (c) 2017 Patrick Scheibe * 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 de.halirutan.mathematica.actions; import com.intellij.ide.actions.CreateFileFromTemplateAction; import com.intellij.ide.actions.CreateFileFromTemplateDialog.Builder; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.ide.fileTemplates.FileTemplateManager; import com.intellij.ide.fileTemplates.FileTemplateUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.ui.InputValidator; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import de.halirutan.mathematica.file.MathematicaFileType; import de.halirutan.mathematica.file.MathematicaTemplateProperties; import de.halirutan.mathematica.module.MathematicaLanguageLevelModuleExtension; import de.halirutan.mathematica.sdk.MathematicaLanguageLevel; import de.halirutan.mathematica.sdk.MathematicaSdkType; import de.halirutan.mathematica.util.MathematicaIcons; import java.util.Properties; /** * Provides the creation of new Mathematica files through the IDEA <em >new...</em> action. * <p> * TODO: This should be reworked. * The global string identifier for the templates should use {@link de.halirutan.mathematica.file.MathematicaFileTemplateProvider} * instead. Furthermore, we don't use the framework of {@link CreateFileFromTemplateAction} which is ugly as shit. * Instead, the variables we set inside the file template could be live templates that are active as soon as the file * is created and we only fill it with the default values. This gives the user the ability to fix settings. Not a pressing * matter so I'll leave it for now. * * @author patrick (4/8/13) */ public class CreateMathematicaFile extends CreateFileFromTemplateAction implements DumbAware { private static final String NEW_M_FILE = "New Mathematica file"; private static final String PACKAGE = "Package"; private static final String PLAIN = "Plain"; private static final String TEST = "Test"; private static final String NOTEBOOK = "Notebook"; private Project myProject = null; public CreateMathematicaFile() { super(NEW_M_FILE, "Creates a new .m Mathematica package file", MathematicaIcons.FILE_ICON); } @Override protected void buildDialog(Project project, PsiDirectory directory, Builder builder) { myProject = project; final MyNameValidator nameValidator = new MyNameValidator(MathematicaFileType.DEFAULT_EXTENSIONS); builder.setTitle(NEW_M_FILE).addKind(PACKAGE, MathematicaIcons.FILE_ICON, PACKAGE); builder.setTitle(NEW_M_FILE).addKind(PLAIN, MathematicaIcons.FILE_ICON, PLAIN); builder.setTitle(NEW_M_FILE).addKind(TEST, MathematicaIcons.FILE_ICON, TEST); builder.setTitle(NEW_M_FILE).addKind(NOTEBOOK, MathematicaIcons.FILE_ICON, NOTEBOOK); builder.setValidator(nameValidator); } @Override protected String getActionName(PsiDirectory directory, String newName, String templateName) { return NEW_M_FILE; } @Override public int hashCode() { return 0; } @Override public boolean equals(Object obj) { return obj instanceof CreateMathematicaFile; } @Override protected PsiFile createFile(String name, String templateName, PsiDirectory dir) { MathematicaLanguageLevel version = null; final String fileWithoutExtension = StringUtil.trimExtensions(name); final Module module = ModuleUtilCore.findModuleForFile(dir.getVirtualFile(), myProject); if (module != null) { final MathematicaLanguageLevelModuleExtension languageLevelModuleExtension = MathematicaLanguageLevelModuleExtension.getInstance(module); if (languageLevelModuleExtension != null) { version = languageLevelModuleExtension.getMathematicaLanguageLevel(); } else { final Sdk projectSdk = ProjectRootManager.getInstance(myProject).getProjectSdk(); if (projectSdk instanceof MathematicaSdkType) { version = MathematicaLanguageLevel.createFromSdk(projectSdk); } } } if (version == null) { version = MathematicaLanguageLevel.HIGHEST; } MathematicaTemplateProperties props = MathematicaTemplateProperties.create(); props.setProperty(MathematicaTemplateProperties.MATHEMATICA_VERSION, version.getName()); props.setProperty(MathematicaTemplateProperties.CONTEXT, fileWithoutExtension + "`"); props.setProperty(MathematicaTemplateProperties.PACKAGE_NAME, fileWithoutExtension); props.setProperty(MathematicaTemplateProperties.PACKAGE_VERSION, "0.1"); final FileTemplateManager fileTemplateManager = FileTemplateManager.getInstance(myProject); final Properties defaultProperties = fileTemplateManager.getDefaultProperties(); defaultProperties.putAll(props.getProperties()); final FileTemplate template = fileTemplateManager.getInternalTemplate(templateName); try { final PsiElement psiElement = FileTemplateUtil.createFromTemplate(template, name, defaultProperties, dir); if (psiElement instanceof PsiFile) { return (PsiFile) psiElement; } } catch (Exception e) { LOG.error("Error while creating new file", e); } LOG.error("Could not create file"); return null; } /** * Provides a simple check for file extension */ private class MyNameValidator implements InputValidator { private final String[] myExtensions; MyNameValidator(String[] myExtensions) { this.myExtensions = myExtensions; } @Override public boolean checkInput(String inputString) { return inputString != null && hasValidFileExtension(inputString, myExtensions); } private boolean hasValidFileExtension(String input, String... extensions) { if (FileUtilRt.getNameWithoutExtension(input).equals(input)) { return true; } for (String ext : extensions) { if (FileUtilRt.extensionEquals(input, ext)) return true; } return false; } @Override public boolean canClose(String inputString) { return checkInput(inputString); } } }
41.73743
130
0.766564
2eb3df50b361242dc147b9ee579dec4597eff8a3
2,220
package com.fy.baselibrary.utils; import java.util.concurrent.BlockingQueue; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * 线程相关 工具类 * Created by fangs on 2018/5/25. */ public class ThreadUtils { /** * 一般说来,大家认为线程池的大小经验值应该这样设置:(其中N为CPU的核数) 如果是IO密集型应用,则线程池大小设置为2N+1 如果是CPU密集型应用,则线程池大小设置为N+1 那么我们的 Android 应用是属于哪一种应用呢?看下他们的定义。 I/O密集型 I/O bound 指的是系统的CPU效能相对硬盘/内存的效能要好很多,此时,系统运作, 大部分的状况是 CPU 在等 I/O (硬盘/内存) 的读/写,此时 CPU Loading 不高。 CPU-bound CPU bound 指的是系统的 硬盘/内存 效能 相对 CPU 的效能 要好很多,此时,系统运作, 大部分的状况是 CPU Loading 100%,CPU 要读/写 I/O (硬盘/内存), I/O在很短的时间就可以完成,而 CPU 还有许多运算要处理,CPU Loading 很高。 我们的Android 应用的话应该是属于IO密集型应用,所以数量一般设置为 2N+1。 */ //参数初始化 public static final int CPU_COUNT = Runtime.getRuntime().availableProcessors(); //核心线程数量大小 public static final int corePoolSize = Math.max(2, Math.min(CPU_COUNT - 1, 4)); //线程池最大容纳线程数 public static final int maximumPoolSize = CPU_COUNT * 2 + 1; //线程空闲后的存活时长 public static final int keepAliveTime = 30; //任务过多后,存储任务的一个阻塞队列 BlockingQueue workQueue = new SynchronousQueue<>(); private ThreadUtils() { /* cannot be instantiated */ throw new UnsupportedOperationException("cannot be instantiated"); } //线程的创建工厂 ThreadFactory threadFactory = new ThreadFactory() { private final AtomicInteger mCount = new AtomicInteger(1); public Thread newThread(Runnable r) { return new Thread(r, "AdvacnedAsyncTask #" + mCount.getAndIncrement()); } }; //线程池任务满载后采取的任务拒绝策略 RejectedExecutionHandler rejectHandler = new ThreadPoolExecutor.DiscardOldestPolicy(); //线程池对象,创建线程 ThreadPoolExecutor mExecute = new ThreadPoolExecutor( corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue, threadFactory, rejectHandler ); }
30
90
0.678829
e3232a3d83f0f286c012b6d16fb19b35966358b1
734
package net.coding.program.common.model; import android.content.Context; /** * Created by chenchao on 2017/1/18. */ public class EnterpriseAccountInfo extends AccountInfo { private static final String ENTERPRISE_DETAIL = "ENTERPRISE_DETAIL"; public static void saveEnterpriseDetail(Context context, EnterpriseDetail data) { new DataCache<CustomHost>().saveGlobal(context, data, ENTERPRISE_DETAIL); } public static EnterpriseDetail loadEnterpriseDetail(Context context) { EnterpriseDetail detail = new DataCache<EnterpriseDetail>().loadGlobalObject(context, ENTERPRISE_DETAIL); if (detail == null) { detail = new EnterpriseDetail(); } return detail; } }
28.230769
113
0.716621
947b68d8d208c5a0cd6fa85236c6c4a1717dd57d
3,183
/* * Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ru.apertum.qsystem.reports.net; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.protocol.HttpRequestHandlerRegistry; /** * * @author Evgeniy Egorov */ public class QSystemHtmlInstance { private static final QSystemHtmlInstance HTML_INSTANCE = new QSystemHtmlInstance(); public static QSystemHtmlInstance htmlInstance(){ return HTML_INSTANCE; } private QSystemHtmlInstance() { this.params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000). setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024). setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false). setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true). setParameter(CoreProtocolPNames.ORIGIN_SERVER, "QSystemReportHttpServer/1.1"); // Set up the HTTP protocol processor final BasicHttpProcessor httpproc = new BasicHttpProcessor(); httpproc.addInterceptor(new ResponseDate()); httpproc.addInterceptor(new ResponseServer()); httpproc.addInterceptor(new ResponseContent()); httpproc.addInterceptor(new ResponseConnControl()); // Set up request handlers final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("*", new HttpQSystemReportsHandler()); // Set up the HTTP service this.httpService = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, this.params); } private final HttpParams params = new BasicHttpParams(); private final HttpService httpService; public HttpService getHttpService() { return httpService; } public HttpParams getParams() { return params; } }
39.7875
94
0.734527
8341392ca501391a8af7c55cd404dad43e55be18
943
package com.xkcoding.dynamic.datasource.service.impl; import com.xkcoding.dynamic.datasource.mapper.UserMapper; import com.xkcoding.dynamic.datasource.model.User; import com.xkcoding.dynamic.datasource.service.UserService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service @RequiredArgsConstructor(onConstructor_ = @Autowired) public class UserServiceImpl implements UserService { private final UserMapper userMapper; @Override public int save(User u) { return userMapper.insert(u); } @Override public int delete(User u) { return userMapper.delete(u); } @Override public int update(User u) { return userMapper.updateByPrimaryKeySelective(u); } @Override public List<User> selectAll() { return userMapper.selectAll(); } }
25.486486
62
0.742312
2eb668d363f6d5b8e16d1b33a5286bab32b6be9c
12,051
package local.model; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.Timer; import local.controller.Sistema; import local.model.database.Avioes; import local.model.database.Destino; import local.model.database.Voos; import local.util.GetDateTime; import local.view.PanelVoos; public class VoosGraphics { private PanelVoos voosPanel; private Sistema sistema; private List<Avioes> avioesCadastrados; private List<Voos> voosList; private int numPagina = 1; private int numTotalPagina = 1; private double[] posicaoXinicialAvioes = new double[4]; private int[] posicaoXfinalAvioes = new int[4]; private double[] posicaoXinicialLines = new double[4]; private double[] posicaoXfinalLines = new double[4]; private int[] widthLine = new int[4]; private JPanel[] jpanelR = new JPanel[4]; private double[] kmPercorrido = new double[4]; private JLabel[] labelAviao = new JLabel[4]; private JLabel[] labelAviaoLine = new JLabel[4]; private final JLabel[] labelModelo = new JLabel[4]; private final JLabel[] labelVoo = new JLabel[4]; private final JLabel[] labelStatus = new JLabel[4]; private final JLabel[] labelDestino = new JLabel[4]; private final JLabel[] labelVelocidade = new JLabel[4]; private final JLabel[] labelTempoRest = new JLabel[4]; public VoosGraphics(PanelVoos voos, Sistema sistema) { this.voosPanel = voos; this.sistema = sistema; timer.start(); avioesCadastrados = sistema.select(new Avioes()); voosList = sistema.getJpaVoos().findVoosEntities(); labelAviao[0] = voosPanel.getjLabelAviao1(); labelAviao[1] = voosPanel.getjLabelAviao2(); labelAviao[2] = voosPanel.getjLabelAviao3(); labelAviao[3] = voosPanel.getjLabelAviao4(); labelAviaoLine[0] = voosPanel.getjLabelAviaoLine1(); labelAviaoLine[1] = voosPanel.getjLabelAviaoLine2(); labelAviaoLine[2] = voosPanel.getjLabelAviaoLine3(); labelAviaoLine[3] = voosPanel.getjLabelAviaoLine4(); labelModelo[0] = voosPanel.getjLabelModelo1(); labelModelo[1] = voosPanel.getjLabelModelo2(); labelModelo[2] = voosPanel.getjLabelModelo3(); labelModelo[3] = voosPanel.getjLabelModelo4(); labelVoo[0] = voosPanel.getjLabelVoo1(); labelVoo[1] = voosPanel.getjLabelVoo2(); labelVoo[2] = voosPanel.getjLabelVoo3(); labelVoo[3] = voosPanel.getjLabelVoo4(); labelStatus[0] = voosPanel.getjLabelStatus1(); labelStatus[1] = voosPanel.getjLabelStatus2(); labelStatus[2] = voosPanel.getjLabelStatus3(); labelStatus[3] = voosPanel.getjLabelStatus4(); labelDestino[0] = voosPanel.getjLabelDestino1(); labelDestino[1] = voosPanel.getjLabelDestino2(); labelDestino[2] = voosPanel.getjLabelDestino3(); labelDestino[3] = voosPanel.getjLabelDestino4(); labelVelocidade[0] = voosPanel.getjLabelVelocidade1(); labelVelocidade[1] = voosPanel.getjLabelVelocidade2(); labelVelocidade[2] = voosPanel.getjLabelVelocidade3(); labelVelocidade[3] = voosPanel.getjLabelVelocidade4(); labelTempoRest[0] = voosPanel.getjLabelTempo1(); labelTempoRest[1] = voosPanel.getjLabelTempo2(); labelTempoRest[2] = voosPanel.getjLabelTempo3(); labelTempoRest[3] = voosPanel.getjLabelTempo4(); jpanelR[0] = voosPanel.getjPanelRAviao1(); jpanelR[1] = voosPanel.getjPanelRAviao2(); jpanelR[2] = voosPanel.getjPanelRAviao3(); jpanelR[3] = voosPanel.getjPanelRAviao4(); voosPanel.setVisible(true); setOriginPositions(); } public void setOriginPositions() { for (int i = 0; i < 4; i++) { posicaoXinicialLines[i] = labelAviaoLine[i].getLocation().getX(); posicaoXinicialAvioes[i] = labelAviao[i].getLocation().getX(); posicaoXfinalLines[i] = labelAviaoLine[i].getLocation().getX() + labelAviaoLine[i].getWidth(); widthLine[i] = labelAviaoLine[i].getWidth(); } } public void updateAvioesList() { avioesCadastrados = sistema.select(new Avioes()); } public void reset() { List<Voos> voos = sistema.getJpaVoos().findVoosEntities(); for (int i = 0; i < voos.size(); i++) { voos.get(i).setStatus("decolou"); try { sistema.getJpaVoos().edit(voos.get(i)); } catch (Exception ex) { System.out.println("erro reset"); } } } ActionListener update = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { List<Voos> voosNaoFinalizados = sistema.getJpaVoos().findVoosEntities(); // for (int i = 0; i < voosNaoFinalizados.size(); i++) { // if (voosNaoFinalizados.get(i).getStatus().equals("pousou")) { // voosNaoFinalizados.remove(i); // i--; // } // } numTotalPagina = (int) Math.round((voosNaoFinalizados.size() / 4) + 0.5); voosPanel.update(); for (int i = 0; i < 4; i++) { try { int id = i + ((numPagina - 1) * 4); Voos voo = voosNaoFinalizados.get(id); Destino destino = sistema.getJpaDestino().findDestino((long) voo.getAeroportoDestinoID()); Avioes aviao = sistema.getJpaAvioes().findAvioes(voo.getAviaoID()); if (voosNaoFinalizados.get(i).getStatus().equals("finalizado")) { labelAviaoLine[i].setSize(1, labelAviaoLine[i].getHeight()); labelAviaoLine[i].setLocation((int) jpanelR[i].getX() - 10, labelAviaoLine[i].getLocation().y); labelAviao[i].setLocation((int) labelAviaoLine[i].getX() - 20, labelAviao[i].getLocation().y); updateInfo(i, aviao, voo, destino, kmPercorrido[i], voosNaoFinalizados); sistema.getJpaVoos().edit(voo); } else { GetDateTime getTime = new GetDateTime(); int horaAtual = Integer.parseInt(getTime.getHoraAtual()); int minutoAtual = Integer.parseInt(getTime.getMinutoAtual()); String decolagem = voo.getHoraDecolagem(); String[] split = decolagem.split(":"); int horaDecolagem = Integer.parseInt(split[0]); int minutoDecolagem = Integer.parseInt(split[1]); if (horaAtual >= horaDecolagem) { if (horaAtual == horaDecolagem && minutoAtual >= minutoDecolagem) { voo.setStatus("decolou"); } else if (horaAtual > horaDecolagem) { voo.setStatus("decolou"); } sistema.getJpaVoos().edit(voo); } else { System.out.println("menor"); int horaRest = horaDecolagem - horaAtual; int minRest = -(minutoDecolagem - minutoAtual); voo.setStatus("decola em " + horaRest + "h" + minRest); sistema.getJpaVoos().edit(voo); } double pixelDistanciaMaxima = widthLine[i]; double kmDistanciaMaxima = destino.getDistancia(); double kmPmilSeg = (aviao.getVelocidade() / 3600.0) / 10.0; kmPercorrido[i] = kmPercorrido[i] + kmPmilSeg; double pixelPkm = pixelDistanciaMaxima / kmDistanciaMaxima; // for (int j = 0; j < 4; j++) { // labelAviaoLine[j].setBackground(new Color(55, 153, 0)); // } if (destino.getDistancia() <= kmPercorrido[i]) { voo.setStatus("finalizado"); sistema.getJpaVoos().edit(voo); } else if (voosNaoFinalizados.get(i).getStatus().equals("decolou")) { widthLine[i] = jpanelR[i].getX() - 10 - (labelVoo[i].getX() + labelVoo[i].getWidth() + 50); labelAviaoLine[i].setSize((int) (widthLine[i] - kmPercorrido[i] * pixelPkm), labelAviaoLine[i].getHeight()); labelAviaoLine[i].setLocation((int) (posicaoXinicialLines[i] + kmPercorrido[i] * pixelPkm), labelAviaoLine[i].getLocation().y); labelAviaoLine[i].setSize(jpanelR[i].getX() - labelAviaoLine[i].getX() - 10, labelAviaoLine[i].getHeight()); labelAviao[i].setLocation((int) (posicaoXinicialAvioes[i] + kmPercorrido[i] * pixelPkm), labelAviao[i].getLocation().y); } updateInfo(i, aviao, voo, destino, kmPercorrido[i], voosNaoFinalizados); } } catch (Exception ex) { // JOptionPane.showMessageDialog(null, ex.getStackTrace()); reset(i); } } } }; Timer timer = new Timer(100, update); private void updateInfo(int i, Avioes aviao, Voos voo, Destino destino, double kmPercorrido, List<Voos> voosNaoFinalizados) { // for (int j = 0; j < 4; j++) { // labelAviaoLine[j].setBackground(new Color(23, 25, 26)); // } labelModelo[i].setText(aviao.getModelo()); labelVoo[i].setText(String.valueOf(voo.getId())); labelStatus[i].setForeground(Color.GREEN); labelStatus[i].setText(voosNaoFinalizados.get(i + ((numPagina - 1) * 4)).getStatus()); labelDestino[i].setText(destino.getNome()); labelVelocidade[i].setText(String.valueOf(aviao.getVelocidade()) + "km/h"); double minutes = (destino.getDistancia() - kmPercorrido) / aviao.getVelocidade() * 60; String text; if (destino.getDistancia() <= kmPercorrido) { text = "finalizado"; } else if (voosNaoFinalizados.get(i + ((numPagina - 1) * 4)).getStatus().equals("decolou")) { if (((int) minutes) == 0) { text = "pousando em segundos..."; } else { text = String.valueOf((int) minutes + "min "); } // text = String.valueOf((int) minutes + "min " + String.format("%.2f", ((minutes - ((int) minutes)) * 60)) + "seg"); // text = String.valueOf((int) minutes + "min " + (int) ((minutes - ((int) minutes)) * 60)) + "seg"; } else { text = " - "; } labelTempoRest[i].setText(text); } private void reset(int i) { labelModelo[i].setText(" - "); labelVoo[i].setText(" - "); labelStatus[i].setForeground(Color.GREEN); labelStatus[i].setText(" - "); labelDestino[i].setText(" - "); labelVelocidade[i].setText(" - " + "km/h"); labelTempoRest[i].setText(" - "); } public int getNumPagina() { return numPagina; } public void setNumPagina(int numPagina) { this.numPagina = numPagina; } public int getNumTotalPagina() { return numTotalPagina; } public void setNumTotalPagina(int numTotalPagina) { this.numTotalPagina = numTotalPagina; } }
44.633333
156
0.561115
534dcbb63bcc248c534d9542a5f489dad0b0f18d
5,796
package said.ahmad.javafx.tracker.controller.connection.uri; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.ResourceBundle; import javafx.application.Platform; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.control.CheckBox; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import javafx.scene.layout.GridPane; import javafx.scene.layout.Pane; import javafx.scene.text.Text; import said.ahmad.javafx.fxGraphics.IntField; import said.ahmad.javafx.tracker.app.ResourcesHelper; import said.ahmad.javafx.tracker.app.ThreadExecutors; import said.ahmad.javafx.tracker.controller.connection.ConnectionController.ConnectionType; import said.ahmad.javafx.tracker.controller.connection.GenericConnectionController; import said.ahmad.javafx.tracker.datatype.ConnectionAccount; import said.ahmad.javafx.tracker.system.file.PathLayer; import said.ahmad.javafx.util.IpAddress; public class URIConnection implements Initializable, GenericConnectionController { /** * @return the portField */ public IntField getPortField() { return portField; } @FXML protected GridPane viewPane; @FXML protected IntField ipPart1Field; @FXML protected IntField ipPart2Field; @FXML protected IntField ipPart3Field; @FXML protected IntField ipPart4Field; @FXML protected IntField portField; @FXML protected TextField usernameField; @FXML protected PasswordField passwordField; @FXML protected CheckBox anonymousCheckBox; @FXML protected Text errorText; // just for easy access iteration protected ArrayList<TextField> allTextField = new ArrayList<>(); /** * Initializes the controller class. */ @Override public void initialize(URL url, ResourceBundle rb) { // IPs field allTextField.add(ipPart1Field); allTextField.add(ipPart2Field); allTextField.add(ipPart3Field); allTextField.add(ipPart4Field); allTextField.add(portField); allTextField.add(usernameField); errorText.setText(""); allTextField.forEach(txt -> txt.setText("")); for (int i = 0; i < 4; i++) { int j = i; allTextField.get(i).setOnKeyPressed(keyEvent -> { if (keyEvent.getCode().equals(KeyCode.DECIMAL)) { allTextField.get(j + 1).requestFocus(); } }); } anonymousCheckBox.selectedProperty().addListener((obser, old, isSelected) -> { if (isSelected) { usernameField.setDisable(true); passwordField.setDisable(true); } else { usernameField.setDisable(false); passwordField.setDisable(false); } }); } @Override public boolean checkInputValidation() { for (TextField textField : allTextField) { if (!textField.isDisabled() && (textField.getText() == null || textField.getText().isEmpty())) { textField.requestFocus(); errorText.setText("Please fill all field. This Field is required!\nHint:" + textField.getPromptText()); return false; } } errorText.setText(""); return true; } public String getIPAddress() { return ipPart1Field.getValue() + "." + ipPart2Field.getValue() + "." + ipPart3Field.getValue() + "." + ipPart4Field.getValue(); } public URI getURIConnection(String scheme) throws URISyntaxException { URI uri = null; String username = usernameField.getText(); String password = passwordField.getText(); if (usernameField.isDisabled()) { username = null; password = null; } String userInfo = username == null || username.isEmpty() ? null : username + (password == null || password.isEmpty() ? "" : ":" + password); uri = new URI(scheme, userInfo, getIPAddress(), portField.getValue(), null, null, null); return uri; } public void initializeInputFieldsWithLocalHost() { ThreadExecutors.recursiveExecutor.execute(() -> { String ip = IpAddress.getLocalAddress(); if (ip != null) { ConnectionAccount account = new ConnectionAccount(); account.setHost(ip); Platform.runLater(() -> setInputFields(account)); } }); } public void setInputFields(ConnectionAccount account) { ArrayList<Integer> ipsAsInt = IpAddress.splitIpAddress(account.getHost()); setInputFields(ipsAsInt.get(0), ipsAsInt.get(1), ipsAsInt.get(2), ipsAsInt.get(3), account.getPort(), account.getUsername(), account.getPassword()); } public void setInputFields(Integer ipPart1, Integer ipPart2, Integer ipPart3, Integer ipPart4, Integer port, String user, String password) { if (ipPart1 != null) { ipPart1Field.setText(ipPart1.toString()); } if (ipPart2 != null) { ipPart2Field.setText(ipPart2.toString()); } if (ipPart3 != null) { ipPart3Field.setText(ipPart3.toString()); } if (ipPart4 != null) { ipPart4Field.setText(ipPart4.toString()); } if (port != null) { portField.setText(port.toString()); } if (user != null) { usernameField.setText(user); } if (password != null) { passwordField.setText(password); } } @Override public boolean testConnection() throws Exception { return false; } @Override public PathLayer connect() throws Exception { return null; } @Override public void clearAllFields() { allTextField.forEach(txt -> txt.setText("")); } @Override public FXMLLoader loadFXML() throws IOException { FXMLLoader loader = new FXMLLoader(); loader.setLocation(ResourcesHelper.getResourceAsURL("/fxml/connection/uri/URIConnection.fxml")); loader.setController(this); loader.load(); return loader; } @Override public Pane getViewPane() { return viewPane; } @Override public ConnectionType getConnectionType() { return null; } @Override public void initializeDefaultFields() { initializeInputFieldsWithLocalHost(); } }
25.991031
109
0.728951
dca040e19a87ae3b174a897ab8db2f3425974ecc
1,088
package com.jishukezhan.http; import com.jishukezhan.annotation.Nullable; import com.jishukezhan.core.exceptions.IoRuntimeException; import java.io.Closeable; import java.io.InputStream; import java.io.Reader; import java.nio.charset.Charset; /** * HTTP响应内容接口 */ public interface ResponseBody extends Closeable { /** * 字节的长度,可能为{@code null} * * @return 字节长度 */ @Nullable Integer length(); /** * 是否支持重复读取,如果为{@code true}则 {@link #byteStream()} 和 {@link #charStream(Charset)} 可以被多次调用 */ boolean isRepeatable(); /** * 获得响应内容的流 * * @throws IoRuntimeException 流操作异常 */ InputStream byteStream() throws IoRuntimeException; /** * 将响应内容按照指定编码{@code charset}转为对应的流 * * @param charset 编码,可空 */ Reader charStream(@Nullable Charset charset) throws IoRuntimeException; /** * 将响应内容转为字符串,并且会自动关闭流 * * @param charset 编码字符集,可空, * @return 响应字符串 * @throws IoRuntimeException IO异常 */ String string(@Nullable Charset charset) throws IoRuntimeException; }
20.528302
93
0.650735
85352f29b3b64b3b816a07da0b4d71d21df2fb6b
2,654
// Copyright (c) 2020, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.tracereferences; import com.android.tools.r8.references.MethodReference; import com.android.tools.r8.tracereferences.TraceReferencesConsumer.TracedClass; import com.android.tools.r8.tracereferences.TraceReferencesConsumer.TracedField; import com.android.tools.r8.tracereferences.TraceReferencesConsumer.TracedMethod; import com.android.tools.r8.utils.StringUtils; import java.util.List; class KeepRuleFormatter extends Formatter { final boolean allowObfuscation; KeepRuleFormatter(boolean allowObfuscation) { this.allowObfuscation = allowObfuscation; } @Override protected void printTypeHeader(TracedClass tracedClass) { append(allowObfuscation ? "-keep,allowobfuscation" : "-keep"); if (tracedClass.getAccessFlags().isInterface()) { appendLine(" interface " + tracedClass.getReference().getTypeName() + " {"); } else if (tracedClass.getAccessFlags().isEnum()) { appendLine(" enum " + tracedClass.getReference().getTypeName() + " {"); } else { appendLine(" class " + tracedClass.getReference().getTypeName() + " {"); } } @Override protected void printConstructorName(MethodReference method) { append("<init>"); } @Override protected void printField(TracedField field) { append( " " + field.getReference().getFieldType().getTypeName() + " " + field.getReference().getFieldName() + ";" + System.lineSeparator()); } @Override protected void printMethod(TracedMethod tracedMethod) { if (tracedMethod.getReference().getMethodName().equals("<clinit>")) { return; } append(" "); if (tracedMethod.getAccessFlags().isPublic()) { append("public "); } else if (tracedMethod.getAccessFlags().isPrivate()) { append("private "); } else if (tracedMethod.getAccessFlags().isProtected()) { append("protected "); } if (tracedMethod.getAccessFlags().isStatic()) { append("static "); } printNameAndReturn(tracedMethod.getReference()); printArguments(tracedMethod.getReference()); appendLine(";"); } @Override protected void printPackageNames(List<String> packageNames) { if (!packageNames.isEmpty()) { append("-keeppackagenames " + StringUtils.join(packageNames, ",") + System.lineSeparator()); } } @Override protected void printTypeFooter() { appendLine("}"); } }
32.765432
98
0.686134
db9f1ecba147354fcdfe3204d21a9175db25a3ca
715
package problems._77; import org.junit.Assert; import org.junit.Test; import java.util.List; import static org.junit.Assert.*; public class SolutionTest { @Test public void test() { { final List<List<Integer>> expected = List.of( List.of(2, 4), List.of(3, 4), List.of(2, 3), List.of(1, 2), List.of(1, 3), List.of(1, 4) ); final List<List<Integer>> calculated = new Solution().combine(4, 2); Assert.assertTrue(expected.containsAll(calculated)); Assert.assertTrue(calculated.containsAll(expected)); } } }
25.535714
80
0.507692
44f555c5b1928e43c5f0c30fa083776d8691cda2
463
package ghostawt; import java.awt.MenuItem; import java.awt.peer.MenuPeer; public class GMenuPeer extends GMenuItemPeer implements MenuPeer { protected GMenuPeer(Object target) { super(target); } public GMenuPeer(MenuItem target) { super(target); } @Override public void addSeparator() { } @Override public void addItem(MenuItem item) { } @Override public void delItem(int index) { } }
17.807692
66
0.647948
785d443cd12405c934ceed5a1f7e67cf03a1eb7a
2,015
/* * C O P Y R I G H T N O T I C E * ----------------------------------------------------------------------- * Copyright (c) 2011-2012 InfoClinika, Inc. 5901 152nd Ave SE, Bellevue, WA 98006, * United States of America. (425) 442-8058. http://www.infoclinika.com. * All Rights Reserved. Reproduction, adaptation, or translation without prior written permission of InfoClinika, * Inc. is prohibited. * Unpublished--rights reserved under the copyright laws of the United States. RESTRICTED RIGHTS LEGEND Use, * duplication or disclosure by the */ package com.infoclinika.mssharing.web.controller; import com.infoclinika.mssharing.platform.model.helper.SharingProjectHelperTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.inject.Inject; import javax.inject.Named; import java.security.Principal; import java.util.List; import static com.infoclinika.mssharing.platform.web.security.RichUser.getUserId; /** * @author Stanislav Kurilin */ @Controller @RequestMapping("/users") public class UsersController extends ErrorHandler { @Inject @Named("defaultSharingProjectShortRecordAdapter") private SharingProjectHelperTemplate sharingProjectHelper; @RequestMapping(method = RequestMethod.GET) @ResponseBody public List<SharingProjectHelperTemplate.UserDetails> getUsers() { return sharingProjectHelper.getAvailableUsers(); } @RequestMapping(value = "/project-collaborators/{experimentId}", method = RequestMethod.GET) @ResponseBody public List<SharingProjectHelperTemplate.UserDetails> getCollaborators( @PathVariable long experimentId, Principal principal ) { return sharingProjectHelper.getCollaborators(getUserId(principal), experimentId); } }
36.636364
114
0.748883
69a01422a43392fb19bda7b15ed64d26c1de525d
753
package ru.otus.mapper; import ru.otus.domain.Author; import ru.otus.domain.Book; import ru.otus.domain.Comment; import ru.otus.domain.Genre; import ru.otus.dto.AuthorDto; import ru.otus.dto.BookDto; import ru.otus.dto.CommentDto; import ru.otus.dto.GenreDto; import java.util.List; public interface Mapper { BookDto sourceToBookDto(Book source); List<BookDto> sourceToListBookDto(List<Book> source); AuthorDto sourceToAuthorDto(Author source); List<AuthorDto> sourceToListAuthorDto(List<Author> source); GenreDto sourceToGenreDto(Genre source); List<GenreDto> sourceToListGenreDto(List<Genre> source); CommentDto sourceToCommentDto(Comment source); List<CommentDto> sourceToListCommentDto(List<Comment> source); }
27.888889
66
0.77822
0c6061f137c3493794564adefacd668e9767a8ce
1,154
package io.github.iliecirciumaru.dcc.rules.integration.model; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.google.auto.value.AutoValue; import java.util.List; @AutoValue @JsonDeserialize(builder = AutoValue_CertLogicTestCase.Builder.class) public abstract class CertLogicTestCase { public static Builder builder() { return new AutoValue_CertLogicTestCase.Builder(); } @JsonProperty("name") public abstract String getName(); @JsonProperty("certLogicExpression") public abstract Object getCertLogicExpression(); @JsonProperty("assertions") public abstract List<CertLogicTestAssertion> getAssertions(); @AutoValue.Builder public abstract static class Builder { @JsonProperty("name") public abstract Builder setName(String newName); @JsonProperty("certLogicExpression") public abstract Builder setCertLogicExpression(Object newCertLogicExpression); @JsonProperty("assertions") public abstract Builder setAssertions(List<CertLogicTestAssertion> newAssertions); public abstract CertLogicTestCase build(); } }
28.85
86
0.791161
f6d3bd12d75fcbf21740796a59d175989ae5596b
6,468
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.authority.provider.database; import org.apache.shardingsphere.authority.model.PrivilegeType; import org.apache.shardingsphere.authority.provider.natived.model.privilege.database.DatabasePrivileges; import org.apache.shardingsphere.authority.provider.natived.model.privilege.database.SchemaPrivileges; import org.apache.shardingsphere.authority.provider.natived.model.privilege.database.TablePrivileges; import org.junit.Before; import org.junit.Test; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.Map; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; public final class DatabasePrivilegesTest { private static DatabasePrivileges privileges = new DatabasePrivileges(); @Before public void setUp() { privileges = buildPrivilege(); } @Test public void assertGetGlobalPrivileges() { assertThat(privileges.getGlobalPrivileges(), instanceOf(Collection.class)); assertTrue(privileges.getGlobalPrivileges().isEmpty()); privileges.getGlobalPrivileges().add(PrivilegeType.SELECT); assertTrue(privileges.getGlobalPrivileges().containsAll(Collections.singletonList(PrivilegeType.SELECT))); assertFalse(privileges.getGlobalPrivileges().containsAll(Collections.singletonList(PrivilegeType.DELETE))); privileges.getGlobalPrivileges().add(PrivilegeType.DELETE); assertTrue(privileges.getGlobalPrivileges().containsAll(Collections.singletonList(PrivilegeType.DELETE))); } @Test public void assertGetSpecificPrivileges() { assertThat(privileges.getSpecificPrivileges(), instanceOf(Map.class)); assertThat(privileges.getSpecificPrivileges().get("schema1"), instanceOf(SchemaPrivileges.class)); assertThat(privileges.getSpecificPrivileges().get("schema1").getSpecificPrivileges().get("table1"), instanceOf(TablePrivileges.class)); assertTrue(privileges.getSpecificPrivileges().get("schema1").getSpecificPrivileges().get("table1").getPrivileges().containsAll(Collections.singletonList(PrivilegeType.SELECT))); assertFalse(privileges.getSpecificPrivileges().get("schema1").getSpecificPrivileges().get("table1").getPrivileges().containsAll(Collections.singletonList(PrivilegeType.DELETE))); assertTrue(privileges.getSpecificPrivileges().get("schema2").getSpecificPrivileges().get("table3").getPrivileges().containsAll(Collections.singletonList(PrivilegeType.DELETE))); assertFalse(privileges.getSpecificPrivileges().get("schema2").getSpecificPrivileges().get("table3").getPrivileges().containsAll(Collections.singletonList(PrivilegeType.UPDATE))); } @Test public void assertHasPrivileges() { assertTrue(privileges.hasPrivileges("schema1", "table1", Collections.singletonList(PrivilegeType.SELECT))); assertFalse(privileges.hasPrivileges("schema1", "table3", Collections.singletonList(PrivilegeType.SELECT))); assertTrue(privileges.hasPrivileges("schema2", "table3", Collections.singletonList(PrivilegeType.SELECT))); assertFalse(privileges.hasPrivileges("schema1", "table1", Collections.singletonList(PrivilegeType.DELETE))); assertFalse(privileges.hasPrivileges("schema1", "table2", Collections.singletonList(PrivilegeType.DELETE))); assertTrue(privileges.hasPrivileges("schema2", "table3", Collections.singletonList(PrivilegeType.DELETE))); privileges.getGlobalPrivileges().add(PrivilegeType.DELETE); assertTrue(privileges.hasPrivileges("schema1", "table1", Collections.singletonList(PrivilegeType.DELETE))); assertTrue(privileges.hasPrivileges("schema1", Collections.singletonList(PrivilegeType.DELETE))); assertTrue(privileges.hasPrivileges("schema2", Collections.singletonList(PrivilegeType.DELETE))); assertFalse(privileges.hasPrivileges("schema1", Collections.singletonList(PrivilegeType.UPDATE))); assertFalse(privileges.hasPrivileges("schema2", Collections.singletonList(PrivilegeType.UPDATE))); privileges.getGlobalPrivileges().add(PrivilegeType.UPDATE); assertTrue(privileges.hasPrivileges("schema1", Collections.singletonList(PrivilegeType.UPDATE))); assertTrue(privileges.hasPrivileges("schema2", Collections.singletonList(PrivilegeType.UPDATE))); } private DatabasePrivileges buildPrivilege() { Collection<PrivilegeType> tablePrivileges1 = new LinkedList<>(); Collection<PrivilegeType> tablePrivileges2 = new LinkedList<>(); tablePrivileges1.add(PrivilegeType.SELECT); tablePrivileges2.add(PrivilegeType.SELECT); tablePrivileges2.add(PrivilegeType.DELETE); SchemaPrivileges schema1Privilege = new SchemaPrivileges("schema1"); schema1Privilege.getSpecificPrivileges().put("table1", new TablePrivileges("table1", tablePrivileges1)); schema1Privilege.getSpecificPrivileges().put("table2", new TablePrivileges("table2", tablePrivileges1)); SchemaPrivileges schema2Privilege = new SchemaPrivileges("schema2"); schema2Privilege.getSpecificPrivileges().put("table3", new TablePrivileges("table3", tablePrivileges2)); schema2Privilege.getSpecificPrivileges().put("table4", new TablePrivileges("table4", tablePrivileges2)); DatabasePrivileges result = new DatabasePrivileges(); result.getSpecificPrivileges().put("schema1", schema1Privilege); result.getSpecificPrivileges().put("schema2", schema2Privilege); return result; } }
61.6
186
0.769635
79af6b3a706535be565e6fb794bbecde7588904e
1,465
package com.bzh.gl.native_lesson1; import android.app.ActivityManager; import android.content.Context; import android.content.pm.ConfigurationInfo; import android.opengl.GLSurfaceView; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; public class NativeLesson1Activity extends AppCompatActivity { private GLSurfaceView mGlSurfaceView; private boolean rendererSet; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo(); boolean supportES2 = configurationInfo.reqGlEsVersion >= 0x2000; if (supportES2) { mGlSurfaceView = new GLSurfaceView(this); mGlSurfaceView.setEGLContextClientVersion(2); mGlSurfaceView.setRenderer(new RendererWrapper()); rendererSet = true; setContentView(mGlSurfaceView); } } @Override protected void onPause() { super.onPause(); if (mGlSurfaceView != null) { mGlSurfaceView.onPause(); } } @Override protected void onResume() { super.onResume(); if (mGlSurfaceView != null) { mGlSurfaceView.onResume(); } } }
30.520833
103
0.694198
dacc5edb4d06eebeb03c0adbdc2d1992ef60e57c
274
package com.zhzteam.zhz233.test; import com.zhzteam.zhz233.common.utils.REVUtils; import org.junit.Test; public class REVTest { @Test public void TestisLogonInfo(){ String str="15123328416_+"; System.err.println(REVUtils.isLogonInfo(str)); } }
21.076923
54
0.70073
0152b7689a7ab088272c2522f519464f0b58f132
2,741
package eas.com.model; import eas.com.exception.QuickMartException; import java.time.LocalDate; import java.util.HashMap; import java.util.Map; /** * Class for simulating the shopping cart * Created by eduardo on 12/12/2016. */ public class ShoppingCart { /** * Key: Name of Item * Value: Relation Item-Quantity @see {@link ItemQuantity} */ private Map<String, ItemQuantity> boughtItemMap; /** * False: Regular Customer * True: Member Customer */ private boolean memberCustomer; /** * The id transaction of the shopping cart */ private String transaction; /** * The date that is created the Shopping Cart */ private LocalDate localDate; public ShoppingCart(boolean memberCustomer, String transaction) { this.boughtItemMap = new HashMap<>(); this.memberCustomer = memberCustomer; this.transaction = transaction; this.localDate = LocalDate.now(); } /** * Remove a quantity of item from shopping cart * @param nameItem name of item * @param quantity count of items * @return ItemQuantity * @throws QuickMartException if do not exist the item or the count is not enough */ public ItemQuantity removeItemQuantity(String nameItem, int quantity) throws QuickMartException { ItemQuantity boughtItem; if ((boughtItem = this.boughtItemMap.get(nameItem)) == null) { throw new QuickMartException("There is not the item: " + nameItem + " in the shopping cart"); } ItemQuantity itemQuantityDecrement = boughtItem.decrease(quantity); if (boughtItem.isItemSoldOut()) this.boughtItemMap.remove(nameItem); return itemQuantityDecrement; } /** * Add an item to shopping cart * * @param itemQuantity for adding */ public void addItemQuantity(ItemQuantity itemQuantity) { if (!this.boughtItemMap.containsKey(itemQuantity.getItem().getName())) { this.boughtItemMap.put(itemQuantity.getItem().getName(), itemQuantity); } else { this.boughtItemMap.get(itemQuantity.getItem().getName()).increase(itemQuantity); } } public boolean isMemberCustomer() { return memberCustomer; } public String getTypeCustomer(){ return this.memberCustomer ? "Rewards Member" : "Regular customer"; } public String getTransaction() { return transaction; } public LocalDate getLocalDate() { return localDate; } public Map<String, ItemQuantity> getBoughtItemMap() { return boughtItemMap; } public boolean isEmpty(){ return this.boughtItemMap.isEmpty(); } }
26.104762
105
0.650128
0273457e8aa5bcd5496fa5befb1a3e698841dbff
1,410
/* * Copyright MapStruct Authors. * * Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 */ package org.mapstruct.ap.test.bugs._1714; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import org.mapstruct.factory.Mappers; @Mapper public interface Issue1714Mapper { Issue1714Mapper INSTANCE = Mappers.getMapper( Issue1714Mapper.class ); @Mapping(source = "programInstance", target = "seasonNumber", qualifiedByName = "getSeasonNumber") OfferEntity map(OnDemand offerStatusDTO); @Named("getTitle") default String mapTitle(Program programInstance) { return "dont care"; } @Named("getSeasonNumber") default Integer mapSeasonNumber(Program programInstance) { return 1; } class OfferEntity { private String seasonNumber; public String getSeasonNumber() { return seasonNumber; } public void setSeasonNumber(String seasonNumber) { this.seasonNumber = seasonNumber; } } class OnDemand { private Program programInstance; public Program getProgramInstance() { return programInstance; } public void setProgramInstance(Program programInstance) { this.programInstance = programInstance; } } class Program { } }
23.114754
105
0.671631
7574272f5c661ef40dc34b4dbb2eea68abd210c3
81
/** * Liquibase specific code. */ package carson.mobi.paycel.config.liquibase;
16.2
44
0.728395
3378827fa3f4bf3822a8b89de565dd961220324b
281
package com.taotao.service; import java.util.List; import com.taotao.pojo.TbItemCat; /** * 商品分类Servie * @author Administrator * */ public interface ItemCatServie { /** * 根据父Id查询商品分类列表 * @param parentId * @return */ List<TbItemCat> getItemCatList(Long parentId); }
14.05
47
0.701068
cc1f6000858165f5ffdaf4662692e51cfce3c273
753
package com.skytala.eCommerce.domain.accounting.relations.glAccount.event.taxAuthority; import com.skytala.eCommerce.framework.pubsub.Event; import com.skytala.eCommerce.domain.accounting.relations.glAccount.model.taxAuthority.TaxAuthorityGlAccount; public class TaxAuthorityGlAccountAdded implements Event{ private TaxAuthorityGlAccount addedTaxAuthorityGlAccount; private boolean success; public TaxAuthorityGlAccountAdded(TaxAuthorityGlAccount addedTaxAuthorityGlAccount, boolean success){ this.addedTaxAuthorityGlAccount = addedTaxAuthorityGlAccount; this.success = success; } public boolean isSuccess() { return success; } public TaxAuthorityGlAccount getAddedTaxAuthorityGlAccount() { return addedTaxAuthorityGlAccount; } }
30.12
108
0.844622
2cab2cf3cb5374ba57accd598f63c1b7bdf6ab07
723
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH under * one or more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Licensed under the Zeebe Community License 1.0. You may not use this file * except in compliance with the Zeebe Community License 1.0. */ package io.zeebe.engine.processor.workflow.deployment.distribute; import io.zeebe.util.sched.future.ActorFuture; import org.agrona.DirectBuffer; public interface DeploymentDistributor { ActorFuture<Void> pushDeployment(long key, long position, DirectBuffer buffer); PendingDeploymentDistribution removePendingDeployment(long key); }
40.166667
81
0.809129
e9813dd30e6b37f02dec37c4d389a363e419cb41
3,573
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.ballerinalang.test.regex; import org.ballerinalang.launcher.util.BCompileUtil; import org.ballerinalang.launcher.util.BRunUtil; import org.ballerinalang.launcher.util.CompileResult; import org.ballerinalang.model.values.BString; import org.ballerinalang.model.values.BValue; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * Test regex package for ballerina */ public class BallerinaRegexTest { private CompileResult compileResult; @BeforeClass public void setup() { compileResult = BCompileUtil.compile("regex/regex-test.bal"); } @Test public void testRegexForAlphabeticValues() { BValue[] input = {new BString("Hello")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForAlphabeticValues", input); Assert.assertTrue(new Boolean(returns[0].toString())); } @Test public void testRegexForAlphabeticValuesFalseCase() { BValue[] input = {new BString("Hello123")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForAlphabeticValues", input); Assert.assertFalse(new Boolean(returns[0].toString())); } @Test public void testRegexForAlphaNumericValues() { BValue[] input = {new BString("hello123")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForAlphaNumericValues", input); Assert.assertTrue(new Boolean(returns[0].toString())); } @Test public void testRegexForAlphaNumericValuesFalseCase() { BValue[] input = {new BString("hello_123")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForAlphaNumericValues", input); Assert.assertFalse(new Boolean(returns[0].toString())); } @Test public void testRegexforNumericValues() { BValue[] input = {new BString("2.4")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForNumericValues", input); Assert.assertTrue(new Boolean(returns[0].toString())); } @Test public void testRegexforNumericValuesFalseCase() { BValue[] input = {new BString("$2.4")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForNumericValues", input); Assert.assertFalse(new Boolean(returns[0].toString())); } @Test public void testRegexForSpecialCharacters() { BValue[] input = {new BString("*")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForSpecialCharacters", input); Assert.assertTrue(new Boolean(returns[0].toString())); } @Test public void testRegexForSpecialCharactersFalseCase() { BValue[] input = {new BString("a")}; BValue[] returns = BRunUtil.invoke(compileResult, "testRegexForSpecialCharacters", input); Assert.assertFalse(new Boolean(returns[0].toString())); } }
37.21875
99
0.695774
5f9e48d44a827180c6c57e0e7c760ff992cb6293
928
package info.bytecraft.database; import java.util.List; import org.bukkit.Location; import info.bytecraft.api.BytecraftPlayer; public interface IHomeDAO { @Deprecated public Location getHome(BytecraftPlayer player) throws DAOException; @Deprecated public Location getHome(String player) throws DAOException; @Deprecated public void setHome(BytecraftPlayer player) throws DAOException; @Deprecated public void updateHome(BytecraftPlayer player) throws DAOException; public Location getHome(BytecraftPlayer player, String name) throws DAOException; public void setHome(BytecraftPlayer player, String name) throws DAOException; public void updateHome(BytecraftPlayer player, String name) throws DAOException; public void deleteHome(BytecraftPlayer player, String name) throws DAOException; public List<String> getHomeNames(BytecraftPlayer player) throws DAOException; }
35.692308
85
0.793103
9f08fc2d893a4438bbb761352a3acafd14baf392
6,176
package net.dankito.jpa.annotationreader.property.relationships; import net.dankito.jpa.annotationreader.JpaEntityConfigurationReader; import net.dankito.jpa.annotationreader.config.PropertyConfig; import net.dankito.jpa.annotationreader.JpaConfigurationReaderTestBase; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import java.sql.SQLException; import java.util.Collection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; public class OneToManyAnnotationTest extends JpaConfigurationReaderTestBase { static class OneSideUnAnnotatedHolder { @Id protected Long id; protected Collection<OneSideUnAnnotated> manys; } static class OneSideUnAnnotated { @Id protected Long id; protected Collection<OneSideUnAnnotated> manys; } @Test(expected = SQLException.class) public void oneToManyAnnotationNotSet_ExceptionIsThrownTypeCannotBeSerialized() throws SQLException, NoSuchFieldException { entityConfigurationReader.readConfiguration(new Class[] { OneSideUnAnnotatedHolder.class }); Assert.fail("Should never come to this as Exception should be thrown"); } @Entity static class OneSideUniDirectional { @Id protected Long id; @OneToMany protected Collection<ManySideUniDirectional> manys; } @Entity static class ManySideUniDirectional { @Id protected Long id; } @Ignore @Test(expected = SQLException.class) // TODO: remove again as soon as unidirectional OneToMany relationships are implemented public void unidirectionalOneToMany_RelationShipPropertiesGetSet() throws SQLException, NoSuchFieldException { entityConfigurationReader.readConfiguration(new Class[]{ OneSideUniDirectional.class, ManySideUniDirectional.class }); PropertyConfig manysPropertyConfig = getPropertyConfigurationForField(OneSideUniDirectional.class, "manys"); testUnidirectionalOneToManyRelationshipProperties(manysPropertyConfig); } @Ignore @Test(expected = SQLException.class) // TODO: remove again as soon as unidirectional OneToMany relationships are implemented public void unidirectionalOneToMany_OneToManyDefaultAttributeValuesGetApplied() throws SQLException, NoSuchFieldException { entityConfigurationReader.readConfiguration(new Class[] { OneSideUniDirectional.class, ManySideUniDirectional.class }); PropertyConfig manysPropertyConfig = getPropertyConfigurationForField(OneSideUniDirectional.class, "manys"); Assert.assertEquals(ManySideUniDirectional.class, manysPropertyConfig.getTargetEntityClass()); Assert.assertEquals(0, manysPropertyConfig.getCascade().length); Assert.assertEquals(FetchType.LAZY, manysPropertyConfig.getFetch()); Assert.assertFalse(manysPropertyConfig.cascadePersist()); Assert.assertFalse(manysPropertyConfig.cascadeRefresh()); Assert.assertFalse(manysPropertyConfig.cascadeMerge()); Assert.assertFalse(manysPropertyConfig.cascadeDetach()); Assert.assertFalse(manysPropertyConfig.cascadeRemove()); } @Entity static class TwoUniDirectionalRelationshipsClassOne { @Id protected Long id; @OneToMany protected Collection<TwoUniDirectionalRelationshipsClassTwo> twos; } @Entity static class TwoUniDirectionalRelationshipsClassTwo { @Id protected Long id; @ManyToOne protected TwoUniDirectionalRelationshipsClassOne one; } @Ignore @Test(expected = SQLException.class) // TODO: remove again as soon as unidirectional OneToMany relationships are implemented public void twoUnidirectionalOneToManyAndManyToOneClasses_RelationShipPropertiesGetSet() throws SQLException, NoSuchFieldException { entityConfigurationReader.readConfiguration(new Class[] { TwoUniDirectionalRelationshipsClassOne.class, TwoUniDirectionalRelationshipsClassTwo.class }); PropertyConfig twosPropertyConfig = getPropertyConfigurationForField(TwoUniDirectionalRelationshipsClassOne.class, "twos"); PropertyConfig onePropertyConfig = getPropertyConfigurationForField(TwoUniDirectionalRelationshipsClassTwo.class, "one"); testUnidirectionalManyToOneRelationshipProperties(onePropertyConfig); testUnidirectionalOneToManyRelationshipProperties(twosPropertyConfig); } @Entity static class OneSideBiDirectional { @Id protected Long id; @OneToMany(mappedBy = "one") protected Collection<ManySideBiDirectional> manys; } @Entity static class ManySideBiDirectional { @Id protected Long id; @ManyToOne protected OneSideBiDirectional one; } @Test public void bidirectionalOneToManyAndManyToOneClasses_RelationShipPropertiesGetSet() throws SQLException, NoSuchFieldException { entityConfigurationReader.readConfiguration(new Class[] { OneSideBiDirectional.class, ManySideBiDirectional.class }); PropertyConfig manysPropertyConfig = getPropertyConfigurationForField(OneSideBiDirectional.class, "manys"); PropertyConfig onePropertyConfig = getPropertyConfigurationForField(ManySideBiDirectional.class, "one"); testBidirectionalOneToManyRelationshipProperties(manysPropertyConfig); testBidirectionalManyToOneRelationshipProperties(onePropertyConfig); Assert.assertFalse(manysPropertyConfig.isOwningSide()); Assert.assertTrue(manysPropertyConfig.isInverseSide()); Assert.assertTrue(onePropertyConfig.isOwningSide()); Assert.assertFalse(onePropertyConfig.isInverseSide()); } @Entity static class OrphanRemovalSet { @Id protected Long id; @OneToMany(orphanRemoval = true) protected Collection<ManySideUniDirectional> manys; } @Test(expected = SQLException.class) public void orphanRemovalSet_ThrowsNotSupportedException() throws SQLException, NoSuchFieldException { try { entityConfigurationReader.readConfiguration(new Class[] { OrphanRemovalSet.class, ManySideUniDirectional.class }); } catch(Exception ex) { Assert.assertTrue(ex.getMessage().endsWith(JpaEntityConfigurationReader.NotSupportedExceptionTrailMessage)); throw ex; } Assert.fail("Should never come to this as Exception must be thrown"); } }
37.658537
156
0.806347
ffa595bfd5815674e40fddcea2c825806f0d1511
1,764
/* * Copyright 2002-2021 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.taotao.cloud.bigdata.hadoop.mr.component.wordcount; import java.io.IOException; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Reducer; /** * KEYIN, VALUEIN 对应 mapper输出的KEYOUT,VALUEOUT类型对应 * <p> * KEYOUT, VALUEOUT 是自定义reduce逻辑处理结果的输出数据类型 * <p> * KEYOUT是单词 VLAUEOUT是总次数 * * @author shuigedeng * @version 1.0.0 * @since 2020/11/26 下午8:08 */ public class WordCountReducer extends Reducer<Text, IntWritable, Text, IntWritable> { /** * <angelababy,1><angelababy,1><angelababy,1><angelababy,1><angelababy,1> * <hello,1><hello,1><hello,1><hello,1><hello,1><hello,1> <banana,1><banana,1><banana,1><banana,1><banana,1><banana,1> * 入参key,是一组相同单词kv对的key */ @Override protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { int count = 0; /*Iterator<IntWritable> iterator = values.iterator(); while(iterator.hasNext()){ count += iterator.next().get(); }*/ for (IntWritable value : values) { count += value.get(); } context.write(key, new IntWritable(count)); } }
30.947368
119
0.722789
b7774e7acef959f3276d9ca4d7e62e24270ab887
2,809
package WebServerLogsModule; /** * This is the Tester for LogEntry class. * * @author Davide Nastri * @version 2/21/2018 */ import java.util.*; public class Tester { public void testLogEntry() { LogEntry le = new LogEntry("1.2.3.4", new Date(), "example request", 200, 500); System.out.println(le); LogEntry le2 = new LogEntry("1.2.100.4", new Date(), "example request 2", 300, 400); System.out.println(le2); } public void testLogAnalyzer() { LogAnalyzer la = new LogAnalyzer(); la.readFile("WebServerLogsModule/weblog2_log"); la.printAll(); int uniqueIPs = la.countUniqueIPs(); System.out.println("There are " + uniqueIPs + " unique IPs"); System.out.println("Unique visitors on Sep 24:"); System.out.println(la.uniqueIPVisitsOnDay("Sep 24").size()); System.out.println("Unique visitors on Sep 30:"); System.out.println(la.uniqueIPVisitsOnDay("Sep 30").size()); System.out.println("Unique ips in range 200,299:"); System.out.println(la.countUniqueIPsInRange(200,299)); System.out.println("Unique ips in range 400,499:"); System.out.println(la.countUniqueIPsInRange(400,499)); System.out.println("printAllHigherThanNum using 400"); la.printAllHigherThanNum(400); System.out.println("Unique visitors on Mar 24:"); System.out.println(la.uniqueIPVisitsOnDay("Mar 24").size()); System.out.println("countVisitsPerIP:"); HashMap<String,Integer> counts = la.countVisitsPerIP(); System.out.println(counts); System.out.println("mostNumbervisitsByIP:"); System.out.println(la.mostNumberVisitsByIP(counts)); System.out.println("iPsMostVisits:"); System.out.println(la.iPsMostVisits(counts)); System.out.println("iPsForDays:"); System.out.println(la.iPsForDays()); System.out.println("dayWithMostIPVisits:"); System.out.println(la.dayWithMostIPVisits(la.iPsForDays())); System.out.println("iPsWithMostVisitsOnDay:"); ArrayList<String> result = la.iPsWithMostVisitsOnDay(la.iPsForDays(), "Sep 29"); for (int k = 0; k < result.size(); k++) { System.out.println(result.get(k)); } } public void quiz() { LogAnalyzer la = new LogAnalyzer(); la.readFile("WebServerLogsModule/weblog1_log"); HashMap<String,Integer> counts = la.countVisitsPerIP(); System.out.println(counts); System.out.println("mostNumbervisitsByIP:"); System.out.println(la.mostNumberVisitsByIP(counts)); System.out.println("iPsMostVisits:"); System.out.println(la.iPsMostVisits(counts)); } }
40.710145
92
0.628693
237f16ebd0789fd77af723c08d2e60919b835008
424
package org.ovirt.engine.core.common.action; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * This annotation is to mark a getter method of a parameter * that should not appear in the debug log */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface ShouldNotBeLogged { }
26.5
60
0.799528
dac7665bac3dd2173518bf7f324bc6b680800a91
4,271
package oneHandedTypist11278; import java.util.*; import java.io.*; public class Main { public static void main(String[] args) { Scanner in = new Scanner(new InputStreamReader(System.in)); while (in.hasNext()) { String os = in.nextLine(); String out = ""; for (char x: os.toCharArray()) { if (x == '4') { out += 'q'; } else if (x == '5') { out += 'j'; } else if (x == '6') { out += 'l'; } else if (x == '7') { out += 'm'; } else if (x == '8') { out += 'f'; } else if (x == '9') { out += 'p'; } else if (x == '0') { out += '/'; } else if (x == '-') { out += '['; } else if (x == '=') { out += ']'; } else if (x == 'q') { out += '4'; } else if (x == 'w') { out += '5'; } else if (x == 'e') { out += '6'; } else if (x == 'r') { out += '.'; } else if (x == 't') { out += 'o'; } else if (x == 'y') { out += 'r'; } else if (x == 'u') { out += 's'; } else if (x == 'i') { out += 'u'; } else if (x == 'o') { out += 'y'; } else if (x == 'p') { out += 'b'; } else if (x == '[') { out += ';'; } else if (x == ']') { out += '='; } else if (x == '\\') { out += '\\'; } else if (x == 'a') { out += '7'; } else if (x == 's') { out += '8'; } else if (x == 'd') { out += '9'; } else if (x == 'f') { out += 'a'; } else if (x == 'g') { out += 'e'; } else if (x == 'h') { out += 'h'; } else if (x == 'j') { out += 't'; } else if (x == 'k') { out += 'd'; } else if (x == 'l') { out += 'c'; } else if (x == ';') { out += 'k'; } else if (x == '\'') { out += '-'; } else if (x == 'z') { out += '0'; } else if (x == 'x') { out += 'z'; } else if (x == 'c') { out += 'x'; } else if (x == 'v') { out += ','; } else if (x == 'b') { out += 'i'; } else if (x == 'n') { out += 'n'; } else if (x == 'm') { out += 'w'; } else if (x == ',') { out += 'v'; } else if (x == '.') { out += 'g'; } else if (x == '/') { out += '\''; } else if (x == '$') { out += 'Q'; } else if (x == '%') { out += 'J'; } else if (x == '^') { out += 'L'; } else if (x == '&') { out += 'M'; } else if (x == '*') { out += 'F'; } else if (x == '(') { out += 'P'; } else if (x == ')') { out += '?'; } else if (x == '_') { out += '{'; } else if (x == '+') { out += '}'; } else if (x == 'Q') { out += '$'; } else if (x == 'W') { out += '%'; } else if (x == 'E') { out += '^'; } else if (x == 'R') { out += '>'; } else if (x == 'T') { out += 'O'; } else if (x == 'Y') { out += 'R'; } else if (x == 'U') { out += 'S'; } else if (x == 'I') { out += 'U'; } else if (x == 'O') { out += 'Y'; } else if (x == 'P') { out += 'B'; } else if (x == '{') { out += ':'; } else if (x == '}') { out += '+'; } else if (x == '|') { out += '|'; } else if (x == 'A') { out += '&'; } else if (x == 'S') { out += '*'; } else if (x == 'D') { out += '('; } else if (x == 'F') { out += 'A'; } else if (x == 'G') { out += 'E'; } else if (x == 'H') { out += 'H'; } else if (x == 'J') { out += 'T'; } else if (x == 'K') { out += 'D'; } else if (x == 'L') { out += 'C'; } else if (x == ':') { out += 'K'; } else if (x == '"') { out += '_'; } else if (x == 'Z') { out += ')'; } else if (x == 'X') { out += 'Z'; } else if (x == 'C') { out += 'X'; } else if (x == 'V') { out += '<'; } else if (x == 'B') { out += 'I'; } else if (x == 'N') { out += 'N'; } else if (x == 'M') { out += 'W'; } else if (x == '<') { out += 'V'; } else if (x == '>') { out += 'G'; } else if (x == '?') { out += '"'; } else { out += x; } } System.out.println(out); } } }
19.682028
61
0.283306
0e31bb6088ae22ae918b7fdcf125581493ef52d9
2,516
package dev.Hilligans.ourcraft.Client.Rendering.Graphics.Vulkan; import dev.Hilligans.ourcraft.Client.MatrixStack; import dev.Hilligans.ourcraft.Client.Rendering.Graphics.IGraphicsEngine; import dev.Hilligans.ourcraft.Client.Rendering.Graphics.Vulkan.Boilerplate.VulkanInstance; import dev.Hilligans.ourcraft.Client.Rendering.Graphics.Vulkan.Boilerplate.VulkanProperties; import dev.Hilligans.ourcraft.Client.Rendering.Graphics.Vulkan.Boilerplate.Window.VulkanWindow; import dev.Hilligans.ourcraft.ClientMain; import dev.Hilligans.ourcraft.GameInstance; import dev.Hilligans.ourcraft.World.Chunk; import dev.Hilligans.ourcraft.World.ClientWorld; public class VulkanEngine implements IGraphicsEngine<VulkanGraphicsContainer, VulkanWindow> { public VulkanInstance vulkanInstance; public GameInstance gameInstance; public VulkanEngine(GameInstance gameInstance) { this.gameInstance = gameInstance; } @Override public VulkanWindow createWindow() { return vulkanInstance.getDefaultDevice().logicalDevice.getWindow(); } @Override public VulkanGraphicsContainer getChunkGraphicsContainer(Chunk chunk) { return null; } @Override public VulkanGraphicsContainer createChunkGraphicsContainer() { return null; } @Override public void putChunkGraphicsContainer(Chunk chunk, VulkanGraphicsContainer container) { } @Override public void render(VulkanWindow window) { } @Override public void renderWorld(MatrixStack matrixStack, ClientWorld world) { } @Override public void renderScreen(MatrixStack screenStack) { } @Override public void setup() { vulkanInstance = getVulkanInstance(); vulkanInstance.run(); } @Override public void close() { vulkanInstance.exit("closing"); } @Override public GameInstance getGameInstance() { return gameInstance; } public static VulkanInstance getVulkanInstance() { return getVulkanInstance(new VulkanProperties(ClientMain.argumentContainer).warningValidation().errorValidation().addValidationLayers("VK_LAYER_KHRONOS_validation", "VK_LAYER_KHRONOS_validation").enableValidationLayers()); } public static VulkanInstance getVulkanInstance(VulkanProperties vulkanProperties) { if(sInstance == null) { sInstance = new VulkanInstance(vulkanProperties); } return sInstance; } public static VulkanInstance sInstance; }
29.255814
230
0.745628
8e0e9eb2a4edd785886c88ace33d92d58b3c9770
2,680
/** * Copyright (c) 2017 European Organisation for Nuclear Research (CERN), All Rights Reserved. */ package org.tensorics.core.math.structures.grouplike; import java.io.Serializable; import org.tensorics.core.math.operations.CommutativeAssociativeOperation; import org.tensorics.core.math.operations.UnaryOperation; public class AbstractAbelianGroup<E> implements AbelianGroup<E>, Serializable { private static final long serialVersionUID = 1L; private final CommutativeAssociativeOperation<E> operation; private final E identity; private final UnaryOperation<E> inversion; public AbstractAbelianGroup(CommutativeAssociativeOperation<E> operation, E identity, UnaryOperation<E> inversion) { this.operation = operation; this.identity = identity; this.inversion = inversion; } @Override public CommutativeAssociativeOperation<E> operation() { return this.operation; } @Override public E identity() { return this.identity; } @Override public UnaryOperation<E> inversion() { return this.inversion; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((identity == null) ? 0 : identity.hashCode()); result = prime * result + ((inversion == null) ? 0 : inversion.hashCode()); result = prime * result + ((operation == null) ? 0 : operation.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } AbstractAbelianGroup<?> other = (AbstractAbelianGroup<?>) obj; if (identity == null) { if (other.identity != null) { return false; } } else if (!identity.equals(other.identity)) { return false; } if (inversion == null) { if (other.inversion != null) { return false; } } else if (!inversion.equals(other.inversion)) { return false; } if (operation == null) { if (other.operation != null) { return false; } } else if (!operation.equals(other.operation)) { return false; } return true; } @Override public String toString() { return "AbstractAbelianGroup [operation=" + operation + ", identity=" + identity + ", inversion=" + inversion + "]"; } }
28.817204
120
0.58209
30b03a3da6e7e7eedc75f520b9faa47b656f72e7
1,801
package com.ctrip.xpipe.redis.core.protocal.protocal; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ctrip.xpipe.redis.core.protocal.RedisClientProtocol; import com.ctrip.xpipe.redis.core.protocal.protocal.AbstractBulkStringEoFJudger.BulkStringEofMarkJudger; import com.ctrip.xpipe.redis.core.protocal.protocal.AbstractBulkStringEoFJudger.BulkStringLengthEofJudger; /** * @author wenchao.meng * * Dec 23, 2016 */ public class BulkStringEofJuderManager { private static Logger logger = LoggerFactory.getLogger(BulkStringEofJuderManager.class); public static BulkStringEofJudger create(byte []data){ int start = 0; if(data[0] == RedisClientProtocol.DOLLAR_BYTE){ start = 1; } if(arraynequals(data, 1, RedisClientProtocol.EOF, RedisClientProtocol.EOF.length)){ if(start + RedisClientProtocol.EOF.length + BulkStringEofMarkJudger.MARK_LENGTH > data.length){ throw new IllegalStateException("bulksting eof mark error:" + new String(data)); } byte []mark = new byte[BulkStringEofMarkJudger.MARK_LENGTH]; System.arraycopy(data, start + RedisClientProtocol.EOF.length, mark, 0, BulkStringEofMarkJudger.MARK_LENGTH); return new BulkStringEofMarkJudger(mark); } logger.debug("[create]len:{}, {}, {}", data.length, new String(data), start); String lengthStr = new String(data, start, data.length - start).trim(); long length = Long.parseLong(lengthStr); return new BulkStringLengthEofJudger(length); } private static boolean arraynequals(byte[] data, int index, byte[] expected, int length) { if(data.length < index + length){ return false; } if(expected.length < length){ return false; } for(int i=0;i<length;i++){ if(data[index+i] != expected[i]){ return false; } } return true; } }
30.016667
112
0.736258
09538cf598144c043a28f532d276d2ceb97e57fa
20,939
package ch.scheitlin.alex.intellij.plugins.toolWindow; import ch.scheitlin.alex.build.swing.ErrorPanel; import ch.scheitlin.alex.intellij.plugins.services.Controller; import ch.scheitlin.alex.build.model.Error; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.ui.JBUI; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; public class BuildSummaryPanel extends JPanel { private JPanel panelContent; private JPanel panelSummary; private JLabel labelBuildStatusKey; private JLabel labelBuildStatusValue; private JLabel labelBuildStatusTextKey; private JLabel labelBuildStatusTextValue; private JLabel labelFailureCategoryKey; private JLabel labelFailureCategoryValue; private JLabel labelFailedGoalKey; private JLabel labelFailedGoalValue; private JLabel labelFailedMessageKey; private JLabel labelFailedMessageValue; private JLabel labelProjectKey; private JLabel labelProjectValue; private JLabel labelBuildConfigurationKey; private JLabel labelBuildConfigurationValue; private JLabel labelBranchKey; private JLabel labelBranchValue; private JLabel labelErrorsKey; private JPanel panelErrorsValue; private JTextPane labelInformation; private JButton buttonBack; private JButton buttonContinue; private JScrollPane scrollPane; private final String BUILD_STATUS_TITLE = "Build Status:"; private final String BUILD_STATUS_TEXT_TITLE = "Status Text:"; private final String FAILURE_CATEGORY_TITLE = "Failure Category:"; private final String FAILED_GOAL_TITLE = "Failed Goal:"; private final String FAILED_MESSAGE_TITLE = "Error Message:"; private final String PROJECT_TITLE = "Project:"; private final String BUILD_CONFIGURATION_TITLE = "Build Configuration:"; private final String BRANCH_NAME_TITLE = "Branch:"; private final String ERRORS_TITLE = "Errors:"; private final String BACK_BUTTON_OVERVIEW = "Back to Overview"; private final String BACK_BUTTON_ABORT = "Abort"; private final String CONTINUE_BUTTON_CHECKOUT = "Checkout"; private final String CONTINUE_BUTTON_FINISH = "Finish"; public BuildSummaryPanel( String buildStatus, String buildStatusText, String failureCategory, String failedGoal, String failedMessage, String projectName, String buildConfigurationName, String branchName, List<Error> errors, boolean isFixing, String newBranch, ActionListener fixAction, ActionListener finishAction, ActionListener abortAction ) { // set layout this.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); // configure and add content panel initAndAddContentPanel(20); this.panelSummary = initSummaryPanel( this.BUILD_STATUS_TITLE, buildStatus, this.BUILD_STATUS_TEXT_TITLE, buildStatusText, this.FAILURE_CATEGORY_TITLE, failureCategory, this.FAILED_GOAL_TITLE, failedGoal, this.FAILED_MESSAGE_TITLE, failedMessage, this.PROJECT_TITLE, projectName, this.BUILD_CONFIGURATION_TITLE, buildConfigurationName, this.BRANCH_NAME_TITLE, branchName ); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 0; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0); c.weightx = 1.0; this.panelContent.add(this.panelSummary, c); if (errors != null) { // configure and add label with errors title this.labelErrorsKey = initLabel(this.ERRORS_TITLE); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 1; c.gridwidth = 2; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(20, 0, 0, 0); c.weightx = 0.0; this.panelContent.add(this.labelErrorsKey, c); // configure and add panel with errors initErrorsValuePanel(errors, failureCategory, isFixing); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 2; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0); c.weightx = 1.0; this.panelContent.add(panelErrorsValue, c); } if (buildStatus.equals("FAILURE")) { // configure and add label with information message initInformationLabel(isFixing, this.CONTINUE_BUTTON_CHECKOUT, this.CONTINUE_BUTTON_FINISH, newBranch); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 3; c.gridwidth = 2; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(20, 0, 0, 0); c.weightx = 1.0; this.panelContent.add(labelInformation, c); } // configure and add button to go back initBackButton(isFixing, this.BACK_BUTTON_OVERVIEW, this.BACK_BUTTON_ABORT, abortAction); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 4; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(20, 0, 0, 0); c.weightx = 0.0; this.panelContent.add(buttonBack, c); if (buildStatus.equals("FAILURE")) { // configure and add button to continue initContinueButton(isFixing, this.CONTINUE_BUTTON_CHECKOUT, this.CONTINUE_BUTTON_FINISH, fixAction, finishAction); c.anchor = GridBagConstraints.LINE_END; c.gridx = 1; c.gridy = 4; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(20, 0, 0, 0); c.weightx = 0.0; this.panelContent.add(buttonContinue, c); } // add panel to stick content to the top JPanel panel = new JPanel(); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 5; c.gridwidth = 2; c.fill = GridBagConstraints.BOTH; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 1.0; c.weighty = 1.0; this.panelContent.add(panel, c); } private void initAndAddContentPanel(int padding) { this.panelContent = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); // create panel to add padding JPanel paddingPanel = new JPanel(); paddingPanel.setLayout(new GridBagLayout()); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 0; c.insets = JBUI.insets(padding); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; paddingPanel.add(this.panelContent, c); // create panel with vertical scroll bar JPanel scrollBarPanel = new JPanel(); scrollBarPanel.setLayout(new GridBagLayout()); this.scrollPane = new JBScrollPane(paddingPanel); this.scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); this.scrollPane.setBorder(null); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 0; c.insets = JBUI.insets(0); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; scrollBarPanel.add(this.scrollPane, c); // add panel to summary panel c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 0; c.insets = JBUI.insets(0); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; this.add(scrollBarPanel, c); } private JPanel initSummaryPanel( String buildStatusTitle, String buildStatusText, String buildStatusTextTitle, String buildStatusTextText, String failureCategoryTitle, String failureCategoryText, String failedGoalTitle, String failedGoalText, String failedMessageTitle, String failedMessageText, String projectTitle, String projectText, String buildConfigurationTitle, String buildConfigurationText, String branchNameTitle, String branchNameText ) { JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); int gap = 10; // configure and add label with build status title this.labelBuildStatusKey = initLabel(buildStatusTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 0; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelBuildStatusKey, c); // configure and add label with build status this.labelBuildStatusValue = initLabel(buildStatusText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 0; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelBuildStatusValue, c); // configure and add label with build status text title this.labelBuildStatusTextKey = initLabel(buildStatusTextTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 1; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelBuildStatusTextKey, c); // configure and add label with build status text this.labelBuildStatusTextValue = initLabel(buildStatusTextText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 1; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelBuildStatusTextValue, c); if (buildStatusText.equals("FAILURE")) { // configure and add label with failure category title this.labelFailureCategoryKey = initLabel(failureCategoryTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 2; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelFailureCategoryKey, c); // configure and add label with failure category this.labelFailureCategoryValue = initLabel(failureCategoryText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 2; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelFailureCategoryValue, c); if (failedMessageText == null) { // configure and add label with failed goal title this.labelFailedGoalKey = initLabel(failedGoalTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 3; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelFailedGoalKey, c); // configure and add label with failed goal this.labelFailedGoalValue = initLabel(failedGoalText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelFailedGoalValue, c); } else { // configure and add label with failed message title this.labelFailedMessageKey = initLabel(failedMessageTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 3; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelFailedMessageKey, c); // configure and add label with failed message this.labelFailedMessageValue = initLabel(failedMessageText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 3; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelFailedMessageValue, c); } } // configure and add label with project title this.labelProjectKey = initLabel(projectTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 4; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelProjectKey, c); // configure and add label with project name this.labelProjectValue = initLabel(projectText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 4; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelProjectValue, c); // configure and add label with build configuration title this.labelBuildConfigurationKey = initLabel(buildConfigurationTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 5; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelBuildConfigurationKey, c); // configure and add label with build configuration name this.labelBuildConfigurationValue = initLabel(buildConfigurationText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 5; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelBuildConfigurationValue, c); // configure and add label with branch name title this.labelBranchKey = initLabel(branchNameTitle); c.anchor = GridBagConstraints.LINE_START; c.gridx = 0; c.gridy = 6; c.fill = GridBagConstraints.NONE; c.insets = JBUI.insets(0, 0, 0, 0); c.weightx = 0.0; panel.add(this.labelBranchKey, c); // configure and add label with branch name this.labelBranchValue = initLabel(branchNameText); c.anchor = GridBagConstraints.LINE_START; c.gridx = 1; c.gridy = 6; c.fill = GridBagConstraints.HORIZONTAL; c.insets = JBUI.insets(0, gap, 0, 0); c.weightx = 1.0; panel.add(this.labelBranchValue, c); return panel; } private JLabel initLabel(String text) { JLabel label = new JLabel(); label.setText(text); return label; } private void initErrorsValuePanel(List<Error> errors, String failureCategory, boolean isFixing) { if (errors == null) { return; } this.panelErrorsValue = new JPanel(); this.panelErrorsValue.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); for (int i = 0; i < errors.size(); i++) { // create new error swing component String actionButton1Text = "Show"; String actionButton2Text = null; if (failureCategory == "TESTING" && isFixing) { actionButton2Text = "Debug"; } ErrorPanel errorComponent = new ErrorPanel(errors.get(i), actionButton1Text, actionButton2Text); // create actions for action buttons of error component final ErrorPanel that = errorComponent; // show file action ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Controller.getInstance().openErrorInFile(that.getError()); } }; errorComponent.addButton1Action(actionListener); if (actionButton2Text != null) { // debug error action ActionListener actionListener2 = new ActionListener() { public void actionPerformed(ActionEvent e) { Controller.getInstance().debugError(that.getError()); } }; errorComponent.addButton2Action(actionListener2); } // add bottom border if there is at least one more error panel if (i < errors.size() - 1) { errorComponent.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.BLACK)); } // add top padding if there was at least one error panel before // add bottom padding if there is at least one more error panel int padding = 5; int paddingTop = 0; if (i != 0) { // not first panel paddingTop = padding; } int paddingBottom = 0; if (i < errors.size() - 1) { // not last panel paddingBottom = padding; } Border border = errorComponent.getBorder(); Border margin = BorderFactory.createEmptyBorder(paddingTop, 0, paddingBottom, 0); errorComponent.setBorder(BorderFactory.createCompoundBorder(border, margin)); c.anchor = GridBagConstraints.LINE_START; c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = i; c.weightx = 1.0; this.panelErrorsValue.add(errorComponent, c); } } private void initInformationLabel(boolean isFixing, String checkoutText, String finishText, String newBranch) { this.labelInformation = new JTextPane(); this.labelInformation.setEditable(false); this.labelInformation.setCursor(null); this.labelInformation.setOpaque(false); this.labelInformation.setFocusable(false); this.labelInformation.setContentType("text/html"); String fontFamily = UIManager.getFont("Label.font").getFamily(); int fontSize = UIManager.getFont("Label.font").getSize(); String information = ""; if (!isFixing) { information = "<p>Your local code may be different from the one that failed on the build server!" + " Explore the errors in your local code using the <b>Show</b> buttons above.</p>" + "<p>Use the <b>" + checkoutText + "</b> button below to change to the code that caused the build " + "failure and explore the errors there. <i>A new branch will be created and uncommitted changes " + "will be stashed automatically.<i></p>"; } else { information = "<p>You are now on branch <b>" + newBranch + "</b> showing the code that caused the build failure.</p>" + "<p>Once you are finished, click the <b>" + finishText + "</b> button.</p>"; } this.labelInformation.setText( "<div style='font-family:" + fontFamily + ";font-size:" + fontSize + ";'>" + information + "</div>" ); } private void initBackButton(boolean isFixing, String overviewText, String abortText, ActionListener abortAction) { this.buttonBack = new JButton(); if (!isFixing) { this.buttonBack.setText(overviewText); } else { this.buttonBack.setText(abortText); } this.buttonBack.addActionListener(abortAction); } private void initContinueButton( boolean isFixing, String checkoutText, String finishText, ActionListener fixAction, ActionListener finishAction) { this.buttonContinue = new JButton(); if (!isFixing) { this.buttonContinue.setText(checkoutText); this.buttonContinue.addActionListener(fixAction); } else { this.buttonContinue.setText(finishText); this.buttonContinue.addActionListener(finishAction); } } }
39.359023
131
0.606237
1a3b8c9f587468b8d16e6fdc6d4a47ccd3b32781
3,454
package com.Da_Technomancer.crossroads.integration.JEI; import com.Da_Technomancer.crossroads.Crossroads; import com.Da_Technomancer.crossroads.blocks.CRBlocks; import com.Da_Technomancer.crossroads.crafting.recipes.MillRec; import com.mojang.blaze3d.matrix.MatrixStack; import mezz.jei.api.constants.VanillaTypes; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.gui.drawable.IDrawable; import mezz.jei.api.gui.drawable.IDrawableAnimated; import mezz.jei.api.gui.drawable.IDrawableStatic; import mezz.jei.api.gui.ingredient.IGuiItemStackGroup; import mezz.jei.api.helpers.IGuiHelper; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.category.IRecipeCategory; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; public class MillstoneCategory implements IRecipeCategory<MillRec>{ public static final ResourceLocation ID = new ResourceLocation(Crossroads.MODID, ".millstone"); private final IDrawable back; private final IDrawable slot; private final IDrawable icon; private final IDrawableAnimated arrow; private final IDrawableStatic arrowStatic; protected MillstoneCategory(IGuiHelper guiHelper){ back = guiHelper.createBlankDrawable(180, 100); slot = guiHelper.getSlotDrawable(); arrowStatic = guiHelper.createDrawable(new ResourceLocation(Crossroads.MODID, "textures/gui/container/millstone_gui.png"), 66, 35, 44, 17); arrow = guiHelper.createAnimatedDrawable(guiHelper.createDrawable(new ResourceLocation(Crossroads.MODID, "textures/gui/container/millstone_gui.png"), 176, 0, 44, 17), 40, IDrawableAnimated.StartDirection.TOP, false); icon = guiHelper.createDrawableIngredient(new ItemStack(CRBlocks.millstone, 1)); } @Override public ResourceLocation getUid(){ return ID; } @Override public Class<? extends MillRec> getRecipeClass(){ return MillRec.class; } @Override public String getTitle(){ return CRBlocks.millstone.getTranslatedName().getString(); } @Override public IDrawable getBackground(){ return back; } @Override public IDrawable getIcon(){ return icon; } @Override public void setIngredients(MillRec recipe, IIngredients ingredients){ ingredients.setInputIngredients(recipe.getIngredients()); ingredients.setOutput(VanillaTypes.ITEM, recipe.getRecipeOutput()); } @Override public void draw(MillRec recipe, MatrixStack matrix, double mouseX, double mouseY){ // GlStateManager.enableAlpha(); // GlStateManager.enableBlend(); slot.draw(matrix, 79, 16); slot.draw(matrix, 61, 52); slot.draw(matrix, 79, 52); slot.draw(matrix, 97, 52); arrowStatic.draw(matrix, 66, 35); arrow.draw(matrix, 66, 35); // GlStateManager.disableBlend(); // GlStateManager.disableAlpha(); } @Override public void setRecipe(IRecipeLayout recipeLayout, MillRec recipe, IIngredients ingredients){ IGuiItemStackGroup itemStackGroup = recipeLayout.getItemStacks(); itemStackGroup.init(0, true, 79, 16); itemStackGroup.set(0, ingredients.getInputs(VanillaTypes.ITEM).get(0)); int length = recipe.getOutputs().length; if(length >= 1){ itemStackGroup.init(1, false, 61, 52); itemStackGroup.set(1, recipe.getOutputs()[0]); if(length >= 2){ itemStackGroup.init(2, false, 79, 52); itemStackGroup.set(2, recipe.getOutputs()[1]); if(length >= 3){ itemStackGroup.init(3, false, 97, 52); itemStackGroup.set(3, recipe.getOutputs()[2]); } } } itemStackGroup.set(ingredients); } }
33.211538
218
0.769832
3728b6fe6b34f3677039d40846f5668b0ab50d98
3,845
package cn.yiya.shiji.entity; import java.util.ArrayList; /** * Created by jerry on 2016/2/25. */ public class OrderListInfo { private ArrayList<Goods> goods; private String current_time; private String create_time; private String close_time; private String order_number; private String sub_order_number; private String status; private String status_des; private GroupInfo group_info; private String amount; //商品金额 private long diff; //店铺订单新增 // "shop_name":'小柿集' //店铺名 // "shop_image":'xxx' //店铺头像 // "shop_id": '1' //店铺id // "consignee_name": "dfjfje", //收货人 // "cash_amount": 100, //佣金 // "goods_num": 1 //商品总数量 private String shop_name; private String shop_image; private String shop_id; private String consignee_name; private String cash_amount; private int goods_num; public long getDiff() { return diff; } public void setDiff(long diff) { this.diff = diff; } public String getOrder_number() { return order_number; } public void setOrder_number(String order_number) { this.order_number = order_number; } public ArrayList<Goods> getGoods() { return goods; } public void setGoods(ArrayList<Goods> goods) { this.goods = goods; } public String getCurrent_time() { return current_time; } public void setCurrent_time(String current_time) { this.current_time = current_time; } public String getCreate_time() { return create_time; } public void setCreate_time(String create_time) { this.create_time = create_time; } public String getClose_time() { return close_time; } public void setClose_time(String close_time) { this.close_time = close_time; } public String getSub_order_number() { return sub_order_number; } public void setSub_order_number(String sub_order_number) { this.sub_order_number = sub_order_number; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getStatus_des() { return status_des; } public void setStatus_des(String status_des) { this.status_des = status_des; } public GroupInfo getGroup_info() { return group_info; } public void setGroup_info(GroupInfo group_info) { this.group_info = group_info; } public String getAmount() { return amount; } public void setAmount(String amount) { this.amount = amount; } public String getShop_name() { return shop_name; } public void setShop_name(String shop_name) { this.shop_name = shop_name; } public String getShop_image() { return shop_image; } public void setShop_image(String shop_image) { this.shop_image = shop_image; } public String getShop_id() { return shop_id; } public void setShop_id(String shop_id) { this.shop_id = shop_id; } public String getCash_amount() { return cash_amount; } public void setCash_amount(String cash_amount) { this.cash_amount = cash_amount; } public String getConsignee_name() { return consignee_name; } public void setConsignee_name(String consignee_name) { this.consignee_name = consignee_name; } public int getGoods_num() { return goods_num; } public void setGoods_num(int goods_num) { this.goods_num = goods_num; } }
22.354651
63
0.604161
3c561f18e34f20c9a1cfb750542048f53aecd806
2,393
package life.genny.qwandaq; import com.fasterxml.jackson.annotation.JsonIgnore; import io.quarkus.runtime.annotations.RegisterForReflection; import javax.persistence.Embeddable; import javax.persistence.FetchType; import javax.persistence.ManyToOne; import life.genny.qwandaq.attribute.Attribute; import life.genny.qwandaq.entity.BaseEntity; /** * AnswerLinkId stores information regarding the source and target BaseEntitys * for AnswerLink objects. * * @author Adam Crow * @author Byron Aguirre */ @Embeddable @RegisterForReflection public class AnswerLinkId implements java.io.Serializable { @JsonIgnore @ManyToOne private BaseEntity source; @JsonIgnore @ManyToOne private BaseEntity target; @JsonIgnore @ManyToOne(optional = true, fetch = FetchType.LAZY) private Attribute attribute; /** * @return the source */ public BaseEntity getSource() { return source; } /** * @param source the source to set */ public void setSource(final BaseEntity source) { this.source = source; } /** * @return the target */ public BaseEntity getTarget() { return target; } /** * @param target the target to set */ public void setTarget(final BaseEntity target) { this.target = target; } /** * @return the attribute */ public Attribute getAttribute() { return attribute; } /** * @param attribute the attribute to set */ public void setAttribute(final Attribute attribute) { this.attribute = attribute; } public AnswerLinkId() { } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final AnswerLinkId that = (AnswerLinkId) o; if (source != null ? !source.equals(that.source) : that.source != null) return false; if (target != null ? !target.equals(that.target) : that.target != null) return false; if (attribute != null ? !attribute.equals(that.attribute) : that.attribute != null) return false; return true; } /** * @return int */ @Override public int hashCode() { int result; result = (source != null ? source.hashCode() : 0); result = 31 * result + (target != null ? target.hashCode() : 0); result = 127 * result + (attribute != null ? attribute.hashCode() : 0); return result; } }
21.366071
87
0.664438
fa879abaa4541693d5acf0b6e7fbb6323bfafe4f
14,954
import java.util.*; import java.awt.Point; public class minimax_Sentient extends AIModule { private int maxPly = 2; //maximum number of moves to play ahead private int prevMoveX, prevMoveY; private int player; //Hold points value //We can experiment with these values //1 coin of ourPlayer with 3 blank spot +x //2 coin of ourPlayer with 2 blank spot +x //3 coin of ourPlayer with 1 blank spot +x //4 coin of ourPlayer with 0 blank spot +x //Contains the negative value as well private static final int[] points = { 0, 10, 100, 500, 100000000 }; private int[][] pointsCoin = { { 3, 4, 5, 7, 7, 5, 4, 3 }, { 4, 6, 8, 10, 10, 8, 6, 4 }, { 5, 8, 11, 13, 13, 11, 8, 5 }, { 7, 10, 13, 16, 16, 13, 10, 7 }, { 7, 10, 13, 16, 16, 13, 10, 7 }, { 5, 8, 11, 13, 13, 11, 8, 5 }, { 4, 6, 8, 10, 10, 8, 6, 4 }, { 3, 4, 5, 7, 7, 5, 4, 3 } }; //generates the moves that can be performed from the current state //as of right now it generates them in left to right order //returns an array of the columns that can be played in //each entry contains either a column number to play in that column //or a -1 to indicate that the move is invalid private int[] generateMoves(final GameStateModule state) { int i; int[] moves = new int[state.getWidth()]; //maybe this should be Integer instead of int? for(i = 0; i < state.getWidth(); ++i) { if(state.canMakeMove(i)) { moves[i] = i; //can play column i } else { moves[i] = -1; //mark move as invalid } } return moves; }//generateMoves //start reading here public void getNextMove(final GameStateModule state) //think of this as minimax or alpah beta { int[] moves = generateMoves(state);//which column to play in int max, colToPlay, oldMax; max = oldMax = Integer.MIN_VALUE; colToPlay = -1; int tmpColToPlay = -1; //set player player = state.getCoins() % 2 + 1; int score = initFirstStateScore( state ); /* System.out.println( "score: " + score ); */ /* int s2 = cS( state ); */ /* System.out.println(); */ /* System.out.println(score); */ /* System.out.println(); */ /* System.out.println(s2); */ while( !terminate ) { max = oldMax = Integer.MIN_VALUE; for(int move : moves) { if(move != -1)//if the move is valid try playing it { if(terminate == true) { System.out.print("terminate\n"); /* System.out.print( maxPly + " "); */ maxPly--; return; } prevMoveX = move; prevMoveY = state.getHeightAt( move ); state.makeMove(move); max = MinVal(state, 1, score); /* System.out.print( move + " " ); */ /* System.out.println(); */ /* System.out.println( "max: " + max + " old Max: " + oldMax ); */ if(max > oldMax)//if the new move was better than the old move that is the one we want to play { oldMax = max; tmpColToPlay = move; }//if the new move was better than the old move that is the one we want to play state.unMakeMove(); }//if the move is valid play it } maxPly++; colToPlay = tmpColToPlay; chosenMove = colToPlay; //set our move } } private int MaxVal(final GameStateModule state, int curPly, int parentScore) { int util = Integer.MIN_VALUE; int[] moves; if(state.isGameOver()) //terminal test of the psuedo code { int winner = state.getWinner(); if(winner == 0)//if the winner is 0 than there was a draw and return no reinforcement return 1; else return Integer.MIN_VALUE + 1; } //if our time has run out we need to return a utility function //right now I'm not sure if it would be better to calculate the utility function each time we reach a state or // only if we are told to terminate //right now we are calculating only if told to return if(curPly == maxPly) //if our time has run out we need to return a utility function { util = parentScore + computeScore( state ); return util; } moves = generateMoves(state); int oldPrevMoveX, oldPrevMoveY; int score = parentScore + computeScore( state ); for(int move : moves) { if(terminate == true) { //System.out.print("terminate\n"); break; }//if we have run out of time if(move != -1)//if the move is valid try playing it { //save state oldPrevMoveX = prevMoveX; oldPrevMoveY = prevMoveY; prevMoveX = move; prevMoveY = state.getHeightAt( move ); state.makeMove(move); util = Math.max(util, MinVal(state, curPly + 1, score)); /* System.out.println(util + " " + curPly + " " + move); */ state.unMakeMove(); //revert back prevMoveX = oldPrevMoveX; prevMoveY = oldPrevMoveY; }//if the move is valid play it }// return util; }//MaxVal private int MinVal(final GameStateModule state, int curPly, int parentScore) { int util = Integer.MAX_VALUE; int[] moves; if(state.isGameOver()) //terminal test of the psuedo code { int winner = state.getWinner(); if(winner == 0)//if the winner is 0 than there was a draw and return no reinforcement return 1; else return Integer.MAX_VALUE; } //if our time has run out we need to return a utility function //right now I'm not sure if it would be better to calculate the utility function each time we reach a state or // only if we are told to terminate //right now we are calculating only if told to return if(curPly == maxPly) //if our time has run out we need to return a utility function { util = parentScore + computeScore( state ); return util; } moves = generateMoves(state); int oldPrevMoveX, oldPrevMoveY; int score = parentScore + computeScore( state ); for(int move : moves) { if(terminate == true) { break; }//if we have run out of time if(move != -1)//if the move is valid try playing it { //save state oldPrevMoveX = prevMoveX; oldPrevMoveY = prevMoveY; prevMoveX = move; prevMoveY = state.getHeightAt( move ); state.makeMove(move); util = Math.min(util, MaxVal(state, curPly + 1, score)); state.unMakeMove(); //revert back prevMoveX = oldPrevMoveX; prevMoveY = oldPrevMoveY; }//if the move is valid try playing it }//for each move play it return util; }//MaxVal /** * Compute the score value of a game state. */ private int computeScore( final GameStateModule state ) { int newScore = 0, oldScore = 0; int x, y; int i, j; int width = state.getWidth(), height = state.getHeight(); /** * Compute new score first and then the old score. Return the difference. */ //check row //x starts at 0 and move to right //y is constant newScore += scoreThis( 0, prevMoveY, 1, 0, state ); //check col //x is constant //y moves from top to bottom newScore += scoreThis( prevMoveX, height - 1, 0, -1, state ); //check +y diag //first grab start x and y value x = prevMoveX - prevMoveY; y = prevMoveY - prevMoveX; if( x < 0 ) x = 0; if( y < 0 ) y = 0; newScore += scoreThis( x, y, 1, 1, state ); //check -y diag //grab start x annd start y for( x = prevMoveX, y = prevMoveY; x > 0 && y < height - 1; --x, ++y ){} newScore += scoreThis( x, y, 1, -1, state ); /* int h = state.getHeightAt( prevMoveX ); */ /* state.unMakeMove(); */ /* //check row */ /* //x starts at 0 and move to right */ /* //y is constant */ /* oldScore += scoreThis( 0, prevMoveY, 1, 0, state ); */ /* //check col */ /* //x is constant */ /* //y moves from top to bottom */ /* oldScore += scoreThis( prevMoveX, height - 1, 0, -1, state ); */ /* //check +y diag */ /* //first grab start x and y value */ /* x = prevMoveX - prevMoveY; */ /* y = prevMoveY - prevMoveX; */ /* if( x < 0 ) x = 0; */ /* if( y < 0 ) y = 0; */ /* oldScore += scoreThis( x, y, 1, 1, state ); */ /* //check -y diag */ /* //grab start x annd start y */ /* for( x = prevMoveX, y = prevMoveY; x > 0 && y < height - 1; --x, ++y ){} */ /* oldScore += scoreThis( x, y, 1, -1, state ); */ /* state.makeMove( prevMoveX ); */ /* int h2 = state.getHeightAt( prevMoveX ); */ /* if( h != h2 ) System.exit(1); */ return newScore - oldScore; } private int scoreThis( int begX, int begY, int dX, int dY, final GameStateModule state ) { LinkedList <Integer> deck = new LinkedList <Integer> (); int width = state.getWidth(), height = state.getHeight(); int score = 0; int sameCoin = 0; int firstCoinOfSet = -1; int i, rind; int tmp, currCoin; int x, y; //cases with columns and -y diagonals if( dY < 0 ) { for( x = begX, y = begY; x < width && y >= 0; x += dX, y += dY ) { currCoin = state.getAt( x, y ); if( currCoin == firstCoinOfSet ) { deck.addLast( currCoin ); sameCoin++; } else { if( currCoin == 0 ) deck.addLast( currCoin ); else { if( firstCoinOfSet > 0 ) { //Also takes care of case when list is initially empty rind = deck.lastIndexOf( firstCoinOfSet ) + 1; for( i = 0; i < rind; ++i ) deck.removeFirst(); } deck.addLast(currCoin); sameCoin = 1; firstCoinOfSet = currCoin; } } if( deck.size() >= 4 ) { if( firstCoinOfSet == player ) score += points[ sameCoin ]; else score -= points[ sameCoin ]; if( deck.removeFirst() == firstCoinOfSet ) --sameCoin; } } } else { for( x = begX, y = begY; x < width && y < height; x += dX, y += dY ) { currCoin = state.getAt( x, y ); if( currCoin == firstCoinOfSet ) { deck.addLast( currCoin ); sameCoin++; } else { if( currCoin == 0 ) deck.addLast( currCoin ); else { if( firstCoinOfSet > 0 ) { //Also takes care of case when list is initially empty rind = deck.lastIndexOf( firstCoinOfSet ) + 1; for( i = 0; i < rind; ++i ) deck.removeFirst(); } deck.addLast(currCoin); sameCoin = 1; firstCoinOfSet = currCoin; } } if( deck.size() >= 4 ) { if( firstCoinOfSet == player ) score += points[ sameCoin ]; else score -= points[ sameCoin ]; if( deck.removeFirst() == firstCoinOfSet ) --sameCoin; } } } return score; } private int initFirstStateScore( final GameStateModule state ) { int width = state.getWidth(), height = state.getHeight(); int minHeight = Integer.MAX_VALUE, maxHeight = Integer.MIN_VALUE; int score = 0; int x, y; //Find lowest and highest height of the blank spot for( int i = 0; i < width; ++i ) { if( state.getHeightAt( i ) < minHeight ) minHeight = i; if( state.getHeightAt( i ) > maxHeight ) maxHeight = i; } //Generate all rows and compute score for( y = minHeight; y <= maxHeight; ++y ) score += scoreThis( 0, y, 1, 0, state ); /* System.out.println( "rows: " + score ); */ //Generate all columns for( x = 0; x < width; ++x ) score += scoreThis( x, height - 1, 0, -1, state ); //Generate +y diagonals left half for( y = height - 4; y >= 0; --y ) score += scoreThis( 0, y, 1, 1, state ); int endX = width - 3; //cache the stop parameter //Generate +y diagonals right half for( x = 1; x < endX; ++x ) score += scoreThis( x, 0, 1, 1, state ); //Generate -y diagonals left half for( y = 3; y < height; ++y ) score += scoreThis( 0, y, 1, -1, state ); //Generate -y diagonals right half for( x = 1; x < endX; ++x ) score += scoreThis( x, height - 1, 1, -1, state ); return score; } }//minimax_WorldEnderH4G1
33.011038
118
0.462619
fe7562b5adbf1b07a2624c5e2c75ed3715eea526
11,705
package com.zainchen.game2048.core; import java.util.Random; /** * 核心游戏逻辑 * * @author Zain Chen * @date 2021/4/6 14:13 */ public class CoreModelImpl implements CoreModel { /** * 数据的行数 */ private final int rowSum; /** * 数据的列数 */ private final int colSum; /** * 数据监听器 */ private DataListener dataListener; /** * 二维数组数据 */ private final int[][] data; /** * 当前得分 */ private int currentScore; /** * 游戏状态, 默认为游戏状态 */ private GameState gameState = GameState.game; /** * 随机数生成器 */ private final Random random; public CoreModelImpl(int rowSum, int colSum, DataListener dataListener) { this.rowSum = rowSum; this.colSum = colSum; this.dataListener = dataListener; data = new int[rowSum][colSum]; random = new Random(); } @Override public void initData() { //所有卡片数字初始化为0 for (int row = 0; row < rowSum; row++) { for (int col = 0; col < colSum; col++) { data[row][col] = 0; } } // 重置状态 currentScore = 0; gameState = GameState.game; // 随机生成两个数字 randomGenerateNumber(); randomGenerateNumber(); } @Override public int[][] getData() { return data; } @Override public int getCurrentScore() { return currentScore; } @Override public void toUp() { //若非正在游戏状态时调用该方法,直接忽略 if (gameState != GameState.game) { return; } //是否有卡片移动或合并的标记 boolean hasMove = false; //竖直方向移动, 依次遍历每一列 for (int col = 0; col < colSum; col++) { //向上移动, 从第 0 行开始依次向下遍历每一行 for (int row = 0; row < rowSum; row++) { //找出当前遍历行 row 下面的首个非空卡片, 将该非空卡片移动到当前 row 行位置 for (int tmpRow = row + 1; tmpRow < rowSum; tmpRow++) { //判断该位置下面的位置,如果是0,就不需要进行移动或合并操作,继续下一个tmpRow循环,遍历下一个位置 if (data[tmpRow][col] == 0) { continue; } //如果遇到下面的row行位置卡片非空,对当前位置进行判断 if (data[row][col] == 0) { //如果当前 row 行位置是空的, 则直接移动卡片 data[row][col] = data[tmpRow][col]; if(dataListener != null){ dataListener.onNumberMove(tmpRow,row,col,true); } hasMove = true; //数字移动后原位置清零 data[tmpRow][col] = 0; //当前空位置被移入新卡片后,break进入下一次row循环,需要再次对刷新数字的该位置进行判断 row--; } else if (data[row][col] == data[tmpRow][col]) { //如果当前row行位置和找到的row下面首个非空卡片的数字相同, 则合并数字 data[row][col] += data[tmpRow][col]; hasMove = true; //增加分数 currentScore += data[row][col]; //回调监听 if (dataListener != null) { dataListener.onNumberMove(tmpRow,row,col,true); dataListener.onNumberMerge(row, col, data[row][col], currentScore); } //合并后原位置清零 data[tmpRow][col] = 0; } //如果数字不相等,进入下一个row循环 break; } } } //进行滑动操作后需要检测是否游戏结束和生成新数字 if (hasMove) { //校验游戏是否结束(过关或失败) checkGameFinish(); //移动完一次后, 随机生成一个数字 randomGenerateNumber(); //防止生成数字后就是不可再移动状态,需要再次检验 checkGameFinish(); } } @Override public void toDown() { if (gameState != GameState.game) { return; } boolean hasMove = false; //从左到右,从下到上 for (int col = 0; col < colSum; col++) { for (int row = rowSum - 1; row > 0; row--) { for (int tmpRow = row - 1; tmpRow >= 0; tmpRow--) { if (data[tmpRow][col] == 0) { continue; } if (data[row][col] == 0) { data[row][col] = data[tmpRow][col]; if(dataListener != null){ dataListener.onNumberMove(tmpRow,row,col,true); } hasMove = true; data[tmpRow][col] = 0; row++; } else if (data[tmpRow][col] == data[row][col]) { data[row][col] += data[tmpRow][col]; hasMove = true; currentScore += data[row][col]; if (dataListener != null) { dataListener.onNumberMove(tmpRow,row,col,true); dataListener.onNumberMerge(row, col, data[row][col], currentScore); } data[tmpRow][col] = 0; } break; } } } if (hasMove) { checkGameFinish(); randomGenerateNumber(); checkGameFinish(); } } @Override public void toLeft() { if (gameState != GameState.game) { return; } boolean hasMove = false; //从上到下,从左到右 for (int row = 0; row < rowSum; row++) { for (int col = 0; col < colSum; col++) { for (int tmpCol = col + 1; tmpCol < colSum; tmpCol++) { if (data[row][tmpCol] == 0) { continue; } if (data[row][col] == 0) { data[row][col] = data[row][tmpCol]; if(dataListener != null){ dataListener.onNumberMove(tmpCol,col,row,false); } hasMove = true; data[row][tmpCol] = 0; col--; } else if (data[row][col] == data[row][tmpCol]) { data[row][col] += data[row][col]; hasMove = true; currentScore += data[row][col]; if (dataListener != null) { dataListener.onNumberMove(tmpCol,col,row,false); dataListener.onNumberMerge(row, col, data[row][col], currentScore); } data[row][tmpCol] = 0; } break; } } } if (hasMove) { checkGameFinish(); randomGenerateNumber(); checkGameFinish(); } } @Override public void toRight() { if (gameState != GameState.game) { return; } boolean hasMove = false; //从上到下,从右到左 for (int row = 0; row < rowSum; row++) { for (int col = colSum - 1; col >= 0; col--) { for (int tmpCol = col - 1; tmpCol >= 0; tmpCol--) { if (data[row][tmpCol] == 0) { continue; } if (data[row][col] == 0) { data[row][col] = data[row][tmpCol]; if(dataListener != null){ dataListener.onNumberMove(tmpCol,col,row,false); } hasMove = true; data[row][tmpCol] = 0; col++; } else if (data[row][col] == data[row][tmpCol]) { data[row][col] += data[row][col]; hasMove = true; currentScore += data[row][col]; if (dataListener != null) { dataListener.onNumberMove(tmpCol,col,row,false); dataListener.onNumberMerge(row, col, data[row][col], currentScore); } data[row][tmpCol] = 0; } break; } } } if (hasMove) { checkGameFinish(); randomGenerateNumber(); checkGameFinish(); } } /** * 随机生成数字2或4,20%的概率生成4,80%的概率生成2 */ private void randomGenerateNumber() { // 计算出空卡片的数量(数字为 0 的卡片) int emptyCardsCount = 0; for (int row = 0; row < rowSum; row++) { for (int col = 0; col < colSum; col++) { if (data[row][col] == 0) { emptyCardsCount++; } } } //如果没有空卡片,游戏结束 if (emptyCardsCount == 0) { gameState = GameState.gameOver; if (dataListener != null) { dataListener.onGameOver(false); } } /* 如果有空卡片,在这些空卡片中随机挑选一个生成数字 */ //在所有空位置中随机挑选一个位置生成数字,位置范围0~emptyCardsCount-1 int newNumPosition = random.nextInt(emptyCardsCount); //通过设置的概率生成2,否则生成4 float newTwoProbability = 0.8f; int newNum = random.nextFloat() < newTwoProbability ? 2 : 4; //寻找指定空位置,放入生成的数字 int emptyCardPosition = 0; for (int row = 0; row < rowSum; row++) { for (int col = 0; col < colSum; col++) { //忽略非空卡片 if (data[row][col] != 0) { continue; } //指定位置的空卡片, 放入数字 if (emptyCardPosition == newNumPosition) { data[row][col] = newNum; // 有数字生成, 回调监听 if (dataListener != null) { dataListener.onGenerateNumber(row, col, newNum); } } // 还没有遍历到指定位置的空卡片, 继续遍历 emptyCardPosition++; } } } /** * 判断游戏是否结束 */ private void checkGameFinish() { //判断是否游戏胜利(过关) for (int row = 0; row < rowSum; row++) { for (int col = 0; col < colSum; col++) { //如果有一个卡片拼凑出2048, 游戏即胜利 if (data[row][col] == 2048) { gameState = GameState.win; if (dataListener != null) { dataListener.onGameOver(true); } } } } //若游戏还没有胜利, 则判断是否还可移动 if (!isRemovable()) { //如果游戏没有胜利, 卡片又不可再移动, 则游戏失败 gameState = GameState.gameOver; if (dataListener != null) { dataListener.onGameOver(false); } } } /** * 判断卡片是否可以再移动 * * @return 是否还可以移动 */ private boolean isRemovable() { //判断水平方式是否可移动 for (int row = 0; row < rowSum; row++) { for (int col = 0; col < colSum-1; col++) { if (data[row][col] == 0 || data[row][col + 1] == 0 || data[row][col] == data[row][col + 1]) { return true; } } } //判断垂直方向是否可移动 for (int col = 0; col < colSum; col++) { for (int row = 0; row < rowSum - 1; row++) { if (data[row][col] == 0 || data[row + 1][col] == 0 || data[row][col] == data[row + 1][col]) { return true; } } } return false; } }
29.783715
109
0.407176
3352fb4272aca301965f2c60dba45179bb7bc53a
5,291
package com.google.android.datatransport.cct.a; import com.google.android.datatransport.cct.a.zza; /* compiled from: com.google.android.datatransport:transport-backend-cct@@2.2.0 */ final class zzd extends zza { private final int zza; private final String zzb; private final String zzc; private final String zzd; private final String zze; private final String zzf; private final String zzg; private final String zzh; /* compiled from: com.google.android.datatransport:transport-backend-cct@@2.2.0 */ static final class zza extends zza.C0043zza { private Integer zza; private String zzb; private String zzc; private String zzd; private String zze; private String zzf; private String zzg; private String zzh; zza() { } public zza.C0043zza zza(int i) { this.zza = Integer.valueOf(i); return this; } public zza.C0043zza zzb(String str) { this.zzh = str; return this; } public zza.C0043zza zzc(String str) { this.zzc = str; return this; } public zza.C0043zza zzd(String str) { this.zzg = str; return this; } public zza.C0043zza zze(String str) { this.zzb = str; return this; } public zza.C0043zza zzf(String str) { this.zzf = str; return this; } public zza.C0043zza zzg(String str) { this.zze = str; return this; } public zza.C0043zza zza(String str) { this.zzd = str; return this; } public zza zza() { String str = ""; if (this.zza == null) { str = str + " sdkVersion"; } if (str.isEmpty()) { return new zzd(this.zza.intValue(), this.zzb, this.zzc, this.zzd, this.zze, this.zzf, this.zzg, this.zzh, (zzc) null); } throw new IllegalStateException("Missing required properties:" + str); } } /* synthetic */ zzd(int i, String str, String str2, String str3, String str4, String str5, String str6, String str7, zzc zzc2) { this.zza = i; this.zzb = str; this.zzc = str2; this.zzd = str3; this.zze = str4; this.zzf = str5; this.zzg = str6; this.zzh = str7; } public boolean equals(Object obj) { String str; String str2; String str3; String str4; String str5; String str6; if (obj == this) { return true; } if (!(obj instanceof zza)) { return false; } zzd zzd2 = (zzd) ((zza) obj); if (this.zza == zzd2.zza && ((str = this.zzb) != null ? str.equals(zzd2.zzb) : zzd2.zzb == null) && ((str2 = this.zzc) != null ? str2.equals(zzd2.zzc) : zzd2.zzc == null) && ((str3 = this.zzd) != null ? str3.equals(zzd2.zzd) : zzd2.zzd == null) && ((str4 = this.zze) != null ? str4.equals(zzd2.zze) : zzd2.zze == null) && ((str5 = this.zzf) != null ? str5.equals(zzd2.zzf) : zzd2.zzf == null) && ((str6 = this.zzg) != null ? str6.equals(zzd2.zzg) : zzd2.zzg == null)) { String str7 = this.zzh; if (str7 == null) { if (zzd2.zzh == null) { return true; } } else if (str7.equals(zzd2.zzh)) { return true; } } return false; } public int hashCode() { int i = (this.zza ^ 1000003) * 1000003; String str = this.zzb; int i2 = 0; int hashCode = (i ^ (str == null ? 0 : str.hashCode())) * 1000003; String str2 = this.zzc; int hashCode2 = (hashCode ^ (str2 == null ? 0 : str2.hashCode())) * 1000003; String str3 = this.zzd; int hashCode3 = (hashCode2 ^ (str3 == null ? 0 : str3.hashCode())) * 1000003; String str4 = this.zze; int hashCode4 = (hashCode3 ^ (str4 == null ? 0 : str4.hashCode())) * 1000003; String str5 = this.zzf; int hashCode5 = (hashCode4 ^ (str5 == null ? 0 : str5.hashCode())) * 1000003; String str6 = this.zzg; int hashCode6 = (hashCode5 ^ (str6 == null ? 0 : str6.hashCode())) * 1000003; String str7 = this.zzh; if (str7 != null) { i2 = str7.hashCode(); } return hashCode6 ^ i2; } public String toString() { return "AndroidClientInfo{sdkVersion=" + this.zza + ", model=" + this.zzb + ", hardware=" + this.zzc + ", device=" + this.zzd + ", product=" + this.zze + ", osBuild=" + this.zzf + ", manufacturer=" + this.zzg + ", fingerprint=" + this.zzh + "}"; } public String zzb() { return this.zzd; } public String zzc() { return this.zzh; } public String zzd() { return this.zzc; } public String zze() { return this.zzg; } public String zzf() { return this.zzb; } public String zzg() { return this.zzf; } public String zzh() { return this.zze; } public int zzi() { return this.zza; } }
29.724719
477
0.516727
82eeaa2d9b293b61a0435e54d6bc3381319cbf2d
916
import java.util.*; class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); String[] line = scanner.nextLine().split(" ", 2); int a = Integer.parseInt(line[0]); int b = Integer.parseInt(line[1]); boolean[] passed = new boolean[n]; passed[a-1] = true; passed[b-1] = true; int k = Integer.parseInt(scanner.nextLine()); line = scanner.nextLine().split(" ", k); boolean yes = true; for (int i = 0; i < k; i++) { int p = Integer.parseInt(line[i]); if (passed[p-1]) { yes = false; break; } passed[p-1] = true; } if (yes) { System.out.println("YES"); } else { System.out.println("NO"); } } }
26.171429
57
0.474891
0ff73f6779eb40be77084405af677b40feb95a68
672
package com.ygy.model; public class OssClientPro { private String endpoint; private String accessKeyId; private String accessKeySecret; public String getAccessKeyId() { return accessKeyId; } public String getAccessKeySecret() { return accessKeySecret; } public String getEndpoint() { return endpoint; } public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; } public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } }
21.677419
60
0.669643
25113b34486553182b456806b32f714bea65dbbe
1,255
import javafx.scene.Node; import javafx.scene.canvas.GraphicsContext; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.shape.Rectangle; public abstract class GameObject { protected int x, y, width, height; //TODO use Yspeed later to replace constant protected Image img; protected Node node; protected ImageView Img; protected Rectangle rectangle; //object for collision GameObject(Image img, int x, int y){ this.img = img; this.x = x; this.y = y; this.width = (int) img.getWidth(); this.height = (int) img.getHeight(); this.Img = new ImageView(img); this.node = Img; this.rectangle = new Rectangle(x, y, img.getWidth(), img.getHeight()); } public int getX(){ return this.x; } public int getY(){ return this.y; } public Image getImg() { return this.img; } public Node getNode(){ return this.node; } public Rectangle getRectangle() { return rectangle; } public void setX(int a){ this.x = a; } public void setY(int b){ this.y = b; } public void moveObject() { node.relocate(x, y); } }
22.410714
83
0.596813
9beec2ded96c1679735e9643208855db6dc6ddff
4,215
/* * Copyright 2014-2016 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.data.hazelcast.repository.support; import org.springframework.data.hazelcast.repository.query.HazelcastPartTreeQuery; import org.springframework.data.keyvalue.core.KeyValueOperations; import org.springframework.data.projection.ProjectionFactory; import org.springframework.data.repository.core.NamedQueries; import org.springframework.data.repository.core.RepositoryMetadata; import org.springframework.data.repository.query.EvaluationContextProvider; import org.springframework.data.repository.query.QueryLookupStrategy; import org.springframework.data.repository.query.RepositoryQuery; import org.springframework.data.repository.query.parser.AbstractQueryCreator; import org.springframework.util.Assert; import java.lang.reflect.Method; /** * <p> * Ensures {@link HazelcastPartTreeQuery} is used for query preparation rather than {@link org.springframework.data.keyvalue.repository.query.KeyValuePartTreeQuery} or * other alternatives. * </P> * * @author Neil Stevenson */ public class HazelcastQueryLookupStrategy implements QueryLookupStrategy { private EvaluationContextProvider evaluationContextProvider; private KeyValueOperations keyValueOperations; private Class<? extends AbstractQueryCreator<?, ?>> queryCreator; /** * <p> * Required constructor, capturing arguments for use in {@link #resolveQuery}. * </P> * <p> * Assertions copied from {@link org.springframework.data.keyvalue.repository.support.KeyValueRepositoryFactory.KeyValueQueryLookupStrategy} which this class essentially * duplicates. * </P> * * @param key Not used * @param evaluationContextProvider For evaluation of query expressions * @param keyValueOperations Bean to use for Key/Value operations on Hazelcast repos * @param queryCreator Likely to be {@link org.springframework.data.hazelcast.repository.query.HazelcastQueryCreator} */ public HazelcastQueryLookupStrategy(QueryLookupStrategy.Key key, EvaluationContextProvider evaluationContextProvider, KeyValueOperations keyValueOperations, Class<? extends AbstractQueryCreator<?, ?>> queryCreator) { Assert.notNull(evaluationContextProvider, "EvaluationContextProvider must not be null!"); Assert.notNull(keyValueOperations, "KeyValueOperations must not be null!"); Assert.notNull(queryCreator, "Query creator type must not be null!"); this.evaluationContextProvider = evaluationContextProvider; this.keyValueOperations = keyValueOperations; this.queryCreator = queryCreator; } /** * <p> * Use {@link HazelcastPartTreeQuery} for resolving queries against Hazelcast repositories. * </P> * * @param method, the query method * @param metadata, not used * @param projectionFactory, not used * @param namedQueries, not used * @return A mechanism for querying Hazelcast repositories */ public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, ProjectionFactory projectionFactory, NamedQueries namedQueries) { HazelcastQueryMethod queryMethod = new HazelcastQueryMethod(method, metadata, projectionFactory); if (queryMethod.hasAnnotatedQuery()) { return new StringBasedHazelcastRepositoryQuery(queryMethod); } return new HazelcastPartTreeQuery(queryMethod, evaluationContextProvider, this.keyValueOperations, this.queryCreator); } }
43.90625
173
0.741874
f3c15ac5f33f6d9ed33db94aa4b317a6da867dc0
10,784
package com.miu360.legworkwrit.mvp.ui.activity; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.RadioButton; import android.widget.TextView; import com.blankj.utilcode.util.ActivityUtils; import com.jess.arms.di.component.AppComponent; import com.miu30.common.config.Config; import com.miu30.common.ui.entity.JCItem; import com.miu360.legworkwrit.R; import com.miu360.legworkwrit.R2; import com.miu360.legworkwrit.di.component.DaggerTalkNoticeComponent; import com.miu360.legworkwrit.di.module.TalkNoticeModule; import com.miu360.legworkwrit.mvp.contract.TalkNoticeContract; import com.miu360.legworkwrit.mvp.data.CacheManager; import com.miu360.legworkwrit.mvp.model.entity.AgencyInfo; import com.miu360.legworkwrit.mvp.model.entity.JCItemWrapper; import com.miu360.legworkwrit.mvp.model.entity.ParentQ; import com.miu360.legworkwrit.mvp.model.entity.TalkNoticeQ; import com.miu360.legworkwrit.mvp.presenter.TalkNoticePresenter; import com.miu360.legworkwrit.util.DialogUtil; import com.miu360.legworkwrit.util.GetUTCUtil; import com.miu360.legworkwrit.util.InputFilterUtil; import com.miu360.legworkwrit.util.TimeTool; import com.mobsandgeeks.saripaar.annotation.NotEmpty; import org.simple.eventbus.Subscriber; import java.util.Date; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; /** * 谈话通知书 */ public class TalkNoticeActivity extends BaseInstrumentActivity<TalkNoticePresenter> implements TalkNoticeContract.View { //当事人 @BindView(R2.id.et_litigant) @NotEmpty EditText etLitigant; //机关地址 @BindView(R2.id.tv_agency_address) @NotEmpty TextView tvAgencyAddress; //机关电话 @BindView(R2.id.tv_agency_phone) @NotEmpty TextView tvAgencyPhone; //车牌号 @BindView(R2.id.et_car_license) @NotEmpty EditText etCarLicense; @BindView(R2.id.tv_illegal_reason) @NotEmpty TextView tvIllegalReason; @BindView(R2.id.rbtn_sure) RadioButton rbtnSure; @BindView(R2.id.rbtn_no) RadioButton rbtnNo; @NotEmpty(message = "请选择送达时间") @BindView(R2.id.tv_send_time) TextView tvSendTime; @BindView(R2.id.ll_send_time) LinearLayout llSendTime; private JCItem mJcItem; private long sTime;//获取默认的开始时间 @Override public void setupActivityComponent(@NonNull AppComponent appComponent) { DaggerTalkNoticeComponent .builder() .appComponent(appComponent) .talkNoticeModule(new TalkNoticeModule(this, this)) .build() .inject(this); } @Override public int initView(@Nullable Bundle savedInstanceState) { return R.layout.activity_talk_notice; } @Override public void initData(@Nullable Bundle savedInstanceState) { instrumentType = Config.T_TALKNOTICE; header.init(self, "谈话通知书"); super.initData(savedInstanceState); sTime = GetUTCUtil.getLiveCheckRecordEndTimeL(mCase); etLitigant.setFilters(InputFilterUtil.getInputFilters(InputFilterUtil.letterChineseRegex, 10)); etCarLicense.setFilters(InputFilterUtil.getInputFilters(InputFilterUtil.letterNumberChineseRegex, 8)); assert mPresenter != null; mPresenter.init(this, etCarLicense, etLitigant, mCase,tvSendTime, sTime); } @Override public void onValidationSucceeded() { assert mPresenter != null; TalkNoticeQ talkNoticeQ = new TalkNoticeQ(); talkNoticeQ.setDSR(etLitigant.getText().toString()); talkNoticeQ.setVNAME(etCarLicense.getText().toString()); talkNoticeQ.setJGDZ(tvAgencyAddress.getText().toString()); talkNoticeQ.setJGDH(tvAgencyPhone.getText().toString()); if (mJcItem != null) { talkNoticeQ.setSXWFSYBC(mJcItem.getLBMC()); } else { talkNoticeQ.setSXWFSYBC(tvIllegalReason.getText().toString()); } talkNoticeQ.setZID(mCase.getID()); talkNoticeQ.setID(instrumentID); if(rbtnSure.isChecked()){ talkNoticeQ.setSTATUS("1"); long endT = TimeTool.getYYHHmm(tvSendTime.getText().toString()).getTime(); talkNoticeQ.setSDSJ(( endT / 1000) + ""); talkNoticeQ.setXZJGSJ(Long.valueOf(GetUTCUtil.setEndTime(sTime*1000,( endT / 1000) + "",Config.UTC_TALKNOTICE)) +""); talkNoticeQ.setQSSJ(Long.valueOf(GetUTCUtil.setEndTime(sTime*1000,( endT / 1000) + "",Config.UTC_TALKNOTICE)) +""); }else{ talkNoticeQ.setSTATUS("0"); talkNoticeQ.setXZJGSJ(String.valueOf(sTime + Config.UTC_TALKNOTICE)); talkNoticeQ.setQSSJ(String.valueOf(sTime + Config.UTC_TALKNOTICE)); } talkNoticeQ.setZFZH1(mCase.getZFZH1()); talkNoticeQ.setZFZH2(mCase.getZHZH2()); talkNoticeQ.setZFRY1(mCase.getZFRYNAME1()); talkNoticeQ.setZFRY2(mCase.getZFRYNAME2()); talkNoticeQ.setZH(mCase.getZH()); if (1 == clickStatus) { startActivityForResult(WebViewActivity.getIntent(self, talkNoticeQ, false), 0x0111); } else if (3 == clickStatus) { startActivityForResult(CaseSignActivity.getIntent(self, talkNoticeQ, false), 0x0001); } else if (!isUpdate) { mPresenter.addTalkNotice(talkNoticeQ); } else { //调更新接口 mPresenter.updateTalkNotice(talkNoticeQ, checkChange(), followInstruments); } } @OnClick({R2.id.tv_illegal_reason, R2.id.tv_agency_address, R2.id.tv_agency_phone,R2.id.tv_send_time, R2.id.rbtn_sure, R2.id.rbtn_no}) public void onViewClicked(View v) { assert mPresenter != null; int i = v.getId(); if (i == R.id.tv_illegal_reason) { ActivityUtils.startActivity(IllegalDetailActivityActivity.class); } else if (i == R.id.tv_agency_address) { mPresenter.showAgencyAddress(self, tvAgencyAddress, tvAgencyPhone); } else if (i == R.id.tv_agency_phone) { mPresenter.showAgencyPhone(self, tvAgencyAddress, tvAgencyPhone); } else if(i == R.id.tv_send_time){ mPresenter.showSendTime(tvSendTime); } else if (i == R.id.rbtn_sure) { llSendTime.setVisibility(View.VISIBLE); } else if (i == R.id.rbtn_no) { llSendTime.setVisibility(View.GONE); } } @SuppressWarnings("all") @Subscriber(tag = Config.ILLEGAL) public void showIllegal(JCItemWrapper wrapper) { mJcItem = wrapper.getIllegalBehavior(); tvIllegalReason.setText(mJcItem.getLBMC()); } /* * 把现场检查笔录相关信息带入 */ @Override public void showViewPartContent() { if (CacheManager.getInstance().getLawToLive() != null) { tvIllegalReason.setText(CacheManager.getInstance().getLawToLive().getWfxw()); } if (CacheManager.getInstance().getLiveCheckRecord() != null) { tvIllegalReason.setText(CacheManager.getInstance().getLiveCheckRecord().getWFXW()); } List<AgencyInfo> agencyInfos = CacheManager.getInstance().getAgencyInfoByZFZH(); if (agencyInfos != null && agencyInfos.size() > 0) { tvAgencyAddress.setText(agencyInfos.get(0).getDZ()); tvAgencyPhone.setText(agencyInfos.get(0).getDH()); } } /* * 把填写到服务器的信息回填到视图上 */ @Override public void showViewContent(ParentQ parentQ) { TalkNoticeQ info = (TalkNoticeQ) parentQ; this.instrumentID = info.getID(); etLitigant.setText(info.getDSR()); etCarLicense.setText(info.getVNAME()); tvAgencyAddress.setText(info.getJGDZ()); tvAgencyPhone.setText(info.getJGDH()); if ("0".equals(info.getSTATUS())) { rbtnNo.setChecked(true); } else { rbtnSure.setChecked(true); } setEffctNr(info); setViewTime(info); } //控件设置时间 private void setViewTime(TalkNoticeQ info) { long duration = 0; if (isConfirmed()) {//如果是待确认的状态 duration = TimeTool.parseDate2(info.getSDSJ()).getTime() - sTime*1000; } if (!"0".equals(info.getSTATUS())) { rbtnSure.setChecked(true); if (isConfirmed()) {//如果是待确认的状态 if (duration > 0) { tvSendTime.setHint(TimeTool.yyyyMMdd_HHmm.format(TimeTool.parseDate2(info.getSDSJ()))); } else { setEndTime(); } } else { tvSendTime.setText(TimeTool.yyyyMMdd_HHmm.format(TimeTool.parseDate2(info.getSDSJ()))); } } else { llSendTime.setVisibility(View.GONE); rbtnNo.setChecked(true); setEndTime(); } } /** * 设置界面上所谓的结束时间;因为已填写的时根据第一次填写的时间段,整段往后移 */ private void setEndTime() { tvSendTime.setText(""); tvSendTime.setHint(TimeTool.yyyyMMdd_HHmm.format(new Date(sTime*1000))); } /* * 当待确认状态时设置违法情形 */ private void setEffctNr(TalkNoticeQ info) { mJcItem = new JCItem(); if (isConfirmed() && CacheManager.getInstance().getLiveCheckRecord() != null) { tvIllegalReason.setText(CacheManager.getInstance().getLiveCheckRecord().getWFXW()); mJcItem.setLBMC(CacheManager.getInstance().getLiveCheckRecord().getWFXW()); } else { tvIllegalReason.setText(info.getSXWFSYBC()); mJcItem.setLBMC(info.getSXWFSYBC()); } } @Override public void showCaseContent() { etCarLicense.setText(mCase.getVNAME()); etLitigant.setText(mCase.getBJCR()); } @Override public void showTime(Date date, boolean isStart) { if (date.getTime() < sTime * 1000) { DialogUtil.showTipDialog(self, "送达时间必须大于现场检查笔录时间和案件创建时间"); return; } tvSendTime.setText(TimeTool.yyyyMMdd_HHmm.format(date)); } @Override public boolean checkChange() { boolean isNeedUpdateStatus = false; for (int i = 0; i < followInstruments.size(); i++) { if (Config.ID_TALKNOTICE.equals(followInstruments.get(i).getId()) && 2 == followInstruments.get(i).getStatus()) { isNeedUpdateStatus = true; } } return isNeedUpdateStatus; } @Override public String getInstrumentId() { return Config.ID_TALKNOTICE; } @Override public void getID(String id) { if (TextUtils.isEmpty(id) || "null".equals(id)) return; this.instrumentID = id; } }
35.827243
129
0.655415
8f38b780ff4baad377b9bc3dd1defa162bb1f00d
1,047
package com.solactive.solactive_code_challenge.calculators; import java.util.*; public class QuantileCalculator extends GenericWindowCalculator { public static Double calculate(Map<Long, Double> ticks, Double percentile) { ArrayList<Double> values = new ArrayList(ticks.values()); Collections.sort(values); Double percentileIncrease = 1.0 / (ticks.size() - 1); Double actualPercentile = 0.0; if (values.size() == 1) { return values.get(0); } for (Iterator<Double> it = values.iterator(); it.hasNext(); ) { Double actualValue = it.next(); if (actualPercentile + percentileIncrease > percentile) { it.hasNext(); Double nextValue = it.next(); Double quantile = (percentile - actualPercentile) * (nextValue - actualValue) / percentileIncrease + actualValue; return quantile; } actualPercentile += percentileIncrease; } return Double.NaN; } }
34.9
129
0.606495
c524b3187e5c2f304183f163f39274b5fda04828
2,070
/* SHOGun, https://terrestris.github.io/shogun/ * * Copyright © 2020-present terrestris GmbH & Co. KG * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * 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 de.terrestris.shogun.lib.config; import de.terrestris.shogun.lib.security.access.BasePermissionEvaluator; import de.terrestris.shogun.lib.security.access.entity.BaseEntityPermissionEvaluator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration; @Configuration @EnableGlobalMethodSecurity(prePostEnabled = true) public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration { @Autowired private BasePermissionEvaluator basePermissionEvaluator; @Autowired private List<BaseEntityPermissionEvaluator> permissionEvaluators; @Override protected MethodSecurityExpressionHandler createExpressionHandler() { DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler(); expressionHandler.setPermissionEvaluator(basePermissionEvaluator); return expressionHandler; } }
42.244898
109
0.809179
142edab629e54f134561d3fa5f0d421fb4479d45
5,214
/* * Copyright 2011 Tyler Blair. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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. * * The views and conclusions contained in the software and documentation are those of the * authors and contributors and should not be interpreted as representing official policies, * either expressed or implied, of anybody else. */ package com.griefcraft.lwc; import com.griefcraft.util.Colors; import com.griefcraft.util.StringUtil; import java.util.HashMap; import java.util.Map; import java.util.ResourceBundle; public class SimpleMessageParser implements MessageParser { /** * The i18n localization bundle */ private final ResourceBundle locale; /** * Cached messages */ private final Map<String, String> basicMessageCache = new HashMap<>(); /** * A heavy cache that includes binds. */ private final Map<String, String> bindMessageCache = new HashMap<>(); public SimpleMessageParser(ResourceBundle locale) { this.locale = locale; } public String parseMessage(String key, Object... args) { key = StringUtil.fastReplace(key, ' ', '_'); // For the bind cache String cacheKey = key; // add the arguments to the cache key if (args != null && args.length > 0) { for (Object argument : args) { cacheKey += argument.toString(); } } if (bindMessageCache.containsKey(cacheKey)) { return bindMessageCache.get(cacheKey); } if (!locale.containsKey(key)) { return null; } Map<String, Object> bind = parseBinds(args); String value = basicMessageCache.get(key); if (value == null) { value = locale.getString(key); // apply colors for (String colorKey : Colors.localeColors.keySet()) { String color = Colors.localeColors.get(colorKey); if (value.contains(colorKey)) { value = StringUtil.fastReplace(value, colorKey, color); } } // Apply aliases String[] aliasvars = new String[]{"cprivate", "cpublic", "cpassword", "cmodify", "cunlock", "cinfo", "cremove"}; // apply command name modification depending on menu style for (String alias : aliasvars) { String replace = "%" + alias + "%"; if (!value.contains(replace)) { continue; } String localeName = alias + ".basic"; value = value.replace(replace, parseMessage(localeName)); } // Cache it basicMessageCache.put(key, value); } // apply binds for (String bindKey : bind.keySet()) { Object object = bind.get(bindKey); value = StringUtil.fastReplace(value, "%" + bindKey + "%", object.toString()); } // include the binds bindMessageCache.put(cacheKey, value); return value; } /** * Convert an even-lengthed argument array to a map containing String keys i.e parseBinds("Test", null, "Test2", obj) = Map().put("test", null).put("test2", obj) * * @param args * @return */ private Map<String, Object> parseBinds(Object... args) { Map<String, Object> bind = new HashMap<>(); if (args == null || args.length < 2) { return bind; } if (args.length % 2 != 0) { throw new IllegalArgumentException("The given arguments length must be equal"); } int size = args.length; for (int index = 0; index < args.length; index += 2) { if ((index + 2) > size) { break; } String key = args[index].toString(); Object object = args[index + 1]; bind.put(key, object); } return bind; } }
32.792453
165
0.607979
991282a281450410560c8ce03d276b3ab7db6d40
1,241
package ru.job4j.filtration; import java.util.Objects; /** * * Class Класс описывает действия ученика * @athor Buryachenko * @since 04.03.19 * @version 1 */ public class Student { private int score; private String surname; public Student(String surname) { this.surname = surname; } public Student(int score) { this.score = score; } public int getScore() { return this.score; } public String getSurname() { return this.surname; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Student other = (Student) obj; if (!Objects.equals(this.surname, other.surname)) { return false; } if (!Objects.equals(this.score, other.score)) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 47 * hash + Objects.hashCode(this.score); hash = 47 * hash + Objects.hashCode(this.surname); return hash; } }
20.683333
59
0.538276
0299a4b367b0409cbd14405add6307fd46f81f02
538
package net.silve.smtpc.client; import net.silve.smtpc.message.SmtpSession; import net.silve.smtpc.listener.DefaultSmtpSessionListener; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class SmtpSessionTest { @Test void shouldHaveDefaultListener() { SmtpSession session = SmtpSession.newInstance("host", 25); session.setListener(null); assertNotNull(session.getListener()); assertTrue(session.getListener() instanceof DefaultSmtpSessionListener); } }
24.454545
80
0.743494
4f6ac83d3cf1f14dfe2f69f12f90fb247644e402
331
package com.ystu.repositories; import com.ystu.entities.User; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface UserRepository extends JpaRepository<User, Long> { List<User> findAllByLoginLike(String login); }
25.461538
67
0.818731
2d04963080a90623e13fd629157430d5e4653010
2,211
package gov.usds.case_issues.model; import java.time.ZonedDateTime; import java.util.Collection; import java.util.List; import java.util.Map; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import gov.usds.case_issues.db.model.CaseManagementSystem; import gov.usds.case_issues.db.model.CaseType; import gov.usds.case_issues.db.model.TroubleCase; import gov.usds.case_issues.db.model.projections.CaseIssueSummary; /** * API Model for the full details of a {@link TroubleCase}, including all issues (open and closed) * and all snoozes (active and past) and notes. */ public class CaseDetails implements PersistedCase { private TroubleCase rootCase; private Collection<? extends CaseIssueSummary> issues; private Collection<? extends CaseSnoozeSummaryFacade> snoozes; private List<AttachmentSummary> notes; public CaseDetails(TroubleCase rootCase, Collection<? extends CaseIssueSummary> issues, Collection<? extends CaseSnoozeSummaryFacade> snoozes, List<AttachmentSummary> notes) { super(); this.rootCase = rootCase; this.issues = issues; this.snoozes = snoozes; this.notes = notes; } public CaseManagementSystem getCaseManagementSystem() { return rootCase.getCaseManagementSystem(); } @Override public String getReceiptNumber() { return rootCase.getReceiptNumber(); } public CaseType getCaseType() { return rootCase.getCaseType(); } @Override public ZonedDateTime getCaseCreation() { return rootCase.getCaseCreation(); } @Override public Map<String, Object> getExtraData() { return rootCase.getExtraData(); } @Override public ZonedDateTime getCaseInitialUploadDate() { return ZonedDateTime.ofInstant(rootCase.getCreatedAt().toInstant(), GMT); } @Override public ZonedDateTime getCaseDataModifiedDate() { return ZonedDateTime.ofInstant(rootCase.getUpdatedAt().toInstant(), GMT); } @JsonSerialize(contentAs=CaseIssueSummary.class) public Collection<? extends CaseIssueSummary> getIssues() { return issues; } @JsonSerialize(contentAs=CaseSnoozeSummaryFacade.class) public Collection<? extends CaseSnoozeSummaryFacade> getSnoozes() { return snoozes; } public List<AttachmentSummary> getNotes() { return notes; } }
28.346154
98
0.779738
25249c349338354555d7cfc9438c7c44c5997fde
903
//- Copyright © 2008-2011 8th Light, Inc. All Rights Reserved. //- Limelight and all included source files are distributed under terms of the MIT License. package limelight.builtin; import limelight.Context; import java.net.URL; public class BuiltinBeacon { private static String builtinPath; public static String getBuiltinPath() { if(builtinPath == null) { final Class<BuiltinBeacon> klass = BuiltinBeacon.class; final String resourcePath = klass.getName().replace(".", "/") + ".class"; final URL resource = klass.getClassLoader().getResource(resourcePath); builtinPath = Context.fs().parentPath(resource.toString()); } return builtinPath; } public static String getBuiltinPlayersPath() { return getBuiltinPath() + "/players"; } public static String getBuiltinProductionsPath() { return getBuiltinPath() + "/productions"; } }
25.083333
91
0.704319
af54e3923442f88d739bef2108d498cd645380d9
3,288
/* * ****************************************************************************** * * Copyright 2015 See AUTHORS file. * * * * 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.uwsoft.editor.controller.commands; import com.badlogic.ashley.core.Entity; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Json; import com.commons.MsgAPI; import com.uwsoft.editor.Overlap2DFacade; import com.uwsoft.editor.renderer.data.CompositeVO; import com.uwsoft.editor.utils.runtime.EntityUtils; import com.uwsoft.editor.view.ui.FollowersUIMediator; import java.util.HashSet; import java.util.Set; /** * Created by azakhary on 4/28/2015. */ public class DeleteItemsCommand extends EntityModifyRevertableCommand { private String backup; private Array<Integer> entityIdsToDelete; private void backup() { Set<Entity> entitySet = new HashSet<>(); if(entityIdsToDelete == null) { entityIdsToDelete = new Array<>(); entitySet = sandbox.getSelector().getSelectedItems(); for(Entity entity: entitySet) { entityIdsToDelete.add(EntityUtils.getEntityId(entity)); } } else { for(Integer entityId: entityIdsToDelete) { entitySet.add(EntityUtils.getByUniqueId(entityId)); } } backup = CopyItemsCommand.getJsonStringFromEntities(entitySet); } @Override public void doAction() { backup(); FollowersUIMediator followersUIMediator = Overlap2DFacade.getInstance().retrieveMediator(FollowersUIMediator.NAME); for (Integer entityId : entityIdsToDelete) { Entity item = EntityUtils.getByUniqueId(entityId); followersUIMediator.removeFollower(item); sandbox.getEngine().removeEntity(item); } sandbox.getSelector().getCurrentSelection().clear(); facade.sendNotification(MsgAPI.DELETE_ITEMS_COMMAND_DONE); } @Override public void undoAction() { Json json = new Json(); CompositeVO compositeVO = json.fromJson(CompositeVO.class, backup); Set<Entity> newEntitiesList = PasteItemsCommand.createEntitiesFromVO(compositeVO); for (Entity entity : newEntitiesList) { Overlap2DFacade.getInstance().sendNotification(MsgAPI.NEW_ITEM_ADDED, entity); } sandbox.getSelector().setSelections(newEntitiesList, true); } public void setItemsToDelete(Set<Entity> entities) { entityIdsToDelete = new Array<>(); for(Entity entity: entities) { entityIdsToDelete.add(EntityUtils.getEntityId(entity)); } } }
34.978723
123
0.648418
c781ff07ee43043b9b431472988a0c5dcf9b39f3
11,655
package ru.bpmink.bpm.api.impl.simple; import com.google.common.base.Joiner; import com.google.common.collect.Maps; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import org.apache.http.client.HttpClient; import org.apache.http.protocol.HttpContext; import org.apache.http.util.Args; import ru.bpmink.bpm.api.client.TaskClient; import ru.bpmink.bpm.model.common.RestEntity; import ru.bpmink.bpm.model.common.RestRootEntity; import ru.bpmink.bpm.model.service.ServiceData; import ru.bpmink.bpm.model.task.TaskActions; import ru.bpmink.bpm.model.task.TaskClientSettings; import ru.bpmink.bpm.model.task.TaskDetails; import ru.bpmink.bpm.model.task.TaskPriority; import ru.bpmink.bpm.model.task.TaskStartData; import ru.bpmink.util.SafeUriBuilder; import javax.annotation.Nonnull; import javax.annotation.concurrent.Immutable; import java.net.URI; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; @Immutable final class TaskClientImpl extends BaseClient implements TaskClient { private final URI rootUri; private final HttpClient httpClient; private final HttpContext httpContext; //Request parameters constants private static final String ACTION = "action"; private static final String ACTIONS = "actions"; private static final String PARAMS = "params"; private static final String DUE_DATE = "dueDate"; private static final String PRIORITY = "priority"; private static final String RELATIVE_URL = "relativeURL"; private static final String SETTINGS_TYPE = "IBM_WLE_Coach"; private static final String TASK_ID_LIST = "taskIDs"; //Methods for tasks private static final String ACTION_ASSIGN = "assign"; private static final String ACTION_COMPLETE = "finish"; private static final String ACTION_CANCEL = "cancel"; private static final String ACTION_START = "start"; private static final String ACTION_UPDATE = "update"; private static final String ACTION_SETTINGS = "clientSettings"; private static final String ACTION_GET_DATA = "getData"; private static final String ACTION_SET_DATA = "setData"; //Assign constants private static final String ASSIGN_BACK = "back"; private static final String ASSIGN_TO_ME = "toMe"; private static final String ASSIGN_TO_USER = "toUser"; private static final String ASSIGN_TO_GROUP = "toGroup"; TaskClientImpl(URI rootUri, HttpClient httpClient, HttpContext httpContext) { this.httpClient = httpClient; this.rootUri = rootUri; this.httpContext = httpContext; } TaskClientImpl(URI rootUri, HttpClient httpClient) { this(rootUri, httpClient, null); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> getTask(@Nonnull String tkiid) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).build(); return makeGet(httpClient, httpContext, uri, new TypeToken<RestRootEntity<TaskDetails>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskStartData> startTask(@Nonnull String tkiid) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_START).build(); return makePost(httpClient, httpContext, uri, new TypeToken<RestRootEntity<TaskStartData>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> assignTaskToMe(@Nonnull String tkiid) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); Map<String, Object> query = Maps.newHashMap(); query.put(ASSIGN_TO_ME, true); return assignTask(tkiid, query); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> assignTaskBack(@Nonnull String tkiid) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); Map<String, Object> query = Maps.newHashMap(); query.put(ASSIGN_BACK, true); return assignTask(tkiid, query); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> assignTaskToUser(@Nonnull String tkiid, String userName) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); Map<String, Object> query = Maps.newHashMap(); if (userName != null) { query.put(ASSIGN_TO_USER, userName); } else { query.put(ASSIGN_BACK, true); } return assignTask(tkiid, query); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> assignTaskToGroup(@Nonnull String tkiid, String groupName) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); Map<String, Object> query = Maps.newHashMap(); if (groupName != null) { query.put(ASSIGN_TO_GROUP, groupName); } else { query.put(ASSIGN_BACK, true); } return assignTask(tkiid, query); } private RestRootEntity<TaskDetails> assignTask(String tkiid, Map<String, Object> query) { SafeUriBuilder uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_ASSIGN); if (query.entrySet().iterator().hasNext()) { Map.Entry<String, Object> entry = query.entrySet().iterator().next(); uri.addParameter(entry.getKey(), String.valueOf(entry.getValue())); } return makePost(httpClient, httpContext, uri.build(), new TypeToken<RestRootEntity<TaskDetails>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> completeTask(@Nonnull String tkiid, Map<String, Object> parameters) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); Gson gson = new GsonBuilder().setDateFormat(DATE_TIME_FORMAT).create(); SafeUriBuilder uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_COMPLETE); if (parameters != null && parameters.size() > 0) { uri.addParameter(PARAMS, gson.toJson(parameters)); } return makePost(httpClient, httpContext, uri.build(), new TypeToken<RestRootEntity<TaskDetails>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<RestEntity> cancelTask(@Nonnull String tkiid) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_CANCEL).build(); return makePost(httpClient, httpContext, uri, new TypeToken<RestRootEntity<RestEntity>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> updateTaskDueTime(@Nonnull String tkiid, @Nonnull Date dueTime) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); dueTime = Args.notNull(dueTime, "Task dueTime"); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_UPDATE) .addParameter(DUE_DATE, dueTime).build(); return makePost(httpClient, httpContext, uri, new TypeToken<RestRootEntity<TaskDetails>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskDetails> updateTaskPriority(@Nonnull String tkiid, @Nonnull TaskPriority priority) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); priority = Args.notNull(priority, "Task priority"); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_UPDATE) .addParameter(PRIORITY, priority).build(); return makePost(httpClient, httpContext, uri, new TypeToken<RestRootEntity<TaskDetails>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskClientSettings> getTaskClientSettings(@Nonnull String tkiid, @Nonnull Boolean isRelativeUrl) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); isRelativeUrl = Args.notNull(isRelativeUrl, "IsRelativeURL"); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).addPath(ACTION_SETTINGS).addPath(SETTINGS_TYPE) .addParameter(RELATIVE_URL, isRelativeUrl).build(); return makeGet(httpClient, httpContext, uri, new TypeToken<RestRootEntity<TaskClientSettings>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskActions> getAvailableActions(@Nonnull List<String> tkiids) { tkiids = Args.notNull(tkiids, "Task ids (tkiids)"); Args.check(!tkiids.isEmpty(), "At least one tkiid must be specified for available actions retrieving"); URI uri = new SafeUriBuilder(rootUri).addPath(ACTIONS) .addParameter(TASK_ID_LIST, Joiner.on(DEFAULT_SEPARATOR).join(tkiids)).build(); return makeGet(httpClient, httpContext, uri, new TypeToken<RestRootEntity<TaskActions>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<TaskActions> getAvailableActions(@Nonnull String tkiid) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); return getAvailableActions(Collections.singletonList(tkiid)); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<ServiceData> getTaskData(@Nonnull String tkiid, String... fields) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); SafeUriBuilder uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_GET_DATA); if (fields != null && fields.length > 0) { uri.addParameter("fields", Joiner.on(DEFAULT_SEPARATOR).join(fields)); } return makeGet(httpClient, httpContext, uri.build(), new TypeToken<RestRootEntity<ServiceData>>() {}); } /** * {@inheritDoc} * * @throws IllegalArgumentException {@inheritDoc} */ @Override public RestRootEntity<ServiceData> setTaskData(@Nonnull String tkiid, @Nonnull Map<String, Object> parameters) { tkiid = Args.notNull(tkiid, "Task id (tkiid)"); parameters = Args.notNull(parameters, "Variables (parameters)"); Args.notEmpty(parameters.keySet(), "Parameters names"); Args.notEmpty(parameters.values(), "Parameters values"); Gson gson = new GsonBuilder().setDateFormat(DATE_TIME_FORMAT).create(); String params = gson.toJson(parameters); URI uri = new SafeUriBuilder(rootUri).addPath(tkiid).addParameter(ACTION, ACTION_SET_DATA) .addParameter(PARAMS, params).build(); return makePost(httpClient, httpContext, uri, new TypeToken<RestRootEntity<ServiceData>>() {}); } }
33.110795
116
0.666924
446340bf9a078a299f9709f1389c651528b5c908
6,014
package net.minecraft.network.play.server; import com.google.common.base.Objects; import com.google.common.collect.Lists; import com.mojang.authlib.GameProfile; import com.mojang.authlib.properties.Property; import java.io.IOException; import java.util.List; import net.aXg; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.Packet; import net.minecraft.network.PacketBuffer; import net.minecraft.network.play.INetHandlerPlayClient; import net.minecraft.network.play.server.S38PacketPlayerListItem$1; import net.minecraft.network.play.server.S38PacketPlayerListItem$Action; import net.minecraft.util.IChatComponent; import net.minecraft.world.WorldSettings$GameType; public class S38PacketPlayerListItem implements Packet { private S38PacketPlayerListItem$Action action; private final List players = Lists.newArrayList(); public S38PacketPlayerListItem() { } public S38PacketPlayerListItem(S38PacketPlayerListItem$Action var1, EntityPlayerMP... var2) { this.action = var1; for(EntityPlayerMP var6 : var2) { this.players.add(new aXg(this, var6.getGameProfile(), var6.ping, var6.theItemInWorldManager.getGameType(), var6.getTabListDisplayName())); } } public S38PacketPlayerListItem(S38PacketPlayerListItem$Action var1, Iterable var2) { this.action = var1; for(EntityPlayerMP var4 : var2) { this.players.add(new aXg(this, var4.getGameProfile(), var4.ping, var4.theItemInWorldManager.getGameType(), var4.getTabListDisplayName())); } } public void readPacketData(PacketBuffer var1) throws IOException { this.action = (S38PacketPlayerListItem$Action)var1.readEnumValue(S38PacketPlayerListItem$Action.class); int var2 = var1.readVarIntFromBuffer(); for(int var3 = 0; var3 < var2; ++var3) { GameProfile var4 = null; int var5 = 0; WorldSettings$GameType var6 = null; IChatComponent var7 = null; switch(S38PacketPlayerListItem$1.$SwitchMap$net$minecraft$network$play$server$S38PacketPlayerListItem$Action[this.action.ordinal()]) { case 1: var4 = new GameProfile(var1.readUuid(), var1.a(16)); int var8 = var1.readVarIntFromBuffer(); int var9 = 0; for(; var9 < var8; ++var9) { String var10 = var1.a(32767); String var11 = var1.a(32767); if(var1.readBoolean()) { var4.getProperties().put(var10, new Property(var10, var11, var1.a(32767))); } else { var4.getProperties().put(var10, new Property(var10, var11)); } } var6 = WorldSettings$GameType.getByID(var1.readVarIntFromBuffer()); var5 = var1.readVarIntFromBuffer(); if(var1.readBoolean()) { var7 = var1.readChatComponent(); } break; case 2: var4 = new GameProfile(var1.readUuid(), (String)null); var6 = WorldSettings$GameType.getByID(var1.readVarIntFromBuffer()); break; case 3: var4 = new GameProfile(var1.readUuid(), (String)null); var5 = var1.readVarIntFromBuffer(); break; case 4: var4 = new GameProfile(var1.readUuid(), (String)null); if(var1.readBoolean()) { var7 = var1.readChatComponent(); } break; case 5: var4 = new GameProfile(var1.readUuid(), (String)null); } this.players.add(new aXg(this, var4, var5, var6, var7)); } } public void writePacketData(PacketBuffer var1) throws IOException { var1.writeEnumValue(this.action); var1.writeVarIntToBuffer(this.players.size()); for(aXg var3 : this.players) { switch(S38PacketPlayerListItem$1.$SwitchMap$net$minecraft$network$play$server$S38PacketPlayerListItem$Action[this.action.ordinal()]) { case 1: var1.writeUuid(var3.a().getId()); var1.writeString(var3.a().getName()); var1.writeVarIntToBuffer(var3.a().getProperties().size()); for(Property var5 : var3.a().getProperties().values()) { var1.writeString(var5.getName()); var1.writeString(var5.getValue()); if(var5.hasSignature()) { var1.writeBoolean(true); var1.writeString(var5.getSignature()); } else { var1.writeBoolean(false); } } var1.writeVarIntToBuffer(var3.d().getID()); var1.writeVarIntToBuffer(var3.c()); if(var3.b() == null) { var1.writeBoolean(false); } else { var1.writeBoolean(true); var1.writeChatComponent(var3.b()); } break; case 2: var1.writeUuid(var3.a().getId()); var1.writeVarIntToBuffer(var3.d().getID()); break; case 3: var1.writeUuid(var3.a().getId()); var1.writeVarIntToBuffer(var3.c()); break; case 4: var1.writeUuid(var3.a().getId()); if(var3.b() == null) { var1.writeBoolean(false); } else { var1.writeBoolean(true); var1.writeChatComponent(var3.b()); } break; case 5: var1.writeUuid(var3.a().getId()); } } } public void processPacket(INetHandlerPlayClient var1) { var1.handlePlayerListItem(this); } public List playersDataList() { return this.players; } public S38PacketPlayerListItem$Action getAction() { return this.action; } public String toString() { return Objects.toStringHelper(this).add("action", this.action).add("entries", this.players).toString(); } private static IOException a(IOException var0) { return var0; } }
34.763006
147
0.606086
ac90ddcc74116a4925d79e2cc91a802334133424
847
package com.webcheckers.model; import com.webcheckers.model.pieces.RedSinglePiece; import com.webcheckers.model.pieces.WhiteSinglePiece; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class PieceTest { /** * Test for opposite method */ @Test void testOpposite(){ Piece.PieceColor CuT = Piece.PieceColor.RED; assertEquals(Piece.PieceColor.WHITE, CuT.opposite()); Piece.PieceColor CuT2 = Piece.PieceColor.WHITE; assertEquals(Piece.PieceColor.RED, CuT2.opposite()); } /** * Test for toString method of PieceType */ @Test void testToString(){ Piece.PieceType CuT = Piece.PieceType.KING; assertEquals("KING", CuT.toString()); } }
24.911765
61
0.688312
ac6f851397d61174eecf11d17b0659d15dcdd47b
1,259
package com.nsskumar.cf.service.pagerdutycfservicepoc.controller; import java.io.IOException; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.squareup.pagerduty.incidents.NotifyResult; import com.squareup.pagerduty.incidents.PagerDuty; import com.squareup.pagerduty.incidents.Trigger; @RestController public class EventController { @Value("vcap.services.PagerDutyService.credentials.integration_key") public static String apiKey; @RequestMapping(value = "/event", method = RequestMethod.POST) public String createEvent(@RequestBody String message) { PagerDuty pagerDuty = PagerDuty.create(apiKey); Trigger trigger = new Trigger.Builder(message).build(); NotifyResult result = null; try { result = pagerDuty.notify(trigger); } catch (IOException e) { System.err.println("There was a problem while sending the event to PagerDuty. Event message is: " + message ); e.printStackTrace(); return "Status: Failed to send event"; } return result.message(); } }
35.971429
113
0.792693
f799969ba796b93c0b02e5766e29c958da8fe3bc
1,795
package com.j6crypto.logic.stop; import com.j6crypto.logic.StopTradeLogic; import com.j6crypto.logic.TradeLogic; import com.j6crypto.logic.entity.state.AutoTradeOrder; import com.j6crypto.service.CandlestickManager; import com.j6crypto.to.setup.ProfitPercentageTpSetup; import com.j6crypto.to.TimeData; import com.j6crypto.to.Trade; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.math.BigDecimal; import java.math.RoundingMode; import java.time.LocalDateTime; import java.util.function.Supplier; import static com.j6crypto.to.Trade.LongShort.LONG; import static com.j6crypto.to.Trade.LongShort.SHORT; /** * @author <a href="mailto:laiseong@gmail.com">Jimmy Au</a> */ public class ProfitPercentageTp extends StopTradeLogic<ProfitPercentageTpSetup> { private static Logger logger = LoggerFactory.getLogger(ProfitPercentageTp.class); public ProfitPercentageTp(AutoTradeOrder autoTradeOrder, ProfitPercentageTpSetup state, Supplier<LocalDateTime> currentDateTimeSupplier, CandlestickManager candlestickManager) { super(autoTradeOrder, state, currentDateTimeSupplier, candlestickManager); } @Override public Trade.LongShort runLogic(TimeData timeData) { //TODO cater for long short BigDecimal percentageBaseCost = getAutoTradeOrder().getTotalCost(); BigDecimal profitPerc = getCurrentPrice().multiply(getAutoTradeOrder().getPositionQty()) .subtract(percentageBaseCost).movePointRight(2).divide(percentageBaseCost, 2, RoundingMode.HALF_UP); logger.debug("Monitor profit profitPerc={} ", profitPerc); if (profitPerc.compareTo(getTradeLogicState().getProfitPercentageTp()) >= 0) { logger.info("TP profit profitPerc={} ", profitPerc); return Trade.LongShort.LONG; } return null; } }
38.191489
138
0.77883
39cc5debc685b9d9c20a970337c1075279a9e491
699
package net.gnu.agrep; public class CheckedString implements Comparable<CheckedString> { boolean checked; String string; public CheckedString(String _s) { this(true, _s); } public CheckedString(boolean _c, String _s) { checked = _c; string = _s; } public String toString() { return (checked ? string : ""); //"true": "false") + "|" + string; } @Override public int compareTo(CheckedString p1) { return string.compareToIgnoreCase(p1.string); } @Override public boolean equals(Object o) { if (o instanceof CheckedString) { return string.equalsIgnoreCase(((CheckedString)o).string); } else { return false; } } }
20.558824
74
0.640916
8bfa839309412c01f8aa74f616b51c98d98a8d18
3,230
package com.feihua.framework.rest.interceptor; import com.feihua.framework.base.modules.user.api.ApiBaseUserAccessLasttimePoService; import com.feihua.framework.base.modules.user.dto.BaseUserAccessLasttimeParamDto; import com.feihua.framework.shiro.pojo.ShiroUser; import com.feihua.framework.shiro.utils.ShiroUtils; import feihua.jdbc.api.utils.OrderbyUtils; import feihua.jdbc.api.utils.PageUtils; import org.apache.commons.lang3.StringUtils; import org.apache.shiro.SecurityUtils; import org.apache.shiro.session.Session; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Date; /** * 用户访问记录 * Created by yw on 2016/1/25. */ public class UserAccessInterceptor extends HandlerInterceptorAdapter { @Autowired private ApiBaseUserAccessLasttimePoService apiBaseUserAccessLasttimePoService; /** * This implementation always returns {@code true}. * * @param request * @param response * @param handler */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { Session session = SecurityUtils.getSubject().getSession(); Long accessDataTime = (Long) session.getAttribute("accessDataTime"); if (accessDataTime == null) { session.setAttribute("accessDataTime",System.currentTimeMillis()); } accessDataTime = (Long) session.getAttribute("accessDataTime"); // 每40秒记录一次 if (System.currentTimeMillis() - accessDataTime > 400000) { ShiroUser su = ShiroUtils.getCurrentUser(); if (su != null && StringUtils.isNotEmpty(su.getLoginClientId())) { BaseUserAccessLasttimeParamDto baseUserAccessLasttimeParamDto = new BaseUserAccessLasttimeParamDto(); baseUserAccessLasttimeParamDto.setUserId(su.getId()); baseUserAccessLasttimeParamDto.setUserNickname(su.getNickname()); baseUserAccessLasttimeParamDto.setClientId(su.getLoginClientId()); baseUserAccessLasttimeParamDto.setClientName(su.getLoginClientName()); baseUserAccessLasttimeParamDto.setAccessIp(session.getHost()); baseUserAccessLasttimeParamDto.setAccessLasttime(new Date()); baseUserAccessLasttimeParamDto.setCurrentUserId(su.getId()); // 防止请求太快有重复提交,数据已加了唯一索引,如果有重复数据会有异常,这里拦截一下 // 不过上面已经加了40s才记录一次,不会有这种情况出现,以防万一 try { apiBaseUserAccessLasttimePoService.saveUserAccessLasttime(baseUserAccessLasttimeParamDto); session.setAttribute("accessDataTime",System.currentTimeMillis()); }catch (Exception e){ } } } return super.preHandle(request, response, handler); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { super.afterCompletion(request, response, handler, ex); } }
41.948052
138
0.714861
6afdf3ba821541ccec353ffee9f17f2d2f8418b1
6,317
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright (c) 2013, 6WIND S.A. All rights reserved. * * * * This file is part of the Jenkins Lockable Resources Plugin and is * * published under the MIT license. * * * * See the "LICENSE.txt" file for more information. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package org.jenkins.plugins.lockableresources.queue; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; import java.util.function.Predicate; import hudson.model.StringParameterValue; import org.jenkins.plugins.lockableresources.LockableResource; import org.jenkins.plugins.lockableresources.LockableResourcesManager; import org.jenkins.plugins.lockableresources.RequiredResourcesProperty; import org.jenkins.plugins.lockableresources.actions.AdsShapesVariableNameAction; import org.jenkins.plugins.lockableresources.actions.AvailabilityDomainVariableNameAction; import org.jenkins.plugins.lockableresources.actions.EndpointVariableNameAction; import org.jenkins.plugins.lockableresources.actions.RegionVariableNameAction; import org.jenkins.plugins.lockableresources.actions.ShapeVariableNameAction; import hudson.EnvVars; import hudson.matrix.MatrixConfiguration; import hudson.model.Job; import hudson.model.Queue; import hudson.model.Run; public final class Utils { private final static String DBSYSTEM = "DBSYSTEM_"; private final static String COMPUTE = "COMPUTE_"; private Utils() { } public static Job<?, ?> getProject(Queue.Item item) { if (item.task instanceof Job) return (Job<?, ?>) item.task; return null; } public static Job<?, ?> getProject(Run<?, ?> build) { Object p = build.getParent(); return (Job<?, ?>) p; } public static LockableResourcesStruct requiredResources(Job<?, ?> project) { EnvVars env = new EnvVars(); if (project instanceof MatrixConfiguration) { env.putAll(((MatrixConfiguration) project).getCombination()); project = (Job<?, ?>) project.getParent(); } RequiredResourcesProperty property = project.getProperty(RequiredResourcesProperty.class); if (property != null) return new LockableResourcesStruct(property, env); return null; } public static int countResourcesPerAvailabilityDomain(String availabilityDomain) { if (availabilityDomain == null) { return 0; } return (int) LockableResourcesManager.get().getResources().stream() .filter(r -> r.getAvailabilityDomain().equals(availabilityDomain)).count(); } public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } public static boolean isBroadLabel(String label) { return !label.contains("_ad"); } public static void addCustomBuildVariables(Run<?, ?> build, LockableResourcesStruct resources, Set<LockableResource> required) { if (resources.requiredNumber != null && Integer.parseInt(resources.requiredNumber) > 1 || required.size() > 1) { StringBuilder sb = new StringBuilder(); for (LockableResource r : required) { sb.append(r.getAvailabilityDomainOCI() + "," + r.getShape() + ";"); } sb.deleteCharAt(sb.lastIndexOf(";")); build.addAction(new AdsShapesVariableNameAction(new StringParameterValue(AdsShapesVariableNameAction.NAME, sb.toString()))); // export variables when all locked resources match the same one exportVariablesIfSamePropertyForAllRequiredResources(build, required, required.iterator().next()); } else { LockableResource firstOne = required.iterator().next(); build.addAction(new AvailabilityDomainVariableNameAction(new StringParameterValue(resolveParameterName(firstOne.getName(), AvailabilityDomainVariableNameAction.NAME), firstOne.getAvailabilityDomainOCI()))); build.addAction(new ShapeVariableNameAction(new StringParameterValue(resolveParameterName(firstOne.getName(), ShapeVariableNameAction.NAME), firstOne.getShape()))); build.addAction(new RegionVariableNameAction(new StringParameterValue(resolveParameterName(firstOne.getName(), RegionVariableNameAction.NAME), firstOne.getRegion()))); exportEndpoint(build, firstOne); } } private static void exportEndpoint (Run<?, ?> build, LockableResource resource) { // do not export endpoint if resource is a compute if (!isCompute(resource.getName())) { build.addAction(new EndpointVariableNameAction(new StringParameterValue(resolveParameterName(resource.getName(), EndpointVariableNameAction.NAME), resource.getEndpoint()))); } } private static String resolveParameterName (String resourceName, String propertyName) { if (isCompute(resourceName)) { return COMPUTE.concat(propertyName); } return DBSYSTEM.concat(propertyName); } private static boolean isCompute (String name) { return name.contains("compute"); } private static void exportVariablesIfSamePropertyForAllRequiredResources (Run<?, ?> build, Set<LockableResource> resources, LockableResource firstOne) { if (resources.stream().allMatch(r -> r.getShape().equals(firstOne.getShape()))) { build.addAction(new ShapeVariableNameAction(new StringParameterValue(resolveParameterName(firstOne.getName(), ShapeVariableNameAction.NAME), firstOne.getShape()))); } if (resources.stream().allMatch(r -> r.getAvailabilityDomainOCI().equals(firstOne.getAvailabilityDomainOCI()))) { build.addAction(new AvailabilityDomainVariableNameAction(new StringParameterValue(resolveParameterName(firstOne.getName(), AvailabilityDomainVariableNameAction.NAME), firstOne.getAvailabilityDomainOCI()))); } if (resources.stream().allMatch(r -> r.getRegion().equals(firstOne.getRegion()))) { build.addAction(new RegionVariableNameAction(new StringParameterValue(resolveParameterName(firstOne.getName(), RegionVariableNameAction.NAME), firstOne.getRegion()))); } if (resources.stream().allMatch(r -> r.getEndpoint().equals(firstOne.getEndpoint()))) { exportEndpoint(build, firstOne); } } }
42.682432
209
0.727877
5ecc1277d89e28477a6759e0ca1ff4e6e5fdbfe5
1,795
package romanNumerals; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JTextField; /** * Listener for the Convert roman to integer button * Takes the source text field and the target result text field * in the constructor. * @author erno */ public class ConvertRomanButtonListener implements ActionListener { // Class constants public static final String TXT_VALUE_NOT_ROMAN = "Not a valid Roman numeral"; // This target component will be updated with the result private JTextField resultTextField; // This source component is used to get the Roman numeral private JTextField valueTextField; /** * Construct the listener * @param resultTarget component which will be updated * @param valueSource component which contains the Roman numeral * to be converted */ public ConvertRomanButtonListener(JTextField resultTarget, JTextField valueSource) { valueTextField = valueSource; resultTextField = resultTarget; } /** * Perform the Roman numeral to integer conversion * @param e event to be handled, not used */ @Override public void actionPerformed(ActionEvent e) { System.out.println("ConvertIntegerButtonListener::actionPerformed invoked"); try { int result = RomanNumeralParser.parseRoman( valueTextField.getText()); String resultString = Integer.toString(result); System.out.printf(" Roman \"%s\" is %s%n", valueTextField.getText(), resultString); resultTextField.setText(resultString); } catch(IllegalArgumentException exception) { String failureText = String.format( " Tried to convert \"%s\" which is not a Roman numeral", valueTextField.getText()); System.out.println(failureText); resultTextField.setText(TXT_VALUE_NOT_ROMAN); } } }
30.423729
83
0.745961
7f708c632c3aaf1c30da28cac06943fda426880b
3,623
/* * Copyright (c) 2010 WiYun Inc. * Author: luma(stubma@gmail.com) * * For all entities this program is free software; you can redistribute * it and/or modify it under the terms of the 'WiEngine' license with * the additional provision that 'WiEngine' must be credited in a manner * that can be be observed by end users, for example, in the credits or during * start up. (please find WiEngine logo in sdk's logo folder) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.wiyun.engine.particle; import com.wiyun.engine.nodes.Director; import com.wiyun.engine.opengl.Texture2D; /** * 用于载入HGE(HAFF'S GAME ENGINE)的粒子系统描述文件 */ public class HGEParticleLoader { /** * 从一个HGE描述文件中载入粒子效果 * * @param resId .psi描述文件的资源id * @param particleCount 指定粒子系统的粒子数量 * @param tex 指定粒子系统的粒子贴图 * * @return {@link QuadParticleSystem} */ public static QuadParticleSystem load(int resId, int particleCount, Texture2D tex) { return QuadParticleSystem.from(nativeLoad(resId, particleCount, tex)); } /** * 从一个Particle Designer描述文件中载入粒子效果 * * @param path 粒子效果描述文件相对于assets的相对路径 * @param particleCount 指定粒子系统的粒子数量 * @param tex 指定粒子系统的粒子贴图 * @return {@link QuadParticleSystem} */ public static QuadParticleSystem load(String path, int particleCount, Texture2D tex) { return load(path, particleCount, tex, false); } /** * 从一个Particle Designer描述文件中载入粒子效果 * * @param path 粒子效果描述文件相对于assets的相对路径或者在文件系统中的路径 * @param particleCount 指定粒子系统的粒子数量 * @param tex 指定粒子系统的粒子贴图 * @param isFile true表示path是文件系统的路径, false表示是assets下的路径 * @return {@link QuadParticleSystem} */ public static QuadParticleSystem load(String path, int particleCount, Texture2D tex, boolean isFile) { return load(path, particleCount, tex, isFile, Director.getDefaultInDensity()); } /** * 从一个Particle Designer描述文件中载入粒子效果 * * @param path 粒子效果描述文件相对于assets的相对路径或者在文件系统中的路径 * @param particleCount 指定粒子系统的粒子数量 * @param tex 指定粒子系统的粒子贴图 * @param isFile true表示path是文件系统的路径, false表示是assets下的路径 * @param inDensity 密度, 缺省为0, 表示使用系统缺省的输入密度 * @return {@link QuadParticleSystem} */ public static QuadParticleSystem load(String path, int particleCount, Texture2D tex, boolean isFile, float inDensity) { return QuadParticleSystem.from(nativeLoad(path, particleCount, tex, isFile, inDensity)); } private native static int nativeLoad(int resId, int particleCount, Texture2D tex); private native static int nativeLoad(String path, int particleCount, Texture2D tex, boolean isFile, float inDensity); }
39.380435
121
0.743583
1a5f598221ce84cc2ff1b63b7b2db2922c8fb615
7,240
/* * This file is part of LanternServer, licensed under the MIT License (MIT). * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.lanternpowered.server.item.predicate; import static com.google.common.base.Preconditions.checkNotNull; import org.lanternpowered.server.inventory.LanternItemStackSnapshot; import org.spongepowered.api.item.ItemType; import org.spongepowered.api.item.inventory.ItemStack; import org.spongepowered.api.item.inventory.ItemStackSnapshot; import java.util.function.Predicate; /** * Represents a predicate for {@link ItemType}s, {@link ItemStack}s and {@link ItemStackSnapshot}s. */ public interface ItemPredicate { /** * Tests whether the provided {@link ItemStack} is valid. * * @param stack The item stack * @return Whether the stack is valid */ boolean test(ItemStack stack); /** * Tests whether the provided {@link ItemType} is valid. * * @param type The item type * @return Whether the type is valid */ boolean test(ItemType type); /** * Tests whether the provided {@link ItemStackSnapshot} is valid. * * @param stack The item stack snapshot * @return Whether the stack is valid */ boolean test(ItemStackSnapshot stack); /** * Gets this {@link ItemPredicate} as a {@link ItemStack} {@link Predicate}. * * @return The predicate */ default Predicate<ItemStack> asStackPredicate() { return this::test; } /** * Gets this {@link ItemPredicate} as a {@link ItemStackSnapshot} {@link Predicate}. * * @return The predicate */ default Predicate<ItemStackSnapshot> asSnapshotPredicate() { return this::test; } /** * Gets this {@link ItemPredicate} as a {@link ItemType} {@link Predicate}. * * @return The predicate */ default Predicate<ItemType> asTypePredicate() { return this::test; } /** * Combines this {@link ItemPredicate} with the other one. Both * {@link ItemPredicate}s must succeed in order to get {@code true} * as a result. * * @param itemPredicate The item predicate * @return The combined item predicate */ default ItemPredicate andThen(ItemPredicate itemPredicate) { final ItemPredicate thisPredicate = this; return new ItemPredicate() { @Override public boolean test(ItemStack stack) { return thisPredicate.test(stack) && itemPredicate.test(stack); } @Override public boolean test(ItemType type) { return thisPredicate.test(type) && itemPredicate.test(type); } @Override public boolean test(ItemStackSnapshot stack) { return thisPredicate.test(stack) && itemPredicate.test(stack); } }; } /** * Inverts this {@link ItemPredicate} as a new {@link ItemPredicate}. * * @return The inverted item filter */ default ItemPredicate invert() { final ItemPredicate thisPredicate = this; return new ItemPredicate() { @Override public boolean test(ItemStack stack) { return !thisPredicate.test(stack); } @Override public boolean test(ItemType type) { return !thisPredicate.test(type); } @Override public boolean test(ItemStackSnapshot stack) { return !thisPredicate.test(stack); } }; } /** * Constructs a {@link ItemPredicate} for the provided * {@link ItemStack} predicate. * * @param predicate The predicate * @return The item filter */ static ItemPredicate ofStackPredicate(Predicate<ItemStack> predicate) { checkNotNull(predicate, "predicate"); return new ItemPredicate() { @Override public boolean test(ItemStack stack) { return predicate.test(stack); } @Override public boolean test(ItemType type) { return predicate.test(ItemStack.of(type, 1)); } @Override public boolean test(ItemStackSnapshot stack) { return predicate.test(stack.createStack()); } }; } /** * Constructs a {@link ItemPredicate} for the provided * {@link ItemStackSnapshot} predicate. * * @param predicate The predicate * @return The item filter */ static ItemPredicate ofSnapshotPredicate(Predicate<ItemStackSnapshot> predicate) { checkNotNull(predicate, "predicate"); return new ItemPredicate() { @Override public boolean test(ItemStack stack) { return predicate.test(LanternItemStackSnapshot.wrap(stack)); } @Override public boolean test(ItemType type) { return predicate.test(LanternItemStackSnapshot.wrap(ItemStack.of(type, 1))); } @Override public boolean test(ItemStackSnapshot stack) { return predicate.test(stack); } }; } /** * Constructs a {@link ItemPredicate} for the provided * {@link ItemType} predicate. * * @param predicate The predicate * @return The item filter */ static ItemPredicate ofTypePredicate(Predicate<ItemType> predicate) { checkNotNull(predicate, "predicate"); return new ItemPredicate() { @Override public boolean test(ItemStack stack) { return predicate.test(stack.getType()); } @Override public boolean test(ItemType type) { return predicate.test(type); } @Override public boolean test(ItemStackSnapshot stack) { return predicate.test(stack.getType()); } }; } }
31.894273
99
0.620856
2fd05798294be9eeb32f36bf9e0fcedd03b15525
609
package org.hexpresso.soulevspy.fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import org.hexpresso.soulevspy.R; /** * Created by Pierre-Etienne Messier <pierre.etienne.messier@gmail.com> on 2015-10-02. */ public class DashboardFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_dashboard, container, false); } }
29
103
0.755337
46b2d2c4fae8d180815e370b0ae9925bab7be6c4
337
package com.flyingfish.repository; import com.flyingfish.infrastructure.authentication.Client; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface ClientRepository extends CrudRepository<Client, Long> { Client findByClientId(String clientId); }
30.636364
72
0.845697
efdea4d5e907a21f19d1e5d1fc6e88ad5afd0133
915
public interface IEventService{ public Set<Event> findEventsWhereUserIsGoing(User user); public Set<Event> findEventsWhereUserIsMaybeGoing(User user); public Set<Event> findCommonEvents(User user1, User user2); public Set<Event> findCommonUsers(Event event1, Event event2); public Set<Event> findEventsNear(User user); public Set<Event> findEventsNear(double latitude, double longitude); public Set<Event> findEventsBy(City city); public Set<Event> findEventsBy(Country country); public Set<Event> findEventsByCategory(Category category); public Set<Event> findEventsByTag(Tag tag); public void addUserToEventAsGoing(User user1, Event event); public void addUserToEventAsMayve(User user1, Event event); public void removeUserFromEvent(User user1, Event event); //Recommendation public Set<Event> findSimilarEvents(Event event); public Set<Event> findRecommendedEventsForUser(User user); }
35.192308
69
0.801093
187511d4c6d16f9a3e608925bb4860f71cd1675d
507
package com.pogeyan.cmis.api; public enum CustomTypeId { CMIS_EXT_RELATIONMD("cmis_ext:relationmd"), CMIS_EXT_RELATIONSHIP("cmis_ext:relationship"), CMIS_EXT_CONFIG("cmis_ext:config"); private final String value; CustomTypeId(String v) { value = v; } public String value() { return value; } public static CustomTypeId fromValue(String v) { for (CustomTypeId c : CustomTypeId.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
16.9
49
0.706114
1d7cadcd7c558e3a27fbb8138054099f1e2872a3
1,285
package br.com.jadson.domain; import br.com.jadson.mocks.CustomContaJDBCRepositoryMock; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; class ContaTestJunit { @Test void testaContaComSaldo(){ Conta conta = new Conta(10.0d); Assertions.assertTrue(conta.temSaldo()); } @Test void testaContaSemSaldo(){ Conta conta = new Conta(0.0d); Assertions.assertFalse(conta.temSaldo()); } @Test void testaContaComSaldoNulo(){ Assertions.assertThrows(IllegalArgumentException.class, () -> new Conta(null).temSaldo()); } @Test void testaSacarValorNegativo1(){ Assertions.assertThrows(IllegalArgumentException.class, () -> new Conta(100.0).sacar(-10.0)); } @Test void testaSacarValorNegativo(){ Exception ex = Assertions.assertThrows(IllegalArgumentException.class, () -> new Conta(100.0).sacar(-10.0)); Assertions.assertEquals("Não pode sacar um valor negativo.", ex.getMessage()); } @Test void testaSacarContaComSaldo(){ Conta conta = new Conta(100.0); conta.setRepository(new CustomContaJDBCRepositoryMock()); Assertions.assertEquals(80.0d, conta.sacar(20.0)); } }
24.711538
98
0.65214
a03f6c9c3f1f00881f3690dfeb9b74d9539caee0
70
package com.interviewBitScaler; public class Lecture9_Searchin_2 { }
14
34
0.828571
e6e04f774fe93204ee46c0ae1e900a31d627ec26
885
package com.waspring.framework.antenna.core.visitor; import com.waspring.framework.antenna.core.util.ExceptionUtil; import com.waspring.framework.antenna.core.util.ResponseCode; /** * 异常返回定义 * * @author felly * */ public class ExceptionResponse extends SimpleResponse { public ExceptionResponse(String message, Exception e) { setMessage(message); setCode(ResponseCode.EXCEPTION.getCode()); if(isdebug) { setData(e); } } public ExceptionResponse(int code, String message, Exception e) { setMessage(message); setCode(code); if(isdebug) { setData(e); } } public ExceptionResponse(Exception e) { this(ExceptionUtil.parseException(e).getMessage(), e); } private boolean isdebug=false; public ExceptionResponse(Exception e,boolean isdebug) { this(ExceptionUtil.parseException(e).getMessage(), e); this.isdebug=isdebug; } }
18.829787
66
0.724294
76c5c5473cbba08afe4784ec01e30edafbcbd0b9
1,670
/* * Copyright 2014 Black Pepper Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.blackpepper.support.logback.test; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.junit.rules.ExternalResource; import org.slf4j.LoggerFactory; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; public class LogbackRule extends ExternalResource { private Map<Class<?>, Level> oldLevelsByClass; @Override protected void before() { oldLevelsByClass = new HashMap<>(); } @Override protected void after() { resetLoggerLevels(); oldLevelsByClass = null; } public void off(Class<?> loggerClass) { Logger logger = getLogger(loggerClass); oldLevelsByClass.put(loggerClass, logger.getLevel()); logger.setLevel(Level.OFF); } private void resetLoggerLevels() { for (Entry<Class<?>, Level> entry : oldLevelsByClass.entrySet()) { Class<?> clazz = entry.getKey(); Level level = entry.getValue(); getLogger(clazz).setLevel(level); } } private static Logger getLogger(Class<?> clazz) { return (Logger) LoggerFactory.getLogger(clazz); } }
25.692308
75
0.729341
d586212f63f3ac49ce4274e8ac0e506ac9ede9bb
1,576
/* List of depths: Given a binary tree, design an algo which creates a linked list of all the nodes at each depth(eg: if you have a tree with depth D, then there will be D lists) */ package BinarySearchTree; import java.util.*; import java.lang.*; class ListOfDepths<T extends Comparable<T>>{ public void createLists(Node<T> node,ArrayList<LinkedList<Node<T>>> lists, int level){ if(node==null) return; LinkedList<Node<T>> list = null; if(lists.size()==level){ list = new LinkedList<Node<T>>(); lists.add(list); } else list = lists.get(level); list.add(node); createLists(node.left, lists, level+1); createLists(node.right, lists, level+1); } public static void main(String[] args){ BinarySearchTree<Integer> bst = new BinarySearchTree<Integer>(); bst.add(10); bst.add(15); bst.add(13); bst.add(17); bst.add(20); bst.add(12); Node<Integer> root = bst.getRootNode(); ArrayList<LinkedList<Node<Integer>>> lists = new ArrayList<LinkedList<Node<Integer>>>(); ListOfDepths<Integer> lod = new ListOfDepths<Integer>(); lod.createLists(root, lists, 0); int index = 0; for(LinkedList<Node<Integer>> l:lists){ System.out.print("level " + index++ + " : "); for(Node<Integer> n:l){ System.out.print(n.data + " "); } System.out.println(); } } }
29.735849
100
0.557741
f0bc267230d05ffbffdb232715aeec219a468322
850
package com.example.schedulegenerator.UserRecycler; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.constraintlayout.widget.ConstraintLayout; import androidx.recyclerview.widget.RecyclerView; import com.example.schedulegenerator.R; public class UserViewHolder extends RecyclerView.ViewHolder { public TextView name; public ImageView userImg; private ConstraintLayout layout; public UserViewHolder(@NonNull View itemView) { super(itemView); name = itemView.findViewById(R.id.theUserName); userImg = itemView.findViewById(R.id.userImgView); layout = itemView.findViewById(R.id.user_viewLayout); } public ConstraintLayout getLayout() { return layout; } }
29.310345
61
0.763529
388a8052706809362d2a8e2e9bd0e5c44ff3f45e
4,419
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.fineract.infrastructure.dataexport.data; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.apache.fineract.infrastructure.core.api.JsonCommand; import org.apache.fineract.infrastructure.core.data.ApiParameterError; import org.apache.fineract.infrastructure.core.data.DataValidatorBuilder; import org.apache.fineract.infrastructure.core.exception.InvalidJsonException; import org.apache.fineract.infrastructure.core.exception.PlatformApiDataValidationException; import org.apache.fineract.infrastructure.core.serialization.FromJsonHelper; import org.apache.fineract.infrastructure.dataexport.api.DataExportApiConstants; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.google.gson.JsonElement; import com.google.gson.reflect.TypeToken; @Component public class ExportDataValidator { private final FromJsonHelper fromJsonHelper; @Autowired public ExportDataValidator(final FromJsonHelper fromJsonHelper) { this.fromJsonHelper = fromJsonHelper; } /** * validate the request to create a new data export tool * * @param jsonCommand -- the JSON command object (instance of the JsonCommand class) * @return None **/ public void validateCreateDataExportRequest(final JsonCommand jsonCommand) { final String jsonString = jsonCommand.json(); final JsonElement jsonElement = jsonCommand.parsedJson(); if (StringUtils.isBlank(jsonString)) { throw new InvalidJsonException(); } final Type typeToken = new TypeToken<Map<String, Object>>() {}.getType(); this.fromJsonHelper.checkForUnsupportedParameters(typeToken, jsonString, DataExportApiConstants.CREATE_DATA_EXPORT_REQUEST_PARAMETERS); final List<ApiParameterError> dataValidationErrors = new ArrayList<>(); final DataValidatorBuilder dataValidatorBuilder = new DataValidatorBuilder(dataValidationErrors). resource(StringUtils.lowerCase(DataExportApiConstants.DATA_EXPORT_ENTITY_NAME)); final String name = this.fromJsonHelper.extractStringNamed( DataExportApiConstants.NAME_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(DataExportApiConstants.BASE_ENTITY_NAME_PARAM_NAME).value(name).notBlank(); final String baseEntity = this.fromJsonHelper.extractStringNamed( DataExportApiConstants.BASE_ENTITY_NAME_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(DataExportApiConstants.BASE_ENTITY_NAME_PARAM_NAME).value(baseEntity).notBlank(); final String[] columns = this.fromJsonHelper.extractArrayNamed(DataExportApiConstants.COLUMNS_PARAM_NAME, jsonElement); dataValidatorBuilder.reset().parameter(DataExportApiConstants.COLUMNS_PARAM_NAME).value(columns).notBlank(); throwExceptionIfValidationWarningsExist(dataValidationErrors); } /** * throw a PlatformApiDataValidationException exception if there are validation errors * * @param dataValidationErrors -- list of ApiParameterError objects * @return None **/ private void throwExceptionIfValidationWarningsExist(final List<ApiParameterError> dataValidationErrors) { if (!dataValidationErrors.isEmpty()) { throw new PlatformApiDataValidationException(dataValidationErrors); } } }
44.636364
128
0.752885
fc5ef53dbdb13d562235bc249459901f8ce67c3a
16,528
/* * Copyright 2016-2018 Axioma srl. * * 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.holonplatform.datastore.mongo.async.test.suite; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.A_BYT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.A_CHR; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.A_ENM; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.A_INT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.A_STR; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.BGD; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.BOOL; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.BYT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.C_ENM; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.C_INT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.C_LNG; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.C_STR; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.DAT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.DBL; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.ENM; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.FLT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.ID; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.INT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.LDAT; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.LNG; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.LTM; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.LTMS; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.NBL; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.SET1; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.SHR; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.STR; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.STR2; import static com.holonplatform.datastore.mongo.async.test.data.ModelTest.TMS; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import org.bson.types.ObjectId; import org.junit.Test; import com.holonplatform.core.property.PropertyBox; import com.holonplatform.core.query.TemporalFunction.CurrentDate; import com.holonplatform.core.query.TemporalFunction.CurrentLocalDate; import com.holonplatform.core.query.TemporalFunction.CurrentLocalDateTime; import com.holonplatform.core.query.TemporalFunction.CurrentTimestamp; import com.holonplatform.datastore.mongo.async.test.data.TestValues; public class BulkUpdateTest extends AbstractDatastoreOperationTest { @Test public void testBulkUpdate() { final ObjectId oid1 = new ObjectId(); final ObjectId oid2 = new ObjectId(); final ObjectId oid3 = new ObjectId(); final PropertyBox value1 = PropertyBox.builder(SET1).set(ID, oid1).set(STR, "bkuv1").set(BOOL, TestValues.BOOL) .set(INT, TestValues.INT).set(LNG, TestValues.LNG).set(DBL, TestValues.DBL).set(FLT, TestValues.FLT) .set(SHR, TestValues.SHR).set(BYT, TestValues.BYT).set(BGD, TestValues.BGD).set(ENM, TestValues.ENM) .set(DAT, TestValues.DAT).set(TMS, TestValues.TMS).set(LDAT, TestValues.LDAT).set(LTMS, TestValues.LTMS) .set(LTM, TestValues.LTM).set(A_STR, TestValues.A_STR).set(A_INT, TestValues.A_INT) .set(A_ENM, TestValues.A_ENM).set(A_CHR, TestValues.A_CHR).set(A_BYT, TestValues.A_BYT) .set(C_STR, TestValues.C_STR).set(C_INT, TestValues.C_INT).set(C_ENM, TestValues.C_ENM) .set(C_LNG, TestValues.C_LNG).set(NBL, true).build(); final PropertyBox value2 = PropertyBox.builder(SET1).set(ID, oid2).set(STR, "bkuv2").set(BOOL, TestValues.BOOL) .set(INT, TestValues.INT).set(LNG, TestValues.LNG).set(DBL, TestValues.DBL).set(FLT, TestValues.FLT) .set(SHR, TestValues.SHR).set(BYT, TestValues.BYT).set(BGD, TestValues.BGD).set(ENM, TestValues.ENM) .set(DAT, TestValues.DAT).set(TMS, TestValues.TMS).set(LDAT, TestValues.LDAT).set(LTMS, TestValues.LTMS) .set(LTM, TestValues.LTM).set(A_STR, TestValues.A_STR).set(A_INT, TestValues.A_INT) .set(A_ENM, TestValues.A_ENM).set(A_CHR, TestValues.A_CHR).set(A_BYT, TestValues.A_BYT) .set(C_STR, TestValues.C_STR).set(C_INT, TestValues.C_INT).set(C_ENM, TestValues.C_ENM) .set(C_LNG, TestValues.C_LNG).set(NBL, true).build(); final PropertyBox value3 = PropertyBox.builder(SET1).set(ID, oid3).set(STR, "bkuv3").set(BOOL, TestValues.BOOL) .set(INT, TestValues.INT).set(LNG, TestValues.LNG).set(DBL, TestValues.DBL).set(FLT, TestValues.FLT) .set(SHR, TestValues.SHR).set(BYT, TestValues.BYT).set(BGD, TestValues.BGD).set(ENM, TestValues.ENM) .set(DAT, TestValues.DAT).set(TMS, TestValues.TMS).set(LDAT, TestValues.LDAT).set(LTMS, TestValues.LTMS) .set(LTM, TestValues.LTM).set(A_STR, TestValues.A_STR).set(A_INT, TestValues.A_INT) .set(A_ENM, TestValues.A_ENM).set(A_CHR, TestValues.A_CHR).set(A_BYT, TestValues.A_BYT) .set(C_STR, TestValues.C_STR).set(C_INT, TestValues.C_INT).set(C_ENM, TestValues.C_ENM) .set(C_LNG, TestValues.C_LNG).set(NBL, true).build(); long count = getDatastore().insert(TARGET, value1).thenAccept(r -> assertEquals(1, r.getAffectedCount())) .thenCompose(v -> getDatastore().insert(TARGET, value2)) .thenAccept(r -> assertEquals(1, r.getAffectedCount())) .thenCompose(v -> getDatastore().insert(TARGET, value3)) .thenAccept(r -> assertEquals(1, r.getAffectedCount())) .thenCompose(v -> getDatastore().query(TARGET).filter(STR.in("bkuv1", "bkuv2", "bkuv3")).count()) .thenAccept(c -> assertEquals(Long.valueOf(3), c)) .thenCompose( v -> getDatastore().bulkUpdate(TARGET).filter(STR.eq("bkuv2")).set(STR, "bkuv2_upd").execute()) .thenAccept(r -> assertEquals(1, r.getAffectedCount())) .thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid2)).findOne(SET1)).thenApply(v2 -> { assertNotNull(v2); assertTrue(v2.isPresent()); return v2.get(); }).thenAccept(v2 -> { assertEquals(oid2, v2.getValue(ID)); assertEquals("bkuv2_upd", v2.getValue(STR)); assertEquals(TestValues.BOOL, v2.getValue(BOOL)); assertEquals(TestValues.INT, v2.getValue(INT)); assertEquals(TestValues.LNG, v2.getValue(LNG)); assertEquals(TestValues.DBL, v2.getValue(DBL)); assertEquals(TestValues.FLT, v2.getValue(FLT)); assertEquals(TestValues.SHR, v2.getValue(SHR)); assertEquals(TestValues.BYT, v2.getValue(BYT)); assertEquals(TestValues.BGD, v2.getValue(BGD)); assertEquals(TestValues.ENM, v2.getValue(ENM)); assertEquals(TestValues.DAT, v2.getValue(DAT)); assertEquals(TestValues.TMS, v2.getValue(TMS)); assertEquals(TestValues.LDAT, v2.getValue(LDAT)); assertEquals(TestValues.LTMS, v2.getValue(LTMS)); assertEquals(TestValues.LTM, v2.getValue(LTM)); assertTrue(Arrays.equals(TestValues.A_STR, v2.getValue(A_STR))); assertTrue(Arrays.equals(TestValues.A_INT, v2.getValue(A_INT))); assertTrue(Arrays.equals(TestValues.A_ENM, v2.getValue(A_ENM))); assertTrue(Arrays.equals(TestValues.A_CHR, v2.getValue(A_CHR))); assertTrue(Arrays.equals(TestValues.A_BYT, v2.getValue(A_BYT))); assertEquals(TestValues.C_STR, v2.getValue(C_STR)); assertEquals(TestValues.C_INT, v2.getValue(C_INT)); assertEquals(TestValues.C_ENM, v2.getValue(C_ENM)); assertEquals(TestValues.C_LNG, v2.getValue(C_LNG)); assertTrue(v2.getValue(NBL)); }) .thenCompose(v -> getDatastore().bulkUpdate(TARGET).filter(ID.in(oid1, oid3)).set(STR, TestValues.U_STR) .set(STR2, TestValues.U_STR2).set(BOOL, TestValues.U_BOOL).set(INT, TestValues.U_INT) .set(LNG, TestValues.U_LNG).set(DBL, TestValues.U_DBL).set(FLT, TestValues.U_FLT) .set(SHR, TestValues.U_SHR).set(BYT, TestValues.U_BYT).set(BGD, TestValues.U_BGD) .set(ENM, TestValues.U_ENM).set(DAT, TestValues.U_DAT).set(TMS, TestValues.U_TMS) .set(LDAT, TestValues.U_LDAT).set(LTMS, TestValues.U_LTMS).set(LTM, TestValues.U_LTM) .set(A_STR, TestValues.U_A_STR).set(A_INT, TestValues.U_A_INT).set(A_ENM, TestValues.U_A_ENM) .set(A_CHR, TestValues.U_A_CHR).set(A_BYT, TestValues.U_A_BYT).set(C_STR, TestValues.U_C_STR) .set(C_INT, TestValues.U_C_INT).set(C_ENM, TestValues.U_C_ENM).set(C_LNG, TestValues.U_C_LNG) .set(NBL, false).execute()) .thenAccept(r -> assertEquals(2, r.getAffectedCount())) .thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid1)).findOne(SET1)).thenApply(v1 -> { assertNotNull(v1); assertTrue(v1.isPresent()); return v1.get(); }).thenAccept(v1 -> { assertEquals(oid1, v1.getValue(ID)); assertEquals(TestValues.U_STR, v1.getValue(STR)); assertEquals(TestValues.U_BOOL, v1.getValue(BOOL)); assertEquals(TestValues.U_INT, v1.getValue(INT)); assertEquals(TestValues.U_LNG, v1.getValue(LNG)); assertEquals(TestValues.U_DBL, v1.getValue(DBL)); assertEquals(TestValues.U_FLT, v1.getValue(FLT)); assertEquals(TestValues.U_SHR, v1.getValue(SHR)); assertEquals(TestValues.U_BYT, v1.getValue(BYT)); assertEquals(TestValues.U_BGD, v1.getValue(BGD)); assertEquals(TestValues.U_ENM, v1.getValue(ENM)); assertEquals(TestValues.U_DAT, v1.getValue(DAT)); assertEquals(TestValues.U_TMS, v1.getValue(TMS)); assertEquals(TestValues.U_LDAT, v1.getValue(LDAT)); assertEquals(TestValues.U_LTMS, v1.getValue(LTMS)); assertEquals(TestValues.U_LTM, v1.getValue(LTM)); assertTrue(Arrays.equals(TestValues.U_A_STR, v1.getValue(A_STR))); assertTrue(Arrays.equals(TestValues.U_A_INT, v1.getValue(A_INT))); assertTrue(Arrays.equals(TestValues.U_A_ENM, v1.getValue(A_ENM))); assertTrue(Arrays.equals(TestValues.U_A_CHR, v1.getValue(A_CHR))); assertTrue(Arrays.equals(TestValues.U_A_BYT, v1.getValue(A_BYT))); assertEquals(TestValues.U_C_STR, v1.getValue(C_STR)); assertEquals(TestValues.U_C_INT, v1.getValue(C_INT)); assertEquals(TestValues.U_C_ENM, v1.getValue(C_ENM)); assertEquals(TestValues.U_C_LNG, v1.getValue(C_LNG)); assertFalse(v1.getValue(NBL)); }).thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid3)).findOne(SET1)).thenApply(v3 -> { assertNotNull(v3); assertTrue(v3.isPresent()); return v3.get(); }).thenAccept(v3 -> { assertEquals(oid3, v3.getValue(ID)); assertEquals(TestValues.U_STR, v3.getValue(STR)); assertEquals(TestValues.U_BOOL, v3.getValue(BOOL)); assertEquals(TestValues.U_INT, v3.getValue(INT)); assertEquals(TestValues.U_LNG, v3.getValue(LNG)); assertEquals(TestValues.U_DBL, v3.getValue(DBL)); assertEquals(TestValues.U_FLT, v3.getValue(FLT)); assertEquals(TestValues.U_SHR, v3.getValue(SHR)); assertEquals(TestValues.U_BYT, v3.getValue(BYT)); assertEquals(TestValues.U_BGD, v3.getValue(BGD)); assertEquals(TestValues.U_ENM, v3.getValue(ENM)); assertEquals(TestValues.U_DAT, v3.getValue(DAT)); assertEquals(TestValues.U_TMS, v3.getValue(TMS)); assertEquals(TestValues.U_LDAT, v3.getValue(LDAT)); assertEquals(TestValues.U_LTMS, v3.getValue(LTMS)); assertEquals(TestValues.U_LTM, v3.getValue(LTM)); assertTrue(Arrays.equals(TestValues.U_A_STR, v3.getValue(A_STR))); assertTrue(Arrays.equals(TestValues.U_A_INT, v3.getValue(A_INT))); assertTrue(Arrays.equals(TestValues.U_A_ENM, v3.getValue(A_ENM))); assertTrue(Arrays.equals(TestValues.U_A_CHR, v3.getValue(A_CHR))); assertTrue(Arrays.equals(TestValues.U_A_BYT, v3.getValue(A_BYT))); assertEquals(TestValues.U_C_STR, v3.getValue(C_STR)); assertEquals(TestValues.U_C_INT, v3.getValue(C_INT)); assertEquals(TestValues.U_C_ENM, v3.getValue(C_ENM)); assertEquals(TestValues.U_C_LNG, v3.getValue(C_LNG)); assertFalse(v3.getValue(NBL)); }) .thenCompose(v -> getDatastore().bulkUpdate(TARGET).filter(ID.in(oid1, oid2, oid3)).set(DBL, 77.99d) .setNull(INT).execute()) .thenAccept(r -> assertEquals(3, r.getAffectedCount())) .thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid1)).findOne(INT)).thenAccept(r -> { assertFalse(r.isPresent()); }).thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid2)).findOne(INT)).thenAccept(r -> { assertFalse(r.isPresent()); }).thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid3)).findOne(INT)).thenAccept(r -> { assertFalse(r.isPresent()); }).thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid1)).findOne(DBL)).thenAccept(dv -> { assertEquals(Double.valueOf(77.99d), dv.orElse(null)); }).thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid2)).findOne(DBL)).thenAccept(dv -> { assertEquals(Double.valueOf(77.99d), dv.orElse(null)); }).thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid3)).findOne(DBL)).thenAccept(dv -> { assertEquals(Double.valueOf(77.99d), dv.orElse(null)); }).thenCompose(v -> getDatastore().bulkDelete(TARGET).filter(ID.in(oid1, oid2, oid3)).execute()) .thenApply(r -> r.getAffectedCount()).toCompletableFuture().join(); assertEquals(3, count); } @Test public void testBulkUpdateDate() { final ObjectId oid = new ObjectId(); long count = getDatastore().insert(TARGET, PropertyBox.builder(SET1).set(ID, oid).set(STR, "bkuv10").build()) .thenAccept(r -> assertEquals(1, r.getAffectedCount())) .thenCompose(v -> getDatastore().bulkUpdate(TARGET).filter(ID.eq(oid)).set(DAT, CurrentDate.create()) .set(LDAT, CurrentLocalDate.create()).set(TMS, CurrentTimestamp.create()) .set(LTMS, CurrentLocalDateTime.create()).execute()) .thenAccept(r -> assertEquals(1, r.getAffectedCount())) .thenCompose(v -> getDatastore().query(TARGET).filter(ID.eq(oid)).findOne(SET1)).thenApply(uvalue -> { assertTrue(uvalue.isPresent()); return uvalue.get(); }).thenAccept(uvalue -> { final Calendar now = Calendar.getInstance(); final LocalDate today = LocalDate.now(); Date dat = uvalue.getValue(DAT); assertNotNull(dat); Calendar c = Calendar.getInstance(); c.setTime(dat); assertEquals(now.get(Calendar.YEAR), c.get(Calendar.YEAR)); assertEquals(now.get(Calendar.MONTH), c.get(Calendar.MONTH)); assertEquals(now.get(Calendar.DAY_OF_MONTH), c.get(Calendar.DAY_OF_MONTH)); LocalDate ldat = uvalue.getValue(LDAT); assertNotNull(ldat); assertEquals(today.getYear(), ldat.getYear()); assertEquals(today.getMonth(), ldat.getMonth()); assertEquals(today.getDayOfMonth(), ldat.getDayOfMonth()); Date tms = uvalue.getValue(TMS); assertNotNull(tms); c = Calendar.getInstance(); c.setTime(dat); assertEquals(now.get(Calendar.YEAR), c.get(Calendar.YEAR)); assertEquals(now.get(Calendar.MONTH), c.get(Calendar.MONTH)); assertEquals(now.get(Calendar.DAY_OF_MONTH), c.get(Calendar.DAY_OF_MONTH)); assertEquals(now.get(Calendar.HOUR), c.get(Calendar.HOUR)); LocalDateTime ltms = uvalue.getValue(LTMS); assertNotNull(ltms); assertEquals(today.getYear(), ltms.getYear()); assertEquals(today.getMonth(), ltms.getMonth()); assertEquals(today.getDayOfMonth(), ltms.getDayOfMonth()); }).thenCompose(v -> getDatastore().bulkDelete(TARGET).filter(ID.eq(oid)).execute()) .thenApply(r -> r.getAffectedCount()).toCompletableFuture().join(); assertEquals(1, count); } }
55.093333
113
0.734753
ff2c9d2cbdfcfe267abab5895bd61db4da293d2a
132
package edu.iastate.metnet.metaomgraph.utils; public interface ExceptionListener { void exception(Throwable paramThrowable); }
22
45
0.810606
982dd65ba681bbe602a84ae1021fa50a77d3f556
309
package wesley.leonardo3.carro.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/") public String mensagem() { return "Seja Bem-Vindo!"; } }
22.071429
62
0.747573
ebfe8f7beba6d3d70e98230ac8cd8beaf50f6d55
2,733
package ru.betterend.entity.model; import com.mojang.blaze3d.vertex.PoseStack; import com.mojang.blaze3d.vertex.VertexConsumer; import net.minecraft.client.model.geom.ModelPart; import net.minecraft.client.renderer.RenderType; import ru.betterend.entity.EndFishEntity; public class EndFishEntityModel extends BlockBenchModel<EndFishEntity> { private final ModelPart model; private final ModelPart fin_top; private final ModelPart fin_bottom; private final ModelPart flipper; private final ModelPart fin_right; private final ModelPart fin_left; public EndFishEntityModel() { super(RenderType::entityCutout); texWidth = 32; texHeight = 32; model = new ModelPart(this); model.setPos(0.0F, 20.0F, 0.0F); model.texOffs(0, 0).addBox(-1.0F, -2.0F, -4.0F, 2.0F, 4.0F, 8.0F, 0.0F); fin_top = new ModelPart(this); fin_top.setPos(0.0F, -2.0F, -4.0F); model.addChild(fin_top); setRotationAngle(fin_top, -0.6981F, 0.0F, 0.0F); fin_top.texOffs(0, 6).addBox(0.0F, -8.0F, 0.0F, 0.0F, 8.0F, 6.0F, 0.0F); fin_bottom = new ModelPart(this); fin_bottom.setPos(0.0F, 2.0F, -4.0F); model.addChild(fin_bottom); setRotationAngle(fin_bottom, 0.6981F, 0.0F, 0.0F); fin_bottom.texOffs(0, 6).addBox(0.0F, 0.0F, 0.0F, 0.0F, 8.0F, 6.0F, 0.0F); flipper = new ModelPart(this); flipper.setPos(0.0F, 0.0F, 2.0F); model.addChild(flipper); setRotationAngle(flipper, -0.7854F, 0.0F, 0.0F); flipper.texOffs(0, 15).addBox(0.0F, -5.0F, 0.0F, 0.0F, 5.0F, 5.0F, 0.0F); fin_right = new ModelPart(this); fin_right.setPos(-1.0F, 0.0F, -1.0F); model.addChild(fin_right); setRotationAngle(fin_right, 1.5708F, 0.7854F, 0.0F); fin_right.texOffs(0, 25).addBox(-3.7071F, 0.7071F, -1.5F, 3.0F, 0.0F, 3.0F, 0.0F); fin_left = new ModelPart(this); fin_left.setPos(1.0F, 0.0F, -1.0F); model.addChild(fin_left); setRotationAngle(fin_left, 1.5708F, -0.7854F, 0.0F); fin_left.texOffs(0, 25).addBox(0.7071F, 0.7071F, -1.5F, 3.0F, 0.0F, 3.0F, 0.0F, true); } @Override public void setupAnim(EndFishEntity entity, float limbAngle, float limbDistance, float animationProgress, float headYaw, float headPitch) { float s1 = (float) Math.sin(animationProgress * 0.1); float s2 = (float) Math.sin(animationProgress * 0.05); flipper.yRot = s1 * 0.3F; fin_top.xRot = s2 * 0.02F - 0.6981F; fin_bottom.xRot = 0.6981F - s2 * 0.02F; fin_left.yRot = s1 * 0.3F - 0.7854F; fin_right.yRot = 0.7854F - s1 * 0.3F; } @Override public void renderToBuffer(PoseStack matrices, VertexConsumer vertices, int light, int overlay, float red, float green, float blue, float alpha) { model.render(matrices, vertices, light, overlay); } }
35.493506
108
0.683498
0972b21f71b652b99d62eb70857ccbfbff67f827
659
class P_Resept extends HvitResept {//arver egenskapene til HvitResept-klassen P_Resept(Legemiddel legemiddel, Lege utskrivingsLege, int pasientID, int reit) { super(legemiddel, utskrivingsLege, pasientID, reit ); } //kaller HvitResept-klassens konstruktør @Override public String farge(){ return RESEPTENS_FARGE + " - P-Resept"; } //Henter info fra HvitResept-klassen ("Hvit") @Override public int prisAaBetale() { int pris = hentLegemiddel().pris; pris -= 108; //Resepten skal få 108kr rabattfradrag if (pris < 0) {pris = 0; } return pris; } }
20.59375
80
0.62519
865e46d719da2b0b6e3fec2106af83ea1677d323
297
package com.konoplyanikovd.interview.design.pattern.factorymethod; public class Main { public static void main(String[] args) { AnimalFactory factory = new CatFactory() ; Animal animal = factory.createAnimal(); animal.setName("123132"); animal.desc(); } }
27
66
0.6633
ddf3bb1c58ad87196b7ca4ae48f99d7f73a60b7b
1,520
// 2021.05.18 // Leetcode 第46题 // https://leetcode-cn.com/problems/permutations/description/ package Search; import java.util.ArrayList; import java.util.List; public class T46 { public static void main(String[] args) { T46 solution = new T46(); int[] nums = { 1, 2, 3 }; List<List<Integer>> result = solution.permute(nums); for (List<Integer> list : result) { for (Integer num : list) { System.out.print(num); } System.out.println(); } } public List<List<Integer>> permute(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null) { return result; } List<Integer> list = new ArrayList<>(); boolean[] visited = new boolean[nums.length]; backtracking(result, list, visited, nums); return result; } private void backtracking(List<List<Integer>> result, List<Integer> list, boolean[] visited, int[] nums) { if (list.size() == nums.length) { // result.add(list); result.add(new ArrayList<>(list)); // 重新构造一个list return; } for (int i = 0; i < nums.length; i++) { if (visited[i] == false) { visited[i] = true; list.add(nums[i]); backtracking(result, list, visited, nums); list.remove(list.size() - 1); // 删除掉 visited[i] = false; } } } }
26.666667
110
0.516447
4200075f27914918b9bb130420042f2e2db8dff9
3,700
/* ### * IP: GHIDRA * * 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 ghidra.util.classfinder; import java.io.File; import java.io.IOException; import java.util.*; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import ghidra.util.Msg; import ghidra.util.exception.CancelledException; import ghidra.util.task.TaskMonitor; class ClassJar { /** * Pattern for matching jar files in a module lib dir * <p> * The pattern roughly states to accept any path that contains <tt>lib</tt> or * <tt>build/libs</tt>, ending in <tt>.jar</tt> (non-capturing) and then * grab that dir's parent and the name of the jar file. */ private static Pattern ANY_MODULE_LIB_JAR_FILE_PATTERN = Pattern.compile(".*/(.*)/(?:lib|build/libs)/(.+).jar"); private String path; private Set<String> classNameList = new HashSet<>(); private Set<Class<?>> classes = new HashSet<>(); ClassJar(String path, TaskMonitor monitor) throws CancelledException { this.path = path; scan(monitor); } void getClasses(Set<Class<?>> set, TaskMonitor monitor) { set.addAll(classes); } private void scan(TaskMonitor monitor) throws CancelledException { File file = new File(path); try (JarFile jarFile = new JarFile(file)) { String pathName = jarFile.getName(); int separatorIndex = pathName.lastIndexOf(File.separator); String jarFilename = pathName.substring(separatorIndex + 1); monitor.setMessage("Scanning jar: " + jarFilename); Enumeration<JarEntry> entries = jarFile.entries(); while (entries.hasMoreElements()) { monitor.checkCanceled(); processClassFiles(entries.nextElement()); } } catch (IOException e) { Msg.error(this, "Error reading jarFile: " + path, e); } } static boolean ignoreJar(String pathName) { // // Note: keep this algorithm simple enough that users can add their own plugins via // jar files. // // // Dev Mode // if (pathName.contains("ExternalLibraries")) { return true; } // // Production Mode - In production, only module lib jar files are scanned. // if (isModuleDependencyJar(pathName)) { return false; } return true; } static boolean isModuleDependencyJar(String pathName) { if (ClassSearcher.SEARCH_ALL_JARS) { return true; // this will search all jar files } String forwardSlashed = pathName.replaceAll("\\\\", "/"); Matcher matcher = ANY_MODULE_LIB_JAR_FILE_PATTERN.matcher(forwardSlashed); if (!matcher.matches()) { return false; } String moduleName = matcher.group(1); String jarName = matcher.group(2); // handle a name match, as well as an extension jar (e.g., /Base/lib/Base_ext.jar) return jarName.startsWith(moduleName); } private void processClassFiles(JarEntry entry) { String name = entry.getName(); if (!name.endsWith(".class")) { return; } name = name.substring(0, name.indexOf(".class")); name = name.replace('/', '.'); Class<?> c = ClassFinder.loadExtensionPoint(path, name); if (c != null) { classNameList.add(name); classes.add(c); } } @Override public String toString() { return path; } }
26.056338
85
0.695676
85fe9e2fe3a634eb168fa3168c49c38b7e823a7e
619
package org.corfudb.infrastructure.logreplication.replication.send.logreader; import org.corfudb.protocols.wireprotocol.ILogData; import java.util.List; /** * Interface for snapshot/log entry read pre-processing. */ public interface ReadProcessor { /** * Process a snapshot/log entry read for any transformation * before sending back to the application callback. * * @param logEntries list of log data * * @return */ List<byte[]> process(List<ILogData> logEntries); /** * * @param logEntry * @return */ byte[] process(ILogData logEntry); }
20.633333
77
0.663974
e197eb9a548441910c3036a644b1611fb0d36650
685
package rholang.parsing.rholang1.Absyn; // Java Package generated by the BNF Converter. public class QInt extends Quantity { public final Integer integer_; public QInt(Integer p1) { integer_ = p1; } public <R,A> R accept(rholang.parsing.rholang1.Absyn.Quantity.Visitor<R,A> v, A arg) { return v.visit(this, arg); } public boolean equals(Object o) { if (this == o) return true; if (o instanceof rholang.parsing.rholang1.Absyn.QInt) { rholang.parsing.rholang1.Absyn.QInt x = (rholang.parsing.rholang1.Absyn.QInt)o; return this.integer_.equals(x.integer_); } return false; } public int hashCode() { return this.integer_.hashCode(); } }
28.541667
117
0.69635
790caac5fffc74c39d7b0eab8eb1cb626c932092
63,152
/* * compile with * javac -classpath `hadoop classpath`:`hbase classpath` blms/batches/spcl/PVLU_UPDATES.java * nohup java -classpath `hadoop classpath`:`hbase classpath` blms/batches/spcl/PVLU_UPDATES 'hdfs://hahdfsqa/user/asp20571bdp/BLMB0102/PMLU/input/111111_20200201130000/VALID_PMLU_INPUT_FOR_JAVA/part-v009-o000-r-00000' '2020-02-01 13:00:00.000' '20200201130000' > PMLU.log 2>&1 & * */ package blms.batches.spcl; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; import org.apache.hadoop.conf.*; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Delete; import org.apache.hadoop.hbase.client.Put; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.client.ResultScanner; import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException; import org.apache.hadoop.hbase.client.RowMutations; import org.apache.hadoop.hbase.client.Scan; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.filter.FilterList; import org.apache.hadoop.hbase.filter.PrefixFilter; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; public class PVLU_UPDATES { private static Properties configProp = new Properties(); static Map<byte[], byte[]> PACK_INFO_TBL = new HashMap<byte[], byte[]>(); static Map<byte[], byte[]> BLMS_PROBE_TBL = new HashMap<byte[], byte[]>(); static Map<byte[], byte[]> VIN_IDX_TBL = new HashMap<byte[], byte[]>(); static Map<byte[], byte[]> PACK_INFO_UPD_IDX_TBL = new HashMap<byte[], byte[]>(); static Map<byte[], byte[]> PACK_INFO_VIN_IDX_TBL = new HashMap<byte[], byte[]>(); static Map<byte[], byte[]> PACK_MAP_TBL = new HashMap<byte[], byte[]>(); static Map<Integer, String> JOB_DETAILS = new HashMap<Integer, String>(); //Collect the success or error case of each pvlu record static int line_cnt = 0; private static Path filePath , jdCSVFilePath ; private static FileHandler fh_pvlu; //private static String wf_id = "0000"; private static String event_set_flag, new_UPD, V_READ_DATE, PkInfo_VAL_s, PkInfo_VAL_t, PkInfo_VAL_v, PkInfo_VAL_w, PkInfo_VAL_x, PkInfo_VAL_h, PkInfo_VAL_i, PkInfo_VAL_j; private static String ProbeKey , newSearch1Key , oldSearch1Key , newSearch2Key , oldSearch2Key , newSearch3Key , oldSearch3Key , pvlu_event_id , event_remove_flag ; private static String defaultFS, hbaseZookeeperPort, hbaseZookeeperQuorum1, hbaseZnodeParent, hbaseMasterPort, hbaseMaster, hbaseRpcTimeout, hbaseClientScannerTimeout, hbaseCellsScannedPerHeartBeatCheck, hbaseClientOperationTimeout, hadoopSecurityAuthentication; private static String PVLU_UPDATES_LOG, hbaseNameSpace, blms_probe, blms_probe_search1, blms_probe_search2, blms_probe_search3, blms_pack_info, blms_pack_info_upd_idx, blms_pack_info_vin_idx, blms_cache_processed; private static byte[] cf_pk, cf_idx, cf_cmn, pkinfo_rmvdate, pkinfo_PackDateKey, pkinfo_Timestamp, pkinfo_event_id, pkinfo_blms_id, pkinfo_vin, pkinfo_upd, pkinfo_orignalKey, pkinfo_alliancePk, pkinfo_pvdate, pkinfo_nissanPack, PkInfo_FLD_q, PkInfo_FLD_r, PkInfo_FLD_s, PkInfo_FLD_t, PkInfo_FLD_u, PkInfo_FLD_v, PkInfo_FLD_w, PkInfo_FLD_x, PkInfo_FLD_h, PkInfo_FLD_i, PkInfo_FLD_j; //pkinfo_rmvdate wil be always 100 since this is a column taken from reserve private static byte[] CP_V_COL_001, CP_V_COL_002, cf_cp; private static Logger LOGGER_EVENT; private static Table blms_pack_info_tblConn, blms_mc_tblConn, blms_pack_info_vin_idx_tblConn, TblBlmsConn, blms_probe_tblConn; private static ResultScanner mc_scanner, scanner,vin_scanner, ProbeScanner, vinIdxScanner; private static FileSystem fs, hdfsOut; private static FSDataOutputStream outPutStream; private static Configuration conf; private static BufferedReader br; static Connection conn; private static final String PropertyFileName = "/home/asp20571bdp/DEV/BDP_BATCHES/COMMON_UTILS/PROPERTIES/conf_blmb0102.properties"; static { try { //InputStream in = new FileInputStream("../../../COMMON_UTILS/PROPERTIES/conf_blmb0102.properties"); InputStream in = new FileInputStream(PropertyFileName); configProp.load(in); defaultFS = configProp.getProperty("defaultFS"); hbaseZookeeperPort = configProp.getProperty("hbaseZookeeperPort"); hbaseZookeeperQuorum1 = configProp.getProperty("hbaseZookeeperQuorum1"); hbaseZnodeParent = configProp.getProperty("hbaseZnodeParent"); hbaseMasterPort = configProp.getProperty("hbaseMasterPort"); hbaseMaster = configProp.getProperty("hbaseMaster"); hbaseRpcTimeout = configProp.getProperty("hbaseRpcTimeout"); hbaseClientScannerTimeout = configProp.getProperty("hbaseClientScannerTimeout"); hbaseCellsScannedPerHeartBeatCheck = configProp.getProperty("hbaseCellsScannedPerHeartBeatCheck"); hbaseClientOperationTimeout = configProp.getProperty("hbaseClientOperationTimeout"); hadoopSecurityAuthentication = configProp.getProperty("hadoopSecurityAuthentication"); PVLU_UPDATES_LOG = configProp.getProperty("PVLU_UPDATES_LOG"); pvlu_event_id = configProp.getProperty("pvlu_event_id"); event_remove_flag = configProp.getProperty("event_remove_flag"); event_set_flag = configProp.getProperty("event_set_flag"); cf_pk = Bytes.toBytes(configProp.getProperty("cf_pk")); cf_idx = Bytes.toBytes(configProp.getProperty("cf_idx")); cf_cmn = Bytes.toBytes(configProp.getProperty("cf_cmn")); cf_cp = Bytes.toBytes(configProp.getProperty("cf_cp")); pkinfo_blms_id = Bytes.toBytes(configProp.getProperty("pkinfo_blms_id")); pkinfo_vin = Bytes.toBytes(configProp.getProperty("pkinfo_vin")); pkinfo_upd = Bytes.toBytes(configProp.getProperty("pkinfo_upd")); pkinfo_orignalKey = Bytes.toBytes(configProp.getProperty("pkinfo_orignalKey")); pkinfo_alliancePk = Bytes.toBytes(configProp.getProperty("pkinfo_alliancePk")); pkinfo_pvdate = Bytes.toBytes(configProp.getProperty("pkinfo_pvdate")); pkinfo_nissanPack = Bytes.toBytes(configProp.getProperty("pkinfo_nissanPack")); pkinfo_rmvdate = Bytes.toBytes(configProp.getProperty("pkinfo_rmvdate")); pkinfo_PackDateKey = Bytes.toBytes(configProp.getProperty("pkinfo_PackDateKey")); pkinfo_Timestamp = Bytes.toBytes(configProp.getProperty("pkinfo_Timestamp")); pkinfo_event_id = Bytes.toBytes(configProp.getProperty("pkinfo_event_id")); CP_V_COL_001 = Bytes.toBytes(configProp.getProperty("CP_V_COL_001")); CP_V_COL_002 = Bytes.toBytes(configProp.getProperty("CP_V_COL_002")); hbaseNameSpace = configProp.getProperty("hbaseNameSpace"); blms_probe = configProp.getProperty("blms_probe"); blms_probe_search1 = configProp.getProperty("blms_probe_search1"); blms_probe_search2 = configProp.getProperty("blms_probe_search2"); blms_probe_search3 = configProp.getProperty("blms_probe_search3"); blms_pack_info = configProp.getProperty("blms_pack_info"); blms_pack_info_upd_idx = configProp.getProperty("blms_pack_info_upd_idx"); blms_pack_info_vin_idx = configProp.getProperty("blms_pack_info_vin_idx"); blms_cache_processed = configProp.getProperty("blms_cache_processed"); //Addition of AMO Cols: PkInfo_VAL_s= configProp.getProperty("PkInfo_VAL_s"); PkInfo_VAL_t= configProp.getProperty("PkInfo_VAL_t"); PkInfo_VAL_v= configProp.getProperty("PkInfo_VAL_v"); PkInfo_VAL_w= configProp.getProperty("PkInfo_VAL_w"); PkInfo_VAL_x= configProp.getProperty("PkInfo_VAL_x"); PkInfo_VAL_h= configProp.getProperty("PkInfo_VAL_h"); PkInfo_VAL_i= configProp.getProperty("PkInfo_VAL_i"); PkInfo_VAL_j= configProp.getProperty("PkInfo_VAL_j"); PkInfo_FLD_q= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_q")); PkInfo_FLD_r= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_r")); PkInfo_FLD_s= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_s")); PkInfo_FLD_t= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_t")); PkInfo_FLD_u= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_u")); PkInfo_FLD_v= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_v")); PkInfo_FLD_w= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_w")); PkInfo_FLD_x= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_x")); PkInfo_FLD_h= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_h")); PkInfo_FLD_i= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_i")); PkInfo_FLD_j= Bytes.toBytes(configProp.getProperty("PkInfo_FLD_j")); LOGGER_EVENT = Logger.getLogger(PVLU_UPDATES.class.getName()); in.close(); } catch (Exception e) { e.printStackTrace(); System.out.println("SEVERE:UnHandled Exception in static intilization block..."+e.getMessage()); System.exit(1); } } private static void printInitialValues() { LOGGER_EVENT.log(Level.INFO,"PropertyFileName: "+PropertyFileName); LOGGER_EVENT.log(Level.INFO,"defaultFS: "+defaultFS); LOGGER_EVENT.log(Level.INFO,"hbaseZookeeperPort: "+hbaseZookeeperPort); LOGGER_EVENT.log(Level.INFO,"hbaseZookeeperQuorum1: "+hbaseZookeeperQuorum1); LOGGER_EVENT.log(Level.INFO,"hbaseZnodeParent: "+hbaseZnodeParent); LOGGER_EVENT.log(Level.INFO,"hbaseMasterPort: "+hbaseMasterPort); LOGGER_EVENT.log(Level.INFO,"hbaseMaster: "+hbaseMaster); LOGGER_EVENT.log(Level.INFO,"hbaseRpcTimeout: "+hbaseRpcTimeout); LOGGER_EVENT.log(Level.INFO,"hbaseClientScannerTimeout: "+hbaseClientScannerTimeout); LOGGER_EVENT.log(Level.INFO,"hbaseCellsScannedPerHeartBeatCheck: "+hbaseCellsScannedPerHeartBeatCheck); LOGGER_EVENT.log(Level.INFO,"hbaseClientOperationTimeout: "+hbaseClientOperationTimeout); LOGGER_EVENT.log(Level.INFO,"hadoopSecurityAuthentication: "+hadoopSecurityAuthentication); LOGGER_EVENT.log(Level.INFO,"PVLU_UPDATES_LOG: "+PVLU_UPDATES_LOG); LOGGER_EVENT.log(Level.INFO,"pvlu_event_id: "+pvlu_event_id); LOGGER_EVENT.log(Level.INFO,"event_remove_flag: "+event_remove_flag); LOGGER_EVENT.log(Level.INFO,"event_set_flag: "+event_set_flag); LOGGER_EVENT.log(Level.INFO,"cf_pk: "+Bytes.toString(cf_pk)); LOGGER_EVENT.log(Level.INFO,"cf_idx: "+Bytes.toString(cf_idx)); LOGGER_EVENT.log(Level.INFO,"cf_cmn: "+Bytes.toString(cf_cmn)); LOGGER_EVENT.log(Level.INFO,"cf_cp: "+Bytes.toString(cf_cp)); LOGGER_EVENT.log(Level.INFO,"pkinfo_blms_id: "+Bytes.toString(pkinfo_blms_id)); LOGGER_EVENT.log(Level.INFO,"pkinfo_vin: "+Bytes.toString(pkinfo_vin)); LOGGER_EVENT.log(Level.INFO,"pkinfo_upd: "+Bytes.toString(pkinfo_upd)); LOGGER_EVENT.log(Level.INFO,"pkinfo_orignalKey: "+Bytes.toString(pkinfo_orignalKey)); LOGGER_EVENT.log(Level.INFO,"pkinfo_alliancePk: "+Bytes.toString(pkinfo_alliancePk)); LOGGER_EVENT.log(Level.INFO,"pkinfo_pvdate: "+Bytes.toString(pkinfo_pvdate)); LOGGER_EVENT.log(Level.INFO,"pkinfo_nissanPack: "+Bytes.toString(pkinfo_nissanPack)); LOGGER_EVENT.log(Level.INFO,"pkinfo_rmvdate: "+Bytes.toString(pkinfo_rmvdate)); LOGGER_EVENT.log(Level.INFO,"pkinfo_PackDateKey: "+Bytes.toString(pkinfo_PackDateKey)); LOGGER_EVENT.log(Level.INFO,"pkinfo_Timestamp: "+Bytes.toString(pkinfo_Timestamp)); LOGGER_EVENT.log(Level.INFO,"pkinfo_event_id: "+Bytes.toString(pkinfo_event_id)); LOGGER_EVENT.log(Level.INFO,"CP_V_COL_001: "+Bytes.toString(CP_V_COL_001)); LOGGER_EVENT.log(Level.INFO,"CP_V_COL_002: "+Bytes.toString(CP_V_COL_002)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_q: "+Bytes.toString(PkInfo_FLD_q)); LOGGER_EVENT.log(Level.INFO,"hbaseNameSpace: "+hbaseNameSpace); LOGGER_EVENT.log(Level.INFO,"blms_probe: "+blms_probe); LOGGER_EVENT.log(Level.INFO,"blms_probe_search1: "+blms_probe_search1); LOGGER_EVENT.log(Level.INFO,"blms_probe_search2: "+blms_probe_search2); LOGGER_EVENT.log(Level.INFO,"blms_probe_search3: "+blms_probe_search3); LOGGER_EVENT.log(Level.INFO,"blms_pack_info: "+blms_pack_info); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_upd_idx: "+blms_pack_info_upd_idx); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_vin_idx: "+blms_pack_info_vin_idx); LOGGER_EVENT.log(Level.INFO,"blms_cache_processed: "+blms_cache_processed); LOGGER_EVENT.log(Level.INFO,"AMO COLUMN LIST FROM PROPERTY FILE(Displaying..) "); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_s: "+PkInfo_VAL_s); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_t: "+PkInfo_VAL_t); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_v: "+PkInfo_VAL_v); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_w: "+PkInfo_VAL_w); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_x: "+PkInfo_VAL_x); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_h: "+PkInfo_VAL_h); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_i: "+PkInfo_VAL_i); LOGGER_EVENT.log(Level.INFO,"PkInfo_VAL_j: "+PkInfo_VAL_j); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_q: "+Bytes.toString(PkInfo_FLD_q)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_r: "+Bytes.toString(PkInfo_FLD_r)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_s: "+Bytes.toString(PkInfo_FLD_s)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_t: "+Bytes.toString(PkInfo_FLD_t)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_u: "+Bytes.toString(PkInfo_FLD_u)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_v: "+Bytes.toString(PkInfo_FLD_v)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_w: "+Bytes.toString(PkInfo_FLD_w)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_x: "+Bytes.toString(PkInfo_FLD_x)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_h: "+Bytes.toString(PkInfo_FLD_h)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_i: "+Bytes.toString(PkInfo_FLD_i)); LOGGER_EVENT.log(Level.INFO,"PkInfo_FLD_j: "+Bytes.toString(PkInfo_FLD_j)); } public static Result getLatestRecord(String tableName, String prefixFilterValue) throws IOException { //List keys = new ArrayList<Result>(); Result LastRow=null ; LOGGER_EVENT.log(Level.INFO, "Fetching Latest Record for Table: " + tableName); TableName blms_tbl = TableName.valueOf(hbaseNameSpace + ":" + tableName); Table blms_tblConn = conn.getTable(blms_tbl); //Scan scan = new Scan(Bytes.toBytes(prefixFilterValue), Bytes.toBytes(prefixFilterValue)); Scan scan = new Scan(); scan.setCaching(1000);//brings the 100 records (default ) by each next request ; even its next() or next(nb) //FilterList allFilters = new FilterList(FilterList.Operator.MUST_PASS_ALL); //allFilters.addFilter(new PrefixFilter(Bytes.toBytes(prefixFilterValue))); scan.setRowPrefixFilter(Bytes.toBytes(prefixFilterValue)); scan.getLoadColumnFamiliesOnDemandValue(); //scan.setFilter(allFilters); //scan.setReversed(true); //Read the latest available key and value //scan.setMaxResultSize(1); //scan.setFilter(new InclusiveStopFilter(Bytes.toBytes(prefixFilterValue))); ResultScanner scanner = blms_tblConn.getScanner(scan); for (Result result = scanner.next(); result != null; result = scanner.next()) { //keys.add(result); LastRow= result; } scanner.close(); //Scanner closed blms_tblConn.close(); if(LastRow != null) LOGGER_EVENT.log(Level.INFO, "Fetched Latest Record for Table: " + tableName + ", Record: " + Bytes.toString(LastRow.getRow())); else LOGGER_EVENT.log(Level.INFO, "Record not Found...."); return LastRow; } public static void pvluRemoveApply(String[] token) throws Exception{ try { LOGGER_EVENT.log(Level.INFO,"Inside Of pvluRemoveApply() for removing AlliancePack: "+token[1]+" & Vin: "+token[4]); /* blms_pack_info_tblConn = getTable(blms_pack_info); Scan scan = new Scan(); FilterList allFilters = new FilterList(FilterList.Operator.MUST_PASS_ALL); allFilters.addFilter(new PrefixFilter(Bytes.toBytes(token[1]))); scan.setFilter(allFilters); scan.setReversed(true); // read the latest available key and values for this AP scan.setMaxResultSize(1); LOGGER_EVENT.log(Level.INFO,"scan object to string before execute: "+scan.toString()); scanner = blms_pack_info_tblConn.getScanner(scan); Result result = scanner.next(); */ Result result = getLatestRecord(blms_pack_info, token[1]); if(result != null) { PACK_INFO_TBL = result.getFamilyMap(cf_pk); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_blms_id: "+Bytes.toString(PACK_INFO_TBL.get(pkinfo_blms_id))); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_vin: "+Bytes.toString(PACK_INFO_TBL.get(pkinfo_vin))); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_upd: "+Bytes.toString(PACK_INFO_TBL.get(pkinfo_upd))); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_orignalKey: "+Bytes.toString(PACK_INFO_TBL.get( pkinfo_orignalKey))); String cond1_blms_pack_id = Bytes.toString(PACK_INFO_TBL.get(pkinfo_blms_id)); String cond2_pkinfo_vin = Bytes.toString(PACK_INFO_TBL.get(pkinfo_vin)); LOGGER_EVENT.log(Level.INFO,"cond1_blms_pack_id: "+cond1_blms_pack_id); LOGGER_EVENT.log(Level.INFO,"cond2_pkinfo_vin: "+cond2_pkinfo_vin); if(cond1_blms_pack_id !=null && !cond1_blms_pack_id.isEmpty()) { LOGGER_EVENT.log(Level.INFO,"Packinfo Contains value for BLMSPACK_ID.."+cond1_blms_pack_id); //blms id present, arrived alliance pack present.: true LOGGER_EVENT.log(Level.INFO,"Next check arrived vin really attached to this pack.."+token[4]); //token[4] <-Arrived vin if((cond2_pkinfo_vin !=null && !cond2_pkinfo_vin.isEmpty()) && cond2_pkinfo_vin.compareTo(token[4])==0){ //Arrived "VIN" is also attached to arrived Alliance pack LOGGER_EVENT.log(Level.INFO,"Arrived Vin is Matching, Arrived VIN: "+token[4]); //PACK_INFO_TBL = result.getFamilyMap(cf_pk); // token[1] <- AP // get the "token[1]+pkinfo_upd" values from packinfo latest record // Use PUT on : upd_idx tbl "new UPD+token[1]"=> b:token[1]; g:new UPD // Use PUT on : vin_idx_tbl "token[4]+new UPD"=> b:token[1]; g:new UPD // Create New Records in pack-info: with new key(token[1]+new UPD) and pk:vin=null,pk:pvdate=null,pk:removedate=removeDate /* b -> Alliance Pack1 -> null g -> T_UPD_DATE1 -> new_UPD f -> Battery setting Date -> null c -> N_Pack(To check PVLC) -> null d -> VIN -> same VIN */ LOGGER_EVENT.log(Level.INFO,"prepare new record for:vin_idx_tbl; Detach VIN.."+cond2_pkinfo_vin); //prepare new record for:vin_idx_tbl; Detach VIN byte [] newVinIdxKey = Bytes.toBytes(token[4].concat(new_UPD)); Put NewVinIdx_kv = new Put(newVinIdxKey); //token[4] <-Arrived VIN NewVinIdx_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_UPD)); NewVinIdx_kv.addColumn(cf_idx,pkinfo_vin,PACK_INFO_TBL.get(pkinfo_vin)); LOGGER_EVENT.log(Level.INFO,Bytes.toString(pkinfo_upd),new_UPD); LOGGER_EVENT.log(Level.INFO,Bytes.toString(pkinfo_vin),Bytes.toString(PACK_INFO_TBL.get(pkinfo_vin))); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_vin_idx tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_pack_info_vin_idx,NewVinIdx_kv); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_vin_idx tbl Insert Finished for the event Line Number: "+line_cnt); //end vin_idx Updated for New record insert LOGGER_EVENT.log(Level.INFO,"vin_idx Updated for New record insert.."+Bytes.toString(newVinIdxKey)); //prepare new record for:upd_idx_tbl LOGGER_EVENT.log(Level.INFO,"Prepare new record for:upd_idx_tbl.."); byte [] newUpdIdxKey = Bytes.toBytes(new_UPD.concat(token[1])); Put NewUpdIdx_kv = new Put(newUpdIdxKey); //token[1] <- AP NewUpdIdx_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_UPD)); NewUpdIdx_kv.addColumn(cf_idx,pkinfo_alliancePk,PACK_INFO_TBL.get(pkinfo_orignalKey)); LOGGER_EVENT.log(Level.INFO,Bytes.toString(pkinfo_upd),new_UPD); LOGGER_EVENT.log(Level.INFO,Bytes.toString(pkinfo_alliancePk),Bytes.toString(PACK_INFO_TBL.get(pkinfo_orignalKey))); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_upd_idx tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_pack_info_upd_idx,NewUpdIdx_kv); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_upd_idx tbl Insert Finished for the event Line Number: "+line_cnt); //end UPD_idx Updated for New record insert LOGGER_EVENT.log(Level.INFO,"End UPD_idx Updated for New record insert.."+Bytes.toString(newUpdIdxKey)); //Preparing new record for packInfo: LOGGER_EVENT.log(Level.INFO,"Preparing new record for packInfo.."); PACK_INFO_TBL.put(pkinfo_vin,null); PACK_INFO_TBL.put(pkinfo_pvdate,null); PACK_INFO_TBL.put(pkinfo_upd,Bytes.toBytes(new_UPD)); PACK_INFO_TBL.put(pkinfo_rmvdate,Bytes.toBytes(token[2])); //token[2] <- battery remove date from pvlu rec PACK_INFO_TBL.put(PkInfo_FLD_r, Bytes.toBytes(token[10])); //Set inputEventFilename as pmlu event registering, AMO cols PACK_INFO_TBL.put(PkInfo_FLD_q, Bytes.toBytes(V_READ_DATE)); //Set ReadDate for this CSV registration, AMO cols //PACK_INFO_TBL.entrySet(); byte [] newPackInfoKey = Bytes.toBytes(token[1].concat(new_UPD)); Put NewPackInfo_kv = new Put(newPackInfoKey); //token[1] <- AP for (Entry<byte[], byte[]> entry : PACK_INFO_TBL.entrySet()) { byte[] key = entry.getKey(); byte[] value = entry.getValue(); LOGGER_EVENT.log(Level.INFO,Bytes.toString(key),Bytes.toString(value)); NewPackInfo_kv.addColumn(cf_pk,key, value); } LOGGER_EVENT.log(Level.INFO,"blms_pack_info tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_pack_info,NewPackInfo_kv); LOGGER_EVENT.log(Level.INFO,"blms_pack_info tbl Insert Finished for the event Line Number: "+line_cnt); //end of new record for packInfo insert LOGGER_EVENT.log(Level.INFO,"End of new record for packInfo insert.."+Bytes.toString(newPackInfoKey)); JOB_DETAILS.put(line_cnt,"success"); LOGGER_EVENT.log(Level.INFO,"Set:- JOB_DETAILS:"+String.valueOf(line_cnt)+"=success"); //@@Insert successful event in cash_processed_tbl LOGGER_EVENT.log(Level.INFO,"CashProcessed tbl Insert Started for the event Line Number: "+line_cnt); putIntoCashProcessed(token); LOGGER_EVENT.log(Level.INFO,"CashProcessed tbl Insert finished for the event Line Number: "+line_cnt); }else { LOGGER_EVENT.log(Level.INFO,"ERROR CASE: Arrived VIN is not attached to Arrived Rmoving Pack.."+token[1]); JOB_DETAILS.put(line_cnt,"ERROR CASE: Arrived VIN is not attached to Arrived Rmoving Pack.."+token[1]); } }else{ LOGGER_EVENT.log(Level.INFO,"ERROR CASE: BLMS PACK ID is not present in Pack_info tbl for removing Pack.."+token[1]); JOB_DETAILS.put(line_cnt,"ERROR CASE: BLMS PACK ID is not present in Pack_info tbl for removing Pack.."+token[1]); } }else { LOGGER_EVENT.log(Level.INFO,"ERROR CASE: Removing Pack is not Present in PackInfo Table.."+token[1]); JOB_DETAILS.put(line_cnt,"ERROR CASE: Removing Pack is not Present in PackInfo Table.."+token[1]); } }catch(Exception e) { LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); throw new Exception("SEVERE:Exception in pvluRemoveApply()....."+e.getMessage()); } }//end pvluRemoveApply() public static void pvluSetApply(String[] token) throws Exception{ try { LOGGER_EVENT.log(Level.INFO,"Inside Of pvluSetApply() for attaching AlliancePack: "+token[1]+" & Vin: "+token[4]); //1. Check AlliancePack, BlmsPack present for arrived event in "pk_info" tbl. //2. if 1 true, then check "vin" feild is empty for this arrived pack in "pk_info" tbl. //(arrived pack is not linked to any other vin.) //3. if 2 true, then check, Arrived "vin" is not already liked with any pack. (in vin_idx tbl) //4. if all above true, then apply the Set to packinfo: //4.1: After pk_info, update the : upd_idx, vin_idx_tbl, //Conditional (probe:timestamp > pkinfo:pvdate ) - probe:cmn, search1, search2, search3. //LOGGER_EVENT.log(Level.INFO,"Inside Of removeApply() for attaching AlliancePack: "+token[1]+" & Vin: ",token[4]); //TableName blms_pack_info_tbl = TableName.valueOf(hbaseNameSpace+":"+blms_pack_info); //Table blms_pack_info_tblConn = conn.getTable(blms_pack_info_tbl); /* blms_pack_info_tblConn = getTable(blms_pack_info); Scan scan = new Scan(); FilterList allFilters = new FilterList(FilterList.Operator.MUST_PASS_ALL); allFilters.addFilter(new PrefixFilter(Bytes.toBytes(token[1]))); scan.setFilter(allFilters); scan.setReversed(true); // read the latest available key and values for this AP scan.setMaxResultSize(1); LOGGER_EVENT.log(Level.INFO,"scan object to string before execute: "+scan.toString()); scanner = blms_pack_info_tblConn.getScanner(scan); Result result = scanner.next(); */ Result result = getLatestRecord(blms_pack_info, token[1]); if(result != null) { PACK_INFO_TBL = result.getFamilyMap(cf_pk); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_blms_id: "+Bytes.toString(PACK_INFO_TBL.get(pkinfo_blms_id))); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_vin: "+Bytes.toString(PACK_INFO_TBL.get(pkinfo_vin))); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_upd: "+Bytes.toString(PACK_INFO_TBL.get(pkinfo_upd))); LOGGER_EVENT.log(Level.INFO,"latest key value from packinfo pkinfo_orignalKey: "+Bytes.toString(PACK_INFO_TBL.get( pkinfo_orignalKey))); String cond1_blms_pack_id = Bytes.toString(PACK_INFO_TBL.get(pkinfo_blms_id)); String cond2_pkinfo_vin = Bytes.toString(PACK_INFO_TBL.get(pkinfo_vin)); String cond3_attaching_vin = token[4]; //arrived attachinging VIN LOGGER_EVENT.log(Level.INFO,"cond1_blms_pack_id: "+cond1_blms_pack_id); LOGGER_EVENT.log(Level.INFO,"cond2_pkinfo_vin: "+cond2_pkinfo_vin); LOGGER_EVENT.log(Level.INFO,"cond3_attaching_vin: "+cond3_attaching_vin); if(cond1_blms_pack_id !=null && !cond1_blms_pack_id.isEmpty()) { LOGGER_EVENT.log(Level.INFO,"Packinfo Contains value for BLMSPACK_ID.."+cond1_blms_pack_id); LOGGER_EVENT.log(Level.INFO,"Next check : vin columns is null or not present for arrived attaching pack in pkinfo tbl: "+token[1]); if(cond2_pkinfo_vin ==null || cond2_pkinfo_vin.isEmpty()) { LOGGER_EVENT.log(Level.INFO,"Arrived Pack is not attached to any other VIN: "+token[1]); LOGGER_EVENT.log(Level.INFO,"Next check arrived VIN is not attached to any other Pack: "+token[4]); /* blms_pack_info_vin_idx_tblConn = getTable(blms_pack_info_vin_idx); Scan vinIdxScan = new Scan(); LOGGER_EVENT.info("Set start Row for scan: "+token[4]); //arrived VIN FilterList vinIdxallFilters = new FilterList(FilterList.Operator.MUST_PASS_ALL); vinIdxallFilters.addFilter(new PrefixFilter(Bytes.toBytes(token[4]))); vinIdxScan.setFilter(vinIdxallFilters); vinIdxScan.setReversed(true); // read the latest available key and values for this AP vinIdxScan.setMaxResultSize(1); LOGGER_EVENT.info("scan object to string before execute: "+vinIdxScan.toString()); vinIdxScanner = blms_pack_info_vin_idx_tblConn.getScanner(vinIdxScan); //logic to check if VIN is already attached to anther nissan pack: Result VinIdxresult = vinIdxScanner.next(); //retrive latest record for this VIN if present. */ Result VinIdxresult = getLatestRecord(blms_pack_info_vin_idx, token[4]); if(VinIdxresult != null) { VIN_IDX_TBL = VinIdxresult.getFamilyMap(cf_idx); LOGGER_EVENT.log(Level.INFO,"latest key value from VIN_IDX TBL for pvlu_vin: "+Bytes.toString(VIN_IDX_TBL.get(pkinfo_vin))); LOGGER_EVENT.log(Level.INFO,"latest key value from VIN_IDX TBL for already attached NissanPack: "+Bytes.toString(VIN_IDX_TBL.get(pkinfo_nissanPack))); //Check AP is Attached or Nissanpack attached(pvlc) to this VIN String vinIdxcond1_pkinfo_nissanPack= Bytes.toString(VIN_IDX_TBL.get(pkinfo_nissanPack)); LOGGER_EVENT.log(Level.INFO,"vinIdxcond1_pkinfo_nissanPack: "+vinIdxcond1_pkinfo_nissanPack); String vinIdxcond2_alliancePk= Bytes.toString(VIN_IDX_TBL.get(pkinfo_alliancePk)); LOGGER_EVENT.log(Level.INFO,"vinIdxcond2_alliancePk: "+vinIdxcond2_alliancePk); if((vinIdxcond1_pkinfo_nissanPack ==null || cond2_pkinfo_vin.isEmpty()) || (vinIdxcond2_alliancePk ==null || vinIdxcond2_alliancePk.isEmpty())) { LOGGER_EVENT.log(Level.INFO,"Arrived Vin is not attached to another nissan Pack: "+token[4]); //1. Update the PACKINFO tbl //Preparing new record for packInfo: LOGGER_EVENT.log(Level.INFO,"Preparing new record for packInfo.."); PACK_INFO_TBL.put(pkinfo_vin,Bytes.toBytes(token[4])); //set the arrived VIN PACK_INFO_TBL.put(pkinfo_pvdate,Bytes.toBytes(token[2])); //set the Battery setting Date as pvdate PACK_INFO_TBL.put(pkinfo_upd,Bytes.toBytes(new_UPD)); // new UPD date for record PACK_INFO_TBL.put(PkInfo_FLD_r, Bytes.toBytes(token[10])); //Set inputEventFilename as pmlu event registering, AMO cols PACK_INFO_TBL.put(PkInfo_FLD_q, Bytes.toBytes(V_READ_DATE)); //Set ReadDate for this CSV registration, AMO cols byte [] newPackInfoKey = Bytes.toBytes(token[1].concat(new_UPD)); //PACK_INFO_TBL.put(pkinfo_rmvdate,Bytes.toBytes(token[2])); //token[2] <- battery remove date from pvlu rec Put NewPackInfo_kv = new Put(newPackInfoKey); //token[1] <- AP for (Entry<byte[], byte[]> entry : PACK_INFO_TBL.entrySet()) { byte[] key = entry.getKey(); byte[] value = entry.getValue(); LOGGER_EVENT.log(Level.INFO,Bytes.toString(key),Bytes.toString(value)); NewPackInfo_kv.addColumn(cf_pk,key, value); } LOGGER_EVENT.log(Level.INFO,"blms_pack_info tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_pack_info,NewPackInfo_kv); LOGGER_EVENT.log(Level.INFO,"blms_pack_info tbl Insert Finished for the event Line Number: "+line_cnt); //end of new record for packInfo insert LOGGER_EVENT.log(Level.INFO,"End of new record for packInfo insert:"+Bytes.toString(newPackInfoKey)); //2. Update the UPD_IDX table // Prepare new record for:upd_idx_tbl LOGGER_EVENT.log(Level.INFO,"Prepare new record for:upd_idx_tbl: "+token[1]); byte [] newUpdKey = Bytes.toBytes(new_UPD.concat(token[1])); Put NewUpdIdx_kv = new Put(newUpdKey); //token[1] <- AP NewUpdIdx_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_UPD)); NewUpdIdx_kv.addColumn(cf_idx,pkinfo_alliancePk,PACK_INFO_TBL.get(pkinfo_orignalKey)); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_upd_idx tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_pack_info_upd_idx,NewUpdIdx_kv); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_upd_idx tbl Insert Finished for the event Line Number: "+line_cnt); //end UPD_idx Updated for New record insert LOGGER_EVENT.log(Level.INFO,"End UPD_idx Updated for New record insert: "+Bytes.toString(newUpdKey)); //3. Update the VIN_IDX tbl /* b <- Alliance Pack1 g <- T_UPD_DATE1 f <- Battery setting Date c <- N_Pack(To check PVLC) d <- VIN */ LOGGER_EVENT.log(Level.INFO,"Prepare new record for:vin_idx_tbl; Attach VIN: "+token[4]); //Prepare new record for:vin_idx_tbl; byte [] newVinKey = Bytes.toBytes(token[4].concat(new_UPD)); Put NewVinIdx_kv = new Put(newVinKey); //token[4] <-Arrived VIN NewVinIdx_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_UPD)); //new_UPD NewVinIdx_kv.addColumn(cf_idx,pkinfo_vin,Bytes.toBytes(token[4])); //VIN column NewVinIdx_kv.addColumn(cf_idx,pkinfo_alliancePk,Bytes.toBytes(token[1])); //Attached AP NewVinIdx_kv.addColumn(cf_idx,pkinfo_pvdate,Bytes.toBytes(token[2])); //Battery Setting Date NewVinIdx_kv.addColumn(cf_idx,pkinfo_nissanPack,PACK_INFO_TBL.get(pkinfo_nissanPack)); //NissanPack LOGGER_EVENT.log(Level.INFO,"blms_pack_info_vin_idx tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_pack_info_vin_idx,NewVinIdx_kv); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_vin_idx tbl Insert Finished for the event Line Number: "+line_cnt); //end vin_idx Updated for New record insert LOGGER_EVENT.log(Level.INFO,"vin_idx Updated for New record insert: "+Bytes.toString(newVinKey)); //4. Enrich the Valid Probe & its idx tbls for this VIN-PACK attachment LOGGER_EVENT.log(Level.INFO,"blms_probe enrichment Started for VIN: "+token[4]); blms_probe_tblConn = getTable(blms_probe); Scan probeScan = new Scan(); LOGGER_EVENT.log(Level.INFO,"Set start Row for scan: "+token[4]+token[2]); probeScan.setStartRow(Bytes.toBytes(token[4]+token[2])); probeScan.addFamily(cf_cmn); probeScan.setBatch(15); probeScan.setCaching(1000); //pvlu_vin+pvlu_setpvDate <- VIN+PVdate(new attaching pvdate, utc converted) FilterList probeAllFilters = new FilterList(FilterList.Operator.MUST_PASS_ALL); probeAllFilters.addFilter(new PrefixFilter(Bytes.toBytes(token[4]))); probeScan.setFilter(probeAllFilters); //scan.setReversed(true); // read the latest available key and values for this AP //scan.setMaxResultSize(1000000000); LOGGER_EVENT.log(Level.INFO,"scan object to string before execute: "+probeScan.toString()); ProbeScanner = blms_probe_tblConn.getScanner(probeScan); //ResultScanner ProbeScanner = getProbeScanner(token[4], token[2], conn); //token[4] :vin, token[2]: pvdate List<Put> puts_probe = new ArrayList<Put>(); List<Put> puts_probe_search1 = new ArrayList<Put>(); List<Put> puts_probe_search2 = new ArrayList<Put>(); List<Put> puts_probe_search3 = new ArrayList<Put>(); List<Delete> delete_probe_search1 = new ArrayList<Delete>(); List<Delete> delete_probe_search2 = new ArrayList<Delete>(); List<Delete> delete_probe_search3 = new ArrayList<Delete>(); for (Result ProbeResult = ProbeScanner.next(); ProbeResult != null; ProbeResult = ProbeScanner.next()) { //4. Update the PROBE and respective idx tbl. //LOGGER_EVENT.info("Check condition for: Probe,search1,search2,search3 updates.."); // for blms_probe, directly issue put for all rowprifix and start row matched. BLMS_PROBE_TBL = ProbeResult.getFamilyMap(cf_cmn); String ProbeKey = Bytes.toString(ProbeResult.getRow()); LOGGER_EVENT.log(Level.INFO,"Probe-RokwKey for Enrichment: "+ProbeKey); //Enrichment for "cmn cf" Put NewProbe_kv = new Put(ProbeResult.getRow()); //VIN+TIMESTAMP NewProbe_kv.addColumn(cf_cmn,pkinfo_blms_id,PACK_INFO_TBL.get(pkinfo_blms_id)); NewProbe_kv.addColumn(cf_cmn,pkinfo_alliancePk,PACK_INFO_TBL.get(pkinfo_alliancePk)); NewProbe_kv.addColumn(cf_cmn,pkinfo_nissanPack,PACK_INFO_TBL.get(pkinfo_nissanPack)); NewProbe_kv.addColumn(cf_cmn,pkinfo_vin,Bytes.toBytes(token[4])); //vin NewProbe_kv.addColumn(cf_cmn,pkinfo_PackDateKey,PACK_INFO_TBL.get(pkinfo_PackDateKey)); NewProbe_kv.addColumn(cf_cmn,pkinfo_pvdate,Bytes.toBytes(token[2])); //BatterysettingDate NewProbe_kv.addColumn(cf_cmn,pkinfo_upd,Bytes.toBytes(new_UPD));//new upd //NewProbe_kv.addColumn(cf_cmn,pkinfo_orignalKey,Bytes.toBytes(new_UPD)); //NewProbe_kv.addColumn(cf_cmn,pkinfo_Timestamp,Bytes.toBytes(new_UPD)); puts_probe.add(NewProbe_kv); //--end of probe enrichment //LOGGER_EVENT.log(Level.INFO,"Preparing Corresponding Index Tbl Updates For PROBE KEY Started: "+ProbeKey); String new_probe_vin = token[4]; //new vin String new_probe_APack = Bytes.toString(PACK_INFO_TBL.get(pkinfo_alliancePk)); String new_probe_upd = new_UPD; String new_probe_ts = Bytes.toString(BLMS_PROBE_TBL.get(pkinfo_Timestamp)); //Start search1 updates using new key from probe: cmn cf String newSearch1Key = new_probe_APack.concat(new_probe_upd).concat(new_probe_ts); Put NewProbe_Search1_kv = new Put(Bytes.toBytes(newSearch1Key)); //VIN+TIMESTAMP NewProbe_Search1_kv.addColumn(cf_idx,pkinfo_vin,Bytes.toBytes(new_probe_vin)); NewProbe_Search1_kv.addColumn(cf_idx,pkinfo_Timestamp,Bytes.toBytes(new_probe_ts)); NewProbe_Search1_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_probe_upd)); NewProbe_Search1_kv.addColumn(cf_idx,pkinfo_alliancePk,Bytes.toBytes(new_probe_APack)); puts_probe_search1.add(NewProbe_Search1_kv); //----end for search1 //Start search2 updates using new key from probe: cmn cf String newSearch2Key = new_probe_upd.concat(new_probe_APack).concat(new_probe_ts); Put NewProbe_Search2_kv = new Put(Bytes.toBytes(newSearch2Key)); //VIN+TIMESTAMP NewProbe_Search2_kv.addColumn(cf_idx,pkinfo_vin,Bytes.toBytes(new_probe_vin)); NewProbe_Search2_kv.addColumn(cf_idx,pkinfo_Timestamp,Bytes.toBytes(new_probe_ts)); NewProbe_Search2_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_probe_upd)); NewProbe_Search2_kv.addColumn(cf_idx,pkinfo_alliancePk,Bytes.toBytes(new_probe_APack)); puts_probe_search2.add(NewProbe_Search2_kv); //----end for search2 //Start search3 updates using new key from probe: cmn cf String newSearch3Key = new_probe_upd.concat(new_probe_vin).concat(new_probe_ts); Put NewProbe_Search3_kv = new Put(Bytes.toBytes(newSearch3Key)); //VIN+TIMESTAMP NewProbe_Search3_kv.addColumn(cf_idx,pkinfo_vin,Bytes.toBytes(new_probe_vin)); NewProbe_Search3_kv.addColumn(cf_idx,pkinfo_Timestamp,Bytes.toBytes(new_probe_ts)); NewProbe_Search3_kv.addColumn(cf_idx,pkinfo_upd,Bytes.toBytes(new_probe_upd)); //NewProbe_Search3_kv.addColumn(cf_idx,pkinfo_alliancePk,Bytes.toBytes(new_probe_APack)); puts_probe_search3.add(NewProbe_Search3_kv); //----end for search3 //collect old keys for search1, search2, search3 for deletion String old_probe_vin = Bytes.toString(BLMS_PROBE_TBL.get(pkinfo_orignalKey)); String old_probe_APack = Bytes.toString(BLMS_PROBE_TBL.get(pkinfo_alliancePk)); String old_probe_upd = Bytes.toString(BLMS_PROBE_TBL.get(pkinfo_upd)); String old_probe_ts = Bytes.toString(BLMS_PROBE_TBL.get(pkinfo_Timestamp)); if(old_probe_APack!=null && !old_probe_APack.isEmpty() && old_probe_upd!=null && !old_probe_upd.isEmpty() && old_probe_ts!=null && !old_probe_ts.isEmpty()) { //Search1:ap+upd+ts String oldSearch1Key = old_probe_APack.concat(old_probe_upd).concat(old_probe_ts); Delete d_old_search1 = new Delete(Bytes.toBytes(oldSearch1Key)); delete_probe_search1.add(d_old_search1); //Search2:upd+ap+ts String oldSearch2Key = old_probe_upd.concat(old_probe_APack).concat(old_probe_ts); Delete d_old_search2 = new Delete(Bytes.toBytes(oldSearch2Key)); delete_probe_search2.add(d_old_search2); } //Search3:upd+vin+ts String oldSearch3Key = old_probe_upd.concat(old_probe_vin).concat(old_probe_ts); Delete d_old_search3 = new Delete(Bytes.toBytes(oldSearch3Key)); delete_probe_search3.add(d_old_search3); } //put new record , enrichment LOGGER_EVENT.log(Level.INFO,"blms_probe tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_probe,puts_probe); LOGGER_EVENT.log(Level.INFO,"blms_probe tbl Insert Finished for the event Line Number: "+line_cnt); //LOGGER_EVENT.log(Level.INFO,"PROBE_TBL-PROBE KEY ENRICHED..: "+ProbeKey); //LOGGER_EVENT.log(Level.INFO,"Starting Index Tbls updates for PROBE KEY: "+ProbeKey); LOGGER_EVENT.log(Level.INFO,"Starting Index Tbls updates for Enriched PROBE KEY Set.. "); LOGGER_EVENT.log(Level.INFO,"blms_probe_search1 tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_probe_search1,puts_probe_search1); LOGGER_EVENT.log(Level.INFO,"blms_probe_search1 tbl Insert Finished for the event Line Number: "+line_cnt); //delete old record,after Enrichment, update the idx table for new mapping LOGGER_EVENT.log(Level.INFO,"blms_probe_search1 tbl delete for Old Keys, Started for the event Line Number: "+line_cnt); deleteFromTable(blms_probe_search1,delete_probe_search1); LOGGER_EVENT.log(Level.INFO,"blms_probe_search1 tbl delete for Old Keys, Finished for the event Line Number: "+line_cnt); //LOGGER_EVENT.log(Level.INFO,"UPDATE IDX:newSearch1Key: "+newSearch1Key); //LOGGER_EVENT.log(Level.INFO,"DELETE IDX:oldSearch1Key: "+oldSearch1Key); LOGGER_EVENT.log(Level.INFO,"blms_probe_search2 tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_probe_search2,puts_probe_search2); LOGGER_EVENT.log(Level.INFO,"blms_probe_search2 tbl Insert Finished for the event Line Number: "+line_cnt); LOGGER_EVENT.log(Level.INFO,"blms_probe_search2 tbl old key delete, Started for the event Line Number: "+line_cnt); deleteFromTable(blms_probe_search2,delete_probe_search2); LOGGER_EVENT.log(Level.INFO,"blms_probe_search2 tbl old key delete, Finished for the event Line Number: "+line_cnt); //LOGGER_EVENT.log(Level.INFO,"UPDATE IDX:newSearch2Key: "+newSearch2Key); //LOGGER_EVENT.log(Level.INFO,"DELETE IDX:oldSearch1Key: "+oldSearch2Key); LOGGER_EVENT.log(Level.INFO,"blms_probe_search3 tbl Insert Started for the event Line Number: "+line_cnt); putInTable(blms_probe_search3,puts_probe_search3); LOGGER_EVENT.log(Level.INFO,"blms_probe_search3 tbl Insert finished for the event Line Number: "+line_cnt); LOGGER_EVENT.log(Level.INFO,"blms_probe_search3 tbl delete for old key, Started for the event Line Number: "+line_cnt); deleteFromTable(blms_probe_search3,delete_probe_search3); LOGGER_EVENT.log(Level.INFO,"blms_probe_search3 tbl delete for old key, Finished for the event Line Number: "+line_cnt); //LOGGER_EVENT.log(Level.INFO,"UPDATE IDX:newSearch3Key: "+newSearch3Key); //LOGGER_EVENT.log(Level.INFO,"DELETE IDX:oldSearch1Key: "+oldSearch3Key); //@@Insert successful event in cash_processed_tbl LOGGER_EVENT.log(Level.INFO,"CashProcessed tbl Insert Started for the event Line Number: "+line_cnt); putIntoCashProcessed(token); LOGGER_EVENT.log(Level.INFO,"CashProcessed tbl Insert finished for the event Line Number: "+line_cnt); //delete old record,after Enrichment, update the idx table for new mapping //end blms_probe Enrichment LOGGER_EVENT.log(Level.INFO,"BlMS_PROBE Enrichment finished for all matched Probe keys with PVLU Events.."); JOB_DETAILS.put(line_cnt,"success"); LOGGER_EVENT.log(Level.INFO,"Set:- JOB_DETAILS:"+String.valueOf(line_cnt)+"=success"); //Put all successfully processed PVLU into "Cash_event_Processed_table here.." }else if(( vinIdxcond1_pkinfo_nissanPack !=null && (!vinIdxcond1_pkinfo_nissanPack.isEmpty())) || (vinIdxcond2_alliancePk !=null && !vinIdxcond2_alliancePk.isEmpty())) { LOGGER_EVENT.log(Level.INFO,"ERROR CASE: Arrived Vin is already attached to another Nissan-Pack: "+vinIdxcond1_pkinfo_nissanPack); LOGGER_EVENT.log(Level.INFO,"ERROR CASE: Arrived Vin is already attached to another Alliance-Pack: "+vinIdxcond2_alliancePk); JOB_DETAILS.put(line_cnt,"ERROR CASE: Arrived Vin is already attached to another Alliance-Pack:"+vinIdxcond2_alliancePk); }//end Arrived Vin is not attached to any Pack. }else{//end vin_idx_tbl ==null? LOGGER_EVENT.log(Level.INFO,"ERROR: Table Mapping Issue, Inconsistent Index with Pack Info tbl for VIN IDX.."); JOB_DETAILS.put(line_cnt,"ERROR: Table Mapping Issue, Inconsistent Index with Pack Info tbl for VIN IDX.."); //throw new IOException("ERROR: Table Mapping Issue, Inconsistent Index with Pack Info tbl for VIN IDX.."); } }else { //end arrived pack not attached to any vin LOGGER_EVENT.log(Level.INFO,"ERROR CASE:Attaching arrived pack is already attached/has value for vin.."+cond2_pkinfo_vin); JOB_DETAILS.put(line_cnt,"ERROR CASE:Attaching arrived pack is already attached/has value for vin.."+cond2_pkinfo_vin); } }else { //end arrived attaching AP not has blmsPack LOGGER_EVENT.log(Level.INFO,"ERROR CASE:Pack_blms_id column in pack_info_tbl is empty.."+token[1]); JOB_DETAILS.put(line_cnt,"ERROR CASE:Pack_blms_id column in pack_info_tbl is empty.."+token[1]); } }else { //end Packinfo result ==null? LOGGER_EVENT.log(Level.INFO,"ERROR CASE:Key not found for this attaching Pack in PackInfo.."+token[1]); JOB_DETAILS.put(line_cnt,"ERROR CASE:Key not found for this attaching Pack in PackInfo.."+token[1]); } }catch(Exception e) { LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); throw new Exception("SEVERE:Exception in pvluSetApply()...."+e.getMessage()); } }//end pvluSetApply() public static void putInTable(String blms_tbl, Put PutRowList) throws Exception{ try { //TblBlmsConn = getTable(blms_tbl); //TblBlmsConn.put(PutRowList); TblBlmsConn = getTable(blms_tbl); RowMutations mutations = new RowMutations(PutRowList.getRow()); mutations.add(PutRowList); TblBlmsConn.mutateRow(mutations); TblBlmsConn.close(); }catch (RetriesExhaustedWithDetailsException e) { int numErrors = e.getNumExceptions(); // Error Handle failed operations. LOGGER_EVENT.log(Level.SEVERE,"Number of exceptions: " + numErrors); for (int n = 0; n < numErrors; n++) { LOGGER_EVENT.log(Level.SEVERE,"Cause[" + n + "]: " + e.getCause(n)); //System.out.println("Cause[" + n + "]: " + e.getCause(n)); LOGGER_EVENT.log(Level.SEVERE,"Hostname[" + n + "]: " + e.getHostnamePort(n)); //System.out.println("Hostname[" + n + "]: " + e.getHostnamePort(n)); LOGGER_EVENT.log(Level.SEVERE,"Row[" + n + "]: " + e.getRow(n)); //System.out.println("Row[" + n + "]: " + e.getRow(n)); // ErrorPut Gain access to the failed operation. } LOGGER_EVENT.log(Level.SEVERE,"Cluster issues: " + e.mayHaveClusterIssues()); LOGGER_EVENT.log(Level.SEVERE,"Description: " + e.getExhaustiveDescription()); //releaseResources(); throw new Exception("SEVERE:Exception in putInTable()...."+e.getMessage()); }catch(Exception e){ LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); //releaseResources(); throw new Exception("SEVERE:Exception in putInTable()...."+e.getMessage()); } }//end putTable() public static void putInTable(String blms_tbl, List<Put> PutRowList) throws Exception { try { TblBlmsConn = getTable(blms_tbl); TblBlmsConn.put(PutRowList); TblBlmsConn.close(); /* TblBlmsConn = getTable(blms_tbl); int i = 0; while(i<=PutRowList.size()) { RowMutations mutations = new RowMutations(PutRowList.get(i).getRow()); mutations.add(PutRowList.get(i)); TblBlmsConn.mutateRow(mutations); i++; } TblBlmsConn.close(); */ }catch (RetriesExhaustedWithDetailsException e) { int numErrors = e.getNumExceptions(); // Error Handle failed operations. LOGGER_EVENT.log(Level.SEVERE,"Number of exceptions: " + numErrors); for (int n = 0; n < numErrors; n++) { LOGGER_EVENT.log(Level.SEVERE,"Cause[" + n + "]: " + e.getCause(n)); //System.out.println("Cause[" + n + "]: " + e.getCause(n)); LOGGER_EVENT.log(Level.SEVERE,"Hostname[" + n + "]: " + e.getHostnamePort(n)); //System.out.println("Hostname[" + n + "]: " + e.getHostnamePort(n)); LOGGER_EVENT.log(Level.SEVERE,"Row[" + n + "]: " + e.getRow(n)); //System.out.println("Row[" + n + "]: " + e.getRow(n)); // ErrorPut Gain access to the failed operation. } LOGGER_EVENT.log(Level.SEVERE,"Cluster issues: " + e.mayHaveClusterIssues()); LOGGER_EVENT.log(Level.SEVERE,"Description: " + e.getExhaustiveDescription()); throw new Exception("SEVERE:Exception in putInTable()...."+e.getMessage()); }catch(Exception e){ LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); throw new Exception("SEVERE:Exception in putInTable()...."+e.getMessage()); } }//end putTable() public static void deleteFromTable(String DeleteFromTable, List<Delete> DeleteRowList) throws Exception{ try { TblBlmsConn = getTable(DeleteFromTable); if(!DeleteFromTable.isEmpty()) TblBlmsConn.delete(DeleteRowList); TblBlmsConn.close(); }catch (RetriesExhaustedWithDetailsException e) { int numErrors = e.getNumExceptions(); // Error Handle failed operations. LOGGER_EVENT.log(Level.SEVERE,"Number of exceptions: " + numErrors); for (int n = 0; n < numErrors; n++) { LOGGER_EVENT.log(Level.SEVERE,"Cause[" + n + "]: " + e.getCause(n)); //System.out.println("Cause[" + n + "]: " + e.getCause(n)); LOGGER_EVENT.log(Level.SEVERE,"Hostname[" + n + "]: " + e.getHostnamePort(n)); //System.out.println("Hostname[" + n + "]: " + e.getHostnamePort(n)); LOGGER_EVENT.log(Level.SEVERE,"Row[" + n + "]: " + e.getRow(n)); //System.out.println("Row[" + n + "]: " + e.getRow(n)); // ErrorPut Gain access to the failed operation. } LOGGER_EVENT.log(Level.SEVERE,"Cluster issues: " + e.mayHaveClusterIssues()); LOGGER_EVENT.log(Level.SEVERE,"Description: " + e.getExhaustiveDescription()); //releaseResources(); throw new Exception("SEVERE:Exception in deleteFromTable()...."+e.getMessage()); }catch(Exception e){ LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); //releaseResources(); throw new Exception("SEVERE:Exception in deleteFromTable()...."+e.getMessage()); } }//end deleteFromTable public static void applyUpdates() throws Exception{ try { conf = getHDFSConf(); fs = FileSystem.get(conf); LOGGER_EVENT.log(Level.INFO,"HDFS file path for pvlu input:-"+filePath); if(!fs.exists(filePath)) { LOGGER_EVENT.log(Level.SEVERE,"INVALID ARGUMENTS: Path doest not exist.."); throw new Exception("SEVERE:INVALID ARGUMENTS: Path doest not exist.."); //LOGGER_EVENT.log(Level.INFO,"INVALID ARGUMENTS: Path doest not exist.."); //releaseResources(); //System.exit(1); }else { LOGGER_EVENT.log(Level.INFO,"Input FilePath Present:"+filePath); hdfsOut = FileSystem.get(conf); outPutStream = hdfsOut.create(jdCSVFilePath, true); FileStatus[] status = fs.listStatus(filePath); String line; for (int i = 0; i < status.length; i++) { LOGGER_EVENT.log(Level.INFO,"subfilepath:"+status[i].getPath().getName()); br = new BufferedReader(new InputStreamReader(fs.open(status[i].getPath()))); LOGGER_EVENT.log(Level.INFO,"In BufferReader..subfilepath:"+status[i].getPath().toString()); while ((line = br.readLine()) != null) { line_cnt++; String token[] = line.split("\t"); LOGGER_EVENT.log(Level.INFO,"token lenght:-"+token.length); LOGGER_EVENT.log(Level.INFO,"input lineCnt taken for processing: "+line_cnt); LOGGER_EVENT.log(Level.INFO,"Input Event Record for Processing: "+token[0]+" "+token[1]+" "+token[2]+" "+token[3]+" "+token[4]); if(token[3].equals(event_remove_flag) && token[0].equals(pvlu_event_id)) { LOGGER_EVENT.log(Level.INFO,"Removing vin:-"+token[4]+" Pack:-"+token[1]); LOGGER_EVENT.log(Level.INFO,"Calling pvluRemoveApply()"); pvluRemoveApply(token); LOGGER_EVENT.log(Level.INFO,"pvluRemoveApply() Process:Done for Event Line number: "+line_cnt); }else if(token[3].equals(event_set_flag) && token[0].equals(pvlu_event_id)) { LOGGER_EVENT.log(Level.INFO,"Attaching vin:-"+token[4]+" Pack:-"+token[1]); LOGGER_EVENT.log(Level.INFO,"Calling pvluSetApply()"); pvluSetApply(token); LOGGER_EVENT.log(Level.INFO,"pvluSetApply() Process:Done for Event Line number: "+line_cnt); }//end pvlu set ProcessErrorEvent(line); }//while end }//End of file list }//end of else file exist }catch(Exception e) { //LOGGER_EVENT.log(Level.SEVERE,"Error In getHDFSConf(), failed to read the hdfs filesystem using provided conf.."); LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); //releaseResources(); throw new Exception("SEVERE:Exception in applyUpdates()....."+e.getMessage()); } LOGGER_EVENT.log(Level.INFO,"JobDetail Log successfully created on HDFS : "+jdCSVFilePath); } private static void ProcessErrorEvent(String line) throws Exception{ String record = JOB_DETAILS.get(line_cnt); if (record.compareTo("success")==0){ LOGGER_EVENT.log(Level.INFO,"SUCCESS, Event Line number: "+line_cnt); }else { LOGGER_EVENT.log(Level.INFO,"ERROR, Event Line number: "+line_cnt); } LOGGER_EVENT.log(Level.INFO,"Writing to CSV... "); WriteToCsvErrFile(line); } private static void WriteToCsvErrFile(String line) throws Exception{ String JDline = line + "\t" + JOB_DETAILS.get(line_cnt) + "\t"; try { outPutStream.writeUTF(JDline); outPutStream.writeUTF("\n"); outPutStream.flush(); LOGGER_EVENT.log(Level.INFO,"Successfuly inserted into CSV, for Event line number: "+line_cnt); } catch (Exception e) { //LOGGER_EVENT.log(Level.SEVERE,"Error In WriteToCsvErrFile(), failed to Write into hdfs filesystem.."+jdCSVFilePath); LOGGER_EVENT.log(Level.SEVERE,e.toString(),e); //releaseResources(); throw new Exception("SEVERE:Exception in WriteToCsvErrFile()....."+e.getMessage()); } } private static Table getTable(String tblName) throws IOException { TableName blms_tbl = TableName.valueOf(hbaseNameSpace+":"+tblName); Table blms_tblConn = conn.getTable(blms_tbl); return blms_tblConn; } private static Configuration getHDFSConf() throws IOException { Configuration config = new Configuration(); config.set("fs.defaultFS", defaultFS); config.set("hadoop.security.authentication", hadoopSecurityAuthentication); UserGroupInformation.setConfiguration(config); // Subject is taken from current user context UserGroupInformation.loginUserFromSubject(null); return config; } private static Configuration getHBASEConf() throws IOException { Configuration configuration = HBaseConfiguration.create(); configuration.set("hbase.zookeeper.property.clientPort", hbaseZookeeperPort); configuration.set("hbase.zookeeper.quorum", hbaseZookeeperQuorum1); configuration.set("zookeeper.znode.parent", hbaseZnodeParent); configuration.set("hbase.master.port", hbaseMasterPort); configuration.set("hbase.master", hbaseMaster); configuration.set("hbase.rpc.timeout", hbaseRpcTimeout); configuration.set("hbase.client.scanner.timeout.period", hbaseClientScannerTimeout); configuration.set("hbase.cells.scanned.per.heartbeat.check", hbaseCellsScannedPerHeartBeatCheck); configuration.set("hbase.client.operation.timeout", hbaseClientOperationTimeout); return configuration; } public static void putIntoCashProcessed(String[] token) throws Exception{ //put all successfully processed pvlu input into table String newCPKey = new_UPD.concat(token[1]).concat(token[4]); Put NewCashProcessed_kv = new Put(Bytes.toBytes(newCPKey)); //token[1] <-AP;token[4] <- vin NewCashProcessed_kv.addColumn(cf_cp,pkinfo_event_id,Bytes.toBytes(token[0])); //token[0]: event_type. NewCashProcessed_kv.addColumn(cf_cp,pkinfo_orignalKey,Bytes.toBytes(token[1])); NewCashProcessed_kv.addColumn(cf_cp,pkinfo_Timestamp,Bytes.toBytes(token[2])); //token[2] <- battery Setting Date NewCashProcessed_kv.addColumn(cf_cp,pkinfo_upd,Bytes.toBytes(new_UPD)); NewCashProcessed_kv.addColumn(cf_cp,CP_V_COL_001,Bytes.toBytes(token[3])); NewCashProcessed_kv.addColumn(cf_cp,CP_V_COL_002,Bytes.toBytes(token[4])); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_r, Bytes.toBytes(token[10])); //Set inputEventFilename as pmlu event registering NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_q, Bytes.toBytes(V_READ_DATE)); //Set ReadDate for this CSV registration. NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_s, Bytes.toBytes(PkInfo_VAL_s)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_t, Bytes.toBytes(PkInfo_VAL_t)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_u, Bytes.toBytes(new_UPD)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_v, Bytes.toBytes(PkInfo_VAL_v)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_w, Bytes.toBytes(PkInfo_VAL_w)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_x, Bytes.toBytes(PkInfo_VAL_x)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_h, Bytes.toBytes(PkInfo_VAL_h)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_i, Bytes.toBytes(PkInfo_VAL_i)); NewCashProcessed_kv.addColumn(cf_cp,PkInfo_FLD_j, Bytes.toBytes(PkInfo_VAL_j)); putInTable(blms_cache_processed,NewCashProcessed_kv); LOGGER_EVENT.log(Level.INFO,"newCPKey Added : "+newCPKey); } public final static void getResources(String WF_ID) throws SecurityException, IOException { SimpleFormatter formatter = new SimpleFormatter(); //Handler for PMLU //fh_pvlu = new FileHandler(PVLU_UPDATES_LOG+"_" + new_UPD.replaceAll("[^0-9]", "")); fh_pvlu = new FileHandler(PVLU_UPDATES_LOG+"_" + WF_ID.replaceAll("[^0-9]", "")); fh_pvlu.setFormatter(formatter); LOGGER_EVENT.addHandler(fh_pvlu); LOGGER_EVENT.setUseParentHandlers(false); ExecutorService executor = Executors.newFixedThreadPool(1); conn = ConnectionFactory.createConnection(getHBASEConf(),executor); } private static void releaseResources() throws Exception{ try { if(ProbeScanner!=null) { ProbeScanner.close(); LOGGER_EVENT.log(Level.INFO,"ProbeScanner.close() executed..."); } if(mc_scanner!=null) { mc_scanner.close(); LOGGER_EVENT.log(Level.INFO,"mc_scanner.close() executed..."); } if(scanner!=null) { scanner.close(); LOGGER_EVENT.log(Level.INFO,"scanner.close() executed..."); } if(vinIdxScanner !=null) { vinIdxScanner.close(); LOGGER_EVENT.log(Level.INFO,"vinIdxScanner.close() executed..."); } if(vin_scanner!=null) { vin_scanner.close(); LOGGER_EVENT.log(Level.INFO,"vin_scanner.close() executed..."); } if(blms_pack_info_tblConn!=null) { blms_pack_info_tblConn.close(); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_tblConn.close() executed..."); } if(blms_mc_tblConn!=null) { blms_mc_tblConn.close(); LOGGER_EVENT.log(Level.INFO,"blms_mc_tblConn.close() executed..."); } if(TblBlmsConn!=null) { TblBlmsConn.close(); LOGGER_EVENT.log(Level.INFO,"TblBlmsConn.close() executed..."); } if(blms_pack_info_vin_idx_tblConn!=null) { blms_pack_info_vin_idx_tblConn.close(); LOGGER_EVENT.log(Level.INFO,"blms_pack_info_vin_idx_tblConn.close() executed..."); } if(blms_probe_tblConn!=null) { blms_probe_tblConn.close(); LOGGER_EVENT.log(Level.INFO,"blms_probe_tblConn.close() executed..."); } if(br!=null) { br.close(); LOGGER_EVENT.log(Level.INFO,"br.close() executed..."); } if(outPutStream!=null) { outPutStream.close(); LOGGER_EVENT.log(Level.INFO,"outPutStream.close() executed..."); } if(hdfsOut!=null) { hdfsOut.close(); LOGGER_EVENT.log(Level.INFO,"hdfsOut.close() executed..."); } if(fs!=null) { fs.close(); LOGGER_EVENT.log(Level.INFO,"fs.close() executed..."); } if(conn!=null) { conn.close(); LOGGER_EVENT.log(Level.INFO,"conn.close() executed..."); } if(conf!=null) { conf.clear(); LOGGER_EVENT.log(Level.INFO,"conf.close() executed..."); } if(fh_pvlu !=null) { LOGGER_EVENT.log(Level.INFO," Executing fh_pvlu.flush() & fh_pvlu.close()..."); fh_pvlu.flush(); fh_pvlu.close(); } }catch(Exception e1) { e1.printStackTrace(); throw new Exception("SEVERE:Exception in releaseResources()...."+e1.getMessage()); } } public static void main(String args[]){ try { if(args.length !=3) { throw new IOException("SEVERE:PVLU JAVA process Requires[filePath, newUPD, V_READ_DATE], number of passed args not matching with expected..."); }else { filePath = new Path(args[0]); jdCSVFilePath = new Path(args[0] + "_JOBDETAILS"); new_UPD=args[1]; V_READ_DATE=args[2]+" +0000"; //Initialize the LogFile for PVLU,PMLU,MASTER,connection getResources(args[2]); printInitialValues(); LOGGER_EVENT.log(Level.INFO,"Log file initiated for the day:- "+new_UPD); LOGGER_EVENT.log(Level.INFO,"Input file path: "+filePath); LOGGER_EVENT.log(Level.INFO,"Input Error CSV file path: "+jdCSVFilePath); LOGGER_EVENT.log(Level.INFO,"Input new upd: "+args[1]); LOGGER_EVENT.log(Level.INFO,"Input new v_read_date: "+V_READ_DATE); //PVLU.wf_id="" //ExecutorService pool; //conn = ConnectionFactory.createConnection(conf, pool);//createConnection(configuration); //Call applyUpdates to process all blms exchange events. applyUpdates(); //Release Resources held by this Process. LOGGER_EVENT.log(Level.INFO,"Job finished..Calling releaseResources() as normal call.."); releaseResources(); System.out.println("END OF JOB..........."); System.exit(0); } }catch(Exception e1){ //releaseResources(); e1.printStackTrace(); System.out.println("SEVERE:Unhandled Exception:"+e1.getMessage()); System.exit(1); } } }
56.185053
386
0.722511
c7081fa2ad1b4571e26d10d55059e3373bcf9cea
2,247
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tatsinktechnologic.entity.account; /** * * @author olivier.tatsinkou */ import java.io.Serializable; import java.util.Objects; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "phone") public class Phone implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(unique = true, nullable = false) private Integer phone_id; @Column(nullable = false) private String phone_number; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "contact_id", nullable = false) private Contact contact; public Integer getPhone_id() { return phone_id; } public void setPhone_id(Integer phone_id) { this.phone_id = phone_id; } public String getPhone_number() { return phone_number; } public void setPhone_number(String phone_number) { this.phone_number = phone_number; } public Contact getContact() { return contact; } public void setContact(Contact contact) { this.contact = contact; } @Override public int hashCode() { int hash = 5; hash = 53 * hash + Objects.hashCode(this.phone_number); return hash; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Phone other = (Phone) obj; if (!Objects.equals(this.phone_number, other.phone_number)) { return false; } return true; } @Override public String toString() { return phone_number ; } }
21.4
79
0.636404
05a750101a53d98edb45ec2b94a96d9dee3a08ab
2,378
package me.retrodaredevil.solarthing.message.implementations; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeName; import me.retrodaredevil.solarthing.message.MessageSender; import net.bis5.mattermost.client4.ApiResponse; import net.bis5.mattermost.client4.MattermostClient; import net.bis5.mattermost.client4.model.ApiError; import net.bis5.mattermost.model.Post; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.TimeUnit; import java.util.logging.Level; @JsonTypeName("mattermost") public class MattermostMessageSender implements MessageSender { private static final Logger LOGGER = LoggerFactory.getLogger(MattermostMessageSender.class); private final MattermostClient client; private final String channelId; public MattermostMessageSender(MattermostClient client, String channelId) { this.client = client; this.channelId = channelId; } @JsonCreator public static MattermostMessageSender create( @JsonProperty(value = "url", required = true) String url, @JsonProperty(value = "token", required = true) String token, @JsonProperty(value = "channel_id", required = true) String channelId, @JsonProperty("connection_timeout") Float connectionTimeoutSeconds, @JsonProperty("read_timeout") Float readTimeoutSeconds ) { java.util.logging.Logger.getLogger("").setLevel(Level.OFF); MattermostClient client = MattermostClient.builder() .url(url) .ignoreUnknownProperties() .logLevel(Level.INFO) .httpConfig(httpClient -> { if (connectionTimeoutSeconds != null) { httpClient.connectTimeout(Math.round(connectionTimeoutSeconds * 1000), TimeUnit.MILLISECONDS); } if (readTimeoutSeconds != null) { httpClient.readTimeout(Math.round(readTimeoutSeconds * 1000), TimeUnit.MILLISECONDS); } }) .build(); client.setAccessToken(token); return new MattermostMessageSender(client, channelId); } @Override public void sendMessage(String message) { Post post = new Post(); post.setChannelId(channelId); post.setMessage(message); ApiResponse<Post> response = client.createPost(post); ApiError error = response.readError(); if (error != null && error.getDetailedError() != null) { LOGGER.info("error: " + error.getDetailedError()); } } }
35.492537
100
0.767452
0c2ffc313483cdd8a10f46010511003feacc0dc7
3,001
package com.trivago.cluecumber.json.postprocessors; import com.trivago.cluecumber.json.pojo.Element; import com.trivago.cluecumber.json.pojo.Report; import com.trivago.cluecumber.json.pojo.Step; import com.trivago.cluecumber.json.pojo.Tag; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static org.hamcrest.core.Is.is; import static org.hamcrest.MatcherAssert.assertThat; public class ReportPostProcessorTest { private ReportPostProcessor reportPostProcessor; @Before public void setup() { reportPostProcessor = new ReportPostProcessor(); } @Test public void postDeserializeTest() { Report report = new Report(); List<Element> elements = new ArrayList<>(); Element backgroundElement = new Element(); List<Step> backgroundSteps = new ArrayList<>(); Step backgroundStep1 = new Step(); backgroundStep1.setName("background step 1"); backgroundSteps.add(backgroundStep1); Step backgroundStep2 = new Step(); backgroundStep2.setName("background step 2"); backgroundSteps.add(backgroundStep2); backgroundElement.setSteps(backgroundSteps); backgroundElement.setType("background"); elements.add(backgroundElement); Element element = new Element(); List<Tag> scenarioTags = new ArrayList<>(); Tag tag = new Tag(); tag.setName("@tag"); scenarioTags.add(tag); element.setTags(scenarioTags); List<Step> steps = new ArrayList<>(); Step step = new Step(); step.setName("element step 1"); steps.add(step); Step step2 = new Step(); step2.setName("element step 2"); steps.add(step2); element.setSteps(steps); elements.add(element); List<Tag> featureTags = new ArrayList<>(); Tag featureTag = new Tag(); tag.setName("@feature"); featureTags.add(featureTag); report.setTags(featureTags); report.setElements(elements); assertThat(report.getElements().size(), is(2)); assertThat(report.getElements().get(1).getTags().size(), is(1)); reportPostProcessor.postDeserialize(report, null, null); assertThat(report.getElements().size(), is(1)); Element firstElement = report.getElements().get(0); assertThat(firstElement.getTags().size(), is(2)); List<Step> firstElementSteps = firstElement.getSteps(); assertThat(firstElementSteps.size(), is(4)); assertThat(firstElementSteps.get(0).getName(), is("background step 1")); assertThat(firstElementSteps.get(1).getName(), is("background step 2")); assertThat(firstElementSteps.get(2).getName(), is("element step 1")); assertThat(firstElementSteps.get(3).getName(), is("element step 2")); } @Test public void postSerializeTest() { reportPostProcessor.postSerialize(null, null, null); } }
34.494253
80
0.65978
0409943082605a0123fa322b928da5aa650b2da6
571
package Binary; public class sqrtx_69 { public int mySqrt(int x) { if(x < 2) return x; long left = 2, right = x / 2 + 1, guess; long result = Integer.MAX_VALUE; while(left <= right) { long mid = left + (right - left) / 2; guess = mid * mid; if(guess == x) return (int)mid; if(guess > x) { right = mid - 1; result = Math.min(result, mid-1); } else { left = mid + 1; } } return (int) result; } }
25.954545
49
0.425569
b1da8ba383b6e1f4f45b2880d06457b52fba0000
4,451
/* MazeRunnerII: A Maze-Solving Game Copyright (C) 2008-2010 Eric Ahnell Any questions should be directed to the author via email at: mazer5d@worldwizard.net */ package com.puttysoftware.mazerunner3.maze.abc; import com.puttysoftware.mazerunner3.Game; import com.puttysoftware.mazerunner3.creatures.StatConstants; import com.puttysoftware.mazerunner3.creatures.party.PartyManager; import com.puttysoftware.mazerunner3.creatures.party.PartyMember; import com.puttysoftware.mazerunner3.loader.SoundConstants; import com.puttysoftware.mazerunner3.loader.SoundLoader; import com.puttysoftware.mazerunner3.maze.MazeConstants; import com.puttysoftware.mazerunner3.maze.objects.Empty; import com.puttysoftware.mazerunner3.maze.utilities.MazeObjectInventory; import com.puttysoftware.mazerunner3.maze.utilities.TypeConstants; import com.puttysoftware.randomrange.RandomRange; public abstract class AbstractPotion extends AbstractMazeObject { // Fields private int statAffected; private int effectValue; private RandomRange effect; private boolean effectValueIsPercentage; private static final long SCORE_SMASH = 20L; private static final long SCORE_CONSUME = 50L; // Constructors protected AbstractPotion(final int stat, final boolean usePercent) { super(false, false); this.statAffected = stat; this.effectValueIsPercentage = usePercent; } protected AbstractPotion(final int stat, final boolean usePercent, final int min, final int max) { super(false, false); this.statAffected = stat; this.effectValueIsPercentage = usePercent; this.effect = new RandomRange(min, max); } @Override public AbstractPotion clone() { final AbstractPotion copy = (AbstractPotion) super.clone(); copy.statAffected = this.statAffected; copy.effectValue = this.effectValue; copy.effectValueIsPercentage = this.effectValueIsPercentage; copy.effect = this.effect; return copy; } @Override public abstract String getName(); @Override public int getLayer() { return MazeConstants.LAYER_OBJECT; } @Override protected void setTypes() { this.type.set(TypeConstants.TYPE_POTION); this.type.set(TypeConstants.TYPE_CONTAINABLE); } @Override public final void postMoveAction(final boolean ie, final int dirX, final int dirY, final MazeObjectInventory inv) { final PartyMember m = PartyManager.getParty().getLeader(); if (this.effect != null) { this.effectValue = this.effect.generate(); } else { this.effectValue = this.getEffectValue(); } if (this.effectValueIsPercentage) { if (this.statAffected == StatConstants.STAT_CURRENT_HP) { if (this.effectValue >= 0) { m.healPercentage(this.effectValue); } else { m.doDamagePercentage(-this.effectValue); } } else if (this.statAffected == StatConstants.STAT_CURRENT_MP) { if (this.effectValue >= 0) { m.regeneratePercentage(this.effectValue); } else { m.drainPercentage(-this.effectValue); } } } else { if (this.statAffected == StatConstants.STAT_CURRENT_HP) { if (this.effectValue >= 0) { m.heal(this.effectValue); } else { m.doDamage(-this.effectValue); } } else if (this.statAffected == StatConstants.STAT_CURRENT_MP) { if (this.effectValue >= 0) { m.regenerate(this.effectValue); } else { m.drain(-this.effectValue); } } } Game.getApplication().getGameManager().decay(); if (this.effectValue >= 0) { SoundLoader.playSound(SoundConstants.SOUND_HEAL); } else { SoundLoader.playSound(SoundConstants.SOUND_HURT); } Game.getApplication().getGameManager().addToScore(AbstractPotion.SCORE_CONSUME); } @Override public boolean arrowHitAction(final int locX, final int locY, final int locZ, final int dirX, final int dirY, final int arrowType, final MazeObjectInventory inv) { Game.getApplication().getGameManager().morph(new Empty(), locX, locY, locZ); SoundLoader.playSound(SoundConstants.SOUND_SHATTER); Game.getApplication().getGameManager().addToScore(AbstractPotion.SCORE_SMASH); return false; } public int getEffectValue() { if (this.effect != null) { return this.effect.generate(); } else { return 0; } } @Override public int getCustomProperty(final int propID) { return AbstractMazeObject.DEFAULT_CUSTOM_VALUE; } @Override public void setCustomProperty(final int propID, final int value) { // Do nothing } }
32.021583
119
0.735565
65c8ae537c30e32d4a3502ccea66beb6add86326
1,365
import java.util.Scanner; public class FruitCoctails { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); String fruit=scanner.nextLine(); String size=scanner.nextLine(); int qty=Integer.parseInt(scanner.nextLine()); double price=0; if (fruit.equals("Watermelon")){ if (size.equals("small")){ price=qty*56.00*2; }else if (size.equals("big")){ price=qty*28.70*5; } }else if (fruit.equals("Mango")){ if (size.equals("small")){ price=qty*36.66*2; }else if (size.equals("big")){ price=qty*19.60*5; } }else if (fruit.equals("Pineapple")){ if (size.equals("small")){ price=qty*42.10*2; }else if (size.equals("big")){ price=qty*24.80*5; } }else if (fruit.equals("Raspberry")){ if (size.equals("small")){ price=qty*20.00*2; }else if (size.equals("big")){ price=qty*15.20*5; } } if (price>1000){ price=price-price*0.50; } if (price>=400&&price<=1000){ price=price-price*0.15; } System.out.printf("%.2f lv.",price); } }
31.022727
53
0.469597
e203da341a7f13761b6e4987d0a2160c3938b7c8
1,123
/** * @(#)WebService * 版权声明 厦门畅享信息技术有限公司, 版权所有 违者必究 * *<br> Copyright: Copyright (c) 2014 *<br> Company:厦门畅享信息技术有限公司 *<br> @author ulyn *<br> 14-12-12 下午5:44 *<br> @version 1.0 *———————————————————————————————— *修改记录 * 修改者: * 修改时间: * 修改原因: *———————————————————————————————— */ package com.sunsharing.eos.clientproxy.ws; import com.sunsharing.eos.client.rpc.DynamicRpc; import com.sunsharing.eos.clientproxy.ServiceRequestProxyProcessor; import com.sunsharing.eos.common.utils.VersionUtil; import org.apache.log4j.Logger; /** * <pre></pre> * <br>---------------------------------------------------------------------- * <br> <b>功能描述:</b> * <br> * <br> 注意事项: * <br> * <br> * <br>---------------------------------------------------------------------- * <br> */ public class WebServiceProxy { private Logger logger = Logger.getLogger(WebServiceProxy.class); /** * @param serviceReqBase64Str ServiceRequest对象的base64字符串 * @return */ public String invoke(String serviceReqBase64Str){ return ServiceRequestProxyProcessor.invoke(serviceReqBase64Str); } }
23.893617
77
0.542297
059f741fa9997a99f099980b42f231c863c39ec1
2,802
package com.mapr.objectpools.model; /** * tierid * tiername * tiertype * url * bucketname * region * * tierPurged * * @return */ public class ContextCold { private String tierId, tierName, tierType, url, bucketName, region; private Long tierPurged; public String getTierId() { return tierId; } public void setTierId(String tierId) { this.tierId = tierId; } public String getTierName() { return tierName; } public void setTierName(String tierName) { this.tierName = tierName; } public String getTierType() { return tierType; } public void setTierType(String tierType) { this.tierType = tierType; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getBucketName() { return bucketName; } public void setBucketName(String bucketName) { this.bucketName = bucketName; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public Long getTierPurged() { return tierPurged; } public void setTierPurged(Long tierPurged) { this.tierPurged = tierPurged; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ContextCold that = (ContextCold) o; if (tierId != null ? !tierId.equals(that.tierId) : that.tierId != null) return false; if (tierName != null ? !tierName.equals(that.tierName) : that.tierName != null) return false; if (tierType != null ? !tierType.equals(that.tierType) : that.tierType != null) return false; if (url != null ? !url.equals(that.url) : that.url != null) return false; if (bucketName != null ? !bucketName.equals(that.bucketName) : that.bucketName != null) return false; if (region != null ? !region.equals(that.region) : that.region != null) return false; return tierPurged != null ? tierPurged.equals(that.tierPurged) : that.tierPurged == null; } @Override public int hashCode() { int result = tierId != null ? tierId.hashCode() : 0; result = 31 * result + (tierName != null ? tierName.hashCode() : 0); result = 31 * result + (tierType != null ? tierType.hashCode() : 0); result = 31 * result + (url != null ? url.hashCode() : 0); result = 31 * result + (bucketName != null ? bucketName.hashCode() : 0); result = 31 * result + (region != null ? region.hashCode() : 0); result = 31 * result + (tierPurged != null ? tierPurged.hashCode() : 0); return result; } }
26.942308
109
0.596717
11223e1191ec312ea5982a089ad5618fc44afade
69
package l.b.a; public abstract class a implements Comparable<a> { }
13.8
50
0.73913
751dccc077caa201b44fa47a67d48759900171ad
392
package no.nav.common.types.identer; import com.fasterxml.jackson.annotation.JsonCreator; /** * Representerer aktør IDen til en bruker. * Eksempel: 1112223334445 */ public class AktorId extends EksternBrukerId { @JsonCreator public AktorId(String id) { super(id); } public static AktorId of(String aktorIdStr) { return new AktorId(aktorIdStr); } }
18.666667
52
0.693878
439c7a4b92cca50bf822d7cba716e1fbe4ba30d3
331
class org.junit.runners.BlockJUnit4ClassRunner$RuleCollector<T> implements org.junit.runners.model.MemberValueConsumer<T> { final java.util.List<T> result; public void accept(org.junit.runners.model.FrameworkMember<?>, T); org.junit.runners.BlockJUnit4ClassRunner$RuleCollector(org.junit.runners.BlockJUnit4ClassRunner$1); }
55.166667
123
0.81571
c260ba1edddd9c81061a3cfb89c6cf14a7fd7e85
784
package example; import java.util.HashMap; import java.util.Map; /** * Attempt to find the mapping "Firstname Lastname" to "Lastname, F.". */ public class NamingSolver extends StringSolver { /** * Entry point. */ public static void main(String... args) { final Map<String,String> mappings = new HashMap<>(); mappings.put("Fred Flintstone", "Flintstone, F."); mappings.put("Barney Rubble", "Rubble, B."); mappings.put("Road Runner", "Runner, R."); mappings.put("Yosemite Sam", "Sam, Y."); mappings.put("Elmer Fudd", "Fudd, E."); mappings.put("Elvis Presley", "Presley, E."); mappings.put("Bruce Wayne", "Wayne, B."); new NamingSolver().solve(mappings); } }
26.133333
70
0.579082
a175e1f885425b7fd0dfb094a021068c5db5b9c7
965
package com.github.bingoohuang.blackcat.consumer; import com.github.bingoohuang.blackcat.sdk.BlackcatMsgHandler; import com.github.bingoohuang.blackcat.sdk.netty.BlackcatServer; import com.github.bingoohuang.blackcat.server.handler.CassandraMsgHandler; import com.github.bingoohuang.blackcat.server.handler.CompositeMsgHandler; import com.google.common.collect.Lists; import lombok.val; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.util.List; public class Main { public static void main(String[] args) throws Exception { val context = new AnnotationConfigApplicationContext(SpringConfig.class); val cassandraMsgHandler = context.getBean(CassandraMsgHandler.class); List<BlackcatMsgHandler> handlers = Lists.newArrayList(); handlers.add(cassandraMsgHandler); val composite = new CompositeMsgHandler(handlers); new BlackcatServer(composite).startup(); } }
37.115385
81
0.790674