text stringlengths 10 2.72M |
|---|
package Assignment_1;
import java.nio.file.*;
import java.util.*;
public class A11 {
public static void main(String[] args) throws Exception {
String content = new String(Files.readAllBytes(Paths.get(args[0])));
LinkedHashSet<String> identifiersUsed = new LinkedHashSet<>(Arrays.asList("WRITE", "READ", "IF", "ELSE", "RETURN", "BEGIN", "END", "MAIN", "STRING", "INT", "REAL"));
int start = 0, pos;
boolean found = false;
for (int i = 0; i < content.length(); i++){
char c = content.charAt(i);
if(Character.isLetter(c) && !found){
found = true;
start = i;
}
if (c == '"') {
if ((pos = isQuoted(content.substring(i + 1), i))!= -1) i = pos;
}
if (!Character.isLetterOrDigit(c) && found) {
found = false;
identifiersUsed.add(content.substring(start, i));
}
}
Files.write(Paths.get("./A1.output"), ("Identifiers: " + (identifiersUsed.size() - 11)).getBytes());
}
private static int isQuoted(String content, int start){
for (int i = 0; i < content.length(); i++) if (content.charAt(i) == '"') return ++i + start;
return -1;
}
} |
package switch2019.project.domain.domainEntities.ledger;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import switch2019.project.domain.domainEntities.person.Address;
import switch2019.project.domain.domainEntities.person.Email;
import switch2019.project.domain.domainEntities.person.Person;
import switch2019.project.domain.domainEntities.shared.*;
import java.time.format.DateTimeFormatter;
import java.util.Currency;
import static org.junit.jupiter.api.Assertions.*;
class TransactionTest {
/**
* Test to see if two transactions are the equals
*/
/*
@Test
@DisplayName("Test if two transactions are the equals - true")
public void testIfTwoTransactionsAreEqualsTrue() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
TransactionJpa transactionJpa = new TransactionJpa( "Switch", 10.0, "euros",
"HomeShopping", "20-05-2020", "shop", "bcp", "bpi", "true");
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(true, result);
}
*/
@Test
@DisplayName("Test if two transactions are the same - true")
public void testIfDatesAreTheSameWithToString() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13,13,02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"),date, category, account1, account2,new Type (false));
String test = transaction.dateToString();
//Act
boolean result = test.equals("2020-01-13 13:02");
//Assert
assertTrue(result);
}
@Test
@DisplayName("Test if two transactions are the same - true")
public void testIfTwoTransactionsAreTheSame() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction);
//Assert
assertTrue(result);
}
@Test
@DisplayName("Test if two transactions are the equals - different account to")
public void testIfTwoTransactionsAreEqualsDifferentAccountTo() {
//Arrange
Person person = new Person("Jose", new DateAndTime(1995, 12, 13),
new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt"));
AccountID account1 = new AccountID(new Denomination("mercearia"), person.getID());
AccountID account2 = new AccountID(new Denomination("transporte"), person.getID());
AccountID account3 = new AccountID(new Denomination("bowling"), person.getID());
CategoryID category = new CategoryID(new Denomination("grocery"), person.getID());
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account3, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - false - different account from")
public void testIfTwoTransactionsAreEqualsFalseDifferentAccountFrom() {
//Arrange
Person person = new Person("Jose", new DateAndTime(1995, 12, 13),
new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt"));
AccountID account1 = new AccountID(new Denomination("mercearia"), person.getID());
AccountID account2 = new AccountID(new Denomination("transporte"), person.getID());
AccountID account3 = new AccountID(new Denomination("bowling"), person.getID());
CategoryID category = new CategoryID(new Denomination("grocery"), person.getID());
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), null, category, account3, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - false - different category")
public void testIfTwoTransactionsAreEqualsFalseDifferentCategory() {
//Arrange
Person person1 = new Person("Alexandre", new DateAndTime(1995, 12, 13), new Address("Porto"),
new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt"));
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),person1.getID());
CategoryID category2 = new CategoryID(new Denomination("transport"),person1.getID());
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), null, category2, account1, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - false - different monetary value")
public void testIfTwoTransactionsAreEqualsFalseDifferentMonetaryValue() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
MonetaryValue monetaryValue2 = new MonetaryValue(30, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue2, new Description("payment"), null, category, account1, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - false - different description")
public void testIfTwoTransactionsAreEqualsFalseDifferentDescription() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("transportation"), null, category, account1, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - false - different date")
public void testIfTwoTransactionsAreEqualsFalseDifferentDate() {
//Arrange
AccountID account1 = new AccountID(new Denomination("Health"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("Transport"),new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - different types")
public void testIfTwoTransactionsAreEqualsDifferentTypes() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("House"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (true));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - True - system date")
public void testIfTwoTransactionsAreEqualsTrueSystemDate() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("House"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime dateNow = new DateAndTime();
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), dateNow, category, account1, account2, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(true, result);
}
@Test
@DisplayName("Test if two transactions are the equals - one is null")
public void testIfTwoTransactionsAreEqualsOneIsNull() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = null;
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - different objects")
public void testIfTwoTransactionsAreEqualsDifferentObjects() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Person person1 = new Person("António", new DateAndTime(1995, 12, 4), new Address("Porto"),
new Address("Rua 2", "Porto", "4620-580"), new Email("1234@isep.pt"));
//Act
boolean result = transaction.equals(person1);
//Assert
assertEquals(false, result);
}
@Test
@DisplayName("Test if two transactions are the equals - false")
public void testIfTwoTransactionsAreEqualsFalse() {
//Arrange
Person person = new Person("Jose", new DateAndTime(1995, 12, 13),
new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt"));
AccountID account1 = new AccountID(new Denomination("mercearia"), person.getID());
AccountID account2 = new AccountID(new Denomination("transporte"), person.getID());
AccountID account3 = new AccountID(new Denomination("bowling"), person.getID());
CategoryID category = new CategoryID(new Denomination("grocery"), person.getID());
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), null, category, account1, account3, new Type (false));
//Act
boolean result = transaction.equals(transaction2);
//Assert
assertEquals(false, result);
}
/**
* Tests for the Transaction method toString
*/
@Test
@DisplayName("Test if method toString returns String Transaction")
public void validateToString() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
String expected = "2020-01-13 13:02 | 200.0 EUR DEBIT | MERCEARIA -> TRANSPORTE | Description: \"PAYMENT\" | GROCERY";
//Act
String result = transaction.toString();
//Assert
assertEquals(expected, result);
}
@Test
@DisplayName("Test if method toString returns String Transaction for Credit")
public void validateToStringCredit() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail2@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (true));
String expected = "2020-01-13 13:02 | 200.0 EUR CREDIT | MERCEARIA -> TRANSPORTE | Description: \"PAYMENT\" | GROCERY";
//Act
String result = transaction.toString();
//Assert
assertEquals(expected, result);
}
/**
* Test if two transactions have the same hashcode
*/
@Test
@DisplayName("Test if two transactions have the same hashcode - true")
public void testIfTwoTransactionsHaveTheSameHashcode() {
//Arrange & Act
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
//Assert
assertEquals(transaction.hashCode(), transaction2.hashCode());
}
@Test
@DisplayName("Test if two transactions have the same hashcode - not the same")
public void testIfTwoTransactionsHaveTheSameHashcodeNo() {
//Arrange & Act
Person person = new Person("Jose", new DateAndTime(1995, 12, 13),
new Address("Lisboa"), new Address("Rua X", "Porto", "4520-266"), new Email("1234@isep.pt"));
AccountID account1 = new AccountID(new Denomination("mercearia"),person.getID());
AccountID account2 = new AccountID(new Denomination("transporte"), person.getID());
AccountID account3 = new AccountID(new Denomination("bowling"), person.getID());
CategoryID category = new CategoryID(new Denomination("grocery"), person.getID());
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account2, new Type (false));
Transaction transaction2 = new Transaction(monetaryValue, new Description("payment"), date, category, account1, account3, new Type (false));
//Assert
assertNotEquals(transaction.hashCode(), transaction2.hashCode());
}
/**
* Tests to validate if a transaction was created
*/
@Test
@DisplayName("Test for validating transaction - success case")
void isAValidTransactionTrue() {
//Arrange
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"),new PersonID(new Email("personEmail@email.pt")));
//Act
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), localDateTime, category, account1, account2, new Type (true));
//Assert
assertTrue(transaction != null);
}
@Test
@DisplayName("Test for validating transaction - with no automatic date - success case")
void isAValidTransactionWithNoAutomaticDate() {
//Arrange
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"),
new PersonID(new Email("personEmail@email.pt")));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//Act
Transaction transaction = new Transaction(monetaryValue, new Description("payment"), localDateTime, category, account1, account2, new Type (false));
//Assert
assertTrue(transaction != null);
}
@Test
@DisplayName("Test for validating transaction - null monetary value")
void isAValidTransactionFalseNullMonetaryValue() {
//Arrange
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"),new PersonID(new Email("personEmail@email.pt")));
//Act
try {
new Transaction(null, new Description("payment"), localDateTime, category, account1, account2, new Type (true));
}
//Assert
catch (IllegalArgumentException description) {
assertEquals("The monetary value cannot be null.", description.getMessage());
}
}
@Test
@DisplayName("Test for validating transaction - negative monetary value")
void isAValidTransactionFalseNuegativeMonetaryValue() {
//Arrange
MonetaryValue monetaryValue = new MonetaryValue(-200, Currency.getInstance("EUR"));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
//Act
try {
new Transaction(monetaryValue, new Description("payment"), localDateTime, category, account1, account2, new Type (true));
}
//Assert
catch (IllegalArgumentException description) {
assertEquals("The monetary value cannot be negative.", description.getMessage());
}
}
@Test
@DisplayName("Test for validating transaction - null category")
void isAValidTransactionFalseNullCategory() {
//Arrange
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
AccountID account1 = new AccountID(new Denomination("mercearia"),new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
//Act
try {
new Transaction(monetaryValue, new Description("payment"), localDateTime, null, account1, account2, new Type (true));
}
//Assert
catch (IllegalArgumentException description) {
assertEquals("The category cannot be null.", description.getMessage());
}
}
@Test
@DisplayName("Test for validating transaction - null account1")
void isAValidTransactionFalseNullAccount1() {
//Arrange
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
AccountID account2 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
//Act
try {
new Transaction(monetaryValue, new Description("payment"), localDateTime, category, null, account2, new Type (true));
}
//Assert
catch (IllegalArgumentException description) {
assertEquals("The accounts cannot be null.", description.getMessage());
}
}
@Test
@DisplayName("Test for validating transaction - null account2")
void isAValidTransactionFalseNullAccount2() {
//Arrange
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
//Act
try {
new Transaction(monetaryValue, new Description("payment"), localDateTime, category, account1, null, new Type (true));
}
//Assert
catch (IllegalArgumentException description) {
assertEquals("The accounts cannot be null.", description.getMessage());
}
}
@Test
@DisplayName("Test for validating transaction - null type")
void isAValidTransactionFalseNullType() {
//Arrange
DateAndTime localDateTime = new DateAndTime(2010, 07, 10, 20, 30);
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
//Act
try {
new Transaction(monetaryValue, new Description("payment"), localDateTime, category, account1, account2, new Type (false));
}
//Assert
catch (IllegalArgumentException description) {
assertEquals("The type can´t be null. Please try again.", description.getMessage());
}
}
/**
* Validate method to get Description
*/
@Test
@DisplayName("Test for getDescription")
void getDescription() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Description description = new Description("Payment");
Transaction transaction = new Transaction(monetaryValue, description, date, category, account1, account2,
new Type (false));
//Act
Description result = transaction.getDescription();
//Assert
assertEquals(description, result);
}
/**
* Validate method categoryToString
*/
@Test
@DisplayName("Test for categoryToString")
void categoryToString() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Description description = new Description("Payment");
Transaction transaction = new Transaction(monetaryValue, description, date, category, account1, account2,
new Type (false));
String expected = "GROCERY, personemail@email.com";
//Act
String result = transaction.categoryToString();
//Assert
assertEquals(expected, result);
}
/**
* Validate method amountToString
*/
@Test
@DisplayName("Test for amountToString")
void amountToString() {
//Arrange
AccountID account1 = new AccountID(new Denomination("mercearia"), new PersonID(new Email("personEmail@email.pt")));
AccountID account2 = new AccountID(new Denomination("transporte"), new PersonID(new Email("personEmail@email.pt")));
CategoryID category = new CategoryID(new Denomination("grocery"),new PersonID(new Email("personEmail@email.com")));
MonetaryValue monetaryValue = new MonetaryValue(200, Currency.getInstance("EUR"));
DateAndTime date = new DateAndTime(2020, 1, 13, 13, 02);
Description description = new Description("Payment");
Transaction transaction = new Transaction(monetaryValue, description, date, category, account1, account2,
new Type (false));
String expected = "200.0 EUR";
//Act
String result = transaction.amountToString();
//Assert
assertEquals(expected, result);
}
} |
package com.artland.service.impl;
import com.artland.dao.BlogTagMapper;
import com.artland.dao.BlogTagRelationMapper;
import com.artland.entity.BlogTag;
import com.artland.entity.BlogTagCount;
import com.artland.service.TagService;
import com.artland.util.PageQueryUtil;
import com.artland.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import java.util.List;
/**
* @author WaylanPunch
* @email waylanpunch@gmail.com
* @link https://github.com/WaylanPunch
* @date 2017-10-31
*/
@Service
public class TagServiceImpl implements TagService {
@Autowired
private BlogTagMapper blogTagMapper;
@Autowired
private BlogTagRelationMapper relationMapper;
@Override
public PageResult getBlogTagPage(PageQueryUtil pageUtil) {
List<BlogTag> tags = blogTagMapper.findTagList(pageUtil);
int total = blogTagMapper.getTotalTags(pageUtil);
PageResult pageResult = new PageResult(tags, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public int getTotalTags() {
return blogTagMapper.getTotalTags(null);
}
@Override
public Boolean saveTag(String tagName) {
BlogTag temp = blogTagMapper.selectByTagName(tagName);
if (temp == null) {
BlogTag blogTag = new BlogTag();
blogTag.setTagName(tagName);
return blogTagMapper.insertSelective(blogTag) > 0;
}
return false;
}
@Override
public Boolean deleteBatch(Integer[] ids) {
//已存在关联关系不删除
List<Long> relations = relationMapper.selectDistinctTagIds(ids);
if (!CollectionUtils.isEmpty(relations)) {
return false;
}
//删除tag
return blogTagMapper.deleteBatch(ids) > 0;
}
@Override
public List<BlogTagCount> getBlogTagCountForIndex() {
return blogTagMapper.getTagCount();
}
}
|
package br.com.satc;
import java.util.Scanner;
/**
*
* @author Edutec
*/
public class Main {
public static void main(String[] args) {
Scanner entrada = new Scanner(System.in);
System.out.println("Digite o valor do produto: ");
float valpro = entrada.nextFloat();
System.out.println("Digite se o produto é nacional ou importado: ");
String nacional = entrada.next();
String importado = entrada.next();
float valt = (float) (valpro * 0.1);
float valt15 = (float) (valpro * 0.15);
float valt50 = (float) (valpro * 0.50);
if (nacional.toUpperCase().equals("NACIONAL")) {
if (valpro <= 999) {
System.out.println("O valor do produto é " + valpro + "\n"
+ "o valor pago de impostos será de " + valt + " .");
} else if (valpro >= 1000) {
System.out.println("O valor do poduto é " + valpro);
System.out.println("O valor pago de impostos será de " + valt15);
} else {
if (importado.toUpperCase().equals("IMPORTADO")) {
System.out.println("O valor do produto é" + valpro);
System.out.println("Ovalor pago de impostos será de " + valt50);
}
}
}
}
} |
package com.comp486.knightsrush;
public class LevelPreferences {
public static final String PREFERENCE_DIFFICULTY_COMPLETED = "difficultyCompleted";
public static final String PREFERENCE_DIFFICULTY = "difficulty";
public static final String PREFERENCE_ACT = "actRow";
public static final String PREFERENCE_AREA = "areaIndex";
public static final String PREFERENCE_AREA_COMPLETED = "areaCompleted";
public static final String PREFERENCE_QUEST = "questIndex";
public static final String PREFERENCE_ACT_COMPLETED = "actCompleted";
}
|
package com.marlabs.project.model;
//this is for testing
import java.util.Iterator;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestQuestion {
static Session session;
//static Transaction transaction;
public static void main(String[] args) {
session = SessionFactoryUtil.getSessionFactory().getCurrentSession();
//session.beginTransaction();
session.close();
//screateQuestion();
//queryQuestion(session);
// transaction.commit();
}
private static List<Question> queryQuestion() {
session.beginTransaction();
Query query = session.createQuery("from Question");
List<Question> list = query.list();
Iterator<Question> iter = list.iterator();
while (iter.hasNext()) {
Question question = iter.next();
System.out.println("Question: \"" + question.getDescription() +"\n" + question.getOptions() +"\n");
}
session.getTransaction().commit();
return list;
}
public static void createQuestion() {
session.beginTransaction();
Question question = new Question();
String description = "what is the sexiest job today? this is a demo question";
String explanation = "no need";
String answer = "B";
String optionA = "president of america";
String optionB = "java web developer";
String optionC = "ceo of google";
String optionD = "Jin Chong Un";
question.setDescription(description);
//question.setId(1);
question.setAnswer(answer);
question.setExplanation(explanation);
question.addOption("A",optionA);
question.addOption("B",optionB);
question.addOption("C",optionC);
question.addOption("D",optionD);
question.setGroupTitle("demo");
//transaction.commit();
int id = (int) session.save(question);
System.out.println(id);
session.getTransaction().commit();
}
}
|
package jp.co.nttdata.rate.fms.core.keyword;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import jp.co.nttdata.rate.exception.FmsRuntimeException;
import jp.co.nttdata.rate.fms.calculate.ICalculateContext;
import jp.co.nttdata.rate.fms.core.Parentheses;
import jp.co.nttdata.rate.fms.core.Range;
import jp.co.nttdata.rate.fms.core.Sequence;
import jp.co.nttdata.rate.fms.core.Token;
import jp.co.nttdata.rate.log.LogFactory;
public abstract class Loop extends Keyword {
private static final long serialVersionUID = 1L;
private static Logger logger = LogFactory.getInstance(Loop.class);
public static final String INDEX = "index";
/** 連続計算のキーワード:sumまたはmult */
protected String keyword;
private String text;
private ICalculateContext _ctx;
private Sequence loopSeq;
/** 合計の条件の範囲 */
private Range condRange;
/** 始値tokens */
private Sequence startSeq;
/** 終値tokens */
private Sequence endSeq;
/** ループの計算ボディ */
private Body body;
/** 合計・累乗の初期値 */
protected BigDecimal ret = null;
public Loop(String keyword, Sequence seq, int pos) {
super(seq, pos);
this.keyword = keyword;
this._ctx = seq.getContext();
if (SUM.equals(keyword)) {
this.type = KeywordType.SUM;
} else {
this.type = KeywordType.MULT;
}
compile();
}
@Override
public void compile() {
// キーワードより範囲を取得
r = getKeywordRange(this.seq, keyword, this.searchRange);
if (r == null) {
throw new FmsRuntimeException("sumやmultのようなループ処理が存在していない");
}
this.loopSeq = this.seq.subSequence(r);
this.text = this.loopSeq.toString();
// 上下限の範囲を取得
int closePos = Parentheses.posMatchCloseParenthese(loopSeq, 1);
this.condRange = new Range(1, closePos);
_getParaInfo(this.condRange);
// ループ計算のボディ
body = new Body(loopSeq, closePos);
setBlocks = body.seq.getAllSetBlocks();
// 有効性チェック
_validate();
}
/**
* 書き方の有効性チェック <br>
* startとmaxの間にコンマが必ず入れる、またstart<max <br>
* bodyの中身にindexが必ず入れる
*
* @throws FmsRuntimeException
*/
private void _validate() {
// コンマ入れのチェック
boolean flg = false;
for (int i = this.condRange.start + 1; i < this.condRange.end; i++) {
if (this.loopSeq.get(i).mark == 'C') {
flg = true;
}
}
if (!flg) {
throw new FmsRuntimeException(this.keyword + "について、始値と終値の間にコンマを入れてください。");
}
// ループカウントindexの存在チェック
if (!_containIndexToken(this.body.seq)) {
throw new FmsRuntimeException(this.keyword + "ループのボディ{}のなかにカウンターindexを入れてください。");
}
}
/**
* ループカウントindexの存在チェック
*
* @param seq
* @return
*/
private boolean _containIndexToken(Sequence seq) {
boolean flg = false;
for (Token t : seq) {
if (t.isVariable()) {
if (t.toVariable().getName().equals(INDEX)) {
return true;
}
} else if (t.isArray()) {
flg = _containIndexToken(t.toArray().indexToken);
} else {
;
}
}
return flg;
}
/**
* SUMのパラメータ範囲より、パラメータ情報(始値、終値)を取得
*
* @param r
*/
private void _getParaInfo(Range r) {
int i = r.start;
/*
* <formula name="sumMaxVV" paras="j,max">
* sum(j,max){
* set{out=index}
* max{sumVij(index,k),sumVij(index,h+index-1)}
* }
* </formula>
* 公式にはパターを指定した場合、そのjとmaxはパラメータの値のまま使う 特に指定しない場合、レートキーや臨時変数を見なして探す
*/
// 括弧ペアマッチのカウント
int openParentheseCount = 0;
while (i < r.end) {
/*
* 特に下記のような算式の場合、コンマの位置を算出するのは、括弧ペアのマッチ は考慮しなければならない
* 1/D[x+t]*sum(max(t,gg),omega-x){D[x+index]*(1+theta1*index)}
*/
Token t = loopSeq.get(i);
if (t.mark == '(') {
// オープン括弧の場合
openParentheseCount++;
} else if (t.mark == ')') {
// オープン括弧の場合
openParentheseCount--;
}
// 一番外のオープン括弧にマッチするおよびコンマの場合、上下限の計算シーケンスを分ける
if (t.mark == Token.COMMA && openParentheseCount == 1) {
this.startSeq = loopSeq.subSequence(new Range(r.start + 1, i - 1));
this.endSeq = loopSeq.subSequence(new Range(i + 1, r.end - 1));
break;
}
i++;
}
}
/**
* 合計の値を算出
*
* @return
* @throws Exception
*/
@Override
public Token calculate() throws Exception {
// コンテキストより始値・終値を算出
Sequence indexCopy = (Sequence) startSeq.clone();
BigDecimal bIndex = indexCopy.eval();
int index = bIndex.intValue();//始値
Sequence maxCopy = (Sequence) endSeq.clone();
int max = maxCopy.eval().intValue();//終値
// start<=maxという制限のチェック
if (index > max) {
//throw new FmsRuntimeException(MessageFormat.format(msg, this.text, index, max));
if (logger.isInfoEnabled()) {
String msg = "{0}について、始値{1}は終値{2}に超えてしまったため、ゼロを返す。";
logger.warn(MessageFormat.format(msg, this.text, index, max));
}
this.resultToken = new Token(BigDecimal.ZERO, 'D', 0, 1);
return this.resultToken;
}
if (logger.isDebugEnabled()) {
logger.debug(this.text + "にてループの範囲:" + index + "〜" + max);
}
Map<String, Object> indexMap = new HashMap<String, Object>();
// 後ろの計算で利用されるため、上位のパラメータMAPをコピーしたうえindexをコンテキストのパラメータstackにpush
Map<String, Object> lastParas = _ctx.getLastParas();
if (lastParas != null) {
indexMap.putAll(lastParas);
}
indexMap.put(INDEX, bIndex);
_ctx.addFunctionPara(indexMap);
if (SUM.equals(this.keyword)) {
this.ret = BigDecimal.ZERO;
// 合計を行う
while (index <= max) {
// 計算用ボディをコピー
Body copy = (Body) body.clone();
ret = ret.add(copy.value());
index++;
// 他の計算式に利用されるため、SYS保留変数のindexを更新
indexMap.put(INDEX, new BigDecimal(index));
}
} else {
this.ret = BigDecimal.ONE;
// 累乗を行う
while (index <= max) {
// 計算用ボディをコピー
Body copy = (Body) body.clone();
ret = ret.multiply(copy.value());
index++;
// 他の計算式に利用されるため、SYS保留変数のindexを更新
indexMap.put(INDEX, new BigDecimal(index));
}
}
_ctx.clearCurrentFunctionPara();
// 計算結果を全体の計算tokensにセットする
this.resultToken = new Token(ret, 'D', 0, 1);
return this.resultToken;
}
} |
package com.zxjdev.smile.domain.common.base;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseMapper<T, O> {
public abstract T transform(O data);
public List<T> transform(List<O> dataList) {
List<T> output = new ArrayList<>();
if (dataList != null) {
for (O data : dataList) {
output.add(transform(data));
}
}
return output;
}
}
|
package com.philippe.app.domain;
public enum Outcome {
DELIVERED, RETURNED;
}
|
package controller.service.transaction;
import controller.exception.ServiceLayerException;
import model.exception.DAOException;
import java.sql.Connection;
public interface VoidTransactionUnit {
void execute(Connection connection) throws DAOException, ServiceLayerException;
}
|
package com.bw.movie.mvp.view.apdater;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.bw.movie.R;
class MyRexommwnViewHoder extends RecyclerView.ViewHolder {
public ImageView ivRxImage;
public TextView tvReName;
public TextView tvRxTitle;
public TextView tvRxJuli;
public ImageView ivRxGuanzhu;
public MyRexommwnViewHoder(View itemView) {
super(itemView);
ivRxImage = itemView.findViewById(R.id.iv_rx_image);
tvReName = itemView. findViewById(R.id.tv_re_name);
tvRxTitle = itemView.findViewById(R.id.tv_rx_title);
tvRxJuli = itemView. findViewById(R.id.tv_rx_juli);
ivRxGuanzhu = itemView. findViewById(R.id.iv_rx_guanzhu);
}
}
|
package pk.edu.kics.dsl.qa.util;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.math3.util.Precision;
import pk.edu.kics.dsl.qa.BiomedQA;
public class CollectionHelper {
public static Map<String, Double> sortByComparator(Map<String, Double> unsortMap, final boolean order)
{
List<Entry<String, Double>> list = new LinkedList<Entry<String, Double>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Entry<String, Double>>()
{
public int compare(Entry<String, Double> o1,
Entry<String, Double> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
for (Entry<String, Double> entry : list)
{
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
public static Map<String, Double> sortByComparatorInt(Map<String, Integer> unsortMap, final boolean order)
{
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(unsortMap.entrySet());
Collections.sort(list, new Comparator<Entry<String, Integer>>()
{
public int compare(Entry<String, Integer> o1,
Entry<String, Integer> o2)
{
if (order)
{
return o1.getValue().compareTo(o2.getValue());
}
else
{
return o2.getValue().compareTo(o1.getValue());
}
}
});
// Maintaining insertion order with the help of LinkedList
Map<String, Double> sortedMap = new LinkedHashMap<String, Double>();
for (Entry<String, Integer> entry : list)
{
sortedMap.put(entry.getKey(), (double) entry.getValue());
}
return sortedMap;
}
public static <T,U> String getTopTerms(Map<T,U> terms, int termsToSelect) {
StringBuilder sb = new StringBuilder();
StringBuilder sb_debug = new StringBuilder();
int counter = 1;
for (Map.Entry<T,U> entry : terms.entrySet()) {
String key = (String) entry.getKey();
sb.append(key).append(" ");
if(BiomedQA.DISPLAY_RESULTS) {
sb_debug.append(key).append("(").append(Precision.round(Double.parseDouble(entry.getValue().toString()), 2)).append(") | ");
}
if(counter++>=termsToSelect) break;
}
if(BiomedQA.DISPLAY_RESULTS) {
System.out.println(sb_debug.toString());
}
return sb.toString();
}
public static Map<String, Double> normalizeScore(Map<String, Double> deNormalizedMap)
{
Map<String, Double> normalizedMap = new LinkedHashMap<String, Double>();
double highest_score = 0.0;
Map.Entry<String,Double> firstEntry = deNormalizedMap.entrySet().iterator().next();
highest_score = firstEntry.getValue();
for (Map.Entry<String, Double> entry : deNormalizedMap.entrySet()) {
normalizedMap.put(entry.getKey(), entry.getValue()/highest_score);
}
return normalizedMap;
}
}
|
package com.ifre.ruleengin.hotcompiler;
import java.net.URI;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
/**
* 缓存字符串格式代码
*
* @author majiang
* @version 2016-06-29
* @since jdk1.6.0
*/
public class StringFileObject extends SimpleJavaFileObject {
private String content;
public StringFileObject(String className, String content) {
super(URI.create("string:///" + className.replace('.', '/') +
JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE);
this.content = content;
}
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return this.content;
}
}
|
package com.phone1000.martialstudyself.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.phone1000.martialstudyself.R;
import com.phone1000.martialstudyself.constants.HttpUrlSecond;
import com.phone1000.martialstudyself.model.LatestGongFa;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by chen on 2016/11/29.
*/
public class BookContentAdapter extends BaseAdapter {
private List<LatestGongFa.ListBean> data;
private LayoutInflater inflater;
public BookContentAdapter(Context context) {
this.inflater = LayoutInflater.from(context);
data = new ArrayList<>();
}
public void updateRes(List<LatestGongFa.ListBean> data) {
if (data != null) {
this.data.clear();
this.data.addAll(data);
this.notifyDataSetChanged();
}
}
@Override
public int getCount() {
return data != null ? data.size() : 0;
}
@Override
public LatestGongFa.ListBean getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.book_latest_item, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(getItem(position).getInfo_title());
holder.comments.setText(getItem(position).getInfo_reply_count() + "");
holder.readcount.setText(getItem(position).getInfo_read_count() + "");
String info_img_path = getItem(position).getInfo_img_path();
String[] split = info_img_path.split(",");
if (split.length == 0) {
holder.image.setVisibility(View.GONE);
}
Picasso.with(holder.image.getContext()).load(HttpUrlSecond.IMAGE_BASE + split[0])
.into(holder.image);
// if (getItem(position).getInfo_type() == 2) {
// holder.video.setVisibility(View.VISIBLE);
// }
return convertView;
}
public void addRes(List<LatestGongFa.ListBean> data) {
if (data != null) {
this.data.addAll(data);
this.notifyDataSetChanged();
}
}
private static class ViewHolder {
TextView title, comments, readcount;
ImageView image, video;
public ViewHolder(View itemview) {
title = (TextView) itemview.findViewById(R.id.child_title);
comments = (TextView) itemview.findViewById(R.id.child_reply_count);
readcount = (TextView) itemview.findViewById(R.id.child_read_count);
image = (ImageView) itemview.findViewById(R.id.child_image);
video = (ImageView) itemview.findViewById(R.id.child_video);
}
}
}
|
package com.rcwang.seal.fetch;
import static org.junit.Assert.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.junit.BeforeClass;
import org.junit.Test;
import com.rcwang.seal.expand.EntityList;
import com.rcwang.seal.expand.Seal;
import com.rcwang.seal.util.GlobalVar;
public class GoogleCustomAPISearcherTest {
@BeforeClass
public static void initLog() throws FileNotFoundException, IOException {
Properties logging = new Properties();
logging.load(new FileInputStream(new File("config/log4j.properties")));
PropertyConfigurator.configure(logging);
Logger.getLogger(GoogleCustomAPISearcher.class).debug("Testing debug log");
}
@Test
public void testOnline() throws FileNotFoundException, IOException {
GlobalVar gv = GlobalVar.getGlobalVar();
gv.load("config/seal.properties.googlecustom");
Seal s = new Seal();
List<String> el = new ArrayList<String>(); Collections.addAll(el,"birds","fish","bears","deer");
s.expand(new EntityList(el));
System.out.println(s.getEntityList().toDetails(20));
assertTrue(s.getEntityList().size() > 0);
}
}
|
package com.goldgov.gtiles.core.web;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.filter.CharacterEncodingFilter;
public class GTilesCharacterEncodingFilter extends CharacterEncodingFilter{
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
if(!GTilesContext.isInstalled()){
String installUri = getInstallBaseUrl(request) + "/installWizard.do";
if(request.getRequestURI().equals(installUri)){
super.doFilterInternal(request, response, filterChain);
}else{
response.sendRedirect(installUri);
}
}else{
super.doFilterInternal(request, response, filterChain);
}
}
private String getInstallBaseUrl(HttpServletRequest request){
String contextPath = request.getContextPath();
if(contextPath == null){
return "/install";
}
if(contextPath.equals("/")){
return "/install";
}
return contextPath + "/install";
}
}
|
import java.util.Scanner;
public class RainFall
{
private double[] rain;
public RainFall(double[] r)
{
rain = new double[r.length];
for(int i = 0; i < r.length; i++)
{
rain[i] = r[i];
}
}
public double getTotalRain()
{
double total = 0.0;
for(int i = 0; i < rain.length; i++)
{
total += rain[i];
}
return total;
}
public double averageRainFaill()
{
double averageRain = getTotalRain() / rain.length;
return averageRain;
}
public double getHighestRainFall()
{
double high = rain[0];
for(int i = 1; i < rain.length; i++)
{
if(rain[i] > high)
{high = rain[i];}
}
return high;
}
public double getLowestRainFall()
{
double lowest = rain[0];
for(int i = 1; i < rain.length; i++)
{
if(rain[i] < lowest)
lowest = rain[i];
}
return lowest;
}
public double getRain(int i)
{
return rain[i];
}
}
|
package com.lingnet.vocs.dao.sewage;
import com.lingnet.common.dao.BaseDao;
import com.lingnet.vocs.entity.SewageBusiness;
public interface SewageBusinessDao extends BaseDao<SewageBusiness, String>{
}
|
package com.gigya.auth;
import com.gigya.socialize.GSArray;
import com.gigya.socialize.GSLogger;
import com.gigya.socialize.GSObject;
import com.gigya.socialize.GSResponse;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
public class GSAuthRequestUtils {
public static final String VERSION = "java_auth_1.0.1";
public static GSLogger logger = new GSLogger();
/**
* Caching the public keys.
* Key - data center (lower cased).
* Value - public key jwk.
*/
private static Map<String, String> publicKeysCache = new HashMap<>();
/**
* Explicitly add a public jwk to cache.
*
* @param dataCenterKey Data center as the key.
* @param jwk JWK value.
*/
public static void addToPublicKeyCache(String dataCenterKey, String jwk) {
publicKeysCache.put(dataCenterKey, jwk);
}
/**
* Clear public key cache.
*/
public static void clearPublicKeysCache() {
publicKeysCache.clear();
}
/**
* Clear cached public key from public keys cache.
*
* @param dataCenter Data center key.
*/
public static void clearPublicKeysCache(String dataCenter) {
publicKeysCache.remove(dataCenter);
}
/**
* Trim .pem style keys from delimiters and wrappers.
*
* @param raw Raw .pem style string.
* @return Stripped base64 encoded key.
*/
private static String trimKey(String raw) {
return raw
.replace("-----BEGIN PRIVATE KEY-----", "") //PKCS#8
.replace("-----END PRIVATE KEY-----", "") //PKCS#8
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace("\\r", "")
.replace("\n", "")
.replace("\\n", "");
}
/**
* Generate an RSA private key instance from given Base64 encoded String.
*
* @param encodedPrivateKey Base64 encoded private key String resource (RSA - PKCS#8).
* @return Generated private key instance.
*/
static PrivateKey rsaPrivateKeyFromBase64String(String encodedPrivateKey) {
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpecPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(
trimKey(encodedPrivateKey)));
return kf.generatePrivate(keySpecPKCS8);
} catch (Exception ex) {
logger.write("Failed to generate RSA private key from encoded string");
logger.write(ex);
ex.printStackTrace();
}
return null;
}
/**
* Generate an RSA public key instance from given Base64 encoded String.
*
* @param encodedPublicKey ase64 encoded public key String resource.
* @return Generated public key instance.
*/
static PublicKey rsaPublicKeyFromBase64String(String encodedPublicKey) {
try {
X509EncodedKeySpec spec = new X509EncodedKeySpec(Base64.getDecoder().decode(
trimKey(encodedPublicKey).getBytes()));
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
} catch (Exception ex) {
logger.write("Failed to generate RSA public key from encoded string");
logger.write(ex);
ex.printStackTrace();
}
return null;
}
/**
* Generate an RSA public key instance from JWK String.
*
* @param jwk JWK String.
* @return Generated public key instance.
*/
static PublicKey rsaPublicKeyFromJWKString(String jwk) {
try {
// JWK to json.
JSONObject jsonObject = new JSONObject(jwk);
final String n = jsonObject.getString("n");
final String e = jsonObject.getString("e");
KeyFactory kf = KeyFactory.getInstance("RSA");
BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(n)); //n
BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(e)); //e
return kf.generatePublic(new RSAPublicKeySpec(modulus, exponent));
} catch (Exception ex) {
logger.write(ex);
ex.printStackTrace();
}
return null;
}
/**
* Compost a JWT given account userKey and privateKey.
*
* @param userKey Account user key.
* @param privateKey Account Base64 encoded private key.
* @return Generated JWT String.
*/
public static String composeJwt(String userKey, String privateKey) {
// #1 - Decode RSA private key (PKCS#1).
final PrivateKey key = rsaPrivateKeyFromBase64String(privateKey);
if (key == null) {
logger.write("Failed to instantiate private key from Base64");
// Key generation failed.
return null;
}
// #2 - Add JWT headers.
final Map<String, Object> header = new HashMap<>();
header.put("alg", "RS256");
header.put("typ", "JWT");
header.put("kid", userKey);
// #3 - Compose & sign Jwt.
return Jwts.builder()
.setHeaderParams(header)
.setId(UUID.randomUUID().toString())
.setIssuedAt(Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime())
.signWith(key, SignatureAlgorithm.RS256)
.compact();
}
/**
* Verify JWT given apiKey and secret.
* ApiKey and secret are required to perform a GSRequest to fetch the DC public key.
* <p>
* Verify Gigya Id Token.
*
* @param jwt Id token.
* @param apiKey Client ApiKey.
* @param apiDomain Api domain.
* @return UID field if validation is successful.
*/
public static String validateSignature(String jwt, String apiKey, String apiDomain) {
final String kid = getKidFromJWSHeader(jwt);
if (kid == null) {
logger.write("Failed to parse kid header");
return null;
}
String publicJWK = null;
// Try to fetch from cache.
if (publicKeysCache.containsKey(apiDomain.toLowerCase())) {
publicJWK = publicKeysCache.get(apiDomain.toLowerCase());
}
if (publicJWK == null) {
// None in cache - fetch from network.
publicJWK = fetchPublicJWK(kid, apiKey, apiDomain);
}
if (publicJWK == null) {
// JWT not available.
logger.write("Failed to fetch jwk public key");
return null;
}
final PublicKey publicKey = GSAuthRequestUtils.rsaPublicKeyFromJWKString(publicJWK);
if (publicKey == null) {
logger.write("Failed to instantiate PublicKey instance from jwk");
return null;
}
// Update public key cache only when it was successfully generated. Useless otherwise.
publicKeysCache.put(apiDomain.toLowerCase(), publicJWK);
return verifyJwt(jwt, apiKey, publicKey);
}
/**
* Try to fetch the "kid" field from a jwt header.
*
* @param jws Json web token.
* @return Kid field from token header.
*/
static String getKidFromJWSHeader(String jws) {
String[] split = jws.split("\\.");
if (split.length > 0) {
final String encodedHeaders = split[0];
final String decodedHeaders = new String(Base64.getDecoder().decode(encodedHeaders.getBytes()));
// Parse json headers. Fetch kid fields.
try {
final JSONObject jsonObject = new JSONObject(decodedHeaders);
return jsonObject.getString("kid");
} catch (JSONException e) {
logger.write("Failed to parse jwk headers");
e.printStackTrace();
}
}
return null;
}
/**
* Fetch available public key JWK representation validated by the "kid".
*
* @param kid validation field.
* @param apiKey Site ApiKey.
* @param apiDomain Data center.
* @return Validated JWK.
*/
static String fetchPublicJWK(String kid, String apiKey, String apiDomain) {
// Fetch the public key using endpoint "accounts.getJWTPublicKey".
final GSAnonymousRequest request = new GSAnonymousRequest(apiKey, apiDomain, "accounts.getJWTPublicKey");
request.setParam("V2", true);
final GSResponse response = request.send();
if (response.getErrorCode() == 0) {
final GSArray keys = response.getArray("keys", null);
if (keys == null) {
logger.write("Failed to obtain JWK from response data");
return null;
}
if (keys.length() == 0) {
logger.write("Failed to obtain JWK from response data - data is empty");
return null;
}
for (Object key : keys) {
if (key instanceof GSObject) {
final String jwkKid = ((GSObject) key).getString("kid", null);
if (jwkKid != null && jwkKid.equals(kid)) {
return ((GSObject) key).toJsonString();
}
}
}
}
return null;
}
/**
* Verify JWT given public key instance & api key constraints.
*
* @param jwt JWT token to verify.
* @param apiKey Account ApiKey.
* @return UID field (jwt subject) if verified.
*/
static String verifyJwt(String jwt, String apiKey, PublicKey key) {
try {
// #1 - Parse token. Signing key must be available.
final Jws<Claims> claimsJws = Jwts.parser()
.setSigningKey(key)
.parseClaimsJws(jwt);
// #2 - Verify JWT provided api key with input api key.
final String issuer = claimsJws.getBody().getIssuer();
final String validIssuer = "https://fidm.gigya.com/jwt/" + apiKey + "/";
if (issuer != null && !issuer.equals(validIssuer)) {
logger.write("JWT verification failed - apiKey does not match");
return null;
}
// #3 - Verify current time is between iat & exp. Add 120 seconds grace period.
final long iat = claimsJws.getBody().get("iat", Long.class);
final long exp = claimsJws.getBody().get("exp", Long.class);
final long skew = 120; // Seconds.
final long currentTimeInUTC = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() / 1000; // UTC (seconds).
if (!(currentTimeInUTC >= iat && (currentTimeInUTC <= exp + skew))) {
logger.write("JWT verification failed - expired");
return null;
}
// #4 - Fetch the UID field - subject field of the jwt.
final String UID = claimsJws.getBody().getSubject();
if (UID != null) {
return UID;
}
} catch (Exception e) {
logger.write("Failed to verify jwt with exception");
logger.write(e);
e.printStackTrace();
}
return null;
}
}
|
package dominio;
import java.util.HashMap;
/**
* Una de las posibles razas de personajes que el jugador puede elegir La cual
* posee sus propias habilidades
*/
public class Humano extends Personaje {
private static final long serialVersionUID = 1L;
private static final int ENERGIAMINIMA = 10;
private static final int ENERGIAEXTRA = 5;
private static final int SALUDEXTRA = 5;
/**
* crea un personaje de raza "Humano" con nombre y casta enviados por
* parametro
* @param nombre Nombre del personaje
* @param casta Clase Casta
* @param id ID del personaje
*/
public Humano(final String nombre, final Casta casta, final int id) {
super(nombre, casta, id);
}
/**
* crea un personaje de raza humano con todas sus caracteristicas enviadas
* por parametro (nombre, saluda, energia, fuerza, etc)
* @param nombre Nombre del Personaje
* @param salud Cantidad de salud
* @param energia Cantidad de energia
* @param fuerza Cantidad de fuerza
* @param destreza Cantidad de destreza
* @param inteligencia Cantidad de inteligencia
* @param casta Clase Casta
* @param experiencia Cantidad de experiencia
* @param nivel Cantidad de nivel
* @param idPersonaje ID del personaje
*/
public Humano(final String nombre, final int salud, final int energia, final int fuerza,
final int destreza, final int inteligencia, final Casta casta,
final int experiencia, final int nivel, final int idPersonaje) {
super(nombre, salud, energia, fuerza, destreza, inteligencia, casta, experiencia, nivel, idPersonaje);
}
/**
* permite el uso de la habilidad "Incentivar" propia de la raza "humano" y
* realiza danio segun el ataque + la magia, cuesta 10 de Energia
* @param atacado Es el recibe el danio
* @param random Numero random de evitar el danio
* @return true Si se puede utilizar la habilidad del Golpe Critico
*/
public boolean habilidadRaza1(final Peleable atacado, final RandomGenerator random) {
HashMap<String, Integer> mapa = new HashMap<String, Integer>();
if (this.getEnergia() > ENERGIAMINIMA) {
mapa.put("energia", this.getEnergia() - ENERGIAMINIMA);
this.actualizar(mapa);
atacado.setAtaque(atacado.getAtaque() + this.getMagia());
return true;
}
return false;
}
/**
* permite el uso de la habilidad "Golpe Fatal" propia de la raza "humano" y
* reduce a la mitad la Salud del enemigo pero cuesta la mitad de la Energia
* @param atacado Es el recibe el danio
* @param random Numero random de evitar el danio
* @return true Si se puede utilizar la habilidad del Golpe Critico
*/
public boolean habilidadRaza2(final Peleable atacado, final RandomGenerator random) {
HashMap<String, Integer> mapa = new HashMap<String, Integer>();
if (this.getEnergia() > ENERGIAMINIMA) {
if (atacado.serAtacado(atacado.getSalud() / 2, random) > 0) {
mapa.put("energia", this.getEnergia() / 2);
this.actualizar(mapa);
return true;
}
}
mapa.put("energia", this.getEnergia() - ENERGIAMINIMA);
this.actualizar(mapa);
return false;
}
@Override
public final int getSALUDEXTRA() {
return SALUDEXTRA;
}
@Override
public final int getENERGIAEXTRA() {
return ENERGIAEXTRA;
}
@Override
public final String getNombreRaza() {
return "Humano";
}
@Override
public final String[] getHabilidadesRaza() {
return new String[] {"Incentivar", "Golpe Fatal"};
}
}
|
package com.javaneversleep.tankwar;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Save {
private boolean gameContinued;
private Position playerPosition;
private List<Position> enemyPositions;
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class Position {
private int x, y;
private Direction direction;
}
}
|
package io.github.jorelali.commandapi.api.exceptions;
@SuppressWarnings("serial")
public class SpigotNotFoundException extends RuntimeException {
private String className;
public SpigotNotFoundException(Class<?> c) {
className = c.getName();
}
@Override
public String getMessage() {
return "Cannot instantiate " + className + " because it requires Spigot.";
}
}
|
package twilight.bgfx.nanovg;
public enum NVGsolidity {
NVG_SOLID, NVG_HOLE
}
|
package searching;
import java.util.Scanner;
public class SquareRoot {
static int sRoot(int x)
{
int l=1,r=x,ans=-1;
while (l<=r)
{
int m=(l+r)/2;
int msquare=m*m;
if(msquare==x)
return m;
else if (msquare>x)
r=m-1;
else
{ l=m+1;
ans=m;
}
}
return ans;
}
public static void main(String[] args) {
System.out.println("enter the square");
Scanner sc=new Scanner(System.in);
int x= sc.nextInt();
int sroot=sRoot(x);
System.out.println("srooot="+sroot);
}
} |
package de.wdwelab.camunda.demo;
import de.wdwelab.camunda.BaseTest;
import org.camunda.bpm.engine.test.Deployment;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.scenario.Scenario;
import org.junit.Test;
import static org.mockito.Mockito.*;
/**
* @author Martin Schimak <martin.schimak@plexiti.com>
*/
@Deployment(resources = {"freischaltung-musikabo.bpmn", "vorauszahlung-ermitteln.dmn"})
public class FreischaltungMusikaboTest extends BaseTest {
@Test
public void vertragskunde_konto_ausgeglichen() {
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo").execute();
passed(times(1), "musikabo-freigeschalten");
}
@Test
public void vertragskunde_a_gemahnt() {
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo", Variables.createVariables().putValue("kunde", "1")).execute();
passed(times(1), "musikabo-freigeschalten");
}
@Test
public void vertragskunde_b_gemahnt_zahlung_ok() {
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo", Variables.createVariables().putValue("kunde", "2").putValue("kreditkarte", "123")).execute();
passed(times(1), "musikabo-freigeschalten");
passed(times(1), "vorauszahlung-einziehen");
passed(never(), "zahlungsdaten-bereitstellen");
}
@Test
public void prepaid_zahlung_ok() {
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo", Variables.createVariables().putValue("kunde", "3").putValue("kreditkarte", "123")).execute();
passed(times(1), "musikabo-freigeschalten");
passed(times(1), "vorauszahlung-einziehen");
passed(never(), "zahlungsdaten-bereitstellen");
}
@Test
public void prepaid_zahlung_nicht_ok() {
when(musikaboFreischaltung.waitsAtUserTask(anyString())).thenReturn(
task -> task.complete(Variables.createVariables().putValue("kreditkarte", "123")
));
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo", Variables.createVariables().putValue("kunde", "3")).execute();
passed(times(1), "musikabo-freigeschalten");
passed(times(2), "vorauszahlung-einziehen");
passed(times(1), "zahlungsdaten-bereitstellen");
}
@Test
public void vertragskunde_b_gemahnt_zahlung_nicht_ok() {
when(musikaboFreischaltung.waitsAtUserTask(anyString())).thenReturn(
task -> task.complete(Variables.createVariables().putValue("kreditkarte", "123")
));
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo", Variables.createVariables().putValue("kunde", "2")).execute();
passed(times(1), "musikabo-freigeschalten");
passed(times(2), "vorauszahlung-einziehen");
passed(times(1), "zahlungsdaten-bereitstellen");
}
@Test
public void vertragskunde_b_gemahnt_zahlung_nicht_ok_fristablauf() {
when(musikaboFreischaltung.waitsAtUserTask(anyString())).thenReturn(
task -> task.defer("P10D", () -> task.complete(Variables.createVariables().putValue("kreditkarte", "123"))
));
Scenario.run(musikaboFreischaltung)
.startByKey("freischaltung-musikabo", Variables.createVariables().putValue("kunde", "2")).execute();
passed(never(), "musikabo-freigeschalten");
passed(times(1), "vorauszahlung-einziehen");
passed(times(1), "zahlungsdaten-bereitstellen");
passed(times(1), "musikabo-nicht-freigeschalten");
}
}
|
package an1;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
import an1.persistence.Membres;
import an1.persistence.Reservations;
public class PageMembre {
private SessionBean1 sessionBean1;
public boolean isAdresse2NonNull() {
Membres m = sessionBean1.getMembreEnCours();
if (m == null) {
return false;
} else {
return (m.getAdresse2() != null);
}
}
public PageMembre() {
try {
sessionBean1 = (SessionBean1)FacesContext.getCurrentInstance()
.getExternalContext().getSessionMap().get("sessionBean1");
} catch (Exception e) {
// log("Calendrier Initialization Failure", e);
throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
}
}
public String deconnectionAction() {
return "login";
}
public String calendrierAction() {
return "calendrier";
}
public String modifMembreAction(){
sessionBean1.setRetourVersMembre(true);
return "modifMembre";
}
public String NouvelleReservationAction() {
sessionBean1.setRetourVersMembre(true);
Reservations res = new Reservations();
res.setCreate(true);
res.setStatut("Demande");
sessionBean1.setReservationEnCours(res);
return "reservation";
}
public String modifReservationAction() {
sessionBean1.setRetourVersMembre(true);
List<Reservations> res = sessionBean1.getReservationsMembreEnCours();
for (int i = 0; i < res.size(); i++) {
if (res.get(i).isSelected()) {
res.get(i).setCreate(false);
sessionBean1.setReservationEnCours(res.get(i));
break;
}
}
return "reservation";
}
}
|
package com.danielnamur.JavaBelt.service;
import java.util.List;
import java.util.Optional;
import org.springframework.stereotype.Service;
import com.danielnamur.JavaBelt.models.Rating;
import com.danielnamur.JavaBelt.repositories.RatingRepository;
@Service
public class RatingService {
private final RatingRepository ratingRepo;
public RatingService(RatingRepository ratingRepo) {
this.ratingRepo = ratingRepo;
}
public List<Rating> allRatings(){
return ratingRepo.findAll();
}
public Rating createRating(Rating rating) {
return ratingRepo.save(rating);
}
public Rating findRating(Long id) {
Optional<Rating> optionalRating = ratingRepo.findById(id);
if(optionalRating.isPresent()) {
return optionalRating.get();
} else {
return null;
}
}
} |
package com.sysh.mapper;
import com.sysh.dto.FamilyAb10Dto;
import com.sysh.entity.aduit.AduitDetailInfo;
import java.util.List;
import java.util.Map;
/**
* ClassName: <br/>
* Function: 信息审核的详情<br/>
* date: 2018年06月06日 <br/>
*
* @author 苏积钰
* @since JDK 1.8
*/
public interface InfoDetailDDMapper {
List<AduitDetailInfo> findDetail(Map<String, String> map);
String findTableName(Long id);
List<AduitDetailInfo> findEightDetail(Long id);
}
|
package com.example.iutassistant.Acitivities;
import android.app.DatePickerDialog;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.iutassistant.R;
public class Quiz_Announcement extends Fragment implements View.OnClickListener {
private EditText quizNo, syllabus, date, time;
private Button AssignmentPost;
public Quiz_Announcement() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_quiz__announcement, container, false);
quizNo = view.findViewById(R.id.et_quizNo);
syllabus = view.findViewById(R.id.et_quizSyllabus);
date = view.findViewById(R.id.et_quizDate);
time = view.findViewById(R.id.et_quizTime);
AssignmentPost = view.findViewById(R.id.quizPost);
return view;
}
@Override
public void onClick(View view) {
}
} |
/**
*
*/
package com.cnk.travelogix.b2c.storefront.validation;
import de.hybris.platform.acceleratorstorefrontcommons.forms.validation.RegistrationValidator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import com.cnk.travelogix.b2c.storefront.forms.EzgRegisterForm;
/**
* @author i322561
*
*/
@Component("ezgRegistrationValidator")
public class EzgRegistrationValidator extends RegistrationValidator
{
public static final Pattern PWD_REGEX = Pattern.compile(
"([0-9].*([a-zA-Z].*[~!@#$%^&*()+=|{}':;',\\[\\].<>/?~]|[~!@#$%^&*()+=|{}':;',\\[\\].<>/?~].*[a-zA-Z])|[a-zA-Z].*([0-9].*[~!@#$%^&*()+=|{}':;',\\[\\].<>/?~]|[~!@#$%^&*()+=|{}':;',\\[\\].<>/?~].*[0-9])|[~!@#$%^&*()+=|{}':;',\\[\\].<>/?~].*([0-9].*[a-zA-Z]|[a-zA-Z].*[0-9]))");
@Override
public void validate(final Object object, final Errors errors)
{
final EzgRegisterForm registerForm = (EzgRegisterForm) object;
final String email = registerForm.getEmail();
final String pwd = registerForm.getPwd();
final String checkPwd = registerForm.getCheckPwd();
final boolean tAndC = registerForm.istAndC();
validateEmail(errors, email);
validatePassword(errors, pwd);
comparePasswords(errors, pwd, checkPwd);
validateTAndC(errors, tAndC);
}
protected void validateTAndC(final Errors errors, final boolean tAndC)
{
if (!tAndC)
{
errors.rejectValue("tAndC", "validation.tAndC.invalid");
}
}
@Override
protected void validatePassword(final Errors errors, final String pwd)
{
if (StringUtils.isEmpty(pwd))
{
errors.rejectValue("pwd", "register.pwd.invalid");
}
else if (StringUtils.length(pwd) < 8 || StringUtils.length(pwd) > 255)
{
errors.rejectValue("pwd", "register.pwd.invalid");
}
else if (!checkPwdComplexity(pwd))
{
errors.rejectValue("pwd", "register.pwd.invalid");
}
}
private boolean checkPwdComplexity(final String pwd)
{
final Matcher m = PWD_REGEX.matcher(pwd);
return m.matches();
}
}
|
package com.company.ch10_UnionFind;
public class UnionFind1 implements UF{
private int[] id;
public UnionFind1(int size){
id=new int[size];
for (int i = 0; i < size; i++) {
id[i]=i;
}
}
private int find(int index){
if(index<0||index>=id.length)
throw new IllegalArgumentException("index is out of bound");
return id[index];
}
@Override
public int getSize() {
return id.length;
}
@Override
public void unionElements(int p, int q) {
int pID=find(p);
int qID=find(q);
if(pID==qID)
return;
for (int i = 0; i < id.length; i++) {
if(id[i]==pID)
id[i]=qID;
}
}
@Override
public boolean isConnected(int p, int q) {
return find(p)==find(q);
}
}
|
package com.thefuzzydragon.jen.codefellowship;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.view.RedirectView;
import java.security.Principal;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
@Controller
public class AppUserController {
@Autowired
AppUserRepository appUserRepository;
@Autowired
PasswordEncoder bCryptPasswordEncoder;
@GetMapping("/")
public String getWelcomePag() {
return "index";
}
@GetMapping("/myprofile")
public String getMyProfile(Principal p, Model m) {
m.addAttribute("principal", p);
AppUser currentUser = appUserRepository.findByUsername(p.getName());
m.addAttribute("currentUser", currentUser);
//get all users
Iterable<AppUser> users = appUserRepository.findAll();
List<AppUser> allUsers = new ArrayList<>();
users.forEach(allUsers::add);
allUsers.remove(currentUser);
m.addAttribute("allUsers", allUsers);
return "myprofile";
}
@PostMapping("/add/{username}")
public RedirectView follow(@PathVariable String username, Principal p) {
AppUser userToAdd = appUserRepository.findByUsername(username);
AppUser currentUser = appUserRepository.findByUsername(p.getName());
currentUser.following.add(userToAdd);
appUserRepository.save(currentUser);
return new RedirectView("/myprofile");
}
@GetMapping("/myprofile/{username}")
public String getFollowingProfile(@PathVariable String username, Model m, Principal p) {
m.addAttribute("principal", false);
AppUser loggedIn = appUserRepository.findByUsername(p.getName());
//converts principal object to my Model object
// AppUser currentUser = (AppUser)((UsernamePasswordAuthenticationToken) p).getPrincipal();
AppUser currentUser = appUserRepository.findByUsername(username);
m.addAttribute("currentUser", currentUser);
if(loggedIn.following.contains(currentUser)) {
m.addAttribute("alreadyFollowing", true);
} else {
m.addAttribute("alreadyFollowing", false);
}
return "myprofile";
}
@GetMapping("/signup")
public String signupPage() {
return "signup";
}
@PostMapping("/signup")
public RedirectView createUser(String username, String password, String firstName, String lastName, String bio, Date dateOfBirth) {
AppUser newUser = new AppUser(username, bCryptPasswordEncoder.encode(password), firstName, lastName, bio, dateOfBirth);
appUserRepository.save(newUser);
//get id
// AppUser dbUser = appUserRepository.findByUsername(username);
Authentication authentication = new UsernamePasswordAuthenticationToken(newUser, null, new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
return new RedirectView("/myprofile");
}
@GetMapping("/login")
public String getLoginPage() {
return "login";
}
} |
package pro.eddiecache.kits.paxos.messages;
import java.io.Serializable;
import pro.eddiecache.kits.paxos.comm.Member;
/**
* @author eddie
* 信息 并 携带发送者的信息
*/
public interface MessageWithSender extends Serializable
{
/**
* 获得发送者的相关信息 member
*/
Member getSender();
}
|
package com.appsnipp.homedesign2.Entity;
import android.app.Application;
import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.annotation.GlideOption;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Objects;
public class iRunning extends Application {
@Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
}
}
|
package switch2019.project.domain.domainEntities.ledger;
import switch2019.project.domain.domainEntities.frameworks.OwnerID;
import switch2019.project.domain.domainEntities.shared.*;
import switch2019.project.utils.StringUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
public class Ledger {
//Private Ledger variables
private final LedgerID ledgerID;
private final DateAndTime creationDate;
private final List<Transaction> ledgerTransactions;
private final ScheduledTasksList scheduledTasksList;
//String literals should not be duplicated
private static final String DATE_NOT_VALID = "One of the specified dates is not valid.";
private static final String DATE_CANT_NULL = "The specified dates cannot be null.";
public Ledger(OwnerID ownerID) {
ledgerID = new LedgerID(ownerID);
ledgerTransactions = new ArrayList<>();
scheduledTasksList = new ScheduledTasksList();
creationDate = new DateAndTime();
}
public Ledger(OwnerID ownerID, ArrayList<Transaction> transactions, DateAndTime creationDate) {
ledgerID = new LedgerID(ownerID);
ledgerTransactions = new ArrayList<>(transactions);
scheduledTasksList = new ScheduledTasksList(); // change later
this.creationDate = creationDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Ledger)) return false;
Ledger ledger = (Ledger) o;
return Objects.equals(ledgerID, ledger.ledgerID);
}
@Override
public int hashCode() {
return Objects.hash(ledgerID);
}
@Override
public String toString() {
return "Ledger:" + ledgerTransactions + ".";
}
public LedgerID getID() {
return ledgerID;
}
public List<Transaction> getLedgerTransactions() {
List<Transaction> newLedger = new ArrayList<>();
newLedger.addAll(ledgerTransactions);
return newLedger;
}
public int getLedgerSize() {
return this.ledgerTransactions.size();
}
public String getCreationDateToString() {return this.creationDate.yearMonthDayToString(); }
public boolean isTransactionInLedger(Transaction transactionInLedger) {
return ledgerTransactions.contains(transactionInLedger);
}
public Transaction addTransactionToLedger(MonetaryValue amount, Description description, DateAndTime localDate,
CategoryID category, AccountID accountFrom, AccountID accountTo, Type type) {
Transaction transaction = new Transaction(amount, description, localDate, category, accountFrom, accountTo, type);
ledgerTransactions.add(transaction);
sortLedgerByTransactionDateDescending();
return transaction;
}
public boolean scheduleNewTransaction(Periodicity periodicity, MonetaryValue amount, Description description, DateAndTime date,
CategoryID category, AccountID accountFrom, AccountID accountTo, Type type) {
return scheduledTasksList.addNewSchedule(this, periodicity, amount, description, date,
category, accountFrom, accountTo, type);
}
public void sortLedgerByTransactionDateAscending() {
Collections.reverse(ledgerTransactions);
}
public void sortLedgerByTransactionDateDescending() {
ledgerTransactions.sort((transaction1, transaction2) -> transaction2.getDate().getYearMonthDayHourMinute()
.compareTo(transaction1.getDate().getYearMonthDayHourMinute()));
}
public List<Transaction> getTransactionsInDateRange(LocalDateTime initialDate, LocalDateTime finalDate) {
if (initialDate == null || finalDate == null)
throw new IllegalArgumentException(DATE_CANT_NULL);
else if (!StringUtils.isCorrectDateRange(
initialDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")),
finalDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"))))
throw new IllegalArgumentException(DATE_NOT_VALID);
List<Transaction> myTransactions = new ArrayList<>();
for (Transaction transactions : ledgerTransactions) {
if ((transactions.getDate().isInTheFuture(initialDate) && transactions.getDate().isInThePast(finalDate)) ||
(transactions.getDate().getYearMonthDayHourMinute().equals(initialDate) ||
transactions.getDate().getYearMonthDayHourMinute().equals(finalDate)))
myTransactions.add(transactions);
}
return myTransactions;
}
public List<Transaction> getTransactionsFromOneAccount(AccountID account1, List<Transaction> listOfTransactions) {
List<Transaction> listOfTransactionsFromOneAccount = new ArrayList<>();
if (account1 != null) {
for (Transaction transaction : listOfTransactions) {
if (transaction.getAccountFrom().equals(account1) || transaction.getAccountTo().equals(account1)) {
listOfTransactionsFromOneAccount.add(transaction);
}
}
return listOfTransactionsFromOneAccount;
} else
throw new IllegalArgumentException("The account cannot be null.");
}
public double getBalanceInDateRange(LocalDateTime initialDate, LocalDateTime finalDate) {
double balance = 0;
if (initialDate == null || finalDate == null)
throw new IllegalArgumentException(DATE_NOT_VALID);
else if (initialDate.isAfter(LocalDateTime.now()) || finalDate.isAfter(LocalDateTime.now()))
throw new IllegalArgumentException(DATE_NOT_VALID);
else if (ledgerTransactions.isEmpty())
throw new IllegalArgumentException("The ledger has no Transactions.");
//Validate if Date is in the correct order
else if (initialDate.isAfter(finalDate)) {
//POR AQUI UMA EXCEÇÃO!!!!!!!
LocalDateTime aux = initialDate;
initialDate = finalDate;
finalDate = aux;
}
//Check if transaction is in that range
for (Transaction transactions : ledgerTransactions) {
if (transactions.getDate().isInTheFuture(initialDate) && transactions.getDate().isInThePast(finalDate)) {
if (transactions.getType()) {
balance = balance + transactions.getAmount();
} else if (!transactions.getType()) {
balance = balance - transactions.getAmount();
}
}
}
return (double) Math.round(balance * 1000) / 1000; // balance rounded to three decimal places
}
}
|
package com.company;
import GameOfLife.Board;
import java.io.IOException;
//Output for a game of life board
public interface BoardWriter {
void write(Board board) throws IOException;
void close() throws IOException;
}
|
package com.dnomaid.iot.mqtt.topic.noJson;
import com.dnomaid.iot.mqtt.topic.ActionTopic;
public class Hum implements ActionTopic
{
private String name = "Hum";
private String Hum;
public String getHum() {
return Hum;
}
public void setHum(String temp) {
Hum = temp;
}
@Override
public String toString() {
return name;
}
@Override
public String getValueTopic(TypeTopic typeTopic) {
String str = "--.--";
switch (typeTopic) {
case Humidity:
str = getHum();
break;
default:
str = "??¿¿";
}
return str;
}
}
|
package com.crud.medicalclinic.service;
import com.crud.medicalclinic.domain.Appointment;
import com.crud.medicalclinic.domain.Office;
import com.crud.medicalclinic.repository.AppointmentRepository;
import com.crud.medicalclinic.repository.OfficeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class AppointmentService {
@Autowired
private AppointmentRepository appointmentRepository;
public List<Appointment> getAll() {
return appointmentRepository.findAll();
}
public Optional<Appointment> get(long id) {
return appointmentRepository.findById(id);
}
public Appointment save(Appointment appointment) {
return appointmentRepository.save(appointment);
}
public void deleteById(long id) {
appointmentRepository.deleteById(id);
}
}
|
package com.komoot.sampl4.ktraker.route_list;
import android.content.Intent;
import android.database.Cursor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import com.komoot.sampl4.ktraker.db.DbAdapter;
import com.komoot.sampl4.ktraker.R;
import com.komoot.sampl4.ktraker.route.RouteActivity;
public class MainActivity extends AppCompatActivity {
private DbAdapter db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
db=new DbAdapter(this);
//long res= db.insertRoutes("route #2");
//Log.d("qq", ""+res);
setContentView(R.layout.activity_main);
setRecykler();
}
private void setRecykler() {
ListView listView=(ListView) findViewById(R.id.rv);
Cursor cursor =db.getRoutes();
//startManagingCursor(cursor);
String[] fields=new String[]{cursor.getColumnName(1)};//
int[] vidgetId=new int[]{R.id.text_id};//
//CursorAdapter cursorAdapter=new SimpleCursorAdapter(getBaseContext(),R.layout.route_item,db.getRoutes(), fields,vidgetId);
CursorAdapter cursorAdapter=new SimpleCursorAdapter(getBaseContext(),R.layout.route_item,cursor,fields,vidgetId,SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
listView.setAdapter(cursorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//look Route
Toast.makeText(getBaseContext(),"id "+id,Toast.LENGTH_SHORT).show();
Intent intent= new Intent(getBaseContext(),RouteActivity.class);
intent.putExtra("routeID",id);
startActivity(intent);
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
long routeID= db.insertRoutes("route #4");
Intent intent= new Intent(getBaseContext(),RouteActivity.class);
intent.putExtra("routeID",routeID);
startActivity(intent);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onDestroy(){
db.onDestroy();
super.onDestroy();
}
}
|
package classhandling;
public class swap {
public void swapNum(int a,int b)
{
//with using 3rd variable
//Example1:
/* int c = a + b; // c= 51 a = 25 b = 26
a = c - a; // a= 26 a = 26 b = 25
b = c - b; // b= 25*/
//Example2:
/* int c = a;
a = b;
b = c;*/
//without using 3rd variable
a = a+b;
b = a-b;
a = b-a;
System.out.println("display a value:-" + a);
System.out.println("display b value:-" + b);
}
}
|
/**
* OpenKM, Open Document Management System (http://www.openkm.com)
* Copyright (c) 2006-2015 Paco Avila & Josep Llort
*
* No bytes were intentionally harmed during the development of this application.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.openkm.servlet.frontend;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.openkm.bean.Document;
import com.openkm.bean.Folder;
import com.openkm.bean.Mail;
import com.openkm.bean.Repository;
import com.openkm.bean.pagination.FilterResult;
import com.openkm.bean.pagination.ObjectToOrder;
import com.openkm.core.DatabaseException;
import com.openkm.core.PathNotFoundException;
import com.openkm.core.RepositoryException;
import com.openkm.dao.NodeBaseDAO;
import com.openkm.dao.NodeDocumentDAO;
import com.openkm.dao.NodeDocumentVersionDAO;
import com.openkm.dao.NodeFolderDAO;
import com.openkm.dao.NodeMailDAO;
import com.openkm.dao.bean.NodeDocument;
import com.openkm.dao.bean.NodeDocumentVersion;
import com.openkm.dao.bean.NodeFolder;
import com.openkm.dao.bean.NodeMail;
import com.openkm.frontend.client.OKMException;
import com.openkm.frontend.client.bean.GWTDocument;
import com.openkm.frontend.client.bean.GWTFolder;
import com.openkm.frontend.client.bean.GWTMail;
import com.openkm.frontend.client.bean.GWTPaginated;
import com.openkm.frontend.client.bean.GWTWorkspace;
import com.openkm.frontend.client.constants.service.ErrorCode;
import com.openkm.frontend.client.service.OKMPaginationService;
import com.openkm.frontend.client.widget.filebrowser.GWTFilter;
import com.openkm.module.db.base.BaseDocumentModule;
import com.openkm.module.db.base.BaseFolderModule;
import com.openkm.module.db.base.BaseMailModule;
import com.openkm.util.GWTUtil;
import com.openkm.util.pagination.FilterUtils;
/**
* Servlet Class
*/
public class PaginationServlet extends OKMRemoteServiceServlet implements OKMPaginationService {
private static Logger log = LoggerFactory.getLogger(PaginationServlet.class);
private static final long serialVersionUID = 1L;
@Override
public GWTPaginated getChildrenPaginated(String fldPath, boolean extraColumns, int offset, int limit, int order,
boolean reverse, boolean folders, boolean documents, boolean mails, String selectedRowId,
Map<String, GWTFilter> mapFilter) throws OKMException {
log.debug("getChildrenPaginated({})", fldPath);
long begin = System.currentTimeMillis();
GWTPaginated paginated = new GWTPaginated();
List<Object> col = new ArrayList<Object>();
List<Object> gwtCol = new ArrayList<Object>();
String user = getThreadLocalRequest().getRemoteUser();
paginated.setObjects(gwtCol);
updateSessionManager();
try {
String fldUuid = "";
// Calculating folder uuid only when is not metadata or thesaurus case
if (!fldPath.startsWith("/" + Repository.THESAURUS) && !fldPath.startsWith("/" + Repository.METADATA)) {
fldUuid = NodeBaseDAO.getInstance().getUuidFromPath(fldPath);
}
// Folders
List<NodeFolder> colFolders = new ArrayList<NodeFolder>();
if (fldPath.startsWith("/" + Repository.CATEGORIES)) {
colFolders = NodeFolderDAO.getInstance().findByCategory(fldUuid);
} else if (fldPath.startsWith("/" + Repository.THESAURUS)) {
String keyword = fldPath.substring(fldPath.lastIndexOf("/") + 1).replace(" ", "_");
colFolders = NodeFolderDAO.getInstance().findByKeyword(keyword);
} else if (fldPath.startsWith("/" + Repository.METADATA)) {
if ((fldPath.split("/").length - 1) == 4) {
String subFolder[] = fldPath.split("/");
String group = subFolder[2];
String property = subFolder[3];
String value = subFolder[4];
colFolders = NodeFolderDAO.getInstance().findByPropertyValue(group, property, value);
}
} else {
colFolders = NodeFolderDAO.getInstance().findByParent(fldUuid);
}
paginated.setTotalFolder(colFolders.size());
if (folders) {
col.addAll(colFolders); // Add in one collection to make full ordering
}
// Documents
List<NodeDocument> colDocuments = new ArrayList<NodeDocument>();
if (fldPath.startsWith("/" + Repository.CATEGORIES)) {
colDocuments = NodeDocumentDAO.getInstance().findByCategory(fldUuid);
} else if (fldPath.startsWith("/" + Repository.THESAURUS)) {
String keyword = fldPath.substring(fldPath.lastIndexOf("/") + 1).replace(" ", "_");
colDocuments = NodeDocumentDAO.getInstance().findByKeyword(keyword);
} else if (fldPath.startsWith("/" + Repository.METADATA)) {
// Case metadata at value level
if (fldPath.split("/").length - 1 == 4) {
String subFolder[] = fldPath.split("/");
String group = subFolder[2];
String property = subFolder[3];
String value = subFolder[4];
colDocuments = NodeDocumentDAO.getInstance().findByPropertyValue(group, property, value);
}
} else {
colDocuments = NodeDocumentDAO.getInstance().findByParent(fldUuid);
}
paginated.setTotalDocuments(colDocuments.size());
if (documents) {
col.addAll(colDocuments); // Add in one collection to make full ordering
}
// Mails
List<NodeMail> colMails = new ArrayList<NodeMail>();
if (fldPath.startsWith("/" + Repository.CATEGORIES)) {
colMails = NodeMailDAO.getInstance().findByCategory(fldUuid);
} else if (fldPath.startsWith("/" + Repository.THESAURUS)) {
String keyword = fldPath.substring(fldPath.lastIndexOf("/") + 1).replace(" ", "_");
colMails = NodeMailDAO.getInstance().findByKeyword(keyword);
} else if (fldPath.startsWith("/" + Repository.METADATA)) {
// Case metadata value level
if (fldPath.split("/").length - 1 == 4) {
String subFolder[] = fldPath.split("/");
String group = subFolder[2];
String property = subFolder[3];
String value = subFolder[4];
colMails = NodeMailDAO.getInstance().findByPropertyValue(group, property, value);
}
} else {
colMails = NodeMailDAO.getInstance().findByParent(fldUuid);
}
paginated.setTotalMails(colMails.size());
if (mails) {
col.addAll(colMails); // Add in one collection to make full ordering
}
// Filtering
GWTWorkspace workspace = getUserWorkspaceSession();
FilterResult fr = FilterUtils.filter(workspace, col, order, selectedRowId, mapFilter);
List<ObjectToOrder> convertedCol = fr.getConvertedCol();
int selectedRow = fr.getSelectedRow();
// Setting total
int total = convertedCol.size();
paginated.setTotal(total);
// Testing offset error ( trying to find correct offset ).
if (offset >= total) {
if (total == 0 || total <= limit) {
offset = 0;
} else if (total % limit != 0) { // case there's some remainder
offset = (total / limit) * limit;
} else { // case exact division
offset = (total / limit) * limit;
offset = offset - limit; // back limit to see latest values
}
paginated.setOutOfRange(true);
paginated.setNewOffset(offset);
}
// Test for selectedRowId between offset - offset+limit otherwise changes offset
if (selectedRow != -1) {
if ((offset > selectedRow) || (selectedRow > (offset + limit))) {
if (selectedRow == 0) {
offset = 0;
} else {
offset = (selectedRow / limit) * limit;
}
paginated.setOutOfRange(true);
paginated.setNewOffset(offset);
}
}
// When selectedRowId any filtering, ordering, reverse etc.. value is empty
// Ordering
switch (order) {
case GWTPaginated.COL_NONE:
// No ordering
break;
case GWTPaginated.COL_TYPE:
// Ordering as has been added
break;
case GWTPaginated.COL_NAME:
Collections.sort(convertedCol, OrderByName.getInstance());
break;
case GWTPaginated.COL_SIZE:
Collections.sort(convertedCol, OrderBySize.getInstance());
break;
case GWTPaginated.COL_DATE:
Collections.sort(convertedCol, OrderByDate.getInstance());
break;
case GWTPaginated.COL_AUTHOR:
Collections.sort(convertedCol, OrderByAuthor.getInstance());
break;
case GWTPaginated.COL_VERSION:
Collections.sort(convertedCol, OrderByVersion.getInstance());
break;
}
// Reverse ordering
if (reverse) {
Collections.reverse(convertedCol);
}
// Copy based in offset - limit
int actual = 0;
if (actual <= offset && offset <= (actual + convertedCol.size())) {
boolean found = false;
found = (actual == offset);
for (ObjectToOrder obj : convertedCol) {
// Jump to actual
if (found) {
if (actual < offset + limit) {
if (obj.getObj() instanceof NodeFolder) {
Folder fld = BaseFolderModule.getProperties(user, (NodeFolder) obj.getObj());
GWTFolder gWTFolder = (extraColumns) ? GWTUtil.copy(fld, workspace)
: GWTUtil.copy(fld, null);
gwtCol.add(gWTFolder);
} else if (obj.getObj() instanceof NodeDocument) {
Document doc = BaseDocumentModule.getProperties(user, (NodeDocument) obj.getObj());
GWTDocument gWTDoc = (extraColumns) ? GWTUtil.copy(doc, workspace)
: GWTUtil.copy(doc, null);
gwtCol.add(gWTDoc);
} else if (obj.getObj() instanceof NodeMail) {
Mail mail = BaseMailModule.getProperties(user, (NodeMail) obj.getObj());
GWTMail gWTMail = (extraColumns) ? GWTUtil.copy(mail, workspace)
: GWTUtil.copy(mail, null);
gwtCol.add(gWTMail);
}
} else {
break;
}
}
actual++;
if (!found) {
found = (actual == offset);
}
}
}
} catch (RepositoryException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFolderService, ErrorCode.CAUSE_Repository),
e.getMessage());
} catch (PathNotFoundException e) {
log.warn(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFolderService, ErrorCode.CAUSE_PathNotFound),
e.getMessage());
} catch (DatabaseException e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFolderService, ErrorCode.CAUSE_Database),
e.getMessage());
} catch (Exception e) {
log.error(e.getMessage(), e);
throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMFolderService, ErrorCode.CAUSE_General),
e.getMessage());
}
log.trace("getChildrenPaginated.Time: {}", System.currentTimeMillis() - begin);
log.debug("getChildrenPaginated: {}", paginated);
return paginated;
}
/**
* OrderByName
*
* @author jllort
*
*/
private static class OrderByName implements Comparator<ObjectToOrder> {
private static final Comparator<ObjectToOrder> INSTANCE = new OrderByName();
public static Comparator<ObjectToOrder> getInstance() {
return INSTANCE;
}
public int compare(ObjectToOrder arg0, ObjectToOrder arg1) {
String value0 = "";
String value1 = "";
if (arg0.getObj() instanceof NodeFolder) {
value0 = ((NodeFolder) arg0.getObj()).getName();
} else if (arg0.getObj() instanceof NodeDocument) {
value0 = ((NodeDocument) arg0.getObj()).getName();
} else if (arg0.getObj() instanceof NodeMail) {
value0 = ((NodeMail) arg0.getObj()).getSubject();
}
if (arg1.getObj() instanceof NodeFolder) {
value1 = ((NodeFolder) arg1.getObj()).getName();
} else if (arg1.getObj() instanceof NodeDocument) {
value1 = ((NodeDocument) arg1.getObj()).getName();
} else if (arg0.getObj() instanceof NodeMail) {
value1 = ((NodeMail) arg1.getObj()).getSubject();
}
return value0.compareTo(value1);
}
}
/**
* OrderBySize
*
* @author jllort
*
*/
private static class OrderBySize implements Comparator<ObjectToOrder> {
private static final Comparator<ObjectToOrder> INSTANCE = new OrderBySize();
public static Comparator<ObjectToOrder> getInstance() {
return INSTANCE;
}
public int compare(ObjectToOrder arg0, ObjectToOrder arg1) {
long value0 = 0;
long value1 = 0;
if (arg0.getObj() instanceof NodeDocument) {
try {
String docUuid = ((NodeDocument) arg0.getObj()).getUuid();
NodeDocumentVersion nDocVer = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid);
value0 = nDocVer.getSize();
} catch (Exception e) {
// Ignore
}
} else if (arg0.getObj() instanceof NodeMail) {
value0 = ((NodeMail) arg0.getObj()).getSize();
}
if (arg1.getObj() instanceof NodeDocument) {
try {
String docUuid = ((NodeDocument) arg1.getObj()).getUuid();
NodeDocumentVersion nDocVer = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid);
value1 = nDocVer.getSize();
} catch (Exception e) {
// Ignore
}
} else if (arg1.getObj() instanceof NodeMail) {
value1 = ((NodeMail) arg1.getObj()).getSize();
}
return new Long(value0 - value1).intValue();
}
}
/**
* OrderByDate
*
* @author jllort
*
*/
private static class OrderByDate implements Comparator<ObjectToOrder> {
private static final Comparator<ObjectToOrder> INSTANCE = new OrderByDate();
public static Comparator<ObjectToOrder> getInstance() {
return INSTANCE;
}
public int compare(ObjectToOrder arg0, ObjectToOrder arg1) {
Calendar value0 = Calendar.getInstance();
Calendar value1 = Calendar.getInstance();
if (arg0.getObj() instanceof NodeFolder) {
value0 = ((NodeFolder) arg0.getObj()).getCreated();
} else if (arg0.getObj() instanceof NodeDocument) {
value0 = ((NodeDocument) arg0.getObj()).getLastModified();
} else if (arg0.getObj() instanceof NodeMail) {
value0 = ((NodeMail) arg0.getObj()).getReceivedDate();
}
if (arg1.getObj() instanceof NodeFolder) {
value1 = ((NodeFolder) arg1.getObj()).getCreated();
} else if (arg1.getObj() instanceof NodeDocument) {
value1 = ((NodeDocument) arg1.getObj()).getLastModified();
} else if (arg1.getObj() instanceof NodeMail) {
value1 = ((NodeMail) arg1.getObj()).getCreated();
}
return value0.compareTo(value1);
}
}
/**
* OrderByAuthor
*
* @author jllort
*
*/
private static class OrderByAuthor implements Comparator<ObjectToOrder> {
private static final Comparator<ObjectToOrder> INSTANCE = new OrderByAuthor();
public static Comparator<ObjectToOrder> getInstance() {
return INSTANCE;
}
public int compare(ObjectToOrder arg0, ObjectToOrder arg1) {
String value0 = "";
String value1 = "";
if (arg0.getObj() instanceof NodeFolder) {
value0 = ((NodeFolder) arg0.getObj()).getAuthor();
} else if (arg0.getObj() instanceof NodeDocument) {
try {
String docUuid = ((NodeDocument) arg0.getObj()).getUuid();
NodeDocumentVersion nDocVer = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid);
value0 = nDocVer.getAuthor();
} catch (Exception e) {
// Ignore
}
} else if (arg0.getObj() instanceof NodeMail) {
value0 = ((NodeMail) arg0.getObj()).getAuthor();
}
if (arg1.getObj() instanceof NodeFolder) {
value1 = ((NodeFolder) arg1.getObj()).getAuthor();
} else if (arg1.getObj() instanceof NodeDocument) {
try {
String docUuid = ((NodeDocument) arg1.getObj()).getUuid();
NodeDocumentVersion nDocVer = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid);
value1 = nDocVer.getAuthor();
} catch (Exception e) {
// Ignore
}
} else if (arg1.getObj() instanceof NodeMail) {
value1 = ((NodeMail) arg1.getObj()).getAuthor();
}
return value0.compareTo(value1);
}
}
/**
* OrderByVersion
*
* @author jllort
*
*/
private static class OrderByVersion implements Comparator<ObjectToOrder> {
private static final Comparator<ObjectToOrder> INSTANCE = new OrderByVersion();
public static Comparator<ObjectToOrder> getInstance() {
return INSTANCE;
}
public int compare(ObjectToOrder arg0, ObjectToOrder arg1) {
if (arg0.getObj() instanceof NodeDocument && arg1.getObj() instanceof NodeDocument) {
try {
String docUuid0 = ((NodeDocument) arg0.getObj()).getUuid();
NodeDocumentVersion nDocVer0 = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid0);
String value0 = getComparableVersion(nDocVer0.getName());
String docUuid1 = ((NodeDocument) arg1.getObj()).getUuid();
NodeDocumentVersion nDocVer1 = NodeDocumentVersionDAO.getInstance().findCurrentVersion(docUuid1);
String value1 = getComparableVersion(nDocVer1.getName());
return value0.compareTo(value1);
} catch (Exception e) {
// Ignore
}
return 0;
} else if (arg0.getObj() instanceof NodeDocument) {
return 1;
} else if (arg1.getObj() instanceof NodeDocument) {
return -1;
} else {
return 0;
}
}
}
/**
* getComparableVersion
*
* @return
*/
private static String getComparableVersion(String version) {
// Based on ExtendedScrollTableSorter considering version number is 1.0 ( number dot number pattern )
String numberParts[] = version.split("\\.");
version = "";
for (int x = 0; x < numberParts.length; x++) {
switch (numberParts[x].length()) {
case 1:
version = version + "00" + numberParts[x];
break;
case 2:
version = version + "0" + numberParts[x];
break;
}
}
if (numberParts.length == 2) {
version = version + "000000";
}
if (numberParts.length == 3) {
version = version + "000";
}
return version;
}
} |
package com.movietoy.api.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
@Configuration
@EnableCaching
public class RedisConfig {
@Bean
public CacheManager dailyMovieCacheManager(RedisConnectionFactory redisConnectionFactory){
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.entryTtl(Duration.ofMinutes(3L));
return RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(redisConnectionFactory).cacheDefaults(redisCacheConfiguration).build();
}
} |
package com.kdp.wanandroidclient.ui.adapter;
import android.view.View;
import android.widget.TextView;
import com.kdp.wanandroidclient.common.ListDataHolder;
import com.kdp.wanandroidclient.R;
import com.kdp.wanandroidclient.bean.Tree;
import com.kdp.wanandroidclient.inter.OnItemClickListener;
/**
* 知识体系
* author: 康栋普
* date: 2018/2/24
*/
public class TreeAdapter extends BaseListAdapter<Tree> {
private OnItemClickListener<Tree> listener;
public TreeAdapter(OnItemClickListener<Tree> listener) {
this.listener = listener;
}
@Override
protected int getLayoutId(int viewType) {
return R.layout.item_tree;
}
@Override
public void bindDatas(ListDataHolder holder, final Tree bean, int itemType, final int position) {
TextView tv_title = holder.getView(R.id.tv_title);
TextView tv_content = holder.getView(R.id.tv_content);
tv_title.setText(bean.getName());
tv_content.setText("");
for (Tree.ChildrenBean child : bean.getChildren()) {
tv_content.append(child.getName() + " ");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (listener!=null)
listener.onItemClick(position,bean);
}
});
}
}
|
package PACKAGE_NAME;
public class RejestrObywateli {
}
|
package com.spring.dao;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import com.spring.domain.DealerPurchaseStatisticsData;
import com.spring.domain.DealerTotalInvoice;
import com.spring.domain.SMEPrincipalSalesManagerEmailForP1SC;
import com.spring.domain.SalesForceDealerDetails;
@Repository
public class P1SCScoreCardDaoImpl extends CustomHibernateDaoSupport implements P1SCScoreCardDao {
private static Logger logger = Logger.getLogger(P1SCScoreCardDaoImpl.class);
public SMEPrincipalSalesManagerEmailForP1SC getSMEPrincipalSalesManagerEmailFromStore(String store_code,String principal_name)
{
logger.info("inside :getSMEPrincipalSalesManagerEmailFromStore() method for store code " +store_code);
List<SMEPrincipalSalesManagerEmailForP1SC> l=null;
Criteria criteria=null;
Session session=null;
SMEPrincipalSalesManagerEmailForP1SC smePrincipalSalesManagerEmailForP1SC=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
criteria=session.createCriteria(SMEPrincipalSalesManagerEmailForP1SC.class);
criteria.add(Restrictions.eq("store_code", store_code));
criteria.add(Restrictions.eq("principal_name", principal_name));
l=criteria.list();
if(!l.isEmpty())
{
smePrincipalSalesManagerEmailForP1SC=l.get(0);
logger.error("smePrincipalSalesManagerEmailForP1SC :: "+smePrincipalSalesManagerEmailForP1SC);
}
}
catch(Exception e)
{
logger.error("Error :: "+e);
}
return smePrincipalSalesManagerEmailForP1SC;
}
public List<Integer> findSellerFromDealerPurchaseData()
{
List<Integer> seller_idFromDPD=new ArrayList<Integer>();
logger.info("inside :findSellerFromDealerPurchaseData() method");
// List reportList = new ArrayList<>();
Session session=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
//String query = "SELECT invoice_value FROM sme_principal_dealers_purchase_data_file WHERE is_processed=0 and dealer_id ='"+dealer_id+"'";// and STR_TO_DATE(purchase_entry_date,'%d-%m-%Y') = CURRENT_DATE()"; // ORDER BY invoice_date
String query = "SELECT DISTINCT main_principal_id FROM sme_principal_dealers_purchase_data_file WHERE is_processed=0";
session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery crt = session.createSQLQuery(query);
seller_idFromDPD = crt.list();
logger.info("main_principal_id From DPD :: "+seller_idFromDPD);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return seller_idFromDPD;
}
@Override
public void updatedpdObjectAsProcessed(DealerPurchaseStatisticsData dealerPurchaseStatisticsData) {
logger.info("inside :updatedpdObjectAsProcessed() method");
// List reportList = new ArrayList<>();
Session session=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
String query = "update sme_principal_dealers_purchase_data_file set is_processed=1 where dealer_id='"+dealerPurchaseStatisticsData.getDealer_id()+"' and principal_id ='"+dealerPurchaseStatisticsData.getPrincipal_id()+"'";
session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery crt = session.createSQLQuery(query);
int rowcount = crt.executeUpdate();
logger.info("Rows updated with 1 :: "+rowcount);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
}
public List<String> findUnprocessedDealersStoreCodesFromDPD(Integer main_principal_id)
{
List<String> unprocessedDealersForStorecodeFromDPD=new ArrayList<String>();
logger.info("inside :findUnprocessedDealersStoreCodesFromDPD() method");
Session session=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
String query2 = "SELECT store_code FROM sme_principal_dealers_purchase_data_file WHERE main_principal_id ='"+main_principal_id+"' and is_processed=0 GROUP BY store_code order by store_code asc";
SQLQuery crt = session.createSQLQuery(query2);
unprocessedDealersForStorecodeFromDPD = crt.list();
logger.info("unprocessedDealersForStorecodeFromDPD :: "+unprocessedDealersForStorecodeFromDPD);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return unprocessedDealersForStorecodeFromDPD;
}
public List<Integer> findUnprocessedDealersCitiesFromDPD(Integer main_principal_id)
{
List<Integer> unprocessedDealersCitiesFromDPD=new ArrayList<Integer>();
logger.info("inside :findUnprocessedDealersCitiesFromDPD() method");
Session session=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
String query2 = "SELECT principal_id FROM sme_principal_dealers_purchase_data_file WHERE main_principal_id ='"+main_principal_id+"' and is_processed=0 GROUP BY principal_id order by principal_id asc";
SQLQuery crt = session.createSQLQuery(query2);
unprocessedDealersCitiesFromDPD = crt.list();
logger.info("unprocessedDealersCitiesFromDPD :: "+unprocessedDealersCitiesFromDPD);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return unprocessedDealersCitiesFromDPD;
}
public List<Double> findAvgInvoicesValueOfOtherDealersFromDPD(Integer main_principal_id, Integer sub_principal_id)
{
List<Double> dealerInvoicesValuefromDPD=new ArrayList<Double>();
logger.info("inside :findAvgInvoicesValueOfOtherDealersFromDPD() method for other dealers");
List<DealerTotalInvoice> dealerTotalInvoices=new ArrayList<DealerTotalInvoice>();
// List reportList = new ArrayList<>();
Map<Integer,Double> finaldealerTotalInvoices=new HashMap<Integer,Double>();
Map<Integer,Double> finaldealerTotalInvoices2=new HashMap<Integer,Double>();
Map<Integer,Double> finaldealerTotalInvoices3=new HashMap<Integer,Double>();
Session session=null;
logger.info("Finding Sum of InvoicesValueOf OtherDealers monthly From DPD");
try{
session=getHibernateTemplate().getSessionFactory().openSession();
String query = "SELECT dealer_id, SUM(invoice_value) "+
"FROM sme_principal_dealers_purchase_data_file "+
"WHERE principal_id='"+sub_principal_id+"' and main_principal_id='"+main_principal_id+"'" +
/*"and dealer_id IN (SELECT DISTINCT dealer_id FROM sme_principal_dealers_purchase_data_file WHERE principal_id ='"+seller_id+"') "+*/
"GROUP BY dealer_id, SUBSTRING(invoice_date,4,2) ";
SQLQuery crt = session.createSQLQuery(query);
List list = crt.list();
Iterator it = list.iterator();
// List<Object> rl = new ArrayList<Object>();
logger.info("Storing in List Sum of InvoicesValueOf OtherDealers monthly From DPD");
logger.info("Adding all sum and count from List in map of InvoicesValueOf OtherDealers monthly From DPD");
while (it.hasNext()) {
Object[] datas = (Object[]) it.next();
DealerTotalInvoice dealerTotalInvoice=new DealerTotalInvoice(datas);
//dealerTotalInvoices.add(dealerTotalInvoice);
// double sum=0.0;
// double count=0.0;
if(finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())!=null)
{
finaldealerTotalInvoices.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())+dealerTotalInvoice.getInvoice_value()));
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())+1));
}
else
{
finaldealerTotalInvoices.put(dealerTotalInvoice.getDealer_id(),dealerTotalInvoice.getInvoice_value());
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),1.0);
}
}
// logger.info("dealerTotalInvoices :: "+dealerTotalInvoices);
//String query = "SELECT avg(invoice_value) FROM sme_principal_dealers_purchase_data_file WHERE principal_id ='"+seller_id+"' group by dealer_id"; // ORDER BY invoice_date
// logger.info("Adding all sum and count from List in map of InvoicesValueOf OtherDealers monthly From DPD");
/*for(DealerTotalInvoice dealerTotalInvoice:dealerTotalInvoices)
{
double sum=0.0;
double count=0.0;
if(finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())!=null)
{
sum=finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())+dealerTotalInvoice.getInvoice_value();
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())+1));
}
else
{
sum=dealerTotalInvoice.getInvoice_value();
finaldealerTotalInvoices.put(dealerTotalInvoice.getDealer_id(),sum);
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),1.0);
}
}*/
// logger.info("Adding count of all sum from List in map of InvoicesValueOf OtherDealers monthly From DPD");
/*for(DealerTotalInvoice dealerTotalInvoice:dealerTotalInvoices)
{
double count=0.0;
if(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())!=null)
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())+1));
else
{
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),1.0);
}
}*/
logger.info("Calculating Avg of all sum from map of InvoicesValueOf OtherDealers monthly From DPD");
for (Map.Entry<Integer,Double> entry : finaldealerTotalInvoices.entrySet())
{
double value=finaldealerTotalInvoices.get(entry.getKey());
// logger.info("value AVG :: "+value);
double count=finaldealerTotalInvoices2.get(entry.getKey());
// logger.info("count Sum :: "+count);
finaldealerTotalInvoices3.put(entry.getKey(), (value/count));
}
logger.info("Getting All AVG map values to list of InvoicesValueOf OtherDealers monthly From DPD");
dealerInvoicesValuefromDPD = new ArrayList<Double>(finaldealerTotalInvoices3.values());
// logger.info("dealerInvoicesValuefromDPD AVG :: "+dealerInvoicesValuefromDPD);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return dealerInvoicesValuefromDPD;
}
public List<Double> findAvgInvoicesValueOfOtherDealersFromDPDUsingStoreCode(Integer main_principal_id, String store_code)
{
List<Double> dealerInvoicesValuefromDPD=new ArrayList<Double>();
logger.info("inside :findAvgInvoicesValueOfOtherDealersFromDPDUsingStoreCode() method for other dealers");
List<DealerTotalInvoice> dealerTotalInvoices=new ArrayList<DealerTotalInvoice>();
// List reportList = new ArrayList<>();
Map<Integer,Double> finaldealerTotalInvoices=new HashMap<Integer,Double>();
Map<Integer,Double> finaldealerTotalInvoices2=new HashMap<Integer,Double>();
Map<Integer,Double> finaldealerTotalInvoices3=new HashMap<Integer,Double>();
Session session=null;
logger.info("Finding Sum of InvoicesValueOf OtherDealers monthly From DPD");
try{
session=getHibernateTemplate().getSessionFactory().openSession();
String query = "SELECT dealer_id, SUM(invoice_value) "+
"FROM sme_principal_dealers_purchase_data_file "+
"WHERE store_code='"+store_code+"' and main_principal_id='"+main_principal_id+"'" +
/*"and dealer_id IN (SELECT DISTINCT dealer_id FROM sme_principal_dealers_purchase_data_file WHERE main_principal_id ='"+main_principal_id+"') "+
*/ "GROUP BY dealer_id, SUBSTRING(invoice_date,4,2) ";
SQLQuery crt = session.createSQLQuery(query);
List list = crt.list();
Iterator it = list.iterator();
// List<Object> rl = new ArrayList<Object>();
logger.info("Storing in List Sum of InvoicesValueOf OtherDealers monthly From DPD");
logger.info("Adding all sum and count from List in map of InvoicesValueOf OtherDealers monthly From DPD");
while (it.hasNext()) {
Object[] datas = (Object[]) it.next();
DealerTotalInvoice dealerTotalInvoice=new DealerTotalInvoice(datas);
//dealerTotalInvoices.add(dealerTotalInvoice);
// double sum = 0.0;
// double count = 0.0;
if(finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())!=null)
{
finaldealerTotalInvoices.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())+dealerTotalInvoice.getInvoice_value()));
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())+1));
}
else
{
finaldealerTotalInvoices.put(dealerTotalInvoice.getDealer_id(),dealerTotalInvoice.getInvoice_value());
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),1.0);
}
}
// logger.info("dealerTotalInvoices :: "+dealerTotalInvoices);
//String query = "SELECT avg(invoice_value) FROM sme_principal_dealers_purchase_data_file WHERE principal_id ='"+seller_id+"' group by dealer_id"; // ORDER BY invoice_date
// logger.info("Adding all sum and count from List in map of InvoicesValueOf OtherDealers monthly From DPD");
/*for(DealerTotalInvoice dealerTotalInvoice:dealerTotalInvoices)
{
double sum=0.0;
double count=0.0;
if(finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())!=null)
{
sum=finaldealerTotalInvoices.get(dealerTotalInvoice.getDealer_id())+dealerTotalInvoice.getInvoice_value();
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())+1));
}
else
{
sum=dealerTotalInvoice.getInvoice_value();
finaldealerTotalInvoices.put(dealerTotalInvoice.getDealer_id(),sum);
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),1.0);
}
}*/
// logger.info("Adding count of all sum from List in map of InvoicesValueOf OtherDealers monthly From DPD");
/*for(DealerTotalInvoice dealerTotalInvoice:dealerTotalInvoices)
{
double count=0.0;
if(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())!=null)
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),(finaldealerTotalInvoices2.get(dealerTotalInvoice.getDealer_id())+1));
else
{
finaldealerTotalInvoices2.put(dealerTotalInvoice.getDealer_id(),1.0);
}
}*/
logger.info("Calculating Avg of all sum from map of InvoicesValueOf OtherDealers monthly From DPD");
for (Map.Entry<Integer,Double> entry : finaldealerTotalInvoices.entrySet())
{
double value=finaldealerTotalInvoices.get(entry.getKey());
// logger.info("value AVG :: "+value);
double count=finaldealerTotalInvoices2.get(entry.getKey());
// logger.info("count Sum :: "+count);
finaldealerTotalInvoices3.put(entry.getKey(), (value/count));
}
logger.info("Getting All AVG map values to list of InvoicesValueOf OtherDealers monthly From DPD");
dealerInvoicesValuefromDPD = new ArrayList<Double>(finaldealerTotalInvoices3.values());
// logger.info("dealerInvoicesValuefromDPD AVG :: "+dealerInvoicesValuefromDPD);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return dealerInvoicesValuefromDPD;
}
public SalesForceDealerDetails getFieldViewDealer(int dealer_id)
{
logger.info("inside :getFieldViewDealer() method");
Criteria criteria=null;
Session session=null;
List<SalesForceDealerDetails> dealerDetails=null;
SalesForceDealerDetails salesForceDealerDetail=null;
try {
session=getHibernateTemplate().getSessionFactory().openSession();
criteria=session.createCriteria(SalesForceDealerDetails.class);
criteria.add(Restrictions.eq("buyer_id",dealer_id));
dealerDetails=criteria.list();
if(!dealerDetails.isEmpty())
salesForceDealerDetail=dealerDetails.get(0);
}
catch(Exception e)
{
logger.info(e);
}
finally
{
if(session!=null)
session.close();
}
return salesForceDealerDetail;
}
public List<Double> findInvoicesValueFromDealerPurchaseData(Integer dealer_id)
{
List<Double> dealerInvoicesValuefromDPD=new ArrayList<Double>();
logger.info("inside :findInvoicesValueFromDealerPurchaseData() method");
// List reportList = new ArrayList<>();
Session session=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
//String query = "SELECT invoice_value FROM sme_principal_dealers_purchase_data_file WHERE is_processed=0 and dealer_id ='"+dealer_id+"'";// and STR_TO_DATE(purchase_entry_date,'%d-%m-%Y') = CURRENT_DATE()"; // ORDER BY invoice_date
String query = "SELECT SUM(invoice_value) "+
"FROM sme_principal_dealers_purchase_data_file WHERE is_processed=0 " +
"AND dealer_id ='"+dealer_id+"' " +
"GROUP BY SUBSTRING(invoice_date,4,2)";
session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery crt = session.createSQLQuery(query);
dealerInvoicesValuefromDPD = crt.list();
/* Iterator it = list.iterator();
List<Object> rl = new ArrayList<Object>();
while (it.hasNext()) {
Object[] report = (Object[]) it.next();
dealerPurchaseDatas.add(new DealerPurchaseStatisticsData(report));
}*/
//logger.info("dealerInvoicesValuefromDPD :: "+dealerInvoicesValuefromDPD);
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return dealerInvoicesValuefromDPD;
}
public List<DealerPurchaseStatisticsData> findStatisticsFromDealerPurchaseDataStoreWise(Integer main_principal_id,String store_code)
{
List<DealerPurchaseStatisticsData> dealerPurchaseDatas=new ArrayList<DealerPurchaseStatisticsData>();
logger.info("inside :findStatisticsFromDealerPurchaseData() method");
// List reportList = new ArrayList<>();
Session session=null;
/*
private String customer_code;
private String invoice_date;
private Double avg_order_amount;
private Long invoice_number_count;
private int dealer_id;
private int principal_id;
private Double order_amount;
private Long invoice_number;
*/
try{
session=getHibernateTemplate().getSessionFactory().openSession();
//STR_TO_DATE(purchase_entry_date,'%d-%m-%Y') = CURRENT_DATE() AND
String query = "SELECT customer_code, SUM(invoice_value) as avg_order_amount, COUNT(invoice_number) as invoice_number_count, invoice_date, dealer_id, principal_id,lender_id,id, main_principal_id,store_code FROM sme_principal_dealers_purchase_data_file WHERE is_processed=0 and main_principal_id = '"+main_principal_id+"' and store_code = '"+store_code+"' GROUP BY customer_code ORDER BY invoice_date , city";
//Query sr = session.createQuery(query);
//sr.setResultTransformer(Transformers.aliasToBean(DealerPurchaseStatisticsData.class));
//dealerPurchaseDatas = (List<DealerPurchaseStatisticsData>)sr.list();
session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery crt = session.createSQLQuery(query);
List list = crt.list();
Iterator it = list.iterator();
// List<Object> rl = new ArrayList<Object>();
while (it.hasNext()) {
Object[] report = (Object[]) it.next();
dealerPurchaseDatas.add(new DealerPurchaseStatisticsData(report));
}
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return dealerPurchaseDatas;
}
public List<DealerPurchaseStatisticsData> findStatisticsFromDealerPurchaseData(Integer main_principal_id)
{
List<DealerPurchaseStatisticsData> dealerPurchaseDatas=new ArrayList<DealerPurchaseStatisticsData>();
logger.info("inside :findStatisticsFromDealerPurchaseData() method");
// List reportList = new ArrayList<>();
Session session=null;
/*
private String customer_code;
private String invoice_date;
private Double avg_order_amount;
private Long invoice_number_count;
private int dealer_id;
private int principal_id;
private Double order_amount;
private Long invoice_number;
*/
try{
session=getHibernateTemplate().getSessionFactory().openSession();
//STR_TO_DATE(purchase_entry_date,'%d-%m-%Y') = CURRENT_DATE() AND
String query = "SELECT customer_code, SUM(invoice_value) as avg_order_amount, COUNT(invoice_number) as invoice_number_count, invoice_date, dealer_id, principal_id,lender_id,id, main_principal_id,store_code FROM sme_principal_dealers_purchase_data_file WHERE is_processed=0 and main_principal_id = "+main_principal_id+" GROUP BY customer_code ORDER BY invoice_date , city";
//Query sr = session.createQuery(query);
//sr.setResultTransformer(Transformers.aliasToBean(DealerPurchaseStatisticsData.class));
//dealerPurchaseDatas = (List<DealerPurchaseStatisticsData>)sr.list();
session = getHibernateTemplate().getSessionFactory().openSession();
SQLQuery crt = session.createSQLQuery(query);
List list = crt.list();
Iterator it = list.iterator();
// List<Object> rl = new ArrayList<Object>();
while (it.hasNext()) {
Object[] report = (Object[]) it.next();
dealerPurchaseDatas.add(new DealerPurchaseStatisticsData(report));
}
} catch (Exception e) {
logger.info(e);
StringWriter stack = new StringWriter();
e.printStackTrace(new PrintWriter(stack));
logger.info("Caught exception; during action : " + stack.toString());
} finally {
if (session != null)
session.close();
}
return dealerPurchaseDatas;
}
public SMEPrincipalSalesManagerEmailForP1SC getSMEPrincipalSalesManagerEmailFromStore(List<String> store_codes,String principal_name)
{
logger.info("inside :getSMEPrincipalSalesManagerEmailFromStore() method for store code " +store_codes);
List<SMEPrincipalSalesManagerEmailForP1SC> l=null;
Criteria criteria=null;
Session session=null;
SMEPrincipalSalesManagerEmailForP1SC smePrincipalSalesManagerEmailForP1SC=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
criteria=session.createCriteria(SMEPrincipalSalesManagerEmailForP1SC.class);
criteria.add(Restrictions.in("store_code", store_codes));
criteria.add(Restrictions.eq("principal_name", principal_name));
l=criteria.list();
if(!l.isEmpty())
{
smePrincipalSalesManagerEmailForP1SC=l.get(0);
logger.error("smePrincipalSalesManagerEmailForP1SC :: "+smePrincipalSalesManagerEmailForP1SC);
}
}
catch(Exception e)
{
logger.error("Error :: "+e);
}
return smePrincipalSalesManagerEmailForP1SC;
}
public SMEPrincipalSalesManagerEmailForP1SC getSMEPrincipalSalesManagerEmailFromStore(String store_code,Integer main_principal_id)
{
logger.info("inside :getSMEPrincipalSalesManagerEmailFromStore() method for store code " +store_code);
List<SMEPrincipalSalesManagerEmailForP1SC> l=null;
Criteria criteria=null;
Session session=null;
SMEPrincipalSalesManagerEmailForP1SC smePrincipalSalesManagerEmailForP1SC=null;
try{
session=getHibernateTemplate().getSessionFactory().openSession();
criteria=session.createCriteria(SMEPrincipalSalesManagerEmailForP1SC.class);
criteria.add(Restrictions.eq("store_code", store_code));
criteria.add(Restrictions.eq("main_principal_id", main_principal_id));
l=criteria.list();
if(!l.isEmpty())
{
smePrincipalSalesManagerEmailForP1SC=l.get(0);
logger.error("smePrincipalSalesManagerEmailForP1SC :: "+smePrincipalSalesManagerEmailForP1SC);
}
}
catch(Exception e)
{
logger.error("Error :: "+e);
}
return smePrincipalSalesManagerEmailForP1SC;
}
}
|
package day23date;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
public class Date01 {
public static void main(String[] args) {
// bu gunun tarihini ekrana yazdiralim
System.out.println(LocalDate.now());
System.out.println(LocalTime.now());
System.out.println(LocalDateTime.now());
}
}
|
/*
* Copyright (c) 2013 University of Tartu
*/
package org.jpmml.manager;
import java.util.*;
import org.dmg.pmml.*;
import com.google.common.collect.*;
import static com.google.common.base.Preconditions.*;
public class AssociationModelManager extends ModelManager<AssociationModel> implements HasEntityRegistry<AssociationRule> {
private AssociationModel associationModel = null;
public AssociationModelManager(){
}
public AssociationModelManager(PMML pmml){
this(pmml, find(pmml.getContent(), AssociationModel.class));
}
public AssociationModelManager(PMML pmml, AssociationModel associationModel){
super(pmml);
this.associationModel = associationModel;
}
@Override
public String getSummary(){
return "Association rules model";
}
public FieldName getActiveField(){
List<FieldName> activeFields = getActiveFields();
if(activeFields.size() < 1){
throw new InvalidFeatureException("No active fields", getMiningSchema());
} else
if(activeFields.size() > 1){
throw new InvalidFeatureException("Too many active fields", getMiningSchema());
}
return activeFields.get(0);
}
@Override
public FieldName getTargetField(){
List<FieldName> predictedFields = getPredictedFields();
if(predictedFields.size() < 1){
return null;
}
return super.getTargetField();
}
@Override
public AssociationModel getModel(){
checkState(this.associationModel != null);
return this.associationModel;
}
/**
* @see #getModel()
*/
public AssociationModel createModel(Double minimumSupport, Double minimumConfidence){
checkState(this.associationModel == null);
this.associationModel = new AssociationModel(new MiningSchema(), MiningFunctionType.ASSOCIATION_RULES, 0, minimumSupport, minimumConfidence, 0, 0, 0);
getModels().add(this.associationModel);
return this.associationModel;
}
/**
* @return A bidirectional map between {@link Item#getId Item identifiers} and {@link Item instances}.
*/
public BiMap<String, Item> getItemRegistry(){
BiMap<String, Item> result = HashBiMap.create();
List<Item> items = getItems();
for(Item item : items){
result.put(item.getId(), item);
}
return result;
}
/**
* @return A bidirectional map between {@link Itemset#getId() Itemset identifiers} and {@link Itemset instances}.
*/
public BiMap<String, Itemset> getItemsetRegistry(){
BiMap<String, Itemset> result = HashBiMap.create();
List<Itemset> itemsets = getItemsets();
for(Itemset itemset : itemsets){
result.put(itemset.getId(), itemset);
}
return result;
}
@Override
public BiMap<String, AssociationRule> getEntityRegistry(){
BiMap<String, AssociationRule> result = HashBiMap.create();
List<AssociationRule> associationRules = getAssociationRules();
EntityUtil.putAll(associationRules, result);
return result;
}
public List<Item> getItems(){
AssociationModel associationModel = getModel();
return associationModel.getItems();
}
public List<Itemset> getItemsets(){
AssociationModel associationModel = getModel();
return associationModel.getItemsets();
}
public List<AssociationRule> getAssociationRules(){
AssociationModel associationModel = getModel();
return associationModel.getAssociationRules();
}
} |
package com.jim.multipos.ui.reports.hourly_sales;
import com.github.mjdev.libaums.fs.UsbFile;
import com.jim.multipos.core.BaseTableReportView;
public interface HourlySalesReportView extends BaseTableReportView{
void initTable(Object[][] objects);
void updateTable(Object[][] objects);
void exportTableToExcel(String fileName, String path, Object[][] objects, String date);
void exportTableToPdf(String fileName, String path, Object[][] objects, String date);
void openExportDialog(int mode);
void exportExcelToUSB(String filename, UsbFile root, Object[][] objects, String date);
void exportTableToPdfToUSB(String fileName, UsbFile path, Object[][] objects, String date);
}
|
package eat_pizza_vistor;
class RemAV {
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package controlador;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
*
* @author LEARNING CENTER
*/
public class Conexion {
public static Connection connection;
private Conexion() {
}
public static Connection obtenerInstancia(){
if (connection==null){
String url= "jdbc:oracle:thin:@MSP-PM-04-01.aws.smartcloud.cl:1521:xe";
String user="usuario05";
String pass="usuario05";
System.out.println("Proceso de Coneccion...");
try {
connection= DriverManager.getConnection(url, user, pass);
System.out.println("Base de datos Conectada!!");
}catch (SQLException e) {
System.out.println(e.getMessage());
}
}
return connection;
}
}
|
package controller;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import dao.FollowDAO;
import dao.UserDAO;
import model.UserModel;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
public class UserController extends Controller {
public UserController(ServletContext context, HttpServletRequest request, HttpServletResponse response) {
super(context, request, response);
}
@Override
public void indexAction() throws Exception {
// TODO Auto-generated method stub
}
@Override
public void showAction() throws Exception {
int user_id = Integer.parseInt(request.getParameter("id"));
if (user_id == 0) {
response.sendRedirect(request.getContextPath() + "/index");
return;
}
HttpSession session = request.getSession();
UserModel currentUser = null;
try {
currentUser = (UserModel) session.getAttribute("user");
} catch (Exception e) {
e.printStackTrace();
}
UserDAO dao = new UserDAO();
FollowDAO fdao = new FollowDAO();
UserModel user = new UserModel();
user = dao.findById(user_id);
if (fdao.isFollowing(currentUser.getId(), user.getId())) {
request.setAttribute("isFollowing", 1);
} else {
request.setAttribute("isFollowing", 0);
}
request.setAttribute("user", user);
}
@Override
public void newAction() throws Exception {
}
@Override
public void editAction() throws Exception {
HttpSession session = request.getSession();
if (session.getAttribute("user") == null) {
List<String> messages = new ArrayList<>();
messages.add("ログインしてください");
alert(messages, "/WEB-INF/jsp/session/new.jsp");
return;
}
}
@Override
public void createAction() throws Exception {
String username = request.getParameter("username");
String email = request.getParameter("email");
String password = request.getParameter("password");
String passwordConfirmation = request.getParameter("passwordConfirmation");
UserDAO dao = new UserDAO();
UserModel user = dao.findByEmail(email);
List<String> messages = new ArrayList<>();
if (username.isEmpty()) {
messages.add("ユーザー名を入力してください。");
}
if (dao.findByUsername(username) != null) {
messages.add("既に登録されているユーザー名です。");
}
if (email.isEmpty()) {
messages.add("Eメールアドレスを入力してください");
}
if (user != null) {
messages.add(email + "は既に登録されています");
}
if (password.isEmpty()) {
messages.add("パスワードを入力してください");
}
if (passwordConfirmation.isEmpty()) {
messages.add("確認パスワードを入力してください");
}
if (!password.equals(passwordConfirmation)) {
messages.add("パスワードと確認パスワードが一致しません");
}
if (!messages.isEmpty()) {
alert(messages, "/WEB-INF/jsp/user/new.jsp");
return;
}
Timestamp createdAt = new Timestamp(System.currentTimeMillis());
dao.createUser(username, email, createHash(password), createdAt, createdAt);
response.sendRedirect(request.getContextPath() + "/index");
}
@Override
public void updateAction() throws Exception {
HttpSession session = request.getSession();
UserModel user = (UserModel) session.getAttribute("user");
String username = request.getParameter("username");
String email = request.getParameter("email");
List<String> messages = new ArrayList<>();
if (username == null && email == null) {
if (username.isEmpty() && username.isEmpty()) {
messages.add("変更する項目がありません");
alert(messages, "/WEB-INF/jsp/user/edit.jsp");
return;
}
}
if (username != null) {
if (!username.isEmpty()) {
user.setUsername(username);
}
}
if (email != null) {
if (!email.isEmpty()) {
user.setEmail(email);
}
}
UserDAO dao = new UserDAO();
dao.updateUser(user);
response.sendRedirect(request.getContextPath() + "/index");
}
@Override
public void deleteAction() throws Exception {
// TODO Auto-generated method stub
}
private String createHash(String password) {
BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
return bcrypt.encode(password);
}
private boolean authenticate(String password, String encryptedPassword) {
BCryptPasswordEncoder bcrypt = new BCryptPasswordEncoder();
return bcrypt.matches(password, encryptedPassword);
}
}
|
package com.tencent.mm.plugin.sns.ui.a;
import com.tencent.mm.model.q;
import com.tencent.mm.plugin.appbrand.s$l;
import com.tencent.mm.plugin.sns.i$f;
import com.tencent.mm.plugin.sns.i$g;
import com.tencent.mm.plugin.sns.i.e;
import com.tencent.mm.plugin.sns.ui.PhotosContent;
import com.tencent.mm.plugin.sns.ui.TagImageView;
import com.tencent.mm.plugin.sns.ui.ap;
import com.tencent.mm.plugin.sns.ui.ar;
import com.tencent.mm.plugin.sns.ui.av;
import com.tencent.mm.plugin.sns.ui.ay;
import com.tencent.mm.protocal.c.atf;
import com.tencent.mm.protocal.c.bsu;
import com.tencent.mm.sdk.platformtools.x;
import java.util.ArrayList;
import java.util.List;
public final class c extends a {
private int nUn = s$l.AppCompatTheme_checkedTextViewStyle;
public final void c(com.tencent.mm.plugin.sns.ui.a.a.c cVar) {
cVar.ojb.setImageResource(e.lucky_friendactivity_comment_icon);
cVar.oiH.setTextColor(-2730427);
if (cVar.oiQ != null) {
cVar.oiQ.setLayoutResource(i$g.sns_hb_reward_item);
if (!cVar.oiR) {
cVar.oji = (PhotosContent) cVar.oiQ.inflate();
cVar.oiR = true;
}
} else {
cVar.oji = (PhotosContent) cVar.jEz.findViewById(i$f.hb_content_rl);
cVar.oiR = true;
}
x.i("MiroMsg.HBRewardTimeLineItem", "viewtype " + this.hER);
TagImageView tagImageView = (TagImageView) cVar.oji.findViewById(ar.nYB[0]);
cVar.oji.a(tagImageView);
tagImageView.setOnClickListener(this.nuc.ntw.nNR);
}
public final void a(com.tencent.mm.plugin.sns.ui.a.a.c cVar, int i, ay ayVar, bsu bsu, int i2, av avVar) {
String str = ayVar.nMU;
if (cVar.ojT != null) {
if (!ayVar.oeM || cVar.nib.smZ == null || cVar.nib.smZ.snB <= 0) {
cVar.ojT.setBackgroundResource(e.friendactivity_comment_detail_list_golden_arror);
} else {
cVar.ojT.setBackgroundResource(e.friendactivity_comment_detail_list_golden_myself);
}
}
TagImageView xm = cVar.oji.xm(0);
List arrayList = new ArrayList();
arrayList.add(xm);
ap apVar = new ap();
apVar.bNH = str;
apVar.index = 0;
apVar.nWx = arrayList;
apVar.nTx = this.nTx;
if (xm != null) {
xm.setTag(apVar);
}
atf atf = ayVar.ofn;
cVar.nJn = atf;
ar arVar;
PhotosContent photosContent;
String str2;
int hashCode;
boolean z;
com.tencent.mm.storage.av clT;
if (atf == null) {
x.e("MiroMsg.HBRewardTimeLineItem", "mediaPostInfo is null " + ayVar.nMU);
} else if (q.GF().equals(bsu.hbL)) {
cVar.oji.setVisibility(0);
arVar = avVar.nUc;
photosContent = cVar.oji;
str2 = ayVar.nMU;
hashCode = this.mActivity.hashCode();
z = this.nTx;
clT = com.tencent.mm.storage.av.clT();
clT.time = bsu.lOH;
arVar.a(photosContent, bsu, str2, hashCode, i2, i, z, clT, true);
} else if (ayVar.oeP) {
cVar.oji.setVisibility(0);
arVar = avVar.nUc;
photosContent = cVar.oji;
str2 = ayVar.nMU;
hashCode = this.mActivity.hashCode();
z = this.nTx;
clT = com.tencent.mm.storage.av.clT();
clT.time = bsu.lOH;
arVar.a(photosContent, bsu, str2, hashCode, i2, i, z, clT, false);
} else if (atf.ceS == 0) {
cVar.oji.setVisibility(0);
arVar = avVar.nUc;
photosContent = cVar.oji;
str2 = ayVar.nMU;
hashCode = this.mActivity.hashCode();
z = this.nTx;
clT = com.tencent.mm.storage.av.clT();
clT.time = bsu.lOH;
arVar.a(photosContent, bsu, str2, hashCode, i2, i, z, clT, true);
} else {
x.e("MiroMsg.HBRewardTimeLineItem", "mediaPostInfo.hbStatus is " + atf.ceS);
}
}
}
|
/**
* @Author LinhNDHSE61828
* @Create on Apr 13, 2016 10:36:45 AM
*/
import java.util.Comparator;
public class Machine implements Comparable {
private String code = "", make = "";
private int voltage = 0;
private double price = 0.0;
public Machine() {
}
public Machine(String c, String m, int v, double p) {
code = c;
make = m;
voltage = v;
price = p;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public int getVoltage() {
return voltage;
}
public void setVoltage(int voltage) {
this.voltage = voltage;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
@Override
public String toString() {
return code + ", " + make + ", " + voltage + ", " + price;
}
@Override
public int compareTo(Object mac) {
if (this.getPrice() > ((Machine) mac).getPrice()) {
return 1;
}
if (this.getPrice() < ((Machine) mac).getPrice()) {
return -1;
}
return 0;
}
} |
package com.tencent.mm.plugin.backup.c;
import android.content.SharedPreferences.Editor;
import android.os.Build;
import android.os.Build.VERSION;
import com.tencent.mm.a.k;
import com.tencent.mm.compatible.e.q;
import com.tencent.mm.plugin.backup.a.b.b;
import com.tencent.mm.plugin.backup.a.g;
import com.tencent.mm.plugin.backup.f.b.c;
import com.tencent.mm.plugin.backup.f.f.a;
import com.tencent.mm.plugin.backup.f.i;
import com.tencent.mm.plugin.backup.h.e;
import com.tencent.mm.plugin.backup.h.f;
import com.tencent.mm.plugin.backup.h.j;
import com.tencent.mm.plugin.backup.h.m;
import com.tencent.mm.plugin.backup.h.o;
import com.tencent.mm.plugin.backup.h.v;
import com.tencent.mm.plugin.backup.h.w;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.sdk.platformtools.ah;
import com.tencent.mm.sdk.platformtools.aj;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.smtt.export.external.interfaces.IX5WebViewClient;
import java.util.Iterator;
import java.util.LinkedList;
public final class d implements b, com.tencent.mm.plugin.backup.f.b.d {
public static boolean gTb = false;
public static boolean gUB = false;
public byte[] bitmapData;
public com.tencent.mm.plugin.backup.a.b.d gSW;
public boolean gTY = false;
public int gUA = 0;
private int gUC;
private int gUD;
private int gUE = 0;
public e gUF = new e(new 5(this), b.arv().aqP());
public c gUo = new 2(this);
private final a gUp = new 3(this);
public final i.a gUq = new 4(this);
public LinkedList<String> gUu;
private com.tencent.mm.plugin.backup.b.b gUv;
private com.tencent.mm.plugin.backup.b.c gUw;
public long gUx = 0;
public long gUy = 0;
public boolean gUz = false;
public final void an(boolean z) {
x.e("MicroMsg.BackupMoveServer", "summerbak BackupMoveServer CANCEL, Caller:%s", new Object[]{aj.cin()});
if (!z) {
arE();
}
if (this.gUw != null) {
this.gUw.cancel();
}
if (this.gUv != null) {
this.gUv.cancel();
this.gUv = null;
}
x.i("MicroMsg.BackupMoveServer", "cancel , notifyall.");
com.tencent.mm.plugin.backup.f.b.asm();
com.tencent.mm.plugin.backup.f.b.aso();
}
public static void c(int i, long j, long j2, int i2) {
x.i("MicroMsg.BackupMoveServer", "setBakupSelectTimeData, timeMode[%d], startTime[%d], endTime[%d], contentType[%d]", new Object[]{Integer.valueOf(i), Long.valueOf(j), Long.valueOf(j2), Integer.valueOf(i2)});
if (i == 0) {
j2 = 0;
j = 0;
}
b.arv();
Editor edit = b.aqU().edit();
edit.putInt("BACKUP_MOVE_CHOOSE_SELECT_TIME_MODE", i);
edit.putLong("BACKUP_MOVE_CHOOSE_SELECT_START_TIME", j);
edit.putLong("BACKUP_MOVE_CHOOSE_SELECT_END_TIME", j2);
edit.putInt("BACKUP_MOVE_CHOOSE_SELECT_CONTENT_TYPE", i2);
edit.commit();
}
public final void a(boolean z, int i, byte[] bArr, int i2) {
String str = "MicroMsg.BackupMoveServer";
String str2 = "summerbak onNotify isLocal:%b type:%d seq:%d buf:%d";
Object[] objArr = new Object[4];
objArr[0] = Boolean.valueOf(z);
objArr[1] = Integer.valueOf(i);
objArr[2] = Integer.valueOf(i2);
objArr[3] = Integer.valueOf(bArr == null ? -1 : bArr.length);
x.i(str, str2, objArr);
if (z && bArr != null && 10011 == i) {
x.i("MicroMsg.BackupMoveServer", "summerbak local disconnect, backupMoveState:%d", new Object[]{Integer.valueOf(b.arv().aqP().gRC)});
switch (b.arv().aqP().gRC) {
case -23:
case -21:
case IX5WebViewClient.ERROR_PROXY_AUTHENTICATION /*-5*/:
b.arv().arw().stop();
break;
case IX5WebViewClient.ERROR_AUTHENTICATION /*-4*/:
an(true);
break;
case 1:
b.arv().arw().stop();
b.arv().aqP().gRC = -100;
mw(-100);
break;
case 12:
case 14:
an(true);
b.arv().arw().stop();
b.arv().aqP().gRC = -4;
mw(-4);
h.mEJ.a(485, 24, 1, false);
if (!(this.gUw == null || this.gUw.gSk == 0)) {
long bH = bi.bH(this.gUw.gSk);
x.i("MicroMsg.BackupMoveServer", "onNotify backup transfer disconnect, backupDataSize:%d kb, backupCostTime:%d s", new Object[]{Long.valueOf(this.gUw.arc()), Long.valueOf(bH / 1000)});
break;
}
}
}
if (i == 1) {
v vVar = (v) g.a(new v(), bArr);
if (vVar == null) {
x.e("MicroMsg.BackupMoveServer", "authReq parseBuf failed:%d", new Object[]{Integer.valueOf(bi.bD(bArr))});
b.arv().aqP().gRC = -5;
mw(-5);
return;
}
if (bi.oW(b.arv().gRu)) {
b.arv().gRu = vVar.ID;
}
if (vVar.ID.equals(b.arv().gRu)) {
x.i("MicroMsg.BackupMoveServer", "authReq info, id:%s, step:%d", new Object[]{vVar.ID, Integer.valueOf(vVar.hcC)});
if (vVar.hcC == 0) {
if (!b.arv().gRv.equals(new String(k.a(vVar.hbs.lR, com.tencent.mm.plugin.backup.a.d.aqT())))) {
w wVar = new w();
wVar.hcC = 0;
wVar.ID = b.arv().gRu;
wVar.hcd = 1;
x.e("MicroMsg.BackupMoveServer", "get authReq step 0, but hello failed");
try {
x.i("MicroMsg.BackupMoveServer", "summerbak send authFailResp.");
com.tencent.mm.plugin.backup.f.b.o(wVar.toByteArray(), 2, i2);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupMoveServer", e, "buf to PACKET_TYPE_AUTHENTICATE_RESPONSE err.", new Object[0]);
}
b.arv().aqP().gRC = -5;
mw(-5);
}
if (vVar.hcD < com.tencent.mm.plugin.backup.a.c.gRm) {
x.i("MicroMsg.BackupMoveServer", "summerbak old move, version:%d", new Object[]{Integer.valueOf(vVar.hcD)});
h.mEJ.a(485, 103, 1, false);
b.arv().aqP().gRC = -12;
mw(-12);
return;
}
x.i("MicroMsg.BackupMoveServer", "summerbak start move");
this.gUD = i2;
if (gUB || gTb) {
if (gUB && gTb && (vVar.hcF & com.tencent.mm.plugin.backup.a.c.gRr) == 0 && (vVar.hcF & com.tencent.mm.plugin.backup.a.c.gRs) == 0) {
b.arv().aqP().gRC = -31;
mw(-31);
this.gUE = 1;
return;
} else if (gUB && (vVar.hcF & com.tencent.mm.plugin.backup.a.c.gRr) == 0) {
b.arv().aqP().gRC = -32;
mw(-32);
this.gUE = 2;
return;
} else if (gTb && (vVar.hcF & com.tencent.mm.plugin.backup.a.c.gRs) == 0) {
b.arv().aqP().gRC = -33;
mw(-33);
this.gUE = 3;
return;
}
}
dw(false);
return;
} else if (vVar.hcC == 1) {
if (!b.arv().gRw.equals(new String(k.a(vVar.hbs.lR, com.tencent.mm.plugin.backup.a.d.aqT())))) {
x.e("MicroMsg.BackupMoveServer", "get authReq step 1 and validate ok failed");
b.arv().aqP().gRC = -5;
mw(-5);
}
x.i("MicroMsg.BackupMoveServer", "get authReq step 1 and validate ok success");
b.arv().aqP().gRC = 2;
mw(2);
return;
} else {
return;
}
}
x.e("MicroMsg.BackupMoveServer", "id not equel:self:%s, authReq.id:%s", new Object[]{b.arv().gRu, vVar.ID});
an(false);
b.arv().aqP().gRC = -5;
mw(-5);
} else if (i == 3) {
this.gUC = i2;
if (b.arv().arz().gTA) {
arJ();
} else {
this.gUz = true;
}
} else if (i == 9) {
e eVar = (e) g.a(new e(), bArr);
if (eVar == null) {
x.e("MicroMsg.BackupMoveServer", "heartBeatRequest parseBuf failed:%d", new Object[]{Integer.valueOf(bi.bD(bArr))});
return;
}
x.i("MicroMsg.BackupMoveServer", "summerbak receive heartbeatReq,req:%s ack:%d", new Object[]{eVar, Long.valueOf(eVar.gXZ)});
f fVar = (f) g.a(new f(), bArr);
fVar.gXZ = eVar.gXZ;
try {
x.i("MicroMsg.BackupMoveServer", "summerbak send heartbeatResp");
com.tencent.mm.plugin.backup.f.b.o(fVar.toByteArray(), 10, i2);
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.BackupMoveServer", e2, "summerbak buf to BackupHeartBeatResponse err.", new Object[0]);
}
} else if (i == 10) {
try {
new f().aG(bArr);
} catch (Throwable e22) {
x.printErrStackTrace("MicroMsg.BackupMoveServer", e22, "summerbak heartbeatResp parse from buf error.", new Object[0]);
}
} else if (i == 5) {
x.i("MicroMsg.BackupMoveServer", "summerbak receive command cancel");
an(true);
b.arv().aqP().gRC = -100;
mw(-100);
} else if (i == 12) {
j jVar = (j) g.a(new j(), bArr);
if (jVar == null) {
x.e("MicroMsg.BackupMoveServer", "requestSessionResp parseBuf failed:%d", new Object[]{Integer.valueOf(bi.bD(bArr))});
b.arv().aqP().gRC = -5;
mw(-5);
return;
}
int i3;
LinkedList b = b(jVar.hbH, jVar.hbI);
str2 = "MicroMsg.BackupMoveServer";
String str3 = "summerbak backup receive requestsession response. backupSessionList:%d ";
Object[] objArr2 = new Object[1];
if (b == null) {
i3 = -1;
} else {
i3 = b.size();
}
objArr2[0] = Integer.valueOf(i3);
x.i(str2, str3, objArr2);
if (b == null) {
x.e("MicroMsg.BackupMoveServer", "requestSessionResp sessionName or timeInterval null or requestSessionResp number error.");
arE();
b.arv().aqP().gRC = -21;
mw(-21);
return;
}
com.tencent.mm.plugin.backup.f.b.a(this.gUp);
com.tencent.mm.plugin.backup.f.b.asl();
this.gUw = new com.tencent.mm.plugin.backup.b.c(b.arv(), 2, this);
this.gUw.dt(false);
this.gUw.a(b, b.arv().aqP().gRF, gTb);
}
}
public final void dw(boolean z) {
if (z) {
switch (this.gUE) {
case 1:
gUB = false;
gTb = false;
this.gUx = 0;
this.gUy = 0;
break;
case 2:
gUB = false;
this.gUx = 0;
this.gUy = 0;
break;
case 3:
gTb = false;
break;
}
}
w wVar = new w();
wVar.hcC = 0;
wVar.ID = b.arv().gRu;
wVar.hcD = com.tencent.mm.plugin.backup.a.c.gRm;
wVar.hcd = 0;
wVar.hcE = this.gUA;
wVar.hbs = new com.tencent.mm.bk.b(k.b(b.arv().gRw.getBytes(), com.tencent.mm.plugin.backup.a.d.aqT()));
if (bi.getInt(com.tencent.mm.k.g.AT().getValue("ChattingRecordsKvstatDisable"), 0) == 0) {
wVar.hcF |= com.tencent.mm.plugin.backup.a.c.gRq;
}
wVar.hcF |= com.tencent.mm.plugin.backup.a.c.gRr;
wVar.hcF |= com.tencent.mm.plugin.backup.a.c.gRs;
try {
x.i("MicroMsg.BackupMoveServer", "summerbak send authSuccessResp.");
com.tencent.mm.plugin.backup.f.b.o(wVar.toByteArray(), 2, this.gUD);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupMoveServer", e, "buf to PACKET_TYPE_AUTHENTICATE_RESPONSE err.", new Object[0]);
}
}
public final void arJ() {
x.i("MicroMsg.BackupMoveServer", "startRequestNotify receive start request.");
this.gUz = false;
b.arv().aqP().gRC = 12;
mw(12);
com.tencent.mm.plugin.backup.g.d.asG().asJ();
if (this.gUu != null) {
long j;
x.i("MicroMsg.BackupMoveServer", "transfer conversation size:%d", new Object[]{Integer.valueOf(this.gUu.size())});
o oVar = new o();
oVar.ID = b.arv().gRu;
oVar.hcb = (long) this.gUu.size();
a arz = b.arv().arz();
if (arz.ars() == null) {
j = 0;
} else {
Iterator it = arz.ars().iterator();
j = 0;
while (it.hasNext()) {
j = ((com.tencent.mm.plugin.backup.a.f.b) it.next()).gRL + j;
}
}
oVar.hcc = j;
oVar.hcd = 0;
oVar.hce = this.gTY ? com.tencent.mm.plugin.backup.a.c.gRl : com.tencent.mm.plugin.backup.a.c.gRk;
if (gTb) {
oVar.hca = 3;
}
m mVar = new m();
mVar.hbO = q.zz();
mVar.hbP = Build.MANUFACTURER;
mVar.hbQ = Build.MODEL;
mVar.hbR = "Android";
mVar.hbS = VERSION.RELEASE;
mVar.hbT = com.tencent.mm.protocal.d.qVN;
mVar.hbU = 0;
x.i("MicroMsg.BackupMoveServer", "startRequestNotify generalinfo wechatversion:%s", new Object[]{Integer.valueOf(com.tencent.mm.protocal.d.qVN)});
oVar.hbY = mVar;
try {
com.tencent.mm.plugin.backup.f.b.o(oVar.toByteArray(), 4, this.gUC);
x.i("MicroMsg.BackupMoveServer", "backupSendRequestSession sessionName[%d], startTime[%d], endTime[%d]", new Object[]{Integer.valueOf(this.gUu.size()), Long.valueOf(this.gUx), Long.valueOf(this.gUy)});
com.tencent.mm.plugin.backup.h.i iVar = new com.tencent.mm.plugin.backup.h.i();
iVar.hbH = this.gUu;
iVar.hbI = new LinkedList();
Iterator it2 = this.gUu.iterator();
while (it2.hasNext()) {
it2.next();
iVar.hbI.add(Long.valueOf(r0));
iVar.hbI.add(Long.valueOf(j));
}
try {
x.i("MicroMsg.BackupMoveServer", "backupSendRequestSession, chooseConvNames size:%d", new Object[]{Integer.valueOf(this.gUu.size())});
com.tencent.mm.plugin.backup.f.b.J(iVar.toByteArray(), 11);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupMoveServer", e, "backupSendRequestSession BackupRequestSession parse req failed.", new Object[0]);
}
} catch (Throwable e2) {
x.e("MicroMsg.BackupMoveServer", "startRequestNotify prase startResp error!!");
x.printErrStackTrace("MicroMsg.BackupMoveServer", e2, "", new Object[0]);
}
}
}
private static void arE() {
com.tencent.mm.plugin.backup.h.a aVar = new com.tencent.mm.plugin.backup.h.a();
aVar.ID = b.arv().gRu;
try {
x.i("MicroMsg.BackupMoveServer", "backupSendCancelRequest.");
com.tencent.mm.plugin.backup.f.b.J(aVar.toByteArray(), 5);
} catch (Throwable e) {
x.printErrStackTrace("MicroMsg.BackupMoveServer", e, "buf to BackupCancelRequest err.", new Object[0]);
}
}
public static String arK() {
return com.tencent.mm.plugin.backup.f.b.asp();
}
public final void mw(int i) {
if (this.gSW != null) {
ah.A(new 1(this, i));
}
}
public final void aqL() {
}
public final void aqM() {
an(false);
}
private static LinkedList<com.tencent.mm.plugin.backup.a.f.a> b(LinkedList<String> linkedList, LinkedList<Long> linkedList2) {
if (linkedList == null || linkedList2 == null || linkedList.isEmpty() || linkedList.size() * 2 != linkedList2.size()) {
return null;
}
LinkedList<com.tencent.mm.plugin.backup.a.f.a> linkedList3 = new LinkedList();
Iterator it = linkedList2.iterator();
long j = 0;
long j2 = 0;
for (int i = 0; i < linkedList.size(); i++) {
if (it.hasNext()) {
j2 = ((Long) it.next()).longValue();
if (it.hasNext()) {
j = ((Long) it.next()).longValue();
}
}
linkedList3.add(new com.tencent.mm.plugin.backup.a.f.a(i, (String) linkedList.get(i), j2, j));
}
return linkedList3;
}
}
|
package com.lubarov.daniel.wedding.admin;
import com.lubarov.daniel.data.option.Option;
import com.lubarov.daniel.data.util.Check;
import com.lubarov.daniel.web.html.Attribute;
import com.lubarov.daniel.web.html.Element;
import com.lubarov.daniel.web.html.Node;
import com.lubarov.daniel.web.html.ParagraphBuilder;
import com.lubarov.daniel.web.html.Tag;
import com.lubarov.daniel.web.http.HttpRequest;
import com.lubarov.daniel.web.http.HttpResponse;
import com.lubarov.daniel.web.http.HttpStatus;
import com.lubarov.daniel.web.http.server.Handler;
import com.lubarov.daniel.web.http.server.util.HttpResponseFactory;
import com.lubarov.daniel.wedding.MiscStorage;
import com.lubarov.daniel.wedding.WeddingLayout;
final class AdminSetupHandler implements Handler {
public static final AdminSetupHandler singleton = new AdminSetupHandler();
private AdminSetupHandler() {}
@Override
public HttpResponse handle(HttpRequest request) {
Check.that(MiscStorage.tryGetAdminPassword().isEmpty(),
"Admin password already set.");
switch (request.getMethod()) {
case GET:
case HEAD:
return handleGet(request);
case POST:
return handlePost(request);
default:
throw new RuntimeException();
}
}
private HttpResponse handlePost(HttpRequest request) {
String adminPassword = request.getUrlencodedPostData().getValues("admin_password")
.tryGetOnlyElement().getOrThrow("Expected exactly one password in post data.");
MiscStorage.setAdminPassword(adminPassword);
Element document = WeddingLayout.createDocument(Option.some("Success"),
new ParagraphBuilder().addEscapedText("Password has been set.").build());
return HttpResponseFactory.xhtmlResponse(HttpStatus.OK, document);
}
private HttpResponse handleGet(HttpRequest request) {
Element passwordInput = new Element.Builder(Tag.INPUT)
.setRawAttribute(Attribute.TYPE, "password")
.setRawAttribute(Attribute.NAME, "admin_password")
.build();
Element submit = new Element.Builder(Tag.INPUT)
.setRawAttribute(Attribute.TYPE, "submit")
.build();
Node content = new Element.Builder(Tag.FORM)
.setRawAttribute(Attribute.ACTION, "admin")
.setRawAttribute(Attribute.METHOD, "post")
.addEscapedText("Create Admin Password:")
.addChild(new Element(Tag.BR))
.addChild(passwordInput)
.addChild(new Element(Tag.BR))
.addChild(submit)
.build();
Element document = WeddingLayout.createDocument(Option.some("Admin Setup"), content);
return HttpResponseFactory.xhtmlResponse(HttpStatus.OK, document);
}
}
|
public class LFU {
// private LinkedList<Integer> linkedList;
//
// /**
// * 最不常用数据淘汰算法
// */
// public LFU() {
// this.linkedList = new LinkedList<>();
// }
//
// @Override
// public Integer get(Integer key) {
// return null;
// }
//
// @Override
// public void put(Integer key, Integer value) {
//
// }
}
|
package com.flutterwave.raveandroid.rave_presentation.banktransfer;
import com.flutterwave.raveandroid.rave_java_commons.Payload;
import com.flutterwave.raveandroid.rave_presentation.FeeCheckListener;
import com.flutterwave.raveandroid.rave_presentation.NullFeeCheckListener;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
class BankTransferInteractorImpl implements BankTransferContract.BankTransferInteractor {
private BankTransferPaymentCallback callback;
private String flwRef;
private FeeCheckListener feeCheckListener;
BankTransferInteractorImpl(BankTransferPaymentCallback callback) {
this.callback = (callback != null) ? callback : new NullBankTransferPaymentCallback();
this.feeCheckListener = new NullFeeCheckListener();
}
@Override
public void showProgressIndicator(boolean active) {
callback.showProgressIndicator(active);
}
@Override
public void onPaymentSuccessful(String status, String flwRef, String responseAsJSONString) {
this.flwRef = flwRef;
callback.onSuccessful(flwRef);
}
@Override
public void onTransactionFeeFetched(String chargeAmount, Payload payload, String fee) {
feeCheckListener.onTransactionFeeFetched(chargeAmount, fee);
}
@Override
public void onFetchFeeError(String errorMessage) {
feeCheckListener.onFetchFeeError(errorMessage);
}
@Override
public void onPaymentFailed(String message, String responseAsJsonString) {
try {
Type type = new TypeToken<JsonObject>() {
}.getType();
JsonObject responseJson = new Gson().fromJson(responseAsJsonString, type);
flwRef = responseJson.getAsJsonObject("data").get("flwref").getAsString();
} catch (Exception e) {
e.printStackTrace();
}
callback.onError(message, flwRef);
}
@Override
public void onTransferDetailsReceived(String amount, String accountNumber, String bankName, String beneficiaryName) {
callback.onTransferDetailsReceived(amount, accountNumber, bankName, beneficiaryName);
}
@Override
public void onPollingTimeout(String flwRef, String txRef, String responseAsJSONString) {
callback.onPollingTimeout(flwRef);
}
@Override
public void onPollingCanceled(String flwRef, String txRef, String responseAsJSONString) {
// User to handle this
}
@Override
public void onPaymentError(String errorMessage) {
callback.onError(errorMessage, null);
}
@Override
public void showPollingIndicator(boolean active) {
callback.showProgressIndicator(active);
}
public String getFlwRef() {
return flwRef;
}
public void setFeeCheckListener(FeeCheckListener feeCheckListener) {
this.feeCheckListener = (feeCheckListener != null) ? feeCheckListener : new NullFeeCheckListener();
}
}
|
package internals;
import java.util.List;
import java.util.Map;
public class Person {
public String name;
public int age;
@JsonIgnore
private float salary;
private int id;
public Job job;
public List<String> favBooks;
//
// public Map<Integer, String> friends;
public void setSalary(float salary) {
this.salary = salary;
}
public void setId(int id) {
this.id = id;
}
}
|
package com.herokuapp.apimotooto.config;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.herokuapp.apimotooto.model.User;
import com.herokuapp.apimotooto.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.herokuapp.apimotooto.util.JwtUtil.EMAIL;
@Component
@RequiredArgsConstructor
public class JwtFilter extends OncePerRequestFilter {
private final UserRepository userRepository;
@Value ("${authentication.jwt.secret}")
private String secret;
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
FilterChain filterChain) throws ServletException, IOException {
String authorization = httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION);
if (authorization == null || authorization.isEmpty()) {
filterChain.doFilter(httpServletRequest, httpServletResponse);
return;
}
String email = getEmail(authorization);
User user = userRepository.findUserByEmail(email)
.orElseThrow(
() -> new UsernameNotFoundException(
"Username with email " + email + " does not exist"));
UsernamePasswordAuthenticationToken token = getToken(user);
token.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpServletRequest));
SecurityContextHolder.getContext().setAuthentication(token);
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
private String getEmail(String authorization) {
JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC512(secret)).build();
DecodedJWT verify = jwtVerifier.verify(authorization.substring(7));
return verify.getClaim(EMAIL).asString();
}
private UsernamePasswordAuthenticationToken getToken(User user) {
return new UsernamePasswordAuthenticationToken(
user,
user.getEmail(),
user.getAuthorities()
);
}
}
|
package com.facebook.react.flat;
import android.graphics.Rect;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ReactStylesDiffMap;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.annotations.ReactPropGroup;
final class RCTView extends FlatShadowNode {
private static final int[] SPACING_TYPES = new int[] { 8, 0, 2, 1, 3 };
private DrawBorder mDrawBorder;
private Rect mHitSlop;
boolean mHorizontal;
boolean mRemoveClippedSubviews;
private DrawBorder getMutableBorder() {
DrawBorder drawBorder = this.mDrawBorder;
if (drawBorder == null) {
this.mDrawBorder = new DrawBorder();
} else if (drawBorder.isFrozen()) {
this.mDrawBorder = (DrawBorder)this.mDrawBorder.mutableCopy();
}
invalidate();
return this.mDrawBorder;
}
public final boolean clipsSubviews() {
return this.mRemoveClippedSubviews;
}
protected final void collectState(StateBuilder paramStateBuilder, float paramFloat1, float paramFloat2, float paramFloat3, float paramFloat4, float paramFloat5, float paramFloat6, float paramFloat7, float paramFloat8) {
super.collectState(paramStateBuilder, paramFloat1, paramFloat2, paramFloat3, paramFloat4, paramFloat5, paramFloat6, paramFloat7, paramFloat8);
DrawBorder drawBorder = this.mDrawBorder;
if (drawBorder != null) {
this.mDrawBorder = (DrawBorder)drawBorder.updateBoundsAndFreeze(paramFloat1, paramFloat2, paramFloat3, paramFloat4, paramFloat5, paramFloat6, paramFloat7, paramFloat8);
paramStateBuilder.addDrawCommand(this.mDrawBorder);
}
}
final boolean doesDraw() {
return (this.mDrawBorder != null || super.doesDraw());
}
final void handleUpdateProperties(ReactStylesDiffMap paramReactStylesDiffMap) {
boolean bool = this.mRemoveClippedSubviews;
boolean bool1 = true;
if (bool || (paramReactStylesDiffMap.hasKey("removeClippedSubviews") && paramReactStylesDiffMap.getBoolean("removeClippedSubviews", false))) {
bool = true;
} else {
bool = false;
}
this.mRemoveClippedSubviews = bool;
if (this.mRemoveClippedSubviews) {
bool = bool1;
if (!this.mHorizontal)
if (paramReactStylesDiffMap.hasKey("horizontal") && paramReactStylesDiffMap.getBoolean("horizontal", false)) {
bool = bool1;
} else {
bool = false;
}
this.mHorizontal = bool;
}
super.handleUpdateProperties(paramReactStylesDiffMap);
}
public final void setBackgroundColor(int paramInt) {
getMutableBorder().setBackgroundColor(paramInt);
}
@ReactPropGroup(customType = "Color", defaultDouble = NaND, names = {"borderColor", "borderLeftColor", "borderRightColor", "borderTopColor", "borderBottomColor"})
public final void setBorderColor(int paramInt, double paramDouble) {
paramInt = SPACING_TYPES[paramInt];
if (Double.isNaN(paramDouble)) {
getMutableBorder().resetBorderColor(paramInt);
return;
}
getMutableBorder().setBorderColor(paramInt, (int)paramDouble);
}
@ReactProp(name = "borderRadius")
public final void setBorderRadius(float paramFloat) {
this.mClipRadius = paramFloat;
if (this.mClipToBounds && paramFloat > 0.5F)
forceMountToView();
getMutableBorder().setBorderRadius(PixelUtil.toPixelFromDIP(paramFloat));
}
@ReactProp(name = "borderStyle")
public final void setBorderStyle(String paramString) {
getMutableBorder().setBorderStyle(paramString);
}
public final void setBorderWidths(int paramInt, float paramFloat) {
super.setBorderWidths(paramInt, paramFloat);
paramInt = SPACING_TYPES[paramInt];
getMutableBorder().setBorderWidth(paramInt, PixelUtil.toPixelFromDIP(paramFloat));
}
@ReactProp(name = "hitSlop")
public final void setHitSlop(ReadableMap paramReadableMap) {
if (paramReadableMap == null) {
this.mHitSlop = null;
return;
}
this.mHitSlop = new Rect((int)PixelUtil.toPixelFromDIP(paramReadableMap.getDouble("left")), (int)PixelUtil.toPixelFromDIP(paramReadableMap.getDouble("top")), (int)PixelUtil.toPixelFromDIP(paramReadableMap.getDouble("right")), (int)PixelUtil.toPixelFromDIP(paramReadableMap.getDouble("bottom")));
}
@ReactProp(name = "nativeBackgroundAndroid")
public final void setHotspot(ReadableMap paramReadableMap) {
if (paramReadableMap != null)
forceMountToView();
}
@ReactProp(name = "pointerEvents")
public final void setPointerEvents(String paramString) {
forceMountToView();
}
final void updateNodeRegion(float paramFloat1, float paramFloat2, float paramFloat3, float paramFloat4, boolean paramBoolean) {
if (!getNodeRegion().matches(paramFloat1, paramFloat2, paramFloat3, paramFloat4, paramBoolean)) {
NodeRegion nodeRegion;
Rect rect = this.mHitSlop;
if (rect == null) {
nodeRegion = new NodeRegion(paramFloat1, paramFloat2, paramFloat3, paramFloat4, getReactTag(), paramBoolean);
} else {
nodeRegion = new HitSlopNodeRegion((Rect)nodeRegion, paramFloat1, paramFloat2, paramFloat3, paramFloat4, getReactTag(), paramBoolean);
}
setNodeRegion(nodeRegion);
}
}
}
/* Location: C:\Users\august\Desktop\tik\df_rn_kit\classes.jar.jar!\com\facebook\react\flat\RCTView.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.ace.easyteacher.DataBase;
import org.xutils.db.annotation.Column;
import org.xutils.db.annotation.Table;
@Table(name = "exam")
public class Exam extends BaseBean {
@Column(name = "type_id")
private int type_id;
@Column(name = "time")
private String time;
@Column(name = "name")
private String name;
public int getType_id() {
return type_id;
}
public void setType_id(int type_id) {
this.type_id = type_id;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
package com.simpson.kisen.idol.model.vo;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Idol {
//git test
private int idolNo;
private int agencyNo;
private String idolName;
private int fanCnt;
private IdolImg idolImg;
private List<IdolMv> idolMv;
}
|
package com.duanxr.yith.easy;
/**
* @author 段然 2021/3/8
*/
public class MinimumMovesToEqualArrayElements {
/**
* Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.
*
* In one move, you can increment n - 1 elements of the array by 1.
*
*
*
* Example 1:
*
* Input: nums = [1,2,3]
* Output: 3
* Explanation: Only three moves are needed (remember each move increments two elements):
* [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
* Example 2:
*
* Input: nums = [1,1,1]
* Output: 0
*
*
* Constraints:
*
* n == nums.length
* 1 <= nums.length <= 104
* -109 <= nums[i] <= 109
*
* 给定一个长度为 n 的 非空 整数数组,每次操作将会使 n - 1 个元素增加 1。找出让数组所有元素相等的最小操作次数。
*
*
*
* 示例:
*
* 输入:
* [1,2,3]
* 输出:
* 3
* 解释:
* 只需要3次操作(注意每次操作会增加两个元素的值):
* [1,2,3] => [2,3,3] => [3,4,3] => [4,4,4]
*
*/
class Solution {
public int minMoves(int[] nums) {
int sum = 0;
int min = Integer.MAX_VALUE;
for (int n : nums) {
sum += n;
min = Math.min(min, n);
}
sum -= min * nums.length;
return sum;
}
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.os.Bundle;
import com.tencent.mm.model.as;
import com.tencent.mm.plugin.report.service.h;
import com.tencent.mm.plugin.setting.a.i;
import com.tencent.mm.plugin.setting.a.k;
import com.tencent.mm.sdk.platformtools.ad;
import com.tencent.mm.sdk.platformtools.w;
import com.tencent.mm.ui.base.preference.CheckBoxPreference;
import com.tencent.mm.ui.base.preference.MMPreference;
import com.tencent.mm.ui.base.preference.Preference;
import com.tencent.mm.ui.base.preference.f;
import java.sql.Time;
import java.text.DateFormat;
public class SettingsActiveTimeUI extends MMPreference {
private boolean bGv = false;
private f eOE;
private Preference gYX;
private Preference gYY;
private int mRD;
private int mRE;
private int mRF;
private int mRG;
private boolean mRH = false;
private final OnTimeSetListener mRI = new 2(this);
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setMMTitle(i.settings_active_time);
this.eOE = this.tCL;
initView();
}
protected final void initView() {
this.eOE.removeAll();
this.eOE.addPreferencesFromResource(k.settings_pref_active_time);
this.gYY = this.eOE.ZZ("settings_active_begin_time");
this.mRD = com.tencent.mm.k.f.Ar();
this.mRE = com.tencent.mm.k.f.At();
this.gYY.setSummary(f(this, this.mRD, this.mRE));
this.gYX = this.eOE.ZZ("settings_active_end_time");
this.mRF = com.tencent.mm.k.f.Aq();
this.mRG = com.tencent.mm.k.f.As();
this.gYX.setSummary(f(this, this.mRF, this.mRG));
this.bGv = !com.tencent.mm.k.f.Ap();
((CheckBoxPreference) this.eOE.ZZ("settings_active_silence_time")).qpJ = this.bGv;
if (this.bGv) {
this.gYY.setEnabled(true);
this.gYX.setEnabled(true);
} else {
this.gYY.setEnabled(false);
this.gYX.setEnabled(false);
}
if (!this.bGv) {
this.eOE.c(this.gYY);
this.eOE.c(this.gYX);
}
this.eOE.bw("settings_active_time_full", true);
this.eOE.notifyDataSetChanged();
setBackBtn(new 1(this));
}
public final int Ys() {
return k.settings_pref_active_time;
}
public final boolean a(f fVar, Preference preference) {
if (preference.mKey.equals("settings_active_begin_time")) {
this.mRH = true;
showDialog(1);
return true;
} else if (preference.mKey.equals("settings_active_end_time")) {
this.mRH = false;
showDialog(1);
return true;
} else if (!preference.mKey.equals("settings_active_silence_time")) {
return false;
} else {
boolean z;
CheckBoxPreference checkBoxPreference = (CheckBoxPreference) this.eOE.ZZ("settings_active_silence_time");
if (checkBoxPreference.isChecked()) {
z = false;
} else {
z = true;
}
com.tencent.mm.k.f.bm(z);
h hVar = h.mEJ;
Object[] objArr = new Object[2];
objArr[0] = Integer.valueOf(0);
objArr[1] = Integer.valueOf(checkBoxPreference.isChecked() ? 1 : 2);
hVar.h(11351, objArr);
initView();
return true;
}
}
protected Dialog onCreateDialog(int i) {
switch (i) {
case 1:
if (this.mRH) {
return new TimePickerDialog(this.mController.tml, this.mRI, this.mRD, this.mRE, false);
}
return new TimePickerDialog(this.mController.tml, this.mRI, this.mRF, this.mRG, false);
default:
return null;
}
}
protected void onPrepareDialog(int i, Dialog dialog) {
switch (i) {
case 1:
if (this.mRH) {
((TimePickerDialog) dialog).updateTime(this.mRD, this.mRE);
return;
} else {
((TimePickerDialog) dialog).updateTime(this.mRF, this.mRG);
return;
}
default:
return;
}
}
private static String f(Context context, int i, int i2) {
String e = w.e(context.getSharedPreferences(ad.chY(), 0));
String chP = w.chP();
if (!e.equalsIgnoreCase("zh_CN") && (!e.equalsIgnoreCase("language_default") || !"zh_CN".equalsIgnoreCase(chP))) {
return DateFormat.getTimeInstance(3, w.Wl(e)).format(new Time(i, i2, 0));
}
int i3;
if (i > 12) {
i3 = i - 12;
} else {
i3 = i;
}
return com.tencent.mm.pluginsdk.f.h.p(context, (((long) i) * 3600000) + (((long) i2) * 60000)) + String.format("%02d:%02d", new Object[]{Integer.valueOf(i3), Integer.valueOf(i2)});
}
protected void onDestroy() {
super.onDestroy();
as.ha(2);
}
}
|
/**
* Copyright 2010 Tobias Sarnowski
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.eveonline.api.character;
import com.eveonline.api.ApiListResult;
import com.eveonline.api.ApiResult;
import java.util.Date;
/**
* @author Tobias Sarnowski
*/
public interface Notifications<N extends Notifications.Notification> extends ApiListResult<N> {
interface Notification extends ApiResult {
/**
* @return the notification's ID
*/
long getId();
/**
* @return the typeID
*/
long getTypeId();
/**
* @return the sender's ID
*/
long getSenderId();
/**
* @return the date when the notification was sent
*/
Date getSentDate();
/**
* @return if the notification is read
*/
boolean isRead();
}
}
|
package Project7Conditional;
public enum Day {
MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATERDAY,SUNDAY
}
|
package com.sdbarletta.salesforce.metadata;
import com.sdbarletta.salesforce.util.Base64;
import com.sdbarletta.salesforce.metadata.MetadataWebService;
public class Test {
public static void main(String[] args) {
MetadataLoginUtil util = new MetadataLoginUtil();
try {
MetadataWebService ws = new MetadataWebService();
System.out.println(ws.ping());
MetadataLoginUtil.MyConnectorConfig config = util.loginToSalesforce("ecm_metadata_api_user@exponentpartners.com", "ecm2013!", MetadataLoginUtil.TEST_LOGIN_ENDPOINT);
System.out.println("Login succeeded.");
String content = "<apex:page>Hello World</apex:page>";
MetadataResult r = ws.createVisualforcePage(config.sessionId, config.serviceEndpoint, "AAA2", "AAA 2", 26.0, Base64.encodeBytes(content.getBytes()));
if(r.success) {
System.out.println("Page successfully created.");
util.logout();
System.out.println("Logout succeeded.");
} else {
System.err.println(r.operationName+" failed. "+r.errorMessage[0]);
}
} catch(Exception e) {
System.err.println(e.getMessage());
}
}
}
|
package com.example.audiotrack;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import android.app.Service;
import android.content.Intent;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioTrack;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
public class MainService extends Service{
private byte[] recvBuf = new byte[1024];
public static final String SERVER_NAME = "0.0.0.0";
public static final int SERVERPORT = 2007;
SocketAddress socketAddr = new InetSocketAddress(SERVERPORT);
Boolean KeepGoing = false;
final int SAMPLE_RATE = 32768;
int minSize = AudioTrack.getMinBufferSize(SAMPLE_RATE,
AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_8BIT);
AudioTrack audioTrack =new AudioTrack(AudioManager.STREAM_MUSIC,
SAMPLE_RATE, AudioFormat.CHANNEL_CONFIGURATION_MONO,
AudioFormat.ENCODING_PCM_8BIT, minSize, AudioTrack.MODE_STREAM);;
@Override
public void onCreate() {
Client c = new Client();
new Thread(c).start();
audioTrack.play();
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
if(intent.getBooleanExtra("keepgoing", true)) {
Client c = new Client();
new Thread(c).start();
audioTrack.play();
KeepGoing = true;
} else {
audioTrack.stop();
KeepGoing = false;
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
audioTrack.stop();
audioTrack.release();
super.onDestroy();
}
class Client implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(KeepGoing)
UDPsendRecv();
} catch (Exception e) {
Log.e("UDP", "C: Error", e);
}
}
public void UDPsendRecv() throws Exception {
DatagramSocket socket = null;
try {
if (socket == null) {
socket = new DatagramSocket(SERVERPORT);
socket.setBroadcast(true);
socket.setReuseAddress(true);
}
DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
socket.receive(packet);
audioTrack.write(recvBuf, 0, recvBuf.length);
Log.d("UDP", "C: Received: " + recvBuf);
socket.close();
} catch (Exception e) {
socket.close();
throw e;
}
}
}
}
|
package FramesComponets;
import java.util.Date;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JSpinner;
public class DatePanel extends JPanel {
private JComboBox dayBox;
private JComboBox monthBox;
private JComboBox yearBox;
/**
* Create the panel.
*/
public DatePanel(String label) {
setLayout(new MigLayout("", "[33.00,grow][40.00,grow][78.00,grow][61.00,grow]", "[]"));
dayBox = new JComboBox();
add(dayBox, "cell 1 0,growx");
monthBox = new JComboBox();
add(monthBox, "cell 2 0,growx");
yearBox = new JComboBox();
add(yearBox, "cell 3 0,growx");
JLabel lblOd = new JLabel(label);
add(lblOd, "cell 0 0");
//dane do boxów danych
for(int i=1;i<32;i++)
{
dayBox.addItem(i);
}
monthBox.addItem("styczeń");
monthBox.addItem("luty");
monthBox.addItem("marzec");
monthBox.addItem("kwiecień");
monthBox.addItem("maj");
monthBox.addItem("czerwiec");
monthBox.addItem("lipiec");
monthBox.addItem("sierpień");
monthBox.addItem("wrzesień");
monthBox.addItem("październik");
monthBox.addItem("listopad");
monthBox.addItem("grudzień");
for(int i=1990;i<2021;i++)
{
yearBox.addItem(i);
}
}
public JComboBox getDayBox() {
return dayBox;
}
public JComboBox getMonthBox() {
return monthBox;
}
public JComboBox getYearBox() {
return yearBox;
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.vasu.Crud.Model;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.RowMapper;
/**
*
* @author Vasu Rajput
*/
public class UserWrapper implements RowMapper<User> {
private static final Logger logger = LoggerFactory.getLogger("UserWrapper.class");
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException {
try {
logger.info("rowNumber = " + rowNum);
User user = new User();
user.setEmailId(rs.getString("EmailId"));
user.setId(rs.getLong("Id"));
user.setPassword(rs.getString("Password"));
user.setRole(rs.getInt("Role"));
return user;
} catch (Exception e) {
logger.error("Error", e);
}
return null;
}
}
|
package websearch.indexing;
import writers.PostingWriter;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import mergeUtils.IndexReader;
import mergeUtils.WrapperIndexEntry;
import dataStructures.BlockInfo;
import dataStructures.Lexicon;
/**
* Main class for merging intermediate index
*
*/
public class IndexMerger {
private String inputDirectory, outputDirectory;
private Lexicon inputLexicon, outputLexicon;
private Map<Integer, IndexReader> readerMap;
public IndexMerger(String inputDirectory, String outputDirectory, Lexicon lexicon) {
this.inputDirectory = inputDirectory;
this.outputDirectory = outputDirectory;
this.inputLexicon = lexicon;
this.outputLexicon = new Lexicon();
File folder = new File(inputDirectory);
String[] filenames = folder.list();
readerMap = new HashMap<Integer, IndexReader>(filenames.length);
// Load readers for all the intermidiate index files.
for(String temp: filenames){
try{
readerMap.put(Integer.valueOf(temp),new IndexReader(lexicon, Integer.valueOf(temp), inputDirectory, false)) ;
//System.out.println(temp);
}catch(NumberFormatException e){} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Done Loading the readers.");
}
// k-way merge implementation for merging indexes.
public boolean merge() throws FileNotFoundException, IOException {
int fileNumber = 1;
File folder = new File(outputDirectory, "FinalIndex");
folder.mkdir();
outputDirectory = folder.getAbsolutePath();
File outputFile = new File(outputDirectory,String.valueOf(fileNumber));
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(outputFile));
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File(outputDirectory+"Lexicon")));
int currentFileOffset = 0;
List<Integer> docVector = new ArrayList<Integer>();
List<Integer> freqVector = new ArrayList<Integer>();
for (Integer termID : inputLexicon.keySet()) {
//System.out.println("Now Merging for term :"+termID);
List<BlockInfo> list = inputLexicon.get(termID);
PriorityQueue<WrapperIndexEntry> pQueue = new PriorityQueue<WrapperIndexEntry>(
list.size(), new Comparator<WrapperIndexEntry>() {
@Override
public int compare(WrapperIndexEntry o1, WrapperIndexEntry o2) {
if(o1.getDocID(o1.getCurrentPosition())==o2.getDocID(o2.getCurrentPosition()))
return 0;
return( ( (o1.getDocID(o1.getCurrentPosition())-o2.getDocID(o2.getCurrentPosition())) )>0)?1:-1;
}
});
int docVectorSize = 0;
for(BlockInfo blockInfo:list){
WrapperIndexEntry indexEntry = new WrapperIndexEntry(readerMap.get(blockInfo.getFileNumber()).openList(termID));
pQueue.add(indexEntry);
docVectorSize += indexEntry.getDocVectorSize();
}
while(!pQueue.isEmpty()){
WrapperIndexEntry indexEntry = pQueue.poll();
docVector.add(WrapperIndexEntry.currentDoc(indexEntry));
freqVector.add(WrapperIndexEntry.currentFrequency(indexEntry));
if(WrapperIndexEntry.incrIndex(indexEntry, docVectorSize))
pQueue.add(indexEntry);
}
currentFileOffset = PostingWriter.writePosting(termID, docVector, freqVector, stream, currentFileOffset, fileNumber, outputLexicon);
}
// Serializing lexicon to disk
objectOutputStream.writeObject(outputLexicon);
objectOutputStream.close();
stream.close();
System.gc();
return true;
}
public static void main(String[] args) throws FileNotFoundException,
IOException, ClassNotFoundException {
ObjectInputStream inputStream = new ObjectInputStream(
new BufferedInputStream(new FileInputStream(
"/Users/Walliee/Documents/workspace/Indexing/temp50/Lexicon")));
Lexicon lexicon = (Lexicon) inputStream
.readObject();
inputStream.close();
System.out.println("Done Loading the Lexicon");
IndexMerger indexMerger = new IndexMerger("/Users/Walliee/Documents/workspace/Indexing/temp50/index",
"/Users/Walliee/Documents/workspace/Indexing/temp50", lexicon);
Long start = System.currentTimeMillis();
indexMerger.merge();
Long stop = System.currentTimeMillis();
System.out.println("Merging done in "+(stop-start)+" milliSeconds");
}
}
|
package com.kingcar.rent.pro.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.kingcar.rent.pro.R;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by cwj on 16/10/21.
*/
public class CWJLoadingView extends FrameLayout {
@Bind(R.id.loading_view2)
ImageView loadingView;
@Bind(R.id.kit_loading)
FrameLayout kitLoading;
public CWJLoadingView(Context context) {
super(context);
if (isInEditMode()) {
return;
}
init();
}
public CWJLoadingView(Context context, AttributeSet attrs) {
super(context, attrs);
if (isInEditMode()) {
return;
}
init();
}
public CWJLoadingView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
if (isInEditMode()) {
return;
}
init();
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CWJLoadingView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
if (isInEditMode()) {
return;
}
init();
}
private void init() {
inflate(getContext(), R.layout.dialog_loading_view, this);
ButterKnife.bind(this, this);
// setBackgroundResource(R.color.default_page_bgcolor);
setClickable(true);
// Glide.with(getContext()).load(R.mipmap.loading).diskCacheStrategy(DiskCacheStrategy.SOURCE).into(loadingView);
}
public void release() {
if (loadingView != null) {
Glide.clear(loadingView);
loadingView.setImageDrawable(null);
}
}
@Override
protected void onDetachedFromWindow() {
ButterKnife.unbind(this);
super.onDetachedFromWindow();
}
public void hideLoadingNoAnmation() {
setVisibility(View.GONE);
release();
}
public void hideLoading(boolean isRelease) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
this.animate().setDuration(200).alpha(0).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
setVisibility(View.GONE);
}
});
} else {
setVisibility(View.GONE);
}
if (isRelease) {
release();
}
}
public void hideLoading(boolean isRelease, long delayMillis) {
if(getVisibility()==GONE)
return;
postDelayed(new Runnable() {
@Override
public void run() {
try {
hideLoading(isRelease);
} catch (Exception e) {
}
}
}, delayMillis);
}
}
|
/**
Copyright [plter] [xtiqin]
http://plter.sinaapp.com
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This is a part of PlterAndroidLib on
http://plter.sinaapp.com/?cat=14
*/
package com.plter.lib.android.java.controls;
import com.plter.lib.android.java.anim.AnimationStyle;
import android.content.Context;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ListViewController extends ViewController {
public ListViewController(Context context, int resid) {
super(context, resid);
setAnimationStyle(AnimationStyle.PUSH_RIGHT_TO_LEFT);
listView=(ListView) findViewByID(android.R.id.list);
}
public ListViewController(Context context){
super(new ListView(context));
setAnimationStyle(AnimationStyle.PUSH_RIGHT_TO_LEFT);
listView=(ListView) getView();
}
public void setOnItemClickListener(OnItemClickListener l){
getListView().setOnItemClickListener(l);
}
public ListView getListView(){
return listView;
}
public void setAdapter(ArrayAdapter<?> adapter){
getListView().setAdapter(adapter);
}
private ListView listView=null;
}
|
package com.greenglobal.eoffice.domain.application.congvandi.commands;
import com.greenglobal.eoffice.domain.application.congvandi.commands.create.CreateCongVanDiCmd;
import com.greenglobal.eoffice.domain.application.congvandi.commands.update.HuyDuyetCongVanDiCmd;
import com.greenglobal.eoffice.domain.application.congvandi.commands.update.KyDuyetCongVanDiCmd;
import com.greenglobal.eoffice.domain.application.congvandi.commands.update.TrinhCongVanDiCmd;
public interface CongVanDiCmdHandler {
void handle(CreateCongVanDiCmd cmd);
void handle(TrinhCongVanDiCmd cmd);
void handle(KyDuyetCongVanDiCmd cmd);
void handle(HuyDuyetCongVanDiCmd cmd);
} |
package com.dzz.user.api.service;
import com.dzz.user.api.config.UserServiceFeignConfiguration;
import com.dzz.user.api.domain.bo.UserDetailBo;
import com.dzz.user.api.domain.bo.UserListBo;
import com.dzz.user.api.domain.dto.UserListParam;
import com.dzz.user.api.domain.dto.UserSaveParam;
import com.dzz.util.page.PageUtil;
import com.dzz.util.response.ResponsePack;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
/**
* 用户接口
*
* @author dzz
* @version 1.0.0
* @since 2019年08月09 09:52
*/
@FeignClient(name = "USER-SERVICE", configuration = UserServiceFeignConfiguration.class)
public interface UserService {
String BASE_URL = "/api/user";
String SAVE_USER_URL = BASE_URL + "/saveUser";
String LIST_USER = BASE_URL + "/listUser";
String DETAIL_USER = BASE_URL + "/detailUser";
/**
* 保存用户
* @param saveParam 参数
* @return 保存结果
*/
@PostMapping(SAVE_USER_URL)
ResponsePack<Boolean> saveUser(@RequestBody UserSaveParam saveParam);
/**
* 用户列表查询
* @param listParam 参数
* @return 结果
*/
@PostMapping(LIST_USER)
ResponsePack<PageUtil<UserListBo>> listUser(@RequestBody UserListParam listParam);
/**
* 用户详情查询
* @param userName 用户名
* @return 结果
*/
@GetMapping(DETAIL_USER)
ResponsePack<UserDetailBo> detailUser(@RequestParam("userName") String userName);
}
|
package com.miao.boot.bpm.editor.controller.param;
import org.hibernate.validator.constraints.NotEmpty;
import lombok.Data;
@Data
public class ModelCreateParam {
private @NotEmpty String processKey;
private @NotEmpty String tenantId;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.controller;
import com.model.dao.TipoVeiculoDao;
import com.model.entity.TipoVeiculo;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* @author renanmarceluchoa
*/
@ManagedBean
@RequestScoped
public class TipoVeiculoController {
@EJB
private TipoVeiculoDao dao;
private TipoVeiculo tipo;
private List<TipoVeiculo> tipos;
public TipoVeiculoController() {
this.tipo = new TipoVeiculo();
}
@PostConstruct
public void listar() {
this.tipos = dao.listar();
}
/**
* @return the tipo
*/
public TipoVeiculo getTipo() {
return tipo;
}
/**
* @param tipo the tipo to set
*/
public void setTipo(TipoVeiculo tipo) {
this.tipo = tipo;
}
/**
* @return the tipos
*/
public List<TipoVeiculo> getTipos() {
return tipos;
}
/**
* @param tipos the tipos to set
*/
public void setTipos(List<TipoVeiculo> tipos) {
this.tipos = tipos;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi.contact;
import android.content.Intent;
import android.provider.ContactsContract.Contacts;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.h.c;
class a$1 implements c {
final /* synthetic */ String bAj;
final /* synthetic */ MMActivity fPh;
final /* synthetic */ a fPi;
a$1(a aVar, MMActivity mMActivity, String str) {
this.fPi = aVar;
this.fPh = mMActivity;
this.bAj = str;
}
public final void ju(int i) {
Intent intent;
switch (i) {
case 0:
intent = new Intent("android.intent.action.INSERT", Contacts.CONTENT_URI);
a.a(this.fPi, intent, this.fPh, this.bAj);
this.fPh.startActivity(intent);
this.fPh.startActivityForResult(intent, hashCode() & 65535);
return;
case 1:
intent = new Intent("android.intent.action.INSERT_OR_EDIT", Contacts.CONTENT_URI);
intent.setType("vnd.android.cursor.item/person");
a.a(this.fPi, intent, this.fPh, this.bAj);
this.fPh.startActivityForResult(intent, hashCode() & 65535);
return;
default:
return;
}
}
}
|
package com.yuecheng.yue.ui.fragment.impl;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.yuecheng.yue.R;
import com.yuecheng.yue.base.YUE_BaseLazyFragment;
import com.yuecheng.yue.http.pinyin.CharacterParser;
import com.yuecheng.yue.http.pinyin.PinyinComparator;
import com.yuecheng.yue.ui.activity.impl.YUE_UserDetailActivity;
import com.yuecheng.yue.ui.adapter.YUE_FridendListAdapter;
import com.yuecheng.yue.ui.bean.YUE_FriendsBean;
import com.yuecheng.yue.ui.fragment.YUE_IContactsFragment;
import com.yuecheng.yue.ui.presenter.YUE_ContactsFragmentPresenter;
import com.yuecheng.yue.util.CommonUtils;
import com.yuecheng.yue.widget.LoadDialog;
import com.yuecheng.yue.widget.SideBar;
import com.yuecheng.yue.widget.YUE_CircleImageView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 联系人页
* Created by yuecheng on 2017/11/6.
*/
public class YUE_ContactsFragment extends YUE_BaseLazyFragment implements YUE_IContactsFragment, View.OnClickListener {
private YUE_ContactsFragmentPresenter mPresenter;
private ListView mListView;
private TextView mNoFriends;
private View mHeadView;
private YUE_CircleImageView mSelectableRoundedImageView;
private TextView mUnreadTextView;
private TextView mNameTextView;
private YUE_FridendListAdapter mAdapter;
private LayoutInflater mLayoutInflater;
/**
* 中部展示的字母提示
*/
private TextView mDialogTextView;
private SideBar mSidBar;
private List<YUE_FriendsBean> mFriendList;
private List<YUE_FriendsBean> mFilteredFriendList;
/**
* 汉字转换成拼音的类
*/
private CharacterParser mCharacterParser;
private PinyinComparator mPinyinComparator;
@Override
protected void onCreateViewLazy(Bundle savedInstanceState) {
super.onCreateViewLazy(savedInstanceState);
mLayoutInflater = LayoutInflater.from(mActivity);
View view = mLayoutInflater.inflate(R.layout.fragment_contacts_layout, null);
setContentView(view);
initViews(view);
initData();
mPresenter.getDataUpdateContact();
}
private void initData() {
mPresenter = new YUE_ContactsFragmentPresenter(mActivity, this);
// 设置 展示在好友列表头部的个人信息,
mPresenter.updatePersonalUI();
mFriendList = new ArrayList<>();
mFilteredFriendList = new ArrayList<>();
YUE_FridendListAdapter adapter = new YUE_FridendListAdapter(mActivity, mFriendList);
mListView.setAdapter(adapter);
//实例化汉字转拼音类
mCharacterParser = CharacterParser.getInstance();
mPinyinComparator = PinyinComparator.getInstance();
}
private void initViews(View view) {
mListView = (ListView) view.findViewById(R.id.friendlistview);
mNoFriends = (TextView) view.findViewById(R.id.show_no_friend);
mDialogTextView = (TextView) view.findViewById(R.id.group_dialog);
mSidBar = (SideBar) view.findViewById(R.id.sidrbar);
mHeadView = mLayoutInflater.inflate(R.layout.item_contact_list_header, null);
mUnreadTextView = (TextView) mHeadView.findViewById(R.id.tv_unread);
RelativeLayout newFriendsLayout = (RelativeLayout) mHeadView.findViewById(R.id.re_newfriends);
RelativeLayout groupLayout = (RelativeLayout) mHeadView.findViewById(R.id.re_chatroom);
RelativeLayout publicServiceLayout = (RelativeLayout) mHeadView.findViewById(R.id.publicservice);
RelativeLayout selfLayout = (RelativeLayout) mHeadView.findViewById(R.id.contact_me_item);
mSelectableRoundedImageView = (YUE_CircleImageView) mHeadView.findViewById(R.id.contact_me_img);
mNameTextView = (TextView) mHeadView.findViewById(R.id.contact_me_name);
mListView.addHeaderView(mHeadView);
mNoFriends.setVisibility(View.VISIBLE);
newFriendsLayout.setOnClickListener(this);
groupLayout.setOnClickListener(this);
publicServiceLayout.setOnClickListener(this);
selfLayout.setOnClickListener(this);
//设置右侧触摸监听
mSidBar.setTextView(mDialogTextView);
mSidBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
@Override
public void onTouchingLetterChanged(String s) {
//该字母首次出现的位置
int position = mAdapter.getPositionForSection(s.charAt(0));
if (position != -1) {
mListView.setSelection(position+1);
}
}
});
}
@Override
public void loadFriendsList(List<YUE_FriendsBean> list) {
boolean isReloadList = false;
if (mFriendList != null && mFriendList.size() > 0) {
mFriendList.clear();
isReloadList = true;
}
mFriendList = list;
if (mFriendList != null && mFriendList.size() > 0) {
mPresenter.handleFriendDataForSort();
mNoFriends.setVisibility(View.GONE);
} else {
mNoFriends.setVisibility(View.VISIBLE);
}
// 根据a-z进行排序源数据
Collections.sort(mFriendList, mPinyinComparator);
if (isReloadList) {
mSidBar.setVisibility(View.VISIBLE);
mAdapter.updateListView(mFriendList);
} else {
mSidBar.setVisibility(View.VISIBLE);
mAdapter = new YUE_FridendListAdapter(mActivity, mFriendList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (mListView.getHeaderViewsCount() > 0) {
startFriendDetailsPage(mFriendList.get(i - 1).getPhonenum(),mFriendList
.get(i-1).getNickname());
} else {
// startFriendDetailsPage(mFilteredFriendList.get(position));
}
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
YUE_FriendsBean bean = mFriendList.get(position - 1);
// startFriendDetailsPage(bean);
return true;
}
});
}
}
private void startFriendDetailsPage(String userId,String nickName) {
Intent intent = new Intent(getActivity(), YUE_UserDetailActivity.class);
// intent.putExtra("type", CLICK_CONTACT_FRAGMENT_FRIEND);
intent.putExtra("userId", userId);
intent.putExtra("nickName", nickName);
startActivity(intent);
}
@Override
public void setpersonalUI(String mId, String mCacheName) {
mSelectableRoundedImageView.setImageDrawable(getResources().getDrawable(R.drawable.default_chatroom));
mNameTextView.setText(mCacheName);
}
@Override
public List<YUE_FriendsBean> getFriendList() {
return mFriendList;
}
@Override
public void dismissLoadingDialog() {
LoadDialog.dismiss(getActivity());
}
@Override
public void showLoadingDialog() {
LoadDialog.show(getActivity());
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.re_newfriends:
break;
case R.id.re_chatroom:
break;
case R.id.publicservice:
break;
case R.id.contact_me_item:
break;
}
}
}
|
package JZOffer;
/**
* @author: zdefys
* @date: 2020/7/3 19:06
* @version: v1.0
* @description: 在一个二维数组中(每个一维数组的长度相同),
* 每一行都按照从左到右递增的顺序排序,
* 每一列都按照从上到下递增的顺序排序。
* 请完成一个函数,输入这样的一个二维数组和一个整数,
* 判断数组中是否含有该整数。
*/
public class JZ1 {
// 在线笔试
public boolean find1(int target, int[][] array) {
for (int[] row : array) {
for (int value : row) {
if (value == target) {
return true;
}
}
}
return false;
}
// 面试
public boolean find2(int target, int[][] array) {
int row = 0;
int col = array[0].length-1;
while (true) {
if (col < 0 || row >= array.length) {
break;
}
if (target == array[row][col]) {
return true;
} else if (target > array[row][col]) {
row++;
continue;
} else if (target < array[row][col]) {
col--;
continue;
}
}
return false;
}
public static void main(String[] args) {
}
}
|
import java.util.HashMap;
import java.util.Map;
public class Library {
Map<String, Book> books;
Map<String, Boolean> reservations;
public Library()
{
books = new HashMap<String, Book>();
reservations = new HashMap<String, Boolean>();
}
public int getNumBooks()
{
return books.size();
}
public void addBook(Book book)
{
books.put(book.isbn, book);
}
public Book getBook(String isbn)
{
return books.get(isbn);
}
public Book getBookByAuthorTitle(String author, String title)
{
String isbn = LibraryUtils.generateIsbn(author, title);
return getBook(isbn);
}
public void removeBook(String isbn) throws Exception
{
if (books.get(isbn) != null)
books.remove(isbn);
else
throw new Exception("Buch mit angegebener ISBN existiert nicht");
}
public void setReserved(String isbn) throws Exception
{
if (books.get(isbn) != null)
{
reservations.put(isbn, true);
getBook(isbn).reserved = true;
}else
{
throw new Exception("Buch mit angegebener ISBN existiert nicht");
}
}
public void clearReservation(String isbn) throws Exception
{
if (books.get(isbn) != null)
{
getBook(isbn).reserved = false;
}else
throw new Exception("Buch mit angegebener ISBN existiert nicht");
}
public Boolean getReserationStatus(String isbn) throws Exception
{
if (books.get(isbn) != null)
{
Boolean status_reservation = reservations.get(isbn);
Boolean status_book = getBook(isbn).reserved;
if (status_reservation != status_book)
throw new Exception("error in reservation system");
else
return status_reservation;
}else
throw new Exception("Buch mit angegebener ISBN existiert nicht");
}
}
|
package cn.xyz.repository.mongo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.annotation.Resource;
import org.apache.commons.codec.digest.DigestUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import cn.xyz.commons.constants.KConstants;
import cn.xyz.commons.constants.KKeyConstant;
import cn.xyz.commons.ex.ServiceException;
import cn.xyz.commons.utils.AESUtil;
import cn.xyz.commons.utils.DateUtil;
import cn.xyz.commons.utils.Md5Util;
import cn.xyz.commons.utils.StringUtil;
import cn.xyz.commons.utils.ValueUtil;
import cn.xyz.mianshi.example.UserExample;
import cn.xyz.mianshi.example.UserQueryExample;
import cn.xyz.mianshi.utils.KSessionUtil;
import cn.xyz.mianshi.vo.Friends;
import cn.xyz.mianshi.vo.Msg;
import cn.xyz.mianshi.vo.Room;
import cn.xyz.mianshi.vo.Room.Member;
import cn.xyz.mianshi.vo.User;
import cn.xyz.mianshi.vo.User.UserSettings;
import cn.xyz.repository.UserRepository;
import cn.xyz.service.KXMPPServiceImpl;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
@Service
public class UserRepositoryImpl extends BaseRepositoryImpl<User, Integer> implements UserRepository {
public static UserRepositoryImpl getInstance() {
return new UserRepositoryImpl();
}
@Resource(name = "dsForTigase")
private Datastore dsForTigase;
@Resource(name = "dsForRoom")
protected Datastore dsForRoom;
@Override
public Map<String, Object> addUser(int userId, UserExample example) {
BasicDBObject jo = new BasicDBObject();
jo.put("_id", userId);// 索引
jo.put("userKey", DigestUtils.md5Hex(example.getPhone()));// 索引
jo.put("username", "");
jo.put("password", example.getPassword());
//新增 头像
jo.put("portrait", example.getPortrait());
jo.put("userType", ValueUtil.parse(example.getUserType()));
jo.put("lsId", example.getPhone());// 罗斯Id
jo.put("isRename", 0);// 是否修改过罗斯号,默认为0
jo.put("isCS", 0);// 是否绑定公众号
jo.put("telephone", example.getTelephone());// 索引
jo.put("phone", example.getPhone());// 索引
jo.put("areaCode", example.getAreaCode());// 索引
jo.put("name", ValueUtil.parse(example.getName()));// 索引
jo.put("nickname", ValueUtil.parse(example.getNickname()));// 索引
jo.put("description", ValueUtil.parse(example.getDescription()));
jo.put("birthday", ValueUtil.parse(example.getBirthday()));// 索引
jo.put("sex", ValueUtil.parse(example.getSex()));// 索引
jo.put("loc", new BasicDBObject("lng", example.getLongitude()).append("lat", example.getLatitude()));// 索引
jo.put("countryId", ValueUtil.parse(example.getCountryId()));
jo.put("provinceId", ValueUtil.parse(example.getProvinceId()));
jo.put("cityId", ValueUtil.parse(example.getCityId()));
jo.put("areaId", ValueUtil.parse(example.getAreaId()));
jo.put("balance", 0);
jo.put("totalRecharge", 0);
jo.put("level", 0);
jo.put("vip", 0);
jo.put("friendsCount", 0);
jo.put("fansCount", 0);
jo.put("attCount", 0);
jo.put("msgNum", 0);
jo.put("createTime", DateUtil.currentTimeSeconds());
jo.put("modifyTime", DateUtil.currentTimeSeconds());
jo.put("idcard", "");
jo.put("idcardUrl", "");
jo.put("isAuth", 0);
jo.put("status", 1);
jo.put("onlinestate", 1);
// 初始化登录日志
jo.put("loginLog", User.LoginLog.init(example, true));
// 初始化用户设置
jo.put("settings", User.UserSettings.getDefault());
// 1、新增用户
dsForRW.getDB().getCollection("user").save(jo);
try {
// 2、缓存用户认证数据到
Map<String, Object> data = saveAT(userId, jo.getString("userKey"));
data.put("userId", userId);
data.put("nickname", jo.getString("nickname"));
data.put("portrait", jo.getString("portrait"));
data.put("name", jo.getString("name"));
data.put("lsId", jo.getString("lsId"));
// 3、缓存用户数据
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
public void addUser(User user) {
dsForRW.save(user);
}
@Override
public void addUser(int userId, String password) {
BasicDBObject jo = new BasicDBObject();
jo.put("_id", userId);// 索引
jo.put("userKey", DigestUtils.md5Hex(userId + ""));// 索引
jo.put("username", String.valueOf(userId));
jo.put("password", DigestUtils.md5Hex(password));
jo.put("lsId", String.valueOf(userId));// 罗斯Id
jo.put("isRename", 0);// 是否修改过罗斯号,默认为0
jo.put("userType", ValueUtil.parse(1));
jo.put("companyId", ValueUtil.parse(0));
jo.put("telephone", "86" + String.valueOf(userId));// 索引
jo.put("areaCode", "86");// 索引
jo.put("name", String.valueOf(userId));// 索引
jo.put("nickname", String.valueOf(userId));// 索引
jo.put("description", String.valueOf(userId));
jo.put("birthday", ValueUtil.parse(userId));// 索引
jo.put("sex", ValueUtil.parse(userId));// 索引
jo.put("loc", new BasicDBObject("lng", 10.00).append("lat", 10.00));// 索引
jo.put("countryId", ValueUtil.parse(0));
jo.put("provinceId", ValueUtil.parse(0));
jo.put("cityId", ValueUtil.parse(400300));
jo.put("areaId", ValueUtil.parse(0));
jo.put("money", 0);
jo.put("moneyTotal", 0);
jo.put("level", 0);
jo.put("vip", 0);
jo.put("friendsCount", 0);
jo.put("fansCount", 0);
jo.put("attCount", 0);
jo.put("createTime", DateUtil.currentTimeSeconds());
jo.put("modifyTime", DateUtil.currentTimeSeconds());
jo.put("idcard", "");
jo.put("idcardUrl", "");
jo.put("isAuth", 0);
jo.put("status", 1);
jo.put("onlinestate", 1);
// 初始化登录日志
// jo.put("loginLog", User.LoginLog.init(example, true));
// 初始化用户设置
jo.put("settings", User.UserSettings.getDefault());
// 1、新增用户
dsForRW.getDB().getCollection("user").save(jo);
}
@Override
public List<User> findByTelephone(List<String> telephoneList) {
Query<User> query = dsForRW.createQuery(User.class).filter("telephone in", telephoneList);
return query.asList();
}
@Override
public Map<String, Object> getAT(int userId, String userKey) {
Jedis resource = jedisPool.getResource();
try {
String atKey = KKeyConstant.atKey(userKey);
String accessToken = resource.get(atKey);
// long expires_in = resource.ttl(atKey);
if (StringUtil.isEmpty(accessToken)) {
// return saveAT(userId, userKey);
} else {
// HashMap<String, Object> data = new HashMap<String, Object>();
//
// data.put("access_token", accessToken);
// data.put("expires_in", expires_in);
//
// return data;
String userIdKey = KKeyConstant.userIdKey(accessToken);
resource.del(userIdKey);
resource.del(atKey);
}
} finally {
jedisPool.returnResource(resource);
}
return saveAT(userId, userKey);
}
@Override
public long getCount(String telephone) {
return dsForRW.createQuery(User.class).field("telephone").equal(telephone).countAll();
}
@Override
public User.LoginLog getLogin(int userId) {
try {
return dsForRW.createQuery(User.class).field("_id").equal(userId).get().getLoginLog();
} catch (NullPointerException e) {
throw new ServiceException("帐号不存在");
}
}
@Override
public User.UserSettings getSettings(int userId) {
UserSettings settings = null;
User user = null;
user = dsForRW.createQuery(User.class).field("_id").equal(userId).get();
if (null == user)
return null;
settings = user.getSettings();
return null != settings ? settings : new UserSettings();
}
@Override
public User getUser(int userId) {
Query<User> query = dsForRW.createQuery(User.class).field("_id").equal(userId);
return query.get();
}
@Override
public User getUser(String telephone) {
Query<User> query = dsForRW.createQuery(User.class).field("telephone").equal(telephone);
return query.get();
}
@Override
public User getUser(String areaCode, String userKey, String password) {
Query<User> query = dsForRW.createQuery(User.class);
if (!StringUtil.isEmpty(userKey))
query.field("areaCode").equal(areaCode);
if (!StringUtil.isEmpty(userKey))
query.field("userKey").equal(userKey);
if (!StringUtil.isEmpty(password))
query.field("password").equal(password);
return query.get();
}
@Override
public User getUserv1(String userKey, String password) {
Query<User> query = dsForRW.createQuery(User.class);
if (!StringUtil.isEmpty(userKey))
query.field("userKey").equal(userKey);
if (!StringUtil.isEmpty(password))
query.field("password").equal(password);
return query.get();
}
@Override
public List<DBObject> queryUser(UserQueryExample example) {
List<DBObject> list = Lists.newArrayList();
// Query<User> query = mongoDs.find(User.class);
// Query<User> query =mongoDs.createQuery(User.class);
// query.filter("_id<", param.getUserId());
DBObject ref = new BasicDBObject();
if (null != example.getUserId())
ref.put("_id", new BasicDBObject("$lt", example.getUserId()));
if (!StringUtil.isEmpty(example.getNickname()))
ref.put("nickname", Pattern.compile(example.getNickname()));
if (null != example.getSex())
ref.put("sex", example.getSex());
if (null != example.getStartTime())
ref.put("birthday", new BasicDBObject("$gte", example.getStartTime()));
if (null != example.getEndTime())
ref.put("birthday", new BasicDBObject("$lte", example.getEndTime()));
DBObject fields = new BasicDBObject();
fields.put("userKey", 0);
fields.put("password", 0);
fields.put("money", 0);
fields.put("moneyTotal", 0);
fields.put("status", 0);
DBCursor cursor = dsForRW.getDB().getCollection("user").find(ref, fields).sort(new BasicDBObject("_id", -1))
.limit(example.getPageSize());
while (cursor.hasNext()) {
DBObject obj = cursor.next();
obj.put("userId", obj.get("_id"));
obj.removeField("_id");
list.add(obj);
}
return list;
}
@Override
public List<DBObject> findUser(int pageIndex, int pageSize) {
List<DBObject> list = Lists.newArrayList();
DBObject fields = new BasicDBObject();
fields.put("userKey", 0);
fields.put("password", 0);
fields.put("money", 0);
fields.put("moneyTotal", 0);
fields.put("status", 0);
DBCursor cursor = dsForRW.getDB().getCollection("user").find(null, fields).sort(new BasicDBObject("_id", -1))
.skip(pageIndex * pageSize).limit(pageSize);
while (cursor.hasNext()) {
DBObject obj = cursor.next();
obj.put("userId", obj.get("_id"));
obj.removeField("_id");
list.add(obj);
}
return list;
}
@Override
public Map<String, Object> saveAT(int userId, String userKey) {
Jedis resource = jedisPool.getResource();
Pipeline pipeline = resource.pipelined();
try {
String accessToken = StringUtil.randomUUID();
// 密钥key
String secretKey = String.format(KSessionUtil.GET_SECRET_KEY, userId);
// 生成信息加密密钥
String secret = userId + StringUtil.randomUUID().substring(0, 8);
int expire = KConstants.Expire.DAY7 * 5;
String atKey = KKeyConstant.atKey(userKey);
pipeline.set(atKey, accessToken);
pipeline.expire(atKey, expire);
pipeline.set(secretKey, secret);
pipeline.expire(secretKey, expire);
String userIdKey = KKeyConstant.userIdKey(accessToken);
pipeline.set(userIdKey, String.valueOf(userId));
pipeline.expire(userIdKey, expire);
pipeline.syncAndReturnAll();
//获取加密密钥的秘钥
String k=Md5Util.md5Hex(accessToken+AESUtil.key).substring(0, 16);
// 对密钥加密
String mdSecret = AESUtil.encrypt(secret,k);
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("access_token", accessToken);
data.put("AESSecret", mdSecret);
data.put("expires_in", expire);
// data.put("userId", userId);
// data.put("nickname", user.getNickname());
return data;
} finally {
jedisPool.returnResource(resource);
}
}
public Map<String, Object> saveATWeb(int userId, String userKey) {
Jedis resource = jedisPool.getResource();
Pipeline pipeline = resource.pipelined();
try {
String accessToken = StringUtil.randomUUID();
int expire = KConstants.Expire.DAY7 * 5;
String atKey = KKeyConstant.atKey(userKey);
pipeline.set(atKey, accessToken);
pipeline.expire(atKey, expire);
String userIdKey = KKeyConstant.userIdKey(accessToken);
pipeline.set(userIdKey, String.valueOf(userId));
pipeline.expire(userIdKey, expire);
pipeline.syncAndReturnAll();
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("access_token", accessToken);
data.put("expires_in", expire);
return data;
} finally {
jedisPool.returnResource(resource);
}
}
@Override
public void updateLogin(int userId, String serial) {
DBObject value = new BasicDBObject();
// value.put("isFirstLogin", 0);
// value.put("loginTime", DateUtil.currentTimeSeconds());
// value.put("apiVersion", example.getApiVersion());
// value.put("osVersion", example.getOsVersion());
// value.put("model", example.getModel());
value.put("serial", serial);
// value.put("latitude", example.getLatitude());
// value.put("longitude", example.getLongitude());
// value.put("location", example.getLocation());
// value.put("address", example.getAddress());
DBObject q = new BasicDBObject("_id", userId);
DBObject o = new BasicDBObject("$set", new BasicDBObject("loginLog", value));
dsForRW.getDB().getCollection("user").update(q, o);
}
@Override
public void updateLogin(int userId, UserExample example) {
BasicDBObject loc = new BasicDBObject(2);
loc.put("loc.lng", example.getLongitude());
loc.put("loc.lat", example.getLatitude());
DBObject values = new BasicDBObject();
values.put("loginLog.isFirstLogin", 0);
values.put("loginLog.loginTime", DateUtil.currentTimeSeconds());
values.put("loginLog.apiVersion", example.getApiVersion());
values.put("loginLog.osVersion", example.getOsVersion());
values.put("loginLog.model", example.getModel());
values.put("loginLog.serial", example.getSerial());
values.put("loginLog.latitude", example.getLatitude());
values.put("loginLog.longitude", example.getLongitude());
values.put("loginLog.location", example.getLocation());
values.put("loginLog.address", example.getAddress());
values.put("loc.lng", example.getLongitude());
values.put("loc.lat", example.getLatitude());
values.put("appId", example.getAppId());
DBObject q = new BasicDBObject("_id", userId);
DBObject o = new BasicDBObject("$set", values);
// ("loginLog",
// loginLog)).append
dsForRW.getCollection(User.class).update(q, o);
}
@Override
public User updateUser(int userId, UserExample example) {
Query<User> q = dsForRW.createQuery(User.class).field("_id").equal(userId);
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
boolean updateName = false;
boolean updatePortrait = false;
if (null != example.getUserType())
ops.set("userType", example.getUserType());
if (!StringUtil.isEmpty(example.getNickname())) {
ops.set("nickname", example.getNickname());
updateName = true;
}
if (!StringUtil.isEmpty(example.getTelephone())) {
ops.set("userKey", DigestUtils.md5Hex(example.getPhone()));
ops.set("telephone", example.getTelephone());
}
if (!StringUtil.isEmpty(example.getPhone()))
ops.set("phone", example.getPhone());
if (!StringUtil.isEmpty(example.getPassword()) && example.getPassword().length() < 32) {
System.out.println("修改密码");
ops.set("password", example.getPassword());
// 修改tigase中的用户信息
KXMPPServiceImpl.getInstance().updateToTig(userId, example.getPassword());
}
if (!StringUtil.isEmpty(example.getDescription()))
ops.set("description", example.getDescription());
if (null != example.getBirthday())
ops.set("birthday", example.getBirthday());
if (null != example.getSex())
ops.set("sex", example.getSex());
if (null != example.getCountryId())
ops.set("countryId", example.getCountryId());
if (null != example.getProvinceId())
ops.set("provinceId", example.getProvinceId());
if (null != example.getCityId())
ops.set("cityId", example.getCityId());
if (null != example.getAreaId())
ops.set("areaId", example.getAreaId());
//修改头像相关
if (null != example.getPortrait()){//头像信息不为空
ops.set("portrait", example.getPortrait());
updatePortrait=true;
}
if (null != example.getName())
ops.set("name", example.getName());
if (null != example.getIdcard())
ops.set("idcard", example.getIdcard());
if (null != example.getIdcardUrl())
ops.set("idcardUrl", example.getIdcardUrl());
ops.set("loc.lng", example.getLongitude());
ops.set("loc.lat", example.getLatitude());
User user = dsForRW.findAndModify(q, ops);
// 删除redis中的用户
KSessionUtil.deleteUserByUserId(userId);
// 修改用户昵称时 同步该用户创建的群主昵称
if (updateName) {
new Thread(new Runnable() {
@Override
public void run() {
BasicDBObject quserId = new BasicDBObject().append("userId", userId);
DBObject values = new BasicDBObject();
values.put("nickname", example.getNickname());
DBObject q = new BasicDBObject("$set", values);
BasicDBObject qtoUserId = new BasicDBObject().append("toUserId", userId);
DBObject values1 = new BasicDBObject();
values1.put("toNickname", example.getNickname());
DBObject o = new BasicDBObject("$set", values1);
// 修改群组中的创建人名称//修改nickname
dsForRoom.getCollection(Room.class).update(quserId, q, false, true);
dsForRoom.getCollection(Member.class).update(quserId, q, false, true);
// 修改好友名称
dsForRW.getCollection(Friends.class).update(qtoUserId, o, false, true);
// 修改朋友圈中的用户名称
DBObject p = new BasicDBObject("$set", values);
dsForRW.getCollection(Msg.class).update(quserId, p, false, true);
}
}).start();
}
//如果修改了头像,则同步,好友列表,房间信息中的头像信息
if (updatePortrait) {
new Thread(new Runnable() {
@Override
public void run() {
BasicDBObject quserId = new BasicDBObject().append("userId", userId);
DBObject values = new BasicDBObject();
values.put("portrait", example.getPortrait());
DBObject q = new BasicDBObject("$set", values);
BasicDBObject qtoUserId = new BasicDBObject().append("toUserId", userId);
DBObject values1 = new BasicDBObject();
values1.put("toPortrait", example.getPortrait());
DBObject o = new BasicDBObject("$set", values1);
// 修改群组中的创建人名称//修改nickname
dsForRoom.getCollection(Room.class).update(quserId, q, false, true);
dsForRoom.getCollection(Member.class).update(quserId, q, false, true);
// 修改好友名称
dsForRW.getCollection(Friends.class).update(qtoUserId, o, false, true);
// 修改朋友圈中的用户名称
DBObject p = new BasicDBObject("$set", values);
dsForRW.getCollection(Msg.class).update(quserId, p, false, true);
}
}).start();
}
return user;
}
@Override
public User updateSettings(int userId, User.UserSettings userSettings) {
Query<User> q = dsForRW.createQuery(User.class).field("_id").equal(userId);
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
if (null != new Integer(userSettings.getAllowAtt()))
ops.set("settings.allowAtt", userSettings.getAllowAtt());
if (null != new Integer(userSettings.getAllowGreet()))
ops.set("settings.allowGreet", userSettings.getAllowGreet());
if (null != new Integer(userSettings.getAllowAtt()))
ops.set("settings.friendsVerify", userSettings.getFriendsVerify());
// 是否开启客服模式
if (null != new Integer(userSettings.getAllowAtt())) {
ops.set("settings.openService", userSettings.getOpenService());
}
User user = getUser(userId);
user.setSettings(userSettings);
KSessionUtil.saveUserByUserId(userId, user); // 数据缓存到redis
return dsForRW.findAndModify(q, ops);
}
@Override
public User updateUser(User user) {
Query<User> q = dsForRW.createQuery(User.class).field("_id").equal(user.getUserId());
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
if (!StringUtil.isNullOrEmpty(user.getTelephone())) {
ops.set("userKey", DigestUtils.md5Hex(user.getTelephone()));
ops.set("telephone", user.getTelephone());
}
if (!StringUtil.isNullOrEmpty(user.getUsername()))
ops.set("username", user.getUsername());
/*
* if (!StringUtil.isNullOrEmpty(user.getPassword()))
* ops.set("password", user.getPassword());
*/
if (null != user.getUserType())
ops.set("userType", user.getUserType());
if (!StringUtil.isNullOrEmpty(user.getName()))
ops.set("name", user.getName());
if (!StringUtil.isNullOrEmpty(user.getNickname()))
ops.set("nickname", user.getNickname());
if (!StringUtil.isNullOrEmpty(user.getDescription()))
ops.set("description", user.getDescription());
if (!StringUtil.isNullOrEmpty(user.getPortrait()))
ops.set("portrait", user.getPortrait());
if (null != user.getBirthday())
ops.set("birthday", user.getBirthday());
if (null != user.getSex())
ops.set("sex", user.getSex());
if (null != user.getCountryId())
ops.set("countryId", user.getCountryId());
if (null != user.getProvinceId())
ops.set("provinceId", user.getProvinceId());
if (null != user.getCityId())
ops.set("cityId", user.getCityId());
if (null != user.getAreaId())
ops.set("areaId", user.getAreaId());
if (null != user.getLevel())
ops.set("level", user.getLevel());
if (null != user.getVip())
ops.set("vip", user.getVip());
if (null != user.getActive()) {
ops.set("active", user.getActive());
}
// if (null != user.getFriendsCount())
// ops.set("friendsCount", user.getFriendsCount());
// if (null != user.getFansCount())
// ops.set("fansCount", user.getFansCount());
// if (null != user.getAttCount())
// ops.set("attCount", user.getAttCount());
// ops.set("createTime", null);
ops.set("modifyTime", DateUtil.currentTimeSeconds());
if (!StringUtil.isNullOrEmpty(user.getIdcard()))
ops.set("idcard", user.getIdcard());
if (!StringUtil.isNullOrEmpty(user.getIdcardUrl()))
ops.set("idcardUrl", user.getIdcardUrl());
if (null != user.getIsAuth())
ops.set("isAuth", user.getIsAuth());
if (null != user.getStatus())
ops.set("status", user.getStatus());
return dsForRW.findAndModify(q, ops);
}
@Override
public void updatePassword(String telephone, String password) {
Query<User> q = dsForRW.createQuery(User.class).field("telephone").equal(telephone);
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
ops.set("password", password);
dsForRW.findAndModify(q, ops);
}
@Override
public void updatePassowrd(int userId, String password) {
Query<User> q = dsForRW.createQuery(User.class).field("_id").equal(userId);
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
ops.set("password", password);
dsForRW.findAndModify(q, ops);
}
@Override
public User getByPhone(String phone) {
Query<User> query = dsForRW.createQuery(User.class);
query.field("telephone").equal(phone);
User user = query.get();
return user;
}
@Override
public User getByLs(String lsId) {
Query<User> query = dsForRW.createQuery(User.class);
query.field("lsId").equal(lsId);
User user = query.get();
return user;
}
@Override
public void changePhone(int userId, String phone, String areaCode) {
Query<User> q = dsForRW.createQuery(User.class).field("userId").equal(userId);
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
ops.set("areaCode", areaCode);
ops.set("phone", phone);
ops.set("userKey", DigestUtils.md5Hex(phone));
ops.set("telephone", areaCode+phone);
dsForRW.findAndModify(q, ops);
// 更新redis
User user = get(userId);
KSessionUtil.saveUserByUserId(userId, user);
}
@Override
public void rename(int userId, String lsId) {
Query<User> q = dsForRW.createQuery(User.class).field("userId").equal(userId);
UpdateOperations<User> ops = dsForRW.createUpdateOperations(User.class);
ops.set("lsId", lsId);
ops.set("isRename", 1);
dsForRW.findAndModify(q, ops);
// 更新redis
User user = get(userId);
KSessionUtil.saveUserByUserId(userId, user);
}
public Map<String, Object> getAtWeb(int userId, String userKey) {
Jedis resource = jedisPool.getResource();
try {
String atKey = KKeyConstant.atKey(userKey+"web");
String accessToken = resource.get(atKey);
if (StringUtil.isEmpty(accessToken)) {
//如果为空则生成
return saveATWeb(userId, userKey+"web");
} else {
//如果存在则返回
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("access_token", accessToken);
return data;
}
} finally {
jedisPool.returnResource(resource);
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.przemo.pdfmanipulate;
/**
*
* @author Przemo
*/
public class Pole {
private int pozycjaX, pozycjaY;
private String oznaczenie, wartosc;
private boolean rightAlign;
public boolean isRightAlign() {
return rightAlign;
}
public void setRightAlign(boolean rightAlign) {
this.rightAlign = rightAlign;
}
public int getPozycjaX() {
return pozycjaX;
}
public void setPozycjaX(int pozycjaX) {
this.pozycjaX = pozycjaX;
}
public int getPozycjaY() {
return pozycjaY;
}
public void setPozycjaY(int pozycjaY) {
this.pozycjaY = pozycjaY;
}
public String getOznaczenie() {
return oznaczenie;
}
public void setOznaczenie(String oznaczenie) {
this.oznaczenie = oznaczenie;
}
public String getWartosc() {
return wartosc;
}
public void setWartosc(String wartosc) {
this.wartosc = wartosc;
}
public Pole(){};
public Pole(int x, int y, String oznaczenie, String wartosc, boolean rightAlign){
this.pozycjaX=x;
this.pozycjaY=y;
this.oznaczenie=oznaczenie;
this.wartosc=wartosc;
this.rightAlign=rightAlign;
}
}
|
package model;
/**
* Created by 11437 on 2017/12/20.
*/
public class History {
private int postid;
private String POI_id;
private String token;
private String userid;
public History(String POI_id,String token,String userid,int postid){
this.POI_id=POI_id;
this.token=token;
this.userid=userid;
this.postid=postid;
}
public void setPOI_id(String POI_id){
this.POI_id=POI_id;
}
public void setToken(String token){
this.token=token;
}
public void setUserid(String userid){
this.userid=userid;
}
public void setPostid(int postid){this.postid=postid;}
public String getPOI_id(){return this.POI_id;}
public String getToken(){return this.token;}
public String getUserid(){return this.userid;}
public int getPostid(){return this.postid;}
}
|
package com.tencent.mm.plugin.luckymoney.ui;
import android.media.SoundPool;
import android.media.SoundPool.OnLoadCompleteListener;
import com.tencent.mm.plugin.luckymoney.b.f;
class LuckyMoneyDetailUI$6 implements OnLoadCompleteListener {
final /* synthetic */ f kUy;
final /* synthetic */ LuckyMoneyDetailUI kVo;
LuckyMoneyDetailUI$6(LuckyMoneyDetailUI luckyMoneyDetailUI, f fVar) {
this.kVo = luckyMoneyDetailUI;
this.kUy = fVar;
}
public final void onLoadComplete(SoundPool soundPool, int i, int i2) {
if (i2 != 0) {
return;
}
if (i == LuckyMoneyDetailUI.s(this.kVo)[0]) {
soundPool.play(i, 1.0f, 1.0f, 0, 0, 1.0f);
} else if (i == LuckyMoneyDetailUI.s(this.kVo)[1] && this.kUy.cfh >= 19000) {
soundPool.play(i, 1.0f, 1.0f, 0, 0, 1.0f);
}
}
}
|
package client;
import server.ChatServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;
public class ClientConnection implements Runnable{
private final Socket socket;
private final Logger logger;
private final ChatServer server;
public ClientConnection(Socket socket, Logger logger, ChatServer server) {
this.socket = socket;
this.logger = logger;
this.server = server;
}
@Override
public void run() {
try(
final InputStream inputStream = socket.getInputStream();
final OutputStream outputStream = socket.getOutputStream()
) {
Scanner input = new Scanner(inputStream);
PrintWriter output = new PrintWriter(outputStream, true);
while (input.hasNext()) {
String content = input.nextLine();
List<ClientConnection> other = server.getClients();
sendToAll(content, other);
}
logger.info("Client closed connection: " + socket.getInetAddress());
} catch (IOException e) {
logger.warning("Can't get connection with client!");
e.printStackTrace();
}
}
public OutputStream getOutput() throws IOException {
return socket.getOutputStream();
}
public void sendToAll(String message, List<ClientConnection> clients){
clients.forEach(client -> {
try{
PrintWriter writer = new PrintWriter(client.getOutput(), true);
if (client != this ) {
writer.println(message);
}
} catch (IOException e) {
logger.warning("Cant send message to other client!");
}
});
}
}
|
package com.szcinda.express;
import com.szcinda.express.dto.*;
import com.szcinda.express.params.QueryUserParams;
import com.szcinda.express.persistence.User;
public interface UserService {
PageResult<User> query(QueryUserParams params);
UserIdentity getUserIdentity(String account, String password);
void createUser(UserCreateDto createDto);
String generatePwd(String password);
void updateUser(UserUpdateDto updateDto);
void updatePassword(UpdatePasswordDto updatePasswordDto);
void delete(String userId);
String getToken(String userId, String password);
User findUserById(String userId);
}
|
package Interface;
import Modelo.Personal;
import Modelo.Usuario;
import java.util.List;
public interface Interfaz {
public List listar();
public boolean add(Personal per);
public boolean eliminar(int id);
public int validar(Usuario per);
}
|
package com.packers.movers.server;
import com.packers.movers.commons.config.contracts.ServerConfiguration;
import com.packers.movers.commons.utils.LogUtils;
import com.packers.movers.configuration.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.logging.Level;
public class Main {
private static final Logger LOG = LoggerFactory.getLogger(Main.class);
private final ApplicationServer server;
public Main() throws Exception {
ServerConfiguration serverConfiguration = Configuration.getServerConfiguration();
this.server = new ApplicationServer(serverConfiguration);
}
public static void main(String[] args) throws Exception {
try {
LOG.trace("Application booting");
LogUtils.initializeLogger(Level.INFO);
final Main main = new Main();
main.server.start();
main.server.waitForCompletion();
} catch (RuntimeException exception) {
LOG.error("Runtime exception", exception);
System.exit(1);
}
}
} |
package com.sporsimdi.model.entity;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import com.sporsimdi.model.base.ExtendedModel;
@Table
@Entity
public class Il extends ExtendedModel {
private static final long serialVersionUID = 8986161490957095179L;
private String adi;
@OneToMany(fetch = FetchType.EAGER, mappedBy = "il")
private Set<Ilce> ilceListesi = new HashSet<Ilce>();
public String getAdi() {
return adi;
}
public void setAdi(String adi) {
this.adi = adi;
}
public Set<Ilce> getIlceListesi() {
return ilceListesi;
}
public void setIlceListesi(Set<Ilce> ilceListesi) {
this.ilceListesi = ilceListesi;
}
public Ilce[] getListeliIlceListesi()
{
return ilceListesi.toArray(new Ilce[ilceListesi.size()]);
}
}
|
package com.app.rabia.myapplication.datasource.server;
import com.app.rabia.myapplication.main.MyApplication;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import static com.app.rabia.myapplication.utils.Constants.BASE_URL;
public class ServerClient {
//reftrofit2 client with cache implemented
public static Retrofit getClient() {
Retrofit retrofit = null;
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder().cache(MyApplication.getInstance().getCacheDirectory());
OkHttpClient okHttpClient= okHttpClientBuilder.build();
if (retrofit == null) retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build();
return retrofit;
}
}
|
package com.sysh.entity.helpmea;
import java.io.Serializable;
import java.math.BigDecimal;
public class ReconstDangerDD implements Serializable {
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.ID
*
* @mbg.generated
*/
private Long id;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.DISTRICT_NAME
*
* @mbg.generated
*/
private String districtName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.TOWN_NAME
*
* @mbg.generated
*/
private String townName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.VILLAGE_NAME
*
* @mbg.generated
*/
private String villageName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.POVERTY_NAME
*
* @mbg.generated
*/
private String povertyName;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.ID_NUMBER
*
* @mbg.generated
*/
private String idNumber;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.IS_START
*
* @mbg.generated
*/
private String isStart;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.START_TIME
*
* @mbg.generated
*/
private String startTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.IS_COMPLETE
*
* @mbg.generated
*/
private String isComplete;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.COMPLETE_TIME
*
* @mbg.generated
*/
private String completeTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.IS_ACCEPTANCE
*
* @mbg.generated
*/
private String isAcceptance;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.ACCEPT_TIME
*
* @mbg.generated
*/
private String acceptTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.IS_CHECKIN
*
* @mbg.generated
*/
private String isCheckin;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.CHECKIN_TIME
*
* @mbg.generated
*/
private String checkinTime;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.HOUSE_AREA
*
* @mbg.generated
*/
private String houseArea;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.HOUSING_SUBSIDY
*
* @mbg.generated
*/
private BigDecimal housingSubsidy;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.PERSON_RAISE
*
* @mbg.generated
*/
private BigDecimal personRaise;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.START_BEFORE
*
* @mbg.generated
*/
private String startBefore;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.CONSTRUCTION
*
* @mbg.generated
*/
private String construction;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.AFTER_COMPLETETION
*
* @mbg.generated
*/
private String afterCompletetion;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.AFTER_CHECKIN
*
* @mbg.generated
*/
private String afterCheckin;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.REMARKS
*
* @mbg.generated
*/
private String remarks;
/**
*
* This field was generated by MyBatis Generator.
* This field corresponds to the database column TBL_RECONST_DANGER.ZONE_YEAR
*
* @mbg.generated
*/
private Long zoneYear;
/**
* This field was generated by MyBatis Generator.
* This field corresponds to the database table TBL_RECONST_DANGER
*
* @mbg.generated
*/
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.ID
*
* @return the value of TBL_RECONST_DANGER.ID
*
* @mbg.generated
*/
public Long getId() {
return id;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.ID
*
* @param id the value for TBL_RECONST_DANGER.ID
*
* @mbg.generated
*/
public void setId(Long id) {
this.id = id;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.DISTRICT_NAME
*
* @return the value of TBL_RECONST_DANGER.DISTRICT_NAME
*
* @mbg.generated
*/
public String getDistrictName() {
return districtName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.DISTRICT_NAME
*
* @param districtName the value for TBL_RECONST_DANGER.DISTRICT_NAME
*
* @mbg.generated
*/
public void setDistrictName(String districtName) {
this.districtName = districtName == null ? null : districtName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.TOWN_NAME
*
* @return the value of TBL_RECONST_DANGER.TOWN_NAME
*
* @mbg.generated
*/
public String getTownName() {
return townName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.TOWN_NAME
*
* @param townName the value for TBL_RECONST_DANGER.TOWN_NAME
*
* @mbg.generated
*/
public void setTownName(String townName) {
this.townName = townName == null ? null : townName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.VILLAGE_NAME
*
* @return the value of TBL_RECONST_DANGER.VILLAGE_NAME
*
* @mbg.generated
*/
public String getVillageName() {
return villageName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.VILLAGE_NAME
*
* @param villageName the value for TBL_RECONST_DANGER.VILLAGE_NAME
*
* @mbg.generated
*/
public void setVillageName(String villageName) {
this.villageName = villageName == null ? null : villageName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.POVERTY_NAME
*
* @return the value of TBL_RECONST_DANGER.POVERTY_NAME
*
* @mbg.generated
*/
public String getPovertyName() {
return povertyName;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.POVERTY_NAME
*
* @param povertyName the value for TBL_RECONST_DANGER.POVERTY_NAME
*
* @mbg.generated
*/
public void setPovertyName(String povertyName) {
this.povertyName = povertyName == null ? null : povertyName.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.ID_NUMBER
*
* @return the value of TBL_RECONST_DANGER.ID_NUMBER
*
* @mbg.generated
*/
public String getIdNumber() {
return idNumber;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.ID_NUMBER
*
* @param idNumber the value for TBL_RECONST_DANGER.ID_NUMBER
*
* @mbg.generated
*/
public void setIdNumber(String idNumber) {
this.idNumber = idNumber == null ? null : idNumber.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.IS_START
*
* @return the value of TBL_RECONST_DANGER.IS_START
*
* @mbg.generated
*/
public String getIsStart() {
return isStart;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.IS_START
*
* @param isStart the value for TBL_RECONST_DANGER.IS_START
*
* @mbg.generated
*/
public void setIsStart(String isStart) {
this.isStart = isStart == null ? null : isStart.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.START_TIME
*
* @return the value of TBL_RECONST_DANGER.START_TIME
*
* @mbg.generated
*/
public String getStartTime() {
return startTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.START_TIME
*
* @param startTime the value for TBL_RECONST_DANGER.START_TIME
*
* @mbg.generated
*/
public void setStartTime(String startTime) {
this.startTime = startTime == null ? null : startTime.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.IS_COMPLETE
*
* @return the value of TBL_RECONST_DANGER.IS_COMPLETE
*
* @mbg.generated
*/
public String getIsComplete() {
return isComplete;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.IS_COMPLETE
*
* @param isComplete the value for TBL_RECONST_DANGER.IS_COMPLETE
*
* @mbg.generated
*/
public void setIsComplete(String isComplete) {
this.isComplete = isComplete == null ? null : isComplete.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.COMPLETE_TIME
*
* @return the value of TBL_RECONST_DANGER.COMPLETE_TIME
*
* @mbg.generated
*/
public String getCompleteTime() {
return completeTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.COMPLETE_TIME
*
* @param completeTime the value for TBL_RECONST_DANGER.COMPLETE_TIME
*
* @mbg.generated
*/
public void setCompleteTime(String completeTime) {
this.completeTime = completeTime == null ? null : completeTime.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.IS_ACCEPTANCE
*
* @return the value of TBL_RECONST_DANGER.IS_ACCEPTANCE
*
* @mbg.generated
*/
public String getIsAcceptance() {
return isAcceptance;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.IS_ACCEPTANCE
*
* @param isAcceptance the value for TBL_RECONST_DANGER.IS_ACCEPTANCE
*
* @mbg.generated
*/
public void setIsAcceptance(String isAcceptance) {
this.isAcceptance = isAcceptance == null ? null : isAcceptance.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.ACCEPT_TIME
*
* @return the value of TBL_RECONST_DANGER.ACCEPT_TIME
*
* @mbg.generated
*/
public String getAcceptTime() {
return acceptTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.ACCEPT_TIME
*
* @param acceptTime the value for TBL_RECONST_DANGER.ACCEPT_TIME
*
* @mbg.generated
*/
public void setAcceptTime(String acceptTime) {
this.acceptTime = acceptTime == null ? null : acceptTime.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.IS_CHECKIN
*
* @return the value of TBL_RECONST_DANGER.IS_CHECKIN
*
* @mbg.generated
*/
public String getIsCheckin() {
return isCheckin;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.IS_CHECKIN
*
* @param isCheckin the value for TBL_RECONST_DANGER.IS_CHECKIN
*
* @mbg.generated
*/
public void setIsCheckin(String isCheckin) {
this.isCheckin = isCheckin == null ? null : isCheckin.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.CHECKIN_TIME
*
* @return the value of TBL_RECONST_DANGER.CHECKIN_TIME
*
* @mbg.generated
*/
public String getCheckinTime() {
return checkinTime;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.CHECKIN_TIME
*
* @param checkinTime the value for TBL_RECONST_DANGER.CHECKIN_TIME
*
* @mbg.generated
*/
public void setCheckinTime(String checkinTime) {
this.checkinTime = checkinTime == null ? null : checkinTime.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.HOUSE_AREA
*
* @return the value of TBL_RECONST_DANGER.HOUSE_AREA
*
* @mbg.generated
*/
public String getHouseArea() {
return houseArea;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.HOUSE_AREA
*
* @param houseArea the value for TBL_RECONST_DANGER.HOUSE_AREA
*
* @mbg.generated
*/
public void setHouseArea(String houseArea) {
this.houseArea = houseArea == null ? null : houseArea.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.HOUSING_SUBSIDY
*
* @return the value of TBL_RECONST_DANGER.HOUSING_SUBSIDY
*
* @mbg.generated
*/
public BigDecimal getHousingSubsidy() {
return housingSubsidy;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.HOUSING_SUBSIDY
*
* @param housingSubsidy the value for TBL_RECONST_DANGER.HOUSING_SUBSIDY
*
* @mbg.generated
*/
public void setHousingSubsidy(BigDecimal housingSubsidy) {
this.housingSubsidy = housingSubsidy;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.PERSON_RAISE
*
* @return the value of TBL_RECONST_DANGER.PERSON_RAISE
*
* @mbg.generated
*/
public BigDecimal getPersonRaise() {
return personRaise;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.PERSON_RAISE
*
* @param personRaise the value for TBL_RECONST_DANGER.PERSON_RAISE
*
* @mbg.generated
*/
public void setPersonRaise(BigDecimal personRaise) {
this.personRaise = personRaise;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.START_BEFORE
*
* @return the value of TBL_RECONST_DANGER.START_BEFORE
*
* @mbg.generated
*/
public String getStartBefore() {
return startBefore;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.START_BEFORE
*
* @param startBefore the value for TBL_RECONST_DANGER.START_BEFORE
*
* @mbg.generated
*/
public void setStartBefore(String startBefore) {
this.startBefore = startBefore == null ? null : startBefore.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.CONSTRUCTION
*
* @return the value of TBL_RECONST_DANGER.CONSTRUCTION
*
* @mbg.generated
*/
public String getConstruction() {
return construction;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.CONSTRUCTION
*
* @param construction the value for TBL_RECONST_DANGER.CONSTRUCTION
*
* @mbg.generated
*/
public void setConstruction(String construction) {
this.construction = construction == null ? null : construction.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.AFTER_COMPLETETION
*
* @return the value of TBL_RECONST_DANGER.AFTER_COMPLETETION
*
* @mbg.generated
*/
public String getAfterCompletetion() {
return afterCompletetion;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.AFTER_COMPLETETION
*
* @param afterCompletetion the value for TBL_RECONST_DANGER.AFTER_COMPLETETION
*
* @mbg.generated
*/
public void setAfterCompletetion(String afterCompletetion) {
this.afterCompletetion = afterCompletetion == null ? null : afterCompletetion.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.AFTER_CHECKIN
*
* @return the value of TBL_RECONST_DANGER.AFTER_CHECKIN
*
* @mbg.generated
*/
public String getAfterCheckin() {
return afterCheckin;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.AFTER_CHECKIN
*
* @param afterCheckin the value for TBL_RECONST_DANGER.AFTER_CHECKIN
*
* @mbg.generated
*/
public void setAfterCheckin(String afterCheckin) {
this.afterCheckin = afterCheckin == null ? null : afterCheckin.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.REMARKS
*
* @return the value of TBL_RECONST_DANGER.REMARKS
*
* @mbg.generated
*/
public String getRemarks() {
return remarks;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.REMARKS
*
* @param remarks the value for TBL_RECONST_DANGER.REMARKS
*
* @mbg.generated
*/
public void setRemarks(String remarks) {
this.remarks = remarks == null ? null : remarks.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column TBL_RECONST_DANGER.ZONE_YEAR
*
* @return the value of TBL_RECONST_DANGER.ZONE_YEAR
*
* @mbg.generated
*/
public Long getZoneYear() {
return zoneYear;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column TBL_RECONST_DANGER.ZONE_YEAR
*
* @param zoneYear the value for TBL_RECONST_DANGER.ZONE_YEAR
*
* @mbg.generated
*/
public void setZoneYear(Long zoneYear) {
this.zoneYear = zoneYear;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table TBL_RECONST_DANGER
*
* @mbg.generated
*/
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
ReconstDangerDD other = (ReconstDangerDD) that;
return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
&& (this.getDistrictName() == null ? other.getDistrictName() == null : this.getDistrictName().equals(other.getDistrictName()))
&& (this.getTownName() == null ? other.getTownName() == null : this.getTownName().equals(other.getTownName()))
&& (this.getVillageName() == null ? other.getVillageName() == null : this.getVillageName().equals(other.getVillageName()))
&& (this.getPovertyName() == null ? other.getPovertyName() == null : this.getPovertyName().equals(other.getPovertyName()))
&& (this.getIdNumber() == null ? other.getIdNumber() == null : this.getIdNumber().equals(other.getIdNumber()))
&& (this.getIsStart() == null ? other.getIsStart() == null : this.getIsStart().equals(other.getIsStart()))
&& (this.getStartTime() == null ? other.getStartTime() == null : this.getStartTime().equals(other.getStartTime()))
&& (this.getIsComplete() == null ? other.getIsComplete() == null : this.getIsComplete().equals(other.getIsComplete()))
&& (this.getCompleteTime() == null ? other.getCompleteTime() == null : this.getCompleteTime().equals(other.getCompleteTime()))
&& (this.getIsAcceptance() == null ? other.getIsAcceptance() == null : this.getIsAcceptance().equals(other.getIsAcceptance()))
&& (this.getAcceptTime() == null ? other.getAcceptTime() == null : this.getAcceptTime().equals(other.getAcceptTime()))
&& (this.getIsCheckin() == null ? other.getIsCheckin() == null : this.getIsCheckin().equals(other.getIsCheckin()))
&& (this.getCheckinTime() == null ? other.getCheckinTime() == null : this.getCheckinTime().equals(other.getCheckinTime()))
&& (this.getHouseArea() == null ? other.getHouseArea() == null : this.getHouseArea().equals(other.getHouseArea()))
&& (this.getHousingSubsidy() == null ? other.getHousingSubsidy() == null : this.getHousingSubsidy().equals(other.getHousingSubsidy()))
&& (this.getPersonRaise() == null ? other.getPersonRaise() == null : this.getPersonRaise().equals(other.getPersonRaise()))
&& (this.getStartBefore() == null ? other.getStartBefore() == null : this.getStartBefore().equals(other.getStartBefore()))
&& (this.getConstruction() == null ? other.getConstruction() == null : this.getConstruction().equals(other.getConstruction()))
&& (this.getAfterCompletetion() == null ? other.getAfterCompletetion() == null : this.getAfterCompletetion().equals(other.getAfterCompletetion()))
&& (this.getAfterCheckin() == null ? other.getAfterCheckin() == null : this.getAfterCheckin().equals(other.getAfterCheckin()))
&& (this.getRemarks() == null ? other.getRemarks() == null : this.getRemarks().equals(other.getRemarks()))
&& (this.getZoneYear() == null ? other.getZoneYear() == null : this.getZoneYear().equals(other.getZoneYear()));
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table TBL_RECONST_DANGER
*
* @mbg.generated
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result = prime * result + ((getDistrictName() == null) ? 0 : getDistrictName().hashCode());
result = prime * result + ((getTownName() == null) ? 0 : getTownName().hashCode());
result = prime * result + ((getVillageName() == null) ? 0 : getVillageName().hashCode());
result = prime * result + ((getPovertyName() == null) ? 0 : getPovertyName().hashCode());
result = prime * result + ((getIdNumber() == null) ? 0 : getIdNumber().hashCode());
result = prime * result + ((getIsStart() == null) ? 0 : getIsStart().hashCode());
result = prime * result + ((getStartTime() == null) ? 0 : getStartTime().hashCode());
result = prime * result + ((getIsComplete() == null) ? 0 : getIsComplete().hashCode());
result = prime * result + ((getCompleteTime() == null) ? 0 : getCompleteTime().hashCode());
result = prime * result + ((getIsAcceptance() == null) ? 0 : getIsAcceptance().hashCode());
result = prime * result + ((getAcceptTime() == null) ? 0 : getAcceptTime().hashCode());
result = prime * result + ((getIsCheckin() == null) ? 0 : getIsCheckin().hashCode());
result = prime * result + ((getCheckinTime() == null) ? 0 : getCheckinTime().hashCode());
result = prime * result + ((getHouseArea() == null) ? 0 : getHouseArea().hashCode());
result = prime * result + ((getHousingSubsidy() == null) ? 0 : getHousingSubsidy().hashCode());
result = prime * result + ((getPersonRaise() == null) ? 0 : getPersonRaise().hashCode());
result = prime * result + ((getStartBefore() == null) ? 0 : getStartBefore().hashCode());
result = prime * result + ((getConstruction() == null) ? 0 : getConstruction().hashCode());
result = prime * result + ((getAfterCompletetion() == null) ? 0 : getAfterCompletetion().hashCode());
result = prime * result + ((getAfterCheckin() == null) ? 0 : getAfterCheckin().hashCode());
result = prime * result + ((getRemarks() == null) ? 0 : getRemarks().hashCode());
result = prime * result + ((getZoneYear() == null) ? 0 : getZoneYear().hashCode());
return result;
}
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table TBL_RECONST_DANGER
*
* @mbg.generated
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", districtName=").append(districtName);
sb.append(", townName=").append(townName);
sb.append(", villageName=").append(villageName);
sb.append(", povertyName=").append(povertyName);
sb.append(", idNumber=").append(idNumber);
sb.append(", isStart=").append(isStart);
sb.append(", startTime=").append(startTime);
sb.append(", isComplete=").append(isComplete);
sb.append(", completeTime=").append(completeTime);
sb.append(", isAcceptance=").append(isAcceptance);
sb.append(", acceptTime=").append(acceptTime);
sb.append(", isCheckin=").append(isCheckin);
sb.append(", checkinTime=").append(checkinTime);
sb.append(", houseArea=").append(houseArea);
sb.append(", housingSubsidy=").append(housingSubsidy);
sb.append(", personRaise=").append(personRaise);
sb.append(", startBefore=").append(startBefore);
sb.append(", construction=").append(construction);
sb.append(", afterCompletetion=").append(afterCompletetion);
sb.append(", afterCheckin=").append(afterCheckin);
sb.append(", remarks=").append(remarks);
sb.append(", zoneYear=").append(zoneYear);
sb.append("]");
return sb.toString();
}
} |
package app;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.*;
@WebServlet("/")
public class AppServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("voos", voos());
request.getRequestDispatcher("/WEB-INF/views/app/index.jsp").forward(request, response);
}
private List<Voo> voos() {
try {
final String URL = "https://opensky-network.org/api/states/all";
Map o = ClientBuilder
.newClient()
.target(URL)
.queryParam("lamin", "45.8389")
.queryParam("lomin", "5.9962")
.queryParam("lamax", "47.8229")
.queryParam("lomax", "10.5226")
.request()
.accept(MediaType.APPLICATION_JSON)
.get(Map.class)
;
return processa(o);
} catch (RuntimeException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private List<Voo> processa(final Map map) {
final List<Voo> voos = new ArrayList<Voo>();
final List lines = (List)map.get("states");
for(int i = 0, l = lines.size(); i < l; i++) {
final List line = (List)lines.get(i);
voos.add(new Voo(line));
}
return voos;
}
} |
package university;
import java.security.InvalidParameterException;
public class Voto implements Comparable<Voto> {
//@ private invariant (voto >= 18) && (voto <= 30);
private /*@ spec_public non_null @*/ Integer voto;
//@ ensures voto == getVoto();
public Voto(int voto) {
if (!(voto >= 18) && (voto <= 30))
throw new InvalidParameterException("Voto non valido. Range di voti = [18, 30]");
this.voto = voto;
}
//@ ensures \result == this.voto;
public /*@ pure @*/ int getVoto() {
return voto;
}
//@ ensures (voto == ((Voto)obj).voto) <== (\result == true);
@Override
public /*@ pure @*/ boolean equals(Object obj) {
if (!(obj instanceof Voto)) return false;
return voto.equals(((Voto)obj).voto);
}
/*@ ensures (voto <= other.voto) <==> (\result <= 0)
@ && (voto >= other.voto) <==> (\result >= 0);
@*/
@Override
public /*@ pure @*/ int compareTo(/*@ non_null @*/ Voto other) {
return voto.compareTo(other.getVoto());
}
@Override
public /*@ pure @*/ /*@ non_null @*/ String toString() {
return "" + voto.toString();
}
}
|
package view;
import java.sql.SQLException;
import controller.DepartamentoController;
public class MainDepartamento {
public static void main(String[] args) {
DepartamentoController departamento = new DepartamentoController();
}
}
|
package com.goodhealth.framework.entity;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
@Getter
@Setter
/**
* 执行定时任务的实体类
*/
public class TaskScheduleModel {
/**
* 计划执行开始时间
*/
private Date scheduleStartTime;
/**
* 每个月于第几天
*/
private Integer intervalDay;
/**
* 每天 '1'
*
*/
private Character everyWeekDay;
/**
* 按日 2
* 按周 4
* 按月 8
* 间隔时间段 16
* 特定时间 32
*/
private Integer jobType;
/**
* 一周内的那几天{1,2,3,4,5,}
*/
private Integer[] dayOfWeeks;
/**
* 每隔几周
*/
private Integer intervalWeek;
/**
* 一个月中的某一天
*/
private Integer whichDay;
/**
* 多个月份{1,3,5,12}
*/
private Integer[] countOfMonths;
/**
* 当月的第几周
*/
private Integer intervalDayOfWeek;
/**
* 当周的第几天
*/
private Integer dayOfWeek;
/**
* 每隔几秒
*/
private Integer intervalCountOfSecond;
/**
* 每隔几分钟
*/
private Integer intervalCountOfMinute;
/**
* 当前小时的那几分钟
*/
private Integer[] minituesOfHour;
/**
* 每隔几天
*/
private Integer intervalCountOfDay;
/**
* 每隔几月
*/
private Integer intervalCountOfMonth;
/**
* 当前天的那几个小时
*/
private Integer[] hoursOfDay;
/**
* 每隔几小时
*/
private Integer intervalCountOfHours;
} |
package com.jbgames.sandsim.particles;
import com.badlogic.gdx.math.Vector2;
import java.awt.*;
public abstract class Powder extends Particle{
public Powder(String type, Vector2 pos, float temperature, Vector2 velocity, float density, boolean solid) {
super(type, pos, temperature, velocity, density, solid);
}
@Override
public void update(float delta, Vector2 gravity, Particle[][] simGrid) {
super.update(delta, gravity, simGrid);
simGrid[posToGrid().y][posToGrid().x] = null;
Vector2 curVec = new Vector2(getX(), getY());
Vector2 newVec = new Vector2(getX(), getY());
newVec.add(getVelocity().scl(delta));
if(newVec.y >= simGrid.length) newVec.y = simGrid.length-1;
Point curPos = new Point((int)curVec.x, (int)curVec.y);
Point newPos = new Point((int)newVec.x, (int)newVec.y);
boolean collided = false;
while(curPos.x != newPos.x || curPos.y != newPos.y) {
Point temp = new Point(curPos.x, curPos.y);
if(curPos.x < newPos.x) curPos.x++;
else if(curPos.x > newPos.x) curPos.x--;
if(curPos.y < newPos.y) curPos.y++;
else if(curPos.y > newPos.x) curPos.y--;
if(simGrid[curPos.y][curPos.x] != null) {
setPos(new Vector2(temp.x, temp.y));
simGrid[temp.y][temp.x] = this;
collided = true;
}
}
if(collided) {
Point p = posToGrid();
while(true) {
if (p.y + 1 >= simGrid.length) break;
boolean b = false;
if(simGrid[p.y+1][p.x] == null) {
p.y++;
b = true;
}
if(p.x-1 >= 0) {
if(simGrid[p.y+1][p.x-1] == null) {
p.x--;
p.y++;
b = true;
}
}
else if(p.x+1 < simGrid[0].length) {
if(simGrid[p.y+1][p.x+1] == null) {
p.x++;
p.y++;
b = true;
}
}
if(!b) break;
}
setPos(new Vector2(p.x, p.y));
simGrid[newPos.y][newPos.x] = this;
}
else {
setPos(newVec);
simGrid[newPos.y][newPos.x] = this;
}
}
}
|
package team1699.subsystems;
import edu.wpi.first.wpilibj.DoubleSolenoid;
import team1699.utils.controllers.BetterSpeedController;
public class Intake implements Subsystem {
public static final double kIntakeSpeed = 0.5; //TODO Give value
//Start the system in an uninitialized state and set a wanted state
private IntakeStates currentState = null;
private IntakeStates wantedState;
private final DoubleSolenoid solenoid;
private final BetterSpeedController speedController;
public Intake(final DoubleSolenoid solenoid, final BetterSpeedController speedController) {
wantedState = IntakeStates.STORED;
this.solenoid = solenoid;
this.speedController = speedController;
}
public void update() {
//We do not have to change states
if (currentState == wantedState) {
return;
}
//TODO Might need to wait for wheels to stop and solenoid to deploy
if (wantedState == IntakeStates.STORED) {
//Store intake and turn off intake wheels
solenoid.set(DoubleSolenoid.Value.kReverse); //TODO Check direction
speedController.set(0.0);
currentState = wantedState;
} else if (wantedState == IntakeStates.DEPLOYED) {
//Deploy intake and turn on intake wheels
solenoid.set(DoubleSolenoid.Value.kForward); //TODO Check direction
speedController.set(kIntakeSpeed);
currentState = wantedState;
}
}
public IntakeStates getWantedState() {
return wantedState;
}
public void setWantedState(final IntakeStates wantedState) {
this.wantedState = wantedState;
}
enum IntakeStates {
DEPLOYED,
STORED
}
}
|
package com.tencent.mm.az;
import com.tencent.mm.aa.c;
import com.tencent.mm.aa.j;
import com.tencent.mm.aa.q;
import com.tencent.mm.g.a.fr;
import com.tencent.mm.model.au;
import com.tencent.mm.model.e;
import com.tencent.mm.platformtools.ab;
import com.tencent.mm.protocal.c.by;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.ar;
import com.tencent.mm.storage.at;
import com.tencent.mm.storage.bd;
import com.tencent.mm.storage.bd.a;
public final class b extends e {
protected final bd a(by byVar, String str, String str2, String str3) {
String a = ab.a(byVar.rcl);
if (a == null || a.length() <= 0) {
x.e("MicroMsg.FMessageExtension", "possible friend msg : content is null");
} else {
a YV = a.YV(a);
if (!(YV.tbE == null && YV.tbF == null) && (YV.scene == 10 || YV.scene == 11)) {
fr frVar = new fr();
frVar.bOi.bOk = YV.tbE;
frVar.bOi.bOl = YV.tbF;
com.tencent.mm.sdk.b.a.sFg.m(frVar);
if (frVar.bOj.bOm) {
x.v("MicroMsg.FMessageExtension", "possible mobile friend is not in local address book");
}
}
if (YV.lWQ > 0) {
c.d(YV.lWQ, YV.tbD);
}
if (bi.oV(YV.otZ).length() > 0) {
j jVar = new j();
jVar.username = YV.otZ;
jVar.csA = 3;
jVar.by(true);
jVar.bWA = -1;
jVar.dHR = YV.tbG;
jVar.dHQ = YV.tbH;
jVar.bWA = -1;
x.d("MicroMsg.FMessageExtension", "dkhurl user:[%s] big:[%s] sm:[%s]", new Object[]{YV.otZ, jVar.Kx(), jVar.Ky()});
q.KH().a(jVar);
}
at atVar = new at();
atVar.field_createTime = c.o(str, (long) byVar.lOH);
atVar.field_isSend = 0;
atVar.field_msgContent = ab.a(byVar.rcl);
atVar.field_svrId = byVar.rcq;
atVar.field_talker = YV.otZ;
atVar.field_type = 0;
ar YL = d.SF().YL(atVar.field_talker);
if (YL != null) {
x.d("MicroMsg.FMessageExtension", "getByEncryptTalker success. encryptTalker = " + atVar.field_talker + " , real talker = " + YL.field_talker);
atVar.field_encryptTalker = atVar.field_talker;
atVar.field_talker = YL.field_talker;
}
au.HU();
com.tencent.mm.storage.ab Yg = com.tencent.mm.model.c.FR().Yg(atVar.field_talker);
if (Yg == null || !com.tencent.mm.l.a.gd(Yg.field_type) || Yg.dhP <= 0) {
d.SE().b(atVar);
} else {
x.d("MicroMsg.FMessageExtension", "The biz contact whose talker is " + atVar.field_talker + " has already been in user's contact list");
}
}
return null;
}
}
|
package com.smxknife.java2.reflection.demo01;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author smxknife
* 2019-07-11
*/
public class ClassDemo2 {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
// Cat cat = new Cat();
// System.out.println(Animal.class.isAssignableFrom(cat.getClass()));
// System.out.println(cat.getClass().getSuperclass());
// System.out.println(cat.getClass().isMemberClass());
// System.out.println(Animal.class.isAssignableFrom(new Animal().getClass()));
// System.out.println(cat instanceof Animal);
// System.out.println(new Animal() instanceof Animal);
Class<?> aClass = Class.forName(Cat.class.getCanonicalName());
Object o = aClass.newInstance();
Method test = aClass.getMethod("test");
Object invoke = test.invoke(o);
}
}
class Animal {
public final void test() {
System.out.println("animal test");
}
}
class Cat extends Animal {
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.