hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
fb2f4b017ae1dc212b839f892b7c939254ef024a | 546 | package net.lecousin.compression.lzma;
import java.util.Arrays;
abstract class RangeCoder {
protected RangeCoder() {
// nothing to do
}
static final int SHIFT_BITS = 8;
static final int TOP_MASK = 0xFF000000;
static final int BIT_MODEL_TOTAL_BITS = 11;
static final int BIT_MODEL_TOTAL = 1 << BIT_MODEL_TOTAL_BITS;
static final short PROB_INIT = (short)(BIT_MODEL_TOTAL / 2);
static final int MOVE_BITS = 5;
public static final void initProbs(short[] probs) {
Arrays.fill(probs, PROB_INIT);
}
}
| 24.818182 | 65 | 0.701465 |
7cb12753288f7d946ae9abeb9d2a4d7ac367f786 | 2,114 | package paxi.maokitty.verify;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.strategy.HystrixPlugins;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import paxi.maokitty.verify.command.AssignkeySilentCommand;
import paxi.maokitty.verify.command.DefaultSettingSilentCommand;
import paxi.maokitty.verify.selfmetrix.MetricErrorCountInMemoryCollector;
import paxi.maokitty.verify.selfmetrix.MetricPublisher;
import paxi.maokitty.verify.service.RemoteLogicService;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Created by maokitty on 19/6/8.
*/
public class PublishMetrixVerify {
private static final Logger LOG = LoggerFactory.getLogger(PublishMetrixVerify.class);
public static void main(String[] args) {
RemoteLogicService logicService = new RemoteLogicService();
publisherVerify(logicService);
}
private static void publisherVerify(RemoteLogicService logicService) {
HystrixCommandKey key = HystrixCommandKey.Factory.asKey("myAssignCollectorCommandKey");
//多个测试防止出现问题,先清空
HystrixPlugins.reset();
HystrixPlugins.getInstance().registerMetricsPublisher(MetricPublisher.getInstance());
for (int i=0;i<10;i++){
String command="another day";
if (i>5){
command="1";
}
AssignkeySilentCommand assignkeyCommand = new AssignkeySilentCommand(key,logicService, command);
assignkeyCommand.execute();
DefaultSettingSilentCommand defaultSettingCommand = new DefaultSettingSilentCommand(logicService,command);
defaultSettingCommand.execute();
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
LOG.error("publisherVerify",e);
}
Set<String> keys = MetricPublisher.getKeys();
for (String k:keys){
LOG.info("collect key:{}",k);
}
MetricErrorCountInMemoryCollector collector = MetricPublisher.get(key.name());
collector.printAll();
collector.stopCollect();
}
}
| 37.75 | 118 | 0.702933 |
9fdc9c3fbcc7db64dab51a682496c8f7b3f94a66 | 218 | package br.com.asyncawait.core.models;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public final class Message<T> {
private final Pid sender;
private final T content;
}
| 18.166667 | 38 | 0.775229 |
0cbc344eebf7f23221ade873726c0ebaf950a025 | 2,299 | /*
* 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 chapter1;
import java.util.Date;
import java.util.concurrent.Phaser;
import java.util.concurrent.TimeUnit;
/**
*
* @author Win7
*/
public class Student implements Runnable {
private Phaser phaser;
public Student(Phaser phaser) {
this.phaser = phaser;
}
@Override
public void run() {
System.out.printf("%s: arrived to do the exam. %s\n", Thread.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s:Is going to do the first excercise.%s\n", Thread.currentThread().getName(), new Date());
doExercise1();
System.out.printf("%s: Has done the first exercise. %s\n", Thread.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s:Is going to do the second excercise.%s\n", Thread.currentThread().getName(), new Date());
doExercise2();
System.out.printf("%s: Has done the second exercise. %s\n", Thread.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
System.out.printf("%s:Is going to do the third excercise.%s\n", Thread.currentThread().getName(), new Date());
doExercise3();
System.out.printf("%s: Has done the third exercise. %s\n", Thread.currentThread().getName(), new Date());
phaser.arriveAndAwaitAdvance();
}
private void doExercise1() {
try {
long duration = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doExercise2() {
try {
long duration = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private void doExercise3() {
try {
long duration = (long) (Math.random() * 10);
TimeUnit.SECONDS.sleep(duration);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
| 31.493151 | 119 | 0.608525 |
f482fd68c092f033bedcb0c0076d169dd2c7ac79 | 1,959 | Partition Array根据pivot把array分成两半。
从array两边开始缩进。while loop到遍历完。非常直白的implement。
注意low/high,或者叫start/end不要越边界
O(n)
Quick sort的基础。
```
/*
Given an array nums of integers and an int k, partition the array (i.e move the elements in "nums") such that:
All elements < k are moved to the left
All elements >= k are moved to the right
Return the partitioning index, i.e the first index i nums[i] >= k.
Example
If nums=[3,2,2,1] and k=2, a valid answer is 1.
Note
You should do really partition in array nums instead of just counting the numbers of integers smaller than k.
If all elements in nums are smaller than k, then return nums.length
Challenge
Can you partition the array in-place and in O(n)?
Tags Expand
Two Pointers Sort Array
Thoughts:
Two pointer sort, still similar to quick sort.
Move small to left and large to right.
When the two pinter meets, that's crossing point about pivot k
*/
public class Solution {
/**
* @param nums: The integer array you should partition
* @param k: As description
* return: The index after partition
*/
public int partitionArray(int[] nums, int k) {
if (nums == null || nums.length == 0) {
return 0;
}
return helper(nums, 0, nums.length - 1, k);
}
public void swap(int[] nums, int x, int y) {
int temp = nums[x];
nums[x] = nums[y];
nums[y] = temp;
}
public int helper(int[] nums, int start, int end, int pivot) {
int low = start;
int high = end;
while (low <= high) {
while (low <= high && nums[low] < pivot) {
low++;
}
while (low <= high && nums[high] >= pivot) {
high--;
}
if (low <= high) {
swap(nums, low, high);
low++;
high--;
}
}
return low;
}
}
``` | 26.12 | 110 | 0.570189 |
422b72beb1c1454148fa1905091040b7889d3ae1 | 1,046 | package com.kiroule.vaadin.demo.ui.view.storefront;
import com.kiroule.vaadin.demo.ui.components.OrdersGrid;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.annotations.DesignRoot;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Panel;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.declarative.Design;
/**
* !! DO NOT EDIT THIS FILE !!
*
* This class is generated by Vaadin Designer and will be overwritten.
*
* Please make a subclass with logic and additional interfaces as needed,
* e.g class LoginView extends LoginDesign implements View { }
*/
@DesignRoot
@AutoGenerated
@SuppressWarnings("serial")
public class StorefrontViewDesign extends VerticalLayout {
protected Panel searchPanel;
protected TextField searchField;
protected Button searchButton;
protected CheckBox includePast;
protected Button newOrder;
protected OrdersGrid list;
public StorefrontViewDesign() {
Design.read(this);
}
}
| 29.055556 | 74 | 0.763862 |
0bd1087753678fae85f802eceb7f67eb68e7edf4 | 3,838 | package club.codecloud.base.util.security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.SecureRandom;
import java.util.Base64;
/**
* @author ulei
* @date 2018/6/29
*/
public final class AESUtils {
/**
* 密钥算法
*/
private static final String AES = "AES";
private static final int KEY_SIZE = 128;
/**
* 加密/解密算法/工作模式/填充方法
*/
private static final String CIPHER_ALGORITHM = "AES/ECB/PKCS5PADDING";
private static KeyGenerator keyGenerator = null;
static {
try {
keyGenerator = KeyGenerator.getInstance(AES);
} catch (Exception e) {
throw new RuntimeException("init AESUtils error", e);
}
}
/**
* 获取密钥
*
* @return
* @throws Exception
*/
public static String getKey() {
try {
//实例化
//AES 要求密钥长度为128位、192位或256位
keyGenerator.init(KEY_SIZE, new SecureRandom());
//生成密钥
byte[] secretKey = keyGenerator.generateKey().getEncoded();
return Base64.getEncoder().encodeToString(secretKey);
} catch (Exception e) {
throw new RuntimeException("获取AES_Key错误,错误信息:", e);
}
}
/**
* 加密
*
* @param data 待加密数据
* @param key 密钥
* @return bytes[] 加密数据
* @throws Exception
*/
public static byte[] encrypt(byte[] data, byte[] key) {
try {
//还原密钥
Key k = new SecretKeySpec(key, AES);
/**
* 实例化
* 使用PKCS7Padding填充方式,按如下方式实现
* Cipher.getInstance(CIPHER_ALGORITHM,"BC");
*/
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//初始化,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, k);
//执行操作
return cipher.doFinal(data);
} catch (Exception e) {
throw new RuntimeException("AES加密错误,错误信息:", e);
}
}
/**
* 加密
*
* @param data 待加密数据
* @param key 密钥
* @return 加密数据
* @throws Exception
*/
public static String encrypt(String data, String key) {
try {
byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8);
byte[] keyBytes = Base64.getDecoder().decode(key);
return Base64.getEncoder().encodeToString(encrypt(dataBytes, keyBytes));
} catch (Exception e) {
throw new RuntimeException("AES加密错误,错误信息:", e);
}
}
/**
* 解密
*
* @param data 待解密数据
* @param key 密钥
* @return byte[] 解密数据
* @throws Exception
*/
private static byte[] decrypt(byte[] data, byte[] key) {
try {
//还原密钥
Key k = new SecretKeySpec(key, AES);
/**
* 实例化
* 使用PKCS7Padding填充方式,按如下方式实现
* Cipher.getInstance(CIPHER_ALGORITHM,"BC");
*/
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//初始化,设置解密模式
cipher.init(Cipher.DECRYPT_MODE, k);
//执行操作
return cipher.doFinal(data);
} catch (Exception e) {
throw new RuntimeException("AES解密错误,错误信息:", e);
}
}
/**
* 解密
*
* @param data 待解密数据
* @param key 密钥
* @return 解密数据
* @throws Exception
*/
public static String decrypt(String data, String key) {
// 解析数据
byte[] dataBytes = Base64.getDecoder().decode(data);
// 还原密钥
byte[] keyBytes = Base64.getDecoder().decode(key);
// 执行操作
return new String(decrypt(dataBytes, keyBytes), StandardCharsets.UTF_8);
}
}
| 25.932432 | 84 | 0.547681 |
0253c2eb1146f3c38c7daac20faa4878156701a4 | 687 | package com.sudwood.advancedutilities.items;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.item.Item;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public class ItemRubber extends Item
{
private int type;
public ItemRubber(int type)
{
super();
this.type = type;
this.setMaxStackSize(64);
}
@SideOnly(Side.CLIENT)
public void registerIcons(IIconRegister par1IconRegister)
{
if(type == 0)
this.itemIcon = par1IconRegister.registerIcon("advancedutilities:rubberitem");
if(type == 1)
this.itemIcon = par1IconRegister.registerIcon("advancedutilities:glueball");
}
}
| 23.689655 | 84 | 0.733624 |
a5c90d2e8f2a73a00833fb254413b5e50a28eba3 | 439 | package pkj.no.tellstick.device.iface;
import pkj.no.tellstick.device.TellstickException;
/**
* A generic device.
* @author peec
*
*/
public interface Device{
/**
* Turns on the device.
* @return
*/
public void on() throws TellstickException;
/**
* Turns off the device.
*/
public void off() throws TellstickException;
/**
* Returns the name of the device.
* @return
*/
public String getType();
}
| 13.30303 | 50 | 0.644647 |
fb41edc72f54db99e02b3c4777196291c5770b59 | 1,009 | package org.springframework.samples.petclinic.care;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
public class CareService {
@Autowired
private CareProvisionRepository careProvisionRepository;
public List<CareProvision> CareProvision(){
return careProvisionRepository.findAll();
}
public List<Care> getAllCares(){
return careProvisionRepository.findAllCares();
}
public List<Care> getAllCompatibleCares(String petTypeName){
return null;
}
public Care getCare(String careName) {
return careProvisionRepository.findCareByName(careName);
}
public CareProvision save(CareProvision p) throws NonCompatibleCaresException, UnfeasibleCareException {
return careProvisionRepository.save(p);
}
public List<CareProvision> getAllCaresProvided(){
return null;
}
public List<CareProvision> getCaresProvided(Integer visitId){
return null;
}
}
| 22.422222 | 108 | 0.719524 |
ff6db5db16940879c9837a02f0217c72cd395a91 | 32,343 | // THIS SOURCE CODE IS SUPPLIED "AS IS" WITHOUT WARRANTY OF ANY KIND, AND ITS AUTHOR AND THE JOURNAL OF MACHINE LEARNING RESEARCH (JMLR) AND JMLR'S PUBLISHERS AND DISTRIBUTORS, DISCLAIM ANY AND ALL WARRANTIES, INCLUDING BUT NOT LIMITED TO ANY IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, AND ANY WARRANTIES OR NON INFRINGEMENT. THE USER ASSUMES ALL LIABILITY AND RESPONSIBILITY FOR USE OF THIS SOURCE CODE, AND NEITHER THE AUTHOR NOR JMLR, NOR JMLR'S PUBLISHERS AND DISTRIBUTORS, WILL BE LIABLE FOR DAMAGES OF ANY KIND RESULTING FROM ITS USE. Without lim- iting the generality of the foregoing, neither the author, nor JMLR, nor JMLR's publishers and distributors, warrant that the Source Code will be error-free, will operate without interruption, or will meet the needs of the user.
//
// --------------------------------------------------------------------------
//
// Copyright 2016 Stephen Piccolo
//
// This file is part of ML-Flex.
//
// ML-Flex is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// ML-Flex 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 ML-Flex. If not, see <http://www.gnu.org/licenses/>.
package mlflex.helper;
import java.util.*;
/** This class contains helper methods for dealing with Java collections and lists. Many of these implement functionality that circumvents some of the awkwardness and verbostity of dealing with lists in Java.
* @author Stephen Piccolo
*/
public class ListUtilities
{
public static final ArrayList<String> ALPHABET = ListUtilities.CreateStringList("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
/** Appends a String value to the end of an existing String array (warning: can be CPU intensive because a new array object is recreated each time).
*
* @param array String array object
* @param newValue Value to be added
* @return New String array object
*/
public static String[] AppendItemToArray(String[] array, String newValue)
{
ArrayList<String> list = CreateStringList(array);
list.add(array.length, newValue);
return ConvertToStringArray(list);
}
/** Appends a String value to the end of an existing String array (warning: can be CPU intensive because a new array object is recreated each time) at a given index position.
*
* @param array String array object
* @param newValue Value to be added
* @param position Index position to where it should be added
* @return New String array object
*/
public static String[] AddItemToArray(String[] array, String newValue, int position)
{
ArrayList<String> list = CreateStringList(array);
list.add(position, newValue);
return ConvertToStringArray(list);
}
public static ArrayList<String> AppendStringToListItems(ArrayList<String> list, String suffix)
{
ArrayList<String> newList = new ArrayList<String>();
for (String item : list)
newList.add(item + suffix);
return newList;
}
/** Creates a list of integers from an array of integers.
*
* @param values Integer values
* @return List of integers
*/
public static ArrayList<Integer> CreateIntegerList(Integer... values)
{
ArrayList<Integer> results = new ArrayList<Integer>();
if (values.length > 0)
Collections.addAll(results, values);
return results;
}
/** Converts a list of Strings that contain integer-compatible values to a list of Integers.
*
* @param values List of String values
* @return List of Integer values
*/
public static ArrayList<Integer> CreateIntegerList(ArrayList<String> values)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (String value : values)
list.add(Integer.parseInt(value));
return list;
}
/** Creates a list of integers starting at one value and ending at another value (increment step is one).
*
* @param startNumber Start number
* @param endNumber End number
* @return List of Integer values
*/
public static ArrayList<Integer> CreateIntegerSequenceList(int startNumber, int endNumber)
{
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i=startNumber; i<=endNumber; i++)
list.add(i);
return list;
}
/** Creates a list of objects from an array of objects.
*
* @param values Array of objects
* @return List of objects
*/
public static ArrayList CreateObjectList(Object... values)
{
ArrayList results = new ArrayList();
Collections.addAll(results, values);
return results;
}
/** Converts a list of Double objects to a list of String objects. If a Double object is Double.NaN, it is specified as "NA."
*
* @param values List of double values
* @return Converted list
*/
public static ArrayList<String> CreateStringListFromDoubleList(ArrayList<Double> values)
{
ArrayList<String> stringList = new ArrayList<String>();
for (Double value : values)
if (value.equals(Double.NaN))
stringList.add("NA");
else
stringList.add(String.valueOf(value));
return stringList;
}
/** Converts a list of Integer objects to a list of String objects. If an Integer object is Integer.MIN_VALUE, it is specified as "NA."
*
* @param values List of Integer values
* @return Converted list
*/
public static ArrayList<String> CreateStringListFromIntegerList(ArrayList<Integer> values)
{
ArrayList<String> stringList = new ArrayList<String>();
for (Integer value : values)
if (value.equals(Integer.MIN_VALUE))
stringList.add("NA");
else
stringList.add(String.valueOf(value));
return stringList;
}
/** Converts an array of objects to a list of String objects.
*
* @param values Array of objects
* @return List of String objects
*/
public static ArrayList<String> CreateStringList(Object... values)
{
return CreateStringList(CreateObjectList(values));
}
/** Converts an array of String objects to a list of String objects.
*
* @param values Array of String objects
* @return List of String objects
*/
public static ArrayList<String> CreateStringList(String... values)
{
ArrayList<String> results = new ArrayList<String>();
if (values.length > 0)
Collections.addAll(results, values);
return results;
}
/** This method iterates over multiple lists of String objects and creates a single list of String objects containing the contents of all.
*
* @param lists Array of String lists
* @return Combined list
*/
public static ArrayList<String> CreateStringList(ArrayList<String>... lists)
{
ArrayList<String> all = new ArrayList<String>();
for (ArrayList<String> list : lists)
all.addAll(list);
return new ArrayList<String>(all);
}
/** Converts a generic collection of objects into a list of String objects.
*
* @param values Collection of objects
* @return List of String objects
*/
public static ArrayList<String> CreateStringList(Collection values)
{
ArrayList<String> results = new ArrayList<String>();
for (Object value : values)
results.add(String.valueOf(value));
return results;
}
/** Converts a list of objects to a list of boolean objects.
*
* @param list List of objects
* @return List of boolean objects
* @throws Exception
*/
public static ArrayList<Boolean> CreateBooleanList(ArrayList list) throws Exception
{
ArrayList<Boolean> booleans = new ArrayList<Boolean>();
for (Object x : list)
booleans.add((Boolean)x);
return booleans;
}
/** Creates a list of Boolean objects from an array of boolean values.
*
* @param values An array of boolean values
* @return List of boolean objects
* @throws Exception
*/
public static ArrayList<Boolean> CreateBooleanList(boolean ... values) throws Exception
{
ArrayList<Boolean> booleans = new ArrayList<Boolean>();
for (boolean value : values)
booleans.add(value);
return booleans;
}
/** Creates a list of double objects from an array of double objects.
*
* @param values Array of double objects
* @return List of double objects
*/
public static ArrayList<Double> CreateDoubleList(double... values)
{
ArrayList<Double> results = new ArrayList<Double>();
for (double d : values)
results.add(d);
return results;
}
/** Converts a list of double-compatible String objects to a list of double objects.
*
* @param values List of String values
* @return List of double values
*/
public static ArrayList<Double> CreateDoubleList(ArrayList<String> values)
{
ArrayList<Double> doubles = new ArrayList<Double>();
for (String value : values)
if (DataTypeUtilities.IsDouble(value))
doubles.add(Double.parseDouble(value));
return doubles;
}
/** Creates a list of double objects.
*
* @param value Value to add to list
* @param repeatTimes Number of times to add value to list
* @return List of double values
*/
public static ArrayList<Double> CreateDoubleList(double value, int repeatTimes)
{
ArrayList<Double> list = new ArrayList<Double>();
for (int i=0; i<repeatTimes; i++)
list.add(value);
return list;
}
/** Creates a list of String objects.
*
* @param value Value to add to list
* @param numRepetitions Number of times to add value to list
* @return List of String values
*/
public static ArrayList<String> CreateStringList(String value, int numRepetitions)
{
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < numRepetitions; i++)
list.add(value);
return list;
}
/** Converts a list of String objects to an array of String objects.
*
* @param collection List of String objects
* @return Array of String objects
*/
public static String[] ConvertToStringArray(ArrayList<String> collection)
{
return collection.toArray(new String[0]);
}
/** Converts a list of double objects to an array of Double objects.
*
* @param collection List of double objects
* @return Array of double objects
*/
public static double[] ConvertToDoubleArray(ArrayList<Double> collection)
{
Double[] rawArray = collection.toArray(new Double[0]);
double[] result = new double[rawArray.length];
for (int i = 0; i < rawArray.length; i++)
result[i] = rawArray[i];
return result;
}
/** Identifies all unique String values in a list.
*
* @param values List of String values
* @return Unique values
*/
public static ArrayList<String> GetUniqueValues(ArrayList<String> values)
{
return new ArrayList<String>(new LinkedHashSet<String>(values));
//return new ArrayList<String>(new LinkedHashSet<String>(values));
}
/** Returns a random subset of values from the specified list.
*
* @param list List to be examined
* @param numValues
* @param random Random number generator
* @return Random subset of values
*/
public static ArrayList<String> GetRandomSubset(ArrayList<String> list, int numValues, Random random)
{
return Subset(Shuffle(list, random), 0, MathUtilities.Min(numValues, list.size()));
}
// /** Convenience method to remove all instances of a given String value from a list.
// *
// * @param list List of String values
// * @param itemToRemove Item to be removed
// * @return New list with items removed
// */
// public static ArrayList<String> RemoveAll(ArrayList<String> list, String itemToRemove)
// {
// return RemoveAll(list, ListUtilities.CreateStringList(itemToRemove));
// }
// /** Convenience method to remove all instances of given String values from a list.
// *
// * @param list List of String values
// * @param itemsToRemove Items to be removed
// * @return New list with items removed
// */
// public static ArrayList<String> RemoveAll(ArrayList<String> list, ArrayList<String> itemsToRemove)
// {
// if (itemsToRemove.size() == 0)
// return list;
//
// ArrayList<String> newList = new ArrayList<String>(list);
// newList.removeAll(itemsToRemove);
//
// return newList;
// }
/** This method returns unique String values that are in the first list but not in the second list (set difference).
*
* @param list1 Primary list
* @param list2 Secondary list to be subtracted
* @return New list with remaining values
*/
public static ArrayList<String> GetDifference(ArrayList<String> list1, ArrayList<String> list2)
{
if (list1.size() == 0)
return new ArrayList<String>();
if (list2.size() == 0)
return list1;
HashSet<String> set1 = new HashSet<String>(list1);
HashSet<String> set2 = new HashSet<String>(list2);
set1.removeAll(set2);
return new ArrayList<String>(set1);
}
/** Identifies all values in a String list that end with a given String value.
*
* @param values List of values to be tested
* @param pattern String value to be matched
* @return List subset
*/
public static ArrayList<String> GetValuesEndingWith(ArrayList<String> values, String pattern)
{
ArrayList<String> results = new ArrayList<String>();
for (String value : values)
if (value.endsWith(pattern))
results.add(value);
return results;
}
/** Identifies all values in a String list that start with a given String value.
*
* @param values List of values to be tested
* @param pattern String value to be matched
* @return List subset
*/
public static ArrayList<String> GetValuesStartingWith(ArrayList<String> values, String pattern)
{
ArrayList<String> results = new ArrayList<String>();
for (String value : values)
if (value.startsWith(pattern))
results.add(value);
return results;
}
/** Identifies all values in a String list that do not start with a given String value.
*
* @param values List of values to be tested
* @param pattern String value to be matched
* @return List subset
*/
public static ArrayList<String> GetValuesNotStartingWith(ArrayList<String> values, String pattern)
{
ArrayList<String> results = new ArrayList<String>();
for (String value : values)
if (!value.startsWith(pattern))
results.add(value);
return results;
}
/** Gets a subset of a String array, starting with the specified index position.
*
* @param array String array
* @param startIndex Start index position
* @return Array subset
*/
public static String[] Subset(String[] array, int startIndex)
{
return Subset(array, startIndex, array.length);
}
/** Gets a subset of a String array, starting with the specified index position.
*
* @param array String array
* @param startIndex Start index position
* @param endIndex End index position
* @return Array subset
*/
public static String[] Subset(String[] array, int startIndex, int endIndex)
{
return ConvertToStringArray(ListUtilities.Subset(ListUtilities.CreateStringList(array), startIndex, endIndex));
}
/** Gets a subset of a String list, starting with the specified index position.
*
* @param list String list
* @param startIndex Start index position
* @return List subset
*/
public static ArrayList<String> Subset(ArrayList<String> list, int startIndex)
{
return Subset(list, startIndex, list.size());
}
/** Gets a subset of a String list, starting with the specified index position.
*
* @param list String list
* @param startIndex Start index position
* @param endIndex End index position
* @return List subset
*/
public static ArrayList<String> Subset(ArrayList<String> list, int startIndex, int endIndex)
{
ArrayList result = new ArrayList();
for (int i = startIndex; i < endIndex; i++)
result.add(list.get(i));
return result;
}
/** Gets a subset of a String list for a given set of indices.
*
* @param values List of String values
* @param indices Indices at which values should be obtained
* @return List subset
*/
public static ArrayList<String> Subset(ArrayList<String> values, ArrayList<Integer> indices)
{
ArrayList<String> subset = new ArrayList<String>();
for (int index : indices)
subset.add(values.get(index));
return subset;
}
/** Finds the intersection between two lists of String objects.
*
* @param list1 First list
* @param list2 Second list
* @return Intersection list (contains values that exist in both lists)
*/
public static ArrayList<String> Intersect(ArrayList<String> list1, ArrayList<String> list2)
{
if (list1.size() == 0)
return list2;
Set intersection = new HashSet(list1);
intersection.retainAll(new HashSet(list2));
return new ArrayList(intersection);
}
/** Finds the union of two lists of String objects
*
* @param list1 First list
* @param list2 Second list
* @return Union list (contains values that exist in either list)
*/
public static ArrayList<String> Union(ArrayList<String> list1, ArrayList<String> list2)
{
Set union = new HashSet(list1);
union.addAll(new HashSet(list2));
return new ArrayList(union);
}
/** For a list of String objects, this method trims any white space from each value.
*
* @param coll List of String objects
* @return List of trimmed String objects
*/
public static ArrayList<String> TrimStrings(ArrayList<String> coll)
{
ArrayList<String> result = new ArrayList<String>();
for (String x : coll)
result.add(x.trim());
return result;
}
/** For a list of String objects, this method identifies all objects that contain a given value and replaces that text with another value.
*
* @param list List of String objects
* @param from Value to search for
* @param to Value with which to replace matches
* @return Replaced list of String objects
*/
public static ArrayList<String> Replace(ArrayList<String> list, String from, String to)
{
ArrayList<String> newList = new ArrayList<String>();
for (String x : list)
newList.add(x.replace(from, to));
return newList;
}
/** For a list of String objects, this method replaces all instances that match a given value with another value.
*
* @param list List of String objects
* @param from Value to search for
* @param to Value with which to replace matches
* @return Replaced list of String objects
*/
public static ArrayList<String> ReplaceAllExactMatches(ArrayList<String> list, String from, String to)
{
if (list.size() == 0)
return list;
ArrayList<String> newList = new ArrayList<String>(list);
for (int i = 0; i < newList.size(); i++)
if (newList.get(i).equals(from))
newList.set(i, to);
return newList;
}
/** This method indicates which element is most frequently observed in a given list of String objects.
*
* @param values String values
* @return Most frequent value
*/
public static String GetMostFrequentValue(ArrayList<String> values)
{
HashMap<String, Integer> frequencyMap = MapUtilities.GetFrequencyMap(values);
int max = 0;
String valueOfMax = null;
for (Map.Entry<String, Integer> entry : frequencyMap.entrySet())
if (entry.getValue() > max)
{
max = entry.getValue();
valueOfMax = entry.getKey();
}
return valueOfMax;
}
/** This list indicates the number of values in a list of String objects that match a given value.
*
* @param values List of String values
* @param matchValue Match value
* @return Number of matches
*/
public static int GetNumMatches(ArrayList<String> values, String matchValue)
{
int count = 0;
for (String value : values)
if (value.equals(matchValue))
count++;
return count;
}
/** From a list of String objects, this method randomly selects one of the objects
*
* @param list List of String objects
* @return Randomly selected value
*/
public static String PickRandomString(ArrayList<String> list, Random random)
{
return (String)PickRandomObject(list, random);
}
/** From a list of objects, this method randomly selects one of the objects
*
* @param list List of objects
* @return Randomly selected object
*/
public static Object PickRandomObject(ArrayList list, Random random)
{
return Shuffle(list, random).get(0);
}
/** For a list of boolean objects, this method indicates whether all are true.
*
* @param booleans List of boolean values
* @return Whether all of the values are true
*/
public static boolean AllTrue(ArrayList<Boolean> booleans)
{
for (Boolean x : booleans)
if (!x.equals(Boolean.TRUE))
return false;
return true;
}
/** For a list of boolean objects, this method indicates whether any are true.
*
* @param booleans List of boolean values
* @return Whether any of the values are true
*/
public static boolean AnyTrue(ArrayList<Boolean> booleans)
{
for (Boolean x : booleans)
if (x.equals(Boolean.TRUE))
return true;
return false;
}
/** For a list of boolean objects, this method indicates whether any are false.
*
* @param booleans List of boolean values
* @return Whether any of the values are false
*/
public static boolean AnyFalse(ArrayList<Boolean> booleans)
{
for (Boolean x : booleans)
if (x.equals(Boolean.FALSE))
return true;
return false;
}
/** This method randomly shuffles a list of String objects.
*
* @param list List of String objects
* @param randomNumberGenerator Random number generator that will be used for shuffling
* @return Shuffled list
*/
public static ArrayList<String> Shuffle(ArrayList<String> list, Random randomNumberGenerator)
{
ArrayList<String> shuffled = new ArrayList<String>(list);
Collections.shuffle(shuffled, randomNumberGenerator);
return shuffled;
}
/** This method converts an array of String objects to a single String representation and inserts a delimiter between each object.
*
* @param s Array of String objects
* @param delimiter Delimiter
* @return Formatted String representation
*/
public static String Join(String[] s, String delimiter)
{
return Join(CreateStringList(s), delimiter);
}
/** This method converts a list of String objects to a single String representation and inserts a delimiter between each object.
*
* @param list List of String objects
* @param delimiter Delimiter
* @return Formatted String representation
*/
public static String Join(ArrayList<String> list, String delimiter)
{
if (list.isEmpty())
return "";
StringBuilder sb = new StringBuilder();
for (String x : list)
sb.append(x + delimiter);
sb.delete(sb.length() - delimiter.length(), sb.length());
return sb.toString();
}
/** For a list of double objects, this method identified the indices of elements that match a specified value.
*
* @param values List of double objects
* @param value Value to search for
* @return Matching indices
*/
public static ArrayList<Integer> GetIndices(ArrayList<Double> values, double value)
{
ArrayList<Integer> indices = new ArrayList<Integer>();
for (int i=0; i<values.size(); i++)
if (values.get(i) == value)
indices.add(i);
return indices;
}
/** For a list of double objects, this method indicates how many elements match a specified value.
*
* @param values List of double objects
* @param matchValue Value to search for
* @return Number of matches
*/
public static int GetNumEqualTo(ArrayList<Double> values, double matchValue)
{
int count = 0;
for (double value : values)
if (value == matchValue)
count++;
return count;
}
/** For a list of double objects, this method indicates which elements are greater than (or equal to) a specified value.
*
* @param values List of double objects
* @param limit Query value
* @param orEqualTo Indicates whether values should be considered a match if they are equal to the query value
* @return Elements that are greater than (or equal to) the query value
*/
public static ArrayList<Double> GreaterThan(ArrayList<Double> values, double limit, boolean orEqualTo)
{
ArrayList<Double> modValues = new ArrayList<Double>();
for (double value : values)
if (value > limit || (value == limit && orEqualTo))
modValues.add(value);
return modValues;
}
/** For a list of double objects, this method indicates which elements are less than (or equal to) a specified value.
*
* @param values List of double objects
* @param limit Query value
* @param orEqualTo Indicates whether values should be considered a match if they are equal to the query value
* @return Elements that are less than (or equal to) the query value
*/
public static ArrayList<Double> LessThan(ArrayList<Double> values, double limit, boolean orEqualTo)
{
ArrayList<Double> modValues = new ArrayList<Double>();
for (double value : values)
if (value < limit || (value == limit && orEqualTo))
modValues.add(value);
return modValues;
}
/** For a list of double objects, this method indicates the indices of elements that are greater than (or equal to) a specified value.
*
* @param values List of double objects
* @param limit Query value
* @param orEqualTo Indicates whether values should be considered a match if they are equal to the query value
* @return Indices of elements that are greater than (or equal to) the query value
*/
public static ArrayList<Integer> WhichGreaterThan(ArrayList<Double> values, double limit, boolean orEqualTo)
{
ArrayList<Integer> greaterThan = new ArrayList<Integer>();
for (int i=0; i<values.size(); i++)
if (values.get(i) > limit || (values.get(i) == limit && orEqualTo))
greaterThan.add(i);
return greaterThan;
}
/** For a list of double objects, this method indicates the indices of elements that are less than (or equal to) a specified value.
*
* @param values List of double objects
* @param limit Query value
* @param orEqualTo Indicates whether values should be considered a match if they are equal to the query value
* @return Indices of elements that are less than (or equal to) the query value
*/
public static ArrayList<Integer> WhichLessThan(ArrayList<Double> values, double limit, boolean orEqualTo)
{
ArrayList<Integer> lessThan = new ArrayList<Integer>();
for (int i=0; i<values.size(); i++)
if (values.get(i) < limit || (values.get(i) == limit && orEqualTo))
lessThan.add(i);
return lessThan;
}
/** For a list of String objects, this method retrieves the elements at the given indices.
*
* @param values List of String objects
* @param indices Indices
* @return List containing values from specified indices
*/
public static ArrayList<String> Get(ArrayList<String> values, ArrayList<Integer> indices)
{
ArrayList<String> matches = new ArrayList<String>();
for (int i : indices)
matches.add(values.get(i));
return matches;
}
/** Convenience methods that makes it easier to sort a collection
*
* @param list Collection to sort
* @return Sorted list
*/
public static ArrayList Sort(Collection list)
{
ArrayList newList = new ArrayList(list);
Collections.sort(newList);
return newList;
}
/** Convenience methods that makes it easier to sort a String list
*
* @param list List to sort
* @return Sorted list
*/
@SuppressWarnings("unchecked")
public static ArrayList<String> SortStringList(ArrayList<String> list)
{
// ArrayList<NumericString> numericStringList = new ArrayList<NumericString>();
// for (String item : list)
// numericStringList.add(new NumericString(item));
//
// Collections.sort(numericStringList);
//
// ArrayList<String> sortedList = new ArrayList<String>();
// for (NumericString item : numericStringList)
// sortedList.add(item.toString());
//
// return sortedList;
return (ArrayList<String>)Sort(list);
}
/** This method inserts a String value at the specified index into a list of String objects.
*
* @param list List of String objects
* @param value Value to insert
* @param index Index at which to insert the value
* @return Modified list
*/
public static ArrayList<String> InsertIntoStringList(ArrayList<String> list, String value, int index)
{
ArrayList<String> newList = new ArrayList<String>(list);
newList.add(index, value);
return newList;
}
/** This method creates a new list with each element of the input list in its lower-case representation.
*
* @param list List to be converted to lower case
* @return New list converted to lower case
*/
public static ArrayList<String> ToLowerCase(ArrayList<String> list)
{
ArrayList<String> newList = new ArrayList<String>();
for (String x : list)
newList.add(x.toLowerCase());
return newList;
}
/** Adds a prefix to each element in the list.
*
* @param list List of strings
* @param prefix Prefix that wil be added
* @return Newly formatted string list
*/
public static ArrayList<String> Prefix(ArrayList<String> list, String prefix)
{
ArrayList<String> newList = new ArrayList<String>();
for (String x : list)
newList.add(prefix + x);
return newList;
}
} | 33.796238 | 815 | 0.638067 |
247cf0135d9d6eeb5b832c785edc60cb8afea9cc | 350 | package de.autoDrive.NetworkServer.rest.dto_v1;
import java.util.ArrayList;
import java.util.List;
public class RoutesResponseDtos {
private List<RouteDto> routes = new ArrayList<>();
public List<RouteDto> getRoutes() {
return routes;
}
public void setRoutes(List<RouteDto> routes) {
this.routes = routes;
}
}
| 20.588235 | 54 | 0.685714 |
f75ab273d8fa2da3ddb3b446504b9aee392e4ba0 | 2,897 | // Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE
package org.bytedeco.systems.windows;
import java.nio.*;
import org.bytedeco.javacpp.*;
import org.bytedeco.javacpp.annotation.*;
import static org.bytedeco.javacpp.presets.javacpp.*;
import static org.bytedeco.systems.global.windows.*;
@Properties(inherit = org.bytedeco.systems.presets.windows.class)
public class PERFORMANCE_INFORMATION extends Pointer {
static { Loader.load(); }
/** Default native constructor. */
public PERFORMANCE_INFORMATION() { super((Pointer)null); allocate(); }
/** Native array allocator. Access with {@link Pointer#position(long)}. */
public PERFORMANCE_INFORMATION(long size) { super((Pointer)null); allocateArray(size); }
/** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */
public PERFORMANCE_INFORMATION(Pointer p) { super(p); }
private native void allocate();
private native void allocateArray(long size);
@Override public PERFORMANCE_INFORMATION position(long position) {
return (PERFORMANCE_INFORMATION)super.position(position);
}
@Override public PERFORMANCE_INFORMATION getPointer(long i) {
return new PERFORMANCE_INFORMATION((Pointer)this).offsetAddress(i);
}
public native @Cast("DWORD") int cb(); public native PERFORMANCE_INFORMATION cb(int setter);
public native @Cast("SIZE_T") long CommitTotal(); public native PERFORMANCE_INFORMATION CommitTotal(long setter);
public native @Cast("SIZE_T") long CommitLimit(); public native PERFORMANCE_INFORMATION CommitLimit(long setter);
public native @Cast("SIZE_T") long CommitPeak(); public native PERFORMANCE_INFORMATION CommitPeak(long setter);
public native @Cast("SIZE_T") long PhysicalTotal(); public native PERFORMANCE_INFORMATION PhysicalTotal(long setter);
public native @Cast("SIZE_T") long PhysicalAvailable(); public native PERFORMANCE_INFORMATION PhysicalAvailable(long setter);
public native @Cast("SIZE_T") long SystemCache(); public native PERFORMANCE_INFORMATION SystemCache(long setter);
public native @Cast("SIZE_T") long KernelTotal(); public native PERFORMANCE_INFORMATION KernelTotal(long setter);
public native @Cast("SIZE_T") long KernelPaged(); public native PERFORMANCE_INFORMATION KernelPaged(long setter);
public native @Cast("SIZE_T") long KernelNonpaged(); public native PERFORMANCE_INFORMATION KernelNonpaged(long setter);
public native @Cast("SIZE_T") long PageSize(); public native PERFORMANCE_INFORMATION PageSize(long setter);
public native @Cast("DWORD") int HandleCount(); public native PERFORMANCE_INFORMATION HandleCount(int setter);
public native @Cast("DWORD") int ProcessCount(); public native PERFORMANCE_INFORMATION ProcessCount(int setter);
public native @Cast("DWORD") int ThreadCount(); public native PERFORMANCE_INFORMATION ThreadCount(int setter);
}
| 61.638298 | 129 | 0.764929 |
02dbbc1d33d5b7c4819a4294cdb87dffee2d5789 | 1,115 | package org.chuanshen.devladder.service;
import org.chuanshen.devladder.mapper.PositionMapper;
import org.chuanshen.devladder.model.Position;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.List;
/**
* @Auther: Chuan Shen
* @Date: 2020/5/22 10:31
* @Description:
**/
@Service
public class PositionService {
@Autowired
PositionMapper positionMapper;
public List<Position> getAllPositions() {
return positionMapper.getAllPos();
}
public Integer addPosition(Position position) {
position.setEnabled(true);
position.setCreateDate(new Date());
return positionMapper.addPos(position);
}
public Integer updatePosition(Position position) {
return positionMapper.updateByPrimaryKeySelective(position);
}
public Integer deletePositionById(Integer id) {
return positionMapper.deleteByPrimaryKey(id);
}
public Integer deletePositionsByIds(Integer[] ids) {
return positionMapper.deletePositionsByIds(ids);
}
}
| 25.930233 | 68 | 0.730942 |
d3a0f52ad8cc2892038208a23346b0691611c0b4 | 748 | package com.vivi.gulimall.product;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableCaching
@EnableTransactionManagement
@EnableFeignClients(basePackages = "com.vivi.gulimall.product.feign")
@EnableDiscoveryClient
@SpringBootApplication
public class GulimallProductApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallProductApplication.class, args);
}
}
| 32.521739 | 78 | 0.858289 |
b5d00995151c5f23c090b138ea64ba36b48d051e | 1,877 | /**
* Copyright 2019 Airbnb. Licensed under Apache-2.0. See LICENSE in the project root for license
* information.
*/
package com.airbnb.dynein.scheduler;
import com.airbnb.dynein.common.job.JobSpecTransformer;
import com.airbnb.dynein.common.token.TokenManager;
import com.airbnb.dynein.scheduler.Schedule.JobStatus;
import com.airbnb.dynein.scheduler.metrics.Metrics;
import java.time.Clock;
import java.time.Instant;
import java.util.concurrent.CompletableFuture;
public class NoOpScheduleManager extends ScheduleManager {
public NoOpScheduleManager(
int maxShardId,
TokenManager tokenManager,
JobSpecTransformer jobSpecTransformer,
Clock clock,
Metrics metrics) {
super(maxShardId, tokenManager, jobSpecTransformer, clock, metrics);
}
@Override
public CompletableFuture<Void> recoverStuckJobs(String partition, Instant instant) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Void> addJob(Schedule schedule) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Schedule> getJob(String token) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Void> deleteJob(String token) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<SchedulesQueryResponse> getOverdueJobs(
String partition, Instant instant) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Schedule> updateStatus(
Schedule schedule, JobStatus oldStatus, JobStatus newStatus) {
return CompletableFuture.completedFuture(null);
}
@Override
public CompletableFuture<Void> deleteDispatchedJob(Schedule schedule) {
return CompletableFuture.completedFuture(null);
}
@Override
public void close() {}
}
| 28.439394 | 96 | 0.770911 |
535d7d9b0f1301d6e03823c054e825853286c52d | 2,677 | package br.com.investira.access.services;
import javax.servlet.http.HttpServletResponse;
import br.com.dbsoft.crud.DBSCrud;
import br.com.dbsoft.error.DBSIOException;
import br.com.dbsoft.message.IDBSMessage;
import br.com.dbsoft.message.IDBSMessages;
import br.com.dbsoft.service.DBSBaseService;
import br.com.dbsoft.util.DBSObject;
import br.com.investira.access.AccessMessages;
public class AbstractService extends DBSBaseService {
protected String wClientToken;
protected final String PATH_V1 = "/api/v1";
//METODOS PUBLICOS ===================================================
//METODOS PROTEGIDOS ==================================================
//Erros-----------------
protected void prGenericError(DBSIOException pException) {
wLogger.error(pException);
getMessages().add(AccessMessages.ErroGenerico);
setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
/**
* Adiciona uma mensagem e configura o HTTP StatusCode para a resposta.
* @param pMessage
*/
protected void prAddMessage(IDBSMessage pMessage) {
if (DBSObject.isNull(pMessage)) {
getMessages().add(AccessMessages.ErroGenerico);
} else {
getMessages().add(pMessage);
}
setStatus(getMessages().getListMessageBase().get(0).getStatusCode());
}
protected void prAddMessages(IDBSMessages pMessages) {
if (DBSObject.isNull(pMessages) || DBSObject.isEmpty(pMessages.getListMessage())) {
getMessages().add(AccessMessages.ErroGenerico);
} else {
getMessages().addAll(pMessages);
}
setStatus(getMessages().getListMessageBase().get(0).getStatusCode());
}
protected void prGenericError(DBSIOException pException, IDBSMessage pMessage) {
wLogger.error(pException);
prAddMessage(pMessage);
}
protected void prGenericError(DBSIOException pException, DBSCrud<?> pCrud) {
prGenericError(pException);
pvGenericErrorCrud(pCrud);
}
protected void prGenericError(DBSIOException pException, IDBSMessage pMessage, DBSCrud<?> pCrud) {
prGenericError(pException, pMessage);
pvGenericErrorCrud(pCrud);
}
protected void prGenericError(DBSIOException pException, IDBSMessage pMessage, IDBSMessages pMessages) {
getMessages().clear();
prGenericError(pException, pMessage);
getMessages().addAll(pMessages);
}
protected void prGenericError(IDBSMessage pMessage, IDBSMessages pCrudMessages) {
prAddMessage(pMessage);
getMessages().addAll(pCrudMessages);
}
//METODOS PRIVADOS ===================================================================
private void pvGenericErrorCrud(DBSCrud<?> pCrud) {
if (!DBSObject.isNull(pCrud) && pCrud.getMessages().hasErrorsMessages()) {
getMessages().addAll(pCrud.getMessages());
}
}
}
| 32.253012 | 105 | 0.714606 |
ea33ebf764f1f50c6f7895bfb471bd7b431dc2cb | 5,374 | /*
* Copyright (C) 2016 The Android Open Source Project
*
* 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.android.systemui.doze;
import android.app.AlarmManager;
import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.text.format.Formatter;
import android.util.Log;
import com.android.systemui.util.wakelock.WakeLock;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* The policy controlling doze.
*/
public class DozeUi implements DozeMachine.Part {
private static final long TIME_TICK_DEADLINE_MILLIS = 90 * 1000; // 1.5min
private final Context mContext;
private final AlarmManager mAlarmManager;
private final DozeHost mHost;
private final Handler mHandler;
private final WakeLock mWakeLock;
private final DozeMachine mMachine;
private final AlarmManager.OnAlarmListener mTimeTick;
private boolean mTimeTickScheduled = false;
private long mLastTimeTickElapsed = 0;
public DozeUi(Context context, AlarmManager alarmManager, DozeMachine machine,
WakeLock wakeLock, DozeHost host, Handler handler) {
mContext = context;
mAlarmManager = alarmManager;
mMachine = machine;
mWakeLock = wakeLock;
mHost = host;
mHandler = handler;
mTimeTick = this::onTimeTick;
}
private void pulseWhileDozing(int reason) {
mHost.pulseWhileDozing(
new DozeHost.PulseCallback() {
@Override
public void onPulseStarted() {
mMachine.requestState(DozeMachine.State.DOZE_PULSING);
}
@Override
public void onPulseFinished() {
mMachine.requestState(DozeMachine.State.DOZE_PULSE_DONE);
}
}, reason);
}
@Override
public void transitionTo(DozeMachine.State oldState, DozeMachine.State newState) {
switch (newState) {
case DOZE_AOD:
scheduleTimeTick();
break;
case DOZE:
case DOZE_AOD_PAUSED:
unscheduleTimeTick();
break;
case DOZE_REQUEST_PULSE:
pulseWhileDozing(mMachine.getPulseReason());
break;
case DOZE_PULSE_DONE:
mHost.abortPulsing();
case INITIALIZED:
mHost.startDozing();
break;
case FINISH:
mHost.stopDozing();
unscheduleTimeTick();
break;
}
mHost.setAnimateWakeup(shouldAnimateWakeup(newState));
}
private boolean shouldAnimateWakeup(DozeMachine.State state) {
switch (state) {
case DOZE_AOD:
case DOZE_REQUEST_PULSE:
case DOZE_PULSING:
case DOZE_PULSE_DONE:
return true;
default:
return false;
}
}
private void scheduleTimeTick() {
if (mTimeTickScheduled) {
return;
}
long delta = roundToNextMinute(System.currentTimeMillis()) - System.currentTimeMillis();
mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + delta, "doze_time_tick", mTimeTick, mHandler);
mTimeTickScheduled = true;
mLastTimeTickElapsed = SystemClock.elapsedRealtime();
}
private void unscheduleTimeTick() {
if (!mTimeTickScheduled) {
return;
}
verifyLastTimeTick();
mAlarmManager.cancel(mTimeTick);
}
private void verifyLastTimeTick() {
long millisSinceLastTick = SystemClock.elapsedRealtime() - mLastTimeTickElapsed;
if (millisSinceLastTick > TIME_TICK_DEADLINE_MILLIS) {
String delay = Formatter.formatShortElapsedTime(mContext, millisSinceLastTick);
DozeLog.traceMissedTick(delay);
Log.e(DozeMachine.TAG, "Missed AOD time tick by " + delay);
}
}
private long roundToNextMinute(long timeInMillis) {
Calendar calendar = GregorianCalendar.getInstance();
calendar.setTimeInMillis(timeInMillis);
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.add(Calendar.MINUTE, 1);
return calendar.getTimeInMillis();
}
private void onTimeTick() {
if (!mTimeTickScheduled) {
// Alarm was canceled, but we still got the callback. Ignore.
return;
}
verifyLastTimeTick();
mHost.dozeTimeTick();
// Keep wakelock until a frame has been pushed.
mHandler.post(mWakeLock.wrap(() -> {}));
mTimeTickScheduled = false;
scheduleTimeTick();
}
}
| 31.798817 | 96 | 0.625605 |
9104781a4ae373101441a0856de22bc88c6ef8f0 | 562 | package uk.gov.hmcts.reform.fpl.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import uk.gov.hmcts.reform.fpl.model.common.DocumentReference;
@Data
@Builder(toBuilder = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PlacementConfidentialDocument {
private PlacementDocumentType type;
private DocumentReference document;
private String description;
public enum PlacementDocumentType {
ANNEX_B,
GUARDIANS_REPORT,
OTHER_CONFIDENTIAL_DOCUMENTS
}
}
| 25.545455 | 62 | 0.775801 |
31f652ba4b302132923f299c1cdfe21a86ed2134 | 1,618 | /*******************************************************************************
* Copyright (c) 2017 Sierra Wireless and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.html.
*
* Contributors:
* Sierra Wireless - initial API and implementation
*******************************************************************************/
package org.eclipse.leshan.server.cluster.serialization;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.eclipse.leshan.Link;
import org.eclipse.leshan.core.response.DiscoverResponse;
import org.eclipse.leshan.core.response.LwM2mResponse;
import org.junit.Test;
import com.eclipsesource.json.JsonObject;
public class ResponseSerDesTest {
@Test
public void ser_and_des_discover_response() throws Exception {
Link[] objs = new Link[2];
Map<String, Object> att = new HashMap<>();
att.put("ts", 12);
att.put("rt", "test");
objs[0] = new Link("/0/1024/2", att);
objs[1] = new Link("/0/2");
DiscoverResponse dr = DiscoverResponse.success(objs);
JsonObject obj = ResponseSerDes.jSerialize(dr);
LwM2mResponse dr2 = ResponseSerDes.deserialize(obj);
assertEquals(dr.toString(), dr2.toString());
}
}
| 33.708333 | 81 | 0.659456 |
126b0c5378761deb92248f9a770f9b52ea2f621d | 623 | package pl.kbeliczynski.salonik_bella.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserRoleEndpoint {
private UserRoleRepository userRoleRepository;
@Autowired
public UserRoleEndpoint(UserRoleRepository userRoleRepository) {
this.userRoleRepository = userRoleRepository;
}
@GetMapping("/api/roles")
public List<UserRole> getAll(){
return userRoleRepository.findAll();
}
}
| 27.086957 | 68 | 0.772071 |
e382be351c1cd71b35f2ab38332fab3e15287989 | 24,818 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.optaplanner.training.workerrostering.persistence;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.optaplanner.persistence.common.api.domain.solution.SolutionFileIO;
import org.optaplanner.training.workerrostering.domain.Employee;
import org.optaplanner.training.workerrostering.domain.Roster;
import org.optaplanner.training.workerrostering.domain.RosterParametrization;
import org.optaplanner.training.workerrostering.domain.ShiftAssignment;
import org.optaplanner.training.workerrostering.domain.Skill;
import org.optaplanner.training.workerrostering.domain.Spot;
import org.optaplanner.training.workerrostering.domain.TimeSlot;
import org.optaplanner.training.workerrostering.domain.TimeSlotState;
public class WorkerRosteringSolutionFileIO implements SolutionFileIO<Roster> {
public static final DateTimeFormatter DATE_TIME_FORMATTER
= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm", Locale.ENGLISH);
public static final DateTimeFormatter DAY_FORMATTER
= DateTimeFormatter.ofPattern("EEE dd-MMM", Locale.ENGLISH);
public static final DateTimeFormatter TIME_FORMATTER
= DateTimeFormatter.ofPattern("HH:mm", Locale.ENGLISH);
private static final IndexedColors NON_EXISTING_COLOR = IndexedColors.GREY_80_PERCENT;
private static final IndexedColors LOCKED_BY_USER_COLOR = IndexedColors.VIOLET;
private static final IndexedColors UNAVAILABLE_COLOR = IndexedColors.BLUE_GREY;
@Override
public String getInputFileExtension() {
return "xlsx";
}
@Override
public String getOutputFileExtension() {
return "xlsx";
}
@Override
public Roster read(File inputSolutionFile) {
Workbook workbook;
try (InputStream in = new BufferedInputStream(new FileInputStream(inputSolutionFile))) {
workbook = new XSSFWorkbook(in);
return new RosterReader(workbook).readRoster();
} catch (IOException | RuntimeException e) {
throw new IllegalStateException("Failed reading inputSolutionFile ("
+ inputSolutionFile + ") to create a roster.", e);
}
}
private static class RosterReader {
private final Workbook workbook;
public RosterReader(Workbook workbook) {
this.workbook = workbook;
}
public Roster readRoster() {
RosterParametrization rosterParametrization = new RosterParametrization();
List<Skill> skillList = readListSheet("Skills", new String[]{"Name"}, (Row row) -> {
String name = row.getCell(0).getStringCellValue();
return new Skill(name);
});
Map<String, Skill> skillMap = skillList.stream().collect(Collectors.toMap(
Skill::getName, skill -> skill));
List<Spot> spotList = readListSheet("Spots", new String[]{"Name", "Required skill"}, (Row row) -> {
String name = row.getCell(0).getStringCellValue();
String requiredSkillName = row.getCell(1).getStringCellValue();
Skill requiredSkill = skillMap.get(requiredSkillName);
if (requiredSkill == null) {
throw new IllegalStateException("The requiredSkillName (" + requiredSkillName
+ ") does not exist in the skillList (" + skillList + ").");
}
return new Spot(name, requiredSkill);
});
Map<String, Spot> spotMap = spotList.stream().collect(Collectors.toMap(
Spot::getName, spot -> spot));
List<TimeSlot> timeSlotList = readListSheet("Timeslots", new String[]{"Start", "End", "State"}, (Row row) -> {
LocalDateTime startDateTime = LocalDateTime.parse(row.getCell(0).getStringCellValue(), DATE_TIME_FORMATTER);
LocalDateTime endDateTime = LocalDateTime.parse(row.getCell(1).getStringCellValue(), DATE_TIME_FORMATTER);
TimeSlot timeSlot = new TimeSlot(startDateTime, endDateTime);
timeSlot.setTimeSlotState(TimeSlotState.valueOf(row.getCell(2).getStringCellValue()));
return timeSlot;
});
List<Employee> employeeList = readListSheet("Employees", new String[]{"Name", "Skills"}, (Row row) -> {
String name = row.getCell(0).getStringCellValue();
Set<Skill> skillSet = Arrays.stream(row.getCell(1).getStringCellValue().split(",")).map((skillName) -> {
Skill skill = skillMap.get(skillName);
if (skill == null) {
throw new IllegalStateException("The skillName (" + skillName
+ ") does not exist in the skillList (" + skillList + ").");
}
return skill;
}).collect(Collectors.toSet());
Employee employee = new Employee(name, skillSet);
employee.setUnavailableTimeSlotSet(new LinkedHashSet<>());
return employee;
});
Map<String, Employee> employeeMap = employeeList.stream().collect(Collectors.toMap(
Employee::getName, employee -> employee));
List<ShiftAssignment> shiftAssignmentList = readGridSheet("Spot roster", new String[]{"Name"}, (Row row) -> {
String spotName = row.getCell(0).getStringCellValue();
Spot spot = spotMap.get(spotName);
if (spot == null) {
throw new IllegalStateException("The spotName (" + spotName
+ ") does not exist in the spotList (" + spotList + ").");
}
return spot;
}, timeSlotList, (Pair<Spot, TimeSlot> pair, Cell cell) -> {
if (hasStyle(cell, NON_EXISTING_COLOR)) {
return null;
}
ShiftAssignment shiftAssignment = new ShiftAssignment(pair.getKey(), pair.getValue());
if (hasStyle(cell, LOCKED_BY_USER_COLOR)) {
shiftAssignment.setLockedByUser(true);
}
String employeeName = cell.getStringCellValue();
if (employeeName.isEmpty()) {
throw new IllegalStateException("The sheet (Spot roster), has a cell ("
+ cell.getRowIndex() + "," + cell.getColumnIndex() + ") which does not contain ? or an employeeName.");
}
if (employeeName.equals("?")) {
shiftAssignment.setEmployee(null);
} else {
Employee employee = employeeMap.get(employeeName);
if (employee == null) {
throw new IllegalStateException("The sheet (Spot roster), has a cell ("
+ cell.getRowIndex() + "," + cell.getColumnIndex()
+ ") with an employeeName (" + employeeName
+ ") that does not exist in the employeeList (" + employeeList + ").");
}
shiftAssignment.setEmployee(employee);
}
return shiftAssignment;
});
readGridSheet("Employee roster", new String[]{"Name"}, (Row row) -> {
String employeeName = row.getCell(0).getStringCellValue();
Employee employee = employeeMap.get(employeeName);
if (employee == null) {
throw new IllegalStateException("The employeeName (" + employeeName
+ ") does not exist in the employeeList (" + employeeList + ").");
}
return employee;
}, timeSlotList, (Pair<Employee, TimeSlot> pair, Cell cell) -> {
if (hasStyle(cell, UNAVAILABLE_COLOR)) {
Employee employee = pair.getKey();
TimeSlot timeSlot = pair.getValue();
employee.getUnavailableTimeSlotSet().add(timeSlot);
}
return null;
});
return new Roster(rosterParametrization,
skillList, spotList, timeSlotList, employeeList,
shiftAssignmentList);
}
private <E> List<E> readListSheet(String sheetName, String[] headerTitles,
Function<Row, E> rowMapper) {
Sheet sheet = workbook.getSheet(sheetName);
if (sheet == null) {
throw new IllegalStateException("The workbook does not contain a sheet with name ("
+ sheetName + ").");
}
Row headerRow = sheet.getRow(1);
if (headerRow == null) {
throw new IllegalStateException("The sheet (" + sheetName + ") has no header data at row (1).");
}
int columnNumber = 0;
for (String headerTitle : headerTitles) {
Cell cell = headerRow.getCell(columnNumber);
if (cell == null) {
throw new IllegalStateException("The sheet (" + sheetName + ") at header cell ("
+ cell.getRowIndex() + "," + cell.getColumnIndex()
+ ") does not contain the headerTitle (" + headerTitle + ").");
}
if (!cell.getStringCellValue().equals(headerTitle)) {
throw new IllegalStateException("The sheet (" + sheetName + ") at header cell ("
+ cell.getRowIndex() + "," + cell.getColumnIndex()
+ ") does not contain the headerTitle (" + headerTitle
+ "), it contains cellValue (" + cell.getStringCellValue() + ") instead.");
}
columnNumber++;
}
List<E> elementList = new ArrayList<>(sheet.getLastRowNum() - 2);
for (int i = 2; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
for (int j = 0; j < headerTitles.length; j++) {
Cell cell = row.getCell(j);
if (cell == null) {
throw new IllegalStateException("The sheet (" + sheetName
+ ") has no cell for " + headerTitles[j]
+ " at row (" + i + ") at column (" + j + ").");
}
}
elementList.add(rowMapper.apply(row));
}
return elementList;
}
private <E, F> List<F> readGridSheet(String sheetName, String[] headerTitles,
Function<Row, E> rowMapper, List<TimeSlot> timeSlotList,
BiFunction<Pair<E, TimeSlot>, Cell, F> cellMapper) {
readListSheet(sheetName, headerTitles, rowMapper);
Sheet sheet = workbook.getSheet(sheetName);
Row higherHeaderRow = sheet.getRow(0);
Row lowerHeaderRow = sheet.getRow(1);
int columnNumber = headerTitles.length;
for (TimeSlot timeSlot : timeSlotList) {
if (timeSlot.getStartDateTime().getHour() == 6) {
String expectedDayString = timeSlot.getStartDateTime().toLocalDate().format(DAY_FORMATTER);
Cell higherCell = higherHeaderRow.getCell(columnNumber);
if (higherCell == null) {
throw new IllegalStateException("The sheet (" + sheetName + ") at header cell ("
+ higherCell.getRowIndex() + "," + higherCell.getColumnIndex()
+ ") does not contain the date (" + expectedDayString + ").");
}
if (!higherCell.getStringCellValue().equals(expectedDayString)) {
throw new IllegalStateException("The sheet (" + sheetName + ") at header cell ("
+ higherCell.getRowIndex() + "," + higherCell.getColumnIndex()
+ ") does not contain the date (" + expectedDayString
+ "), it contains cellValue (" + higherCell.getStringCellValue() + ") instead.");
}
}
String expectedStartDateTimeString = timeSlot.getStartDateTime().format(TIME_FORMATTER);
Cell lowerCell = lowerHeaderRow.getCell(columnNumber);
if (lowerCell == null) {
throw new IllegalStateException("The sheet (" + sheetName + ") at header cell ("
+ lowerCell.getRowIndex() + "," + lowerCell.getColumnIndex()
+ ") does not contain the startDateTime (" + expectedStartDateTimeString + ").");
}
if (!lowerCell.getStringCellValue().equals(expectedStartDateTimeString)) {
throw new IllegalStateException("The sheet (" + sheetName + ") at header cell ("
+ lowerCell.getRowIndex() + "," + lowerCell.getColumnIndex()
+ ") does not contain the startDateTime (" + expectedStartDateTimeString
+ "), it contains cellValue (" + lowerCell.getStringCellValue() + ") instead.");
}
columnNumber++;
}
List<F> cellElementList = new ArrayList<>((sheet.getLastRowNum() - 2) * timeSlotList.size());
for (int i = 2; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
if (row == null) {
continue;
}
E rowElement = rowMapper.apply(row);
for (int j = 0; j < timeSlotList.size(); j++) {
TimeSlot timeSlot = timeSlotList.get(j);
Cell cell = row.getCell(headerTitles.length + j);
if (cell == null) {
throw new IllegalStateException("The sheet (" + sheetName
+ ") has no cell for " + headerTitles[j]
+ " at row (" + i + ") at column (" + j + ").");
}
F cellElement = cellMapper.apply(Pair.of(rowElement, timeSlot), cell);
if (cellElement != null) {
cellElementList.add(cellElement);
}
}
}
return cellElementList;
}
private boolean hasStyle(Cell cell, IndexedColors color) {
return cell.getCellStyle().getFillForegroundColor() == color.getIndex()
&& cell.getCellStyle().getFillPattern() == CellStyle.SOLID_FOREGROUND;
}
}
@Override
public void write(Roster roster, File outputSolutionFile) {
Workbook workbook = new RosterWriter(roster).writeWorkbook();
try (FileOutputStream out = new FileOutputStream(outputSolutionFile)) {
workbook.write(out);
} catch (IOException e) {
throw new IllegalStateException("Failed writing outputSolutionFile ("
+ outputSolutionFile + ") for roster (" + roster + ").", e);
}
}
private static class RosterWriter {
private final Roster roster;
private final Workbook workbook;
private final CellStyle headerStyle;
private final CellStyle nonExistingStyle;
private final CellStyle lockedByUserStyle;
private final CellStyle unavailableStyle;
public RosterWriter(Roster roster) {
this.roster = roster;
workbook = new XSSFWorkbook();
headerStyle = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBold(true);
headerStyle.setFont(font);
nonExistingStyle = createStyle(NON_EXISTING_COLOR);
lockedByUserStyle = createStyle(LOCKED_BY_USER_COLOR);
unavailableStyle = createStyle(UNAVAILABLE_COLOR);
}
public Workbook writeWorkbook() {
Map<Pair<Spot, TimeSlot>, ShiftAssignment> spotMap = roster.getShiftAssignmentList().stream()
.collect(Collectors.toMap(
shiftAssignment -> Pair.of(shiftAssignment.getSpot(), shiftAssignment.getTimeSlot()),
shiftAssignment -> shiftAssignment));
Map<Pair<Employee, TimeSlot>, List<ShiftAssignment>> employeeMap = roster.getShiftAssignmentList().stream()
.collect(Collectors.groupingBy(
shiftAssignment -> Pair.of(shiftAssignment.getEmployee(), shiftAssignment.getTimeSlot()),
Collectors.toList()));
writeGridSheet("Spot roster", new String[]{"Name"}, roster.getSpotList(), (Row row, Spot spot) -> {
row.createCell(0).setCellValue(spot.getName());
}, (Cell cell, Pair<Spot, TimeSlot> pair) -> {
ShiftAssignment shiftAssignment = spotMap.get(pair);
if (shiftAssignment == null) {
cell.setCellStyle(nonExistingStyle);
cell.setCellValue(" "); // TODO HACK to get a clearer xlsx file
return;
}
if (shiftAssignment.isLockedByUser()) {
cell.setCellStyle(lockedByUserStyle);
}
Employee employee = shiftAssignment.getEmployee();
if (employee == null) {
cell.setCellValue("?");
return;
}
cell.setCellValue(employee.getName());
});
writeGridSheet("Employee roster", new String[]{"Name"}, roster.getEmployeeList(), (Row row, Employee employee) -> {
row.createCell(0).setCellValue(employee.getName());
}, (Cell cell, Pair<Employee, TimeSlot> pair) -> {
Employee employee = pair.getKey();
TimeSlot timeSlot = pair.getValue();
if (employee.getUnavailableTimeSlotSet().contains(timeSlot)) {
cell.setCellStyle(unavailableStyle);
}
List<ShiftAssignment> shiftAssignmentList = employeeMap.get(pair);
if (shiftAssignmentList == null) {
cell.setCellValue(" "); // TODO HACK to get a clearer xlsx file
return;
}
cell.setCellValue(shiftAssignmentList.stream()
.map((shiftAssignment) -> shiftAssignment.getSpot().getName())
.collect(Collectors.joining(",")));
});
writeListSheet("Employees", new String[]{"Name", "Skills"}, roster.getEmployeeList(), (Row row, Employee employee) -> {
row.createCell(0).setCellValue(employee.getName());
row.createCell(1).setCellValue(employee.getSkillSet().stream()
.map(Skill::getName).collect(Collectors.joining(",")));
});
writeListSheet("Timeslots", new String[]{"Start", "End", "State"}, roster.getTimeSlotList(), (Row row, TimeSlot timeSlot) -> {
row.createCell(0).setCellValue(timeSlot.getStartDateTime().format(DATE_TIME_FORMATTER));
row.createCell(1).setCellValue(timeSlot.getEndDateTime().format(DATE_TIME_FORMATTER));
row.createCell(2).setCellValue(timeSlot.getTimeSlotState().name());
});
writeListSheet("Spots", new String[]{"Name", "Required skill"}, roster.getSpotList(), (Row row, Spot spot) -> {
row.createCell(0).setCellValue(spot.getName());
row.createCell(1).setCellValue(spot.getRequiredSkill().getName());
});
writeListSheet("Skills", new String[]{"Name"}, roster.getSkillList(), (Row row, Skill skill) -> {
row.createCell(0).setCellValue(skill.getName());
});
return workbook;
}
private <E> Sheet writeListSheet(String sheetName, String[] headerTitles, List<E> elementList,
BiConsumer<Row, E> rowConsumer) {
Sheet sheet = workbook.createSheet(sheetName);
sheet.setDefaultColumnWidth(20);
int rowNumber = 0;
sheet.createRow(rowNumber++); // Leave empty
Row headerRow = sheet.createRow(rowNumber++);
int columnNumber = 0;
for (String headerTitle : headerTitles) {
Cell cell = headerRow.createCell(columnNumber);
cell.setCellValue(headerTitle);
cell.setCellStyle(headerStyle);
columnNumber++;
}
sheet.createFreezePane(1, 2);
for (E element : elementList) {
Row row = sheet.createRow(rowNumber);
rowConsumer.accept(row, element);
rowNumber++;
}
return sheet;
}
private <E> void writeGridSheet(String sheetName, String[] headerTitles, List<E> rowElementList,
BiConsumer<Row, E> rowConsumer,
BiConsumer<Cell, Pair<E, TimeSlot>> cellConsumer) {
Sheet sheet = writeListSheet(sheetName, headerTitles, rowElementList, rowConsumer);
sheet.setDefaultColumnWidth(5);
sheet.createFreezePane(headerTitles.length, 2);
Row higherHeaderRow = sheet.getRow(0);
Row lowerHeaderRow = sheet.getRow(1);
int columnNumber = headerTitles.length;
for (TimeSlot timeSlot : roster.getTimeSlotList()) {
if (timeSlot.getStartDateTime().getHour() == 6) {
Cell cell = higherHeaderRow.createCell(columnNumber);
cell.setCellValue(timeSlot.getStartDateTime().toLocalDate().format(DAY_FORMATTER));
cell.setCellStyle(headerStyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, columnNumber, columnNumber + 2));
}
Cell cell = lowerHeaderRow.createCell(columnNumber);
cell.setCellValue(timeSlot.getStartDateTime().toLocalTime().format(TIME_FORMATTER));
cell.setCellStyle(headerStyle);
columnNumber++;
}
int rowNumber = 2;
for (E rowElement : rowElementList) {
Row row = sheet.getRow(rowNumber);
columnNumber = headerTitles.length;
for (TimeSlot timeSlot : roster.getTimeSlotList()) {
Cell cell = row.createCell(columnNumber);
cellConsumer.accept(cell, Pair.of(rowElement, timeSlot));
columnNumber++;
}
rowNumber++;
}
}
private CellStyle createStyle(IndexedColors color) {
CellStyle style = workbook.createCellStyle();
style.setFillForegroundColor(color.getIndex());
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
return style;
}
}
}
| 50.960986 | 138 | 0.569707 |
24f5686cc442aa317461894bdb58cd823a3ec9e6 | 1,318 | package com.tapiadevelopmentinc.firstgame;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class KeyInput extends KeyAdapter {
private Handler handler;
public KeyInput(Handler handler) {
this.handler = handler;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
System.out.println(key);
for(int i = 0; i < handler.object.size(); i++){
GameObject tempObject = handler.object.get(i);
if(tempObject.getID() == ID.Player){
//key events for player 1
if(key == KeyEvent.VK_W) tempObject.setVelY(-5);
if(key == KeyEvent.VK_S) tempObject.setVelY(5);
if(key == KeyEvent.VK_D) tempObject.setVelX(5);
if(key == KeyEvent.VK_A) tempObject.setVelX(-5);
}
}
if(key == KeyEvent.VK_ESCAPE) System.exit(1);
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
System.out.println(key);
for(int i = 0; i < handler.object.size(); i++){
GameObject tempObject = handler.object.get(i);
if(tempObject.getID() == ID.Player){
//key events for player 1
if(key == KeyEvent.VK_W) tempObject.setVelY(0);
if(key == KeyEvent.VK_S) tempObject.setVelY(0);
if(key == KeyEvent.VK_D) tempObject.setVelX(0);
if(key == KeyEvent.VK_A) tempObject.setVelX(0);
}
}
}
}
| 28.652174 | 53 | 0.64871 |
a49da967c57f5cfbfe786a2143a29796cf78270b | 1,246 | package edu.gwu.algorithms.dp.boxStack;
import java.util.HashSet;
//import java.util.List;
import java.util.List;
public class StackCreator {
List<Box> rotatedBoxes;
public StackCreator(List<Box> b){
rotatedBoxes = b;
}
public void stack(){
int[] height = new int[rotatedBoxes.size()];
HashSet<Integer> stacks[] = new HashSet[rotatedBoxes.size()];
for(int i = 0; i < rotatedBoxes.size(); i++){
HashSet hs = new HashSet();
hs.add(rotatedBoxes.get(i).getName());
height[i]=rotatedBoxes.get(i).getHeight();
stacks[i]=hs;
}
for (int i = 1; i < stacks.length; i++) {
for (int j = 0; j < i; j++) {
if (rotatedBoxes.get(i).getFace()[0] < rotatedBoxes.get(j).getFace()[0] &&
rotatedBoxes.get(i).getFace()[1] < rotatedBoxes.get(j).getFace()[1] &&
height[i] < height[j] + rotatedBoxes.get(i).getHeight())
{
stacks[i] = (HashSet)stacks[j].clone();
height[i]= height[j];
if(stacks[i].add(rotatedBoxes.get(i).getName()))
height[i]+=rotatedBoxes.get(i).getHeight();
}
}
}
int h=0;
int j=0;
for(int i=0;i<height.length;i++){
if(h<height[i]){
h=height[i];
j=i;
}
}
System.out.println("size:"+stacks[j].size());
System.out.println("height:"+h);
}
}
| 27.086957 | 78 | 0.609952 |
948369fac33a77dcb222e7093fb3081159aa5d00 | 412 | package com.lqg.service.impl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lqg.base.DaoSupportImpl;
import com.lqg.model.UploadFile;
import com.lqg.service.UploadFileService;
@Service(value = "uploadFileService")
@Transactional
public class UploadFileServiceImpl extends DaoSupportImpl<UploadFile> implements UploadFileService{
}
| 27.466667 | 99 | 0.84466 |
8661a1ab9c85528e4cc7f2f049dfadad72ab1589 | 302 | package pw.mr03.mapper;
import org.springframework.stereotype.Repository;
import pw.mr03.domain.dto.GetAdmin;
import pw.mr03.entity.Admin;
/**
* Created by Administrator on 2017/12/29.
*/
@Repository
public interface AdminMapper {
boolean insertAdmin(Admin admin);
GetAdmin getAdmin();
}
| 17.764706 | 49 | 0.751656 |
923fbcc9c64e92b6bd19f33d66376ad50408fe2f | 1,362 | package com.qxczh.common.dto;
import java.io.Serializable;
public class UploadResult implements Serializable{
/**
* 0表示成功 ,其余失败
*/
private Integer code;
/**
* 错误消息
*/
private String msg;
private Data data;
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public static class Data {
/**
* 路径
*/
private String src;
/**
* 名称
*/
private String title;
public String getSrc() {
return src;
}
public String getTitle() {
return title;
}
public Data(String src) {
this.src = src;
}
}
/**
* 成功的构造函数
* @param code
* @param data
*/
public UploadResult(Integer code, Data data) {
this.code = code;
this.data = data;
}
/**
* 失败的构造函数
* @param code
* @param msg
*/
public UploadResult(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
| 15.303371 | 51 | 0.489721 |
75832754dbc703495321040816dba700235216fa | 933 | package com.bridgefy.samples.twitter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.util.Log;
/**
* @author dekaru on 11/28/17.
*/
public class NetworkStateReceiver extends BroadcastReceiver {
private static String TAG = "NetworkStateReceiver";
public static String WIFI_STATE_CONNECTED = "WIFI_STATE_CONNECTED";
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
if (info != null && info.isConnected()) {
Log.i(TAG, "isConnected!");
LocalBroadcastManager.getInstance(context).sendBroadcast(
new Intent(WIFI_STATE_CONNECTED));
}
}
}
| 31.1 | 85 | 0.732047 |
af08d85b0ddaf4f3d9f707cf4ebac74956390595 | 16,551 | package org.abc.dash;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.CancellationException;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import org.abc.tools.ThreadedBrokerIterator;
import org.apache.ojb.broker.query.Criteria;
import org.apache.ojb.broker.query.Query;
import org.apache.ojb.broker.query.QueryByCriteria;
import com.follett.fsc.core.framework.persistence.BeanQuery;
import com.follett.fsc.core.framework.persistence.InsertQuery;
import com.follett.fsc.core.framework.persistence.UpdateQuery;
import com.follett.fsc.core.k12.beans.QueryIterator;
import com.follett.fsc.core.k12.beans.X2BaseBean;
import com.follett.fsc.core.k12.business.X2Broker;
import com.x2dev.utils.LoggerUtils;
/**
* This implements the BrokerDash (and all the X2Broker methods).
* <p>
* Certain calls are intercepted/optimized, and all other calls are
* delegated to an existing X2Broker.
* <p>
* This is implemented dynamically (using an InvocationHandler) because
* we assume methods will continue to be added to the X2Broker interface
* over time. If we created a class that actually implemented X2Broker:
* then our class would be missing methods as the X2Broker is enhanced over
* time. This approach, by contrast, should support new methods because
* it will just pass anything it doesn't recognize to its delegate.
* <p>
* Like all brokers: this object is not thread-safe; it should only
* be used on one thread at a time.
*/
class DashInvocationHandler implements InvocationHandler {
static RuntimeException constructionException;
static Method method_getIteratorByQuery;
static Method method_getBeanByQuery;
static Method method_getDash;
static Method method_clearCache;
static Method method_rollbackTransaction1;
static Method method_rollbackTransaction2;
static Method method_deleteBean;
static Method method_deleteBeanByOid;
static Method method_deleteByQuery;
static Method method_executeUpdateQuery;
static Method method_executeInsertQuery;
static Method method_getCollectionByQuery;
static Method method_getGroupedCollectionByQuery1;
static Method method_getGroupedCollectionByQuery2;
static Method method_getMapByQuery;
static Method method_getNestedMapByQuery1;
static Method method_getNestedMapByQuery2;
static Method method_getBeanByOid;
static boolean initialized = false;
static {
try {
method_getDash = BrokerDash.class.getMethod("getDash");
method_getIteratorByQuery = X2Broker.class.getMethod(
"getIteratorByQuery", Query.class);
method_getBeanByQuery = X2Broker.class.getMethod("getBeanByQuery",
Query.class);
method_clearCache = X2Broker.class.getMethod("clearCache");
method_rollbackTransaction1 = X2Broker.class
.getMethod("rollbackTransaction");
method_rollbackTransaction2 = X2Broker.class.getMethod(
"rollbackTransaction", Boolean.TYPE);
method_deleteBean = X2Broker.class.getMethod("deleteBean",
X2BaseBean.class);
method_deleteBeanByOid = X2Broker.class.getMethod(
"deleteBeanByOid", Class.class, String.class);
method_deleteByQuery = X2Broker.class.getMethod("deleteByQuery",
Query.class);
method_executeUpdateQuery = X2Broker.class.getMethod(
"executeUpdateQuery", UpdateQuery.class);
method_executeInsertQuery = X2Broker.class.getMethod(
"executeInsertQuery", InsertQuery.class);
method_getCollectionByQuery = X2Broker.class.getMethod(
"getCollectionByQuery", Query.class);
method_getGroupedCollectionByQuery1 = X2Broker.class.getMethod(
"getGroupedCollectionByQuery", Query.class, String.class,
Integer.TYPE);
method_getGroupedCollectionByQuery2 = X2Broker.class.getMethod(
"getGroupedCollectionByQuery", Query.class, String[].class,
new int[0].getClass());
method_getMapByQuery = X2Broker.class.getMethod("getMapByQuery",
Query.class, String.class, Integer.TYPE);
method_getNestedMapByQuery1 = X2Broker.class.getMethod(
"getNestedMapByQuery", Query.class, String.class,
String.class, Integer.TYPE, Integer.TYPE);
method_getNestedMapByQuery2 = X2Broker.class.getMethod(
"getNestedMapByQuery", Query.class, String[].class,
new int[0].getClass());
method_getBeanByOid = X2Broker.class.getMethod("getBeanByOid",
Class.class, String.class);
initialized = true;
} catch (Exception e) {
constructionException = new RuntimeException(
"An error occurred initializing the Dash cache architecture, so it is being deactivated.",
e);
}
}
X2Broker broker;
boolean active = initialized;
Dash dash;
/**
* Create a new DashInvocationHandler.
*
* @param broker the broker all requests are eventually passed to if we
* cannot optimize them.
* @param dash the Dash used to manage the cached layer/data.
*/
DashInvocationHandler(X2Broker broker, Dash dash) {
if (constructionException != null)
throw constructionException;
Objects.requireNonNull(broker);
Objects.requireNonNull(dash);
this.broker = broker;
this.dash = dash;
}
long lastPurge = -1;
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
ThreadedBrokerIterator.checkInterruptNoYield();
// The following purges (some) cached info every 30 seconds.
// This is NOT essential for the caches to drop elements.
// Every time either object (weakReferenceCache or cachePool)
// is used: it will also look to see if it can purge expired
// or unusable data.
// ... but where this might come handy is this scenario:
// If you've used weakReferenceCache and created a cache
// relating to SisStudents, and then you proceed to not
// call that particular cache (related to SisStudents) for
// a long time: we may benefit from explicitly purging that
// cache. If we do not: in a worst-case scenario that cache
// may keep a large number of Strings and unusable WeakReferences
// in memory.
long currentTime = System.currentTimeMillis();
long elapsed = currentTime - lastPurge;
if(elapsed>30000) {
dash.weakReferenceCache.purge();
dash.cachePool.purge();
lastPurge = currentTime;
}
Logger log = dash.getLog();
logMethod(Level.FINER, method, args, null);
// handle methods unique to the BrokerDash interface:
if (method_getDash.equals(method)) {
return dash;
} else if (method.getName().equals("setDashActive")) {
active = ((Boolean) args[0]).booleanValue();
return Void.TYPE;
} else if (method.getName().equals("isDashActive")) {
return active;
}
// if possible: intercept methods using our caching model/layer
if (active) {
try {
long t = System.currentTimeMillis();
Object returnValue = invokeCached(proxy, method, args);
t = System.currentTimeMillis() - t;
if ((t > 10 || returnValue!=null) && log != null && log.isLoggable(Level.FINEST)) {
logMethod(Level.FINEST, method, args, "(ended) "+returnValue);
}
return returnValue;
} catch(CancellationException e) {
throw e;
} catch (Exception e) {
Exception e2 = new Exception(
"An error occurred using the Dash cache architecture, so it is being deactivated.",
e);
UncaughtExceptionHandler ueh = dash.getUncaughtExceptionHandler();
if (ueh != null) {
ueh.uncaughtException(Thread.currentThread(), e2);
}
if (log != null && log.isLoggable(Level.WARNING))
log.warning(LoggerUtils.convertThrowableToString(e2));
active = false;
}
}
// ... if that fails: invoke the method without our caching
// model/layer:
long t = System.currentTimeMillis();
Object returnValue = method.invoke(broker, args);
t = System.currentTimeMillis() - t;
if ((t > 10 || returnValue!=null) && log != null && log.isLoggable(Level.FINEST)) {
logMethod(Level.FINEST, method, args, "(ended) "+returnValue);
}
return returnValue;
}
/**
* Invoke a method using the Dash caching model.
*/
@SuppressWarnings({ "rawtypes" })
protected Object invokeCached(Object proxy, Method method, Object[] args) throws Throwable {
// our first rule here should be: do no harm.
// So if someone passes null in as an argument: we should just skip
// over our caching implementation. If the parent broker wants to throw
// a NPE: that's great. But adding this broker implementation shouldn't
// risk breaking anything that existing brokers handle without complaint.
// If something doesn't explicitly return in these if-then clauses:
// then it falls to the bottom of this method that always defaults to
// delegating the method to the original X2broker.
if (method_getBeanByOid.equals(method)) {
Class beanType = (Class) args[0];
String beanOid = (String) args[1];
if(beanType!=null && beanOid!=null) {
X2BaseBean bean = dash.getBeanByOid(
beanType, beanOid);
if (bean != null)
return bean;
}
// convert to a BeanQuery to pass through other caching layers:
Criteria criteria = new Criteria();
criteria.addEqualTo(X2BaseBean.COL_OID, beanOid);
BeanQuery beanQuery = new BeanQuery(beanType, criteria);
try(QueryIterator iter = (QueryIterator) invoke(proxy, method_getIteratorByQuery, new Object[] { beanQuery })) {
if(iter.hasNext())
return iter.next();
return null;
}
} else if (method_getIteratorByQuery.equals(method)
&& Dash.isBeanQuery(args[0])) {
QueryByCriteria query = (QueryByCriteria) args[0];
if(query!=null) {
active = false;
try {
// use THIS broker (the proxy) just so we continue
// to benefit from potential logging
QueryIterator returnValue = dash.createQueryIterator(
(X2Broker) proxy, query);
return returnValue;
} finally {
active = true;
}
}
} else if (method_getBeanByQuery.equals(method)
&& Dash.isBeanQuery(args[0])) {
// pass through getIteratorByQuery to benefit from our caching
try (QueryIterator queryIter = (QueryIterator) invoke(proxy,
method_getIteratorByQuery, args)) {
if (queryIter.hasNext())
return (X2BaseBean) queryIter.next();
return null;
}
} else if (method_getCollectionByQuery.equals(method)
&& Dash.isBeanQuery(args[0])) {
// pass through getIteratorByQuery to benefit from our caching
try (QueryIterator queryIter = (QueryIterator) invoke(proxy,
method_getIteratorByQuery, args)) {
Collection<X2BaseBean> result = new ArrayList<>();
while (queryIter.hasNext()) {
ThreadedBrokerIterator.checkInterruptNoYield();
X2BaseBean bean = (X2BaseBean) queryIter.next();
result.add(bean);
}
return result;
}
} else if (method_getGroupedCollectionByQuery1.equals(method)
&& Dash.isBeanQuery(args[0])) {
String groupColumn = (String) args[1];
int initialMapSize = ((Integer) args[2]).intValue();
if(groupColumn!=null) {
Object[] newArgs = new Object[] { args[0],
new String[] { groupColumn },
new int[] { initialMapSize } };
return invoke(proxy, method_getGroupedCollectionByQuery2, newArgs);
}
} else if (method_getGroupedCollectionByQuery2.equals(method)
&& Dash.isBeanQuery(args[0])) {
QueryByCriteria query = (QueryByCriteria) args[0];
String[] columns = (String[]) args[1];
int[] mapSizes = (int[]) args[2];
if(query!=null && columns!=null && mapSizes!=null) {
return createNestedMap(proxy, query, columns, mapSizes, true);
}
} else if (method_getMapByQuery.equals(method)
&& Dash.isBeanQuery(args[0])) {
String keyColumn = (String) args[1];
int initialMapSize = ((Integer) args[2]).intValue() ;
if(keyColumn!=null) {
Object[] newArgs = new Object[] { args[0],
new String[] { keyColumn },
new int[] { initialMapSize } };
return invoke(proxy, method_getNestedMapByQuery2, newArgs);
}
} else if (method_getNestedMapByQuery1.equals(method)
&& Dash.isBeanQuery(args[0])) {
String outerKeyColumn = (String) args[1];
String innerKeyColumn = (String) args[2];
int initialOuterMapSize = ((Integer) args[3]).intValue();
int initialInnerMapSize = ((Integer) args[4]).intValue();
if(outerKeyColumn!=null && innerKeyColumn!=null) {
Object[] newArgs = new Object[] {
args[0],
new String[] { outerKeyColumn, innerKeyColumn },
new int[] { initialOuterMapSize, initialInnerMapSize} };
return invoke(proxy, method_getNestedMapByQuery2, newArgs);
}
} else if (method_getNestedMapByQuery2.equals(method)
&& Dash.isBeanQuery(args[0])) {
QueryByCriteria query = (QueryByCriteria) args[0];
String[] columns = (String[]) args[1];
int[] mapSizes = (int[]) args[2];
if(query!=null && columns!=null && mapSizes!=null) {
return createNestedMap(proxy, query, columns, mapSizes, false);
}
} else if (method_clearCache.equals(method)) {
dash.clearAll();
} else if (method_rollbackTransaction1.equals(method)
|| method_rollbackTransaction2.equals(method)) {
dash.clearModifiedBeanTypes();
} else if ((method_deleteBean.equals(method) || method.getName()
.startsWith("saveBean")) && args[0] instanceof X2BaseBean) {
X2BaseBean bean = (X2BaseBean) args[0];
if(bean!=null) {
Class t = bean.getClass();
dash.modifyBeanRecord(t);
}
} else if (method_deleteBeanByOid.equals(method)) {
Class beanType = (Class) args[0];
String beanOid = (String) args[1];
if(beanType!=null && beanOid!=null) {
dash.modifyBeanRecord(beanType);
}
} else if (method_deleteByQuery.equals(method)
|| method_executeUpdateQuery.equals(method)
|| method_executeInsertQuery.equals(method)) {
Query query = (Query) args[0];
if(query!=null) {
dash.modifyBeanRecord(query.getBaseClass());
}
}
Object returnValue = method.invoke(broker, args);
if (returnValue instanceof X2BaseBean) {
dash.storeBean((X2BaseBean) returnValue);
}
return returnValue;
}
private boolean logMethod(Level level, Method method, Object[] args,String suffix) {
Logger log = dash.getLog();
if(log==null || !log.isLoggable(level) || method.getName().equals("getPersistenceKey"))
return false;
if(suffix!=null) {
log.log(level, method.getName()+" "+suffix);
} else if (args == null || args.length == 0) {
log.log(level, method.getName());
} else {
Object[] argsCopy = new Object[args.length];
for(int a = 0; a<args.length; a++) {
if(args[a]!=null && args[a].getClass().isArray()) {
List<Object> list = new LinkedList<>();
int size = Array.getLength(args[a]);
for(int i = 0; i<size; i++) {
Object element = Array.get(args[a], i);
list.add(element);
}
argsCopy[a] = list;
} else {
argsCopy[a] = args[a];
}
}
log.log(level, method.getName() + " " + Arrays.asList(argsCopy));
}
return true;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private Object createNestedMap(Object proxy, QueryByCriteria beanQuery,
String[] columns, int[] mapSizes, boolean useLists)
throws Throwable {
// pass through getIteratorByQuery to benefit from our caching
try (QueryIterator queryIter = (QueryIterator) invoke(proxy,
method_getIteratorByQuery, new Object[] { beanQuery })) {
Map map = new HashMap(mapSizes[0]);
while (queryIter.hasNext()) {
ThreadedBrokerIterator.checkInterruptNoYield();
X2BaseBean bean = (X2BaseBean) queryIter.next();
Map currentMap = map;
for (int a = 0; a < columns.length; a++) {
// TODO: getFieldValueByBeanPath might invoke its own
// queries. We could instead use a ColumnQuery to
// include this in the query if needed
Object key = bean.getFieldValueByBeanPath(columns[a]);
if (a == columns.length - 1) {
if (useLists) {
List list = (List) currentMap.get(key);
if (list == null) {
list = new LinkedList();
currentMap.put(key, list);
}
list.add(bean);
} else {
currentMap.put(key, bean);
}
} else {
Map innerMap = (Map) currentMap.get(key);
if (innerMap == null) {
innerMap = new HashMap(mapSizes[a + 1]);
currentMap.put(key, innerMap);
}
currentMap = innerMap;
}
}
}
return map;
}
}
} | 36.536424 | 115 | 0.705516 |
5212a78e07ce061dfaad4c76b48b00aa80a4b7f3 | 3,143 | package com.amsavarthan.hify.adapters;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.view.ViewGroup;
import com.amsavarthan.hify.models.DrawerItem;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by amsavarthan on 29/3/18.
*/
public class DrawerAdapter extends RecyclerView.Adapter<DrawerAdapter.ViewHolder> {
private List<DrawerItem> items;
private Map<Class<? extends DrawerItem>, Integer> viewTypes;
private SparseArray<DrawerItem> holderFactories;
private OnItemSelectedListener listener;
public DrawerAdapter(List<DrawerItem> items) {
this.items = items;
this.viewTypes = new HashMap<>();
this.holderFactories = new SparseArray<>();
processViewTypes();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
ViewHolder holder = holderFactories.get(viewType).createViewHolder(parent);
holder.adapter = this;
return holder;
}
@Override
@SuppressWarnings("unchecked")
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
items.get(position).bindViewHolder(holder);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemCount() {
return items.size();
}
@Override
public int getItemViewType(int position) {
return viewTypes.get(items.get(position).getClass());
}
private void processViewTypes() {
int type = 0;
for (DrawerItem item : items) {
if (!viewTypes.containsKey(item.getClass())) {
viewTypes.put(item.getClass(), type);
holderFactories.put(type, item);
type++;
}
}
}
public void setSelected(int position) {
DrawerItem newChecked = items.get(position);
if (!newChecked.isSelectable()) {
return;
}
for (int i = 0; i < items.size(); i++) {
DrawerItem item = items.get(i);
if (item.isChecked()) {
item.setChecked(false);
notifyItemChanged(i);
break;
}
}
newChecked.setChecked(true);
notifyItemChanged(position);
if (listener != null) {
listener.onItemSelected(position);
}
}
public void setListener(OnItemSelectedListener listener) {
this.listener = listener;
}
public interface OnItemSelectedListener {
void onItemSelected(int position);
}
public static abstract class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private DrawerAdapter adapter;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
}
@Override
public void onClick(View v) {
adapter.setSelected(getAdapterPosition());
}
}
} | 26.191667 | 109 | 0.629017 |
2ea99b8361f2cf4a86ff83a23eef5ea5b13160d0 | 3,457 | public class BankAccount {
// There are two static variables that apply to all instances of BankAccount
private static double interestRate = 0.0375;
private static int masterAccountNumber = 1000;
// Instance variables
private double balance;
private String name;
private int accountNumber;
// CONSTRUCTORS ---------------------------------------------------
// Default constructor
public BankAccount() {
System.out.println("Default constructor called [BankAccount]");
balance = 0;
name = "";
accountNumber = masterAccountNumber;
masterAccountNumber++;
}
// Constructor that takes the starting balance and a name
public BankAccount(double bal, String name) {
System.out.println("double, String constructor called [BankAccount]");
balance = bal;
this.name = name;
accountNumber = masterAccountNumber;
masterAccountNumber++;
}
// END CONSTRUCTORS -----------------------------------------------
// ACCESSORS & MUTATORS -------------------------------------------
// balance
public double getBalance() {
return balance;
}
public void setBalance(double amt) {
balance = amt;
}
// name
public String getName() {
return name;
}
public void setName(String name) {
if (name.equals("null")) {
// some condition
System.out.println("Please choose a different name");
this.name = "ERROR";
} else {
this.name = name;
}
}
// accountNumber - only ACCESSOR
public int getAccountNumber() {
return accountNumber;
}
// interestRate
public static double getInterestRate() {
return interestRate;
}
public static void setInterestRate(double rate) {
interestRate = rate;
}
// END ACCESSORS & MUTATORS ---------------------------------------
// Overriding the 'toString()' method inherited from Object -------
public String toString() {
return getName() + " has $" + getBalance() + " and account number #" + getAccountNumber();
}
// END Overriding the 'toString()' method inherited from Object ---
// CLASS METHODS --------------------------------------------------
// Add 'amt' to 'balance'
// Check to see that 'amt' is positive
public void deposit(double amt) {
if (amt < 0) {
System.out.println("Amount must be greater than zero.");
return;
}
balance += amt;
System.out.println("The balance for account number " + accountNumber + " is $" + balance);
}
// Subtract 'amt' from 'balance'
// Check to see if 'amt' is greater than 'balance'
// Check to see that 'amt' is a positive number
public void withdraw(double amt) {
if (amt < 0) {
System.out.println("Amount must be greater than zero.");
return;
}
if (amt > balance) {
System.out.println("Insufficient funds");
return;
}
balance -= amt;
System.out.println("The balance for account number " + accountNumber + " is " + balance);
}
// Modify the balance by the 'interestRate'
public void accrueInterest() {
balance *= (1 + interestRate);
}
// END CLASS METHODS ----------------------------------------------
}
| 24.34507 | 98 | 0.538617 |
e32908cda072dc1a0f034cf553f872582cde4fd8 | 5,763 | package com.samourai.whirlpool.client.tx0;
import com.samourai.wallet.SamouraiWallet;
import com.samourai.wallet.api.backend.beans.UnspentResponse;
import com.samourai.wallet.segwit.SegwitAddress;
import com.samourai.wallet.segwit.bech32.Bech32Util;
import com.samourai.wallet.send.MyTransactionInput;
import com.samourai.wallet.send.MyTransactionOutPoint;
import com.samourai.wallet.util.FeeUtil;
import com.samourai.wallet.util.FormatsUtil;
import com.samourai.whirlpool.client.wallet.WhirlpoolWalletConfig;
import org.bitcoinj.core.Address;
import org.bitcoinj.core.Coin;
import org.bitcoinj.core.ECKey;
import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.core.Transaction;
import org.bitcoinj.core.TransactionOutPoint;
import org.bitcoinj.core.TransactionWitness;
import org.bitcoinj.crypto.TransactionSignature;
import org.bitcoinj.script.Script;
import org.bitcoinj.script.ScriptBuilder;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.math.BigInteger;
import java.util.Collection;
public class AndroidTx0Service extends Tx0Service {
private Logger log = LoggerFactory.getLogger(AndroidTx0Service.class.getSimpleName());
private final FeeUtil feeUtil = FeeUtil.getInstance();
public AndroidTx0Service(WhirlpoolWalletConfig config) {
super(config);
}
@Override
protected long computeTx0MinerFee(int nbPremix, long feeTx0, Collection<? extends UnspentResponse.UnspentOutput> spendFroms) {
int nbOutputsNonOpReturn = nbPremix + 2; // outputs + change + fee
int nbP2PKH = 0;
int nbP2SH = 0;
int nbP2WPKH = 0;
if (spendFroms != null) { // spendFroms can be NULL (for fee simulation)
for (UnspentResponse.UnspentOutput uo : spendFroms) {
if (Bech32Util.getInstance().isP2WPKHScript(uo.script)) {
nbP2WPKH++;
} else {
String address = new Script(Hex.decode(uo.script)).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString();
if (Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) {
nbP2SH++;
} else {
nbP2PKH++;
}
}
}
}
long tx0MinerFee = feeUtil.estimatedFeeSegwit(nbP2PKH, nbP2SH, nbP2WPKH, nbOutputsNonOpReturn, 1, feeTx0);
if (log.isDebugEnabled()) {
log.debug(
"tx0 minerFee: "
+ tx0MinerFee
+ "sats, totalBytes="
+ "b for nbPremix="
+ nbPremix
+ ", feeTx0="
+ feeTx0);
}
return tx0MinerFee;
}
@Override
protected void buildTx0Input(Transaction tx, UnspentOutputWithKey input, NetworkParameters params) {
ECKey spendFromKey = ECKey.fromPrivate(input.getKey());
TransactionOutPoint depositSpendFrom = input.computeOutpoint(params);
SegwitAddress segwitAddress = new SegwitAddress(spendFromKey.getPubKey(), params);
MyTransactionOutPoint _outpoint = new MyTransactionOutPoint(depositSpendFrom.getHash(), (int)depositSpendFrom.getIndex(), BigInteger.valueOf(depositSpendFrom.getValue().longValue()), segwitAddress.segWitRedeemScript().getProgram(), segwitAddress.getBech32AsString());
MyTransactionInput _input = new MyTransactionInput(params, null, new byte[0], _outpoint, depositSpendFrom.getHash().toString(), (int)depositSpendFrom.getIndex());
tx.addInput(_input);
}
@Override
protected void signTx0(Transaction tx, Collection<UnspentOutputWithKey> inputs, NetworkParameters params) {
int idx = 0;
for (UnspentOutputWithKey input : inputs) {
String address = input.addr;
ECKey spendFromKey = ECKey.fromPrivate(input.getKey());
// sign input
if(FormatsUtil.getInstance().isValidBech32(address) || Address.fromBase58(params, address).isP2SHAddress()) {
SegwitAddress segwitAddress = new SegwitAddress(spendFromKey.getPubKey(), params);
final Script redeemScript = segwitAddress.segWitRedeemScript();
final Script scriptCode = redeemScript.scriptCode();
TransactionSignature sig = tx.calculateWitnessSignature(idx, spendFromKey, scriptCode, Coin.valueOf(input.value), Transaction.SigHash.ALL, false);
final TransactionWitness witness = new TransactionWitness(2);
witness.setPush(0, sig.encodeToBitcoin());
witness.setPush(1, spendFromKey.getPubKey());
tx.setWitness(idx, witness);
if(!FormatsUtil.getInstance().isValidBech32(address) && Address.fromBase58(params, address).isP2SHAddress()) {
final ScriptBuilder sigScript = new ScriptBuilder();
sigScript.data(redeemScript.getProgram());
tx.getInput(idx).setScriptSig(sigScript.build());
// tx.getInput(idx).getScriptSig().correctlySpends(tx, idx, new Script(Hex.decode(input.script)), Coin.valueOf(input.value), Script.ALL_VERIFY_FLAGS);
}
}
else {
TransactionSignature sig = tx.calculateSignature(idx, spendFromKey, new Script(Hex.decode(input.script)), Transaction.SigHash.ALL, false);
tx.getInput(idx).setScriptSig(ScriptBuilder.createInputScript(sig, spendFromKey));
}
idx++;
}
super.signTx0(tx, inputs, params);
}
}
| 45.023438 | 275 | 0.658685 |
b145e5c447f99965df017dcbcc3322a1aacfc12a | 25,712 | package com.oliwen.util.mail;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import javax.mail.internet.MimeUtility;
import org.apache.commons.mail.EmailAttachment;
import org.apache.commons.mail.HtmlEmail;
/**
* @descript (邮件发送器)
* @author 李海涛
* @createTime 2016年11月16日上午9:57:09
* @version 1.0
*/
public class MailClient {
/**
* 邮箱服务器
*/
private String hostName;
/**
* 邮箱端口
*/
private String smtPort;
/**
* 邮箱用户名
*/
private String smtUsername;
/**
* 邮箱用户名
*/
private String smtPassword;
/**
* 邮箱昵称
*/
private String smtName;
public MailClient(String hostName, String smtPort, String smtUsername, String smtPassword, String smtName) {
this.hostName = hostName;
this.smtPort = smtPort;
this.smtUsername = smtUsername;
this.smtPassword = smtPassword;
this.smtName = smtName;
}
/**
*
* @descript (发送带附件的邮件)
* @author 李海涛
* @since 2016年11月16日上午10:42:31
* @param sendTo 接收人 (多个)
* @param title 邮件标题
* @param htmlMessage html格式的内容
* @param attachPath 附件地址
* @return success为成功 error为失败
*/
public String sendHtmlEmail(List<String> sendTo,String title,String htmlMessage,String attachPath) {
try {
HtmlEmail email = new HtmlEmail();
email.setHostName(this.hostName);
email.setSSL(true);
email.setSslSmtpPort(this.smtPort);
//邮件标题
email.setSubject(title);
email.setCharset("GB2312");
email.setAuthentication(this.smtUsername, this.smtPassword);
email.setFrom(this.smtName+"<"+this.smtUsername+">");
//发送附件
EmailAttachment attachment = null;
if(attachPath!=null && attachPath!=""){
String attachName=attachPath.substring(attachPath.lastIndexOf(File.separator)+1, attachPath.length());
attachment = new EmailAttachment();
try {
attachment.setPath(attachPath);
attachment.setName(MimeUtility.encodeText(attachName));
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription(attachName);
email.attach(attachment);
}catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
//循环将多个接收邮箱放入发送器
for(String aTo : sendTo){
email.addTo(aTo);
}
email.setHtmlMsg(htmlMessage);
email.send();
return "success";
} catch (Exception ee) {
ee.printStackTrace();
return "error";
}
}
/**
*
* @descript (发送不带附件的邮件)
* @author 李海涛
* @since 2016年11月16日上午10:42:31
* @param sendTo 接收人 (多个)
* @param title 邮件标题
* @param htmlMessage html格式的内容
* @return success为成功 error为失败
*/
public String sendHtmlEmail(List<String> sendTo,String title,String htmlMessage) {
return sendHtmlEmail(sendTo,title,htmlMessage,null);
}
public String sendHtmlEmail(String sendTo,String title,String htmlMessage) {
List<String> list=new ArrayList<>();
list.add(sendTo);
return sendHtmlEmail(list,title,htmlMessage,null);
}
public static void main(String[] args) {
MailClient mailClient = new MailClient("smtp.139.com","465","qiyihbo@139.com","18070156853hai","江西新云科技有限公司");
mailClient.sendHtmlEmail("1083573600@qq.com","您有新的邮件,请注意查收","<!DOCTYPE html>" +
"<html>" +
"<head>" +
"<meta charset=\"UTF-8\">" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=yes\" />" +
"<meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">" +
"<title>还款服务</title>" +
"<style>" +
"*{" +
"margin: 0px;" +
"padding: 0px;" +
"}" +
"body{" +
"height:100%;" +
"font-family:\"PingFang SC\",\"微软雅黑\",\"Helvetica Neue\",Helvetica,STHeiTi,sans-serif;" +
"font-weight:200;" +
"font-size:14px;" +
"color:#333;" +
"background:#F5F7F9;" +
"max-width:700px;" +
"margin: 0 auto;" +
"}" +
"main{" +
"background: #FFFFFF;" +
"margin-top: 7px;" +
"}" +
"ul, li{" +
"list-style: none;" +
"padding: 10px 0;" +
"}" +
"main li .content{" +
"height: 93px;" +
"margin: 0 15px;" +
"background: url(https://static.kdz6.cn/m.51kabao.cn/201901repay_service/card_cash.png) no-repeat center;" +
"background-size: cover;" +
"border-radius: 8px;" +
"}" +
"main li .content.card_cash{" +
"background-image: url(https://static.kdz6.cn/m.51kabao.cn/201901repay_service/card_cash.png);" +
"}" +
"main li .content.card_cash .left label{" +
"color: #9EE5D5;" +
"}" +
"main li .content.card_pay{" +
"background-image: url(https://static.kdz6.cn/m.51kabao.cn/201901repay_service/card_pay.png);" +
"}" +
"main li .content.card_pay .left label{" +
"color: #ABD4FF;" +
"}" +
"main li .content.card_date{" +
"background-image: url(https://static.kdz6.cn/m.51kabao.cn/201901repay_service/card_date.png);" +
"}" +
"main li .content.card_date .left label{" +
"color: #F6E5C7;" +
"}" +
"main li .content .left{" +
"float: left;" +
"width: calc(100% - 98px - 23px);" +
"padding: 22px 0 0 27px;" +
"box-sizing: border-box;" +
"}" +
"main li .content .left span{" +
"display: block;" +
"color: #FFFFFF;" +
"font-size: 17px;" +
"line-height: 24px;" +
"font-family: PingFangSC-Medium;" +
"}" +
"main li .content .left label{" +
"font-size: 14px;" +
"line-height: 20px;" +
"margin-top: 6.5px;" +
"}" +
"main li .content .right{" +
"width: 98px;" +
"float: right;" +
"margin-right: 23px;" +
"}" +
"main li .content .right button{" +
"height: 37px;" +
"width: 100%;" +
"color: #2C957D;" +
"background: #FFFFFF;" +
"border-radius: 20px;" +
"border: none;" +
"outline: none;" +
"margin: 28px auto;" +
"font-size: 14px;" +
"font-weight:200;" +
"line-height: 20px;" +
"box-shadow: 2.5px 2.5px #2C957D;" +
"}" +
"main dl{" +
"margin-top: 12px;" +
"}" +
"main dd{" +
"line-height: 20px;" +
"color: #999999;" +
"font-size: 14px;" +
"margin: 6px 0 6px 26.5px;" +
"}" +
"main dd label{" +
"width: 7px;" +
"height: 7px;" +
"line-height: 20px;" +
"display: inline-block;" +
"border-radius: 50%;" +
"background-color: #CBCBCB;" +
"vertical-align: top;" +
"margin: 6.5px 10.5px;" +
"}" +
"" +
"/**加载中loadding star*/" +
".loadding,.prompt{" +
"position: fixed;" +
"z-index: 1001;" +
"width: 100%;" +
"height: 100%;" +
"top: 0; " +
"display: none;" +
"}" +
".loadding .mask,.prompt .mask {" +
"position: fixed;" +
"top: 0;" +
"left: 0;" +
"right: 0;" +
"bottom: 0;" +
"background: rgba(0, 0, 0, .3);" +
"}" +
".loadding .loadding-content {" +
"position: absolute;" +
"top: 50%;" +
"left: 50%;" +
"transform: translate(-50%, -50%);" +
"text-align: center;" +
"background: rgba(0, 0, 0, .69);" +
"border-radius: 10px;" +
"padding: 2px 15px 20px;" +
"}" +
".loadding .loadding-content img{" +
"width: 70px;" +
"}" +
".loadding .loadding-content p{" +
"color: #fff;" +
"font-size: 13px;" +
"margin-top: -7px;" +
"}" +
"/**加载中loadding end*/" +
"/**prompt弹窗 star*/" +
".prompt .prompt-content{" +
"position: absolute;" +
"top: calc(50% - 50px);" +
"left: calc(50% - 120px);" +
"text-align: center;" +
"background: #fff;" +
"border-radius: 10px;" +
"width: 240px;" +
"height: 100px;" +
"overflow: hidden;" +
"}" +
".prompt .prompt-content span{" +
"display: block;" +
"width: 100%;" +
"padding: 20px 0px;" +
"height: 60px;" +
"box-sizing: border-box;" +
"font-weight: normal;" +
"}" +
".prompt .prompt-content .btns{" +
"bottom: 0px;" +
"left: 0;" +
"position: absolute;" +
"width: 100%;" +
"height: 40px;" +
"border-top: 1px solid #ccc;" +
"box-sizing: border-box;" +
"}" +
".prompt .prompt-content .btns button{" +
"width: 50%;" +
"padding: 10px 0;" +
"float: left;" +
"outline: none;" +
"border: none;" +
"height: 100%;" +
"background: #fff;" +
"}" +
".prompt .prompt-content .btns button:first-child{" +
"border-right: 1px solid #ccc;" +
"color: #666;" +
"}" +
"/**prompt弹窗 end*/" +
"" +
"/* toast提示 */" +
".toast {" +
"position: fixed;" +
"min-width: 144px;" +
"max-width: 280px;" +
"padding: 8px 12px;" +
"line-height: 26px;" +
"border-radius: 6px;" +
"font-size: 14px;" +
"text-align: center;" +
"background: rgba(102, 102, 102, 0.9);" +
"color: #fff;" +
"top: 50%;" +
"left: 50%;" +
"transform: translate(-50%, -50%);" +
"-webkit-transform: translate(-50%, -50%);" +
"z-index: 9999;" +
"}" +
"</style>" +
"</head>" +
"<body>" +
"<main>" +
"<ul>" +
"<li>" +
"<div class=\"content card_cash\" data-id=\"1\" style=\"background-image: url(https://static.kdz6.cn/m.51kabao.cn/201901repay_service/card_cash.png);\">" +
"<div class=\"left\">" +
"<span>信用卡取现</span>" +
"<label>省时省心 安全无忧</label>" +
"</div>" +
"<div class=\"right\">" +
"<button>立即取现</button>" +
"</div>" +
"</div>" +
"<dl>" +
"<dd><label></label>支持多家银行 实时到账 手续费低</dd>" +
"<dd><label></label>单日单卡最高可取现50000元</dd>" +
"</dl>" +
"</li>" +
"<li>" +
"<div class=\"content card_pay\" data-id=\"2\">" +
"<div class=\"left\">" +
"<span>信用卡代还</span>" +
"<label>快速缓解还款压力</label>" +
"</div>" +
"<div class=\"right\">" +
"<button>立即取现</button>" +
"</div>" +
"</div>" +
"<dl>" +
"<dd><label></label>手续费低 操作简单</dd>" +
"<dd><label></label>卡内仅需预留超低额度即可使用</dd>" +
"</dl>" +
"</li>" +
"<li>" +
"<div class=\"content card_date\" data-id=\"3\">" +
"<div class=\"left\">" +
"<span>信用分期</span>" +
"<label>取现 分期一次搞定</label>" +
"</div>" +
"<div class=\"right\">" +
"<button>立即取现</button>" +
"</div>" +
"</div>" +
"<dl>" +
"<dd><label></label>当日到账 最多可分12期还款</dd>" +
"<dd><label></label>无需另外偿还银行分期手续费</dd>" +
"</dl>" +
"</li>" +
"</ul>" +
"</main>" +
"" +
"<div class=\"loadding\">" +
"<div class=\"mask\"></div>" +
"<div class=\"loadding-content\">" +
" <img src=\"https://static.kdz6.cn/m.51kabao.cn/201901repay_service/load.gif\">" +
" <p>正在加载</p>" +
"</div>" +
"</div>" +
"<div class=\"prompt\">" +
"<div class=\"mask\"></div>" +
"<div class=\"prompt-content\">" +
"<span>请先完成身份证</span>" +
"<div class=\"btns\">" +
"<button onclick=\"hidePrompt();\">取消</button>" +
"<button class=\"goto\">前往认证</button>" +
"</div>" +
"</div>" +
"</div>" +
"<div style=\"display: none\">" +
"<script src=\"https://hm.baidu.com/hm.js?6c4b4dfb9e3898b66abab45e0be83cd6\"></script>" +
"<script src=\"https://s11.cnzz.com/z_stat.php?id=1261768606&web_id=1261768606\"></script>" +
"</div>" +
"</body>" +
"" +
"<script src=\"http://static.kdz6.cn/lib/crypto.js\"></script>" +
"<script src=\"http://static.kdz6.cn/lib/zepto.js\"></script>" +
"" +
"<script>" +
"function stat_click(key,url){" +
"try {" +
"if(_hmt){" +
"_hmt.push(['_trackEvent', '201901repay_service', key, 1]);" +
"$.ajax({url:\"https://zmi6.cn/ge2oxu\",data:{event:'201901repay_service'}});" +
"}" +
"} catch(e) {" +
"console.log(e)" +
"}" +
"}" +
"</script>" +
"<script language=\"javascript\">" +
"" +
"var ukey = getQueryString('ukey');" +
"var ugroupId = getQueryString('ugroupId');" +
"var lkey = \"\";" +
"var mobile = \"\"; //手机号码" +
"" +
"// 正式参数" +
"var baseUrl = 'http://sophora.dev.zmapi.cn/CMD/';" +
"var appId = '10761'; // 渠道ID" +
"var appKey = 'Q5i0dj9ZTe6ERwzj';" +
"" +
"var appVer = '230';" +
"var encode = 1; // 1-加密 0-不加密" +
"var authStep = 1;" +
"$(document).ready(function(){" +
"" +
"}); " +
"" +
"//立即取现/分期" +
"$(\"main li .content .right button\").click(function(){" +
"let that = $(this).parent().parent();" +
"alert($(that).attr(\"data-id\"));" +
"showLoadding();" +
"var params = {" +
"ukey: ukey," +
"appId: $(that).attr(\"data-id\")" +
"};" +
"//请求接口,判断用户是否已经认证" +
"postRequest(baseUrl + 'C.C.U.0.2', setParams(params, 'C.C.U.0.2'), function (data) {" +
"var data = JSON.parse(data);" +
"hideLoadding();" +
"if (data.code === 1) {" +
"mobile = data.data.mobile;" +
"authStep = data.data.state;" +
"if(data.data.state === 1){" +
"$(\".prompt .prompt-content span\").html(\"请先进行身份认证\");" +
"$(\".prompt .btns .goto\").html(\"前往认证\");" +
"$(\".prompt\").show();" +
"}else if(data.data.state === 2){" +
"$(\".prompt .prompt-content span\").html(\"使用信用分期需进行人脸识别\");" +
"$(\".prompt .btns .goto\").html(\"前往验证\");" +
"$(\".prompt\").show();" +
"}else if(data.data.state === 3){" +
"//加入统计" +
"stat_click($(that).find(\".left span\").text(),'');" +
"document.location.href = data.data.uri;" +
"}" +
"} else {" +
"toast(data.msg)" +
"}" +
"}) " +
"});" +
"" +
"//前往认证按钮" +
"$(\".prompt .btns .goto\").click(function(){" +
"if(authStep === 1){" +
"authIdCard();" +
"}else if(authStep === 2){" +
"authFace();" +
"}" +
"hidePrompt();" +
"});" +
"" +
"//设置参数" +
"function setParams(data, cmd) {" +
"data.g_lkey = lkey;" +
"data.g_encode = encode;" +
"data.g_time = new Date().getTime();" +
"data.ugroupId = 1; // 第三方应用标识" +
"var p = JSON.stringify(data)" +
"var token = cmd + '#' + p + '#' + appKey" +
"var k = appId + '.' + appVer + '.' + CryptoJS.SHA1(token)" +
"var form = {" +
"p: encode === 1 ? xorEncode(p, appKey) : p," +
"k: k," +
"cmd: cmd" +
"}" +
"return form" +
"}" +
"" +
"// 接口请求" +
"function postRequest(url, params, callback) {" +
"$.ajax({" +
"url: url," +
"type: 'POST'," +
"data: params," +
"dataType: 'text'," +
"success: function (data) {" +
"encode === 1 ? callback(xorDecode(data, appKey)) : callback(data)" +
"}," +
"error: function (data) {" +
"toast(data)" +
"}" +
"})" +
"}" +
"" +
"function showPrompt(){" +
"$(\".loadding\").hide();" +
"$(\".prompt\").show();" +
"$('.toast-box').remove();" +
"}" +
"function hidePrompt(){" +
"$(\".prompt\").hide();" +
"}" +
"" +
"function showLoadding(){" +
"$(\".prompt\").hide();" +
"$(\".loadding\").show();" +
"$('.toast-box').remove();" +
"}" +
"function hideLoadding(){" +
"$(\".loadding\").hide();" +
"}" +
"" +
"//跳转原生进行身份认证" +
"function authIdCard() {" +
"window.location.href = \"kabao://panda/id?mobile=\" + mobile + \"&ugroupId=\" + ugroupId +\"&callback=authCallBack\";" +
"}" +
"//调整原生进行人脸识别" +
"function authFace() {" +
"window.location.href = \"kabao://panda/face?mobile=\" + mobile + \"&ugroupId=\" + ugroupId +\"&callback=authCallBack\";" +
"}" +
"" +
"//认证成功后原生回调方法" +
"function authCallBack() {" +
"window.location.reload();" +
"}" +
"" +
"// 提示" +
"function toast(tips) {" +
"$('.toast-box').remove();" +
"var html = '<div class=\"toast-box\">' +" +
"'<div class=\"toast\">' +" +
"'<p>' + tips + '</p>' +" +
"'</div>' +" +
"'</div>';" +
"" +
"$('body').append(html);" +
"setTimeout(function () {" +
"$('.toast-box').remove();" +
"}, 1000);" +
"return;" +
"}" +
"" +
"//获取查询参数" +
"function getQueryString(name) {" +
"var reg = new RegExp(\"(^|&)\" + name + \"=([^&]*)(&|$)\", \"i\");" +
"var r = window.location.search.substr(1).match(reg);" +
"if (r != null) return unescape(r[2]);" +
"return null;" +
"}" +
"// 加密" +
"function xorEncode(str, key) {" +
"str = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str))" +
"var data = stringToByte(str)" +
"var keyData = stringToByte(key + '')" +
"var keyIndex = 0" +
"for (var x = 0; x < data.length; x++) {" +
"data[x] = (data[x] ^ keyData[keyIndex])" +
"if (++keyIndex === keyData.length) {" +
"keyIndex = 0" +
"}" +
"}" +
"str = byteToString(data)" +
"str = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str))" +
"return str" +
"}" +
"// 解密" +
"function xorDecode(str, key) {" +
"str = CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8)" +
"var data = stringToByte(str)" +
"var keyData = stringToByte(key + '')" +
"" +
"var keyIndex = 0" +
"for (var x = 0; x < data.length; x++) {" +
"data[x] = (data[x] ^ keyData[keyIndex])" +
"keyIndex += 1" +
"if (keyIndex === keyData.length) {" +
"keyIndex = 0" +
"}" +
"}" +
"str = byteToString(data)" +
"str = CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8)" +
"return str" +
"}" +
"" +
"function stringToByte(str) {" +
"var bytes = []" +
"var len, c" +
"len = str.length" +
"for (var i = 0; i < len; i++) {" +
"c = str.charCodeAt(i)" +
"if (c >= 0x010000 && c <= 0x10FFFF) {" +
"bytes.push(((c >> 18) & 0x07) | 0xF0)" +
"bytes.push(((c >> 12) & 0x3F) | 0x80)" +
"bytes.push(((c >> 6) & 0x3F) | 0x80)" +
"bytes.push((c & 0x3F) | 0x80)" +
"} else if (c >= 0x000800 && c <= 0x00FFFF) {" +
"bytes.push(((c >> 12) & 0x0F) | 0xE0)" +
"bytes.push(((c >> 6) & 0x3F) | 0x80)" +
"bytes.push((c & 0x3F) | 0x80)" +
"} else if (c >= 0x000080 && c <= 0x0007FF) {" +
"bytes.push(((c >> 6) & 0x1F) | 0xC0)" +
"bytes.push((c & 0x3F) | 0x80)" +
"} else {" +
"bytes.push(c & 0xFF)" +
"}" +
"}" +
"return bytes" +
"}" +
"" +
"function byteToString(arr) {" +
"if (typeof arr === 'string') {" +
"return arr" +
"}" +
"var str = ''" +
"var _arr = arr" +
"for (var i = 0; i < _arr.length; i++) {" +
"var one = _arr[i].toString(2)" +
"var v = one.match(/^1+?(?=0)/)" +
"if (v && one.length === 8) {" +
"var bytesLength = v[0].length" +
"var store = _arr[i].toString(2).slice(7 - bytesLength)" +
"for (var st = 1; st < bytesLength; st++) {" +
"store += _arr[st + i].toString(2).slice(2)" +
"}" +
"str += String.fromCharCode(parseInt(store, 2))" +
"i += bytesLength - 1" +
"} else {" +
"str += String.fromCharCode(_arr[i])" +
"}" +
"}" +
"return str" +
"}" +
"</script>" +
"</html>");
}
}
| 38.548726 | 171 | 0.37325 |
7bc271ceb3d721eb669ae4227f54296b3d177c7d | 2,619 | package com.springboot.bcode.api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.springboot.bcode.domain.video.Video;
import com.springboot.bcode.service.VideoService;
import com.springboot.common.exception.SystemException;
import com.springboot.core.web.mvc.BaseRest;
import com.springboot.core.web.mvc.ResponseResult;
/**
* 视频接口
*
* @Author: LCF
* @Date: 2020/1/2 16:13
* @Package: com.springboot.bcode.api
*/
@RestController
@RequestMapping(value = "/rest/video")
public class VideoRest extends BaseRest {
@Autowired
private VideoService videoService;
@RequestMapping(value = "/tiktok/list", method = RequestMethod.POST)
public ResponseResult list(@RequestBody Video vo) {
ResponseResult rep = new ResponseResult();
try {
rep.setResult(videoService.queryPage(vo));
} catch (SystemException e) {
rep.setCode(CODE_500);
rep.setMsg(e.getMessage());
} catch (Exception e) {
rep.setCode(CODE_500);
rep.setMsg("系统异常.请稍后再试");
}
return rep;
}
@RequestMapping(value = "/tiktok/upload", method = RequestMethod.POST)
public ResponseResult upload(MultipartFile file) {
ResponseResult rep = new ResponseResult();
try {
videoService.upload(file);
rep.setResult(file.getBytes());
} catch (SystemException e) {
rep.setCode(CODE_500);
rep.setMsg(e.getMessage());
} catch (Exception e) {
rep.setCode(CODE_500);
rep.setMsg(e.getMessage());
}
return rep;
}
@RequestMapping(value = "/tiktok/view")
public void video(@RequestParam("path") String path) {
videoService.view(path);
}
@RequestMapping(value = "/tiktok/delete")
public ResponseResult delete(@RequestParam("id") Integer id) {
ResponseResult rep = new ResponseResult();
try {
videoService.delete(id);
} catch (SystemException e) {
rep.setCode(CODE_500);
rep.setMsg(e.getMessage());
} catch (Exception e) {
rep.setCode(CODE_500);
rep.setMsg("系统异常.请稍后再试");
}
return rep;
}
}
| 31.939024 | 74 | 0.655594 |
609b86ae1fff02dc58113f969674e8f5e0542793 | 610 | package io.fairyproject.bukkit.plugin;
import io.fairyproject.bukkit.FairyBukkitPlatform;
import org.bukkit.plugin.java.JavaPlugin;
public class FairyInternalPlugin extends JavaPlugin {
@Override
public void onLoad() {
FairyBukkitPlatform.PLUGIN = this;
FairyBukkitPlatform.INSTANCE = new FairyBukkitPlatform(this.getDataFolder());
FairyBukkitPlatform.INSTANCE.load();
}
@Override
public void onEnable() {
FairyBukkitPlatform.INSTANCE.enable();
}
@Override
public void onDisable() {
FairyBukkitPlatform.INSTANCE.disable();
}
}
| 22.592593 | 85 | 0.704918 |
315451aa5b77021103c1be4014322580913b994a | 2,782 | package com.async.demo.service;
import com.async.demo.exception.RestException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestTemplate;
import java.io.IOException;
@Slf4j
@Service
public class RestServiceImpl implements RestService {
private RestTemplate restTemplate;
private ObjectMapper objectMapper;
@Async
@Override
public ListenableFuture<String> get(String URL) {
String responseBody = call(null, URL, HttpMethod.GET);
// ProductsServiceResponse productsServiceResponse = createResponse(responseBody, valueType);
return new AsyncResult<>(responseBody);
}
@Override
public String post(HttpEntity httpEntity, String URL) {
return call(httpEntity, URL, HttpMethod.POST);
}
public <T> T createResponse(String content, Class<T> valueType) throws RestException {
T response;
try {
response = objectMapper.readValue(content, valueType);
} catch (IOException ioEx) {
throw new RestException("Error while parsing JSON");
}
return response;
}
private String call(HttpEntity httpEntity, String URL, HttpMethod httpMethod) {
String responseBody;
ResponseEntity<String> responseEntity;
try {
responseEntity = restTemplate.exchange(URL, httpMethod, httpEntity,
new ParameterizedTypeReference<String>() {
});
responseBody = responseEntity.getBody();
} catch (ResourceAccessException reAEx) {
throw new RestException("Network error while calling service");
} catch (HttpServerErrorException ex) {
throw new RestException("Not a valid response from service");
} catch (Exception ex) {
throw new RestException("Fatal error occurred getting response from service");
}
return responseBody;
}
@Autowired
public RestServiceImpl(RestTemplate restTemplate, ObjectMapper objectMapper) {
this.restTemplate = restTemplate;
this.objectMapper = objectMapper;
}
}
| 37.093333 | 100 | 0.722861 |
798e31374abd088176e3526499d3e7dde0d145c2 | 225 | package cn.appsys.service.appcategory;
import java.util.List;
import cn.appsys.pojo.AppCategory;
public interface AppCategoryService {
public List<AppCategory> getAppCategoryListByParentId(Integer parentId);
}
| 20.454545 | 74 | 0.786667 |
eb5b2a48a9ff1e015fccc8a782287bb12cbf57d3 | 402 | package me.bristermitten.privatemines.listeners;
import me.bristermitten.privatemines.util.Util;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerQuitEvent;
public class UserLeaveEvent implements Listener {
@EventHandler
public void onLeave(PlayerQuitEvent event) {
Util.removeFromOnlinePlayers(event.getPlayer());
}
}
| 26.8 | 56 | 0.791045 |
98e50b7beddbb42004c30035bb4298bb554b30c6 | 1,526 | package com.lijun.demo1.task5;
import android.opengl.GLES20;
import android.opengl.GLSurfaceView;
import javax.microedition.khronos.opengles.GL10;
/**
* Creator: yiming
* FuncDesc: 渲染器类MyGLRenderer (openGL画笔)
* copyright ©2018-2020 Ququ Technology Corporation. All rights reserved.
*/
public class MyGLRenderer implements GLSurfaceView.Renderer {
private Triangle mTriangle;
/**
* @param type GLES20.GL_VERTEX_SHADER or GLES20.GL_FRAGMENT_SHADER
* @param shaderCode shader code string
* @return GLES20.glCreateShader(type)
*/
public static int loadShader(int type, String shaderCode) {
// create a vertex shader type (GLES20.GL_VERTEX_SHADER)
// or a fragment shader type (GLES20.GL_FRAGMENT_SHADER)
int shader = GLES20.glCreateShader(type);
// add the source code to the shader and compile it
GLES20.glShaderSource(shader, shaderCode);
GLES20.glCompileShader(shader);
return shader;
}
@Override
public void onSurfaceCreated(GL10 gl, javax.microedition.khronos.egl.EGLConfig config) {
mTriangle = new Triangle(); // 创建时初始化三角形实例
GLES20.glClearColor(-255.5f, 0.0f, 0.0f, 1.0f);
}
@Override
public void onDrawFrame(GL10 unused) {
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); // 每次都重绘背景
mTriangle.draw(); // 直接调用draw()方法
}
@Override
public void onSurfaceChanged(GL10 unused, int width, int height) {
GLES20.glViewport(0, 0, width, height);
}
} | 31.142857 | 92 | 0.688729 |
4f64d71fb6ef4a41d2d495f4181b781f562d0ffe | 7,782 |
package com.prowidesoftware.swift.model.mx.dic;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
/**
* Scope
* The Receiver of the MeetingInstruction or MeetingInstructionCancellationRequest sends the MeetingInstructionStatus message to the Sender of these messages.
* The message gives the status of a complete message or of one or more specific instructions within the message.
* Usage
* The MeetingInstructionStatus message is used for four purposes.
* First, it provides the status on the processing of a MeetingInstructionCancellationRequest message, ie, whether the request message is rejected or accepted.
* Second, it is used to provide a global processing or rejection status of a MeetingInstruction message.
* Third, it is used to provide a detailed processing or rejection status of a MeetingInstruction message, ie, for each instruction in the MeetingInstruction message the processing or rejection status is individually reported by using the InstructionIdentification element. This identification allows the receiver of the status message to link the status confirmation to its original instruction.
* The blocking of securities should be confirmed via an MT 508 (Intra-Position Advice).
* Fourth, it is used as a reminder to request voting instructions. This is done by indicating NONREF in the Identification element of the InstructionIdentification component and by using the status code NotReceived in the ProcessingStatus.
*
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "MeetingInstructionStatusV02", propOrder = {
"mtgInstrStsId",
"instrId",
"instrCxlId",
"mtgRef",
"rptgPty",
"sctyId",
"instrSts",
"cxlSts"
})
public class MeetingInstructionStatusV02 {
@XmlElement(name = "MtgInstrStsId", required = true)
protected MessageIdentification1 mtgInstrStsId;
@XmlElement(name = "InstrId")
protected MessageIdentification instrId;
@XmlElement(name = "InstrCxlId")
protected MessageIdentification instrCxlId;
@XmlElement(name = "MtgRef", required = true)
protected MeetingReference3 mtgRef;
@XmlElement(name = "RptgPty", required = true)
protected PartyIdentification9Choice rptgPty;
@XmlElement(name = "SctyId", required = true)
protected SecurityIdentification3 sctyId;
@XmlElement(name = "InstrSts")
protected InstructionStatus1Choice instrSts;
@XmlElement(name = "CxlSts")
protected CancellationStatus1Choice cxlSts;
/**
* Gets the value of the mtgInstrStsId property.
*
* @return
* possible object is
* {@link MessageIdentification1 }
*
*/
public MessageIdentification1 getMtgInstrStsId() {
return mtgInstrStsId;
}
/**
* Sets the value of the mtgInstrStsId property.
*
* @param value
* allowed object is
* {@link MessageIdentification1 }
*
*/
public MeetingInstructionStatusV02 setMtgInstrStsId(MessageIdentification1 value) {
this.mtgInstrStsId = value;
return this;
}
/**
* Gets the value of the instrId property.
*
* @return
* possible object is
* {@link MessageIdentification }
*
*/
public MessageIdentification getInstrId() {
return instrId;
}
/**
* Sets the value of the instrId property.
*
* @param value
* allowed object is
* {@link MessageIdentification }
*
*/
public MeetingInstructionStatusV02 setInstrId(MessageIdentification value) {
this.instrId = value;
return this;
}
/**
* Gets the value of the instrCxlId property.
*
* @return
* possible object is
* {@link MessageIdentification }
*
*/
public MessageIdentification getInstrCxlId() {
return instrCxlId;
}
/**
* Sets the value of the instrCxlId property.
*
* @param value
* allowed object is
* {@link MessageIdentification }
*
*/
public MeetingInstructionStatusV02 setInstrCxlId(MessageIdentification value) {
this.instrCxlId = value;
return this;
}
/**
* Gets the value of the mtgRef property.
*
* @return
* possible object is
* {@link MeetingReference3 }
*
*/
public MeetingReference3 getMtgRef() {
return mtgRef;
}
/**
* Sets the value of the mtgRef property.
*
* @param value
* allowed object is
* {@link MeetingReference3 }
*
*/
public MeetingInstructionStatusV02 setMtgRef(MeetingReference3 value) {
this.mtgRef = value;
return this;
}
/**
* Gets the value of the rptgPty property.
*
* @return
* possible object is
* {@link PartyIdentification9Choice }
*
*/
public PartyIdentification9Choice getRptgPty() {
return rptgPty;
}
/**
* Sets the value of the rptgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification9Choice }
*
*/
public MeetingInstructionStatusV02 setRptgPty(PartyIdentification9Choice value) {
this.rptgPty = value;
return this;
}
/**
* Gets the value of the sctyId property.
*
* @return
* possible object is
* {@link SecurityIdentification3 }
*
*/
public SecurityIdentification3 getSctyId() {
return sctyId;
}
/**
* Sets the value of the sctyId property.
*
* @param value
* allowed object is
* {@link SecurityIdentification3 }
*
*/
public MeetingInstructionStatusV02 setSctyId(SecurityIdentification3 value) {
this.sctyId = value;
return this;
}
/**
* Gets the value of the instrSts property.
*
* @return
* possible object is
* {@link InstructionStatus1Choice }
*
*/
public InstructionStatus1Choice getInstrSts() {
return instrSts;
}
/**
* Sets the value of the instrSts property.
*
* @param value
* allowed object is
* {@link InstructionStatus1Choice }
*
*/
public MeetingInstructionStatusV02 setInstrSts(InstructionStatus1Choice value) {
this.instrSts = value;
return this;
}
/**
* Gets the value of the cxlSts property.
*
* @return
* possible object is
* {@link CancellationStatus1Choice }
*
*/
public CancellationStatus1Choice getCxlSts() {
return cxlSts;
}
/**
* Sets the value of the cxlSts property.
*
* @param value
* allowed object is
* {@link CancellationStatus1Choice }
*
*/
public MeetingInstructionStatusV02 setCxlSts(CancellationStatus1Choice value) {
this.cxlSts = value;
return this;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
}
@Override
public boolean equals(Object that) {
return EqualsBuilder.reflectionEquals(this, that);
}
@Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
| 28.298182 | 396 | 0.642894 |
4c93edcfd7fe556c288c0e3ba9b2ad9f9c283250 | 3,342 | package de.sswis.controller;
import de.sswis.exceptions.DuplicateObjectNameException;
import de.sswis.model.*;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class ModelProviderTest {
private static ModelProvider modelProvider;
private static Game game;
private static Configuration configuration;
private static Initialization initialization;
private static MixedStrategy strategy;
private static CombinedStrategy combinedStrategy;
@BeforeClass
public static void instantiate() {
modelProvider = ModelProvider.getInstance();
game = new Game("testGame", "", null);
configuration = new Configuration("testConfig", null, null, null,
null, null, 1, 1, 0, 100, 0.2);
initialization = new Initialization("testInit", 0);
strategy = new MixedStrategy("testStrategy", null, null);
combinedStrategy = new CombinedStrategy("testCombStrat", null, null);
}
@Before
public void init() {
modelProvider.addGame(game);
modelProvider.addConfiguration(configuration);
modelProvider.addInitialization(initialization);
modelProvider.addMixedStrategy(strategy);
modelProvider.addCombinedStrategy(combinedStrategy);
}
@After
public void tearDown() {
modelProvider.deleteAllObjects();
}
@Test
public void objectsShouldBeAdded() {
assertEquals(game, modelProvider.getGame("testGame"));
assertEquals(configuration, modelProvider.getConfiguration("testConfig"));
assertEquals(initialization, modelProvider.getInitialization("testInit"));
assertEquals(strategy, modelProvider.getMixedStrategy("testStrategy"));
assertEquals(combinedStrategy, modelProvider.getCombinedStrategy("testCombStrat"));
}
@Test
public void objectsShouldBeDeleted() {
modelProvider.deleteGame("testGame");
modelProvider.deleteConfiguration("testConfig");
modelProvider.deleteInitialization("testInit");
modelProvider.deleteMixedStrategy("testStrategy");
modelProvider.deleteCombinedStrategy("testCombStrat");
assertNull(modelProvider.getGame("testGame"));
assertNull(modelProvider.getConfiguration("testConfig"));
assertNull(modelProvider.getInitialization("testInit"));
assertNull(modelProvider.getMixedStrategy("testStrategy"));
assertNull(modelProvider.getCombinedStrategy("testCombStrat"));
}
@Test
public void nothingShouldBeDeleted() {
modelProvider.deleteGame("foo");
modelProvider.deleteConfiguration("foo");
modelProvider.deleteInitialization("testinit");
modelProvider.deleteMixedStrategy("Strategy");
modelProvider.deleteCombinedStrategy("test");
assertEquals(game, modelProvider.getGame("testGame"));
assertEquals(configuration, modelProvider.getConfiguration("testConfig"));
assertEquals(initialization, modelProvider.getInitialization("testInit"));
assertEquals(strategy, modelProvider.getMixedStrategy("testStrategy"));
assertEquals(combinedStrategy, modelProvider.getCombinedStrategy("testCombStrat"));
}
}
| 37.977273 | 91 | 0.722322 |
a23ff932985ffcf32c5db783f5ef2e597ef761f3 | 443 | package org.apereo.cas.consent;
import org.junit.platform.suite.api.SelectClasses;
import org.junit.platform.suite.api.Suite;
/**
* This is {@link AllTestsSuite}.
*
* @author Misagh Moayyed
* @since 6.0.0-RC3
*/
@SelectClasses({
JpaConsentRepositoryTests.class,
PostgresJpaConsentRepositoryTests.class,
OracleJpaConsentRepositoryTests.class,
MySQLJpaConsentRepositoryTests.class
})
@Suite
public class AllTestsSuite {
}
| 21.095238 | 50 | 0.76298 |
c91e78ee3d507e9b2597a41db5edc2df54c82fa4 | 1,196 | package com.home.shine.dataEx.watch;
import com.home.shine.support.collection.IntObjectMap;
/** 线程观测总数据 */
public class ThreadWatchAllData
{
/** 是否生效中 */
public boolean enabled=true;
/** 观测索引 */
public int index;
/** 观测线程总数 */
public int total;
/** 当前回归数据 */
public int num;
/** 时间次数 */
public int timeCount;
/** 数据组 */
private IntObjectMap<IntObjectMap<ThreadWatchOneData>> _datas=new IntObjectMap<>(IntObjectMap[]::new);
/** 回归数据(观测线程) */
public void addData(ThreadWatchOneData data)
{
//已失效
if(!enabled)
return;
getOneDic(data.type).put(data.index,data);
++num;
}
public IntObjectMap<ThreadWatchOneData> getOneDic(int type)
{
IntObjectMap<ThreadWatchOneData> dic=_datas.get(type);
if(dic==null)
{
_datas.put(type,dic=new IntObjectMap<>(ThreadWatchOneData[]::new));
}
return dic;
}
/** 获取数据 */
public ThreadWatchOneData getData(int type)
{
return getData(type,0);
}
/** 获取数据 */
public ThreadWatchOneData getData(int type,int index)
{
IntObjectMap<ThreadWatchOneData> dic=_datas.get(type);
if(dic==null)
return null;
return dic.get(index);
}
}
| 19.290323 | 104 | 0.642977 |
b07d011daff945be920058ef8801a2e86f8d4277 | 7,775 | package zmaster587.advancedRocketry.util;
import org.lwjgl.Sys;
import zmaster587.advancedRocketry.AdvancedRocketry;
import zmaster587.advancedRocketry.api.dimension.solar.StellarBody;
public class AstronomicalBodyHelper {
/**
* Returns the size multiplier for a body at the input distance, relative to either 1AU or the moon's orbital distance, depending on parent body
* @param orbitalDistance the distance from the parent body
* @return the float multiplier for size
*/
public static float getBodySizeMultiplier(float orbitalDistance) {
//Returns size multiplier relative to Earth standard (1AU = 100 Distance)
return 100f/orbitalDistance;
}
/**
* Returns the orbital period for a body at a given distance around its star
* @param orbitalDistance the distance from the parent body
* @param solarSize the size of the sun in question
* @return the orbital period in MC Days (24000 ticks)
*/
public static double getOrbitalPeriod(int orbitalDistance, float solarSize) {
//One MC Year is 48 MC days (16 IRL Hours), one month is 8 MC Days
return 48d*Math.pow(Math.pow((orbitalDistance/(100d * solarSize)), 3), 0.5d);
}
/**
* Returns the orbital period for a body at a given distance around its parent planet
* @param orbitalDistance the distance from the parent body
* @param planetaryMass the mass of the planet in question
* @return the orbital period in MC Days (24000 ticks)
*/
public static double getMoonOrbitalPeriod(float orbitalDistance, float planetaryMass) {
//One (lunar) MC month is 8 MC days, so the moon orbits in 8
//The same a the function for planets, but since gravity is directly correlated with mass uses the gravity of the plant for mass
return 8d*Math.pow(Math.pow((orbitalDistance/100d), 3)/planetaryMass, 0.5d);
}
/**
* Returns the orbital theta for a body at a given distance around its star, at this current moment
* @param orbitalDistance the distance from the parent body
* @param solarSize the size of the sun in question
* @return the current angle around the star in radians
*/
public static double getOrbitalTheta(int orbitalDistance, float solarSize) {
double orbitalPeriod = getOrbitalPeriod(orbitalDistance, solarSize);
//Returns angle, relative to 0, of a planet at any given time
return ((AdvancedRocketry.proxy.getWorldTimeUniversal(0) % (24000d*orbitalPeriod))/(24000d*orbitalPeriod))*(2d*Math.PI);
}
/**
* Returns the orbital theta for a body at a given distance around its parent planet, at this current moment
* @param orbitalDistance the distance from the parent body
* @param parentGravitationalMultiplier the size of the parent planet in question
* @return the current angle around the planet in radians
*/
public static double getMoonOrbitalTheta(int orbitalDistance, float parentGravitationalMultiplier) {
//Because the function is still in AU and solar mass, some correctional factors to convert to those units
double orbitalPeriod = getMoonOrbitalPeriod(orbitalDistance, parentGravitationalMultiplier);
//Returns angle, relative to 0, of a moon at any given time
return ((AdvancedRocketry.proxy.getWorldTimeUniversal(0) % (24000d*orbitalPeriod))/(24000d*orbitalPeriod))*(2d*Math.PI);
}
/**
* Returns the visual orbital theta for a body at a given distance around its parent planet, at this current moment, as a value from 0 - 360
* @param rotationalPeriod the rotational period of the moon we are rendering from
* @param orbitalDistance the distance from the parent body
* @param parentGravitationalMultiplier the distance from the parent body
* @param currentOrbitalTheta the orbital theta of the moon we are rendering from
* @param baseOrbitalTheta the base orbital theta of the planet in question
* @return the current angle around the planet normalized 0 - 360, for GL calls
*/
public static float getParentPlanetThetaFromMoon(int rotationalPeriod, int orbitalDistance, float parentGravitationalMultiplier, double currentOrbitalTheta, double baseOrbitalTheta) {
//Convert from radians to degrees for easier math
float degreeOrbitalTheta = (float)(currentOrbitalTheta * 180/Math.PI);
//Computer the number of rotations per revolution and use that for how fast the planet would seem to orbit from the moon
//Planet will not move at all if it is tidally locked
float planetPositionTheta = (((float)(AstronomicalBodyHelper.getMoonOrbitalPeriod(orbitalDistance, parentGravitationalMultiplier) * 24000)/rotationalPeriod) - 1) * degreeOrbitalTheta;
//Add the base orbital theta so the planet is in the correct place
return (planetPositionTheta + (float)(baseOrbitalTheta * 180/Math.PI)) % 360;
}
/**
* Returns the average temperature of a planet with the passed parameters
* @param star the stellar body that the planet orbits
* @param orbitalDistance the distance from the star
* @param atmPressure the pressure of the planet's atmosphere
* @return the temperature of the planet in Kelvin
*/
public static int getAverageTemperature(StellarBody star, int orbitalDistance, int atmPressure) {
int starSurfaceTemperature = 58 * star.getTemperature();
float starRadius = star.getSize()/215f;
//Gives output in AU
float planetaryOrbitalRadius = orbitalDistance/100f;
//Albedo is 0.3f hardcoded because of inability to easily calculate
double averageWithoutAtmosphere = starSurfaceTemperature * Math.pow(starRadius/(2* planetaryOrbitalRadius), 0.5) * Math.pow((1f-0.3f), 0.25);
//Slightly kludgey solution that works out mostly for Venus and well for Earth, without being overly complex
//Output is in Kelvin
return (int)(averageWithoutAtmosphere * Math.max(1, (1.125d * Math.pow((atmPressure/100d), 0.25))));
}
/**
* Returns the average insolation of a planet with the passed parameters
* @param star the stellar body that the planet orbits
* @param orbitalDistance the distance from the star
* @return the insolation of the planet relative to Earth insolation
*/
public static double getStellarBrightness(StellarBody star, int orbitalDistance) {
//Normal stars are 1.0 times this value, black holes with accretion discs emit less and so modify it
float lightMultiplier = 1.0f;
//Make all values ratios of Earth normal to get ratio compared to Earth
float normalizedStarTemperature = star.getTemperature()/100f;
float planetaryOrbitalRadius = orbitalDistance/100f;
//Check to see if the star is a black hole
boolean blackHole = star.isBlackHole();
for(StellarBody star2 : star.getSubStars())
if(!star2.isBlackHole()) {
blackHole = false;
break;
}
//There's no real easy way to get the light emitted by an accretion disc, so this substitutes
if(blackHole)
lightMultiplier *= 0.25;
//Returns ratio compared to a planet at 1 AU for Sol, because the other values in AR are normalized,
//and this works fairly well for hooking into with other mod's solar panels & such
return (lightMultiplier * ((Math.pow(star.getSize(), 2) * Math.pow(normalizedStarTemperature, 4))/Math.pow(planetaryOrbitalRadius, 2)));
}
/**
* Returns the human-eye-perceivable brightness of this insolation multiplier
* @param stellarBrightnessMultiplier the insolation multiplier to use
* @return the brightness multiplier perceivable to a human
*/
public static double getPlanetaryLightLevelMultiplier(double stellarBrightnessMultiplier) {
double log2Multiplier = (Math.log10(stellarBrightnessMultiplier)/Math.log10(2.0));
//Returns the brightness visible to the eye, compared to the actual flux - this is a factor of ~1.5x for every 2x increase in luminosity
//This is used for planetary light levels, as those would be eyesight based unlike the stellar brightness or similar
return Math.pow(1.5, log2Multiplier);
}
}
| 54.370629 | 185 | 0.767203 |
8e98013c47c43246ccb3cbdb6a5636383bdd0ebe | 738 | package cf.kuiprux.spbeat.util;
import java.util.concurrent.*;
import java.util.function.Supplier;
public class AsyncTask<T> {
private final static ExecutorService executor;
static {
executor = Executors.newCachedThreadPool();
}
private AsyncCallable<T> supplier;
public AsyncTask(AsyncCallable<T> supplier) {
this.supplier = supplier;
}
public CompletableFuture<T> run() {
return CompletableFuture.supplyAsync(supplier, executor);
}
public T getSync() {
return supplier.get();
}
public static abstract class AsyncCallable<T> implements Supplier<T> {
public <A>A await(AsyncTask<A> task){
return task.run().join();
}
}
}
| 21.705882 | 74 | 0.650407 |
9c6ffd5da07a9b58dfb0954cf22ae14536f7943b | 1,857 | /**
* Copyright (C) 2010 Asterios Raptis
*
* 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 de.alpharogroup.wicket.markup.html;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.filter.JavaScriptFilteredIntoFooterHeaderResponse;
import org.apache.wicket.markup.html.IHeaderResponseDecorator;
/**
* This class is a decorator for resources that shell be rendered in the footer section.
*/
public class ResourceFilteredIntoFooterHeaderResponseDecorator implements IHeaderResponseDecorator
{
/**
* The constant for the default filter name.
*/
private static final String DEFAULT_FILTER_NAME = "footer-container";
/**
* The filter name.
*/
private String filterName;
/**
* The default constructor with the default filter name.
*/
public ResourceFilteredIntoFooterHeaderResponseDecorator()
{
this(DEFAULT_FILTER_NAME);
}
/**
* The constructor with a filter name as parameter.
*
* @param filterName
* The filter name to set.
*/
public ResourceFilteredIntoFooterHeaderResponseDecorator(final String filterName)
{
this.filterName = filterName;
}
/**
* {@inheritDoc}
*/
@Override
public IHeaderResponse decorate(final IHeaderResponse response)
{
return new JavaScriptFilteredIntoFooterHeaderResponse(response, this.filterName);
}
} | 28.136364 | 98 | 0.752289 |
8520365bbc8f05541387f6f62faa7591a56cc4c6 | 3,766 | package com.ggx.pay.core.util;
import java.net.SocketTimeoutException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import org.jsoup.Connection;
import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.helper.HttpConnection;
public class HTTPCommonUtil {
static {
trustEveryone();
}
// 信任https
public static void trustEveryone() {
try {
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, new X509TrustManager[] { new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static Object getHttpHeaders(String url, int timeout) {
Connection conn = null;
try {
conn = HttpConnection.connect(url);
conn.timeout(timeout);
conn.header("Accept-Encoding", "gzip,deflate,sdch");
conn.header("Connection", "close");
conn.get();
Map<String, String> result = conn.response().headers();
result.put("title", conn.response().parse().title());
return result;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getHttpBody(String url, String method, Map<String, String> params, int timeout) {
Connection conn = null;
try {
conn = HttpConnection.connect(url);
conn.timeout(timeout);
if (params != null) {
conn.data(params);
}
if ("post".equalsIgnoreCase(method)) {
conn.post();
} else {
conn.get();
}
return conn.response().body();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String getHttpBody(String url, String method, Map<String, String> params) {
return getHttpBody(url, method, params, 10000);
}
public static String getHttpBody(String url, String method) {
return getHttpBody(url, method, null, 10000);
}
public static Response getHttpResponse(String url, Map<String, String> params, int timeout)
throws SocketTimeoutException {
Connection conn = null;
try {
conn = HttpConnection.connect(url);
conn.timeout(timeout);
conn.ignoreContentType(true);
// conn.header("Content-Type","text/*");
if (params != null) {
conn.data(params);
conn.post();
} else {
conn.get();
}
return conn.response();
} catch (Exception e) {
if (e instanceof SocketTimeoutException || e instanceof java.net.ConnectException) {
throw new SocketTimeoutException("time out!!");
} else {
throw new RuntimeException(e);
}
}
}
public static String postRequestBody(String url, String requestBody, int timeout) {
Connection conn = null;
try {
conn = HttpConnection.connect(url).ignoreContentType(true);
conn.timeout(timeout);
if (requestBody != null) {
conn.requestBody(requestBody);
}
conn.method(Method.POST);
Response response = conn.execute();
return response.body();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 25.972414 | 106 | 0.704461 |
c99e640412be26e707f05a21f216f6d9c6e025af | 12,547 | package com.vaklinov.zcashui;
import java.awt.Component;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.ProgressMonitorInputStream;
import javax.xml.bind.DatatypeConverter;
import com.vaklinov.zcashui.OSUtil.OS_TYPE;
/**
* Fetches the proving key. Deliberately hardcoded.
* @author zab
*/
public class ProvingKeyFetcher {
private static final int PROVING_KEY_SIZE = 910173851;
private static final String SHA256 = "8bc20a7f013b2b58970cddd2e7ea028975c88ae7ceb9259a5344a16bc2c0eef7";
private static final String pathURL = "https://0cash.org/downloads/sprout-proving.key";
private static final int SPROUT_GROTH_SIZE = 725523612;
private static final String SHA256SG = "b685d700c60328498fbde589c8c7c484c722b788b265b72af448a5bf0ee55b50";
private static final String pathURLSG = "https://0cash.org/downloads/sprout-groth16.params";
private static final int SAPLING_SPEND_SIZE = 47958396;
private static final String SHA256SS = "8e48ffd23abb3a5fd9c5589204f32d9c31285a04b78096ba40a79b75677efc13";
private static final String pathURLSS = "https://0cash.org/downloads/sapling-spend.params";
// TODO: add backups
private LanguageUtil langUtil;
public void fetchIfMissing(StartupProgressDialog parent) throws IOException {
langUtil = LanguageUtil.instance();
try {
verifyOrFetch(parent);
} catch (InterruptedIOException iox) {
JOptionPane.showMessageDialog(parent, langUtil.getString("proving.key.fetcher.option.pane.message"));
System.exit(-3);
}
}
private void verifyOrFetch(StartupProgressDialog parent)
throws IOException
{
OS_TYPE ost = OSUtil.getOSType();
File zCashParams = null;
// TODO: isolate getting ZcashParams in a utility method
if (ost == OS_TYPE.WINDOWS)
{
zCashParams = new File(System.getenv("APPDATA") + "/ZcashParams");
} else if (ost == OS_TYPE.MAC_OS)
{
File userHome = new File(System.getProperty("user.home"));
zCashParams = new File(userHome, "Library/Application Support/ZcashParams");
}
zCashParams = zCashParams.getCanonicalFile();
boolean needsFetch = false;
boolean needsFetchSG = false;
boolean needsFetchSS = false;
if (!zCashParams.exists())
{
needsFetch = true;
needsFetchSG = true;
needsFetchSS = true;
zCashParams.mkdirs();
}
// verifying key is small, always copy it
File verifyingKeyFile = new File(zCashParams,"sprout-verifying.key");
FileOutputStream fos = new FileOutputStream(verifyingKeyFile);
InputStream is = ProvingKeyFetcher.class.getClassLoader().getResourceAsStream("keys/sprout-verifying.key");
copy(is,fos);
fos.close();
is = null;
// sapling output params is small, always copy it
File saplingOutputFile = new File(zCashParams,"sapling-output.params");
FileOutputStream fosB = new FileOutputStream(saplingOutputFile);
InputStream isB = ProvingKeyFetcher.class.getClassLoader().getResourceAsStream("keys/sapling-output.params");
copy(isB,fosB);
fosB.close();
isB = null;
File provingKeyFile = new File(zCashParams,"sprout-proving.key");
provingKeyFile = provingKeyFile.getCanonicalFile();
File sproutGrothFile = new File(zCashParams,"sprout-groth16.params");
sproutGrothFile = sproutGrothFile.getCanonicalFile();
File saplingSpendFile = new File(zCashParams,"sapling-spend.params");
saplingSpendFile = saplingSpendFile.getCanonicalFile();
if (!provingKeyFile.exists())
{
needsFetch = true;
} else if (provingKeyFile.length() != PROVING_KEY_SIZE)
{
needsFetch = true;
}
if (!sproutGrothFile.exists())
{
needsFetchSG = true;
} else if (sproutGrothFile.length() != SPROUT_GROTH_SIZE)
{
needsFetchSG = true;
}
if (!saplingSpendFile.exists())
{
needsFetchSS = true;
} else if (saplingSpendFile.length() != SAPLING_SPEND_SIZE)
{
needsFetchSS = true;
}
/*
* We skip proving key verification every start - this is impractical.
* If the proving key exists and is the correct size, then it should be OK.
else
{
parent.setProgressText("Verifying proving key...");
needsFetch = !checkSHA256(provingKeyFile,parent);
}*/
if (!needsFetch && !needsFetchSG && !needsFetchSS)
{
return;
}
JOptionPane.showMessageDialog(
parent,
langUtil.getString("proving.key.fetcher.option.pane.verify.message"));
parent.setProgressText(langUtil.getString("proving.key.fetcher.option.pane.verify.progress.text"));
if (needsFetch) {
provingKeyFile.delete();
OutputStream os = new BufferedOutputStream(new FileOutputStream(provingKeyFile));
URL keyURL = new URL(pathURL);
URLConnection urlc = keyURL.openConnection();
urlc.setRequestProperty("User-Agent", "Wget/1.17.1 (linux-gnu)");
try
{
is = urlc.getInputStream();
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent, langUtil.getString("proving.key.fetcher.option.pane.verify.progress.monitor.text"), is);
pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE);
pmis.getProgressMonitor().setMillisToPopup(10);
copy(pmis,os);
os.close();
} finally
{
try { if (is != null) is.close(); } catch (IOException ignore){}
}
parent.setProgressText(langUtil.getString("proving.key.fetcher.option.pane.verify.key.text"));
if (!checkSHA256(provingKeyFile, parent))
{
JOptionPane.showMessageDialog(parent, langUtil.getString("proving.key.fetcher.option.pane.verify.key.failed.text"));
System.exit(-4);
}
}
if (needsFetchSG) {
sproutGrothFile.delete();
OutputStream os = new BufferedOutputStream(new FileOutputStream(sproutGrothFile));
URL keyURL = new URL(pathURLSG);
URLConnection urlc = keyURL.openConnection();
urlc.setRequestProperty("User-Agent", "Wget/1.17.1 (linux-gnu)");
try
{
is = urlc.getInputStream();
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent, langUtil.getString("sprout.groth.fetcher.option.pane.verify.progress.monitor.text"), is);
pmis.getProgressMonitor().setMaximum(SPROUT_GROTH_SIZE);
pmis.getProgressMonitor().setMillisToPopup(10);
copy(pmis,os);
os.close();
} finally
{
try { if (is != null) is.close(); } catch (IOException ignore){}
}
parent.setProgressText(langUtil.getString("sprout.groth.fetcher.option.pane.verify.key.text"));
if (!checkSHA256SG(sproutGrothFile, parent))
{
JOptionPane.showMessageDialog(parent, langUtil.getString("sapsproutling.groth.fetcher.option.pane.verify.key.failed.text"));
System.exit(-4);
}
}
if (needsFetchSS) {
saplingSpendFile.delete();
OutputStream os = new BufferedOutputStream(new FileOutputStream(saplingSpendFile));
URL keyURL = new URL(pathURLSS);
URLConnection urlc = keyURL.openConnection();
urlc.setRequestProperty("User-Agent", "Wget/1.17.1 (linux-gnu)");
try
{
is = urlc.getInputStream();
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent, langUtil.getString("sapling.spend.fetcher.option.pane.verify.progress.monitor.text"), is);
pmis.getProgressMonitor().setMaximum(SAPLING_SPEND_SIZE);
pmis.getProgressMonitor().setMillisToPopup(10);
copy(pmis,os);
os.close();
} finally
{
try { if (is != null) is.close(); } catch (IOException ignore){}
}
parent.setProgressText(langUtil.getString("sapling.spend.fetcher.option.pane.verify.key.text"));
if (!checkSHA256SS(saplingSpendFile, parent))
{
JOptionPane.showMessageDialog(parent, langUtil.getString("sapling.spend.fetcher.option.pane.verify.key.failed.text"));
System.exit(-4);
}
}
}
private static void copy(InputStream is, OutputStream os) throws IOException {
byte[] buf = new byte[0x1 << 13];
int read;
while ((read = is.read(buf)) >- 0) {
os.write(buf,0,read);
}
os.flush();
}
private static boolean checkSHA256(File provingKey, Component parent) throws IOException {
MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException impossible) {
throw new IOException(impossible);
}
try (InputStream is = new BufferedInputStream(new FileInputStream(provingKey))) {
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,
LanguageUtil.instance().getString("proving.key.fetcher.option.pane.verify.progress.monitor.text"),
is);
pmis.getProgressMonitor().setMaximum(PROVING_KEY_SIZE);
pmis.getProgressMonitor().setMillisToPopup(10);
DigestInputStream dis = new DigestInputStream(pmis, sha256);
byte [] temp = new byte[0x1 << 13];
while(dis.read(temp) >= 0);
byte [] digest = sha256.digest();
return SHA256.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
}
}
private static boolean checkSHA256SG(File sproutGroth, Component parent) throws IOException {
MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException impossible) {
throw new IOException(impossible);
}
try (InputStream is = new BufferedInputStream(new FileInputStream(sproutGroth))) {
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,
LanguageUtil.instance().getString("sprout.groth.fetcher.option.pane.verify.progress.monitor.text"),
is);
pmis.getProgressMonitor().setMaximum(SPROUT_GROTH_SIZE);
pmis.getProgressMonitor().setMillisToPopup(10);
DigestInputStream dis = new DigestInputStream(pmis, sha256);
byte [] temp = new byte[0x1 << 13];
while(dis.read(temp) >= 0);
byte [] digest = sha256.digest();
return SHA256SG.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
}
}
private static boolean checkSHA256SS(File saplingSpend, Component parent) throws IOException {
MessageDigest sha256;
try {
sha256 = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException impossible) {
throw new IOException(impossible);
}
try (InputStream is = new BufferedInputStream(new FileInputStream(saplingSpend))) {
ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(parent,
LanguageUtil.instance().getString("sapling.spend.fetcher.option.pane.verify.progress.monitor.text"),
is);
pmis.getProgressMonitor().setMaximum(SAPLING_SPEND_SIZE);
pmis.getProgressMonitor().setMillisToPopup(10);
DigestInputStream dis = new DigestInputStream(pmis, sha256);
byte [] temp = new byte[0x1 << 13];
while(dis.read(temp) >= 0);
byte [] digest = sha256.digest();
return SHA256SS.equalsIgnoreCase(DatatypeConverter.printHexBinary(digest));
}
}
}
| 41.137705 | 175 | 0.647565 |
9caca17dfd1eac061e062fa73c1669d0833b56cf | 1,018 | package org.plytimebandit.web.webbootflux.handler;
import org.plytimebandit.web.webbootflux.data.Foo;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class ExampleHandler {
public Mono<ServerResponse> hello(ServerRequest request) {
return ServerResponse.ok().contentType(MediaType.TEXT_PLAIN)
.body(BodyInserters.fromObject("Hello the 2nd!"));
}
public Flux<Foo> hi(ServerRequest request) {
return Flux.just(new Foo("foo", "one"), new Foo("bar", "two"));
}
public Mono<ServerResponse> hi2(ServerRequest request) {
Flux<Foo> foos = hi(request);
return ServerResponse.ok().body(foos, Foo.class);
}
}
| 32.83871 | 71 | 0.74558 |
f98817d5b4ac259edeac81571b06833b162a8dfb | 2,906 |
package ca.uhn.fhir.testmodel;
import java.util.ArrayList;
import java.util.List;
import ca.uhn.fhir.context.FhirVersionEnum;
import ca.uhn.fhir.model.api.IElement;
import ca.uhn.fhir.model.api.IResource;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.dstu.resource.BaseResource;
/**
* HAPI/FHIR <b>Patient</b> Resource
* (Information about a person or animal receiving health care services)
*
* <p>
* <b>Definition:</b>
* Demographics and other administrative information about a person or animal receiving care or other health-related services
* </p>
*
* <p>
* <b>Requirements:</b>
* Tracking patient is the center of the healthcare process
* </p>
*/
@ResourceDef(name="Patient", profile="http://hl7.org/fhir/profiles/Patient")
public class Patient extends BaseResource implements IResource {
@Child(name="identifier", type=IdentifierDt.class, order=0, min=0, max=Child.MAX_UNLIMITED)
@Description(
shortDefinition="An identifier for the person as this patient",
formalDefinition="An identifier that applies to this person as a patient"
)
private List<IdentifierDt> myIdentifier;
@Override
public <T extends IElement> List<T> getAllPopulatedChildElementsOfType(Class<T> theType) {
return ca.uhn.fhir.util.ElementUtil.allPopulatedChildElements(theType, myIdentifier );
}
@Override
public boolean isEmpty() {
return super.isBaseEmpty() && ca.uhn.fhir.util.ElementUtil.isEmpty( myIdentifier);
}
/**
* Gets the value(s) for <b>identifier</b> (An identifier for the person as this patient).
* creating it if it does
* not exist. Will not return <code>null</code>.
*
* <p>
* <b>Definition:</b>
* An identifier that applies to this person as a patient
* </p>
*/
public List<IdentifierDt> getIdentifier() {
if (myIdentifier == null) {
myIdentifier = new ArrayList<IdentifierDt>();
}
return myIdentifier;
}
/**
* Sets the value(s) for <b>identifier</b> (An identifier for the person as this patient)
*
* <p>
* <b>Definition:</b>
* An identifier that applies to this person as a patient
* </p>
*/
public void setIdentifier(List<IdentifierDt> theValue) {
myIdentifier = theValue;
}
/**
* Adds and returns a new value for <b>identifier</b> (An identifier for the person as this patient)
*
* <p>
* <b>Definition:</b>
* An identifier that applies to this person as a patient
* </p>
*/
public IdentifierDt addIdentifier() {
IdentifierDt newType = new IdentifierDt();
getIdentifier().add(newType);
return newType;
}
@Override
public String getResourceName() {
return Patient.class.getName();
}
@Override
public FhirVersionEnum getStructureFhirVersionEnum() {
return FhirVersionEnum.DSTU1;
}
} | 23.626016 | 125 | 0.704061 |
8b80a9b0bb428637b927cca900c6404ada8b90c3 | 387 | package tom.jiafei;
public class PrimNumber
{ public void getPrimnumber(int n)
{ int sum=0,i,j;
for(i=1;i<=n;i++)
{ for(j=2;j<=i/2;j++)
{ if(i%j==0)
break;
}
if(j>i/2)
System.out.print(" "+i);
}
}
public static void main(String args[])
{ PrimNumber p=new PrimNumber();
p.getPrimnumber(20);
}
}
| 20.368421 | 38 | 0.490956 |
f623811350b98b68563e53579dffc4c2ecd19d41 | 481 | package com.r4intellij.debugger.frame;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class RValueModifierHandlerImplTest {
@Test
public void ordinary() {
final RValueModifierHandlerImpl handler = new RValueModifierHandlerImpl();
handler.setLastFrameNumber(2);
assertTrue(handler.isModificationAvailable(2));
assertFalse(handler.isModificationAvailable(1));
}
} | 25.315789 | 82 | 0.748441 |
5a1739b569c2ef96784ad14a2527c394337648ac | 5,888 | package com.simpleharmonics.kismis.classes;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.util.Hex;
import com.google.firebase.auth.FirebaseUser;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Random;
public class CustomTools {
private static final String TAG = "CustomToolsTAG";
private static final String numericString = "0123456789";
private static final String alphaNumericString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWZYZ0123456789";
public static String getReducedNumber(long videoLikesLong) {
float videoLikes = (float) videoLikesLong;
float oneMillion = 1000000;
float oneThousand = 1000;
if (videoLikes >= oneMillion) {
float likes = videoLikes / oneMillion;
return String.format(Locale.ENGLISH, "%.1f", likes).concat("k");
} else if (videoLikes >= oneThousand) {
float likes = videoLikes / oneThousand;
return String.format(Locale.ENGLISH, "%.1f", likes).concat("k");
} else {
return String.valueOf(videoLikes);
}
}
public static void showToast(Activity activity, String message) {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
}
private static String getCurrentTime() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS", Locale.ENGLISH);
return simpleDateFormat.format(new Date());
}
static String getSHA256(String inputString) {
String output = null;
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
byte[] hashByteArray = messageDigest.digest(inputString.getBytes(StandardCharsets.UTF_8));
output = Hex.bytesToStringLowercase(hashByteArray);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return output;
}
public static String convertToEasyFormat(String inputDate) {
try {
DateFormat originalFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.ENGLISH);
DateFormat targetFormat = new SimpleDateFormat("dd MMMM, yyyy hh:mm a", Locale.ENGLISH);
Date date = originalFormat.parse(inputDate);
if (date == null) {
return null;
} else {
return targetFormat.format(date);
}
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
public static File getVideoFile(Context context) {
try {
File externalFile = context.getExternalFilesDir(null);
if (externalFile == null) {
Log.e(TAG, "Kismis: getVideoFile: externalFile is null");
return null;
} else {
File videoFolder = new File(externalFile.getAbsolutePath() + "/ShotVideos");
Log.i(TAG, "Kismis: getVideoFile: Folder created: " + videoFolder.mkdir());
File videoFile = new File(videoFolder, "kaymra_video_" + getCurrentTime() + ".mp4");
Log.i(TAG, "Kismis: getVideoFile: File created: " + videoFile.createNewFile());
return videoFile;
}
} catch (IOException e) {
Log.e(TAG, "Kismis: getVideoFilePath: IOException: " + e);
return null;
}
}
public static File getVideoFileTranscoded(Context context, String videoUriString) {
try {
String fileName = videoUriString.substring(videoUriString.lastIndexOf("/"));
fileName = fileName.concat("_transcoded.mp4");
File externalFile = context.getExternalFilesDir(null);
if (externalFile == null) {
Log.e(TAG, "Kismis: getVideoFileTranscoded: externalFile is null");
return null;
} else {
File videoFolder = new File(externalFile.getAbsolutePath() + "/ShotVideos");
Log.i(TAG, "Kismis: getVideoFileTranscoded: Folder created: " + videoFolder.mkdir());
File videoFile = new File(videoFolder, fileName);
Log.i(TAG, "Kismis: getVideoFileTranscoded: File created: " + videoFile.createNewFile());
return videoFile;
}
} catch (IOException e) {
Log.e(TAG, "Kismis: getVideoFileTranscoded: IOException: " + e);
return null;
}
}
public static String getRandomStringNumeric(int size) {
StringBuilder stringBuilder = new StringBuilder(size);
int length = numericString.length();
Random random = new Random();
for (int i = 0; i < size; i++) {
stringBuilder.append(numericString.charAt(random.nextInt(length)));
}
return String.valueOf(stringBuilder);
}
public static String getRandomStringAlphaNumeric(int size) {
StringBuilder stringBuilder = new StringBuilder(size);
int length = alphaNumericString.length();
Random random = new Random();
for (int i = 0; i < size; i++) {
stringBuilder.append(alphaNumericString.charAt(random.nextInt(length)));
}
return String.valueOf(stringBuilder);
}
public static String getKaymraEmail(String userName) {
return userName.concat("@kaymra.com");
}
public static FirebaseUser getFirebaseUser() {
return null;
// return FirebaseAuth.getInstance().getCurrentUser();//TODO change this
}
}
| 38.993377 | 118 | 0.634171 |
b3440178d5fde7fdc612a2ae59fb96c5a0b4acf8 | 2,342 | package ajedrez;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class PanelTorneo extends JPanel implements VistaTorneo {
private JTextField jtfFicheroEntrada;
private JTextField jtfFicheroSalida;
private JButton jbLee;
private JButton jbRonda;
private JButton jbGuarda;
private JTextArea jtaTexto;
private JLabel jlMensaje;
public PanelTorneo() {
setLayout(new BorderLayout());
jtfFicheroEntrada = new JTextField(20);
jtfFicheroEntrada.setBorder(BorderFactory.createTitledBorder("Nombre Fichero Entrada"));
jtfFicheroSalida = new JTextField(20);
jtfFicheroSalida.setBorder(BorderFactory.createTitledBorder("Nombre Fichero Salida"));
JPanel panelNorte = new JPanel();
panelNorte.setLayout(new FlowLayout());
panelNorte.add(jtfFicheroEntrada);
panelNorte.add(jtfFicheroSalida);
add(panelNorte, BorderLayout.NORTH);
jbLee = new JButton("Lee");
jbRonda = new JButton("Ronda");
jbGuarda = new JButton("Guarda");
JPanel jpDerecho = new JPanel();
jpDerecho.setLayout(new BoxLayout(jpDerecho, BoxLayout.Y_AXIS));
jpDerecho.add(jbLee);
jpDerecho.add(jbRonda);
jpDerecho.add(jbGuarda);
add(jpDerecho, BorderLayout.EAST);
jtaTexto = new JTextArea(30,70);
add(new JScrollPane(jtaTexto), BorderLayout.CENTER);
jlMensaje = new JLabel(" ");
add(jlMensaje, BorderLayout.SOUTH);
}
@Override
public String getFicheroEntrada() {
return jtfFicheroEntrada.getText();
}
@Override
public String getFicheroSalida() {
return jtfFicheroSalida.getText();
}
@Override
public void agregaLinea(String linea) {
jtaTexto.append(linea+"\n");
}
@Override
public void limpiaPantalla() {
jtaTexto.setText("");
}
@Override
public void setMensaje(String msg) {
jlMensaje.setText(msg);
}
public void controlador(ActionListener ctr) {
jbLee.setActionCommand(VistaTorneo.LEE);
jbLee.addActionListener(ctr);
jbGuarda.setActionCommand(VistaTorneo.GUARDA);
jbGuarda.addActionListener(ctr);
jbRonda.setActionCommand(VistaTorneo.RONDA);
jbRonda.addActionListener(ctr);
}
}
| 26.022222 | 90 | 0.766012 |
86e784c5ab9b42b1cffcc1ff8513362f8a7f5507 | 1,603 | package org.rabix.engine.rest.api.impl;
import java.util.Collections;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.rabix.bindings.model.Job;
import org.rabix.engine.rest.api.JobHTTPService;
import org.rabix.engine.rest.service.JobServiceException;
import org.rabix.engine.rest.service.JobService;
import com.google.inject.Inject;
public class JobHTTPServiceImpl implements JobHTTPService {
private final JobService jobService;
@Inject
public JobHTTPServiceImpl(JobService jobService) {
this.jobService = jobService;
}
@Override
public Response create(Job job) {
try {
return ok(jobService.start(job, null));
} catch (Exception e) {
return error();
}
}
@Override
public Response get() {
return ok(jobService.get());
}
@Override
public Response get(String id) {
Job job = jobService.get(id);
if (job == null) {
return entityNotFound();
}
return ok(job);
}
@Override
public Response save(String id, Job job) {
try {
jobService.update(job);
} catch (JobServiceException e) {
return error();
}
return ok();
}
private Response entityNotFound() {
return Response.status(Status.NOT_FOUND).build();
}
private Response error() {
return Response.status(Status.BAD_REQUEST).build();
}
private Response ok() {
return Response.ok(Collections.emptyMap()).build();
}
private Response ok(Object items) {
if (items == null) {
return ok();
}
return Response.ok().entity(items).build();
}
}
| 21.092105 | 59 | 0.668122 |
9e719532d7f77523cb65bf4f6d4b331ca6df9a85 | 3,975 | package ie.dit.giantbombapp.view.activities;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.squareup.picasso.Picasso;
import ie.dit.giantbombapp.R;
import ie.dit.giantbombapp.controller.MainController;
/**
* Author: Graham Byrne
*
* Created: 23/11/2016
* Modified: 25/11/2016
*
* Activity formerly used to show a more detailed view of each object
* in the PromoListActivity List. Replaced with a web browser intent call
*/
public class PromoActivity extends AppCompatActivity
{
private static final String TAG = "PromoActivity";
private MainController controller;
private Cursor result;
private ImageView header;
private TextView title, deck;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.promo_activity);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
try
{
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch (NullPointerException e)
{
Log.d(TAG, "Cannot setup home button");
}
controller = new MainController(getBaseContext(), getString(R.string.api_key), getString(R.string.format), getString(R.string.sort));
Intent i = getIntent();
result = controller.fetchPromo(i.getIntExtra("PromoId", -1));
header = (ImageView) findViewById(R.id.header_image);
title = (TextView) findViewById(R.id.title);
deck = (TextView) findViewById(R.id.promo_deck);
Button connectButton = (Button) findViewById(R.id.connect);
Picasso.with(this).load(result.getString(result.getColumnIndexOrThrow("thumbnail"))).into(header);
title.setText(result.getString(result.getColumnIndexOrThrow("promo_title")));
deck.setText(result.getString(result.getColumnIndexOrThrow("deck")));
connectButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Uri uri = Uri.parse(result.getString(result.getColumnIndexOrThrow("site_url")));
Intent i = new Intent(Intent.ACTION_VIEW, uri);
startActivity(i);
}
});
}
@Override
protected void onResume()
{
super.onResume();
controller.openDatabase();
}
@Override
protected void onPause()
{
super.onPause();
controller.closeDatabase();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.promo_action_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
switch (id)
{
case R.id.action_settings:
{
Toast.makeText(getBaseContext(), "There are no settings", Toast.LENGTH_SHORT).show();
return true;
}
case R.id.to_reviews:
{
Intent i = new Intent(getBaseContext(), ReviewListActivity.class);
finish();
startActivity(i);
return true;
}
case R.id.to_search:
{
Intent i = new Intent(getBaseContext(), SearchListActivity.class);
finish();
startActivity(i);
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
| 29.227941 | 141 | 0.633711 |
8dc6d33d5ab8c8f20f24ff468083edc725b10299 | 4,710 | package spoon.test.executable;
import org.junit.Assert;
import org.junit.Test;
import spoon.Launcher;
import spoon.reflect.code.CtAbstractInvocation;
import spoon.reflect.code.CtBlock;
import spoon.reflect.code.CtConstructorCall;
import spoon.reflect.code.CtInvocation;
import spoon.reflect.code.CtLiteral;
import spoon.reflect.code.CtStatement;
import spoon.reflect.declaration.CtClass;
import spoon.reflect.declaration.CtMethod;
import spoon.reflect.declaration.CtType;
import spoon.reflect.factory.Factory;
import spoon.reflect.reference.CtExecutableReference;
import spoon.reflect.visitor.Query;
import spoon.reflect.visitor.filter.InvocationFilter;
import spoon.reflect.visitor.filter.TypeFilter;
import spoon.test.executable.testclasses.Pozole;
import spoon.testing.utils.ModelUtils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static spoon.testing.utils.ModelUtils.build;
import static spoon.testing.utils.ModelUtils.canBeBuilt;
public class ExecutableRefTest {
@Test
public void methodTest() throws Exception {
CtAbstractInvocation<?> ctAbstractInvocation = this.getInvocationFromMethod("testMethod");
Assert.assertTrue(ctAbstractInvocation instanceof CtInvocation<?>);
CtExecutableReference<?> executableReference = ctAbstractInvocation.getExecutable();
Assert.assertNotNull(executableReference);
Method method = executableReference.getActualMethod();
Assert.assertNotNull(method);
assertEquals("Hello World",
method.invoke(null, ((CtLiteral<?>) ctAbstractInvocation.getArguments().get(0)).getValue()));
}
@Test
public void constructorTest() throws Exception {
CtAbstractInvocation<?> ctAbstractInvocation = this.getInvocationFromMethod("testConstructor");
Assert.assertTrue(ctAbstractInvocation instanceof CtConstructorCall<?>);
CtExecutableReference<?> executableReference = ctAbstractInvocation.getExecutable();
Assert.assertNotNull(executableReference);
Constructor<?> constructor = executableReference.getActualConstructor();
Assert.assertNotNull(constructor);
assertEquals("Hello World",
constructor.newInstance(((CtLiteral<?>) ctAbstractInvocation.getArguments().get(0)).getValue()));
}
@Test
public void testGetActualClassTest() throws Exception {
Factory factory = build(ExecutableRefTestSource.class, MyIntf.class);
CtMethod<?> method = factory.Class().get(ExecutableRefTestSource.class).getMethod("myMethod");
CtExecutableReference<?> ref = method.getReference();
Method m = ref.getActualMethod();
assertEquals("myMethod", m.getName());
assertEquals(0, m.getExceptionTypes().length);
}
@Test
public void testSameTypeInConstructorCallBetweenItsObjectAndItsExecutable() {
final Launcher launcher = new Launcher();
launcher.getEnvironment().setNoClasspath(true);
launcher.addInputResource("./src/test/resources/executable/CmiContext_1.2.java");
launcher.setSourceOutputDirectory("./target/executable");
launcher.run();
final CtClass<Object> aClass = launcher.getFactory().Class().get("org.objectweb.carol.jndi.spi.CmiContext");
final List<CtConstructorCall> ctConstructorCalls = aClass.getElements(new TypeFilter<CtConstructorCall>(CtConstructorCall.class));
for (CtConstructorCall constructorCall : ctConstructorCalls) {
assertNotNull(constructorCall.getExecutable());
}
canBeBuilt("./target/executable", 8, true);
}
private CtAbstractInvocation<?> getInvocationFromMethod(String methodName) throws Exception {
Factory factory = build(ExecutableRefTestSource.class, MyIntf.class);
CtClass<ExecutableRefTestSource> clazz = factory.Class().get(ExecutableRefTestSource.class);
Assert.assertNotNull(clazz);
List<CtMethod<?>> methods = clazz.getMethodsByName(methodName);
assertEquals(1, methods.size());
CtMethod<?> ctMethod = methods.get(0);
CtBlock<?> ctBody = (CtBlock<?>) ctMethod.getBody();
Assert.assertNotNull(ctBody);
List<CtStatement> ctStatements = ctBody.getStatements();
assertEquals(1, ctStatements.size());
CtStatement ctStatement = ctStatements.get(0);
Assert.assertTrue(ctStatement instanceof CtAbstractInvocation<?>);
return (CtAbstractInvocation<?>) ctStatement;
}
@Test
public void testOverridingMethod() throws Exception {
final CtType<Pozole> aPozole = ModelUtils.buildClass(Pozole.class);
final CtExecutableReference<?> run = aPozole.getMethodsByName("run").get(0).getReference();
final List<CtInvocation<?>> elements = Query.getElements(run.getFactory(), new InvocationFilter(run));
assertEquals(1, elements.size());
assertEquals(run, elements.get(0).getExecutable());
}
}
| 37.380952 | 132 | 0.790021 |
43b82a413648e2139d2860f3c10b8015aa97c3bb | 1,896 | /*
* Copyright © 2017 camunda services GmbH (info@camunda.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.
*/
package io.zeebe.dispatcher.impl.log;
import static io.zeebe.dispatcher.impl.log.LogBufferDescriptor.PARTITION_COUNT;
import static io.zeebe.dispatcher.impl.log.LogBufferDescriptor.PARTITION_META_DATA_LENGTH;
import static org.assertj.core.api.Assertions.assertThat;
import io.zeebe.util.allocation.AllocatedBuffer;
import io.zeebe.util.allocation.BufferAllocators;
import org.junit.Before;
import org.junit.Test;
public class PartitionBuilderTest {
PartitionBuilder partitionBuilder;
@Before
public void setup() {
partitionBuilder = new PartitionBuilder();
}
@Test
public void shouldSlicePartitions() {
final int partitionSize = 1024;
final int capacity =
(PARTITION_COUNT * partitionSize) + (PARTITION_COUNT * PARTITION_META_DATA_LENGTH);
final AllocatedBuffer buffer = BufferAllocators.allocateDirect(capacity);
final LogBufferPartition[] partitions = partitionBuilder.slicePartitions(partitionSize, buffer);
assertThat(partitions.length).isEqualTo(PARTITION_COUNT);
for (LogBufferPartition logBufferPartition : partitions) {
assertThat(logBufferPartition.getPartitionSize()).isEqualTo(partitionSize);
assertThat(logBufferPartition.getDataBuffer().capacity()).isEqualTo(partitionSize);
}
}
}
| 35.773585 | 100 | 0.771624 |
c0c41f71b8fc5216b17f884b1174da89e0c6812c | 606 | package com.securemessaging.sm;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.securemessaging.client.ClientRequestHandler;
import lombok.Data;
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
/**
* Session is a domain object for capturing the reply to login and recieve the authentication token.
*/
public class Session {
public String sessionToken;
public String firstName;
public String lastName;
public String state;
public String emailAddress;
public ClientRequestHandler client;
//logout
/*
public void logout(){
}
*/
}
| 20.896552 | 100 | 0.739274 |
d64a68eda5ec79870b16db343715589ba4d7180b | 2,956 | /*
* The MIT License (MIT)
*
* Copyright (c) 2019 Tyler Bucher
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package net.reallifegames.atlas.module.fx;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import net.reallifegames.atlas.Atlas;
import java.net.URL;
/**
* JavaFX application class endpoint.
*
* @author Tyler Bucher
*/
public class FxApplication extends Application {
/**
* The main entry point for all JavaFX applications. The start method is called after the init method has returned,
* and after the system is ready for the application to begin running.
*
* <p>
* NOTE: This method is called on the JavaFX Application Thread.
* </p>
*
* @param primaryStage the primary stage for this application, onto which the application scene can be set. The
* primary stage will be embedded in the browser if the application was launched as an applet.
* Applications may create other stages, if needed, but they will not be primary stages and will
* not be embedded in the browser.
*/
@Override
public void start(Stage primaryStage) throws Exception {
URL loc = getClass().getResource("/fx/ui.fxml");
Parent parent = FXMLLoader.load(loc);
primaryStage.setTitle("AtlasMaker UI Controller");
Scene scene = new Scene(parent);
primaryStage.setScene(scene);
primaryStage.show();
primaryStage.setX((Atlas.videoModeWidth - (scene.getWidth())) / 2 + (Atlas.width / 2.0) + scene.getX());
primaryStage.setY((Atlas.videoModeHeight - scene.getHeight()) / 2.0 - scene.getY());
primaryStage.setOnCloseRequest(event->{
if (!Atlas.closed) {
event.consume();
}
});
}
}
| 41.055556 | 120 | 0.691813 |
55a014d0ae75418471486b096348e301b29a4f54 | 873 | package com.yarolegovich.mp.io;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import androidx.annotation.Nullable;
/**
* Created by yarolegovich on 16.05.2016.
*/
public class SharedPrefsStorageFactory implements StorageModule.Factory {
private String preferencesName;
public SharedPrefsStorageFactory(@Nullable String preferencesName) {
this.preferencesName = preferencesName;
}
@Override
public StorageModule create(Context context) {
SharedPreferences prefs;
if (preferencesName != null) {
prefs = context.getSharedPreferences(preferencesName, Context.MODE_PRIVATE);
} else {
prefs = PreferenceManager.getDefaultSharedPreferences(context);
}
return new SharedPreferenceStorageModule(prefs);
}
}
| 30.103448 | 88 | 0.733104 |
a311ded60b3718bd550e1a918bee4a99ade0a90c | 6,339 | /**
* The MIT License (MIT)
*
* MSUSEL Quamoco Implementation
* Copyright (c) 2015-2017 Montana State University, Gianforte School of Computing,
* Software Engineering Laboratory
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package edu.montana.gsoc.msusel.quamoco.model.qm2;
import org.eclipse.jdt.annotation.NonNull;
/**
* A class to provide the capability to rank and weight the evaluation of
* measures which affect a factor.
*
* @author Isaac Griffith
* @version 1.1.1
*/
public class MeasureRanking extends Ranking {
/**
* Measure associated with this ranking
*/
private Measure measure;
/**
* Normalization measure used to normalize the findings of the associated
* measure
*/
private Measure normalizationMeasure;
/**
* Normalization range applicable to normalizing findings of the associated
* measure
*/
private NormalizationRange range;
/**
* Function used to determine the effect of the measure associated with this
* ranking
*/
private Function function;
/**
* Constructs a new Ranking for the given measure
*
* @param measure
* The measure
*/
public MeasureRanking(Measure measure)
{
super();
this.measure = measure;
}
/**
* @return the measure
*/
public Measure getMeasure()
{
return measure;
}
/**
* @param measure
* the measure to set
*/
public void setMeasure(Measure measure)
{
this.measure = measure;
}
/**
* @return the normalizationMeasure
*/
public Measure getNormalizationMeasure()
{
return normalizationMeasure;
}
/**
* @param normalizationMeasure
* the normalizationMeasure to set
*/
public void setNormalizationMeasure(Measure normalizationMeasure)
{
this.normalizationMeasure = normalizationMeasure;
}
/**
* @return the range
*/
public NormalizationRange getRange()
{
return range;
}
/**
* @param range
* the range to set
*/
public void setRange(NormalizationRange range)
{
this.range = range;
}
/**
* @return the function
*/
public Function getFunction()
{
return function;
}
/**
* @param function
* the function to set
*/
public void setFunction(Function function)
{
this.function = function;
}
/**
* Constructs and returns a new instance of a ranking builder
*
* @param measure
* The measure this ranking is for
* @return The ranking builder instance
*/
public static Builder builder(Measure measure)
{
return new Builder(measure);
}
/**
* Builder used to construct a ranking.
*
* @author Isaac Griffith
* @version 1.1.1
*/
public static class Builder {
/**
* The ranking under construction
*/
private MeasureRanking ranking;
/**
* Constructs a new Builder for a ranking of the given measure
*
* @param measure
* The measure
*/
public Builder(Measure measure)
{
ranking = new MeasureRanking(measure);
}
/**
* @return The instance under construction
*/
public MeasureRanking create()
{
return ranking;
}
/**
* Sets the rank of the ranking under construction to the given value
*
* @param rank
* The rank
* @return this
*/
@NonNull
public Builder rank(int rank)
{
ranking.setRank(rank);
return this;
}
/**
* Sets the weight of the ranking under construction to the given value
*
* @param weight
* The weight
* @return this
*/
@NonNull
public Builder weight(double weight)
{
ranking.setWeight(weight);
return this;
}
/**
* Sets the function associated with the measure
*
* @param function
* Linear Distribution function
* @return this
*/
@NonNull
public Builder function(Function function)
{
ranking.setFunction(function);
return this;
}
/**
* Sets the normalization measure of the ranking
*
* @param norm
* NormalizationMeasure
* @return this
*/
@NonNull
public Builder normalizer(NormalizationMeasure norm)
{
ranking.setNormalizationMeasure(norm);
return this;
}
/**
* Sets the normalization range of the ranking
*
* @param range
* The Range
* @return this
*/
@NonNull
public Builder range(NormalizationRange range)
{
ranking.setRange(range);
return this;
}
}
}
| 24.474903 | 83 | 0.571226 |
c92d472774cc73c781a41f4e2d47f5f7c6eeb6c3 | 1,839 | package com.co.almundo.prueba.callcenter.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* Entidad empleado llamada (EmployeeCall)
* @author fernbecr
*
*/
@Entity
@Table(name = "am_empleado_llamada", schema="ALMUNDO_CALLCENTER")
public class EmployeeCall {
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "empleado_id")
private Employee employee;
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name = "llamada_id")
private Call call;
private Long duration;
@Temporal(TemporalType.DATE)
private Date date;
public EmployeeCall() {
}
public EmployeeCall(Employee employee, Call call, Long duration) {
this.employee = employee;
this.call = call;
this.duration = duration;
this.date = new Date();
}
/**
* Inicio de los métodos setters y getters
*/
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public Call getCall() {
return call;
}
public void setCall(Call call) {
this.call = call;
}
public Long getDuration() {
return duration;
}
public void setDuration(Long duration) {
this.duration = duration;
}
public Date getDate() {
return date;
}
public void setFecha(Date date) {
this.date = date;
}
}
| 18.958763 | 67 | 0.723763 |
2154930a59addfce5eae78efdc2c5fb070799a30 | 14,048 | package org.apache.poi.hssf.record;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.CFRuleRecord;
import org.apache.poi.hssf.record.RecordInputStream;
import org.apache.poi.hssf.record.StandardRecord;
import org.apache.poi.hssf.record.cf.BorderFormatting;
import org.apache.poi.hssf.record.cf.FontFormatting;
import org.apache.poi.hssf.record.cf.PatternFormatting;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.ss.formula.Formula;
import org.apache.poi.ss.formula.FormulaType;
import org.apache.poi.ss.formula.ptg.Ptg;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.util.BitField;
import org.apache.poi.util.BitFieldFactory;
import org.apache.poi.util.LittleEndianOutput;
import org.apache.poi.util.POILogFactory;
import org.apache.poi.util.POILogger;
public abstract class CFRuleBase extends StandardRecord implements Cloneable {
protected static final POILogger logger = POILogFactory.getLogger(CFRuleBase.class);
private byte condition_type;
public static final byte CONDITION_TYPE_CELL_VALUE_IS = 1;
public static final byte CONDITION_TYPE_FORMULA = 2;
public static final byte CONDITION_TYPE_COLOR_SCALE = 3;
public static final byte CONDITION_TYPE_DATA_BAR = 4;
public static final byte CONDITION_TYPE_FILTER = 5;
public static final byte CONDITION_TYPE_ICON_SET = 6;
private byte comparison_operator;
public static final int TEMPLATE_CELL_VALUE = 0;
public static final int TEMPLATE_FORMULA = 1;
public static final int TEMPLATE_COLOR_SCALE_FORMATTING = 2;
public static final int TEMPLATE_DATA_BAR_FORMATTING = 3;
public static final int TEMPLATE_ICON_SET_FORMATTING = 4;
public static final int TEMPLATE_FILTER = 5;
public static final int TEMPLATE_UNIQUE_VALUES = 7;
public static final int TEMPLATE_CONTAINS_TEXT = 8;
public static final int TEMPLATE_CONTAINS_BLANKS = 9;
public static final int TEMPLATE_CONTAINS_NO_BLANKS = 10;
public static final int TEMPLATE_CONTAINS_ERRORS = 11;
public static final int TEMPLATE_CONTAINS_NO_ERRORS = 12;
public static final int TEMPLATE_TODAY = 15;
public static final int TEMPLATE_TOMORROW = 16;
public static final int TEMPLATE_YESTERDAY = 17;
public static final int TEMPLATE_LAST_7_DAYS = 18;
public static final int TEMPLATE_LAST_MONTH = 19;
public static final int TEMPLATE_NEXT_MONTH = 20;
public static final int TEMPLATE_THIS_WEEK = 21;
public static final int TEMPLATE_NEXT_WEEK = 22;
public static final int TEMPLATE_LAST_WEEK = 23;
public static final int TEMPLATE_THIS_MONTH = 24;
public static final int TEMPLATE_ABOVE_AVERAGE = 25;
public static final int TEMPLATE_BELOW_AVERAGE = 26;
public static final int TEMPLATE_DUPLICATE_VALUES = 27;
public static final int TEMPLATE_ABOVE_OR_EQUAL_TO_AVERAGE = 29;
public static final int TEMPLATE_BELOW_OR_EQUAL_TO_AVERAGE = 30;
static final BitField modificationBits = bf(4194303);
static final BitField alignHor = bf(1);
static final BitField alignVer = bf(2);
static final BitField alignWrap = bf(4);
static final BitField alignRot = bf(8);
static final BitField alignJustLast = bf(16);
static final BitField alignIndent = bf(32);
static final BitField alignShrin = bf(64);
static final BitField mergeCell = bf(128);
static final BitField protLocked = bf(256);
static final BitField protHidden = bf(512);
static final BitField bordLeft = bf(1024);
static final BitField bordRight = bf(2048);
static final BitField bordTop = bf(4096);
static final BitField bordBot = bf(8192);
static final BitField bordTlBr = bf(16384);
static final BitField bordBlTr = bf('\u8000');
static final BitField pattStyle = bf(65536);
static final BitField pattCol = bf(131072);
static final BitField pattBgCol = bf(262144);
static final BitField notUsed2 = bf(3670016);
static final BitField undocumented = bf(62914560);
static final BitField fmtBlockBits = bf(2080374784);
static final BitField font = bf(67108864);
static final BitField align = bf(134217728);
static final BitField bord = bf(268435456);
static final BitField patt = bf(536870912);
static final BitField prot = bf(1073741824);
static final BitField alignTextDir = bf(Integer.MIN_VALUE);
protected int formatting_options;
protected short formatting_not_used;
protected FontFormatting _fontFormatting;
protected BorderFormatting _borderFormatting;
protected PatternFormatting _patternFormatting;
private Formula formula1;
private Formula formula2;
private static BitField bf(int i) {
return BitFieldFactory.getInstance(i);
}
protected CFRuleBase(byte conditionType, byte comparisonOperation) {
this.setConditionType(conditionType);
this.setComparisonOperation(comparisonOperation);
this.formula1 = Formula.create(Ptg.EMPTY_PTG_ARRAY);
this.formula2 = Formula.create(Ptg.EMPTY_PTG_ARRAY);
}
protected CFRuleBase(byte conditionType, byte comparisonOperation, Ptg[] formula1, Ptg[] formula2) {
this(conditionType, comparisonOperation);
this.formula1 = Formula.create(formula1);
this.formula2 = Formula.create(formula2);
}
protected CFRuleBase() {}
protected int readFormatOptions(RecordInputStream in) {
this.formatting_options = in.readInt();
this.formatting_not_used = in.readShort();
int len = 6;
if(this.containsFontFormattingBlock()) {
this._fontFormatting = new FontFormatting(in);
len += this._fontFormatting.getDataLength();
}
if(this.containsBorderFormattingBlock()) {
this._borderFormatting = new BorderFormatting(in);
len += this._borderFormatting.getDataLength();
}
if(this.containsPatternFormattingBlock()) {
this._patternFormatting = new PatternFormatting(in);
len += this._patternFormatting.getDataLength();
}
return len;
}
public byte getConditionType() {
return this.condition_type;
}
protected void setConditionType(byte condition_type) {
if(this instanceof CFRuleRecord && condition_type != 1 && condition_type != 2) {
throw new IllegalArgumentException("CFRuleRecord only accepts Value-Is and Formula types");
} else {
this.condition_type = condition_type;
}
}
public void setComparisonOperation(byte operation) {
if(operation >= 0 && operation <= 8) {
this.comparison_operator = operation;
} else {
throw new IllegalArgumentException("Valid operators are only in the range 0 to 8");
}
}
public byte getComparisonOperation() {
return this.comparison_operator;
}
public boolean containsFontFormattingBlock() {
return this.getOptionFlag(font);
}
public void setFontFormatting(FontFormatting fontFormatting) {
this._fontFormatting = fontFormatting;
this.setOptionFlag(fontFormatting != null, font);
}
public FontFormatting getFontFormatting() {
return this.containsFontFormattingBlock()?this._fontFormatting:null;
}
public boolean containsAlignFormattingBlock() {
return this.getOptionFlag(align);
}
public void setAlignFormattingUnchanged() {
this.setOptionFlag(false, align);
}
public boolean containsBorderFormattingBlock() {
return this.getOptionFlag(bord);
}
public void setBorderFormatting(BorderFormatting borderFormatting) {
this._borderFormatting = borderFormatting;
this.setOptionFlag(borderFormatting != null, bord);
}
public BorderFormatting getBorderFormatting() {
return this.containsBorderFormattingBlock()?this._borderFormatting:null;
}
public boolean containsPatternFormattingBlock() {
return this.getOptionFlag(patt);
}
public void setPatternFormatting(PatternFormatting patternFormatting) {
this._patternFormatting = patternFormatting;
this.setOptionFlag(patternFormatting != null, patt);
}
public PatternFormatting getPatternFormatting() {
return this.containsPatternFormattingBlock()?this._patternFormatting:null;
}
public boolean containsProtectionFormattingBlock() {
return this.getOptionFlag(prot);
}
public void setProtectionFormattingUnchanged() {
this.setOptionFlag(false, prot);
}
public int getOptions() {
return this.formatting_options;
}
private boolean isModified(BitField field) {
return !field.isSet(this.formatting_options);
}
private void setModified(boolean modified, BitField field) {
this.formatting_options = field.setBoolean(this.formatting_options, !modified);
}
public boolean isLeftBorderModified() {
return this.isModified(bordLeft);
}
public void setLeftBorderModified(boolean modified) {
this.setModified(modified, bordLeft);
}
public boolean isRightBorderModified() {
return this.isModified(bordRight);
}
public void setRightBorderModified(boolean modified) {
this.setModified(modified, bordRight);
}
public boolean isTopBorderModified() {
return this.isModified(bordTop);
}
public void setTopBorderModified(boolean modified) {
this.setModified(modified, bordTop);
}
public boolean isBottomBorderModified() {
return this.isModified(bordBot);
}
public void setBottomBorderModified(boolean modified) {
this.setModified(modified, bordBot);
}
public boolean isTopLeftBottomRightBorderModified() {
return this.isModified(bordTlBr);
}
public void setTopLeftBottomRightBorderModified(boolean modified) {
this.setModified(modified, bordTlBr);
}
public boolean isBottomLeftTopRightBorderModified() {
return this.isModified(bordBlTr);
}
public void setBottomLeftTopRightBorderModified(boolean modified) {
this.setModified(modified, bordBlTr);
}
public boolean isPatternStyleModified() {
return this.isModified(pattStyle);
}
public void setPatternStyleModified(boolean modified) {
this.setModified(modified, pattStyle);
}
public boolean isPatternColorModified() {
return this.isModified(pattCol);
}
public void setPatternColorModified(boolean modified) {
this.setModified(modified, pattCol);
}
public boolean isPatternBackgroundColorModified() {
return this.isModified(pattBgCol);
}
public void setPatternBackgroundColorModified(boolean modified) {
this.setModified(modified, pattBgCol);
}
private boolean getOptionFlag(BitField field) {
return field.isSet(this.formatting_options);
}
private void setOptionFlag(boolean flag, BitField field) {
this.formatting_options = field.setBoolean(this.formatting_options, flag);
}
protected int getFormattingBlockSize() {
return 6 + (this.containsFontFormattingBlock()?this._fontFormatting.getRawRecord().length:0) + (this.containsBorderFormattingBlock()?8:0) + (this.containsPatternFormattingBlock()?4:0);
}
protected void serializeFormattingBlock(LittleEndianOutput out) {
out.writeInt(this.formatting_options);
out.writeShort(this.formatting_not_used);
if(this.containsFontFormattingBlock()) {
byte[] fontFormattingRawRecord = this._fontFormatting.getRawRecord();
out.write(fontFormattingRawRecord);
}
if(this.containsBorderFormattingBlock()) {
this._borderFormatting.serialize(out);
}
if(this.containsPatternFormattingBlock()) {
this._patternFormatting.serialize(out);
}
}
public Ptg[] getParsedExpression1() {
return this.formula1.getTokens();
}
public void setParsedExpression1(Ptg[] ptgs) {
this.formula1 = Formula.create(ptgs);
}
protected Formula getFormula1() {
return this.formula1;
}
protected void setFormula1(Formula formula1) {
this.formula1 = formula1;
}
public Ptg[] getParsedExpression2() {
return Formula.getTokens(this.formula2);
}
public void setParsedExpression2(Ptg[] ptgs) {
this.formula2 = Formula.create(ptgs);
}
protected Formula getFormula2() {
return this.formula2;
}
protected void setFormula2(Formula formula2) {
this.formula2 = formula2;
}
protected static int getFormulaSize(Formula formula) {
return formula.getEncodedTokenSize();
}
public static Ptg[] parseFormula(String formula, HSSFSheet sheet) {
if(formula == null) {
return null;
} else {
int sheetIndex = sheet.getWorkbook().getSheetIndex((Sheet)sheet);
return HSSFFormulaParser.parse(formula, sheet.getWorkbook(), FormulaType.CELL, sheetIndex);
}
}
protected void copyTo(CFRuleBase rec) {
rec.condition_type = this.condition_type;
rec.comparison_operator = this.comparison_operator;
rec.formatting_options = this.formatting_options;
rec.formatting_not_used = this.formatting_not_used;
if(this.containsFontFormattingBlock()) {
rec._fontFormatting = this._fontFormatting.clone();
}
if(this.containsBorderFormattingBlock()) {
rec._borderFormatting = this._borderFormatting.clone();
}
if(this.containsPatternFormattingBlock()) {
rec._patternFormatting = (PatternFormatting)this._patternFormatting.clone();
}
rec.setFormula1(this.getFormula1().copy());
rec.setFormula2(this.getFormula2().copy());
}
public abstract CFRuleBase clone();
public static final class ComparisonOperator {
public static final byte NO_COMPARISON = 0;
public static final byte BETWEEN = 1;
public static final byte NOT_BETWEEN = 2;
public static final byte EQUAL = 3;
public static final byte NOT_EQUAL = 4;
public static final byte GT = 5;
public static final byte LT = 6;
public static final byte GE = 7;
public static final byte LE = 8;
private static final byte max_operator = 8;
}
}
| 33.769231 | 190 | 0.725797 |
28f2105537cd65f1ca4b5f0b12632e04b531832c | 268 | package com.huanchengfly.tieba.post.interfaces;
import android.graphics.Bitmap;
import android.webkit.WebView;
public interface WebViewListener {
void onPageFinished(WebView view, String url);
void onPageStarted(WebView view, String url, Bitmap favicon);
}
| 24.363636 | 65 | 0.791045 |
68e48ff206afd7b83bbbdb5bedcac4eeaad5e760 | 554 | package noppes.npcs.api.event;
import noppes.npcs.api.handler.IFactionHandler;
import noppes.npcs.api.handler.IRecipeHandler;
public class HandlerEvent {
public static class RecipesLoadedEvent extends CustomNPCsEvent{
public final IRecipeHandler handler;
public RecipesLoadedEvent(IRecipeHandler handler) {
this.handler = handler;
}
}
public static class FactionsLoadedEvent extends CustomNPCsEvent{
public final IFactionHandler handler;
public FactionsLoadedEvent(IFactionHandler handler) {
this.handler = handler;
}
}
}
| 23.083333 | 65 | 0.788809 |
6d970b8a3772a9be465f3cac099f79422697daeb | 331 | package xyz.einandartun.movieshelf.viewholders;
import android.support.v7.widget.RecyclerView;
import android.view.View;
/**
* Created by einandartun on 12/31/17.
*/
public class ItemMovieReviewViewHolder extends RecyclerView.ViewHolder {
public ItemMovieReviewViewHolder(View itemView) {
super(itemView);
}
}
| 22.066667 | 72 | 0.761329 |
78d1690b054f9543012d65d20135ea35d99ed3b2 | 24,714 | package edu.wofford.wocoin;
import java.io.*;
import java.sql.*;
import java.security.NoSuchAlgorithmException;
import java.lang.InterruptedException;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutionException;
import javax.crypto.Cipher;
import org.apache.commons.beanutils.converters.SqlDateConverter;
import org.apache.commons.io.FileUtils;
import org.web3j.crypto.CipherException;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.http.HttpService;
import org.web3j.crypto.WalletUtils;
import java.security.*;
import java.util.List;
import java.util.ArrayList;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Optional;
import org.web3j.crypto.Credentials;
import org.web3j.crypto.RawTransaction;
import org.web3j.crypto.TransactionEncoder;
import org.web3j.protocol.Web3j;
import org.web3j.protocol.core.DefaultBlockParameterName;
import org.web3j.protocol.core.methods.response.EthGetTransactionCount;
import org.web3j.protocol.core.methods.response.EthGetTransactionReceipt;
import org.web3j.protocol.core.methods.response.EthGetBalance;
import org.web3j.protocol.core.methods.response.EthSendTransaction;
import org.web3j.protocol.core.methods.response.TransactionReceipt;
import org.web3j.protocol.http.HttpService;
import org.web3j.utils.Convert;
import org.web3j.utils.Convert.Unit;
import org.web3j.utils.Numeric;
public class Database {
private String adminPwd;
private String url;
private Connection con;
public boolean detectsExisting;
private Web3j web3;
private String address;
private RawTransaction rt;
private BigInteger nonce;
private String senderAddress;
/**
* This is the constructor for db
* @param fileName relative pathname of database to be created
*/
public Database(String fileName) {
adminPwd = "adminpwd";
url = "jdbc:sqlite:" + fileName;
File file = new File(fileName);
if(!file.exists()){
Utilities.createNewDatabase(fileName);
}
}
/**
* Returns the administrator password
* @return the administrators password
*/
public String getAdminPwd(){
return adminPwd;
}
/**
* Checks if administrator is valid
* @param password - user input to check against
* @return boolean if the password exists or not
*/
public boolean checkIsAdmin(String password){
if(password.equals(getAdminPwd())){
return true;
}
else{
return false;
}
}
/**
* Checks if user already exists in the table
* @param id username
* @return boolean if the user exists
*/
public boolean userExists(String id) {
// String testQuery = "SELECT id FROM users WHERE id = ?;";
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM users WHERE id = ?;")) {
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
if (rs.getString(1).equals(id)) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return true;
}
}
/**
* Adds user to the table
*
* @param id this will be the value stored in the id column of the Database
* @param password this value will be salted and hashed and stored in the salt and hash columns of the DB
* @return boolean if user exists or not
*/
public boolean addUser (String id, String password){
if (!userExists(id)) {
String saltedPasswd;
int salt = generateSalt();
saltedPasswd = getSaltedPasswd(password, salt);
String hash = getHash(saltedPasswd);
//url is empty
//sql statement addUser
String testQuery = "INSERT INTO users (id, salt, hash) VALUES (?, ?, ?);";
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement(testQuery)) {
stmt.setString(1, id);
stmt.setInt(2, salt);
stmt.setString(3, hash);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
/**
* Removes a user identified by their id from the Database
*
* @param id a value passed in by the user to be removed
* @return a boolean value of if the user was removed or not
*/
public boolean removeUser (String id){
if (userExists(id)) {
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("DELETE FROM users WHERE id = ?;")) {
stmt.setString(1, id);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
}
/**
* Salts the username
* @return a random salt value
*/
private int generateSalt () {
int saltValue = Utilities.generateSalt();
return saltValue;
}
/**
* Creates salted password
* @param passWd - the plain text password passed into the functions initially
* @param saltValue - a random int that is converted to a string
* @return passWd concatenated with SaltValue
*/
private String getSaltedPasswd (String passWd,int saltValue){
String SaltValueString = Integer.toString(saltValue);
String builder = passWd + SaltValueString;
return builder;
}
/**
* Creates hash of salted password
* @param saltedPasswd this is the value returned from the above function
* @return a string that will be stored in the hash field of the DB
*/
private String getHash (String saltedPasswd){
return Utilities.applySha256(saltedPasswd);
}
/**
* Checks to see if the user has a wallet in the table
* @param id the name of the user
* @return boolean of if the user has a wallet
*/
public boolean walletExists (String id){
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("SELECT id FROM wallets WHERE id = ?;")) {
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
if (rs.getString(1).equals(id)) {
return true;
} else {
return false;
}
} else {
return false;
}
} catch (SQLException e) {
e.printStackTrace();
return true;
}
}
/**
* Creates a wallet for the user
* @param id this is the parameter that reprent's username
* @return whether or not if the wallet was created.
*/
public boolean createWallet (String id, String filename, String password){
String temp = filename + "//" + id + "//";
File dir = new File(temp);
dir.mkdirs();
try {
web3 = Web3j.build(new HttpService());
String walletFileName = WalletUtils.generateFullNewWalletFile(password, dir);
String[] fetchAddress = walletFileName.split("--");
String getAddress = fetchAddress[fetchAddress.length - 1].split("\\.")[0];
address = getAddress;
} catch (NoSuchAlgorithmException e) {
System.out.println("exception");
e.printStackTrace();
return false;
} catch (SecurityException | GeneralSecurityException | IOException | CipherException e) {
e.printStackTrace();
return false;
}
try (Connection conne = DriverManager.getConnection(url);
PreparedStatement stmt = conne.prepareStatement("DELETE FROM wallets WHERE id = ?;")) {
stmt.setString(1, id);
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
String testQuery = "INSERT INTO wallets (id, publickey) VALUES (?, ?);";
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement(testQuery)) {
stmt.setString(1, id);
stmt.setString(2, address);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
private String turnPublicKeyToId (String publicKey){
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM wallets WHERE publickey = ?;")) {
stmt.setString(1, publicKey);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
if (rs.getString(2).equals(publicKey)) {
String builder = rs.getString(1);
return builder;
} else {
return "";
}
} else {
return "";
}
} catch (SQLException e) {
e.printStackTrace();
return "";
}
}
public String turnIdtoPublickey (String id){
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("SELECT * FROM wallets WHERE id = ?;")) {
stmt.setString(1, id);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
return rs.getString(2);
} else {
return "";
}
} catch (SQLException e) {
e.printStackTrace();
return "";
}
}
private boolean isValidName (String name){
return !name.equals("");
}
private boolean isValidPrice ( int price){
return price > 0;
}
private boolean isValidDescription (String description){
return !description.equals("");
}
/**
* Adds a product to the table
* @param seller this is the public key found in the wallets table of the seller of the product
* @param price this is the amount of Wocoins a product costs.
* @param name this is the name of the product.
* @param description this is a user defined description of the product.
* @return whether or not the product was added.
*/
public boolean addProduct (String seller,int price, String name, String description){
String id = turnPublicKeyToId(seller);
if (walletExists(id)) {
if (isValidName(name) && isValidPrice(price) && isValidDescription(description)) {
String testQuery = "INSERT INTO products (seller, price, name, description) VALUES (?, ?, ?, ?);";
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement(testQuery)) {
stmt.setString(1, seller);
stmt.setInt(2, price);
stmt.setString(3, name);
stmt.setString(4, description);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
} else {
return false;
}
}
/**
* Removes a product identified by their id from the Database
* @param name a value passed in by the product to be removed
* @return a boolean value of if the product was removed or not
*/
public boolean removeProduct (String name){
try (Connection conn = DriverManager.getConnection(url);
PreparedStatement stmt = conn.prepareStatement("DELETE FROM product WHERE name = ?;")) {
stmt.setString(1, name);
stmt.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
/**
* Displays the product
* @return a list of all of the products in order by price and name
*/
public List<Product> displayProductF6() {
List<Product> list = new ArrayList<>();
try(Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
ResultSet rsCount = stmt.executeQuery("select count(*) from products;");
int n = rsCount.getInt(1);
ResultSet rs = stmt.executeQuery("select * from products order by price, name collate nocase;");
rs.next();
for (int i = 1; i <= n; i++) {
Product p = new Product(rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5));
list.add(p);
rs.next();
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
/**
* Displays a list of the products for the specified user
* @param seller the publicKey for the user
* @return a list of the products created under the user
*/
public List displayProductF5(String seller) {
List<Product> list = new ArrayList<>();
try(Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
ResultSet rsCount = stmt.executeQuery("select count(*) from products;");
int n = rsCount.getInt(1);
ResultSet rs = stmt.executeQuery("select * from products order by price, name collate nocase;");
rs.next();
for (int i = 1; i <= n; i++) {
Product p = new Product(rs.getString(2), rs.getInt(3), rs.getString(4), rs.getString(5));
list.add(p);
rs.next();
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
//write unit tests
/**
* Determines if the password is correct
* @param username of the person querying the db
* @param password of the person querying the db
* @return whether or not if the password is correct g
*/
public boolean passwordCorrect (String username, String password){
return true;
}
/**
* Returns the BigInteger value of the number of times a transaction is sent.
* @return nonce value
* @throws Exception
*/
public BigInteger getNonce() throws Exception {
web3 = Web3j.build(new HttpService("https://mainnet.infura.io/v3/338a115fa5324abeadccd992f9c6cbab"));
senderAddress = "0fce4741f3f54fbffb97837b4ddaa8f769ba0f91";
String toAddr = "0x" + senderAddress;
EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(
toAddr, DefaultBlockParameterName.LATEST).sendAsync().get();
//BigInteger nonce1 = getNonce(toAddress);
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
return nonce;
}
/**
* Sends a transaction of WoCoins to the specified user.
* @param id the user's id
* @param value the amount of WoCoins sent
* @return a boolean indicating if the transaction was sent
*/
public boolean sendTransaction (String id,int value){
String bigValString = Integer.toString(value);
BigInteger bigValue = new BigInteger(bigValString);
String gasLim = "12288";
BigInteger gasLimit = new BigInteger(gasLim);
//maybe change value to big int
senderAddress = "0fce4741f3f54fbffb97837b4ddaa8f769ba0f91";
String toAddress = "0x" + turnIdtoPublickey(id);
if (userExists(id) && walletExists(id)) {
web3 = Web3j.build(new HttpService("https://mainnet.infura.io/v3/338a115fa5324abeadccd992f9c6cbab"));
String path = "ethereum/node0/keystore/UTC--2019-08-07T17-24-10.532680697Z--0fce4741f3f54fbffb97837b4ddaa8f769ba0f91.json";
//getting the nonce
address = "0x" + senderAddress;
try{
EthGetTransactionCount ethGetTransactionCount = web3.ethGetTransactionCount(
address, DefaultBlockParameterName.LATEST).sendAsync().get();
//BigInteger nonce1 = getNonce(toAddress);
BigInteger nonce = ethGetTransactionCount.getTransactionCount();
//create raw transaction object
BigInteger f = new BigInteger("0");
String v = Integer.toString(value);
BigInteger val = new BigInteger(v);
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(
nonce, f,f, toAddress, bigValue);
rt = rawTransaction;
}
catch(InterruptedException | ExecutionException e){
System.out.println("there is an error");
}
try{
//encode and sign transaction object
Credentials credentials = WalletUtils.loadCredentials(
"adminpwd",
"ethereum/node0/keystore/UTC--2019-08-07T17-24-10.532680697Z--0fce4741f3f54fbffb97837b4ddaa8f769ba0f91.json");
byte[] signedMessage = TransactionEncoder.signMessage(rt, credentials);
String hexValue = Numeric.toHexString(signedMessage);
//send the raw transaction object to the node
EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).send();
String transactionHash = ethSendTransaction.getTransactionHash();
EthGetTransactionReceipt ethGetTransactionReceiptResp = web3.ethGetTransactionReceipt(transactionHash).send();
return true;
}
catch(IOException | CipherException e){
System.out.println("error");
}
} else {
return false;
}
return true;
}
/**
* Creating a raw transaction object in order to send a transaction
* @param toAddress wallet that the transaction is being sent to
* @param gasPrice amount of ether willing to pay for ever unit of gas
* @param gasLimit maximum amount of gasPrice willing to spend
* @param amount amount of WoCoins sent
* @param nonce number of times a transaction has been sent
* @return a string hexValue that is the transaction hash
* @throws IOException
* @throws CipherException
*/
public String createOfflineTx(String toAddress, BigInteger gasPrice, BigInteger gasLimit, BigInteger amount, BigInteger nonce) throws IOException, CipherException {
Credentials credentials = WalletUtils.loadCredentials(
"adminpwd",
"ethereum/node0/keystore/UTC--2019-08-07T17-24-10.532680697Z--0fce4741f3f54fbffb97837b4ddaa8f769ba0f91.json");
RawTransaction rawTransaction = RawTransaction.createEtherTransaction(nonce, gasPrice, gasLimit, toAddress, amount);
byte[] signedMessage = TransactionEncoder.signMessage(rawTransaction, credentials);
String hexValue = Numeric.toHexString(signedMessage);
return hexValue;
}
/**
* Sends the transaction
* @param hexValue the transaction hash
* @return a boolean indicating if the transaction was sent
*/
public boolean sendOfflineTx(String hexValue){
try{
EthSendTransaction ethSendTransaction = web3.ethSendRawTransaction(hexValue).send();
String transactionHash = ethSendTransaction.getTransactionHash();
EthGetTransactionReceipt ethGetTransactionReceiptResp = web3.ethGetTransactionReceipt(transactionHash).send();
return true;
}
catch(IOException e){
System.out.println("exception");
return false;
}
}
/**
* Displays the balance of a user's account.
* @param id the user
* @return a string containing the balance of the user's account
* @throws InterruptedException
* @throws ExecutionException
* @throws IOException
* @throws CipherException
*/
public String displayAccountBalance(String id) throws InterruptedException, ExecutionException, IOException, CipherException {
if(!userExists(id)){
return "No such user.";
}
else if (!walletExists(id)){
return "User has no wallet.";
}
else{
Web3j web3 = Web3j.build(new HttpService());
String pubKey = "0x" + turnIdtoPublickey(id);
int balanceInt = -1;
Credentials credentials = WalletUtils.loadCredentials(
"adminpwd",
"ethereum/node0/keystore/UTC--2019-08-07T17-24-10.532680697Z--0fce4741f3f54fbffb97837b4ddaa8f769ba0f91.json");
// send asynchronous requests to get balance
EthGetBalance ethGetBalance = web3
.ethGetBalance(pubKey, DefaultBlockParameterName.LATEST)
.sendAsync()
.get();
BigInteger wei = ethGetBalance.getBalance();
int weiInt=0;
weiInt = wei.intValue();
System.out.println(weiInt);
if(weiInt == 1){
return "User has 1 WoCoin.";
}
else if (weiInt > 1 ) {
return "User has " + weiInt + " WoCoins.";
}
else{
return "User has 0 WoCoins." + weiInt;
}
}
}
public String Carrats (String id){
String builder = "";
String carrats;
String wocoin;
if (userExists(id)) {
//String key = getPublicKey(id);
try (Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement()) {
ResultSet rs = stmt.executeQuery("select *, count(*) over () total_rows from products order by price, name collate nocase;");
rs.next();
int rows = rs.getInt(6);
for (int i = 1; i <= rows; i++) {
if (rs.getString(2).equals(turnIdtoPublickey(id))) {
carrats = ">>> ";
} else {
carrats = "";
}
rs.next();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return builder;
}
}
| 36.078832 | 168 | 0.55066 |
c312fe9460886c06bc9eacf9207a2e71b5cc2a36 | 605 | package org.csuc.typesafe.server;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Test;
import java.io.IOException;
import static org.junit.Assert.assertNotNull;
public class ServerConfigTest {
private static Logger logger = LogManager.getLogger(ServerConfigTest.class);
@Test
public void getConfig() throws IOException {
Application application = new ServerConfig(null).getConfig();
assertNotNull(application);
System.out.println(application.getParserFolder("82fee5e1-7c77-499b-b51a-e6b9ff10e9d1"));
}
} | 26.304348 | 96 | 0.757025 |
9f86e4c75cb7ff544ea2b7ebd2603d889b25c7d4 | 3,917 | /*
* Copyright 2015, TopicQuests
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions
* and limitations under the License.
*/
package org.topicquests.backside.servlet.persist.rdbms;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Statement;
import org.apache.log4j.Logger;
import org.topicquests.backside.servlet.ServletEnvironment;
import org.topicquests.backside.servlet.api.IRDBMSDatabase;
import org.topicquests.support.api.IResult;
/**
* <p>Title: StoryReader Engine</p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2008 Jack Park</p>
*
* <p>Company: NexistGroup</p>
*
* @author Jack Park
*/
public class H2DatabaseDriver implements IRDBMSDatabase {
protected ServletEnvironment environment;
public static final String h2JdbcDriver =
"org.h2.Driver";
protected String userName, password, connectionString;
public H2DatabaseDriver(ServletEnvironment env, String dbName,String userName, String pwd, String filePath)
throws Exception {
System.out.println("H2DBStart "+filePath);
environment = env;
this.userName = userName;
this.password = pwd;
connectionString = "jdbc:h2:file:"+filePath+"/"+dbName;//+";create=true;";
Class.forName(h2JdbcDriver).newInstance();
environment.logDebug("H2Database started: "+dbName);
}
public Connection getSQLConnection() throws SQLException {
System.out.println("DATABASE GETCONNECTION "+connectionString);
//userName and password are used when creating tables, so they must be
// used when accessing those tables
return DriverManager.getConnection(connectionString, userName,password);
}
////////////////////////////
//Utilities
public void closeConnection(Connection conn, IResult r) {
try {
if (conn != null)
conn.close();
} catch (Exception e) {
environment.logError(e.getMessage(), e);
r.addErrorString(e.getMessage());
}
}
public void closeResultSet(ResultSet rs, IResult r) {
try {
if (rs != null)
rs.close();
} catch (Exception e) {
environment.logError(e.getMessage(), e);
r.addErrorString(e.getMessage());
}
}
public void closePreparedStatement(PreparedStatement ps, IResult r) {
try {
if (ps != null)
ps.close();
} catch (Exception e) {
environment.logError(e.getMessage(), e);
r.addErrorString(e.getMessage());
}
}
public void closeStatement(Statement s, IResult r) {
try {
if (s != null)
s.close();
} catch (Exception e) {
environment.logError(e.getMessage(), e);
r.addErrorString(e.getMessage());
}
}
@Override
public Connection getConnection() throws Exception {
return getSQLConnection();
}
@Override
public void shutDown() {
// TODO Auto-generated method stub
}
@Override
public void closeConnection(Connection con) throws SQLException {
// TODO Auto-generated method stub
}
}
/**
* Template
IResult result = new ResultObject();
Connection conn = null;
PreparedStatement s = null;
ResultSet rs = null;
try {
conn = getSQLConnection();
//TODO
} catch (Exception e) {
environment.logError(e.getMessage(),e);
result.addErrorString(e.getMessage());
} finally {
closeResultSet(rs,result);
closePreparedStatement(s,result);
closeConnection(conn,result);
}
return result;
*/
| 27.584507 | 111 | 0.696196 |
172df3892a417aaf09c1fc448d9394b0271d0341 | 1,871 | /*
* SchemaListModel.java
*
* Created on Fri Feb 20 13:58:56 EST 2004
*
* Copyright (c) 2004 Spallation Neutron Source
* Oak Ridge National Laboratory
* Oak Ridge, TN 37830
*/
package xal.app.dbbrowser;
import javax.swing.*;
/**
* SchemaListModel
*
* @author tap
*/
public class SchemaListModel extends AbstractListModel<String> {
/** serialization identifier */
private static final long serialVersionUID = 1L;
/** Browser model providing the list of database tables */
protected BrowserModel _model;
/**
* TableListModel constructor
*/
public SchemaListModel(BrowserModel aModel) {
_model = aModel;
_model.addBrowserModelListener( new BrowserModelListener() {
/**
* Database schema changed notification
* @param model The browser model whose database schema changed
* @param newSchema The new database schema
*/
public void schemaChanged(BrowserModel model, String newSchema) {}
/**
* Database table changed notification
* @param model The browser model whose database table changed
* @param newTable The new database table
*/
public void tableChanged(BrowserModel model, String newTable) {}
/**
* The model's connection has changed
* @param model The model whose connection changed
*/
public void connectionChanged(BrowserModel model) {
fireContentsChanged(this, 0, getSize());
}
});
}
/**
* Get the number of schemas for the selected schema
* @return The number of schemas to display
*/
public int getSize() {
return _model.getSchemas().size();
}
/**
* Get the schema name for the specified schema index
* @param index The index of the schema to display
* @return the name of the schema for the specified index
*/
public String getElementAt(int index) {
return _model.getSchemas().get(index);
}
}
| 22.817073 | 69 | 0.691074 |
6b588f9a83498c80a5a7243b37b53304d8af7731 | 1,765 | package org.kie.services.client.serialization.jaxb;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import org.kie.services.client.serialization.jaxb.impl.JaxbProcessInstanceResponse;
import org.kie.services.client.serialization.jaxb.impl.JaxbProcessInstanceWithVariablesResponse;
import org.kie.services.client.serialization.jaxb.impl.JaxbVariablesResponse;
import org.kie.services.client.serialization.jaxb.rest.JaxbGenericResponse;
// TODO: Add object version checking
public class JaxbSerializationProvider {
private static Class<?> [] jaxbClasses = {
JaxbCommandsRequest.class,
JaxbCommandsResponse.class,
JaxbVariablesResponse.class,
JaxbGenericResponse.class,
JaxbProcessInstanceResponse.class,
JaxbProcessInstanceWithVariablesResponse.class
};
public static String convertJaxbObjectToString(Object object) throws JAXBException {
Marshaller marshaller = JAXBContext.newInstance(jaxbClasses).createMarshaller();
StringWriter stringWriter = new StringWriter();
marshaller.marshal(object, stringWriter);
String output = stringWriter.toString();
return output;
}
public static Object convertStringToJaxbObject(String xmlStr) throws JAXBException {
Unmarshaller unmarshaller = JAXBContext.newInstance(jaxbClasses).createUnmarshaller();
ByteArrayInputStream xmlStrInputStream = new ByteArrayInputStream(xmlStr.getBytes());
Object jaxbObj = unmarshaller.unmarshal(xmlStrInputStream);
return jaxbObj;
}
}
| 36.770833 | 96 | 0.753541 |
73ac0e4002c7853c709b6c4421e73c08ee6a76dc | 813 | package threads.server.model;
import android.app.Application;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import java.util.List;
import threads.server.core.peers.PEERS;
import threads.server.core.peers.User;
import threads.server.core.peers.UsersDatabase;
public class LiteUsersViewModel extends AndroidViewModel {
@NonNull
private final UsersDatabase usersDatabase;
public LiteUsersViewModel(@NonNull Application application) {
super(application);
usersDatabase = PEERS.getInstance(
application.getApplicationContext()).getUsersDatabase();
}
@NonNull
public LiveData<List<User>> getLiteUsers() {
return usersDatabase.userDao().getLiveDataNonBlockedLiteUsers();
}
} | 27.1 | 72 | 0.758918 |
d324f02ab30be358d5d8fbf612803fd358e669ef | 3,537 | package com.webcheckers.ui;
import com.webcheckers.application.GameManager;
import com.webcheckers.application.PlayerLobby;
import com.webcheckers.model.Player;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.Session;
import java.util.logging.Logger;
import static com.webcheckers.ui.GetHomeRoute.ERROR_MESSAGE_KEY;
import static spark.Spark.halt;
/**
* The {@code POST /requestGame} route handler.
*
* @author Austin Miller 'akm8654'
* @author Mario Castano
*/
public class PostRequestGameRoute implements Route
{
private static final Logger LOG = Logger.getLogger(GetHomeRoute.class.getName());
// Values used in the view-model map for rendering the Challenge Player/requestGame screen
static final String MESSAGE = "message";
static final String REQUEST_VAL = "gameRequest";
/**
* {@inheritDoc}
* <p>
* The handler for requests by players to start a game. First, a user challenges another user,
* and a request is sent consists of the player's username and the challengee's username from
* the list of users logged onto the playerLobby.
*/
@Override
public String handle(Request request, Response response)
{
LOG.config("PostRequestGame has been invoked");
//retrieve the playerLobby object from which the usernames of logged in players can be retrieved
final Session httpSession = request.session();
final GameManager gameManager = httpSession.attribute(GetHomeRoute.GAME_MANAGER_KEY);
final PlayerLobby playerLobby =
httpSession.attribute(GetHomeRoute.PLAYER_LOBBY_KEY);
final Player player = httpSession.attribute(GetHomeRoute.PLAYER_KEY);
/* A null playerLobby indicates a timed out session or an illegal request on this URL.
* In either case, we will redirect back to home.
*/
if (playerLobby != null)
{
// person who is being challenged.
String challengerStr = request.queryParams(REQUEST_VAL);
challengerStr = challengerStr.replace('-', ' ');
String username = player.getUsername();
//if the victim is being
if (playerLobby.getChallenges().get(username) != null)
{
httpSession.attribute(ERROR_MESSAGE_KEY, "Request Not Sent! You have a pending request.");
response.redirect(WebServer.HOME_URL);
return null;
} else if (playerLobby.getChallengers().contains(username))
{
httpSession.attribute(ERROR_MESSAGE_KEY, "Request Not Sent! You've already" +
" sent a challenge!");
response.redirect(WebServer.HOME_URL);
return null;
} else if (gameManager.getInGame().contains(challengerStr))
{
httpSession.attribute(ERROR_MESSAGE_KEY, "Request Not Sent! " +
challengerStr + " is already in a game.");
} else if (!playerLobby.challenge(challengerStr, username))
{
httpSession.attribute(ERROR_MESSAGE_KEY, "Request Not Sent! " +
challengerStr + " has already been challenged.");
} else
{
if (playerLobby.challenging(challengerStr, username))
{
httpSession.attribute(ERROR_MESSAGE_KEY, "Request Not Sent! " +
challengerStr + " is already challenging someone!");
} else
{
httpSession.attribute(MESSAGE, "Request sent to " + challengerStr +
".");
}
}
response.redirect(WebServer.HOME_URL);
} else
{
response.redirect(WebServer.HOME_URL);
halt();
}
return null;
}
}
| 35.37 | 100 | 0.681934 |
1ee6ce71a469bc3d2c2684e3fa14fc7aa0e94a98 | 6,983 | /*
* Copyright 2015-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.protocols.raft;
import io.atomix.primitive.PrimitiveException;
import static com.google.common.base.MoreObjects.toStringHelper;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Base type for Raft protocol errors.
* <p>
* Raft errors are passed on the wire in lieu of exceptions to reduce the overhead of serialization.
* Each error is identifiable by an error ID which is used to serialize and deserialize errors.
*/
public class RaftError {
private final Type type;
private final String message;
public RaftError(Type type, String message) {
this.type = checkNotNull(type, "type cannot be null");
this.message = message;
}
/**
* Returns the error type.
*
* @return The error type.
*/
public Type type() {
return type;
}
/**
* Returns the error message.
*
* @return The error message.
*/
public String message() {
return message;
}
/**
* Creates a new exception for the error.
*
* @return The error exception.
*/
public PrimitiveException createException() {
return type.createException(message);
}
@Override
public String toString() {
return toStringHelper(this)
.add("type", type)
.add("message", message)
.toString();
}
/**
* Raft error types.
*/
public enum Type {
/**
* No leader error.
*/
NO_LEADER {
@Override
PrimitiveException createException() {
return createException("Failed to locate leader");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.Unavailable(message) : createException();
}
},
/**
* Read application error.
*/
QUERY_FAILURE {
@Override
PrimitiveException createException() {
return createException("Failed to obtain read quorum");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.QueryFailure(message) : createException();
}
},
/**
* Write application error.
*/
COMMAND_FAILURE {
@Override
PrimitiveException createException() {
return createException("Failed to obtain write quorum");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.CommandFailure(message) : createException();
}
},
/**
* User application error.
*/
APPLICATION_ERROR {
@Override
PrimitiveException createException() {
return createException("An application error occurred");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.ServiceException(message) : createException();
}
},
/**
* Illegal member state error.
*/
ILLEGAL_MEMBER_STATE {
@Override
PrimitiveException createException() {
return createException("Illegal member state");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.Unavailable(message) : createException();
}
},
/**
* Unknown client error.
*/
UNKNOWN_CLIENT {
@Override
PrimitiveException createException() {
return createException("Unknown client");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.UnknownClient(message) : createException();
}
},
/**
* Unknown session error.
*/
UNKNOWN_SESSION {
@Override
PrimitiveException createException() {
return createException("Unknown member session");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.UnknownSession(message) : createException();
}
},
/**
* Unknown state machine error.
*/
UNKNOWN_SERVICE {
@Override
PrimitiveException createException() {
return createException("Unknown primitive service");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.UnknownService(message) : createException();
}
},
/**
* Closed session error.
*/
CLOSED_SESSION {
@Override
PrimitiveException createException() {
return createException("Closed session");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.ClosedSession(message) : createException();
}
},
/**
* Internal error.
*/
PROTOCOL_ERROR {
@Override
PrimitiveException createException() {
return createException("Failed to reach consensus");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.Unavailable(message) : createException();
}
},
/**
* Configuration error.
*/
CONFIGURATION_ERROR {
@Override
PrimitiveException createException() {
return createException("Configuration failed");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.Unavailable(message) : createException();
}
},
/**
* Unavailable service error.
*/
UNAVAILABLE {
@Override
PrimitiveException createException() {
return createException("Service is unavailable");
}
@Override
PrimitiveException createException(String message) {
return message != null ? new PrimitiveException.Unavailable(message) : createException();
}
};
/**
* Creates an exception with a default message.
*
* @return the exception
*/
abstract PrimitiveException createException();
/**
* Creates an exception with the given message.
*
* @param message the exception message
* @return the exception
*/
abstract PrimitiveException createException(String message);
}
}
| 25.485401 | 102 | 0.645997 |
cea2f32ff6bb38d5689eec3b9ecd63d42ff78ef9 | 4,085 | /*
* Copyright (C) 2006-2021 Talend Inc. - www.talend.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.
*/
package org.talend.components.rest.service.client;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.talend.components.common.text.Substitutor;
import org.talend.components.rest.configuration.RequestBody;
import org.talend.components.rest.configuration.RequestConfig;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.talend.components.common.service.http.UrlEncoder.queryEncode;
@Data
@AllArgsConstructor
public class Body {
public final static String BODY_FORMADATA_BOUNDARY = System.getProperty(
"org.talend.components.rest.service.body_formdata_boundary",
"----------------------- org.talend.components.rest.service.body_formdata_boundary");
private final RequestBody conf;
private final Substitutor substitutor;
private final String charsetName;
public Body(final RequestConfig config, final Substitutor substitutor) {
this.conf = config.getDataset().getBody();
this.substitutor = substitutor;
if (config.getDataset().isHasHeaders()) {
Map<String, List<String>> headers = config.headers().entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, e -> Collections.singletonList(e.getValue())));
charsetName = ContentType.getCharsetName(headers);
} else {
charsetName = null;
}
}
public byte[] getContent() {
switch (conf.getType()) {
case FORM_DATA:
return formDataStrategy();
case X_WWW_FORM_URLENCODED:
return xwwwformStrategy();
default:
return textStrategy();
}
}
private byte[] xwwwformStrategy() {
return encode(Optional.ofNullable(conf.getParams()).orElse(Collections.emptyList()).stream()
.filter(p -> p.getKey() != null && p.getValue() != null)
.filter(p -> !p.getKey().isEmpty() || !p.getValue().isEmpty())
.map(param -> param.getKey() + "=" + queryEncode(substitute(param.getValue()))).collect(Collectors.joining("&")));
}
private byte[] formDataStrategy() {
return encode("--" + BODY_FORMADATA_BOUNDARY + "\n" + Optional.ofNullable(conf.getParams())
.orElse(Collections.emptyList()).stream().filter(p -> p.getKey() != null && p.getValue() != null)
.filter(p -> !p.getKey().isEmpty() || !p.getValue().isEmpty())
.map(param -> "Content-Disposition: form-data; name=\"" + param.getKey() + "\"\n\n"
+ substitute(param.getValue()))
.collect(Collectors.joining("\n" + "--" + BODY_FORMADATA_BOUNDARY + "\n")) + "\n" + "--" + BODY_FORMADATA_BOUNDARY
+ "--");
}
private byte[] textStrategy() {
return encode(substitute(Optional.ofNullable(conf.getTextContent()).orElse("")));
}
private byte[] encode(String s) {
if (charsetName == null) {
if (ContentType.DEFAULT_ENCODING == null) {
return s.getBytes();
} else {
return s.getBytes(Charset.forName(ContentType.DEFAULT_ENCODING));
}
} else {
return s.getBytes(Charset.forName(charsetName));
}
}
private String substitute(final String value) {
return this.substitutor.replace(value);
}
}
| 38.537736 | 130 | 0.640636 |
c50fdd4e5c4f3195ae824850e75ac6a8ac7cf7ab | 973 | package com.example.demo.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private DiscoveryClient client;
@GetMapping("/info")
public String info() {
@SuppressWarnings("deprecation")
ServiceInstance instance = client.getLocalServiceInstance();
String info = "host:" + instance.getHost() + ",service_id:" + instance.getServiceId();
log.info(info);
return info;
}
@GetMapping("/hello")
public String hello() {
return "hello world";
}
}
| 29.484848 | 94 | 0.73073 |
6d2888aa506aab1ac3d4215964f42bf2e7a8b739 | 248 | package org.bidtime.activiti.server.provider.service.LeaveApply.dao;
import org.bidtime.activiti.server.api.po.LeaveApply;
public interface LeaveApplyMapper {
void save(LeaveApply apply);
LeaveApply get(int id);
void update(LeaveApply app);
}
| 24.8 | 68 | 0.802419 |
148878a846cf57a329c4bbe4f96a73aeb47846bf | 538 | import java.lang.*;
import java.util.*;
class Solution {
public int solution(String S) {
if (S.length() == 0) {
return 1;
}
int openingBraces = 0;
for (char letter : S.toCharArray()) {
if (letter == '(') {
openingBraces++;
}
else {
--openingBraces;
if (openingBraces < 0) {
return 0;
}
}
}
return openingBraces == 0 ? 1 : 0;
}
} | 22.416667 | 45 | 0.384758 |
6ff47254fd35806779c7dcde27319494621cb14c | 836 | package com.withertech.tim_wim_holes.mixin.client.tardis.models.exterior;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.tardis.mod.client.models.exteriors.ExteriorModel;
import net.tardis.mod.client.models.exteriors.PoliceBoxExteriorModel;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(PoliceBoxExteriorModel.class)
public abstract class MixinPoliceBoxExteriorModel extends ExteriorModel
{
@Shadow @Final private ModelRenderer boti;
@Inject(method = "<init>()V", at = @At("TAIL"))
public void init(CallbackInfo ci)
{
boti.showModel = false;
}
}
| 34.833333 | 73 | 0.815789 |
a6209a5e26582d14791351e9e41ed7536f3f6bb6 | 535 | package com.crosshairengine.firstgame.engine.Abstract_classes;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import java.util.Vector;
/**
* Created by CrossHairEngine team on 5/1/2017.
*/
// Tile is static should be part of the Map
// Tile is needed, so it get to be defined in engine
//
public abstract class Tile extends CDrawable {
public Tile(Bitmap bitmap) {
this.m_bSprate = bitmap;
}
public Tile(Bitmap bitmap, int leftPx, int topPx) {
super(bitmap, leftPx, topPx);
}
}
| 21.4 | 62 | 0.704673 |
389037d374bac8357d6f0039c2553630656a9185 | 864 | package com.allen.springframework.filter;
import org.springframework.util.StringUtils;
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;
public class MyOncePerRequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String allen = request.getParameter("allen");
System.out.println(allen);
if(StringUtils.isEmpty(allen) || !"xxx".equalsIgnoreCase(allen)) {
throw new ServletException("过滤了。。。");
}
filterChain.doFilter(request,response);
}
}
| 36 | 157 | 0.769676 |
a2d114c99681526b619f7d88cec381dd587ac817 | 4,163 | package org.opencv.ml;
import org.opencv.core.Mat;
public class CvSVM extends CvStatModel {
public static final int f207C = 0;
public static final int COEF = 4;
public static final int C_SVC = 100;
public static final int DEGREE = 5;
public static final int EPS_SVR = 103;
public static final int GAMMA = 1;
public static final int LINEAR = 0;
public static final int NU = 3;
public static final int NU_SVC = 101;
public static final int NU_SVR = 104;
public static final int ONE_CLASS = 102;
public static final int f208P = 2;
public static final int POLY = 1;
public static final int RBF = 2;
public static final int SIGMOID = 3;
private static native long CvSVM_0();
private static native long CvSVM_1(long j, long j2, long j3, long j4, long j5);
private static native long CvSVM_2(long j, long j2);
private static native void clear_0(long j);
private static native void delete(long j);
private static native int get_support_vector_count_0(long j);
private static native int get_var_count_0(long j);
private static native float predict_0(long j, long j2, boolean z);
private static native float predict_1(long j, long j2);
private static native void predict_all_0(long j, long j2, long j3);
private static native boolean train_0(long j, long j2, long j3, long j4, long j5, long j6);
private static native boolean train_1(long j, long j2, long j3);
private static native boolean train_auto_0(long j, long j2, long j3, long j4, long j5, long j6, int i, long j7, long j8, long j9, long j10, long j11, long j12, boolean z);
private static native boolean train_auto_1(long j, long j2, long j3, long j4, long j5, long j6);
protected CvSVM(long addr) {
super(addr);
}
public CvSVM() {
super(CvSVM_0());
}
public CvSVM(Mat trainData, Mat responses, Mat varIdx, Mat sampleIdx, CvSVMParams params) {
super(CvSVM_1(trainData.nativeObj, responses.nativeObj, varIdx.nativeObj, sampleIdx.nativeObj, params.nativeObj));
}
public CvSVM(Mat trainData, Mat responses) {
super(CvSVM_2(trainData.nativeObj, responses.nativeObj));
}
public void clear() {
clear_0(this.nativeObj);
}
public int get_support_vector_count() {
return get_support_vector_count_0(this.nativeObj);
}
public int get_var_count() {
return get_var_count_0(this.nativeObj);
}
public float predict(Mat sample, boolean returnDFVal) {
return predict_0(this.nativeObj, sample.nativeObj, returnDFVal);
}
public float predict(Mat sample) {
return predict_1(this.nativeObj, sample.nativeObj);
}
public void predict_all(Mat samples, Mat results) {
predict_all_0(this.nativeObj, samples.nativeObj, results.nativeObj);
}
public boolean train(Mat trainData, Mat responses, Mat varIdx, Mat sampleIdx, CvSVMParams params) {
return train_0(this.nativeObj, trainData.nativeObj, responses.nativeObj, varIdx.nativeObj, sampleIdx.nativeObj, params.nativeObj);
}
public boolean train(Mat trainData, Mat responses) {
return train_1(this.nativeObj, trainData.nativeObj, responses.nativeObj);
}
public boolean train_auto(Mat trainData, Mat responses, Mat varIdx, Mat sampleIdx, CvSVMParams params, int k_fold, CvParamGrid Cgrid, CvParamGrid gammaGrid, CvParamGrid pGrid, CvParamGrid nuGrid, CvParamGrid coeffGrid, CvParamGrid degreeGrid, boolean balanced) {
return train_auto_0(this.nativeObj, trainData.nativeObj, responses.nativeObj, varIdx.nativeObj, sampleIdx.nativeObj, params.nativeObj, k_fold, Cgrid.nativeObj, gammaGrid.nativeObj, pGrid.nativeObj, nuGrid.nativeObj, coeffGrid.nativeObj, degreeGrid.nativeObj, balanced);
}
public boolean train_auto(Mat trainData, Mat responses, Mat varIdx, Mat sampleIdx, CvSVMParams params) {
return train_auto_1(this.nativeObj, trainData.nativeObj, responses.nativeObj, varIdx.nativeObj, sampleIdx.nativeObj, params.nativeObj);
}
protected void finalize() throws Throwable {
delete(this.nativeObj);
}
}
| 37.845455 | 277 | 0.714629 |
76c3329f2128f56d74b116a6b07270bcb7b4e404 | 235 | package rpc;
/**
* Created by Administrator on 2017/10/7.
*/
/**
*服务提供者实现类
*/
public class HelloServiceImpl implements HelloService{
@Override
public String sayHello(String name) {
return "Hello " + name;
}
}
| 14.6875 | 54 | 0.642553 |
e53e8e45437c52a3c280924f852c991368295cee | 662 | package com.loserico.java8.stream.grouping;
import com.loserico.java8.stream.grouping.model.Person;
import com.loserico.java8.stream.grouping.model.Pet;
import java.util.Arrays;
import java.util.List;
public abstract class AbstractGroup {
protected static List<Person> buildPersonsList() {
Person person1 = new Person("John", "USA", "NYC", new Pet("Max", 5));
Person person2 = new Person("Steve", "UK", "London", new Pet("Lucy", 8));
Person person3 = new Person("Anna", "USA", "NYC", new Pet("Buddy", 12));
Person person4 = new Person("Mike", "USA", "Chicago", new Pet("Duke", 10));
return Arrays.asList(person1, person2, person3, person4);
}
} | 33.1 | 77 | 0.703927 |
2c8064ca74dc6ea6461b94afeb100110d4e1a7f1 | 1,714 | package io.memoria.reactive.core.eventsourcing;
import io.memoria.reactive.core.db.RDB;
import io.memoria.reactive.core.db.Read;
import io.memoria.reactive.core.db.Sub;
import io.memoria.reactive.core.id.Id;
import io.vavr.collection.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import java.util.concurrent.ConcurrentHashMap;
public class ESUtils {
private static final Logger log = LoggerFactory.getLogger(ESUtils.class.getName());
public static Mono<ConcurrentHashMap<Id, State>> buildState(Read<Event> eventRepo, Evolver evolver) {
var state = new ConcurrentHashMap<Id, State>();
return eventRepo.read(0).doOnNext(events -> buildState(state, evolver, events)).then(Mono.just(state));
}
public static Flux<State> pipeline(State initState,
RDB<Event> eventRDB,
Evolver evolver,
Sub<Command> cmdSub,
int cmdOffset,
Decider decider) {
return ESUtils.buildState(eventRDB, evolver)
.map(ns -> new EventStore(initState, ns, eventRDB, decider, evolver))
.flatMapMany(eventStore -> cmdSub.subscribe(cmdOffset).flatMap(eventStore))
.onErrorContinue(ESException.class, (t, o) -> log.error("An error occurred", t));
}
private ESUtils() {}
private static void buildState(ConcurrentHashMap<Id, State> stateStore, Evolver evolver, List<Event> events) {
events.forEach(event -> stateStore.compute(event.aggId(), (k, oldV) -> evolver.apply(oldV, event)));
}
}
| 41.804878 | 112 | 0.655193 |
8bf06db1474fde1753e16a96b24161f28197254f | 936 | /**
* Copyright (c) 2016-2022 Deephaven Data Labs and Patent Pending
*/
package io.deephaven.javascript.proto.dhinternal.grpcweb.client;
import io.deephaven.javascript.proto.dhinternal.grpcweb.transports.transport.TransportFactory;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsProperty;
import jsinterop.annotations.JsType;
import jsinterop.base.Js;
import jsinterop.base.JsPropertyMap;
@JsType(
isNative = true,
name = "dhinternal.grpcWeb.client.RpcOptions",
namespace = JsPackage.GLOBAL)
public interface RpcOptions {
@JsOverlay
static RpcOptions create() {
return Js.uncheckedCast(JsPropertyMap.of());
}
@JsProperty
TransportFactory getTransport();
@JsProperty
boolean isDebug();
@JsProperty
void setDebug(boolean debug);
@JsProperty
void setTransport(TransportFactory transport);
}
| 26 | 94 | 0.747863 |
25b6f446b9b37d9f93ecd031e75e2f66b507a494 | 444 | package de.bennetgallein;
import java.util.ArrayList;
import de.bennetgallein.neuron.Input;
import de.bennetgallein.neuron.Neuron;
public class Main {
public static void main(String[] args) {
Input i = new Input(-2, 0);
Input i2 = new Input(-2, 0);
ArrayList<Input> inputs = new ArrayList<Input>();
inputs.add(i);
inputs.add(i2);
Neuron n = new Neuron(inputs, 3);
System.out.print(n.fire());
}
}
| 20.181818 | 52 | 0.648649 |
78d92cb74311167f295b82d81d04c1cc3116d782 | 1,474 | /**
* Copyright 2005-2015 Red Hat, Inc.
*
* Red Hat licenses this file to you under the Apache License, version
* 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.fabric8.spring.boot;
import io.fabric8.kubernetes.client.DefaultKubernetesClient;
import io.fabric8.kubernetes.client.KubernetesClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConditionalOnMissingBean(KubernetesClient.class)
public class KubernetesClientConfiguration {
private static final Logger LOGGER = LoggerFactory.getLogger(KubernetesClientConfiguration.class);
@Bean
public KubernetesClient kubernetesClient() {
LOGGER.debug("Trying to init {} by auto-configuration.", KubernetesClient.class.getSimpleName());
return new DefaultKubernetesClient();
}
}
| 38.789474 | 105 | 0.774763 |
cec71d24baef2cab836f88e68c28bc2d82f16d9c | 2,515 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.nemo.compiler.frontend.spark.coder;
import org.apache.nemo.common.coder.DecoderFactory;
import org.apache.spark.serializer.DeserializationStream;
import org.apache.spark.serializer.Serializer;
import org.apache.spark.serializer.SerializerInstance;
import scala.reflect.ClassTag$;
import java.io.InputStream;
/**
* Spark DecoderFactory for serialization.
* @param <T> type of the object to deserialize.
*/
public final class SparkDecoderFactory<T> implements DecoderFactory<T> {
private final Serializer serializer;
/**
* Default constructor.
*
* @param serializer Spark serializer.
*/
public SparkDecoderFactory(final Serializer serializer) {
this.serializer = serializer;
}
@Override
public Decoder<T> create(final InputStream inputStream) {
return new SparkDecoder<>(inputStream, serializer.newInstance());
}
@Override
public String toString() {
return "SparkDecoderFactory{"
+ "serializer=" + serializer
+ '}';
}
/**
* SparkDecoder.
* @param <T2> type of the object to deserialize.
*/
private final class SparkDecoder<T2> implements Decoder<T2> {
private final DeserializationStream in;
/**
* Constructor.
*
* @param inputStream the input stream to decode.
* @param sparkSerializerInstance the actual spark serializer instance to use.
*/
private SparkDecoder(final InputStream inputStream,
final SerializerInstance sparkSerializerInstance) {
this.in = sparkSerializerInstance.deserializeStream(inputStream);
}
@Override
public T2 decode() {
return (T2) in.readObject(ClassTag$.MODULE$.Any());
}
}
}
| 30.670732 | 82 | 0.717296 |
7e4c93e113c60ade80153b9cd3dcebc6b017aec7 | 10,501 | package net.anotheria.moskito.core.util.storage;
import net.anotheria.moskito.core.inspection.CreationInfo;
import net.anotheria.moskito.core.inspection.Inspectable;
import net.anotheria.moskito.core.producers.IStatsProducer;
import net.anotheria.moskito.core.registry.IProducerRegistry;
import net.anotheria.moskito.core.registry.ProducerRegistryFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* This class represents a monitorable, map-like storage.
* @author lrosenberg
*
* @param <K>
* @param <V>
*/
public class Storage<K,V> implements IStatsProducer<StorageStats>, Inspectable, Map<K,V> {
/**
* Default category used for producer registration.
*/
public static final String DEF_CATEGORY = "storage";
/**
* Default subsystem used for producer registration.
*/
public static final String DEF_SUBSYSTEM = "default";
/**
* The underlying wrapper.
*/
private StorageWrapper<K, V> wrapper;
/**
* Instance counter for better distinction in webui. It also helps to find out the order storages are instantiated.
*/
private static AtomicInteger instanceCount = new AtomicInteger(0);
/**
* Name of the storage for webui.
*/
private String name;
/**
* Category for webui.
*/
private String category;
/**
* Subsystem for webui.
*/
private String subsystem;
/**
* Stats object.
*/
private StorageStats stats;
/**
* Stats list for getStats method.
*/
private List<StorageStats> statsList;
/**
* Info about storage creation.
*/
private CreationInfo creationInfo;
/**
* Creates a new anonymous storage with given wrapper.
* @param aWrapper
*/
public Storage(StorageWrapper<K, V> aWrapper){
this("storage", aWrapper);
}
/**
* Creates a new storage with given wrapper.
* @param aName storage name
* @param aWrapper wrapper name
*/
public Storage(String aName, StorageWrapper<K, V> aWrapper){
name = aName + '-' + instanceCount.incrementAndGet();
wrapper = aWrapper;
stats = new StorageStats(name);
statsList = new ArrayList<StorageStats>(1);
statsList.add(stats);
category = DEF_CATEGORY;
subsystem = DEF_SUBSYSTEM;
IProducerRegistry reg = ProducerRegistryFactory.getProducerRegistryInstance();
reg.registerProducer(this);
RuntimeException e = new RuntimeException();
e.fillInStackTrace();
creationInfo = new CreationInfo(e.getStackTrace());
}
@Override public V get(Object key){
V v = wrapper.get(key);
stats.addGet();
if (v == null)
stats.addMissedGet();
return v;
}
@Override public V put(K key, V value){
V v = wrapper.put(key, value);
stats.addPut();
if (v == null)
stats.increaseSize();
else
stats.addOverwritePut();
return v;
}
@Override public int size(){
int size = wrapper.size();
//use this call to update the stats-size value.
stats.setSize(size);
return size;
}
@Override public boolean isEmpty(){
return wrapper.isEmpty();
}
@Override public boolean containsKey(Object key){
boolean ret = wrapper.containsKey(key);
if (ret)
stats.addContainsKeyHit();
else
stats.addContainsKeyMiss();
return ret;
}
@Override public boolean containsValue(Object value){
boolean ret = wrapper.containsValue(value);
if (ret)
stats.addContainsValueHit();
else
stats.addContainsValueMiss();
return ret;
}
@Override public V remove(Object key){
V v = wrapper.remove(key);
stats.addRemove();
if (v==null)
stats.addNoopRemove();
else
stats.decreaseSize();
return v;
}
@Override
public Set<Entry<K, V>> entrySet() {
return wrapper.entrySet();
}
/**
* Puts all elements from anotherStorage to this storage.
* @param anotherStorage
*/
public void putAll(Storage<? extends K, ? extends V> anotherStorage){
wrapper.putAll(anotherStorage.getWrapper());
stats.setSize(wrapper.size());
}
@Override public Set<K> keySet(){
return wrapper.keySet();
}
/**
* Convenience method for old hashtable users.
* @return the collection of all keys.
*/
public Collection<K> keys(){
return wrapper.keys();
}
@Override public Collection<V> values(){
return wrapper.values();
}
@Override public void clear(){
wrapper.clear();
}
/**
* Returns the wrapper.
* @return
*/
private StorageWrapper<K, V> getWrapper(){
return wrapper;
}
/**
* Creates a map copy of this storage with all contained elements.
* @return a map containing lal elements from the storage.
*/
public Map<K,V> toMap(){
return wrapper.toMap();
}
/**
* Puts all elements into a given map.
* @param toFill map to fill to.
* @return the map.
*/
public Map<K,V> fillMap(Map<K,V> toFill){
return wrapper.fillMap(toFill);
}
@Override public void putAll(Map<? extends K, ? extends V> anotherMap){
wrapper.putAll(anotherMap);
stats.setSize(wrapper.size());
}
////////////// IStatsProducer Method ////////////
@Override public String getCategory() {
return category;
}
@Override public String getProducerId() {
return getName();
}
@Override public List<StorageStats> getStats() {
return statsList;
}
@Override public String getSubsystem() {
return subsystem;
}
//////////////////////// OTHER
/**
* Sets the subsystem of this producer.
* @param aSubsystem subsystem to set.
*/
public void setSubsystem(String aSubsystem) {
subsystem = aSubsystem;
}
/**
* Sets the category of this producer.
* @param aCategory category to set.
*/
public void setCategory(String aCategory) {
category = aCategory;
}
/**
* Returns this storage's name.
* @return
*/
public String getName(){
return name;
}
@Override public CreationInfo getCreationInfo(){
return creationInfo;
}
/**
* Unregister storage from producer registry.
*/
public void unregister() {
ProducerRegistryFactory.getProducerRegistryInstance().unregisterProducer(this);
}
////// static factory methods
/**
* Factory method to create a new storage backed by a hashmap.
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashMapStorage(){
return new Storage<K,V>(new MapStorageWrapper<K, V>(new HashMap<K, V>()));
}
/**
* Factory method to create a new storage backed by a hashmap.
* @param initialSize
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashMapStorage(int initialSize){
return new Storage<K,V>(new MapStorageWrapper<K, V>(new HashMap<K, V>(initialSize)));
}
/**
* Factory method to create a new storage backed by a hashmap.
* @param name
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashMapStorage(String name){
return new Storage<K,V>(name, new MapStorageWrapper<K, V>(new HashMap<K, V>()));
}
/**
* Factory method to create a new storage backed by a concurrent hash map.
* @param name
* @param initialSize
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashMapStorage(String name, int initialSize){
return new Storage<K,V>(name, new MapStorageWrapper<K, V>(new HashMap<K, V>(initialSize)));
}
/**
* Factory method to create a new storage backed by a concurrent hash map.
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createConcurrentHashMapStorage(){
return new Storage<K,V>(new MapStorageWrapper<K, V>(new ConcurrentHashMap<K, V>()));
}
/**
* Factory method to create a new storage backed by a concurrent hash map.
* @param initialSize initial size of the storage.
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createConcurrentHashMapStorage(int initialSize){
return new Storage<K,V>(new MapStorageWrapper<K, V>(new ConcurrentHashMap<K, V>(initialSize)));
}
/**
* Factory method to create a new storage backed by a concurrent hash map.
* @param name
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createConcurrentHashMapStorage(String name){
return new Storage<K,V>(name, new MapStorageWrapper<K, V>(new ConcurrentHashMap<K, V>()));
}
/**
* Factory method to create a new storage backed by a concurrent hash map.
* @param name
* @param initialSize
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createConcurrentHashMapStorage(String name, int initialSize){
return new Storage<K,V>(name, new MapStorageWrapper<K, V>(new ConcurrentHashMap<K, V>(initialSize)));
}
/**
* Factory method to create a new storage backed by a hashtable.
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashtableStorage(){
return new Storage<K,V>(new MapStorageWrapper<K, V>(new HashMap<K, V>()));
}
/**
* Factory method to create a new storage backed by a hashtable.
* @param initialSize
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashtableStorage(int initialSize){
return new Storage<K,V>(new MapStorageWrapper<K, V>(new HashMap<K, V>(initialSize)));
}
/**
* Factory method to create a new storage backed by a hashtable.
* @param name
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashtableStorage(String name){
return new Storage<K,V>(name, new MapStorageWrapper<K, V>(new HashMap<K, V>()));
}
/**
* Factory method to create a new storage backed by a hashtable.
* @param name
* @param initialSize
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createHashtableStorage(String name, int initialSize){
return new Storage<K,V>(name, new MapStorageWrapper<K, V>(new HashMap<K, V>(initialSize)));
}
/**
* Creates a new TreeMap backed Storage.
* @param name name of the map
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createTreeMapStorage(String name){
return new Storage<K, V>(name, new MapStorageWrapper<K, V>(new TreeMap<K, V>()));
}
/**
* Creates a new TreeMap backed Storage.
* @param name name
* @param comparator comparator
* @param <K>
* @param <V>
* @return
*/
public static <K,V> Storage<K,V> createTreeMapStorage(String name, Comparator comparator){
return new Storage<K, V>(name, new MapStorageWrapper<K, V>(new TreeMap<K, V>(comparator)));
}
}
| 24.195853 | 116 | 0.680888 |
76b1fb4708148839cae0553cba5af11132ff3c03 | 3,276 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.coders;
/**
* The exception thrown when a {@link CoderRegistry} or {@link CoderProvider} cannot
* provide a {@link Coder} that has been requested.
*/
public class CannotProvideCoderException extends Exception {
private final ReasonCode reason;
public CannotProvideCoderException(String message) {
this(message, ReasonCode.UNKNOWN);
}
public CannotProvideCoderException(String message, ReasonCode reason) {
super(message);
this.reason = reason;
}
public CannotProvideCoderException(String message, Throwable cause) {
this(message, cause, ReasonCode.UNKNOWN);
}
public CannotProvideCoderException(String message, Throwable cause, ReasonCode reason) {
super(message, cause);
this.reason = reason;
}
public CannotProvideCoderException(Throwable cause) {
this(cause, ReasonCode.UNKNOWN);
}
public CannotProvideCoderException(Throwable cause, ReasonCode reason) {
super(cause);
this.reason = reason;
}
/**
* @return the reason that Coder inference failed.
*/
public ReasonCode getReason() {
return reason;
}
/**
* Returns the inner-most {@link CannotProvideCoderException} when they are deeply nested.
*
* <p>For example, if a coder for {@code List<KV<Integer, Whatsit>>} cannot be provided because
* there is no known coder for {@code Whatsit}, the root cause of the exception should be a
* CannotProvideCoderException with details pertinent to {@code Whatsit}, suppressing the
* intermediate layers.
*/
public Throwable getRootCause() {
Throwable cause = getCause();
if (cause == null) {
return this;
} else if (!(cause instanceof CannotProvideCoderException)) {
return cause;
} else {
return ((CannotProvideCoderException) cause).getRootCause();
}
}
/**
* Indicates the reason that {@link Coder} inference failed.
*/
public enum ReasonCode {
/**
* The reason a coder could not be provided is unknown or does not have an established
* {@link ReasonCode}.
*/
UNKNOWN,
/**
* The reason a coder could not be provided is type erasure, for example when requesting
* coder inference for a {@code List<T>} where {@code T} is unknown.
*/
TYPE_ERASURE,
/**
* The reason a coder could not be provided is because the type variable {@code T} is
* over specified with multiple incompatible coders.
*/
OVER_SPECIFIED
}
}
| 31.805825 | 97 | 0.706044 |
2ce58173d930f2e1b770bf6ce365e68e01c9c5f7 | 2,254 | package com.oblong.gjgwms.service.impl;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.oblong.gjgwms.dao.DistributeMapper;
import com.oblong.gjgwms.dao.Distribute_detailMapper;
import com.oblong.gjgwms.dao.InventoryMapper;
import com.oblong.gjgwms.entity.Distribute;
import com.oblong.gjgwms.entity.Distribute_detail;
import com.oblong.gjgwms.entity.Inventory;
import com.oblong.gjgwms.entity.Page;
import com.oblong.gjgwms.service.DistributeService;
@Service(value = "distributeService")
public class DistributeServiceImpl extends BaseServiceImpl<Distribute> implements DistributeService {
@Autowired
protected DistributeMapper distributeMapper;
@Autowired
protected Distribute_detailMapper distribute_detailMapper;
@Autowired
protected InventoryMapper inventoryMapper;
@Override
public int insertDistribute(Distribute distribute) throws Exception {
int i=0;
String distributeId=UUID.randomUUID().toString().replace("-", "");
distribute.setDistributeId(distributeId);
i = distributeMapper.insert(distribute);
for(Distribute_detail dd : distribute.getDistributeDetail()){
dd.setDistributeDetailId(UUID.randomUUID().toString().replace("-", ""));
dd.setDistributeId(distributeId);
Inventory inventory=new Inventory();
inventory.setInventoryId(dd.getInventoryId());
Integer inventoryAmount = inventoryMapper.selectAmount(inventory.getInventoryId());
inventoryAmount=inventoryAmount-dd.getDistributeAmount();
if(inventoryAmount<0){
return 0;
}else{
inventory.setInventoryAmount(inventoryAmount);
inventoryMapper.updateAmount(inventory);
}
}
distribute_detailMapper.insertList(distribute.getDistributeDetail());
return i;
}
@Override
public Page<Distribute> selectPage(Page<Distribute> page) {
page.setList(distributeMapper.selectPageList(page));
page.setTotalRecord(distributeMapper.selectPageCount());
return page;
}
@Override
public Page<Distribute_detail> selectPageUseId(Page<Distribute_detail> page) {
page.setList(distribute_detailMapper.selectPageListUseId(page));
page.setTotalRecord(distribute_detailMapper.selectPageCountUseId(page));
return page;
}
}
| 32.666667 | 101 | 0.800799 |
a7c43f3862f6f5fcd4e1d7104c6a9a03f242f110 | 2,532 | package com.project.convertedCode.globalNamespace.functions;
import com.runtimeconverter.runtime.classes.RuntimeClassBase;
import com.runtimeconverter.runtime.RuntimeEnv;
import com.runtimeconverter.runtime.passByReference.RuntimeArgsWithReferences;
import com.runtimeconverter.runtime.ZVal;
import com.runtimeconverter.runtime.annotations.ConvertedParameter;
import com.runtimeconverter.runtime.arrays.ZPair;
import com.runtimeconverter.runtime.interfaces.ContextConstants;
import com.runtimeconverter.runtime.exceptions.ConvertedException;
import com.runtimeconverter.runtime.functions.FunctionBaseRegular;
import com.project.convertedCode.globalNamespace.functions.report;
import com.runtimeconverter.runtime.nativeInterfaces.Throwable;
import com.runtimeconverter.runtime.annotations.ConvertedMethod;
import com.project.convertedCode.globalNamespace.functions.value;
import static com.runtimeconverter.runtime.ZVal.assignParameter;
/*
Converted with The Runtime Converter (runtimeconverter.com)
vendor/laravel/framework/src/Illuminate/Foundation/helpers.php
*/
public class rescue extends FunctionBaseRegular {
public static rescue f = new rescue();
@ConvertedMethod
@ConvertedParameter(index = 0, name = "callback", typeHint = "callable")
@ConvertedParameter(
index = 1,
name = "rescue",
defaultValue = "NULL",
defaultValueType = "constant"
)
public Object call(RuntimeEnv env, Object... args) {
Object callback = assignParameter(args, 0, false);
Object rescue = assignParameter(args, 1, true);
if (null == rescue) {
rescue = ZVal.getNull();
}
Object e = null;
try {
return ZVal.assign(
env.callFunctionDynamic(callback, new RuntimeArgsWithReferences()).value());
} catch (ConvertedException convertedException44) {
if (convertedException44.instanceOf(Throwable.class, "Throwable")) {
e = convertedException44.getObject();
report.f.env(env).call(e);
return ZVal.assign(value.f.env(env).call(rescue).value());
} else {
throw convertedException44;
}
}
}
@Override
protected ContextConstants getContextConstantsProtected() {
return new ContextConstants()
.setDir("/vendor/laravel/framework/src/Illuminate/Foundation")
.setFile("/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php");
}
}
| 38.363636 | 96 | 0.711295 |
a93c14e67f6a50f4b44f9fdc40080b092a8a5dbc | 1,763 | package org.mike;
import org.restlet.Client;
import org.restlet.Context;
import org.restlet.data.ChallengeScheme;
import org.restlet.data.Protocol;
import org.restlet.resource.ClientResource;
import org.restlet.resource.ResourceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TryThreeJson
{
private static final Logger LOGGER = LoggerFactory.getLogger(TryThreeJson.class);
static final String APP_REPORT_REST_V2 = "%s/api/v2/applications/%s/reports/%s";
static final String ALL_REPORTS_REST_V2 = "%s/api/v2/reports/applications";
//Change these to match your IQ Server
static final String BASE_URL = "http://localhost:8060/iq";
static final String USERNAME = "admin";
static final String PASSWORD = "admin123";
/**
* Demonstrate Restlet JSON Extension
*
* @param pUrl
* @return TODO
* @throws Exception
*/
public <T> T get(String pUrl, Class<T> pReturnClassType) throws Exception
{
T returnValue = null;
Client client = new Client(new Context(), Protocol.HTTP);
ClientResource res = new ClientResource(pUrl);
res.setChallengeResponse(ChallengeScheme.HTTP_BASIC, USERNAME, PASSWORD);
res.setNext(client);
try
{
returnValue = res.get(pReturnClassType);
int code = res.getStatus().getCode();
String description = res.getStatus().getDescription();
LOGGER.info("GET {}: Response {}-{}", pUrl, code, description);
LOGGER.debug("Payload:\n{}", returnValue.toString());
}
catch (ResourceException ex)
{
int code = ex.getStatus().getCode();
String description = ex.getStatus().getDescription();
LOGGER.info("GET {}: Response {}: {}", pUrl, code, description);
}
return returnValue;
}
}
| 28.435484 | 83 | 0.698242 |
be79e5462b60eb7994cdb2fc19002926b734c9f5 | 717 | /*
* This file is part of alloy2smt.
* Copyright (C) 2018-2019 The University of Iowa
*
* @author Mudathir Mohamed, Paul Meng
*
*/
package edu.uiowa.smt.smtAst;
abstract public class Declaration extends SmtAst
{
private final String name;
private final Sort sort;
protected Variable variable;
protected Declaration(String name, Sort sort)
{
this.name = name;
this.sort = sort;
this.variable = new Variable(this);
}
public String getName()
{
return this.name;
}
public Sort getSort()
{
return this.sort;
}
public Variable getVariable()
{
return this.variable;
}
}
| 17.925 | 50 | 0.587169 |
d6b8ebe8e28da68746f81f63c132be0d82563a80 | 307 | package net.mehmetatas.devdb.exceptions;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(HttpStatus.FORBIDDEN)
public class Forbidden extends DevDbException {
public Forbidden(String message) {
super(message);
}
}
| 25.583333 | 62 | 0.788274 |
03f905f0421d009cca2b263d14a032afa6f3788d | 14,879 | /*
* Kodkod -- Copyright (c) 2005-present, Emina Torlak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package kodkod.util.collections;
import java.util.AbstractMap;
import java.util.AbstractSet;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Set;
/**
* A map with a fixed set of keys that acts as an indexer, assigning a unique
* integer in the range [0..#keys) to each key. This class implements the
* <tt>Map</tt> interface with an array, using reference-equality in place of
* object-equality when comparing keys (and values). In other words, in a
* <tt>FixedMap</tt>, two keys <tt>k1</tt> and <tt>k2</tt> are considered equal
* if and only if <tt>(k1==k2)</tt>. (In normal <tt>Map</tt> implementations
* (like <tt>HashMap</tt>) two keys <tt>k1</tt> and <tt>k2</tt> are considered
* equal if and only if <tt>(k1==null ? k2==null : k1.equals(k2))</tt>.)
* </p>
* <p>
* <b>This class is <i>not</i> a general-purpose <tt>Map</tt> implementation!
* While this class implements the <tt>Map</tt> interface, it intentionally
* violates <tt>Map's</tt> general contract, which mandates the use of the
* <tt>equals</tt> method when comparing objects. </b>
* </p>
* <p>
* This class provides {@link #put(Object, Object)} operation for the keys
* within its fixed key set and permits <tt>null</tt> values and the
* <tt>null</tt> key. The {@link #remove(Object)} operation is not supported.
* This class guarantees that the order of the map will remain constant over
* time.
* </p>
* <p>
* This class provides log-time performance for the basic operations
* (<tt>get</tt> and <tt>put</tt>), assuming the system identity hash function
* ({@link System#identityHashCode(Object)}) disperses elements properly among
* the buckets.
* </p>
* <p>
* This implementation is not synchronized, and its iterators are not fail-fast.
* </p>
*
* @specfield keys: set K
* @specfield map: keys -> one V
* @specfield indices: keys lone->one [0..#keys)
* @author Emina Torlak
*/
public final class FixedMap<K, V> extends AbstractMap<K,V> implements Indexer<K> {
private final Object[] keys;
private final Object[] values;
/**
* Constructs a new fixed map from the given map.
*
* @ensures this.keys' = keys && this.map = map.map
*/
public FixedMap(Map<K,V> map) {
this(map.keySet());
for (int i = 0, size = map.size(); i < size; i++) {
values[i] = map.get(keys[i]);
}
}
/**
* Constructs a new fixed map for the given set of keys.
*
* @ensures this.keys' = keys && no this.map'
*/
public FixedMap(Set<K> keys) {
final int size = keys.size();
this.keys = Containers.identitySort(keys.toArray(new Object[size]));
values = new Object[size];
}
/**
* Constructs a new fixed map, backed by the given array of keys. The
* provided array must not contain duplicates, its entries must be sorted in
* the increasing order of identity hashcodes, and it must not be modified
* while in use by this map. The map will not behave correctly if these
* requirements are violated.
*
* @requires no disj i, j: [0..keys.length) | keys[i] == keys[j]
* @requires all i, j: [0..keys.length) | i < j =>
* System.identityHashCode(keys[i]) <=
* System.identityHashCode(keys[j])
* @ensures this.keys' = keys && no this.map'
*/
public FixedMap(K[] keys) {
this.keys = keys;
this.values = new Object[keys.length];
}
/**
* Returns the index of the given key, if it is in this.keys. Otherwise
* returns a negative number.
*
* @return key in this.keys => this.indices[key], {i: int | i < 0 }
*/
public final int indexOf(K key) {
return Containers.identityBinarySearch(keys, key);
}
/**
* Returns the key at the given index.
*
* @return this.indices.index
* @throws IndexOutOfBoundsException index !in this.indices[this.keys]
*/
@SuppressWarnings("unchecked")
public final K keyAt(int index) {
try {
return (K) keys[index];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
}
/**
* Tests whether the specified object reference is a key in this fixed map.
*
* @return key in this.keys
*/
@SuppressWarnings("unchecked")
public final boolean containsKey(Object key) {
return indexOf((K) key) >= 0;
}
/**
* Tests whether the specified object reference is a value in this fixed
* map.
*
* @return value in this.map[this.keys]
*/
public final boolean containsValue(Object value) {
for (Object o : values) {
if (o == value)
return true;
}
return false;
}
/**
* Returns a set view of the mappings contained in this map. Each element in
* the returned set is a reference-equality-based <tt>Map.Entry</tt>. The
* set is backed by the map, so changes to the map are reflected in the set,
* and vice-versa. If the map is modified while an iteration over the set is
* in progress, the results of the iteration are undefined. The set does
* support neither removal nor addition.
* <p>
* Like the backing map, the <tt>Map.Entry</tt> objects in the set returned
* by this method define key and value equality as reference-equality rather
* than object-equality. This affects the behavior of the <tt>equals</tt>
* and <tt>hashCode</tt> methods of these <tt>Map.Entry</tt> objects. A
* reference-equality based <tt>Map.Entry
* e</tt> is equal to an object <tt>o</tt> if and only if <tt>o</tt> is a
* <tt>Map.Entry</tt> and <tt>e.getKey()==o.getKey() &&
* e.getValue()==o.getValue()</tt>. To accommodate these equals semantics,
* the <tt>hashCode</tt> method returns
* <tt>System.identityHashCode(e.getKey()) ^
* System.identityHashCode(e.getValue())</tt>.
* <p>
* <b>Owing to the reference-equality-based semantics of the
* <tt>Map.Entry</tt> instances in the set returned by this method, it is
* possible that the symmetry and transitivity requirements of the
* {@link Object#equals(Object)} contract may be violated if any of the
* entries in the set is compared to a normal map entry, or if the set
* returned by this method is compared to a set of normal map entries (such
* as would be returned by a call to this method on a normal map). However,
* the <tt>Object.equals</tt> contract is guaranteed to hold among
* identity-based map entries, and among sets of such entries. </b>
*
* @return a set view of the identity-mappings contained in this map.
*/
public final Set<Map.Entry<K,V>> entrySet() {
return new AbstractSet<Map.Entry<K,V>>() {
@SuppressWarnings("unchecked")
public boolean contains(Object o) {
final Map.Entry<K,V> e = (Map.Entry<K,V>) o;
final int index = FixedMap.this.indexOf(e.getKey());
return index < 0 ? false : values[index] == e.getValue();
}
public Iterator<java.util.Map.Entry<K,V>> iterator() {
return new EntryIterator();
}
public int size() {
return keys.length;
}
public Object[] toArray() {
int size = size();
Object[] result = new Object[size];
for (int i = 0; i < size; i++)
result[i] = new Entry(i);
return result;
}
@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
int size = size();
if (a.length < size)
a = (T[]) java.lang.reflect.Array.newInstance(a.getClass().getComponentType(), size);
for (int i = 0; i < size; i++)
a[i] = (T) new Entry(i);
if (a.length > size)
a[size] = null;
return a;
}
};
}
/**
* Returns the value to which the specified key is mapped in this fixed map,
* or <tt>null</tt> if the map contains no mapping for this key. A return
* value of <tt>null</tt> does not <i>necessarily</i> indicate that the map
* contains no mapping for the key; it is also possible that the map
* explicitly maps the key to <tt>null</tt>. The <tt>containsKey</tt> method
* may be used to distinguish these two cases.
*
* @return this.map[key]
*/
@SuppressWarnings("unchecked")
public final V get(Object key) {
final int index = indexOf((K) key);
return index < 0 ? null : (V) values[index];
}
/**
* Returns the value to which the key at the specified index is mapped in
* this fixed map.
*
* @requires index in this.indices[this.keys]
* @return this.map[this.indices.index]
* @throws IndexOutOfBoundsException index !in this.indices[this.keys]
*/
@SuppressWarnings("unchecked")
public final V get(int index) {
try {
return (V) values[index];
} catch (ArrayIndexOutOfBoundsException e) {
throw new IndexOutOfBoundsException();
}
}
/**
* @see java.util.Map#isEmpty()
*/
public final boolean isEmpty() {
return keys.length == 0;
}
/**
* Associates the specified value with the specified key in this fixed map.
* If the map previously contained a mapping for this key, the old value is
* replaced. This method assumes that the given key is in the fixed keyset
* of this map.
*
* @requires key in this.keys
* @return this.map[key]
* @ensures this.map' = this.map ++ key->value
* @throws IllegalArgumentException key !in this.keys
*/
@SuppressWarnings("unchecked")
public final V put(K key, V value) {
final int index = indexOf((K) key);
if (index < 0)
throw new IllegalArgumentException();
final V oldValue = (V) values[index];
values[index] = value;
return oldValue;
}
/**
* Throws an {@link UnsupportedOperationException} exception.
*
* @see java.util.Map#remove(java.lang.Object)
*/
public final V remove(Object key) {
throw new UnsupportedOperationException();
}
/**
* @see java.util.Map#size()
*/
public final int size() {
return keys.length;
}
/**
* Returns the hash code value for this map. The hash code of a map is
* defined to be the sum of the hashcode of each entry in the map's entrySet
* view. This ensures that <tt>t1.equals(t2)</tt> implies that
* <tt>t1.hashCode()==t2.hashCode()</tt> for any two <tt>FixedMap</tt>
* instances <tt>t1</tt> and <tt>t2</tt>, as required by the general
* contract of {@link Object#hashCode()}.
* <p>
* <b>Owing to the reference-equality-based semantics of the
* <tt>Map.Entry</tt> instances in the set returned by this map's
* <tt>entrySet</tt> method, it is possible that the contractual requirement
* of <tt>Object.hashCode</tt> mentioned in the previous paragraph will be
* violated if one of the two objects being compared is an <tt>FixedMap</tt>
* instance and the other is a normal map.</b>
*
* @return the hash code value for this map.
* @see Object#hashCode()
* @see Object#equals(Object)
* @see #equals(Object)
*/
public int hashCode() {
int result = 0;
for (int i = 0; i < keys.length; i++)
result += System.identityHashCode(keys[i]) ^ System.identityHashCode(values[i]);
return result;
}
/**
* Compares the specified object with this map for equality. Returns
* <tt>true</tt> if the given object is also a map and the two maps
* represent identical object-reference mappings. More formally, this map is
* equal to another map <tt>m</tt> if and only if map
* <tt>this.entrySet().equals(m.entrySet())</tt>.
* <p>
* <b>Owing to the reference-equality-based semantics of this map it is
* possible that the symmetry and transitivity requirements of the
* <tt>Object.equals</tt> contract may be violated if this map is compared
* to a normal map. However, the <tt>Object.equals</tt> contract is
* guaranteed to hold among <tt>FixedMap</tt> instances.</b>
*
* @param o object to be compared for equality with this map.
* @return <tt>true</tt> if the specified object is equal to this map.
* @see Object#equals(Object)
*/
public boolean equals(Object o) {
if (o == this) {
return true;
} else if (o instanceof FixedMap) {
FixedMap< ? , ? > m = (FixedMap< ? , ? >) o;
if (m.size() != size())
return false;
for (int i = 0; i < keys.length; i++) {
if (keys[i] != m.keys[i] || values[i] != m.values[i])
return false;
}
return true;
} else if (o instanceof Map) {
Map< ? , ? > m = (Map< ? , ? >) o;
return entrySet().equals(m.entrySet());
} else {
return false; // o is not a Map
}
}
private class Entry implements Map.Entry<K,V> {
int index;
Entry(int index) {
this.index = index;
}
@SuppressWarnings("unchecked")
public final K getKey() {
return (K) keys[index];
}
@SuppressWarnings("unchecked")
public final V getValue() {
return (V) values[index];
}
public V setValue(V value) {
throw new UnsupportedOperationException();
}
public int hashCode() {
return System.identityHashCode(keys[index]) ^ System.identityHashCode(values[index]);
}
public boolean equals(Object o) {
if (o instanceof Map.Entry) {
final Map.Entry< ? , ? > e = (Map.Entry< ? , ? >) o;
return keys[index] == e.getKey() && values[index] == e.getValue();
} else
return false;
}
public String toString() {
return keys[index] + "=" + values[index];
}
}
private final class EntryIterator extends Entry implements Iterator<Map.Entry<K,V>> {
int next = 0;
EntryIterator() {
super(-1);
}
@SuppressWarnings("unchecked")
public V setValue(V value) {
final V oldValue = (V) values[index];
values[index] = value;
return oldValue;
}
public boolean hasNext() {
return next < keys.length;
}
public Map.Entry<K,V> next() {
if (!hasNext())
throw new NoSuchElementException();
index = next++;
return this;
}
public int hashCode() {
return index < 0 ? System.identityHashCode(this) : super.hashCode();
}
public boolean equals(Object o) {
return index < 0 ? this == o : super.equals(o);
}
public void remove() {
throw new UnsupportedOperationException();
}
public String toString() {
return index < 0 ? "[]" : super.toString();
}
}
}
| 32.4869 | 90 | 0.668728 |
0af719d4f0095688386e9f4b722f216cfda5befa | 378 | package tools.datasync.dao.jdbc;
import tools.datasync.api.msg.SyncEntityMessage;
import tools.datasync.utils.SqlGenUtil;
public class InsertSqlCreator implements SqlCreator {
public String createSQL(String entityName, SyncEntityMessage syncEntityMsg,
String keyColumn) {
String sql = SqlGenUtil.getInsertStatement(entityName, syncEntityMsg);
return sql;
}
}
| 25.2 | 79 | 0.796296 |
2e4068483903d0814235938c4d16176347d1a00e | 52,325 | package com.example.NCEPU.Student.Predict;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.example.NCEPU.R;
import com.example.NCEPU.Utils.Apriori;
import com.example.NCEPU.Utils.Grade;
import com.example.NCEPU.Utils.ShowDialogUtil;
import com.example.NCEPU.Utils.ToastUtil;
import com.example.NCEPU.adapter.AprioriAdapter;
import java.util.ArrayList;
import static com.example.NCEPU.MainActivity.connectJWGL;
import static com.example.NCEPU.Student.Query.QueryFragment.dip2px;
public class MajorActivity extends AppCompatActivity {
private ImageButton back;
private LinearLayout ly_back;
private Button query;
private ExpandableListView expandableListView;
private TextView textView;
private ProgressDialog progressDialog = null;
private Handler handler = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_major);
initViews();
setHeight();
}
private void setHeight() {
SharedPreferences sharedPreferences = getSharedPreferences("user_info", Context.MODE_PRIVATE);
float pagerHeight = sharedPreferences.getInt("pager", 0);
LinearLayout.LayoutParams linearParams = (LinearLayout.LayoutParams)ly_back.getLayoutParams();
linearParams.height = dip2px(this, (float) (pagerHeight * 0.062));
ly_back.setLayoutParams(linearParams);
linearParams = (LinearLayout.LayoutParams)back.getLayoutParams();
linearParams.height = dip2px(this, (float) (pagerHeight * 0.0325));
linearParams.width = dip2px(this, (float) (pagerHeight * 0.0279));
back.setLayoutParams(linearParams);
//查询按钮=48dp=0.0744
linearParams = (LinearLayout.LayoutParams)query.getLayoutParams();
linearParams.height = dip2px(this, (float) (pagerHeight * 0.0744));
query.setLayoutParams(linearParams);
}
@Override
protected void onDestroy() {
super.onDestroy();
if(handler != null) {
handler.removeCallbacksAndMessages(null);
}
}
private void initViews() {
ly_back = findViewById(R.id.ly_back_majors);
back = findViewById(R.id.ib_back_majors);
back.setOnClickListener(v -> {
onBackPressed();
});
expandableListView = findViewById(R.id.expand_majors);
textView = findViewById(R.id.majors_show);
query = findViewById(R.id.btn_query_majors);
query.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
progressDialog = new ProgressDialog(MajorActivity.this);
progressDialog.setTitle("提示");
progressDialog.setMessage("正在生成...");
progressDialog.setIcon(R.drawable.running);
new Thread(){
public void run(){
try{
runOnUiThread(() -> initData());
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
}.start();//线程启动
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
ToastUtil.showMessage(MajorActivity.this, "加载完成!");
}
};
progressDialog.show();
}
});
}
private String convert(String x) {
float score = Float.parseFloat(x.trim());
if(score >= 4.0) {
return "A";
}else if(score >= 3.0) {
return "B";
}else if(score >= 2.0) {
return "C";
}else if(score >= 1.0) {
return "D";
}else {
return "E";
}
}
private String contains(ArrayList<String> courses, String course) {
for(String cour : courses) {
if(cour.contains(course)) {
return cour;
}
}
return "";
}
private void initData() {
ArrayList<Apriori> list = new ArrayList<>();
try {
ArrayList<Grade> grades_list = connectJWGL.getStudentGrade("", "", "全部");
ArrayList<String> courses = new ArrayList<>();
for(Grade grade : grades_list) {
courses.add(grade.getCourse_name());
}
//添加规则
//规则0:计算机组成原理-B--->计算机体系结构-B, conf = 85.88%
Apriori apriori = new Apriori();
ArrayList<String> antecedents = new ArrayList<>();
antecedents.add("计算机组成原理-B");
ArrayList<String> consequents = new ArrayList<>();
consequents.add("计算机体系结构-B");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("85.88%");
//寻找成绩
ArrayList<String> preCourses = new ArrayList<>();
ArrayList<String> backCourses = new ArrayList<>();
String mark;
String convert;
int index;
boolean flag1 = false, flag2 = false;
boolean []check = {false, false, false, false, false, false, false, false};
if(contains(courses, "计算机组成原理") != "") {
index = courses.indexOf(contains(courses, "计算机组成原理"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("B")) {
check[0] = true;
}
String x = "计算机组成原理" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "计算机组成原理暂无数据";
preCourses.add(x);
}
if(contains(courses, "计算机体系结构") != "") {
index = courses.indexOf(contains(courses, "计算机体系结构"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("B")) {
check[1] = true;
}
String x = "计算机体系结构" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "计算机体系结构暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
apriori.setSuggestion("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则1:自动控制理论-A, 运筹学-A--->过程控制-A, conf = 91.03%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("自动控制理论-A");
antecedents.add("运筹学-A");
consequents = new ArrayList<>();
consequents.add("过程控制-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("91.03%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "自动控制理论") != "") {
index = courses.indexOf(contains(courses, "自动控制理论"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "自动控制理论" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "自动控制理论暂无数据";
preCourses.add(x);
}
if(contains(courses, "运筹学") != "") {
index = courses.indexOf(contains(courses, "运筹学"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "运筹学" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "运筹学暂无数据";
preCourses.add(x);
}
if(contains(courses, "过程控制") != "") {
index = courses.indexOf(contains(courses, "过程控制"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "过程控制" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "过程控制暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则2:现代控制-A, 高等数学B(2)-A--->信号分析-A, conf = 90.27%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("大现代控制-A");
antecedents.add("高等数学B(2)-A");
consequents = new ArrayList<>();
consequents.add("信号分析-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("90.27%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "现代控制") != "") {
index = courses.indexOf(contains(courses, "现代控制"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "现代控制" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "现代控制暂无数据";
preCourses.add(x);
}
if(contains(courses, "高等数学B(2)") != "") {
index = courses.indexOf(contains(courses, "高等数学B(2)"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "高等数学B(2)" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "高等数学B(2)暂无数据";
preCourses.add(x);
}
if(contains(courses, "信号分析") != "") {
index = courses.indexOf(contains(courses, "信号分析"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "信号分析" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "信号分析暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则3:复变-A, 运筹学-A--->现代控制-A, conf = 89.66%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("复变函数-A");
antecedents.add("运筹学-A");
consequents = new ArrayList<>();
consequents.add("现代控制-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("89.66%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "复变函数") != "") {
index = courses.indexOf(contains(courses, "复变函数"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "复变函数" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "复变函数暂无数据";
preCourses.add(x);
}
if(contains(courses, "运筹学") != "") {
index = courses.indexOf(contains(courses, "运筹学"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "运筹学" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "运筹学暂无数据";
preCourses.add(x);
}
if(contains(courses, "现代控制") != "") {
index = courses.indexOf(contains(courses, "现代控制"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "现代控制" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "现代控制暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则4:复变-A, 运筹学-A--->模拟电子技术-A, conf = 89.66%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("复变函数-A");
antecedents.add("运筹学-A");
consequents = new ArrayList<>();
consequents.add("模拟电子技术-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("89.66%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "复变函数") != "") {
index = courses.indexOf(contains(courses, "复变函数"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "复变函数" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "复变函数暂无数据";
preCourses.add(x);
}
if(contains(courses, "运筹学") != "") {
index = courses.indexOf(contains(courses, "运筹学"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "运筹学" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "运筹学暂无数据";
preCourses.add(x);
}
if(contains(courses, "模拟电子技术") != "") {
index = courses.indexOf(contains(courses, "模拟电子技术"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "模拟电子技术" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "模拟电子技术暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则5:运筹学-A, 概率论-A--->过程控制-A, conf = 89.66%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("复变函数-A");
antecedents.add("概率论与数理统计-A");
consequents = new ArrayList<>();
consequents.add("过程控制-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("89.66%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "复变函数") != "") {
index = courses.indexOf(contains(courses, "复变函数"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "复变函数" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "复变函数暂无数据";
preCourses.add(x);
}
if(contains(courses, "概率论") != "") {
index = courses.indexOf(contains(courses, "概率论"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "概率论与数理统计" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "概率论与数理统计暂无数据";
preCourses.add(x);
}
if(contains(courses, "过程控制") != "") {
index = courses.indexOf(contains(courses, "过程控制"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "过程控制" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "过程控制暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则6:电路理论B(2)-A, 软件工程-A--->操作系统A-A, conf = 89.29%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("电路理论B(2)-A");
antecedents.add("软件工程-A");
consequents = new ArrayList<>();
consequents.add("操作系统A-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("89.26%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "电路理论B(2)") != "") {
index = courses.indexOf(contains(courses, "电路理论B(2)"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "电路理论B(2)" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "电路理论B(2)暂无数据";
preCourses.add(x);
}
if(contains(courses, "软件工程") != "") {
index = courses.indexOf(contains(courses, "软件工程"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "软件工程" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "软件工程暂无数据";
preCourses.add(x);
}
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "操作系统A暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则7:热工理论-A, 高等数学B(1)-B--->模拟电子技术-A, conf = 83.33%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("热工理论-A");
antecedents.add("高等数学B(1)-B");
consequents = new ArrayList<>();
consequents.add("模拟电子技术-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("89.33%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "热工理论") != "") {
index = courses.indexOf(contains(courses, "热工理论"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "热工理论" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "热工理论暂无数据";
preCourses.add(x);
}
if(contains(courses, "高等数学B(1)") != "") {
index = courses.indexOf(contains(courses, "高等数学B(1)"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "高等数学B(1)" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("B")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "高等数学B(1)暂无数据";
preCourses.add(x);
}
if(contains(courses, "模拟电子技术") != "") {
index = courses.indexOf(contains(courses, "模拟电子技术"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "模拟电子技术" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "模拟电子技术暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则8:操作系统A-A, 编译-A--->软件工程-A, conf = 65.55%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("操作系统A-A");
antecedents.add("编译技术-A");
consequents = new ArrayList<>();
consequents.add("软件工程-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("65.55%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "操作系统A暂无数据";
preCourses.add(x);
}
if(contains(courses, "编译") != "") {
index = courses.indexOf(contains(courses, "编译"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "编译技术" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "编译技术暂无数据";
preCourses.add(x);
}
if(contains(courses, "软件工程") != "") {
index = courses.indexOf(contains(courses, "软件工程"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "软件工程" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "软件工程暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则9:汇编语言-A, 计算机网络-A--->操作系统A-A, conf = 65.66%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("汇编语言-A");
antecedents.add("计算机网络-A");
consequents = new ArrayList<>();
consequents.add("操作系统A-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("65.66%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "汇编") != "") {
index = courses.indexOf(contains(courses, "汇编"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "汇编语言" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "汇编语言暂无数据";
preCourses.add(x);
}
if(contains(courses, "计算机网络") != "") {
index = courses.indexOf(contains(courses, "计算机网络"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "计算机网络" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "计算机网络暂无数据";
preCourses.add(x);
}
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "操作系统A暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则10:高等数学B(2)-B, 面向对象的程序设计-A--->操作系统A-A, conf = 62.62%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("高等数学B(2)-B");
antecedents.add("面向对象的程序设计-A");
consequents = new ArrayList<>();
consequents.add("操作系统A-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("62.62%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "高等数学B(2)") != "") {
index = courses.indexOf(contains(courses, "高等数学B(2)"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("B")) {
check[0] = true;
}
String x = "高等数学B(2)" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "高等数学B(2)暂无数据";
preCourses.add(x);
}
if(contains(courses, "面向对象") != "") {
index = courses.indexOf(contains(courses, "面向对象"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "面向对象的程序设计" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "面向对象的程序设计暂无数据";
preCourses.add(x);
}
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "操作系统A暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则11:数据库原理-A, 汇编语言-A--->操作系统A-A, conf = 62.41%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("数据库原理-A");
antecedents.add("汇编语言-A");
consequents = new ArrayList<>();
consequents.add("操作系统A-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("62.41%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "数据库原理") != "") {
index = courses.indexOf(contains(courses, "数据库原理"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "数据库原理" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "数据库原理暂无数据";
preCourses.add(x);
}
if(contains(courses, "汇编") != "") {
index = courses.indexOf(contains(courses, "汇编"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "汇编语言" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "汇编语言暂无数据";
preCourses.add(x);
}
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "操作系统A暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则12:概率论与数理统计-A, 编译技术-A--->操作系统A-A, conf = 62.37%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("概率论与数理统计-A");
antecedents.add("编译技术-A");
consequents = new ArrayList<>();
consequents.add("操作系统A-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("62.37%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "概率论与数理统计") != "") {
index = courses.indexOf(contains(courses, "概率论与数理统计"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "概率论与数理统计" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "概率论与数理统计暂无数据";
preCourses.add(x);
}
if(contains(courses, "编译") != "") {
index = courses.indexOf(contains(courses, "编译"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "编译技术" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "编译技术暂无数据";
preCourses.add(x);
}
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "操作系统A暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则13:操作系统A-A, 汇编语言-A--->计算机网络-A, conf = 60.19%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("操作系统A-A");
antecedents.add("汇编语言-A");
consequents = new ArrayList<>();
consequents.add("计算机网络-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("60.19%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "操作系统A暂无数据";
preCourses.add(x);
}
if(contains(courses, "汇编") != "") {
index = courses.indexOf(contains(courses, "汇编"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "汇编语言" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "汇编语言暂无数据";
preCourses.add(x);
}
if(contains(courses, "计算机网络") != "") {
index = courses.indexOf(contains(courses, "计算机网络"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "计算机网络" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "计算机网络暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//规则14:操作系统A-A, 数据库原理-A--->计算机网络-A, conf = 61.11%
apriori = new Apriori();
antecedents = new ArrayList<>();
antecedents.add("操作系统A-A");
antecedents.add("汇编语言-A");
consequents = new ArrayList<>();
consequents.add("计算机网络-A");
apriori.setAntecedents(antecedents);
apriori.setConsequents(consequents);
apriori.setConf("61.11%");
//寻找成绩
preCourses = new ArrayList<>();
backCourses = new ArrayList<>();
if(contains(courses, "操作系统A") != "") {
index = courses.indexOf(contains(courses, "操作系统A"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[0] = true;
}
String x = "操作系统A" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
}else {
flag1 = true;
String x = "操作系统A暂无数据";
preCourses.add(x);
}
if(contains(courses, "数据库原理") != "") {
index = courses.indexOf(contains(courses, "数据库原理"));
mark = grades_list.get(index).getGpa();
convert = convert(mark);
String grade = grades_list.get(index).getMark();
String x = "数据库原理" + "-" + convert + "(" + grade + ")";
preCourses.add(x);
if(convert.equals("A")) {
check[1] = true;
}
}else {
flag1 = true;
String x = "数据库原理暂无数据";
preCourses.add(x);
}
if(contains(courses, "计算机网络") != "") {
index = courses.indexOf(contains(courses, "计算机网络"));
mark = grades_list.get(index).getGpa();
String grade = grades_list.get(index).getMark();
convert = convert(mark);
if(convert.equals("A")) {
check[2] = true;
}
String x = "计算机网络" + "-" + convert + "(" + grade + ")";
backCourses.add(x);
}else {
flag2 = true;
String x = "计算机网络暂无数据";
backCourses.add(x);
}
if(flag1 && flag2) { //前后都没有
apriori.setState("暂无");
}else if(!flag1 && flag2) {//前有后没有
if(check[0] && check[1]) {
apriori.setState("待验证");
}else {
apriori.setState("无法验证");
}
}else if(!flag1 && !flag2) { //前后都有
apriori.setState("已验证");
}else { //后有前没有
apriori.setState("无法验证");
}
flag1 = false; flag2 = false; check[0] = false; check[1] = false; check[2] = false;
apriori.setPreCourses(preCourses);
apriori.setBackCourses(backCourses);
list.add(apriori);
//数据显示
AprioriAdapter aprioriAdapter = new AprioriAdapter(this, list);
expandableListView.setAdapter(aprioriAdapter);
ShowDialogUtil.closeProgressDialog();
String s = "对于关联规则:操作系统A-A, 编译技术-A ---> 软件工程-A\n" +
"置信度:65.55%, 其解释为:\n" +
"在操作系统A-A, 编译技术-A的情况下有65.55%的可能软件工程-A.";
textView.setText(s);
} catch (Exception e) {
e.printStackTrace();
}
}
} | 40.405405 | 102 | 0.447033 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.