text
stringlengths 10
2.72M
|
|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.webbeans.container;
import org.apache.webbeans.annotation.EmptyAnnotationLiteral;
import org.apache.webbeans.util.AnnotationUtil;
import jakarta.enterprise.inject.spi.AnnotatedType;
import jakarta.enterprise.util.Nonbinding;
import java.lang.annotation.Annotation;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.Comparator;
import java.util.function.Function;
import java.util.stream.Stream;
public final class BeanCacheKey
{
private static final Comparator<Annotation> ANNOTATION_COMPARATOR = new AnnotationComparator();
private final boolean isDelegate;
private final Type type;
private final String path;
private final Annotation qualifier;
private final Annotation[] qualifiers;
private final int hashCode;
private volatile LazyAnnotatedTypes lazyAnnotatedTypes; // only needed for the "main" key
private final Function<Class<?>, AnnotatedType<?>> lazyAtLoader;
public BeanCacheKey(boolean isDelegate, Type type, String path,
Function<Class<?>, AnnotatedType<?>> lazyAtLoader,
Annotation... qualifiers)
{
this.isDelegate = isDelegate;
this.type = type;
this.path = path;
this.lazyAtLoader = lazyAtLoader;
int length = qualifiers != null ? qualifiers.length : 0;
if (length == 0)
{
qualifier = null;
this.qualifiers = null;
}
else if (length == 1)
{
qualifier = qualifiers[0];
this.qualifiers = null;
}
else
{
qualifier = null;
// to save array creations, we only create an array, if we have more than one annotation
this.qualifiers = new Annotation[length];
System.arraycopy(qualifiers, 0, this.qualifiers, 0, length);
Arrays.sort(this.qualifiers, ANNOTATION_COMPARATOR);
}
// this class is directly used in ConcurrentHashMap.get() so simply init the hasCode here
hashCode = computeHashCode();
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
BeanCacheKey cacheKey = (BeanCacheKey) o;
if (!isDelegate == cacheKey.isDelegate)
{
return false;
}
if (!type.equals(cacheKey.type))
{
return false;
}
if (qualifier != null && cacheKey.qualifier != null)
{
ensureQualifierAtAreLoaded();
if (!qualifierEquals(lazyAnnotatedTypes.qualifierAt, qualifier, cacheKey.qualifier))
{
return false;
}
}
if (!qualifierArrayEquals(qualifiers, cacheKey.qualifiers))
{
return false;
}
return path != null ? path.equals(cacheKey.path) : cacheKey.path == null;
}
private void ensureQualifierAtAreLoaded()
{
if (lazyAnnotatedTypes == null)
{
synchronized (this)
{
if (lazyAnnotatedTypes == null)
{
if (qualifier != null)
{
lazyAnnotatedTypes = new LazyAnnotatedTypes(lazyAtLoader.apply(qualifier.annotationType()), null);
}
else
{
lazyAnnotatedTypes = new LazyAnnotatedTypes(null, Stream.of(qualifiers)
.map(Annotation::annotationType)
.map(lazyAtLoader)
.toArray(AnnotatedType[]::new));
}
}
}
}
}
private boolean qualifierArrayEquals(Annotation[] qualifiers1, Annotation[] qualifiers2)
{
if (qualifiers1 == qualifiers2)
{
return true;
}
else if (qualifiers1 == null || qualifiers2 == null)
{
return false;
}
if (qualifiers1.length != qualifiers2.length)
{
return false;
}
ensureQualifierAtAreLoaded();
for (int i = 0; i < qualifiers1.length; i++)
{
Annotation a1 = qualifiers1[i];
Annotation a2 = qualifiers2[i];
if (a1 == null ? a2 != null : !qualifierEquals(lazyAnnotatedTypes.qualifierAts[i], a1, a2))
{
return false;
}
}
return true;
}
@Override
public int hashCode()
{
return hashCode;
}
/**
* We need this method as some weird JVMs return 0 as hashCode for classes.
* In that case we return the hashCode of the String.
*/
private int getTypeHashCode(Type type)
{
int typeHash = type.hashCode();
if (typeHash == 0 && type instanceof Class)
{
return ((Class)type).getName().hashCode();
// the type.toString() is always the same: "java.lang.Class@<hexid>"
// was: return type.toString().hashCode();
}
return typeHash;
}
/**
* Compute the HashCode. This should be called only in the constructor.
*/
private int computeHashCode()
{
int computedHashCode = 31 * getTypeHashCode(type) + (path != null ? path.hashCode() : 0)
+ (isDelegate ? 29 : 0);
if (qualifier != null)
{
computedHashCode = 31 * computedHashCode + getQualifierHashCode(qualifier);
}
if (qualifiers != null)
{
for (int i = 0; i < qualifiers.length; i++)
{
computedHashCode = 31 * computedHashCode + getQualifierHashCode(qualifiers[i]);
}
}
return computedHashCode;
}
/**
* Calculate the hashCode() of a qualifier.
* We do not do any in-depth hashCode down to member hashes
* but only use the hashcode of the AnnotationType itself.
* This is WAY faster and spreads well enough in practice.
* We can do this as we do not need to return a perfectly unique
* result anyway.
*/
private int getQualifierHashCode(Annotation a)
{
return a.annotationType().hashCode();
}
/**
* Implements the equals() method for qualifiers, which ignores {@link Nonbinding} members.
*/
private boolean qualifierEquals(AnnotatedType<?> at, Annotation qualifier1, Annotation qualifier2)
{
if (at == null)
{
return AnnotationUtil.isCdiAnnotationEqual(qualifier1, qualifier2);
}
return AnnotationUtil.isCdiAnnotationEqual(at, qualifier1, qualifier2);
}
/**
* Helper method for calculating the hashCode of an annotation.
*/
private static Object callMethod(Object instance, Method method)
{
try
{
if (!method.isAccessible())
{
method.setAccessible(true);
}
return method.invoke(instance, AnnotationUtil.EMPTY_OBJECT_ARRAY);
}
catch (Exception e)
{
throw new RuntimeException("Exception in method call : " + method.getName(), e);
}
}
/**
* for debugging ...
*/
@Override
public String toString()
{
return "BeanCacheKey{" + "type=" + type + ", path='" + path + '\''
+ ", delegate=" + isDelegate + ", qualifiers="
+ (qualifiers == null ? qualifier : Arrays.asList(qualifiers)) + ", hashCode=" + hashCode + '}';
}
/**
* to keep the annotations ordered.
*/
private static class AnnotationComparator implements Comparator<Annotation>
{
// Notice: Sorting is a bit costly, but the use of this code is very rar.
@Override
public int compare(Annotation annotation1, Annotation annotation2)
{
Class<? extends Annotation> type1 = annotation1.annotationType();
Class<? extends Annotation> type2 = annotation2.annotationType();
int temp = type1.getName().compareTo(type2.getName());
if (temp != 0)
{
return temp;
}
if (annotation1 instanceof EmptyAnnotationLiteral || annotation2 instanceof EmptyAnnotationLiteral)
{
// if any of those 2 annotations are known to have no members
// then we can immediately return as we know the 2 annotations mean the same
return 0;
}
Method[] member1 = type1.getDeclaredMethods();
Method[] member2 = type2.getDeclaredMethods();
// TBD: the order of the list of members seems to be deterministic
int i = 0;
int j = 0;
int length1 = member1.length;
int length2 = member2.length;
// find next nonbinding
for (;; i++, j++)
{
while (i < length1 && member1[i].isAnnotationPresent(Nonbinding.class))
{
i++;
}
while (j < length2 && member2[j].isAnnotationPresent(Nonbinding.class))
{
j++;
}
if (i >= length1 && j >= length2)
{ // both ended
return 0;
}
else if (i >= length1)
{ // #1 ended
return 1;
}
else if (j >= length2)
{ // #2 ended
return -1;
}
else
{ // not ended
int c = member1[i].getName().compareTo(member2[j].getName());
if (c != 0)
{
return c;
}
Object value1 = callMethod(annotation1, member1[i]);
Object value2 = callMethod(annotation2, member2[j]);
assert value1.getClass().equals(value2.getClass());
if (value1 instanceof Comparable)
{
c = ((Comparable)value1).compareTo(value2);
if (c != 0)
{
return c;
}
}
else if (value1.getClass().isArray())
{
c = value1.getClass().getComponentType().getName()
.compareTo(value2.getClass().getComponentType().getName());
if (c != 0)
{
return c;
}
int length = Array.getLength(value1);
c = length - Array.getLength(value2);
if (c != 0)
{
return c;
}
for (int k = 0; k < length; k++)
{
c = ((Comparable)Array.get(value1, k)).compareTo(Array.get(value2, k));
if (c != 0)
{
return c;
}
}
}
else if (value1 instanceof Class)
{
c = ((Class)value1).getName().compareTo(((Class) value2).getName());
if (c != 0)
{
return c;
}
}
else
{
// valid types for members are only Comparable, Arrays, or Class
assert false;
}
}
}
}
}
private static final class LazyAnnotatedTypes
{
private final AnnotatedType<?> qualifierAt;
private final AnnotatedType<?>[] qualifierAts;
private LazyAnnotatedTypes(final AnnotatedType<?> qualifierAt,
final AnnotatedType<?>[] qualifierAts)
{
this.qualifierAt = qualifierAt;
this.qualifierAts = qualifierAts;
}
}
}
|
package com.midashnt.taekwondo.app.mapper;
import com.midashnt.taekwondo.app.dto.WeightClass;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;
@Repository
@Mapper
public interface WeightClassMapper {
String createWeightClass(WeightClass weightClass);
void updateWeightClass(WeightClass weightClass);
WeightClass getWeightClassByIndex(int weightClassIndex);
List<WeightClass> getWeightClassListByEventIndex(int eventIndex);
List<Map<String, Object>> getWeightClassMapListByEventIndex(int eventIndex);
void deleteWeightClass(int weightClassIndex);
}
|
/* ===========================================================================
Created: 2015/10/13 Thomas Nguyen - thomas_ejob@hotmail.com
Purpose: Test an online calculator using DataProvider from a CSV file
=========================================================================== */
package com.thomas.tests;
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import lib.DriverFactory;
import lib.MyCSV;
import lib.MyCollection;
import page_objects.P_WebCalculator;
public class WebCalculator {
private WebDriver driver;
@BeforeMethod
public void setUp() throws Exception {
driver = new DriverFactory().driver();
}
@AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
@DataProvider(name="WebCalculatorCSV")
public String[][] WebCalculatorCSV()
{
MyCSV myCSV = new MyCSV();
//Get The data from the second line
List<String[]> data = myCSV.read("WebCalculator.csv", 1);
String[][] result = MyCollection.convertStringArray(data);
//Get rid of comma everywhere
for (int i=0; i<result.length; i++)
{
//for (int j=0; j<result[i].length; j++)
// result[i][j] = result[i][j].replaceAll(",", "");
result[i][3] = result[i][3].replaceAll(",", "");
}
return result;
}
@Test(groups="smokeTesting", dataProvider="WebCalculatorCSV", enabled = true)
public void basicOperationUsingButtons(String number1, String number2, String operation, String expectedResult) {
System.out.println("TESTING: basicOperationUsingButtons");
P_WebCalculator page = PageFactory.initElements(driver, P_WebCalculator.class);
page.visit();
page.windowsMaximize();
page.pressButtons(number1);
page.pressOperation(operation);
page.pressButtons(number2);
page.pressButtons("=");
String result = page.getConsole();
assertEquals(result, expectedResult);
}
@Test(groups="smokeTesting", dataProvider="WebCalculatorCSV", enabled = true)
public void basicOperationUsingConsole(String number1, String number2, String operation, String expectedResult) {
System.out.println("TESTING: basicOperationUsingConsole");
P_WebCalculator page = PageFactory.initElements(driver, P_WebCalculator.class);
page.visit();
page.windowsMaximize();
String equation = number1 + page.convertOperation(operation) + number2;
page.setConsole(equation);
page.pressButtons("=");
String result = page.getConsole();
assertEquals(result, expectedResult);
}
}
|
package com.example.twoclasses;
/**
* @author Roman Katerinenko
*/
public class JavaAccessor {
public String callJavaClass() {
return new StringBuilder("1").append("2").toString();
}
}
|
package LC0_200.LC50_100;
import LeetCodeUtils.MyMatrix;
import org.junit.Test;
public class LC63_Unique_Paths2 {
@Test
public void test() {
System.out.println(uniquePathsWithObstacles(MyMatrix.IntMatrixAdapter("[[0,0,0],[0,1,0],[0,0,0]]", 3, 3)));
}
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int R = obstacleGrid.length, C = obstacleGrid[0].length;
if (obstacleGrid[0][0] == 1)
return 0;
obstacleGrid[0][0] = 1;
for (int i = 1; i < R; ++i)
obstacleGrid[i][0] = (obstacleGrid[i][0] == 0 && obstacleGrid[i - 1][0] == 1) ? 1 : 0;
for (int i = 1; i < C; ++i)
obstacleGrid[0][i] = (obstacleGrid[0][i] == 0 && obstacleGrid[0][i - 1] == 1) ? 1 : 0;
for (int i = 1; i < R; ++i)
for (int j = 1; j < C; ++j)
if (obstacleGrid[i][j] == 0)
obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1];
else
obstacleGrid[i][j] = 0;
return obstacleGrid[R - 1][C - 1];
}
}
|
package edu.sit.bancodedados.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import edu.sit.bancodedados.conexao.Conexao;
import edu.sit.bancodedados.conexao.ConexaoException;
import edu.sit.erros.dao.DaoException;
import edu.sit.erros.dao.EErrosDao;
import edu.sit.model.Categoria;
public class CategoriaDao extends InstaladorDao implements IDao<Categoria> {
@Override
public boolean criaTabela() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
Statement st = conexao.createStatement();
st.executeUpdate("CREATE TABLE IF NOT EXISTS Categoria (" +
"id INT NOT NULL AUTO_INCREMENT," +
"Nome VARCHAR(45) NOT NULL," +
"PRIMARY KEY (id)) ENGINE = InnoDB;");
return true;
} catch (Exception e) {
throw new DaoException(EErrosDao.CRIAR_TABELA, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public boolean excluiTabela() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
Statement st = conexao.createStatement();
st.execute("DROP TABLE Categoria;");
return true;
} catch (Exception e) {
throw new DaoException(EErrosDao.EXCLUI_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public Categoria consulta(Integer idCategoria) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement("SELECT * FROM Categoria WHERE id = ?;");
pst.setInt(1, idCategoria);
ResultSet rs = pst.executeQuery();
return rs.first() ? new Categoria(rs.getInt("id"), rs.getString("Nome")) : null;
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public List<Categoria> consultaTodos() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
List<Categoria> categorias = new ArrayList<Categoria>();
try {
Statement st = conexao.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM Categoria;");
while (rs.next()) {
categorias.add( new Categoria(rs.getInt("id"), rs.getString("Nome")));
}
return categorias;
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public List<Categoria> consultaVariosPorID(Integer... codigos) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
List<Categoria> categorias = new ArrayList<Categoria>();
try {
PreparedStatement pst = conexao.prepareStatement("SELECT * FROM Categoria WHERE id = ?;");
for (Integer codigo : codigos) {
try {
pst.setInt(1, codigo);
ResultSet rs = pst.executeQuery();
if (rs.first()) {
categorias.add( new Categoria(rs.getInt("id"), rs.getString("Nome")));
}
} catch (Exception c) {
new DaoException(EErrosDao.CONSULTA_DADO, c.getMessage(), this.getClass());
}
}
} catch (Exception e) {
throw new DaoException(EErrosDao.CONSULTA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
return categorias;
}
@Override
public boolean insere(Categoria objeto) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement(
"INSERT INTO Categoria (Nome) values (?);");
pst.setString(1, objeto.getNome());
return pst.executeUpdate() > 0;
} catch (Exception e) {
throw new DaoException(EErrosDao.INSERE_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public boolean altera(Categoria objeto) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement(
"UPDATE Categoria SET Nome = ? WHERE id = ?;");
pst.setString(1, objeto.getNome());
pst.setInt(2, objeto.getId());
return pst.executeUpdate() > 0;
} catch (Exception e) {
throw new DaoException(EErrosDao.ALTERA_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
@Override
public boolean exclui(Integer... codigos) throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
PreparedStatement pst = conexao.prepareStatement("DELETE FROM Categoria WHERE id = ?;");
for (Integer novo : codigos) {
pst.setInt(1, novo);
pst.execute();
}
} catch (Exception e) {
throw new DaoException(EErrosDao.EXCLUI_DADO, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
return true;
}
public Integer pegaUltimoID() throws DaoException, ConexaoException {
Connection conexao = Conexao.abreConexao();
try {
Statement st = conexao.createStatement();
ResultSet rs = st.executeQuery("SELECT MAX(id) FROM Categoria;");
return rs.first() ? rs.getInt(1) : 0;
} catch (Exception e) {
throw new DaoException(EErrosDao.PEGA_ID, e.getMessage(), this.getClass());
} finally {
Conexao.fechaConexao();
}
}
}
|
package com.ibm.ive.tools.japt.obfuscation;
import java.util.*;
import com.ibm.jikesbt.*;
import com.ibm.ive.tools.japt.*;
/**
* @author sfoley
*
*/
public class MultipleClassNameGenerator {
List list;
BT_ClassVector classes;
public class ListEntry {
int frequency;
String entry;
ListEntry(String s) {
this.frequency = 1;
this.entry = s;
}
public boolean equals(Object o) {
if(o instanceof ListEntry) {
ListEntry other = (ListEntry) o;
return other.entry.equals(entry);
}
return false;
}
}
private void addEntry(HashMap entries, String string) {
if(entries.containsKey(string)) {
((ListEntry) entries.get(string)).frequency++;
}
else {
entries.put(string, new ListEntry(string));
}
}
public MultipleClassNameGenerator(BT_ClassVector classes, boolean addMemberNames, boolean reuseStrings) throws BT_ClassFileException {
this.classes = classes;
HashMap entries = new HashMap();
for(int j=0; j<classes.size(); j++) {
BT_Class clazz = classes.elementAt(j);
if(reuseStrings) {
LinkedList stringList = ConstantPoolNameGenerator.getStringList(clazz);
for(int i=1; i<stringList.size(); i++) {
String string = (String) stringList.get(i);
addEntry(entries, string);
}
}
if(addMemberNames) {
//now try method and field names
HashSet namesFound = new HashSet();
BT_MethodVector methods = clazz.getMethods();
for(int k=0; k<methods.size(); k++) {
BT_Method method = methods.elementAt(k);
String string = method.getName();
if(!namesFound.contains(string)) {
namesFound.add(string);
if(!Identifier.isValidJavaIdentifier(string)) {
continue;
}
addEntry(entries, string);
}
}
BT_FieldVector fields = clazz.getFields();
for(int k=0; k<fields.size(); k++) {
BT_Field field = fields.elementAt(k);
String string = field.getName();
if(!namesFound.contains(string)) {
addEntry(entries, string);
if(!Identifier.isValidJavaIdentifier(string)) {
continue;
}
namesFound.add(string);
}
}
}
}
list = new ArrayList(entries.size());
list.addAll(entries.values());
//the list is sorted by shortest UTF8 length and then by frequency
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
ListEntry l1 = (ListEntry) o1;
ListEntry l2 = (ListEntry) o2;
String s1 = l1.entry;
String s2 = l2.entry;
int s1Length = getUTF8Length(s1);
int s2Length = getUTF8Length(s2);
if(s1Length > s2Length) {
return -1;
}
else if(s1Length < s2Length) {
return 1;
}
else {
return l1.frequency - l2.frequency;
}
}
public boolean equals(Object obj) {
return obj.getClass().equals(getClass());
}
}
);
}
private static int getUTF8Length(String string) {
return UTF8Converter.convertToUtf8(string).length;
}
/**
* take a look at the next name without dispensing it
*/
public String peekName() {
if(!list.isEmpty()) {
return ((ListEntry) list.get(0)).entry;
}
return null;
}
/**
* dispense the next name
*/
public String getName() {
if(!list.isEmpty()) {
return ((ListEntry) list.remove(0)).entry;
}
return null;
}
/**
* dispense the next entry (name and frequency)
*/
public ListEntry getEntry() {
if(!list.isEmpty()) {
return (ListEntry) list.remove(0);
}
return null;
}
/**
* take a look at the next entry (name and frequency) without dispensing it
*/
public ListEntry peekEntry() {
if(!list.isEmpty()) {
return (ListEntry) list.get(0);
}
return null;
}
}
|
package com.example.todo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth/secured")
public class SecuredController {
//here is only for test for jwt authentication
@GetMapping
public ResponseEntity reachSecureEndpoint(){
return new ResponseEntity("if you are reading this you have reached out secure point", HttpStatus.OK);
}
}
|
class SparseVector {
HashMap<Integer, Integer> map;
SparseVector(int[] nums) {
map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
map.put(i, nums[i]);
}
}
}
// Return the dotProduct of two sparse vectors
public int dotProduct(SparseVector vec) {
int res = 0;
for (int i : map.keySet()) {
if (vec.map.containsKey(i)) {
res += map.get(i) * vec.map.get(i);
}
}
return res;
}
}
// Your SparseVector object will be instantiated and called as such:
// SparseVector v1 = new SparseVector(nums1);
// SparseVector v2 = new SparseVector(nums2);
// int ans = v1.dotProduct(v2);
|
import java.io.IOException;
class Ttest{
//private static Cfunction c = new Cfunction();
private static 토끼 T = new 토끼();
static festival f = new festival();
public static void main(String[]args) throws IOException, InterruptedException{
//c.clsFunction();
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
System.out.println("┌────────────────────┐\n│ │\n│ ~토끼 키우기~ │\n│ │\n│ │\n│ │\n│〔〕 〔〕 1. 게임 스타트 │\n│〔o w o〕 2. 게임 설명 │\n│〔) (〕 3. 게임 종료 │\n│ │\n│ │\n└────────────────────┘\n");
//시작 스토리
while(T.day<7){
T.응답(T.명령());
T.상태출력();
}
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
f.progress(T.Full(), T.Mood(), T.Health());
int tes = f.reward(T.Love());
System.out.print(tes);
//엔딩
}
}
|
package ca.mohawk.jdw.shifty.desktopclient.myshifts;
/*
I, Josh Maione, 000320309 certify that this material is my original work.
No other person's work has been used without due acknowledgement.
I have not made my work available to anyone else.
Module: desktop-client
Developed By: Josh Maione (000320309)
*/
import ca.mohawk.jdw.shifty.companyapi.model.shift.Shift;
import ca.mohawk.jdw.shifty.desktopclient.ui.UI;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Comparator;
import javafx.application.Platform;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextArea;
import javafx.scene.layout.BorderPane;
import static ca.mohawk.jdw.shifty.desktopclient.DesktopClient.client;
public class MyShiftsPane extends BorderPane {
private static class ShiftCell extends ListCell<Shift> {
@Override
protected void updateItem(final Shift shift, final boolean empty){
super.updateItem(shift, empty);
if(shift == null)
return;
Platform.runLater(() -> setGraphic(new MyShiftPane(shift)));
}
}
// private final TilePane tiles;
private final ListView<Shift> list;
private final TextArea selectedInfoArea;
public MyShiftsPane(){
getStylesheets().add(UI.css("contentPane"));
final Label placeholder = new Label("No Shifts");
placeholder.getStyleClass().add("placeholderLabel");
list = new ListView<>(client.myShifts().sorted(Comparator.comparing(Shift::startTimestamp)));
list.setCellFactory(param -> new ShiftCell());
list.setPlaceholder(placeholder);
selectedInfoArea = new TextArea();
selectedInfoArea.setEditable(false);
selectedInfoArea.setWrapText(true);
selectedInfoArea.setPrefRowCount(5);
list.getSelectionModel()
.selectedItemProperty()
.addListener((ob, o, n) -> {
if(n != null){
final LocalDateTime startDateTime = n.startTimestamp().toLocalDateTime();
final LocalDateTime finishDateTime = n.finishTimestamp().toLocalDateTime();
selectedInfoArea.setText(
String.format(
"Starts: %s @ %s%nFinishes: %s @ %s%n%n%s",
startDateTime.format(DateTimeFormatter.ISO_DATE),
startDateTime.format(DateTimeFormatter.ISO_TIME),
finishDateTime.format(DateTimeFormatter.ISO_DATE),
finishDateTime.format(DateTimeFormatter.ISO_TIME),
n.description()
)
);
}else
selectedInfoArea.setText("");
});
setCenter(list);
setBottom(selectedInfoArea);
}
}
|
package cz.cvut.fel.matyapav.afnearbystatus.nearbystatus.devicestatus.model.partial;
/**
* Network status model - keeps information about device connectivity and active network
*
* @author Pavel Matyáš (matyapav@fel.cvut.cz).
* @since 1.0.0..
*/
public class NetworkStatus {
private boolean connected;
private String networkTypeName; //wifi, mobile
private String networkSubtypeName;
private WifiStatus wifiStatus;
public NetworkStatus() {
}
public boolean isConnected() {
return connected;
}
public void setConnected(boolean connected) {
this.connected = connected;
}
public String getNetworkTypeName() {
return networkTypeName;
}
public void setNetworkTypeName(String networkTypeName) {
this.networkTypeName = networkTypeName;
}
public String getNetworkSubtypeName() {
return networkSubtypeName;
}
public void setNetworkSubtypeName(String networkSubtypeName) {
if(!networkSubtypeName.isEmpty()) {
this.networkSubtypeName = networkSubtypeName;
}
}
public WifiStatus getWifiStatus() {
return wifiStatus;
}
public void setWifiStatus(WifiStatus wifiStatus) {
this.wifiStatus = wifiStatus;
}
}
|
import java.io.IOException;
import java.nio.file.Paths;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.FSDirectory;
/**
* Searches for files under a directory indexed using indexer {@code Indexer}
* @author Kedar
*
*/
public class Searcher {
private final String indexPath;
private final String field;
private final int hitsPerPage =10;
private final boolean raw;
public Searcher(String indexPath,String field,boolean raw,String searchfield,StringBuilder sb){
this.indexPath = indexPath;
this.field = field;
this.raw = raw;
String search = searchfield;
SearchFiles(search,sb);
}
public void SearchFiles(String queryString,StringBuilder sb){
try {
IndexReader reader = DirectoryReader.open(
FSDirectory.open(Paths.get(indexPath)));
IndexSearcher searcher = new IndexSearcher(reader);
Analyzer analyzer = new StandardAnalyzer();
QueryParser parser = new QueryParser(field, analyzer);
try {
Query query = parser.parse(queryString);
sb.append("Searching for: " + query.toString(field)+"\n");
System.out.println("Searching for: " + query.toString(field));
doSearch(searcher, query,raw,sb);
reader.close();
} catch (ParseException e) {
System.out.println("Unable to parse the query " + queryString);
}
} catch (IOException e) {
System.out.println("Unable to read indexes from " + indexPath);
}
}
private void doSearch(IndexSearcher searcher,Query query,boolean raw,StringBuilder sb) {
try {
long startTime = System.nanoTime();
TopDocs results = searcher.search(query, 5 * hitsPerPage);
long endTime = System.nanoTime();
ScoreDoc[] hits = results.scoreDocs;
int numTotalHits = results.totalHits;
System.out.println(numTotalHits + " total matching documents found in "
+ (endTime-startTime)/1e9 + " secs");
sb.append(numTotalHits + " total matching documents found in "
+ (endTime-startTime)/1e9 + " secs \n");
int start = 0;
int end = Math.min(numTotalHits, hitsPerPage);
end = numTotalHits;
for (int i = start; i < end; i++) {
Document doc = searcher.doc(hits[i].doc);
String path = doc.get("path");
String uri = doc.get("uri"); //Get Uri from index files
if (path != null) {
System.out.println((i+1) + ". " + uri);//Print Line uri
sb.append((i+1) + ". " + uri+" \n");
String title = doc.get("title");
if (title != null) {
System.out.println(" Title: " + doc.get("title"));
}
} else {
System.out.println((i+1) + ". " + "No path for this document");
}
if (raw) {
System.out.println("doc="+hits[i].doc+" score="+hits[i].score);
}
}
} catch (IOException e) {
e.printStackTrace();
}
SpiderControllerXML.unlockButton(); //Unlock button
}
}
|
package frontend;
import backend.WeatherClient;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
public class UserInterface {
public void ui() throws InterruptedException, URISyntaxException, IOException {
System.out.println("Welcome to MyWeather!");
TimeUnit.SECONDS.sleep(1);
System.out.println("What do you want to do?");
Scanner scanner = new Scanner(System.in);
String menu = "1 - Check current weather\n"
+ "2 - Check daily forecast\n"
+ "3 - Close application\n";
char response;
do {
System.out.println(menu);
response = scanner.next().charAt(0);
switch (response) {
case '1':
checkWeather();
break;
case '2':
//TODO
break;
case '3':
System.out.println("Closing Down Bye Bye");
System.exit(0);
default:
System.out.print("Incorrect input, try again \n \n");
TimeUnit.SECONDS.sleep(1);
}
} while (response != 1 || response != 2 || response != 3);
}
public void checkWeather() throws InterruptedException, URISyntaxException, IOException {
System.out.println("Enter City");
Scanner scanner = new Scanner(System.in);
String city = scanner.nextLine();
city = city.replaceAll(" ", "+");
if ((Pattern.matches("[a-zA-Z+]+", city) || city.length() <= 2)) {
System.out.print("Checking current weather please wait");
TimeUnit.MILLISECONDS.sleep(500);
System.out.print(".");
TimeUnit.MILLISECONDS.sleep(500);
System.out.print(".");
TimeUnit.MILLISECONDS.sleep(500);
System.out.print(".\n\n");
WeatherClient weatherClient = new WeatherClient();
weatherClient.currentWeatherClient(city);
} else
System.out.println("Entered value is not valid try again");
}
}
|
package com.example.ozangokdemir.movision.models;
import java.util.List;
public class InitialReviewResponse {
int id;
int page;
List<Review> results;
public List<Review> getReviewResults() {
return results;
}
}
|
package com.demo.test.configurer;
import com.demo.test.constant.Constant;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.*;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
/**
* @author Jack
* @date 2019/10/07 update
* @Profile 注解 标识加载在dev和test文件使用
*/
@Configuration
@EnableWebMvc
@EnableSwagger2
@Profile({"dev", "test"})
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Value("${swagger.enable}")
private boolean enableSwagger;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).groupName("spring-test-interface")
//加载配置信息
.apiInfo(apiInfo())
// 生产环境的时候关闭 swagger 比较安全
.enable(enableSwagger)
//将Timestamp类型全部转为Long类型
//.directModelSubstitute(Timestamp.class, Long.class)
// 将Date类型全部转为Long类型
//.directModelSubstitute(Date.class, Long.class)
.forCodeGeneration(true)
//设置全局参数
.globalOperationParameters(globalParamBuilder())
//设置全局响应参数
.globalResponseMessage(RequestMethod.GET, responseBuilder())
.globalResponseMessage(RequestMethod.POST, responseBuilder())
.globalResponseMessage(RequestMethod.PUT, responseBuilder())
.globalResponseMessage(RequestMethod.DELETE, responseBuilder())
.select()
//加载swagger 扫描包 扫描接口的包路径,不要忘记改成自己的
.apis(RequestHandlerSelectors.basePackage(Constant.BASE_PACKAGE))
//.paths(regex("^.*(?<!error)$"))
.paths(PathSelectors.any())
.build()
//设置安全认证
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
private List<SecurityContext> securityContexts() {
List<SecurityContext> securityContexts = new ArrayList<>();
securityContexts.add(
SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!token).*$"))
.build());
return securityContexts;
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
List<SecurityReference> securityReferences = new ArrayList<>();
securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
return securityReferences;
}
/**
* 获取swagger创建初始化信息
*
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger REST API")
.description("©2019 Copyright. Powered By Jack.")
// .termsOfServiceUrl("")
.contact("xxxx@163.com")
.license("Apache License Version 2.0")
.licenseUrl("https://github.com/wx8900/SpringBootPage")
.version("2.0")
.build();
}
/**
* 安全认证参数
*
* @return
*/
private List<ApiKey> securitySchemes() {
List<ApiKey> list = new ArrayList<>();
list.add(new ApiKey("token", "token", "header"));
return list;
}
/**
* 构建全局参数列表
*
* @return
*/
private List<Parameter> globalParamBuilder() {
List<Parameter> pars = new ArrayList<>();
pars.add(parameterBuilder("token", "令牌", "string"
, "header", false).build());
return pars;
}
/**
* 创建参数
*
* @return
*/
private ParameterBuilder parameterBuilder(String name, String desc, String type,
String parameterType, boolean required) {
ParameterBuilder tokenPar = new ParameterBuilder();
tokenPar.name(name).description(desc).modelRef(new ModelRef(type))
.parameterType(parameterType).required(required).build();
return tokenPar;
}
/**
* 创建全局响应值
*
* @return
*/
private List<ResponseMessage> responseBuilder() {
List<ResponseMessage> responseMessageList = new ArrayList<>();
responseMessageList.add(new ResponseMessageBuilder().code(200).message("响应成功").build());
responseMessageList.add(new ResponseMessageBuilder().code(500).message("服务器内部错误").build());
return responseMessageList;
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
|
function maxminAvg(arr)
{
var sum = 0;
var max = arr[0];
var min = arr[0];
for (var i = 0; i < arr.length; i++)
{
if (arr[i]>max)
{
max = arr[i];
}
}
for (var i = 0; i < arr.length; i++)
{
if (arr[i]<min)
{
min = arr[i];
}
}
for (var i = 0; i < arr.length; i++)
{
sum = sum + arr[i];
}
var avg = sum/arr.length;
var arr2 = [max,min,avg];
return arr2;
}
|
/*
* The purpose of this lab is to learn how to count specific
* occurances of values in an array.
*
* Author: Victor (Zach) Johnson
* Date: 10/29/17
*/
package chapter7;
public class Ex7_7 {
public static void main(String[] args) {
int[] counts = new int[10];
int randomNumber;
for(int i = 0; i < 100; i++) {
randomNumber = (int) (Math.random() * 10);
counts[randomNumber]++;
}
findOccurance(counts);
}
public static void findOccurance(int[] counts) {
for(int i = 0; i < counts.length; i++) {
System.out.println(i + " occurs " + counts[i] + " times");
}
}
}
|
public class Example4 {
public boolean equals(Example4 other) {
System.out.println("Inside of Test.equals");
return false;
}
@Override
public boolean equals(Object other) {
System.out.println("Inside @override: this is dynamic binding");
return false;
}
public static void main(String[] args) {
Object t1 = new Example4();
Object t2 = new Example4();
Example4 t3 = new Example4();
Object o1 = new Object();
int count = 0;
System.out.println(count++);// prints 0
t1.equals(t2);
System.out.println(count++);// prints 1
t1.equals(t3);
System.out.println(count++);// prints 2
t3.equals(o1);
System.out.println(count++);// prints 3
t3.equals(t3);
System.out.println(count++);// prints 4
t3.equals(t2);
}
}
|
package cn.it.homework6;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import cn.it.homework6.db.dao.DBUtils;
import cn.it.homework6.utils.Constants;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private EditText mAccountEdt;//账号编辑框
private EditText mPwdEdt;//密码编辑框
private Context context;//上下文
private CheckBox mRemenberChx;//复选框
private SharedPreferences mSp;//偏好设置存储对象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
//1.初始化视图
initView();
//2.自动填充数据
autoFill();
}
//自动填充数据
private void autoFill() {
if(mSp.getBoolean("isChecked", false)){ //存储的复选状态为 真
mAccountEdt.setText(mSp.getString("username", null));
try {
mPwdEdt.setText( mSp.getString("password", null));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRemenberChx.setChecked(true);
}
}
private void initView() {
mAccountEdt=(EditText)findViewById(R.id.account_et);
mPwdEdt=(EditText)findViewById(R.id.pwd_et);
mRemenberChx=(CheckBox)findViewById(R.id.remenber_chb);
context=this;
mSp=getSharedPreferences("info", Context.MODE_PRIVATE);
}
//登录方法
public void login(View v){
final String account=mAccountEdt.getText().toString().trim();//用户输入的账号
final String pwd=mPwdEdt.getText().toString().trim();//用户输入的密码
//1.用户名和密码都不能为空 ,前端验证格式
if(TextUtils.isEmpty(account)||TextUtils.isEmpty(pwd)){
Toast.makeText(context, "用户名或者密码不能为空", Toast.LENGTH_SHORT).show();
return;
}
// 通过AndroidAsyncHttp框架访问网络,从网络中验证用户名和密码
AsyncHttpClient httpClient=new AsyncHttpClient();
//2. 设置请求参数
RequestParams params=new RequestParams();
params.add("account", account);
params.add("pwd", pwd);
// 发送请求
httpClient.post(Constants.WEB_LOGIN, params, new AsyncHttpResponseHandler() {
//访问网络成功 ,包含验证成功和验证失败的返回信息
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
remenberInfo(account,pwd);
try {
JSONObject jsonObject=new JSONObject(new String(responseBody));
if(jsonObject.getBoolean("success")){//验证成功
//保存账号信息
remenberInfo(account, pwd);
// 把账号信息通过SharedPreferes保存
mSp.edit().putString("nick", jsonObject.getString("msg")).commit();
//进入到HomeActivity
Intent intent=new Intent();
intent.setClass(context, HomeActivity.class);
startActivity(intent);//执行意图
finish();//关闭当前的Activity
}else{//验证失败
Toast.makeText(getApplicationContext(), jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
mAccountEdt.setText(null);
mPwdEdt.setText(null);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
//访问网络失败
@Override
public void onFailure(int statusCode, Header[] headers,
byte[] responseBody, Throwable error) {
Toast.makeText(getApplicationContext(), "网络访问异常-直接进入系统", 0).show();
Intent intent=new Intent();
intent.setClass(context, HomeActivity.class);
startActivity(intent);//执行意图
finish();//关闭当前的Activity
}
});
}
//记住用户信息
private void remenberInfo(String account, String pwd) {
Editor edit = mSp.edit();//取得编辑器
//先判断复选框是否选择
if(mRemenberChx.isChecked()){
edit.putString("username", account);
// seed :加密的种子,密钥 clearText :明文,原文
try {
edit.putString("password", pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
edit.putBoolean("isChecked", true);
}else{
edit.putBoolean("isChecked", false);
}
edit.commit();//提交数据
}
//注册
public void register(View v){
Toast.makeText(getApplicationContext(), "注册太晚了", 0).show();
}
}
|
package com.tencent.mm.plugin.account.friend.ui;
public interface h$a {
void ck(boolean z);
}
|
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.log4j.helpers;
/**
This class used to output log statements from within the log4j package.
<p>Log4j components cannot make log4j logging calls. However, it is
sometimes useful for the user to learn about what log4j is
doing. You can enable log4j internal logging by defining the
<b>log4j.configDebug</b> variable.
<p>All log4j internal debug calls go to <code>System.out</code>
whereas internal error messages are sent to
<code>System.err</code>. All internal messages are prepended with
the string "log4j: ".
@since 0.8.2
@author Ceki Gülcü
*/
public class LogLog {
/**
Defining this value makes log4j print log4j-internal debug
statements to <code>System.out</code>.
<p> The value of this string is <b>log4j.debug</b>.
<p>Note that the search for all option names is case-sensitive. */
public static final String DEBUG_KEY = "log4j.debug";
/**
Defining this value makes log4j components print log4j-internal
debug statements to <code>System.out</code>.
<p> The value of this string is <b>log4j.configDebug</b>.
<p>Note that the search for all option names is case-sensitive.
@deprecated Use {@link #DEBUG_KEY} instead.
*/
public static final String CONFIG_DEBUG_KEY = "log4j.configDebug";
protected static boolean debugEnabled = false;
/**
In quietMode not even errors generate any output.
*/
private static boolean quietMode = false;
private static final String PREFIX = "log4j: ";
private static final String ERR_PREFIX = "log4j:ERROR ";
private static final String WARN_PREFIX = "log4j:WARN ";
static {
}
/**
Allows to enable/disable log4j internal logging.
*/
static public void setInternalDebugging(boolean enabled) {
debugEnabled = enabled;
}
/**
This method is used to output log4j internal debug
statements. Output goes to <code>System.out</code>.
*/
public static void debug(String msg) {
if (debugEnabled && !quietMode) {
System.out.println(PREFIX + msg);
}
}
/**
This method is used to output log4j internal debug
statements. Output goes to <code>System.out</code>.
*/
public static void debug(String msg, Throwable t) {
if (debugEnabled && !quietMode) {
System.out.println(PREFIX + msg);
if (t != null)
t.printStackTrace(System.out);
}
}
/**
This method is used to output log4j internal error
statements. There is no way to disable error statements.
Output goes to <code>System.err</code>.
*/
public static void error(String msg) {
if (quietMode)
return;
System.err.println(ERR_PREFIX + msg);
}
/**
This method is used to output log4j internal error
statements. There is no way to disable error statements.
Output goes to <code>System.err</code>.
*/
public static void error(String msg, Throwable t) {
if (quietMode)
return;
System.err.println(ERR_PREFIX + msg);
if (t != null) {
t.printStackTrace();
}
}
/**
In quite mode no LogLog generates strictly no output, not even
for errors.
@param quietMode A true for not
*/
public static void setQuietMode(boolean quietMode) {
LogLog.quietMode = quietMode;
}
/**
This method is used to output log4j internal warning
statements. There is no way to disable warning statements.
Output goes to <code>System.err</code>. */
public static void warn(String msg) {
if (quietMode)
return;
System.err.println(WARN_PREFIX + msg);
}
/**
This method is used to output log4j internal warnings. There is
no way to disable warning statements. Output goes to
<code>System.err</code>. */
public static void warn(String msg, Throwable t) {
if (quietMode)
return;
System.err.println(WARN_PREFIX + msg);
if (t != null) {
t.printStackTrace();
}
}
}
|
package tests;
import enums.PacketCommand;
import logging.*;
import remote.RemoteData;
import remote.Server;
public class LoggingTest {
public static void main(String[] args) throws InterruptedException {
RemoteData<Integer> intData = new RemoteData<>(PacketCommand.REQUEST_LATERAL_DISTANCE, Server.getInstance());
DataLogger<Integer> logger = new LimitDataLogger<>(15);
intData.subscribe(logger);
for (int i = 0; i < 1000; i++) {
intData.update(i);
Thread.sleep(10);
}
for (DataPoint<Integer> p : logger.getLogPoints()) {
System.out.println((p.getTime().getNano() / 100000) + ": " + p.getValue());
}
System.out.println(logger);
}
}
|
package model.entities;
import java.io.Serializable;
import java.util.Objects;
/*
* Department entity class
*Entity class checklist:
* Attributes
* Constructors
* Getters/Setters
* hashCode and equals (APENAS o ID)
* toString
* implements Serializable
*/
public class Departamento implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
public Departamento() {
}
public Departamento(Integer id, String name) {
//super();
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//aqui só o ID:
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Departamento other = (Departamento) obj;
return Objects.equals(id, other.id);
}
@Override
public String toString() {
return "Departamento [id=" + id + ", name=" + name + "]";
}
}
|
package br.com.becommerce.core.inventory;
import java.time.ZonedDateTime;
import java.util.Optional;
import java.util.UUID;
import com.github.javafaker.Faker;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Setter;
@Data
@Setter(AccessLevel.PROTECTED)
public class Inventory {
private String id;
private String name;
private ZonedDateTime deletedDateTime;
public Optional<String> getOptionalId() {
return Optional.ofNullable(id);
}
public static Inventory fake() {
Inventory fake = new Inventory();
fake.id = UUID.randomUUID().toString();
fake.name = Faker.instance().lorem().characters();
return fake;
}
}
|
//import java.util.*;
interface Storage<E> {
public void insert();
public void remove();
public void contain();
public void size();
public void getAll();
public void addAll();
}
|
/**
* original(c) zhuoyan company
* projectName: java-design-pattern
* fileName: PandaFactory.java
* packageName: cn.zy.pattern.factory.deep
* date: 2018-12-09 18:36
* history:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
package cn.zy.pattern.factory.high;
/**
* @version: V1.0
* @author: ending
* @className: PandaFactory
* @packageName: cn.zy.pattern.factory.deep
* @description: 熊猫工厂类
* @data: 2018-12-09 18:36
**/
public class PandaFactory implements Factory {
@Override
public Animal createAnimal() {
return new PandaAnimal();
}
}
|
/**
*/
package ErdiagramDSL;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Chen Weak Entity</b></em>'.
* <!-- end-user-doc -->
*
*
* @see ErdiagramDSL.ErdiagramDSLPackage#getChenWeakEntity()
* @model
* @generated
*/
public interface ChenWeakEntity extends ChenWeakElement {
} // ChenWeakEntity
|
/*******************************************************************************
* =============LICENSE_START=========================================================
*
* =================================================================================
* Copyright (c) 2019 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*
*******************************************************************************/
package org.onap.ccsdk.dashboard.model.deploymenthandler;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Map;
import java.util.Optional;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Model for message POST-ed to controller to create a Deployment via the
* Deployment Handler API:
*
* <pre>
{
"component" : "comp",
"deploymentTag" : "tag",
"blueprintName" : "name",
"blueprintVersion" : "version",
"blueprintId" : "bp_id",
"inputs" :
{
"input1" : "parameter1",
"input2" : "parameter2",
...
"inputn" : "parametern"
},
"tenant" : "tenant_name"
}
* </pre>
*
* THIS OBJECT INCLUDES THE DEPLOYMENTID CREATED BY THE USER!
*/
public class DeploymentInput {
/** component or namespace for the service */
private final String component;
/** tag to identify the deployment */
private final String tag;
/** The blueprint name for the service to be deployed. */
private final String blueprintName;
/** blueprint version for the service to be deployed */
private final Optional<Integer> blueprintVersion;
/** blueprint typeId from inventory */
private final Optional<String> blueprintId;
/** The cloudify tenant name for the deployment */
private final String tenant;
/**
* Object containing inputs needed by the service blueprint to create an
* instance of the service. Content of the object depends on the service being
* deployed.
*/
private final Map<String, Object> inputs;
private final Collection<String> reinstall_list;
private final boolean skip_install;
private final boolean skip_uninstall;
private final boolean skip_reinstall;
private final boolean force;
private final boolean ignore_failure;
private final boolean install_first;
@JsonCreator
public DeploymentInput(@JsonProperty("component") String component,
@JsonProperty("tag") String tag, @JsonProperty("blueprintName") String blueprintName,
@JsonProperty("blueprintVersion") Integer blueprintVersion,
@JsonProperty("blueprintId") String blueprintId,
@JsonProperty("inputs") Map<String, Object> inputs, @JsonProperty("tenant") String tenant,
@JsonProperty("reinstall_list") Collection<String> reinstallList,
@JsonProperty("skip_install") boolean skipInstall,
@JsonProperty("skip_uninstall") boolean skipUninstall,
@JsonProperty("skip_reinstall") boolean skipReinstall, @JsonProperty("force") boolean force,
@JsonProperty("ignore_failure") boolean ignoreFailure,
@JsonProperty("install_first") boolean installFirst) {
this.component = component;
this.tag = tag;
this.blueprintName = blueprintName;
this.blueprintVersion = Optional.ofNullable(blueprintVersion);
this.blueprintId = Optional.ofNullable(blueprintId);
this.inputs = inputs;
this.tenant = tenant;
this.reinstall_list = (reinstallList == null) ? new LinkedList<String>() : reinstallList;
this.skip_install = skipInstall;
this.skip_uninstall = skipUninstall;
this.skip_reinstall = skipReinstall;
this.force = force;
this.ignore_failure = ignoreFailure;
this.install_first = installFirst;
}
public String getBlueprintName() {
return this.blueprintName;
}
public Map<String, Object> getInputs() {
return this.inputs;
}
public String getTenant() {
return this.tenant;
}
public Optional<Integer> getBlueprintVersion() {
return blueprintVersion;
}
public String getTag() {
return tag;
}
public String getComponent() {
return component;
}
public Optional<String> getBlueprintId() {
return blueprintId;
}
public Collection<String> getReinstall_list() {
return reinstall_list;
}
public boolean isSkip_install() {
return skip_install;
}
public boolean isSkip_uninstall() {
return skip_uninstall;
}
public boolean isSkip_reinstall() {
return skip_reinstall;
}
public boolean isForce() {
return force;
}
public boolean isIgnore_failure() {
return ignore_failure;
}
public boolean isInstall_first() {
return install_first;
}
}
|
package it.ozimov.seldon.core.algorithms.rounding;
import static java.lang.StrictMath.round;
import javax.annotation.Nonnull;
import it.ozimov.seldon.core.algorithms.Algorithm;
import it.unimi.dsi.fastutil.floats.FloatBigArrayBigList;
import it.unimi.dsi.fastutil.ints.IntBigArrayBigList;
/**
* @version 0.1.0
* @since 0.1.0
*/
public class FloatToIntCumulativeRoundingForecastAlgorithm
extends CumulativeRoundingForecastAlgorithm<FloatBigArrayBigList, IntBigArrayBigList> {
private FloatToIntCumulativeRoundingForecastAlgorithm(@Nonnull final FloatBigArrayBigList fromBigList) {
super(fromBigList);
}
/**
* Fluent accessor to the default constructor.
*
* @return a new instance of the class.
*/
@Nonnull
public static FloatToIntCumulativeRoundingForecastAlgorithm cumulativeRoundingAlgorithm(
@Nonnull final FloatBigArrayBigList fromBigList) {
return new FloatToIntCumulativeRoundingForecastAlgorithm(fromBigList);
}
/**
*/
@Override
protected Algorithm<IntBigArrayBigList> compute() {
final long size = fromBigList.size64();
final IntBigArrayBigList intArrayList = new IntBigArrayBigList(size);
float d = .0f;
for (long i = 0L; i < size; i++) {
final int roundedValue = round(fromBigList.getFloat(i) + d + .5f);
d += fromBigList.getFloat(i) - roundedValue;
intArrayList.add(roundedValue);
}
toBigList = intArrayList;
return this;
}
@Override
public IntBigArrayBigList apply(@Nonnull final FloatBigArrayBigList fromBigList) {
return compute().getOutput();
}
}
|
package variaveis.casting;
public class Main {
public static void main(String[] args) {
// double - int
double pi = 3.14;
int intpi = (int) pi;
System.out.println(pi);
System.out.println(intpi);
// int - double
int i = 5;
double d2 = i;
System.out.println(i);
System.out.println(d2);
// long - int
long x = 100;
int a = (int) x;
System.out.println(x);
System.out.println(a);
// float - double
double preco = 12.9;
float novoPreco = (float) preco;
System.out.println(preco);
System.out.println(novoPreco);
}
}
|
import java.util.HashMap;
import java.util.Map;
class MapSum_677 {
HashMap<String, Integer> map;
TrieNodeV root;
public MapSum_677() {
map = new HashMap();
root = new TrieNodeV();
}
public void insert(String key, int val) {
int delta = val - map.getOrDefault(key, 0);
map.put(key, val);
TrieNodeV cur = root;
cur.score += delta;
for (char c: key.toCharArray()) {
cur.children.putIfAbsent(c, new TrieNodeV());
cur = cur.children.get(c);
cur.score += delta;
}
}
public int sum(String prefix) {
TrieNodeV cur = root;
for (char c: prefix.toCharArray()) {
cur = cur.children.get(c);
if (cur == null) return 0;
}
return cur.score;
}
}
class TrieNodeV {
Map<Character, TrieNodeV> children = new HashMap();
int score;
}
|
package com.soup;
import java.util.ArrayList;
public class Command {
private String cmd;
private ArrayList<String> subs = new ArrayList<String>();
public Command(String command) {
if(command.contains(";")) {
cmd = command.substring(0, command.indexOf(';'));
if (command.contains("|")) {
for (String sub : command.substring(command.indexOf(";") + 1).split("\\|")) {
subs.add(sub);
}
} else {
if (!command.substring(command.indexOf(";")).isEmpty()) {
subs.add(command.substring(command.indexOf(";") + 1));
}
}
} else {
cmd = command;
}
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
}
public ArrayList<String> getSubs() {
return subs;
}
public void setSubs(ArrayList<String> subs) {
this.subs = subs;
}
public void addSub(String sub) {
subs.add("sub");
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append(cmd + ";");
for (String sub: subs) {
builder.append(sub + "|");
}
return builder.toString();
}
}
|
package com.tencent.mm.plugin.wallet_core.ui;
class WalletOrderInfoNewUI$b {
public String bQa;
public String myq;
public String pjF;
public long pqh;
public String pwm;
public String pwn;
public String pwo;
public long pwp;
public String pwq;
public WalletOrderInfoNewUI$b(String str, String str2, String str3, String str4, String str5, String str6, long j, String str7) {
this.pjF = str;
this.pwm = str2;
this.pwn = str3;
this.pwo = str4;
this.bQa = str5;
this.myq = str6;
this.pqh = j;
this.pwq = str7;
}
public WalletOrderInfoNewUI$b(String str, String str2, String str3, String str4, String str5, String str6, long j, long j2) {
this.pjF = str;
this.pwm = str2;
this.pwn = str3;
this.pwo = str4;
this.bQa = str5;
this.myq = str6;
this.pqh = j;
this.pwp = j2;
this.pwq = null;
}
}
|
package com.e6soft.bpm.controllers;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.e6soft.bpm.BpmController;
import com.e6soft.bpm.BpmFactory;
import com.e6soft.bpm.model.FlowOperatorTarget;
import com.e6soft.bpm.model.Flowbase;
import com.e6soft.bpm.model.Flownode;
import com.e6soft.bpm.model.FlownodeOperator;
import com.e6soft.bpm.vo.FlownodeOperatorGrid;
import com.e6soft.core.views.PageFilter;
import com.e6soft.core.views.PageGrid;
import com.e6soft.core.views.ViewMsg;
@Controller
@RequestMapping(value=BpmFactory.module+"/flownodeoperator")
public class FlownodeOperatorController extends BpmController {
@RequestMapping(value="grid")
@ResponseBody
public String grid(@RequestParam String nodeId,@ModelAttribute PageFilter pageFilter ) {
pageFilter.addFilter("nodeId", nodeId);
PageGrid<FlownodeOperatorGrid> pageGrid = this.voService.createPageGrid(FlownodeOperatorGrid.class,pageFilter);
return this.toJson(pageGrid);
}
@RequestMapping(value="add")
public String add(@RequestParam String nodeid,Model model) {
Flownode flownode = this.flownodeService.getById(nodeid);
model.addAttribute("flownode", flownode);
model.addAttribute("flownodeoperator",new FlownodeOperator());
Flowbase flowbase = flowbaseService.getById(flownode.getFlowId());
model.addAttribute("flowbase", flowbase);
return BpmFactory.modulePath+"/flownode/nodeoperatoradd";
}
@RequestMapping(value="modify")
public String modify(@RequestParam String nodeid,@RequestParam String id,Model model) {
Flownode flownode = flownodeService.getById(nodeid);
Flowbase flowbase = flowbaseService.getById(flownode.getFlowId());
FlownodeOperator flownodeOperator = flownodeOperatorService.getById(id);
model.addAttribute("flowbase", flowbase);
model.addAttribute("flownode", flownode);
model.addAttribute("flownodeoperator",flownodeOperator);
model.addAttribute("targetValue",flowOperatorTargetService.getTargetValueByOperator(id));
model.addAttribute("targetText",flowOperatorTargetService.getTargetTextByOperator(id,flownodeOperator.getTargetType()));
flowOperatorTargetService.queryByOperatorId(id);
return BpmFactory.modulePath+"/flownode/nodeoperatoradd";
}
@RequestMapping(value="delete")
@ResponseBody
public String delete(@RequestParam String id) {
this.flownodeOperatorService.deleteById(id);
return new ViewMsg(1).toString();
}
@RequestMapping(value="updatebase")
@ResponseBody
public String save(@ModelAttribute FlownodeOperator flownodeOperator){
this.flownodeOperatorService.save(flownodeOperator);
return new ViewMsg(1).toString();
}
@RequestMapping(value="save")
@ResponseBody
public String save(@ModelAttribute FlownodeOperator flownodeOperator,@RequestParam String targetvalue_) {
String [] tarArr = targetvalue_.split(",");
List<FlowOperatorTarget> flowOperatorTargetList = new ArrayList<FlowOperatorTarget>();
for(int i=0;i<tarArr.length;i++)
{
FlowOperatorTarget flowOperatorTarget = new FlowOperatorTarget();
flowOperatorTarget.setTargetId(tarArr[i]);
flowOperatorTargetList.add(flowOperatorTarget);
}
this.flownodeOperatorService.save(flownodeOperator, flowOperatorTargetList);
return new ViewMsg(1).toString();
}
}
|
package com.tencent.mm.plugin.sns.f;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.sns.f.d.b;
import com.tencent.mm.plugin.sns.ui.a.a.c;
class c$2 implements OnClickListener {
final /* synthetic */ d$a nuk;
final /* synthetic */ b nul;
final /* synthetic */ c nun;
final /* synthetic */ d nuo;
final /* synthetic */ c nup;
final /* synthetic */ Context val$context;
c$2(c cVar, Context context, d$a d_a, b bVar, c cVar2, d dVar) {
this.nup = cVar;
this.val$context = context;
this.nuk = d_a;
this.nul = bVar;
this.nun = cVar2;
this.nuo = dVar;
}
public final void onClick(View view) {
c.a(this.nup, this.val$context, view, this.nuk, this.nul, this.nun, this.nuo);
}
}
|
package com.samyotech.laundry.interfaces;
import android.view.View;
public interface RecycleViewClickListner {
void onClick(View view, int position);
}
|
package com.zhouyi.business.core.service;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import javax.management.modelmbean.XMLParseException;
import com.zhouyi.business.core.common.ReturnCode;
import com.zhouyi.business.core.config.FtpConfig;
import com.zhouyi.business.core.dao.*;
import com.zhouyi.business.core.exception.AuthenticationException;
import com.zhouyi.business.core.model.*;
import com.zhouyi.business.core.utils.MathUtil;
import com.zhouyi.business.core.utils.ResponseUtil;
import javafx.beans.property.adapter.ReadOnlyJavaBeanBooleanProperty;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.ibatis.javassist.bytecode.ByteArray;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.zhouyi.business.core.utils.FingerXmlParse;
import com.zhouyi.business.core.vo.LedenCollectFingerVo;
import com.zhouyi.business.core.vo.xml.FingerXml;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import sun.misc.BASE64Encoder;
@Service
public class LedenCollectFingerServiceImpl
extends BaseServiceImpl<LedenCollectFinger, LedenCollectFingerVo>
implements LedenCollectFingerService {
@Value("${finger.dir}")
private String fingerDir;
@Autowired
private LedenCollectFingerMapper ledenCollectFingerMapper;
@Autowired
private FtpConfig ftpConfig;
@Autowired
private LedenCollectFourfingerMapper ledenCollectFourfingerMapper;
@Autowired
private LedenCollectPalmMapper ledenCollectPalmMapper;
@Autowired
private LedenCollectFullpalmMapper ledenCollectFullpalmMapper;
@Autowired
private LedenCollectPhalangeMapper ledenCollectPhalangeMapper;
private static final Logger logger= LoggerFactory.getLogger(LedenCollectFingerServiceImpl.class);
/**
* @param
* @return
* @author 李秸康
* @Description 录入xml中的指纹数据
* @date 2019/7/6
**/
@Override
@Transactional
public Boolean inputFingersByXml(String path,String compressionAlgorithm) throws XMLParseException, AuthenticationException {
FingerAndPalm fingerAndPalm = FingerXmlParse.parseFptx(path,compressionAlgorithm);
//指纹数据
List<? extends LedenCollectFinger> fingers = fingerAndPalm.getFingers();
if(fingers!=null&&fingers.size()>0){
//删除原有的指纹数据
String ryjcxxcjbh = fingers.get(0).getRyjcxxcjbh();
logger.info("第一条数据为:"+fingers.get(0).toString());
ledenCollectFingerMapper.deleteByPersonCode(ryjcxxcjbh,compressionAlgorithm);
fingers.forEach(x->x.setPkId(UUID.randomUUID().toString().replace("-","")));
ledenCollectFingerMapper.insertFingers(fingers);
}
//四指数据
List<LedenCollectFourfinger> fourfingers = fingerAndPalm.getFourfingers();
if(fourfingers!=null&& fourfingers.size()>0){
//删除数据
if (fourfingers.get(0).getRyjcxxcjbh() == null){
ledenCollectFourfingerMapper.deleteFourFingerByPersonId(fingers.get(0).getRyjcxxcjbh(),compressionAlgorithm);
}else {
ledenCollectFourfingerMapper.deleteFourFingerByPersonId(fourfingers.get(0).getRyjcxxcjbh(),compressionAlgorithm);
}
fourfingers.forEach(x-> {
x.setPkId(MathUtil.generateUUID());
if (x.getRyjcxxcjbh() == null){
x.setRyjcxxcjbh(fingers.get(0).getRyjcxxcjbh());
}
});
ledenCollectFourfingerMapper.insertBatch(fourfingers);
}
//掌纹数据
List<LedenCollectPalm> palms = fingerAndPalm.getPalms();
if(palms!=null&&palms.size()>0){
ledenCollectPalmMapper.deletePalmByPersonId(palms.get(0).getRyjcxxcjbh(),compressionAlgorithm);
palms.forEach(x->x.setPkId(MathUtil.generateUUID()));
ledenCollectPalmMapper.insertBatch(palms);
}
//全掌纹
List<LedenCollectFullpalm> fullpalms = fingerAndPalm.getFullpalms();
if(fullpalms!=null&&fullpalms.size()>0){
ledenCollectFullpalmMapper.deleteFullPalmByPersonId(fullpalms.get(0).getRyjcxxcjbh(),compressionAlgorithm);
fullpalms.forEach(x->x.setPkId(MathUtil.generateUUID()));
}
if(fullpalms!=null&&fullpalms.size()>0){
ledenCollectFullpalmMapper.insertBatch(fullpalms);
}
//指节纹
List<LedenCollectPhalange> phalanges = fingerAndPalm.getPhalanges();
if(phalanges!=null&&phalanges.size()>0){
//删除原有的指节纹数据
ledenCollectPhalangeMapper.deletePhalangeByPersonId(phalanges.get(0).getRyjcxxcjbh(),compressionAlgorithm);
phalanges.forEach(x->x.setPkId(MathUtil.generateUUID()));
}
if(phalanges!=null&&phalanges.size()>0){
ledenCollectPhalangeMapper.insertBatch(phalanges);
}
return true;
}
@Override
public Response selectFingerByPersonCode(String id) {
List<LedenCollectFinger> list = ledenCollectFingerMapper.selectFingerByPersonCode(id);
if (list == null || list.size() < 1) {
return ResponseUtil.returnError(ReturnCode.ERROR_05);
}
//BASE64Encoder base64Encoder = new BASE64Encoder();
//加密图片信息
list.stream().forEach(s -> {
//0是指纹采集为正常
/*if ("0".equals(s.getZzhwqsqkdm())) {
*//*String encode = base64Encoder.encode(s.getZwTxsj());
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("data:image/png;base64,");
stringBuilder.append(encode);
s.setZwzp(stringBuilder.toString());*//*
s.setZwzp(new String(s.getZwTxsj()));
s.setZwTxsj(null);
}*/
if (s.getZwTxsj() != null){
s.setZwzp(new String(s.getZwTxsj()));
s.setZwTxsj(null);
}
//添加状态码(供前端归类)
if (s.getZwzwdm() != null) {
s.setTypeCode(Integer.parseInt(s.getZwzwdm()));
}
});
return ResponseUtil.getResponseInfo(ReturnCode.SUCCESS, list);
}
/**
* 生成xml
*
* @return
*/
@Override
public Boolean generateXml(String cjrybh) throws IOException {
StringBuffer stringBuffer = new StringBuffer(cjrybh);
stringBuffer.append(".xml");
//生成文件夹
File fingerDirFile = new File(fingerDir);
if (!fingerDirFile.exists()) {
fingerDirFile.mkdirs();
}
//生成文件
File file = new File(fingerDir + File.separator + stringBuffer.toString());
//设置生成xml
OutputFormat format = OutputFormat.createCompactFormat();
//设置编码
format.setEncoding("UTF-8");
XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(file), format);
xmlWriter.setEscapeText(false); //关闭字符串中xml特殊字符转义
//查询出该人员的所有信息
List<LedenCollectFinger> ledenCollectFingers = ledenCollectFingerMapper.selectFingerByPersonCode(cjrybh);
xmlWriter.write(createDocument(ledenCollectFingers));
//将文件推送到ftp服务器
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftpConfig.getIp(), ftpConfig.getPort());
ftpClient.login(ftpConfig.getUser(), ftpConfig.getPassword());
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpConfig.getDir());
int reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return false;
}
String newFileName = new String(stringBuffer.toString().getBytes("UTF-8"), "iso-8859-1");
FileInputStream fileInputStream = new FileInputStream(file);
//上传文件
if (!ftpClient.storeFile(newFileName, fileInputStream)) {
return false;
}
fileInputStream.close();
ftpClient.logout();
return true;
}
@Override
public List<LedenCollectFinger> listFingerByConditions(String personCode, String compressionAlgorithm) {
return ledenCollectFingerMapper.listFingerByConditions(new HashMap<String,Object>(2){{put("personCode",personCode);put("compressionAlgorithm",compressionAlgorithm);}});
}
/**
* 生成document对象
*
* @return
*/
private Document createDocument(List<LedenCollectFinger> fingers) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement("root");
//生成头部
// Element head = root.addElement("head");
// head.addElement("EQUIPMENT_CODE");
// head.addElement("USER_CODE");
// head.addElement("USER_UNIT_CODE");
// head.addElement("RYJCXXCJBH");
//生成指纹列表
Element fingerlist = root.addElement("FINGERLIST");
for (int i = 0; i < 20; i++) {
//添加20个指纹节点
Element finger = fingerlist.addElement("FINGER");
if (fingers.get(i) != null) {
LedenCollectFinger fingerTemp=fingers.get(i);
finger.addElement("ZWZWDM").setText(setTxt(fingerTemp.getZwzwdm()));
finger.addElement("ZZHWQSQKDM").setText(setTxt(fingerTemp.getZzhwqsqkdm()));
finger.addElement("ZW_TXYSFFMS").setText(setTxt(fingerTemp.getZwTxysffms()));
finger.addElement("ZW_TXZL").setText(setTxt(fingerTemp.getZwTxzl()));
finger.addElement("ZW_TXSJ").setText(setTxt(fingerTemp.getZwTxsj()));
}
}
//掌纹列表
Element plamlist = root.addElement("PLAMLIST");
for (int i = 0; i < 4; i++) {
Element plam = plamlist.addElement("PLAM");
plam.addElement("ZHWZHWDM");
plam.addElement("ZHW_ZZHWQSQKDM");
plam.addElement("ZHW_TXYSFFMS");
plam.addElement("ZHW_TXZL");
plam.addElement("ZHW_TXSJ");
}
//四指纹列表
Element fourfingerlist = root.addElement("FOURFINGERLIST");
for (int i = 0; i < 2; i++) {
Element fourFinger = fourfingerlist.addElement("FOURFINGER");
fourFinger.addElement("SLZ_ZWZWDM");
fourFinger.addElement("SLZ_ZZHWQSQKDM");
fourFinger.addElement("SLZ_TXYSFFMS");
fourFinger.addElement("SLZ_TXZL");
fourFinger.addElement("SLZ_TXSJ");
}
//指节纹列表
Element phalangelist = root.addElement("PHALANGELIST");
//全掌纹列表
Element fullplamlist = root.addElement("FULLPLAMLIST");
for (int i = 0; i < 2; i++) {
Element fullPlam = fullplamlist.addElement("FULLPLAM");
fullPlam.addElement("QZ_ZHWZHWDM");
fullPlam.addElement("QZ_ZZHWQSQKDM");
fullPlam.addElement("QZ_TXYSFSMS");
fullPlam.addElement("QZ_TXZL");
fullPlam.addElement("QZ_TXSJ");
}
return document;
}
private String setTxt(Object object){
if(object==null)
return "";
else if(object instanceof String)
return object.toString();
else
return new String((byte[])object);
}
}
|
package in.kodecamp.web;
import java.util.Locale;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.mvc.Controller;
import javax.mvc.Models;
import javax.mvc.MvcContext;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
/**
* @author hantsy
*/
@Path("locale")
@Controller
@RequestScoped
public class LocaleController {
@Inject
MvcContext mvc;
@Inject
Models models;
@Inject
Logger log;
@GET
public String get() {
Locale locale = mvc.getLocale();
models.put("locale", locale);
return "locale.xhtml";
}
}
|
//package com.sprmvc.web.ch5.config;
//
//import com.sprmvc.web.ch5.filters.MyFilter;
//import com.sprmvc.web.ch5.services.AppConfig;
//import com.sprmvc.web.ch5.servlets.MyServlet;
//import org.springframework.context.annotation.ComponentScan;
//import org.springframework.web.WebApplicationInitializer;
//import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
//import org.springframework.web.servlet.DispatcherServlet;
//import org.springframework.web.servlet.ViewResolver;
////import org.springframework.web.servlet.view.tiles3.TilesConfigurer;
////import org.springframework.web.servlet.view.tiles3.TilesViewResolver;
//
//import javax.servlet.*;
//
//public class MyServletInitializer implements WebApplicationInitializer {
//
// @Override
// public void onStartup(ServletContext servletContext) throws ServletException {
// AnnotationConfigWebApplicationContext ctx =
// new AnnotationConfigWebApplicationContext();
// ctx.register(AppConfig.class);
// ctx.setServletContext(servletContext);
// ServletRegistration.Dynamic servlet =
// servletContext.addServlet("springDispatcherServlet",
// new DispatcherServlet(ctx));
//
// servlet.setLoadOnStartup(1);
// servlet.addMapping("/");
//
//
//
//// DispatcherServlet ds = new DispatcherServlet();
//// ServletRegistration.Dynamic dispatcher = servletContext.addServlet("appServletTwo", ds);
//// dispatcher.setLoadOnStartup(1);
//// dispatcher.addMapping("/");
//// dispatcher.addMapping("*.service");
//// ServletRegistration.Dynamic registration = servletContext.addServlet("appServlet", ds);
//// registration.addMapping("/");
//// registration.setMultipartConfig(
//// new MultipartConfigElement("/tmp/spittr/uploads"));
////
//// ServletRegistration.Dynamic myServlet =
//// servletContext.addServlet("myServlet", MyServlet.class);
//// myServlet.addMapping("/custom/**");
////
//// javax.servlet.FilterRegistration.Dynamic filter =
//// servletContext.addFilter("myFilter", MyFilter.class);
//// filter.addMappingForUrlPatterns(null, false, "/custom/**");
// }
//}
|
package com.kplibwork.libcommon;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import com.facebook.ads.AdError;
import java.util.Timer;
import java.util.TimerTask;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_INTERNAL_ERROR;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_NETWORK_ERROR;
import static com.google.android.gms.ads.AdRequest.ERROR_CODE_NO_FILL;
/**
* Created by saiful on 9/15/18.
*/
public class KPBannerController
{
private static final String TAG = KPBannerController.class.getName();
private Timer retryTimer;
public interface AdFailedToShowListener{
void onFailedToLoadAd();
}
public static class Builder {
private Context mCurrentContext; //This is important, so we'll pass it to the constructor.
private com.google.android.gms.ads.AdSize admobAdSize = com.google.android.gms.ads.AdSize.SMART_BANNER;
private com.facebook.ads.AdSize fanAdSize = com.facebook.ads.AdSize.BANNER_HEIGHT_50;
private View bannerHolder;
private long mAdRotationIntervalTime = 30000;
private String admob_banner_id;
private String fan_banner_id;
private String admob_app_id;
private int ad_rotation_policy = KPConstants.AD_ROTATION_POLICY_ON_FAIL;
private int ad_priority_policy = KPConstants.AD_PRIORITY_POLICY_ADMOB_FIRST;
private static final int DEFAULT_BANNER_RETRY_COUNT = 2;
private int mAdmobRetryCount = DEFAULT_BANNER_RETRY_COUNT;
private int mFanRetryCount = DEFAULT_BANNER_RETRY_COUNT;
private AdFailedToShowListener mAdFailedToShowListener;
private boolean mBothAd = false;
private boolean mAdmobOnly = false;
private boolean mFanOnly = false;
public Builder setAdFailedToShowListener(AdFailedToShowListener mAdFailedToShowListener) {
this.mAdFailedToShowListener = mAdFailedToShowListener;
return this;
}
public Builder(Context mCurrentContext) {
this.mCurrentContext = mCurrentContext;
}
public Builder setAdmobAppId(String admob_app_id){
this.admob_app_id = admob_app_id;
return this;
}
public Builder setAdmobBannerId(String admob_banner_id){
this.mAdmobOnly = true;
if(null!=fan_banner_id && fan_banner_id.length()>0){
this.mBothAd = true;
this.mAdmobOnly = false;
this.mFanOnly = false;
}
this.admob_banner_id = admob_banner_id;
//Log.d("Advertise", "setAdmobBanner " + admob_banner_id);
//Log.d("Advertise", "setAdmobBannerThis " + this.admob_banner_id);
return this;
}
public Builder setFanBannerId(String fan_banner_id){
this.mFanOnly = true;
if(null!=admob_banner_id && admob_banner_id.length()>0){
this.mBothAd = true;
this.mAdmobOnly = false;
this.mFanOnly = false;
}
this.fan_banner_id = fan_banner_id;
return this;
}
private boolean admobAd() throws Exception{
if(null==admob_banner_id || !(admob_banner_id.length()>0)){
throw new Exception("You need to setAdmobBannerId");
}else{
return true;
}
}
private boolean fanAd() throws Exception{
if(null==fan_banner_id || !(fan_banner_id.length()>0)){
throw new Exception("You need to setFanBannerId");
}else{
return true;
}
}
private boolean bothAd() throws Exception{
return (admobAd() && fanAd());
}
public Builder setShowAdmobOnly(boolean mAdmobOnly) throws Exception{
if(admobAd()){
this.mAdmobOnly = mAdmobOnly;
}
return this;
}
public Builder setShowFanOnly(boolean mFanOnly) throws Exception{
if(fanAd()){
this.mFanOnly = mFanOnly;
}
return this;
}
/*
default ad_priority_policy KPConstants.AD_PRIORITY_POLICY_ADMOB_FIRST
*/
public Builder setAdPriorityPolicy(int mAdPriorityPolicy) throws Exception{
if(!mBothAd){
throw new Exception("You need to setAdmobBannerId and setFanBannerId both");
}
this.ad_priority_policy = mAdPriorityPolicy;
return this;
}
public Builder setAdRotationPolicy(int mAdRotationPolicy) throws Exception{
if(!mBothAd){
throw new Exception("setAdRotationPolicy is valid only for both ad. You need to setAdmobBannerId and setFanBannerId both if you want to apply AdRotationPolicy. Also use setAdmobRetryCount setFanRetryCount to specify retry attempt if you use AD_ROTATION_POLICY_ON_FAIL, default is"+DEFAULT_BANNER_RETRY_COUNT+" ");
}
this.ad_rotation_policy = mAdRotationPolicy;
return this;
}
public Builder setAdRotationIntervalTime(long mAdRotationIntervalTime) throws Exception{
if(this.ad_rotation_policy!=KPConstants.AD_ROTATION_POLICY_TIME_INTERVAL){
throw new Exception("setAdRotationIntervalTime is valid when you set setAdRotationPolicy to AD_ROTATION_POLICY_TIME_INTERVAL.");
}
this.mAdRotationIntervalTime = mAdRotationIntervalTime;
return this;
}
public Builder setAdmobRetryCount(int mAdmobRetryCount) throws Exception{
if(!mBothAd){
throw new Exception("setAdmobRetryCount is valid only for both ad. You need to setAdmobBannerId and setFanBannerId both if you want to apply AdmobRetryCount");
}
this.mAdmobRetryCount = mAdmobRetryCount;
return this;
}
public Builder setFanRetryCount(int mFanRetryCount) throws Exception{
if(!mBothAd){
throw new Exception("setFanRetryCount is valid only for both ad. You need to setAdmobBannerId and setFanBannerId both if you want to apply FanRetryCount");
}
this.mFanRetryCount = mFanRetryCount;
return this;
}
public Builder setAdmobAdSize(com.google.android.gms.ads.AdSize admobAdSize) throws Exception{
if(admobAd()) {
this.admobAdSize = admobAdSize;
}
return this;
}
public Builder setFanAdSize(com.facebook.ads.AdSize fanAdSize) throws Exception{
if(fanAd()) {
this.fanAdSize = fanAdSize;
}
return this;
}
public Builder setBannerHolder(final View view) throws Exception{
if(!(view instanceof LinearLayout)){
throw new Exception("View is not a linear layout");
}
this.bannerHolder = view;
return this;
}
public KPBannerController build(){
//Here we create the actual bank account object, which is always in a fully initialised state when it's returned.
KPBannerController bannerController2 = new KPBannerController(); //Since the builder is in the BankAccount class, we can invoke its private constructor.
bannerController2.mCurrentContext = this.mCurrentContext;
bannerController2.admobAdSize = this.admobAdSize;
bannerController2.fanAdSize = this.fanAdSize;
bannerController2.bannerHolder = this.bannerHolder;
bannerController2.mAdRotationIntervalTime = this.mAdRotationIntervalTime;
bannerController2.admob_app_id = this.admob_app_id;
bannerController2.admob_banner_id = this.admob_banner_id;
bannerController2.fan_banner_id = this.fan_banner_id;
bannerController2.ad_rotation_policy = this.ad_rotation_policy;
bannerController2.mAdmobRetryCount = this.mAdmobRetryCount;
bannerController2.mFanRetryCount = this.mFanRetryCount;
bannerController2.mAdFailedToShowListener = this.mAdFailedToShowListener;
bannerController2.mBothAd = this.mBothAd;
bannerController2.mAdmobOnly = this.mAdmobOnly;
bannerController2.mFanOnly = this.mFanOnly;
bannerController2.ad_priority_policy = this.ad_priority_policy;
return bannerController2;
}
}
private Context mCurrentContext;
private com.google.android.gms.ads.AdSize admobAdSize = com.google.android.gms.ads.AdSize.SMART_BANNER;
private com.facebook.ads.AdSize fanAdSize = com.facebook.ads.AdSize.BANNER_HEIGHT_50;
private View bannerHolder;
private long mAdRotationIntervalTime = 30000;
private String admob_banner_id;
private String fan_banner_id;
private String admob_app_id;
private int ad_rotation_policy = KPConstants.AD_ROTATION_POLICY_ON_FAIL;
private int ad_priority_policy = KPConstants.AD_PRIORITY_POLICY_ADMOB_FIRST;
private static final int DEFAULT_BANNER_RETRY_COUNT = 2;
private int mAdmobRetryCount = DEFAULT_BANNER_RETRY_COUNT;
private int mFanRetryCount = DEFAULT_BANNER_RETRY_COUNT;
private int mAdmobRetryCounter = DEFAULT_BANNER_RETRY_COUNT;
private int mFanRetryCounter = DEFAULT_BANNER_RETRY_COUNT;
private AdFailedToShowListener mAdFailedToShowListener;
private boolean mBothAd = false;
private boolean mAdmobOnly = false;
private boolean mFanOnly = false;
private com.google.android.gms.ads.AdView admobAdView;
private com.facebook.ads.AdView fanAdView;
private Handler handler;
private Runnable mAdRunnable;
//Fields omitted for brevity.
private KPBannerController() {
//Constructor is now private.
this.handler = new Handler();
}
public void onBannerDestroy(){
try {
if(admobAdView!=null) {
admobAdView.setAdListener(null);
admobAdView.destroy();
admobAdView = null;
}
if(fanAdView!=null) {
fanAdView.setAdListener(null);
fanAdView.destroy();
fanAdView = null;
}
if(null!=mAdRunnable) {
handler.removeCallbacks(mAdRunnable);
}
mAdRunnable = null;
handler = null;
} catch (Exception e) {
}
}
public void onBannerPause(){
try {
if(admobAdView!=null) {
admobAdView.pause();
}
} catch (Exception e) {
// TODO: handle exception
}
}
public void onBannerResume(){
try {
if(admobAdView!=null) {
admobAdView.resume();
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void loadFanBannerAds(final View view){
if(null!=fanAdSize){
loadFanBannerAds(view, fanAdSize);
}else {
loadFanBannerAds(view, com.facebook.ads.AdSize.BANNER_HEIGHT_50);
}
}
private void loadFanBannerAds(final View view, final com.facebook.ads.AdSize mFanAdSize){
try {
LinearLayout adHolder = (LinearLayout)view;
adHolder.setGravity(Gravity.BOTTOM);
try {
if(fanAdView!=null) {
fanAdView.setAdListener(null);
fanAdView.destroy();
fanAdView = null;
}
}catch (Exception e){}
try {
if(admobAdView!=null) {
admobAdView.setAdListener(null);
admobAdView.destroy();
admobAdView = null;
}
}catch (Exception e){}
try {
adHolder.removeAllViews();
}catch (Exception e){}
if(KPUtils.isNetworkPresent(mCurrentContext)){
fanAdView = new com.facebook.ads.AdView(mCurrentContext,fan_banner_id, mFanAdSize);
fanAdView.setAdListener(new com.facebook.ads.AbstractAdListener() {
@Override
public void onError(com.facebook.ads.Ad ad, com.facebook.ads.AdError adError) {
fanAdView.destroy();
//Log.d("AD_TEST", "fan ad loading error: " + adError.getErrorMessage());
if(mBothAd && ad_rotation_policy == KPConstants.AD_ROTATION_POLICY_ON_FAIL) {
if(ad_priority_policy == KPConstants.AD_PRIORITY_POLICY_ADMOB_FIRST){
if(adError.getErrorCode() == AdError.NO_FILL_ERROR_CODE
|| adError.getErrorCode() == AdError.SERVER_ERROR_CODE
|| adError.getErrorCode() == AdError.INTERNAL_ERROR_CODE
|| adError.getErrorCode() == AdError.NETWORK_ERROR_CODE){
retryAfterGivenTime(view, true, KPConstants.THIRTY_SECONDS);
}else if(adError.getErrorCode() == AdError.LOAD_TOO_FREQUENTLY_ERROR_CODE){
KPConstants.SHOWING_FAN_LOAD_TOO_FREQUENTLY_ERROR = true;
retryAfterGivenTime(view, true, KPConstants.THIRTY_SECONDS);
retryAfterGivenTime(view, false, KPConstants.THIRTY_MINUTE);
}
}else{
KPBannerController.this.loadAdmobBannerAds(view);
}
}else if(null!=mAdFailedToShowListener) {
mAdFailedToShowListener.onFailedToLoadAd();
}
}
@Override
public void onAdLoaded(com.facebook.ads.Ad ad) {
//Log.d("AD_TEST", "fan ad loaded");
KPConstants.SHOWING_FAN_LOAD_TOO_FREQUENTLY_ERROR = false;
loadRunnables();
if(null!=handler && null!=mAdRunnable && ad_rotation_policy == KPConstants.AD_ROTATION_POLICY_TIME_INTERVAL) {
handler.removeCallbacks(mAdRunnable);
handler.postDelayed(mAdRunnable, mAdRotationIntervalTime);
}
}
@Override
public void onAdClicked(com.facebook.ads.Ad ad) {
}
});
adHolder.setGravity(Gravity.BOTTOM);
adHolder.addView(fanAdView);
fanAdView.loadAd();
}
}catch (Exception e){
e.printStackTrace();
}
}
private void loadAdmobBannerAds(final View view,com.google.android.gms.ads.AdSize mAdmobAdsize){
try {
final LinearLayout adholder = (LinearLayout)view;
adholder.setGravity(Gravity.BOTTOM);
try {
if(admobAdView!=null) {
admobAdView.setAdListener(null);
admobAdView.destroy();
admobAdView = null;
}
}catch (Exception e){}
try {
if(fanAdView!=null) {
fanAdView.setAdListener(null);
fanAdView.destroy();
fanAdView = null;
}
}catch (Exception e){}
try {
adholder.removeAllViews();
}catch (Exception e){}
if(KPUtils.isNetworkPresent(mCurrentContext)) {
admobAdView = new com.google.android.gms.ads.AdView(mCurrentContext);
admobAdView.setAdSize(mAdmobAdsize);
admobAdView.setAdListener(new com.google.android.gms.ads.AdListener() {
@Override
public void onAdClosed() {
super.onAdClosed();
}
@Override
public void onAdFailedToLoad(int errorCode) {
//Log.d("AD_TEST", "google ad error: "+errorCode);
admobAdView.destroy();
if(mBothAd && ad_rotation_policy == KPConstants.AD_ROTATION_POLICY_ON_FAIL) {
if(ad_priority_policy == KPConstants.AD_PRIORITY_POLICY_FAN_FIRST){
if((errorCode == ERROR_CODE_NO_FILL
|| errorCode == ERROR_CODE_NETWORK_ERROR
|| errorCode == ERROR_CODE_INTERNAL_ERROR) && !KPConstants.SHOWING_FAN_LOAD_TOO_FREQUENTLY_ERROR){
retryAfterGivenTime(view, false, KPConstants.THIRTY_SECONDS);
}else{
retryAfterGivenTime(view, true, KPConstants.THIRTY_SECONDS);
}
}else{
if(!KPConstants.SHOWING_FAN_LOAD_TOO_FREQUENTLY_ERROR){
KPBannerController.this.loadFanBannerAds(view);
}else{
retryAfterGivenTime(view, true, KPConstants.THIRTY_SECONDS);
}
}
}else if(null!=mAdFailedToShowListener) {
mAdFailedToShowListener.onFailedToLoadAd();
}
super.onAdFailedToLoad(errorCode);
}
@Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
@Override
public void onAdLoaded() {
//Log.d("AD_TEST", "google ad loaded");
loadRunnables();
if(null!=handler && null!=mAdRunnable && ad_rotation_policy == KPConstants.AD_ROTATION_POLICY_TIME_INTERVAL) {
handler.removeCallbacks(mAdRunnable);
handler.postDelayed(mAdRunnable, mAdRotationIntervalTime);
}
super.onAdLoaded();
}
@Override
public void onAdOpened() {
super.onAdOpened();
}
});
String admb = admob_banner_id;
// Start loading the ad in the background.
admobAdView.setAdUnitId(admb);
adholder.setGravity(Gravity.BOTTOM);
adholder.addView(admobAdView);
com.google.android.gms.ads.AdRequest adRequest = null;
adRequest = new com.google.android.gms.ads.AdRequest.Builder()
.addTestDevice(com.google.android.gms.ads.AdRequest.DEVICE_ID_EMULATOR)
.build();
admobAdView.loadAd(adRequest);
}
} catch (Exception e) {
// TODO: handle exception
}
}
private void loadAdmobBannerAds(final View view){
if(null!=admobAdSize){
loadAdmobBannerAds(view, admobAdSize);
}else {
loadAdmobBannerAds(view, com.google.android.gms.ads.AdSize.SMART_BANNER);
}
}
private void loadRunnables(){
if(ad_rotation_policy == KPConstants.AD_ROTATION_POLICY_TIME_INTERVAL) {
if(handler==null){
handler = new Handler();
}
if(mAdRunnable==null) {
mAdRunnable = new Runnable() {
public void run() {
if (mFanRetryCounter <= 0) {
mFanRetryCounter = mFanRetryCount;
}
if (mAdmobRetryCounter <= 0) {
mAdmobRetryCounter = mAdmobRetryCount;
}
onRequestBannerAds();
}
};
}
}
}
private void onRequestBannerAds(){
if(null!=handler && null!=mAdRunnable && ad_rotation_policy == KPConstants.AD_ROTATION_POLICY_TIME_INTERVAL){
handler.removeCallbacks(mAdRunnable);
handler.postDelayed(mAdRunnable, mAdRotationIntervalTime);
}
if(mAdmobOnly || (mBothAd && ad_priority_policy==KPConstants.AD_PRIORITY_POLICY_ADMOB_FIRST)){
KPBannerController.this.loadAdmobBannerAds(bannerHolder);
}else if(mFanOnly || (mBothAd && ad_priority_policy==KPConstants.AD_PRIORITY_POLICY_FAN_FIRST)){
KPBannerController.this.loadFanBannerAds(bannerHolder);
}else{
//Log.d(TAG,"No Ad");
}
}
private void loadBannerAds() throws Exception{
try {
com.google.android.gms.ads.MobileAds.initialize(mCurrentContext, admob_app_id);
}catch (Exception e){
Log.v(KPBannerController.class.getName(),"You need to setAdmobAppId (Optional).");
}
if(null==bannerHolder || !(bannerHolder instanceof LinearLayout)){
throw new Exception("BannerHolder view is not a linear layout, use setBannerHolder inside Builder");
}else {
loadRunnables();
onRequestBannerAds();
}
}
public void requestBannerAds() throws Exception{
loadBannerAds();
}
public class MyTimerTask extends TimerTask {
Runnable runnable;
MyTimerTask(Runnable runnable){
this.runnable = runnable;
}
@Override
public void run() {
if(runnable != null){
((Activity) mCurrentContext).runOnUiThread(runnable);
}
}
}
private void retryAfterGivenTime(final View view, final boolean isGoogleAd, final int givenTime) {
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
if (isGoogleAd) {
//Log.d("AD_TEST", "requesting admob banner ad");
KPBannerController.this.loadAdmobBannerAds(view);
} else {
//Log.d("AD_TEST", "requesting fan banner ad");
KPBannerController.this.loadFanBannerAds(view);
if(givenTime == KPConstants.THIRTY_MINUTE) KPConstants.SHOWING_FAN_LOAD_TOO_FREQUENTLY_ERROR = false;
}
} catch (Exception e) {}
}
};
startTimer(runnable, givenTime);
}
private void startTimer(Runnable runnable, int time){
try{
if(retryTimer == null){
retryTimer = new Timer("retryTimer", true);
}
TimerTask timerTask = new MyTimerTask(runnable);
retryTimer.schedule(timerTask, time);
}catch (Exception e){}
}
}
|
package com.webcloud.func.map;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import com.alibaba.fastjson.JSON;
import com.amap.api.services.core.PoiItem;
import com.webcloud.R;
import com.webcloud.manager.SystemManager;
import com.webcloud.manager.client.UserManager;
import com.webcloud.map.BaseMapActivity;
import com.webcloud.model.PoiInfo;
/**
* 设置家和公司页面。
*
* @author bangyue
* @version [版本号, 2013-11-29]
* @version [版本号, 2013-12-5]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class VehicleSetHomeCompanyActivity extends BaseMapActivity implements OnClickListener {
public static final String TAG = "VehicleSetHomeCompanyActivity";
/**设置家或公司的类型:3家/4公司*/
int searchType = 3;
private Button btnBack;
private TextView tvHome, tvCompany, tvHomeTitle, tvCompanyTitle;
private View laySetCompany, laySetHome;
private UserManager userMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.vehicle_home_company_set);
userMgr = SystemManager.getInstance(this).userMgr;
btnBack = (Button)findViewById(R.id.btnBack);
btnBack.setOnClickListener(this);
tvHome = (TextView)findViewById(R.id.tvHome);
tvCompany = (TextView)findViewById(R.id.tvCompany);
tvHomeTitle = (TextView)findViewById(R.id.tvHomeTitle);
tvCompanyTitle = (TextView)findViewById(R.id.tvCompanyTitle);
laySetCompany = findViewById(R.id.laySetCompany);
laySetHome = findViewById(R.id.laySetHome);
laySetHome.setOnClickListener(this);
laySetCompany.setOnClickListener(this);
Intent data = getIntent();
parseIntentData(data);
}
private void parseIntentData(Intent intent) {
searchType = intent.getIntExtra("searchType", 3);
if (searchType == 3) {
setHome();
} else {
setCompany();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null) {
parseIntentData(intent);
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnBack:
onBackPressed();
break;
//设置家的地址
case R.id.laySetHome: {
Intent intent = new Intent(this, VehiclePoiSearchActivity.class);
searchType = 3;
intent.putExtra("searchType", 3);
this.startActivityForResult(intent, 10);
}
break;
//设置公司地址
case R.id.laySetCompany: {
Intent intent = new Intent(this, VehiclePoiSearchActivity.class);
searchType = 4;
intent.putExtra("searchType", 4);
this.startActivityForResult(intent, 10);
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (data == null)
return;
if (requestCode == 10) {
PoiItem PoiItem = (PoiItem)data.getParcelableExtra("poiItem");
PoiInfo poi = new PoiInfo(PoiItem.getLatLonPoint(), PoiItem.getTitle(), PoiItem.getTitle(), null);
if (searchType == 3) {
userMgr.saveCache(UserManager.CACHE_HOME, JSON.toJSONString(poi));
userMgr.home = poi;
setHome();
} else if (searchType == 4) {
userMgr.saveCache(UserManager.CACHE_COMPANY, JSON.toJSONString(poi));
userMgr.company = poi;
setCompany();
}
}
}
/**
* 设置家位置
*
* @see [类、类#方法、类#成员]
*/
public void setHome() {
if (userMgr.home != null) {
tvHomeTitle.setText("修改家地址");
tvHome.setText(userMgr.home.getAddress());
} else {
tvHomeTitle.setText("家地址");
tvHome.setText("点击设置");
}
}
/**
* 设置公司位置
*
* @see [类、类#方法、类#成员]
*/
public void setCompany() {
if (userMgr.company != null) {
tvCompanyTitle.setText("修改公司地址");
tvCompany.setText(userMgr.company.getAddress());
} else {
tvCompanyTitle.setText("公司地址");
tvCompany.setText("点击设置");
}
}
}
|
import java.io.*;
import java.util.*;
import java.lang.*;
public class ReadFromFile{
public String read;
private Scanner x;
int aa;
int[] data = new int[6];
public void openFile(){
try{
x = new Scanner(new File("CarWashStats.txt"));
}
catch (Exception e){
System.out.println("there was an error reading from file");
}
}
public void readFile(){
try{
while(x.hasNext()){
String a = x.next(); // spend
String b = x.next(); // bad
String c = x.next(); // good
String d = x.next(); // super
String e = x.next(); // carswashed
String f = x.next(); // average
System.out.println("Cars washed: \t\t\t"+e);
System.out.println("Total spend: \t\t\t"+a);
System.out.println("Bad washes: \t\t\t"+b);
System.out.println("Good washes: \t\t\t"+c);
System.out.println("Super washes: \t\t\t"+d);
System.out.println("Average spend: \t\t"+f+"\n");
}
} catch (Exception e){
System.out.println("Nothing has been logged yet.");
}
}
public void closeFile(){
try{
x.close();
}catch (Exception e){
System.out.println("Could not close file because it doesnt excist.");
}
}
}
|
package com.fundwit.sys.shikra.authentication;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
public class RequestHelper {
public static boolean isPostLoginPath(ServerHttpRequest request, String loginPath) {
return HttpMethod.POST.equals(request.getMethod()) && loginPath!=null && loginPath.equals(request.getPath().value());
}
public static boolean isWithAuthorization(ServerHttpRequest request) {
return request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION);
}
public static boolean isBearerAuthorization(ServerHttpRequest request) {
String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
return authorization!=null && authorization.toLowerCase().startsWith("bearer ");
}
public static boolean isBasicAuthorization(ServerHttpRequest request) {
String authorization = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
return authorization!=null && authorization.toLowerCase().startsWith("basic ");
}
}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.net.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import javax.net.ssl.KeyManager;
import javax.net.ssl.X509ExtendedKeyManager;
import org.apache.commons.net.io.Util;
/**
* General KeyManager utilities
* <p>
* How to use with a client certificate:
*
* <pre>
* KeyManager km = KeyManagerUtils.createClientKeyManager("JKS",
* "/path/to/privatekeystore.jks","storepassword",
* "privatekeyalias", "keypassword");
* FTPSClient cl = new FTPSClient();
* cl.setKeyManager(km);
* cl.connect(...);
* </pre>
*
* If using the default store type and the key password is the same as the store password, these parameters can be omitted. <br>
* If the desired key is the first or only key in the keystore, the keyAlias parameter can be omitted, in which case the code becomes:
*
* <pre>
* KeyManager km = KeyManagerUtils.createClientKeyManager(
* "/path/to/privatekeystore.jks","storepassword");
* FTPSClient cl = new FTPSClient();
* cl.setKeyManager(km);
* cl.connect(...);
* </pre>
*
* @since 3.0
*/
public final class KeyManagerUtils {
private static class ClientKeyStore {
private final X509Certificate[] certChain;
private final PrivateKey key;
private final String keyAlias;
ClientKeyStore(final KeyStore ks, final String keyAlias, final String keyPass) throws GeneralSecurityException {
this.keyAlias = keyAlias;
this.key = (PrivateKey) ks.getKey(this.keyAlias, keyPass.toCharArray());
final Certificate[] certs = ks.getCertificateChain(this.keyAlias);
final X509Certificate[] x509certs = new X509Certificate[certs.length];
Arrays.setAll(x509certs, i -> (X509Certificate) certs[i]);
this.certChain = x509certs;
}
final String getAlias() {
return this.keyAlias;
}
final X509Certificate[] getCertificateChain() {
return this.certChain;
}
final PrivateKey getPrivateKey() {
return this.key;
}
}
private static class X509KeyManager extends X509ExtendedKeyManager {
private final ClientKeyStore keyStore;
X509KeyManager(final ClientKeyStore keyStore) {
this.keyStore = keyStore;
}
// Call sequence: 1
@Override
public String chooseClientAlias(final String[] keyType, final Principal[] issuers, final Socket socket) {
return keyStore.getAlias();
}
@Override
public String chooseServerAlias(final String keyType, final Principal[] issuers, final Socket socket) {
return null;
}
// Call sequence: 2
@Override
public X509Certificate[] getCertificateChain(final String alias) {
return keyStore.getCertificateChain();
}
@Override
public String[] getClientAliases(final String keyType, final Principal[] issuers) {
return new String[] { keyStore.getAlias() };
}
// Call sequence: 3
@Override
public PrivateKey getPrivateKey(final String alias) {
return keyStore.getPrivateKey();
}
@Override
public String[] getServerAliases(final String keyType, final Principal[] issuers) {
return null;
}
}
private static final String DEFAULT_STORE_TYPE = KeyStore.getDefaultType();
/**
* Create a client key manager which returns a particular key. Does not handle server keys. Uses the default store type and assumes the key password is the
* same as the store password. The key alias is found by searching the keystore for the first private key entry
*
* @param storePath the path to the keyStore
* @param storePass the keyStore password
* @return the customised KeyManager
* @throws IOException if there is a problem creating the keystore
* @throws GeneralSecurityException if there is a problem creating the keystore
*/
public static KeyManager createClientKeyManager(final File storePath, final String storePass) throws IOException, GeneralSecurityException {
return createClientKeyManager(DEFAULT_STORE_TYPE, storePath, storePass, null, storePass);
}
/**
* Create a client key manager which returns a particular key. Does not handle server keys. Uses the default store type and assumes the key password is the
* same as the store password
*
* @param storePath the path to the keyStore
* @param storePass the keyStore password
* @param keyAlias the alias of the key to use, may be {@code null} in which case the first key entry alias is used
* @return the customised KeyManager
* @throws IOException if there is a problem creating the keystore
* @throws GeneralSecurityException if there is a problem creating the keystore
*/
public static KeyManager createClientKeyManager(final File storePath, final String storePass, final String keyAlias)
throws IOException, GeneralSecurityException {
return createClientKeyManager(DEFAULT_STORE_TYPE, storePath, storePass, keyAlias, storePass);
}
/**
* Create a client key manager which returns a particular key. Does not handle server keys.
*
* @param ks the keystore to use
* @param keyAlias the alias of the key to use, may be {@code null} in which case the first key entry alias is used
* @param keyPass the password of the key to use
* @return the customised KeyManager
* @throws GeneralSecurityException if there is a problem creating the keystore
*/
public static KeyManager createClientKeyManager(final KeyStore ks, final String keyAlias, final String keyPass) throws GeneralSecurityException {
final ClientKeyStore cks = new ClientKeyStore(ks, keyAlias != null ? keyAlias : findAlias(ks), keyPass);
return new X509KeyManager(cks);
}
/**
* Create a client key manager which returns a particular key. Does not handle server keys.
*
* @param storeType the type of the keyStore, e.g. "JKS"
* @param storePath the path to the keyStore
* @param storePass the keyStore password
* @param keyAlias the alias of the key to use, may be {@code null} in which case the first key entry alias is used
* @param keyPass the password of the key to use
* @return the customised KeyManager
* @throws GeneralSecurityException if there is a problem creating the keystore
* @throws IOException if there is a problem creating the keystore
*/
public static KeyManager createClientKeyManager(final String storeType, final File storePath, final String storePass, final String keyAlias,
final String keyPass) throws IOException, GeneralSecurityException {
final KeyStore ks = loadStore(storeType, storePath, storePass);
return createClientKeyManager(ks, keyAlias, keyPass);
}
private static String findAlias(final KeyStore ks) throws KeyStoreException {
final Enumeration<String> e = ks.aliases();
while (e.hasMoreElements()) {
final String entry = e.nextElement();
if (ks.isKeyEntry(entry)) {
return entry;
}
}
throw new KeyStoreException("Cannot find a private key entry");
}
private static KeyStore loadStore(final String storeType, final File storePath, final String storePass)
throws KeyStoreException, IOException, GeneralSecurityException {
final KeyStore ks = KeyStore.getInstance(storeType);
FileInputStream stream = null;
try {
stream = new FileInputStream(storePath);
ks.load(stream, storePass.toCharArray());
} finally {
Util.closeQuietly(stream);
}
return ks;
}
private KeyManagerUtils() {
// Not instantiable
}
}
|
package com.ricex.cartracker.android.data.manager;
import com.j256.ormlite.stmt.QueryBuilder;
import com.ricex.cartracker.android.data.dao.RawReadingDao;
import com.ricex.cartracker.android.data.dao.RawTripDao;
import com.ricex.cartracker.android.data.entity.RawReading;
import com.ricex.cartracker.android.data.entity.RawTrip;
import java.sql.SQLException;
import java.util.List;
/**
* Created by Mitchell on 2016-10-28.
*/
public class RawTripManager extends ServerEntityManager<RawTrip> {
private RawTripDao tripDao;
private RawReadingDao readingDao;
public RawTripManager(RawTripDao tripDao, RawReadingDao readingDao) {
super(tripDao);
this.tripDao = tripDao;
this.readingDao = readingDao;
}
public List<RawTrip> getTripsWithUnsyncedReadings() {
try {
QueryBuilder<RawTrip, Long> queryBuilder = getQueryBuilder();
QueryBuilder<RawReading, Long> readingQb = readingDao.queryBuilder();
readingQb.where().eq(RawReading.PROPERTY_SYNCED_WITH_SERVER, false);
queryBuilder.join(readingQb);
return executeQuery(queryBuilder);
}
catch (SQLException e) {
logException("Failed to fetch trips with unsynced readings", e);
}
return null;
}
}
|
package com.tencent.mm.plugin.remittance.model;
import com.tencent.mm.protocal.c.xc;
import java.util.List;
public interface c {
void bW(List<xc> list);
}
|
package com.demo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class MyReceiver2 extends BroadcastReceiver{
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(context, "MyReceive2½ΣΚΥ΅½:"+action, 1000).show();
Log.i("MyReceive2","current priority is 20");
}
}
|
package com.nju.edu.cn.controller;
import com.alibaba.fastjson.JSON;
import com.nju.edu.cn.dao.ContractRepository;
import com.nju.edu.cn.dao.TradeRepository;
import com.nju.edu.cn.entity.Contract;
import com.nju.edu.cn.entity.Trade;
import com.nju.edu.cn.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;
/**
* Created by shea on 2018/9/8.
*/
@RestController
@RequestMapping(value = "/api/file", produces = "application/json;charset=UTF-8")
public class FileController {
private static Logger logger = LoggerFactory.getLogger(FileController.class);
@Autowired
private FileService fileService;
@Autowired
private ContractRepository contractRepository;
@GetMapping("/initFuturesUpdating")
public void initFuturesUpdating() {
logger.info("initFuturesUpdating");
// fileService.initFuturesUpdating("/Users/shea/Downloads/futures_updating.csv");
// fileService.initFuturesUpdating("/Users/shea/Downloads/updating.csv");
}
@GetMapping("/updateFuturesUpdating")
public void updateFuturesUpdating() {
logger.info("updateFuturesUpdating");
// fileService.updateFuturesUpdating("/Users/shea/Downloads/rate33.csv",33l);
// fileService.initFuturesUpdating("/Users/shea/Downloads/updating.csv");
}
@GetMapping("/insertFuturesUpdating")
public void insertFuturesUpdating() {
logger.info("insertFuturesUpdating");
// fileService.insertFuturesUpdating("/Users/shea/file/f297_300_303.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f333_336_339.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/futures_updating.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f67_68_69.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f97_98_99.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f124_125_126.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f55_56_57.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f58-61.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f62-64.csv");
// fileService.insertFuturesUpdating("/Users/shea/file/f65_66.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/54.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/51.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/48.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/45.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/42.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/30.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/24.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/36.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/39.csv");
// fileService.insertFuturesUpdating("/Users/shea/Downloads/21.csv");
// fileService.initFuturesUpdating("/Users/shea/Downloads/updating.csv");
}
@GetMapping("/initParams")
public void initParams() {
logger.info("initParams");
// fileService.initParams("/Users/shea/Downloads/params.csv");
// fileService.initParams("/Users/shea/file/(125,126)contract_back_test_params.csv");
// fileService.initParams("/Users/shea/file/contract_back_test_params(1).csv");
// fileService.initParams("/Users/shea/file/contract_back_test_params.csv");
// fileService.initParams("/Users/shea/Downloads/params2.csv");
}
@GetMapping("/initTrade")
public void initTrade() {
logger.info("initTrade");
// fileService.initTrade("/Users/shea/Downloads/trade_xu.csv");
// fileService.initContractBackTest("/Users/shea/Downloads/contract_back_test_xu.csv");
// fileService.initTrade("/Users/shea/Downloads/trade_li.csv");
// fileService.initContractBackTest("/Users/shea/Downloads/contract_back_test_li.csv");
}
@GetMapping("/resetYield")
public void resetYield() {
logger.info("resetYield");
// fileService.resetYield();
}
@GetMapping("/initSpotUpdating")
public void initSpotUpdating() {
logger.info("initFuturesUpdating");
// fileService.initFuturesUpdating("/Users/shea/Downloads/futures_updating.csv");
// fileService.initFuturesUpdating("/Users/shea/Downloads/updating.csv");
// fileService.initSpotUpdating("/Users/shea/Downloads/spot_upadting.csv");
}
@GetMapping("/insertContractBackTest")
public void insertContractBackTest(){
// fileService.initContractBackTest("/Users/shea/file/(125,126)contract_back_test.csv");
// fileService.initContractBackTest("/Users/shea/file/contract_back_test(1).csv");
}
@GetMapping("/test")
public void test(){
// List<Contract> contracts = contractRepository.findAll();
// contracts.forEach(contract -> {
// contract.setType(contract.getNearbyFutures().getType());
// });
// contractRepository.saveAll(contracts);
// List<Trade> trades = tradeRepository.findAll();
// trades.forEach(trade -> {
// trade.setType(trade.getContract().getNearbyFutures().getType());
// });
// tradeRepository.saveAll(trades);
}
}
|
package com.redbus.utils;
import org.apache.log4j.Logger;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeSuite;
import com.redbus.base.BaseClass;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
public class ExtentReport extends BaseClass {
public static final Logger log = Logger.getLogger(ExtentReport.class);
// for reports
public static ExtentReports extent;
public static ExtentTest extentTest;
// CREATING THE EXTENT REPORT
@BeforeSuite
public void setExtent() {
extent = new ExtentReports(CommonUtils.prop.getProperty("REPORT_PATH"));
}
// TAKING THE SCREENSHOTS FOR FAILED SCENARIOS
@AfterMethod
public void attachScreenshot(ITestResult result) {
if (result.getStatus() == ITestResult.FAILURE) {
String screenshotPath = Screenshots.takeScreenShot(driver, result.getName());
System.out.println(screenshotPath);
extentTest.log(LogStatus.FAIL, extentTest.addScreenCapture(screenshotPath));
log.info("Screenshot captured!! ");
} else if (result.getStatus() == ITestResult.SUCCESS) {
extentTest.log(LogStatus.PASS, "Test case passed successfully");
}
extent.endTest(extentTest);
}
@AfterMethod
public static void reportclose() {
extent.endTest(extentTest);
log.info("Report Generated");
}
// STOP THE REPORT GENERATION
@AfterSuite
public void endReport() {
extent.flush();
extent.close();
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* MChecktool generated by hbm2java
*/
public class MChecktool implements java.io.Serializable {
private MChecktoolId id;
public MChecktool() {
}
public MChecktool(MChecktoolId id) {
this.id = id;
}
public MChecktoolId getId() {
return this.id;
}
public void setId(MChecktoolId id) {
this.id = id;
}
}
|
public class CoffeeTest {
public static void main(String[] agrs) { // 데코레이터 패턴으로 코딩되어 있다! IOStream 또한 이렇게 데코레이터 패턴으로 코딩되어 있다
Coffee americano = new KenyaAmericano();
americano.brewing();
System.out.println();
Coffee kenyaLatte = new Latte(new KenyaAmericano());
kenyaLatte.brewing();
System.out.println();
Coffee kenyaMocha = new Mocha(new Latte(new KenyaAmericano())); // 데코레이터 패턴! ex) 보조 스트림(보조 스트림(기반 스트림))
kenyaMocha.brewing();
System.out.println();
Coffee etiopiaLatte = new Latte(new EtiopiaAmericano());
etiopiaLatte.brewing();
}
}
|
package com.imesne.office.excel.html;
import java.util.Collection;
import java.util.Map;
/**
* Created by liyd on 17/7/17.
*/
public class ExcelHtml {
private String beginFragment;
private String endFragment;
private String inlineStyle;
private Map<Integer, String> sheetHtmlMap;
public String getHtml() {
StringBuilder sb = new StringBuilder();
sb.append(beginFragment)
.append(inlineStyle);
for (String s : sheetHtmlMap.values()) {
sb.append(s).append(System.lineSeparator());
}
sb.append(endFragment);
return sb.toString();
}
public String getSheetHtml(int sheetNum) {
return sheetHtmlMap.get(sheetNum - 1);
}
public Collection<String> getSheetHtmls() {
return sheetHtmlMap.values();
}
public String getBeginFragment() {
return beginFragment;
}
public void setBeginFragment(String beginFragment) {
this.beginFragment = beginFragment;
}
public String getEndFragment() {
return endFragment;
}
public void setEndFragment(String endFragment) {
this.endFragment = endFragment;
}
public String getInlineStyle() {
return inlineStyle;
}
public void setInlineStyle(String inlineStyle) {
this.inlineStyle = inlineStyle;
}
public Map<Integer, String> getSheetHtmlMap() {
return sheetHtmlMap;
}
public void setSheetHtmlMap(Map<Integer, String> sheetHtmlMap) {
this.sheetHtmlMap = sheetHtmlMap;
}
}
|
package arrays.module;
import java.util.Scanner;
public class MinimumElement {
private static Scanner scnanner = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("Enter couunt");
int count = scnanner.nextInt();
scnanner.nextLine();
// int[] returnedArray = readInteger(count);
// int returnedInt = findMind(returnedArray);
// System.out.println("Min: "+returnedInt);
System.out.println(Integer.MAX_VALUE);
}
private static int[] readInteger(int count){
int[] array = new int[count];
for( int i = 0; i<array.length;i++){
System.out.println("Enter a Number");
int number = scnanner.nextInt();
scnanner.nextLine();
array[i] = number;
}
return array;
}
private static int findMind(int[] array){
int min = Integer.MAX_VALUE;
for(int i = 0; i<array.length;i++){
int value = array[i];
if(value < min){
min = value;
}
}
return min;
}
}
|
package org.oscii.corpus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Stream;
/**
* Indexed corpus.
*/
public class Corpus {
final Map<String, PostingList> postings = new HashMap<>();
final List<String[]> lines = new ArrayList<>();
final Tokenizer tokenizer;
private final static Logger log = LogManager.getLogger(Corpus.class);
public Corpus(Tokenizer tokenizer) {
this.tokenizer = tokenizer;
}
public void addLines(String path) throws IOException {
log.info("Loading corpus from {}", path);
Stream<String> newLines = Files.lines(Paths.get(path)).parallel();
addLines(newLines);
}
public void addLines(Stream<String> newLines) {
int start = lines.size();
newLines.map(tokenizer::tokenize).map(this::internAll).forEachOrdered(lines::add);
for (int i = start; i < lines.size(); i++) {
String[] tokens = lines.get(i);
for (int j = 0; j < tokens.length; j++) {
indexWord(tokens[j], i, j);
}
}
}
public int count(String word) {
return postings(word).size();
}
public PostingList postings(String word) {
return postings.getOrDefault(word, PostingList.EMPTY);
}
private String[] internAll(String[] strings) {
for (int i = 0; i < strings.length; i++) {
strings[i] = strings[i].intern();
}
return strings;
}
private void indexWord(String word, int line, int position) {
PostingList p = postings.getOrDefault(word, null);
if (p == null) {
p = new PostingList();
postings.put(word, p);
}
p.addPosting(line, position);
}
public Set<String> vocab() {
return postings.keySet();
}
}
|
package com.tencent.mm.plugin.sysvideo.ui.video;
import android.os.Message;
import com.tencent.mm.sdk.platformtools.ag;
class VideoRecorderPreviewUI$2 extends ag {
final /* synthetic */ VideoRecorderPreviewUI ouS;
VideoRecorderPreviewUI$2(VideoRecorderPreviewUI videoRecorderPreviewUI) {
this.ouS = videoRecorderPreviewUI;
}
public final void handleMessage(Message message) {
this.ouS.getWindow().setFlags(1024, 1024);
this.ouS.mController.hideTitleView();
}
}
|
package Domain.Effetti;
import Domain.Risorsa;
import java.io.Serializable;
/**
* Created by pietro on 18/05/17.
*/
public abstract class Effetto implements Serializable {
/**
* @param bonus
* @param malusRisorsa
* @return costo derivante dal malusRisorsa
* @apiNote per calcolare il malus derivante da malusAttivazioneBonus in fase di Attivazione
* @implSpec costo ritornato >=0
*/
public Risorsa applicaMalus(Risorsa bonus, Risorsa malusRisorsa){
Risorsa risultato = Risorsa.sub(bonus, malusRisorsa);
risultato=Risorsa.setNegToZero(risultato);
return risultato;
}
}
|
package com.chavhun.partlist.service;
import com.chavhun.partlist.dao.PartDao;
import com.chavhun.partlist.model.Part;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
import java.util.List;
@Service
public class PartServiceImpl implements PartService {
private PartDao partDao;
@Transactional
public void setPartDao(PartDao partDao) {
this.partDao = partDao;
}
@Transactional
public void addPart(Part part) {
partDao.addPart(part);
}
@Transactional
public void updatePart(Part part) {
partDao.updatePart(part);
}
@Transactional
public void removePart(int id) {
partDao.removePart(id);
}
@Transactional
public Part getPartById(int id) {
return partDao.getPartById(id);
}
@Transactional
public List<Part> listParts() {
return partDao.listParts();
}
}
|
package com.tencent.mm.ui.base;
import java.util.HashSet;
import java.util.Set;
public interface MMSlideDelView$d {
public static final Set<MMSlideDelView> kwC = new HashSet();
void a(MMSlideDelView mMSlideDelView, boolean z);
boolean aYk();
void aYl();
void aYm();
}
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.presenter.impl.security.model;
import seava.ad.domain.impl.security.AccessControl;
import seava.ad.domain.impl.security.AccessControlAsgn;
import seava.j4e.api.annotation.Ds;
import seava.j4e.api.annotation.DsField;
import seava.j4e.api.annotation.Param;
import seava.j4e.api.annotation.RefLookup;
import seava.j4e.api.annotation.RefLookups;
import seava.j4e.api.annotation.SortField;
import seava.j4e.presenter.impl.model.AbstractAuditable_Ds;
@Ds(entity = AccessControlAsgn.class, sort = {@SortField(field = AccessControlAsgn_Ds.f_asgnName)})
@RefLookups({@RefLookup(refId = AccessControlAsgn_Ds.f_accessControlId, namedQuery = AccessControl.NQ_FIND_BY_NAME, params = {@Param(name = "name", field = AccessControlAsgn_Ds.f_accessControl)})})
public class AccessControlAsgn_Ds
extends
AbstractAuditable_Ds<AccessControlAsgn> {
public static final String ALIAS = "ad_AccessControlAsgn_Ds";
public static final String f_asgnName = "asgnName";
public static final String f_queryAllowed = "queryAllowed";
public static final String f_updateAllowed = "updateAllowed";
public static final String f_importAllowed = "importAllowed";
public static final String f_exportAllowed = "exportAllowed";
public static final String f_accessControlId = "accessControlId";
public static final String f_accessControl = "accessControl";
@DsField
private String asgnName;
@DsField
private Boolean queryAllowed;
@DsField
private Boolean updateAllowed;
@DsField
private Boolean importAllowed;
@DsField
private Boolean exportAllowed;
@DsField(join = "left", path = "accessControl.id")
private String accessControlId;
@DsField(join = "left", path = "accessControl.name")
private String accessControl;
public AccessControlAsgn_Ds() {
super();
}
public AccessControlAsgn_Ds(AccessControlAsgn e) {
super(e);
}
public String getAsgnName() {
return this.asgnName;
}
public void setAsgnName(String asgnName) {
this.asgnName = asgnName;
}
public Boolean getQueryAllowed() {
return this.queryAllowed;
}
public void setQueryAllowed(Boolean queryAllowed) {
this.queryAllowed = queryAllowed;
}
public Boolean getUpdateAllowed() {
return this.updateAllowed;
}
public void setUpdateAllowed(Boolean updateAllowed) {
this.updateAllowed = updateAllowed;
}
public Boolean getImportAllowed() {
return this.importAllowed;
}
public void setImportAllowed(Boolean importAllowed) {
this.importAllowed = importAllowed;
}
public Boolean getExportAllowed() {
return this.exportAllowed;
}
public void setExportAllowed(Boolean exportAllowed) {
this.exportAllowed = exportAllowed;
}
public String getAccessControlId() {
return this.accessControlId;
}
public void setAccessControlId(String accessControlId) {
this.accessControlId = accessControlId;
}
public String getAccessControl() {
return this.accessControl;
}
public void setAccessControl(String accessControl) {
this.accessControl = accessControl;
}
}
|
package com.cjava.test;
import java.util.List;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.cjava.spring.service.Carrito;
//import com.cjava.spring.entity.Venta;
import com.cjava.spring.service.VentaService;
import com.cjava.spring.service.ServiceFactory;
public class VentaTest extends AbstractBaseUnitTest {
@Autowired
VentaService VentaService;
@Autowired
private ServiceFactory serviceFactory;
@Test
public void registrar() throws Exception {
//En el mapeo hibernate mediante anotaciones esta id automatico, ERROR SI SE PONE
// Long id = new Long(2);
// Venta Venta = new Venta("Carlos","raul","romani");
VentaService.grabarVenta(new Carrito());
// Assert.assertNotNull(Venta.getId());
}
}
|
package coffeeMaker;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class LightTest {
@Test
void testLedOff_Off_Correct() {
Light indicator = new Light();
indicator.off();
assertEquals("OFF", indicator.state);
}
@Test
void testLedCycle_On_Correct() {
Light indicator = new Light();
indicator.onCycleLight();
assertEquals("BLUE", indicator.state);
}
@Test
void testLedReady_On_Correct() {
Light indicator = new Light();
indicator.readyLight();
assertEquals("GREEN", indicator.state);
}
}
|
package io.bega.kduino.activities;
import android.app.Activity;
import android.os.Bundle;
import io.bega.kduino.fragments.help.UserSettingsFragment;
public class UserSettingsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new UserSettingsFragment()).commit();
}
}
|
/**
* @author ${Prashanth Thipparthi}
*/
package com.example.demo;
/*
* This class represents the parameters of the request body while adding an application
*/
public class AddApplicationParameters {
private String job_id;
private String candidate_id;
private String status;
/*Getters and Setters of the private variables*/
public String getJob_id() {
return job_id;
}
public void setJob_id(String job_id) {
this.job_id = job_id;
}
public String getCandidate_id() {
return candidate_id;
}
public void setCandidate_id(String candidate_id) {
this.candidate_id = candidate_id;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}
|
package c10.s01.t07;
import static org.junit.Assert.*;
import org.junit.Test;
public class StackTest {
Stack stack=new Stack(10);
@Test
public void test() throws Exception {
stack.push(10);
stack.push(20);
stack.push(30);
assertEquals(false, stack.isEmpty());
assertEquals(3, stack.size());
assertEquals(30, stack.pop());
assertEquals(20, stack.pop());
assertEquals(10, stack.pop());
assertEquals(0, stack.size());
assertEquals(true, stack.isEmpty());
}
}
|
package org.rebioma.server.services;
import java.util.ArrayList;
import java.sql.Connection;
import java.util.Date;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.rebioma.client.bean.RecordReview;
import org.rebioma.server.util.ManagedSession;
public class RecordReviewDbImpl implements RecordReviewDb {
/**
* The {@link Logger} for this class.
*/
private static final Logger log = Logger.getLogger(RecordReviewDbImpl.class);
public static final int UNLIMITED = -1;
public void clear() {
// Set<String> occIds = new HashSet<String>();
try {
Session session = ManagedSession.createNewSessionAndTransaction();
session.createQuery("delete RecordReview").executeUpdate();
// Criteria criteria = session.createCriteria(RecordReview.class);
// criteria.add(Restrictions.isNull("reviewedDate"));
// for (Object obj : criteria.list()) {
// RecordReview recordReview = (RecordReview) obj;
// session.delete(recordReview);
// occIds.add(recordReview.getOccurrenceId() + "");
// }
ManagedSession.commitTransaction(session);
} catch (RuntimeException re) {
log.error("error :" + re.getMessage() + " on clearWaitingReviews()", re);
throw re;
}
}
public boolean delete(RecordReview recordReview) {
Session session = ManagedSession.createNewSessionAndTransaction();
try {
//session.delete(recordReview);
delete(session,recordReview);
ManagedSession.commitTransaction(session);
return true;
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage() + " on delete(RecordReview)", re);
return false;
}
}
public boolean delete(Session session,RecordReview recordReview) {
try {
session.delete(recordReview);
return true;
} catch (RuntimeException re) {
log.error("error :" + re.getMessage() + " on delete(RecordReview)", re);
return false;
}
}
public RecordReview getRecordReview(int userId, int occurrenceId) {
Session session = ManagedSession.createNewSessionAndTransaction();
RecordReview recordReview = null;
try {
Criteria criteria = session.createCriteria(RecordReview.class);
criteria.add(Restrictions.eq("userId", userId));
criteria.add(Restrictions.eq("occurrenceId", occurrenceId));
recordReview = (RecordReview) criteria.uniqueResult();
ManagedSession.commitTransaction(session);
} catch (RuntimeException re) {
if(session!=null)
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage()
+ " on getRecordReview(userId, occurrenceId)", re);
throw re;
}
return recordReview;
}
public List<Integer> getRecordReviewOccIds(int userId, Boolean reviewed) {
Session session = ManagedSession.createNewSessionAndTransaction();
RecordReview recordReview = null;
try {
String queryString = "select occurrenceId from RecordReview r where r.userId="
+ userId + " and r.reviewed";
if (reviewed == null) {
queryString += " is null";
} else {
queryString += "=" + reviewed;
}
Query query = session.createQuery(queryString);
List<Integer> result = query.list();
ManagedSession.commitTransaction(session);
return result;
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage()
+ " on getRecordReview(userId, occurrenceId)", re);
throw re;
}
}
public List<RecordReview> getRecordReviewsByOcc(int occurrenceId) {
return findByProperty("occurrenceId", occurrenceId);
}
public List<RecordReview> getRecordReviewsByOcc(Session session,int occurrenceId) {
return findByProperty(session,"occurrenceId", occurrenceId);
}
public List<RecordReview> getRecordReviewsByUser(int userId) {
return findByProperty("userId", userId);
}
public RecordReview reviewedRecord(int userId, int occurrenceId,
boolean reviewed) {
Session session = ManagedSession.createNewSessionAndTransaction();
try {
RecordReview recordReview = getRecordReview(userId, occurrenceId);
recordReview.setReviewed(reviewed);
recordReview.setReviewedDate(new Date());
session.update(recordReview);
// List<RecordReview> recordReviews = getRecordReviewsByOcc(occurrenceId);
ManagedSession.commitTransaction(session);
OccurrenceDb occurrenceDb = DBFactory.getOccurrenceDb();
boolean isChanged = occurrenceDb.checkForReviewedChanged(occurrenceId);
if (isChanged) {
return recordReview;
} else {
return null;
}
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage() + " on update(RecordReview)", re);
throw re;
} catch (Exception e) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + e.getMessage() + " on update(RecordReview)", e);
throw new RuntimeException(e.getMessage(), e);
}
}
public RecordReview reviewedRecord(int userId, int occurrenceId,
boolean reviewed, Date date) {
Session session = ManagedSession.createNewSessionAndTransaction();
try {
RecordReview recordReview = getRecordReview(userId, occurrenceId);
recordReview.setReviewed(reviewed);
recordReview.setReviewedDate(date);
session.update(recordReview);
// List<RecordReview> recordReviews = getRecordReviewsByOcc(occurrenceId);
ManagedSession.commitTransaction(session);
OccurrenceDb occurrenceDb = DBFactory.getOccurrenceDb();
boolean isChanged = occurrenceDb.checkForReviewedChanged(occurrenceId);
if (isChanged) {
return recordReview;
} else {
return null;
}
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage() + " on update(RecordReview)", re);
throw re;
} catch (Exception e) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + e.getMessage() + " on update(RecordReview)", e);
throw new RuntimeException(e.getMessage(), e);
}
}
public RecordReview save(RecordReview recordReview) {
Session session = ManagedSession.createNewSessionAndTransaction();
try {
recordReview = save(recordReview, session);
ManagedSession.commitTransaction(session);
return recordReview;
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage() + " on save(RecordReview)", re);
throw re;
}
}
public RecordReview save(RecordReview recordReview, Session session) {
RecordReview existenceRecordReview = getRecordReview(recordReview
.getUserId(), recordReview.getOccurrenceId());
if (existenceRecordReview == null) {
session.save(recordReview);
} else {
recordReview = null;
}
return recordReview;
}
public RecordReview update(RecordReview recordReview) {
Session session = ManagedSession.createNewSessionAndTransaction();
try {
session.update(recordReview);
ManagedSession.commitTransaction(session);
return recordReview;
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage() + " on update(RecordReview)", re);
throw re;
}
}
protected List<RecordReview> findByProperty(String property, Object value) {
Session session = ManagedSession.createNewSessionAndTransaction();
List<RecordReview> recordReviews = null;
try {
/*Criteria criteria = session.createCriteria(RecordReview.class).add(
Restrictions.eq(property, value));
recordReviews = criteria.list();*/
recordReviews = findByProperty(session, property, value);
ManagedSession.commitTransaction(session);
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage()
+ " on findByProperty(property, value)", re);
throw re;
}
return recordReviews;
}
protected List<RecordReview> findByProperty(Session session, String property, Object value) {
List<RecordReview> recordReviews = null;
try {
Criteria criteria = session.createCriteria(RecordReview.class).add(
Restrictions.eq(property, value));
recordReviews = criteria.list();
} catch (RuntimeException re) {
throw re;
}
return recordReviews;
}
public List<RecordReview> findByProperty() {
Session session = ManagedSession.createNewSessionAndTransaction();
List<RecordReview> recordReviews = null;
try {
Criteria criteria = session.createCriteria(RecordReview.class);
recordReviews = criteria.list();
ManagedSession.commitTransaction(session);
} catch (RuntimeException re) {
ManagedSession.rollbackTransaction(session);
log.error("error :" + re.getMessage()
+ " on findByProperty(property, value)", re);
throw re;
}
return recordReviews;
}
public List<RecordReview> findByProperty(Object value,List<RecordReview> RecordReviews) {
List<RecordReview> recordReviews =new ArrayList<RecordReview>();
for(RecordReview rv : RecordReviews){
if(rv.getOccurrenceId().equals(value))recordReviews.add(rv);
}
return recordReviews;
}
}
|
package net.sourceforge.vrapper.vim.commands.motions;
import net.sourceforge.vrapper.platform.TextContent;
import net.sourceforge.vrapper.vim.commands.BorderPolicy;
public class LineEndMotion extends AbstractModelSideMotion {
private final BorderPolicy borderPolicy;
public LineEndMotion(BorderPolicy borderPolicy) {
this.borderPolicy = borderPolicy;
}
public BorderPolicy borderPolicy() {
return borderPolicy;
}
@Override
protected int destination(int modelOffset, TextContent modelContent, int count) {
return getDestination(modelOffset, modelContent, count);
}
public static int getDestination(int modelOffset, TextContent content, int count) {
int currentLine = content.getLineInformationOfOffset(modelOffset).getNumber();
int lineCount = content.getNumberOfLines();
int lineNo = Math.min(lineCount, currentLine + count - 1);
return content.getLineInformation(lineNo).getEndOffset();
}
}
|
package de.jmda.gen.java.impl;
import java.util.ArrayList;
import java.util.List;
import de.jmda.gen.Generator;
import de.jmda.gen.impl.AbstractCompoundGenerator;
import de.jmda.gen.java.AnnotationStatementGenerator;
import de.jmda.gen.java.AnnotationStatementsGenerator;
import de.jmda.gen.java.DeclarationGenerator;
import de.jmda.gen.java.JavaDocGenerator;
/**
* Sets component separator to {@link System#lineSeparator()}. Maintains a
* <ul>
* <li>{@link #javaDocGenerator} and an</li>
* <li>{@link #annotationStatementsGenerator}.</li>
* </ul>
*
* @author ruu.jmda@gmail.com
*/
public abstract class AbstractDeclarationGenerator
extends AbstractCompoundGenerator
implements DeclarationGenerator
{
private JavaDocGenerator javaDocGenerator;
private AnnotationStatementsGenerator annotationStatementsGenerator;
/**
* Sets separator for component generation process to {@link
* System#lineSeparator()}.
*
* @see #getGeneratorComponents()
* @see #generate()
* @see #setComponentSeparator(String)
*/
public AbstractDeclarationGenerator()
{
super();
setComponentSeparator(System.lineSeparator());
}
/**
* @return collection of <code>Generator</code>s with the return values of the
* following methods in the following order:
* <ul>
* <li>{@link #getJavaDocGenerator()}</li>
* <li>{@link #getAnnotationStatementsGenerator()}</li>
* <li>{@link #getDeclaredElementGenerator()}</li>
* </ul>
*
* @see de.jmda.gen.CompoundGenerator#getGeneratorComponents()
*/
@Override
public final List<Generator> getGeneratorComponents()
{
List<Generator> result = new ArrayList<Generator>();
result.add(getJavaDocGenerator());
result.add(getAnnotationStatementsGenerator());
result.add(getDeclaredElementGenerator());
return result;
}
/**
* @return {@link #javaDocGenerator}, may be <code>null</code> because
* documentation is optional
*
* @see de.jmda.gen.java.DeclarationGenerator#getJavaDocGenerator()
*/
@Override
public JavaDocGenerator getJavaDocGenerator()
{
return javaDocGenerator;
}
@Override
public void setJavaDocGenerator(JavaDocGenerator javaDocGenerator)
{
this.javaDocGenerator = javaDocGenerator;
}
@Override
public JavaDocGenerator demandJavaDocGenerator()
{
if (javaDocGenerator == null)
{
javaDocGenerator = new DefaultJavaDocGenerator();
}
return javaDocGenerator;
}
/**
* @return {@link #annotationStatementsGenerator}, may be <code>null</code>
* because annotations are optional (in general)
*
* @see de.jmda.gen.java.DeclarationGenerator#getAnnotationStatementsGenerator()
*/
@Override
public AnnotationStatementsGenerator getAnnotationStatementsGenerator()
{
return annotationStatementsGenerator;
}
@Override
public void setAnnotationStatementsGenerator(
AnnotationStatementsGenerator annotationStatementsGenerator)
{
this.annotationStatementsGenerator = annotationStatementsGenerator;
}
@Override
public AnnotationStatementsGenerator demandAnnotationStatementsGenerator()
{
if (annotationStatementsGenerator == null)
{
annotationStatementsGenerator = new DefaultAnnotationStatementsGenerator();
}
return annotationStatementsGenerator;
}
/**
* Convenience method to add an <code>AnnotationStatementGenerator</code> to
* <code>AnnotationStatementGenerator</code>s in {@link
* #getAnnotationStatementsGenerator()}.
*
* @param annotationStatementGenerator
*/
public void add(AnnotationStatementGenerator annotationStatementGenerator)
{
getAnnotationStatementsGenerator().getAnnotationStatementGenerators()
.add(annotationStatementGenerator);
}
}
|
package edu.ap.facilitytoolspringboot.repositories;
import edu.ap.facilitytoolspringboot.models.ExternalFirm;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ExternalFirmRepository extends MongoRepository<ExternalFirm, String> {
}
|
package cn.creable.android.demo;
import android.graphics.Canvas;
import android.widget.Toast;
import cn.creable.gridgis.controls.App;
import cn.creable.gridgis.controls.IMapTool;
import cn.creable.gridgis.controls.MapControl;
import cn.creable.gridgis.geometry.Point;
import cn.creable.gridgis.shapefile.Selector;
public class PointTool implements IMapTool {
public MapControl mapControl;
public Selector selector;
private boolean isSelecting;
public PointTool(MapControl mapControl)
{
this.mapControl=mapControl;
selector=new Selector(mapControl);
selector.setMode(1);
selector.setOffset(0, 100);
isSelecting=true;
}
@Override
public void action() {
// TODO Auto-generated method stub
}
@Override
public void draw(Canvas g) {
if (isSelecting)
selector.draw(g);
}
@Override
public boolean keyPressed(int arg0) {
if (isSelecting) selector.keyPressed(arg0);
return false;
}
@Override
public void pointerDragged(int x, int y,int x2,int y2) {
if (isSelecting) selector.pointerDragged(x, y, x2, y2);
}
@Override
public void pointerPressed(int x, int y,int x2,int y2) {
if (isSelecting) selector.pointerPressed(x, y, x2, y2);
}
@Override
public void pointerReleased(int x, int y,int x2,int y2) {
if (isSelecting)
{
selector.pointerReleased(x, y, x2, y2);
x=selector.getX();
y=selector.getY();
selector.reset();
}
Point pt=new Point();
mapControl.getDisplay().getDisplayTransformation().toMapPoint(new Point(x,y), pt);
Toast.makeText(App.getInstance(), String.format("µØÍ¼×ø±êx=%f,y=%f", pt.getX(),pt.getY()), Toast.LENGTH_SHORT).show();
Point[] pts=new Point[1];
pts[0]=pt;
String[] ts=new String[1];
ts[0]="²âÊÔ";
MyCustomDraw mcd=new MyCustomDraw(mapControl,pts,ts,null);
mapControl.setCustomDraw(mcd);
mapControl.refresh();
}
}
|
package rhtn_homework;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class BOJ_1809_점프 {
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int n = Integer.parseInt(br.readLine());
int[][] map = new int[n][n];
long[][] dp = new long[n][n];
for (int i = 0; i < map.length; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < map[i].length; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
dp[0][0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int len = map[i][j];
if(len == 0 || dp[i][j] == 0) {
continue;
}
int down = i+ len;
int right = j+ len;
if(down < n) {
dp[down][j]+=dp[i][j];
}
if(right < n) {
dp[i][right]+=dp[i][j];
}
}
}
// for (int i = 0; i < dp.length; i++) {
// System.out.println(Arrays.toString(dp[i]));
// }
System.out.println(dp[n-1][n-1]);
}
public static class Pair {
int r, c;
public Pair(int r, int c) {
super();
this.r = r;
this.c = c;
}
@Override
public String toString() {
return "Pair [r=" + r + ", c=" + c + "]";
}
}
}
|
/*
* Copyright (c) 2010 University of Tartu
*/
package org.jpmml.xjc;
import java.util.*;
import com.sun.codemodel.*;
import com.sun.tools.xjc.*;
import com.sun.tools.xjc.model.*;
import com.sun.tools.xjc.outline.*;
import org.xml.sax.*;
public class ValueConstructorPlugin extends Plugin {
private boolean ignoreAttributes = false;
private boolean ignoreElements = false;
private boolean ignoreValues = false;
@Override
public String getOptionName(){
return "XvalueConstructor";
}
@Override
public String getUsage(){
return null;
}
@Override
public int parseArgument(Options options, String[] args, int i){
int result = 0;
String prefix = ("-" + getOptionName());
for(int j = i; j < args.length; j++, result++){
String arg = args[j];
if(prefix.equals(arg)){
// Ignored
} else
if((prefix + ":" + "ignoreAttributes").equals(arg)){
setIgnoreAttributes(true);
} else
if((prefix + ":" + "ignoreElements").equals(arg)){
setIgnoreElements(true);
} else
if((prefix + ":" + "ignoreValues").equals(arg)){
setIgnoreValues(true);
} else
{
break;
}
}
return result;
}
@Override
@SuppressWarnings (
value = {"unused"}
)
public boolean run(Outline outline, Options options, ErrorHandler errorHandler){
Collection<? extends ClassOutline> clazzes = outline.getClasses();
for(ClassOutline clazz : clazzes){
List<JFieldVar> superClassFields = getSuperClassFields(clazz);
List<JFieldVar> classFields = getClassFields(clazz);
if(superClassFields.size() > 0 || classFields.size() > 0){
JMethod defaultConstructor = (clazz.implClass).constructor(JMod.PUBLIC);
JInvocation defaultSuperInvocation = defaultConstructor.body().invoke("super");
// XXX
defaultConstructor.annotate(Deprecated.class);
JMethod valueConstructor = (clazz.implClass).constructor(JMod.PUBLIC);
JInvocation valueSuperInvocation = valueConstructor.body().invoke("super");
for(JFieldVar superClassField : superClassFields){
JVar param = valueConstructor.param(JMod.FINAL, superClassField.type(), superClassField.name());
valueSuperInvocation.arg(param);
}
for(JFieldVar classField : classFields){
JVar param = valueConstructor.param(JMod.FINAL, classField.type(), classField.name());
valueConstructor.body().assign(JExpr.refthis(param.name()), param);
}
}
}
return true;
}
private List<JFieldVar> getSuperClassFields(ClassOutline clazz){
List<JFieldVar> result = new ArrayList<JFieldVar>();
for(ClassOutline superClazz = clazz.getSuperClass(); superClazz != null; superClazz = superClazz.getSuperClass()){
result.addAll(0, getValueFields(superClazz));
}
return result;
}
private List<JFieldVar> getClassFields(ClassOutline clazz){
return getValueFields(clazz);
}
private List<JFieldVar> getValueFields(ClassOutline clazz){
List<JFieldVar> result = new ArrayList<JFieldVar>();
FieldOutline[] fields = clazz.getDeclaredFields();
for(FieldOutline field : fields){
CPropertyInfo propertyInfo = field.getPropertyInfo();
if(propertyInfo.isCollection()){
continue;
}
JFieldVar fieldVar = (clazz.implClass.fields()).get(propertyInfo.getName(false));
if((fieldVar.mods().getValue() & JMod.STATIC) == JMod.STATIC){
continue;
} // End if
if(propertyInfo instanceof CAttributePropertyInfo && !getIgnoreAttributes()){
CAttributePropertyInfo attributePropertyInfo = (CAttributePropertyInfo)propertyInfo;
if(attributePropertyInfo.isRequired()){
result.add(fieldVar);
}
} // End if
if(propertyInfo instanceof CElementPropertyInfo && !getIgnoreElements()){
CElementPropertyInfo elementPropertyInfo = (CElementPropertyInfo)propertyInfo;
if(elementPropertyInfo.isRequired()){
result.add(fieldVar);
}
} // End if
if(propertyInfo instanceof CValuePropertyInfo && !getIgnoreValues()){
{
result.add(fieldVar);
}
}
}
return result;
}
public boolean getIgnoreAttributes(){
return this.ignoreAttributes;
}
private void setIgnoreAttributes(boolean ignoreAttributes){
this.ignoreAttributes = ignoreAttributes;
}
public boolean getIgnoreElements(){
return this.ignoreElements;
}
private void setIgnoreElements(boolean ignoreElements){
this.ignoreElements = ignoreElements;
}
public boolean getIgnoreValues(){
return this.ignoreValues;
}
private void setIgnoreValues(boolean ignoreValues){
this.ignoreValues = ignoreValues;
}
}
|
package com.example.appfootball;
import com.example.appfootball.adapters.NewEventDetailsArrayAdapter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class EventDetailsNew extends Fragment {
String[] newEventName = { "First Event", "Second Event", "Third Event" };
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater
.inflate(R.layout.events_fragment, container, false);
ListView lv = (ListView) view.findViewById(R.id.lvEvents);
NewEventDetailsArrayAdapter nEAdapter = new NewEventDetailsArrayAdapter(
getActivity(), newEventName);
lv.setAdapter(nEAdapter);
return view;
}
}
|
package com.onplan.service;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.common.collect.Range;
import com.onplan.adviser.AdviserPredicateInfo;
import com.onplan.adviser.AlertInfo;
import com.onplan.adviser.TemplateInfo;
import com.onplan.adviser.alert.Alert;
import com.onplan.adviser.alert.AlertEvent;
import com.onplan.adviser.predicate.AdviserPredicate;
import com.onplan.adviser.predicate.pricevalue.PriceValuePredicate;
import com.onplan.dao.TestingAlertConfigurationDao;
import com.onplan.domain.configuration.AdviserPredicateConfiguration;
import com.onplan.domain.configuration.AlertConfiguration;
import com.onplan.domain.transitory.PriceTick;
import com.onplan.service.impl.AlertServiceImpl;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import static com.google.common.collect.Iterables.size;
import static com.onplan.adviser.AdviserConfigurationFactory.createAlertConfiguration;
import static com.onplan.adviser.alert.TestingAlertConfigurationFactory.createSampleAlertConfigurationWithNullId;
import static com.onplan.adviser.predicate.AdviserPredicateUtil.createAdviserPredicateTemplateInfo;
import static com.onplan.adviser.predicate.TestingAdviserPredicateUtils.checkAdviserPredicate;
import static com.onplan.domain.TestingPriceFactory.createPriceTicks;
import static com.onplan.util.TestingConstants.*;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
public class AlertServiceImplTest {
private AlertServiceImpl alertService;
private InstrumentSubscriptionListener instrumentSubscriptionListener;
private EventNotificationService eventNotificationService;
private TestingAlertConfigurationDao alertConfigurationDao;
@Before
public void init() throws Exception {
instrumentSubscriptionListener = mock(InstrumentSubscriptionListener.class);
eventNotificationService = mock(EventNotificationService.class);
alertConfigurationDao = new TestingAlertConfigurationDao();
alertService = new AlertServiceImpl();
alertService.setAlertConfigurationDao(alertConfigurationDao);
alertService.setInstrumentSubscriptionListener(instrumentSubscriptionListener);
alertService.setEventNotificationService(eventNotificationService);
alertService.setHistoricalPriceService(new TestingHistoricalPriceService());
alertService.setInstrumentService(new TestingInstrumentService());
}
@Test
public void getAlerts() throws Exception {
alertService.loadAllAlerts();
List<Alert> alerts = alertService.getAlerts();
assertTrue(!alerts.isEmpty());
for (Alert alert : alerts) {
assertValidAlert(alert);
}
assertEquals(alerts.size(), alertConfigurationDao.findAll().size());
}
@Test
public void testHasAlertsBeforeInitialization() throws Exception {
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
}
@Test
public void testHasAlertsAfterInitialization() throws Exception {
alertService.loadAllAlerts();
assertTrue(alertService.hasAlerts());
}
@Test
public void testHasAlertsAfterRemoveAll() throws Exception {
alertService.loadAllAlerts();
for (Alert alert : alertService.getAlerts()) {
alertService.removeAlert(alert.getId());
}
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
}
@Test
public void testHasAlertsAfterUnloadAll() throws Exception {
alertService.loadAllAlerts();
alertService.unLoadAllAlerts();
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
}
@Test
public void testLoadAllAlerts() throws Exception {
alertService.loadAllAlerts();
assertTrue(alertService.hasAlerts());
assertTrue(!alertService.getAlerts().isEmpty());
for (String instrumentId : INSTRUMENT_IDS) {
verify(instrumentSubscriptionListener, times(1))
.onInstrumentSubscriptionRequest(instrumentId);
}
for (String instrumentId : INSTRUMENT_IDS) {
verify(instrumentSubscriptionListener, never())
.onInstrumentUnSubscriptionRequest(instrumentId);
}
}
@Test
public void testUnLoadAllAlerts() throws Exception {
alertService.loadAllAlerts();
reset(instrumentSubscriptionListener);
alertService.unLoadAllAlerts();
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
for (String instrumentId : INSTRUMENT_IDS) {
verify(instrumentSubscriptionListener, never())
.onInstrumentSubscriptionRequest(instrumentId);
}
for (String instrumentId : INSTRUMENT_IDS) {
verify(instrumentSubscriptionListener, times(1))
.onInstrumentUnSubscriptionRequest(instrumentId);
}
}
@Test
public void testRemoveAlertAfterInitialization() throws Exception {
alertService.loadAllAlerts();
Alert alertToRemove = alertService.getAlerts()
.stream()
.findFirst()
.get();
assertValidAlert(alertToRemove);
assertTrue(alertService.removeAlert(alertToRemove.getId()));
assertTrue(alertService.getAlerts()
.stream()
.noneMatch(alert -> alertToRemove.getId().equals(alert.getId())));
assertTrue(alertService.hasAlerts());
}
@Test
public void testRemoveAlertAfterUnloadAll() throws Exception {
alertService.loadAllAlerts();
alertService.unLoadAllAlerts();
assertTrue(!alertService.removeAlert(DEFAULT_ALERT_ID));
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
}
@Test
public void testRemoveAlertWhenEmpty() throws Exception {
assertTrue(!alertService.removeAlert(DEFAULT_ALERT_ID));
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
}
@Test
public void testRemoveSingleAlert() throws Exception {
AlertConfiguration alertConfiguration = createSampleAlertConfigurationWithNullId();
alertService.addAlert(alertConfiguration);
Alert alert = alertService.getAlerts()
.stream()
.findFirst()
.get();
assertTrue(alertConfigurationDao.findAll().stream()
.anyMatch(record -> alert.getId().equals(record.getId())));
assertTrue(alertService.removeAlert(alert.getId()));
assertTrue(!alertService.hasAlerts());
assertTrue(alertService.getAlerts().isEmpty());
assertTrue(alertConfigurationDao.findAll().stream()
.noneMatch(record -> alert.getId().equals(record.getId())));
}
@Test
public void testAddAlertAfterInitialization() throws Exception {
alertService.loadAllAlerts();
AlertConfiguration alertConfiguration = createSampleAlertConfigurationWithNullId();
String id = alertService.addAlert(alertConfiguration);
long counter = alertService.getAlerts()
.stream()
.filter(alert -> id.equals(alert.getId()))
.count();
assertEquals(1, counter);
assertEquals(INITIAL_ALERTS_LIST_SIZE + 1, alertService.getAlerts().size());
assertTrue(alertService.hasAlerts());
Alert loadedAlert = alertService.getAlerts()
.stream()
.filter(alert -> id.equals(alert.getId()))
.findFirst()
.get();
alertConfiguration.setId(id);
assertMatch(alertConfiguration, loadedAlert);
}
@Test
public void testAddAlertBeforeInitialization() throws Exception {
AlertConfiguration alertConfiguration = createSampleAlertConfigurationWithNullId();
String id = alertService.addAlert(alertConfiguration);
assertTrue(alertService.hasAlerts());
assertEquals(1, alertService.getAlerts().size());
Alert loadedAlert = alertService.getAlerts()
.stream()
.findFirst()
.get();
alertConfiguration.setId(id);
assertMatch(alertConfiguration, loadedAlert);
}
@Test
public void testAddAlertReplacingExisting() throws Exception {
alertService.loadAllAlerts();
AlertConfiguration alertConfiguration = alertConfigurationDao.findAll()
.stream()
.findFirst()
.get();
alertConfiguration.setRepeat(!alertConfiguration.getRepeat());
alertConfiguration.setInstrumentId("IX.DAX.DAILY");
alertConfiguration.setMessage("NewMessage");
alertService.addAlert(alertConfiguration);
Alert alert = alertService.getAlerts()
.stream()
.filter(a -> alertConfiguration.getId().equals(a.getId()))
.findFirst()
.get();
assertMatch(alertConfiguration, alert);
}
@Test
public void testLoadSampleAlerts() throws Exception {
alertService.loadSampleAlerts();
List<Alert> sampleAlerts = alertService.getAlerts();
assertTrue(alertService.hasAlerts());
assertEquals(INITIAL_ALERTS_LIST_SIZE, sampleAlerts.size());
alertService.unLoadAllAlerts();
alertService.loadAllAlerts();
List<Alert> savedAlerts = alertService.getAlerts();
assertEquals(INITIAL_ALERTS_LIST_SIZE, savedAlerts.size());
for (Alert sampleAlert : sampleAlerts) {
assertTrue(savedAlerts.contains(sampleAlert));
}
}
@Test
public void testGetAlertsInfo() throws Exception {
alertService.loadAllAlerts();
List<Alert> alerts = alertService.getAlerts();
List<AlertInfo> alertsInfo = alertService.getAlertsInfo();
assertEquals(alerts.size(), INITIAL_ALERTS_LIST_SIZE);
assertEquals(alerts.size(), alertsInfo.size());
for (AlertInfo alertInfo : alertsInfo) {
assertMatch(
alertInfo,
alerts.stream()
.filter(record -> alertInfo.getId().equals(record.getId()))
.findFirst()
.get());
}
}
@Test
public void testOnPriceTickForRepeatTrue() throws Exception {
AlertConfiguration alertConfiguration = createAlertConfiguration(
PriceValuePredicate.class,
INSTRUMENT_EURUSD_ID,
ImmutableMap.of(
PriceValuePredicate.PARAMETER_COMPARISON_OPERATOR, PriceValuePredicate.OPERATOR_EQUALS,
PriceValuePredicate.PARAMETER_PRICE_VALUE, String.valueOf(PRICE_VALUE_FROM)),
DEFAULT_ALERT_MESSAGE,
true,
DEFAULT_CREATION_DATE.getMillis());
alertService.addAlert(alertConfiguration);
List<PriceTick> priceTicks = createPriceTicks(
INSTRUMENT_EURUSD_ID,
Range.closed(DEFAULT_START_DATE.getMillis(), DEFAULT_START_DATE.getMillis() + 4),
Range.closed(PRICE_VALUE_FROM, PRICE_VALUE_TO),
0);
for (PriceTick priceTick : priceTicks) {
alertService.onPriceTick(priceTick);
}
assertAlertEventFired(eventNotificationService, alertConfiguration, 1);
reset(eventNotificationService);
for (PriceTick priceTick : priceTicks) {
alertService.onPriceTick(priceTick);
}
assertAlertEventFired(eventNotificationService, alertConfiguration, 1);
}
@Test
public void testOnPriceTickForRepeatFalse() throws Exception {
AlertConfiguration alertConfiguration = createAlertConfiguration(
PriceValuePredicate.class,
INSTRUMENT_EURUSD_ID,
ImmutableMap.of(
PriceValuePredicate.PARAMETER_COMPARISON_OPERATOR, PriceValuePredicate.OPERATOR_EQUALS,
PriceValuePredicate.PARAMETER_PRICE_VALUE, String.valueOf(PRICE_VALUE_FROM)),
DEFAULT_ALERT_MESSAGE,
false,
DEFAULT_CREATION_DATE.getMillis());
alertService.addAlert(alertConfiguration);
List<PriceTick> priceTicks = createPriceTicks(
INSTRUMENT_EURUSD_ID,
Range.closed(DEFAULT_START_DATE.getMillis(), DEFAULT_END_DATE.getMillis()),
Range.closed(PRICE_VALUE_FROM, PRICE_VALUE_TO),
0);
for (PriceTick priceTick : priceTicks) {
alertService.onPriceTick(priceTick);
}
assertAlertEventFired(eventNotificationService, alertConfiguration, 1);
reset(eventNotificationService);
for (PriceTick priceTick : priceTicks) {
alertService.onPriceTick(priceTick);
}
assertAlertEventFired(eventNotificationService, alertConfiguration, 0);
}
private static void assertAlertEventFired(EventNotificationService eventNotificationService,
AlertConfiguration alertConfiguration, int times) {
ArgumentCaptor<AlertEvent> alertEventCaptor = ArgumentCaptor.forClass(AlertEvent.class);
if (times == 0) {
verify(eventNotificationService, never())
.notifyAlertEventAsync(alertEventCaptor.capture());
} else {
verify(eventNotificationService, times(times))
.notifyAlertEventAsync(alertEventCaptor.capture());
AlertEvent alertEvent = alertEventCaptor.getValue();
assertEquals(alertEvent.getMessage(), alertConfiguration.getMessage());
assertEquals(alertEvent.getSeverityLevel(), alertConfiguration.getSeverityLevel());
assertEquals(alertEvent.getAdviserId(), alertConfiguration.getId());
}
}
private static void assertValidAlert(Alert alert) {
assertNotNull(alert);
assertTrue(!Strings.isNullOrEmpty(alert.getId()));
assertTrue(!Strings.isNullOrEmpty(alert.getInstrumentId()));
assertTrue(!Strings.isNullOrEmpty(alert.getMessage()));
assertNotNull(alert.getSeverityLevel());
assertNotNull(alert.getPredicatesChain());
assertTrue(!Iterables.isEmpty(alert.getPredicatesChain()));
for (AdviserPredicate adviserPredicate : alert.getPredicatesChain()) {
checkAdviserPredicate(adviserPredicate);
}
}
private static void assertMatch(AlertInfo alertInfo, Alert alert) {
assertNotNull(alertInfo);
assertNotNull(alert);
assertEquals(alertInfo.getId(), alert.getId());
assertEquals(alertInfo.getInstrumentId(), alert.getInstrumentId());
assertEquals(alertInfo.getMessage(), alert.getMessage());
assertEquals(alertInfo.getCreatedOn(), alert.getCreatedOn());
assertEquals(alertInfo.getLastFiredOn(), alert.getLastFiredOn());
assertEquals(alertInfo.getRepeat(), alert.getRepeat());
assertEquals(alertInfo.getSeverityLevel(), alert.getSeverityLevel());
for (AdviserPredicateInfo adviserPredicateInfo : alertInfo.getPredicatesChainInfo()) {
for (AdviserPredicate adviserPredicate : alert.getPredicatesChain()) {
boolean recordFound = false;
if (adviserPredicateInfo.getClassName().equals(adviserPredicate.getClass().getName()) &&
adviserPredicateInfo.getExecutionParameters()
.equals(adviserPredicate.getParametersCopy())) {
assertTrue("Duplicated record found.", !recordFound);
recordFound = true;
TemplateInfo templateInfo =
createAdviserPredicateTemplateInfo(adviserPredicate.getClass());
assertEquals(adviserPredicateInfo.getAvailableParameters(),
templateInfo.getAvailableParameters());
assertEquals(adviserPredicateInfo.getDisplayName(), templateInfo.getDisplayName());
}
assertTrue(recordFound);
}
}
}
private static void assertMatch(AlertConfiguration alertConfiguration, Alert alert) {
assertNotNull(alertConfiguration);
assertNotNull(alert);
assertEquals(alertConfiguration.getId(), alert.getId());
assertEquals(alertConfiguration.getMessage(), alert.getMessage());
assertEquals(alertConfiguration.getInstrumentId(), alert.getInstrumentId());
assertEquals(alertConfiguration.getCreateOn(), alert.getCreatedOn());
assertEquals(alertConfiguration.getSeverityLevel(), alert.getSeverityLevel());
assertEquals(alertConfiguration.getRepeat(), alert.getRepeat());
assertEquals(size(alertConfiguration.getPredicatesChain()), size(alert.getPredicatesChain()));
for (AdviserPredicateConfiguration predicateConfiguration
: alertConfiguration.getPredicatesChain()) {
boolean recordFound = false;
for (AdviserPredicate predicate : alert.getPredicatesChain()) {
if (predicateConfiguration.getClassName().equals(predicate.getClass().getName()) &&
predicateConfiguration.getParameters().equals(predicate.getParametersCopy())) {
assertTrue("Duplicated record found.", !recordFound);
recordFound = true;
}
}
assertTrue(
String.format("Predicate not found [%s].", predicateConfiguration), recordFound);
}
}
}
|
package eu.lsem.bakalarka.service;
import eu.lsem.bakalarka.model.PieChart;
import eu.lsem.bakalarka.model.*;
import eu.lsem.bakalarka.model.ColumnChart;
import eu.lsem.bakalarka.dao.categories.CategoryDao;
import eu.lsem.bakalarka.dao.ThesesDao;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.krysalis.jcharts.properties.PropertyException;
import org.krysalis.jcharts.chartData.ChartDataException;
public class ChartGeneratorImpl implements ChartGenerator {
private ThesesDao thesesDao;
private CategoryDao thesesCategoriesDao;
private CategoryDao fieldsOfStudyDao;
private CategoryDao formsOfStudyDao;
private final int COLUMN_CHART_WIDTH = 400;
private final int COLUMN_CHART_HEIGHT = 250;
private final int PIE_CHART_WIDTH = 400;
private final int PIE_CHART_HEIGHT = 400;
public void setThesesDao(ThesesDao thesesDao) {
this.thesesDao = thesesDao;
}
public void setThesesCategoriesDao(CategoryDao thesesCategoriesDao) {
this.thesesCategoriesDao = thesesCategoriesDao;
}
public void setFieldsOfStudyDao(CategoryDao fieldsOfStudyDao) {
this.fieldsOfStudyDao = fieldsOfStudyDao;
}
public void setFormsOfStudyDao(CategoryDao formsOfStudyDao) {
this.formsOfStudyDao = formsOfStudyDao;
}
private Map<ChartTypes, File> charts;
private boolean regenerate = true;
@Override
public synchronized void setRegenerate() {
regenerate = true;
}
@Override
public synchronized InputStream getChart(ChartTypes type) {
try {
if (regenerate)
regenerateCharts();
try {
return new FileInputStream(charts.get(type));
} catch (IOException e) { /* pokud chyba, prepocitat a znova */
regenerateCharts();
regenerate = false;
return new FileInputStream(charts.get(type));
}
} catch (Exception e) {
return null;
}
}
private synchronized void regenerateCharts() {
try {
Map<ChartTypes, File> tempMap = new HashMap<ChartTypes, File>();
/* typesChart*/
tempMap.put(ChartTypes.CATEGORIES_CHART, categoriesChart());
/*fields Chart */
tempMap.put(ChartTypes.FIELDS_CHART, fieldsChart());
/*forms chart*/
tempMap.put(ChartTypes.FORMS_CHART, formsChart());
/*years chart*/
tempMap.put(ChartTypes.YEARS_CHART, yearsChart());
/* date and field chart*/
tempMap.put(ChartTypes.YEARS_AND_FIELDS_CHART, yearsAndFieldsChart());
/* date and category chart*/
tempMap.put(ChartTypes.YEARS_AND_CATEGORIES_CHART, yearsAndCategoriesChart());
/* categories and fields pie */
tempMap.put(ChartTypes.CATEGORIES_AND_FIELDS_CHART, categoriesAndFieldsCharts());
/*uncomplete metadata*/
tempMap.put(ChartTypes.UNCOMPLETE_METADATA_CHART, uncompleteMetadataChart());
/*missing data*/
tempMap.put(ChartTypes.MISSING_DATA_CHART, missingDataFile());
/*not selected docs*/
tempMap.put(ChartTypes.NOT_SELECTED_DOCUMENTATION_CHART, notSelectedDocumentationChart());
charts = tempMap;
regenerate = false;
} catch (Exception e) {
}
}
private File categoriesChart() throws IOException, PropertyException, ChartDataException {
List<Category> categories = thesesCategoriesDao.getCategories();
double[] data = new double[categories.size()];
String[] labels = new String[categories.size()];
for (int i = 0; i < categories.size(); i++) {
data[i] = thesesDao.countThesesWithThesisCategory(categories.get(i).getId());
labels[i] = categories.get(i).getName();
}
File chart = File.createTempFile("chart", ".png");
new PieChart("Graf typů prací", PIE_CHART_WIDTH, PIE_CHART_HEIGHT + data.length * 20, labels, data, true).saveChart(chart);
return chart;
}
private File fieldsChart() throws IOException, PropertyException, ChartDataException {
List<Category> categories = fieldsOfStudyDao.getCategories();
double[] data = new double[categories.size()];
String[] labels = new String[categories.size()];
for (int i = 0; i < categories.size(); i++) {
data[i] = thesesDao.countThesesWithFieldOfStudy(categories.get(i).getId());
labels[i] = categories.get(i).getName();
}
File chart = File.createTempFile("chart", ".png");
new PieChart("Graf prací s oborem studia", PIE_CHART_WIDTH, PIE_CHART_HEIGHT + data.length * 20, labels, data, true).saveChart(chart);
return chart;
}
private File formsChart() throws IOException, PropertyException, ChartDataException {
List<Category> categories = formsOfStudyDao.getCategories();
double[] data = new double[categories.size()];
String[] labels = new String[categories.size()];
for (int i = 0; i < categories.size(); i++) {
data[i] = thesesDao.countThesesWithFormOfStudy(categories.get(i).getId());
labels[i] = categories.get(i).getName();
}
File chart = File.createTempFile("chart", ".png");
new PieChart("Graf prací s formou studia", PIE_CHART_WIDTH, PIE_CHART_HEIGHT + data.length * 20, labels, data, true).saveChart(chart);
return chart;
}
private File yearsChart() throws IOException, PropertyException, ChartDataException {
List<Integer> years = thesesDao.getYears();
String[] labels = new String[years.size()];
double[] data = new double[years.size()];
for (int i = 0; i < years.size(); i++) {
labels[i] = String.valueOf(years.get(i));
data[i] = thesesDao.countThesesAtYear(years.get(i));
}
File chart = File.createTempFile("chart", ".png");
new ColumnChart("Graf prací podle data obhajoby", COLUMN_CHART_WIDTH, COLUMN_CHART_HEIGHT + data.length * 20,
"Roky", "Počet prací", new double[][]{data}, labels, new String[]{"Práce v daném roce"}).saveChart(chart);
return chart;
}
private File yearsAndCategoriesChart() throws IOException, PropertyException, ChartDataException {
List<Integer> years = thesesDao.getYears();
List<Category> categories = thesesCategoriesDao.getCategories();
String[] labels = new String[years.size()];
String[] legendLabels = new String[categories.size()];
double[][] data = new double[categories.size()][years.size()];
for (int i = 0; i < years.size(); i++) {
labels[i] = years.get(i).toString();
}
for (int i = 0; i < categories.size(); i++) {
legendLabels[i] = categories.get(i).getName();
for (int j = 0; j < years.size(); j++) {
data[i][j] = thesesDao.countThesesAtYearAndCategory(years.get(j), categories.get(i).getId());
}
}
File f = File.createTempFile("chart", ".png");
new ColumnChart("Graf prací podle data obhajoby a kategorie práce",
COLUMN_CHART_WIDTH, COLUMN_CHART_HEIGHT + data.length * 20,
"Roky", "Počet prací", data, labels, legendLabels
).saveChart(f);
return f;
}
private File yearsAndFieldsChart() throws IOException, PropertyException, ChartDataException {
List<Integer> years = thesesDao.getYears();
List<Category> fieldsOfStudy = fieldsOfStudyDao.getCategories();
String[] labels = new String[years.size()];
String[] legendLabels = new String[fieldsOfStudy.size()];
double[][] data = new double[fieldsOfStudy.size()][years.size()];
for (int i = 0; i < years.size(); i++) {
labels[i] = years.get(i).toString();
}
for (int i = 0; i < fieldsOfStudy.size(); i++) {
legendLabels[i] = fieldsOfStudy.get(i).getName();
for (int j = 0; j < years.size(); j++) {
data[i][j] = thesesDao.countThesesAtYearAndFieldOfStudy(years.get(j), fieldsOfStudy.get(i).getId());
}
}
File f = File.createTempFile("chart", ".png");
new ColumnChart("Graf prací podle data obhajoby a oboru studia",
COLUMN_CHART_WIDTH, COLUMN_CHART_HEIGHT + data.length * 20,
"Roky", "Počet prací", data, labels, legendLabels).saveChart(f);
return f;
}
private File categoriesAndFieldsCharts() throws IOException, PropertyException, ChartDataException {
List<Category> categories = thesesCategoriesDao.getCategories();
List<Category> fieldsOfStudy = fieldsOfStudyDao.getCategories();
double[] data = new double[categories.size() * fieldsOfStudy.size()];
String[] labels = new String[categories.size() * fieldsOfStudy.size()];
int counter = 0;
for (Category category : categories) {
String temp = category.getName() + " v oboru ";
for (Category fieldOfStudy : fieldsOfStudy) {
data[counter] = thesesDao.countThesesWithThesisCategoryAndFieldOfStudy(category.getId(), fieldOfStudy.getId());
labels[counter] = temp + fieldOfStudy.getName();
counter++;
}
}
File f = File.createTempFile("chart", ".png");
new PieChart("Graf typů prací v jednotlivých oborech studia", PIE_CHART_WIDTH*3/2, PIE_CHART_HEIGHT + data.length * 20, labels, data, true).saveChart(f);
return f;
}
private File uncompleteMetadataChart() throws IOException, PropertyException, ChartDataException {
double nekompletniPrace = thesesDao.countThesesWithUncompleteMetadata();
double kompletniPrace = thesesDao.countTheses() - nekompletniPrace;
File f = File.createTempFile("chart", ".png");
new PieChart("Graf kompletnosti metadat", PIE_CHART_WIDTH, PIE_CHART_HEIGHT + 2 * 20,
new String[]{"Práce s kompletními metadaty", "Práce s nekompletními metadaty"},
new double[]{kompletniPrace, nekompletniPrace}, true).saveChart(f);
return f;
}
private File missingDataFile() throws IOException, PropertyException, ChartDataException {
double missingDataCount = thesesDao.countThesesWithMissingData();
double restCount = thesesDao.countTheses() - missingDataCount;
File f = File.createTempFile("chart", ".png");
new PieChart("Graf poměru prací s daty", PIE_CHART_WIDTH, PIE_CHART_HEIGHT + 40,
new String[]{"Práce s nechybějícími daty", "Práce s chybějícími daty"},
new double[]{restCount, missingDataCount}, true).saveChart(f);
return f;
}
private File notSelectedDocumentationChart() throws IOException, PropertyException, ChartDataException {
double notSelectedDocumentationCount = thesesDao.countThesesWithoutSelectedDocumentation();
double restCount = thesesDao.countTheses() - notSelectedDocumentationCount;
File f = File.createTempFile("chart", ".png");
new PieChart("Graf poměru prací s vybranou dokumentací", PIE_CHART_WIDTH, PIE_CHART_HEIGHT + 40,
new String[]{"Práce s vybranou dokumentací", "Práce bez vybrané dokumentace"},
new double[]{restCount, notSelectedDocumentationCount}, true).saveChart(f);
return f;
}
}
|
class if_Test1 {
public static void main(String ar[]){
int a=3;
if (a>0){
System.out.println("¾ç¼ö");
}
}
}
|
package com.tencent.mm.plugin.ab;
import com.tencent.mm.ab.l;
import com.tencent.mm.ao.b;
import com.tencent.mm.ao.e;
import com.tencent.mm.ao.f;
import com.tencent.mm.bt.h.d;
import com.tencent.mm.kernel.api.bucket.c;
import com.tencent.mm.kernel.g;
import com.tencent.mm.model.p;
import com.tencent.mm.plugin.messenger.foundation.a.o;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.bi;
import java.util.HashMap;
public final class a extends p implements com.tencent.mm.kernel.api.bucket.a, c {
private static HashMap<Integer, d> cVM;
private static a lEC;
private com.tencent.mm.ao.d lED = null;
private bi lEE = null;
private com.tencent.mm.ao.c lEF = null;
private e lEG = new e();
private final com.tencent.mm.ab.e lEH = new com.tencent.mm.ab.e() {
public final void a(int i, int i2, String str, l lVar) {
}
};
private a() {
super(f.class);
}
public static synchronized a bjh() {
a aVar;
synchronized (a.class) {
if (lEC == null) {
lEC = new a();
}
aVar = lEC;
}
return aVar;
}
static {
HashMap hashMap = new HashMap();
cVM = hashMap;
hashMap.put(Integer.valueOf("NEWTIPS_TABLE".hashCode()), new 2());
}
public final void onAccountInitialized(com.tencent.mm.kernel.e.c cVar) {
super.onAccountInitialized(cVar);
((o) g.n(o.class)).getSysCmdMsgExtension().a("newtips", this.lEG);
g.DF().a(597, this.lEH);
bji();
com.tencent.mm.ao.d.b(b.ebm, b.ebl, "", b.ebt);
x.i("MicroMsg.NewTipsManager", "dancy register dynamic newtips, tipsId:%s, path:%s", new Object[]{Integer.valueOf(r0), r1});
}
public final void onAccountRelease() {
super.onAccountRelease();
((o) g.n(o.class)).getSysCmdMsgExtension().b("newtips", this.lEG);
g.DF().b(597, this.lEH);
}
public static com.tencent.mm.ao.d bji() {
g.Eg().Ds();
if (bjh().lED == null) {
bjh().lED = new com.tencent.mm.ao.d();
}
return bjh().lED;
}
public static bi bjj() {
g.Eg().Ds();
if (bjh().lEE == null) {
a bjh = bjh();
g.Ek();
bjh.lEE = new bi(g.Ei().dqq);
}
return bjh().lEE;
}
public static com.tencent.mm.ao.c bjk() {
g.Eg().Ds();
if (bjh().lEF == null) {
bjh().lEF = new com.tencent.mm.ao.c();
}
return bjh().lEF;
}
public final HashMap<Integer, d> collectDatabaseFactory() {
return cVM;
}
}
|
package com.mes.old.meta;
// Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final
/**
* MBatchnumBarcode generated by hbm2java
*/
public class MBatchnumBarcode implements java.io.Serializable {
private MBatchnumBarcodeId id;
private long barcode;
private Long maxsn;
public MBatchnumBarcode() {
}
public MBatchnumBarcode(MBatchnumBarcodeId id, long barcode) {
this.id = id;
this.barcode = barcode;
}
public MBatchnumBarcode(MBatchnumBarcodeId id, long barcode, Long maxsn) {
this.id = id;
this.barcode = barcode;
this.maxsn = maxsn;
}
public MBatchnumBarcodeId getId() {
return this.id;
}
public void setId(MBatchnumBarcodeId id) {
this.id = id;
}
public long getBarcode() {
return this.barcode;
}
public void setBarcode(long barcode) {
this.barcode = barcode;
}
public Long getMaxsn() {
return this.maxsn;
}
public void setMaxsn(Long maxsn) {
this.maxsn = maxsn;
}
}
|
package com.br.cortex.cambio.application.domain.model;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Data {
private LocalDate value;
private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
public Data(LocalDate value) {
this.value = value;
}
public String asString(){
return this.value.format(formatter);
}
}
|
package cs455.scaling.server.workers;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import cs455.scaling.server.IWorker;
import cs455.scaling.server.ServerStatus;
import cs455.scaling.shared.GlobalLogger;
public class WriteWorker implements IWorker {
private final ByteBuffer buf;
private int totalBytesWritten = 0;
private final int errorCount = 0;
protected final SocketChannel sockc;
private final ServerStatus status;
public WriteWorker(SocketChannel sockc, ByteBuffer buf, ServerStatus status) {
this.buf = getHash(buf);
this.sockc = sockc;
this.status = status;
}
private ByteBuffer getHash(ByteBuffer data) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA1");
byte[] hash = digest.digest(data.array());
return ByteBuffer.wrap(hash);
} catch (NoSuchAlgorithmException e) {
GlobalLogger.severe(this, "No SHA1 algorithm, wtf?");
}
return null;
}
@Override
public void execute() {
try {
Selector selector = Selector.open();
SelectionKey key = sockc.register(selector, SelectionKey.OP_WRITE);
String clientName = ((SocketChannel) key.channel()).socket().getInetAddress().getHostName();
while (totalBytesWritten < buf.array().length && key.isValid()) {
try {
int selected = selector.select(1);
if (key.isWritable() && selected > 0) {
writeToStream(selector);
}
} catch (IOException ex) {
GlobalLogger.severe(this, "Failed to select on write selector.");
}
}
System.out.println(String.format("[ClientMessage - %s] - %s", clientName, new BigInteger(1, buf.array()).toString(16)));
System.out.println(String.format("[ServerMessage] Served by thread: %s", Thread.currentThread().getName()));
status.packetServed();
selector.close();
GlobalLogger.debug2(this, "Done writing.");
} catch (IOException ex) {
GlobalLogger.severe(this, "Failed to register write with write selector.");
}
}
private void writeToStream(Selector selector) {
int ret = 0;
boolean nothingToWrite = buf == null;
if (!nothingToWrite) {
try {
ret = sockc.write(buf);
} catch (IOException e) {
GlobalLogger.severe(this, "IOException received while writing: " + e.getMessage());
try {
status.removeClient();
sockc.close();
return;
} catch (IOException ex) {
// Don't care.
}
}
} else {
GlobalLogger.info(this, "Writer didn't have anything to write, this probably means a client hasn't been responded to.");
}
if (ret > 0) {
totalBytesWritten += ret;
}
if (nothingToWrite || ret > 0 && totalBytesWritten >= buf.array().length) {
GlobalLogger.debug2(this, "Successfully wrote all bytes.");
} else if (ret == -1) {
GlobalLogger.severe(this, "End of stream received, had to close connection.");
try {
status.removeClient();
sockc.close();
} catch (IOException e) {
// Ignore a failed close.
}
} else { // Probably wasn't writeable, put back in loop
try {
sockc.register(selector, SelectionKey.OP_WRITE);
} catch (ClosedChannelException e) {
status.removeClient();
GlobalLogger.severe(this, "Failed to a write socket because the socket was closed.");
}
}
}
}
|
package com.team6.app;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* Handles all account related requests.
*/
@Controller
@EnableMongoRepositories
public class CharacterController {
@Autowired
private CharacterService service;
@Autowired
private UserRepository repository;
//Retrieve a character's info through querying for associated user
@RequestMapping(value = "/MyCharacter", method = RequestMethod.GET)
public ModelAndView characterInfo(Model model, HttpServletRequest request) {
String userid = request.getSession(true).getAttribute("userid").toString();
User user = service.getCharacter(userid);
Character c = user.getCharacter();
model.addAttribute("character", c);
return new ModelAndView(Constants.CHAR_PROFILE_PATH_FILE);
}
//Add experience to character and revise appropriate fields
@RequestMapping(value = "/adjustStats", method = RequestMethod.GET)
public ModelAndView adjustCharacterStats(@RequestParam("experience") String experience, Model model, HttpServletRequest request) {
String userid = request.getSession(true).getAttribute("userid").toString();
service.changeStats(userid, Integer.parseInt(experience));
return new ModelAndView(Constants.HOME_PATH_FILE);
}
}
|
package Second;
/*
return有两个基本用途
1、返回方法的返回值
2、终止当前程序
*/
public class ReturnDemo {
public static void main(String[] args) {
System.out.println(get());
for(int i = 0;i < 10; i++){
System.out.println(i);
if (i==5){
//return 和下面功能一样
System.exit(-1);//里面这个数字 什莫意思都没有;就是退出;
}
System.out.println("接着执行");
}
}
public static int get(){
return 100;
}
}
|
package jvm;
import java.util.ArrayList;
import java.util.List;
/**
* @author yinchao
* @date 2020/4/9 18:29
*/
public class GCTest {
/**
* -XX:+PrintTenuringDistribution 每次 Mainor GC 的时候输出年龄
* -XX:+PrintCommandLineFlags
* -Xms10m
* -Xmx10m
* -XX:NewSize=256k
* -XX:SurvivorRatio=1
* -XX:+PrintGCDetails
* <p>
* -XX:InitialTenuringThreshold=20
* -XX:MaxTenuringThreshold=20
* 通过上面两个参数可以设置新生代到老年代的年龄大小
* <p>
* attention: jdk 7 年龄是可以超过15的!
* 而 JDK 8 设置超过 15 ,例如20,则会出现以下错误:
* MaxTenuringThreshold of 20 is invalid; must be between 0 and 15
*/
@org.junit.Test
public void testMaxAge() {
List<GCTest> list = new ArrayList<>();
while (true) {
list.add(new GCTest());
// Thread.sleep(1000);
}
}
}
|
package com.graphql.test.model;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
@Builder
@EqualsAndHashCode
public class Post {
private Integer id;
private User user;
private Integer userId;
private String title;
private String body;
private List<Comment> comments;
}
|
package com.olfu.meis.data;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by mykelneds on 13/12/2016.
*/
public class EZSharedPreferences {
private final static String USER_PREFERENCES = "MarikinaEIS";
public final static String KEY_MAGNITUDE = "Magnitude";
public final static String KEY_DISTANCE = "Distance";
public final static String KEY_TIME = "TimeFrame";
public final static String KEY_SAVE_FILTER = "SaveFilterPref";
public final static String KEY_FTU = "FirstTimeUse";
public static SharedPreferences getSharedPref(Context ctx) {
return ctx.getSharedPreferences(USER_PREFERENCES, Context.MODE_PRIVATE);
}
public static void dropSharedPref(Context ctx) {
SharedPreferences.Editor editor = getSharedPref(ctx).edit();
editor.clear();
editor.apply();
}
/**
* G E T T E R
*/
public static int getMagnitudePref(Context ctx) {
return getSharedPref(ctx).getInt(KEY_MAGNITUDE, 0);
}
public static boolean getFTU(Context ctx) {
return getSharedPref(ctx).getBoolean(KEY_FTU, true);
}
/**
* S E T T E R
*/
public static void setFTU(Context ctx) {
SharedPreferences.Editor editor = getSharedPref(ctx).edit();
editor.putBoolean(KEY_FTU, false);
editor.apply();
}
}
|
package models.user;
import models.academics.OfferedCourse;
import models.academics.coursework.TakenCourse;
import javax.persistence.*;
import java.util.List;
@Entity
@DiscriminatorValue("STU")
public class Student extends BasicUser {
public Integer departmentNo;
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
public List<TeachingAssistance> teachingAssistanceList;
@OneToMany(mappedBy = "student", cascade = CascadeType.ALL)
public List<TakenCourse> takenCourses;
public static Finder<String, Student> find = new Finder<>(Student.class);
public String getStudentID() {
return this.id;
}
public void takeCourse(OfferedCourse offeredCourse) {
TakenCourse t = new TakenCourse();
t.student = this;
t.offeredCourse = offeredCourse;
t.save();
}
@Override
public String toString() {
return String.format("Stud[%s, %s]", this.id, this.name);
}
}
|
package com.nmoumoulidis.opensensor.model;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.nmoumoulidis.opensensor.model.processing.DateManager;
import com.nmoumoulidis.opensensor.view.SensorStationActivity;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* SQLite database management class (extends {@link SQLiteOpenHelper}), used for storing
* persistently data on the phone, that were retrieved from a Wi-Fi connected OpenSensor Station.
* @author Nikos Moumoulidis
*
*/
public class DatabaseHelper extends SQLiteOpenHelper
{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "sensorReadingsManager";
private static final String TABLE_SENSOR_DATA = "sensor_data";
public static final String KEY_ID = "_id";
public static final String KEY_DATE = "date";
public static final String KEY_LOCATION = "location";
public static final String KEY_SENSOR_TYPE = "sensor_type_id";
public static final String KEY_DATA_VALUE = "data_value";
public static final String FUNC_AVG_VALUE = "avg("+KEY_DATA_VALUE+")";
public static final String FUNC_MIN_VALUE = "min("+KEY_DATA_VALUE+")";
public static final String FUNC_MAX_VALUE = "max("+KEY_DATA_VALUE+")";
private SensorStationActivity conSensAct;
private SQLiteDatabase privateDB;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
if(context.getClass() == SensorStationActivity.class) {;
conSensAct = (SensorStationActivity) context;
}
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_SENSOR_DATA_TABLE = "CREATE TABLE " + TABLE_SENSOR_DATA
+ "("
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ KEY_DATE + " TEXT NOT NULL,"
+ KEY_LOCATION + " TEXT NOT NULL,"
+ KEY_SENSOR_TYPE + " TEXT NOT NULL,"
+ KEY_DATA_VALUE + " REAL NOT NULL"
+ ");";
db.execSQL(CREATE_SENSOR_DATA_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVer, int newVer) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_SENSOR_DATA);
onCreate(db);
System.out.println("SQLITE HELPER -> ON UPGRADE WAS RUN...");
}
@Override
public void close() {
super.close();
if(privateDB != null) {
privateDB.close();
privateDB = null;
}
}
public ArrayList<String> getAllStoredSensorTypes() {
ArrayList<String> sensorTypesList = new ArrayList<String>();
privateDB = this.getReadableDatabase();
Cursor cursor = privateDB.rawQuery("SELECT DISTINCT "+
KEY_SENSOR_TYPE+
" FROM "+
TABLE_SENSOR_DATA+";"
, null);
if (cursor.moveToFirst()) {
do {
sensorTypesList.add(cursor.getString(0));
} while (cursor.moveToNext());
}
conSensAct.addUsedCursor(cursor);
return sensorTypesList;
}
/**
* Main INSERT query.
* @param data
*/
public void insertBatchData(ArrayList<HashMap<String,String>> data) {
data = DateManager.transformDateBeforeInsert(data);
privateDB = this.getWritableDatabase();
Iterator it;
HashMap.Entry pairs;
for(int i=0 ; i<data.size() ; i++) {
// Insert all data elements to the database.
it = data.get(i).entrySet().iterator();
while (it.hasNext()) {
pairs = (HashMap.Entry)it.next();
if(!pairs.getKey().equals("datetime") && !pairs.getKey().equals("location")) {
privateDB.execSQL("INSERT INTO "+ TABLE_SENSOR_DATA
+" ("
+ KEY_DATE +", "
+ KEY_LOCATION +", "
+ KEY_SENSOR_TYPE +", "
+ KEY_DATA_VALUE
+") VALUES ("
+"'"+ data.get(i).get("datetime") +"', "
+"'"+ data.get(i).get("location") +"', "
+"'"+ pairs.getKey() +"', "
+ pairs.getValue()
+");"
);
}
}
}
privateDB.close(); // explicitly close it...
}
/**
* Main SELECT query.
* @param sensor
* @param fromDate
* @param toDate
* @return
*/
public Cursor getDetailedQueryCursor(String sensor, String fromDate, String toDate) {
privateDB = this.getReadableDatabase();
Cursor cursor = privateDB.rawQuery("SELECT "+
KEY_ID+", " +
KEY_DATE+", " +
KEY_LOCATION+", " +
FUNC_AVG_VALUE+", " +
FUNC_MIN_VALUE+", " +
FUNC_MAX_VALUE+", " +
KEY_SENSOR_TYPE+" " +
"FROM " +TABLE_SENSOR_DATA+" "+
"WHERE "+KEY_SENSOR_TYPE+" = '"+ sensor +"' "+
"AND ("+KEY_DATE+" " +
"BETWEEN Date('"+fromDate+ "') AND Date('"+toDate+"')) "+
"GROUP BY "+KEY_DATE
, null);
if (cursor.moveToFirst()) {
return cursor;
}
else {
return null;
}
}
public void deleteAllBatchData() {
privateDB = this.getReadableDatabase();
privateDB.delete(TABLE_SENSOR_DATA, null, null);
}
public long getDataCount() {
privateDB = this.getReadableDatabase();
return DatabaseUtils.queryNumEntries(privateDB, TABLE_SENSOR_DATA);
}
}
|
package com.psl.flashnotes.bean;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
@Embeddable
public class CompositeId2 implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Column(name = "answerId")
private int answerId;
@Column(name = "userId")
private int userId;
public int getAnswerId() {
return answerId;
}
public void setAnswerId(int answerId) {
this.answerId = answerId;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
|
package com.spring.domain;
import java.util.List;
public class MultiChequeInvoice {
List<ChequeInventory> chequeList;
List<Transaction_Process> transaction_ProcessList;
public List<ChequeInventory> getChequeList() {
return chequeList;
}
public void setChequeList(List<ChequeInventory> chequeList) {
this.chequeList = chequeList;
}
public List<Transaction_Process> getTransaction_ProcessList() {
return transaction_ProcessList;
}
public void setTransaction_ProcessList(List<Transaction_Process> transaction_ProcessList) {
this.transaction_ProcessList = transaction_ProcessList;
}
}
|
package crossing.strategy;
import bplusTree.BPlusTree;
import common.TimeInForce;
import crossing.TestOrderEntryFactory;
import leafNode.OrderEntry;
import leafNode.OrderList;
import leafNode.OrderListImpl;
import orderBook.OrderBook;
import org.joda.time.DateTime;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by dharmeshsing on 29/07/15.
*/
public class TimeInForceStrategyTest {
@Test
public void testRemoveOrderIOC() throws Exception {
boolean result = TimeInForceStrategy.removeOrder(100,TimeInForce.IOC.getValue());
assertEquals(true,result);
}
@Test
public void testRemoveOrderDAY() throws Exception {
boolean result = TimeInForceStrategy.removeOrder(100,TimeInForce.DAY.getValue());
assertEquals(false,result);
}
@Test
public void testCanFOKOrderBeFilled() throws Exception {
OrderBook orderBook = new OrderBook(1);
OrderList orderList = new OrderListImpl();
OrderEntry orderEntry = TestOrderEntryFactory.createOrderEntry("10:00");
orderEntry.setQuantity(1000);
orderList.add(orderEntry);
orderBook.getOfferTree().put(orderEntry.getPrice(), orderList);
BPlusTree.BPlusTreeIterator iterator = orderBook.getPriceIterator(OrderBook.SIDE.OFFER);
boolean result = TimeInForceStrategy.canFOKOrderBeFilled(iterator, 500, 100, -1, OrderBook.SIDE.BID);
assertEquals(true,result);
}
@Test
public void testFOKOrderCannotBeFilled() throws Exception {
OrderBook orderBook = new OrderBook(1);
OrderList orderList = new OrderListImpl();
OrderEntry orderEntry = TestOrderEntryFactory.createOrderEntry("10:00");
orderEntry.setQuantity(1000);
orderList.add(orderEntry);
orderBook.getOfferTree().put(orderEntry.getPrice(), orderList);
BPlusTree.BPlusTreeIterator iterator = orderBook.getPriceIterator(OrderBook.SIDE.OFFER);
boolean result = TimeInForceStrategy.canFOKOrderBeFilled(iterator,2000,100,-1, OrderBook.SIDE.BID);
assertEquals(false,result);
}
@Test
public void testExpireOrder() throws Exception {
OrderBook orderBook = new OrderBook(1);
OrderList orderList = new OrderListImpl();
OrderEntry orderEntry = TestOrderEntryFactory.createOrderEntry("10:00");
orderEntry.setTimeInForce(TimeInForce.OPG.getValue());
orderList.add(orderEntry);
orderBook.getOfferTree().put(orderEntry.getPrice(), orderList);
TimeInForceStrategy.expireOrders(orderBook, TimeInForce.OPG);
int result = orderBook.getOfferTree().size();
assertEquals(0, result);
}
@Test
public void testIsPastMaxDuration() throws Exception{
DateTime submittedDate = new DateTime(2015,3,1,0,0,0);
boolean result = TimeInForceStrategy.isPastMaxDuration(submittedDate.getMillis());
assertEquals(true, result);
}
@Test
public void testIsPastExpiryDateOrMaxDuration() throws Exception{
DateTime submittedDate = new DateTime(2015,3,1,0,0,0);
DateTime expiryDate = new DateTime(2015,3,2,0,0,0);
boolean result = TimeInForceStrategy.isPastExpiryDateOrMaxDuration(expiryDate.getMillis(), submittedDate.getMillis());
assertEquals(true, result);
}
}
|
package com.cg.mobilebilling.daoservices;
import java.util.List;
import com.cg.mobilebilling.beans.Bill;
import com.cg.mobilebilling.beans.Customer;
import com.cg.mobilebilling.beans.Plan;
import com.cg.mobilebilling.beans.PostpaidAccount;
import com.cg.mobilebilling.exceptions.BillingServicesDownException;
import com.cg.mobilebilling.exceptions.PlanDetailsNotFoundException;
public class BillingDAOServicesImpl implements BillingDAOServices {
@Override
public int insertCustomer(Customer customer) throws BillingServicesDownException {
// TODO Auto-generated method stub
return 0;
}
@Override
public long insertPostPaidAccount(int customerID, PostpaidAccount account) {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean updatePostPaidAccount(int customerID, PostpaidAccount account) {
// TODO Auto-generated method stub
return false;
}
@Override
public int insertMonthlybill(int customerID, long mobileNo, Bill bill) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int insertPlan(Plan plan) throws PlanDetailsNotFoundException {
// TODO Auto-generated method stub
return 0;
}
@Override
public boolean deletePostPaidAccount(int customerID, long mobileNo) {
// TODO Auto-generated method stub
return false;
}
@Override
public Bill getMonthlyBill(int customerID, long mobileNo, String billMonth) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Bill> getCustomerPostPaidAccountAllBills(int customerID, long mobileNo) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<PostpaidAccount> getCustomerPostPaidAccounts(int customerID) {
// TODO Auto-generated method stub
return null;
}
@Override
public Customer getCustomer(int customerID) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Customer> getAllCustomers() {
// TODO Auto-generated method stub
return null;
}
@Override
public List<Plan> getAllPlans() {
// TODO Auto-generated method stub
return null;
}
@Override
public Plan getPlan(int planID) {
// TODO Auto-generated method stub
return null;
}
@Override
public PostpaidAccount getCustomerPostPaidAccount(int customerID, long mobileNo) {
// TODO Auto-generated method stub
return null;
}
@Override
public Plan getPlanDetails(int customerID, long mobileNo) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean deleteCustomer(int customerID) {
// TODO Auto-generated method stub
return false;
}
}
|
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* Created by zhongjian on 2016/11/23.
* 0/1背包问题,动态规划
*/
public class DKNAP {
/**
* 物品数量
*/
private int n;
/**
* 物品效益
*/
private int[] p;
/**
* 物品重量
*/
private int[] w;
/**
* 最优解
*/
private int[] x;
private int[] F;
private List<Integer> P = new ArrayList<>();
private List<Integer> W = new ArrayList<>();
public DKNAP(int n, int[] p, int[] w) {
set(n, p, w);
}
public void set(int n, int[] p, int[] w) {
this.n = n;
this.p = p;
this.w = w;
F = new int[n + 1];
P.clear();
W.clear();
}
/**
* dknap算法
* <p>
* it's so amazing
*
* @param M
*/
public void dknap(int M) {
F[0] = 0;
P.add(0);
W.add(0);//S^0//
int pp, ww;
int l = 0, h = 0; //S^0 的首段和末端
F[1] = 1;
int next = 1;
for (int i = 1; i <= n; i++) { //生成S^i
int k = l;
int u = max(l, h, M, i - 1);
for (int j = l; j <= u; j++) { //生成S^i_1 及归并
//S^i_1的下一个元素
pp = P.get(j) + p[i - 1];
ww = W.get(j) + w[i - 1];
//从S^i_1 中取元素归并
while (k <= h && W.get(k) < ww) {
P.add(P.get(k));
W.add(W.get(k));
++k;
++next;
}
if (k <= h && W.get(k) == ww) {
pp = Math.max(pp, P.get(k));
++k;
}
if (pp > P.get(next - 1)) {
P.add(pp);
W.add(ww);
++next;
}
//清除
while (k <= h && P.get(k) <= P.get(next - 1)) {
++k;
}
}
//将S^{i-1} 中的剩余元素并入S^i
while (k <= h) {
P.add(P.get(k));
W.add(W.get(k));
++next;
++k;
}
// 对S^{i+1}置初值
l = h + 1;
h = next - 1;
if (i + 1 < F.length) {
F[i + 1] = next;
}
}
//生成X
x = new int[n];
int px = P.get(P.size() - 1);
int wx = W.get(W.size() - 1);
// int py;
for (int i = n - 1; i >= 0; --i) {
int high = F[i + 1];
int low = F[i];
// int index = -1;
// int max = -1;
for (int j = high - 1; j >= low; --j) {//在前一个S中寻找是否有px,wx,若有,则x置为0,若无则是新加入的,x置为1
// if (W.get(j) <= (wx - w[i]) && W.get(j) > max) {
// index = j;
// break;
// }
x[i] = 1;
if(px == P.get(j) && wx == W.get(j)){//在前一个S中
x[i] = 0;
break;
}
}
if(x[i] == 1){
px = px - p[i];
wx -= w[i];
}
// if (index == -1) {
// x[i] = 0;
// continue;
// }
// py = P.get(index) + p[i];
// if(px > py){
// x[i] = 0;
// }else{
// x[i] = 1;
// px = P.get(index);
// wx = W.get(index);
// }
}
}
/**
* 求W(r)+w(i)<=M 最大的值的r,l<=r<=h
*
* @param l 最小范围
* @param h 最大范围
* @param M 背包容量
* @param i 第i+1个物品
* @return
*/
private int max(int l, int h, int M, int i) {
int max = 0;
int r = 0;
for (int j = l; j <= h; j++) {
int temp = W.get(j) + w[i];
if (temp > max && temp <= M) {
max = temp;
r = j;
}
}
return r;
}
public void print() {
System.out.print("P: ");
for (int i = 0; i < P.size(); i++) {
System.out.print(P.get(i) + " ");
}
System.out.println();
System.out.print("W: ");
for (int i = 0; i < W.size(); i++) {
System.out.print(W.get(i) + " ");
}
System.out.println();
System.out.print("X: ");
for (int i = 0; i < n; i++) {
System.out.print(x[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
DKNAP dknap = new DKNAP(3, new int[]{1, 2, 5}, new int[]{2, 3, 4});
dknap.dknap(6);
dknap.print();
dknap.set(6, new int[]{100, 50, 20, 10, 7, 3}, new int[]{100, 50, 20, 10, 7, 3});
dknap.dknap(165);
dknap.print();
dknap.set(4, new int[]{2,5,8,1}, new int[]{10, 15, 6, 9});
dknap.dknap(15);
dknap.print();
}
}
|
package com.bit.myfood.controller.api;
import com.bit.myfood.controller.CrudController;
import com.bit.myfood.model.entity.Item;
import com.bit.myfood.model.network.request.ItemApiRequest;
import com.bit.myfood.model.network.response.ItemApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
@RequestMapping("/api/item")
public class ItemApiController extends CrudController<ItemApiRequest,ItemApiResponse, Item> {
}
/*@Autowired
private ItemApiLogicService itemApiLogicService;
@PostConstruct
public void init() {
this.baseService = itemApiLogicService;
}
// CRUD*/
/*
@Autowired
private ItemApiLogicService itemApiLogicService;
@Override
@PostMapping("") // /api/item
public Header<ItemApiResponse> create(@RequestBody Header<ItemApiRequest> request) {
return itemApiLogicService.create(request);
}
@Override
@GetMapping("{id}") // /api/item/1 ...
public Header<ItemApiResponse> read(@PathVariable Long id) {
return itemApiLogicService.read(id);
}
@Override
@PutMapping("") // /api/item
public Header<ItemApiResponse> update(@RequestBody Header<ItemApiRequest> request) {
return itemApiLogicService.update(request);
}
@Override
@DeleteMapping("{id}") // /api/item/1 ...
public Header delete(@PathVariable Long id) {
return itemApiLogicService.delete(id);
}
*/
|
package org.seckill.service;
import org.seckill.dto.SeckillResponse;
import org.seckill.entity.SecKill;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.exception.SeckillException;
import java.util.List;
/**
* <pre>
* desc :业务接口: 站在""
* author :lizj
* date :2020-03-29 11:47
* </pre>
*/
public interface SeckillService {
List<SecKill> getSeckillList();
SecKill getSeckillById(long seckillId);
SeckillResponse executeSeckill(long seckillId, String userPhone, String md5)
throws SeckillException, RepeatKillException, SeckillCloseException;
}
|
package com.lbsp.promotion.entity.enumeration;
public class ExceptionCode {
public static final int AuthKeyNotExistException = 97;
public static final int PasswordErrorException = 98;
public static final int DuplicateKeyException = 99;
public static final int OrderNotFoundException = 200;
public static final int OrderPayedExpception = 201;
public static final int RechargeOrderNotFoundException = 203;
}
|
package com.swqs.schooltrade.activity;
import com.swqs.schooltrade.R;
import com.swqs.schooltrade.fragment.BuyDetailsFragment;
import com.swqs.schooltrade.fragment.SellDetailsFragment;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class BuyAndSelledActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_buy_sell);
String flag=getIntent().getStringExtra("flag");
FragmentTransaction ft=getFragmentManager().beginTransaction();
if(flag.equals("buy")){
ft.replace(R.id.container, new BuyDetailsFragment());
ft.commit();
}else if(flag.equals("sell")){
ft.replace(R.id.container, new SellDetailsFragment());
ft.commit();
}
}
}
|
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package edu.tsinghua.lumaqq.ecore.option;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Message Option</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isAutoEject <em>Auto Eject</em>}</li>
* <li>{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isEnableSound <em>Enable Sound</em>}</li>
* <li>{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectStranger <em>Reject Stranger</em>}</li>
* <li>{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectTempSessionIM <em>Reject Temp Session IM</em>}</li>
* <li>{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInMessageMode <em>Use Enter In Message Mode</em>}</li>
* <li>{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInTalkMode <em>Use Enter In Talk Mode</em>}</li>
* </ul>
* </p>
*
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption()
* @model
* @generated
*/
public interface MessageOption extends EObject {
/**
* Returns the value of the '<em><b>Auto Eject</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Auto Eject</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Auto Eject</em>' attribute.
* @see #isSetAutoEject()
* @see #unsetAutoEject()
* @see #setAutoEject(boolean)
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption_AutoEject()
* @model unique="false" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean" required="true"
* @generated
*/
boolean isAutoEject();
/**
* Sets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isAutoEject <em>Auto Eject</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Auto Eject</em>' attribute.
* @see #isSetAutoEject()
* @see #unsetAutoEject()
* @see #isAutoEject()
* @generated
*/
void setAutoEject(boolean value);
/**
* Unsets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isAutoEject <em>Auto Eject</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetAutoEject()
* @see #isAutoEject()
* @see #setAutoEject(boolean)
* @generated
*/
void unsetAutoEject();
/**
* Returns whether the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isAutoEject <em>Auto Eject</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Auto Eject</em>' attribute is set.
* @see #unsetAutoEject()
* @see #isAutoEject()
* @see #setAutoEject(boolean)
* @generated
*/
boolean isSetAutoEject();
/**
* Returns the value of the '<em><b>Enable Sound</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Enable Sound</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Enable Sound</em>' attribute.
* @see #isSetEnableSound()
* @see #unsetEnableSound()
* @see #setEnableSound(boolean)
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption_EnableSound()
* @model unique="false" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean" required="true"
* @generated
*/
boolean isEnableSound();
/**
* Sets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isEnableSound <em>Enable Sound</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Enable Sound</em>' attribute.
* @see #isSetEnableSound()
* @see #unsetEnableSound()
* @see #isEnableSound()
* @generated
*/
void setEnableSound(boolean value);
/**
* Unsets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isEnableSound <em>Enable Sound</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetEnableSound()
* @see #isEnableSound()
* @see #setEnableSound(boolean)
* @generated
*/
void unsetEnableSound();
/**
* Returns whether the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isEnableSound <em>Enable Sound</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Enable Sound</em>' attribute is set.
* @see #unsetEnableSound()
* @see #isEnableSound()
* @see #setEnableSound(boolean)
* @generated
*/
boolean isSetEnableSound();
/**
* Returns the value of the '<em><b>Reject Stranger</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Reject Stranger</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Reject Stranger</em>' attribute.
* @see #isSetRejectStranger()
* @see #unsetRejectStranger()
* @see #setRejectStranger(boolean)
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption_RejectStranger()
* @model unique="false" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean" required="true"
* @generated
*/
boolean isRejectStranger();
/**
* Sets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectStranger <em>Reject Stranger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Reject Stranger</em>' attribute.
* @see #isSetRejectStranger()
* @see #unsetRejectStranger()
* @see #isRejectStranger()
* @generated
*/
void setRejectStranger(boolean value);
/**
* Unsets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectStranger <em>Reject Stranger</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetRejectStranger()
* @see #isRejectStranger()
* @see #setRejectStranger(boolean)
* @generated
*/
void unsetRejectStranger();
/**
* Returns whether the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectStranger <em>Reject Stranger</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Reject Stranger</em>' attribute is set.
* @see #unsetRejectStranger()
* @see #isRejectStranger()
* @see #setRejectStranger(boolean)
* @generated
*/
boolean isSetRejectStranger();
/**
* Returns the value of the '<em><b>Reject Temp Session IM</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Reject Temp Session IM</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Reject Temp Session IM</em>' attribute.
* @see #isSetRejectTempSessionIM()
* @see #unsetRejectTempSessionIM()
* @see #setRejectTempSessionIM(boolean)
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption_RejectTempSessionIM()
* @model unique="false" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean" required="true"
* @generated
*/
boolean isRejectTempSessionIM();
/**
* Sets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectTempSessionIM <em>Reject Temp Session IM</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Reject Temp Session IM</em>' attribute.
* @see #isSetRejectTempSessionIM()
* @see #unsetRejectTempSessionIM()
* @see #isRejectTempSessionIM()
* @generated
*/
void setRejectTempSessionIM(boolean value);
/**
* Unsets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectTempSessionIM <em>Reject Temp Session IM</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetRejectTempSessionIM()
* @see #isRejectTempSessionIM()
* @see #setRejectTempSessionIM(boolean)
* @generated
*/
void unsetRejectTempSessionIM();
/**
* Returns whether the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isRejectTempSessionIM <em>Reject Temp Session IM</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Reject Temp Session IM</em>' attribute is set.
* @see #unsetRejectTempSessionIM()
* @see #isRejectTempSessionIM()
* @see #setRejectTempSessionIM(boolean)
* @generated
*/
boolean isSetRejectTempSessionIM();
/**
* Returns the value of the '<em><b>Use Enter In Message Mode</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Use Enter In Message Mode</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Use Enter In Message Mode</em>' attribute.
* @see #isSetUseEnterInMessageMode()
* @see #unsetUseEnterInMessageMode()
* @see #setUseEnterInMessageMode(boolean)
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption_UseEnterInMessageMode()
* @model unique="false" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean" required="true"
* @generated
*/
boolean isUseEnterInMessageMode();
/**
* Sets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInMessageMode <em>Use Enter In Message Mode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Use Enter In Message Mode</em>' attribute.
* @see #isSetUseEnterInMessageMode()
* @see #unsetUseEnterInMessageMode()
* @see #isUseEnterInMessageMode()
* @generated
*/
void setUseEnterInMessageMode(boolean value);
/**
* Unsets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInMessageMode <em>Use Enter In Message Mode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetUseEnterInMessageMode()
* @see #isUseEnterInMessageMode()
* @see #setUseEnterInMessageMode(boolean)
* @generated
*/
void unsetUseEnterInMessageMode();
/**
* Returns whether the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInMessageMode <em>Use Enter In Message Mode</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Use Enter In Message Mode</em>' attribute is set.
* @see #unsetUseEnterInMessageMode()
* @see #isUseEnterInMessageMode()
* @see #setUseEnterInMessageMode(boolean)
* @generated
*/
boolean isSetUseEnterInMessageMode();
/**
* Returns the value of the '<em><b>Use Enter In Talk Mode</b></em>' attribute.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Use Enter In Talk Mode</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Use Enter In Talk Mode</em>' attribute.
* @see #isSetUseEnterInTalkMode()
* @see #unsetUseEnterInTalkMode()
* @see #setUseEnterInTalkMode(boolean)
* @see edu.tsinghua.lumaqq.ecore.option.OptionPackage#getMessageOption_UseEnterInTalkMode()
* @model unique="false" unsettable="true" dataType="org.eclipse.emf.ecore.xml.type.Boolean" required="true"
* @generated
*/
boolean isUseEnterInTalkMode();
/**
* Sets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInTalkMode <em>Use Enter In Talk Mode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Use Enter In Talk Mode</em>' attribute.
* @see #isSetUseEnterInTalkMode()
* @see #unsetUseEnterInTalkMode()
* @see #isUseEnterInTalkMode()
* @generated
*/
void setUseEnterInTalkMode(boolean value);
/**
* Unsets the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInTalkMode <em>Use Enter In Talk Mode</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #isSetUseEnterInTalkMode()
* @see #isUseEnterInTalkMode()
* @see #setUseEnterInTalkMode(boolean)
* @generated
*/
void unsetUseEnterInTalkMode();
/**
* Returns whether the value of the '{@link edu.tsinghua.lumaqq.ecore.option.MessageOption#isUseEnterInTalkMode <em>Use Enter In Talk Mode</em>}' attribute is set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @return whether the value of the '<em>Use Enter In Talk Mode</em>' attribute is set.
* @see #unsetUseEnterInTalkMode()
* @see #isUseEnterInTalkMode()
* @see #setUseEnterInTalkMode(boolean)
* @generated
*/
boolean isSetUseEnterInTalkMode();
} // MessageOption
|
/*
* @project: (Sh)ower (R)econstructing (A)pplication for (M)obile (P)hones
* @version: ShRAMP v0.0
*
* @objective: To detect extensive air shower radiation using smartphones
* for the scientific study of ultra-high energy cosmic rays
*
* @institution: University of California, Irvine
* @department: Physics and Astronomy
*
* @author: Eric Albin
* @email: Eric.K.Albin@gmail.com
*
* @updated: 3 May 2019
*/
package sci.crayfis.shramp.battery;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.BatteryManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import org.jetbrains.annotations.Contract;
import sci.crayfis.shramp.util.NumToString;
import sci.crayfis.shramp.util.StopWatch;
////////////////////////////////////////////////////////////////////////////////////////////////////
// (TODO) UNDER CONSTRUCTION (TODO)
////////////////////////////////////////////////////////////////////////////////////////////////////
// This class is basically fine, the to-do is adding additional broadcast listeners (low-priority)
/**
* Public interface to battery functions
*/
@TargetApi(21)
public class BatteryController {
// Private Class Constants
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// mInstance....................................................................................
// Reference to single instance of BatteryController
private static final BatteryController mInstance = new BatteryController();
// Private Instance Fields
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// mBatteryManager..............................................................................
// Reference to system battery manager
private BatteryManager mBatteryManager;
// mBatteryChanged..............................................................................
// Reference to battery broadcast listener
private BatteryChanged mBatteryChanged;
/*
// TODO: other broadcast listeners that may or may not be added soon
private static Intent mBatteryOkay;
private static Intent mBatteryLow;
private static Intent mPowerConnected;
private static Intent mPowerDisconnected;
private static Intent mPowerSummary;
*/
// mStopWatch1..................................................................................
// For now, monitoring performance for getting temperature -- (TODO) to be removed later
private static final StopWatch mStopWatch = new StopWatch("BatteryController.getCurrentTemperature()");
////////////////////////////////////////////////////////////////////////////////////////////////
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
////////////////////////////////////////////////////////////////////////////////////////////////
// Constructors
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/**
* Disable ability to create multiple instances
*/
private BatteryController() {}
// Public Class Methods
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
// initialize...................................................................................
/**
* Start up battery monitoring
* @param activity Main activity that is controlling the app
*/
public static void initialize(@NonNull Activity activity) {
mInstance.mBatteryManager = (BatteryManager) activity.getSystemService(Context.BATTERY_SERVICE);
mInstance.mBatteryChanged = new BatteryChanged(activity);
/*
// TODO: other broadcast listeners that may or may not be added soon
mBatteryOkay = activity.registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_OKAY));
mBatteryLow = activity.registerReceiver(this, new IntentFilter(Intent.ACTION_BATTERY_LOW));
mPowerConnected = activity.registerReceiver(this, new IntentFilter(Intent.ACTION_POWER_CONNECTED));
mPowerDisconnected = activity.registerReceiver(this, new IntentFilter(Intent.ACTION_POWER_DISCONNECTED));
//mPowerSummary = activity.registerReceiver(this, new IntentFilter(Intent.ACTION_POWER_USAGE_SUMMARY));
*/
}
// refresh......................................................................................
/**
* Refresh battery information to latest values
*/
public static void refresh() {
if (mInstance.mBatteryChanged == null) {
return;
}
mInstance.mBatteryChanged.refresh();
}
// getRemainingCapacity.........................................................................
/**
* @return remaining battery level as a percent with no decimal part
*/
public static int getRemainingCapacity() {
if (mInstance.mBatteryManager == null) {
return -1;
}
return mInstance.mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
}
// getBatteryCapacity...........................................................................
/**
* Warning: could be garbage
* @return capacity in milli-amp-hours
*/
public static double getBatteryCapacity() {
if (mInstance.mBatteryManager == null) {
return Double.NaN;
}
return mInstance.mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CHARGE_COUNTER) / 1e3;
}
// getInstantaneousCurrent......................................................................
/**
* Warning: could be net current (out - in) or out only
* @return current current in milli-amps
*/
public static double getInstantaneousCurrent() {
if (mInstance.mBatteryManager == null) {
return Double.NaN;
}
return mInstance.mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW) / 1e3;
}
// getAverageCurrent............................................................................
/**
* Warning: could be garbage
* @return average current in milli-amps
*/
public static double getAverageCurrent() {
if (mInstance.mBatteryManager == null) {
return Double.NaN;
}
return mInstance.mBatteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_AVERAGE) / 1e3;
}
// getRemainingTime.............................................................................
/**
* Warning: garbage if getAverageCurrent() is garbage
* @return hours remaining
*/
public static double getRemainingTime() {
return getBatteryCapacity() / getAverageCurrent();
}
// getRemainingEnergy...........................................................................
/**
* Warning: usually garbage
* @return remaining power in milli-watt-hours
*/
public static double getRemainingEnergy() {
if (mInstance.mBatteryManager == null) {
return Double.NaN;
}
return mInstance.mBatteryManager.getLongProperty(BatteryManager.BATTERY_PROPERTY_ENERGY_COUNTER) / 1e6;
}
// getRemainingPower............................................................................
/**
* Warning: garbage if either getRemainingEnergy() or getRemainingTime() is garbage,
* i.e. most likely garbage
* @return average continuous milli-watts of power remaining
*/
public static double getRemainingPower() {
return getRemainingEnergy() / getRemainingTime();
}
// getInstantaneousPower........................................................................
/**
* Warning: either net power (out - in) or out power
* @return instantaneous power in milli-watts
*/
@Nullable
public static Double getInstantaneousPower() {
Double voltage = BatteryChanged.getCurrentVoltage();
if (voltage == null) {
return null;
}
double current = getInstantaneousCurrent();
return voltage * current;
}
// getAveragePower..............................................................................
/**
* Warning: garbage if getAverageCurrent() is garbage
* @return average power in milli-watts
*/
@Nullable
public static Double getAveragePower() {
Double voltage = BatteryChanged.getCurrentVoltage();
if (voltage == null) {
return null;
}
double current = getAverageCurrent();
return voltage * current;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// getCurrentIcon...............................................................................
/**
* TODO: No idea what the hell this is
* @return it's an integer, that's all I know
*/
@Contract(pure = true)
@Nullable
public static Integer getCurrentIcon() {
return BatteryChanged.getCurrentIcon();
}
// getTechnology................................................................................
/**
* Warning: most devices don't have this
* @return Likely a null string, otherwise it's text describing the technology (e.g. Li-ion)
*/
@Contract(pure = true)
@Nullable
public static String getTechnology() {
return BatteryChanged.getTechnology();
}
// isBatteryPresent.............................................................................
/**
* @return True if battery is identified by the system, false if not
*/
@Contract(pure = true)
@NonNull
public static Boolean isBatteryPresent() {
return BatteryChanged.isBatteryPresent();
}
// getCurrentHealth.............................................................................
/**
* @return "GOOD", "COLD", "DEAD", "OVERHEAT", "OVER VOLTAGE", "UNKNOWN", "UNSPECIFIED FAILURE",
* "UNKNOWN CONDITION OR NOT AVAILABLE"
*/
@Contract(pure = true)
@Nullable
public static String getCurrentHealth() {
return BatteryChanged.getCurrentHealth();
}
// getCurrentStatus.............................................................................
/**
* @return "CHARGING", "DISCHARGING", "FULLY CHARGED", "NOT CHARGING", "CHARGING STATUS UNKNOWN",
* "UNKNOWN STATUS"
*/
@Contract(pure = true)
@Nullable
public static String getCurrentStatus() {
return BatteryChanged.getCurrentStatus();
}
// getCurrentPowerSource........................................................................
/**
* @return "USING BATTERY POWER ONLY", "USING AC ADAPTER POWER", "USING USB POWER",
* "USING WIRELESS POWER", "UNKNOWN POWER SOURCE"
*/
@Contract(pure = true)
@Nullable
public static String getCurrentPowerSource() {
return BatteryChanged.getCurrentPowerSource();
}
// getCurrentVoltage............................................................................
/**
* @return Battery voltage in volts
*/
@Contract(pure = true)
@Nullable
public static Double getCurrentVoltage() {
return BatteryChanged.getCurrentVoltage();
}
// mBatteryTemperature..........................................................................
/**
* @return Battery temperature in degrees Celsius
*/
@Contract(pure = true)
@Nullable
public static Double getCurrentTemperature() {
mStopWatch.start();
Double temperature = BatteryChanged.getCurrentTemperature();
mStopWatch.addTime();
return temperature;
}
// getCurrentLevel..............................................................................
/**
* @return Usually the same as getRemainingCapacity(), but could be energy or charge units
*/
@Contract(pure = true)
@Nullable
public static Integer getCurrentLevel() {
return BatteryChanged.getCurrentLevel();
}
// getScale.....................................................................................
/**
* @return Maximal value of getCurrentLevel(), usually 100 as in percent, but could be
* energy or charge or something..
*/
@Contract(pure = true)
@Nullable
public static Integer getScale() {
return BatteryChanged.getScale();
}
// getCurrentPercent............................................................................
/**
* @return Same as getRemainingCapacity(), but possibly (not often) higher precision
*/
@Contract(pure = true)
@Nullable
public static Double getCurrentPercent() { return BatteryChanged.getCurrentPercent(); }
////////////////////////////////////////////////////////////////////////////////////////////////
// getString....................................................................................
/**
* @return Status string of current battery conditions
*/
@NonNull
public static String getString() {
refresh();
String out = " \n";
out += "\t" + "Battery charge level: " + NumToString.number(getRemainingCapacity()) + "%\n";
out += "\t" + "Battery capacity: " + NumToString.number(getBatteryCapacity()) + " [mA hr]\n";
out += "\t" + "Instantaneous current: " + NumToString.number(getInstantaneousCurrent()) + " [mA]\n";
out += "\t" + "Average current: " + NumToString.number(getAverageCurrent()) + " [mA]\n";
out += "\t" + "Time until drained: " + NumToString.number(getRemainingTime()) + " [hr]\n";
out += "\t" + "Remaining energy: " + NumToString.number(getRemainingEnergy()) + " [mW hr]\n";
out += "\t" + "Remaining continuous power: " + NumToString.number(getRemainingPower()) + " [mW]\n";
Double power = getInstantaneousPower();
String powerString;
if (power == null) {
powerString = "UNKNOWN\n";
}
else {
powerString = NumToString.number(power) + " [mW]\n";
}
out += "\t" + "Instantaneous power: " + powerString;
power = getAveragePower();
if (power == null) {
powerString = "UNKNOWN\n";
}
else {
powerString = NumToString.number(power) + " [mW]\n";
}
out += "\t" + "Average power: " + powerString;
out += "\n";
out += mInstance.mBatteryChanged.getString();
return out;
}
// shutdown.....................................................................................
/**
* Disable battery broadcast listening
*/
public static void shutdown() {
mInstance.mBatteryChanged.shutdown();
}
}
|
package other;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Stack;
public class MergeOverlappingIntervals {
public class Interval {
int start;
int end;
Interval() {
start = 0;
end = 0;
}
Interval(int s, int e) {
start = s;
end = e;
}
}
public ArrayList<Interval> merge(ArrayList<Interval> intervals) {
if (intervals.size() < 2) {
return intervals;
}
intervals.sort(new Comparator<Interval>() {
@Override
public int compare(Interval a, Interval b) {
return a.start - b.start;
}
});
Stack<Interval> stack = new Stack<Interval>();
stack.push(intervals.get(0));
for (int i = 1; i < intervals.size(); i++) {
Interval b = intervals.get(i);
// if (stack.isEmpty() == false) {
Interval a = stack.pop();
if (a.end < b.start) {
System.out.println("push");
stack.push(a);
stack.push(b);
} else {
Interval n = new Interval(Math.min(a.start, b.start), Math.max(a.end, b.end));
System.out.println("new push" + n.start + " " + n.end);
stack.push(n);
}
// }
}
Stack<Interval> stack2 = new Stack<Interval>();
for(Interval i : stack) {
stack2.push(i);
}
ArrayList<Interval> res = new ArrayList<Interval>();
for(Interval i : stack2) {
res.add(i);
}
return res;
}
public static void main(String [] args) {
ArrayList<Interval> intervals = new ArrayList<Interval>();
MergeOverlappingIntervals merge = new MergeOverlappingIntervals();
intervals.add(merge.new Interval(8, 10));
intervals.add(merge.new Interval(1, 3));
intervals.add(merge.new Interval(2, 6));
intervals.add(merge.new Interval(15, 18));
ArrayList<Interval> result = merge.merge(intervals);
for(Interval i : result) {
System.out.println(i.start + " " + i.end);
}
}
}
|
package logic.game;
import util.MyStringUtils;
public class GamePrinter {
Game game;
int dimX;
int dimY;
String[][] board;
final String space = " ";
/** Constructor de GamePrinter */
public GamePrinter(Game game, int dimX, int dimY) {
this.game = game;
this.dimX = dimX;
this.dimY = dimY;
encodeGame(game);
}
/** Crea un array bidimensional de String y lo rellena de espacios. Luego recorre las listas añadiendo lo que sea oportuno en cada casilla y llama a el método toString. */
private void encodeGame(Game game) {
board = new String[dimX][dimY];
for (int i = 0; i < dimX; i++) {
for (int j = 0; j < dimY; j++) {
board[i][j] = space;
}
}
for (int i = 0; i < game.GetPScount(); i++) {
board[game.GetPSy(i)][game.GetPSx(i)] = game.PStoString(i);
}
for (int i = 0; i < game.GetSFcount(); i++) {
board[game.GetSFy(i)][game.GetSFx(i)] = game.SFtoString(i);
}
for (int i = 0; i < game.GetZcount(); i++) {
board[game.GetZy(i)][game.GetZx(i)] = this.game.ZtoString(i);
}
toString();
}
@Override
/** Usa MyStringUtils para hacer que el tablero sea imprimible de forma correcta y devuelve la string a imprimir.s */
public String toString() {
int cellSize = 7;
int marginSize = 2;
String vDelimiter = "|";
String hDelimiter = "-";
String rowDelimiter = MyStringUtils.repeat(hDelimiter, (dimY * (cellSize + 1)) - 1);
String margin = MyStringUtils.repeat(space, marginSize);
String lineDelimiter = String.format("%n%s%s%n", margin + space, rowDelimiter);
StringBuilder str = new StringBuilder();
str.append(lineDelimiter);
for(int i=0; i<dimX; i++) {
str.append(margin).append(vDelimiter);
for (int j=0; j<dimY; j++) {
str.append( MyStringUtils.centre(board[i][j], cellSize)).append(vDelimiter);
}
str.append(lineDelimiter);
}
return str.toString();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.