repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Geistes/FinchyBlockTracker
src/com/Geisteskranken/FinchyBlockTracker/FinchyBlockTracker.java
1310
package com.Geisteskranken.FinchyBlockTracker; import java.util.logging.Logger; import net.canarymod.Canary; import net.canarymod.plugin.Plugin; public class FinchyBlockTracker extends Plugin { public static String host; public static String port; public static String database; public static String dbuser; public static String dbpass; public static boolean Track = true; public static String Name = "FinchyBlockTracker"; public static String Version = "1.0"; public static Logger logger = Logger.getLogger(Name + " " + Version); @Override public void disable() { Track = false; logger.warning(Name + " " + Version + " disabled."); } @Override public boolean enable() { logger.info("Loading " + Name + " " + Version); Canary.hooks().registerListener(new FinchyEventHandler(), this); this.setName("FinchyBlockTracker"); if (FinchyBlockTrackerConfig.readConfig()) { logger.info("Checking SQL DB..."); if (FinchyBlockTrackerSQL.checkDB()) { logger.info("Checking SQL Table..."); if (FinchyBlockTrackerSQL.checkTable()) { logger.info("Everything appears OK"); Track = true; logger.info(Name + " " + Version + " " + "Enabled!"); } else { disable(); } } else { disable(); } } else { disable(); } return true; } }
mit
dvsa/motr-webapp
webapp/src/test/java/uk/gov/dvsa/motr/web/resource/ResendSmsResourceTest.java
3036
package uk.gov.dvsa.motr.web.resource; import org.junit.Before; import org.junit.Test; import uk.gov.dvsa.motr.web.component.subscription.helper.UrlHelper; import uk.gov.dvsa.motr.web.component.subscription.service.SmsConfirmationService; import uk.gov.dvsa.motr.web.cookie.MotrSession; import javax.ws.rs.core.Response; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ResendSmsResourceTest { private static final String PHONE_NUMBER = "07801856718"; private static final String CONFIRMATION_ID = "ABC123"; private static final String SMS_CONFIRMATION_CODE_LINK = "confirm-phone"; private SmsConfirmationService smsConfirmationService = mock(SmsConfirmationService.class); private MotrSession motrSession; private ResendSmsResource resendSmsResource; private UrlHelper urlHelper; @Before public void setup() { smsConfirmationService = mock(SmsConfirmationService.class); motrSession = mock(MotrSession.class); urlHelper = mock(UrlHelper.class); resendSmsResource = new ResendSmsResource(motrSession, smsConfirmationService, urlHelper); when(motrSession.getPhoneNumberFromSession()).thenReturn(PHONE_NUMBER); when(motrSession.getConfirmationIdFromSession()).thenReturn(CONFIRMATION_ID); } @Test public void smsIsResentOnValidGet() throws Exception { when(motrSession.isAllowedToResendSmsConfirmationCode()).thenReturn(true); when(smsConfirmationService.smsSendingNotRestrictedByRateLimiting(eq(PHONE_NUMBER), eq(CONFIRMATION_ID))) .thenReturn(true); when(smsConfirmationService.resendSms(any(), any())).thenReturn(SMS_CONFIRMATION_CODE_LINK); Response response = resendSmsResource.resendSmsResourceGet(); verify(smsConfirmationService, times(1)).resendSms(PHONE_NUMBER, CONFIRMATION_ID); assertEquals(302, response.getStatus()); assertEquals("confirm-phone", response.getLocation().toString()); } @Test public void testNoResendOfSms_whenResendIsLimited() throws Exception { when(motrSession.isAllowedToResendSmsConfirmationCode()).thenReturn(true); when(smsConfirmationService.smsSendingNotRestrictedByRateLimiting(eq(PHONE_NUMBER), eq(CONFIRMATION_ID))) .thenReturn(false); when(smsConfirmationService.resendSms(any(), any())).thenReturn(SMS_CONFIRMATION_CODE_LINK); when(urlHelper.phoneConfirmationLink()).thenReturn(SMS_CONFIRMATION_CODE_LINK); Response response = resendSmsResource.resendSmsResourceGet(); verify(smsConfirmationService, times(0)).resendSms(PHONE_NUMBER, CONFIRMATION_ID); assertEquals(302, response.getStatus()); assertEquals("confirm-phone", response.getLocation().toString()); } }
mit
IvayloP/JavaDemoApp
blog/src/main/java/demoblog/service/PageWrapper.java
2566
package demoblog.service; import org.springframework.data.domain.Page; import java.util.ArrayList; import java.util.List; /** * Created by Ivaylo on 2.3.2017 г.. */ public class PageWrapper<T> { public static final int MAX_PAGE_ITEM_DISPLAY = 5; private Page<T> page; private List<PageItem> items; private int currentNumber; private String url; public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public PageWrapper(Page<T> page, String url){ this.page = page; this.url = url; items = new ArrayList<PageItem>(); currentNumber = page.getNumber() + 1; //start from 1 to match page.page int start, size; if (page.getTotalPages() <= MAX_PAGE_ITEM_DISPLAY){ start = 1; size = page.getTotalPages(); } else { if (currentNumber <= MAX_PAGE_ITEM_DISPLAY - MAX_PAGE_ITEM_DISPLAY/2){ start = 1; size = MAX_PAGE_ITEM_DISPLAY; } else if (currentNumber >= page.getTotalPages() - MAX_PAGE_ITEM_DISPLAY/2){ start = page.getTotalPages() - MAX_PAGE_ITEM_DISPLAY + 1; size = MAX_PAGE_ITEM_DISPLAY; } else { start = currentNumber - MAX_PAGE_ITEM_DISPLAY/2; size = MAX_PAGE_ITEM_DISPLAY; } } for (int i = 0; i<size; i++){ items.add(new PageItem(start+i, (start+i)==currentNumber)); } } public List<PageItem> getItems(){ return items; } public int getNumber(){ return currentNumber; } public List<T> getContent(){ return page.getContent(); } public int getSize(){ return page.getSize(); } public int getTotalPages(){ return page.getTotalPages(); } public boolean isFirstPage(){ return page.isFirst(); } public boolean isLastPage(){ return page.isLast(); } public boolean isHasPreviousPage(){ return page.hasPrevious(); } public boolean isHasNextPage(){ return page.hasNext(); } public class PageItem { private int number; private boolean current; public PageItem(int number, boolean current){ this.number = number; this.current = current; } public int getNumber(){ return this.number; } public boolean isCurrent(){ return this.current; } } }
mit
tamerman/mobile-starting-framework
push/api/src/main/java/org/kuali/mobility/push/entity/PushConfigConstants.java
1562
/** * The MIT License * Copyright (c) 2011 Kuali Mobility Team * * 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.kuali.mobility.push.entity; /** * Created by charl on 2014/07/11. */ public interface PushConfigConstants { public static final String BLACKBERRY_APPLICATION_ID = "blackberry.appId"; public static final String BLACKBERRY_PUSH_URL = "blackberry.pushUrl"; public static final String BLACKBERRY_PUSH_PORT = "blackberry.pushPort"; public static final String ANDROID_SENDER_ID = "android.senderId"; }
mit
enviniom/parqueadero
sistemaParqueadero/src/Vista/frmVehiculos.java
34931
/* * 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 Vista; import Controlador.fVehiculo; import Modelo.vVehiculo; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.DefaultTableModel; /** * * @author Jhon */ public class frmVehiculos extends javax.swing.JFrame { /** * Creates new form frmVehiculos */ public frmVehiculos() { initComponents(); this.setLocationRelativeTo(null); mostrar(""); inhabilitar(); } private String accion = "Guardar"; void ocultar_columnas (){ tablaListado.getColumnModel().getColumn(0).setMaxWidth(0); tablaListado.getColumnModel().getColumn(0).setMinWidth(0); tablaListado.getColumnModel().getColumn(0).setPreferredWidth(0); } void inhabilitar (){ txtIdVehiculo.setVisible(false); cmbTipo.setEnabled(false); txtPlaca.setEnabled(false); txtMarca.setEnabled(false); txtModelo.setEnabled(false); txtAno.setEnabled(false); txtColor.setEnabled(false); txtPropietario.setEnabled(false); cmbEstado.setEnabled(false); btnCancelar.setEnabled(false); btnGuardar.setEnabled(false); btnEliminar.setEnabled(false); txtIdVehiculo.setText(""); txtPlaca.setText(""); txtMarca.setText(""); txtModelo.setText(""); txtAno.setText(""); txtColor.setText(""); txtPropietario.setText(""); } void habilitar (){ txtIdVehiculo.setVisible(false); cmbTipo.setEnabled(true); txtPlaca.setEnabled(true); txtMarca.setEnabled(true); txtModelo.setEnabled(true); txtAno.setEnabled(true); txtColor.setEnabled(true); txtPropietario.setEnabled(true); cmbEstado.setEnabled(false); btnCancelar.setEnabled(true); btnGuardar.setEnabled(true); btnEliminar.setEnabled(true); txtIdVehiculo.setText(""); txtPlaca.setText(""); txtMarca.setText(""); txtModelo.setText(""); txtAno.setText(""); txtColor.setText(""); txtPropietario.setText(""); } void mostrar (String buscar){ try { DefaultTableModel modelo; fVehiculo func = new fVehiculo(); modelo = func.mostrar(buscar); tablaListado.setModel(modelo); ocultar_columnas(); lblTotalRegistros.setText("Total registros "+ Integer.toString(func.totalRegistros)); } catch (Exception e) { JOptionPane.showConfirmDialog(rootPane, e); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); cmbTipo = new javax.swing.JComboBox<>(); jLabel3 = new javax.swing.JLabel(); txtPlaca = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtMarca = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); txtModelo = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); txtAno = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); txtColor = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); txtPropietario = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); cmbEstado = new javax.swing.JComboBox<>(); btnNuevo = new javax.swing.JButton(); btnGuardar = new javax.swing.JButton(); btnCancelar = new javax.swing.JButton(); txtIdVehiculo = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); txtBuscar = new javax.swing.JTextField(); jScrollPane1 = new javax.swing.JScrollPane(); tablaListado = new javax.swing.JTable(); btnBuscar = new javax.swing.JButton(); btnEliminar = new javax.swing.JButton(); btnSalir = new javax.swing.JButton(); lblTotalRegistros = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jLabel1.setFont(new java.awt.Font("Verdana", 1, 18)); // NOI18N jLabel1.setText("VEHÍCULOS"); jPanel1.setBackground(new java.awt.Color(255, 255, 204)); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Registro de Vehículos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 0, 14))); // NOI18N jLabel2.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel2.setText("Tipo"); cmbTipo.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Moto", "Carro" })); cmbTipo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbTipoActionPerformed(evt); } }); jLabel3.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel3.setText("Placa"); txtPlaca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtPlacaActionPerformed(evt); } }); jLabel4.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel4.setText("Marca"); txtMarca.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtMarcaActionPerformed(evt); } }); jLabel5.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel5.setText("Modelo"); txtModelo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtModeloActionPerformed(evt); } }); jLabel6.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel6.setText("Año"); txtAno.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtAnoActionPerformed(evt); } }); jLabel7.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel7.setText("Color"); txtColor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtColorActionPerformed(evt); } }); jLabel8.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel8.setText("Propietario"); txtPropietario.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtPropietarioActionPerformed(evt); } }); jLabel9.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel9.setText("Estado"); cmbEstado.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Habilitado", "Deshabilitado" })); cmbEstado.setSelectedIndex(1); cmbEstado.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cmbEstadoActionPerformed(evt); } }); btnNuevo.setBackground(new java.awt.Color(204, 204, 204)); btnNuevo.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N btnNuevo.setForeground(new java.awt.Color(15, 171, 223)); btnNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Archivos/nuevo_doc.png"))); // NOI18N btnNuevo.setText("Nuevo"); btnNuevo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnNuevoActionPerformed(evt); } }); btnGuardar.setBackground(new java.awt.Color(204, 204, 204)); btnGuardar.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N btnGuardar.setForeground(new java.awt.Color(15, 171, 223)); btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Archivos/guardar_doc.png"))); // NOI18N btnGuardar.setText("Guardar"); btnGuardar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnGuardarActionPerformed(evt); } }); btnCancelar.setBackground(new java.awt.Color(204, 204, 204)); btnCancelar.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N btnCancelar.setForeground(new java.awt.Color(15, 171, 223)); btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Archivos/cancelar_doc.png"))); // NOI18N btnCancelar.setText("Cancelar"); btnCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCancelarActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel3) .addComponent(jLabel7) .addComponent(jLabel8) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jLabel9)) .addGap(69, 69, 69) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(cmbEstado, 0, 197, Short.MAX_VALUE) .addComponent(cmbTipo, 0, 197, Short.MAX_VALUE) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtMarca, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtModelo, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtColor, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtPropietario, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(txtIdVehiculo)))) .addContainerGap(29, Short.MAX_VALUE)) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(btnNuevo) .addGap(18, 18, 18) .addComponent(btnGuardar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(btnCancelar) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(txtIdVehiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(cmbTipo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(txtMarca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(txtColor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(txtPropietario, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(26, 26, 26) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(cmbEstado, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(39, 39, 39) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnNuevo) .addComponent(btnGuardar) .addComponent(btnCancelar)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.setBackground(new java.awt.Color(204, 255, 204)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Listado de Vehículos", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Verdana", 0, 14))); // NOI18N jLabel10.setFont(new java.awt.Font("Verdana", 0, 12)); // NOI18N jLabel10.setText("Buscar"); tablaListado.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); tablaListado.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { tablaListadoMouseClicked(evt); } }); jScrollPane1.setViewportView(tablaListado); btnBuscar.setBackground(new java.awt.Color(204, 204, 204)); btnBuscar.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N btnBuscar.setForeground(new java.awt.Color(15, 171, 223)); btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Archivos/buscar_doc.png"))); // NOI18N btnBuscar.setText("Buscar"); btnBuscar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnBuscarActionPerformed(evt); } }); btnEliminar.setBackground(new java.awt.Color(204, 204, 204)); btnEliminar.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N btnEliminar.setForeground(new java.awt.Color(15, 171, 223)); btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Archivos/eliminar_doc.png"))); // NOI18N btnEliminar.setText("Eliminar"); btnEliminar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnEliminarActionPerformed(evt); } }); btnSalir.setBackground(new java.awt.Color(204, 204, 204)); btnSalir.setFont(new java.awt.Font("Verdana", 0, 11)); // NOI18N btnSalir.setForeground(new java.awt.Color(15, 171, 223)); btnSalir.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Archivos/salir_inicio.png"))); // NOI18N btnSalir.setText("Salir"); btnSalir.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnSalirActionPerformed(evt); } }); lblTotalRegistros.setText("Registros"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(lblTotalRegistros) .addGap(151, 151, 151)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 249, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnBuscar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnEliminar) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btnSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(19, 19, 19)))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(txtBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(btnBuscar) .addComponent(btnEliminar) .addComponent(btnSalir))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 317, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lblTotalRegistros) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(367, 367, 367) .addComponent(jLabel1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNuevoActionPerformed // TODO add your handling code here: habilitar(); btnGuardar.setText("Guardar"); accion = "guardar"; }//GEN-LAST:event_btnNuevoActionPerformed private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed // TODO add your handling code here: if(txtPlaca.getText().length() == 0){ JOptionPane.showMessageDialog(rootPane, "Debes ingresar la Placa del vehículo"); txtPlaca.requestFocus(); return; } if(txtMarca.getText().length() == 0){ JOptionPane.showMessageDialog(rootPane, "Debes ingresar la Marca del vehículo"); txtMarca.requestFocus(); return; } if(txtModelo.getText().length() == 0){ JOptionPane.showMessageDialog(rootPane, "Debes ingresar el Modelo del vehículo"); txtModelo.requestFocus(); return; } if(txtAno.getText().length() == 0){ JOptionPane.showMessageDialog(rootPane, "Debes ingresar el Año del vehículo"); txtAno.requestFocus(); return; } if(txtColor.getText().length() == 0){ JOptionPane.showMessageDialog(rootPane, "Debes ingresar el Color del vehículo"); txtColor.requestFocus(); return; } if(txtPropietario.getText().length() == 0){ JOptionPane.showMessageDialog(rootPane, "Debes ingresar el Propietario del vehículo"); txtPropietario.requestFocus(); return; } vVehiculo dts = new vVehiculo(); fVehiculo func = new fVehiculo(); String seleccionado =(String) cmbTipo.getSelectedItem(); dts.setTipo(seleccionado); dts.setPlaca(txtPlaca.getText()); dts.setMarca(txtMarca.getText()); dts.setModelo(txtModelo.getText()); dts.setAno(txtAno.getText()); dts.setColor(txtColor.getText()); dts.setPropietario(txtPropietario.getText()); seleccionado =(String) cmbEstado.getSelectedItem(); dts.setEstado(seleccionado); if (accion.equals("guardar")) { if (func.insertar(dts)) { JOptionPane.showMessageDialog(rootPane, "El vehículo fué registrado satisfactoriamente"); mostrar(""); inhabilitar(); } } else if(accion.equals("editar")){ dts.setIdVehiculo(Integer.parseInt(txtIdVehiculo.getText())); if (func.editar(dts)) { JOptionPane.showMessageDialog(rootPane, "El vehículo fué editado satisfactoriamente"); mostrar(""); inhabilitar(); } } }//GEN-LAST:event_btnGuardarActionPerformed private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed // TODO add your handling code here: if (!txtIdVehiculo.getText().equals("")) { int confirmacion = JOptionPane.showConfirmDialog(rootPane, "¿Esta seguro de elimnar el vehículo?","confirmar",2); if (confirmacion == 0) { fVehiculo func = new fVehiculo(); vVehiculo dts = new vVehiculo(); dts.setIdVehiculo(Integer.parseInt(txtIdVehiculo.getText())); func.eliminar(dts); mostrar(""); inhabilitar(); } } }//GEN-LAST:event_btnEliminarActionPerformed private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed // TODO add your handling code here: mostrar(txtBuscar.getText()); }//GEN-LAST:event_btnBuscarActionPerformed private void cmbTipoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbTipoActionPerformed // TODO add your handling code here: cmbTipo.transferFocus(); }//GEN-LAST:event_cmbTipoActionPerformed private void txtPlacaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPlacaActionPerformed // TODO add your handling code here: txtPlaca.transferFocus(); }//GEN-LAST:event_txtPlacaActionPerformed private void txtMarcaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtMarcaActionPerformed // TODO add your handling code here: txtMarca.transferFocus(); }//GEN-LAST:event_txtMarcaActionPerformed private void txtModeloActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtModeloActionPerformed // TODO add your handling code here: txtModelo.transferFocus(); }//GEN-LAST:event_txtModeloActionPerformed private void txtAnoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtAnoActionPerformed // TODO add your handling code here: txtAno.transferFocus(); }//GEN-LAST:event_txtAnoActionPerformed private void txtColorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtColorActionPerformed // TODO add your handling code here: txtColor.transferFocus(); }//GEN-LAST:event_txtColorActionPerformed private void txtPropietarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPropietarioActionPerformed // TODO add your handling code here: txtPropietario.transferFocus(); }//GEN-LAST:event_txtPropietarioActionPerformed private void cmbEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmbEstadoActionPerformed // TODO add your handling code here: cmbEstado.transferFocus(); }//GEN-LAST:event_cmbEstadoActionPerformed private void tablaListadoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tablaListadoMouseClicked // TODO add your handling code here: btnGuardar.setText("Editar"); habilitar(); btnEliminar.setEnabled(true); accion = "editar"; int fila = tablaListado.rowAtPoint(evt.getPoint()); txtIdVehiculo.setText(tablaListado.getValueAt(fila, 0).toString()); cmbTipo.setSelectedItem(tablaListado.getValueAt(fila, 1).toString()); txtPlaca.setText(tablaListado.getValueAt(fila, 2).toString()); txtMarca.setText(tablaListado.getValueAt(fila, 3).toString()); txtModelo.setText(tablaListado.getValueAt(fila, 4).toString()); txtAno.setText(tablaListado.getValueAt(fila, 5).toString()); txtColor.setText(tablaListado.getValueAt(fila, 6).toString()); txtPropietario.setText(tablaListado.getValueAt(fila, 7).toString()); cmbEstado.setSelectedItem(tablaListado.getValueAt(fila, 8).toString()); }//GEN-LAST:event_tablaListadoMouseClicked private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalirActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_btnSalirActionPerformed private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed // TODO add your handling code here: inhabilitar(); }//GEN-LAST:event_btnCancelarActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(frmVehiculos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(frmVehiculos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(frmVehiculos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(frmVehiculos.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new frmVehiculos().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnBuscar; private javax.swing.JButton btnCancelar; private javax.swing.JButton btnEliminar; private javax.swing.JButton btnGuardar; private javax.swing.JButton btnNuevo; private javax.swing.JButton btnSalir; private javax.swing.JComboBox<String> cmbEstado; private javax.swing.JComboBox<String> cmbTipo; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lblTotalRegistros; private javax.swing.JTable tablaListado; private javax.swing.JTextField txtAno; private javax.swing.JTextField txtBuscar; private javax.swing.JTextField txtColor; private javax.swing.JTextField txtIdVehiculo; private javax.swing.JTextField txtMarca; private javax.swing.JTextField txtModelo; private javax.swing.JTextField txtPlaca; private javax.swing.JTextField txtPropietario; // End of variables declaration//GEN-END:variables }
mit
ccsu-cs416F15/CS416ClassDemos
HW2Soln/src/java/edu/ccsu/hw2soln/DisplayVotesServlet.java
3868
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.ccsu.hw2soln; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.sql.DataSource; /** * This servlet just displays the vote data */ @WebServlet(name = "DisplayVotesServlet", urlPatterns = {"/DisplayVotesServlet"}) public class DisplayVotesServlet extends HttpServlet { @Resource(name = "jdbc/HW2DB") DataSource dataSource; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("<html>"); out.println("<head>"); out.println("<title>Display votes</title>"); out.println("</head>"); out.println("<body>"); Connection connection = dataSource.getConnection(); String selectSQL = "select * from VOTES"; PreparedStatement selectStatement = connection.prepareStatement(selectSQL); ResultSet resultSet = selectStatement.executeQuery(); while (resultSet.next()) { String musicType = resultSet.getString("MUSICTYPE"); int numVotes = resultSet.getInt("NUMVOTES"); out.println(musicType + " has " + numVotes + " votes<br/>"); } Integer curVotes = (Integer) request.getSession().getAttribute("sessionVotes"); if (curVotes!=null){ out.println("You have voted "+curVotes+" times"); }else{ out.println("You have not voted yet"); } out.println("</body>"); out.println("</html>"); resultSet.close(); selectStatement.close(); connection.close(); } catch (Exception e) { out.println("Had a problem getting the vote data from the database " + e.getMessage()); } finally { out.close(); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
mit
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/chain/web/RefreshShippingOrderNosController.java
2447
package com.swfarm.biz.chain.web; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; import com.swfarm.biz.chain.bo.CustomerOrder; import com.swfarm.biz.chain.srv.ChainService; import com.swfarm.biz.warehouse.bo.AllocationProductVoucher; import com.swfarm.biz.warehouse.bo.AllocationProductVoucherList; import com.swfarm.biz.warehouse.srv.WarehouseService; public class RefreshShippingOrderNosController extends AbstractController { private WarehouseService warehouseService; private ChainService chainService; public void setWarehouseService(WarehouseService warehouseService) { this.warehouseService = warehouseService; } public void setChainService(ChainService chainService) { this.chainService = chainService; } protected ModelAndView handleRequestInternal(HttpServletRequest req, HttpServletResponse res) throws Exception { String apvlIdStr = req.getParameter("apvl"); if (StringUtils.isNotEmpty(apvlIdStr)) { Long apvlId = new Long(apvlIdStr); AllocationProductVoucherList apvl = this.warehouseService .findAllocationProductVoucherList(apvlId); for (Iterator iter = apvl.getAllocationProductVoucherList() .iterator(); iter.hasNext();) { AllocationProductVoucher apv = (AllocationProductVoucher) iter .next(); if (StringUtils.isEmpty(apv.getShippingOrderNo()) || !apv.getShippingOrderNo().startsWith("WS") || apv.getShippingOrderNo().length() != 13) { CustomerOrder customerOrder = apv.getCustomerOrder(); customerOrder.setShippingOrderNo(null); this.chainService.persistCustomerOrder(customerOrder); logger.warn("shipping order no [" + customerOrder.getShippingOrderNo()); if (StringUtils.isNotEmpty(customerOrder .getCustomerOrderNo())) { apv.setShippingOrderNo(customerOrder .getShippingOrderNo()); this.warehouseService.saveAllocationProductVoucher(apv); } } } return new ModelAndView( "redirect:/warehouse/allocationproductvoucherlist.shtml", "id", apvlIdStr); } else { return new ModelAndView( "redirect:/warehouse/search_allocationproductvoucherlists.shtml"); } } }
mit
jglrxavpok/jglrEngine
src/main/java/org/jge/commands/ShadowColorCommand.java
792
package org.jge.commands; import org.jge.CoreEngine; import org.jge.maths.Vector3; public class ShadowColorCommand extends AbstractCommand { @Override public String getCommand() { return "cl_shadowColor"; } @Override public String run(CommandArgument[] args) { if(args.length != 3) return BAD_USAGE; CoreEngine.getCurrent().getRenderEngine().setVector3("shadowColor", Vector3.get(args[0].getContentAsFloat(), args[1].getContentAsFloat(), args[2].getContentAsFloat())); return "Successfully changed shadow color"; } @Override public int getPermissionLevel() { return 1; } public String[] getCorrectUsages() { return new String[] { getCommand() + " <red> <green> <blue>" }; } public String getDescription() { return "Set the color of shadows"; } }
mit
ghajba/CodingContestConfig
java_original/src/main/java/hu/japy/dev/contestconfig/Main.java
3291
package hu.japy.dev.contestconfig; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.function.Function; /** * Created by GHajba on 2014.10.10.. */ public class Main { public static void main(String... args) throws IOException { Code code = new Code(); //doItNasty("level0", false, code::doLevel0); //doItNasty("level0", true, code::doLevel0); doItNasty("level1", false, code::doLevel1); //doItNasty("level2", false, code::doLevel1); //doItNasty("level3", false, code::doLevel1); //doItNasty("level4", false, code::doLevel1); } private static void doItNasty(String folderName, boolean levelDone, Function<String, String> levelFunction) throws IOException { createFolder(folderName); for (File inputFile : listInputFiles(folderName)) { String input = readFile(inputFile); String result = levelFunction.apply(input); File outFile = new File(inputFile.getPath().replace(".in", ".out")); if (!levelDone) { writeFile(outFile, result); } else { String expected = readFile(outFile); if (!StringUtils.equals(result, expected)) { throw new AssertionError(String.format("Expected and actual result are not the same!\nExpected: " + "%s\nActual: %s", expected, result)); } } } } private static void doLevel1(Code code) throws IOException { createFolder("level1"); for (File inputFile : listInputFiles("level1")) { String input = readFile(inputFile); String result = code.doLevel1(input); String outFileName = inputFile.getName().replace(".in", ".out"); writeFile(inputFile.getPath(), outFileName, result); //assert readFile(inputFile.getPath(), outFileName).equals(result); } } private static void doLevel2(Code code) throws IOException { createFolder("level2"); } private static void doLevel3(Code code) throws IOException { createFolder("level3"); } private static void doLevel4(Code code) throws IOException { createFolder("level4"); } private static void createFolder(String folderName) throws IOException { FileUtils.forceMkdir(new File(folderName)); } private static String readFile(String filePath, String fileName) throws IOException { return readFile(new File(filePath, fileName)); } private static String readFile(File file) throws IOException { return FileUtils.readFileToString(file); } private static void writeFile(String filePath, String fileName, String content) throws IOException { writeFile(new File(filePath, fileName), content); } private static void writeFile(File file, String content) throws IOException { FileUtils.write(file, content); } private static Collection<File> listInputFiles(String folder) { return FileUtils.listFiles(new File(folder), new String[]{"in"}, false); } }
mit
lyg5623/lightgbm_predict4j
src/main/java/org/lightgbm/predict4j/v2/ConfigBase.java
2816
package org.lightgbm.predict4j.v2; import java.util.HashMap; import java.util.List; import java.util.Map; import org.lightgbm.predict4j.Common; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author lyg5623 */ public abstract class ConfigBase { private static final Logger logger = LoggerFactory.getLogger(ConfigBase.class); public abstract void set(Map<String, String> params); /* * ! \brief Get string value by specific name of key \param params Store the key and value for params \param name * Name of key \param out Value will assign to out if key exists \return True if key exists */ String getString(Map<String, String> params, String name) { return params.get(name); } /* * ! \brief Get int value by specific name of key \param params Store the key and value for params \param name Name * of key \param out Value will assign to out if key exists \return True if key exists */ Integer getInt(Map<String, String> params, String name) { String s = params.get(name); if (s == null) return null; return Integer.valueOf(s); } /* * ! \brief Get double value by specific name of key \param params Store the key and value for params \param name * Name of key \param out Value will assign to out if key exists \return True if key exists */ Double getDouble(Map<String, String> params, String name) { String s = params.get(name); if (s == null) return null; return Double.valueOf(s); } /* * ! \brief Get bool value by specific name of key \param params Store the key and value for params \param name Name * of key \param out Value will assign to out if key exists \return True if key exists */ Boolean getBool(Map<String, String> params, String name) { String s = params.get(name); if (s == null) return null; return Boolean.valueOf(s); } static Map<String, String> str2Map(String parameters) { Map<String, String> params = new HashMap<>(); List<String> args = Common.split(parameters, " \t\n\r"); for (String arg : args) { List<String> tmp_strs = Common.split(arg, '='); if (tmp_strs.size() == 2) { String key = Common.removeQuotationSymbol(tmp_strs.get(0).trim()); String value = Common.removeQuotationSymbol(tmp_strs.get(1).trim()); if (key.length() <= 0) { continue; } params.put(key, value); } else if (arg.trim().length() > 0) { logger.warn("Unknown parameter " + arg); } } ParameterAlias.keyAliasTransform(params); return params; } }
mit
zaza/swistak-webapi
src-tst/com/swistak/webapi/category/CategoryTreeBuilderTest.java
2126
package com.swistak.webapi.category; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.File; import org.junit.Test; import com.swistak.webapi.category.Tree.TreeNode; public class CategoryTreeBuilderTest { @Test public void build_kategorie_xml() { CategoryTreeBuilder builder = new CategoryTreeBuilder(new File("data-tst/auctions-root/kategorie.xml")); Tree<Category> tree = builder.build(); assertEquals(6, builder.getExceptions().size()); assertNotNull(tree); assertEquals("2014-05-13 12:31:28", tree.getRoot().getData().getName()); assertEquals(23751, tree.getSize()); } @Test public void build_single_node_xml() { CategoryTreeBuilder builder = new CategoryTreeBuilder(new File("data-tst/single-node.xml")); Tree<Category> tree = builder.build(); assertNotNull(tree); assertTrue(builder.getExceptions().isEmpty()); assertEquals(1, tree.getRoot().getChildren().size()); assertEquals(1, tree.getSize()); TreeNode<Category> node = tree.getRoot().getChildren().get(0); assertNode(node, 1, "Node", 1); } @Test public void build_three_levels_xml() { CategoryTreeBuilder builder = new CategoryTreeBuilder(new File("data-tst/three-levels.xml")); Tree<Category> tree = builder.build(); assertNotNull(tree); assertTrue(builder.getExceptions().isEmpty()); assertEquals(1, tree.getRoot().getChildren().size()); assertEquals(3, tree.getSize()); TreeNode<Category> level1 = tree.getRoot().getChildren().get(0); assertNode(level1, 1, "Level1", 1); TreeNode<Category> level2 = level1.getChildren().get(0); assertNode(level2, 2, "Level2", 2); TreeNode<Category> level3 = level2.getChildren().get(0); assertNode(level3, 3, "Level3", 3); } // TODO: add more tests private static void assertNode(TreeNode<Category> node, int depth, String name, int id) { assertEquals(depth, node.getDepth()); assertEquals(name, node.getData().name); assertEquals(id, node.getData().id); } }
mit
AliYusuf95/iUOB-2
app/src/main/java/com/muqdd/iuob2/features/about/AboutFragment.java
4164
package com.muqdd.iuob2.features.about; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import androidx.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.firebase.analytics.FirebaseAnalytics; import com.muqdd.iuob2.BuildConfig; import com.muqdd.iuob2.R; import com.muqdd.iuob2.app.BaseFragment; import com.muqdd.iuob2.databinding.FragmentAboutBinding; import com.muqdd.iuob2.features.main.Menu; /** * Created by Ali Yusuf on 3/11/2017. * iUOB-2 */ public class AboutFragment extends BaseFragment { private FragmentAboutBinding binding; public AboutFragment() { // Required empty public constructor } public static AboutFragment newInstance() { AboutFragment fragment = new AboutFragment(); Bundle bundle = new Bundle(); bundle.putString(TITLE, Menu.ABOUT.toString()); fragment.setArguments(bundle); return fragment; } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater,container,savedInstanceState); if (binding == null) { // Inflate the layout for this fragment binding = FragmentAboutBinding.inflate(inflater, container, false); initiate(); } return binding.getRoot(); } @Override public void onResume() { super.onResume(); toolbar.setTitle(title); } private void initiate() { // initialize variables binding.title.setText(String.format("%s Version %s", getString(R.string.app_name), BuildConfig.VERSION_NAME)); binding.github.setText(R.string.about_github); binding.github.setOnClickListener(view -> { Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Github"); mFirebaseAnalytics.logEvent("about_item", bundle); openLink("https://github.com/AliYusuf95/iUOB-2"); }); binding.email.setText(R.string.about_email); binding.email.setOnClickListener(view -> { Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Email"); mFirebaseAnalytics.logEvent("about_item", bundle); sendEmail(getString(R.string.about_email)); }); binding.twitter.setText(R.string.about_twitter); binding.twitter.setOnClickListener(view -> { Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Twitter"); mFirebaseAnalytics.logEvent("about_item", bundle); openTwitterAccount(); }); binding.website.setText(R.string.about_website); binding.website.setOnClickListener(view -> { Bundle bundle = new Bundle(); bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, "Website"); mFirebaseAnalytics.logEvent("about_item", bundle); openLink("http://iuob.net"); }); requestReviewFlowDelayed(1); } private void openLink(String url) { Intent intent = new Intent(Intent.ACTION_VIEW); intent.setData(Uri.parse(url)); startActivity(intent); } private void sendEmail(String email) { Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:" + email)); startActivity(Intent.createChooser(intent, "Send Email")); } private void openTwitterAccount() { Intent intent; try { // get the Twitter app if possible requireActivity().getPackageManager().getPackageInfo("com.twitter.android", 0); intent = new Intent(Intent.ACTION_VIEW, Uri.parse("twitter://user?user_id=aliyusuf_95")); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } catch (Exception e) { // no Twitter app, revert to browser intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/aliyusuf_95")); } this.startActivity(intent); } }
mit
jwiesel/sfdcCommander
sfdcCommander/src/main/java/com/sforce/soap/_2006/_04/metadata/ContentAssetLink.java
6488
/** * ContentAssetLink.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter. */ package com.sforce.soap._2006._04.metadata; public class ContentAssetLink implements java.io.Serializable { private com.sforce.soap._2006._04.metadata.ContentAssetAccess access; private java.lang.Boolean isManagingWorkspace; private java.lang.String name; public ContentAssetLink() { } public ContentAssetLink( com.sforce.soap._2006._04.metadata.ContentAssetAccess access, java.lang.Boolean isManagingWorkspace, java.lang.String name) { this.access = access; this.isManagingWorkspace = isManagingWorkspace; this.name = name; } /** * Gets the access value for this ContentAssetLink. * * @return access */ public com.sforce.soap._2006._04.metadata.ContentAssetAccess getAccess() { return access; } /** * Sets the access value for this ContentAssetLink. * * @param access */ public void setAccess(com.sforce.soap._2006._04.metadata.ContentAssetAccess access) { this.access = access; } /** * Gets the isManagingWorkspace value for this ContentAssetLink. * * @return isManagingWorkspace */ public java.lang.Boolean getIsManagingWorkspace() { return isManagingWorkspace; } /** * Sets the isManagingWorkspace value for this ContentAssetLink. * * @param isManagingWorkspace */ public void setIsManagingWorkspace(java.lang.Boolean isManagingWorkspace) { this.isManagingWorkspace = isManagingWorkspace; } /** * Gets the name value for this ContentAssetLink. * * @return name */ public java.lang.String getName() { return name; } /** * Sets the name value for this ContentAssetLink. * * @param name */ public void setName(java.lang.String name) { this.name = name; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof ContentAssetLink)) return false; ContentAssetLink other = (ContentAssetLink) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = true && ((this.access==null && other.getAccess()==null) || (this.access!=null && this.access.equals(other.getAccess()))) && ((this.isManagingWorkspace==null && other.getIsManagingWorkspace()==null) || (this.isManagingWorkspace!=null && this.isManagingWorkspace.equals(other.getIsManagingWorkspace()))) && ((this.name==null && other.getName()==null) || (this.name!=null && this.name.equals(other.getName()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = 1; if (getAccess() != null) { _hashCode += getAccess().hashCode(); } if (getIsManagingWorkspace() != null) { _hashCode += getIsManagingWorkspace().hashCode(); } if (getName() != null) { _hashCode += getName().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(ContentAssetLink.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ContentAssetLink")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("access"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "access")); elemField.setXmlType(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "ContentAssetAccess")); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("isManagingWorkspace"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "isManagingWorkspace")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "boolean")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("name"); elemField.setXmlName(new javax.xml.namespace.QName("http://soap.sforce.com/2006/04/metadata", "name")); elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
mit
napcs/qedserver
jetty/modules/jetty/src/main/java/org/mortbay/jetty/handler/ResourceHandler.java
11880
// ======================================================================== // Copyright 1999-2005 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== package org.mortbay.jetty.handler; import java.io.IOException; import java.io.OutputStream; import java.net.MalformedURLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.mortbay.io.Buffer; import org.mortbay.io.ByteArrayBuffer; import org.mortbay.io.WriterOutputStream; import org.mortbay.jetty.HttpConnection; import org.mortbay.jetty.HttpFields; import org.mortbay.jetty.HttpHeaders; import org.mortbay.jetty.HttpMethods; import org.mortbay.jetty.MimeTypes; import org.mortbay.jetty.Request; import org.mortbay.jetty.Response; import org.mortbay.jetty.handler.ContextHandler.SContext; import org.mortbay.log.Log; import org.mortbay.resource.FileResource; import org.mortbay.resource.Resource; import org.mortbay.util.StringUtil; import org.mortbay.util.TypeUtil; import org.mortbay.util.URIUtil; /* ------------------------------------------------------------ */ /** Resource Handler. * * This handle will serve static content and handle If-Modified-Since headers. * No caching is done. * Requests that cannot be handled are let pass (Eg no 404's) * * @author Greg Wilkins (gregw) * @org.apache.xbean.XBean */ public class ResourceHandler extends AbstractHandler { ContextHandler _context; Resource _baseResource; String[] _welcomeFiles={"index.html"}; MimeTypes _mimeTypes = new MimeTypes(); ByteArrayBuffer _cacheControl; boolean _aliases; /* ------------------------------------------------------------ */ public ResourceHandler() { } /* ------------------------------------------------------------ */ public MimeTypes getMimeTypes() { return _mimeTypes; } /* ------------------------------------------------------------ */ public void setMimeTypes(MimeTypes mimeTypes) { _mimeTypes = mimeTypes; } /* ------------------------------------------------------------ */ /** * @return True if resource aliases are allowed. */ public boolean isAliases() { return _aliases; } /* ------------------------------------------------------------ */ /** * Set if resource aliases (eg symlink, 8.3 names, case insensitivity) are allowed. * Allowing aliases can significantly increase security vulnerabilities. * @param aliases True if aliases are supported. */ public void setAliases(boolean aliases) { _aliases = aliases; } /* ------------------------------------------------------------ */ public void doStart() throws Exception { SContext scontext = ContextHandler.getCurrentContext(); _context = (scontext==null?null:scontext.getContextHandler()); if (!_aliases && !FileResource.getCheckAliases()) throw new IllegalStateException("Alias checking disabled"); super.doStart(); } /* ------------------------------------------------------------ */ /** * @return Returns the resourceBase. */ public Resource getBaseResource() { if (_baseResource==null) return null; return _baseResource; } /* ------------------------------------------------------------ */ /** * @return Returns the base resource as a string. */ public String getResourceBase() { if (_baseResource==null) return null; return _baseResource.toString(); } /* ------------------------------------------------------------ */ /** * @param base The resourceBase to set. */ public void setBaseResource(Resource base) { _baseResource=base; } /* ------------------------------------------------------------ */ /** * @param resourceBase The base resource as a string. */ public void setResourceBase(String resourceBase) { try { setBaseResource(Resource.newResource(resourceBase)); } catch (Exception e) { Log.warn(e.toString()); Log.debug(e); throw new IllegalArgumentException(resourceBase); } } /* ------------------------------------------------------------ */ /** * @return the cacheControl header to set on all static content. */ public String getCacheControl() { return _cacheControl.toString(); } /* ------------------------------------------------------------ */ /** * @param cacheControl the cacheControl header to set on all static content. */ public void setCacheControl(String cacheControl) { _cacheControl=cacheControl==null?null:new ByteArrayBuffer(cacheControl); } /* ------------------------------------------------------------ */ /* */ public Resource getResource(String path) throws MalformedURLException { if (path==null || !path.startsWith("/")) throw new MalformedURLException(path); Resource base = _baseResource; if (base==null) { if (_context==null) return null; base=_context.getBaseResource(); if (base==null) return null; } try { path=URIUtil.canonicalPath(path); Resource resource=base.addPath(path); return resource; } catch(Exception e) { Log.ignore(e); } return null; } /* ------------------------------------------------------------ */ protected Resource getResource(HttpServletRequest request) throws MalformedURLException { String path_info=request.getPathInfo(); if (path_info==null) return null; return getResource(path_info); } /* ------------------------------------------------------------ */ public String[] getWelcomeFiles() { return _welcomeFiles; } /* ------------------------------------------------------------ */ public void setWelcomeFiles(String[] welcomeFiles) { _welcomeFiles=welcomeFiles; } /* ------------------------------------------------------------ */ protected Resource getWelcome(Resource directory) throws MalformedURLException, IOException { for (int i=0;i<_welcomeFiles.length;i++) { Resource welcome=directory.addPath(_welcomeFiles[i]); if (welcome.exists() && !welcome.isDirectory()) return welcome; } return null; } /* ------------------------------------------------------------ */ /* * @see org.mortbay.jetty.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int) */ public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { Request base_request = request instanceof Request?(Request)request:HttpConnection.getCurrentConnection().getRequest(); if (base_request.isHandled()) return; boolean skipContentBody = false; if(!HttpMethods.GET.equals(request.getMethod())) { if(!HttpMethods.HEAD.equals(request.getMethod())) return; skipContentBody = true; } Resource resource=getResource(request); if (resource==null || !resource.exists()) return; if (!_aliases && resource.getAlias()!=null) { Log.info(resource+" aliased to "+resource.getAlias()); return; } // We are going to server something base_request.setHandled(true); if (resource.isDirectory()) { if (!request.getPathInfo().endsWith(URIUtil.SLASH)) { response.sendRedirect(response.encodeRedirectURL(URIUtil.addPaths(request.getRequestURI(),URIUtil.SLASH))); return; } resource=getWelcome(resource); if (resource==null || !resource.exists() || resource.isDirectory()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } } // set some headers long last_modified=resource.lastModified(); if (last_modified>0) { long if_modified=request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE); if (if_modified>0 && last_modified/1000<=if_modified/1000) { response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); return; } } Buffer mime=_mimeTypes.getMimeByExtension(resource.toString()); if (mime==null) mime=_mimeTypes.getMimeByExtension(request.getPathInfo()); // set the headers doResponseHeaders(response,resource,mime!=null?mime.toString():null); response.setDateHeader(HttpHeaders.LAST_MODIFIED,last_modified); if(skipContentBody) return; // Send the content OutputStream out =null; try {out = response.getOutputStream();} catch(IllegalStateException e) {out = new WriterOutputStream(response.getWriter());} // See if a short direct method can be used? if (out instanceof HttpConnection.Output) { // TODO file mapped buffers ((HttpConnection.Output)out).sendContent(resource.getInputStream()); } else { // Write content normally resource.writeTo(out,0,resource.length()); } } /* ------------------------------------------------------------ */ /** Set the response headers. * This method is called to set the response headers such as content type and content length. * May be extended to add additional headers. * @param response * @param resource * @param mimeType */ protected void doResponseHeaders(HttpServletResponse response, Resource resource, String mimeType) { if (mimeType!=null) response.setContentType(mimeType); long length=resource.length(); if (response instanceof Response) { HttpFields fields = ((Response)response).getHttpFields(); if (length>0) fields.putLongField(HttpHeaders.CONTENT_LENGTH_BUFFER,length); if (_cacheControl!=null) fields.put(HttpHeaders.CACHE_CONTROL_BUFFER,_cacheControl); } else { if (length>0) response.setHeader(HttpHeaders.CONTENT_LENGTH,TypeUtil.toString(length)); if (_cacheControl!=null) response.setHeader(HttpHeaders.CACHE_CONTROL,_cacheControl.toString()); } } }
mit
jmigual/IA2016
Cerca Local/AIMA.src/src/aima/search/informed/IterativeDeepeningAStarSearch.java
1414
/* * Created on Sep 8, 2004 * */ package aima.search.informed; import java.util.ArrayList; import java.util.List; import aima.search.framework.Metrics; import aima.search.framework.NodeExpander; import aima.search.framework.Problem; import aima.search.framework.Search; /** * @author Ravi Mohan * */ public class IterativeDeepeningAStarSearch extends NodeExpander implements Search { private int limit; private Metrics iterationMetrics; public IterativeDeepeningAStarSearch() { this.limit = Integer.MAX_VALUE; iterationMetrics = new Metrics(); iterationMetrics.set(NODES_EXPANDED, 0); } public List search(Problem p) throws Exception { for (int i = 1; i <= limit; i++) { DepthLimitedSearch dls = new DepthLimitedSearch(i); List result = dls.search(p); iterationMetrics.set(NODES_EXPANDED, iterationMetrics .getInt(NODES_EXPANDED) + dls.getMetrics().getInt(NODES_EXPANDED)); if (!cutOffResult(result)) { return result; } } return new ArrayList();//failure } private boolean cutOffResult(List result) { //TODO remove this duplication return result.size() == 1 && result.get(0).equals("cutoff"); } public Metrics getMetrics() { return iterationMetrics; } public Object getGoalState(){ return(null); }; public List getPathStates() { throw new UnsupportedOperationException("Not supported yet."); } }
mit
vanting/course-java-example
src/ex4_5/WelcomeApplet.java
696
package ex4_5; // WelcomeApplet.java: Applet for displaying a message import javax.swing.*; public class WelcomeApplet extends JApplet { /** Construct the applet */ JLabel jlb; public WelcomeApplet() { jlb = new JLabel("Welcome to Java", JLabel.CENTER); add(jlb); repaint(); System.out.println("Construct..."); } public void init() { //jlb.setText("Init..."); System.out.println("Init..."); } public void start() { //jlb.setText("Start..."); System.out.println("Start..."); } public void stop() { //jlb.setText("Stop..."); System.out.println("Stop..."); } public void destroy() { //jlb.setText("Destory..."); System.out.println("Destory..."); } }
mit
jgonian/commons-ip-math
commons-ip-math/src/main/java/com/github/jgonian/ipmath/Asn.java
5213
/** * The MIT License (MIT) * * Copyright (c) 2011-2017, Yannis Gonianakis * * 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.github.jgonian.ipmath; import java.math.BigInteger; public final class Asn implements SingleInternetResource<Asn, AsnRange>, Comparable<Asn> { private static final long serialVersionUID = -1L; private static final int SIXTEEN = 16; private static final int THIRTY_TWO = 32; public static final long ASN_MIN_VALUE = 0L; public static final long ASN_16_BIT_MAX_VALUE = (1L << SIXTEEN) - 1L; public static final long ASN_32_BIT_MAX_VALUE = (1L << THIRTY_TWO) - 1L; public static final Asn FIRST_ASN = Asn.of(ASN_MIN_VALUE); public static final Asn LAST_16_BIT_ASN = Asn.of(ASN_16_BIT_MAX_VALUE); public static final Asn LAST_32_BIT_ASN = Asn.of(ASN_32_BIT_MAX_VALUE); public static final int NUMBER_OF_BITS = THIRTY_TWO; private final long value; public Asn(Long value) { this.value = Validate.notNull(value, "value is required"); Validate.checkRange(this.value, ASN_MIN_VALUE, ASN_32_BIT_MAX_VALUE); } long value() { return value; } public static Asn of(Long value) { return new Asn(value); } public static Asn of(String value) { return parse(value); } /** * Parses a <tt>String</tt> into an {@link Asn}. The representation formats that are supported are * asplain, asdot+ and asdot as defined in RFC5396. * * @param text a string of an AS number e.g. "AS123", "AS0.123", "123" e.t.c. * @return a new {@link Asn} * @throws IllegalArgumentException if the string cannot be parsed * @see <a href="http://tools.ietf.org/html/rfc5396">RFC5396 - * Textual Representation of Autonomous System (AS) Numbers</a> */ public static Asn parse(String text) { try { String asnString = Validate.notNull(text, "AS Number must not be null").trim().toUpperCase(); if (asnString.startsWith("AS")) { asnString = asnString.substring(2); } long low; long high = 0L; int indexOfDot = asnString.indexOf('.'); if (indexOfDot != -1) { low = Validate.checkRange(Long.valueOf(asnString.substring(indexOfDot + 1)), ASN_MIN_VALUE, ASN_16_BIT_MAX_VALUE); high = Validate.checkRange(Long.valueOf(asnString.substring(0, indexOfDot)), ASN_MIN_VALUE, ASN_16_BIT_MAX_VALUE); } else { low = Long.valueOf(asnString); } return new Asn((high << SIXTEEN) | low); } catch (Exception ex) { throw new IllegalArgumentException("Invalid AS number: '" + text + "'. Details: " + ex.getMessage(), ex); } } public boolean is16Bit() { return this.compareTo(LAST_16_BIT_ASN) <= 0; } public boolean is32Bit() { return !is16Bit(); } @Override public int compareTo(Asn other) { return value > other.value ? 1 : value < other.value ? -1 : 0; } @Override public Asn next() { return new Asn(value + 1); } @Override public Asn previous() { return new Asn(value - 1); } @Override public boolean hasNext() { return this.compareTo(LAST_32_BIT_ASN) < 0; } @Override public boolean hasPrevious() { return this.compareTo(FIRST_ASN) > 0; } @Override public String toString() { return "AS" + value; } @Override public AsnRange asRange() { return new AsnRange(this, this); } @Override public int bitSize() { return NUMBER_OF_BITS; } @Override public BigInteger asBigInteger() { return BigInteger.valueOf(value); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Asn that = (Asn) o; return value == that.value; } @Override public int hashCode() { return (int) (value ^ (value >>> 32)); } }
mit
sunyoboy/java-tutorial
java-tutorial/src/main/java/com/javase/net/jcip/examples/LifecycleWebServer.java
1578
package com.javase.net.jcip.examples; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.*; import java.util.logging.*; /** * LifecycleWebServer * <p/> * Web server with shutdown support * * @author Brian Goetz and Tim Peierls */ public class LifecycleWebServer { private final ExecutorService exec = Executors.newCachedThreadPool(); public void start() throws IOException { ServerSocket socket = new ServerSocket(80); while (!exec.isShutdown()) { try { final Socket conn = socket.accept(); exec.execute(new Runnable() { public void run() { handleRequest(conn); } }); } catch (RejectedExecutionException e) { if (!exec.isShutdown()) log("task submission rejected", e); } } } public void stop() { exec.shutdown(); } private void log(String msg, Exception e) { Logger.getAnonymousLogger().log(Level.WARNING, msg, e); } void handleRequest(Socket connection) { Request req = readRequest(connection); if (isShutdownRequest(req)) stop(); else dispatchRequest(req); } interface Request { } private Request readRequest(Socket s) { return null; } private void dispatchRequest(Request r) { } private boolean isShutdownRequest(Request r) { return false; } }
mit
mauricio-ms/generator-data-table-report
src/main/java/br/com/keyworks/generatordatatablereport/addcolumn/AddColumnForList.java
1126
package br.com.keyworks.generatordatatablereport.addcolumn; import ar.com.fdvs.dj.domain.builders.FastReportBuilder; import ar.com.fdvs.dj.domain.entities.columns.AbstractColumn; import br.com.keyworks.generatordatatablereport.annotations.ColumnReport.List; import br.com.keyworks.generatordatatablereport.customexpression.CustomExpressionForList; import br.com.keyworks.generatordatatablereport.model.DataColumn; /** * Classe para adicionar uma coluna * a um {@link FastReportBuilder} * quando o tipo de dado for um {@link List} * * Exibe a lista concateda por ', ' * * @see CustomExpressionForList * * @author mauricio.scopel * * @since 2 de jan de 2017 */ public final class AddColumnForList extends AddColumn { public AddColumnForList(final FastReportBuilder fastReportBuilder, final DataColumn dataColumn) { super(fastReportBuilder, dataColumn); } @Override public AbstractColumn getColumn() { return getBuilder() .setCustomExpression(new CustomExpressionForList( getDataColumn().getProperty(), getDataColumn().getColumnReport().whenNoData())) .build(); } }
mit
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/CIM/IEC61970/Informative/InfAssets/ShuntImpedanceInfo.java
26905
/** */ package CIM.IEC61970.Informative.InfAssets; import CIM.IEC61970.Core.PhaseCode; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Shunt Impedance Info</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLowVoltageOverride <em>Low Voltage Override</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getCellSize <em>Cell Size</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getHighVoltageOverride <em>High Voltage Override</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getRegBranchKind <em>Reg Branch Kind</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#isNormalOpen <em>Normal Open</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getShuntCompensatorInfos <em>Shunt Compensator Infos</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getRegBranchEnd <em>Reg Branch End</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#isVRegLineLine <em>VReg Line Line</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getSwitchOperationCycle <em>Switch Operation Cycle</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLocalOffLevel <em>Local Off Level</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getSensingPhaseCode <em>Sensing Phase Code</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLocalControlKind <em>Local Control Kind</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getBranchDirect <em>Branch Direct</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getMaxSwitchOperationCount <em>Max Switch Operation Count</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#isLocalOverride <em>Local Override</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLocalOnLevel <em>Local On Level</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getRegBranch <em>Reg Branch</em>}</li> * <li>{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getControlKind <em>Control Kind</em>}</li> * </ul> * * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Properties of a shunt impedance.'" * annotation="http://langdale.com.au/2005/UML Profile\040documentation='Properties of a shunt impedance.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Properties of a shunt impedance.' Profile\040documentation='Properties of a shunt impedance.'" * @generated */ public interface ShuntImpedanceInfo extends ElectricalInfo { /** * Returns the value of the '<em><b>Low Voltage Override</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Low Voltage Override</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Low Voltage Override</em>' attribute. * @see #setLowVoltageOverride(float) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_LowVoltageOverride() * @model dataType="CIM.IEC61970.Domain.PU" required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For locally controlled shunt impedances which have a voltage override feature, the low voltage override value. If the voltage is below this value, the shunt impedance will be turned on regardless of the other local controller settings.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For locally controlled shunt impedances which have a voltage override feature, the low voltage override value. If the voltage is below this value, the shunt impedance will be turned on regardless of the other local controller settings.'" * @generated */ float getLowVoltageOverride(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLowVoltageOverride <em>Low Voltage Override</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Low Voltage Override</em>' attribute. * @see #getLowVoltageOverride() * @generated */ void setLowVoltageOverride(float value); /** * Returns the value of the '<em><b>Cell Size</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Cell Size</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Cell Size</em>' attribute. * @see #setCellSize(float) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_CellSize() * @model dataType="CIM.IEC61970.Domain.ReactivePower" required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='The size of the individual units that make up the bank.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='The size of the individual units that make up the bank.'" * @generated */ float getCellSize(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getCellSize <em>Cell Size</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Cell Size</em>' attribute. * @see #getCellSize() * @generated */ void setCellSize(float value); /** * Returns the value of the '<em><b>High Voltage Override</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>High Voltage Override</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>High Voltage Override</em>' attribute. * @see #setHighVoltageOverride(float) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_HighVoltageOverride() * @model dataType="CIM.IEC61970.Domain.PU" required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For locally controlled shunt impedances which have a voltage override feature, the high voltage override value. If the voltage is above this value, the shunt impedance will be turned off regardless of the other local controller settings.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For locally controlled shunt impedances which have a voltage override feature, the high voltage override value. If the voltage is above this value, the shunt impedance will be turned off regardless of the other local controller settings.'" * @generated */ float getHighVoltageOverride(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getHighVoltageOverride <em>High Voltage Override</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>High Voltage Override</em>' attribute. * @see #getHighVoltageOverride() * @generated */ void setHighVoltageOverride(float value); /** * Returns the value of the '<em><b>Reg Branch Kind</b></em>' attribute. * The literals are from the enumeration {@link CIM.IEC61970.Informative.InfAssets.RegulationBranchKind}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Reg Branch Kind</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Reg Branch Kind</em>' attribute. * @see CIM.IEC61970.Informative.InfAssets.RegulationBranchKind * @see #setRegBranchKind(RegulationBranchKind) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_RegBranchKind() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='(For VAR, amp, or power factor locally controlled shunt impedances) Kind of regulation branch.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='(For VAR, amp, or power factor locally controlled shunt impedances) Kind of regulation branch.'" * @generated */ RegulationBranchKind getRegBranchKind(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getRegBranchKind <em>Reg Branch Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Reg Branch Kind</em>' attribute. * @see CIM.IEC61970.Informative.InfAssets.RegulationBranchKind * @see #getRegBranchKind() * @generated */ void setRegBranchKind(RegulationBranchKind value); /** * Returns the value of the '<em><b>Normal Open</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Normal Open</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Normal Open</em>' attribute. * @see #setNormalOpen(boolean) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_NormalOpen() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='True if open is normal status for a fixed capacitor bank, otherwise normal status is closed.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='True if open is normal status for a fixed capacitor bank, otherwise normal status is closed.'" * @generated */ boolean isNormalOpen(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#isNormalOpen <em>Normal Open</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Normal Open</em>' attribute. * @see #isNormalOpen() * @generated */ void setNormalOpen(boolean value); /** * Returns the value of the '<em><b>Shunt Compensator Infos</b></em>' reference list. * The list contents are of type {@link CIM.IEC61970.Informative.InfAssets.ShuntCompensatorInfo}. * It is bidirectional and its opposite is '{@link CIM.IEC61970.Informative.InfAssets.ShuntCompensatorInfo#getShuntImpedanceInfo <em>Shunt Impedance Info</em>}'. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Shunt Compensator Infos</em>' reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Shunt Compensator Infos</em>' reference list. * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_ShuntCompensatorInfos() * @see CIM.IEC61970.Informative.InfAssets.ShuntCompensatorInfo#getShuntImpedanceInfo * @model opposite="ShuntImpedanceInfo" * @generated */ EList<ShuntCompensatorInfo> getShuntCompensatorInfos(); /** * Returns the value of the '<em><b>Reg Branch End</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Reg Branch End</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Reg Branch End</em>' attribute. * @see #setRegBranchEnd(int) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_RegBranchEnd() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For VAR, amp, or power factor locally controlled shunt impedances, the end of the branch that is regulated. The field has the following values: from side, to side, and tertiary (only if the branch is a transformer).'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For VAR, amp, or power factor locally controlled shunt impedances, the end of the branch that is regulated. The field has the following values: from side, to side, and tertiary (only if the branch is a transformer).'" * @generated */ int getRegBranchEnd(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getRegBranchEnd <em>Reg Branch End</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Reg Branch End</em>' attribute. * @see #getRegBranchEnd() * @generated */ void setRegBranchEnd(int value); /** * Returns the value of the '<em><b>VReg Line Line</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>VReg Line Line</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>VReg Line Line</em>' attribute. * @see #setVRegLineLine(boolean) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_VRegLineLine() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='True if regulated voltages are measured line to line, otherwise they are measured line to ground.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='True if regulated voltages are measured line to line, otherwise they are measured line to ground.'" * @generated */ boolean isVRegLineLine(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#isVRegLineLine <em>VReg Line Line</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>VReg Line Line</em>' attribute. * @see #isVRegLineLine() * @generated */ void setVRegLineLine(boolean value); /** * Returns the value of the '<em><b>Switch Operation Cycle</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Switch Operation Cycle</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Switch Operation Cycle</em>' attribute. * @see #setSwitchOperationCycle(float) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_SwitchOperationCycle() * @model dataType="CIM.IEC61970.Domain.Hours" required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Time interval between consecutive switching operations.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Time interval between consecutive switching operations.'" * @generated */ float getSwitchOperationCycle(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getSwitchOperationCycle <em>Switch Operation Cycle</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Switch Operation Cycle</em>' attribute. * @see #getSwitchOperationCycle() * @generated */ void setSwitchOperationCycle(float value); /** * Returns the value of the '<em><b>Local Off Level</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Local Off Level</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Local Off Level</em>' attribute. * @see #setLocalOffLevel(String) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_LocalOffLevel() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Upper control setting.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Upper control setting.'" * @generated */ String getLocalOffLevel(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLocalOffLevel <em>Local Off Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Local Off Level</em>' attribute. * @see #getLocalOffLevel() * @generated */ void setLocalOffLevel(String value); /** * Returns the value of the '<em><b>Sensing Phase Code</b></em>' attribute. * The literals are from the enumeration {@link CIM.IEC61970.Core.PhaseCode}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Sensing Phase Code</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Sensing Phase Code</em>' attribute. * @see CIM.IEC61970.Core.PhaseCode * @see #setSensingPhaseCode(PhaseCode) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_SensingPhaseCode() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Phases that are measured for controlling the device.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Phases that are measured for controlling the device.'" * @generated */ PhaseCode getSensingPhaseCode(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getSensingPhaseCode <em>Sensing Phase Code</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Sensing Phase Code</em>' attribute. * @see CIM.IEC61970.Core.PhaseCode * @see #getSensingPhaseCode() * @generated */ void setSensingPhaseCode(PhaseCode value); /** * Returns the value of the '<em><b>Local Control Kind</b></em>' attribute. * The literals are from the enumeration {@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceLocalControlKind}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Local Control Kind</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Local Control Kind</em>' attribute. * @see CIM.IEC61970.Informative.InfAssets.ShuntImpedanceLocalControlKind * @see #setLocalControlKind(ShuntImpedanceLocalControlKind) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_LocalControlKind() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Kind of local controller.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Kind of local controller.'" * @generated */ ShuntImpedanceLocalControlKind getLocalControlKind(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLocalControlKind <em>Local Control Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Local Control Kind</em>' attribute. * @see CIM.IEC61970.Informative.InfAssets.ShuntImpedanceLocalControlKind * @see #getLocalControlKind() * @generated */ void setLocalControlKind(ShuntImpedanceLocalControlKind value); /** * Returns the value of the '<em><b>Branch Direct</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Branch Direct</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Branch Direct</em>' attribute. * @see #setBranchDirect(int) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_BranchDirect() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For VAR, amp, or power factor locally controlled shunt impedances, the flow direction: in, out.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For VAR, amp, or power factor locally controlled shunt impedances, the flow direction: in, out.'" * @generated */ int getBranchDirect(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getBranchDirect <em>Branch Direct</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Branch Direct</em>' attribute. * @see #getBranchDirect() * @generated */ void setBranchDirect(int value); /** * Returns the value of the '<em><b>Max Switch Operation Count</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Max Switch Operation Count</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Max Switch Operation Count</em>' attribute. * @see #setMaxSwitchOperationCount(int) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_MaxSwitchOperationCount() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='IdmsShuntImpedanceData.maxNumSwitchOps'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='IdmsShuntImpedanceData.maxNumSwitchOps'" * @generated */ int getMaxSwitchOperationCount(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getMaxSwitchOperationCount <em>Max Switch Operation Count</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Max Switch Operation Count</em>' attribute. * @see #getMaxSwitchOperationCount() * @generated */ void setMaxSwitchOperationCount(int value); /** * Returns the value of the '<em><b>Local Override</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Local Override</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Local Override</em>' attribute. * @see #setLocalOverride(boolean) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_LocalOverride() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='True if the locally controlled capacitor has voltage override capability.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='True if the locally controlled capacitor has voltage override capability.'" * @generated */ boolean isLocalOverride(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#isLocalOverride <em>Local Override</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Local Override</em>' attribute. * @see #isLocalOverride() * @generated */ void setLocalOverride(boolean value); /** * Returns the value of the '<em><b>Local On Level</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Local On Level</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Local On Level</em>' attribute. * @see #setLocalOnLevel(String) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_LocalOnLevel() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Lower control setting.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Lower control setting.'" * @generated */ String getLocalOnLevel(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getLocalOnLevel <em>Local On Level</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Local On Level</em>' attribute. * @see #getLocalOnLevel() * @generated */ void setLocalOnLevel(String value); /** * Returns the value of the '<em><b>Reg Branch</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Reg Branch</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Reg Branch</em>' attribute. * @see #setRegBranch(String) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_RegBranch() * @model required="true" * annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='For VAR, amp, or power factor locally controlled shunt impedances, the index of the regulation branch.'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='For VAR, amp, or power factor locally controlled shunt impedances, the index of the regulation branch.'" * @generated */ String getRegBranch(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getRegBranch <em>Reg Branch</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Reg Branch</em>' attribute. * @see #getRegBranch() * @generated */ void setRegBranch(String value); /** * Returns the value of the '<em><b>Control Kind</b></em>' attribute. * The literals are from the enumeration {@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceControlKind}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Control Kind</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Control Kind</em>' attribute. * @see CIM.IEC61970.Informative.InfAssets.ShuntImpedanceControlKind * @see #setControlKind(ShuntImpedanceControlKind) * @see CIM.IEC61970.Informative.InfAssets.InfAssetsPackage#getShuntImpedanceInfo_ControlKind() * @model annotation="http://iec.ch/TC57/2009/CIM-schema-cim14 Documentation='Kind of control (if any).'" * annotation="http://www.eclipse.org/emf/2002/GenModel Documentation='Kind of control (if any).'" * @generated */ ShuntImpedanceControlKind getControlKind(); /** * Sets the value of the '{@link CIM.IEC61970.Informative.InfAssets.ShuntImpedanceInfo#getControlKind <em>Control Kind</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Control Kind</em>' attribute. * @see CIM.IEC61970.Informative.InfAssets.ShuntImpedanceControlKind * @see #getControlKind() * @generated */ void setControlKind(ShuntImpedanceControlKind value); } // ShuntImpedanceInfo
mit
leotizzei/MobileMedia-Cosmos-v2
src/br/unicamp/ic/sed/mobilemedia/photo_mobilephonemgr/impl/IMobilePhoneAdapter.java
638
package br.unicamp.ic.sed.mobilemedia.photo_mobilephonemgr.impl; import javax.microedition.lcdui.Command; import br.unicamp.ic.sed.mobilemedia.photo.spec.req.IMobilePhone; class IMobilePhoneAdapter implements IMobilePhone{ Manager manager; IMobilePhoneAdapter(Manager mgr) { manager = mgr; } public void postCommand ( Command comand ){ br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.prov.IMobilePhone mobilePhone; mobilePhone = (br.unicamp.ic.sed.mobilemedia.mobilephonemgr.spec.prov.IMobilePhone)manager.getRequiredInterface("IMobilePhone"); mobilePhone.postCommand(comand); } }
mit
solambda/swiffer
swiffer-api/src/main/java/com/solambda/swiffer/api/OnChildWorkflowCanceled.java
1121
package com.solambda.swiffer.api; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import com.amazonaws.services.simpleworkflow.model.ChildWorkflowExecutionCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.EventType; /** * Handler for the {@link EventType#ChildWorkflowExecutionCanceled} event. * <p> * The annotated method may have the following parameters: * <ul> * <li>any parameter that is common to all event handlers * <li>the default parameter is {@link String} {@code details}: the details provided for workflow cancellation (if any). * </ul> * * @see EventHandlerCommonParameter * @see ChildWorkflowExecutionCanceledEventAttributes */ @Documented @Retention(RUNTIME) @Target(METHOD) @EventHandler public @interface OnChildWorkflowCanceled { /** * The child {@link WorkflowType} that was cancelled. * * @return the cancelled workflow type */ Class<?> value(); }
mit
nobullet/library
src/main/java/com/nobullet/algo/CoinChange.java
3514
package com.nobullet.algo; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * Coin/bill change problem: http://stackoverflow.com/questions/2633848/dynamic-programming-coin-change-decision?rq=1 */ public class CoinChange { /** * Returns minimal number of coins to give change. Very slow as recalculates previous results again and again. * * @param sum Sum. * @param denominations Available denominations. Note: for US coins greedy solution works fine. * @return Minimal number of coins to give change. */ public static int getMinimumNumberOfCoinsRecursive(int sum, Set<Integer> denominations) { if (sum <= 0 || denominations == null || denominations.isEmpty()) { throw new IllegalArgumentException("Expected non empty set of integers and positive sum."); } if (denominations.contains(sum)) { return 1; } int min = Integer.MAX_VALUE; int result = min; for (Integer denomination : denominations) { if (sum > denomination) { min = 1 + getMinimumNumberOfCoinsRecursive(sum - denomination, denominations); if (result > min) { result = min; } } } if (result == Integer.MAX_VALUE) { return 0; } return result; } /** * Returns optimal solution for minimal number of coins to give change. Internal cameFrom path could be re-used and * solution could be returned in O(1) from cache. * * @param sum Sum. * @param denominations Coin denominations. * @return Set of coins that builds the sum. Or empty list when there is no solution. */ public static List<Integer> getChange(int sum, Set<Integer> denominations) { if (denominations == null || denominations.isEmpty() || sum <= 0) { throw new IllegalArgumentException("Expected non empty set of integers and positive sum."); } Map<Integer, Integer> cameFrom = new HashMap<>(); // Path. Map<Integer, Integer> solutions = new HashMap<>(); solutions.put(0, 0); solutions.put(sum, Integer.MAX_VALUE); for (int x = 1; x <= sum; x++) { solutions.put(x, Integer.MAX_VALUE); for (Integer denomination : denominations) { if (x >= denomination) { // Look for previous solution. Integer previous = solutions.get(x - denomination); if (previous != null && previous != Integer.MAX_VALUE && previous + 1 < solutions.get(x)) { solutions.put(x, previous + 1); cameFrom.put(x, x - denomination); } } } } // Came from contains all the paths for all the sums: 1..sum Integer result = solutions.get(sum); if (result == null || result == Integer.MAX_VALUE) { return Collections.emptyList(); } List<Integer> change = new ArrayList<>(); int remaining = sum; while (cameFrom.containsKey(remaining)) { int diff = remaining - cameFrom.get(remaining); change.add(diff); remaining = cameFrom.get(remaining); } Collections.sort(change); return change; } private CoinChange() { } }
mit
ajayramesh23/ubiquitous-eureka
TTG_Spark/src/main/java/spark_trial/PiExample.java
1139
package spark_trial; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import java.util.ArrayList; import java.util.List; /** * SparkPi example used for testing. * * Based on https://github.com/apache/spark/blob/master/examples/src/main/java/org/apache/spark/examples/JavaSparkPi.java */ public class PiExample { public static void main(String... argv) { System.out.println("Solving Pi"); JavaSparkContext sc = new JavaSparkContext("local[4]", "PiSample"); int slices = sc.defaultParallelism(); int n = 100000 * slices; List<Integer> l = new ArrayList<>(n); for (int i = 0; i < n; i++) { l.add(i); } JavaRDD<Integer> dataSet = sc.parallelize(l, slices); int count = dataSet.map(i -> { double x = Math.random() * 2 - 1; double y = Math.random() * 2 - 1; return (x * x + y * y < 1) ? 1 : 0; }).reduce((i1, i2) -> i1 + i2); double pi = 4.0 * (double)count / (double)n; System.out.println("Pi is roughly " + pi); sc.stop(); } }
mit
androididentification/android
servlet/src/com/tum/ident/fastdtw/dtw/WarpPathWindow.java
757
/* * WarpPathWindow.java Jul 14, 2004 * * PROJECT DESCRIPTION */ package com.tum.ident.fastdtw.dtw; /** * This class... * * @author Stan Salvador, stansalvador@hotmail.com * @version last changed: Jun 30, 2004 * @see * @since Jun 30, 2004 */ public class WarpPathWindow extends SearchWindow { // CONSTANTS private final static int defaultRadius = 0; // CONSTRUCTORS public WarpPathWindow(WarpPath path, int searchRadius) { super(path.get(path.size()-1).getCol()+1, path.get(path.size()-1).getRow()+1); for (int p=0; p<path.size(); p++) super.markVisited(path.get(p).getCol(), path.get(p).getRow()); super.expandWindow(searchRadius); } // end Constructor } // end class WarpPathWindow
mit
karim/adila
database/src/main/java/adila/db/vee7e_lg2dp713tr.java
220
// This file is automatically generated. package adila.db; /* * LG Optimus L7 II * * DEVICE: vee7e * MODEL: LG-P713TR */ final class vee7e_lg2dp713tr { public static final String DATA = "LG|Optimus L7 II|"; }
mit
Bjornkjohnson/javaServer
src/test/java/bjohnson/ParameterParserTest.java
1796
package bjohnson; import org.junit.Test; import static org.junit.Assert.*; public class ParameterParserTest { @Test public void TestReturnsArrayOfSizeOneForSimpleString() throws Exception { ParameterParser parameterParser = new ParameterParser(); assertEquals(1, parameterParser.parseParameters("/route?params").length); } @Test public void TestRemovesRoute() throws Exception { ParameterParser parameterParser = new ParameterParser(); assertEquals("params", parameterParser.parseParameters("/route?params")[0]); } @Test public void TestParserSplitsOnAmpersand() throws Exception { ParameterParser parameterParser = new ParameterParser(); assertEquals(2, parameterParser.parseParameters("/route?params&otherParams").length); assertEquals("params", parameterParser.parseParameters("/route?params&otherParams")[0]); assertEquals("otherParams", parameterParser.parseParameters("/route?params&otherParams")[1]); } @Test public void TestParserReplacesAllCharactersGivenAHash() throws Exception { ParameterParser parameterParser = new ParameterParser(); String rawParams = "/parameters?variable_1=Operators%20%3C%2C%20%3E%2C%20%3D%2C%20!%3D%3B%20%2B%2C%20-%2C%20*%2C%20%26%2C%20%40%2C%20%23%2C%20%24%2C%20%5B%2C%20%5D%3A%20%22is%20that%20all%22%3F&variable_2=stuff"; String parsedParams1 = "variable_1 = Operators <, >, =, !=; +, -, *, &, @, #, $, [, ]: \"is that all\"?"; String parsedParams2 = "variable_2 = stuff"; String paramsArray[] = parameterParser.parseParameters(rawParams); assertEquals(2, paramsArray.length); assertEquals(parsedParams1, paramsArray[0]); assertEquals(parsedParams2, paramsArray[1]); } }
mit
divotkey/cogaen3-java
Cogaen LWJGL/src/org/cogaen/lwjgl/resource/SpriteResourceParser.java
1493
package org.cogaen.lwjgl.resource; import javax.xml.stream.XMLStreamReader; import org.cogaen.core.Core; import org.cogaen.lwjgl.scene.SpriteHandle; import org.cogaen.name.CogaenId; import org.cogaen.resource.AbstractXmlResourceParser; import org.cogaen.resource.ParsingException; import org.cogaen.resource.ResourceHandle; import org.cogaen.resource.ResourceService; public class SpriteResourceParser extends AbstractXmlResourceParser { public static final String RESOURCE_TYPE = "sprite"; private static final String WIDTH_ATTR = "width"; private static final String HEIGHT_ATTR = "height"; private static final String TEXTURE_ATTR = "texture"; public SpriteResourceParser(Core core) { super(core); } @Override public void parseResource(XMLStreamReader xmlReader, CogaenId groupId) throws ParsingException { ResourceService resSrv = ResourceService.getInstance(getCore()); ResourceHandle handle = new SpriteHandle(parseTexture(xmlReader), parseWidth(xmlReader), parseHeight(xmlReader)); resSrv.declareResource(parseName(xmlReader), groupId, handle); } private String parseTexture(XMLStreamReader xmlReader) throws ParsingException { return parseAttribute(xmlReader, TEXTURE_ATTR); } private double parseWidth(XMLStreamReader xmlReader) throws ParsingException { return parseDouble(xmlReader, WIDTH_ATTR); } private double parseHeight(XMLStreamReader xmlReader) throws ParsingException { return parseDouble(xmlReader, HEIGHT_ATTR); } }
mit
changedi/better-spring
src/test/java/com/cloudex/spring/jdbc/UserDO.java
475
package com.cloudex.spring.jdbc; /** * Created by zunyuan.jy on 16/11/20. */ public class UserDO { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { return "[" + id + ":" + name + "]"; } }
mit
RaimondKempees/fast-classpath-scanner
src/test/java/io/github/lukehutch/fastclasspathscanner/test/whitelisted/blacklistedsub/BlacklistedSub.java
115
package io.github.lukehutch.fastclasspathscanner.test.whitelisted.blacklistedsub; public class BlacklistedSub { }
mit
fordfrog/apgdiff
src/main/java/cz/startnet/utils/pgdiff/parsers/Parser.java
15942
/** * Copyright 2006 StartNet s.r.o. * * Distributed under MIT license */ package cz.startnet.utils.pgdiff.parsers; import cz.startnet.utils.pgdiff.Resources; import java.text.MessageFormat; import java.util.Locale; /** * Class for parsing strings. * * @author fordfrog */ @SuppressWarnings("FinalClass") public final class Parser { /** * String to be parsed. */ private String string; /** * Current position. */ private int position; /** * Creates new instance of Parser. * * @param string {@link #string} */ public Parser(final String string) { this.string = string; skipWhitespace(); } /** * Checks whether the string contains given word on current position. If not * then throws an exception. * * @param words list of words to check */ public void expect(final String... words) { for (final String word : words) { expect(word, false); } } /** * Checks whether the string contains given word on current position. If not * and expectation is optional then position is not changed and method * returns true. If expectation is not optional, exception with error * description is thrown. If word is found, position is moved at first * non-whitespace character following the word. * * @param word word to expect * @param optional true if word is optional, otherwise false * * @return true if word was found, otherwise false */ public boolean expect(final String word, final boolean optional) { final int wordEnd = position + word.length(); if (wordEnd <= string.length() && string.substring(position, wordEnd).equalsIgnoreCase(word) && (wordEnd == string.length() || Character.isWhitespace(string.charAt(wordEnd)) || string.charAt(wordEnd) == '(' || string.charAt(wordEnd) == ')' || string.charAt(wordEnd) == ';' || string.charAt(wordEnd) == ',' || string.charAt(wordEnd) == '[' || "(".equals(word) || ",".equals(word) || "[".equals(word) || "]".equals(word))) { position = wordEnd; skipWhitespace(); return true; } if (optional) { return false; } int dumpEndPosition = position + 20; if (string.length() - (position + 1) < 20) { dumpEndPosition = string.length() - 1; } throw new ParserException(MessageFormat.format( Resources.getString("CannotParseStringExpectedWord"), string, word, position + 1, string.substring(position, dumpEndPosition))); } /** * Checks whether string contains at current position sequence of the words. * * @param words array of words * * @return true if whole sequence was found, otherwise false */ public boolean expectOptional(final String... words) { final int oldPosition = position; boolean found = expect(words[0], true); if (!found) { return false; } for (int i = 1; i < words.length; i++) { skipWhitespace(); found = expect(words[i], true); if (!found) { position = oldPosition; return false; } } return true; } /** * Moves position in the string to next non-whitespace string. */ public void skipWhitespace() { for (; position < string.length(); position++) { if (!Character.isWhitespace(string.charAt(position))) { break; } } } /** * Parses identifier from current position. If identifier is quoted, it is * returned quoted. If the identifier is not quoted, it is converted to * lowercase. If identifier does not start with letter then exception is * thrown. Position is placed at next first non-whitespace character. * * @return parsed identifier */ public String parseIdentifier() { String identifier = parseIdentifierInternal(); while (string.charAt(position) == '.') { position++; identifier += '.' + parseIdentifierInternal(); } skipWhitespace(); return identifier; } /** * Parses single part of the identifier. * * @return parsed identifier */ private String parseIdentifierInternal() { final boolean quoted = string.charAt(position) == '"'; if (quoted) { final int endPos = string.indexOf('"', position + 1); final String result = string.substring(position, endPos + 1); position = endPos + 1; return result; } else { int endPos = position; for (; endPos < string.length(); endPos++) { final char chr = string.charAt(endPos); if (Character.isWhitespace(chr) || chr == ',' || chr == ')' || chr == '(' || chr == ';' || chr == '.') { break; } } final String result = string.substring(position, endPos).toLowerCase( Locale.ENGLISH); position = endPos; return result; } } /** * Returns rest of the string. If the string ends with ';' then it is * removed from the string before returned. If there is nothing more in the * string, null is returned. * * @return rest of the string, without trailing ';' if present, or null if * there is nothing more in the string */ public String getRest() { final String result; if (string.charAt(string.length() - 1) == ';') { if (position == string.length() - 1) { return null; } else { result = string.substring(position, string.length() - 1); } } else { result = string.substring(position); } position = string.length(); return result; } /** * Parses integer from the string. If next word is not integer then * exception is thrown. * * @return parsed integer value */ public int parseInteger() { int endPos = position; for (; endPos < string.length(); endPos++) { if (!Character.isLetterOrDigit(string.charAt(endPos))) { break; } } try { final int result = Integer.parseInt(string.substring(position, endPos)); position = endPos; skipWhitespace(); return result; } catch (final NumberFormatException ex) { throw new ParserException(MessageFormat.format( Resources.getString("CannotParseStringExpectedInteger"), string, position + 1, string.substring(position, position + 20)), ex); } } /** * Parses string from the string. String can be either quoted or unqouted. * Quoted string is parsed till next unescaped quote. Unquoted string is * parsed till whitespace, ',' ')' or ';' is found. If string should be * empty, exception is thrown. * * @return parsed string, if quoted then including quotes */ public String parseString() { final boolean quoted = string.charAt(position) == '\''; if (quoted) { boolean escape = false; int endPos = position + 1; for (; endPos < string.length(); endPos++) { final char chr = string.charAt(endPos); if (chr == '\\') { escape = !escape; } else if (!escape && chr == '\'') { if (endPos + 1 < string.length() && string.charAt(endPos + 1) == '\'') { endPos++; } else { break; } } } final String result; try { if (endPos >= string.length()) { //try to fix StringIndexOutOfBoundsException endPos = string.lastIndexOf('\''); } result = string.substring(position, endPos + 1); } catch (final Throwable ex) { throw new RuntimeException("Failed to get substring: " + string + " start pos: " + position + " end pos: " + (endPos + 1), ex); } position = endPos + 1; skipWhitespace(); return result; } else { int endPos = position; for (; endPos < string.length(); endPos++) { final char chr = string.charAt(endPos); if (Character.isWhitespace(chr) || chr == ',' || chr == ')' || chr == ';') { break; } } if (position == endPos) { throw new ParserException(MessageFormat.format( Resources.getString("CannotParseStringExpectedString"), string, position + 1)); } final String result = string.substring(position, endPos); position = endPos; skipWhitespace(); return result; } } /** * Returns expression that is ended either with ',', ')' or with end of the * string. If expression is empty then exception is thrown. * * @return expression string */ public String getExpression() { final int endPos = getExpressionEnd(); if (position == endPos) { throw new ParserException(MessageFormat.format( Resources.getString("CannotParseStringExpectedExpression"), string, position + 1, string.substring(position, position + 20))); } final String result = string.substring(position, endPos).trim(); position = endPos; return result; } /** * Returns position of last character of single command within statement * (like CREATE TABLE). Last character is either ',' or ')'. If no such * character is found and method reaches the end of the command then * position after the last character in the command is returned. * * @return end position of the command * * @todo Support for dollar quoted strings is missing here. */ private int getExpressionEnd() { int bracesCount = 0; boolean singleQuoteOn = false; int charPos = position; for (; charPos < string.length(); charPos++) { final char chr = string.charAt(charPos); if (chr == '(' || chr == '[') { bracesCount++; } else if (chr == ')' || chr == ']') { if (bracesCount == 0) { break; } else { bracesCount--; } } else if (chr == '\'') { singleQuoteOn = !singleQuoteOn; // escaped single quote is like two single quotes if (charPos > 0 && string.charAt(charPos - 1) == '\\') { singleQuoteOn = !singleQuoteOn; } } else if ((chr == ',') && !singleQuoteOn && (bracesCount == 0)) { break; } else if (chr == ';' && bracesCount == 0 && !singleQuoteOn) { break; } } return charPos; } /** * Returns current position in the string. * * @return current position in the string */ public int getPosition() { return position; } /** * Returns parsed string. * * @return parsed string */ public String getString() { return string; } /** * Throws exception about unsupported command in statement. */ public void throwUnsupportedCommand() { throw new ParserException(MessageFormat.format( Resources.getString("CannotParseStringUnsupportedCommand"), string, position + 1, string.substring(position, string.length() > position + 20 ? position + 20 : string.length()))); } /** * Checks whether one of the words is present at current position. If the * word is present then the word is returned and position is updated. * * @param words words to check * * @return found word or null if non of the words has been found * * @see #expectOptional(java.lang.String[]) */ public String expectOptionalOneOf(final String... words) { for (final String word : words) { if (expectOptional(word)) { return word; } } return null; } /** * Returns substring from the string. * * @param startPos start position * @param endPos end position exclusive * * @return substring */ public String getSubString(final int startPos, final int endPos) { return string.substring(startPos, endPos); } /** * Changes current position in the string. * * @param position new position */ public void setPosition(final int position) { this.position = position; } /** * Parses data type from the string. Position is updated. If data type * definition is not found then exception is thrown. * * @return data type string */ public String parseDataType() { int endPos = position; while (endPos < string.length() && !Character.isWhitespace(string.charAt(endPos)) && string.charAt(endPos) != '(' && string.charAt(endPos) != ')' && string.charAt(endPos) != ',') { endPos++; } if (endPos == position) { throw new ParserException(MessageFormat.format( Resources.getString("CannotParseStringExpectedDataType"), string, position + 1, string.substring(position, position + 20))); } String dataType = string.substring(position, endPos); position = endPos; skipWhitespace(); if ("character".equalsIgnoreCase(dataType) && expectOptional("varying")) { dataType = "character varying"; } else if ("double".equalsIgnoreCase(dataType) && expectOptional("precision")) { dataType = "double precision"; } final boolean timestamp = "timestamp".equalsIgnoreCase(dataType) || "time".equalsIgnoreCase(dataType); if (string.charAt(position) == '(') { dataType += getExpression(); } if (timestamp) { if (expectOptional("with", "time", "zone")) { dataType += " with time zone"; } else if (expectOptional("without", "time", "zone")) { dataType += " without time zone"; } } if (expectOptional("[")) { expect("]"); dataType += "[]"; } return dataType; } /** * Checks whether the whole string has been consumed. * * @return true if there is nothing left to parse, otherwise false */ public boolean isConsumed() { return position == string.length() || position + 1 == string.length() && string.charAt(position) == ';'; } }
mit
HerrB92/obp
OpenBeaconPackage/libraries/hibernate-release-4.2.7.SP1/project/hibernate-core/src/test/java/org/hibernate/test/annotations/embeddables/DollarValueUserType.java
3220
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2012, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.test.annotations.embeddables; import java.io.Serializable; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; import org.hibernate.HibernateException; import org.hibernate.engine.spi.SessionImplementor; import org.hibernate.usertype.UserType; /** * @author Chris Pheby */ public class DollarValueUserType implements UserType { @Override public int[] sqlTypes() { return new int[] {Types.BIGINT}; } @Override public Class<DollarValue> returnedClass() { return DollarValue.class; } @Override public boolean equals(Object x, Object y) throws HibernateException { if (!(x instanceof DollarValue) || !(y instanceof DollarValue)) { throw new HibernateException("Expected DollarValue"); } return ((DollarValue)x).getAmount().equals(((DollarValue)y).getAmount()); } @Override public int hashCode(Object x) throws HibernateException { if (!(x instanceof DollarValue)) { throw new HibernateException("Expected DollarValue"); } return ((DollarValue)x).getAmount().hashCode(); } @Override public DollarValue nullSafeGet(ResultSet rs, String[] names, SessionImplementor session, Object owner) throws HibernateException, SQLException { DollarValue result = new DollarValue(rs.getBigDecimal(rs.findColumn(names[0]))); return result; } @Override public void nullSafeSet(PreparedStatement st, Object value, int index, SessionImplementor session) throws HibernateException, SQLException { st.setBigDecimal(index, ((DollarValue)value).getAmount()); } @Override public Object deepCopy(Object value) throws HibernateException { DollarValue result = new DollarValue(); return result; } @Override public boolean isMutable() { return false; } @Override public Serializable disassemble(Object value) throws HibernateException { return null; } @Override public Object assemble(Serializable cached, Object owner) throws HibernateException { return null; } @Override public Object replace(Object original, Object target, Object owner) throws HibernateException { return null; } }
mit
srp33/ShinyLearner
JavaCode/src/shinylearner/dataprocessors/ArffDataProcessor.java
5032
package shinylearner.dataprocessors; import shinylearner.core.DataInstanceCollection; import shinylearner.helper.BigFileReader; import shinylearner.helper.ListUtilities; import shinylearner.helper.MiscUtilities; import java.util.ArrayList; import java.util.HashMap; /** This data processor class is designed to parse text files in the ARFF format. * @author Stephen Piccolo */ public class ArffDataProcessor extends AbstractDataProcessor { /** This constructor accepts a relative path to an ARFF file that will be parsed. * @param filePath Relative or absolute path where the file is located (under the InputData directory) */ public ArffDataProcessor(String filePath) { DataFilePath = filePath; } @Override public ArrayList<String> ParseInstanceIDs() throws Exception { int idIndex = ParseDataPointNames("").indexOf("ID"); if (idIndex != -1) { BigFileReader reader = new BigFileReader(DataFilePath); ArrayList<String> instanceIDs = new ArrayList<String>(); boolean data = false; for (String line : reader) { if (line.startsWith("%")) continue; if (line.toUpperCase().startsWith("@DATA")) { data = true; continue; } if (data) instanceIDs.add(ListUtilities.CreateStringList(line.trim().split(",")).get(idIndex)); } reader.Close(); return instanceIDs; } BigFileReader reader = new BigFileReader(DataFilePath); ArrayList<String> instanceIDs = null; for (String line : reader) { if (line.startsWith("%")) continue; if (line.toUpperCase().startsWith("@DATA")) instanceIDs = new ArrayList<String>(); else { if (instanceIDs != null) instanceIDs.add("Instance" + (instanceIDs.size() + 1)); } } reader.Close(); return instanceIDs; } @Override public ArrayList<String> ParseDataPointNames(String dataPointNamePrefix) throws Exception { BigFileReader reader = new BigFileReader(DataFilePath); ArrayList<String> dataPointNames = new ArrayList<String>(); for (String line : reader) { if (line.toUpperCase().startsWith("@ATTRIBUTE")) { ArrayList<String> rowItems = new ArrayList<String>(); for (String item : ListUtilities.CreateStringList(line.split(" "))) if (item != " ") rowItems.add(item); String dataPointName = rowItems.get(1).trim(); dataPointName = MiscUtilities.trimSpecific(dataPointName, "'"); if (dataPointName.toUpperCase().equals("ID")) dataPointName = "ID"; if (dataPointName.toUpperCase().equals("CLASS")) dataPointName = "Class"; dataPointNames.add(dataPointName); } } reader.Close(); PrefixDataPointNames(dataPointNames, dataPointNamePrefix); return dataPointNames; } @Override public void SaveData(DataInstanceCollection dataInstanceCollection, String dataPointNamePrefix) throws Exception { ArrayList<String> dataPointNames = ParseDataPointNames(dataPointNamePrefix); ArrayList<String> instanceIDs = ParseInstanceIDs(); BigFileReader reader = new BigFileReader(DataFilePath); int instanceCount = -1; HashMap<String, String> nameValueMap; for (String line : reader) { if (line.startsWith("%")) continue; if (line.toUpperCase().startsWith("@DATA")) instanceCount = 0; else { if (instanceCount > -1) { String instanceID = instanceIDs.get(instanceCount); instanceCount++; int masterInstanceIndex = dataInstanceCollection.GetIndexOfInstance(instanceID); if (masterInstanceIndex == -1) continue; ArrayList<String> rowValues = ListUtilities.CreateStringList(line.trim().split(",")); nameValueMap = new HashMap<String, String>(); for (int i=0; i<rowValues.size(); i++) { String dataPointName = dataPointNames.get(i); if (dataPointName != "ID") nameValueMap.put(dataPointNames.get(i), MiscUtilities.trimSpecific(rowValues.get(i), "'")); } dataInstanceCollection.SetValues(masterInstanceIndex, nameValueMap); } } } reader.Close(); } }
mit
PoisonBOx/design-patterns
src/command/java/Invoker.java
247
package command; public class Invoker { private Command command = null; public void setCommand(Command command) { System.out.println("Invoker: setCommand"); this.command = command; } public void runCommand() { command.execute(); } }
mit
flesire/ontrack
ontrack-service/src/main/java/net/nemerosa/ontrack/service/DecorationServiceImpl.java
2790
package net.nemerosa.ontrack.service; import net.nemerosa.ontrack.common.BaseException; import net.nemerosa.ontrack.extension.api.DecorationExtension; import net.nemerosa.ontrack.extension.api.ExtensionManager; import net.nemerosa.ontrack.model.security.SecurityService; import net.nemerosa.ontrack.model.structure.Decoration; import net.nemerosa.ontrack.model.structure.DecorationService; import net.nemerosa.ontrack.model.structure.Decorator; import net.nemerosa.ontrack.model.structure.ProjectEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.Collections; import java.util.List; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @Service @Transactional public class DecorationServiceImpl implements DecorationService { private final ExtensionManager extensionManager; private final SecurityService securityService; @Autowired public DecorationServiceImpl(ExtensionManager extensionManager, SecurityService securityService) { this.extensionManager = extensionManager; this.securityService = securityService; } @Override public List<Decoration<?>> getDecorations(ProjectEntity entity) { // Downloading a decoration with the current security context Function<Decorator, Stream<Decoration<?>>> securedDecoratorFunction = securityService.runner( decorator -> getDecorations(entity, decorator).stream() ); // OK return extensionManager.getExtensions(DecorationExtension.class) .stream() // ... and filters per entity .filter(decorator -> decorator.getScope().contains(entity.getProjectEntityType())) // ... and gets the decoration .flatMap(securedDecoratorFunction) // OK .collect(Collectors.toList()); } /** * Gets the decoration for an entity, and returns an "error" decoration in case of problem. */ protected <T> List<? extends Decoration> getDecorations(ProjectEntity entity, Decorator<T> decorator) { try { return decorator.getDecorations(entity); } catch (Exception ex) { return Collections.singletonList( Decoration.error(decorator, getErrorMessage(ex)) ); } } /** * Decoration error message */ protected String getErrorMessage(Exception ex) { if (ex instanceof BaseException) { return ex.getMessage(); } else { return "Problem while getting decoration"; } } }
mit
tuliren/my_leetcode
src/java/CombinationSumII.java
2451
/** * * Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T. * * Each number in C may only be used once in the combination. * * Note: * All numbers (including target) will be positive integers. * Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). * The solution set must not contain duplicate combinations. * For example, given candidate set 10,1,2,7,6,1,5 and target 8, * A solution set is: * [1, 7] * [1, 2, 5] * [2, 6] * [1, 1, 6] * */ import java.util.ArrayList; import java.util.Collections; import java.util.Arrays; public class CombinationSumII { public static ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) { // Note: The Solution object is instantiated only once and is reused by each test case. int N = candidates.length; // sort the array to prevent duplicated solution together with line 35 Arrays.sort(candidates); ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); for (int i = 0; i < N; i++) { // consider a solution with candidate[i] int num = candidates[i]; // check if the current num is equal to previous; // because the array is sorted, this step prevents duplication together with line 28 if (i != 0 && candidates[i] == candidates[i-1]) continue; if (num < target) { // get the result for target - candidate[i] ArrayList<ArrayList<Integer>> restSum = combinationSum2(Arrays.copyOfRange(candidates, i+1, N), target-num); for (ArrayList<Integer> l : restSum) { if (!l.isEmpty()) { //System.out.printf("num: %d, list: %s\n", num, l.toString()); l.add(num); Collections.sort(l); result.add(l); } } } else if (num == target) { ArrayList<Integer> base = new ArrayList<Integer>(); base.add(num); result.add(base); } } return result; } public static void main() { int[] a = {10, 1, 2, 7, 6, 1, 5}; System.out.println(combinationSum2(a, 8)); } }
mit
pgriffel/pacioli
src/pacioli/types/ast/TypeApplicationNode.java
2002
/* * Copyright (c) 2013 - 2014 Paul Griffioen * * 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 pacioli.types.ast; import java.util.List; import pacioli.Location; import pacioli.ast.Visitor; public class TypeApplicationNode extends AbstractTypeNode { public final TypeIdentifierNode op; public final List<TypeNode> args; public TypeApplicationNode(Location location, TypeIdentifierNode name, List<TypeNode> args) { super(location); this.op = name; this.args = args; } public TypeNode transform(TypeIdentifierNode name, List<TypeNode> args) { return new TypeApplicationNode(getLocation(), name, args); } public TypeIdentifierNode getOperator() { return op; } public String getName() { return op.getName(); } public List<TypeNode> getArgs() { return args; } @Override public void accept(Visitor visitor) { visitor.visit(this); } }
mit
israelba/ifbaeventos
src/main/java/br/edu/ifba/bru/sistemas/ifbaeventos/controller/CadastroTipoAtividadeBean.java
1410
package br.edu.ifba.bru.sistemas.ifbaeventos.controller; import java.io.Serializable; import javax.faces.application.FacesMessage; import javax.faces.context.FacesContext; import javax.inject.Inject; import javax.inject.Named; import br.edu.ifba.bru.sistemas.ifbaeventos.model.TipoAtividade; import br.edu.ifba.bru.sistemas.service.CadastroTipoAtividades; import br.edu.ifba.bru.sistemas.service.NegocioException; @Named @javax.faces.view.ViewScoped public class CadastroTipoAtividadeBean implements Serializable{ /** * */ private static final long serialVersionUID = 1L; @Inject private CadastroTipoAtividades cadastro; private TipoAtividade tipoAtividade; public void prepararCadastro(){ if (this.tipoAtividade == null){ this.tipoAtividade = new TipoAtividade(); } } public void salvar() { FacesContext context = FacesContext.getCurrentInstance(); try { this.cadastro.salvar(this.tipoAtividade); context.addMessage(null, new FacesMessage( "Tipo de atividade salva com sucesso!")); } catch (NegocioException e) { FacesMessage mensagem = new FacesMessage(e.getMessage()); mensagem.setSeverity(FacesMessage.SEVERITY_ERROR); context.addMessage(null, mensagem); } } public TipoAtividade getTipoAtividade() { return tipoAtividade; } public void setTipoAtividade(TipoAtividade tipoAtividade) { this.tipoAtividade = tipoAtividade; } }
mit
m0er/university-projects
cafeteria-struts/src/kr/ac/bu/test/ActionServletTest.java
2975
package kr.ac.bu.test; import java.io.File; import kr.ac.bu.index.IndexVO; import org.apache.log4j.Logger; import servletunit.struts.MockStrutsTestCase; public class ActionServletTest extends MockStrutsTestCase { private static Logger logger = Logger.getLogger(ActionServletTest.class); @Override protected void setUp() throws Exception { super.setUp(); this.setContextDirectory(new File("WebContent")); this.setConfigFile("/WEB-INF/struts-config.xml"); } public void testIndex() throws Exception { this.setRequestPathInfo("/index"); this.actionPerform(); logger.info(this.getActualForward()); } public void testUserLogin() throws Exception { this.setRequestPathInfo("/index"); this.addRequestParameter("userLogin", ""); this.addRequestParameter("id", "20046326"); this.addRequestParameter("pw", "test"); this.actionPerform(); logger.info(this.getActualForward()); } public void testAdminLogin() throws Exception { this.setRequestPathInfo("/index"); this.addRequestParameter("adminLogin", ""); this.addRequestParameter("id", "admin1"); this.addRequestParameter("pw", "test"); this.actionPerform(); logger.info(this.getActualForward()); } public void testBuilding() throws Exception { IndexVO vo = new IndexVO(); vo.setId("20046326"); this.getRequest().getSession().setAttribute("user", vo); this.addRequestParameter("building", "bonbu"); this.setRequestPathInfo("/index"); this.actionPerform(); logger.info(this.getActualForward()); } public void testPlex() throws Exception { IndexVO vo = new IndexVO(); vo.setId("20046326"); this.getRequest().getSession().setAttribute("user", vo); this.getRequest().getSession().setAttribute("building", "bonbu"); this.setRequestPathInfo("/plex"); this.actionPerform(); logger.info(this.getActualForward()); } public void testRegisterMenu() throws Exception { this.setRequestPathInfo("/plex"); this.addRequestParameter("title", "¸Þ´º Å×½ºÆ®1"); this.addRequestParameter("price", "2000"); this.addRequestParameter("provideDateAlt", "2010-05-16"); this.addRequestParameter("building", "º»ºÎµ¿"); this.addRequestParameter("registerMenu", ""); this.actionPerform(); logger.info(this.getActualForward()); } public void testLogout() throws Exception { this.setRequestPathInfo("/index"); IndexVO vo = new IndexVO(); vo.setId("20046326"); this.getRequest().getSession().setAttribute("user", vo); this.addRequestParameter("logout", ""); this.actionPerform(); logger.info(this.getActualForward()); } public void testSearchMenu() throws Exception { this.setRequestPathInfo("/plex"); this.addRequestParameter("searchDate", "2010-05-16"); this.addRequestParameter("searchMenu", ""); this.actionPerform(); logger.info(this.getActualForward()); } }
mit
mickleness/pumpernickel
src/main/java/com/pump/animation/quicktime/JPEGMovWriter.java
4976
/** * This software is released as part of the Pumpernickel project. * * All com.pump resources in the Pumpernickel project are distributed under the * MIT License: * https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt * * More information about the Pumpernickel project is available here: * https://mickleness.github.io/pumpernickel/ */ package com.pump.animation.quicktime; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; import javax.imageio.IIOImage; import javax.imageio.ImageIO; import javax.imageio.ImageWriteParam; import javax.imageio.ImageWriter; import javax.imageio.stream.MemoryCacheImageOutputStream; import javax.swing.ProgressMonitor; import com.pump.UserCancelledException; import com.pump.animation.AnimationReader; import com.pump.animation.quicktime.atom.VideoSampleDescriptionEntry; /** * A MovWriter that encodes frames as a series of JPEG images. */ public class JPEGMovWriter extends MovWriter { private static final float DEFAULT_JPG_QUALITY = .85f; /** * This property is used to determine the JPG image quality. It is a float * between [0, 1], where 1 is a lossless image. This value should be the key * in a key/value pair in the Map passed to <code>addFrame(..)</code>. */ public static final String PROPERTY_QUALITY = "jpeg-quality"; float defaultQuality; public JPEGMovWriter(File file) throws IOException { this(file, DEFAULT_JPG_QUALITY); } /** * * @param file * the destination file to write to. * @param defaultQuality * the default JPEG quality (from [0,1]) to use if a frame is * added without otherwise specifying this value. * @throws IOException */ public JPEGMovWriter(File file, float defaultQuality) throws IOException { super(file); this.defaultQuality = defaultQuality; } @Override protected VideoSampleDescriptionEntry getVideoSampleDescriptionEntry() { return VideoSampleDescriptionEntry.createJPEGDescription(videoTrack.w, videoTrack.h); } /** * Add an image to this animation using a specific jpeg compression quality. * * @param duration * the duration (in seconds) of this frame * @param bi * the image to add * @param jpegQuality * a value from [0,1] indicating the quality of this image. A * value of 1 represents a losslessly encoded image. * @throws IOException */ public synchronized void addFrame(float duration, BufferedImage bi, float jpegQuality) throws IOException { Map<String, Object> settings = new HashMap<String, Object>(1); settings.put(PROPERTY_QUALITY, new Float(jpegQuality)); super.addFrame(duration, bi, settings); } private static boolean printWarning = false; @Override protected void writeFrame(OutputStream out, BufferedImage image, Map<String, Object> settings) throws IOException { if (image.getType() == BufferedImage.TYPE_INT_ARGB || image.getType() == BufferedImage.TYPE_INT_ARGB_PRE) { if (printWarning == false) { printWarning = true; System.err .println("JPEGMovWriter Warning: a BufferedImage of type TYPE_INT_ARGB may produce unexpected results. The recommended type is TYPE_INT_RGB."); } } float quality; if (settings != null && settings.get(PROPERTY_QUALITY) instanceof Number) { quality = ((Number) settings.get(PROPERTY_QUALITY)).floatValue(); } else if (settings != null && settings.get(PROPERTY_QUALITY) instanceof String) { quality = Float.parseFloat((String) settings.get(PROPERTY_QUALITY)); } else { quality = defaultQuality; } MemoryCacheImageOutputStream iOut = new MemoryCacheImageOutputStream( out); ImageWriter iw = ImageIO.getImageWritersByMIMEType("image/jpeg").next(); ImageWriteParam iwParam = iw.getDefaultWriteParam(); iwParam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); iwParam.setCompressionQuality(quality); iw.setOutput(iOut); IIOImage img = new IIOImage(image, null, null); iw.write(null, img, iwParam); } /** * Add all the frames from an AnimationReader. * * @param r * the animation to read. * @param monitor * an optional ProgressMonitor to update * @throws IOException * if an error occurs copying frames. */ public void addFrames(AnimationReader r, ProgressMonitor monitor) throws IOException { if (monitor != null) monitor.setMaximum(r.getFrameCount()); BufferedImage bi = r.getNextFrame(false); int ctr = 1; while (bi != null) { if (monitor != null) { if (monitor.isCanceled()) { throw new UserCancelledException(); } monitor.setProgress(ctr); } float d; try { d = (float) r.getFrameDuration(); } catch (Exception e) { e.printStackTrace(); d = 1; } addFrame(d, bi, .98f); bi = r.getNextFrame(false); ctr++; } } }
mit
SquidDev-CC/plethora
src/main/java/org/squiddev/plethora/integration/astralsorcery/MethodsAstralSorcery.java
5643
package org.squiddev.plethora.integration.astralsorcery; import dan200.computercraft.api.lua.LuaException; import hellfirepvp.astralsorcery.AstralSorcery; import hellfirepvp.astralsorcery.common.auxiliary.CelestialGatewaySystem; import hellfirepvp.astralsorcery.common.constellation.ConstellationRegistry; import hellfirepvp.astralsorcery.common.constellation.IConstellation; import hellfirepvp.astralsorcery.common.data.research.PlayerProgress; import hellfirepvp.astralsorcery.common.data.research.ResearchManager; import hellfirepvp.astralsorcery.common.data.research.ResearchProgression; import hellfirepvp.astralsorcery.common.data.world.data.GatewayCache; import hellfirepvp.astralsorcery.common.tile.TileCelestialGateway; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.fml.relauncher.Side; import org.squiddev.plethora.api.meta.TypedMeta; import org.squiddev.plethora.api.method.IContext; import org.squiddev.plethora.api.method.wrapper.FromSubtarget; import org.squiddev.plethora.api.method.wrapper.FromTarget; import org.squiddev.plethora.api.method.wrapper.PlethoraMethod; import org.squiddev.plethora.api.module.IModuleContainer; import org.squiddev.plethora.gameplay.modules.PlethoraModules; import org.squiddev.plethora.integration.EntityIdentifier; import org.squiddev.plethora.utils.Helpers; import javax.annotation.Nonnull; import java.util.*; import java.util.stream.Collectors; public final class MethodsAstralSorcery { private MethodsAstralSorcery() { } //REFINE This method is potentially OP, as it exposes all available `GatewayNode`s. // That said, players can already name a gateway, and they could add signs to the destination // so that it shows in the preview (if it is working; haven't tested) // If Hellfire complains, it's easy enough to delete... @PlethoraMethod( modId = AstralSorcery.MODID, doc = "-- Get a list of all Celestial Gateways, grouped by dimension" ) public static Map<String, ?> getGateways(@FromTarget TileCelestialGateway gateway) { Map<Integer, List<GatewayCache.GatewayNode>> nodesByDimension = CelestialGatewaySystem.instance.getGatewayCache(Side.SERVER); Map<String, Object> fullOut = new HashMap<>(nodesByDimension.size()); //TODO This will break badly if dimensions aren't identified by number, e.g. 1.13, NEID, JEID, etc. for (Map.Entry<Integer, List<GatewayCache.GatewayNode>> entry : nodesByDimension.entrySet()) { // I was going to filter this for the current node, but that will result in excessive collection manipulation // if I can't convert to a stream API chain; otherwise, I would risk modifying the actual server data... List<GatewayCache.GatewayNode> dimNodes = entry.getValue(); List<Map<String, Object>> dimOut = Helpers.map(dimNodes, node -> { Map<String, Object> inner = new HashMap<>(4); inner.put("posX", node.getX()); inner.put("posY", node.getY()); inner.put("posZ", node.getZ()); inner.put("name", node.display); return inner; }); //TODO Determine how to get a dimension's name; `DimensionType.getById(int).getName` is a start, but // it doesn't account for named dimensions, e.g. RFTools Dimensions, Mystcraft, etc. ... //REFINE I recall there being a difference between `String.valueOf` and `toString` for primitives, but I // don't remember the specifics... fullOut.put(String.valueOf(entry.getKey()), dimOut); } return fullOut; } //Mainly useful if a player wants to design some sort of organizer to track their progress @PlethoraMethod( modId = AstralSorcery.MODID, module = PlethoraModules.INTROSPECTION_S, doc = "-- Get this player's progress in Astral Sorcery" ) public static Map<String, ?> getAstralProgress(@Nonnull IContext<IModuleContainer> context, @FromSubtarget EntityIdentifier.Player playerId) throws LuaException { EntityPlayerMP player = playerId.getPlayer(); Map<String, Object> out = new HashMap<>(); PlayerProgress progress = ResearchManager.getProgress(player); //Refers to the constellations that you have seen on a paper out.put("seenConstellations", getConstellationMeta(context, progress.getSeenConstellations())); //Refers to the constellations that you have discovered via telescope, after seeing them on a paper out.put("knownConstellations", getConstellationMeta(context, progress.getKnownConstellations())); out.put("availablePerkPoints", progress.getAvailablePerkPoints(player)); IConstellation attuned = progress.getAttunedConstellation(); if (attuned != null) { out.put("attunedConstellation", context.makePartialChild(attuned).getMeta()); } out.put("progressTier", progress.getTierReached().toString()); //REFINE Do we want the name, the ordinal, or a LuaList with both? // ... shouldn't the `progressId` field be the same as the ordinal? ... whatever. //noinspection SimplifyOptionalCallChains It may be simpler, but it (to me) hurts readability... String researchTier = progress.getResearchProgression().stream() .max(Comparator.comparingInt(ResearchProgression::getProgressId)) .map(Enum::toString).orElse(null); if (researchTier != null) { out.put("researchTier", researchTier); } //REFINE Someone else can expose the Perks if they want; cost/benefit says "no" at this time return out; } @Nonnull private static List<TypedMeta<IConstellation, ?>> getConstellationMeta(IContext<?> context, Collection<String> translationKeys) { return translationKeys.stream() .map(ConstellationRegistry::getConstellationByName) .filter(Objects::nonNull) .map(x -> context.makePartialChild(x).getMeta()) .collect(Collectors.toList()); } }
mit
johngodoi/JavaDataScience
src/main/java/br/unifesp/henrique/john/research/datascience/charts/ChartViewer.java
206
package br.unifesp.henrique.john.research.datascience.charts; import javafx.application.Application; /** * Created by jgodoi on 10/02/2017. */ public abstract class ChartViewer extends Application { }
mit
rapier-web/rapier
src/main/java/thosakwe/rapier/RapierEntryPoint.java
351
package thosakwe.rapier; public class RapierEntryPoint { private String title, src; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getSrc() { return src; } public void setSrc(String src) { this.src = src; } }
mit
IMSmobile/Fahrplan
opendatatransport/src/main/java/ch/schoeb/opendatatransport/LocalOpenTransportRepository.java
2021
package ch.schoeb.opendatatransport; import java.util.ArrayList; import java.util.Random; import ch.schoeb.opendatatransport.model.Connection; import ch.schoeb.opendatatransport.model.ConnectionList; import ch.schoeb.opendatatransport.model.ConnectionQuery; import ch.schoeb.opendatatransport.model.Station; import ch.schoeb.opendatatransport.model.StationList; public class LocalOpenTransportRepository implements IOpenTransportRepository { @Override public StationList findStations(String query) { ArrayList<Station> stations = new ArrayList<>(); for (int i = 0; i < 5; i++) { Station station = new Station(); stations.add(station); } waitRandomTime(); StationList list = new StationList(); list.setStations(stations); return list; } @Override public ConnectionList searchConnections(String from, String to) { return searchConnections(from, to, null, null, null, false); } @Override public ConnectionList searchConnections(ConnectionQuery query) throws OpenDataTransportException { return searchConnections(query.getFrom(), query.getTo(), null, query.getDate(), query.getTime(), query.isArrivalTime()); } @Override public ConnectionList searchConnections(String from, String to, String via, String date, String time, Boolean isArrivalTime) { ArrayList<Connection> connections = new ArrayList<>(); Connection firstDirectConnection = new Connection(); connections.add(firstDirectConnection); Connection secondIndirectConnection = new Connection(); connections.add(secondIndirectConnection); waitRandomTime(); ConnectionList list = new ConnectionList(); list.setConnections(connections); return list; } private void waitRandomTime() { Random r = new Random(); try { Thread.sleep(r.nextInt(10000)); } catch (InterruptedException e) { } } }
mit
honeyqa/honeyqa-android
honeyqa/client/src/main/java/io/honeyqa/client/network/okhttp/internal/framed/HQ_NameValueBlockReader.java
4463
/* * Copyright (C) 2013 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.honeyqa.client.network.okhttp.internal.framed; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import io.honeyqa.client.network.okio.Buffer; import io.honeyqa.client.network.okio.BufferedSource; import io.honeyqa.client.network.okio.ByteString; import io.honeyqa.client.network.okio.ForwardingSource; import io.honeyqa.client.network.okio.InflaterSource; import io.honeyqa.client.network.okio.Okio; import io.honeyqa.client.network.okio.Source; /** * Reads a SPDY/3 Name/Value header block. This class is made complicated by the * requirement that we're strict with which bytes we put in the compressed bytes * buffer. We need to put all compressed bytes into that buffer -- but no other * bytes. */ class HQ_NameValueBlockReader { /** This source transforms compressed bytes into uncompressed bytes. */ private final InflaterSource inflaterSource; /** * How many compressed bytes must be read into inflaterSource before * {@link #readNameValueBlock} returns. */ private int compressedLimit; /** This source holds inflated bytes. */ private final BufferedSource source; public HQ_NameValueBlockReader(BufferedSource source) { // Limit the inflater input stream to only those bytes in the Name/Value // block. We cut the inflater off at its source because we can't predict the // ratio of compressed bytes to uncompressed bytes. Source throttleSource = new ForwardingSource(source) { @Override public long read(Buffer sink, long byteCount) throws IOException { if (compressedLimit == 0) return -1; // Out of data for the current block. long read = super.read(sink, Math.min(byteCount, compressedLimit)); if (read == -1) return -1; compressedLimit -= read; return read; } }; // Subclass inflater to install a dictionary when it's needed. Inflater inflater = new Inflater() { @Override public int inflate(byte[] buffer, int offset, int count) throws DataFormatException { int result = super.inflate(buffer, offset, count); if (result == 0 && needsDictionary()) { setDictionary(HQ_Spdy3.DICTIONARY); result = super.inflate(buffer, offset, count); } return result; } }; this.inflaterSource = new InflaterSource(throttleSource, inflater); this.source = Okio.buffer(inflaterSource); } public List<HQ_Header> readNameValueBlock(int length) throws IOException { this.compressedLimit += length; int numberOfPairs = source.readInt(); if (numberOfPairs < 0) throw new IOException("numberOfPairs < 0: " + numberOfPairs); if (numberOfPairs > 1024) throw new IOException("numberOfPairs > 1024: " + numberOfPairs); List<HQ_Header> entries = new ArrayList<>(numberOfPairs); for (int i = 0; i < numberOfPairs; i++) { ByteString name = readByteString().toAsciiLowercase(); ByteString values = readByteString(); if (name.size() == 0) throw new IOException("name.size == 0"); entries.add(new HQ_Header(name, values)); } doneReading(); return entries; } private ByteString readByteString() throws IOException { int length = source.readInt(); return source.readByteString(length); } private void doneReading() throws IOException { // Move any outstanding unread bytes into the inflater. One side-effect of // deflate compression is that sometimes there are bytes remaining in the // stream after we've consumed all of the content. if (compressedLimit > 0) { inflaterSource.refill(); if (compressedLimit != 0) throw new IOException("compressedLimit > 0: " + compressedLimit); } } public void close() throws IOException { source.close(); } }
mit
toru1055/elrec
src/test/java/jp/thotta/elrec/common/BasePreferencesTest.java
926
package jp.thotta.elrec.common; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.util.Map; import java.util.HashMap; public class BasePreferencesTest extends TestCase { public BasePreferencesTest(String testName) { super(testName); } public void testGetPreferenceIdsCsv() { BasePreferences p = new BasePreferences(100, "1,2,3,4,5,10"); p.addPreference(9); p.addPreference(10); p.addPreference(100); String res = p.getPreferenceIdsCsv(); System.out.println(res); assertTrue(res.indexOf("9") != -1); assertTrue(res.indexOf("5") != -1); assertTrue(res.indexOf("7") == -1); Map<Long,Boolean> list = p.getPreferenceIds(); assertTrue(list.get((long)10)); assertTrue(list.get((long)1)); assertTrue(list.get((long)3)); assertEquals(list.get((long)8), null); assertEquals(p.getId(), (long)100); } }
mit
bladestery/Sapphire
example_apps/AndroidStudioMinnie/sapphire/src/main/java/org/ddogleg/clustering/AssignCluster.java
1821
/* * Copyright (c) 2012-2015, Peter Abeles. All Rights Reserved. * * This file is part of DDogleg (http://ddogleg.org). * * 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.ddogleg.clustering; import java.io.Serializable; /** * Used to assign a point to set of clusters. Clusters are given labels from 0 to N-1, where N is the number of * clusters. * * @author Peter Abeles */ public interface AssignCluster<D> extends Serializable { /** * Assigns the point to cluster which is the best fit. * * @param point Point which is to be assigned * @return Index of the cluster from 0 to N-1 */ public int assign( D point ); /** * Performs a soft assignment of a point to all the clusters. Clusters with a better fit will have * a larger value in 'fit'. The sum of fit is equal to 1, unless everything is zero. Then it is zero. * * @param point Point which is to be assigned * @param fit Storage for relative fit quality of each cluster. Length must be at least the number of clusters. */ public void assign( D point , double fit[] ); /** * Total number of clusters. * @return The total number of clusters. */ public int getNumberOfClusters(); /** * Creates an exact copy of this class. * @return Copy of class */ public AssignCluster<D> copy(); }
mit
Col-E/Recaf
src/test/java/me/coley/recaf/FlowGraphTest.java
3908
package me.coley.recaf; import me.coley.recaf.graph.*; import me.coley.recaf.graph.flow.FlowGraph; import me.coley.recaf.graph.flow.FlowVertex; import me.coley.recaf.workspace.JarResource; import me.coley.recaf.workspace.Workspace; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.objectweb.asm.ClassReader; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.Set; import static org.junit.jupiter.api.Assertions.*; /** * Tests for method flow graph. * * @author Matt */ public class FlowGraphTest extends Base { private FlowGraph graph; @BeforeEach public void setup() throws IOException { Path file = getClasspathFile("calls.jar"); Workspace workspace = new Workspace(new JarResource(file)); graph = workspace.getFlowGraph(); } @Test public void testSimpleOutbound() { // Just a "System.out.println", so we need the "println" call FlowVertex one = graph.getVertex("test/Parent", "thing", "()V"); assertEquals(1, one.getEdges().size()); FlowVertex other = (FlowVertex) one.getEdges().iterator().next().getOther(one); assertEquals("java/io/PrintStream", other.getOwner()); assertEquals("println", other.getName()); assertEquals("(Ljava/lang/String;)V", other.getDesc()); } @Test public void testRecursive() { // Recursive call to self should link to the same vertex FlowVertex count = graph.getVertex("test/Recursion", "countTo10", "(I)V"); FlowVertex calledCount = getSingleEdgeOther(count); assertEquals(count, calledCount); } @Test public void testChain() { // one -> two --> three FlowVertex one = graph.getVertex("test/Chain", "one", "()V"); FlowVertex two = graph.getVertex("test/Chain", "two", "()V"); FlowVertex three = graph.getVertex("test/Chain", "three", "()V"); // Use search to show the path following the chain SearchResult<ClassReader> result = new ClassDfsSearch(ClassDfsSearch.Type.ALL).find(one, three); assertNotNull(result); List<Vertex<ClassReader>> path = result.getPath(); assertEquals(3, path.size()); assertEquals(one, path.get(0)); assertEquals(two, path.get(1)); assertEquals(three, path.get(2)); } @Test public void testLoopback() { // one -> two --> three --> one FlowVertex one = graph.getVertex("test/Loopback", "one", "()V"); FlowVertex two = graph.getVertex("test/Loopback", "two", "()V"); FlowVertex three = graph.getVertex("test/Loopback", "three", "()V"); // Show that the edges point to the next expected vertex FlowVertex oneEdge = getSingleEdgeOther(one); assertEquals(two, oneEdge); FlowVertex twoEdge = getSingleEdgeOther(two); assertEquals(three, twoEdge); FlowVertex threeEdge = getSingleEdgeOther(three); assertEquals(one, threeEdge); } @Test public void testChildCallsParent() { // Child extends Parent // Method calls "super.doThing" FlowVertex parentThing = graph.getVertex("test/Parent", "thing", "()V"); FlowVertex callsParent = graph.getVertex("test/Child", "callParentThing", "()V"); FlowVertex calledParent = getSingleEdgeOther(callsParent); assertEquals(parentThing, calledParent); } @Test public void testChildCallsInterface() { // Child implements Interface // Method calls "Interface.super.doThing" FlowVertex interfaceThing = graph.getVertex("test/Interface", "thing", "()V"); FlowVertex callsInterface = graph.getVertex("test/Child", "callInterfaceThing", "()V"); FlowVertex calledInterface = getSingleEdgeOther(callsInterface); assertEquals(interfaceThing, calledInterface); } /** * @param vertex * Vertex with one edge. * * @return The vertex on the other end of the edge. */ private static FlowVertex getSingleEdgeOther(FlowVertex vertex) { Set<Edge<ClassReader>> edges = vertex.getEdges(); assertEquals(1, edges.size()); return (FlowVertex) edges.iterator().next().getOther(vertex); } }
mit
masgari/avatar
src/test/java/avatar/LetterAvatarGeneratorTest.java
803
package avatar; import org.junit.Assert; import org.junit.Test; /** * @author mamad * @since 09/11/14. */ public class LetterAvatarGeneratorTest { /** * png header bytes. */ static final int HEADER[] = {137, 80, 78, 71, 13, 10, 26, 10}; @Test public void testGenerateColor() throws Exception { LetterAvatarGenerator generator = new LetterAvatarGenerator(); byte[] me = generator.generate("Me"); verify(me); byte[] you = generator.generate("You"); verify(you); } private void verify(byte[] image) { Assert.assertNotNull(image); Assert.assertFalse(image.length < HEADER.length); for (int i = 0; i < HEADER.length; i++) { Assert.assertEquals(HEADER[i], image[i] & 0xFF); } } }
mit
calimbak/GitRepo
app/src/main/java/holtz/cedric/gitrepo/view/repository/GitRepositoryFragment.java
7526
package holtz.cedric.gitrepo.view.repository; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ProgressBar; import android.widget.TextView; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.NetworkImageView; import java.util.List; import holtz.cedric.gitrepo.R; import holtz.cedric.gitrepo.adapter.RepositoryAdapter; import holtz.cedric.gitrepo.model.GitRetainedData; import holtz.cedric.gitrepo.model.Repository; import holtz.cedric.gitrepo.model.RepositoryList; import holtz.cedric.gitrepo.model.User; import holtz.cedric.gitrepo.net.NetQuery; import holtz.cedric.gitrepo.net.VolleyRequestQueue; import holtz.cedric.gitrepo.utils.NetworkUtils; import holtz.cedric.gitrepo.view.LoadingListView; /** * Created by holtz_c on 1/27/16. * Fragment handling data regarding the repositories * GitRepo */ public class GitRepositoryFragment extends Fragment { private TextView mUsername; private LoadingListView mRepositoryList; private ProgressBar mLoading; private TextView mCount; /* The avatar was meant to be displayed in a CollapsingToolbarLayout with a parallax NetworkImageView The only solution for the nested ListView to work was to use a minimal API of 21 or a Recycler View In this case, we will just display the avatar on the view */ private NetworkImageView mAvatar; // Current view private View mView; // Current User private User mUser; // Adapter populating the list private RepositoryAdapter mRepositoryAdapter; public GitRepositoryFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_git_repo, container, false); mAvatar = (NetworkImageView) mView.findViewById(R.id.repo_avatar); mUsername = (TextView) mView.findViewById(R.id.repo_username); mRepositoryList = (LoadingListView) mView.findViewById(R.id.repo_list); mLoading = (ProgressBar) mView.findViewById(R.id.repo_loading); mCount = (TextView) mView.findViewById(R.id.repo_count); mRepositoryAdapter = new RepositoryAdapter(getActivity()); mRepositoryList.setAdapter(mRepositoryAdapter); mRepositoryList.setLoadingListener(new LoadingListView.OnLoadingListener() { @Override public void onLoading() { // If there is still repositories to be fetched, request another page Integer totalCount = GitRetainedData.getInstance().getTotalUserCount(); if (totalCount != null && mRepositoryAdapter.getCount() < totalCount) { // Disable further loading call mRepositoryList.setLoadingEnabled(false); // Add the loading footer view mRepositoryList.addFooterView(); // Request another page requestRepositoryData(); } } }); mRepositoryList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // On repository click, launch the repository URL Repository repository = mRepositoryAdapter.getItem(position); launchUrl(repository.url); } }); return mView; } /** * Launch the specified url on the Android system browser * @param url Url to be launched */ private void launchUrl(String url) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); startActivity(browserIntent); } /** * Send a request to the GitHub API searching repositories for an user */ private void requestRepositoryData() { // If the network isn't available, display immediately an error if (!NetworkUtils.inNetworkAvailable(getContext())) { displayError(null); return; } // Request the new page with the current search and the correct page // The pagination starts at page 1 NetQuery.getRepoForUser(getContext(), new Response.Listener<RepositoryList>() { @Override public void onResponse(RepositoryList response) { // Restore view state mLoading.setVisibility(View.INVISIBLE); mRepositoryList.removeFooterView(); // Save current search data GitRetainedData retainedData = GitRetainedData.getInstance(); retainedData.addRepositories(response.repositories); retainedData.setTotalRepositoryCount(response.totalCount); // Load current search data List<Repository> repositories = GitRetainedData.getInstance().getRepositories(); mRepositoryAdapter.setRepositoryData(repositories); mRepositoryList.setLoadingEnabled(response.totalCount != repositories.size()); setResultCount(response.totalCount); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { // Handle error response displayError(error); } }, mUser.login, (int) Math.floor(mRepositoryAdapter.getCount() / NetQuery.MAX_ITEM_PAGE) + 1); } /** * Display an error message on the view * @param error The error to be parsed, can be null */ private void displayError(VolleyError error) { // Restore view state mLoading.setVisibility(View.INVISIBLE); mRepositoryList.removeFooterView(); mCount.setText(""); // Display an error on the view Snackbar.make(mView, NetworkUtils.parseError(error, getContext()), Snackbar.LENGTH_LONG).show(); } /** * Update the view with user data, can force a new repository search * @param user User to be loaded on the view * @param needsSearch True if the repository list need to be fetched on the GitHub API, false otherwise */ public void loadUser(User user, boolean needsSearch) { if (user == null) { return; } mUser = user; // If we are on landscape orientation, set the username otherwise it will be displayed on the Toolbar if (getResources().getBoolean(R.bool.has_two_panes)) { mUsername.setText(mUser.login); } mAvatar.setImageUrl(mUser.avatarUrl, VolleyRequestQueue.getInstance(getContext()).getImageLoader()); if (needsSearch) { // Request a new repository search for the current user loadRepoUser(); } else { // Load saved repository data on the view loadRepoData(); } } /** * Clear the stored data and request the repository list for the current user */ private void loadRepoUser() { // Clear view and saved data state mCount.setText(""); mLoading.setVisibility(View.VISIBLE); mRepositoryAdapter.clearRepositoryData(); GitRetainedData.getInstance().clearSavedRepositories(); // Request a new repository list for this user requestRepositoryData(); } /** * Load the saved data on the view */ public void loadRepoData() { // Restore view data GitRetainedData retainedData = GitRetainedData.getInstance(); mRepositoryAdapter.setRepositoryData(retainedData.getRepositories()); Integer totalCount = retainedData.getTotalRepositoryCount(); if (totalCount != null) { mRepositoryList.setLoadingEnabled(mRepositoryAdapter.getCount() != totalCount); setResultCount(totalCount); } } /** * Display the current repository count on the total repository count * @param total Total result count */ private void setResultCount(int total) { String resultCount = String.format(getString(R.string.result_repository_count), mRepositoryAdapter.getCount(), total); mCount.setText(resultCount); } }
mit
kemitix/ldap-user-manager
app/src/test/java/net/kemitix/ldapmanager/ContextIT.java
416
package net.kemitix.ldapmanager; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles("test") public class ContextIT { @Test public void contextLoads() { } }
mit
bing-ads-sdk/BingAds-Java-SDK
src/test/java/com/microsoft/bingads/v12/api/test/entities/adgroup_remarketing_list_association/read/BulkAdGroupRemarketingListAssociationReadFromRowValuesAudienceIdTest.java
2143
package com.microsoft.bingads.v12.api.test.entities.adgroup_remarketing_list_association.read; import java.util.Arrays; import java.util.Collection; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; import com.microsoft.bingads.internal.functionalinterfaces.Function; import com.microsoft.bingads.v12.api.test.entities.adgroup_remarketing_list_association.BulkAdGroupRemarketingListAssociationTest; import com.microsoft.bingads.v12.bulk.entities.BulkAdGroupRemarketingListAssociation; import com.microsoft.bingads.v12.campaignmanagement.AudienceCriterion; @RunWith(Parameterized.class) public class BulkAdGroupRemarketingListAssociationReadFromRowValuesAudienceIdTest extends BulkAdGroupRemarketingListAssociationTest { @Parameter(value = 1) public Long expectedResult; /* * Test data generator. * This method is called the the JUnit parameterized test runner and * returns a Collection of Arrays. For each Array in the Collection, * each array element corresponds to a parameter in the constructor. */ @Parameters public static Collection<Object[]> data() { // In this example, the parameter generator returns a List of // arrays. Each array has two elements: { datum, expected }. // These data are hard-coded into the class, but they could be // generated or loaded in any way you like. return Arrays.asList(new Object[][]{ {"123", 123L}, {"9223372036854775807", 9223372036854775807L}, {"", null}, {null, null} }); } @Test public void testRead() { this.<Long>testReadProperty("Audience Id", this.datum, this.expectedResult, new Function<BulkAdGroupRemarketingListAssociation, Long>() { @Override public Long apply(BulkAdGroupRemarketingListAssociation c) { return ((AudienceCriterion) c.getBiddableAdGroupCriterion().getCriterion()).getAudienceId(); } }); } }
mit
Dacaspex/Fractal
fractals/settings/SettingsManager.java
189
package fractals.settings; import fractals.settings.properties.Property; public interface SettingsManager { public Property<?>[] getProperties(); public void updateProperties(); }
mit
pguil/acoustic-sort
acoustic-sort/src/sort/ISort.java
84
package sort; public interface ISort { public void sort(Integer[] t); }
mit
Ganitzsh/Bonobo
src/main/java/fr/jweb/app/mbeans/SignUpMB.java
2300
package fr.jweb.app.mbeans; import fr.jweb.app.entities.User; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import java.io.Serializable; import java.sql.SQLException; import org.apache.commons.codec.digest.DigestUtils; /** * SignUp ManagedBean * Handle the creation of new Users */ @ManagedBean(name = "signupUtility") @RequestScoped public class SignUpMB implements Serializable { private static final long serialVersionUID = 1L; private String email; private String username; private String password; private Boolean newsletter; public SignUpMB() { } public DatabaseManagerMB getDbManager() { return dbManager; } public void setDbManager(DatabaseManagerMB dbManager) { this.dbManager = dbManager; } @ManagedProperty(value = "#{dbManager}") private DatabaseManagerMB dbManager; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Boolean getNewsletter() { return newsletter; } public void setNewsletter(Boolean newsletter) { this.newsletter = newsletter; } /** * Post a new User in the database with the given informations * * @return Redirection to the index */ public String newUser() { try { User tmp = new User(); tmp.setUsername(this.username); tmp.setEmail(this.email); tmp.setNewsletter(this.newsletter); tmp.setPasswordHash(DigestUtils.sha1Hex(this.password)); tmp.setAdmin(false); dbManager.getUserDao().create(tmp); dbManager.getConn().close(); } catch (SQLException e) { System.out.println("SQLException while creating new user: " + e.getMessage()); e.printStackTrace(); } return ("index?faces-redirect=true"); } }
mit
peterarsentev/course_test
src/main/java/ru/job4j/collection/Parentheses.java
134
package ru.job4j.collection; public class Parentheses { public static boolean valid(char[] data) { return false; } }
mit
nodchip/QMAClone
src/main/java/tv/dyndns/kishibe/qmaclone/client/setting/PanelSettingRestrictedUser.java
4211
package tv.dyndns.kishibe.qmaclone.client.setting; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import tv.dyndns.kishibe.qmaclone.client.ServiceAsync; import tv.dyndns.kishibe.qmaclone.client.packet.RestrictionType; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.IsWidget; import com.google.gwt.user.client.ui.Widget; public class PanelSettingRestrictedUser implements IsWidget { interface View extends IsWidget { RestrictionType getType(); int getUserCode(); String getRemoteAddress(); void setUserCodes(Set<Integer> userCodes); void setRemoteAddresses(Set<String> remoteAddresses); } private static final Logger logger = Logger.getLogger(PanelSettingRestrictedUser.class .getName()); @VisibleForTesting View view; private final ServiceAsync service; public PanelSettingRestrictedUser(ServiceAsync service) { this.service = Preconditions.checkNotNull(service); } @VisibleForTesting PanelSettingRestrictedUser(ServiceAsync service, View view) { this.service = Preconditions.checkNotNull(service); this.view = Preconditions.checkNotNull(view); update(); } public void setView(View view) { this.view = Preconditions.checkNotNull(view); update(); } public void onTypeChanged() { update(); } @VisibleForTesting void update() { RestrictionType restrictionType = view.getType(); service.getRestrictedUserCodes(restrictionType, callbackGetRestrictedUserCodes); } @VisibleForTesting final AsyncCallback<Set<Integer>> callbackGetRestrictedUserCodes = new AsyncCallback<Set<Integer>>() { @Override public void onSuccess(Set<Integer> result) { view.setUserCodes(result); RestrictionType restrictionType = view.getType(); service.getRestrictedRemoteAddresses(restrictionType, callbackGetRestrictedRemoteAddresses); } @Override public void onFailure(Throwable caught) { logger.log(Level.WARNING, "制限ユーザーコードの取得に失敗しました"); } }; @VisibleForTesting final AsyncCallback<Set<String>> callbackGetRestrictedRemoteAddresses = new AsyncCallback<Set<String>>() { @Override public void onSuccess(Set<String> result) { view.setRemoteAddresses(result); } @Override public void onFailure(Throwable caught) { logger.log(Level.WARNING, "制限リモートアドレスの取得に失敗しました"); } }; public void onAddUserCodeButton() { int userCode = view.getUserCode(); RestrictionType restrictionType = view.getType(); service.addRestrictedUserCode(userCode, restrictionType, callbackRestrictedUser); } public void onRemoveUserCodeButton() { int userCode = view.getUserCode(); RestrictionType restrictionType = view.getType(); service.removeRestrictedUserCode(userCode, restrictionType, callbackRestrictedUser); } public void onClearUserCodesButton() { RestrictionType restrictionType = view.getType(); service.clearRestrictedUserCodes(restrictionType, callbackRestrictedUser); } public void onAddRemoteAddressButton() { String remoteAddress = view.getRemoteAddress(); RestrictionType restrictionType = view.getType(); service.addRestrictedRemoteAddress(remoteAddress, restrictionType, callbackRestrictedUser); } public void onRemoveRemoteAddressButton() { String remoteAddress = view.getRemoteAddress(); RestrictionType restrictionType = view.getType(); service.removeRestrictedRemoteAddress(remoteAddress, restrictionType, callbackRestrictedUser); } public void onClearRemoteAddressesButton() { RestrictionType restrictionType = view.getType(); service.clearRestrictedRemoteAddresses(restrictionType, callbackRestrictedUser); } @VisibleForTesting final AsyncCallback<Void> callbackRestrictedUser = new AsyncCallback<Void>() { @Override public void onSuccess(Void result) { update(); } @Override public void onFailure(Throwable caught) { logger.log(Level.WARNING, "制限ユーザーの追加/削除/クリアに失敗しました"); } }; @Override public Widget asWidget() { return view.asWidget(); } }
mit
pmarques/SocketIO-Server
SocketIO-Netty/src/main/java/eu/k2c/socket/io/server/SocketIOSession.java
8586
/** * Copyright (C) 2011 K2C @ Patrick Marques <patrickfmarques@gmail.com> * * 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. * * Except as contained in this notice, the name(s) of the above copyright holders * shall not be used in advertising or otherwise to promote the sale, use or other * dealings in this Software without prior written authorization. */ package eu.k2c.socket.io.server; import static eu.k2c.socket.io.frames.SocketIOFrame.EMPTY_FIELD; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.atomic.AtomicLong; import org.apache.log4j.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.timeout.ReadTimeoutException; import eu.k2c.socket.io.frames.FrameType; import eu.k2c.socket.io.frames.SocketIOFrame; import eu.k2c.socket.io.server.api.AckHandler; import eu.k2c.socket.io.server.api.ConnectionState; import eu.k2c.socket.io.server.api.DisconnectReason; import eu.k2c.socket.io.server.api.SocketIOInbound; import eu.k2c.socket.io.server.api.SocketIOOutbound; import eu.k2c.socket.io.server.exceptions.SocketIOException; import eu.k2c.socket.io.server.exceptions.SocketIOMalformedMessageException; /** * This class only deals with the transport layer of SocketIO. It read and * interpret the raw messages format and the sends it to the session * implementation * * @author "Patrick F. Marques <patrick.marques@k2c.eu>" */ public class SocketIOSession extends SimpleChannelUpstreamHandler implements SocketIOOutbound { private static final Logger LOGGER = Logger.getLogger(SocketIOServer.class); private final String sessionID; private final SocketIOInbound inbound; private Channel channel = null; private ConnectionState connectionState; private AtomicLong messageIDSeq = new AtomicLong(0); // TODO: View "maps" performance and select the best one... private final Map<Long, AckHandler> ackHandlers = new IdentityHashMap<Long, AckHandler>(100); public SocketIOSession(final String sessionID, final SocketIOInbound inbound) { this.sessionID = sessionID; this.inbound = inbound; connectionState = ConnectionState.CONNECTING; } @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof SocketIOFrame)) { throw new UnsupportedOperationException(); } SocketIOFrame frame = (SocketIOFrame) msg; LOGGER.trace(frame.toString()); final long messageID = frame.getMessageID(); final String endPoint = frame.getEndPoint(); final String eventName = frame.getEventName(); final String data = frame.getData(); final boolean ackForm = frame.getTreasAsEvent(); switch (frame.getFrameType()) { case CONNECT: onConnect(endPoint); break; case EVENT: inbound.onEvent(messageID, endPoint, eventName, data); break; case MESSAGE: returnAck(messageID); inbound.onMessage(messageID, endPoint, data); break; case JSON: returnAck(messageID); inbound.onJSONMessage(messageID, endPoint, data); break; case ACK: onAck(messageID, data, ackForm); break; case HEARTBEAT: // The hearbeat is catched by the Netty ReadTimeoutHandler. break; case DISCONNECT: final DisconnectReason reason = DisconnectReason.CLOSED_REMOTELY; final String errorMessage = "Session closed by user"; inbound.onDisconnect(reason, errorMessage); break; default: // Never should reach this point... throw new UnsupportedOperationException("Methode: [" + frame.getFrameType().toString() + "]Session ID: " + sessionID); } } private void returnAck(final long messageID) { channel.write(new SocketIOFrame(FrameType.ACK, messageID, null)); } private void onConnect(final String endPoint) { channel.write(new SocketIOFrame(FrameType.CONNECT, endPoint)); inbound.onConnect(this, endPoint); } private void onAck(final long messageID, final String data, final boolean ackForm) { if (ackForm) { if (ackHandlers.containsKey(messageID)) ackHandlers.get(messageID).onEvent(data); else // TODO: This can happen? what i do with it? throw new UnsupportedOperationException("something is wrong where, where is the ack handler?"); } else { throw new UnsupportedOperationException(); } } @Override public void disconnect() { try { channel.write(new SocketIOFrame(FrameType.DISCONNECT)); } catch (SocketIOMalformedMessageException e) { LOGGER.fatal(e); } } @Override public void close() { throw new UnsupportedOperationException(); } @Override public ConnectionState getConnectionState() { // TODO Auto-generated method stub return connectionState; } @Override public void sendMessage(final String message, final String endPoint) throws SocketIOException { channel.write(new SocketIOFrame(FrameType.MESSAGE, EMPTY_FIELD, endPoint, message)); } @Override public void sendJSONMessage(final String message, final String endPoint) throws SocketIOException { channel.write(new SocketIOFrame(FrameType.JSON, EMPTY_FIELD, endPoint, message)); } @Override public void sendEventMessage(final String eventName, final String message, final String endPoint) throws SocketIOException { channel.write(new SocketIOFrame(FrameType.EVENT, EMPTY_FIELD, endPoint, eventName, message)); } @Override public void sendMessage(final String message, final String endPoint, final AckHandler handler) throws SocketIOException { long mid = messageIDSeq.getAndIncrement(); ackHandlers.put((long) mid, handler); channel.write(new SocketIOFrame(FrameType.MESSAGE, mid, false, endPoint, null, message)); } @Override public void sendJSONMessage(final String message, final String endPoint, final AckHandler handler) throws SocketIOException { long mid = messageIDSeq.getAndIncrement(); ackHandlers.put((long) mid, handler); channel.write(new SocketIOFrame(FrameType.JSON, mid, false, endPoint, null, message)); } @Override public void sendEventMessage(final String eventName, final String message, final String endPoint, final AckHandler handler) throws SocketIOException { long mid = messageIDSeq.getAndIncrement(); ackHandlers.put((long) mid, handler); channel.write(new SocketIOFrame(FrameType.EVENT, mid, true, endPoint, eventName, message)); } @Override public void sendAck(long messageID, String message) throws SocketIOException { channel.write(new SocketIOFrame(FrameType.ACK, messageID, message)); } public void onHandshake(final ChannelHandlerContext ctx) { this.channel = ctx.getChannel(); onConnect(null); connectionState = ConnectionState.CONNECTED; } @Override public void exceptionCaught(final ChannelHandlerContext ctx, final ExceptionEvent e) throws Exception { if (e.getCause() instanceof ReadTimeoutException) { LOGGER.debug("Send HeartBeat to client with SessionID[" + sessionID + "]"); if (channel.isOpen()) { channel.write(new SocketIOFrame(FrameType.HEARTBEAT)); } else { inbound.onDisconnect(DisconnectReason.TIMEOUT, "user not respond to timeouts"); } return; } // FIX: Pass exception information to user is not a good practice! Throwable thr = e.getCause(); inbound.onError(null, e.getCause().getMessage(), e.getCause().getMessage()); LOGGER.fatal("Unknow exception behavior", thr); } }
mit
shunjikonishi/form-validation
src/main/java/jp/co/flect/formvalidation/rules/Number.java
202
package jp.co.flect.formvalidation.rules; public class Number extends RegexRule { public Number() { super("^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)?(?:\\.\\d+)?$", "Please enter a valid number."); } }
mit
everalbum/roliedex
app/src/androidTest/java/com/everalbum/roliedex/sample/ApplicationTest.java
360
package com.everalbum.roliedex.sample; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
Omega-R/OmegaRecyclerView
omegarecyclerview/src/main/java/androidx/recyclerview/widget/ExpandedRecyclerView.java
1572
package androidx.recyclerview.widget; import android.content.Context; import android.util.AttributeSet; import android.view.View; import androidx.annotation.NonNull; import androidx.annotation.Nullable; public class ExpandedRecyclerView extends RecyclerView { public static final int STEP_START = 1; public static final int STEP_LAYOUT = 2; public static final int STEP_ANIMATIONS = 4; public ExpandedRecyclerView(Context context) { super(context); } public ExpandedRecyclerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public ExpandedRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected int getAdapterPositionFor(RecyclerView.ViewHolder viewHolder) { return super.getAdapterPositionFor(viewHolder); } public static ViewHolder getChildViewHolderInt(View child) { return child == null ? null : (ViewHolder) ((RecyclerView.LayoutParams) child.getLayoutParams()).mViewHolder; } public int getLayoutStep() { return mState.mLayoutStep; } public static class ViewHolder extends RecyclerView.ViewHolder { public ViewHolder(@NonNull View itemView) { super(itemView); } public final boolean isAddedInPreLayout() { return (mFlags & FLAG_APPEARED_IN_PRE_LAYOUT) != 0; } public boolean isAttachedScrap() { return super.isScrap() && !mInChangeScrap; } } }
mit
UchihaMadarafjjUchihaMadara/FrameworkTest
SBM2Demo/src/main/java/com/demo/config/mybatis/MybatisConfig.java
2587
package com.demo.config.mybatis; import javax.sql.DataSource; import org.apache.ibatis.session.SqlSessionFactory; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.mapper.MapperScannerConfigurer; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import com.alibaba.druid.pool.DruidDataSource; /** * @Description: mybatis的配置类 * * @author DELL * * @since 2017-04-26 * */ @Configuration public class MybatisConfig { /** * * @Title: getDataSource * @Description: 数据源的配置 * * @param: * @return: DataSource * @throws: * */ @Bean @ConfigurationProperties(prefix = "spring.datasource.sbm2") public DataSource getDataSource() { return new DruidDataSource(); } /** * * @Title: sqlSessionFactory * @Description: mybatis的sqlSessionFactory配置 * * @param: dataSource * @return: SqlSessionFactory * @throws Exception * */ @Bean public SqlSessionFactory sqlSessionFactory(DataSource dataSource)throws Exception { SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean(); sqlSessionFactoryBean.setDataSource(dataSource); PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:mapper/*Mapper.xml")); sqlSessionFactoryBean.setTypeAliasesPackage("com.demo.pojo"); return sqlSessionFactoryBean.getObject(); } /** * * @Title: mapperScannerConfigurer * @Description: mapper接口扫描包 * * @param: * @return: MapperScannerConfigurer * @throws * */ @Bean public MapperScannerConfigurer mapperScannerConfigurer() { MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer(); mapperScannerConfigurer.setBasePackage("com.demo.mapper"); return mapperScannerConfigurer; } /** * * @Title: transactionManager * @Description: 配置事务管理器 * * @param: dataSource * @return: DataSourceTransactionManager * @throws: Exception * */ @Bean public DataSourceTransactionManager transactionManager(DataSource dataSource)throws Exception { return new DataSourceTransactionManager(dataSource); } }
mit
UCSB-CS56-W14/CS56-W14-lab06
src/edu/ucsb/cs56/W14/drawings/khalid/simple/PictureComponent.java
3879
package edu.ucsb.cs56.w14.drawings.khalid.simple; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JPanel; import javax.swing.JComponent; // the four tools things we'll use to draw import java.awt.geom.Line2D; // single lines import java.awt.geom.Ellipse2D; // ellipses and circles import java.awt.Rectangle; // squares and rectangles import java.awt.geom.GeneralPath; // combinations of lines and curves /** A component that draws a Picture by Phill Conrad @author Phill Conrad (original drawing) @author Khalid Dhanani (fixed the snowmans's head) @version for UCSB CS56, S13 */ // Your class should "extend JComponent // This is "inheritance", which we'll start readina about in Chapter 10 // It means that PictureComponent "is a" JComponent // that is, a special type of JComponent that is for a specific purpose public class PictureComponent extends JComponent { /** The paintComponent method is always required if you want * any graphics to appear in your JComponent. * * There is a paintComponent * method that is created for you in the JComponent class, but it * doesn't do what we want, so we have to "override" that method with * our own method. * * This overriding is typical when inheritance is used. * In inheritance, you take something that is a "basic" version of * what you want, then you "trick it out" with your own custom features. * Sort of a "pimp my Java class" kind of thing. */ public void paintComponent(Graphics g) { // Recover Graphics2D--we always do this. // See sections 2.12, p. 60-61 for an explanation Graphics2D g2 = (Graphics2D) g; // Now the fun part---we draw stuff! // @@@ YOU'LL CUSTOMIZE EVERYTHING BELOW THIS LINE Rectangle house = new Rectangle(100, 200, 100, 100); g2.draw( house); // lroof and rroof are the left and right sides of the roof, Line2D.Double lroof = new Line2D.Double(100, 200, 150, 150); Line2D.Double rroof = new Line2D.Double(150,150, 200,200); g2.draw(lroof); g2.draw(rroof); // now a snowman: three circles // here we use constants, so that if we want to change // the dimensions later, or move the snowman around, // it becomes easier. // Instead of doing the math ourselves, and putting "hard coded numbers" // in the constructors for the Ellipses, we let the computer do the math! final double bottomRadius = 20; final double middleRadius = 15; final double topRadius = 10; final double snowManCenterBottomX = 400; final double snowManCenterBottomY = 300; Circle snowManBottomCircle = new Circle ( snowManCenterBottomX, snowManCenterBottomY - bottomRadius, bottomRadius ); g2.draw(snowManBottomCircle); Circle snowManMiddleCircle = new Circle ( snowManCenterBottomX, snowManCenterBottomY - bottomRadius * 2 - middleRadius, middleRadius ); g2.draw(snowManMiddleCircle); // @@@ ADD CODE HERE TO DRAW THE TOP CIRCLE Circle snowManTopCircle = new Circle ( snowManCenterBottomX, snowManCenterBottomY - bottomRadius * 2 - middleRadius * 2 - topRadius, topRadius ); g2.draw(snowManTopCircle); // @@@ FINALLY, SIGN AND LABEL YOUR DRAWING g2.drawString("A house and a snowman, by Phill Conrad", 20,20); g2.drawString("Top of snowman added by Khalid Dhanani", 20,40); } }
mit
narakai/DemoApp2
app/src/main/java/com/clem/ipoca1/activity/StatisticsActivity.java
6570
package com.clem.ipoca1.activity; import android.content.SharedPreferences; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RadioButton; import android.widget.TextView; import com.afollestad.materialdialogs.color.CircleView; import com.clem.ipoca1.R; import com.clem.ipoca1.adapter.StatisticsListAdapter; import com.clem.ipoca1.core.preferences.UserPreferences; import com.clem.ipoca1.core.storage.DBReader; import com.clem.ipoca1.core.util.Converter; import rx.Observable; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Displays the 'statistics' screen */ public class StatisticsActivity extends AppCompatActivity implements AdapterView.OnItemClickListener { private static final String TAG = StatisticsActivity.class.getSimpleName(); private static final String PREF_NAME = "StatisticsActivityPrefs"; private static final String PREF_COUNT_ALL = "countAll"; private Subscription subscription; private TextView totalTimeTextView; private ListView feedStatisticsList; private ProgressBar progressBar; private StatisticsListAdapter listAdapter; private boolean countAll = false; private SharedPreferences prefs; @Override protected void onCreate(Bundle savedInstanceState) { setTheme(UserPreferences.getTheme()); super.onCreate(savedInstanceState); getSupportActionBar().setDisplayShowHomeEnabled(true); setContentView(R.layout.statistics_activity); prefs = getSharedPreferences(PREF_NAME, MODE_PRIVATE); countAll = prefs.getBoolean(PREF_COUNT_ALL, false); totalTimeTextView = (TextView) findViewById(R.id.total_time); feedStatisticsList = (ListView) findViewById(R.id.statistics_list); progressBar = (ProgressBar) findViewById(R.id.progressBar); listAdapter = new StatisticsListAdapter(this); listAdapter.setCountAll(countAll); feedStatisticsList.setAdapter(listAdapter); feedStatisticsList.setOnItemClickListener(this); int primaryPreselect = UserPreferences.getPrefColor(); ColorDrawable drawable = new ColorDrawable(primaryPreselect); if (getSupportActionBar() != null) { getSupportActionBar().setBackgroundDrawable(drawable); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().setStatusBarColor(CircleView.shiftColorDown(primaryPreselect)); getWindow().setNavigationBarColor(primaryPreselect); } } @Override public void onResume() { super.onResume(); refreshStatistics(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.statistics, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } else if (item.getItemId() == R.id.statistics_mode) { selectStatisticsMode(); return true; } else { return super.onOptionsItemSelected(item); } } private void selectStatisticsMode() { View contentView = View.inflate(this, R.layout.statistics_mode_select_dialog, null); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(contentView); builder.setTitle(R.string.statistics_mode); if (countAll) { ((RadioButton) contentView.findViewById(R.id.statistics_mode_count_all)).setChecked(true); } else { ((RadioButton) contentView.findViewById(R.id.statistics_mode_normal)).setChecked(true); } builder.setPositiveButton(android.R.string.ok, (dialog, which) -> { countAll = ((RadioButton) contentView.findViewById(R.id.statistics_mode_count_all)).isChecked(); listAdapter.setCountAll(countAll); prefs.edit().putBoolean(PREF_COUNT_ALL, countAll).apply(); refreshStatistics(); }); builder.show(); } private void refreshStatistics() { progressBar.setVisibility(View.VISIBLE); totalTimeTextView.setVisibility(View.GONE); feedStatisticsList.setVisibility(View.GONE); loadStatistics(); } private void loadStatistics() { if (subscription != null) { subscription.unsubscribe(); } subscription = Observable.fromCallable(() -> DBReader.getStatistics(countAll)) .subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(result -> { if (result != null) { totalTimeTextView.setText(Converter .shortLocalizedDuration(this, countAll ? result.totalTimeCountAll : result.totalTime)); listAdapter.update(result.feedTime); progressBar.setVisibility(View.GONE); totalTimeTextView.setVisibility(View.VISIBLE); feedStatisticsList.setVisibility(View.VISIBLE); } }, error -> Log.e(TAG, Log.getStackTraceString(error))); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DBReader.StatisticsItem stats = listAdapter.getItem(position); AlertDialog.Builder dialog = new AlertDialog.Builder(this); dialog.setTitle(stats.feed.getTitle()); dialog.setMessage(getString(R.string.statistics_details_dialog, countAll ? stats.episodesStartedIncludingMarked : stats.episodesStarted, stats.episodes, Converter.shortLocalizedDuration(this, countAll ? stats.timePlayedCountAll : stats.timePlayed), Converter.shortLocalizedDuration(this, stats.time))); dialog.setPositiveButton(android.R.string.ok, null); dialog.show(); } }
mit
DeathByTape/jettyREST
src/main/java/com/deathbytape/jettyREST/HelloServlet.java
796
/* * Copyright (C) 2014 Dennis J. McWherter, Jr. * * This software may be modified and distributed under the terms of the MIT License. */ package com.deathbytape.jettyREST; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Hello-world servlet to show and example usage of Jersey and Jetty * with pure Servlet 3.0. */ @Path("hello") public class HelloServlet { @GET @Path("{name}") @Produces(MediaType.TEXT_HTML) public Response helloName(@PathParam("name") String name) { if(name != null) { return Response.status(200) .entity("Hello, " + name) .build(); } return Response.status(404).build(); } }
mit
nico01f/z-pec
ZimbraSelenium/src/java/com/zimbra/qa/selenium/staf/StafIntegration.java
19061
package com.zimbra.qa.selenium.staf; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.StringTokenizer; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import com.ibm.staf.STAFException; import com.ibm.staf.STAFHandle; import com.ibm.staf.STAFResult; import com.ibm.staf.STAFUtil; import com.ibm.staf.service.STAFCommandParseResult; import com.ibm.staf.service.STAFCommandParser; import com.ibm.staf.service.STAFServiceInterfaceLevel30; import com.zimbra.qa.selenium.framework.core.ExecuteHarnessMain; import com.zimbra.qa.selenium.framework.util.*; import com.zimbra.qa.selenium.framework.util.ZimbraSeleniumProperties.AppType; public class StafIntegration implements STAFServiceInterfaceLevel30 { static private Logger mLog = Logger.getLogger(StafIntegration.class); // STAF Specifics // private final String kVersion = "1.1.0"; private static final int kDeviceInvalidSerialNumber = 4001; private String stafServiceName; private STAFHandle stafServiceHandle; // SERVICE Specifics private static class Parsers { public static STAFCommandParser stafParserExecute; public static STAFCommandParser stafParserQuery; public static STAFCommandParser stafParserHelp; public static STAFCommandParser stafParserHalt; } private static class Arguments { public static final String optionExecute = "execute"; public static final String argServer = "server"; public static final String argConfig = "config"; public static final String argConfigHost = "host"; public static final String argRoot = "root"; public static final String argJarfile = "jarfile"; public static final String argPattern = "pattern"; public static final String argGroup = "group"; public static final String argDesktopURL = "url"; public static final String argLog = "log"; public static final String argLog4j = "log4j"; public static final String optionQuery= "query"; public static final String optionHelp = "help"; public static final String optionHalt = "halt"; } private static final String defaultLog4jProperties = "/tmp/log4j.properties"; // private boolean serviceIsRunning = false; public STAFResult acceptRequest(RequestInfo info) { mLog.info("StafIntegration: acceptRequest ..."); File f = new File(defaultLog4jProperties); if ( f.exists() ) { PropertyConfigurator.configure(defaultLog4jProperties); } else { BasicConfigurator.configure(); } // Convert the request to all lower case StringTokenizer requestTokenizer = new StringTokenizer(info.request); // Determine what the first argument is String request = requestTokenizer.nextToken().toLowerCase(); // call the appropriate method to handle the command if (request.equals(Arguments.optionExecute.toLowerCase())) { return handleExecute(info); } else if (request.equals(Arguments.optionQuery.toLowerCase())) { return handleQuery(info); } else if (request.equals(Arguments.optionHalt.toLowerCase())) { return handleHalt(info); } else if (request.equals(Arguments.optionHelp.toLowerCase())) { return handleHelp(); } else { return new STAFResult(STAFResult.InvalidRequestString, "Unknown (STAF) Request: " + request); } } private STAFResult parseExecute(STAFCommandParseResult request, ExecuteHarnessMain harness) { // Convert the args to variables String valueServer = request.optionValue(Arguments.argServer); String valueRoot = request.optionValue(Arguments.argRoot); String valueJarfile = request.optionValue(Arguments.argJarfile); String valuePattern = request.optionValue(Arguments.argPattern); String valueConfig = request.optionValue(Arguments.argConfig); String valueConfigHost = request.optionValue(Arguments.argConfigHost); String valueURL = request.optionValue(Arguments.argDesktopURL); String valueLog = request.optionValue(Arguments.argLog); mLog.info("valueServer="+ valueServer); mLog.info("valueRoot="+ valueRoot); mLog.info("valueJarfile="+ valueJarfile); mLog.info("valuePattern="+ valuePattern); mLog.info("valueConfig="+ valueConfig); mLog.info("valueConfigHost="+ valueConfigHost); mLog.info("valueURL="+ valueURL); mLog.info("valueLog="+ valueLog); // Since multiple GROUP arguments can be specified, process each one ArrayList<String> valueGroup = new ArrayList<String>(); for (int i = 1; i <= request.optionTimes(Arguments.argGroup); i++) { String g = request.optionValue(Arguments.argGroup, i); valueGroup.add(g); mLog.info("valueGroup="+ g); } if ( valueGroup.isEmpty() ) { // If no groups were specified, default to sanity valueGroup = new ArrayList<String>(Arrays.asList("always", "sanity")); mLog.info("valueGroup=always,sanity"); } //// Configure the harness based on the arguments // // Set the base folder name ZimbraSeleniumProperties.setBaseDirectory(valueRoot); if ( (valueConfig != null) && (valueConfig.trim().length() > 0) ) { //// // Grab the specified config.properties from the remote client //// // Determine which remote host to grab the config.properties from String host = valueServer; if ( (valueConfigHost != null) && (valueConfigHost.trim().length() > 0) ) { host = valueConfigHost; } // Set the config.properties values try { // Get the remote file and initialize the properties StafDevProperties configProperties = new StafDevProperties(); // Get the remote file contents configProperties.load(host, valueConfig, valueLog); // Save the temp file in the log folder for the records String filename = configProperties.save(valueLog); // Tell the harness to load the temp file ZimbraSeleniumProperties.setConfigProperties(filename); } catch (HarnessException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } catch (IOException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } } else { //// // Use the 'local' config.properties //// // Set the config.properties values try { // Load the original properties StafProperties configProperties = new StafProperties(valueRoot + "/conf/config.properties"); configProperties.setProperty("server.host", valueServer); configProperties.setProperty("adminName", "globaladmin@" + valueServer); configProperties.setProperty("seleniumMode", "Local"); configProperties.setProperty("serverName", "localhost"); configProperties.setProperty("serverPort", "4444"); if ( valueURL != null ) configProperties.setProperty("desktop.buildUrl", valueURL); // Save the temp file in the log folder for the records String filename = configProperties.save(valueLog); // Tell the harness to load the temp file ZimbraSeleniumProperties.setConfigProperties(filename); } catch (FileNotFoundException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } catch (IOException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } } // Set the app type on the properties // Must happen before setTestOutputFolderName() for (AppType t : AppType.values()) { // Look for ".type." (e.g. ".ajax.") in the pattern if ( valuePattern.contains(t.toString().toLowerCase()) ) { ZimbraSeleniumProperties.setAppType(t); break; } } harness.setTestOutputFolderName(valueLog); // If specified, load the log4j property file first // so that we start logging immediately if (request.optionTimes(Arguments.argLog4j) > 0 ) { PropertyConfigurator.configure(request.optionValue(Arguments.argLog4j)); } // Set the harness parameters harness.jarfilename = valueJarfile; harness.classfilter = valuePattern; harness.groups = valueGroup; // Done! return (new STAFResult(STAFResult.Ok)); } private STAFResult handleExecute(RequestInfo info) { mLog.info("STAF: handleExecute ..."); // Check whether Trust level is sufficient for this command. if (info.trustLevel < 4) { return new STAFResult(STAFResult.AccessDenied, "Trust level 4 required for "+ Arguments.optionExecute +" request.\n" + "The requesting machine's trust level: " + info.trustLevel); } // Make sure the request is valid STAFCommandParseResult parsedRequest = Parsers.stafParserExecute.parse(info.request); if (parsedRequest.rc != STAFResult.Ok) { return new STAFResult(STAFResult.InvalidRequestString, parsedRequest.errorBuffer); } if (serviceIsRunning) { return (new STAFResult(STAFResult.Ok, "already running")); } StringBuilder resultString = new StringBuilder(); try { serviceIsRunning = true; // Reset all static references this.reset(); // Create the execution object ExecuteHarnessMain harness = new ExecuteHarnessMain(); // Parse Arguments STAFResult parseResult = parseExecute(parsedRequest, harness); if (parseResult.rc != STAFResult.Ok) { return (parseResult); } // Execute! try { String response = harness.execute(); resultString.append(response); } catch (FileNotFoundException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } catch (IOException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } } catch (HarnessException e) { return (new STAFResult(STAFResult.JavaError, getStackTrace(e))); } finally { serviceIsRunning = false; } // Return ok code with the parsable return string return (new STAFResult(STAFResult.Ok, resultString.toString())); } /** * Convert a stack trace to a string * @param t * @return */ private String getStackTrace(Throwable t) { String s = t.getMessage(); try { Writer writer = null; PrintWriter printer = null; try { writer = new StringWriter(); printer = new PrintWriter(writer); t.printStackTrace(printer); s = writer.toString(); } finally { if ( printer != null ) { printer.close(); printer = null; } if ( writer != null ) { writer.close(); writer = null; } } } catch (IOException e) { mLog.warn("IOException while closing writer ", e); } return (s); } private STAFResult handleQuery(RequestInfo info) { mLog.info("STAF: handleExecute ..."); // Check whether Trust level is sufficient for this command. if (info.trustLevel < 2) { return new STAFResult(STAFResult.AccessDenied, "Trust level 2 required for "+ Arguments.optionQuery +" request.\n" + "The requesting machine's trust level: " + info.trustLevel); } String status = "Not running"; if ( ExecuteHarnessMain.currentResultListener != null ) { status = ExecuteHarnessMain.currentResultListener.getResults(); } return (new STAFResult(STAFResult.Ok, status)); } private STAFResult handleHalt(RequestInfo info) { return (new STAFResult(STAFResult.JavaError, "handleHalt: Implement me!")); } private STAFResult handleHelp() { mLog.info("StafTestStaf: handleHelp ..."); // TODO: Need to convert the help command into the variables, aEXECUTE, aHELP, etc. return new STAFResult(STAFResult.Ok, "StafTest Service Help\n\n" + "EXECUTE SERVER <servername|IP address> ROOT <ZimbraSelenium path> JARFILE <path> PATTERN <projects.ajax.tests> [ GROUP <always|sanity|smoke|functional> ]* [ CONFIG <path> [ HOST <host> ] ] [ URL <desktop installer folder> ] [ LOG <folder> ] [ LOG4J <properties file> ]\n\n" + "QUERY -- TBD: should return statistics on active jobs \n\n" + "HALT <TBD> -- TBD: should stop any executing tests\n\n" + "HELP\n\n"); } /** * Reset any static refrences between executions **/ protected void reset() { ZimbraAdminAccount.reset(); ZimbraAccount.reset(); } private void createBundles(String jarfilename) { List<String> names = Arrays.asList("AjxMsg", "I18nMsg", "ZaMsg", "ZbMsg", "ZhMsg", "ZmMsg", "ZsMsg", "ZMsg"); Locale locale = Locale.ENGLISH; for (String name : names) { try { ResourceBundle rb = ResourceBundle.getBundle(name, locale, this.getClass().getClassLoader()); if ( rb == null ) { mLog.error("Unable to load resource bundle: "+ name); continue; } mLog.info("Loaded resource bundle: "+ name); } catch (MissingResourceException e) { mLog.error("Unable to load resource bundle: "+ name, e); } } // try { // ResourceBundle rb1 = ResourceBundle.getBundle("ZaMsg", Locale.ENGLISH, this.getClass().getClassLoader()); // for (Enumeration<String> e = rb1.getKeys(); e.hasMoreElements(); ) { // mLog.info("key: "+ e.nextElement()); // } // } catch (MissingResourceException e) { // mLog.error("unable to load resource bundle", e); // } } public STAFResult init(InitInfo info) { mLog.info("StafIntegration: init ..."); File f = new File(defaultLog4jProperties); if ( f.exists() ) { PropertyConfigurator.configure(defaultLog4jProperties); } else { BasicConfigurator.configure(); } mLog.info("serviceJar.getName(): " + info.serviceJar.getName()); // STAF specific stuff ... try { stafServiceName = info.name; stafServiceHandle = new STAFHandle("STAF/SERVICE/" + info.name); } catch (STAFException e) { return (new STAFResult(STAFResult.STAFRegistrationError)); } // EXECUTE parser Parsers.stafParserExecute = new STAFCommandParser(); Parsers.stafParserExecute.addOption(Arguments.optionExecute, 1, STAFCommandParser.VALUENOTALLOWED); Parsers.stafParserExecute.addOption(Arguments.argServer, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argRoot, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argJarfile, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argPattern, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argGroup, 0, STAFCommandParser.VALUEREQUIRED); // Can be specified infinite amount of times Parsers.stafParserExecute.addOption(Arguments.argConfig, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argConfigHost, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argDesktopURL, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argLog, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOption(Arguments.argLog4j, 1, STAFCommandParser.VALUEREQUIRED); Parsers.stafParserExecute.addOptionNeed(Arguments.optionExecute, Arguments.argRoot +" "+ Arguments.argJarfile +" "+ Arguments.argPattern +" "+ Arguments.argGroup); // QUERY parser Parsers.stafParserQuery = new STAFCommandParser(); Parsers.stafParserQuery.addOption(Arguments.optionQuery, 1, STAFCommandParser.VALUENOTALLOWED); // HELP parser Parsers.stafParserHelp = new STAFCommandParser(); Parsers.stafParserHelp.addOption(Arguments.optionHelp, 1, STAFCommandParser.VALUENOTALLOWED); // HALT parser Parsers.stafParserHalt = new STAFCommandParser(); Parsers.stafParserHalt.addOption(Arguments.optionHalt, 1, STAFCommandParser.VALUENOTALLOWED); createBundles(info.serviceJar.getName()); // Register Help Data registerHelpData( kDeviceInvalidSerialNumber, "Invalid serial number", "A non-numeric value was specified for serial number"); // Now, do the Selenium specific setup ... BasicConfigurator.configure(); // Now, the service is ready ... mLog.info("STAF Selenium: Ready ..."); return (new STAFResult(STAFResult.Ok)); } public STAFResult term() { mLog.info("StafIntegration: term ..."); try { // Un-register Help Data unregisterHelpData(kDeviceInvalidSerialNumber); // Un-register the service handle stafServiceHandle.unRegister(); } catch (STAFException ex) { return (new STAFResult(STAFResult.STAFRegistrationError)); } return (new STAFResult(STAFResult.Ok)); } // Register error codes for the STAX Service with the HELP service private void registerHelpData(int errorNumber, String info, String description) { stafServiceHandle.submit2("local", "HELP", "REGISTER SERVICE " + stafServiceName + " ERROR " + errorNumber + " INFO " + STAFUtil.wrapData(info) + " DESCRIPTION " + STAFUtil.wrapData(description)); } // Un-register error codes for the STAX Service with the HELP service private void unregisterHelpData(int errorNumber) { stafServiceHandle.submit2("local", "HELP", "UNREGISTER SERVICE " + stafServiceName + " ERROR " + errorNumber); } }
mit
cdai/interview
1-algorithm/13-leetcode/java/src/fundamentals/string/search/lc125_validpalindrome/Solution.java
3100
package fundamentals.string.search.lc125_validpalindrome; /** * Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases. * For example, * "A man, a plan, a canal: Panama" is a palindrome. * "race a car" is not a palindrome. * Note: Have you consider that the string might be empty? This is a good question to ask during an interview. For the purpose of this problem, we define empty string as valid palindrome. */ public class Solution { public boolean isPalindrome(String s) { for (int i = 0, j = s.length() - 1; i < j; ) { if (!Character.isLetterOrDigit(s.charAt(i))) i++; else if (!Character.isLetterOrDigit(s.charAt(j))) j--; else if (Character.toLowerCase(s.charAt(i++)) != Character.toLowerCase(s.charAt(j--))) return false; /* else ignore empty space, comma... */ } return true; } // My 3AC. O(N) time. public boolean isPalindrome3(String s) { char[] c = s.toCharArray(); for (int i = 0, j = c.length - 1; i < j; ) { if (!Character.isLetterOrDigit(c[i])) i++; // error: isWhitespace is not applicable eg.":,1" else if (!Character.isLetterOrDigit(c[j])) j--; else if (Character.toLowerCase(c[i++]) != Character.toLowerCase(c[j--])) return false; } return true; } // My 2nd: use helpful Character method public boolean isPalindrome21(String s) { char[] c = s.toCharArray(); // Invariant: [0,i) and (j,N-1] are matched excluding whitespace for (int i = 0, j = c.length - 1; i < j; ) { if (!Character.isLetterOrDigit(c[i])) i++; // error: isWhitespace is not applicable eg.":,1" else if (!Character.isLetterOrDigit(c[j])) j--; else if (Character.toLowerCase(c[i]) != Character.toLowerCase(c[j])) return false; else { i++; j--; } } return true; } // Regex solution: remove all non-alpha eg." ,.:", but too slow public boolean isPalindrome22(String s) { s = s.toLowerCase().replaceAll("[^a-z0-9]", ""); return new StringBuilder(s).reverse().toString().equals(s); } // My 1st public boolean isPalindrome1(String s) { int i = 0; int j = s.length() - 1; do { while (i < j && !isAlphanumeric(s.charAt(i))) { i++; } while (i < j && !isAlphanumeric(s.charAt(j))) { j--; } if (i >= j) { return true; } if (!s.substring(i, i+1).equalsIgnoreCase(s.substring(j, j+1))) { //error1: ignore case return false; } i++; // error2: forget causing dead loop j--; } while (true); } private static boolean isAlphanumeric(char c) { return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9'); } }
mit
Azure/azure-sdk-for-java
sdk/delegatednetwork/azure-resourcemanager-delegatednetwork/src/main/java/com/azure/resourcemanager/delegatednetwork/models/Operations.java
1433
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.delegatednetwork.models; import com.azure.core.http.rest.PagedIterable; import com.azure.core.util.Context; /** Resource collection API of Operations. */ public interface Operations { /** * Lists all of the available DelegatedNetwork service REST API operations. * * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of REST API operations supported by an Azure Resource Provider. */ PagedIterable<Operation> list(); /** * Lists all of the available DelegatedNetwork service REST API operations. * * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return a list of REST API operations supported by an Azure Resource Provider. */ PagedIterable<Operation> list(Context context); }
mit
Data2Semantics/mustard
mustard-ducktape-experiments/src/main/java/org/data2semantics/mustard/experiments/modules/kernels/AbstractKernelModule.java
1456
package org.data2semantics.mustard.experiments.modules.kernels; import org.data2semantics.mustard.kernels.data.GraphData; import org.data2semantics.mustard.kernels.graphkernels.GraphKernel; import org.data2semantics.platform.Global; import org.data2semantics.platform.annotation.In; import org.data2semantics.platform.annotation.Main; import org.data2semantics.platform.annotation.Module; import org.data2semantics.platform.annotation.Out; /** * AbstractKernelModule generalizes the module stuff needed for GraphKernel's * * @author Gerben * */ @Module(name="AbstractKernel") public abstract class AbstractKernelModule<G extends GraphData> { protected GraphKernel<G> kernel; protected G graphData; protected double[][] matrix; protected long runtime; public AbstractKernelModule( @In(name="kernel") GraphKernel<G> kernel, @In(name="graphData") G graphData) { this.kernel = kernel; this.graphData = graphData; } @Main public double[][] compute() { long tic = System.currentTimeMillis(); matrix = kernel.compute(graphData); long toc = System.currentTimeMillis(); runtime = toc - tic; Global.log().info("Computed kernel: " + kernel.getLabel() + ", in: " + runtime + " msecs."); return matrix; } @Out(name="matrix") public double[][] getMatrix() { return matrix; } @Out(name="runtime") public Long getRuntime() { return runtime; } }
mit
newmann/shop
src/main/java/com/iwc/shop/common/utils/DateUtils.java
4711
/** * Copyright &copy; 2012-2014 <a href="http://www.iwantclick.com">iWantClick</a>iwc.shop All rights reserved. */ package com.iwc.shop.common.utils; import java.text.ParseException; import java.util.Date; import org.apache.commons.lang3.time.DateFormatUtils; /** * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类 * @author Tony Wong * @version 2014-4-15 */ public class DateUtils extends org.apache.commons.lang3.time.DateUtils { private static String[] parsePatterns = { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; /** * 得到当前日期字符串 格式(yyyy-MM-dd) */ public static String getDate() { return getDate("yyyy-MM-dd"); } /** * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */ public static String getDate(String pattern) { return DateFormatUtils.format(new Date(), pattern); } /** * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E" */ public static String formatDate(Date date, Object... pattern) { String formatDate = null; if (pattern != null && pattern.length > 0) { formatDate = DateFormatUtils.format(date, pattern[0].toString()); } else { formatDate = DateFormatUtils.format(date, "yyyy-MM-dd"); } return formatDate; } /** * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss) */ public static String formatDateTime(Date date) { return formatDate(date, "yyyy-MM-dd HH:mm:ss"); } /** * 得到当前时间字符串 格式(HH:mm:ss) */ public static String getTime() { return formatDate(new Date(), "HH:mm:ss"); } /** * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss) */ public static String getDateTime() { return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"); } /** * 得到当前年份字符串 格式(yyyy) */ public static String getYear() { return formatDate(new Date(), "yyyy"); } /** * 得到当前月份字符串 格式(MM) */ public static String getMonth() { return formatDate(new Date(), "MM"); } /** * 得到当天字符串 格式(dd) */ public static String getDay() { return formatDate(new Date(), "dd"); } /** * 得到当前星期字符串 格式(E)星期几 */ public static String getWeek() { return formatDate(new Date(), "E"); } /** * 日期型字符串转化为日期 格式 * { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", * "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" } */ public static Date parseDate(Object str) { if (str == null){ return null; } try { return parseDate(str.toString(), parsePatterns); } catch (ParseException e) { return null; } } /** * 获取过去的天数 * @param date * @return */ public static long pastDays(Date date) { long t = new Date().getTime()-date.getTime(); return t/(24*60*60*1000); } /** * 获取过去的小时 * @param date * @return */ public static long pastHour(Date date) { long t = new Date().getTime()-date.getTime(); return t/(60*60*1000); } /** * 获取过去的分钟 * @param date * @return */ public static long pastMinutes(Date date) { long t = new Date().getTime()-date.getTime(); return t/(60*1000); } /** * 转换为时间(天,时:分:秒.毫秒) * @param timeMillis * @return */ public static String formatDateTime(long timeMillis){ long day = timeMillis/(24*60*60*1000); long hour = (timeMillis/(60*60*1000)-day*24); long min = ((timeMillis/(60*1000))-day*24*60-hour*60); long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60); long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000); return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss; } /** * 获取两个日期之间的天数 * * @param before * @param after * @return */ public static double getDistanceOfTwoDate(Date before, Date after) { long beforeTime = before.getTime(); long afterTime = after.getTime(); return (afterTime - beforeTime) / (1000 * 60 * 60 * 24); } /** * @param args * @throws ParseException */ public static void main(String[] args) throws ParseException { // System.out.println(formatDate(parseDate("2010/3/6"))); // System.out.println(getDate("yyyy年MM月dd日 E")); // long time = new Date().getTime()-parseDate("2012-11-19").getTime(); // System.out.println(time/(24*60*60*1000)); } }
mit
vnukovkirill/jtest
src/main/java/com/springsource/petclinic/web/VetController.java
403
package com.springsource.petclinic.web; import com.springsource.petclinic.domain.Vet; import org.springframework.roo.addon.web.mvc.controller.RooWebScaffold; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RooWebScaffold(path = "vets", formBackingObject = Vet.class) @RequestMapping("/vets") @Controller public class VetController { }
mit
dusadpiyush96/Competetive
HackerRank/Algorithm/Implementation/ViralAdvertising.java
460
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n=sc.nextInt(); int liking=2; int total=2; for(int i=0;i<n-1;i++){ int sent=liking*3; liking=sent/2; total+=liking; } System.out.println(total); } }
mit
Tirke/cup-plugin
src/tirke/cupPlugin/editor/CupJavaInjector.java
1289
package tirke.cupPlugin.editor; import com.intellij.lang.java.JavaLanguage; import com.intellij.openapi.util.TextRange; import com.intellij.psi.InjectedLanguagePlaces; import com.intellij.psi.LanguageInjector; import com.intellij.psi.PsiLanguageInjectionHost; import org.jetbrains.annotations.NotNull; import tirke.cupPlugin.options.CupSettings; import tirke.cupPlugin.psi.impl.CupJavaImpl; /** * Created by Tirke on 22/02/2016 */ public class CupJavaInjector implements LanguageInjector { public static final String PREFIX = "{:"; public static final String SUFFIX = ":}"; private CupSettings settings = CupSettings.getInstance(); @Override public void getLanguagesToInject(@NotNull PsiLanguageInjectionHost host, @NotNull InjectedLanguagePlaces injectionPlacesRegistrar) { if (!(host instanceof CupJavaImpl) || !(settings.ENABLE_JAVA_INJECTION)) { return; } final CupJavaImpl cupJavaCode = (CupJavaImpl) host; final String text = cupJavaCode.getText(); if (!(text.startsWith(PREFIX) && text.endsWith(SUFFIX))) { return; } injectionPlacesRegistrar.addPlace(JavaLanguage.INSTANCE, new TextRange(SUFFIX.length(), text.length() - SUFFIX.length()), "public class Dummy { public void dummyMethod(){", "}}"); } }
mit
zunath/Contagion_JVM
src/contagionJVM/System/SpawnSystem.java
12341
package contagionJVM.System; import contagionJVM.Helper.LocalArray; import contagionJVM.NWNX.NWNX_Funcs; import contagionJVM.NWNX.NWNX_TMI; import org.nwnx.nwnx2.jvm.NWLocation; import org.nwnx.nwnx2.jvm.NWObject; import org.nwnx.nwnx2.jvm.NWScript; import org.nwnx.nwnx2.jvm.Scheduler; import org.nwnx.nwnx2.jvm.constants.ObjectType; import java.util.Objects; public class SpawnSystem { // The amount of time between spawns, in seconds // Default: 120 (2 minutes) final int ZSS_SPAWN_DELAY = 120; // The name of the variable which determines the name of the spawn points in an area // This variable is stored on the area object final String ZSS_WAYPOINT_NAME = "ZSS_WAYPOINT_NAME"; // The name of the variable which determines which group to pull spawn resrefs from. // This variable is stored on the area object final String ZSS_GROUP_ID = "ZSS_GROUP_ID"; // The name of the variable which determines how many spawn points there are in an area // This variable is stored on the area object final String ZSS_SPAWN_WAYPOINT_COUNT = "ZSS_SPAWN"; // The name of the variable which determines how many respawn points there are in an area // This variable is stored on the area object final String ZSS_RESPAWN_WAYPOINT_COUNT = "ZSS_RESPAWN"; // The name of the array which stores spawn waypoint locations final String ZSS_SPAWN_WAYPOINT_LOCATION_ARRAY = "ZSS_SPAWN_WAYPOINT_LOCATION_ARRAY"; // The name of the array which stores respawn waypoint locations final String ZSS_RESPAWN_WAYPOINT_LOCATION_ARRAY = "ZSS_RESPAWN_WAYPOINT_LOCATION_ARRAY"; // The name of the variable which stores the number of zombies to spawn in an area // This variable is stored on the area object final String ZSS_ZOMBIE_COUNT = "ZSS_COUNT"; // Name of the variable which tells the system whether or not a zombie was spawned by the system // as opposed to being spawned by a DM. final String ZSS_ZOMBIE_SPAWNED = "ZSS_ZOMBIE_SPAWNED"; // Name of the variable which keeps track of the number of players in an area final String ZSS_PLAYER_COUNT = "ZSS_PLAYER_COUNT"; // Resref of the spawn waypoints. final String ZSS_SPAWN_WAYPOINT_RESREF = "zombie_spawn"; // Resref of the respawn waypoints. final String ZSS_RESPAWN_WAYPOINT_RESREF = "zombie_respawn"; private void ZSS_DelayCreateZombie(String sZombieResref, NWLocation lWaypointLocation, NWObject oArea) { // Only respawn if there's PCs in the area if(NWScript.getLocalInt(oArea, ZSS_PLAYER_COUNT) > 0) { final NWObject oZombie = NWScript.createObject(ObjectType.CREATURE, sZombieResref, lWaypointLocation, false, ""); // Just to make sure this zombie was spawned by the spawn system and not by a DM NWScript.setLocalInt(oZombie, ZSS_ZOMBIE_SPAWNED, 1); Scheduler.assign(oZombie, new Runnable() { @Override public void run() { NWScript.setFacing(0.01f * NWScript.random(3600)); NWScript.actionRandomWalk(); } }); } } public void ZSS_OnAreaEnter(NWObject oArea) { NWObject oPC = NWScript.getEnteringObject(); if(!NWScript.getIsPC(oPC)) return; int iZombieCount = NWScript.getLocalInt(oArea, ZSS_ZOMBIE_COUNT); int iWaypointCount = NWScript.getLocalInt(oArea, ZSS_SPAWN_WAYPOINT_COUNT); int iGroupID = NWScript.getLocalInt(oArea, ZSS_GROUP_ID); if(iGroupID < 1) iGroupID = 1; // Determine if this is the first PC in the area int iPCCount = 0; NWObject[] players = NWScript.getPCs(); for(NWObject pc : players) { if(oArea.equals(NWScript.getArea(pc))) { iPCCount++; } } // Only spawn zombies if this is the first PC in the area if(iPCCount == 1) { boolean bUnique = true; for(int iCurrentZombie = 1; iCurrentZombie <= iZombieCount; iCurrentZombie++) { int iWaypoint; // Ensure that at least one zombie will be placed at each spawn point if(iCurrentZombie > iWaypointCount) { iWaypoint = NWScript.random(iWaypointCount) + 1; } else { iWaypoint = iCurrentZombie; } String sResref = ZSS_GetZombieToSpawn(iGroupID, bUnique); NWLocation lLocation = LocalArray.GetLocalArrayLocation(oArea, ZSS_SPAWN_WAYPOINT_LOCATION_ARRAY, iWaypoint); final NWObject oZombie = NWScript.createObject(ObjectType.CREATURE, sResref, lLocation, false, ""); // Mark zombie as spawned via the system (as opposed from a DM) NWScript.setLocalInt(oZombie, ZSS_ZOMBIE_SPAWNED, 1); // NWScript.randomize facing Scheduler.assign(oZombie, new Runnable() { @Override public void run() { NWScript.setFacing(0.01f * NWScript.random(3600)); } }); // No more chances to spawn a unique creature bUnique = false; } } // Update PC counter NWScript.setLocalInt(oArea, ZSS_PLAYER_COUNT, iPCCount); } public void ZSS_OnAreaExit(NWObject oArea) { NWObject oPC = NWScript.getExitingObject(); if(!NWScript.getIsPC(oPC)) return; int iPCCount = 0; NWObject[] players = NWScript.getPCs(); for(NWObject pc : players) { if(oArea.equals(NWScript.getArea(pc))) { iPCCount++; } } // Last PC exited the area. Despawn all zombies. if(iPCCount <= 0) { NWObject[] objects = NWScript.getObjectsInArea(oArea); for(NWObject currentObject : objects) { if(NWScript.getLocalInt(currentObject, ZSS_ZOMBIE_SPAWNED) == 1) { NWScript.destroyObject(currentObject, 0.0f); } } } // Update PC counter NWScript.setLocalInt(oArea, ZSS_PLAYER_COUNT, iPCCount); } public void ZSS_OnModuleLoad() { int tmiLimit = NWNX_TMI.GetTMILimit(); NWNX_TMI.SetTMILimit(7000000); NWObject oArea = NWNX_Funcs.GetFirstArea(); while(NWScript.getIsObjectValid(oArea)) { String sSpawnID = NWScript.getResRef(oArea); int iSpawnCount = 0; int iRespawnCount = 0; NWObject[] areaObjects = NWScript.getObjectsInArea(oArea); for(NWObject obj : areaObjects) { String sResref = NWScript.getResRef(obj); // Spawn waypoint if(Objects.equals(sResref, ZSS_SPAWN_WAYPOINT_RESREF)) { iSpawnCount++; LocalArray.SetLocalArrayLocation(oArea, ZSS_SPAWN_WAYPOINT_LOCATION_ARRAY, iSpawnCount, NWScript.getLocation(obj)); } // Respawn waypoint else if(Objects.equals(sResref, ZSS_RESPAWN_WAYPOINT_RESREF)) { iRespawnCount++; LocalArray.SetLocalArrayLocation(oArea, ZSS_RESPAWN_WAYPOINT_LOCATION_ARRAY, iRespawnCount, NWScript.getLocation(obj)); } } // Mark the number of spawn and respawn waypoints for this area NWScript.setLocalInt(oArea, ZSS_SPAWN_WAYPOINT_COUNT, iSpawnCount); NWScript.setLocalInt(oArea, ZSS_RESPAWN_WAYPOINT_COUNT, iRespawnCount); // Mark the unique identifier (the resref) NWScript.setLocalString(oArea, ZSS_WAYPOINT_NAME, sSpawnID); oArea = NWNX_Funcs.GetNextArea(); } // Set the TMI limit back to normal NWNX_TMI.SetTMILimit(tmiLimit); } public void ZSS_OnZombieDeath(NWObject oZombie) { final NWObject oArea = NWScript.getArea(oZombie); int iWaypointCount = NWScript.getLocalInt(oArea, ZSS_RESPAWN_WAYPOINT_COUNT); if(NWScript.getLocalInt(oZombie, ZSS_ZOMBIE_SPAWNED) != 1 || iWaypointCount <= 0) return; int iPCCount = NWScript.getLocalInt(oArea, ZSS_PLAYER_COUNT); int iGroupID = NWScript.getLocalInt(oArea, ZSS_GROUP_ID); if(iGroupID <= 0) iGroupID = 1; if(iPCCount > 0) { int iWaypoint = NWScript.random(iWaypointCount) + 1; final String sResref = ZSS_GetZombieToSpawn(iGroupID, false); final NWLocation lLocation = LocalArray.GetLocalArrayLocation(oArea, ZSS_RESPAWN_WAYPOINT_LOCATION_ARRAY, iWaypoint); Scheduler.delay(oZombie, ZSS_SPAWN_DELAY * 1000, new Runnable() { @Override public void run() { ZSS_DelayCreateZombie(sResref, lLocation, oArea); } }); } } private String ZSS_GetZombieToSpawn(int iGroupID, boolean bUnique) { String sResref = ""; switch(iGroupID) { // Group #1 - Basic Zombies (Tier 1) case 1: { int iNumberOfChoices = 15; switch(NWScript.random(iNumberOfChoices) + 1) { case 1: sResref = "reo_zombie_1"; break; case 2: sResref = "reo_zombie_2"; break; case 3: sResref = "reo_zombie_3"; break; case 4: sResref = "reo_zombie_4"; break; case 5: sResref = "reo_zombie_5"; break; case 6: sResref = "reo_zombie_6"; break; case 7: sResref = "reo_zombie_7"; break; case 8: sResref = "reo_zombie_8"; break; case 9: sResref = "reo_zombie_9"; break; case 10: sResref = "reo_zombie_10"; break; case 11: sResref = "reo_zombie_11"; break; case 12: sResref = "reo_zombie_12"; break; case 13: sResref = "reo_zombie_13"; break; case 14: sResref = "reo_zombie_14"; break; case 15: sResref = "reo_zombie_15"; break; } break; } // Group #2 - Walkers and MA-121 Hunter Alphas (Tier 2) case 2: { if(bUnique) { int iChance = NWScript.random(100) + 1; // 15% to spawn a Hunter if(iChance <= 15) { sResref = "reo_hunter_1"; } } if(Objects.equals(sResref, "")) { int iNumberOfChoices = 15; // In all other cases, spawn normal Walkers switch(NWScript.random(iNumberOfChoices) + 1) { case 1: sResref = "reo_walker_1"; break; case 2: sResref = "reo_walker_2"; break; case 3: sResref = "reo_walker_3"; break; case 4: sResref = "reo_walker_4"; break; case 5: sResref = "reo_walker_5"; break; case 6: sResref = "reo_walker_6"; break; case 7: sResref = "reo_walker_7"; break; case 8: sResref = "reo_walker_8"; break; case 9: sResref = "reo_walker_9"; break; case 10: sResref = "reo_walker_10"; break; case 11: sResref = "reo_walker_11"; break; case 12: sResref = "reo_walker_12"; break; case 13: sResref = "reo_walker_13"; break; case 14: sResref = "reo_walker_14"; break; case 15: sResref = "reo_walker_15"; break; } } break; } } return sResref; } }
mit
arya-aag/EpsilonData
Project/workspace/DemosJDBC/src/demos/jdbc/PreparedStatementDemo.java
2911
package demos.jdbc; import java.sql.*; import java.math.*; public class PreparedStatementDemo { public static void main(String[] args) { // Set up a default JDBC driver and database name. String jdbcDriver = "com.mysql.jdbc.Driver"; String databaseUri = "jdbc:mysql://localhost/mydatabase?user=root"; if (args.length == 2) { jdbcDriver = args[0]; databaseUri = args[1]; } // Load JDBC driver. try { Class.forName(jdbcDriver); } catch (ClassNotFoundException e) { System.out.println("Error loading JDBC driver: " + e); } // Connect to a database. Connection cn = null; try { cn = DriverManager.getConnection(databaseUri); } catch (SQLException e) { System.out.println("Error connecting to a database: " + e); } // Execute some prepared statements. try { // Create a prepared statement, to do some INSERTs PreparedStatement ps = cn.prepareStatement("INSERT INTO Employees (Name, Salary, Region) VALUES (?, ?, ?)"); // Insert some rows ps.setString(1, "Thomas"); ps.setBigDecimal(2, new BigDecimal(10000)); ps.setString(3, "Wales"); ps.executeUpdate(); ps.setString(1, "Emily"); ps.setBigDecimal(2, new BigDecimal(20000)); ps.setString(3, "Wales"); ps.executeUpdate(); ps.setString(1, "Laura"); ps.setBigDecimal(2, new BigDecimal(50000)); ps.setString(3, "London"); ps.executeUpdate(); // Create a prepared statement, to do some UPDATEs ps = cn.prepareStatement("UPDATE Employees SET Salary = Salary * ? WHERE Region = ?"); ps.setDouble(1, 1.25); ps.setString(2, "Wales"); ps.executeUpdate(); ps.setDouble(1, 1.10); ps.setString(2, "London"); ps.executeUpdate(); } catch (SQLException e) { System.out.println("Error executing INSERT, DELETE, or UPDATE statement: " + e); } // Display the new contents of the Employees table ResultSet rsEmps = null; try { Statement st = cn.createStatement(); rsEmps = st.executeQuery("SELECT Name, Salary, Region FROM Employees"); while (rsEmps.next() != false) { String name = rsEmps.getString("Name"); BigDecimal salary = rsEmps.getBigDecimal("Salary"); String region = rsEmps.getString("Region"); System.out.println("Name: " + name + "\tsalary: " + salary + "\tRegion: " + region); } } catch (SQLException e) { System.out.println("Error executing SELECT statement: " + e); } } }
mit
iMarketingPlus/foundation-service
src/main/java/com/icompany/foundation/model/AccountType.java
424
package com.icompany.foundation.model; /** * Created by Administrator on 2016/5/31. */ public enum AccountType { PLATFORM_ADMIN("platform administrator"), SYS_ADMIN("system administrator"), NORMAL("normal"); private String description; AccountType(String description) { this.description = description; } @Override public String toString() { return this.description; } }
mit
BioPAX/validator
biopax-validator/src/main/java/org/biopax/validator/rules/ControlledVocabularyTermCRRule.java
433
package org.biopax.validator.rules; import org.biopax.paxtools.model.level3.ControlledVocabulary; import org.biopax.validator.CardinalityAndRangeRule; import org.springframework.stereotype.Component; @Component public class ControlledVocabularyTermCRRule extends CardinalityAndRangeRule<ControlledVocabulary> { public ControlledVocabularyTermCRRule() { super(ControlledVocabulary.class, "term", 1, 0, String.class); } }
mit
arieldossantos/cherryserver
src/cherryserver/server/Settings.java
503
package cherryserver.server; /** * * @author Ariel Reis */ public abstract class Settings { public static final int PORT = 8080; public static final String USER_EXECUTION_PATH = System.getProperty("user.dir"); // User class execute path public static final String PATH_RENDER = USER_EXECUTION_PATH + "\\dist\\public\\index.html"; public static final String TYPE_RENDER_LANG = "php"; /* Type file render: 'php' or null to html */ public static boolean SERVER_IS_RUNNING = true; }
mit
jonesd/udanax-gold2java
abora-gold/src/main/java/info/dgjones/abora/gold/java/urdi/Urdi.java
6325
/** * The MIT License * Copyright (c) 2003 David G Jones * * 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 info.dgjones.abora.gold.java.urdi; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.RandomAccessFile; import java.nio.channels.FileChannel; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.SortedSet; import info.dgjones.abora.gold.collection.basic.UInt8Array; import info.dgjones.abora.gold.java.exception.AboraRuntimeException; import info.dgjones.abora.gold.xpp.basic.Heaper; public class Urdi extends Heaper { private String filename; private int lruCount; private Map space = new HashMap(); private int totalSnarfs = -1; private UrdiView lastView = null; private static final int DEFAULT_TOTAL_SNARFS = 64; //TODO guess at size. Seems like it needs to be a multiple of 4 in size protected static final int SNARF_SIZE = 32000; public Urdi(String filename, int lruCount) { super(); this.filename = filename; this.lruCount = lruCount; try { File file = new File(filename); if (file.exists()) { loadFile(); } else { initializeEmptySpace(); writeFile(); } } catch (IOException e) { throw new AboraRuntimeException("Failed to initialize Urd: "+this+" due to: "+e); } } private void initializeEmptySpace() { totalSnarfs = DEFAULT_TOTAL_SNARFS; for (int i = 0; i < totalSnarfs; i++) { UInt8Array snarfSpace = UInt8Array.make(SNARF_SIZE); space.put(new Integer(i), snarfSpace); } } private void writeFile() throws IOException { FileOutputStream fileOutputStream = new FileOutputStream(filename, false); try { for (int i = 0; i < totalSnarfs; i++) { UInt8Array blockArray = (UInt8Array)space.get(new Integer(i)); byte[] block = blockArray.gutsOfByteArray(); try { if (block.length != SNARF_SIZE) { throw new IllegalStateException("Snarf not expected size: "+SNARF_SIZE+", but was: "+block.length); } fileOutputStream.write(block); } finally { blockArray.noMoreGuts(); } } } finally { fileOutputStream.close(); } } private void loadFile() throws IOException { if (!space.isEmpty()) { throw new IllegalStateException("Urdi space already contains content, cant load: "+this); } FileInputStream fileInputStream = new FileInputStream(filename); try { totalSnarfs = 0; while (readSnarf(fileInputStream, totalSnarfs)) { totalSnarfs += 1; } } finally { fileInputStream.close(); } } private boolean readSnarf(FileInputStream fileInputStream, int index) throws IOException { byte[] block = new byte[SNARF_SIZE]; int next = 0; do { int read = fileInputStream.read(block, next, block.length - next); if (read != -1) { next += read; } else { next = -1; } } while (next != -1 && next != block.length); UInt8Array array = UInt8Array.makeShared(block); space.put(new Integer(index), array); return next != -1; } public UrdiView makeWriteView() { return onlyView(new UrdiView(this, true)); } public static Urdi urdi(String fname, int lruCount) { return new Urdi(fname, lruCount); } private UrdiView onlyView(UrdiView view) { if (lastView != null) { lastView.spent = true; } lastView = view; return view; } public int usableSnarfs() { //TODO rubbish - See SnarfInfoHandle return totalSnarfs; } public int getDataSizeOfSnarf(int i) { return SNARF_SIZE; } public int usableStages() { //TODO have no idea what this means... return 100; } public UrdiView makeReadView() { return onlyView(new UrdiView(this, false)); } public void printOn(PrintWriter oo) { oo.print(getAboraClass().name()); oo.print("("); oo.print(filename); oo.print(")"); } protected UInt8Array getSpace(int snarfID) { UInt8Array snarfSpace = (UInt8Array)space.get(new Integer(snarfID)); if (snarfSpace == null) { throw new AboraRuntimeException("Unknown snarfId: "+snarfID+" for urdi: "+this); } return snarfSpace; } public void writeSnarfs(SortedSet toCommit) { System.out.print(toString()+" writeAll: ("); for (Iterator iter = toCommit.iterator(); iter.hasNext();) { SnarfHandle handle = (SnarfHandle) iter.next(); System.out.print(handle.getSnarfID()); System.out.print(" "); } System.out.println(")"); try { //TODO cache stream // Review mode - need some forcing going on here! RandomAccessFile file = new RandomAccessFile(filename, "rwd"); try { for (Iterator iter = toCommit.iterator(); iter.hasNext();) { SnarfHandle handle = (SnarfHandle) iter.next(); UInt8Array array = handle.getData(); file.seek(handle.getSnarfID() * (long)SNARF_SIZE); //TODO not safe if later failure try { file.write(array.gutsOfByteArray()); } finally { array.noMoreGuts(); } space.put(new Integer(handle.getSnarfID()), array); } } finally { file.close(); } } catch (IOException e) { // TODO not transactionally safe... System.out.println("WARNING: Transactionally unsafe failure of writeSnarf"); throw new AboraRuntimeException("Failed to write snarfs, due to: "+e); } } }
mit
rodillos/intensamenteHaskell
src/TestRememorar.java
3455
import static org.junit.Assert.*; import java.util.ArrayList; import org.junit.Before; import org.junit.Test; public class TestRememorar { private Niña riley = new Niña(11); private Niña riley1 = new Niña(11); private Niña riley2 = new Niña(11); private Alegria alegria = new Alegria(); private int añoTest = 1999; private int mesTest = 0; private int diaTest = 19; private ArrayList<Recuerdo> recuerdosTest = new ArrayList<Recuerdo>(); private Recuerdo recuerdo1 = new Recuerdo(); private Recuerdo recuerdo2 = new Recuerdo(); private Recuerdo recuerdo3 = new Recuerdo(); @Before //8.Hacer rememorar algo a Riley public void antesQue8(){ recuerdo1.establecerDescripcion("saltar la soga"); recuerdo1.establecerEmocionDominante(alegria); recuerdo1.establecerFecha(añoTest , mesTest , diaTest); riley2.establecerEmocionDominante(alegria); riley2.memoriaALargoPlazo.add(recuerdo1); riley2.memoriaALargoPlazo.add(recuerdo2); riley2.memoriaALargoPlazo.add(recuerdo3); } @Test public void hacerRememorar(){ assertEquals(recuerdo1.obtenerDescripcion(), riley2.rememorar().obtenerDescripcion()); assertEquals(recuerdo1.obtenerEmocionDominante(), riley2.rememorar().obtenerEmocionDominante()); assertEquals(recuerdo1.obtenerAño(), riley2.rememorar().obtenerAño()); assertEquals(recuerdo1.obtenerMes(), riley2.rememorar().obtenerMes()); assertEquals(recuerdo1.obtenerDia(), riley2.rememorar().obtenerDia()); } @Before //9.Cantidad de repeticiones de un recuerdo en la memoria a largo plazo. public void antesQue9(){ recuerdo1.establecerDescripcion("saltar la soga"); recuerdo2.establecerDescripcion("jugar al futbol"); recuerdo3.establecerDescripcion("pasear al perro"); recuerdosTest.add(recuerdo1); recuerdosTest.add(recuerdo2); recuerdosTest.add(recuerdo3); int iterador = 0; while (iterador < recuerdosTest.size()){ recuerdosTest.get(iterador).establecerEmocionDominante(alegria); recuerdosTest.get(iterador).establecerFecha(añoTest, mesTest , diaTest); iterador++; } riley.memoriaALargoPlazo.add(recuerdo1); riley.memoriaALargoPlazo.add(recuerdo2); riley.memoriaALargoPlazo.add(recuerdo1); riley.memoriaALargoPlazo.add(recuerdo3); riley.memoriaALargoPlazo.add(recuerdo1); } @Test public void conocercCantidadDeRepeticiones(){ assertEquals(3 , riley.cantidadDeRepeticionesDeUnRecuerdo(recuerdo1)); assertEquals(1 , riley.cantidadDeRepeticionesDeUnRecuerdo(recuerdo2)); assertEquals(1 , riley.cantidadDeRepeticionesDeUnRecuerdo(recuerdo3)); } @Before //10.Saber si Riley esta teniendo un Deja vu public void antesQue10(){ recuerdo1.establecerDescripcion("saltar la soga"); recuerdo2.establecerDescripcion("jugar al futbol"); recuerdo3.establecerDescripcion("pasear al perro"); recuerdosTest.add(recuerdo1); recuerdosTest.add(recuerdo2); recuerdosTest.add(recuerdo3); int iterador = 0; while (iterador < recuerdosTest.size()){ recuerdosTest.get(iterador).establecerEmocionDominante(alegria); recuerdosTest.get(iterador).establecerFecha(añoTest , mesTest , diaTest); iterador++; } riley1.pensamientoActual = recuerdo1; riley1.memoriaALargoPlazo.add(recuerdo1); riley1.memoriaALargoPlazo.add(recuerdo2); riley1.memoriaALargoPlazo.add(recuerdo1); riley1.memoriaALargoPlazo.add(recuerdo3); riley1.memoriaALargoPlazo.add(recuerdo1); } @Test public void conocerSiEsDejaVu(){ assert(riley1.tieneUnDejaVu()); } }
mit
Azure/azure-sdk-for-java
sdk/spring/azure-spring-integration-servicebus/src/test/java/com/azure/spring/integration/servicebus/ServiceBusMessageHandlerTest.java
1693
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.spring.integration.servicebus; import com.azure.spring.integration.core.DefaultMessageHandler; import com.azure.spring.integration.core.api.PartitionSupplier; import com.azure.spring.integration.servicebus.queue.ServiceBusQueueOperation; import com.azure.spring.integration.test.support.MessageHandlerTest; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.mockito.MockitoAnnotations; import org.springframework.messaging.Message; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isA; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServiceBusMessageHandlerTest extends MessageHandlerTest<ServiceBusQueueOperation> { private AutoCloseable closeable; @BeforeEach @Override @SuppressWarnings("unchecked") public void setUp() { this.closeable = MockitoAnnotations.openMocks(this); this.future.complete(null); this.sendOperation = mock(ServiceBusQueueOperation.class); when(this.sendOperation.sendAsync(eq(this.destination), isA(Message.class), isA(PartitionSupplier.class))).thenReturn(future); when( this.sendOperation.sendAsync(eq(this.dynamicDestination), isA(Message.class), isA(PartitionSupplier.class))) .thenReturn(future); this.handler = new DefaultMessageHandler(this.destination, this.sendOperation); } @AfterEach public void close() throws Exception { closeable.close(); } }
mit
ligoj/bootstrap
bootstrap-business/src/test/java/org/ligoj/bootstrap/model/test/DummyBusinessEntity3.java
549
/* * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE) */ package org.ligoj.bootstrap.model.test; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.ligoj.bootstrap.core.model.AbstractBusinessEntity; import lombok.Getter; import lombok.Setter; /** * Simple business entity */ @Getter @Setter @Entity @Table(name = "DEMO_DUMMY") public class DummyBusinessEntity3 extends AbstractBusinessEntity<Integer> { @ManyToOne private DummyBusinessEntity3 parent; }
mit
kremnev8/AdvancedSpaceStaion-mod
src/main/java/net/glider/src/network/packets/DeconstructPacket.java
4295
package net.glider.src.network.packets; import io.netty.buffer.ByteBuf; import java.util.ArrayList; import java.util.List; import net.glider.src.strucures.DeconstructHandler; import net.glider.src.strucures.Structure; import net.glider.src.utils.ChatUtils; import net.glider.src.utils.GLoger; import net.glider.src.utils.LocalizedChatComponent; import net.glider.src.utils.LocalizedString; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.ChatComponentText; import net.minecraft.util.EnumChatFormatting; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import cpw.mods.fml.common.network.ByteBufUtils; import cpw.mods.fml.common.network.simpleimpl.IMessage; import cpw.mods.fml.common.network.simpleimpl.IMessageHandler; import cpw.mods.fml.common.network.simpleimpl.MessageContext; public class DeconstructPacket implements IMessage { private List<Structure> objects = new ArrayList<Structure>(); private int[] pos; public DeconstructPacket() { } public DeconstructPacket(List<Structure> objs, int[] pos) { objects = objs; this.pos = pos; } public DeconstructPacket(Structure obj, int[] pos) { objects.add(obj); this.pos = pos; } private int FindDir(ForgeDirection dir) { for (int i = 0; i < 6; i++) { if (dir == ForgeDirection.getOrientation(i)) { return i; } } return -1; } @Override public void fromBytes(ByteBuf buf) { NBTTagCompound tag = ByteBufUtils.readTag(buf); pos = tag.getIntArray("INF_POS"); if (tag.getBoolean("OBJ")) { for (int i = 0; i < tag.getInteger("N_O"); i++) { Structure str = Structure.FindStructure(tag.getString("O" + i + "_OBJ")); int[] t1 = tag.getIntArray("O" + i + "_POS"); int t2 = tag.getInteger("O" + i + "_ROT"); ForgeDirection t3 = ForgeDirection.getOrientation(tag.getInteger("O" + i + "_DIR")); str.Configure(t1, t2, t3); objects.add(str); } } } @Override public void toBytes(ByteBuf buf) { NBTTagCompound tag = new NBTTagCompound(); if (objects != null && objects.size() > 0) { tag.setInteger("N_O", objects.size()); tag.setBoolean("OBJ", true); for (int i = 0; i < objects.size(); i++) { tag.setInteger("O" + i + "_DIR", objects.get(i).placementDir.ordinal()); tag.setInteger("O" + i + "_ROT", objects.get(i).placementRotation); tag.setIntArray("O" + i + "_POS", objects.get(i).placementPos); tag.setString("O" + i + "_OBJ", objects.get(i).getUnlocalizedName()); } } else { tag.setBoolean("OBJ", false); } tag.setIntArray("INF_POS", pos); ByteBufUtils.writeTag(buf, tag); } public static class Handler implements IMessageHandler<DeconstructPacket, IMessage> { @Override public IMessage onMessage(DeconstructPacket pkt, MessageContext ctx) { if (pkt.objects != null && pkt.objects.size() > 0) { GLoger.logInfo("Deconstruct Packet Sucsessfuly recived!"); EntityPlayerMP player = ctx.getServerHandler().playerEntity; if (player == null) return null; World world = player.worldObj; int deconstruct = DeconstructHandler.HandleDeconstruct(world, pkt.objects, player, pkt.pos); if (deconstruct == 0) { ChatUtils.SendChatMessageOnClient(player, new LocalizedChatComponent(new LocalizedString("builder.deconstruct.failed", EnumChatFormatting.RED))); } else if (deconstruct == 1) { ChatUtils.SendChatMessageOnClient(player, new LocalizedChatComponent(new LocalizedString("builder.deconstruct.partfailed", EnumChatFormatting.YELLOW))); } else { ChatUtils .SendChatMessageOnClient(player, new LocalizedChatComponent(new LocalizedString("builder.deconstruct.successfully", EnumChatFormatting.GREEN)) .appendSibling(new ChatComponentText("!"))); } // player.addChatMessage(ChatUtils.modifyColor(new // ChatComponentText(StatCollector.translateToLocal("builder.deconstruct.successfully")+"!"),EnumChatFormatting.GREEN)); // System.out.println("Building on server was failed!"); } else { GLoger.logWarn("An error on handling deconstruct packet. report this to dev!"); GLoger.logWarn("info: Structures List null or empty"); } return null; } } }
mit
edmundophie/kafka-chat
src/main/java/com/edmundophie/chat/ChatServer.java
12655
package com.edmundophie.chat; import com.edmundophie.rpc.Request; import com.edmundophie.rpc.Response; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import kafka.consumer.Consumer; import kafka.consumer.ConsumerConfig; import kafka.consumer.ConsumerIterator; import kafka.consumer.KafkaStream; import kafka.javaapi.consumer.ConsumerConnector; import kafka.javaapi.producer.Producer; import kafka.message.MessageAndMetadata; import kafka.producer.KeyedMessage; import kafka.producer.ProducerConfig; import java.io.IOException; import java.util.*; /** * Created by edmundophie on 10/16/15. */ public class ChatServer { private static Producer responseProducer; private final static String BROKER_LIST = "localhost:9092"; private final static String PRODUCER_TYPE= "sync"; private final static String SERIALIZER = "kafka.serializer.StringEncoder"; private final static String REQUEST_REQUIRED_ACK = "1"; private final static String RPC_REQUEST_TOPIC_NAME = "rpcRequestTopic"; private final static String ZOOKEEPER_SERVER = "localhost:2181"; private final static String RPC_RESPONSE_TOPIC_NAME = "rpcResponseTopic"; private final static String SERVER_CONSUMER_GROUP = "server-consumer-group"; private final static int MAX_GENERATED_RANDOM_ACCOUNT_INT = 99999; private static Map<String, User> userMap; private static Map<String, Channel> channelMap; private ConsumerConnector consumerConnector; private ConsumerIterator<byte[], byte[]> consumerIterator; private ObjectMapper mapper; public ChatServer() { initResponseProducer(); initRequestConsumer(); mapper = new ObjectMapper(); } public static void main(String[] args) throws JsonProcessingException { System.out.println("- Starting server..."); initConfiguration(); ChatServer server = new ChatServer(); server.start(); server.shutdown(); responseProducer.close(); } public static void initConfiguration() { userMap = new HashMap<String, User>(); channelMap = new HashMap<String, Channel>(); } private void initResponseProducer() { Properties props = new Properties(); props.put("metadata.broker.list", BROKER_LIST); props.put("request.required.acks", REQUEST_REQUIRED_ACK); props.put("producer.type", PRODUCER_TYPE); props.put("serializer.class", SERIALIZER); props.put("retry.backoff.ms", "500"); ProducerConfig config = new ProducerConfig(props); responseProducer = new Producer(config); } private void initRequestConsumer() { Properties props = new Properties(); props.put("zookeeper.connect", ZOOKEEPER_SERVER); props.put("group.id", SERVER_CONSUMER_GROUP); props.put("zookeeper.session.timeout.ms", "400"); props.put("zookeeper.sync.time.ms", "200"); props.put("auto.commit.interval.ms", "1000"); props.put("auto.offset.reset", "largest"); ConsumerConfig config = new ConsumerConfig(props); consumerConnector = Consumer.createJavaConsumerConnector(config); Map<String, Integer> topicCountMap = new HashMap<String, Integer>(); topicCountMap.put(RPC_REQUEST_TOPIC_NAME, 1); Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumerConnector.createMessageStreams(topicCountMap); KafkaStream<byte[], byte[]> stream = consumerMap.get(RPC_REQUEST_TOPIC_NAME).get(0); consumerIterator = stream.iterator(); } private static void sendRpcResponse(String message, String corrId) { KeyedMessage<String, String> msg = new KeyedMessage<String, String>(RPC_RESPONSE_TOPIC_NAME, corrId, message); responseProducer.send(msg); } private static void sendMessageToTopic(String message, String topic) { KeyedMessage<String, String> msg = new KeyedMessage<String, String>(topic, message); responseProducer.send(msg); } private void start() throws JsonProcessingException { System.out.println("- Server started"); String requestMessage; String corrId; while (true) { if(consumerIterator.hasNext()) { MessageAndMetadata<byte[], byte[]> request = consumerIterator.next(); corrId = new String(request.key()); requestMessage = new String(request.message()); String responseMessage = processRequest(requestMessage); sendRpcResponse(responseMessage, corrId); } } } private void shutdown() { consumerConnector.shutdown(); } private String processRequest(String requestMessage) throws JsonProcessingException { Request request = null; try { request = mapper.readValue(requestMessage, Request.class); } catch (IOException e) { Response response = new Response(); response.putStatus(false); response.setMessage("* Server Encountered An Error On Processing Message!"); return mapper.writeValueAsString(response); } if (request.getCommand().equalsIgnoreCase("NICK")) { return login(request.getNickname()); } else if (request.getCommand().equalsIgnoreCase("JOIN")) { return join(request.getNickname(), request.getChannelName()); } else if (request.getCommand().equalsIgnoreCase("LEAVE")) { return leave(request.getNickname(), request.getChannelName()); } else if (request.getCommand().equalsIgnoreCase("LOGOUT")) { return logout(request.getNickname()); } else if (request.getCommand().equalsIgnoreCase("EXIT")) { return exit(request.getNickname()); } else if (request.getCommand().equalsIgnoreCase("SEND")) { return sendMessage(request.getNickname(), request.getChannelName(), request.getMessage()); } else if (request.getCommand().equalsIgnoreCase("BROADCAST")) { return broadcastMessage(request.getNickname(), request.getMessage()); } else { Response response = new Response(); response.putStatus(false); response.setMessage("* Unknown Message Command!"); return mapper.writeValueAsString(response); } } private String login(String nickname) { System.out.println("- Login method invoked"); StringBuilder message = new StringBuilder(); if(nickname==null || nickname.isEmpty() || userMap.containsKey(nickname)) { if(userMap.containsKey(nickname)) message.append("* Username exist!\n"); nickname = generateRandomNickname(); message.append("* Random user generated\n"); } message.append("* Successfully logged in as " + nickname); userMap.put(nickname, new User(nickname)); Response response = new Response(true, message.toString(), nickname); return response.toString(); } private static String generateRandomNickname() { String newNickname; Random random = new Random(); do { newNickname = "user" + random.nextInt(MAX_GENERATED_RANDOM_ACCOUNT_INT); } while(userMap.containsKey(newNickname)); return newNickname; } public static String join(String nickname, String channelName) { System.out.println("- " + nickname + " requested to join #" + channelName); List userChannelList = userMap.get(nickname).getJoinedChannel(); StringBuilder message = new StringBuilder(); Response response = new Response(); if(userChannelList.contains(channelName)) { message.append("* You are already a member of #" + channelName); response.putStatus(false); } else { if(!channelMap.containsKey(channelName)) { channelMap.put(channelName, new Channel(channelName)); message.append("* Created new channel #" + channelName + "\n"); } userChannelList.add(channelName); message.append("* #" + channelName + " joined successfully"); response.putStatus(true); } response.setMessage(message.toString()); return response.toString(); } public static String leave(String nickname, String channelName) { System.out.println("- " + nickname + " request to leave #" + channelName); StringBuilder message = new StringBuilder(); Response response = new Response(); if(!userMap.get(nickname).getJoinedChannel().contains(channelName)) { System.err.println("- Failed to leave channel. " + nickname + " is not a member of #" + channelName); message.append("* Failed to leave.\n* You are not a member of #" + channelName); response.putStatus(false); } else { userMap.get(nickname).getJoinedChannel().remove(channelName); response.putStatus(true); message.append("* You are no longer a member of #" + channelName); } response.setMessage(message.toString()); return response.toString(); } public static String logout(String nickname) { System.out.println("- " + nickname + " requested to logout"); userMap.remove(nickname); Response response = new Response(); response.putStatus(true); response.setMessage("* " + nickname + " have been logged out"); return response.toString(); } public static String exit(String nickname) { return logout(nickname); } public static String sendMessage(String nickname, String channelName, String message) { System.out.println("- " + nickname + " sends a message to #" + channelName); StringBuilder returnedMessage = new StringBuilder(); Response response = new Response(); List<String> userChannelList = userMap.get(nickname).getJoinedChannel(); if(!userChannelList.contains(channelName)) { System.err.println("- Failed to send " + nickname + " message to #" + channelName + ". User is not a member of the channel."); returnedMessage.append("* You are not a member of #" + channelName); response.putStatus(false); } else { try { Message msg = new Message(nickname, message); distributeMessage(msg, channelName); } catch (IOException e) { e.printStackTrace(); response.putStatus(false); response.setMessage("* Server Encountered An Error On Publishing the Message"); return response.toString(); } response.putStatus(true); } response.setMessage(returnedMessage.toString()); return response.toString(); } public static String broadcastMessage(String nickname, String message) { System.out.println("- " + nickname + " broadcasts a message"); StringBuilder returnedMessage = new StringBuilder(); Response response = new Response(); List<String> userChannelList = userMap.get(nickname).getJoinedChannel(); if(userChannelList.size()==0) { System.err.println("- Failed to send " + nickname + " message. No channel found."); returnedMessage.append("* Failed to send the message\n* You haven't join any channel yet"); response.putStatus(false); } else { try { Message msg = new Message(nickname, message); distributeMessage(msg, userChannelList); } catch (IOException e) { e.printStackTrace(); response.putStatus(false); response.setMessage("* Server Encountered An Error On Publishing the Message"); return response.toString(); } response.putStatus(true); } response.setMessage(returnedMessage.toString()); return response.toString(); } public static void distributeMessage(Message message, List<String> userChannelList) throws IOException { for(String channelName:userChannelList) { distributeMessage(message, channelName); } } public static void distributeMessage(Message message, String channelName) throws IOException { String enrichedMessage = "@" + channelName + " " + message.getSender()+ ": " + message.getText(); sendMessageToTopic(enrichedMessage, channelName); } }
mit
asakasa/BBLink
BBLink/src/jp/ac/kansai_u/kutc/BBLink/ImageUtils.java
6700
package jp.ac.kansai_u.kutc.BBLink; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.media.ExifInterface; import android.net.Uri; import android.util.Log; import android.view.Gravity; import android.widget.Toast; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; /** * 画像関連の処理を纏めたもの * * @author akasaka */ public class ImageUtils{ static private final String TAG = ImageUtils.class.getSimpleName(); static public Bitmap loadBitmapFromFileName(Context context, String fileName){ FileInputStream fis = null; Bitmap bitmap = null; try{ // 画像ファイル名からストリームを作成する fis = context.openFileInput(fileName + ".png"); bitmap = BitmapFactory.decodeStream(fis); }catch(FileNotFoundException e){ // ファイルが存在しない場合,初期画像を表示する bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.init_img); }finally{ if(fis != null) try{ fis.close(); }catch(IOException e){ Log.d(TAG, "ストリームの解放に失敗しました"); } } return bitmap; } /** * ギャラリーで選択した画像から縮小したBitmap画像を作成する * * @param uri ギャラリーインテントから取得したURI * @return bmp Bitmap画像 */ static public Bitmap createBmpImageFromUri(Context context, Uri uri){ // 最終的にリサイズしたい幅と高さを指定 // final int SCALE_WIDTH = img.getWidth(); // final int SCALE_HEIGHT = img.getHeight(); // TODO: 変更の可能性大 final int SCALE_WIDTH = 300; final int SCALE_HEIGHT = 700; InputStream is = null; // 画像オプションを設定するインスタンスを生成 BitmapFactory.Options opt = new BitmapFactory.Options(); // 画像のサイズ情報を読み込み,縮小率(inSampleSize)を決定する { // true: メモリ上に画像サイズの情報だけ読み込む opt.inJustDecodeBounds = true; try{ is = context.getContentResolver().openInputStream(uri); BitmapFactory.decodeStream(is, null, opt); }catch(FileNotFoundException e){ Toast.makeText(context, "ファイルが見つかりません", Toast.LENGTH_SHORT).show(); }finally{ if(is != null) try{ is.close(); }catch(IOException e){ Log.e(TAG, "ストリームのクローズに失敗しました"); } } // スケールする値を決める int sw = opt.outWidth / SCALE_WIDTH; // opt.outWidth: 画像の幅 int sh = opt.outHeight / SCALE_HEIGHT; // opt.outHeight: 画像の高さ // 縮小するサイズを指定 // 2のべき乗を指定する(べき乗でない場合は丸められる) // 2: 1/2, 4: 1/4, ... opt.inSampleSize = Math.max(sw, sh); // false: メモリ上に画像を読み込む opt.inJustDecodeBounds = false; } // 画像をメモリ上に展開する Bitmap bmp = null; try{ is = context.getContentResolver().openInputStream(uri); bmp = BitmapFactory.decodeStream(is, null, opt); }catch(FileNotFoundException e){ Toast.makeText(context, "ファイルが見つかりません", Toast.LENGTH_SHORT).show(); }finally{ if(is != null) try{ is.close(); }catch(IOException e){ Log.e(TAG, "ストリームのクローズに失敗しました"); } } if(bmp == null){ // 画像の取得に失敗した場合 Toast toast = Toast.makeText(context, "画像の読み込みに失敗しました", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); return null; } int bmpWidth = bmp.getWidth(); int bmpHeight = bmp.getHeight(); // 縮小したいサイズ/画像サイズ = 縮小率 float scale = Math.min((float)SCALE_WIDTH / bmpWidth, (float)SCALE_HEIGHT / bmpHeight); Matrix matrix = new Matrix(); // 画像の表示角度を変更 matrix.preRotate(getAngleFromExif(PathUtils.getPath(context, uri))); // 画像のサイズを指定 matrix.postScale(scale, scale); // 画像の作成 try{ bmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true); }catch(OutOfMemoryError error){ // メモリエラーが出た場合,ガベージコレクションを走らせてトライ java.lang.System.gc(); bmp = Bitmap.createBitmap(bmp, 0, 0, bmpWidth, bmpHeight, matrix, true); } return bmp; } /** * 画像ファイルのEXIF情報から角度を取得する * * @param path 画像ファイルのパス * @return angle 角度(0, 90, 180, 270) */ static public int getAngleFromExif(String path){ if(path == null) return 0; ExifInterface exifInterface; try{ // 画像のパスからEXIF情報を弄るためのオブジェクトを生成 exifInterface = new ExifInterface(path); }catch(IOException e){ Log.e(TAG, "CANNOT INSTANCE EXIFINTERFACE"); return 0; } // 画像の表示角度の取得 int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL); // 画像の表示角度を修正するための変数(angle)の宣言 int angle = 0; if(orientation == ExifInterface.ORIENTATION_ROTATE_90) // 表示角度が90度の場合 angle = 90; else if(orientation == ExifInterface.ORIENTATION_ROTATE_180) // 表示角度が180度の場合 angle = 180; else if(orientation == ExifInterface.ORIENTATION_ROTATE_270) // 表示角度が270度の場合 angle = 270; return angle; } }
mit
Samulus/neovib
src/input/Input.java
3897
/* Input.java ---------- The Input module is responsible for polling the user input and detecting which keys are being held, it only allows users to repeatedly trigger at whatever VibConstant.MIN_DELAY is set at. I included the depress and isDown methods for the Game module so that it would have low latency access to the keyboard so that it could perform more reliable beat detection without relying on the events traveling through the system fast enough. */ package input; import constants.*; import processing.core.PConstants; import clock.Clock; import event.EQ; import event.VibEvent; public class Input { private static Clock time; private static double lastTime; private static boolean[] pressed; private static boolean held; public static void Init() { pressed = new boolean[VibEvent.INPUT_LENGTH.getCode()]; time = new Clock(); lastTime = time.elapsedTime(); } public static void poll() { if (time == null) { System.err.println("Input.java: Call Input.Init() first!"); throw new RuntimeException(); } if (held) { double now = time.elapsedTime(); if (now - lastTime < VibConstant.MIN_DELAY) return; lastTime = now; } if (!held) return; /* avoid locking up system */ /* General Traversal */ if (pressed[VibEvent.INPUT_DOWN.getCode()]) EQ.enqueue(VibEvent.INPUT_DOWN); if (pressed[VibEvent.INPUT_UP.getCode()]) EQ.enqueue(VibEvent.INPUT_UP); if (pressed[VibEvent.INPUT_LEFT.getCode()]) EQ.enqueue(VibEvent.INPUT_LEFT); if (pressed[VibEvent.INPUT_RIGHT.getCode()]) EQ.enqueue(VibEvent.INPUT_RIGHT); if (pressed[VibEvent.INPUT_ACCEPT.getCode()]) EQ.enqueue(VibEvent.INPUT_ACCEPT); if (pressed[VibEvent.INPUT_CANCEL.getCode()]) EQ.enqueue(VibEvent.INPUT_CANCEL); if (pressed[VibEvent.INPUT_MARK_DIR.getCode()]) EQ.enqueue(VibEvent.INPUT_MARK_DIR); if (pressed[VibEvent.INPUT_PREVIOUS.getCode()]) EQ.enqueue(VibEvent.INPUT_PREVIOUS); } public static void keyAction(char key, boolean isPress) { held = isPress; // @formatter:off switch (key) { case 'k': case PConstants.UP: pressed[VibEvent.INPUT_UP.getCode()] = isPress; break; case 'j': case PConstants.DOWN: pressed[VibEvent.INPUT_DOWN.getCode()] = isPress; break; case 'h': case PConstants.LEFT: pressed[VibEvent.INPUT_LEFT.getCode()] = isPress; break; case 'l': case PConstants.RIGHT: pressed[VibEvent.INPUT_RIGHT.getCode()] = isPress; break; case 'm': pressed[VibEvent.INPUT_MARK_DIR.getCode()] = isPress; break; case 'q': pressed[VibEvent.INPUT_CANCEL.getCode()] = isPress; break; case PConstants.ENTER: case PConstants.RETURN: pressed[VibEvent.INPUT_ACCEPT.getCode()] = isPress; break; case PConstants.BACKSPACE: pressed[VibEvent.INPUT_PREVIOUS.getCode()] = isPress; break; case 'a': pressed[VibEvent.INPUT_DODGE_CROSS.getCode()] = isPress; break; case 's': pressed[VibEvent.INPUT_DODGE_CIRCLE.getCode()] = isPress; break; case 'd': pressed[VibEvent.INPUT_DODGE_SQUARE.getCode()] = isPress; break; case 'f': pressed[VibEvent.INPUT_DODGE_TRIANGLE.getCode()] = isPress; break; } // @formatter:on } public static void depress(VibEvent check) { try { pressed[check.getCode()] = false; } catch (Exception e) { System.err.printf("Input.java: %s isn't a valid key\n", check); e.printStackTrace(); } } public static boolean isDown(VibEvent check) { try { return pressed[check.getCode()]; } catch (Exception e) { System.err.printf("Input.java: %s isn't a valid key\n", check); e.printStackTrace(); } return false; } }
mit
ryoa912/java_training
src/jpl/ch14/ex03/MyThread.java
783
//Copyright © 2017 Ryoh Aruga, All Rights Reserved. package jpl.ch14.ex03; public class MyThread { public static int addNum1 = 100; public static int addNum2 = 200; public static int delayTime1 = 300; public static int delayTime2 = 400; public MyThread(Number obj, int addNum, int delayTime) { Runnable service = new Runnable() { public void run() { for (;;) { obj.addNum(addNum); System.out.println(obj.getNum()); try { Thread.sleep(delayTime); } catch (InterruptedException e) { e.printStackTrace(); return; } } } }; new Thread(service).start(); } public static void main(String[] args) { Number obj = new Number(); new MyThread(obj, addNum1, delayTime1); new MyThread(obj, addNum2, delayTime2); } }
mit
zhugejunwei/Algorithms-in-Java-Swift-CPP
CreateMirrorBinaryTree/TreeNode.java
194
package io.kongming; /** * Created by zhugejunwei on 12/4/16. */ public class TreeNode { int val; TreeNode left, right; public TreeNode(int val) { this.val = val; } }
mit
Wrywulf/Mortar-architect
architect/src/main/java/architect/Dispatcher.java
10716
package architect; import java.util.ArrayList; import java.util.List; import mortar.MortarScope; /** * Dispatch consequences of history manipulation * * @author Lukasz Piliszczuk - lukasz.pili@gmail.com */ class Dispatcher { private final Navigator navigator; private final List<History.Entry> entries = new ArrayList<>(); private boolean dispatching; private boolean killed; private boolean active; Dispatcher(Navigator navigator) { this.navigator = navigator; } /** * Stop the dispatcher forever * Its only salvation lies in garbage collection now */ void kill() { Preconditions.checkArgument(!killed, "Did you try to kill the dispatcher twice? Not cool brah"); killed = true; } /** * Attach the dispatcher on new context */ void activate() { Preconditions.checkArgument(!active, "Dispatcher already active"); Preconditions.checkArgument(entries.isEmpty(), "Dispatcher stack must be empty"); Preconditions.checkNotNull(navigator.getScope(), "Navigator scope cannot be null"); // clean dead entries that may had happen on history while dispatcher // was inactive List<History.Entry> dead = navigator.history.removeAllDead(); if (dead != null && !dead.isEmpty()) { History.Entry entry; for (int i = 0; i < dead.size(); i++) { entry = dead.get(i); Logger.d("Dead entry: %s", entry.scopeName); MortarScope scope = navigator.getScope().findChild(entry.scopeName); if (scope != null) { Logger.d("Clean and destroy scope %s", entry.scopeName); scope.destroy(); } } } History.Entry entry = navigator.history.getLastAlive(); Preconditions.checkNotNull(entry, "No alive entry"); Logger.d("Last alive entry: %s", entry.scopeName); MortarScope entryScope = navigator.getScope().findChild(entry.scopeName); if (entryScope == null) { entryScope = StackFactory.createScope(navigator.getScope(), entry.path, entry.scopeName); } List<Dispatch> dispatches = null; if (entry.isModal()) { // entry modal, get previous displayed List<History.Entry> previous = navigator.history.getPreviousOfModal(entry); if (previous != null && !previous.isEmpty()) { dispatches = new ArrayList<>(previous.size() + 1); History.Entry prevEntry; MortarScope scope; for (int i = previous.size() - 1; i >= 0; i--) { prevEntry = previous.get(i); Logger.d("Get previous entry: %s", prevEntry.scopeName); scope = navigator.getScope().findChild(prevEntry.scopeName); if (scope == null) { scope = StackFactory.createScope(navigator.getScope(), prevEntry.path, prevEntry.scopeName); } dispatches.add(new Dispatch(prevEntry, scope)); } } } if (dispatches == null) { dispatches = new ArrayList<>(1); } dispatches.add(new Dispatch(entry, entryScope)); navigator.presenter.restore(dispatches); active = true; } void desactivate() { Preconditions.checkArgument(active, "Dispatcher already desactivated"); active = false; entries.clear(); } void dispatch(List<History.Entry> e) { if (!active) return; entries.addAll(e); startDispatch(); } void dispatch(History.Entry entry) { if (!active) return; entries.add(entry); startDispatch(); } void startDispatch() { Preconditions.checkArgument(active, "Dispatcher must be active"); if (killed || dispatching || !navigator.presenter.isActive() || entries.isEmpty()) return; dispatching = true; Preconditions.checkNotNull(navigator.getScope(), "Dispatcher navigator scope cannot be null"); Preconditions.checkArgument(!navigator.history.isEmpty(), "Cannot dispatch on empty history"); Preconditions.checkArgument(!entries.isEmpty(), "Cannot dispatch on empty stack"); final History.Entry entry = entries.remove(0); Preconditions.checkArgument(navigator.history.existInHistory(entry), "Entry does not exist in history"); Logger.d("Get entry with scope: %s", entry.scopeName); ViewTransitionDirection direction; History.Entry nextEntry; final History.Entry previousEntry; if (entry.dead) { direction = ViewTransitionDirection.BACKWARD; previousEntry = entry; nextEntry = navigator.history.getLeftOf(entry); } else { direction = ViewTransitionDirection.FORWARD; nextEntry = entry; previousEntry = navigator.history.getLeftOf(entry); } Preconditions.checkNotNull(nextEntry, "Next entry cannot be null"); Preconditions.checkNotNull(previousEntry, "Previous entry cannot be null"); Preconditions.checkNull(nextEntry.receivedResult, "Next entry cannot have already a result"); if (!entries.isEmpty()) { boolean fastForwarded = fastForward(entry, previousEntry); if (fastForwarded) { return; } } if (entry.dead && previousEntry.returnsResult != null) { nextEntry.receivedResult = previousEntry.returnsResult; previousEntry.returnsResult = null; } present(nextEntry, previousEntry, direction); } private void present(History.Entry nextEntry, final History.Entry previousEntry, ViewTransitionDirection direction) { MortarScope currentScope = navigator.presenter.getCurrentScope(); Preconditions.checkNotNull(currentScope, "Current scope cannot be null"); Logger.d("Current container scope is: %s", currentScope.getName()); navigator.presenter.present(createDispatch(nextEntry), previousEntry, direction, new Callback() { @Override public void onComplete() { if (previousEntry.dead) { destroyDead(previousEntry); } endDispatch(); startDispatch(); } }); } private boolean fastForward(History.Entry entry, History.Entry previousEntry) { boolean fastForwarded = false; List<Dispatch> modals = null; History.Entry nextDispatch = null; while (!entries.isEmpty() && (nextDispatch = entries.get(0)) != null) { Logger.d("Get next dispatch: %s", nextDispatch.scopeName); if (entry.isModal()) { // fast forward for modals works only with other modals // it will animate all the fast-forwarded modals at once (in parallel) if (!nextDispatch.isModal()) { break; } if (modals == null) { modals = new ArrayList<>(); modals.add(createDispatch(entry)); } fastForwarded = true; entries.remove(0); modals.add(createDispatch(nextDispatch)); Logger.d("Modal fast forward to next entry: %s", nextDispatch.scopeName); continue; } // non-modal fast-forward if (nextDispatch.isModal()) { // fast forward only on non-modals break; } fastForwarded = true; entries.remove(0); if (nextDispatch.dead) { History.Entry toDestroy = nextDispatch; nextDispatch = navigator.history.getLeftOf(nextDispatch); destroyDead(toDestroy); } Logger.d("Fast forward to next entry: %s", nextDispatch.scopeName); } if (!fastForwarded) { return false; } if (entry.isModal()) { final List<Dispatch> finalModals = modals; navigator.presenter.presentModals(modals, new Callback() { @Override public void onComplete() { Dispatch dispatch; for (int i = 0; i < finalModals.size(); i++) { dispatch = finalModals.get(i); if (dispatch.entry.dead) { destroyDead(dispatch.entry); } } endDispatch(); startDispatch(); } }); } else { ViewTransitionDirection direction; if (nextDispatch.direction != null) { direction = nextDispatch.direction; nextDispatch.direction = null; } else { direction = previousEntry.dead ? ViewTransitionDirection.BACKWARD : ViewTransitionDirection.FORWARD; } present(nextDispatch, previousEntry, direction); } return true; } private Dispatch createDispatch(History.Entry entry) { MortarScope nextScope = navigator.getScope().findChild(entry.scopeName); if (nextScope == null) { nextScope = StackFactory.createScope(navigator.getScope(), entry.path, entry.scopeName); } return new Dispatch(entry, nextScope); } private void destroyDead(History.Entry entry) { Logger.d("Remove dead entry: %s", entry.scopeName); navigator.history.remove(entry); if (navigator.getScope() != null) { MortarScope scope = navigator.getScope().findChild(entry.scopeName); if (scope != null) { Logger.d("Destroy scope %s", entry.scopeName); scope.destroy(); } } } private void endDispatch() { Preconditions.checkArgument(dispatching, "Calling endDispatch while not dispatching"); dispatching = false; } interface Callback { void onComplete(); } // enum Direction { // FORWARD, BACKWARD // } static class Dispatch { History.Entry entry; MortarScope scope; public Dispatch(History.Entry entry, MortarScope scope) { Preconditions.checkArgument(entry.scopeName.equals(scope.getName()), "Dispatch entry scope name does not match"); this.entry = entry; this.scope = scope; } } }
mit
opensourceconsultant/java-design-patterns
singleton/src/main/java/com/saradhi/EnumIvoryTower.java
285
package com.saradhi; /** * * Enum Singleton class. * Effective Java 2nd Edition (Joshua Bloch) p. 18 * */ public enum EnumIvoryTower { INSTANCE; @Override public String toString() { return getDeclaringClass().getCanonicalName() + "@" + hashCode(); } }
mit
Minestack/DoubleChest
src/main/java/io/minestack/doublechest/model/pluginhandler/servertype/repository/mongo/MongoServerTypeRepository.java
5155
package io.minestack.doublechest.model.pluginhandler.servertype.repository.mongo; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.DBCursor; import com.mongodb.DBObject; import io.minestack.doublechest.databases.mongo.MongoDatabase; import io.minestack.doublechest.databases.mongo.MongoModelRepository; import io.minestack.doublechest.model.plugin.PluginHolderPlugin; import io.minestack.doublechest.model.pluginhandler.servertype.ServerType; import io.minestack.doublechest.model.world.ServerTypeWorld; import org.bson.types.ObjectId; import sun.reflect.generics.reflectiveObjects.NotImplementedException; import java.util.ArrayList; import java.util.Date; import java.util.List; public class MongoServerTypeRepository extends MongoModelRepository<ServerType> { public MongoServerTypeRepository(MongoDatabase database) { super(database); } @Override public List<ServerType> getModels() { List<ServerType> serverTypes = new ArrayList<>(); DBCursor serverTypeCursor = getDatabase().findMany("servertypes"); while (serverTypeCursor.hasNext()) { serverTypes.add(getModel((ObjectId) serverTypeCursor.next().get("_id"))); } return serverTypes; } @Override public ServerType getModel(ObjectId id) { DBObject dbServerType = getDatabase().findOne("servertypes", new BasicDBObject("_id", id)); if (dbServerType == null) { return null; } ServerType serverType = new ServerType((ObjectId) dbServerType.get("_id"), (Date) dbServerType.get("created_at")); serverType.setUpdated_at((Date) dbServerType.get("updated_at")); serverType.setName((String) dbServerType.get("name")); serverType.setDescription((String) dbServerType.get("description")); serverType.setPlayers(Integer.parseInt((String) dbServerType.get("players"))); serverType.setRam(Integer.parseInt((String) dbServerType.get("ram"))); if (dbServerType.containsField("plugins")) { BasicDBList pluginList = (BasicDBList) dbServerType.get("plugins"); for (Object objPluginHolderPlugin : pluginList) { DBObject dbPluginHolderPlugin = (DBObject) objPluginHolderPlugin; PluginHolderPlugin pluginHolderPlugin = new PluginHolderPlugin((ObjectId) dbPluginHolderPlugin.get("_id"), (Date) dbPluginHolderPlugin.get("created_at")); pluginHolderPlugin.setUpdated_at((Date) dbPluginHolderPlugin.get("updated_at")); pluginHolderPlugin.setPlugin(getDatabase().getPluginRepository().getModel(new ObjectId((String) dbPluginHolderPlugin.get("plugin_id")))); if (dbPluginHolderPlugin.containsField("pluginversion_id") == true && dbPluginHolderPlugin.get("pluginversion_id") != null) { pluginHolderPlugin.setVersion(pluginHolderPlugin.getPlugin().getVersions().get(new ObjectId((String) dbPluginHolderPlugin.get("pluginversion_id")))); } if (dbPluginHolderPlugin.containsField("pluginconfig_id") == true && dbPluginHolderPlugin.get("pluginconfig_id") != null) { pluginHolderPlugin.setConfig(pluginHolderPlugin.getPlugin().getConfigs().get(new ObjectId((String) dbPluginHolderPlugin.get("pluginconfig_id")))); } serverType.getPlugins().add(pluginHolderPlugin); } } if (dbServerType.containsField("worlds")) { BasicDBList worldList = (BasicDBList) dbServerType.get("worlds"); for (Object objServerTypeWorld : worldList) { DBObject dbServerTypeWorld = (DBObject) objServerTypeWorld; ServerTypeWorld serverTypeWorld = new ServerTypeWorld((ObjectId) dbServerTypeWorld.get("_id"), (Date) dbServerTypeWorld.get("created_at")); serverTypeWorld.setWorld(getDatabase().getWorldRepository().getModel(new ObjectId((String) dbServerTypeWorld.get("world_id")))); if (dbServerType.containsField("worldversion_id") == true) { serverTypeWorld.setVersion(serverTypeWorld.getWorld().getVersions().get(new ObjectId((String) dbServerTypeWorld.get("worldversion_id")))); } serverTypeWorld.setDefaultWorld((boolean) dbServerTypeWorld.get("defaultWorld")); serverType.getWorlds().add(serverTypeWorld); } } return serverType; } public ServerType getModel(String typeName) { DBObject query = new BasicDBObject("name", typeName); DBObject dbServerType = getDatabase().findOne("servertypes", query); if (dbServerType == null) { return null; } return getModel((ObjectId) dbServerType.get("_id")); } @Override public void saveModel(ServerType model) { throw new NotImplementedException(); } @Override public void insertModel(ServerType model) { throw new NotImplementedException(); } @Override public void removeModel(ServerType model) { throw new NotImplementedException(); } }
mit
frc-862/SummerSirius
src/org/usfirst/frc862/jlib/math/interp/Interpolator.java
622
package org.usfirst.frc862.jlib.math.interp; public interface Interpolator { /** * Interpolate a value * * @param xLow Low source value, must be less than or equal to xHigh * @param xHigh High source value, must be greater than or equal to xLow * @param xActual Actual source value, should be between xLow and xHigh * @param yLow Low result value, must be less than or equal to yHigh * @param yHigh High result value, must be greater than or equal to yLow * @return Estimated result value for xActual */ double interpolate(double xLow, double xHigh, double xActual, double yLow, double yHigh); }
mit
expositionrabbit/Sbahjsic-runtime
src/sbahjsic/runtime/type/SType.java
5121
package sbahjsic.runtime.type; import java.util.HashMap; import java.util.Map; import sbahjsic.runtime.Method; import sbahjsic.runtime.Operator; import sbahjsic.runtime.SValue; import sbahjsic.runtime.Type; import sbahjsic.util.FuncUtils; /** A Sbahjsic value that contains a Sbahjsic type.*/ public final class SType extends AbstractValue { private final Type type; public SType(Type type) { this.type = type; } @Override public Type getType() { return STypeType.INSTANCE; } @Override public int asInt() { return 0; } @Override public String asString() { return type.getName() + "_type"; } @Override public Type asType() { return type; } @Override public Map<String, SValue> asMap() { Map<String, SValue> map = new HashMap<>(); for(String key : type.getFields()) { map.put(key, SNull.NULL); } for(String method : type.getDefinedOperators()) { map.put(method, new SFunc((context, args) -> { Method m = type.getMethod(method); SValue called = args[0]; SValue[] newArgs = new SValue[args.length-1]; System.arraycopy(args, 1, newArgs, 0, newArgs.length); return m.apply(context, called, newArgs); })); } for(String op : type.getDefinedOperators()) { map.put(op, new SFunc((context, args) -> { Operator o = type.getOperator(op); return o.apply(context, args); })); } return map; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof SType)) { return false; } SType other = (SType) obj; if (type == null) { if (other.type != null) { return false; } } else if (!type.equals(other.type)) { return false; } return true; } /** The type of STypes.*/ public final static class STypeType extends Type { public final static STypeType INSTANCE = new STypeType(); { addBiOperator("==", (con, a1, a2) -> { return a1.asType().equals(a2.asType()) ? SBool.TRUE : SBool.FALSE; }); addBiOperator("!=", (con, a1, a2) -> { return a1.asType().equals(a2.asType()) ? SBool.FALSE : SBool.TRUE; }); addMethod("is_sub", Method.with1Arg((con, called, arg) -> { return called.asType().getSupertypes().contains(arg.asType()) ? SBool.TRUE : SBool.FALSE; })); addMethod("methods", Method.with0Args((con, called) -> { return new SArray(called.asType().getMethods() .stream().map(SString::new).toArray(SValue[]::new)); })); addMethod("fields", Method.with0Args((con, called) -> { return new SArray(called.asType().getFields() .stream().map(SString::new).toArray(SValue[]::new)); })); addMethod("operators", Method.with0Args((con, called) -> { return new SArray(called.asType().getDefinedOperators() .stream().map(SString::new).toArray(SValue[]::new)); })); addMethod("extend", Method.with1Arg((con, called, arg) -> { called.asType().addSupertype(arg.asType()); return SVoid.VOID; })); addMethod("help", Method.with0Args((con, called) -> { StringBuilder str = new StringBuilder(); Type type = called.asType(); str.append(type.getName() + " : " + type.getSupertypes() + '\n'); str.append("OPERATORS: "); for(String op : type.getDefinedOperators()) { str.append(op + " "); } str.append('\n'); str.append("FIELDS: "); for(String field : type.getFields()) { str.append(field + " "); } str.append('\n'); str.append("METHODS: "); for(String method : type.getMethods()) { str.append(method + " "); } return new SString(str.toString()); })); addBiOperator("::", (con, a1, a2) -> { Type type = a1.asType(); String string = a2.asAddress(); if(type.getMethods().contains(string)) { Method method = type.getMethod(string); return new SFunc((context, args) -> { SValue[] methodArgs = new SValue[args.length-1]; System.arraycopy(args, 1, methodArgs, 0, methodArgs.length); return method.apply(context, args[0], methodArgs); }); } if(type.getDefinedOperators().contains(string)) { Operator op = type.getOperator(string); return new SFunc((context, args) -> { return op.apply(context, args); }); } if(type.getFields().contains(string)) { return new SFunc((context, args) -> { FuncUtils.requireArguments(1, args.length); return args[0].getType().getOperator("$").apply(context, args[0], new SString(string)); }); } return SUndefined.UNDEFINED; }); addMethod("new", Method.with0Args((con, called) -> { return new SStruct(called.refersTo().asType()); })); } private STypeType() {} @Override public String getName() { return "type"; } @Override public SValue cast(SValue object) { return new SType(object.getType()); } } }
mit
gustavopuga/comente-sobre
src/test/java/br/com/talkabout/domain/model/DiscussionTest.java
941
package br.com.talkabout.domain.model; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; public class DiscussionTest { @Test public void testEmptyDiscussionWhenThereIsNotMessages() { Discussion conversation = new Discussion(); Assert.assertTrue(conversation.isEmpty()); } @Test public void testEmptyConversationWhenMessagesListIsEmpty() { Discussion conversation = new Discussion(); conversation.setMessages(new ArrayList<Message>()); Assert.assertEquals(conversation.isEmpty(), conversation.getMessages().isEmpty()); } @Test public void testNotEmptyConversationWhenMessagesListNotIsEmpty() { List<Message> messages = new ArrayList<Message>(); messages.add(new Message()); Discussion conversation = new Discussion(); conversation.setMessages(messages); Assert.assertEquals(conversation.isEmpty(), conversation.getMessages().isEmpty()); } }
mit
thjanssen/HibernateTips
AssociationsWithAttributes/src/main/java/org/thoughts/on/java/model/BookPublisherId.java
1361
package org.thoughts.on.java.model; import java.io.Serializable; import java.util.Objects; import javax.persistence.Embeddable; @Embeddable public class BookPublisherId implements Serializable { private static final long serialVersionUID = -3287715633608041039L; private Long bookId; private Long publisherId; public BookPublisherId() { } public BookPublisherId(Long bookId, Long publisherId) { this.bookId = bookId; this.publisherId = publisherId; } public Long getBookId() { return bookId; } public Long getPublisherId() { return publisherId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bookId == null) ? 0 : bookId.hashCode()); result = prime * result + ((publisherId == null) ? 0 : publisherId.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; BookPublisherId other = (BookPublisherId) obj; return Objects.equals(bookId, other.bookId) && Objects.equals(publisherId, other.getPublisherId()); } @Override public String toString() { return "BookPublisherId [bookId=" + bookId + ", publisherId=" + publisherId + "]"; } }
mit
fmarchioni/mastertheboss
javaee7-hol-jdg/src/main/java/infinispan/Team.java
1809
/* * JBoss, Home of Professional Open Source * Copyright 2013, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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 infinispan; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * @author Martin Gencur */ public class Team implements Serializable { private static final long serialVersionUID = -181403229462007401L; private String teamName; private List<String> players; public Team(String teamName) { this.teamName = teamName; players = new ArrayList<String>(); } public void addPlayer(String name) { players.add(name); } public void removePlayer(String name) { players.remove(name); } public List<String> getPlayers() { return players; } public String getName() { return teamName; } @Override public String toString() { StringBuilder b = new StringBuilder("=== Team: " + teamName + " ===\n"); b.append("Players:\n"); for (String player : players) { b.append("- " + player + "\n"); } return b.toString(); } }
mit
Palehors68/Botnak
src/main/java/util/misc/Donation.java
2060
package util.misc; import java.util.Date; /** * Created by Nick on 11/22/2014. */ public class Donation implements Comparable<Donation> { private double amount; private String donationID, note, fromWho; private Date received; public Donation(String ID, String fromWho, String note, double amount, Date received) { this.amount = amount; this.donationID = ID; this.note = note; this.fromWho = fromWho; this.received = received; } public double getAmount() { return amount; } public Date getDateReceived() { return received; } public String getDonationID() { return donationID; } public String getFromWhom() { return fromWho; } public String getNote() { return note; } /** * We sort in descending order based on date. The latest donation should * match the one that DonationCheck checks every 5 seconds. * * @param o The other donation. * @return Negative if this donation is older, 0 if it's equal, and positive if * this donation is more recent than Donation o. */ @Override public int compareTo(Donation o) { if (this.getDateReceived().after(o.getDateReceived())) { //this donation is newer, put the other behind return -1; } if (o.getDateReceived().equals(this.getDateReceived())) {//two donations at the exact same time? //just incase return 0; } else {//the other donation is more recent return 1; } } @Override public boolean equals(Object obj) { return (obj instanceof Donation && ((Donation) obj).getAmount() == this.getAmount() && ((Donation) obj).getDateReceived().equals(this.getDateReceived()) && ((Donation) obj).getFromWhom().equals(this.getFromWhom()) && ((Donation) obj).getNote().equals(this.getNote()) && ((Donation) obj).getDonationID().equals(this.getDonationID())); } }
mit
pandu1990/AndroidRemoteServer
src/AppFrame.java
2504
import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; import javax.swing.JFrame; public class AppFrame extends JFrame { private static String title = "Remote Mouse & Keyboard Server (Beta)"; private String[] lines; private static final long serialVersionUID = 4648172894076113183L; public AppFrame() { super(title); initializeVars(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocation(100, 100); setSize(410, 300); setBackground(Color.GRAY); setDefaultLookAndFeelDecorated(true); setResizable(false); setVisible(true); } private String getIp() { String ip = null; try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); StringBuilder buff = new StringBuilder(); while(networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); while(inetAddresses.hasMoreElements()) { InetAddress inetAddress = inetAddresses.nextElement(); //if the address is not a loopback address and is an IPv4 if(!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { buff.append(inetAddress.getHostAddress() + ", "); } } } //remove the extra , added at the last buff.delete(buff.length()-2, buff.length()); ip = buff.toString(); } catch (Exception e) { ip = "Error determining IP address"; } return ip; } private void initializeVars() { lines = new String[9]; lines[0] = "The server application is now running"; String ip = getIp(); lines[1] = " "; lines[2] = "Your IP : " + ip; lines[3] = " "; lines[4] = "Enter this IP on the start screen of the"; lines[5] = "Remote Mouse & Keyboard application on your phone to begin."; lines[6] = " "; lines[7] = " "; lines[8] = "Copyright 2013 Pandurang Kamath"; } @Override public void paint(Graphics g) { super.paint(g); Font fontHeader = new Font(Font.SANS_SERIF, Font.PLAIN, 20); Font fontNormal = new Font(Font.SERIF, Font.PLAIN, 14); g.setFont(fontHeader); g.drawString(title, 20, 50); g.setFont(fontNormal); for(int i = 0, y = 80; i < lines.length; i++, y+=20){ g.drawString(lines[i], 20, y); } } }
mit
TheoKah/CarrotShop
src/main/java/com/carrot/carrotshop/shop/Toggle.java
5716
package com.carrot.carrotshop.shop; import java.math.BigDecimal; import java.util.List; import java.util.Optional; import java.util.Stack; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; import org.spongepowered.api.Sponge; import org.spongepowered.api.block.BlockState; import org.spongepowered.api.block.BlockTypes; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.scheduler.Task; import org.spongepowered.api.service.economy.account.UniqueAccount; import org.spongepowered.api.service.economy.transaction.ResultType; import org.spongepowered.api.service.economy.transaction.TransactionResult; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.world.Location; import org.spongepowered.api.world.World; import com.carrot.carrotshop.CarrotShop; import com.carrot.carrotshop.Lang; import com.carrot.carrotshop.ShopConfig; import com.carrot.carrotshop.ShopsData; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class Toggle extends Shop { @Setting private Location<World> lever; @Setting private float price; static private String type = "Toggle"; public Toggle() { } public Toggle(Player player, Location<World> sign) throws ExceptionInInitializerError { super(sign); if (!player.hasPermission("carrotshop.create.device")) throw new ExceptionInInitializerError(Lang.SHOP_PERM.replace("%type%", type)); Stack<Location<World>> locations = ShopsData.getItemLocations(player); if (locations.isEmpty()) throw new ExceptionInInitializerError(Lang.SHOP_LEVER.replace("%type%", type)); BlockState targetBlock = locations.peek().getBlock(); if (!targetBlock.getType().equals(BlockTypes.LEVER)) throw new ExceptionInInitializerError(Lang.SHOP_LEVER.replace("%type%", type)); lever = locations.peek(); float cost = 0; if (CarrotShop.getEcoService() != null) { price = getPrice(sign); if (price < 0) throw new ExceptionInInitializerError(Lang.SHOP_PRICE); cost = ShopConfig.getNode("cost", type).getFloat(0); if (cost > 0) { UniqueAccount buyerAccount = CarrotShop.getEcoService().getOrCreateAccount(player.getUniqueId()).get(); TransactionResult result = buyerAccount.withdraw(getCurrency(), BigDecimal.valueOf(cost), CarrotShop.getCause()); if (result.getResult() != ResultType.SUCCESS) throw new ExceptionInInitializerError(Lang.SHOP_COST.replace("%type%", type).replace("%cost%", formatPrice(BigDecimal.valueOf(cost)))); } } setOwner(player); ShopsData.clearItemLocations(player); if (cost > 0) player.sendMessage(Text.of(TextColors.DARK_GREEN, Lang.SHOP_DONE_COST.replace("%type%", type).replace("%cost%", formatPrice(BigDecimal.valueOf(cost))))); else player.sendMessage(Text.of(TextColors.DARK_GREEN, Lang.SHOP_DONE.replace("%type%", type))); done(player); info(player); } @Override public List<Location<World>> getLocations() { List<Location<World>> locations = super.getLocations(); locations.add(lever); return locations; } @Override public void info(Player player) { if (CarrotShop.getEcoService() != null) player.sendMessage(Text.of(Lang.SHOP_TOGGLE_HELP.replace("%price%", formatPrice(price)))); else player.sendMessage(Text.of(Lang.SHOP_TOGGLE_HELP_NOECON)); update(); } @Override public boolean trigger(Player player) { String recap = Lang.SHOP_TOGGLE_NOECON; String orecap = Lang.SHOP_DEVICE_OTHER_NOECON; if (CarrotShop.getEcoService() != null) { UniqueAccount buyerAccount = CarrotShop.getEcoService().getOrCreateAccount(player.getUniqueId()).get(); UniqueAccount sellerAccount = CarrotShop.getEcoService().getOrCreateAccount(getOwner()).get(); float tax = ShopConfig.getNode("taxes", type).getFloat(0); TransactionResult accountResult; if (tax > 0) { accountResult = buyerAccount.withdraw(getCurrency(), BigDecimal.valueOf(price), CarrotShop.getCause()); if (accountResult.getResult() == ResultType.SUCCESS) { accountResult = sellerAccount.deposit(getCurrency(), BigDecimal.valueOf(price - price * tax / 100), CarrotShop.getCause()); } } else { accountResult = buyerAccount.transfer(sellerAccount, getCurrency(), BigDecimal.valueOf(price), CarrotShop.getCause()); } if (accountResult.getResult() != ResultType.SUCCESS) { player.sendMessage(Text.of(TextColors.DARK_RED, Lang.SHOP_MONEY)); return false; } recap = Lang.SHOP_TOGGLE.replace("%price%", formatPrice(price)); if (tax > 0) orecap = Lang.SHOP_DEVICE_OTHER_TAX.replace("%tax%", String.valueOf(tax)).replace("%tprice%", formatPrice(price - price * tax / 100)); else orecap = Lang.SHOP_DEVICE_OTHER; orecap = orecap.replace("%price%", formatPrice(price)); } lever.offer(Keys.POWERED, true, CarrotShop.getCause()); Sponge.getScheduler().createTaskBuilder().execute(new Consumer<Task>() { @Override public void accept(Task t) { t.cancel(); lever.offer(Keys.POWERED, false, CarrotShop.getCause()); } }).delay(2, TimeUnit.SECONDS).submit(CarrotShop.getInstance()); player.sendMessage(Text.of(recap)); if (!CarrotShop.noSpam(getOwner())) { Optional<Player> seller = Sponge.getServer().getPlayer(getOwner()); if (seller.isPresent()) seller.get().sendMessage(Text.of(orecap.replace("%player%", player.getName()).replace("%type%", type))); } return true; } }
mit
microsoftgraph/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/WorkbookFunctionsCeiling_MathRequest.java
3028
// Template Source: BaseMethodRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.models.WorkbookFunctionResult; import com.microsoft.graph.models.WorkbookFunctions; import com.microsoft.graph.requests.WorkbookFunctionsCeiling_MathRequest; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.http.HttpMethod; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.models.WorkbookFunctionsCeiling_MathParameterSet; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Workbook Functions Ceiling_Math Request. */ public class WorkbookFunctionsCeiling_MathRequest extends BaseRequest<WorkbookFunctionResult> { /** * The request for this WorkbookFunctionsCeiling_Math * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public WorkbookFunctionsCeiling_MathRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, WorkbookFunctionResult.class); } /** The body for the method */ @Nullable public WorkbookFunctionsCeiling_MathParameterSet body; /** * Invokes the method and returns a future with the result * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<WorkbookFunctionResult> postAsync() { return sendAsync(HttpMethod.POST, body); } /** * Invokes the method and returns the result * @return result of the method invocation * @throws ClientException an exception occurs if there was an error while the request was sent */ @Nullable public WorkbookFunctionResult post() throws ClientException { return send(HttpMethod.POST, body); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public WorkbookFunctionsCeiling_MathRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public WorkbookFunctionsCeiling_MathRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } }
mit