blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 7 410 | content_id stringlengths 40 40 | detected_licenses listlengths 0 51 | license_type stringclasses 2
values | repo_name stringlengths 5 132 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 80 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 5.85k 684M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 132
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 9.45M | extension stringclasses 28
values | content stringlengths 3 9.45M | authors listlengths 1 1 | author_id stringlengths 0 352 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3534551c1c6d90ec44de4a3b8c118244ce287be9 | 480beb8e6931f9492969b6bd5dc25c4877dab576 | /recursion/Boj1182.java | da5ace5b632f2171c7ac4b6397c904e18f406965 | [] | no_license | wonseok5893/algorithm | a2905de9abf7b9dc538aaec334ac75996f45b6d3 | 8c00674321ffa1ee61a2552e425102cf0bcf714c | refs/heads/master | 2023-05-28T03:24:25.264814 | 2021-05-28T07:48:51 | 2021-05-28T07:48:51 | 296,323,238 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,286 | java | package com.wonseok.recursion;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
public class Boj1182 {
static int[]isUsed;
static int count = 0;
static int s;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] info = br.readLine().split(" ");
int n = Integer.parseInt(info[0]);
s = Integer.parseInt(info[1]);
int[] arr = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt)
.toArray();
for (int i = 1; i <= n; i++) {
isUsed = new int[n+1];
int sum = 0;
int temp = 0;
backtracking(arr,i,temp,sum);
}
System.out.println(count);
}
private static void backtracking(int[] arr, int i,int temp,int sum) {
if(i==0){
if(sum==s) count++;
return;
}
for (int j = temp; j < arr.length; j++) {
if(isUsed[j]==1)continue;
isUsed[j]=1;
sum+=arr[j];
temp = j;
backtracking(arr,i-1,temp+1,sum);
sum-=arr[j];
isUsed[j]=0;
}
}
}
| [
"wonseok5893@naver.com"
] | wonseok5893@naver.com |
259f2ed1b92868eedcd593e2ec4e316580b95099 | ba16caf5c27ba0176b1505ee8ce4891097901898 | /src/main/java/io/github/rusyasoft/example/bank/ipoteka/business/model/FinanceStatPredictResponse.java | 83bc7127e3d3d314734d677acff64edaf2391fa4 | [] | no_license | rusyasoft/spring-ipoteka | 970e936229aaf51caa8290789da8df4594b7a2d7 | 13d7cd16ab1c42b6d26652c783571fd06a53656d | refs/heads/master | 2020-06-21T05:09:10.849161 | 2019-07-23T12:44:23 | 2019-07-23T12:44:23 | 197,351,992 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 263 | java | package io.github.rusyasoft.example.bank.ipoteka.business.model;
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class FinanceStatPredictResponse {
private String bank;
private int year;
private int month;
private int amount;
}
| [
"fedor@within.co.kr"
] | fedor@within.co.kr |
9b11af485f5f26fe80590c4b53151fe654fce1d9 | df134b422960de6fb179f36ca97ab574b0f1d69f | /org/apache/logging/log4j/core/pattern/AbstractStyleNameConverter.java | e605bd9f4b3defea6581664c3337ca5581c04d51 | [] | no_license | TheShermanTanker/NMS-1.16.3 | bbbdb9417009be4987872717e761fb064468bbb2 | d3e64b4493d3e45970ec5ec66e1b9714a71856cc | refs/heads/master | 2022-12-29T15:32:24.411347 | 2020-10-08T11:56:16 | 2020-10-08T11:56:16 | 302,324,687 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 11,056 | java | /* */ package org.apache.logging.log4j.core.pattern;
/* */
/* */ import java.lang.reflect.Constructor;
/* */ import java.lang.reflect.InvocationTargetException;
/* */ import java.util.Arrays;
/* */ import java.util.List;
/* */ import org.apache.logging.log4j.core.LogEvent;
/* */ import org.apache.logging.log4j.core.config.Configuration;
/* */ import org.apache.logging.log4j.core.config.plugins.Plugin;
/* */ import org.apache.logging.log4j.core.layout.PatternLayout;
/* */ import org.apache.logging.log4j.util.PerformanceSensitive;
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public abstract class AbstractStyleNameConverter
/* */ extends LogEventPatternConverter
/* */ {
/* */ private final List<PatternFormatter> formatters;
/* */ private final String style;
/* */
/* */ protected AbstractStyleNameConverter(String name, List<PatternFormatter> formatters, String styling) {
/* 47 */ super(name, "style");
/* 48 */ this.formatters = formatters;
/* 49 */ this.style = styling;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "black", category = "Converter")
/* */ @ConverterKeys({"black"})
/* */ public static final class Black
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "black";
/* */
/* */
/* */
/* */
/* */
/* */ public Black(List<PatternFormatter> formatters, String styling) {
/* 69 */ super("black", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Black newInstance(Configuration config, String[] options) {
/* 81 */ return newInstance(Black.class, "black", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "blue", category = "Converter")
/* */ @ConverterKeys({"blue"})
/* */ public static final class Blue
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "blue";
/* */
/* */
/* */
/* */
/* */
/* */ public Blue(List<PatternFormatter> formatters, String styling) {
/* 102 */ super("blue", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Blue newInstance(Configuration config, String[] options) {
/* 114 */ return newInstance(Blue.class, "blue", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "cyan", category = "Converter")
/* */ @ConverterKeys({"cyan"})
/* */ public static final class Cyan
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "cyan";
/* */
/* */
/* */
/* */
/* */
/* */ public Cyan(List<PatternFormatter> formatters, String styling) {
/* 135 */ super("cyan", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Cyan newInstance(Configuration config, String[] options) {
/* 147 */ return newInstance(Cyan.class, "cyan", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "green", category = "Converter")
/* */ @ConverterKeys({"green"})
/* */ public static final class Green
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "green";
/* */
/* */
/* */
/* */
/* */
/* */ public Green(List<PatternFormatter> formatters, String styling) {
/* 168 */ super("green", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Green newInstance(Configuration config, String[] options) {
/* 180 */ return newInstance(Green.class, "green", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "magenta", category = "Converter")
/* */ @ConverterKeys({"magenta"})
/* */ public static final class Magenta
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "magenta";
/* */
/* */
/* */
/* */
/* */
/* */ public Magenta(List<PatternFormatter> formatters, String styling) {
/* 201 */ super("magenta", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Magenta newInstance(Configuration config, String[] options) {
/* 213 */ return newInstance(Magenta.class, "magenta", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "red", category = "Converter")
/* */ @ConverterKeys({"red"})
/* */ public static final class Red
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "red";
/* */
/* */
/* */
/* */
/* */
/* */ public Red(List<PatternFormatter> formatters, String styling) {
/* 234 */ super("red", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Red newInstance(Configuration config, String[] options) {
/* 246 */ return newInstance(Red.class, "red", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "white", category = "Converter")
/* */ @ConverterKeys({"white"})
/* */ public static final class White
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "white";
/* */
/* */
/* */
/* */
/* */
/* */ public White(List<PatternFormatter> formatters, String styling) {
/* 267 */ super("white", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static White newInstance(Configuration config, String[] options) {
/* 279 */ return newInstance(White.class, "white", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */ @Plugin(name = "yellow", category = "Converter")
/* */ @ConverterKeys({"yellow"})
/* */ public static final class Yellow
/* */ extends AbstractStyleNameConverter
/* */ {
/* */ protected static final String NAME = "yellow";
/* */
/* */
/* */
/* */
/* */
/* */ public Yellow(List<PatternFormatter> formatters, String styling) {
/* 300 */ super("yellow", formatters, styling);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ public static Yellow newInstance(Configuration config, String[] options) {
/* 312 */ return newInstance(Yellow.class, "yellow", config, options);
/* */ }
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ protected static <T extends AbstractStyleNameConverter> T newInstance(Class<T> asnConverterClass, String name, Configuration config, String[] options) {
/* 327 */ List<PatternFormatter> formatters = toPatternFormatterList(config, options);
/* 328 */ if (formatters == null) {
/* 329 */ return null;
/* */ }
/* */ try {
/* 332 */ Constructor<T> constructor = asnConverterClass.getConstructor(new Class[] { List.class, String.class });
/* 333 */ return constructor.newInstance(new Object[] { formatters, AnsiEscape.createSequence(new String[] { name }) });
/* 334 */ } catch (SecurityException e) {
/* 335 */ LOGGER.error(e.toString(), e);
/* 336 */ } catch (NoSuchMethodException e) {
/* 337 */ LOGGER.error(e.toString(), e);
/* 338 */ } catch (IllegalArgumentException e) {
/* 339 */ LOGGER.error(e.toString(), e);
/* 340 */ } catch (InstantiationException e) {
/* 341 */ LOGGER.error(e.toString(), e);
/* 342 */ } catch (IllegalAccessException e) {
/* 343 */ LOGGER.error(e.toString(), e);
/* 344 */ } catch (InvocationTargetException e) {
/* 345 */ LOGGER.error(e.toString(), e);
/* */ }
/* 347 */ return null;
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */
/* */ private static List<PatternFormatter> toPatternFormatterList(Configuration config, String[] options) {
/* 358 */ if (options.length == 0 || options[0] == null) {
/* 359 */ LOGGER.error("No pattern supplied on style for config=" + config);
/* 360 */ return null;
/* */ }
/* 362 */ PatternParser parser = PatternLayout.createPatternParser(config);
/* 363 */ if (parser == null) {
/* 364 */ LOGGER.error("No PatternParser created for config=" + config + ", options=" + Arrays.toString((Object[])options));
/* 365 */ return null;
/* */ }
/* 367 */ return parser.parse(options[0]);
/* */ }
/* */
/* */
/* */
/* */
/* */
/* */ @PerformanceSensitive({"allocation"})
/* */ public void format(LogEvent event, StringBuilder toAppendTo) {
/* 376 */ int start = toAppendTo.length();
/* 377 */ for (int i = 0; i < this.formatters.size(); i++) {
/* 378 */ PatternFormatter formatter = this.formatters.get(i);
/* 379 */ formatter.format(event, toAppendTo);
/* */ }
/* 381 */ if (toAppendTo.length() > start) {
/* 382 */ toAppendTo.insert(start, this.style);
/* 383 */ toAppendTo.append(AnsiEscape.getDefaultStyle());
/* */ }
/* */ }
/* */ }
/* Location: C:\Users\Josep\Downloads\Decompile Minecraft\tuinity-1.16.3.jar!\org\apache\logging\log4j\core\pattern\AbstractStyleNameConverter.class
* Java compiler version: 7 (51.0)
* JD-Core Version: 1.1.3
*/ | [
"tanksherman27@gmail.com"
] | tanksherman27@gmail.com |
115a876f5bb8c27a90925bd4259729a20d1b227f | d457364f912cbb7ca83a196c4581dcb0f2de2747 | /app/src/main/java/com/diting/pingxingren/entity/Industry.java | f7bb62d108b400347f2dab5496fef996c968a2fb | [] | no_license | 767954322/PXR | 748ad1fb729f1a923e6cd55ff81a60b51a82f3be | e1da0bafda03d24e0625e85a2efb1a41714196f3 | refs/heads/master | 2020-03-12T22:54:25.328313 | 2018-04-24T13:06:48 | 2018-04-24T13:06:48 | 130,855,762 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 457 | java | package com.diting.pingxingren.entity;
import com.chad.library.adapter.base.entity.MultiItemEntity;
/**
* Creator: Gu FanFan.
* Date: 2017 - 11 - 16, 14:58.
* Description: .
*/
public class Industry implements MultiItemEntity {
public String industryItem;
public Industry(String industryItem) {
this.industryItem = industryItem;
}
@Override
public int getItemType() {
return 1;
}
}
| [
"18911211362@163.com"
] | 18911211362@163.com |
2706daf0a8a644e15a7044825cbaf0fb6e475fc0 | 47880dbed6b97814d66a819314ace5f86f84938d | /lesson6-2/average_q/Average.java | 457a36ec9bd97c9a82919a5e743ba9db957a3733 | [] | no_license | pvs013/Java_Classwork | 457469174e7743ac9e29891835879971ec4baa56 | 37e12fa1e6825efe92076a754163b699f1fa6bbe | refs/heads/master | 2020-04-25T16:44:31.465115 | 2015-04-15T14:33:15 | 2015-04-15T14:33:15 | 33,998,942 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 988 | java | // Bluej project: lesson6/average_q
import java.util.Scanner;
// TODO: Update your method average() so that it can accept
// altitudes (which can be positive, negative or zero).
// Use Q as a sentinel value instead of 0.
// Use the scanner method hasNextDouble to control your loop.
// Remember to change the prompt.
public class Average
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double value;
int count = 0;
double sum = 0;
boolean done = false;
while (!done)
{
System.out.print("Enter a value, Q to quit: ");
if (!in.hasNextDouble())
{
done = true;
}
else
{
value = in.nextDouble();
count++;
sum = sum+value;
}
}
double average = sum / count;
System.out.printf("Average: %.2f\n", average);
}
}
| [
"chris.palmer@capitalone.com"
] | chris.palmer@capitalone.com |
c9bc54762cc4f92ed2e3b07a3aa698663cc36797 | 92636c48cb4a384db3e6e0ee8ea828f090d1c3a2 | /src/main/java/golzitsky/Sapper/GUI/SapperLauncher.java | fdb8a77f26778f5260a068a017835a8dbdaa68b4 | [] | no_license | GolzitskyNikolay/ProgJava2k18 | 3bd6a2fbf99963d5855b38dc68f1baf12f9a0a13 | 302742b65967e291d5f1a1347a40044287b77ed8 | refs/heads/master | 2021-01-25T00:17:35.063821 | 2018-11-20T20:07:58 | 2018-11-20T20:07:58 | 123,291,767 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,224 | java | package golzitsky.Sapper.GUI;
import golzitsky.Sapper.core.Field;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.io.IOException;
import static golzitsky.Sapper.GUI.Menu.createMenu;
public class SapperLauncher {
public static void main(String[] args) throws IOException {
JFrame jFrame = new JFrame();
JPanel panel = new JPanel();
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
jFrame.setResizable(false);
Field board = new Field();
board.mapSize = 8;
board.chanceOfBombs = 30;
createMenu(board, jFrame, panel);
startGame(board, jFrame, panel);
jFrame.add(panel);
}
static void startGame(Field classField, JFrame jFrame, JPanel panel) {
int mapSize = classField.mapSize;
jFrame.setBounds(540 - 3 * mapSize, 360 - 20 * mapSize, mapSize * 50, mapSize * 50 + 25);
panel.setLayout(new GridLayout(mapSize, mapSize));
classField.allBombs = 0;
classField.quantityOfOpenButtons = 0;
classField.numbersOfEmptyButtons.clear();
classField.numbersOfBombs.clear();
classField.buttons = new RedrawCell[mapSize * mapSize];
panel.removeAll();
GenerateField field = new GenerateField();
field.createEmptyField(panel, classField, jFrame);
jFrame.setVisible(true);
}
static void endGame(String message, Field classField, JFrame jFrame, JPanel panel) {
for (RedrawCell button : classField.buttons) {
button.setPressedIcon(null);
for (ActionListener actionListener : button.getActionListeners()) {
button.removeActionListener(actionListener);
}
for (MouseListener mouseListener : button.getMouseListeners()) {
button.removeMouseListener(mouseListener);
}
}
int result = JOptionPane.showConfirmDialog(null,
message + "\n" + "Do you want to start a new game?");
if (result == JOptionPane.YES_OPTION) startGame(classField, jFrame, panel);
if (result == JOptionPane.NO_OPTION) System.exit(0);
}
} | [
"Golzitskynikolay@gmail.com"
] | Golzitskynikolay@gmail.com |
c6470a26ef1f2ccde738b607d735ec3c27c20d1e | 6dd9f8ef75e4f2017bbb91ba99fb6a2a14daf651 | /src/main/java/org/snail/NIO/App.java | bb7de9e973c18e9cc01805efb0c48d208c5efc4f | [] | no_license | caiyangli/NIO | 4c4fa8d0f78c535f7961362f91f86a949269dfc6 | 2559c48a47f097f9316182b7c56ebd2b8dca322c | refs/heads/master | 2020-05-30T08:34:50.739914 | 2017-03-02T08:16:27 | 2017-03-02T08:16:27 | 83,643,713 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 176 | java | package org.snail.NIO;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
System.out.println( "Hello World!" );
}
}
| [
"2375537812@qq.com"
] | 2375537812@qq.com |
3074932d70e50975d3dfdcd799ac4f5df7fd5806 | d700d8973c9eb33176ca399e09c669304e1da681 | /Study.SpringMVC只加webmvc的source文件2/src/org/springframework/beans/factory/support/AbstractBeanFactory.java | 70446b0b8dfdd4386e1ef4bd1ff7b41be027ccf4 | [] | no_license | Silentdoer/demos | b0acb79d4f925ea66bed51d85a0868fd64abfda4 | 6f832d549458c05af831da5cce49c98ba8c562e7 | refs/heads/master | 2022-12-22T15:38:41.494276 | 2019-10-21T10:46:29 | 2019-10-21T10:46:29 | 118,134,224 | 1 | 0 | null | 2022-12-16T10:35:02 | 2018-01-19T14:22:06 | Java | UTF-8 | Java | false | false | 67,183 | java | /*
* Copyright 2002-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.support;
import java.beans.PropertyEditor;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.PropertyEditorRegistrySupport;
import org.springframework.beans.SimpleTypeConverter;
import org.springframework.beans.TypeConverter;
import org.springframework.beans.TypeMismatchException;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.BeanCurrentlyInCreationException;
import org.springframework.beans.factory.BeanDefinitionStoreException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.BeanIsAbstractException;
import org.springframework.beans.factory.BeanIsNotAFactoryException;
import org.springframework.beans.factory.BeanNotOfRequiredTypeException;
import org.springframework.beans.factory.CannotLoadBeanClassException;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.SmartFactoryBean;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.BeanExpressionContext;
import org.springframework.beans.factory.config.BeanExpressionResolver;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.beans.factory.config.Scope;
import org.springframework.core.DecoratingClassLoader;
import org.springframework.core.NamedThreadLocal;
import org.springframework.core.ResolvableType;
import org.springframework.core.convert.ConversionService;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.StringValueResolver;
/**
* Abstract base class for {@link org.springframework.beans.factory.BeanFactory}
* implementations, providing the full capabilities of the
* {@link org.springframework.beans.factory.config.ConfigurableBeanFactory} SPI.
* Does <i>not</i> assume a listable bean factory: can therefore also be used
* as base class for bean factory implementations which obtain bean definitions
* from some backend resource (where bean definition access is an expensive operation).
*
* <p>This class provides a singleton cache (through its base class
* {@link org.springframework.beans.factory.support.DefaultSingletonBeanRegistry},
* singleton/prototype determination, {@link org.springframework.beans.factory.FactoryBean}
* handling, aliases, bean definition merging for child bean definitions,
* and bean destruction ({@link org.springframework.beans.factory.DisposableBean}
* interface, custom destroy methods). Furthermore, it can manage a bean factory
* hierarchy (delegating to the parent in case of an unknown bean), through implementing
* the {@link org.springframework.beans.factory.HierarchicalBeanFactory} interface.
*
* <p>The main template methods to be implemented by subclasses are
* {@link #getBeanDefinition} and {@link #createBean}, retrieving a bean definition
* for a given bean name and creating a bean instance for a given bean definition,
* respectively. Default implementations of those operations can be found in
* {@link DefaultListableBeanFactory} and {@link AbstractAutowireCapableBeanFactory}.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Costin Leau
* @author Chris Beams
* @since 15 April 2001
* @see #getBeanDefinition
* @see #createBean
* @see AbstractAutowireCapableBeanFactory#createBean
* @see DefaultListableBeanFactory#getBeanDefinition
*/
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
/** Parent bean factory, for bean inheritance support */
private BeanFactory parentBeanFactory;
/** ClassLoader to resolve bean class names with, if necessary */
private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader();
/** ClassLoader to temporarily resolve bean class names with, if necessary */
private ClassLoader tempClassLoader;
/** Whether to cache bean metadata or rather reobtain it for every access */
private boolean cacheBeanMetadata = true;
/** Resolution strategy for expressions in bean definition values */
private BeanExpressionResolver beanExpressionResolver;
/** Spring ConversionService to use instead of PropertyEditors */
private ConversionService conversionService;
/** Custom PropertyEditorRegistrars to apply to the beans of this factory */
private final Set<PropertyEditorRegistrar> propertyEditorRegistrars =
new LinkedHashSet<PropertyEditorRegistrar>(4);
/** A custom TypeConverter to use, overriding the default PropertyEditor mechanism */
private TypeConverter typeConverter;
/** Custom PropertyEditors to apply to the beans of this factory */
private final Map<Class<?>, Class<? extends PropertyEditor>> customEditors =
new HashMap<Class<?>, Class<? extends PropertyEditor>>(4);
/** String resolvers to apply e.g. to annotation attribute values */
private final List<StringValueResolver> embeddedValueResolvers = new LinkedList<StringValueResolver>();
/** BeanPostProcessors to apply in createBean */
private final List<BeanPostProcessor> beanPostProcessors = new ArrayList<BeanPostProcessor>();
/** Indicates whether any InstantiationAwareBeanPostProcessors have been registered */
private boolean hasInstantiationAwareBeanPostProcessors;
/** Indicates whether any DestructionAwareBeanPostProcessors have been registered */
private boolean hasDestructionAwareBeanPostProcessors;
/** Map from scope identifier String to corresponding Scope */
private final Map<String, Scope> scopes = new LinkedHashMap<String, Scope>(8);
/** Security context used when running with a SecurityManager */
private SecurityContextProvider securityContextProvider;
/** Map from bean name to merged RootBeanDefinition */
private final Map<String, RootBeanDefinition> mergedBeanDefinitions =
new ConcurrentHashMap<String, RootBeanDefinition>(256);
/** Names of beans that have already been created at least once */
private final Set<String> alreadyCreated =
Collections.newSetFromMap(new ConcurrentHashMap<String, Boolean>(256));
/** Names of beans that are currently in creation */
private final ThreadLocal<Object> prototypesCurrentlyInCreation =
new NamedThreadLocal<Object>("Prototype beans currently in creation");
/**
* Create a new AbstractBeanFactory.
*/
public AbstractBeanFactory() {
}
/**
* Create a new AbstractBeanFactory with the given parent.
* @param parentBeanFactory parent bean factory, or {@code null} if none
* @see #getBean
*/
public AbstractBeanFactory(BeanFactory parentBeanFactory) {
this.parentBeanFactory = parentBeanFactory;
}
//---------------------------------------------------------------------
// Implementation of BeanFactory interface
//---------------------------------------------------------------------
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
@Override
public <T> T getBean(String name, Class<T> requiredType) throws BeansException {
return doGetBean(name, requiredType, null, false);
}
@Override
public Object getBean(String name, Object... args) throws BeansException {
return doGetBean(name, null, args, false);
}
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
public <T> T getBean(String name, Class<T> requiredType, Object... args) throws BeansException {
return doGetBean(name, requiredType, args, false);
}
/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
throws BeansException {
final String beanName = transformedBeanName(name);
Object bean;
// Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName);
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
// Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
// Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
registerDependentBean(dep, beanName);
getBean(dep);
}
}
// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
try {
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
@Override
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
// Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
try {
return getTypeConverter().convertIfNecessary(bean, requiredType);
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
@Override
public boolean containsBean(String name) {
String beanName = transformedBeanName(name);
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// Not found -> check parent.
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}
@Override
public boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
if (beanInstance instanceof FactoryBean) {
return (BeanFactoryUtils.isFactoryDereference(name) || ((FactoryBean<?>) beanInstance).isSingleton());
}
else {
return !BeanFactoryUtils.isFactoryDereference(name);
}
}
else if (containsSingleton(beanName)) {
return true;
}
else {
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isSingleton(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// In case of FactoryBean, return singleton status of created object if not a dereference.
if (mbd.isSingleton()) {
if (isFactoryBean(beanName, mbd)) {
if (BeanFactoryUtils.isFactoryDereference(name)) {
return true;
}
FactoryBean<?> factoryBean = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
return factoryBean.isSingleton();
}
else {
return !BeanFactoryUtils.isFactoryDereference(name);
}
}
else {
return false;
}
}
}
@Override
public boolean isPrototype(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isPrototype(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isPrototype()) {
// In case of FactoryBean, return singleton status of created object if not a dereference.
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName, mbd));
}
else {
// Singleton or scoped - not a prototype.
// However, FactoryBean may still produce a prototype object...
if (BeanFactoryUtils.isFactoryDereference(name)) {
return false;
}
if (isFactoryBean(beanName, mbd)) {
final FactoryBean<?> fb = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
@Override
public Boolean run() {
return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) ||
!fb.isSingleton());
}
}, getAccessControlContext());
}
else {
return ((fb instanceof SmartFactoryBean && ((SmartFactoryBean<?>) fb).isPrototype()) ||
!fb.isSingleton());
}
}
else {
return false;
}
}
}
@Override
public boolean isTypeMatch(String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
if (beanInstance instanceof FactoryBean) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
Class<?> type = getTypeForFactoryBean((FactoryBean<?>) beanInstance);
return (type != null && typeToMatch.isAssignableFrom(type));
}
else {
return typeToMatch.isInstance(beanInstance);
}
}
else {
return (!BeanFactoryUtils.isFactoryDereference(name) && typeToMatch.isInstance(beanInstance));
}
}
else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
// null instance registered
return false;
}
else {
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.isTypeMatch(originalBeanName(name), typeToMatch);
}
// Retrieve corresponding bean definition.
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class<?> classToMatch = typeToMatch.getRawClass();
Class<?>[] typesToMatch = (FactoryBean.class == classToMatch ?
new Class<?>[] {classToMatch} : new Class<?>[] {FactoryBean.class, classToMatch});
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd, typesToMatch);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
return typeToMatch.isAssignableFrom(targetClass);
}
}
Class<?> beanType = predictBeanType(beanName, mbd, typesToMatch);
if (beanType == null) {
return false;
}
// Check bean class whether we're dealing with a FactoryBean.
if (FactoryBean.class.isAssignableFrom(beanType)) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
// If it's a FactoryBean, we want to look at what it creates, not the factory class.
beanType = getTypeForFactoryBean(beanName, mbd);
if (beanType == null) {
return false;
}
}
}
else if (BeanFactoryUtils.isFactoryDereference(name)) {
// Special case: A SmartInstantiationAwareBeanPostProcessor returned a non-FactoryBean
// type but we nevertheless are being asked to dereference a FactoryBean...
// Let's check the original bean class and proceed with it if it is a FactoryBean.
beanType = predictBeanType(beanName, mbd, FactoryBean.class);
if (beanType == null || !FactoryBean.class.isAssignableFrom(beanType)) {
return false;
}
}
return typeToMatch.isAssignableFrom(beanType);
}
}
@Override
public boolean isTypeMatch(String name, Class<?> typeToMatch) throws NoSuchBeanDefinitionException {
return isTypeMatch(name, ResolvableType.forRawClass(typeToMatch));
}
@Override
public Class<?> getType(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
// Check manually registered singletons.
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
if (beanInstance instanceof FactoryBean && !BeanFactoryUtils.isFactoryDereference(name)) {
return getTypeForFactoryBean((FactoryBean<?>) beanInstance);
}
else {
return beanInstance.getClass();
}
}
else if (containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
// null instance registered
return null;
}
else {
// No singleton instance found -> check bean definition.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// No bean definition found in this factory -> delegate to parent.
return parentBeanFactory.getType(originalBeanName(name));
}
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
// Check decorated bean definition, if any: We assume it'll be easier
// to determine the decorated bean's type than the proxy's type.
BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
if (dbd != null && !BeanFactoryUtils.isFactoryDereference(name)) {
RootBeanDefinition tbd = getMergedBeanDefinition(dbd.getBeanName(), dbd.getBeanDefinition(), mbd);
Class<?> targetClass = predictBeanType(dbd.getBeanName(), tbd);
if (targetClass != null && !FactoryBean.class.isAssignableFrom(targetClass)) {
return targetClass;
}
}
Class<?> beanClass = predictBeanType(beanName, mbd);
// Check bean class whether we're dealing with a FactoryBean.
if (beanClass != null && FactoryBean.class.isAssignableFrom(beanClass)) {
if (!BeanFactoryUtils.isFactoryDereference(name)) {
// If it's a FactoryBean, we want to look at what it creates, not at the factory class.
return getTypeForFactoryBean(beanName, mbd);
}
else {
return beanClass;
}
}
else {
return (!BeanFactoryUtils.isFactoryDereference(name) ? beanClass : null);
}
}
}
@Override
public String[] getAliases(String name) {
String beanName = transformedBeanName(name);
List<String> aliases = new ArrayList<String>();
boolean factoryPrefix = name.startsWith(FACTORY_BEAN_PREFIX);
String fullBeanName = beanName;
if (factoryPrefix) {
fullBeanName = FACTORY_BEAN_PREFIX + beanName;
}
if (!fullBeanName.equals(name)) {
aliases.add(fullBeanName);
}
String[] retrievedAliases = super.getAliases(beanName);
for (String retrievedAlias : retrievedAliases) {
String alias = (factoryPrefix ? FACTORY_BEAN_PREFIX : "") + retrievedAlias;
if (!alias.equals(name)) {
aliases.add(alias);
}
}
if (!containsSingleton(beanName) && !containsBeanDefinition(beanName)) {
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null) {
aliases.addAll(Arrays.asList(parentBeanFactory.getAliases(fullBeanName)));
}
}
return StringUtils.toStringArray(aliases);
}
//---------------------------------------------------------------------
// Implementation of HierarchicalBeanFactory interface
//---------------------------------------------------------------------
@Override
public BeanFactory getParentBeanFactory() {
return this.parentBeanFactory;
}
@Override
public boolean containsLocalBean(String name) {
String beanName = transformedBeanName(name);
return ((containsSingleton(beanName) || containsBeanDefinition(beanName)) &&
(!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(beanName)));
}
//---------------------------------------------------------------------
// Implementation of ConfigurableBeanFactory interface
//---------------------------------------------------------------------
@Override
public void setParentBeanFactory(BeanFactory parentBeanFactory) {
if (this.parentBeanFactory != null && this.parentBeanFactory != parentBeanFactory) {
throw new IllegalStateException("Already associated with parent BeanFactory: " + this.parentBeanFactory);
}
this.parentBeanFactory = parentBeanFactory;
}
@Override
public void setBeanClassLoader(ClassLoader beanClassLoader) {
this.beanClassLoader = (beanClassLoader != null ? beanClassLoader : ClassUtils.getDefaultClassLoader());
}
@Override
public ClassLoader getBeanClassLoader() {
return this.beanClassLoader;
}
@Override
public void setTempClassLoader(ClassLoader tempClassLoader) {
this.tempClassLoader = tempClassLoader;
}
@Override
public ClassLoader getTempClassLoader() {
return this.tempClassLoader;
}
@Override
public void setCacheBeanMetadata(boolean cacheBeanMetadata) {
this.cacheBeanMetadata = cacheBeanMetadata;
}
@Override
public boolean isCacheBeanMetadata() {
return this.cacheBeanMetadata;
}
@Override
public void setBeanExpressionResolver(BeanExpressionResolver resolver) {
this.beanExpressionResolver = resolver;
}
@Override
public BeanExpressionResolver getBeanExpressionResolver() {
return this.beanExpressionResolver;
}
@Override
public void setConversionService(ConversionService conversionService) {
this.conversionService = conversionService;
}
@Override
public ConversionService getConversionService() {
return this.conversionService;
}
@Override
public void addPropertyEditorRegistrar(PropertyEditorRegistrar registrar) {
Assert.notNull(registrar, "PropertyEditorRegistrar must not be null");
this.propertyEditorRegistrars.add(registrar);
}
/**
* Return the set of PropertyEditorRegistrars.
*/
public Set<PropertyEditorRegistrar> getPropertyEditorRegistrars() {
return this.propertyEditorRegistrars;
}
@Override
public void registerCustomEditor(Class<?> requiredType, Class<? extends PropertyEditor> propertyEditorClass) {
Assert.notNull(requiredType, "Required type must not be null");
Assert.isAssignable(PropertyEditor.class, propertyEditorClass);
this.customEditors.put(requiredType, propertyEditorClass);
}
@Override
public void copyRegisteredEditorsTo(PropertyEditorRegistry registry) {
registerCustomEditors(registry);
}
/**
* Return the map of custom editors, with Classes as keys and PropertyEditor classes as values.
*/
public Map<Class<?>, Class<? extends PropertyEditor>> getCustomEditors() {
return this.customEditors;
}
@Override
public void setTypeConverter(TypeConverter typeConverter) {
this.typeConverter = typeConverter;
}
/**
* Return the custom TypeConverter to use, if any.
* @return the custom TypeConverter, or {@code null} if none specified
*/
protected TypeConverter getCustomTypeConverter() {
return this.typeConverter;
}
@Override
public TypeConverter getTypeConverter() {
TypeConverter customConverter = getCustomTypeConverter();
if (customConverter != null) {
return customConverter;
}
// TODO 仅对于spring而言,似乎TypeConverter和ConversionService是两种东西
// TODO 后者是spring自带的一些转换器,内部的converter实现的接口是ConditionalConverter(Converter)
// TODO 而前者的对象 一般都是同时实现了PropertyEditorRegistry和TypeConverter接口,用于提取用户自定义的PropertyEditor??
else {
// Build default TypeConverter, registering custom editors.
SimpleTypeConverter typeConverter = new SimpleTypeConverter();
// TODO 在beanFactory里就有了ConversionService
typeConverter.setConversionService(getConversionService());
registerCustomEditors(typeConverter);
return typeConverter;
}
}
@Override
public void addEmbeddedValueResolver(StringValueResolver valueResolver) {
Assert.notNull(valueResolver, "StringValueResolver must not be null");
this.embeddedValueResolvers.add(valueResolver);
}
@Override
public boolean hasEmbeddedValueResolver() {
return !this.embeddedValueResolvers.isEmpty();
}
@Override
public String resolveEmbeddedValue(String value) {
if (value == null) {
return null;
}
String result = value;
for (StringValueResolver resolver : this.embeddedValueResolvers) {
result = resolver.resolveStringValue(result);
if (result == null) {
return null;
}
}
return result;
}
@Override
public void addBeanPostProcessor(BeanPostProcessor beanPostProcessor) {
Assert.notNull(beanPostProcessor, "BeanPostProcessor must not be null");
this.beanPostProcessors.remove(beanPostProcessor);
this.beanPostProcessors.add(beanPostProcessor);
if (beanPostProcessor instanceof InstantiationAwareBeanPostProcessor) {
this.hasInstantiationAwareBeanPostProcessors = true;
}
if (beanPostProcessor instanceof DestructionAwareBeanPostProcessor) {
this.hasDestructionAwareBeanPostProcessors = true;
}
}
@Override
public int getBeanPostProcessorCount() {
return this.beanPostProcessors.size();
}
/**
* Return the list of BeanPostProcessors that will get applied
* to beans created with this factory.
*/
public List<BeanPostProcessor> getBeanPostProcessors() {
return this.beanPostProcessors;
}
/**
* Return whether this factory holds a InstantiationAwareBeanPostProcessor
* that will get applied to singleton beans on shutdown.
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor
*/
protected boolean hasInstantiationAwareBeanPostProcessors() {
return this.hasInstantiationAwareBeanPostProcessors;
}
/**
* Return whether this factory holds a DestructionAwareBeanPostProcessor
* that will get applied to singleton beans on shutdown.
* @see #addBeanPostProcessor
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
*/
protected boolean hasDestructionAwareBeanPostProcessors() {
return this.hasDestructionAwareBeanPostProcessors;
}
@Override
public void registerScope(String scopeName, Scope scope) {
Assert.notNull(scopeName, "Scope identifier must not be null");
Assert.notNull(scope, "Scope must not be null");
if (SCOPE_SINGLETON.equals(scopeName) || SCOPE_PROTOTYPE.equals(scopeName)) {
throw new IllegalArgumentException("Cannot replace existing scopes 'singleton' and 'prototype'");
}
Scope previous = this.scopes.put(scopeName, scope);
if (previous != null && previous != scope) {
if (logger.isInfoEnabled()) {
logger.info("Replacing scope '" + scopeName + "' from [" + previous + "] to [" + scope + "]");
}
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Registering scope '" + scopeName + "' with implementation [" + scope + "]");
}
}
}
@Override
public String[] getRegisteredScopeNames() {
return StringUtils.toStringArray(this.scopes.keySet());
}
@Override
public Scope getRegisteredScope(String scopeName) {
Assert.notNull(scopeName, "Scope identifier must not be null");
return this.scopes.get(scopeName);
}
/**
* Set the security context provider for this bean factory. If a security manager
* is set, interaction with the user code will be executed using the privileged
* of the provided security context.
*/
public void setSecurityContextProvider(SecurityContextProvider securityProvider) {
this.securityContextProvider = securityProvider;
}
/**
* Delegate the creation of the access control context to the
* {@link #setSecurityContextProvider SecurityContextProvider}.
*/
@Override
public AccessControlContext getAccessControlContext() {
return (this.securityContextProvider != null ?
this.securityContextProvider.getAccessControlContext() :
AccessController.getContext());
}
@Override
public void copyConfigurationFrom(ConfigurableBeanFactory otherFactory) {
Assert.notNull(otherFactory, "BeanFactory must not be null");
setBeanClassLoader(otherFactory.getBeanClassLoader());
setCacheBeanMetadata(otherFactory.isCacheBeanMetadata());
setBeanExpressionResolver(otherFactory.getBeanExpressionResolver());
if (otherFactory instanceof AbstractBeanFactory) {
AbstractBeanFactory otherAbstractFactory = (AbstractBeanFactory) otherFactory;
this.customEditors.putAll(otherAbstractFactory.customEditors);
this.propertyEditorRegistrars.addAll(otherAbstractFactory.propertyEditorRegistrars);
this.beanPostProcessors.addAll(otherAbstractFactory.beanPostProcessors);
this.hasInstantiationAwareBeanPostProcessors = this.hasInstantiationAwareBeanPostProcessors ||
otherAbstractFactory.hasInstantiationAwareBeanPostProcessors;
this.hasDestructionAwareBeanPostProcessors = this.hasDestructionAwareBeanPostProcessors ||
otherAbstractFactory.hasDestructionAwareBeanPostProcessors;
this.scopes.putAll(otherAbstractFactory.scopes);
this.securityContextProvider = otherAbstractFactory.securityContextProvider;
}
else {
setTypeConverter(otherFactory.getTypeConverter());
}
}
/**
* Return a 'merged' BeanDefinition for the given bean name,
* merging a child bean definition with its parent if necessary.
* <p>This {@code getMergedBeanDefinition} considers bean definition
* in ancestors as well.
* @param name the name of the bean to retrieve the merged definition for
* (may be an alias)
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
@Override
public BeanDefinition getMergedBeanDefinition(String name) throws BeansException {
String beanName = transformedBeanName(name);
// Efficiently check whether bean definition exists in this factory.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
return ((ConfigurableBeanFactory) getParentBeanFactory()).getMergedBeanDefinition(beanName);
}
// Resolve merged bean definition locally.
return getMergedLocalBeanDefinition(beanName);
}
@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
String beanName = transformedBeanName(name);
Object beanInstance = getSingleton(beanName, false);
if (beanInstance != null) {
return (beanInstance instanceof FactoryBean);
}
else if (containsSingleton(beanName)) {
// null instance registered
return false;
}
// No singleton instance found -> check bean definition.
if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
// No bean definition found in this factory -> delegate to parent.
return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
}
return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}
@Override
public boolean isActuallyInCreation(String beanName) {
return (isSingletonCurrentlyInCreation(beanName) || isPrototypeCurrentlyInCreation(beanName));
}
/**
* Return whether the specified prototype bean is currently in creation
* (within the current thread).
* @param beanName the name of the bean
*/
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
/**
* Callback before prototype creation.
* <p>The default implementation register the prototype as currently in creation.
* @param beanName the name of the prototype about to be created
* @see #isPrototypeCurrentlyInCreation
*/
@SuppressWarnings("unchecked")
protected void beforePrototypeCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
if (curVal == null) {
this.prototypesCurrentlyInCreation.set(beanName);
}
else if (curVal instanceof String) {
Set<String> beanNameSet = new HashSet<String>(2);
beanNameSet.add((String) curVal);
beanNameSet.add(beanName);
this.prototypesCurrentlyInCreation.set(beanNameSet);
}
else {
Set<String> beanNameSet = (Set<String>) curVal;
beanNameSet.add(beanName);
}
}
/**
* Callback after prototype creation.
* <p>The default implementation marks the prototype as not in creation anymore.
* @param beanName the name of the prototype that has been created
* @see #isPrototypeCurrentlyInCreation
*/
@SuppressWarnings("unchecked")
protected void afterPrototypeCreation(String beanName) {
Object curVal = this.prototypesCurrentlyInCreation.get();
if (curVal instanceof String) {
this.prototypesCurrentlyInCreation.remove();
}
else if (curVal instanceof Set) {
Set<String> beanNameSet = (Set<String>) curVal;
beanNameSet.remove(beanName);
if (beanNameSet.isEmpty()) {
this.prototypesCurrentlyInCreation.remove();
}
}
}
@Override
public void destroyBean(String beanName, Object beanInstance) {
destroyBean(beanName, beanInstance, getMergedLocalBeanDefinition(beanName));
}
/**
* Destroy the given bean instance (usually a prototype instance
* obtained from this factory) according to the given bean definition.
* @param beanName the name of the bean definition
* @param bean the bean instance to destroy
* @param mbd the merged bean definition
*/
protected void destroyBean(String beanName, Object bean, RootBeanDefinition mbd) {
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), getAccessControlContext()).destroy();
}
@Override
public void destroyScopedBean(String beanName) {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
if (mbd.isSingleton() || mbd.isPrototype()) {
throw new IllegalArgumentException(
"Bean name '" + beanName + "' does not correspond to an object in a mutable scope");
}
String scopeName = mbd.getScope();
Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope SPI registered for scope name '" + scopeName + "'");
}
Object bean = scope.remove(beanName);
if (bean != null) {
destroyBean(beanName, bean, mbd);
}
}
//---------------------------------------------------------------------
// Implementation methods
//---------------------------------------------------------------------
/**
* Return the bean name, stripping out the factory dereference prefix if necessary,
* and resolving aliases to canonical names.
* @param name the user-specified name
* @return the transformed bean name
*/
protected String transformedBeanName(String name) {
return canonicalName(BeanFactoryUtils.transformedBeanName(name));
}
/**
* Determine the original bean name, resolving locally defined aliases to canonical names.
* @param name the user-specified name
* @return the original bean name
*/
protected String originalBeanName(String name) {
String beanName = transformedBeanName(name);
if (name.startsWith(FACTORY_BEAN_PREFIX)) {
beanName = FACTORY_BEAN_PREFIX + beanName;
}
return beanName;
}
/**
* Initialize the given BeanWrapper with the custom editors registered
* with this factory. To be called for BeanWrappers that will create
* and populate bean instances.
* <p>The default implementation delegates to {@link #registerCustomEditors}.
* Can be overridden in subclasses.
* @param bw the BeanWrapper to initialize
*/
protected void initBeanWrapper(BeanWrapper bw) {
bw.setConversionService(getConversionService());
registerCustomEditors(bw);
}
/**
* Initialize the given PropertyEditorRegistry with the custom editors
* that have been registered with this BeanFactory.
* <p>To be called for BeanWrappers that will create and populate bean
* instances, and for SimpleTypeConverter used for constructor argument
* and factory method type conversion.
* @param registry the PropertyEditorRegistry to initialize
*/
protected void registerCustomEditors(PropertyEditorRegistry registry) {
PropertyEditorRegistrySupport registrySupport =
(registry instanceof PropertyEditorRegistrySupport ? (PropertyEditorRegistrySupport) registry : null);
if (registrySupport != null) {
registrySupport.useConfigValueEditors();
}
if (!this.propertyEditorRegistrars.isEmpty()) {
for (PropertyEditorRegistrar registrar : this.propertyEditorRegistrars) {
try {
registrar.registerCustomEditors(registry);
}
catch (BeanCreationException ex) {
Throwable rootCause = ex.getMostSpecificCause();
if (rootCause instanceof BeanCurrentlyInCreationException) {
BeanCreationException bce = (BeanCreationException) rootCause;
if (isCurrentlyInCreation(bce.getBeanName())) {
if (logger.isDebugEnabled()) {
logger.debug("PropertyEditorRegistrar [" + registrar.getClass().getName() +
"] failed because it tried to obtain currently created bean '" +
ex.getBeanName() + "': " + ex.getMessage());
}
onSuppressedException(ex);
continue;
}
}
throw ex;
}
}
}
if (!this.customEditors.isEmpty()) {
for (Map.Entry<Class<?>, Class<? extends PropertyEditor>> entry : this.customEditors.entrySet()) {
Class<?> requiredType = entry.getKey();
Class<? extends PropertyEditor> editorClass = entry.getValue();
registry.registerCustomEditor(requiredType, BeanUtils.instantiateClass(editorClass));
}
}
}
/**
* Return a merged RootBeanDefinition, traversing the parent bean definition
* if the specified bean corresponds to a child bean definition.
* @param beanName the name of the bean to retrieve the merged definition for
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws NoSuchBeanDefinitionException if there is no bean with the given name
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
// Quick check on the concurrent map first, with minimal locking.
RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
if (mbd != null) {
return mbd;
}
return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}
/**
* Return a RootBeanDefinition for the given top-level bean, by merging with
* the parent if the given bean's definition is a child bean definition.
* @param beanName the name of the bean definition
* @param bd the original bean definition (Root/ChildBeanDefinition)
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
throws BeanDefinitionStoreException {
return getMergedBeanDefinition(beanName, bd, null);
}
/**
* Return a RootBeanDefinition for the given bean, by merging with the
* parent if the given bean's definition is a child bean definition.
* @param beanName the name of the bean definition
* @param bd the original bean definition (Root/ChildBeanDefinition)
* @param containingBd the containing bean definition in case of inner bean,
* or {@code null} in case of a top-level bean
* @return a (potentially merged) RootBeanDefinition for the given bean
* @throws BeanDefinitionStoreException in case of an invalid bean definition
*/
protected RootBeanDefinition getMergedBeanDefinition(
String beanName, BeanDefinition bd, BeanDefinition containingBd)
throws BeanDefinitionStoreException {
synchronized (this.mergedBeanDefinitions) {
RootBeanDefinition mbd = null;
// Check with full lock now in order to enforce the same merged instance.
if (containingBd == null) {
mbd = this.mergedBeanDefinitions.get(beanName);
}
if (mbd == null) {
if (bd.getParentName() == null) {
// Use copy of given root bean definition.
if (bd instanceof RootBeanDefinition) {
mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
}
else {
mbd = new RootBeanDefinition(bd);
}
}
else {
// Child bean definition: needs to be merged with parent.
BeanDefinition pbd;
try {
String parentBeanName = transformedBeanName(bd.getParentName());
if (!beanName.equals(parentBeanName)) {
pbd = getMergedBeanDefinition(parentBeanName);
}
else {
BeanFactory parent = getParentBeanFactory();
if (parent instanceof ConfigurableBeanFactory) {
pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
}
else {
throw new NoSuchBeanDefinitionException(parentBeanName,
"Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
"': cannot be resolved without an AbstractBeanFactory parent");
}
}
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
"Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
}
// Deep copy with overridden values.
mbd = new RootBeanDefinition(pbd);
mbd.overrideFrom(bd);
}
// Set default singleton scope, if not configured before.
if (!StringUtils.hasLength(mbd.getScope())) {
mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
}
// A bean contained in a non-singleton bean cannot be a singleton itself.
// Let's correct this on the fly here, since this might be the result of
// parent-child merging for the outer bean, in which case the original inner bean
// definition will not have inherited the merged outer bean's singleton status.
if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
mbd.setScope(containingBd.getScope());
}
// Only cache the merged bean definition if we're already about to create an
// instance of the bean, or at least have already created an instance before.
if (containingBd == null && isCacheBeanMetadata()) {
this.mergedBeanDefinitions.put(beanName, mbd);
}
}
return mbd;
}
}
/**
* Check the given merged bean definition,
* potentially throwing validation exceptions.
* @param mbd the merged bean definition to check
* @param beanName the name of the bean
* @param args the arguments for bean creation, if any
* @throws BeanDefinitionStoreException in case of validation failure
*/
protected void checkMergedBeanDefinition(RootBeanDefinition mbd, String beanName, Object[] args)
throws BeanDefinitionStoreException {
if (mbd.isAbstract()) {
throw new BeanIsAbstractException(beanName);
}
}
/**
* Remove the merged bean definition for the specified bean,
* recreating it on next access.
* @param beanName the bean name to clear the merged definition for
*/
protected void clearMergedBeanDefinition(String beanName) {
this.mergedBeanDefinitions.remove(beanName);
}
/**
* Clear the merged bean definition cache, removing entries for beans
* which are not considered eligible for full metadata caching yet.
* <p>Typically triggered after changes to the original bean definitions,
* e.g. after applying a {@code BeanFactoryPostProcessor}. Note that metadata
* for beans which have already been created at this point will be kept around.
* @since 4.2
*/
public void clearMetadataCache() {
Iterator<String> mergedBeans = this.mergedBeanDefinitions.keySet().iterator();
while (mergedBeans.hasNext()) {
if (!isBeanEligibleForMetadataCaching(mergedBeans.next())) {
mergedBeans.remove();
}
}
}
/**
* Resolve the bean class for the specified bean definition,
* resolving a bean class name into a Class reference (if necessary)
* and storing the resolved Class in the bean definition for further use.
* @param mbd the merged bean definition to determine the class for
* @param beanName the name of the bean (for error handling purposes)
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the resolved bean class (or {@code null} if none)
* @throws CannotLoadBeanClassException if we failed to load the class
*/
protected Class<?> resolveBeanClass(final RootBeanDefinition mbd, String beanName, final Class<?>... typesToMatch)
throws CannotLoadBeanClassException {
try {
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() {
@Override
public Class<?> run() throws Exception {
return doResolveBeanClass(mbd, typesToMatch);
}
}, getAccessControlContext());
}
else {
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
}
private Class<?> doResolveBeanClass(RootBeanDefinition mbd, Class<?>... typesToMatch)
throws ClassNotFoundException {
ClassLoader beanClassLoader = getBeanClassLoader();
ClassLoader classLoaderToUse = beanClassLoader;
if (!ObjectUtils.isEmpty(typesToMatch)) {
// When just doing type checks (i.e. not creating an actual instance yet),
// use the specified temporary class loader (e.g. in a weaving scenario).
ClassLoader tempClassLoader = getTempClassLoader();
if (tempClassLoader != null) {
classLoaderToUse = tempClassLoader;
if (tempClassLoader instanceof DecoratingClassLoader) {
DecoratingClassLoader dcl = (DecoratingClassLoader) tempClassLoader;
for (Class<?> typeToMatch : typesToMatch) {
dcl.excludeClass(typeToMatch.getName());
}
}
}
}
String className = mbd.getBeanClassName();
if (className != null) {
Object evaluated = evaluateBeanDefinitionString(className, mbd);
if (!className.equals(evaluated)) {
// A dynamically resolved expression, supported as of 4.2...
if (evaluated instanceof Class) {
return (Class<?>) evaluated;
}
else if (evaluated instanceof String) {
return ClassUtils.forName((String) evaluated, classLoaderToUse);
}
else {
throw new IllegalStateException("Invalid class name expression result: " + evaluated);
}
}
// When resolving against a temporary class loader, exit early in order
// to avoid storing the resolved Class in the bean definition.
if (classLoaderToUse != beanClassLoader) {
return ClassUtils.forName(className, classLoaderToUse);
}
}
return mbd.resolveBeanClass(beanClassLoader);
}
/**
* Evaluate the given String as contained in a bean definition,
* potentially resolving it as an expression.
* @param value the value to check
* @param beanDefinition the bean definition that the value comes from
* @return the resolved value
* @see #setBeanExpressionResolver
*/
protected Object evaluateBeanDefinitionString(String value, BeanDefinition beanDefinition) {
if (this.beanExpressionResolver == null) {
return value;
}
Scope scope = (beanDefinition != null ? getRegisteredScope(beanDefinition.getScope()) : null);
return this.beanExpressionResolver.evaluate(value, new BeanExpressionContext(this, scope));
}
/**
* Predict the eventual bean type (of the processed bean instance) for the
* specified bean. Called by {@link #getType} and {@link #isTypeMatch}.
* Does not need to handle FactoryBeans specifically, since it is only
* supposed to operate on the raw bean type.
* <p>This implementation is simplistic in that it is not able to
* handle factory methods and InstantiationAwareBeanPostProcessors.
* It only predicts the bean type correctly for a standard bean.
* To be overridden in subclasses, applying more sophisticated type detection.
* @param beanName the name of the bean
* @param mbd the merged bean definition to determine the type for
* @param typesToMatch the types to match in case of internal type matching purposes
* (also signals that the returned {@code Class} will never be exposed to application code)
* @return the type of the bean, or {@code null} if not predictable
*/
protected Class<?> predictBeanType(String beanName, RootBeanDefinition mbd, Class<?>... typesToMatch) {
if (mbd.getFactoryMethodName() != null) {
return null;
}
return resolveBeanClass(mbd, beanName, typesToMatch);
}
/**
* Check whether the given bean is defined as a {@link FactoryBean}.
* @param beanName the name of the bean
* @param mbd the corresponding bean definition
*/
protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
}
/**
* Determine the bean type for the given FactoryBean definition, as far as possible.
* Only called if there is no singleton instance registered for the target bean already.
* <p>The default implementation creates the FactoryBean via {@code getBean}
* to call its {@code getObjectType} method. Subclasses are encouraged to optimize
* this, typically by just instantiating the FactoryBean but not populating it yet,
* trying whether its {@code getObjectType} method already returns a type.
* If no type found, a full FactoryBean creation as performed by this implementation
* should be used as fallback.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @return the type for the bean if determinable, or {@code null} else
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
* @see #getBean(String)
*/
protected Class<?> getTypeForFactoryBean(String beanName, RootBeanDefinition mbd) {
if (!mbd.isSingleton()) {
return null;
}
try {
FactoryBean<?> factoryBean = doGetBean(FACTORY_BEAN_PREFIX + beanName, FactoryBean.class, null, true);
return getTypeForFactoryBean(factoryBean);
}
catch (BeanCreationException ex) {
if (ex instanceof BeanCurrentlyInCreationException) {
if (logger.isDebugEnabled()) {
logger.debug("Bean currently in creation on FactoryBean type check: " + ex);
}
}
else if (mbd.isLazyInit()) {
if (logger.isDebugEnabled()) {
logger.debug("Bean creation exception on lazy FactoryBean type check: " + ex);
}
}
else {
if (logger.isWarnEnabled()) {
logger.warn("Bean creation exception on non-lazy FactoryBean type check: " + ex);
}
}
onSuppressedException(ex);
return null;
}
}
/**
* Mark the specified bean as already created (or about to be created).
* <p>This allows the bean factory to optimize its caching for repeated
* creation of the specified bean.
* @param beanName the name of the bean
*/
protected void markBeanAsCreated(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
synchronized (this.mergedBeanDefinitions) {
if (!this.alreadyCreated.contains(beanName)) {
// Let the bean definition get re-merged now that we're actually creating
// the bean... just in case some of its metadata changed in the meantime.
clearMergedBeanDefinition(beanName);
this.alreadyCreated.add(beanName);
}
}
}
}
/**
* Perform appropriate cleanup of cached metadata after bean creation failed.
* @param beanName the name of the bean
*/
protected void cleanupAfterBeanCreationFailure(String beanName) {
synchronized (this.mergedBeanDefinitions) {
this.alreadyCreated.remove(beanName);
}
}
/**
* Determine whether the specified bean is eligible for having
* its bean definition metadata cached.
* @param beanName the name of the bean
* @return {@code true} if the bean's metadata may be cached
* at this point already
*/
protected boolean isBeanEligibleForMetadataCaching(String beanName) {
return this.alreadyCreated.contains(beanName);
}
/**
* Remove the singleton instance (if any) for the given bean name,
* but only if it hasn't been used for other purposes than type checking.
* @param beanName the name of the bean
* @return {@code true} if actually removed, {@code false} otherwise
*/
protected boolean removeSingletonIfCreatedForTypeCheckOnly(String beanName) {
if (!this.alreadyCreated.contains(beanName)) {
removeSingleton(beanName);
return true;
}
else {
return false;
}
}
/**
* Check whether this factory's bean creation phase already started,
* i.e. whether any bean has been marked as created in the meantime.
* @since 4.2.2
* @see #markBeanAsCreated
*/
protected boolean hasBeanCreationStarted() {
return !this.alreadyCreated.isEmpty();
}
/**
* Get the object for the given bean instance, either the bean
* instance itself or its created object in case of a FactoryBean.
* @param beanInstance the shared bean instance
* @param name name that may include factory dereference prefix
* @param beanName the canonical bean name
* @param mbd the merged bean definition
* @return the object to expose for the bean
*/
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, RootBeanDefinition mbd) {
// Don't let calling code try to dereference the factory if the bean isn't a factory.
if (BeanFactoryUtils.isFactoryDereference(name) && !(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
}
// Now we have the bean instance, which may be a normal bean or a FactoryBean.
// If it's a FactoryBean, we use it to create a bean instance, unless the
// caller actually wants a reference to the factory.
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
return beanInstance;
}
Object object = null;
if (mbd == null) {
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
// Return bean instance from factory.
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
// Caches object obtained from FactoryBean if it is a singleton.
if (mbd == null && containsBeanDefinition(beanName)) {
mbd = getMergedLocalBeanDefinition(beanName);
}
boolean synthetic = (mbd != null && mbd.isSynthetic());
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
/**
* Determine whether the given bean name is already in use within this factory,
* i.e. whether there is a local bean or alias registered under this name or
* an inner bean created with this name.
* @param beanName the name to check
*/
public boolean isBeanNameInUse(String beanName) {
return isAlias(beanName) || containsLocalBean(beanName) || hasDependentBean(beanName);
}
/**
* Determine whether the given bean requires destruction on shutdown.
* <p>The default implementation checks the DisposableBean interface as well as
* a specified destroy method and registered DestructionAwareBeanPostProcessors.
* @param bean the bean instance to check
* @param mbd the corresponding bean definition
* @see org.springframework.beans.factory.DisposableBean
* @see AbstractBeanDefinition#getDestroyMethodName()
* @see org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor
*/
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
return (bean != null &&
(DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}
/**
* Add the given bean to the list of disposable beans in this factory,
* registering its DisposableBean interface and/or the given destroy method
* to be called on factory shutdown (if applicable). Only applies to singletons.
* @param beanName the name of the bean
* @param bean the bean instance
* @param mbd the bean definition for the bean
* @see RootBeanDefinition#isSingleton
* @see RootBeanDefinition#getDependsOn
* @see #registerDisposableBean
* @see #registerDependentBean
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}
//---------------------------------------------------------------------
// Abstract methods to be implemented by subclasses
//---------------------------------------------------------------------
/**
* Check if this bean factory contains a bean definition with the given name.
* Does not consider any hierarchy this factory may participate in.
* Invoked by {@code containsBean} when no cached singleton instance is found.
* <p>Depending on the nature of the concrete bean factory implementation,
* this operation might be expensive (for example, because of directory lookups
* in external registries). However, for listable bean factories, this usually
* just amounts to a local hash lookup: The operation is therefore part of the
* public interface there. The same implementation can serve for both this
* template method and the public interface method in that case.
* @param beanName the name of the bean to look for
* @return if this bean factory contains a bean definition with the given name
* @see #containsBean
* @see org.springframework.beans.factory.ListableBeanFactory#containsBeanDefinition
*/
protected abstract boolean containsBeanDefinition(String beanName);
/**
* Return the bean definition for the given bean name.
* Subclasses should normally implement caching, as this method is invoked
* by this class every time bean definition metadata is needed.
* <p>Depending on the nature of the concrete bean factory implementation,
* this operation might be expensive (for example, because of directory lookups
* in external registries). However, for listable bean factories, this usually
* just amounts to a local hash lookup: The operation is therefore part of the
* public interface there. The same implementation can serve for both this
* template method and the public interface method in that case.
* @param beanName the name of the bean to find a definition for
* @return the BeanDefinition for this prototype name (never {@code null})
* @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
* if the bean definition cannot be resolved
* @throws BeansException in case of errors
* @see RootBeanDefinition
* @see ChildBeanDefinition
* @see org.springframework.beans.factory.config.ConfigurableListableBeanFactory#getBeanDefinition
*/
protected abstract BeanDefinition getBeanDefinition(String beanName) throws BeansException;
/**
* Create a bean instance for the given merged bean definition (and arguments).
* The bean definition will already have been merged with the parent definition
* in case of a child definition.
* <p>All bean retrieval methods delegate to this method for actual bean creation.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
*/
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, Object[] args)
throws BeanCreationException;
}
| [
"1010993610@qq.com"
] | 1010993610@qq.com |
09ec3065681d2c392ace90280365f9ff0db67cf5 | e22483adf7123bcfb0534aba76396b8d1b97e05f | /src/com/demo/servlet/ProductServlet.java | e9e47999320566347b3dbe5114ca06661fdd7b58 | [] | no_license | rahul21101996/advjava | 375ff4bd8d4ad5bb457f35927b738eeed21055cd | bc8ec94bc801ee4ac29caee5433690d97a995fb8 | refs/heads/master | 2023-01-25T04:07:36.317345 | 2020-12-07T14:05:58 | 2020-12-07T14:05:58 | 319,338,912 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,494 | java | package com.demo.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.demo.bean.Product;
import com.demo.service.LoginService;
import com.demo.service.LoginServiceImpl;
import com.demo.service.ProductService;
import com.demo.service.ProductServiceImpl;
@WebServlet("/Product")
public class ProductServlet extends HttpServlet {
private ProductService pservice;
public void init()
{
pservice= new ProductServiceImpl();
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
ArrayList<Product> plist=pservice.getAllProduct();
out.println("<table border=1><tr><th>Product Id</th><th>Product Name</th><th>Product Price</th><th>Modify Product</th></tr>");
for(Product p:plist)
{
out.println("<tr><td>"+p.getPid()+"</td><td>"+p.getPname()+"</td><td>"+p.getPrice()+"</td>");
out.println("<td><a href='editproduct?Pid="+p.getPid()+"'>Edit/</a><a href='deleteproduct?Pid="+p.getPid()+"'>Delete</a></td></tr>");
}
out.println("</table>");
out.println("<a href=AddProduct.html>add product</a>");
}
}
| [
"pr.patilrahul@gmail.com"
] | pr.patilrahul@gmail.com |
42eb05c304e43673b31a0da61cc9cc6f3cf215ba | 6374a226f973717a5deb040e730b90accf85f251 | /Spring-05-JavaCode-Configuration/src/main/java/com/cybertek/CybertekApp.java | d0ff0736f6f687fd261d33881436dc62431f6fcb | [] | no_license | waris0129/jd-spring-framework | 140b8167f5ceeeac7c3ea4f3725ddeea2ce8fab9 | 79a1e5b819bf8811b981be30d3c115f5051c2207 | refs/heads/main | 2023-03-16T13:36:10.228057 | 2021-03-06T18:58:08 | 2021-03-06T18:58:08 | 304,898,793 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 579 | java | package com.cybertek;
import com.cybertek.config.CybertekAppConfig;
import com.cybertek.interfaces.Course;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class CybertekApp {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(CybertekAppConfig.class);
Course course = context.getBean("java",Course.class);
course.getTeachingHours();
System.out.println(course.toString());
}
}
| [
"waris0129@hotmail.com"
] | waris0129@hotmail.com |
73a282666a270cfd431c74d09e388949474b28c4 | 0858a464aa2e31d5106addbb604b3f6070bf3f4a | /src/pingball/server/Request.java | e8399bf28c0decd5c191c11dbb5643e833b84496 | [] | no_license | ammubhave/pingball-phase2 | f8543221b3c4ef8da6b6fb69653932298f309ac3 | 48c5ef2514f3d239fe9bc05ecf6f7230694b510f | refs/heads/master | 2020-06-08T14:36:59.462110 | 2014-05-15T14:55:20 | 2014-05-15T14:55:20 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,726 | java | package pingball.server;
import java.util.concurrent.BlockingQueue;
import pingball.proto.HelloMessage;
import pingball.proto.Message;
import pingball.proto.WelcomeMessage;
/**
* The data needed to fulfill a client's request.
*
* Requests are immutable, so they are thread-safe.
*/
public class Request {
/** The name of the client's board. */
private final String boardName;
/** The message sent by the client. */
private final Message message;
/** The client's send queue. */
private final BlockingQueue<Message> clientQueue;
// Rep invariant:
// message is not null
// (message is a HelloMessage and clientQueue is not null) or
// (message is not a HelloMessage and clientQueue is null)
// Abstraction function:
// message represents the request line sent by the client on its socket,
// such as "look\n"; responseQueue is a reference to the client thread's
// response queue
// Thread-safety argument:
// all fields are final, so this is an immutable data type; clientQueue
// itself is mutable, but it is an instance of a thread-safe data type
/**
* Sets up a structure for a request sent by a client.
*
* @param message the message sent by the client
* @param clientQueue the queue that takes messages to the client
*/
public Request(HelloMessage message, BlockingQueue<Message> clientQueue) {
assert message != null;
assert clientQueue != null;
this.boardName = message.getBoardName();
this.message = message;
this.clientQueue = clientQueue;
}
/**
* Sets up a structure for a client request.
*
* @param boardName the name of the client's board
* @param message the message sent by the client
*/
public Request(String boardName, Message message) {
assert message != null;
assert !(message instanceof HelloMessage);
this.boardName = boardName;
this.message = message;
this.clientQueue = null;
}
/**
* The message sent by the client.
*
* @return the message sent by the client; will never be null
*/
public Message getMessage() {
return message;
}
/**
* The name of the client's board.
*
* @return the name of the client's board; this can be null if the client
* disconnects before sending a {@link HelloMessage} successfully
*/
public String getBoardName() {
return boardName;
}
/**
* The client's send queue.
*
* @return the client's send queue; this is only non-null when the message
* is a {@link HelloMessage} instance
*/
public BlockingQueue<Message> getClientQueue() {
return clientQueue;
}
/** Singleton request that tells a links controller to terminate. */
public static final Request EXIT = new Request(
"\n\n", new WelcomeMessage());
} | [
"ammubhave@gmail.com"
] | ammubhave@gmail.com |
0762710c56609a28a639384b3c0b9f7499a4fb90 | e2e16122bdac2a75f58272e3e66685f290dfa059 | /app/src/main/java/com/patientz/VO/PublicProviderVO.java | 07c9c38cbf9775524c9354985c4e5a3fdbe53af4 | [] | no_license | RanjithTesting/git-git.assembla.com-vaidyaconnect.callambulance | 880f2a6a0dbf156958345124fd2018f58b55d7d3 | ea2f25cd5fad34a989badeba845c83efbb8ccde7 | refs/heads/master | 2020-03-25T17:08:57.450433 | 2018-08-08T05:57:27 | 2018-08-08T05:57:27 | 143,965,219 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 893 | java | package com.patientz.VO;
/**
* Created by sunil on 05/10/16.
*/
public class PublicProviderVO {
String displayName;
String emergencyPhoneNo;
String fireNumber;
String policeNo;
public String getFireNumber() {
return fireNumber;
}
public void setFireNumber(String fireNumber) {
this.fireNumber = fireNumber;
}
public String getPoliceNo() {
return policeNo;
}
public void setPoliceNo(String policeNo) {
this.policeNo = policeNo;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getEmergencyPhoneNo() {
return emergencyPhoneNo;
}
public void setEmergencyPhoneNo(String emergencyPhoneNo) {
this.emergencyPhoneNo = emergencyPhoneNo;
}
}
| [
"ranjith@doctrz.com"
] | ranjith@doctrz.com |
d41d69a6672b1d0ee101cb364cdfc17630668589 | 33e69f89bada8dcefda048f6963172454d349c0e | /app/src/main/java/com/yt8492/nakimanebattle/mocks/NetworkManager.java | 13f2aa9ce16799ca7fe10c73bbe079c8185d4548 | [] | no_license | yt8492/NakimaneBattle | a0faeb7e2c499396f5a22cf26d7b7332243c779a | 6afb78b92878b41c98c67e59d258d214fd96df89 | refs/heads/master | 2020-04-05T03:14:09.126903 | 2018-12-16T07:54:19 | 2018-12-16T07:54:19 | 156,506,405 | 0 | 3 | null | 2018-12-16T07:54:20 | 2018-11-07T07:23:42 | Java | UTF-8 | Java | false | false | 826 | java | // 他のデバイス上のアプリとの通信を司るクラス
// 1台の相手デバイスに対してこのクラスのインスタンス1つが対応する
public class NetworkManager{
// 相手と通信確立
public NetworkManager( final String opponentAddr ){
// 処理:未実装
}
// 相手にメッセージ送信
// 成功ならtrue, 失敗ならfalseを返す
public boolean Send( final String message ){
// 処理:未実装
return true;
}
// 相手からメッセージ受信
// 受け取ったメッセージを返す
public String Receive(){
// 処理:未実装
return "";
}
// ここいる? ソケットか何かでやるなら変えた方がいいね。
// private String opponentAddr;
} | [
"albus0sh@gmail.com"
] | albus0sh@gmail.com |
4cc5588f7c96faeb500ca63df51e21f0b76342df | 81771d9ed4b802c6a9828ad46c1099b9ee495d62 | /src/main/java/com/jxj/jdoctorassistant/health/BloodRecordActivity.java | a084feef455ddbb4bcabd550d780dcc02a8b7a67 | [] | no_license | zeroys0/jdoctorassistant | 7191252fb08d9de0ef1793dd4e259c23fa1dd92c | 200b4906c440c248d5dbceca4242f0752791230b | refs/heads/master | 2020-11-25T16:22:23.484459 | 2019-12-18T05:12:33 | 2019-12-18T05:12:33 | 228,753,094 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 9,922 | java | package com.jxj.jdoctorassistant.health;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.NumberPicker;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jxj.jdoctorassistant.R;
import com.jxj.jdoctorassistant.adapter.BloodMeasureRecordAdapter;
import com.jxj.jdoctorassistant.app.ApiConstant;
import com.jxj.jdoctorassistant.app.AppConstant;
import com.jxj.jdoctorassistant.thread.ControlCenterServiceThread;
import com.jxj.jdoctorassistant.thread.JAssistantAPIThread;
import com.jxj.jdoctorassistant.util.GetDate;
import com.jxj.jdoctorassistant.util.UiUtil;
import com.jxj.jdoctorassistant.view.DateDialog;
public class BloodRecordActivity extends Activity {
private NumberPicker mPicker;
private int heartTime;
@Bind(value = R.id.title_tv)
TextView titleTv;
@Bind(value = R.id.right_btn_igv)
ImageView recordIgv;
@Bind(R.id.recode_date_ll)
LinearLayout recodeDateLl;
@Bind(R.id.blood_date_tv)
TextView bloodDateTv;
@Bind(R.id.measure_recode_lv)
ListView listview;
@Bind(R.id.br_interval_tv)
TextView brIntervalTv;
@Bind(R.id.br_set_interval_rl)
RelativeLayout setIntervalRl;
@OnClick({ R.id.back_igv, R.id.right_btn_igv, R.id.blood_query_btn,R.id.bloodrecord_monitor_rl })
public void Click(View v) {
switch (v.getId()) {
case R.id.back_igv:
finish();
break;
case R.id.right_btn_igv:
Intent intent = new Intent(new Intent(context, ChartActivity.class));
intent.putExtra("type", AppConstant.CHART_BP);
startActivity(intent);
break;
case R.id.blood_query_btn:
query();
break;
case R.id.bloodrecord_monitor_rl:
sendCmd(ApiConstant.bloodpressuremonitor);
break;
default:
break;
}
}
private JAssistantAPIThread thread, setBloodPressuperiodThread,
getBloodPressuperiodThread;
private ControlCenterServiceThread sendCmdThread;
private Handler handler_getrecord;
private Context context;
private SharedPreferences sp;
// private Editor editor;
private String customerId;
private String mProductModel;
private int uId;
private BloodMeasureRecordAdapter adapter;
private JSONArray jsonarray = new JSONArray();
private DateDialog dateDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_blood_record);
context = this;
ButterKnife.bind(this);
initviews();
}
@SuppressLint("NewApi")
private void setHeartTimeSet() {
View viewTimeSet = LayoutInflater.from(context).inflate(
R.layout.view_number_picker, null);
mPicker = (NumberPicker) viewTimeSet.findViewById(R.id.numpicker);
mPicker.setMinValue(1);
mPicker.setMaxValue(30);
mPicker.setValue(heartTime);
AlertDialog mAlertDialog = new AlertDialog.Builder(context)
.setTitle(getResources().getString(R.string.blood_title))
.setView(viewTimeSet)
.setPositiveButton(getResources().getString(R.string.mycancel),
null)
.setNegativeButton(getResources().getString(R.string.ok),
new ok()).create();
mAlertDialog.show();
}
@SuppressLint("NewApi")
private class ok implements DialogInterface.OnClickListener {
@Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
int value = mPicker.getValue();
brIntervalTv.setText(value + "");
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x133) {
String result = setBloodPressuperiodThread.getResult();
if (UiUtil.isResultSuccess(context, result)) {
JSONObject json = JSONObject.fromObject(result);
int code = json.getInt("code");
if (code == 200) {
UiUtil.showToast(context,
json.getString("message"));
sendCmd(ApiConstant.openbloodpressure);
}else {
String message=json.getString("message");
UiUtil.showToast(context,message);
}
}
}
};
};
setBloodPressuperiodThread = new JAssistantAPIThread(
ApiConstant.SETBLOODPRESSUREPERIOD, handler, context);
setBloodPressuperiodThread
.setCustomerId(customerId);
setBloodPressuperiodThread.setPeriod(value);
setBloodPressuperiodThread.setuId(uId);
setBloodPressuperiodThread.start();
}
}
private void sendCmd(String action) {
// TODO Auto-generated method stub
Handler sendCmdHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 0x134) {
String mResult = sendCmdThread.getResult();
if (UiUtil.isResultSuccess(context, mResult)) {
UiUtil.showSendCmdResult(context, mResult);
}
// queryHeartRateRecord();
}
}
};
sendCmdThread = new ControlCenterServiceThread(context,
customerId, action, sendCmdHandler);
sendCmdThread.setMethodName(ApiConstant.SENDCMD);
sendCmdThread.start();
}
@SuppressLint("NewApi")
private void initviews() {
// sp = getSharedPreferences(AppConstant.USER_sp_name, MODE_PRIVATE);
sp=getSharedPreferences(AppConstant.USER_sp_name, MODE_PRIVATE);
// editor = sp.edit();
customerId=sp.getString(AppConstant.USER_customerId, "");
mProductModel = sp.getString(AppConstant.USER_jwotchModel, null);
uId=sp.getInt(AppConstant.ADMIN_userId, 0);
titleTv.setText(getResources().getString(R.string.blood_measure_record));
recordIgv.setImageResource(R.drawable.line_chart);
bloodDateTv.setText(GetDate.lastDay());
if(mProductModel.equals(AppConstant.JWOTCHMODEL_041)){
setIntervalRl.setVisibility(View.VISIBLE);
setIntervalRl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
setHeartTimeSet();
}
});
}
recodeDateLl.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if(msg.what==AppConstant.MSG_DATEDIALOG){
bloodDateTv.setText(dateDialog.getDate());
}
}
};
dateDialog = new DateDialog(context,handler);
dateDialog.setDate();
}
});
adapter = new BloodMeasureRecordAdapter(jsonarray, context);
listview.setAdapter(adapter);
// listview.setOnItemClickListener(new OnItemClickListener() {
//
// @Override
// public void onItemClick(AdapterView<?> arg0, View arg1,
// int position, long arg3) {
// // TODO Auto-generated method stub
// JSONObject jsonSend = jsonarray.getJSONObject(position);
// String jsonSendStr = jsonSend.toString();
// Intent intent = new Intent(context, PluseChartActivity.class);
// intent.putExtra("pluseInfo", jsonSendStr);
// intent.putExtra("jwotchModel",mProductModel);
// startActivity(intent);
// }
// });
query();
getBPinterval();
}
private void getBPinterval() {
Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 0x133) {
String result = getBloodPressuperiodThread.getResult();
System.out.println(result+"***********");
if (UiUtil.isResultSuccess(context, result)) {
JSONObject json = JSONObject.fromObject(result);
int code = json.getInt("code");
if (code == 200) {
int period = json.getInt("BloodPressurePeriod");
// System.out.println(period+"**********");
brIntervalTv.setText(period + "");
}
}
}
};
};
getBloodPressuperiodThread = new JAssistantAPIThread(
ApiConstant.GETBLOODPRESSUREPERIOD, handler, context);
getBloodPressuperiodThread.setuId(uId);
getBloodPressuperiodThread.setCustomerId(customerId);
getBloodPressuperiodThread.start();
}
private void query() {
handler_getrecord = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
if (msg.what == 0x133) {
String mResult = thread.getResult();
if (UiUtil.isResultSuccess(context, mResult)) {
JSONObject jsonObj = JSONObject.fromObject(mResult);
int code = jsonObj.getInt("code");
if (code == 200) {
mResult = jsonObj.getString("Data");
try {
jsonarray = JSONArray.fromObject(mResult);
if (jsonarray.size() < 1) {
UiUtil.showToast(context, getResources()
.getString(R.string.the_date_no_data));
}
} catch (Exception e) {
e.printStackTrace();
jsonarray = null;
UiUtil.showToast(
context,
getResources().getString(
R.string.the_date_no_data));
}
}else{
String message=jsonObj.getString("message");
UiUtil.showToast(context, message);
jsonarray=null;
}
adapter.setJsonarray(jsonarray);
adapter.notifyDataSetChanged();
}
}
}
};
String methodName = ApiConstant.GETCUSTOMERDATA_DAY;
if (mProductModel.equals("JXJ-HM041")) {
methodName = ApiConstant.GETHM041BLOODPRESSUREBYDATE;
}
thread = new JAssistantAPIThread(methodName, handler_getrecord,
context);
thread.setuId(uId);
thread.setCustomerId(customerId);
thread.setStartTime(bloodDateTv.getText().toString().trim());
thread.start();
}
}
| [
"370099094@qq.com"
] | 370099094@qq.com |
9585ff0824ad9e4ac9ec0bedbfe9b9b4a3c5cfac | c1689f2502efc7fc822d182d46d376c706cd8979 | /sources/src/main/java/com/practicaSV/gameLabz/utils/comparators/GameOfferReleaseDateComparator.java | acc792ce5433deb976e103e4ff67a32411118eb2 | [] | no_license | SOFTVISION-University/game-labz-restful-api | 8eff6c2cecfeeff0b3ad6f1004bb5e7f85285da4 | 4eb1b01bb43542b57fb1b74fdcd414dda97279d8 | refs/heads/master | 2020-09-23T10:54:53.950916 | 2016-09-05T14:45:15 | 2016-09-05T14:45:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,093 | java | package com.practicaSV.gameLabz.utils.comparators;
import com.practicaSV.gameLabz.domain.GameOffer;
import com.practicaSV.gameLabz.utils.GetFilter;
public class GameOfferReleaseDateComparator extends GameOfferComparator {
@Override
public int compare(GameOffer o1, GameOffer o2) {
if (o1.getOfferType() == GameOffer.OfferType.SINGLE && o2.getOfferType() == GameOffer.OfferType.BUNDLE) {
return -1;
}
if (o1.getOfferType() == GameOffer.OfferType.BUNDLE && o2.getOfferType() == GameOffer.OfferType.SINGLE) {
return 1;
}
if (o1.getOfferType() == GameOffer.OfferType.BUNDLE && o2.getOfferType() == GameOffer.OfferType.BUNDLE) {
return 0;
}
int result = o1.getGames().stream().findFirst().get().getReleaseDate().intValue() - o2.getGames().stream().findFirst().get().getReleaseDate().intValue();
if (getOrderDirection() == null || getOrderDirection() == GetFilter.OrderDirection.ASC) {
return result;
} else {
return (-1) * result;
}
}
}
| [
"andrei.cimpean@softvision.ro"
] | andrei.cimpean@softvision.ro |
7a2e4f2c294ef09893eb969a5bd242497bad1cb5 | c173fc0a3d23ffda1a23b87da425036a6b890260 | /hrsaas/src/org/paradyne/model/loan/LoanClosureModel.java | e7f085a434e6b726733ef2fd3651b72e2b0b80e0 | [
"Apache-2.0"
] | permissive | ThirdIInc/Third-I-Portal | a0e89e6f3140bc5e5d0fe320595d9b02d04d3124 | f93f5867ba7a089c36b1fce3672344423412fa6e | refs/heads/master | 2021-06-03T05:40:49.544767 | 2016-08-03T07:27:44 | 2016-08-03T07:27:44 | 62,725,738 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 55,236 | java | /**
*
*/
package org.paradyne.model.loan;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.paradyne.bean.Loan.LoanClosure;
import org.paradyne.lib.ModelBase;
import org.paradyne.lib.Utility;
import org.paradyne.lib.report.ReportGenerator;
/**
* @author Tarun Chaturvedi
* @date 21-07-2008
* @description LoanClosureModel class to write business logic to save, update, delete
* and view loan closure detail for yhe selected application
*/
public class LoanClosureModel extends ModelBase {
static org.apache.log4j.Logger logger=org.apache.log4j.Logger.getLogger(LoanClosureModel.class);
/**@Method saveLoanClosure
* @Purpose To save the pre payment details or closure details for the selected loan application
* @param bean
* @param installmentDate
* @param principalAmount
* @param interestAmount
* @param installmentAmount
* @param balancePrincipalAmt
* @param isPaid
* @return String
*/
//NumberFormat testNumberFormat = NumberFormat.getNumberInstance();
NumberFormat formatter = new DecimalFormat("#0.00");
public String saveLoanClosure(LoanClosure bean, String [] installmentDate, String [] principalAmount, String [] interestAmount,
String []installmentAmount, String [] balancePrincipalAmt, String [] isPaid){
logger.info("in saveLoanClosure method");
String result = "";
Object [][] insertData = new Object [1][9];
insertData [0][0] = bean.getLoanAppCode();
insertData [0][1] = bean.getLoanAppCode();
insertData [0][2] = bean.getClosureDate();
insertData [0][3] = bean.getAmtPaidByEmp();
insertData [0][5] = bean.getAmountPaid();
insertData [0][6] = bean.getBalanceAmount();
insertData [0][4] = "";
insertData [0][7] = "";
insertData [0][8] = "";
if(bean.getHiddenCalType().equals("P")){
insertData [0][8] = bean.getMonthlyPrincAmount();
}else if(bean.getHiddenCalType().equals("E")){
insertData [0][7] = bean.getEmiAmount();
}else{
if(bean.getInterestType().equals("I")){
insertData [0][4] = bean.getNoOfInstallmentsReduceInt();
}else{
insertData [0][4] = bean.getNoOfInstallmentOther();
}
}
boolean queryResult = getSqlModel().singleExecute(getQuery(1), insertData);
if(queryResult){
if(installmentDate != null && installmentDate.length != 0){
queryResult = insertInstallmentData(bean, installmentDate, principalAmount, interestAmount, installmentAmount, balancePrincipalAmt, isPaid);
} //end of if
else {
logger.info("bean.getLoanAppCode() "+bean.getLoanAppCode());
String deleteQuery = "DELETE FROM HRMS_LOAN_INSTALMENT WHERE LOAN_APPL_CODE = "+bean.getLoanAppCode()
+" AND LOAN_INSTALLMENT_IS_PAID != 'Y'";
queryResult = getSqlModel().singleExecute(deleteQuery);
}
} //end of if
if(queryResult){
result = "saved";
Object [][]updateProcessObj= new Object[1][3];
updateProcessObj [0][0] = bean.getInterestRate();
updateProcessObj [0][1] = bean.getInterestType();
updateProcessObj [0][2] = bean.getLoanAppCode();
getSqlModel().singleExecute(getQuery(14), updateProcessObj);
} //end of if
return result;
}
/**@Method insertInstallmentData
* @Purpose To generate and save installment details for the selected loan application
* @param bean
* @param installmentDate
* @param principalAmount
* @param interestAmount
* @param installmentAmount
* @param balancePrincipalAmt
* @param isPaid
* @return boolean
*/
public boolean insertInstallmentData(LoanClosure bean, String [] installmentDate, String [] principalAmount, String [] interestAmount,
String []installmentAmount, String [] balancePrincipalAmt, String [] isPaid){
String [] dateSplit;
String day = "";
String month = "";
String year = "";
int j = 0;
boolean queryResult = false;
logger.info("bean.getLoanAppCode() "+bean.getLoanAppCode());
String deleteQuery = "DELETE FROM HRMS_LOAN_INSTALMENT WHERE LOAN_APPL_CODE = "+bean.getLoanAppCode()
+" AND LOAN_INSTALLMENT_IS_PAID != 'Y'";
queryResult = getSqlModel().singleExecute(deleteQuery);
if(installmentDate!=null && installmentDate.length>0)
if(queryResult){
Object [][] installmentData = new Object [installmentDate.length][9];
for (int i = 0; i < installmentDate.length; i++) {
dateSplit = installmentDate[i].split("-");
day = dateSplit [0];
month = getMonthNumber(dateSplit[1]);
year = dateSplit [2];
if(isPaid [i].equals("Paid")){
} //end of if
else{
installmentData[j][0] = bean.getLoanAppCode();
installmentData[j][1] = month;
installmentData[j][2] = year;
installmentData[j][3] = principalAmount [i];
installmentData[j][4] = interestAmount [i];
installmentData[j][5] = installmentAmount [i];
installmentData[j][6] = balancePrincipalAmt [i];
installmentData[j][7] = day;
installmentData[j][8] = bean.getEmpCode();
j++;
} //end of else
} //end of for loop
queryResult = getSqlModel().singleExecute(getQuery(9), installmentData);
} //end of if
return queryResult;
}
/**@Method getMonthNumber
* @Purpose To convert the string representation of the month in to the number format
* @param month
* @return no of month in string form i.e. like Jan, Feb etc.
*/
public String getMonthNumber(String month){
String query = "SELECT TO_CHAR(TO_DATE('"+month+"','MON'),'MM') FROM DUAL";
Object [][]monthNo = getSqlModel().getSingleResult(query);
return String.valueOf(monthNo[0][0]);
}
/**@Method updateLoanClosure
* @Purpose To update the pre payment details or closure details for the selected
* loan application (if the record is latest then only)
* @param bean
* @param installmentDate
* @param principalAmount
* @param interestAmount
* @param installmentAmount
* @param balancePrincipalAmt
* @param isPaid
* @return String
*/
public String updateLoanClosure(LoanClosure bean, String [] installmentDate, String [] principalAmount, String [] interestAmount,
String []installmentAmount, String [] balancePrincipalAmt, String [] isPaid){
logger.info("in deleteLoanClosure method");
String result = "";
Object [][] insertData = new Object [1][9];
insertData [0][0] = bean.getClosureDate();
insertData [0][1] = bean.getAmtPaidByEmp();
insertData [0][3] = bean.getAmountPaid();
insertData [0][4] = bean.getBalanceAmount();
insertData [0][2] = "";
insertData [0][5] = "";
insertData [0][6] = "";
if(bean.getHiddenCalType().equals("P")){
insertData [0][6] = bean.getMonthlyPrincAmount();
}else if(bean.getHiddenCalType().equals("E")){
insertData [0][5] = bean.getEmiAmount();
}else{
if(bean.getInterestType().equals("I")){
insertData [0][2] = bean.getNoOfInstallmentsReduceInt();
}else{
insertData [0][2] = bean.getNoOfInstallmentOther();
}
}
insertData [0][7] = bean.getLoanAppCode();
insertData [0][8] = bean.getLoanClosureCode();
Object [] loanCode = new Object [1];
loanCode [0] = bean.getLoanAppCode();
Object [][] loanClosureCode = getSqlModel().getSingleResult(getQuery(4), loanCode);
if(loanClosureCode != null && loanClosureCode.length != 0){
if(String.valueOf(loanClosureCode [0][0]).equals(bean.getLoanClosureCode())){
boolean queryResult = getSqlModel().singleExecute(getQuery(5), insertData);
if(queryResult){
queryResult = insertInstallmentData(bean, installmentDate, principalAmount, interestAmount, installmentAmount, balancePrincipalAmt, isPaid);
if(queryResult){
result = "updated";
Object [][]updateProcessObj= new Object[1][3];
updateProcessObj [0][0] = bean.getInterestRate();
updateProcessObj [0][1] = bean.getInterestType();
updateProcessObj [0][2] = bean.getLoanAppCode();
getSqlModel().singleExecute(getQuery(14), updateProcessObj);
} //end of if
else{
result = "error";
} //end of else
} //end of if
else{
result = "error";
} //end of else
} //end of if
} //end of if
return result;
}
/**@Method deleteLoanClosure
* @Purpose To delete all the details of a selected loan application
* @param bean
* @return String
*/
public String deleteLoanClosure(LoanClosure bean){
logger.info("in deleteLoanClosure method");
String result = "";
boolean queryResult = false;
Object [][] loanApplCode = new Object[1][2];
loanApplCode [0][0] = bean.getLoanAppCode();
loanApplCode [0][1] = bean.getLoanClosureCode();
Object [] loanCode = new Object [1];
loanCode [0] = bean.getLoanAppCode();
Object [][] loanClosureCode = getSqlModel().getSingleResult(getQuery(4), loanCode);
if(loanClosureCode != null && loanClosureCode.length != 0){
if(String.valueOf(loanClosureCode [0][0]).equals(bean.getLoanClosureCode())){
queryResult = getSqlModel().singleExecute(getQuery(2), loanApplCode);
if(queryResult){
result = "deleted";
} //end of if
else{
result = "error";
} //end of else
} //end of if
} //end of if
return result;
}
/**@Method generateReport
* @Purpose To generate report for the selected application
* @param bean
* @param response
*/
public void generateReport(LoanClosure bean, HttpServletResponse response){
logger.info("in generateReport method");
String name = "Loan Closure Report";
String type = "Pdf";
String title = "Loan Closure Report";
org.paradyne.lib.report.ReportGenerator rg=new ReportGenerator(type,title);
//rg.genHeader("Conference Booking");
rg = getHeader(rg,bean);
rg.createReport(response);
}
/**@Method getHeader
* @Purpose To generate report for the selected application
* @param rg
* @param bean
* @return ReportGenerator instance
*/
public ReportGenerator getHeader(ReportGenerator rg, LoanClosure bean){
Object[] loanApplCode = new Object[1];
Object [][] heading = new Object [1][1];
int []cells={25};
int []align={0};
loanApplCode[0] = bean.getLoanAppCode();
Object[][] getHdrData = getSqlModel().getSingleResult(getQuery(6), loanApplCode);
logger.info("result.length " + getHdrData.length);
String dateQuery = "SELECT TO_CHAR(SYSDATE,'DD-MM-YYYY') FROM DUAL";
Object [][]today = getSqlModel().getSingleResult(dateQuery);
String date = "Date : "+(String)today[0][0];
Object[][] getTableData = getSqlModel().getSingleResult(getQuery(7), loanApplCode);
logger.info("result1.length " + getTableData.length);
setBalanceAmount(bean);
Object [][] empName = new Object [1][1];
Object [][] setHdrData = new Object[3][2];
Object [][] settableData = new Object[getTableData.length][3];
for (int i = 0; i < getTableData.length; i++) {
settableData[i][0] = i+1;//String.valueOf(result1[i][0]);
settableData[i][1] = String.valueOf(getTableData[i][0]);
settableData[i][2] = String.valueOf(getTableData[i][1]);
} //end of for loop
String header = " Loan Closure Report ";
empName [0][0] = String.valueOf(" Employee Name :")+" "+checkNull(String.valueOf(getHdrData[0][0]));
setHdrData [0][0] = String.valueOf(" Branch :")+" "+checkNull(String.valueOf(getHdrData[0][3]));
setHdrData [0][1] = String.valueOf(" Department : ")+" "+checkNull(String.valueOf(getHdrData[0][4]));
setHdrData [1][0] = String.valueOf(" Sanction Amount : ")+" "+checkNull(String.valueOf(getHdrData[0][2]));
setHdrData [1][1] = String.valueOf(" Sanction Date :")+" "+checkNull(String.valueOf(getHdrData[0][1]));
setHdrData [2][0] = String.valueOf(" Amount Paid :")+" "+bean.getAmountPaid();
setHdrData [2][1] = String.valueOf(" Balance Amount :")+" "+bean.getBalanceAmount();
String colNames [] = { "Sr. No.", "Loan Payment/Closure Date", "Pre Payment Amount"};
int[] cellwidth = {15, 30, 30,};
int [] alignment = {0, 2, 2};
int [] emprowcellwidth = {100};
int [] emprowalignmnet = {0};
int [] rowcellwidth = {50, 50};
int [] rowalignmnet = {0,0};
try {
rg.addFormatedText(header, 6, 0, 1, 0);
rg.addText(date, 0, 2, 0);
//rg.addText("\n", 0, 0, 0);
heading [0][0] = "Report Details :-";
rg.tableBodyBold(heading, cells, align) ;
//rg.addFormatedText("Report Details :-", 4, 0, 0, 0);
rg.tableBody(empName, emprowcellwidth, emprowalignmnet);
rg.tableBody(setHdrData, rowcellwidth, rowalignmnet);
rg.addText("\n", 0, 0, 0);
} catch (Exception e) {
//e.printStackTrace();
logger.error(e);
}
heading [0][0] = "Pre Payment Details :-";
rg.tableBodyBold(heading, cells, align) ;
//rg.addFormatedText("Installment Details :-", 4, 0, 0, 0);
rg.tableBody(colNames, settableData, cellwidth, alignment);
return rg;
}
/**@Method rescheduleInstallments
* @Purpose To reschedule the installment details for the selected application
* @param bean
* @param principalAmount
* @param interestRate
* @param interestType
* @param noOfInstallment
* @param startDate
* @param request
*/
public void rescheduleInstallments(LoanClosure bean, String principalAmount, String interestRate,
String interestType, String noOfInstallment, String startDate, HttpServletRequest request){
LoanProccessModel model = new LoanProccessModel();
Double principal = Double.parseDouble(principalAmount);
int installments = Integer.parseInt(noOfInstallment);
HashMap mapdata = new HashMap();
logger.info("hiddden "+bean.getInterestType());
double totalEmi = 0.0;
double totalIntPaid = 0.0;
double totalPrincipal = 0.0;
int count = 0;
ArrayList<Object> tableList = new ArrayList<Object>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date startDateParse = sdf.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateParse);
//cal.add(cal.MONTH, 1);
String lastInstallmentDate = "";
boolean dateFlag = false;
String stringDate = sdf.format(cal.getTime());
logger.info("stringDate "+stringDate);
Object [] applCode = {bean.getLoanAppCode()};
Object [][] getPaidInstallmentsData = null;
getPaidInstallmentsData = getSqlModel().getSingleResult(getQuery(10), applCode);
if(getPaidInstallmentsData != null && getPaidInstallmentsData.length != 0){
for (int i = 0; i < getPaidInstallmentsData.length; i++) {
LoanClosure bean1 = new LoanClosure();
String installmentDate = String.valueOf(getPaidInstallmentsData[i][0])+"-"
+String.valueOf(getPaidInstallmentsData[i][1])+"-"
+String.valueOf(getPaidInstallmentsData[i][2]);
if(i == getPaidInstallmentsData.length-1){
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[i][8]);
} //end of if statement
bean1.setMonthYear(installmentDate);
bean1.setPrincipalAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][3])));
bean1.setInterestAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][4])));
bean1.setInstallmentAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][5])));
bean1.setBalancePrincipalAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][6])));
if(String.valueOf(getPaidInstallmentsData[i][7]).equals("Y")){
mapdata.put("installment"+count,"Paid");
} //end of if statement
else{
mapdata.put("installment"+count,"To Be Paid");
} //end of else statement
totalEmi += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][5]));
totalIntPaid += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][4]));
totalPrincipal += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][3]));
tableList.add(bean1);
count++;
dateFlag = true;
} //end of for loop
} //end of if statement
else{
dateFlag = false;
getPaidInstallmentsData = getSqlModel().getSingleResult(getQuery(12), applCode);
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[0][3]);
logger.info("lastInstallmentDate 11111 "+lastInstallmentDate);
} //end of else statement
Object [] firstInstallment = calculateFirstInstallment(bean, stringDate, lastInstallmentDate, principal, interestRate,
installments, dateFlag, String.valueOf(getPaidInstallmentsData[0][0])+"-"+String.valueOf(getPaidInstallmentsData[0][1]));
LoanClosure bean1 = new LoanClosure();
if(dateFlag){
bean1.setMonthYear(String.valueOf(firstInstallment[0]));
} //end of if statement
else{
bean1.setMonthYear(String.valueOf(getPaidInstallmentsData[0][2]));
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[0][0])+"-"+String.valueOf(getPaidInstallmentsData[0][1]);
logger.info("lastInstallmentDate for reducing "+lastInstallmentDate);
} //end of else statement
if(interestType.equals("I")){
bean1.setPrincipalAmt(formatter.format(Double.parseDouble(""+firstInstallment[1])));
bean1.setInterestAmt(formatter.format(Double.parseDouble(""+firstInstallment[2])));
bean1.setInstallmentAmt(formatter.format(Double.parseDouble(""+firstInstallment[3])));
bean1.setBalancePrincipalAmt(Utility.twoDecimals(principalAmount));
mapdata.put("installment"+count,"To Be Paid");
count++;
totalEmi += Double.parseDouble(formatter.format(Double.parseDouble(""+firstInstallment[3])));
totalIntPaid += Double.parseDouble(formatter.format(Double.parseDouble(""+firstInstallment[2])));
totalPrincipal += Double.parseDouble(formatter.format(Double.parseDouble(""+firstInstallment[1])));
tableList.add(bean1);
}
Calendar calInst = Calendar.getInstance();
Date instDate = sdf.parse(lastInstallmentDate);
calInst.setTime(instDate);
calInst.add(calInst.MONTH, 1);
model.initiate(context, session);
if(installments!=0){
String [][] installmentData = model.calculateInstallment(principal, installments, interestRate, interestType, sdf.format(calInst.getTime()),Double.parseDouble(String.valueOf(firstInstallment[2])),false);
model.terminate();
if(installmentData != null && installmentData.length !=0){
if(interestType.equals("I")){
for (int i = 0; i < installmentData.length; i++) {
LoanClosure bean2 = new LoanClosure();
bean2.setMonthYear(String.valueOf(installmentData[i][0]));
bean2.setPrincipalAmt(formatter.format(Double.parseDouble(installmentData[i][1])));
bean2.setInterestAmt(formatter.format(Double.parseDouble(installmentData[i][2])));
bean2.setInstallmentAmt(formatter.format(Double.parseDouble(installmentData[i][3])));
bean2.setBalancePrincipalAmt(formatter.format(Double.parseDouble(installmentData[i][4])));
mapdata.put("installment"+count,"To Be Paid");
totalEmi += Double.parseDouble(installmentData[i][3]);
totalIntPaid += Double.parseDouble(installmentData[i][2]);
totalPrincipal += Double.parseDouble(installmentData[i][1]);
tableList.add(bean2);
count++;
} //end of for loop
}
else{
for (int i = 0; i < installmentData.length; i++) {
LoanClosure bean2 = new LoanClosure();
bean2.setMonthYear(String.valueOf(installmentData[i][0]));
bean2.setPrincipalAmt(formatter.format(Double.parseDouble(installmentData[i][1])));
bean2.setInterestAmt(formatter.format(Double.parseDouble(installmentData[i][2])));
bean2.setInstallmentAmt(formatter.format(Double.parseDouble(installmentData[i][3])));
bean2.setBalancePrincipalAmt(formatter.format(Double.parseDouble(installmentData[i][4])));
mapdata.put("installment"+count,"To Be Paid");
totalEmi += Double.parseDouble(installmentData[i][3]);
totalIntPaid += Double.parseDouble(installmentData[i][2]);
totalPrincipal += Double.parseDouble(installmentData[i][1]);
tableList.add(bean2);
count++;
} //end of for loop
}
if (!bean.getInterestType().equals("R")) {
bean.setTotalPrincipalAmt(formatter.format(Double.parseDouble(bean.getSanctionAmount())));
bean.setTotalInstallmenteAmt(formatter.format((Double.parseDouble(bean.getSanctionAmount()))
+ totalIntPaid));
} //end of if statement
else
bean.setTotalInstallmenteAmt(formatter.format(totalEmi));
bean.setTotalInterestAmt(formatter.format(totalIntPaid));
} //end of if statement
}
bean.setInstallmentFlag("true");
bean.setInstallmentList(tableList);
request.setAttribute("mapData", mapdata);
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
// TODO: handle exception
} //end of try-catch block
}
/**@Method rescheduleInstallmentsForPrinc
* @Purpose To reschedule the installment details for the selected application
* @param bean
* @param principalAmount
* @param interestRate
* @param interestType
* @param noOfInstallment
* @param startDate
* @param request
*/
public void rescheduleInstallmentsForPrinc(LoanClosure bean, String principalAmount, String interestRate,
String interestType, String noOfInstallment, String startDate, HttpServletRequest request){
LoanProccessModel model = new LoanProccessModel();
Double principal = Double.parseDouble(principalAmount);
//int installments = Integer.parseInt(noOfInstallment);
int installments = 0;
String noOfInstallmentString =String.valueOf(Math.ceil(principal/Double.parseDouble(bean.getMonthlyPrincAmount())));
installments =Integer.parseInt(noOfInstallmentString.substring(0,noOfInstallmentString.indexOf(".")));
HashMap mapdata = new HashMap();
logger.info("hiddden "+bean.getInterestType());
double totalEmi = 0.0;
double totalIntPaid = 0.0;
double totalPrincipal = 0.0;
int count = 0;
ArrayList<Object> tableList = new ArrayList<Object>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date startDateParse = sdf.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateParse);
//cal.add(cal.MONTH, 1);
String lastInstallmentDate = "";
boolean dateFlag = false;
String stringDate = sdf.format(cal.getTime());
logger.info("stringDate "+stringDate);
Object [] applCode = {bean.getLoanAppCode()};
Object [][] getPaidInstallmentsData = null;
getPaidInstallmentsData = getSqlModel().getSingleResult(getQuery(10), applCode);
if(getPaidInstallmentsData != null && getPaidInstallmentsData.length != 0){
for (int i = 0; i < getPaidInstallmentsData.length; i++) {
LoanClosure bean1 = new LoanClosure();
String installmentDate = String.valueOf(getPaidInstallmentsData[i][0])+"-"
+String.valueOf(getPaidInstallmentsData[i][1])+"-"
+String.valueOf(getPaidInstallmentsData[i][2]);
if(i == getPaidInstallmentsData.length-1){
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[i][8]);
} //end of if statement
bean1.setMonthYear(installmentDate);
bean1.setPrincipalAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][3])));
bean1.setInterestAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][4])));
bean1.setInstallmentAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][5])));
bean1.setBalancePrincipalAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][6])));
if(String.valueOf(getPaidInstallmentsData[i][7]).equals("Y")){
mapdata.put("installment"+count,"Paid");
} //end of if statement
else{
mapdata.put("installment"+count,"To Be Paid");
} //end of else statement
totalEmi += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][5]));
totalIntPaid += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][4]));
totalPrincipal += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][3]));
tableList.add(bean1);
count++;
dateFlag = true;
} //end of for loop
} //end of if statement
else{
dateFlag = false;
getPaidInstallmentsData = getSqlModel().getSingleResult(getQuery(12), applCode);
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[0][3]);
logger.info("lastInstallmentDate 11111 "+lastInstallmentDate);
} //end of else statement
Object [] firstInstallment = calculateFirstInstallment(bean, stringDate, lastInstallmentDate, principal, interestRate,
installments, dateFlag, String.valueOf(getPaidInstallmentsData[0][0])+"-"+String.valueOf(getPaidInstallmentsData[0][1]));
LoanClosure bean1 = new LoanClosure();
if(dateFlag){
bean1.setMonthYear(String.valueOf(firstInstallment[0]));
} //end of if statement
else{
bean1.setMonthYear(String.valueOf(getPaidInstallmentsData[0][2]));
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[0][0])+"-"+String.valueOf(getPaidInstallmentsData[0][1]);
logger.info("lastInstallmentDate for reducing "+lastInstallmentDate);
} //end of else statement
bean1.setPrincipalAmt(formatter.format(Double.parseDouble(""+firstInstallment[1])));
bean1.setInterestAmt(formatter.format(Double.parseDouble(""+firstInstallment[2])));
bean1.setInstallmentAmt(formatter.format(Double.parseDouble(""+firstInstallment[3])));
bean1.setBalancePrincipalAmt(Utility.twoDecimals(principalAmount));
mapdata.put("installment"+count,"To Be Paid");
count++;
totalEmi += Double.parseDouble(formatter.format(Double.parseDouble(""+firstInstallment[3])));
totalIntPaid += Double.parseDouble(formatter.format(Double.parseDouble(""+firstInstallment[2])));
totalPrincipal += Double.parseDouble(formatter.format(Double.parseDouble(""+firstInstallment[1])));
tableList.add(bean1);
Calendar calInst = Calendar.getInstance();
Date instDate = sdf.parse(lastInstallmentDate);
calInst.setTime(instDate);
calInst.add(calInst.MONTH, 1);
model.initiate(context, session);
logger.info("balance principal after prepayment=="+principal);
String [][]installmentData = model.calcReduceInterestInstallmentSch(principal-(Double.parseDouble(bean.getMonthlyPrincAmount())),installments-1,Double.parseDouble(interestRate),
sdf.format(calInst.getTime()),Double.parseDouble(bean.getMonthlyPrincAmount()));
//String [][] installmentData = model.calculateInstallment(principal, installments, interestRate, interestType, sdf.format(calInst.getTime()),Double.parseDouble(String.valueOf(firstInstallment[2])));
model.terminate();
if(installmentData != null && installmentData.length !=0){
for (int i = 0; i < installmentData.length; i++) {
LoanClosure bean2 = new LoanClosure();
bean2.setMonthYear(String.valueOf(installmentData[i][0]));
bean2.setPrincipalAmt(formatter.format(Double.parseDouble(installmentData[i][1])));
bean2.setInterestAmt(formatter.format(Double.parseDouble(installmentData[i][2])));
bean2.setInstallmentAmt(formatter.format(Double.parseDouble(installmentData[i][3])));
bean2.setBalancePrincipalAmt(formatter.format(Double.parseDouble(installmentData[i][4])));
mapdata.put("installment"+count,"To Be Paid");
totalEmi += Double.parseDouble(installmentData[i][3]);
totalIntPaid += Double.parseDouble(installmentData[i][2]);
totalPrincipal += Double.parseDouble(installmentData[i][1]);
tableList.add(bean2);
count++;
} //end of for loop
bean.setTotalPrincipalAmt(formatter.format(Double.parseDouble(bean.getSanctionAmount())));
bean.setTotalInstallmenteAmt(formatter.format((Double.parseDouble(bean.getSanctionAmount()))
+ totalIntPaid));
bean.setTotalInterestAmt(formatter.format(totalIntPaid));
bean.setInstallmentFlag("true");
bean.setInstallmentList(tableList);
request.setAttribute("mapData", mapdata);
} //end of if statement
} catch (Exception e) {
e.printStackTrace();
logger.error(e);
// TODO: handle exception
} //end of try-catch block
}
/**@Method rescheduleInstallmentsForEmi
* @Purpose To reschedule the installment details for the selected application
* @param bean
* @param principalAmount
* @param interestRate
* @param interestType
* @param noOfInstallment
* @param startDate
* @param request
*/
public void rescheduleInstallmentsForEmi(LoanClosure bean, String principalAmount, String interestRate,
double emiAmount, String startDate, HttpServletRequest request){
LoanProccessModel model = new LoanProccessModel();
double principal = Double.parseDouble(principalAmount);
HashMap mapdata = new HashMap();
logger.info("hiddden "+bean.getInterestType());
double totalEmi = 0.0;
double totalIntPaid = 0.0;
double totalPrincipal = 0.0;
int count = 0;
ArrayList<Object> tableList = new ArrayList<Object>();
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date startDateParse = sdf.parse(startDate);
Calendar cal = Calendar.getInstance();
cal.setTime(startDateParse);
//cal.add(cal.MONTH, 1);
String lastInstallmentDate = "";
boolean dateFlag = false;
String stringDate = sdf.format(cal.getTime());
logger.info("stringDate "+stringDate);
Object [] applCode = {bean.getLoanAppCode()};
Object [][] getPaidInstallmentsData = null;
getPaidInstallmentsData = getSqlModel().getSingleResult(getQuery(10), applCode);
if(getPaidInstallmentsData != null && getPaidInstallmentsData.length != 0){
for (int i = 0; i < getPaidInstallmentsData.length; i++) {
LoanClosure bean1 = new LoanClosure();
String installmentDate = String.valueOf(getPaidInstallmentsData[i][0])+"-"
+String.valueOf(getPaidInstallmentsData[i][1])+"-"
+String.valueOf(getPaidInstallmentsData[i][2]);
if(i == getPaidInstallmentsData.length-1){
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[i][8]);
} //end of if statement
bean1.setMonthYear(installmentDate);
bean1.setPrincipalAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][3])));
bean1.setInterestAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][4])));
bean1.setInstallmentAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][5])));
bean1.setBalancePrincipalAmt(Utility.twoDecimals(String.valueOf(getPaidInstallmentsData[i][6])));
if(String.valueOf(getPaidInstallmentsData[i][7]).equals("Y")){
mapdata.put("installment"+count,"Paid");
} //end of if statement
else{
mapdata.put("installment"+count,"To Be Paid");
} //end of else statement
totalEmi += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][5]));
totalIntPaid += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][4]));
totalPrincipal += Double.parseDouble(String.valueOf(getPaidInstallmentsData[i][3]));
tableList.add(bean1);
count++;
dateFlag = true;
} //end of for loop
} //end of if statement
else{
dateFlag = false;
getPaidInstallmentsData = getSqlModel().getSingleResult(getQuery(12), applCode);
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[0][3]);
logger.info("lastInstallmentDate 11111 "+lastInstallmentDate);
} //end of else statement
if(!dateFlag){
lastInstallmentDate = String.valueOf(getPaidInstallmentsData[0][0])+"-"+String.valueOf(getPaidInstallmentsData[0][1]);
}
double firstInterest = 0.0;
LoanClosure bean1 = new LoanClosure();
bean1.setMonthYear(String.valueOf(getPaidInstallmentsData[0][2]));
logger.info("lastInstallmentDate for reducing "+lastInstallmentDate);
Calendar calInst = Calendar.getInstance();
Date instDate = sdf.parse(lastInstallmentDate);
calInst.setTime(instDate);
calInst.add(calInst.MONTH, 1);
model.initiate(context, session);
String [][] installmentData = null;
if(bean.getInterestType().equals("N")){
installmentData = model.calculateNoOfInstallment(principal, emiAmount,sdf.format(calInst.getTime()));
}else{
firstInterest = generateFirstInterest(bean, stringDate, lastInstallmentDate, principal, interestRate,
dateFlag, String.valueOf(getPaidInstallmentsData[0][0])+"-"+String.valueOf(getPaidInstallmentsData[0][1]));
if(bean.getInterestType().equals("R")){
installmentData = model.calculateNoOfInstallmentForReduce(principal, emiAmount,Double.parseDouble(interestRate), sdf.format(calInst.getTime()));
}else
installmentData = model.calculateNoOfInstallment(principal, emiAmount,interestRate, sdf.format(calInst.getTime()),firstInterest);
}
model.terminate();
logger.info("installmentData length=="+installmentData.length);
if(installmentData != null && installmentData.length !=0){
for (int i = 0; i < installmentData.length; i++) {
LoanClosure bean2 = new LoanClosure();
bean2.setMonthYear(String.valueOf(installmentData[i][0]));
bean2.setPrincipalAmt(Utility.twoDecimals(installmentData[i][1]));
bean2.setInterestAmt(Utility.twoDecimals(installmentData[i][2]));
bean2.setInstallmentAmt(Utility.twoDecimals(installmentData[i][3]));
bean2.setBalancePrincipalAmt(Utility.twoDecimals(installmentData[i][4]));
mapdata.put("installment"+count,"To Be Paid");
totalEmi += Double.parseDouble(installmentData[i][3]);
totalIntPaid += Double.parseDouble(installmentData[i][2]);
totalPrincipal += Double.parseDouble(installmentData[i][1]);
tableList.add(bean2);
count++;
} //end of for loop
/*bean.setTotalPrincipalAmt(formatter.format(Double.parseDouble(bean.getSanctionAmount())).replace(",", ",")));
bean.setTotalInstallmenteAmt(formatter.format((Double.parseDouble(bean.getSanctionAmount()))
+ totalIntPaid)));
bean.setTotalInterestAmt(formatter.format(totalIntPaid)));*/
if (!bean.getInterestType().equals("R")) {
bean.setTotalPrincipalAmt(formatter.format(Double.parseDouble(bean.getSanctionAmount())));
bean.setTotalInstallmenteAmt(formatter.format((Double.parseDouble(bean.getSanctionAmount()))
+ totalIntPaid));
} //end of if statement
else
bean.setTotalInstallmenteAmt(formatter.format(totalEmi));
bean.setTotalInterestAmt(formatter.format(totalIntPaid));
bean.setInstallmentFlag("true");
bean.setInstallmentList(tableList);
request.setAttribute("mapData", mapdata);
} //end of if statement
else{
bean.setInstallmentFlag("false");
}
} catch (Exception e) {
//e.printStackTrace();
logger.error(e);
bean.setInstallmentFlag("false");
// TODO: handle exception
} //end of try-catch block
}
/**@method calculateNumberOfDays
* @purpose to calculate the no of days between two dates
* @param fromDate
* @param toDate
* @return no of days between two dates
*/
public int calculateNumberOfDays(String fromDate, String toDate){
int daysBetween = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date fromDateParse = sdf.parse(fromDate);
Date toDateParse = sdf.parse(toDate);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDateParse);
Calendar calTo = Calendar.getInstance();
calTo.setTime(toDateParse);
while(cal.before(calTo)){
cal.add(cal.DAY_OF_MONTH, 1);
daysBetween++;
} //end of while loop
//logger.info("daysBetween "+daysBetween);
}catch (Exception e) {
logger.error("error in date parse "+e);
//e.printStackTrace();
// TODO: handle exception
} //end of try-catch block
return daysBetween;
}
/**@method generateFirstInterest
* @purpose to calculate details for first installment
* @param bean
* @param prePayDate
* @param lastInstallmentDate
* @param principalAmount
* @param interestRate
* @param installments
* @param dateFlag
* @param startDate
* @return installment details object array
*/
public double generateFirstInterest(LoanClosure bean, String prePayDate, String lastInstallmentDate,
double principalAmount, String interestRate, boolean dateFlag, String startDate){
double firstInterest =0.0;
String date = "";
int noOfDays = 0;
double interestAmount = 0.0;
//int daysBeforePrePay = calculateNumberOfDays(lastInstallmentDate, prePayDate);
//logger.info("daysBeforePrePay "+daysBeforePrePay);
//interestAmount = Double.parseDouble(interestAmount(Double.parseDouble(bean.getBalanceAmount()), interestRate, daysBeforePrePay));
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
if(dateFlag){
date = lastInstallmentDate;
} //end of if statement
else{
date = startDate;
} //end of else statement
Date fromDateParse = sdf.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDateParse);
cal.add(cal.MONTH, 1);
/**
* select the pre payment date, pre payment amount and balance amount at time of pre payment
* form HRMS_LOAN_CLOSURE to calculate the interest amount for first installment after every pre payment
*/
String selectQuery = "SELECT TO_CHAR(LOAN_PREPAY_DATE, 'DD-MM-YYYY'), LOAN_PREPAY_AMOUNT, LOAN_BALANCE_AMOUNT "
+"FROM HRMS_LOAN_CLOSURE "
+"WHERE LOAN_APPL_CODE = "+bean.getLoanAppCode()+" AND LOAN_PREPAY_DATE BETWEEN "
+"TO_DATE('"+lastInstallmentDate+"', 'DD-MM-YYYY') AND TO_DATE('"+sdf.format(cal.getTime())+"', 'DD-MM-YYYY')"
+" ORDER BY LOAN_CLOSURE_CODE";
Object [][] prePayData = getSqlModel().getSingleResult(selectQuery); //getting the data from HRMS_LOAN_CLOSURE in prePayData object array
if(prePayData != null && prePayData.length != 0){ //if pre payment data available
double princiAmount = 0.0;
for (int i = 0; i < prePayData.length; i++) { //then iterator over the prePayData array
if(i == 0){
//calculate the no of days between last installment date and last pre payment date
noOfDays = calculateNumberOfDays(lastInstallmentDate, String.valueOf(prePayData[i][0]));
princiAmount = Double.parseDouble(String.valueOf(prePayData[i][2])); //principal amount at the time of first pre payment
} //end of if statement
else{
//calculate the no of days between two successive pre payment dates
noOfDays = calculateNumberOfDays(String.valueOf(prePayData[i-1][0]), String.valueOf(prePayData[i][0]));
princiAmount -= Double.parseDouble(String.valueOf(prePayData[i-1][1])); //principal amount at the time of each pre payment
} //end of else statement
logger.info("noOfDays if-----------------"+noOfDays);
logger.info("princiAmount-----------------"+princiAmount);
logger.info("interestRate-----------------"+interestRate);
//calculate interest amount after each pre payment
interestAmount += Double.parseDouble(interestAmount(princiAmount, interestRate, noOfDays));
logger.info("total interest amount "+interestAmount);
} //end of for loop
princiAmount -= Double.parseDouble(String.valueOf(prePayData[prePayData.length-1][1])); //principal amount at the time of last pre payment
//calculate no of days between last pre payment date and latest pre payment date
noOfDays = calculateNumberOfDays(String.valueOf(prePayData[prePayData.length-1][0]), prePayDate);
logger.info("noOfDays after-----------------"+noOfDays);
logger.info("princiAmount after-----------------"+princiAmount);
logger.info("interestRate after-----------------"+interestRate);
interestAmount += Double.parseDouble(interestAmount(princiAmount, interestRate, noOfDays)); //calculate interest amount for this duration
} //end of if statement
else{ //if pre payment data is not available then
//calculate the no of days between last installment date and latest pre payment date
noOfDays = calculateNumberOfDays(lastInstallmentDate, prePayDate);
logger.info("daysBeforePrePay "+noOfDays);
logger.info("principal amount "+Double.parseDouble(bean.getBalanceAmount()));
//calculate interest amount for this duration
interestAmount = Double.parseDouble(interestAmount(Double.parseDouble(bean.getBalanceAmount()), interestRate, noOfDays));
} //end of else statement
//calculate the no of days between latest pre payment date and next installment date
noOfDays = calculateNumberOfDays(prePayDate, sdf.format(cal.getTime()));
logger.info("daysAfterPrePay "+noOfDays);
logger.info("principal amount last "+principalAmount);
//calculate interest amount for this duration
interestAmount += Double.parseDouble(interestAmount(principalAmount, interestRate, noOfDays));
} catch (Exception e) {
logger.error("error in date parse "+e);
// TODO: handle exception
} //end of try-catch block
//calculate installment amount
firstInterest = interestAmount;
return firstInterest;
}
/**@method calculateFirstInstallment
* @purpose to calculate details for first installment
* @param bean
* @param prePayDate
* @param lastInstallmentDate
* @param principalAmount
* @param interestRate
* @param installments
* @param dateFlag
* @param startDate
* @return installment details object array
*/
public Object[] calculateFirstInstallment(LoanClosure bean, String prePayDate, String lastInstallmentDate,
double principalAmount, String interestRate, int installments, boolean dateFlag, String startDate){
Object [] firstInstallment = new Object [4];
String date = "";
int noOfDays = 0;
double interestAmount = 0.0;
//int daysBeforePrePay = calculateNumberOfDays(lastInstallmentDate, prePayDate);
//logger.info("daysBeforePrePay "+daysBeforePrePay);
//interestAmount = Double.parseDouble(interestAmount(Double.parseDouble(bean.getBalanceAmount()), interestRate, daysBeforePrePay));
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
if(dateFlag){
date = lastInstallmentDate;
} //end of if statement
else{
date = startDate;
} //end of else statement
Date fromDateParse = sdf.parse(date);
Calendar cal = Calendar.getInstance();
cal.setTime(fromDateParse);
cal.add(cal.MONTH, 1);
/**
* select the pre payment date, pre payment amount and balance amount at time of pre payment
* form HRMS_LOAN_CLOSURE to calculate the interest amount for first installment after every pre payment
*/
String selectQuery = "SELECT TO_CHAR(LOAN_PREPAY_DATE, 'DD-MM-YYYY'), LOAN_PREPAY_AMOUNT, LOAN_BALANCE_AMOUNT "
+"FROM HRMS_LOAN_CLOSURE "
+"WHERE LOAN_APPL_CODE = "+bean.getLoanAppCode()+" AND LOAN_PREPAY_DATE BETWEEN "
+"TO_DATE('"+lastInstallmentDate+"', 'DD-MM-YYYY') AND TO_DATE('"+sdf.format(cal.getTime())+"', 'DD-MM-YYYY')"
+" ORDER BY LOAN_CLOSURE_CODE";
Object [][] prePayData = getSqlModel().getSingleResult(selectQuery); //getting the data from HRMS_LOAN_CLOSURE in prePayData object array
//int daysAfterPrePay = calculateNumberOfDays(prePayDate, sdf.format(cal.getTime()));
//logger.info("daysAfterPrePay "+daysAfterPrePay);
//interestAmount += Double.parseDouble(interestAmount(principalAmount, interestRate, daysAfterPrePay));
firstInstallment [0] = new SimpleDateFormat("dd-MMM-yyyy").format(cal.getTime());
logger.info("date-----------------"+firstInstallment [0]);
if(prePayData != null && prePayData.length != 0){ //if pre payment data available
double princiAmount = 0.0;
for (int i = 0; i < prePayData.length; i++) { //then iterator over the prePayData array
if(i == 0){
//calculate the no of days between last installment date and last pre payment date
noOfDays = calculateNumberOfDays(lastInstallmentDate, String.valueOf(prePayData[i][0]));
princiAmount = Double.parseDouble(String.valueOf(prePayData[i][2])); //principal amount at the time of first pre payment
} //end of if statement
else{
//calculate the no of days between two successive pre payment dates
noOfDays = calculateNumberOfDays(String.valueOf(prePayData[i-1][0]), String.valueOf(prePayData[i][0]));
princiAmount -= Double.parseDouble(String.valueOf(prePayData[i-1][1])); //principal amount at the time of each pre payment
} //end of else statement
logger.info("noOfDays if-----------------"+noOfDays);
logger.info("princiAmount-----------------"+princiAmount);
logger.info("interestRate-----------------"+interestRate);
//calculate interest amount after each pre payment
interestAmount += Double.parseDouble(interestAmount(princiAmount, interestRate, noOfDays));
logger.info("total interest amount "+interestAmount);
} //end of for loop
princiAmount -= Double.parseDouble(String.valueOf(prePayData[prePayData.length-1][1])); //principal amount at the time of last pre payment
//calculate no of days between last pre payment date and latest pre payment date
noOfDays = calculateNumberOfDays(String.valueOf(prePayData[prePayData.length-1][0]), prePayDate);
logger.info("noOfDays after-----------------"+noOfDays);
logger.info("princiAmount after-----------------"+princiAmount);
logger.info("interestRate after-----------------"+interestRate);
interestAmount += Double.parseDouble(interestAmount(princiAmount, interestRate, noOfDays)); //calculate interest amount for this duration
} //end of if statement
else{ //if pre payment data is not available then
//calculate the no of days between last installment date and latest pre payment date
noOfDays = calculateNumberOfDays(lastInstallmentDate, prePayDate);
logger.info("daysBeforePrePay "+noOfDays);
logger.info("principal amount "+Double.parseDouble(bean.getBalanceAmount()));
//calculate interest amount for this duration
interestAmount = Double.parseDouble(interestAmount(Double.parseDouble(bean.getBalanceAmount()), interestRate, noOfDays));
} //end of else statement
//calculate the no of days between latest pre payment date and next installment date
noOfDays = calculateNumberOfDays(prePayDate, sdf.format(cal.getTime()));
logger.info("daysAfterPrePay "+noOfDays);
logger.info("principal amount last "+principalAmount);
//calculate interest amount for this duration
interestAmount += Double.parseDouble(interestAmount(principalAmount, interestRate, noOfDays));
} catch (Exception e) {
logger.error("error in date parse "+e);
// TODO: handle exception
} //end of try-catch block
//calculate installment amount
double monthlyPrincAmt =0;
if(bean.getHiddenCalType().equals("P")){
monthlyPrincAmt =Double.parseDouble(bean.getMonthlyPrincAmount());
firstInstallment[1] = formatter.format(monthlyPrincAmt);
}else{
if(installments==0){
firstInstallment[1] = 0;
}else{
firstInstallment[1] = formatter.format((principalAmount/installments));
}
}
double installmentAmount = Double.parseDouble(String.valueOf(firstInstallment[1]))+interestAmount;
logger.info("installmentAmount "+installmentAmount);
firstInstallment[2] = formatter.format(interestAmount);
firstInstallment[3] = formatter.format(installmentAmount);
logger.info("firstInstallment[1] "+firstInstallment[1]);
logger.info("firstInstallment[2] "+firstInstallment[2]);
logger.info("firstInstallment[3] "+firstInstallment[3]);
return firstInstallment;
}
/**@method interestAmount
* @purpose to calculate interest amount for first installment
* @param principalAmount
* @param interestRate
* @param noOfDays
* @return interest amount
*/
public String interestAmount(double principalAmount, String interestRate, int noOfDays){
String interestAmount = Utility.twoDecimals(((principalAmount * Double.parseDouble(interestRate)*noOfDays))/(100.0*365));
logger.info("intAmt inside generateFirstInterest==="+interestAmount);
return interestAmount;
}
/**@Method showInstallmentSchedule
* @Purpose To retrieve all the installment details for the selected application
* @param bean
* @param request
*/
public void showInstallmentSchedule(LoanClosure bean, HttpServletRequest request){
try {
logger.info("inside showInstallmentSchedule");
String monthYear = "";
double totalEmi = 0.0;
double totalIntPaid = 0.0;
double totalPrincipal = 0.0;
ArrayList<Object> tableList = new ArrayList<Object>();
HashMap mapdata = new HashMap();
Object[] loanApplCode = { bean.getLoanAppCode() };
Object[] loanClosureCode = { bean.getLoanClosureCode(), bean.getLoanAppCode()};
Object [][]noOfInstallment = getSqlModel().getSingleResult(getQuery(13), loanClosureCode);
if(!bean.getInterestType().equals("I")){
bean.setNoOfInstallmentOther(checkNull(String.valueOf(noOfInstallment[0][1])));
}else{
bean.setNoOfInstallmentsReduceInt(checkNull(String.valueOf(noOfInstallment[0][1])));
}
bean.setEmiAmount(checkNull(String.valueOf(noOfInstallment[0][0])));
bean.setMonthlyPrincAmount(checkNull(String.valueOf(noOfInstallment[0][2])));
if(!bean.getEmiAmount().equals("")){
bean.setHiddenCalType("E");
}else if(!bean.getMonthlyPrincAmount().equals("")){
bean.setHiddenCalType("P");
} else{
bean.setHiddenCalType("I");
}
Object[][] installData = getSqlModel().getSingleResult(getQuery(8), loanApplCode);
for (int i = 0; i < installData.length; i++) {
LoanClosure bean1 = new LoanClosure();
monthYear = String.valueOf(installData[i][0])+ "-" + String.valueOf(installData[i][1])
+"-" + String.valueOf(installData[i][2]);
bean1.setMonthYear(monthYear);
bean1.setPrincipalAmt(String.valueOf(Double.parseDouble(String.valueOf(installData[i][3]))));
bean1.setInterestAmt(String.valueOf(Double.parseDouble(String.valueOf(installData[i][4]))));
bean1.setInstallmentAmt(String.valueOf(Double.parseDouble(String.valueOf(installData[i][5]))));
bean1.setBalancePrincipalAmt(Utility.twoDecimals(String.valueOf(installData[i][6])));
totalEmi += Double.parseDouble(String.valueOf(installData[i][5]));
totalIntPaid += Double.parseDouble(String.valueOf(installData[i][4]));
totalPrincipal += Double.parseDouble(String.valueOf(installData[i][3]));
if(String.valueOf(installData[i][7]).equals("Y"))
mapdata.put("installment"+i,"Paid");
else
mapdata.put("installment"+i,"To Be Paid");
tableList.add(bean1);
} //end of for loop
bean.setInstallmentFlag("true");
/*
* bean.setTotalInstallmenteAmt(String.valueOf(Double.parseDouble(bean.getSanctionAmount())));
* bean.setTotalInterestAmt(String.valueOf(Double.parseDouble("0.0")));
* bean.setTotalPrincipalAmt(String.valueOf(Double.parseDouble(bean.getSanctionAmount())));
*/
if (!bean.getInterestType().equals("R")) {
bean.setTotalPrincipalAmt(String.valueOf(Double.parseDouble(bean.getSanctionAmount())));
bean.setTotalInstallmenteAmt(String.valueOf((Double.parseDouble(bean.getSanctionAmount()))
+ totalIntPaid));
} //end of if
else
bean.setTotalInstallmenteAmt(Utility.twoDecimals(totalEmi));
bean.setTotalInterestAmt(Utility.twoDecimals(totalIntPaid));
bean.setInstallmentList(tableList);
request.setAttribute("mapData", mapdata);
} catch (Exception e) {
//e.printStackTrace();
logger.error(e);
}
}
/**@Method checkNull
* @Purpose To check whether the value is null or not
* @param result
* @return String
*/
public String checkNull(String result) {
if (result == null || result.equals("null")) {
return "";
} //end of if
else {
return result;
} //end of else
}
/**@Method setBalanceAmount
* @Purpose To calculate the balance amount and set it to the respective field
* @param bean
*/
public void setBalanceAmount(LoanClosure bean){
logger.info("in setBalanceAmount method");
double paidAmount = 0; //Double.parseDouble(bean.getAmountPaid());
Object [] loanApplCode = {bean.getLoanAppCode()};
Object [][] result = getSqlModel().getSingleResult(getQuery(3), loanApplCode);
Object [][] prePayAmount = getSqlModel().getSingleResult(getQuery(11), loanApplCode);
if(result != null && result.length != 0){
paidAmount = Double.parseDouble(String.valueOf(result[0][0]))
+ Double.parseDouble(String.valueOf(prePayAmount[0][0]));
bean.setAmountPaid(formatter.format(paidAmount));
} //end of if
else {
bean.setAmountPaid("0");
} //end of else
double sanctionAmount = Double.parseDouble((bean.getSanctionAmount()));
//double paidAmount = Double.parseDouble(bean.getAmountPaid());
double balanceAmount = sanctionAmount-paidAmount;
bean.setBalanceAmount(formatter.format(balanceAmount).replace(",", ""));
logger.info("bean.getInterestType() "+bean.getInterestType());
//bean.setInterestType(bean.getInterestType());
}
}
| [
"Jigar.V@jigar_vasani.THIRDI.COM"
] | Jigar.V@jigar_vasani.THIRDI.COM |
45afe6fc393c9c67bcdd43f32bcccf7db9cfe3c0 | c7a2725bbd646649fbf9dbbd8126c091ffcca3c5 | /app/src/main/java/com/example/saurabh/smc/LOGIN.java | c84898ec342388cfb45d4b8232cd2415023cad68 | [] | no_license | pragneshjogadiya/SMC | 4ff7e8413a52ff34a29aaa5b362324d993441ea8 | 16d01db4ba5c8fbba5f3e5297c4f4e930fac05e7 | refs/heads/master | 2021-01-17T08:07:30.234362 | 2016-06-02T16:32:31 | 2016-06-02T16:32:31 | 60,279,819 | 0 | 1 | null | null | null | null | UTF-8 | Java | false | false | 1,005 | java | package com.example.saurabh.smc;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
/**
* Created by Saurabh on 5/25/2016.
*/
public class LOGIN extends AppCompatActivity {
Button signin;
boolean buttonpress = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login_activity);
signin = (Button) findViewById(R.id.signin_button);
signin.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
buttonpress = true;
Intent openH = new Intent(LOGIN.this, HOMEPAGE.class);
startActivity(openH);
}
});
}
@Override
protected void onPause(){
super.onPause();
if(buttonpress == true){
finish();
}
}
}
| [
"pragneshjogadiya@gmail.com"
] | pragneshjogadiya@gmail.com |
67be0249f80f7fe935f1cdcb3a444a7128238005 | e96172bcad99d9fddaa00c25d00a319716c9ca3a | /plugin/src/main/java/com/intellij/java/impl/codeInsight/lookup/TypedLookupItem.java | ca3a0f7161ed45136f559a02a2356278c292f5cb | [
"Apache-2.0"
] | permissive | consulo/consulo-java | 8c1633d485833651e2a9ecda43e27c3cbfa70a8a | a96757bc015eff692571285c0a10a140c8c721f8 | refs/heads/master | 2023-09-03T12:33:23.746878 | 2023-08-29T07:26:25 | 2023-08-29T07:26:25 | 13,799,330 | 5 | 4 | Apache-2.0 | 2023-01-03T08:32:23 | 2013-10-23T09:56:39 | Java | UTF-8 | Java | false | false | 1,001 | java | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* 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.intellij.java.impl.codeInsight.lookup;
import consulo.language.editor.completion.ClassConditionKey;
import com.intellij.java.language.psi.PsiType;
import javax.annotation.Nullable;
/**
* @author peter
*/
public interface TypedLookupItem {
ClassConditionKey<TypedLookupItem> CLASS_CONDITION_KEY = ClassConditionKey.create(TypedLookupItem.class);
@Nullable
PsiType getType();
}
| [
"vistall.valeriy@gmail.com"
] | vistall.valeriy@gmail.com |
0e1845fc57172b029599b8d178719334d3cabc08 | 6246ead40970de7586337989821a53ad21909a2f | /app/src/main/java/com/power/travel/xixuntravel/app/BaseActivity.java | 3ce3e1149e5de2a671bad8ebc7fe9ce64892f4ee | [] | no_license | Power-Android/xixun | 7f05f65e12dfd0d8bb9b4a61df4ca8d39c4f87c1 | c0421e147222fecc630b34f3252d5cd28de8e84e | refs/heads/master | 2021-05-08T07:40:57.952498 | 2018-03-19T08:48:36 | 2018-03-19T08:48:36 | 106,783,602 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,232 | java | package com.power.travel.xixuntravel.app;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import com.power.travel.xixuntravel.R;
import com.power.travel.xixuntravel.utils.DialogUtils;
public class BaseActivity extends FragmentActivity implements OnClickListener {
@Override
protected void onCreate(Bundle arg0) {
setTranslucentStatus();
super.onCreate(arg0);
}
@Override
public void onClick(View v) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
protected void showEnsure(String message){
DialogUtils.showEnsure(this, message, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
/**
* isConnect 判断网络连接
* @return
*/
public boolean isConnect() {
ConnectivityManager conManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = conManager.getActiveNetworkInfo();
if (networkInfo != null) { // 注意,这个判断一定要的哦,要不然会出错
return networkInfo.isAvailable();
}
return false;
}
public void onPause() {
super.onPause();
// MobclickAgent.onPause(this);
}
@Override
protected void onResume() {
super.onResume();
// MobclickAgent.onResume(this);
if (isConnect() == false) {// 判断网络连接 if语句
DialogUtils.showEnsure(this, "网络连接失败, 请确认网络连接!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
}
/**
* 设置状态栏背景状态
*/
private void setTranslucentStatus() {
setStatusBarTranslucent(true);
SystemBarTintManager tintManager = new SystemBarTintManager(this);
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarTintResource(R.color.title_layout_bg_color);// 状态栏的背景颜色(0表示无背景)
}
/**
* 设置状态栏是否透明
*
* @param isTransparent
*/
private void setStatusBarTranslucent(boolean isTransparent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT
&& isTransparent) {
Window win = getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
// 导航栏透明
final int sBits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
winParams.flags |= sBits;
win.setAttributes(winParams);
}
}
public Resources getResources() {
Resources res = super.getResources();
Configuration config=new Configuration();
config.setToDefaults();
res.updateConfiguration(config,res.getDisplayMetrics() );
return res;
}
}
| [
"power_android@163.com"
] | power_android@163.com |
7e48b886a418665c624a0ed853fc474369019d43 | fca7bdb976cd6133776ab2faae5542b1379ad79d | /src/main/java/com/google/glassware/Weather.java | 95d5130bd0be93688eaf90a0d407cdcc02d5b72a | [
"CC-BY-3.0",
"Apache-2.0"
] | permissive | getglassedatpace/MirrorAPIdemo | 87944b20d667e3c2be001f8a4275acecbd6f4c28 | d38c1d9c5d3e15e6174c0f66a13e7f74da7d67c1 | refs/heads/master | 2020-05-17T20:54:39.667260 | 2015-02-02T07:27:49 | 2015-02-02T07:27:49 | 30,005,966 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,315 | java | package com.google.glassware;
/**
* Created by Diana Melara on 2/2/15.
*/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
public class Weather {
private final String units = "imperial"; //Imperial, metric
private String cityName;
private String weather;
private String humidity;
private String icon;
private String temperature;
private String windSpeed;
public String getWeather(){
return weather;
}
public String getHumidity(){
return humidity;
}
public String getIcon(){
return icon;
}
public String getTemperature(){
return temperature;
}
public String getWindSpeed(){
return windSpeed;
}
public String getCityName(){
return cityName;
}
public Weather(String zipCode){
String s = "";
try{
s = "["+readUrl("http://api.openweathermap.org/data/2.5/find?q="+zipCode+",USA&units="+units)+"]";
} catch(Exception e){
}
JSONParser parser = new JSONParser();
try{
Object obj = parser.parse(s);
JSONArray array = (JSONArray)obj;
JSONObject obj2 = (JSONObject)array.get(0);
array = (JSONArray)(parser.parse(obj2.get("list").toString()));
JSONObject obj3 = (JSONObject)( array.get(0));
cityName = obj3.get("name").toString();
/*---------------------weather---------------------*/
array = (JSONArray)(parser.parse(obj3.get("weather").toString()));
JSONObject obj4 = (JSONObject)array.get(0);
weather = obj4.get("description").toString();
icon = "http://openweathermap.org/img/w/"+obj4.get("icon")+".png";
/*---------------------main---------------------*/
String temp = "["+obj3.get("main").toString()+"]";
array = (JSONArray)(parser.parse(temp));
JSONObject obj6 = (JSONObject)array.get(0);
humidity = obj6.get("humidity")+"%";
temperature = obj6.get("temp")+" F";
/*---------------------wind---------------------*/
temp = "["+obj3.get("wind").toString()+"]";
array = (JSONArray)(parser.parse(temp));
JSONObject obj8 = (JSONObject)array.get(0);
windSpeed = obj8.get("speed")+" mph";
}catch(ParseException pe){
System.out.println("position: " + pe.getPosition());
System.out.println(pe);
}
}
private static String readUrl(String urlString) throws Exception {
BufferedReader reader = null;
try {
URL url = new URL(urlString);
reader = new BufferedReader(new InputStreamReader(url.openStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
return buffer.toString();
} finally {
if (reader != null)
reader.close();
}
}
}
| [
"geekmlle@gmail.com"
] | geekmlle@gmail.com |
0c6ba1ed0115fe7d546a4780ab0f9eec765bb9bf | 2a99a287228e446eb30096abb0f920bb320262f5 | /yikangYouthFountain/src/main/java/com/yikangyiliao/pension/dao/QuestionAnswerDao.java | 9cd0e20d65ee53e44de7e184487aca2867800742 | [] | no_license | yikangmc/youthFountain | fc76a8e2e696189758e4a20fcee0c9abd138f2ef | 7f24f43beb42488d15bdd958e462403f9c564ee2 | refs/heads/master | 2021-01-19T02:35:22.358453 | 2016-11-08T08:22:23 | 2016-11-08T08:22:23 | 44,161,283 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,445 | java | package com.yikangyiliao.pension.dao;
import java.util.List;
import java.util.Map;
import com.yikangyiliao.pension.entity.QuestionAnswer;
public interface QuestionAnswerDao {
int deleteByPrimaryKey(Long questionAnswerId);
int insert(QuestionAnswer record);
int insertSelective(QuestionAnswer record);
QuestionAnswer selectByPrimaryKey(Long questionAnswerId);
int updateByPrimaryKeySelective(QuestionAnswer record);
int updateByPrimaryKey(QuestionAnswer record);
/**
* @author liushuaic
* @date 2016-05-10 15:44
* @desc 添加问题支持
* */
int updateQuestionAnsweStartup(Long questionAnswerId);
/**
* @author liushuaic
* @date 2016-05-10 15:47
* @desc 取消回答的支持
* */
int updateQuestionAnswerdown(Long questionAnswerId);
/**
* @author liushuaic
* @date 2016-05-30 15:08
* @desc 获取问题的所有答案
* */
List<QuestionAnswer> selectQuestionAnswer(Map<String,Object> paramMap);
/**
* @author liushuaic
* @date 2016-06-6 19:28
* @desc 获取精彩回答
* */
List<QuestionAnswer> getHotQuestionAnswer(Map<String,Object> paramMap);
/**
* @author liushuaic
* @date 2016-06-13 15:48
* @desc 支持某一个问题回答
* */
int updateQuestionAnswerStarUpByQuestionAnswerId(Long questionAnswerId);
} | [
"lavedream@hotmail.com"
] | lavedream@hotmail.com |
44e81f63dabec0a8e1d629775e4386203bdb5b7d | 927a2ffd971f084f7c4c15d0e80f1471959049f3 | /Principal.java | 2868d87c85396c1bd7b25c635b96fe6174fcf93a | [] | no_license | GianCarloGall/Examen-3erPacial | 31659cfd42409760ab76881694d36eef84d9a33c | 49fd00cb403ab72265a9e1315cbd29b88d934bba | refs/heads/master | 2023-02-13T18:08:55.250158 | 2021-01-09T02:09:31 | 2021-01-09T02:09:31 | 328,054,970 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,160 | java | import java.util.*;
public class Principal{
public static void main(String[] args){
char eror = 0;
Scanner in = new Scanner(System.in);
do{
char elec;
System.out.println("---AHORCADOS EL JUEGO---");
System.out.println("Quieres Jugar en Multijugador? s/n");
elec = in.next().charAt(0);
switch (elec) {
case 'n':
Individual obj = new Individual();
obj.Individual();
System.out.println("Quieres volver al menu? s/n");
eror = in.next().charAt(0);
break;
case 's':
Multijugador obj1 = new Multijugador();
obj1.Multijugador();
System.out.println("Quieres volver al menu? s/n");
eror = in.next().charAt(0);
break;
default:
System.out.print("Solo s/n");
eror = 's';
break;
}
}while(eror == 's');
System.out.println("Gracias por jugar :)");
}
} | [
"ggallegosg1900@alumno.ipn.mx"
] | ggallegosg1900@alumno.ipn.mx |
b33412866d493af89abb847c5d9ad8e132a20254 | 0a8f59d4e468a334bc7133b7170b853fa8ddd2e5 | /src/main/java/Core/CommandsList.java | 1af455fb346a42d08b702cf51ae3d947ebe7744c | [] | no_license | Trapping/Emulator | c18ff871cdf88e80f9bfaa06df7bbf920dcb7857 | d02f7222c64da86d593133683e907e987ac2c638 | refs/heads/master | 2020-03-12T11:10:55.266215 | 2018-06-18T01:02:34 | 2018-06-18T01:02:34 | 130,590,431 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 624 | java | package Core;
import java.util.ArrayList;
public class CommandsList {
private ArrayList<Command> commandArrayList = new ArrayList<>();
public CommandsList(){
}
public void addCommand(Command command){
commandArrayList.add(command);
}
public ArrayList<Command> getCommandArrayList() {
return commandArrayList;
}
public ArrayList<String> getCodesArrayList() {
ArrayList<String> arrayList = new ArrayList<>();
for (Command command: commandArrayList
) {
arrayList.add(command.getCode());
}
return arrayList;
}
}
| [
"trappingzero@gmail.com"
] | trappingzero@gmail.com |
303a23bcc4c52a7097516b6f9616fa32951eceb1 | 4e22fe5ddc0139c4d3f1cf0f46c8f801390d6940 | /workspace/site/src/com/internousdev/site/action/UserCreateCompleteAction.java | b3991f8b0e8bb376bf8353706e21c4a164d99f67 | [] | no_license | nskrium/backup | c86d8984091851eebc0914e7344c2e4a195a55dc | 9314f180313c3de25f9b50cae220693538a53be9 | refs/heads/master | 2021-09-05T22:08:47.854866 | 2018-01-31T08:23:34 | 2018-01-31T08:23:34 | 114,215,710 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,337 | java | package com.internousdev.site.action;
import java.sql.SQLException;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.internousdev.site.dao.UserCreateCompleteDAO;
import com.opensymphony.xwork2.ActionSupport;
public class UserCreateCompleteAction extends ActionSupport implements SessionAware {
private String loginUserId;
private String loginPassword;
private String userName;
public Map<String, Object> session;
private String result;
private UserCreateCompleteDAO userCreateCompleteDAO= new UserCreateCompleteDAO();
public String execute() throws SQLException {
userCreateCompleteDAO.createUser(session.get("loginUserId").toString(),
session.get("loginPassword").toString(),
session.get("userName").toString());
result= SUCCESS;
return result;
}
public String getLoginUserId() {
return loginUserId;
}
public void setLoginUserId (String loginUserId) {
this.loginUserId= loginUserId;
}
public String getLoginPassword() {
return loginPassword;
}
public void setLoginPassword (String loginPassword) {
this.loginPassword= loginPassword;
}
public String getUserName() {
return userName;
}
public void setUserName (String userName) {
this.userName= userName;
}
public void setSession (Map<String, Object> session) {
this.session= session;
}
}
| [
"nskrium@outlook.jp"
] | nskrium@outlook.jp |
6facb244d053486195ca13dd6c04fac6d7216260 | 8b77de92dc2f45c96ee8317f302a5a953bf8c7f3 | /src/main/java/koschei/models/Ocean1.java | 25a0f43d9ab710f543d3e9b08444054ef1a995ca | [] | no_license | Saykh/JM4 | 9dfac2c2ee73ac65118ef3282aa6b863ce5bb595 | 183faa7c3dcf54e8f94b4789f836d7676d8fd6d3 | refs/heads/master | 2023-07-12T17:50:13.905704 | 2021-08-21T18:16:11 | 2021-08-21T18:16:11 | 398,626,978 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 338 | java | package koschei.models;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Ocean1 {
@Autowired
private Island2 island;
@Override
public String toString() {
return "на океане остров " + island.toString();
}
} | [
"edilov_st@mail.ru"
] | edilov_st@mail.ru |
619268fd71537d8c29713819f51cef65bfee5771 | e7f900cc49765c06b661db0f2ff3d1b0815f47dd | /microservices/microservice-player/src/main/java/com/eldermoraes/microservice/player/service/ApplicationConfig.java | 951f24492dd9bd46c45844189ef1a97cca340064 | [
"Apache-2.0"
] | permissive | eldermoraes/javaee8oracledevs | 42c7f9fcf0a8f3b4e13ff091b9e95b4bfb10637e | 12371fae68caf665ba0a4553c141cc1f00036ce1 | refs/heads/master | 2021-04-06T05:58:24.418557 | 2018-09-21T14:36:58 | 2018-09-21T14:36:58 | 125,381,655 | 7 | 8 | null | null | null | null | UTF-8 | Java | false | false | 848 | java | /*
* Copyright 2018 eldermoraes.
*
* 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.eldermoraes.microservice.player.service;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
/**
*
* @author eldermoraes
*/
@ApplicationPath("resources")
public class ApplicationConfig extends Application{
}
| [
"elder.moraes@gmail.com"
] | elder.moraes@gmail.com |
cc318e4978a94355793ae64303c31e41e8f80694 | 0e475e81a0bdc6ddb3c0b56fa7984c805f79478b | /app/src/main/java/com/example/phoneauth/MySingleton.java | 7f618c193e6900381be72aa494248f1e5dae5b25 | [] | no_license | Haider029/HiFriendApp | b2ce66ef8b4c444f3dc2c30addc2f3d3aed28a20 | 5d3c57dd2c2dd649fe9902ebac574d3207f1c8a8 | refs/heads/master | 2020-12-07T00:10:06.886069 | 2020-01-08T15:07:37 | 2020-01-08T15:07:37 | 232,590,077 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,083 | java | package com.example.phoneauth;
import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class MySingleton {
private static MySingleton instance;
private RequestQueue requestQueue;
private Context ctx;
private MySingleton(Context context) {
ctx = context;
requestQueue = getRequestQueue();
}
public static synchronized MySingleton getInstance(Context context) {
if (instance == null) {
instance = new MySingleton(context);
}
return instance;
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
// getApplicationContext() is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
requestQueue = Volley.newRequestQueue(ctx.getApplicationContext());
}
return requestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
}
| [
"haider.ali.adeel@gmail.com"
] | haider.ali.adeel@gmail.com |
3e6d2d6b1f24f2a3d450efe48dde96c398b0202f | e9adc2f72d647807eb6900b945b0ddeb5bdda2a7 | /src/main/java/com/jsyn/unitgen/PitchToFrequency.java | 9086749bb64ff75bdb7e95cf601e8d164f0dace8 | [
"Apache-2.0"
] | permissive | philburk/jsyn | 720ae13cf80afee666edc8d4e01679ee9f05f884 | 06f9a9a4d6aa4ddabde81f77878826a62e5d79ab | refs/heads/master | 2023-08-31T05:11:59.337101 | 2023-08-28T20:26:04 | 2023-08-28T20:26:04 | 28,650,412 | 226 | 76 | Apache-2.0 | 2023-08-28T20:26:06 | 2014-12-31T00:33:56 | Java | UTF-8 | Java | false | false | 602 | java | package com.jsyn.unitgen;
import com.softsynth.math.AudioMath;
public class PitchToFrequency extends PowerOfTwo {
public PitchToFrequency() {
input.setup(0.0, 60.0, 127.0);
}
/**
* Convert from MIDI pitch to an octave offset from Concert A.
*/
@Override
public double adjustInput(double in) {
return (in - AudioMath.CONCERT_A_PITCH) * (1.0/12.0);
}
/**
* Convert scaler to a frequency relative to Concert A.
*/
@Override
public double adjustOutput(double out) {
return out * AudioMath.getConcertAFrequency();
}
}
| [
"philburk@mobileer.com"
] | philburk@mobileer.com |
dbf4a7e17829a72f07beed014122b043a56e9cae | 8b1692d9daf2d2339d2c63444ca8ebb12bbeb62f | /src/main/java/com/ncl/sindhu/repository/PersistenceAuditEventRepository.java | b7aaee927457e263b929a9c408ccb3b9c5ffd2d4 | [] | no_license | shyamailene/nclsindhu | 11fbb2233c6803c671a517b57a08c14154cc0683 | 782446b603151ebe9aa0332a042d6957adc22fa2 | refs/heads/master | 2021-09-03T08:29:20.771868 | 2018-01-07T14:34:54 | 2018-01-07T14:34:54 | 114,122,561 | 0 | 0 | null | 2018-01-07T14:44:10 | 2017-12-13T13:12:50 | Java | UTF-8 | Java | false | false | 968 | java | package com.ncl.sindhu.repository;
import com.ncl.sindhu.domain.PersistentAuditEvent;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import java.time.Instant;
import java.util.List;
/**
* Spring Data JPA repository for the PersistentAuditEvent entity.
*/
public interface PersistenceAuditEventRepository extends JpaRepository<PersistentAuditEvent, Long> {
List<PersistentAuditEvent> findByPrincipal(String principal);
List<PersistentAuditEvent> findByAuditEventDateAfter(Instant after);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfter(String principal, Instant after);
List<PersistentAuditEvent> findByPrincipalAndAuditEventDateAfterAndAuditEventType(String principle, Instant after, String type);
Page<PersistentAuditEvent> findAllByAuditEventDateBetween(Instant fromDate, Instant toDate, Pageable pageable);
}
| [
"shyam.ailene@hpe.com"
] | shyam.ailene@hpe.com |
2d4dda003ce31104a8737c556053d6f0bee37030 | 1f307ae64e45c00d1849aee23fa99e9bcb74005b | /core/src/main/java/org/newdawn/test/core/Triangle.java | 7dd2051cfd418a4db8b82af5ef05d07eafb6b433 | [] | no_license | Endolf/LibGDX-Test | b4de2745f097477cd3a20bdfc7c66a106556bf25 | 365c5b77ba729a9a16afa739b1ddaa74a4350fd8 | refs/heads/master | 2020-06-03T18:11:09.208482 | 2013-07-03T09:31:47 | 2013-07-03T09:31:47 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 481 | java | package org.newdawn.test.core;
public class Triangle extends Shape {
public Triangle(boolean isBillboard) {
super();
setVertices(new float[] {0.0f, 0.622008459f, 0.0f,
-0.5f, -0.311004243f, 0.0f,
0.5f, -0.311004243f, 0.0f });
setIndecies(new short[] { 0, 1, 2 });
setTwoSided(true);
setDiffuseColour(new float[]{0,1,0,1});
setBillboard(isBillboard);
setNormals(new float[] {0,0,1,
0,0,1,
0,0,1});
initialise();
}
}
| [
"endolf@computerbooth.com"
] | endolf@computerbooth.com |
1631b39a95149a2a2338f7b10a3e93cab79e3a83 | 45f67ab178e4640ac3eb0d005377f704e5c3bde6 | /src/main/java/A_SeleniumAssignment/FooterLink.java | 3d092bdeedbc7c4d578e2930f544a9c0c38e7f41 | [] | no_license | Jackdhokiya/Selenium-Session | 15fedef04a263b188fbce90331228f97b58245ad | 6e85535c29fb5c5221b7e2556c69a8c30814a7a7 | refs/heads/master | 2022-12-08T12:48:13.950586 | 2020-09-03T00:37:18 | 2020-09-03T00:37:18 | 292,425,967 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 842 | java | package A_SeleniumAssignment;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import io.github.bonigarcia.wdm.WebDriverManager;
public class FooterLink {
static WebDriver driver;
public static void main(String[] args) {
WebDriverManager.chromedriver().setup();
driver = new ChromeDriver();
driver.get("https://www.freshworks.com/");
List<WebElement> Linklist = driver.findElements(By.xpath("//ul[@class='footer-nav']/li/a"));
System.out.println("Total Links are: " + Linklist.size());
for (int i=0; i<Linklist.size(); i++) {
String text = Linklist.get(i).getText();
if(! text.isEmpty()) {
System.out.println(i + "-->"+ text);
}
}
driver.quit();
}
}
| [
"jackdhokiya@gmail.com"
] | jackdhokiya@gmail.com |
b45ff24a3fbe0487d6cc50026a235c11ee5fa24b | b4fe2062116c8130278a28374c526b6eedb9cc96 | /src/POO2/Humano.java | 7caaf00d8f755864df83ad9ef6937ddc340524a6 | [] | no_license | ArielDIazMartinez/POO3-Tarea-java | e0bcc3c7650704520cef9a2a04144312f4825ede | 4c2c4c38fd03f1f1ae7a44eceecc86857aa17185 | refs/heads/master | 2023-01-09T01:25:15.101790 | 2020-11-08T03:06:18 | 2020-11-08T03:06:18 | 297,686,633 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 770 | java | package POO2;
public abstract class Humano {
private String nombre;
private String apellido;
private int edad;
public Humano(String nombre, String apellido, int edad) {
this.nombre = nombre;
this.apellido = apellido;
this.edad = edad;
}
public String getNombre() {
return nombre;
}
public String getApellido() {
return apellido;
}
public int getEdad() {
return edad;
}
public abstract String getGenero();
public abstract void ejecutarAccion();
public abstract boolean esAdulto();
@Override
public String toString() {
return " nombre = " + nombre + " apellido = " + apellido + " edad = " + edad;
}
}
| [
"20199079@itla.edu.do"
] | 20199079@itla.edu.do |
9b257f053bd527422eb6b3a83b9d84c5f1945056 | 5cb0c96cc6613b99c8849ef07c3a2340f3fe21a2 | /fizzBuzz/20121116-carl_and_david/src/test/java/com/fizzbuzz/FizzBuzzPrinterShould.java | 655196fae5f406fd96c4e358189c39a1c5b428d7 | [] | no_license | novoda/dojos | 2e5a671025924df5674f55e9e8d89db51abf0dcf | 2e7391623b42617af1bbdad227e3e4701e89af2c | refs/heads/master | 2020-04-12T02:27:04.819306 | 2019-04-10T19:55:32 | 2019-04-10T19:55:32 | 6,509,909 | 68 | 20 | null | 2019-03-28T15:27:16 | 2012-11-02T17:34:28 | Java | UTF-8 | Java | false | false | 62 | java | package com.fizzbuzz;
public class FizzBuzzPrinterShould {
}
| [
"malmstein@gmail.com"
] | malmstein@gmail.com |
415f89857b4e9c2ff2d8b7a3422d07bc4522ac46 | f274b5f7a88fc18115c0d5b6e6dbca9590077c41 | /app/src/main/java/com/ics/admin/BasicAdmin/StudentDetails/StudentAssinviewActivity.java | 5dc7f1665851ced1c4befbd1ff3c08df20252364 | [] | no_license | NothingbutPro/adminkota20dec2019 | cff4ba12c02419c82a2a0ce770e2cac32f2ac881 | d85018f968b332a1eb260442eaccc0b4b3fe811c | refs/heads/master | 2020-11-27T02:18:56.854920 | 2020-02-01T07:50:05 | 2020-02-01T07:50:05 | 229,270,592 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 6,419 | java | package com.ics.admin.BasicAdmin.StudentDetails;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Dialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import com.ics.admin.Adapter.AdminAdapters.StudentAdapter;
import com.ics.admin.Model.Students;
import com.ics.admin.R;
import com.ics.admin.ShareRefrance.Shared_Preference;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class StudentAssinviewActivity extends AppCompatActivity {
ArrayList<Students> studentsList = new ArrayList<>();
StudentAdapter studentAdapter;
RecyclerView stuview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_assinview);
//Recycler++++++++++++
stuview = findViewById(R.id.stuview);
//++++++++++++
new GellAllStudebnts(new Shared_Preference().getId(this)).execute();
}
private class GellAllStudebnts extends AsyncTask<String, Void, String> {
String userid;
// String Faculty_id;
private Dialog dialog;
String name; String email; String password; String mobile; String address;
public GellAllStudebnts(String id) {
this.userid = id;
}
@Override
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://ihisaab.in/school_lms/api/get_assignstudents");
JSONObject postDataParams = new JSONObject();
// postDataParams.put("otp", Mobile_Number);
// postDataParams.put("user_id", userid);
Log.e("postDataParams", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /*milliseconds*/);
conn.setConnectTimeout(15000 /*milliseconds*/);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
StringBuffer Ss = sb.append(line);
Log.e("Ss", Ss.toString());
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
// dialog.dismiss();
JSONObject jsonObject1 = null;
Log.e("PostRegistration", result.toString());
try {
jsonObject1 = new JSONObject(result);
if(jsonObject1.getBoolean("responce")){
JSONArray jsonArray = jsonObject1.getJSONArray("data");
for(int i=0;i<jsonArray.length();i++) {
JSONObject jsonObject11 = jsonArray.getJSONObject(i);
String id = jsonObject11.getString("id");
String name = jsonObject11.getString("name");
String mobile = jsonObject11.getString("mobile");
String email = jsonObject11.getString("email");
String address = jsonObject11.getString("address");
// String Batch = jsonObject11.getString("Batch");
studentsList.add(new Students(id, name, mobile, email, password,address,"","Not Assigned", "feedone"));
}
}else {
}
studentAdapter = new StudentAdapter(StudentAssinviewActivity.this,studentsList);
LinearLayoutManager layoutManager = new LinearLayoutManager(StudentAssinviewActivity.this );
layoutManager.setOrientation(RecyclerView.VERTICAL);
stuview.setLayoutManager(layoutManager);
stuview.setAdapter(studentAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
}
| [
"paragsharma611@gmail.com"
] | paragsharma611@gmail.com |
27aec22050c6768d69675646b80e25109fb5ee6d | 5d9ad77fc9bc68855a235141506992b65e43c41a | /src/test/java/com/twilio/rest/ipmessaging/v2/service/RoleTest.java | 737a3a987d100c4e4a72bbf9628162510ba585c8 | [
"MIT"
] | permissive | BotMill/twilio-java | 03aebc489a0f164b4622bfd74c8ab717be588bf9 | 04b5b18e49bc75df32617dec7d46e22173b242f1 | refs/heads/master | 2021-01-02T09:35:37.224718 | 2017-07-27T19:49:33 | 2017-07-27T19:49:33 | 99,255,446 | 1 | 0 | null | 2017-08-03T16:52:02 | 2017-08-03T16:52:01 | null | UTF-8 | Java | false | false | 10,799 | java | /**
* This code was generated by
* \ / _ _ _| _ _
* | (_)\/(_)(_|\/| |(/_ v1.0.0
* / /
*/
package com.twilio.rest.ipmessaging.v2.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.twilio.Twilio;
import com.twilio.converter.DateConverter;
import com.twilio.converter.Promoter;
import com.twilio.exception.TwilioException;
import com.twilio.http.HttpMethod;
import com.twilio.http.Request;
import com.twilio.http.Response;
import com.twilio.http.TwilioRestClient;
import com.twilio.rest.Domains;
import mockit.Mocked;
import mockit.NonStrictExpectations;
import org.junit.Before;
import org.junit.Test;
import java.net.URI;
import static com.twilio.TwilioTest.serialize;
import static org.junit.Assert.*;
public class RoleTest {
@Mocked
private TwilioRestClient twilioRestClient;
@Before
public void setUp() throws Exception {
Twilio.init("AC123", "AUTH TOKEN");
}
@Test
public void testFetchRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.GET,
Domains.IPMESSAGING.toString(),
"/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Role.fetcher("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testFetchResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
assertNotNull(Role.fetcher("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").fetch());
}
@Test
public void testDeleteRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.DELETE,
Domains.IPMESSAGING.toString(),
"/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Role.deleter("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testDeleteResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("null", TwilioRestClient.HTTP_STATUS_CODE_NO_CONTENT);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
Role.deleter("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").delete();
}
@Test
public void testCreateRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.POST,
Domains.IPMESSAGING.toString(),
"/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles");
request.addPostParam("FriendlyName", serialize("friendlyName"));
request.addPostParam("Type", serialize(Role.RoleType.CHANNEL));
request.addPostParam("Permission", serialize("permission"));
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Role.creator("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendlyName", Role.RoleType.CHANNEL, Promoter.listOfOne("permission")).create();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testCreateResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", TwilioRestClient.HTTP_STATUS_CODE_CREATED);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
Role.creator("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "friendlyName", Role.RoleType.CHANNEL, Promoter.listOfOne("permission")).create();
}
@Test
public void testReadRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.GET,
Domains.IPMESSAGING.toString(),
"/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles");
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Role.reader("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").read();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testReadFullResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"roles\"},\"roles\": [{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}]}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
assertNotNull(Role.reader("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").read());
}
@Test
public void testReadEmptyResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"meta\": {\"page\": 0,\"page_size\": 50,\"first_page_url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"previous_page_url\": null,\"url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles?PageSize=50&Page=0\",\"next_page_url\": null,\"key\": \"roles\"},\"roles\": []}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
assertNotNull(Role.reader("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa").read());
}
@Test
public void testUpdateRequest() {
new NonStrictExpectations() {{
Request request = new Request(HttpMethod.POST,
Domains.IPMESSAGING.toString(),
"/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
request.addPostParam("Permission", serialize("permission"));
twilioRestClient.request(request);
times = 1;
result = new Response("", 500);
twilioRestClient.getAccountSid();
result = "AC123";
}};
try {
Role.updater("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Promoter.listOfOne("permission")).update();
fail("Expected TwilioException to be thrown for 500");
} catch (TwilioException e) {}
}
@Test
public void testUpdateResponse() {
new NonStrictExpectations() {{
twilioRestClient.request((Request) any);
result = new Response("{\"sid\": \"RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"service_sid\": \"ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"friendly_name\": \"channel user\",\"type\": \"channel\",\"permissions\": [\"sendMessage\",\"leaveChannel\",\"editOwnMessage\",\"deleteOwnMessage\"],\"date_created\": \"2016-03-03T19:47:15Z\",\"date_updated\": \"2016-03-03T19:47:15Z\",\"url\": \"https://chat.twilio.com/v2/Services/ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Roles/RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"}", TwilioRestClient.HTTP_STATUS_CODE_OK);
twilioRestClient.getObjectMapper();
result = new ObjectMapper();
}};
Role.updater("ISaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "RLaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Promoter.listOfOne("permission")).update();
}
} | [
"niu@jingming.ca"
] | niu@jingming.ca |
a9cab57de4784eb10b09ef37fd8f7a4f824923e4 | 3a90bd264e1779e5f2303a9b85e3853141356497 | /src/main/java/ocp/collections/ArrayDequeueTest.java | a5ca8275a7dcfdf763f9d0d45313562f744de390 | [] | no_license | RosenPIvanov/certJ | eab566cc0f40175abad3916b7a6991b7185474ce | f929585a8d41b8464f7b4374b2036c3d9f73f35d | refs/heads/master | 2021-01-21T14:53:46.109401 | 2017-09-27T17:37:33 | 2017-09-27T17:37:33 | 95,355,925 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,287 | java | package ocp.collections;
import java.util.ArrayDeque;
import java.util.Deque;
public class ArrayDequeueTest {
public static void main(String args[]) {
ArrayDeque<String> greetings = new ArrayDeque<String>();
//Since we call push() rather than offer(), we are treating the ArrayDeque as a LIFO
greetings.push("hello");
greetings.push("hi");
greetings.push("ola");
System.out.println(greetings);
greetings.pop();
greetings.peek();
while (greetings.peek() != null)
System.out.println(greetings.pop());
fifo();
test2();
}
static void test2(){
System.out.println("test2");
Deque<Integer> d = new ArrayDeque<>();
d.add(1);
d.push(2);
d.pop();
d.offerFirst(3);
d.remove();
System.out.println(d);
}
static void fifo(){
System.out.println();
ArrayDeque<String> greetings = new ArrayDeque<String>();
greetings.offer("hello");
greetings.push("hi");
greetings.offer("ola");
System.out.println(greetings);
// greetings.poll();
greetings.pop();
while (greetings.peek() != null)
System.out.println(greetings.pop());
}
}
| [
"rosen.p.ivanov@gmail.com"
] | rosen.p.ivanov@gmail.com |
5714d7a38bf7007d2f01a5e5bea872e0cd3d3e9a | 5451fce788a2f31b52d0ab4a868968546e0d3400 | /M2. Taller en Clase Programacion/Ejercicio14.java | 26311002a76dd814bc24c06fe455eacb1537b78a | [
"MIT"
] | permissive | camila-barona/UCC_PROG_II-2020s2 | 7e51faae18a947aefe61dfebb8d8e56f6baf5fad | ebc4986eb5089a22f55d20b9e49ec2e7689f4661 | refs/heads/master | 2023-01-06T13:40:31.569054 | 2020-11-03T22:19:09 | 2020-11-03T22:19:09 | 299,807,364 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,368 | java | package co.edu.campusucc;
public class Ejercicio14 {
public static void main(String[] args) {
System.out.println(" ************************************** ");
System.out.println(" * Autor: Maria Camila Barona * ");
System.out.println(" * Fecha: 01/OCT 2020 * ");
System.out.println(" ************************************** ");
System.out.println(" * Taller M2 001 * ");
System.out.println(" * Tres Embarcaciones * ");
System.out.println(" * La pinta, la niña, y la santamaria * ");
System.out.println(" ************************************** ");
System.out.println();
System.out.println("La Niña, La Pinta, La Santamaría");
int totalmillas =0;
int medioviajeIda =600;
int medioviajeRegreso =600;
int ninaida = 8, ninavuelta =12;
int pintaIda = 9, pintavuelta =11;
int samtariaIda = 10, santamariavuelva= 8;
int contadorNina=0,contadorPinta=0,contadorSantamaria=0;
int temporalNina=0, temporalPinta=0, temporalSantamaria=0;
while(contadorNina <= 1200 || contadorPinta <= 1200 || contadorSantamaria <= 1200) {
if(contadorNina <= 1200 ) {
temporalNina = 8 + 12;
contadorNina = contadorNina + temporalNina;
temporalNina = 0;
if(contadorNina == 1200) {
System.out.println("Barco NIÑA es la primera en llegar");
}
}
if(contadorPinta <= 1200 ) {
temporalPinta = + 11;
contadorPinta = contadorPinta + temporalPinta;
temporalPinta = 0;
if(contadorPinta == 1200) {
System.out.println("Barco PINTA es la primera en llegar");
}
}
if(contadorSantamaria <= 1200 ) {
temporalSantamaria = 10 + 8;
contadorSantamaria = contadorSantamaria + temporalSantamaria;
temporalSantamaria = 0;
if(contadorSantamaria== 1200) {
System.out.println("Barco SANTAMARIA es la primera en llegar");
}
}
}
System.out.println("LLEGÓ A 1200");
}
}
**************************************
* Autor: Maria Camila Barona *
* Fecha: 01/OCT 2020 *
**************************************
* Taller M2 001 *
* Tres Embarcaciones *
* La pinta, la niña, y la santamaria *
**************************************
La Niña, La Pinta, La Santamaría
Barco NIÑA es la primera en llegar
LLEGÓ A 1200
| [
"camilabarona12@gmail.com"
] | camilabarona12@gmail.com |
3f53909d16f25001585ca9801c9b97c31e019776 | 125fbca5fc0e0a83f5db0dbc37a2558bddcdfd13 | /src/main/java/com/km/leetcode/MyQueue.java | ec991d1b7cd810acf87faa668aa11a5e3d27750c | [] | no_license | zhouyimian/leetcode | 64fc106bbbbacb1e531e14d682b5296194ab1bd4 | 9b041f713ab18c8f851ada3c1eb10bc145da8a2e | refs/heads/master | 2021-06-28T04:24:08.839203 | 2020-08-23T15:16:08 | 2020-08-23T15:16:08 | 159,493,481 | 2 | 0 | null | 2020-10-13T11:03:36 | 2018-11-28T11:46:05 | Java | UTF-8 | Java | false | false | 1,016 | java | package com.km.leetcode;
import java.util.*;
public class MyQueue {
/** Initialize your data structure here. */
Stack<Integer> s1=new Stack<>();
Stack<Integer> s2=new Stack<>();
public MyQueue() {
}
/** Push element x to the back of queue. */
public void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int pop() {
while(s1.size()!=1) {
s2.push(s1.pop());
}
int num=s1.pop();
while(!s2.isEmpty()) {
s1.push(s2.pop());
}
return num;
}
/** Get the front element. */
public int peek() {
while(s1.size()!=1) {
s2.push(s1.pop());
}
int num=s1.pop();
s1.push(num);
while(!s2.isEmpty()) {
s1.push(s2.pop());
}
return num;
}
/** Returns whether the queue is empty. */
public boolean empty() {
return s1.isEmpty();
}
}
| [
"313976009@qq.com"
] | 313976009@qq.com |
b06b6d65e72422d9c8980f0e7c360d8c98876c41 | bc6e096c0b665ca4e93dcae0446cb2a932deb58e | /src/main/java/io/bonitoo/flux/operator/restriction/Restrictions.java | 18e3750ae7f3be3916102431501e9a0e80bb8d51 | [
"MIT"
] | permissive | bonitoo-io/flux-java | 7a62df63bde67d92d833a6b61a5ad1899fbbe11c | 0b76139d2bb835769f12d5e0d33563cb7f657aab | refs/heads/master | 2020-03-24T22:55:55.893429 | 2019-01-14T13:29:19 | 2019-01-14T13:29:19 | 143,109,416 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,060 | java | /*
* The MIT License
* Copyright © 2018
*
* 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 io.bonitoo.flux.operator.restriction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nonnull;
/**
* @author Jakub Bednar (bednar@github) (28/06/2018 13:03)
*/
public abstract class Restrictions {
Restrictions() {
}
@Nonnull
public static Restrictions and(@Nonnull final Restrictions... restrictions) {
return new Logical("AND", restrictions);
}
@Nonnull
public static Restrictions or(@Nonnull final Restrictions... restrictions) {
return new Logical("OR", restrictions);
}
/**
* Create Record measurement restriction.
*
* @return restriction
*/
@Nonnull
public static ColumnRestriction measurement() {
return new ColumnRestriction("_measurement");
}
/**
* Create Record field restriction.
*
* @return restriction
*/
@Nonnull
public static ColumnRestriction field() {
return new ColumnRestriction("_field");
}
/**
* Create Record start restriction.
*
* @return restriction
*/
@Nonnull
public static ColumnRestriction start() {
return new ColumnRestriction("_start");
}
/**
* Create Record stop restriction.
*
* @return restriction
*/
@Nonnull
public static ColumnRestriction stop() {
return new ColumnRestriction("_stop");
}
/**
* Create Record time restriction.
*
* @return restriction
*/
@Nonnull
public static ColumnRestriction time() {
return new ColumnRestriction("_time");
}
/**
* Create Record value restriction.
*
* @return restriction
*/
@Nonnull
public static ColumnRestriction value() {
return new ColumnRestriction("_value");
}
/**
* Create Record tag restriction.
*
* @param tagName tag name
* @return restriction
*/
@Nonnull
public static ColumnRestriction tag(@Nonnull final String tagName) {
return column(tagName);
}
/**
* Create Record column restriction.
*
* @param columnName column name
* @return restriction
*/
@Nonnull
public static ColumnRestriction column(@Nonnull final String columnName) {
return new ColumnRestriction(columnName);
}
private static class Logical extends Restrictions {
private final String operator;
private final Restrictions[] restrictions;
Logical(@Nonnull final String operator, @Nonnull final Restrictions... restrictions) {
super();
this.operator = operator;
this.restrictions = restrictions;
}
@Override
public String toString() {
return Stream.of(restrictions)
.map(Object::toString)
.collect(Collectors.joining(" " + operator + " ", "(", ")"));
}
}
}
| [
"jakub.bednar@gmail.com"
] | jakub.bednar@gmail.com |
5f2f3d0ef077089a7c8b2e578ef3788370afee0e | 3c6f34b3e210fd521ce774e8ac0116554819400e | /src/main/java/com/selva/scopedemo/BookDao.java | df760ce1409377289110d024f61f46897a1ec617 | [] | no_license | cselvaraju/spring-demo-day03 | de312be113e9cbd768e5fdee6d3a2cda181ab9ed | 34435a62966e2cc8e4b27635ae029e5bf43b0121 | refs/heads/main | 2023-07-01T12:45:08.210201 | 2021-08-03T13:31:00 | 2021-08-03T13:31:00 | 392,247,955 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 439 | java | package com.selva.scopedemo;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;
@Component
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE,
proxyMode = ScopedProxyMode.TARGET_CLASS)
public class BookDao {
public BookDao() {
}
}
| [
"cselvaraju@gmail.com"
] | cselvaraju@gmail.com |
a2e5e704e28a72aa2346c193a00d42e1e7be8dc7 | d7a0973e05d9f84caa852fdd5f528790b7731313 | /brennus-asm/src/test/java/brennus/asm/ref/ReferenceClass.java | 1f221641c81234812dcf9175fc223b6ac300f8e4 | [
"Apache-2.0"
] | permissive | julienledem/brennus | 0a01ffc68d3e534d903bf8221b4208b8e3ee40ae | 0798fb565d95af19ddc5accd084e58c4e882dbd0 | refs/heads/master | 2023-09-05T14:26:21.493151 | 2017-12-27T20:06:13 | 2017-12-27T20:06:13 | 4,732,484 | 4 | 0 | Apache-2.0 | 2021-08-12T00:48:09 | 2012-06-20T22:57:14 | Java | UTF-8 | Java | false | false | 1,861 | java | package brennus.asm.ref;
import brennus.asm.BaseClass;
public class ReferenceClass extends BaseClass {
private String a;
private int b;
private long c;
private float d;
private double e;
private byte f;
private char g;
private boolean h;
private short i;
@Override
public Object get(int index) {
println("get");
println(index);
switch (index) {
case 0:
return a;
case 1:
return b;
case 2:
return c;
case 3:
return d;
case 4:
return e;
case 5:
return f;
case 6:
return g;
case 7:
return h;
case 8:
return i;
default:
throw error();
}
}
@Override
public void set(int index, Object o) {
println("set");
println(index);
switch (index) {
case 0:
a = (String) o;
break;
case 1:
b = (Integer) o;
break;
case 2:
c = (Long) o;
break;
case 3:
d = (Float) o;
break;
case 4:
e = (Double) o;
break;
case 5:
f = (Byte) o;
break;
case 6:
g = (Character) o;
break;
case 7:
h = (Boolean) o;
break;
case 8:
i = (Short) o;
break;
default:
throw error();
}
}
@Override
public boolean equals(Object o) {
if (o instanceof BaseClass) {
return equalOrBothNull(((BaseClass)o).get(0),a)
&& equalOrBothNull(((BaseClass)o).get(1),b)
&& equalOrBothNull(((BaseClass)o).get(2),c)
&& equalOrBothNull(((BaseClass)o).get(3),d)
&& equalOrBothNull(((BaseClass)o).get(4),e)
&& equalOrBothNull(((BaseClass)o).get(5),f)
&& equalOrBothNull(((BaseClass)o).get(6),g)
&& equalOrBothNull(((BaseClass)o).get(7),h)
&& equalOrBothNull(((BaseClass)o).get(8),i);
}
return false;
}
}
| [
"julien@twitter.com"
] | julien@twitter.com |
1b474fc346a27490ccfaf0a09761861dce7eeb2f | 7074abcc1221df9b2b0392880689989d2b29ab94 | /java/src/b4a/community/donmanfred/widget/bcSpinner.java | c63fa02acb7838f54cf450ebccc6cd00bcd421da | [] | no_license | yeskaysystems/bcMaterial | 609d214d9c64b8b9ae975fb35d636ab4b719ee29 | 4f53ae20b5180542b75f7ad3b29cf2f19e37033a | refs/heads/master | 2020-07-22T13:57:44.299195 | 2015-06-13T10:22:43 | 2015-06-13T10:22:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,200 | java | package b4a.community.donmanfred.widget;
import com.rey.material.widget.Spinner;
import com.rey.material.widget.Spinner.OnItemClickListener;
import com.rey.material.widget.Spinner.OnItemSelectedListener;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.BA.Events;
import anywheresoftware.b4a.BA.Hide;
import anywheresoftware.b4a.BA.Pixel;
import anywheresoftware.b4a.BA.ShortName;
import anywheresoftware.b4a.BALayout;
import anywheresoftware.b4a.keywords.Common.DesignerCustomView;
import anywheresoftware.b4a.objects.LabelWrapper;
import anywheresoftware.b4a.objects.PanelWrapper;
import anywheresoftware.b4a.objects.ViewWrapper;
@ShortName("bcSpinner")
//@Permissions(values={"android.permission.INTERNET", "android.permission.ACCESS_NETWORK_STATE"})
@Events(values={
"ondatechanged(oldDay As Int, oldMonth As Int, oldYear As Int, newDay As Int, newMonth As Int, newYear As Int)"
})
//@DependsOn(values={"android-viewbadger"})
@Hide
public class bcSpinner extends ViewWrapper<Spinner> implements DesignerCustomView {
private BA ba;
private String eventName;
/*
* Initialize the HTML-TextView
*/
@Override
public void Initialize(final BA ba, String EventName) {
_initialize(ba, null, EventName);
}
@Override
@Hide
public void _initialize(final BA ba, Object activityClass, String EventName) {
this.eventName = EventName.toLowerCase(BA.cul);
this.ba = ba;
this.setObject(new Spinner(ba.context));
this.getObject().setOnItemClickListener(new OnItemClickListener(){
@Override
public boolean onItemClick(Spinner parent, View view, int position, long id) {
// TODO Auto-generated method stub
return false;
}
});
this.getObject().setOnItemSelectedListener(new OnItemSelectedListener(){
@Override
public void onItemSelected(Spinner parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
});
//if (ba.subExists(eventName + "_ondatechanged")) {
// //ba.Log("lib:Raising.. "+eventName + "_ondatechanged()");
// ba.raiseEvent(ba.context, eventName+"_ondatechanged", oldDay, oldMonth, oldYear, newDay, newMonth, newYear);
//}else {
// //BA.Log("lib: NOTFOUND '"+eventName + "_ondatechanged");
//}
}
public View getSelectedView() {
return this.getObject().getSelectedView();
}
public void setSelection(int position) {
this.getObject().setSelection(position);
}
public int getSelectedItemPosition() {
return this.getObject().getSelectedItemPosition();
}
public void setBackgroundColor(int backgroundColor) {
this.getObject().setBackgroundColor(backgroundColor);
}
public void setPopupBackgroundDrawable(Drawable background) {
this.getObject().setPopupBackgroundDrawable(background);
}
public Drawable getPopupBackground() {
return this.getObject().getPopupBackground();
}
public void setDropDownVerticalOffset(int pixels) {
this.getObject().setDropDownVerticalOffset(pixels);
}
public int getDropDownVerticalOffset() {
return this.getObject().getDropDownVerticalOffset();
}
public void setDropDownHorizontalOffset(int pixels) {
this.getObject().setDropDownVerticalOffset(pixels);
}
public int getDropDownHorizontalOffset() {
return this.getObject().getDropDownHorizontalOffset();
}
public void setDropDownWidth(int pixels) {
this.getObject().setDropDownWidth(pixels);
}
public int getDropDownWidth() {
return this.getObject().getDropDownWidth();
}
public void setGravity(int gravity) {
this.getObject().setGravity(gravity);
}
//programmatically add view
public void AddToParent(ViewGroup Parent, @Pixel int left, @Pixel int top, @Pixel int width, @Pixel int height) {
//AttributeSet attrs;
//XmlPullParser parser = Resources.getXml(myResouce);
//AttributeSet myAttributes = Xml.asAttributeSet(parser);
//AttributeSet myAttributes = null;
//anywheresoftware.b4a.
//mSignaturePad = new SignaturePad(ba.context, myAttributes);
Parent.addView(this.getObject(), new BALayout.LayoutParams(left, top, width, height));
}
//this method cannot be hidden.
@Override
public void DesignerCreateView(PanelWrapper base, LabelWrapper lw, anywheresoftware.b4a.objects.collections.Map props) {
ViewGroup vg = (ViewGroup) base.getObject().getParent();
AddToParent(vg, base.getLeft(), base.getTop(), base.getWidth(), base.getHeight());
base.RemoveView();
//set text properties
}
@Override
public void setLeft(int left) {
BALayout.LayoutParams lp = (BALayout.LayoutParams)this.getObject().getLayoutParams();
lp.left = left;
this.getObject().getParent().requestLayout();
}
@Override
public int getLeft() {
BALayout.LayoutParams lp = (BALayout.LayoutParams)this.getObject().getLayoutParams();
return lp.left;
}
@Override
public void setTop(int top) {
BALayout.LayoutParams lp = (BALayout.LayoutParams)this.getObject().getLayoutParams();
lp.top = top;
this.getObject().getParent().requestLayout();
}
@Override
public int getTop() {
BALayout.LayoutParams lp = (BALayout.LayoutParams)this.getObject().getLayoutParams();
return lp.top;
}
}
| [
"msy@gmx.de"
] | msy@gmx.de |
5a3ea457e6ea34f82530295950299b97e0c5ae52 | c0920bd32c05ff07006382834fbeffbe29e6dde9 | /week6-102.GradeDistribution/src/Grade.java | be1c3517a44ac458c93696446e225c635a9835a1 | [] | no_license | hughwin/mooc-2013-OOProgrammingWithJava-PART1 | f3266804f4abc36311124ac490df677db60d7b44 | 54ff7a6c97506bed09e68280c5439127e5d2ff0c | refs/heads/master | 2020-05-04T16:18:15.467700 | 2019-06-03T11:33:10 | 2019-06-03T11:33:10 | 179,274,853 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,897 | java | /*
* 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.
*/
/**
*
* @author Hugh
*/
import java.util.ArrayList;
public class Grade {
private ArrayList<Integer> scores;
public Grade() {
this.scores = new ArrayList<Integer>();
}
public void addGrade(int score) {
scores.add(score);
}
public float printAcceptance() {
int i = 0;
for (int x : this.scores) {
if (x >= 30) {
i++;
}
}
return ((float) (i * 100.0 / this.scores.size()));
}
public void printScores() {
String zero = "";
String one = "";
String two = "";
String three = "";
String four = "";
String five = "";
for (int a : this.scores) {
if (a >= 0 && a < 30) {
zero = zero + "*";
}
if (a >= 30 && a < 35) {
one = one + "*";
}
if (a >= 35 && a < 40) {
two = two + "*";
}
if (a >= 40 && a < 45) {
three = three + "*";
}
if (a >= 45 && a < 50) {
four = four + "*";
}
if (a >= 50 && a <= 60) {
five = five + "*";
}
}
System.out.println("Grade distribution:");
System.out.println("5: " + five);
System.out.println("4: " + four);
System.out.println("3: " + three);
System.out.println("2: " + two);
System.out.println("1: " + one);
System.out.println("0: " + zero);
System.out.println("Acceptance percentage: " + this.printAcceptance() );
}
}
| [
"hugh.winchester@gmail.com"
] | hugh.winchester@gmail.com |
0f1306512909d1241dedaf3825ef073274c9947d | ea8013860ed0b905c64f449c8bce9e0c34a23f7b | /SystemUIGoogle/sources/androidx/core/app/NotificationCompatJellybean.java | 42274a41bffb29ac5f64b494ff2ff0bc9f668a25 | [] | no_license | TheScarastic/redfin_b5 | 5efe0dc0d40b09a1a102dfb98bcde09bac4956db | 6d85efe92477576c4901cce62e1202e31c30cbd2 | refs/heads/master | 2023-08-13T22:05:30.321241 | 2021-09-28T12:33:20 | 2021-09-28T12:33:20 | 411,210,644 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,991 | java | package androidx.core.app;
import android.app.Notification;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import androidx.core.app.NotificationCompat;
import androidx.core.graphics.drawable.IconCompat;
import java.lang.reflect.Field;
import java.util.List;
/* access modifiers changed from: package-private */
/* loaded from: classes.dex */
public class NotificationCompatJellybean {
private static Field sExtrasField;
private static boolean sExtrasFieldAccessFailed;
private static final Object sExtrasLock = new Object();
private static final Object sActionsLock = new Object();
public static SparseArray<Bundle> buildActionExtrasMap(List<Bundle> list) {
int size = list.size();
SparseArray<Bundle> sparseArray = null;
for (int i = 0; i < size; i++) {
Bundle bundle = list.get(i);
if (bundle != null) {
if (sparseArray == null) {
sparseArray = new SparseArray<>();
}
sparseArray.put(i, bundle);
}
}
return sparseArray;
}
public static Bundle getExtras(Notification notification) {
synchronized (sExtrasLock) {
if (sExtrasFieldAccessFailed) {
return null;
}
try {
if (sExtrasField == null) {
Field declaredField = Notification.class.getDeclaredField("extras");
if (!Bundle.class.isAssignableFrom(declaredField.getType())) {
Log.e("NotificationCompat", "Notification.extras field is not of type Bundle");
sExtrasFieldAccessFailed = true;
return null;
}
declaredField.setAccessible(true);
sExtrasField = declaredField;
}
Bundle bundle = (Bundle) sExtrasField.get(notification);
if (bundle == null) {
bundle = new Bundle();
sExtrasField.set(notification, bundle);
}
return bundle;
} catch (IllegalAccessException e) {
Log.e("NotificationCompat", "Unable to access notification extras", e);
sExtrasFieldAccessFailed = true;
return null;
} catch (NoSuchFieldException e2) {
Log.e("NotificationCompat", "Unable to access notification extras", e2);
sExtrasFieldAccessFailed = true;
return null;
}
}
}
public static Bundle writeActionAndGetExtras(Notification.Builder builder, NotificationCompat.Action action) {
IconCompat iconCompat = action.getIconCompat();
builder.addAction(iconCompat != null ? iconCompat.getResId() : 0, action.getTitle(), action.getActionIntent());
Bundle bundle = new Bundle(action.getExtras());
if (action.getRemoteInputs() != null) {
bundle.putParcelableArray("android.support.remoteInputs", toBundleArray(action.getRemoteInputs()));
}
if (action.getDataOnlyRemoteInputs() != null) {
bundle.putParcelableArray("android.support.dataRemoteInputs", toBundleArray(action.getDataOnlyRemoteInputs()));
}
bundle.putBoolean("android.support.allowGeneratedReplies", action.getAllowGeneratedReplies());
return bundle;
}
/* access modifiers changed from: package-private */
public static Bundle getBundleForAction(NotificationCompat.Action action) {
Bundle bundle;
Bundle bundle2 = new Bundle();
IconCompat iconCompat = action.getIconCompat();
bundle2.putInt("icon", iconCompat != null ? iconCompat.getResId() : 0);
bundle2.putCharSequence("title", action.getTitle());
bundle2.putParcelable("actionIntent", action.getActionIntent());
if (action.getExtras() != null) {
bundle = new Bundle(action.getExtras());
} else {
bundle = new Bundle();
}
bundle.putBoolean("android.support.allowGeneratedReplies", action.getAllowGeneratedReplies());
bundle2.putBundle("extras", bundle);
bundle2.putParcelableArray("remoteInputs", toBundleArray(action.getRemoteInputs()));
bundle2.putBoolean("showsUserInterface", action.getShowsUserInterface());
bundle2.putInt("semanticAction", action.getSemanticAction());
return bundle2;
}
private static Bundle toBundle(RemoteInput remoteInput) {
new Bundle();
throw null;
}
private static Bundle[] toBundleArray(RemoteInput[] remoteInputArr) {
if (remoteInputArr == null) {
return null;
}
Bundle[] bundleArr = new Bundle[remoteInputArr.length];
for (int i = 0; i < remoteInputArr.length; i++) {
bundleArr[i] = toBundle(remoteInputArr[i]);
}
return bundleArr;
}
}
| [
"warabhishek@gmail.com"
] | warabhishek@gmail.com |
56a527c85ea2db5abc0ce9ea0b3fed80e65ee9b2 | 8ae48cca7f1e09d4d77562c3f72f72d7f85e4df9 | /shop_parent/dw_web/src/main/java/cn/ktte/dw/realtime/service/impl/DashboardServiceImpl.java | cfc0afd47bd10605a80b31f2e7923fcce4c95a97 | [] | no_license | ktte/flink_etl | c97aa7f27be8429a44b07b2d8bfc8a50faa3fd60 | f46ca01a5eb697b559938954a2861a89630b3a93 | refs/heads/master | 2022-12-23T20:59:37.068908 | 2020-03-21T04:31:41 | 2020-03-21T04:31:41 | 248,895,478 | 1 | 0 | null | 2022-12-15T23:25:48 | 2020-03-21T02:54:30 | Scala | UTF-8 | Java | false | false | 19,407 | java | package cn.ktte.dw.realtime.service.impl;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
import cn.ktte.dw.realtime.beans.WeekBean;
import cn.ktte.dw.realtime.service.DashboardService;
import cn.ktte.utils.DateUtil;
import cn.ktte.utils.DruidHelper;
import cn.ktte.utils.RedisUtil;
/**
* 实时数仓指标业务类
* Created by: mengyao
* 2019年8月29日
*/
@SuppressWarnings("all")
@Service
public class DashboardServiceImpl implements DashboardService {
private Logger logger = LoggerFactory.getLogger(getClass());
RedisUtil client = RedisUtil.build("node2", 6379);
// 游客指标
private static final String QUOTA_VISITOR = "quota_visitor";
// 转化率指标
private static final String QUOTA_CONVERT = "quota_convert";
@Override
public List<Map<String, String>> dau() {
List<Map<String, String>> userChartDataes = new ArrayList<Map<String, String>>();
String visitorJsonStr = null;
try {
client = RedisUtil.build("node2", 6379);
//visitorJsonStr = client.get(QUOTA_VISITOR);
// 获取今日的PV、UV、IP
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
String currentDate = simpleDateFormat.format(new Date());
String pv = client.hGet("itcast_shop:pv", currentDate).toString();
Long uv = client.sCard("itcast_shop:guid:" + currentDate);
Long ip = client.sCard("itcast_shop:ip:" + currentDate);
visitorJsonStr = "{\"pv\": " + pv + ", \"uv\": " + uv + ", \"ip\": " + ip + "}";
} catch (Exception e) {
logger.info("==== Redis connection field! 访客{}指标数据获取失败 ====", QUOTA_VISITOR);
}
if (!StringUtils.isEmpty(visitorJsonStr)) {
if (visitorJsonStr.contains("uv")) {visitorJsonStr=visitorJsonStr.replace("uv", "UV");}
if (visitorJsonStr.contains("pv")) {visitorJsonStr=visitorJsonStr.replace("pv", "PV");}
if (visitorJsonStr.contains("ip")) {visitorJsonStr=visitorJsonStr.replace("ip", "总访客数");}
JSONObject visitorJson = JSONObject.parseObject(visitorJsonStr);
if (visitorJson instanceof Map) {
visitorJson.forEach((k,v) -> userChartDataes.add(new HashMap<String, String>(){{
put("name", k);
put("value", ((v instanceof Integer ? (int)v : 0))+"");
}}));
}
} else {
userChartDataes.add(new HashMap<String, String>(){{
put("name", "PV");
put("value", "0");
}});
userChartDataes.add(new HashMap<String, String>(){{
put("name", "UV");
put("value", "0");
}});
userChartDataes.add(new HashMap<String, String>(){{
put("name", "总访客数");
put("value", "0");
}});
}
return userChartDataes;
}
@Override
public List<Map<String, String>> convert() {
List<Map<String, String>> rateChartDataes = new ArrayList<Map<String, String>>();
String visitorJsonStr = null;
try {
client = RedisUtil.build("node2", 6379);
visitorJsonStr = client.get(QUOTA_CONVERT);
} catch (Exception e) {
logger.error("==== Redis connection field! 转化率{}指标数据获取失败 ====", QUOTA_CONVERT);
}
if (!StringUtils.isEmpty(visitorJsonStr)) {
// bn = browseNumber
// cn = cartNumber
// on = orderNumber
// pn = payNumber
if (visitorJsonStr.contains("bn")) {visitorJsonStr=visitorJsonStr.replace("bn", "浏览");}
if (visitorJsonStr.contains("cn")) {visitorJsonStr=visitorJsonStr.replace("cn", "加购物车");}
if (visitorJsonStr.contains("on")) {visitorJsonStr=visitorJsonStr.replace("on", "下单");}
if (visitorJsonStr.contains("pn")) {visitorJsonStr=visitorJsonStr.replace("pn", "付款");}
JSONObject visitorJson = JSONObject.parseObject(visitorJsonStr);
if (visitorJson instanceof Map) {
visitorJson.forEach((k,v) -> rateChartDataes.add(new HashMap<String, String>(){{
put("name", k);
put("value", ((v instanceof Integer ? (int)v : 0))+"");
}}));
}
} else {
rateChartDataes.add(new HashMap<String, String>(){{
put("name", "浏览");
put("value", "0");
}});
rateChartDataes.add(new HashMap<String, String>(){{
put("name", "加购物车");
put("value", "0");
}});
rateChartDataes.add(new HashMap<String, String>(){{
put("name", "下单");
put("value", "0");
}});
rateChartDataes.add(new HashMap<String, String>(){{
put("name", "付款");
put("value", "0");
}});
}
return rateChartDataes;
}
@Override
public Map<String, Object> weekSale() {
// 近6天,含今天,共7天
int twNum = 6;
// 本周近一周
LinkedList<WeekBean> twDay = new LinkedList<WeekBean>();
for (int i = twNum; i >= 0; i--) {
String day = DateUtil.latelyNday(i);
String week = DateUtil.dayForWeek(day);
twDay.add(new WeekBean(day, week, 0L, i));
}
// 上周
int lwNum = 7;
// 上周的近一周
LinkedList<WeekBean> lwDay = new LinkedList<WeekBean>();
for (int i = twNum; i >= 0; i--) {
String day = DateUtil.latelyNday(7, i);
String week = DateUtil.dayForWeek(day);
lwDay.add(new WeekBean(day, week, 0L, i));
}
// 按时间从过去到现在进行排序(本周)
twDay.stream().sorted((o1,o2) -> o2.getSort().compareTo(o1.getSort()));
// 按时间从过去到现在进行排序(上周)
lwDay.stream().sorted((o1,o2) -> o2.getSort().compareTo(o1.getSort()));
Map<String, Object> result = new HashMap<String, Object>();
// 上周 last week SQL
String lwSql = "SELECT SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) AS d,sum(\"totalMoney\") FROM \"dws_order\" where \"__time\" BETWEEN ((CURRENT_TIMESTAMP - INTERVAL '7' DAY) - INTERVAL '7' DAY) AND (CURRENT_TIMESTAMP - INTERVAL '7' DAY) GROUP BY SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) ORDER BY SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) ASC";
// 本周 this week SQL
String twSql = "SELECT SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) AS d,sum(\"totalMoney\") FROM \"dws_order\" where \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '6' DAY GROUP BY SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) ORDER BY SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) ASC";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
// 上周1-7天的时间
LinkedList<String> lwd = new LinkedList<String>();
// 上周1-7天的数据
LinkedList<Long> lw = new LinkedList<Long>();
// 本周1-7天的时间
LinkedList<String> twd = new LinkedList<String>();
// 本周1-7天的数据
LinkedList<Long> tw = new LinkedList<Long>();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(lwSql);
while (rs.next()) {
String day = rs.getString(1);
long val = rs.getLong(2);
for (int i=0; i<lwDay.size(); i++) {
WeekBean wb = lwDay.get(i);
lwd.add(wb.getWeek());
if(day.equals(wb.getDay())) {
lw.add(val);
} else {
lw.add(wb.getValue());
}
}
}
rs = st.executeQuery(twSql);
while (rs.next()) {
String day = rs.getString(1);
long val = rs.getLong(2);
for (int i=0; i<twDay.size(); i++) {
WeekBean wb = twDay.get(i);
twd.add(wb.getWeek());
if(day.equals(wb.getDay())) {
tw.add(val);
} else {
tw.add(wb.getValue());
}
}
}
result.put("lw", lw);
result.put("lwd", lwd);
result.put("tw", tw);
result.put("twd", twd);
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public long dayOrderNum() {
long result = 0;
String sql = "SELECT SUM(\"count\") FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' DAY";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result = rs.getLong(1);
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public long weekOrderNum() {
long result = 0;
String sql = "SELECT SUM(\"count\") FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '7' DAY";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result = rs.getLong(1);
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public long monthOrderNum() {
long result = 0;
String sql = "SELECT SUM(\"count\") FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '30' DAY";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result = rs.getLong(1);
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public Map<Integer, Long> areaOrderNum() {
Map<Integer, Long> result = new HashMap<Integer, Long>();
String sql = "SELECT areaId,SUM(\"count\") FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' DAY GROUP BY \"areaId\"";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result.put(rs.getInt(1), rs.getLong(2));
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public String monthSale() {
long sale = 0;
String sql = "SELECT SUM(\"totalMoney\") AS \"curMonthSales\" FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' MONTH";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
sale = rs.getLong(1);
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return amountFormat(sale);
}
@Override
public String daySale() {
long sale = 0;
String sql = "SELECT SUM(\"totalMoney\") AS \"curMonthSales\" FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' DAY";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
sale = rs.getLong(1);
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return amountFormat(sale);
}
@Override
public Map<String, Double> hourSale() {
Map<String, Double> result = new HashMap<String, Double>(){{
put("0", 0d);put("1", 0d);put("2", 0d);put("3", 0d);put("4", 0d);put("5", 0d);put("6", 0d);put("7", 0d);
put("8", 0d);put("9", 0d);put("10", 0d);put("11", 0d);put("12", 0d);put("13", 0d);put("14", 0d);put("15", 0d);
put("16", 0d);put("17", 0d);put("18", 0d);put("19", 0d);put("20", 0d);put("21", 0d);put("22", 0d);put("23", 0d);
}};
String sql = "SELECT EXTRACT(HOUR FROM \"__time\") AS \"curHour\",SUM(\"totalMoney\") AS \"curHourSales\" FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' HOUR GROUP BY EXTRACT(HOUR FROM \"__time\")";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result.put(rs.getInt(1)+"", rs.getDouble(2));
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public Map<Integer, Long> areaOrderState() {
Map<Integer, Long> result = new HashMap<Integer, Long>();
String sql = "SELECT areaId, SUM(\"count\") as odn FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' DAY GROUP BY \"areaId\" ORDER BY odn DESC limit 8";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result.put(rs.getInt(1), rs.getLong(2));
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public Map<String, Long> weekOrderFinish() {
// 近6天,含今天,共7天
int twNum = 6;
// 本周近一周
LinkedList<WeekBean> twDay = new LinkedList<WeekBean>();
for (int i = twNum; i >= 0; i--) {
String day = DateUtil.latelyNday(i);
String week = DateUtil.dayForWeek(day);
twDay.add(new WeekBean(day, week, 0L, i));
}
// 按时间从过去到现在进行排序(本周)
twDay.stream().sorted((o1,o2) -> o2.getSort().compareTo(o1.getSort()));
LinkedHashMap<String, Long> result = new LinkedHashMap<String, Long>();
String sql = "SELECT SUBSTR(CAST(\"__time\" AS VARCHAR),1,10) AS d,sum(\"count\") FROM \"dws_order\" where \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '7' DAY GROUP BY SUBSTR(CAST(\"__time\" AS VARCHAR),1,10)";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
String day = rs.getString(1);
long val = rs.getLong(2);
for (int i=0; i<twDay.size(); i++) {
WeekBean wb = twDay.get(i);
if(day.equals(wb.getDay())) {
result.put(wb.getWeek(), val);
} else {
result.put(wb.getWeek(), 0L);
}
}
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
@Override
public Map<Integer, Double> top4AreaSale() {
Map<Integer, Double> result = new HashMap<Integer, Double>();
String sql = "SELECT areaId, SUM(\"totalMoney\") as ta FROM \"dws_order\" WHERE \"__time\" >= CURRENT_TIMESTAMP - INTERVAL '1' DAY GROUP BY \"areaId\" ORDER BY ta DESC limit 4";
// 实例化Druid JDBC连接
DruidHelper helper = new DruidHelper();
Connection connection = null;
Statement st = null;
ResultSet rs = null;
try {
connection = helper.getConnection();
st = connection.createStatement();
rs = st.executeQuery(sql);
while (rs.next()) {
result.put(rs.getInt(1), rs.getDouble(2));
}
} catch (Exception e){
e.printStackTrace();
} finally {
helper.close(connection, st, rs);
}
return result;
}
/**
* 当amount的长度小于10,则进行补0
* @return
*/
public String amountFormat(Long amount) {
String zero = "0".intern();
String temp = null;
int length = 10;
String amountStr = amount.toString();
int amountLength = amountStr.length();
if(amountLength < length) {
int diff = length - amountLength;
for (int i=0; i<diff; i++) {
if (i==0) {
temp = zero;
} else {
temp = temp+zero;
}
}
amountStr = temp + amountStr;
}
return amountStr;
}
public static void main(String[] args) {
// DashboardServiceImpl service = new DashboardServiceImpl();
// System.out.println(service.amountFormat(1000L));
// // UV、PV、访客数
// List<Map<String, String>> dau = service.dau();
// // 转化率
// List<Map<String, String>> convert = service.convert();
// // 周销售环比分析
// Map<String, Object> weekSale = service.weekSale();
// // 日订单数
// long dayOrderNum = service.dayOrderNum();
// // 周订单数
// long weekOrderNum = service.weekOrderNum();
// // 月订单数
// long monthOrderNum = service.monthOrderNum();
// // 所有区域订单数
// Map<Integer, Long> areaOrderNum = service.areaOrderNum();
// // 月总销售额
// String monthSale = service.monthSale();
// // 日总销售额
// String daySale = service.daySale();
// // 今日24小时销售额
// Map<String, Double> hourSale = service.hourSale();
// // Top8区域订单的订单数
// Map<Integer, Long> areaOrderState = service.areaOrderState();
// // 本周一到本周日每天的订单数
// Map<String, Long> weekOrderFinish = service.weekOrderFinish();
// // Top4地区销售排行
// Map<Integer, Double> top4AreaSale = service.top4AreaSale();
//
// System.out.println("UV、PV、访客数:"+dau);
// System.out.println("转化率:"+convert);
// System.out.println("周销售环比分析:"+weekSale);
// System.out.println("日订单数:"+dayOrderNum);
// System.out.println("周订单数:"+weekOrderNum);
// System.out.println("月订单数:"+monthOrderNum);
// System.out.println("所有区域订单数:"+areaOrderNum);
// System.out.println("月总销售额:"+monthSale);
// System.out.println("日总销售额:"+daySale);
// System.out.println("今日24小时销售额:"+hourSale);
// System.out.println("Top8区域订单的订单数:"+areaOrderState);
// System.out.println("本周一到本周日每天的订单数:"+weekOrderFinish);
// System.out.println("Top4地区销售排行:"+top4AreaSale);
}
}
| [
"1015446795@qq.com"
] | 1015446795@qq.com |
59742b42bda9b18f66650e0c754a62a922a66850 | 75635c1205c77fa3f42eea3e44103fa233079581 | /app/src/main/java/com/subgraph/orchid/circuits/hs/HSDescriptorCookie.java | 9559c7982d95434e099e828514e3a61cb90877fc | [
"BSD-3-Clause"
] | permissive | mike-lambert/sakura-proxy | aa7c7c364aa7d5941aa6645e259a90668300b4c6 | bada4d2e8a774b6ad6ee5c4609a1e74eb24ad65e | refs/heads/develop | 2020-09-03T00:40:58.216560 | 2019-11-03T15:11:54 | 2019-11-03T15:11:54 | 219,341,959 | 2 | 0 | null | 2019-11-03T18:09:48 | 2019-11-03T17:54:54 | Java | UTF-8 | Java | false | false | 723 | java | package com.subgraph.orchid.circuits.hs;
public class HSDescriptorCookie {
public enum CookieType {COOKIE_BASIC, COOKIE_STEALTH}
;
private final CookieType type;
private final byte[] value;
public HSDescriptorCookie(CookieType type, byte[] value) {
this.type = type;
this.value = value;
}
public byte getAuthTypeByte() {
switch (type) {
case COOKIE_BASIC:
return 1;
case COOKIE_STEALTH:
return 2;
default:
throw new IllegalStateException();
}
}
public CookieType getType() {
return type;
}
public byte[] getValue() {
return value;
}
}
| [
"cyberspacelabs@gmail.com"
] | cyberspacelabs@gmail.com |
91a350684711c27a64ff2a45f06b190e1f64d595 | f6beea8ab88dad733809e354ef9a39291e9b7874 | /com/planet_ink/coffee_mud/Items/Weapons/Arquebus.java | ea292e8d9d419a342c095da37ba0cbc344b4444f | [
"Apache-2.0"
] | permissive | bonnedav/CoffeeMud | c290f4d5a96f760af91f44502495a3dce3eea415 | f629f3e2e10955e47db47e66d65ae2883e6f9072 | refs/heads/master | 2020-04-01T12:13:11.943769 | 2018-10-11T02:50:45 | 2018-10-11T02:50:45 | 153,196,768 | 0 | 0 | Apache-2.0 | 2018-10-15T23:58:53 | 2018-10-15T23:58:53 | null | UTF-8 | Java | false | false | 2,371 | java | package com.planet_ink.coffee_mud.Items.Weapons;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;
/*
Copyright 2001-2018 Bo Zimmerman
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.
*/
public class Arquebus extends StdWeapon
{
@Override
public String ID()
{
return "Arquebus";
}
public Arquebus()
{
super();
setName("an arquebus");
setDisplayText("an arquebus is on the ground.");
setDescription("It\\`s got a metal barrel and wooden stock.");
basePhyStats().setAbility(0);
basePhyStats().setLevel(0);
basePhyStats.setWeight(15);
basePhyStats().setAttackAdjustment(-1);
basePhyStats().setDamage(10);
setAmmunitionType("bullets");
setAmmoCapacity(1);
setAmmoRemaining(1);
minRange=0;
maxRange=5;
baseGoldValue=500;
recoverPhyStats();
wornLogicalAnd=true;
material=RawMaterial.RESOURCE_IRON;
properWornBitmap=Wearable.WORN_HELD|Wearable.WORN_WIELD;
weaponClassification=Weapon.CLASS_RANGED;
weaponDamageType=Weapon.TYPE_PIERCING;
}
// protected boolean isBackfire()
// {
//
// }
}
| [
"bo@zimmers.net"
] | bo@zimmers.net |
fab2598216a56c3128aa0fa9931e99e1ad53b545 | 696aa05ec959063d58807051902d8e2c48a989b9 | /ole-common/ole-utility/src/main/java/org/kuali/ole/docstore/model/xmlpojo/security/patron/oleml/AddressWithDates.java | 59f43eca3df727575c54cd6603cf34f0c9f98b70 | [] | no_license | sheiksalahudeen/ole-30-sprint-14-intermediate | 3e8bcd647241eeb741d7a15ff9aef72f8ad34b33 | 2aef659b37628bd577e37077f42684e0977e1d43 | refs/heads/master | 2023-01-09T00:59:02.123787 | 2017-01-26T06:09:02 | 2017-01-26T06:09:02 | 80,089,548 | 0 | 0 | null | 2023-01-02T22:05:38 | 2017-01-26T05:47:58 | PLSQL | UTF-8 | Java | false | false | 7,806 | java | ////
//// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
//// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
//// Any modifications to this file will be lost upon recompilation of the source schema.
//// Generated on: 2012.03.15 at 02:03:46 PM IST
////
//
//
//package org.kuali.ole.docstore.model.xmlpojo.security.patron.oleml;
//
//import com.thoughtworks.xstream.annotations.XStreamAlias;
//import com.thoughtworks.xstream.annotations.XStreamImplicit;
//
//import javax.xml.bind.annotation.*;
//import javax.xml.datatype.XMLGregorianCalendar;
//import java.util.ArrayList;
//import java.util.List;
//
//
///**
// * This is an address with the other attributes that make it useful.
// * Inactivated indicates that the library has forced the address to deactivate
// * manually, rather than because the dates are invalid. Some other validation will be
// * necessary for addresses. More than one address can be primary, as long as their date
// * ranges do not intersect.
// *
// * <p>Java class for addressWithDates complex type.
// *
// * <p>The following schema fragment specifies the expected content contained within this class.
// *
// * <pre>
// * <complexType name="addressWithDates">
// * <complexContent>
// * <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
// * <sequence>
// * <element name="type" type="{http://www.w3.org/2001/XMLSchema}string"/>
// * <choice maxOccurs="unbounded">
// * <element name="postalAddress" type="{http://ole.kuali.org/standards/ole-patron}postalAddress"/>
// * <element name="emailAddress" type="{http://ole.kuali.org/standards/ole-patron}emailAddress"/>
// * <element name="telephoneNumber" type="{http://ole.kuali.org/standards/ole-patron}telephoneNumber"/>
// * </choice>
// * <element name="activeDates" type="{http://ole.kuali.org/standards/ole-patron}beginEndDate" minOccurs="0"/>
// * <element name="inactivated" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
// * <element name="validated" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
// * </sequence>
// * <attribute name="primary" use="required" type="{http://www.w3.org/2001/XMLSchema}boolean" />
// * </restriction>
// * </complexContent>
// * </complexType>
// * </pre>
// *
// *
// * @author Rajesh Chowdary K
// * @created Mar 15, 2012
// */
//
//@XmlAccessorType(XmlAccessType.FIELD)
//@XmlType(name = "addressWithDates", propOrder = {
// "type",
// "postalAddressOrEmailAddressOrTelephoneNumber",
// "activeDates",
// "inactivated",
// "validated"
//})
//
//@XStreamAlias("addressWithDates")
//public class AddressWithDates {
//
// @XmlElement(required = true)
// protected String type;
//
// @XmlElements({
// @XmlElement(name = "telephoneNumber", type = TelephoneNumber.class),
// @XmlElement(name = "emailAddress", type = EmailAddress.class),
// @XmlElement(name = "postalAddress", type = PostalAddress.class)
// })
//
// @XStreamImplicit
// protected List<Object> postalAddressOrEmailAddressOrTelephoneNumber = new ArrayList<Object>();
//
// protected PostalAddress postalAddress;
//
// protected EmailAddress emailAddress;
//
// protected TelephoneNumber telephoneNumber;
//
// protected BeginEndDate activeDates;
//
// protected String inactivated;
//
// protected String validated;
// @XmlAttribute(required = true)
// protected boolean primary;
//
//
// public PostalAddress getPostalAddress() {
// return postalAddress;
// }
//
// public void setPostalAddress(PostalAddress postalAddress) {
// this.postalAddress = postalAddress;
// }
//
// public EmailAddress getEmailAddress() {
// return emailAddress;
// }
//
// public void setEmailAddress(EmailAddress emailAddress) {
// this.emailAddress = emailAddress;
// }
//
// public TelephoneNumber getTelephoneNumber() {
// return telephoneNumber;
// }
//
// public void setTelephoneNumber(TelephoneNumber telephoneNumber) {
// this.telephoneNumber = telephoneNumber;
// }
//
// /**
// * Gets the value of the type property.
// *
// * @return
// * possible object is
// * {@link String }
// *
// */
// public String getType() {
// return type;
// }
//
// /**
// * Sets the value of the type property.
// *
// * @param value
// * allowed object is
// * {@link String }
// *
// */
// public void setType(String value) {
// this.type = value;
// }
//
// /**
// * Gets the value of the postalAddressOrEmailAddressOrTelephoneNumber property.
// *
// * <p>
// * This accessor method returns a reference to the live list,
// * not a snapshot. Therefore any modification you make to the
// * returned list will be present inside the JAXB object.
// * This is why there is not a <CODE>set</CODE> method for the postalAddressOrEmailAddressOrTelephoneNumber property.
// *
// * <p>
// * For example, to add a new item, do as follows:
// * <pre>
// * getPostalAddressOrEmailAddressOrTelephoneNumber().add(newItem);
// * </pre>
// *
// *
// * <p>
// * Objects of the following type(s) are allowed in the list
// * {@link TelephoneNumber }
// * {@link EmailAddress }
// * {@link PostalAddress }
// *
// *
// */
//
// public List<Object> getPostalAddressOrEmailAddressOrTelephoneNumber() {
// return this.postalAddressOrEmailAddressOrTelephoneNumber;
// }
//
// /**
// * Gets the value of the activeDates property.
// *
// * @return
// * possible object is
// * {@link BeginEndDate }
// *
// */
// public BeginEndDate getActiveDates() {
// return activeDates;
// }
//
// /**
// * Sets the value of the activeDates property.
// *
// * @param value
// * allowed object is
// * {@link BeginEndDate }
// *
// */
// public void setActiveDates(BeginEndDate value) {
// this.activeDates = value;
// }
//
// /**
// * Gets the value of the inactivated property.
// *
// * @return
// * possible object is
// * {@link XMLGregorianCalendar }
// *
// */
// public String getInactivated() {
// return inactivated;
// }
//
// /**
// * Sets the value of the inactivated property.
// *
// * @param value
// * allowed object is
// * {@link XMLGregorianCalendar }
// *
// */
// public void setInactivated(String value) {
// this.inactivated = value;
// }
//
// /**
// * Gets the value of the validated property.
// *
// * @return
// * possible object is
// * {@link XMLGregorianCalendar }
// *
// */
// public String getValidated() {
// return validated;
// }
//
// /**
// * Sets the value of the validated property.
// *
// * @param value
// * allowed object is
// * {@link XMLGregorianCalendar }
// *
// */
// public void setValidated(String value) {
// this.validated = value;
// }
//
// /**
// * Gets the value of the primary property.
// *
// */
// public boolean isPrimary() {
// return primary;
// }
//
// /**
// * Sets the value of the primary property.
// *
// */
// public void setPrimary(boolean value) {
// this.primary = value;
// }
//
//}
| [
"sheiksalahudeen.m@kuali.org"
] | sheiksalahudeen.m@kuali.org |
689aa95da7ae573ee0d2b762f7e685d02ec3f45f | 0999801c2fb5d36505f68a0b72256bc056a6acb0 | /src/com/chrisleung/leetcode/solutions/Problem_048_Rotate_Image.java | 9340f1aff2ba13d0543d9efd8cdc0a9b35fc2ae9 | [] | no_license | nagen010/CodingProblems | c5273675080dd0450975db961d78c30338d6dac8 | ecc1e4e1e01302fb9813e0b0c15531961e905e6a | refs/heads/master | 2020-03-28T13:43:51.695065 | 2018-09-07T05:20:43 | 2018-09-07T05:20:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 608 | java | package com.chrisleung.leetcode.solutions;
public class Problem_048_Rotate_Image {
public void rotate(int[][] matrix) {
if(matrix == null || matrix.length == 0) return;
int n = matrix.length;
for(int layer=0; layer<n/2; layer++) {
for(int x=layer; x<n-layer-1; x++) {
int tmp = matrix[layer][x];
matrix[layer][x]=matrix[n-1-x][layer];
matrix[n-1-x][layer]=matrix[n-1-layer][n-1-x];
matrix[n-1-layer][n-1-x]=matrix[x][n-1-layer];
matrix[x][n-1-layer]=tmp;
}
}
}
}
| [
"me@chrisleung.com"
] | me@chrisleung.com |
7bdfdd02f1f625ec8fb45c7d95bb44540bb27364 | f7fbc015359f7e2a7bae421918636b608ea4cef6 | /base/branches/j5proxy/src/org/hsqldb/lib/StringUtil.java | b585bd4db0aa6782488df3ce063b36d7704720fd | [] | no_license | svn2github/hsqldb | cdb363112cbdb9924c816811577586f0bf8aba90 | 52c703b4d54483899d834b1c23c1de7173558458 | refs/heads/master | 2023-09-03T10:33:34.963710 | 2019-01-18T23:07:40 | 2019-01-18T23:07:40 | 155,365,089 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 11,264 | java | /* Copyright (c) 2001-2007, The HSQL Development Group
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the HSQL Development Group nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hsqldb.lib;
import java.lang.reflect.Array;
/** Provides a collection of convenience methods for processing and
* creating objects with <code>String</code> value components.
*
* @author fredt@users
* @author boucherb@users
* @version 1.9.0
* @since 1.7.0
*/
public class StringUtil {
static final long[] precisionLimits = {
0, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
1000000000, 10000000000L
};
/**
* If necessary, adds zeros to the beginning of the value so that the
* given precision is matched, otherwise crops the initial digits. Returns
* only a substring of length maxSize after this if maxSize is smaller than
* precision.
*
*
*/
public static String toZeroPaddedString(long value, int precision,
int maxSize) {
StringBuffer buffer = new StringBuffer();
if (value < 0) {
value = -value;
buffer.append('-');
}
int i;
for (i = 0; i < precision; i++) {
if (value < precisionLimits[i]) {
break;
}
}
for (; i < precision; i++) {
buffer.append('0');
}
buffer.append(value);
if (maxSize < precision) {
buffer.setLength(maxSize);
}
return buffer.toString();
}
/**
* Returns a string with non alphanumeric chars converted to the
* substitute character. A digit first character is also converted.
* By sqlbob@users
* @param source string to convert
* @param substitute character to use
* @return converted string
*/
public static String toLowerSubset(String source, char substitute) {
int len = source.length();
StringBuffer src = new StringBuffer(len);
char ch;
for (int i = 0; i < len; i++) {
ch = source.charAt(i);
if (!Character.isLetterOrDigit(ch)) {
src.append(substitute);
} else if ((i == 0) && Character.isDigit(ch)) {
src.append(substitute);
} else {
src.append(Character.toLowerCase(ch));
}
}
return src.toString();
}
/**
* Builds a bracketed CSV list from the array
* @param array an array of Objects
* @return string
*/
public static String arrayToString(Object array) {
int len = Array.getLength(array);
int last = len - 1;
StringBuffer sb = new StringBuffer(2 * (len + 1));
sb.append('{');
for (int i = 0; i < len; i++) {
sb.append(Array.get(array, i));
if (i != last) {
sb.append(',');
}
}
sb.append('}');
return sb.toString();
}
/**
* Builds a CSV list from the specified String[], separator string and
* quote string. <p>
*
* <ul>
* <li>All arguments are assumed to be non-null.
* <li>Separates each list element with the value of the
* <code>separator</code> argument.
* <li>Prepends and appends each element with the value of the
* <code>quote</code> argument.
* <li> No attempt is made to escape the quote character sequence if it is
* found internal to a list element.
* <ul>
* @return a CSV list
* @param separator the <code>String</code> to use as the list element separator
* @param quote the <code>String</code> with which to quote the list elements
* @param s array of <code>String</code> objects
*/
public static String getList(String[] s, String separator, String quote) {
int len = s.length;
StringBuffer b = new StringBuffer(len * 16);
for (int i = 0; i < len; i++) {
b.append(quote);
b.append(s[i]);
b.append(quote);
if (i + 1 < len) {
b.append(separator);
}
}
return b.toString();
}
public static String getList(Object[] s, String separator, String quote) {
int len = s.length;
StringBuffer b = new StringBuffer(len * 16);
for (int i = 0; i < len; i++) {
b.append(quote);
b.append(s[i]);
b.append(quote);
if (i + 1 < len) {
b.append(separator);
}
}
return b.toString();
}
/**
* Builds a CSV list from the specified int[], <code>separator</code>
* <code>String</code> and <code>quote</code> <code>String</code>. <p>
*
* <ul>
* <li>All arguments are assumed to be non-null.
* <li>Separates each list element with the value of the
* <code>separator</code> argument.
* <li>Prepends and appends each element with the value of the
* <code>quote</code> argument.
* <ul>
* @return a CSV list
* @param s the array of int values
* @param separator the <code>String</code> to use as the separator
* @param quote the <code>String</code> with which to quote the list elements
*/
public static String getList(int[] s, String separator, String quote) {
int len = s.length;
StringBuffer b = new StringBuffer(len * 8);
for (int i = 0; i < len; i++) {
b.append(quote);
b.append(s[i]);
b.append(quote);
if (i + 1 < len) {
b.append(separator);
}
}
return b.toString();
}
/**
* Builds a CSV list from the specified String[][], separator string and
* quote string. <p>
*
* <ul>
* <li>All arguments are assumed to be non-null.
* <li>Uses only the first element in each subarray.
* <li>Separates each list element with the value of the
* <code>separator</code> argument.
* <li>Prepends and appends each element with the value of the
* <code>quote</code> argument.
* <li> No attempt is made to escape the quote character sequence if it is
* found internal to a list element.
* <ul>
* @return a CSV list
* @param separator the <code>String</code> to use as the list element separator
* @param quote the <code>String</code> with which to quote the list elements
* @param s the array of <code>String</code> array objects
*/
public static String getList(String[][] s, String separator,
String quote) {
int len = s.length;
StringBuffer b = new StringBuffer(len * 16);
for (int i = 0; i < len; i++) {
b.append(quote);
b.append(s[i][0]);
b.append(quote);
if (i + 1 < len) {
b.append(separator);
}
}
return b.toString();
}
/**
* Appends a pair of string to the string buffer, using the separator between
* and terminator at the end
* @param b the buffer
* @param s1 first string
* @param s2 second string
* @param separator separator string
* @param terminator terminator string
*/
public static void appendPair(StringBuffer b, String s1, String s2,
String separator, String terminator) {
b.append(s1);
b.append(separator);
b.append(s2);
b.append(terminator);
}
/**
* Checks if text is empty (characters <= space)
* @author: Nitin Chauhan
* @return boolean true if text is null or empty, false otherwise
* @param s java.lang.String
*/
public static boolean isEmpty(String s) {
int i = s == null ? 0
: s.length();
while (i > 0) {
if (s.charAt(--i) > ' ') {
return false;
}
}
return true;
}
/**
* Returns the size of substring that does not contain any trailing spaces
* @param s the string
* @return trimmed size
*/
public static int rTrimSize(String s) {
int i = s.length();
while (i > 0) {
i--;
if (s.charAt(i) != ' ') {
return i + 1;
}
}
return 0;
}
/**
* Skips any spaces at or after start and returns the index of first
* non-space character;
* @param s the string
* @param start index to start
* @return index of first non-space
*/
public static int skipSpaces(String s, int start) {
int limit = s.length();
int i = start;
for (; i < limit; i++) {
if (s.charAt(i) != ' ') {
break;
}
}
return i;
}
/**
* Splits the string into an array, using the separator. If separator is
* not found in the string, the whole string is returned in the array.
*
* @param s the string
* @param separator the separator
* @return array of strings
*/
public static String[] split(String s, String separator) {
HsqlArrayList list = new HsqlArrayList();
int currindex = 0;
for (boolean more = true; more; ) {
int nextindex = s.indexOf(separator, currindex);
if (nextindex == -1) {
nextindex = s.length();
more = false;
}
list.add(s.substring(currindex, nextindex));
currindex = nextindex + separator.length();
}
return (String[]) list.toArray(new String[list.size()]);
}
}
| [
"unsaved@7c7dc5f5-a22d-0410-a3af-b41755a11667"
] | unsaved@7c7dc5f5-a22d-0410-a3af-b41755a11667 |
20cc36d58e3419d0e77e00f52eb1aa1a4609e45d | ecbc8c7c998f6d8ffee906b922c084c450338ffe | /Critters/Shark.java | d3216ac61b11714b051da5426deefc7ff7b60fd0 | [] | no_license | salmawardha/Pemrograman-1 | db66e5069315ac6d83a47d3bcf2cae48d58542fc | 3537e1fffa076549f9df6348a6e71dbbc657b8dc | refs/heads/master | 2023-07-03T17:31:04.630506 | 2021-08-05T06:21:32 | 2021-08-05T06:21:32 | 392,925,763 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 575 | java | public class Shark extends Critter {
private int count;
private int max;
private Direction direction;
public Shark() {
count = 0;
max = 1;
direction = Direction.NORTH;
}
public Direction getMove() {
count++;
if (count > max) {
count = 1;
max++;
if (direction == Direction.NORTH) {
direction = Direction.SOUTH;
} else {
direction = Direction.NORTH;
}
}
return direction;
}
} | [
"salmawardha@gmail.com"
] | salmawardha@gmail.com |
6ddab439944d345efa7a1dbc26109ee6227f2bb6 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /cts/tools/dasm/src/java_cup/production_part.java | cdb92f7bd78c02c7ef4b09bb36e7befbec3f15cb | [
"MIT"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | Java | false | false | 2,678 | java | package java_cup;
/** This class represents one part (either a symbol or an action) of a
* production. In this base class it contains only an optional label
* string that the user can use to refer to the part within actions.<p>
*
* This is an abstract class.
*
* @see java_cup.production
* @version last updated: 11/25/95
* @author Scott Hudson
*/
public abstract class production_part {
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Simple constructor. */
public production_part(String lab)
{
_label = lab;
}
/*-----------------------------------------------------------*/
/*--- (Access to) Instance Variables ------------------------*/
/*-----------------------------------------------------------*/
/** Optional label for referring to the part within an action (null for
* no label).
*/
protected String _label;
/** Optional label for referring to the part within an action (null for
* no label).
*/
public String label() {return _label;}
/*-----------------------------------------------------------*/
/*--- General Methods ---------------------------------------*/
/*-----------------------------------------------------------*/
/** Indicate if this is an action (rather than a symbol). Here in the
* base class, we don't this know yet, so its an abstract method.
*/
public abstract boolean is_action();
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Equality comparison. */
public boolean equals(production_part other)
{
if (other == null) return false;
/* compare the labels */
if (label() != null)
return label().equals(other.label());
else
return other.label() == null;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Generic equality comparison. */
public boolean equals(Object other)
{
if (!(other instanceof production_part))
return false;
else
return equals((production_part)other);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Produce a hash code. */
public int hashCode()
{
return label()==null ? 0 : label().hashCode();
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Convert to a string. */
public String toString()
{
if (label() != null)
return label() + ":";
else
return " ";
}
/*-----------------------------------------------------------*/
};
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
322b609b5661839c362f22e2b47064dd802f0df2 | d2412377569e90c76d41fe7326584893cbdf30a4 | /AndroidStudioProject/phoneSafeManager/app/src/main/java/com/sam/safemanager/test/TestContactInfoService.java | 016cd972c0aef123c25214a591da396b0af76ed7 | [] | no_license | Easyhood/Gallery3 | 7a3edf697098ff41aa128b79330e129402681690 | 1042328e04d5e0f909bac40173be75fe893abf09 | refs/heads/master | 2021-01-19T00:25:51.792199 | 2016-11-21T12:04:43 | 2016-11-21T12:04:43 | 73,033,631 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 560 | java | package com.sam.safemanager.test;
import java.util.List;
import com.sam.safemanager.bean.ContactInfo;
import com.sam.safemanager.engine.ContactInfoService;
import android.test.AndroidTestCase;
public class TestContactInfoService extends AndroidTestCase {
public void testGetContacts() throws Exception{
ContactInfoService service = new ContactInfoService(getContext());
List<ContactInfo> infos = service.getContactInfos();
for(ContactInfo info : infos ){
System.out.println(info.getName());
System.out.println(info.getPhone());
}
}
}
| [
"357802051@qq.com"
] | 357802051@qq.com |
cb766cbf0c1f9a2d222617fd873e52476cc3b697 | e5277067d6c74dcd4c7b54120a3941376bc2d4bb | /socket/src/socket/C_ECO.java | 2969a8c5b7597d1fef4cf9aacd3bcd260b9e35df | [] | no_license | 0189971/Java | 2eaf06246c6b10fbc678a60e6be6c81ab7b452dc | 7a7615e45cf13d33f9a0f0584a118f8ede9f7f94 | refs/heads/master | 2020-04-23T18:35:32.240308 | 2018-07-20T12:59:02 | 2018-07-20T12:59:02 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,258 | java | package socket;
import java.net.*;
import java.io.*;
public class C_ECO{
public static void main(String[] args) {
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Escribe la direccion IP del servidor:");
String ip = br.readLine();
System.out.print("Ingresa el puerto:");
int pto = Integer.parseInt(br.readLine());
Socket cl = new Socket(ip,pto);
PrintWriter pw = new PrintWriter(new OutputStreamWriter(cl.getOutputStream()));
BufferedReader br1 = new BufferedReader(new InputStreamReader(cl.getInputStream()));
System.out.println("Conexion establecida... escribe texto para enviar <enter> para salir \"Adios\" o \"salir\" para terminar");
String datos = " ";
while(true){
datos=br.readLine();
System.out.println("Datos enviados: "+datos);
if(datos.indexOf("Adios")>=0 || datos.indexOf("salir")>=0){
System.out.println("Finaliza programa");
pw.println(datos);
pw.flush();
br.close(); //checar
br1.close();
pw.close();
System.exit(0);
}else{
pw.println(datos);
pw.flush();
String eco = br1.readLine();
System.out.println("ECO: "+ eco);
}
}
}catch (Exception e) {
e.printStackTrace();
}
}
} | [
"javisever2@gmail.com"
] | javisever2@gmail.com |
6cc37392b9bba9fd83bbd99b9dfa5c171456808d | 33f5388d8d2dba6637d4751100f49f878570b1b2 | /src/com/company/tweeter/CacheManager.java | 55f8d40a6eff1780700a7fe69c30e9b7dc8a51a7 | [] | no_license | andrecurvello/Tweeter | 8482ea72f8f309b53f18fab5e896c6c5a7fa1422 | f67b68683162f5d68b1a414292e7c7f741396f53 | refs/heads/master | 2021-01-16T21:34:57.529609 | 2012-06-22T17:42:36 | 2012-06-22T17:42:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 582 | java | package com.company.tweeter;
import java.util.Hashtable;
public class CacheManager {
private static CacheManager manager = null;
private Hashtable<String, String> imageList;
private CacheManager() {
imageList = new Hashtable<String, String>();
}
public static CacheManager getInstance() {
if(manager == null) {
manager = new CacheManager();
}
return manager;
}
public void setImageForKey(String imageKey, String filePath) {
imageList.put(imageKey, filePath);
}
public String getImageForKey(String imageKey) {
return imageList.get(imageKey);
}
}
| [
"vravindranath@gmail.com"
] | vravindranath@gmail.com |
3b467b47bd5d3c22d73fdcb9594654933d893e01 | 32f81656bfe66e80ca1161b5b432169fafb913c2 | /Software_Engineer_Project/Elearning-platform/src/com/example/learning_platform/service/UserManager.java | 06d2235c25ce21caccea1e9ce4ba6d049b304a3c | [] | no_license | riverchuanzhang/Course-Project | 62c98e500ba611f5f940e447fefddf99fdd907b1 | e98a578228191fbce3e180ba18b95431da0856eb | refs/heads/master | 2016-09-14T20:57:57.157613 | 2016-04-22T01:23:12 | 2016-04-22T01:23:12 | 56,642,902 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,986 | java | package com.example.learning_platform.service;
import java.util.List;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import com.example.learning_platform.dao.UserDao;
import com.example.learning_platform.exception.AppException;
import com.example.learning_platform.exception.ExceptionInfo;
import com.example.learning_platform.exception.Status;
import com.example.learning_platform.orm.Page;
import com.example.learning_platform.orm.PropertyFilter;
import com.example.learning_platform.orm.TransactionSupport;
import com.example.learning_platform.pojo.LearningGroup;
import com.example.learning_platform.pojo.Question;
import com.example.learning_platform.pojo.User;
public class UserManager implements TransactionSupport {
// 编程式事务
private TransactionDefinition transactionDefinition;
private PlatformTransactionManager transactionManager;
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public User get(Long id) throws AppException {
User user = null;
TransactionStatus status = transactionManager
.getTransaction(transactionDefinition);
try {
user = userDao.get(id);
transactionManager.commit(status);
} catch (Exception e) {
transactionManager.rollback(status);
throw new AppException(new Status(ExceptionInfo.Type.DB_SEARCH, e));
}
return user;
}
public User get(String userName) throws AppException {
User user = null;
TransactionStatus status = transactionManager
.getTransaction(transactionDefinition);
try {
Criterion criterion = Restrictions.eq("userName", userName);
user = userDao.findUnique(criterion);
transactionManager.commit(status);
} catch (Exception e) {
transactionManager.rollback(status);
throw new AppException(new Status(ExceptionInfo.Type.DB_SEARCH, e));
}
return user;
}
public void save(User user) throws AppException {
TransactionStatus status = transactionManager
.getTransaction(transactionDefinition);
try {
userDao.save(user);
userDao.getSession().clear();
transactionManager.commit(status);
} catch (Exception e) {
transactionManager.rollback(status);
throw new AppException(new Status(ExceptionInfo.Type.DB_SAVE, e));
}
}
public User getUserByNameAndPassword(String userName, String password)
throws AppException {
User user = null;
TransactionStatus status = transactionManager
.getTransaction(transactionDefinition);
try {
Criterion criterion = Restrictions.eq("userName", userName);
criterion = Restrictions.and(criterion,
Restrictions.eq("password", password));
user = userDao.findUnique(criterion);
transactionManager.commit(status);
} catch (Exception e) {
e.printStackTrace();
transactionManager.rollback(status);
throw new AppException(new Status(ExceptionInfo.Type.DB_OTHERS, e));
}
return user;
}
public Page<User> findPage(final Page<User> page,
final List<PropertyFilter> filters) throws AppException {
Page<User> result = null;
TransactionStatus status = transactionManager
.getTransaction(transactionDefinition);
try {
result = userDao.findPage(page, filters);
transactionManager.commit(status);
} catch (Exception e) {
e.printStackTrace();
transactionManager.rollback(status);
throw new AppException(new Status(ExceptionInfo.Type.DB_SEARCH, e));
}
return result;
}
public void test() throws RuntimeException {
throw new RuntimeException();
}
@Override
public void setTransactionDefinition(
TransactionDefinition transactionDefinition) {
this.transactionDefinition = transactionDefinition;
}
@Override
public void setTransactionManager(
PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
}
| [
"riverchuanzh@gmail.com"
] | riverchuanzh@gmail.com |
b22ce19951d3bba606659055c6d458c042232431 | d104854fecbf15e522db98436de2ac42c832b92d | /src/test/java/what/the/spring/WhatTheSpring/service/MemberServiceIntegrationTest.java | 506532c96e4da3889b6f01fce621490355f47ebe | [] | no_license | conquerex/WhatTheSpring | 9feff5c781451c44508f5cc691f5cfd9e0739333 | 7ef069bd373096afb6002f58d82fd0889cd832e3 | refs/heads/main | 2023-04-17T05:02:52.414491 | 2021-05-06T01:43:54 | 2021-05-06T01:43:54 | 363,823,062 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,480 | java | package what.the.spring.WhatTheSpring.service;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.annotation.Transactional;
import what.the.spring.WhatTheSpring.domain.Member;
import what.the.spring.WhatTheSpring.repository.MemberRepository;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
@Transactional
class MemberServiceIntegrationTest {
@Autowired
MemberService service;
@Autowired
MemberRepository memberRepository;
@Test
void 회원가입() {
// given
Member member = new Member();
member.setName("spring22");
// when
Long saveId = service.join(member);
// then
Member findMember = service.findOne(saveId).get();
assertThat(member.getName()).isEqualTo(findMember.getName());
}
@Test
void 중복_회원_예외() {
// given
Member member1 = new Member();
member1.setName("spring33");
Member member2 = new Member();
member2.setName("spring33");
// when
service.join(member1);
IllegalStateException e = assertThrows(IllegalStateException.class, () -> service.join(member2));
assertThat(e.getMessage()).isEqualTo("이미 존재하는 회원입니다.");
}
} | [
"conquerex@gmail.com"
] | conquerex@gmail.com |
83be8bc728bacd53bdf1f5f7a1cf7c341d57a9c0 | bd23cdb755e23c7e130078322a9d58a4dc59757a | /src/day46_Static/Restaurant.java | 975448c140c25f7b6bc9d630ec27b9afaffcd693 | [] | no_license | olenamazikina/java-practice | 2cac24d3b1bf038ed2c06c541dc86360f7a7ee06 | 457329117a012fbf68817ea0031d81b0a2bd5bef | refs/heads/master | 2020-05-18T03:43:08.734990 | 2019-05-29T22:24:43 | 2019-05-29T22:24:43 | 184,151,862 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 353 | java | package day46_Static;
public class Restaurant {
public static void main(String[] args) {
Dinner Mom = new Dinner();
Dinner kid = new Dinner();
Dinner Dad = new Dinner();
System.out.println("Total slices:"+Dinner.pizzaSlices);
System.out.println("Total slices:"+Dad.pizzaSlices);
Dad.takeASlice(2);
kid.takeASlice(3);
Mom.takeASlice(2);
}
} | [
"elenavmazikina@gmail.com"
] | elenavmazikina@gmail.com |
6d6220c46ab3d249668ce8e965ca8e96f36fda64 | 8aa8635ece403d3ca38c7cb6c8f2f0614962f558 | /event-detection-master/src/eventdetection/validator/types/ArticleOnlyValidator.java | e5fb63078ca1ff7c117064760e284d5a3d1a38d4 | [
"MIT"
] | permissive | a-raina/Event-Detection-using-NLP | e1740281d01550f007c73d72b9b6c3a130411bf5 | 0f68e90635cb64745083bdaa39c4e4617b490509 | refs/heads/master | 2021-01-20T20:32:38.743272 | 2016-06-27T22:53:34 | 2016-06-27T22:53:34 | 62,093,548 | 13 | 1 | null | null | null | null | UTF-8 | Java | false | false | 795 | java | package eventdetection.validator.types;
import eventdetection.common.Article;
import eventdetection.common.Query;
import eventdetection.validator.ValidationResult;
/**
* Base class for implementations of validation algorithms that take one {@link Article} that are callable by this library.
*
* @author Joshua Lipstone
*/
public abstract class ArticleOnlyValidator {
/**
* Executes the algorithm that the {@link Validator} implements
*
* @param article
* the {@link Article} with which to validate {@link Query Queries}
* @return an array of {@link ValidationResult ValidationResults} with the appropriate information
* @throws Exception
* if something goes wrong
*/
public abstract ValidationResult[] call(Article article) throws Exception;
}
| [
"anmol.raina642@gmail.com"
] | anmol.raina642@gmail.com |
0f230711e14e57317c772e973875087be46ec267 | 13987e1e23a2e05a6bb3103abbdce91812b3a71b | /other/src/main/java/com/dandan/other/spring/aop/aspect/MyServiceAspect.java | aa82f3c236e15dac37eb7799cbd61017de6f20fb | [] | no_license | Shirley-Huang/learn | 89faa519e60145b48c38c6cff884a2a019749b03 | 48ca9c53f135b53b7b4750b46a15842233637a0d | refs/heads/master | 2022-06-29T22:51:54.612232 | 2021-07-05T02:21:55 | 2021-07-05T02:21:55 | 204,466,570 | 0 | 0 | null | 2022-06-29T17:42:35 | 2019-08-26T12:02:58 | Java | UTF-8 | Java | false | false | 3,647 | java | package com.dandan.other.spring.aop.aspect;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
/**
* @Description
* @Author dandan
* @Date 2019-10-16
*/
@Aspect
public class MyServiceAspect {
public void beforeHandler(){
System.out.println("前置通知");
}
public void afterHandler(){
System.out.println("后置通知");
}
public void returnHandler(Object name){
System.out.println("返回通知:"+name);
}
public void throwExceptionHandler(Throwable ex){
System.out.println("异常通知" + ex.getMessage());
}
public Object doAround(ProceedingJoinPoint jp) {
try {
System.out.println("环绕通知开始");
// System.out.println("toString() ---" + jp.toString());//连接点所在位置的相关信息
// System.out.println("toShortString() ---" + jp.toShortString());//连接点所在位置的简短相关信息
// System.out.println("toLongString() ---" + jp.toLongString());//连接点所在位置的全部相关信息
// System.out.println(jp.getThis());
// System.out.println(jp.getTarget());
//
// Object[] args = jp.getArgs();
// for (int i = 1; i <= args.length; i++) {
// System.out.println("第"+i+"个参数:" + args[i - 1]);
// }
Signature signature = jp.getSignature();
System.out.println(signature.getName());
System.out.println(signature.getDeclaringType());
System.out.println(signature.getDeclaringTypeName());
System.out.println(signature.getModifiers());
System.out.println(signature.toString());
System.out.println(signature.toShortString());
System.out.println(signature.toLongString());
System.out.println();
System.out.printf(jp.getKind());
JoinPoint.StaticPart staticPart = jp.getStaticPart();
System.out.println(staticPart.getId());
System.out.println(staticPart.getKind());
System.out.println(staticPart.getSignature().getName());
System.out.println(staticPart.getSourceLocation());
System.out.println(staticPart.toString());
System.out.println();
System.out.println("MethodSignature------");
MethodSignature methodSignature = (MethodSignature)jp.getSignature();
System.out.println(methodSignature.getMethod());
System.out.println(methodSignature.getReturnType());
String[] parameterNames = methodSignature.getParameterNames();
for (String parameterName : parameterNames) {
System.out.println("parameterName");
System.out.println(parameterName);
}
// Object result = pjp.proceed();
System.out.println("环绕通知结束");
// return result;
} catch (Throwable throwable) {
}
return null;
}
public static int i = 1;
@Pointcut("execution (* com.dandan.other.spring.aop.service.MyServiceImpl.createOrder(..))")
private void createOrderPointcut(){}
@After(value = "createOrderPointcut()")
public void staticCreateOrderCount(){
System.out.println("发布工单数:" + i);
i++;
}
}
| [
"799745061@qq.com"
] | 799745061@qq.com |
17ed535b4c2a1515cf4280e261b764cb4eb0655f | 4daf3724da66f55609295814604ca561465ed403 | /java/visualchat/at/ac/uni_linz/tk/vchat/RoomCanvas.java | 39d72490f4f85d02c03fd1aabf7627f8c064a4a4 | [] | no_license | ArnoHue/legacy | 05140dc322b704f4b8706bc84eb14ceb76e183bf | 92cd94aa291dd69ddab7519895e5d1b78d5cdaea | refs/heads/master | 2020-05-19T09:21:48.713502 | 2019-05-05T19:52:11 | 2019-05-05T19:52:11 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,270 | java | package at.ac.uni_linz.tk.vchat;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
/**
* A Room's graphical representation. Users are painted as colored circles, the
* current User is marked by a special cursor. Changing position or heading can
* be done by mouse-clicking and -dragging.
*
* @author Arno Huetter
* (C)opyright 1997/98 by the Institute for Computer Science, Telecooperation Department, University of Linz
*/
public class RoomCanvas extends Canvas implements MouseListener, MouseMotionListener, ActionListener {
private ChatApplet chatApplet;
private Color nameColor = Color.black;
private PopupMenu ownRoomPopup, roomPopup, ownUserPopup, userPopup;
private Menu inviteUserMenu, kickUserMenu;
private MenuItem roomInfoItem, roomSettingsItem, userInfoItem, userSettingsItem, whisperItem;
private int selectedUserId;
public final int ACTION_NONE = 0;
public final int ACTION_MOVING = 1;
public final int ACTION_ROTATING = 2;
private int userAction = ACTION_NONE;
private int focusedUserId = -1;
/**
* Constructs the RoomCanvas.
*
* @param chatParam the ChatApplet which administrates the
* users
*/
public RoomCanvas(ChatApplet chatAdministratorParam) {
super();
chatApplet = chatAdministratorParam;
addMouseListener(this);
addMouseMotionListener(this);
roomPopup = new PopupMenu();
ownRoomPopup = new PopupMenu();
userPopup = new PopupMenu();
ownUserPopup = new PopupMenu();
roomInfoItem = new MenuItem("View room settings");
roomSettingsItem = new MenuItem("Edit room settings");
userInfoItem = new MenuItem("View user info");
userSettingsItem = new MenuItem("Edit user info");
inviteUserMenu = new Menu("Invite user to room");
kickUserMenu = new Menu("Kick user from room");
whisperItem = new MenuItem("Whisper to user");
roomPopup.add(roomInfoItem);
ownRoomPopup.add(roomSettingsItem);
userPopup.add(whisperItem);
userPopup.add(userInfoItem);
userPopup.add(inviteUserMenu);
userPopup.add(kickUserMenu);
ownUserPopup.add(userSettingsItem);
add(roomPopup);
add(ownRoomPopup);
add(userPopup);
add(ownUserPopup);
roomPopup.addActionListener(this);
ownRoomPopup.addActionListener(this);
userPopup.addActionListener(this);
ownUserPopup.addActionListener(this);
inviteUserMenu.addActionListener(this);
kickUserMenu.addActionListener(this);
}
/**
* Paints the PortraitCanvas.
*
* @param g the graphics context
*/
public void paint (Graphics g) {
Hashtable userTable;
Vector vecCurrentSituation;
HistoryEntry histEntry;
g.setFont(ChatRepository.SMALL_FONT);
vecCurrentSituation = chatApplet.historyMode() ? chatApplet.getHistoryEntryVector(chatApplet.getHistoryDate()) : chatApplet.getCurrentSituationVector();
for (int i = 0; i < vecCurrentSituation.size(); i++) {
histEntry = (HistoryEntry)vecCurrentSituation.elementAt(i);
if (chatApplet.getUser(histEntry.userId) != null) {
// histEntry has been cloned, so we can work on it...
if (histEntry.userId == chatApplet.getCurrentUserId()) {
histEntry.position = chatApplet.getCurrentUser().getPosition();
histEntry.heading = chatApplet.getCurrentUser().getHeading();
histEntry.color = chatApplet.getCurrentUser().getColor();
}
g.setColor(ChatUtil.brighten(ChatUtil.brighten(histEntry.color)));
g.fillOval(histEntry.position.x - ChatRepository.USER_SIZE / 2, histEntry.position.y - ChatRepository.USER_SIZE / 2, ChatRepository.USER_SIZE, ChatRepository.USER_SIZE);
g.setColor(histEntry.color);
g.fillOval(histEntry.position.x - ChatRepository.USER_SIZE / 3, histEntry.position.y - ChatRepository.USER_SIZE / 3, ChatRepository.USER_SIZE * 2 / 3, ChatRepository.USER_SIZE * 2 / 3);
// g.drawLine(histEntry.position.x, histEntry.position.y, histEntry.position.x + (int)(ChatMath.getCos(histEntry.heading) * ChatRepository.USER_SIZE / 2), histEntry.position.y - (int)(ChatMath.getSin(histEntry.heading) * ChatRepository.USER_SIZE / 2));
g.setColor(ChatUtil.brighten(histEntry.color));
for (int j = ChatRepository.USER_SIZE + 5; j <= ChatRepository.USER_SIZE + 5; j += 10)
g.drawArc(histEntry.position.x - j, histEntry.position.y - j, j * 2, j * 2, histEntry.heading - ChatRepository.PHONICAL_ANGLE / 2, ChatRepository.PHONICAL_ANGLE);
if (histEntry.userId == focusedUserId) {
g.setColor(Color.lightGray);
g.drawOval(histEntry.position.x - ChatRepository.USER_SIZE / 2 - 2, histEntry.position.y - ChatRepository.USER_SIZE / 2 - 2, ChatRepository.USER_SIZE + 4, ChatRepository.USER_SIZE + 4);
g.drawOval(histEntry.position.x - ChatRepository.USER_SIZE / 2 - 3, histEntry.position.y - ChatRepository.USER_SIZE / 2 - 3, ChatRepository.USER_SIZE + 6, ChatRepository.USER_SIZE + 6);
}
else if (histEntry.userId == chatApplet.getCurrentUserId()) {
g.setColor(Color.black);
g.drawOval(histEntry.position.x - ChatRepository.USER_SIZE / 2 - 2, histEntry.position.y - ChatRepository.USER_SIZE / 2 - 2, ChatRepository.USER_SIZE + 4, ChatRepository.USER_SIZE + 4);
g.drawOval(histEntry.position.x - ChatRepository.USER_SIZE / 2 - 3, histEntry.position.y - ChatRepository.USER_SIZE / 2 - 3, ChatRepository.USER_SIZE + 6, ChatRepository.USER_SIZE + 6);
}
g.setColor(nameColor);
g.drawString(chatApplet.getUser(histEntry.userId).getName(), histEntry.position.x + ChatRepository.USER_SIZE / 2, histEntry.position.y + ChatRepository.USER_SIZE / 2);
}
}
}
/**
* Returns the id of a User at a certain Point in the Room, resp. -1 if there is no
* User at this very Point.
*
* @param positionParam the Point to observe
*/
private int getUserAtPosition(Point positionParam) {
Enumeration userIdEnum;
User user;
userIdEnum = chatApplet.getRoomUserIdVector(chatApplet.getCurrentRoomId()).elements();
while (userIdEnum.hasMoreElements()) {
user = chatApplet.getUser(((Integer)userIdEnum.nextElement()).intValue());
if (new Rectangle(user.getPosition().x - ChatRepository.USER_SIZE / 2, user.getPosition().y - ChatRepository.USER_SIZE / 2, ChatRepository.USER_SIZE, ChatRepository.USER_SIZE).contains(positionParam))
return user.getId();
}
return -1;
}
/**
* Invoked when an action occurs.
*
* @param event the ActionEvent
*/
public void actionPerformed(ActionEvent event) {
Room room;
if (event.getActionCommand().equals(roomInfoItem.getLabel()))
chatApplet.showRoom(chatApplet.getCurrentRoomId());
else if (event.getActionCommand().equals(roomSettingsItem.getLabel()))
chatApplet.editRoom(chatApplet.getCurrentRoomId());
else if (event.getActionCommand().equals(userInfoItem.getLabel()))
chatApplet.showUser(selectedUserId);
else if (event.getActionCommand().equals(userSettingsItem.getLabel()))
chatApplet.editUser(selectedUserId);
else if (event.getActionCommand().equals(whisperItem.getLabel()))
chatApplet.whisperToUser(selectedUserId);
else if (event.getSource() == inviteUserMenu || event.getSource() == kickUserMenu) {
room = chatApplet.getRoom(event.getActionCommand());
if (room != null) {
if (event.getSource() == inviteUserMenu) {
room.inviteUser(chatApplet.getUser(selectedUserId).getName());
}
else {
room.kickUser(chatApplet.getUser(selectedUserId).getName());
}
chatApplet.updateRoom(room, chatApplet.isConnected());
}
}
}
/**
* Invoked when the mouse has been clicked on a component.
*
* @param event the MouseEvent
*/
public void mouseClicked(MouseEvent event) {
}
/**
* Invoked when the mouse enters a component.
*
* @param event the MouseEvent
*/
public void mouseEntered(MouseEvent event) {
}
/**
* Invoked when the mouse enters a component.
*
* @param event the MouseEvent
*/
public void mouseExited(MouseEvent event) {
int prevFocusedUserId = focusedUserId;
focusedUserId = getUserAtPosition(event.getPoint());
if (focusedUserId != prevFocusedUserId) {
repaint();
}
if (userAction == ACTION_MOVING)
move(event.getPoint(), true);
else if (userAction == ACTION_ROTATING)
rotate(event.getPoint(), true);
}
/**
* Invoked when the mouse enters a component.
*
* @param event the MouseEvent
*/
public void mousePressed(MouseEvent event) {
int positionX, positionY, angle;
if (!event.isMetaDown()) {
if (userAction == ACTION_NONE) {
positionX = chatApplet.getCurrentUser().getPosition().x;
positionY = chatApplet.getCurrentUser().getPosition().y;
if (new Rectangle(positionX - ChatRepository.USER_SIZE / 2, positionY - ChatRepository.USER_SIZE / 2, ChatRepository.USER_SIZE, ChatRepository.USER_SIZE).contains(event.getPoint()))
userAction = ACTION_MOVING;
else
userAction = ACTION_ROTATING;
}
if (userAction == ACTION_MOVING)
move(event.getPoint(), false);
else if (userAction == ACTION_ROTATING)
rotate(event.getPoint(), false);
}
}
/**
* Invoked when the mouse enters a component.
*
* @param event the MouseEvent
*/
public void mouseReleased(MouseEvent event) {
Enumeration roomIdEnum;
Room room;
if (event.isMetaDown()) {
selectedUserId = getUserAtPosition(new Point(event.getX(), event.getY()));
if (selectedUserId != -1) {
if (selectedUserId == chatApplet.getCurrentUserId())
ownUserPopup.show(this, event.getX(), event.getY());
else {
inviteUserMenu.removeAll();
kickUserMenu.removeAll();
roomIdEnum = chatApplet.getRoomIds();
while (roomIdEnum.hasMoreElements()) {
room = chatApplet.getRoom(((Integer)roomIdEnum.nextElement()).intValue());
if (room.isAdministrator(chatApplet.getCurrentUser().getName())) {
if (room.isPrivate())
inviteUserMenu.add(room.getName());
else
kickUserMenu.add(room.getName());
}
}
inviteUserMenu.setEnabled(inviteUserMenu.getItemCount() > 0);
kickUserMenu.setEnabled(kickUserMenu.getItemCount() > 0);
userPopup.show(this, event.getX(), event.getY());
}
}
else {
if (chatApplet.getCurrentRoom().isAdministrator(chatApplet.getCurrentUser().getName()))
ownRoomPopup.show(this, event.getX(), event.getY());
else
roomPopup.show(this, event.getX(), event.getY());
}
}
else {
if (userAction == ACTION_MOVING)
move(event.getPoint(), true);
else if (userAction == ACTION_ROTATING)
rotate(event.getPoint(), true);
userAction = ACTION_NONE;
}
}
/**
* Invoked when the mouse has been dragged on a component.
*
* @param event the MouseEvent
*/
public void mouseDragged(MouseEvent event) {
if (!event.isMetaDown()) {
if (userAction == ACTION_MOVING)
move(event.getPoint(), false);
else if (userAction == ACTION_ROTATING)
rotate(event.getPoint(), false);
}
}
/**
* Invoked when the mouse enters a component.
*
* @param event the MouseEvent
*/
public void mouseMoved(MouseEvent event) {
int prevFocusedUserId = focusedUserId;
focusedUserId = getUserAtPosition(event.getPoint());
if (focusedUserId != prevFocusedUserId) {
repaint();
}
}
/**
* Handles a User's movement.
*
* @param positionParam the Point where the User moved to
* @param send determines whether the new position should be
* broadcasted to other Users
*/
public void move(Point positionParam, boolean send) {
if (new Rectangle(getSize()).contains(positionParam)) {
chatApplet.setUserPosition(chatApplet.getCurrentUser().getId(), positionParam, send);
}
// When the mouse has exited, we have to adjust the position
else if (send) {
if (new Rectangle(getSize()).contains(positionParam.x, 0)) {
chatApplet.setUserPosition(chatApplet.getCurrentUser().getId(), new Point(positionParam.x, chatApplet.getCurrentUser().getPosition().y), send);
}
else if (new Rectangle(getSize()).contains(0, positionParam.y)) {
chatApplet.setUserPosition(chatApplet.getCurrentUser().getId(), new Point(chatApplet.getCurrentUser().getPosition().x, positionParam.y), send);
}
}
repaint();
}
/**
* Handles a change of a User's heading.
*
* @param positionParam the Point where the User is facing
* @param send determines whether the new heading should be
* broadcasted to other Users
*/
public void rotate(Point point, boolean send) {
chatApplet.setUserHeading(chatApplet.getCurrentUser().getId(), ChatUtil.getMiddleAngle(chatApplet.getCurrentUser().getHeading(), ChatUtil.getAngle(chatApplet.getCurrentUser().getPosition(), point)), send);
repaint();
}
} | [
"arno.huetter@liwest.at"
] | arno.huetter@liwest.at |
a5bb6082a6935492f9c7152d432c392adf7781c8 | 719c2223ac22ac69f80821272876ce84fb3252d2 | /tp4/Ejercicio11C.java | ac770a01eb67353f2099c1cdb7b8b8bee9b518f9 | [] | no_license | fran-gomez/Estructuras-de-Datos | 7ef5001eda96fb3892603d43febb6d36e5295f48 | 6dfff058970ecaa92a8aba9a6aa34909d5e2df90 | refs/heads/master | 2020-03-27T18:12:01.623536 | 2018-08-31T15:17:29 | 2018-08-31T15:17:29 | 146,904,964 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,651 | java | package tp4;
import TDALista.BoundaryViolationException;
import TDALista.EmptyListException;
import TDALista.InvalidPositionException;
import TDALista.Position;
import TDALista.PositionList;
public class Ejercicio11C {
private static <E> void eliminar(ListaCircular<E> LC, int n) throws EmptyListException, InvalidPositionException, BoundaryViolationException {
Position<E> p = LC.first();
while (LC.size() > 1) {
for (int i = 0; i < n; i++)
p = LC.next(p);
LC.remove(p);
}
}
private static void imprimir(PositionList<Integer> L) throws EmptyListException {
Position<Integer> p = L.first();
try {
System.out.print("[ ");
while (p != null) {
System.out.print(p.element() + " ");
p = (p == L.last())? null:L.next(p);
}
System.out.println("]");
} catch (InvalidPositionException | BoundaryViolationException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
ListaCircular<Integer> LC = new ListaCircular<>();
//Position<Integer> p;
try {
LC.addLast(1);
LC.addLast(2);
LC.addLast(3);
LC.addLast(4);
LC.addLast(5);
LC.addLast(6);
imprimir(LC);
/*p = LC.first();
for (int i = 0; i < 13; i++) {
System.out.print(p.element() + " ");
p = LC.next(p);
}*/
eliminar(LC, 4);
} catch (EmptyListException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidPositionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (BoundaryViolationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| [
"31447177+fran-gomez@users.noreply.github.com"
] | 31447177+fran-gomez@users.noreply.github.com |
b6297ef28c7f09cd4fac3d098e5afd2555a24a1a | 26bde6e345a70c8f6436c3afb2d210ff83f221b5 | /HeapFile/src/heap/SpaceNotAvailableException.java | b7330a51c0a33b0ab93e6d09b95ca5c3b6094c11 | [] | no_license | Hossam-Mahmoud/MinibaseProject_Wisconsin | 00117acfd308f4731ca83fe627bacda20a1bb3c3 | 8e48dfeb5049cb771d3592a7f7e61ea8e2c83dd0 | refs/heads/master | 2021-01-23T06:45:38.940711 | 2014-03-08T18:42:37 | 2014-03-08T18:42:37 | 17,547,250 | 4 | 1 | null | null | null | null | UTF-8 | Java | false | false | 316 | java | package heap;
import chainexception.ChainException;
@SuppressWarnings("serial")
public class SpaceNotAvailableException extends ChainException
{
public SpaceNotAvailableException()
{
}
public SpaceNotAvailableException(Exception exception, String s)
{
super(exception, s);
}
} | [
"hossam.mahmoud@funwavegames.com"
] | hossam.mahmoud@funwavegames.com |
59b285b4eac9c0c51dc840f3ebd7a0f1270e11e3 | 9c3cf7854521c59a8d284ccddae01998a5dbce5a | /app/src/androidTest/java/qrcodelocalizator/qrcodelocalizator/ExampleInstrumentedTest.java | e7c89da4c95ca61d1ead63b38252a8a217a1af74 | [] | no_license | busyman624/QRCodeLocalizaotor | b509c08d9d364abe53b6027e094873f8e0967f9b | d754685c1bd3765b02a0b1c7a282686405efccec | refs/heads/master | 2020-04-07T01:11:23.422022 | 2018-12-09T12:19:59 | 2018-12-09T12:19:59 | 157,934,004 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 774 | java | package qrcodelocalizator.qrcodelocalizator;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("qrcodelocalizator.qrcodelocalizator", appContext.getPackageName());
}
}
| [
"busyman624@gmail.com"
] | busyman624@gmail.com |
63aec6b54d5e6ffe1a5531af888039ce6b70cc17 | 7be56ff0fd54b04db24e0cd2a7efd43e44adb28a | /src/CauLenhDieuKhien/For$SquareRoot.java | b83ba6e8a6fe51fa40b52dbb1584eb47ee23fd01 | [] | no_license | WillyDolly/JV_CauLenhDieuKhien | a68f28156fc26308c19bbd914d16e35fac11183a | f11f9aa070473a256b4eeaf71d63cab08d3d09e3 | refs/heads/master | 2020-03-28T06:14:02.819988 | 2018-09-07T12:44:03 | 2018-09-07T12:44:03 | 147,822,155 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 743 | java | /*
* 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 CauLenhDieuKhien;
/**
*
* @author hai
*/
public class For$SquareRoot {
public static void main(String[] args) {
double loopControlVar, sroot, saiSoLamTron;
for(loopControlVar = 1.0;loopControlVar<100.0;loopControlVar++){
sroot = Math.sqrt(loopControlVar);
System.out.println("Square Root of "+loopControlVar+" = "+sroot);
saiSoLamTron = loopControlVar -(sroot*sroot);
System.out.println("sai so lam tron la "+saiSoLamTron);
}
}
}
| [
"nguyenpk007@gmail.com"
] | nguyenpk007@gmail.com |
ed448c8e3ba4b18db23dc94b98fef23ca2f8e8d3 | 8d415cfee93d5a9f3d8a092b708e4ec4f5d787bc | /src/com/tc/segment/SegmentDB.java | 77c8e0f631504c56afca31e3a374a5d7e121d9db | [] | no_license | imleibao/corpusconstruction | 7ea5f4622591c54fc040468a56bf91c93e448fdb | 40260df641bb223b9155929a6d9af8b9153e8100 | refs/heads/master | 2021-06-15T02:51:45.710275 | 2017-02-24T12:56:22 | 2017-02-24T12:56:22 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,089 | java | package com.tc.segment;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import com.tc.corpus.DBConnector;
public class SegmentDB {
public static void ICTCLASSegmentMethod(String tableName,String userdicfile,String stopwordfile,int sqlid) throws Exception{
// TODO Auto-generated method stub
//数据库的连接对象
Connection conn = null;
//PreparedStatement 预处理
PreparedStatement pstmt = null;
//ResultSet 结果集
ResultSet result = null;
//sql语句 选择employees表
String sql = "select * from "+tableName+" WHERE id="+sqlid+";";
try {
conn = DBConnector.createConnection();
//实例化PreparedStatement
pstmt = conn.prepareStatement(sql);
//返回结果集
result = pstmt.executeQuery();
//输出结果集
while (result.next()) {
//System.out.println(result.getString("content"));
String content = result.getString("content");
String segment=Segment.DBsegment(content, userdicfile, stopwordfile);
// System.out.println("分词结果"+segment);
//4-将解析结果存储到数据库中
String id=result.getString("id");
//System.out.println(result.getString("id"));
SegmentDB.updateCorpus(tableName, segment, id);
}
}catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static String updateCorpus(String tableName,String segment,String id) {
String updateSql="update "+tableName+" set segment='"+segment+"' WHERE id="+id+";";
String info = "";
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBConnector.createConnection();
int result = 0;
if (conn == null) {
info = "数据库连接失败";
return info;
}
ps = conn.prepareStatement(updateSql);
ps.executeUpdate();
info = "更新成功";
System.out.println("更新成功");
} catch (Exception e) {
info = "更新失败";
return info;
} finally {
try {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return info;
}
public static void main(String[] args) throws Exception {
for(int i=193840;i<=253839;i++){
System.out.println(i);
SegmentDB.ICTCLASSegmentMethod("themecorpus", "F:\\ertaicorpus\\userdic.txt", "F:\\ertaicorpus\\stopworddic.txt",i);
}
}
}
| [
"bobadray@gmail.com"
] | bobadray@gmail.com |
436b5a3003f4163bdcb55b5ee2917446aeea1923 | f89f4ce7dd5613f9c8ec00beee225d32185128c0 | /goods/src/cn/itcast/goods/cart/web/servlet/CartItemServlet.java | a86fabb7dba59ac750e98460aeab4a1b7a503cda | [] | no_license | DrivenPluto/wtuPriactice | 44c657e2a66652652e01a5305cc2e76e2dca3924 | f548a0dbc316fc4d179a47a9a16f2588eac8b065 | refs/heads/master | 2023-06-19T04:11:43.396696 | 2021-07-11T16:00:15 | 2021-07-11T16:00:15 | 384,738,285 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,958 | java | package cn.itcast.goods.cart.web.servlet;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.commons.CommonUtils;
import cn.itcast.goods.book.domain.Book;
import cn.itcast.goods.cart.domain.CartItem;
import cn.itcast.goods.cart.service.CartItemService;
import cn.itcast.goods.user.domain.User;
import cn.itcast.servlet.BaseServlet;
/**
* 购物车web层
* @author Administrator
*
*/
public class CartItemServlet extends BaseServlet {
private CartItemService cartItemService = new CartItemService();
/**
* 加载多个CartItem
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String loadCartItems(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取cartItemIds参数
*/
String cartItemIds = req.getParameter("cartItemIds");
double total = Double.parseDouble(req.getParameter("total"));
/*
* 2. 通过service得到List<CartItem>
*/
List<CartItem> cartItemList = cartItemService.loadCartItems(cartItemIds);
/*
* 3. 保存,然后转发到/cart/showitem.jsp
*/
req.setAttribute("cartItemList", cartItemList);
req.setAttribute("total", total);
req.setAttribute("cartItemIds", cartItemIds);
return "f:/jsps/cart/showitem.jsp";
}
public String updateQuantity(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String cartItemId = req.getParameter("cartItemId");
int quantity = Integer.parseInt(req.getParameter("quantity"));
CartItem cartItem = cartItemService.updateQuantity(cartItemId, quantity);
// 给客户端返回一个json对象
StringBuilder sb = new StringBuilder("{");
sb.append("\"quantity\"").append(":").append(cartItem.getQuantity());
sb.append(",");
sb.append("\"subtotal\"").append(":").append(cartItem.getSubtotal());
sb.append("}");
resp.getWriter().print(sb);
return "";
}
/**
* 批量删除功能
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String batchDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 获取cartItemIds参数
* 2. 调用service方法完成工作
* 3. 返回到list.jsp
*/
String cartItemIds = req.getParameter("cartItemIds");
cartItemService.batchDelete(cartItemIds);
return myCart(req, resp);
}
/**
* 添加条目
* @throws IOException
* @throws ServletException
*/
public String add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
/*
* 1. 封装表单数据到CartItem(bid, quantity)
*/
Map map = req.getParameterMap();
CartItem cartItem = CommonUtils.toBean(map, CartItem.class);
Book book = CommonUtils.toBean(map, Book.class);
User user = (User)req.getSession().getAttribute("sessionUser");
cartItem.setBook(book);
cartItem.setUser(user);
/*
* 2. 调用service完成添加
*/
cartItemService.add(cartItem);
/*
* 3. 查询出当前用户的所有条目,转发到list.jsp显示
*/
return myCart(req, resp);
}
/**
* 我的购物车
* @param req
* @param resp
* @return
* @throws ServletException
* @throws IOException
*/
public String myCart(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
/*
* 1. 得到uid
*/
User user = (User)req.getSession().getAttribute("sessionUser");
String uid = user.getUid();
/*
* 2. 通过service得到当前用户的所有购物车条目
*/
List<CartItem> cartItemLIst = cartItemService.myCart(uid);
/*
* 3. 保存起来,转发到/cart/list.jsp
*/
req.setAttribute("cartItemList", cartItemLIst);
return "f:/jsps/cart/list.jsp";
}
}
| [
"pluto@qq.com"
] | pluto@qq.com |
0139ab6e650a6a8e84533e17daacfc3bbf08d87f | 248de82f6c2e12b0d442654cc2871e9af2905300 | /SpringExamples/src/com/lara/beanClasses/Person4.java | a6f5eb96d2ad802f9fe08abd851b2af2491f28b0 | [] | no_license | tulu131/qv-matrix-data | 685d9358b179cf593d27b37d76d069102edf4564 | bfb2f3d02da02cf591951504adfa5b74ee45959a | refs/heads/master | 2021-01-16T19:04:43.088059 | 2015-05-20T07:20:11 | 2015-05-20T07:20:11 | 32,249,316 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,315 | java | package com.lara.beanClasses;
import java.util.ArrayList;
@SuppressWarnings("rawtypes")
public class Person4
{
private int pId;
private String firstName;
private String middleName;
private String lastName;
private int age;
private ArrayList mailId;
private long mobNo;
private Address1 add;
public int getpId()
{
return pId;
}
public void setpId(int pId)
{
this.pId = pId;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getMiddleName()
{
return middleName;
}
public void setMiddleName(String middleName)
{
this.middleName = middleName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public ArrayList getMailId()
{
return mailId;
}
public void setMailId(ArrayList mailId)
{
this.mailId = mailId;
}
public long getMobNo()
{
return mobNo;
}
public void setMobNo(long mobNo)
{
this.mobNo = mobNo;
}
public Address1 getAdd()
{
return add;
}
public void setAdd(Address1 add)
{
this.add = add;
}
}
| [
"sailendra.n.jena@gmail.com@376d9f85-88c3-4b5c-aff6-862f136f3076"
] | sailendra.n.jena@gmail.com@376d9f85-88c3-4b5c-aff6-862f136f3076 |
43807b10de732e9061d7a206de62f9e4731f09bd | 231b8bfd668b315f5127c365be302ea092f71333 | /upgrade/src/main/java/br/com/sysdesc/upgrade/ui/FrmPrincipal.java | f240994d5cfea7cc698321d876c700a8de0f258a | [] | no_license | leandroZanatta/SysDesc | 98142b525a854ea346f285d0c65c584de007b9c2 | 0cb39f594dc92c53ca8f8896c24c48b62675c513 | refs/heads/master | 2022-11-17T01:57:28.012919 | 2019-10-13T03:31:15 | 2019-10-13T03:31:15 | 186,448,488 | 0 | 1 | null | 2022-11-10T20:48:10 | 2019-05-13T15:36:28 | Java | UTF-8 | Java | false | false | 4,177 | java | package br.com.sysdesc.upgrade.ui;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import org.apache.commons.io.FileUtils;
import com.google.gson.Gson;
import br.com.sysdesc.upgrade.changelog.core.Changelog;
import br.com.sysdesc.upgrade.changelog.core.Conexao;
import br.com.sysdesc.upgrade.startup.GerarVersaoERP;
import br.com.sysdesc.upgrade.startup.GerarVersaoPDV;
import br.com.sysdesc.upgrade.util.classes.LookAndFeelUtil;
import br.com.sysdesc.upgrade.vo.VersaoVO;
public class FrmPrincipal extends JFrame {
private static final long serialVersionUID = 1L;
private JLabel lbVersaoERP;
private JLabel lbVersaoFront;
private JLabel lbConfiguracao;
private JTextField txConfiguracao;
private JTextField txVersaoErp;
private JTextField txVersaoFront;
private JButton btAtualizarBt;
private JButton btGerarVersao;
private JButton btnGerarPdv;
private JButton btUpgade;
public FrmPrincipal() {
setTitle("Ações Projeto");
getContentPane().setLayout(null);
setSize(444, 274);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
lbConfiguracao = new JLabel("Arquivo de Configuração:");
lbVersaoERP = new JLabel("Versão ERP:");
lbVersaoFront = new JLabel("Versão PDV:");
txConfiguracao = new JTextField();
txVersaoErp = new JTextField();
txVersaoFront = new JTextField();
btGerarVersao = new JButton("Gerar ERP");
btAtualizarBt = new JButton("Atualizar DB");
btnGerarPdv = new JButton("Gerar PDV");
btUpgade = new JButton("Upgade");
btAtualizarBt.addActionListener(e -> new FrmConexao(txConfiguracao.getText()).setVisible(true));
btUpgade.addActionListener(e -> executarUpgade());
btGerarVersao.addActionListener(e -> atualizarVersaoERP());
btnGerarPdv.addActionListener(e -> atualizarVersaoPDV());
VersaoVO versaoVO = buscarVersoes();
txConfiguracao.setText(new File(System.getProperty("user.dir")).getParent() + "\\interface\\config\\config.01");
txVersaoErp.setText(versaoVO.getVersaoERP());
txVersaoFront.setText(versaoVO.getVersaoPDV());
btAtualizarBt.setBounds(103, 80, 104, 34);
txConfiguracao.setBounds(10, 29, 408, 20);
txVersaoErp.setBounds(10, 159, 185, 20);
lbVersaoERP.setBounds(10, 142, 130, 14);
txVersaoFront.setBounds(233, 159, 185, 20);
lbVersaoFront.setBounds(233, 142, 128, 14);
btGerarVersao.setBounds(36, 190, 104, 34);
lbConfiguracao.setBounds(10, 11, 145, 14);
btnGerarPdv.setBounds(277, 190, 104, 34);
btUpgade.setBounds(223, 80, 104, 34);
getContentPane().add(btAtualizarBt);
getContentPane().add(txConfiguracao);
getContentPane().add(txVersaoErp);
getContentPane().add(lbVersaoERP);
getContentPane().add(txVersaoFront);
getContentPane().add(lbVersaoFront);
getContentPane().add(btGerarVersao);
getContentPane().add(lbConfiguracao);
getContentPane().add(btnGerarPdv);
getContentPane().add(btUpgade);
}
private void atualizarVersaoPDV() {
txVersaoFront.setText(new GerarVersaoPDV(txVersaoFront.getText()).build());
}
private void atualizarVersaoERP() {
txVersaoErp.setText(new GerarVersaoERP(txVersaoErp.getText()).build());
}
private void executarUpgade() {
try {
Changelog.runChangelog(Conexao.buscarConexao(txConfiguracao.getText()));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
private VersaoVO buscarVersoes() {
try {
File pathDir = new File(System.getProperty("user.dir")).getParentFile();
String arquivoJson = FileUtils.readFileToString(new File(pathDir, "versoes\\versao.json"),
Charset.defaultCharset());
return new Gson().fromJson(arquivoJson, VersaoVO.class);
} catch (IOException e) {
return new VersaoVO();
}
}
public static void main(String[] args) throws Exception {
LookAndFeelUtil.configureLayout("Times New Roman plain 11");
new FrmPrincipal().setVisible(true);
}
}
| [
"Leandro@DESKTOP-7K69IQ7"
] | Leandro@DESKTOP-7K69IQ7 |
5c1c04ba0849a04067c47175312396e77462fa52 | fa619423dbd4675cb5528e5ce8ea4a5bbda85043 | /src/com/candela/workflow/job/OverTimeCronJob.java | 8d5316989bb5f9237ffbc02e2d92a8aff76fb5bc | [] | no_license | PrettyBoy2018/ecology | 187412c80550e1c153950113084af19ef4fd1ce8 | 34282609eecd5efedf4f2618b916b0932f4f1eb0 | refs/heads/master | 2020-09-14T09:52:19.862327 | 2020-03-23T03:15:57 | 2020-03-23T03:15:57 | 223,095,460 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 694 | java | package com.candela.workflow.job;
import com.candela.workflow.bean.ScheduleSign;
import com.candela.workflow.service.OverTimeService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import weaver.interfaces.schedule.BaseCronJob;
import java.util.List;
public class OverTimeCronJob extends BaseCronJob {
private Log log = LogFactory.getLog(this.getClass());
private OverTimeService service = new OverTimeService();
@Override
public void execute() {
log.info("开始执行OverTimeCronJob");
List<ScheduleSign> list = service.getList();
service.handle(list);
log.info("结束OverTimeCronJob");
}
}
| [
"linbin_work@foxmail.com"
] | linbin_work@foxmail.com |
fd7ebb4d582d3100e88b2fa7ee074c61339abfc6 | 36a62b8849cadfe34f549775499e075dc50edca1 | /2. Back-end/1. JavaCore/Tham khảo/Demo JavaCore/AccessModifierDemo/src/demo/access/defaults/DefaultAccessMethodVariable.java | 3a0b9bee3b17c3174b140060618da39208d271d4 | [] | no_license | youngdeveloperVN/JAVA_WEB_FULLSTACK | a3a8364864d737e3186bc06727853c2903ba59d1 | 84ab4a769bbb4765e3d711e6d99383451b89fc02 | refs/heads/master | 2023-01-07T09:30:00.159816 | 2021-12-18T16:45:28 | 2021-12-18T16:45:28 | 143,231,382 | 7 | 3 | null | 2023-01-02T22:01:35 | 2018-08-02T02:24:27 | Java | UTF-8 | Java | false | false | 201 | java | package demo.access.defaults;
public class DefaultAccessMethodVariable {
String name;
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
}
| [
"huypn@Desktop088.nttdata.com.vn"
] | huypn@Desktop088.nttdata.com.vn |
cd2ac01a4c33bd1e78793af49c5b9b1e3582e926 | be7aff0272e09ab45b923a980b35524c6182d0ff | /app/src/test/java/com/zhuimeng/testpopwin/ExampleUnitTest.java | 648b474b8bb2de9e5bbd6d61b6d8150dd0ff49cb | [] | no_license | zhuimengkuangren/TestPopwin | 75c85298b2dd8ef5451c6ae7098c0e00cf9ce542 | 14544f8f56107d308954686b32a20db2f9aec5c4 | refs/heads/master | 2021-07-25T02:50:06.026444 | 2017-11-05T14:31:56 | 2017-11-05T14:31:56 | 109,586,561 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 401 | java | package com.zhuimeng.testpopwin;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | [
"guofeizouandroid@163.com"
] | guofeizouandroid@163.com |
6ebcc0765d77f84bdd3dca02e4b3bffaf39e0959 | 35f4769061018385078ef5864f6a9d5fb56fafb0 | /app/src/main/java/com/example/blogappdemo/MainActivity.java | b10caabe4b0115e0b08357c4e7b0c4f371a02882 | [] | no_license | lqDaiLoc/AndroidApp_BlogApp | c75e21fc096e875741f7a994630f2d30edcb1c95 | 66496d6944fa31bc7c4d4450a950787655790d40 | refs/heads/master | 2020-05-30T21:34:30.455513 | 2019-06-03T09:44:02 | 2019-06-03T09:44:02 | 189,972,994 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 5,846 | java | package com.example.blogappdemo;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;
public class MainActivity extends AppCompatActivity {
private String current_user_id;
private Toolbar mainToolbar;
private FirebaseAuth mAuth;
private FloatingActionButton addPostBtn;
private FirebaseFirestore firebaseFirestore;
private BottomNavigationView mainBottomNav;
private HomeFragment homeFragment;
private NotificationFragment notificationFragment;
private AccountFragment accountFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
setContentView(R.layout.activity_main);
mainToolbar = findViewById(R.id.main_toolbar);
setSupportActionBar(mainToolbar);
getSupportActionBar().setTitle("Photo Blog");
if (mAuth.getCurrentUser() != null)
{
mainBottomNav = findViewById(R.id.main_bottom_nav);
//FRAGMENTS
homeFragment = new HomeFragment();
accountFragment = new AccountFragment();
notificationFragment = new NotificationFragment();
replaceFragment(homeFragment);
mainBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId())
{
case R.id.bottom_action_home:
replaceFragment(homeFragment);
return true;
case R.id.bottom_action_account:
replaceFragment(accountFragment);
return true;
case R.id.bottom_action_notification:
replaceFragment(notificationFragment);
return true;
default:
return false;
}
}
});
addPostBtn = findViewById(R.id.post_btn);
addPostBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent newPostIntent = new Intent(MainActivity.this, NewPostActivity.class);
startActivity(newPostIntent);
}
});
}
}
@Override
protected void onStart() {
super.onStart();
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
if(currentUser == null)
{
sendToLogin();
}
else
{
current_user_id = mAuth.getCurrentUser().getUid();
firebaseFirestore.collection("Users").document(current_user_id).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if(task.isSuccessful())
{
if(!task.getResult().exists())
{
Intent setUpIntent = new Intent(MainActivity.this, SetupActivity.class);
startActivity(setUpIntent);
finish();
}
}
else
{
String error = task.getException().getMessage();
Toast.makeText(MainActivity.this, "Error: " + error, Toast.LENGTH_LONG).show();
}
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch ((item.getItemId()))
{
case R.id.action_logout_btn:
logOut();
return true;
case R.id.action_setting_btn:
Intent settingsIntent = new Intent(MainActivity.this, SetupActivity.class);
startActivity(settingsIntent);
return true;
default:
return false;
}
}
private void logOut() {
mAuth.signOut();
sendToLogin();
}
private void sendToLogin() {
Intent loginIntent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(loginIntent);
finish();
}
private void replaceFragment(Fragment fragment)
{
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.main_container, fragment);
fragmentTransaction.commit();
}
}
| [
"1651012105loc@ou.edu.vn"
] | 1651012105loc@ou.edu.vn |
9951380ee0a26e5c32ae547468d75a807e8178eb | 1ef8ffbc4b5737b651d9f04846012a94a42a91ab | /03.rest-api/fastweb-mongodb/src/main/java/com/supermy/mongodb/domain/MenuItem.java | d6aee4a00e2dda314d2dbf9ee838b2502511c004 | [] | no_license | rucky2013/fastweb-mobile | ccd693a975080dfe51b009ca68d0b1bee8ce48c1 | 30a8630c982f1346a12443440cd9538666b4aa40 | refs/heads/master | 2020-12-28T12:05:43.946915 | 2014-09-03T06:31:17 | 2014-09-03T06:31:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 734 | java | package com.supermy.mongodb.domain;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
/**
* @author jamesmo
*
*/
@Document(collection="menuitem")
public class MenuItem implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
private String id;
private String title;
private String url;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
| [
"moyong@bonc.com.cn"
] | moyong@bonc.com.cn |
3669d9b66d3550794fd5c1c9f4a3a0cc4a7ad0c9 | 0af8b92686a58eb0b64e319b22411432aca7a8f3 | /single-large-project/src/test/java/org/gradle/test/performancenull_265/Testnull_26409.java | 62a6d45a0c878e4e6985c3f910bde1c75dfdc629 | [] | no_license | gradle/performance-comparisons | b0d38db37c326e0ce271abebdb3c91769b860799 | e53dc7182fafcf9fedf07920cbbea8b40ee4eef4 | refs/heads/master | 2023-08-14T19:24:39.164276 | 2022-11-24T05:18:33 | 2022-11-24T05:18:33 | 80,121,268 | 17 | 15 | null | 2022-09-30T08:04:35 | 2017-01-26T14:25:33 | null | UTF-8 | Java | false | false | 308 | java | package org.gradle.test.performancenull_265;
import static org.junit.Assert.*;
public class Testnull_26409 {
private final Productionnull_26409 production = new Productionnull_26409("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
} | [
"cedric.champeau@gmail.com"
] | cedric.champeau@gmail.com |
32660b75f222497c8ed2b3af851be78d0f55ff81 | 149b205dcc1a3672970d06d979c7c80aac61d3e4 | /src/main/java/net/yangziwen/httptest/dao/CaseParamDao.java | 7456bca6892e8750027fed6611dbb9db87281afe | [] | no_license | yangziwen/httptest | c575d4b3583829bccb2d579c9f8ec6aa566175ab | e08547b485cde19702e8e01612b71939e93d4847 | refs/heads/master | 2016-09-16T16:52:26.513504 | 2016-05-08T12:54:11 | 2016-05-08T12:56:40 | 41,776,940 | 5 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,327 | java | package net.yangziwen.httptest.dao;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import net.yangziwen.httptest.dao.base.AbstractEditPropertyJdbcDaoImpl;
import net.yangziwen.httptest.dao.base.CustomPropertyEditor;
import net.yangziwen.httptest.dao.base.QueryParamMap;
import net.yangziwen.httptest.model.CaseParam;
@Repository
public class CaseParamDao extends AbstractEditPropertyJdbcDaoImpl<CaseParam> {
@SuppressWarnings("serial")
private Map<Class<?>, CustomPropertyEditor> propertyEditorMap = new HashMap<Class<?>, CustomPropertyEditor>() {{
put(CaseParam.Type.class, new CaseParam.TypePropertyEditor());
}};
@Override
protected Map<Class<?>, CustomPropertyEditor> getPropertyEditorMap() {
return propertyEditorMap;
}
public int deleteByCaseIds(Long... caseIds) {
if(caseIds == null) {
return 0;
}
return deleteByCaseIds(Arrays.asList(caseIds));
}
public int deleteByCaseIds(List<Long> caseIdList) {
if(caseIdList == null || caseIdList.isEmpty()) {
return 0;
}
String sql = "delete from " + getTableName() + " where case_id in (:caseIdList)";
Map<String, Object> params = new QueryParamMap().addParam("caseIdList", caseIdList);
return jdbcTemplate.update(sql, params);
}
}
| [
"yzwcroco@gmail.com"
] | yzwcroco@gmail.com |
e4e0db13f85ed78c24dc32c1b945acb080ca6813 | efd27fd833adb18be7890bb3e6afbf8d23e3a3ed | /app/src/main/java/com/android/aman/movieapp/Models/TrailerModel.java | 28c76f6e7fa9e534ce6be28374a8703db5e1d14f | [
"MIT"
] | permissive | Aman2028/project-3-movie-app-2 | 40579d1b530a908bb91e603ea816e484a938bb05 | eb93d576dfbafb9b1c61bd9be6e78db0f5359861 | refs/heads/master | 2022-10-19T22:44:43.339153 | 2020-06-06T10:40:13 | 2020-06-06T10:40:13 | 269,948,550 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 291 | java | package com.android.aman.movieapp.Models;
public class TrailerModel
{
String key;
public TrailerModel(String key)
{
this.key=key;
}
public String getKey()
{
return key;
}
public void setKey(String key)
{
this.key = key;
}
}
| [
"amangangwar2028@gmail.com"
] | amangangwar2028@gmail.com |
99cb2d2bf92362377f3263969a2487823e415e56 | 039678702fed0e68afcdb504a28b48c679d411d8 | /src/main/java/own/drapala/TaskManager/security/AuthoritiesConstants.java | 7b67269897ed6290760cdcfba3af1c90cee07ca1 | [
"MIT"
] | permissive | Danieldrapala/TaskManager | 4adf46014a83db3780099270804d519c265004b9 | 71433a2d4e3e76121b29fa02c2595ee2be0d87e4 | refs/heads/master | 2023-05-15T02:37:48.767946 | 2021-05-12T23:42:01 | 2021-05-12T23:42:01 | 357,638,097 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 348 | java | package own.drapala.TaskManager.security;
/**
* Constants for Spring Security authorities.
*/
public final class AuthoritiesConstants {
public static final String ADMIN = "ROLE_ADMIN";
public static final String USER = "ROLE_USER";
public static final String ANONYMOUS = "ROLE_ANONYMOUS";
private AuthoritiesConstants() {}
}
| [
"danieldr1212@gmail.com"
] | danieldr1212@gmail.com |
2606ca5f73bb506b75be8652c4bbdb0a6df7dfe3 | 9af1a4d6baa4ef94b56a98d97e30cb3b63027d48 | /lib/src/main/java/com/algorithmdemo/shoot_at_offer/Question29.java | 7e38f451feffcd4cce9c8ac11ff0bb52ea1186e5 | [] | no_license | totond/AlgorithmDemo | 0d988597de1b543e2ba300735e3011e5a8b8d7e1 | bf2e1a7f055bc653c2e6ef40bafb609bce93d2d3 | refs/heads/master | 2021-10-24T05:04:37.986607 | 2019-03-22T04:44:20 | 2019-03-22T04:44:20 | 108,247,280 | 0 | 0 | null | 2018-03-13T12:38:12 | 2017-10-25T09:17:24 | Java | UTF-8 | Java | false | false | 1,834 | java | package com.algorithmdemo.shoot_at_offer;
import java.util.ArrayList;
/**
* author : yany
* e-mail : yanzhikai_yjk@qq.com
* time : 2018/03/24
* desc : 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
*/
public class Question29 {
public ArrayList<Integer> printMatrix(int[][] matrix) {
ArrayList<Integer> result = new ArrayList<>();
if (matrix == null) {
return result;
}
//从外圈到里圈,分层处理,因为最里圈的坐标是行数和列数的一半,所以有这个限制条件
for (int x = 0, y = 0; x * 2 < matrix.length && y * 2 < matrix[0].length; x++, y++) {
printRowsAndColumns(matrix, x, y, result);
}
return result;
}
private void printRowsAndColumns(int[][] matrix, int x, int y, ArrayList<Integer> result) {
int endX = matrix.length - 1 - x;
int endY = matrix[0].length - 1 - y;
//从左往右遍历
for (int i = y; i <= endY; i++) {
result.add(matrix[x][i]);
}
//从上往下,注意第一个已经被遍历了
if (x < endX) {
for (int i = x + 1; i <= endX; i++){
result.add(matrix[i][endY]);
}
}
//从右往左,注意第一个已经被遍历,还有y坐标是要递减
if (x < endX && y < endY){
for (int i = endY - 1; i >= y; i-- ){
result.add(matrix[endX][i]);
}
}
//从下往上,注意第一个和最后一个已经被遍历,x坐标要递减
if (x < endX && y < endY){
for (int i = endX - 1; i > x; i--){
result.add(matrix[i][y]);
}
}
}
}
| [
"yanzhikai_yjk@qq.com"
] | yanzhikai_yjk@qq.com |
9aa3dc1af69cfdff913617b7e951a5e4e2d21e68 | c15f37773118cd563e07d1790b8794f3d89f328a | /src/org/processmining/plugins/neconformance/bags/naieve/NaieveLogBag.java | b06046fcfc8c28d4335b9b2a96da21305c1fbccf | [
"Apache-2.0"
] | permissive | reissnda/AutomataConformance | 62390ba793dae9dfe7a85d6b279cb225a5c628ba | b8a232a4129444697a4ae28f2a484b4a8dbbb58a | refs/heads/master | 2022-02-27T11:44:07.915837 | 2022-01-30T08:56:06 | 2022-01-30T08:56:06 | 253,990,164 | 1 | 5 | Apache-2.0 | 2021-07-26T01:17:55 | 2020-04-08T05:04:03 | HTML | UTF-8 | Java | false | false | 3,610 | java | package org.processmining.plugins.neconformance.bags.naieve;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.deckfour.xes.classification.XEventClass;
import org.deckfour.xes.classification.XEventClasses;
import org.deckfour.xes.classification.XEventClassifier;
import org.deckfour.xes.info.impl.XLogInfoImpl;
import org.deckfour.xes.model.XLog;
import org.deckfour.xes.model.XTrace;
import org.processmining.plugins.neconformance.bags.LogBag;
public class NaieveLogBag implements LogBag {
private XLog log;
private XEventClassifier classifier;
private int windowSize;
List<XEventClass> eventClasses;
Map<String, Set<BitSet>> bagsPerClass;
public NaieveLogBag(XLog log) {
this(log, XLogInfoImpl.STANDARD_CLASSIFIER, -1);
}
public NaieveLogBag(XLog log, XEventClassifier classifier) {
this(log, classifier, -1);
}
public NaieveLogBag(XLog log, XEventClassifier classifier, int windowSize) {
this.log = log;
this.classifier = classifier;
this.windowSize = windowSize;
constructLookupTable();
}
private void constructLookupTable() {
eventClasses = new ArrayList<XEventClass>(XEventClasses.deriveEventClasses(classifier, log).getClasses());
bagsPerClass = new HashMap<String, Set<BitSet>>();
for (XEventClass ec : eventClasses)
bagsPerClass.put(ec.toString(), new HashSet<BitSet>());
for (int t = 0; t < log.size(); t++) {
XTrace trace = log.get(t);
for (int startIndex = 0; startIndex < trace.size(); startIndex++) {
String eventClassP = classifier.getClassIdentity(trace.get(startIndex));
BitSet eventBag = getEventBagBeforePosition(trace, startIndex);
bagsPerClass.get(eventClassP).add(eventBag);
}
}
}
public int getLargestSharedBagSize(Set<String> window, String entryClass) {
BitSet windowBag = getEventBag(window);
int largestShared = -1;
for (BitSet eventBag : bagsPerClass.get(entryClass)) {
BitSet andWindowBag = (BitSet) windowBag.clone();
andWindowBag.and(eventBag);
int shared = andWindowBag.cardinality();
if (shared > largestShared)
largestShared = shared;
if (largestShared == window.size())
return largestShared;
}
return largestShared;
}
public int getSmallestSharedSize(Set<String> window, String entryClass) {
BitSet windowBag = getEventBag(window);
int smallestShared = -1;
for (BitSet eventBag : bagsPerClass.get(entryClass)) {
BitSet andWindowBag = (BitSet) windowBag.clone();
andWindowBag.and(eventBag);
int shared = andWindowBag.cardinality();
if (shared < smallestShared || smallestShared == -1)
smallestShared = shared;
if (smallestShared == 0)
return smallestShared;
}
return smallestShared;
}
private BitSet getEventBagBeforePosition(XTrace trace, int position) {
Set<String> eventBag = new HashSet<String>();
int startPos = position - windowSize;
if (windowSize < 0 || startPos < 0) startPos = 0;
for (int checkPos = position-1; checkPos >= startPos; checkPos--) {
String eventClassP = classifier.getClassIdentity(trace.get(checkPos));
eventBag.add(eventClassP);
}
return getEventBag(eventBag);
}
private BitSet getEventBag(Set<String> window) {
BitSet bitBag = new BitSet(eventClasses.size());
for (int i = 0; i < eventClasses.size(); i++) {
if (window.contains(eventClasses.get(i).toString())) {
bitBag.set(i, true);
}
}
return bitBag;
}
}
| [
"dreissner@student.unimelb.edu.au"
] | dreissner@student.unimelb.edu.au |
3e735dcd890cab37baac30cba48cd91c85f5dc69 | 8f42eba18845f4b92b7c2b070ae9eeccea969b21 | /springboot-1/src/main/java/com/example/demo/pojo/Cat.java | 86ea82fc12243e6fd663977211cb08a71c724e3d | [] | no_license | ctscts123/Test | bb6d1fa5088c38b77633368fa7f9ce6f6493c648 | de0edb5e26f04c622567d5602bb4c3b219a72dfa | refs/heads/master | 2020-04-30T15:00:22.005179 | 2019-04-22T12:26:11 | 2019-04-22T12:26:11 | 176,907,957 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 235 | java | package com.example.demo.pojo;
import lombok.Data;
import lombok.experimental.Accessors;
@Data
@Accessors(chain = true)
public class Cat {
private Integer id;
private String catName;
private Integer age;
}
| [
"cts@my"
] | cts@my |
851cfb5e8045094ba3b49a2ae1ccc26b7da98cea | 995f73d30450a6dce6bc7145d89344b4ad6e0622 | /P9-8.0/src/main/java/com/android/server/wifi/HwWifiConnectivityMonitor.java | 8c643013f194f52b8aa899681231ae3313cef25e | [] | no_license | morningblu/HWFramework | 0ceb02cbe42585d0169d9b6c4964a41b436039f5 | 672bb34094b8780806a10ba9b1d21036fd808b8e | refs/heads/master | 2023-07-29T05:26:14.603817 | 2021-09-03T05:23:34 | 2021-09-03T05:23:34 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 37,193 | java | package com.android.server.wifi;
import android.common.HwFrameworkFactory;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Message;
import android.os.PowerManager;
import android.os.SystemProperties;
import android.util.Log;
import android.view.WindowManagerPolicy;
import com.android.internal.util.State;
import com.android.internal.util.StateMachine;
import com.android.server.LocalServices;
import com.android.server.policy.AbsPhoneWindowManager;
import com.android.server.wifi.HwQoE.HwQoEService;
import com.android.server.wifi.wifipro.PortalAutoFillManager;
import com.android.server.wifi.wifipro.WifiHandover;
import com.android.server.wifi.wifipro.WifiProStateMachine;
import com.android.server.wifi.wifipro.WifiproUtils;
import com.android.server.wifipro.WifiProCommonUtils;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
public class HwWifiConnectivityMonitor extends StateMachine {
public static final String ACTION_11v_ROAMING_NETWORK_FOUND = "com.huawei.wifi.action.11v_ROAMING_NETWORK_FOUND";
private static final int BAD_AVE_RTT = 800;
private static final int CMD_11v_ROAMING_TIMEOUT = 108;
private static final int CMD_BG_WIFI_LINK_STATUS = 113;
private static final int CMD_DISCONNECT_POOR_LINK = 105;
private static final int CMD_LEAVE_POOR_WIFI_LINK = 110;
private static final int CMD_NETWORK_CONNECTED_RCVD = 101;
private static final int CMD_NETWORK_DISCONNECTED_RCVD = 102;
private static final int CMD_NEW_RSSI_RCVD = 104;
private static final int CMD_QUERY_11v_ROAMING_NETWORK = 103;
private static final int CMD_REQUEST_ROAMING_NETWORK = 109;
private static final int CMD_ROAMING_COMPLETED_RCVD = 107;
private static final int CMD_ROAMING_STARTED_RCVD = 106;
private static final int CMD_TOP_UID_INTERNET_STATUS = 112;
private static final int CMD_USER_MOVE_DETECTED = 111;
private static final int CMD_VERIFY_WIFI_LINK_STATE = 114;
private static final int CURR_UID_INTERNET_BAD = 1;
private static final int CURR_UID_INTERNET_GOOD = 0;
private static final int CURR_UID_INTERNET_VERY_BAD = 2;
private static final int[] DELAYED_MS_TABLE = new int[]{2000, 4000, 10000, HwQoEService.KOG_CHECK_FG_APP_PERIOD, 0};
private static final int GOOD_LINK_MONITOR_MS = 8000;
private static final float LESS_PKTS_BAD_RATE = 0.3f;
private static final float LESS_PKTS_VERY_BAD_RATE = 0.4f;
private static final int MIN_RX_PKTS = 100;
private static final int MIN_TX_PKTS = 3;
private static final float MORE_PKTS_BAD_RATE = 0.2f;
private static final float MORE_PKTS_VERY_BAD_RATE = 0.3f;
private static final int MORE_TX_PKTS = 20;
private static final int POOR_LINK_MONITOR_MS = 4000;
private static final String PROP_DISABLE_AUTO_DISC = "hw.wifi.disable_auto_disc";
private static final int QUERY_11v_ROAMING_NETWORK_DELAYED_MS = 5000;
private static final int QUERY_REASON_LOW_RSSI = 16;
private static final int QUERY_REASON_PREFERRED_BSS = 19;
private static final int ROAMING_11v_NETWORK_TIMEOUT_MS = 8000;
private static final int SIGNAL_LEVEL_0 = 0;
private static final int SIGNAL_LEVEL_1 = 1;
private static final int SIGNAL_LEVEL_2 = 2;
private static final int SIGNAL_LEVEL_3 = 3;
private static final int SIGNAL_LEVEL_4 = 4;
private static final int STEP_INCREASE_THRESHOLD = 10;
private static final String TAG = "HwWifiConnectivityMonitor";
private static final float TX_GOOD_RATE = 0.3f;
private static final String[] URGENT_APP_PKT_NAME = new String[]{PortalAutoFillManager.BROWSER_PACKET_NAME, "com.UCMobile", "com.tencent.mtt", "com.netease.newsreader.activity", "com.ss.android.article.news", "com.sina.news", "com.tencent.news", "com.sohu.newsclient", "com.ifeng.news2", "com.android.chrome", "com.myzaker.ZAKER_Phone", "com.sina.weibo", "com.hexin.plat.android", "com.android.email", "com.google.android.gm", "com.huawei.works"};
private static final String[] URGENT_MINI_APP_PKT_NAME = new String[]{"com.tencent.mm", "com.tencent.mobileqq", "com.eg.android.AlipayGphone", "com.sdu.didi.psnger", "com.szzc.ucar.pilot", "com.ichinait.gbpassenger", "com.mobike.mobikeapp", "so.ofo.labofo", "com.baidu.BaiduMap", "com.autonavi.minimap", "com.google.android.apps.maps", "com.huawei.health", "com.huawei.espacev2", "com.baidu.searchbox", "com.whatsapp", "com.facebook.katana"};
private static final int VERY_BAD_AVE_RTT = 1200;
private static HwWifiConnectivityMonitor mWifiConnectivityMonitor = null;
private AtomicBoolean mAccSensorRegistered = new AtomicBoolean(false);
private State mConnectedMonitorState = new ConnectedMonitorState();
private Context mContext;
private State mDefaultState = new DefaultState();
private State mDisconnectedMonitorState = new DisconnectedMonitorState();
private boolean mInitialized = false;
private PowerManager mPowerManager;
private final StepSensorEventListener mSensorEventListener = new StepSensorEventListener();
private SensorManager mSensorManager;
private Sensor mStepCntSensor;
private WifiManager mWifiManager;
private WifiNative mWifiNative;
class ConnectedMonitorState extends State {
private int m11vRoamingFailedCounter;
private boolean m11vRoamingOnGoing;
private WifiConfiguration mConnectedConfig = null;
private int mCurrMonitorTopUid = -1;
private int mCurrRssiVal;
private int mCurrTopUidBadCnt = 0;
private int mCurrTopUidVeryBadCnt = 0;
private boolean mEnterVerifyLinkState = false;
private long mLast11vRoamingFailedTs;
private int mLastSignalLevel;
private int mPoorLinkRssi = WifiHandover.INVALID_RSSI;
private boolean mRoamingOnGoing;
private int mRssiBeforeSwitchWifi = WifiHandover.INVALID_RSSI;
private int mRssiGoodCnt = 0;
private int mStrongRssiCnt = 0;
ConnectedMonitorState() {
}
public void enter() {
HwWifiConnectivityMonitor.this.LOGD("###ConnectedMonitorState, enter()");
this.mRoamingOnGoing = false;
this.m11vRoamingOnGoing = false;
this.m11vRoamingFailedCounter = 0;
this.mLast11vRoamingFailedTs = 0;
this.mConnectedConfig = WifiProCommonUtils.getCurrentWifiConfig(HwWifiConnectivityMonitor.this.mWifiManager);
this.mEnterVerifyLinkState = false;
this.mRssiGoodCnt = 0;
this.mStrongRssiCnt = 0;
this.mRssiBeforeSwitchWifi = WifiHandover.INVALID_RSSI;
this.mPoorLinkRssi = WifiHandover.INVALID_RSSI;
this.mCurrTopUidBadCnt = 0;
this.mCurrTopUidVeryBadCnt = 0;
this.mCurrMonitorTopUid = -1;
WifiInfo wifiInfo = HwWifiConnectivityMonitor.this.mWifiManager.getConnectionInfo();
if (wifiInfo != null) {
this.mLastSignalLevel = HwFrameworkFactory.getHwInnerWifiManager().calculateSignalLevelHW(wifiInfo.getRssi());
this.mCurrRssiVal = wifiInfo.getRssi();
HwWifiConnectivityMonitor.this.LOGD("ConnectedMonitorState, network = " + wifiInfo.getSSID() + ", 802.11v = " + is11vNetworkConnected() + ", 2.4GHz = " + wifiInfo.is24GHz() + ", current level = " + this.mLastSignalLevel);
if (!is11vNetworkConnected()) {
return;
}
if (wifiInfo.is24GHz() || this.mLastSignalLevel <= 2) {
HwWifiConnectivityMonitor.this.sendMessageDelayed(103, 5000);
}
}
}
public boolean processMessage(Message message) {
switch (message.what) {
case 102:
HwWifiConnectivityMonitor.this.removeMessages(103);
HwWifiConnectivityMonitor.this.removeMessages(108);
HwWifiConnectivityMonitor.this.removeMessages(105);
HwWifiConnectivityMonitor.this.removeMessages(110);
HwWifiConnectivityMonitor.this.transitionTo(HwWifiConnectivityMonitor.this.mDisconnectedMonitorState);
break;
case 103:
query11vRoamingNetowrk(16);
break;
case 104:
handleNewRssiRcvd(message.arg1);
break;
case 105:
disconnectPoorWifiConnection();
break;
case 106:
if (HwWifiConnectivityMonitor.this.hasMessages(105)) {
HwWifiConnectivityMonitor.this.LOGD("CMD_DISCONNECT_POOR_LINK remove due to roaming received.");
HwWifiConnectivityMonitor.this.removeMessages(105);
}
this.mRoamingOnGoing = true;
break;
case 107:
if (HwWifiConnectivityMonitor.this.hasMessages(108)) {
HwWifiConnectivityMonitor.this.LOGD("CMD_11v_ROAMING_TIMEOUT remove due to roaming completed received.");
HwWifiConnectivityMonitor.this.removeMessages(108);
}
this.mRoamingOnGoing = false;
this.m11vRoamingOnGoing = false;
this.m11vRoamingFailedCounter = 0;
this.mLast11vRoamingFailedTs = 0;
break;
case 108:
if (HwWifiConnectivityMonitor.this.hasMessages(103)) {
HwWifiConnectivityMonitor.this.removeMessages(103);
}
this.m11vRoamingOnGoing = false;
this.m11vRoamingFailedCounter++;
this.mLast11vRoamingFailedTs = System.currentTimeMillis();
HwWifiConnectivityMonitor.this.LOGD("CMD_11v_ROAMING_TIMEOUT received, counter = " + this.m11vRoamingFailedCounter + ", ts = " + DateFormat.getDateTimeInstance().format(new Date(this.mLast11vRoamingFailedTs)));
if (this.mLastSignalLevel == 0) {
disconnectPoorWifiConnection();
break;
}
break;
case 109:
if (is11vNetworkConnected() && this.m11vRoamingFailedCounter <= 1) {
if (HwWifiConnectivityMonitor.this.hasMessages(103)) {
HwWifiConnectivityMonitor.this.removeMessages(103);
}
query11vRoamingNetowrk(16);
break;
}
case 110:
handleSignalPoorLevelOne();
break;
case 111:
if (this.mLastSignalLevel <= 1) {
handleUserMoveDetected();
break;
}
break;
case 112:
handleTopUidInternetStatusChanged(message.arg1, message.arg2);
switchWifiNetworkQuickly();
break;
case 113:
handleBgWifiLinkStatusChanged(message.arg1, ((Boolean) message.obj).booleanValue());
break;
case 114:
boolean newState = ((Boolean) message.obj).booleanValue();
HwWifiConnectivityMonitor.this.LOGD("CMD_VERIFY_WIFI_LINK_STATE, newState = " + newState + ", oldState = " + this.mEnterVerifyLinkState + ", mPoorLinkRssi = " + this.mPoorLinkRssi);
if (!(newState && this.mEnterVerifyLinkState) && ((newState || (this.mEnterVerifyLinkState ^ 1) == 0) && this.mPoorLinkRssi != WifiHandover.INVALID_RSSI)) {
this.mEnterVerifyLinkState = newState;
this.mRssiGoodCnt = 0;
this.mStrongRssiCnt = 0;
if (!this.mEnterVerifyLinkState) {
this.mRssiBeforeSwitchWifi = WifiHandover.INVALID_RSSI;
this.mPoorLinkRssi = WifiHandover.INVALID_RSSI;
break;
}
this.mRssiBeforeSwitchWifi = this.mPoorLinkRssi;
break;
}
default:
return false;
}
return true;
}
private void handleTopUidInternetStatusChanged(int uid, int status) {
HwWifiConnectivityMonitor.this.LOGD("handleTopUidInternetStatusChanged, uid = " + uid + ", status = " + status);
if (this.mCurrMonitorTopUid == -1 || uid == -1 || uid == this.mCurrMonitorTopUid) {
this.mCurrMonitorTopUid = uid;
if (status == 0) {
this.mCurrTopUidVeryBadCnt = 0;
this.mCurrTopUidBadCnt = 0;
} else if (status == 1) {
this.mCurrTopUidBadCnt++;
} else if (status == 2) {
this.mCurrTopUidVeryBadCnt++;
}
return;
}
this.mCurrMonitorTopUid = uid;
if (status == 0) {
this.mCurrTopUidVeryBadCnt = 0;
this.mCurrTopUidBadCnt = 0;
} else if (status == 1) {
this.mCurrTopUidBadCnt = 1;
this.mCurrTopUidVeryBadCnt = 0;
} else if (status == 2) {
this.mCurrTopUidVeryBadCnt = 1;
this.mCurrTopUidBadCnt = 0;
}
}
/* JADX WARNING: Missing block: B:4:0x0018, code:
return;
*/
/* Code decompiled incorrectly, please refer to instructions dump. */
private void switchWifiNetworkQuickly() {
if (this.mCurrMonitorTopUid != -1 && this.mCurrMonitorTopUid == WifiProCommonUtils.getForegroundAppUid(HwWifiConnectivityMonitor.this.mContext) && !HwWifiConnectivityMonitor.this.isMobileDataInactive() && (HwWifiConnectivityMonitor.this.mPowerManager.isScreenOn() ^ 1) == 0 && !HwWifiConnectivityMonitor.this.isFullScreen() && !WifiProCommonUtils.isLandscapeMode(HwWifiConnectivityMonitor.this.mContext)) {
String pktName = WifiProCommonUtils.getPackageName(HwWifiConnectivityMonitor.this.mContext, this.mCurrMonitorTopUid);
WifiInfo wifiInfo = HwWifiConnectivityMonitor.this.mWifiManager.getConnectionInfo();
if (wifiInfo != null) {
this.mCurrRssiVal = wifiInfo.getRssi();
if (this.mLastSignalLevel <= 1) {
if (this.mCurrTopUidBadCnt >= 1 || this.mCurrTopUidVeryBadCnt >= 1) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 1, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt);
notifyWifiLinkPoor(true);
}
} else if (this.mLastSignalLevel == 2) {
if (WifiProCommonUtils.isInMonitorList(pktName, HwWifiConnectivityMonitor.URGENT_MINI_APP_PKT_NAME)) {
if (this.mCurrTopUidVeryBadCnt >= 1 || this.mCurrTopUidBadCnt >= 1) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 2, URGENT_MINI, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt);
notifyWifiLinkPoor(true);
}
return;
} else if (WifiProCommonUtils.isWpaOrWpa2(this.mConnectedConfig)) {
if (this.mCurrTopUidBadCnt >= 2 || this.mCurrTopUidVeryBadCnt >= 2 || (this.mCurrTopUidBadCnt == 1 && this.mCurrTopUidVeryBadCnt == 1)) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 2, WPA2, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt);
notifyWifiLinkPoor(true);
}
} else if (WifiProCommonUtils.isInMonitorList(pktName, HwWifiConnectivityMonitor.URGENT_APP_PKT_NAME)) {
if (this.mCurrTopUidBadCnt >= 1 || this.mCurrTopUidVeryBadCnt >= 1) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 2, URGENT, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt);
notifyWifiLinkPoor(true);
}
} else if (this.mCurrTopUidBadCnt >= 2 || this.mCurrTopUidVeryBadCnt >= 2 || (this.mCurrTopUidBadCnt == 1 && this.mCurrTopUidVeryBadCnt == 1)) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 2, NORMAL, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt);
notifyWifiLinkPoor(true);
}
} else if (this.mLastSignalLevel != 3 || this.mCurrRssiVal > -70) {
if (this.mCurrRssiVal > -70 && WifiProCommonUtils.isOpenType(this.mConnectedConfig) && (this.mCurrTopUidVeryBadCnt >= 3 || (this.mCurrTopUidBadCnt == 1 && this.mCurrTopUidVeryBadCnt == 2))) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 4, NORMAL, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt + ", rssi = " + this.mCurrRssiVal);
notifyWifiLinkPoor(true);
}
} else if ((this.mCurrTopUidBadCnt >= 2 && this.mCurrTopUidVeryBadCnt >= 1) || this.mCurrTopUidVeryBadCnt >= 2) {
HwWifiConnectivityMonitor.this.LOGD("signal level = 3, NORMAL, and bad cnt = " + this.mCurrTopUidBadCnt + ", very bad cnt = " + this.mCurrTopUidVeryBadCnt + ", rssi = " + this.mCurrRssiVal);
notifyWifiLinkPoor(true);
}
return;
}
HwWifiConnectivityMonitor.this.LOGD("switchWifiNetworkQuickly, can't get rssi from wifi info!");
}
}
private void handleBgWifiLinkStatusChanged(int currentRssi, boolean txGood) {
if (this.mEnterVerifyLinkState && this.mRssiBeforeSwitchWifi != WifiHandover.INVALID_RSSI) {
if (!txGood) {
this.mRssiGoodCnt = 0;
this.mStrongRssiCnt = 0;
}
if (this.mRssiBeforeSwitchWifi >= -65 || currentRssi < -65) {
this.mStrongRssiCnt = 0;
} else if (currentRssi - this.mRssiBeforeSwitchWifi >= 5) {
this.mStrongRssiCnt++;
} else {
this.mStrongRssiCnt = 0;
}
if (currentRssi - this.mRssiBeforeSwitchWifi >= 8) {
this.mRssiGoodCnt++;
} else {
this.mRssiGoodCnt = 0;
}
if (this.mStrongRssiCnt == 6 || this.mRssiGoodCnt == 16) {
HwWifiConnectivityMonitor.this.LOGD("handleBgWifiLinkStatusChanged, notify switch back to stable wifi, curr rssi = " + currentRssi + ", last rssi = " + this.mRssiBeforeSwitchWifi + ", strong cnt = " + this.mStrongRssiCnt + ", good cnt = " + this.mRssiGoodCnt);
notifyWifiLinkPoor(false);
this.mRssiGoodCnt = 0;
this.mStrongRssiCnt = 0;
}
}
}
private void handleNewRssiRcvd(int newRssi) {
this.mCurrRssiVal = newRssi;
int currentSignalLevel = HwFrameworkFactory.getHwInnerWifiManager().calculateSignalLevelHW(newRssi);
if (currentSignalLevel >= 0 && currentSignalLevel != this.mLastSignalLevel) {
HwWifiConnectivityMonitor.this.LOGD("signal level changed: " + this.mLastSignalLevel + " --> " + currentSignalLevel + ", 802.11v = " + is11vNetworkConnected());
if (currentSignalLevel == 2) {
HwWifiConnectivityMonitor.this.registerStepCntSensor();
} else if (currentSignalLevel == 1) {
HwWifiConnectivityMonitor.this.registerStepCntSensor();
HwWifiConnectivityMonitor.this.sendMessageDelayed(110, 4000);
} else if (currentSignalLevel == 4) {
HwWifiConnectivityMonitor.this.unregisterStepCntSensor();
}
if (currentSignalLevel == 0 && (HwWifiConnectivityMonitor.this.hasMessages(105) ^ 1) != 0) {
HwWifiConnectivityMonitor.this.sendMessageDelayed(105, 4000);
} else if (currentSignalLevel >= 2) {
HwWifiConnectivityMonitor.this.removeMessages(105);
HwWifiConnectivityMonitor.this.removeMessages(110);
} else if (currentSignalLevel > 0) {
HwWifiConnectivityMonitor.this.removeMessages(105);
}
if (is11vNetworkConnected() && (this.m11vRoamingOnGoing ^ 1) != 0 && currentSignalLevel <= 2 && this.m11vRoamingFailedCounter <= 1) {
if (HwWifiConnectivityMonitor.this.hasMessages(103)) {
HwWifiConnectivityMonitor.this.removeMessages(103);
}
HwWifiConnectivityMonitor.this.LOGD("to delay " + HwWifiConnectivityMonitor.DELAYED_MS_TABLE[currentSignalLevel] + " ms to request roaming 802.11v network.");
HwWifiConnectivityMonitor.this.sendMessageDelayed(103, (long) HwWifiConnectivityMonitor.DELAYED_MS_TABLE[currentSignalLevel]);
}
}
this.mLastSignalLevel = currentSignalLevel;
}
private void disconnectPoorWifiConnection() {
boolean isRoaming;
if (this.mRoamingOnGoing || this.m11vRoamingOnGoing) {
isRoaming = true;
} else {
isRoaming = HwWifiConnectivityMonitor.this.hasMessages(103);
}
boolean disableAutoDisconnect = SystemProperties.getBoolean(HwWifiConnectivityMonitor.PROP_DISABLE_AUTO_DISC, false);
HwWifiConnectivityMonitor.this.LOGD("disconnectPoorWifiConnection, isRoaming = " + isRoaming + ", isFullScreen = " + HwWifiConnectivityMonitor.this.isFullScreen());
if (HwWifiConnectivityMonitor.this.mWifiManager != null && (disableAutoDisconnect ^ 1) != 0) {
if (((!HwWifiConnectivityMonitor.this.isFullScreen() && (WifiProCommonUtils.isLandscapeMode(HwWifiConnectivityMonitor.this.mContext) ^ 1) != 0) || HwWifiConnectivityMonitor.this.isNeedDiscInGame()) && (HwWifiConnectivityMonitor.this.isMobileDataInactive() ^ 1) != 0 && (WifiProCommonUtils.isCalling(HwWifiConnectivityMonitor.this.mContext) ^ 1) != 0) {
HwWifiConnectivityMonitor.this.LOGD("WARN: to auto disconnect network quickly due to poor rssi and no roaming (signal level = 0)");
HwWifiConnectivityMonitor.this.mWifiManager.disconnect();
}
}
}
private void query11vRoamingNetowrk(int reason) {
HwWifiConnectivityMonitor.this.LOGD("query11vRoamingNetowrk, mRoamingOnGoing = " + this.mRoamingOnGoing + ", m11vRoamingOnGoing = " + this.m11vRoamingOnGoing);
if (!this.mRoamingOnGoing && (this.m11vRoamingOnGoing ^ 1) != 0) {
HwWifiConnectivityMonitor.this.mWifiNative.query11vRoamingNetwork(reason);
this.m11vRoamingOnGoing = true;
if (HwWifiConnectivityMonitor.this.hasMessages(108)) {
HwWifiConnectivityMonitor.this.removeMessages(108);
}
HwWifiConnectivityMonitor.this.sendMessageDelayed(108, 8000);
}
}
private boolean is11vNetworkConnected() {
String currentBssid = WifiProCommonUtils.getCurrentBssid(HwWifiConnectivityMonitor.this.mWifiManager);
if (!(HwWifiConnectivityMonitor.this.mWifiManager == null || currentBssid == null)) {
List<ScanResult> scanResults = WifiproUtils.getScanResultsFromWsm();
if (scanResults != null) {
for (ScanResult scanResult : scanResults) {
if (currentBssid.equals(scanResult.BSSID) && scanResult.dot11vNetwork) {
return true;
}
}
}
}
return false;
}
private void handleSignalPoorLevelOne() {
if (this.mConnectedConfig != null && !WifiProCommonUtils.isWpaOrWpa2(this.mConnectedConfig) && (HwWifiConnectivityMonitor.this.isMobileDataInactive() ^ 1) != 0 && (WifiProCommonUtils.isCalling(HwWifiConnectivityMonitor.this.mContext) ^ 1) != 0 && HwWifiConnectivityMonitor.this.mPowerManager.isScreenOn()) {
if (HwUidTcpMonitor.getInstance(HwWifiConnectivityMonitor.this.mContext).isAppAccessInternet(WifiProCommonUtils.getForegroundAppUid(HwWifiConnectivityMonitor.this.mContext))) {
notifyWifiLinkPoor(true);
}
}
}
private void handleUserMoveDetected() {
HwWifiConnectivityMonitor.this.LOGD("handleUserMoveDetected, isScreenOn = " + HwWifiConnectivityMonitor.this.mPowerManager.isScreenOn() + ", isMobileDataInactive = " + HwWifiConnectivityMonitor.this.isMobileDataInactive() + ", isFullScreen = " + HwWifiConnectivityMonitor.this.isFullScreen());
if (HwWifiConnectivityMonitor.this.mPowerManager.isScreenOn() && (HwWifiConnectivityMonitor.this.isMobileDataInactive() ^ 1) != 0 && (HwWifiConnectivityMonitor.this.isFullScreen() ^ 1) != 0 && (WifiProCommonUtils.isCalling(HwWifiConnectivityMonitor.this.mContext) ^ 1) != 0 && (WifiProCommonUtils.isLandscapeMode(HwWifiConnectivityMonitor.this.mContext) ^ 1) != 0) {
if (HwUidTcpMonitor.getInstance(HwWifiConnectivityMonitor.this.mContext).isAppAccessInternet(WifiProCommonUtils.getForegroundAppUid(HwWifiConnectivityMonitor.this.mContext))) {
notifyWifiLinkPoor(true);
HwWifiConnectivityMonitor.this.unregisterStepCntSensor();
}
}
}
private void notifyWifiLinkPoor(boolean poorLink) {
WifiProStateMachine wifiProStateMachine = WifiProStateMachine.getWifiProStateMachineImpl();
if (wifiProStateMachine != null) {
if (poorLink) {
this.mPoorLinkRssi = this.mCurrRssiVal;
}
wifiProStateMachine.notifyWifiLinkPoor(poorLink);
}
}
}
static class DefaultState extends State {
DefaultState() {
}
public boolean processMessage(Message message) {
int i = message.what;
return true;
}
}
class DisconnectedMonitorState extends State {
DisconnectedMonitorState() {
}
public void enter() {
HwWifiConnectivityMonitor.this.LOGD("###DisconnectedMonitorState, enter()");
HwWifiConnectivityMonitor.this.unregisterStepCntSensor();
}
public boolean processMessage(Message message) {
switch (message.what) {
case 101:
HwWifiConnectivityMonitor.this.transitionTo(HwWifiConnectivityMonitor.this.mConnectedMonitorState);
return true;
default:
return false;
}
}
}
class StepSensorEventListener implements SensorEventListener {
private int mLastStepCnt = 0;
private int mMotionDetectedCnt = 0;
private long mSensorEventRcvdTs = -1;
public void reset() {
this.mLastStepCnt = 0;
this.mMotionDetectedCnt = 0;
this.mSensorEventRcvdTs = -1;
}
public void onSensorChanged(SensorEvent event) {
if (event != null && event.sensor != null && event.sensor.getType() == 19) {
long currentTimestamp = System.currentTimeMillis();
int currentStepCnt = (int) event.values[0];
if (currentStepCnt - this.mLastStepCnt > 0) {
this.mMotionDetectedCnt++;
if (this.mMotionDetectedCnt == 10) {
Log.d(HwWifiConnectivityMonitor.TAG, "SensorEventListener:: USER's MOVING......");
this.mMotionDetectedCnt = 0;
HwWifiConnectivityMonitor.this.sendMessage(111);
}
} else if (this.mSensorEventRcvdTs > 0 && currentTimestamp - this.mSensorEventRcvdTs > 2000) {
this.mMotionDetectedCnt = 0;
}
this.mLastStepCnt = currentStepCnt;
this.mSensorEventRcvdTs = currentTimestamp;
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(HwWifiConnectivityMonitor.TAG, "SensorEventListener::onAccuracyChanged, accuracy = " + accuracy);
}
}
public static synchronized HwWifiConnectivityMonitor getInstance(Context context, WifiStateMachine wsm) {
HwWifiConnectivityMonitor hwWifiConnectivityMonitor;
synchronized (HwWifiConnectivityMonitor.class) {
if (mWifiConnectivityMonitor == null) {
mWifiConnectivityMonitor = new HwWifiConnectivityMonitor(context, wsm);
}
hwWifiConnectivityMonitor = mWifiConnectivityMonitor;
}
return hwWifiConnectivityMonitor;
}
public static synchronized HwWifiConnectivityMonitor getInstance() {
HwWifiConnectivityMonitor hwWifiConnectivityMonitor;
synchronized (HwWifiConnectivityMonitor.class) {
hwWifiConnectivityMonitor = mWifiConnectivityMonitor;
}
return hwWifiConnectivityMonitor;
}
private HwWifiConnectivityMonitor(Context context, WifiStateMachine wsm) {
super(TAG);
this.mContext = context;
this.mWifiManager = (WifiManager) this.mContext.getSystemService("wifi");
this.mWifiNative = WifiInjector.getInstance().getWifiNative();
this.mPowerManager = (PowerManager) context.getSystemService("power");
this.mSensorManager = (SensorManager) this.mContext.getSystemService("sensor");
this.mStepCntSensor = this.mSensorManager.getDefaultSensor(19);
addState(this.mDefaultState);
addState(this.mConnectedMonitorState, this.mDefaultState);
addState(this.mDisconnectedMonitorState, this.mDefaultState);
setInitialState(this.mDisconnectedMonitorState);
start();
}
public synchronized void setup() {
if (!this.mInitialized) {
this.mInitialized = true;
LOGD("setup DONE!");
registerReceivers();
}
}
public void registerReceivers() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.STATE_CHANGE");
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
intentFilter.addAction("android.net.wifi.RSSI_CHANGED");
intentFilter.addAction(ACTION_11v_ROAMING_NETWORK_FOUND);
this.mContext.registerReceiver(new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if ("android.net.wifi.STATE_CHANGE".equals(intent.getAction())) {
NetworkInfo info = (NetworkInfo) intent.getParcelableExtra("networkInfo");
if (info != null && info.getDetailedState() == DetailedState.DISCONNECTED) {
HwWifiConnectivityMonitor.this.sendMessage(102);
} else if (info != null && info.getDetailedState() == DetailedState.CONNECTED) {
HwWifiConnectivityMonitor.this.sendMessage(101);
}
} else if ("android.net.wifi.RSSI_CHANGED".equals(intent.getAction())) {
int newRssi = intent.getIntExtra("newRssi", -127);
if (newRssi != -127) {
HwWifiConnectivityMonitor.this.sendMessage(104, newRssi, 0);
}
}
}
}, intentFilter);
}
private boolean isFullScreen() {
AbsPhoneWindowManager policy = (AbsPhoneWindowManager) LocalServices.getService(WindowManagerPolicy.class);
return policy != null ? policy.isTopIsFullscreen() : false;
}
private boolean isNeedDiscInGame() {
if (HwQoEService.getInstance() != null) {
return HwQoEService.getInstance().isInGameAndNeedDisc();
}
return false;
}
private void registerStepCntSensor() {
if (!this.mAccSensorRegistered.get()) {
LOGD("registerStepCntSensor, mSensorEventListener");
this.mSensorEventListener.reset();
this.mSensorManager.registerListener(this.mSensorEventListener, this.mStepCntSensor, 3);
this.mAccSensorRegistered.set(true);
}
}
private void unregisterStepCntSensor() {
if (this.mAccSensorRegistered.get() && this.mSensorEventListener != null) {
LOGD("unregisterStepCntSensor, mSensorEventListener");
this.mSensorManager.unregisterListener(this.mSensorEventListener);
this.mAccSensorRegistered.set(false);
}
}
public synchronized void notifyTopUidTcpInfo(int uid, int tx, int rx, int reTx, int rtt, int rttPkts) {
if (this.mInitialized && uid != -1 && tx > 0) {
float tr = ((float) reTx) / ((float) tx);
LOGD("ENTER: notifyTopUidTcpInfo, tx = " + tx + ", rx = " + rx + ", reTx = " + reTx + ", uid = " + uid + ", tr = " + tr);
float aveRtt = 0.0f;
if (rtt > 0 && rttPkts > 0) {
aveRtt = ((float) rtt) / ((float) rttPkts);
}
LOGD("ENTER: notifyTopUidTcpInfo, rtt = " + rtt + ", rttPkts = " + rttPkts + ", aveRtt = " + aveRtt + ", app = " + WifiProCommonUtils.getPackageName(this.mContext, uid));
if ((tr >= 0.3f && tx >= 20 && rx <= 100) || (tr >= 0.4f && tx < 20 && tx >= 3 && rx <= 200)) {
sendMessage(112, uid, 2);
} else if ((tr >= MORE_PKTS_BAD_RATE && tx >= 20 && rx <= 100) || (tr >= 0.3f && tx < 20 && tx >= 3 && rx <= 200)) {
sendMessage(112, uid, 1);
} else if (aveRtt > 1200.0f) {
sendMessage(112, uid, 2);
} else if (aveRtt > 800.0f) {
sendMessage(112, uid, 1);
} else if (rx > 1) {
sendMessage(112, uid, 0);
}
}
}
public synchronized void notifyBackgroundWifiLinkInfo(int rssi, int txgood, int txbad, int rxgood) {
if (this.mInitialized && txgood > 0) {
if (((float) txbad) / ((float) (txbad + txgood)) < 0.3f) {
sendMessage(113, rssi, 0, Boolean.valueOf(true));
} else {
sendMessage(113, rssi, 0, Boolean.valueOf(false));
}
}
}
public synchronized void notifyWifiRoamingStarted() {
LOGD("ENTER: notifyWifiRoamingStarted()");
if (this.mInitialized) {
sendMessage(106);
}
}
public synchronized void notifyWifiRoamingCompleted() {
LOGD("ENTER: notifyWifiRoamingCompleted()");
if (this.mInitialized) {
sendMessage(107);
}
}
public synchronized void requestRoamingByNoInternet() {
LOGD("ENTER: requestRoamingByNoInternet()");
if (this.mInitialized) {
sendMessage(109);
}
}
public synchronized void notifyWifiDisconnected() {
if (this.mInitialized) {
sendMessage(102);
}
}
public synchronized void notifyVerifyingLinkState(boolean enterVerifyingLinkState) {
if (this.mInitialized) {
sendMessage(114, Boolean.valueOf(enterVerifyingLinkState));
}
}
public synchronized void disconnectePoorWifi() {
if (this.mInitialized) {
sendMessage(105);
}
}
private boolean isMobileDataInactive() {
return !WifiProCommonUtils.isMobileDataOff(this.mContext) ? WifiProCommonUtils.isNoSIMCard(this.mContext) : true;
}
public void LOGD(String msg) {
Log.d(TAG, msg);
}
}
| [
"dstmath@163.com"
] | dstmath@163.com |
a37360122b07b136e424c5347b2b88998fc54aea | 883d561da84d11457402785696f4e2a746a0b5a7 | /app/src/main/java/com/example/LViewModelProviders.java | c4a456fd091a574127d86193f64ae54048eccfa7 | [] | no_license | Zhangyc1998/Rxjava_Retrofit | 423c73601d26d56ae09819aa626e030a77dcde81 | 0810fc00509d06cf851788db57f992be1e38cdbf | refs/heads/master | 2023-03-12T10:53:33.157425 | 2021-02-25T10:24:37 | 2021-02-25T10:24:37 | 342,111,360 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 736 | java | package com.example;
import com.example.basis.base.BaseViewModel;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProviders;
public class LViewModelProviders {
public static <T extends BaseViewModel> T of(@NonNull FragmentActivity activity, Class<T> modelClass) {
T t = ViewModelProviders.of(activity).get(modelClass);
t.setLifecycleOwner(activity);
return t;
}
public static <T extends BaseViewModel> T of(@NonNull Fragment activity, Class<T> modelClass) {
T t = ViewModelProviders.of(activity).get(modelClass);
t.setLifecycleOwner(activity);
return t;
}
}
| [
"1332234917@qq.com"
] | 1332234917@qq.com |
054df99f1231bf0651fc645f4e0bdfbc64b42a15 | 4ac51f07e5e4d5da395caa5cc8c3516923ef3012 | /taverna-workflowmodel-api/src/main/java/net/sf/taverna/t2/workflowmodel/processor/activity/config/ActivityPortDefinitionBean.java | 05d991f7c2285fea4d2f5cc8ef79081f3fd655c6 | [] | no_license | taverna-incubator/incubator-taverna-engine | eb2b5d2c956982696e06b9404c6b94a2346417fe | 1eca6315f88bfd19672114e3f3b574246a2994a5 | refs/heads/master | 2021-01-01T18:11:06.502122 | 2015-02-21T23:43:42 | 2015-02-21T23:43:42 | 28,545,860 | 0 | 1 | null | 2015-02-04T15:45:25 | 2014-12-27T20:40:19 | Java | UTF-8 | Java | false | false | 3,021 | java | /*******************************************************************************
* Copyright (C) 2007 The University of Manchester
*
* Modifications to the initial code base are copyright of their
* respective authors, or their employers as appropriate.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
******************************************************************************/
package net.sf.taverna.t2.workflowmodel.processor.activity.config;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import net.sf.taverna.t2.workflowmodel.processor.config.ConfigurationBean;
import net.sf.taverna.t2.workflowmodel.processor.config.ConfigurationProperty;
/**
* A generic bean that describes the shared properties of input and output
* ports.
*
* @author Stuart Owen
*
*/
@ConfigurationBean(uri = "http://ns.taverna.org.uk/2010/scufl2#PortDefinition")
public abstract class ActivityPortDefinitionBean {
private String name;
private int depth;
private List<String> mimeTypes;
/**
* @return the port name
*/
public String getName() {
return name;
}
/**
* @param name
* the port name
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the depth of the port
*/
public int getDepth() {
return depth;
}
/**
* @param depth
* the depth of the port
*/
public void setDepth(int depth) {
this.depth = depth;
}
/**
* @return a list a MIME types that describe the port
*/
public List<String> getMimeTypes() {
if (mimeTypes == null)
return Collections.emptyList();
return mimeTypes;
}
/**
* @param mimeTypes
* the list of MIME-types that describe the port
*/
public void setMimeTypes(List<String> mimeTypes) {
this.mimeTypes = mimeTypes;
}
/**
* @param mimeTypes
* the list of MIME-types that describe the port
*/
@ConfigurationProperty(name = "expectedMimeType", label = "Mime Types", description = "The MIME-types that describe the port", required = false)
public void setMimeTypes(Set<URI> mimeTypes) {
this.mimeTypes = new ArrayList<>();
for (URI uri : mimeTypes)
this.mimeTypes.add("'"
+ URI.create("http://purl.org/NET/mediatypes/").relativize(
uri) + "'");
}
}
| [
"stain@apache.org"
] | stain@apache.org |
b3c26435007d987462cc49309c6d4801bcc91e70 | 44bdb9995b5c886788f9abbeb5b50c9029aba3a5 | /oracle/apps/ap/oie/entry/header/lov/server/CuxOAAboardTravelEmpLovVORowImpl.java | 8082c288dce8a7617f1ed90229da14e7e4f6cbee | [] | no_license | alosummer/enfi | ad8cd1e5beadce88257df1aeb6cac3218019500a | 8221accfdd409bc6225d248a6b7fee5204211f73 | refs/heads/master | 2021-04-15T09:43:09.181927 | 2018-04-03T01:10:54 | 2018-04-03T01:10:54 | 126,925,232 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,990 | java | package cux.oracle.apps.ap.oie.entry.header.lov.server;
import oracle.apps.fnd.framework.server.OAViewRowImpl;
import oracle.jbo.domain.Number;
import oracle.jbo.server.AttributeDefImpl;
// ---------------------------------------------------------------------
// --- File generated by Oracle ADF Business Components Design Time.
// --- Custom code may be added to this class.
// --- Warning: Do not modify method signatures of generated methods.
// ---------------------------------------------------------------------
public class CuxOAAboardTravelEmpLovVORowImpl extends OAViewRowImpl {
public static final int EMPID = 0;
public static final int EMPNAME = 1;
public static final int EMPNUMBER = 2;
public static final int EMPDEPT = 3;
public static final int OAABROADTRAVELHEADERID = 4;
public static final int OAABROADTRAVELLINEID = 5;
/**This is the default constructor (do not remove)
*/
public CuxOAAboardTravelEmpLovVORowImpl() {
}
/**Gets the attribute value for the calculated attribute EmpId
*/
public Number getEmpId() {
return (Number)getAttributeInternal(EMPID);
}
/**Sets <code>value</code> as the attribute value for the calculated attribute EmpId
*/
public void setEmpId(Number value) {
setAttributeInternal(EMPID, value);
}
/**Gets the attribute value for the calculated attribute EmpName
*/
public String getEmpName() {
return (String)getAttributeInternal(EMPNAME);
}
/**Sets <code>value</code> as the attribute value for the calculated attribute EmpName
*/
public void setEmpName(String value) {
setAttributeInternal(EMPNAME, value);
}
/**Gets the attribute value for the calculated attribute EmpNumber
*/
public String getEmpNumber() {
return (String)getAttributeInternal(EMPNUMBER);
}
/**Sets <code>value</code> as the attribute value for the calculated attribute EmpNumber
*/
public void setEmpNumber(String value) {
setAttributeInternal(EMPNUMBER, value);
}
/**Gets the attribute value for the calculated attribute EmpDept
*/
public String getEmpDept() {
return (String)getAttributeInternal(EMPDEPT);
}
/**Sets <code>value</code> as the attribute value for the calculated attribute EmpDept
*/
public void setEmpDept(String value) {
setAttributeInternal(EMPDEPT, value);
}
/**Gets the attribute value for the calculated attribute OaAbroadTravelHeaderId
*/
public Number getOaAbroadTravelHeaderId() {
return (Number)getAttributeInternal(OAABROADTRAVELHEADERID);
}
/**Sets <code>value</code> as the attribute value for the calculated attribute OaAbroadTravelHeaderId
*/
public void setOaAbroadTravelHeaderId(Number value) {
setAttributeInternal(OAABROADTRAVELHEADERID, value);
}
/**Gets the attribute value for the calculated attribute OaAbroadTravelLineId
*/
public Number getOaAbroadTravelLineId() {
return (Number)getAttributeInternal(OAABROADTRAVELLINEID);
}
/**Sets <code>value</code> as the attribute value for the calculated attribute OaAbroadTravelLineId
*/
public void setOaAbroadTravelLineId(Number value) {
setAttributeInternal(OAABROADTRAVELLINEID, value);
}
/**getAttrInvokeAccessor: generated method. Do not modify.
*/
protected Object getAttrInvokeAccessor(int index,
AttributeDefImpl attrDef) throws Exception {
switch (index) {
case EMPID:
return getEmpId();
case EMPNAME:
return getEmpName();
case EMPNUMBER:
return getEmpNumber();
case EMPDEPT:
return getEmpDept();
case OAABROADTRAVELHEADERID:
return getOaAbroadTravelHeaderId();
case OAABROADTRAVELLINEID:
return getOaAbroadTravelLineId();
default:
return super.getAttrInvokeAccessor(index, attrDef);
}
}
/**setAttrInvokeAccessor: generated method. Do not modify.
*/
protected void setAttrInvokeAccessor(int index, Object value,
AttributeDefImpl attrDef) throws Exception {
switch (index) {
case EMPID:
setEmpId((Number)value);
return;
case EMPNAME:
setEmpName((String)value);
return;
case EMPNUMBER:
setEmpNumber((String)value);
return;
case EMPDEPT:
setEmpDept((String)value);
return;
case OAABROADTRAVELHEADERID:
setOaAbroadTravelHeaderId((Number)value);
return;
case OAABROADTRAVELLINEID:
setOaAbroadTravelLineId((Number)value);
return;
default:
super.setAttrInvokeAccessor(index, value, attrDef);
return;
}
}
}
| [
"772856742@qq.com"
] | 772856742@qq.com |
902a6b9398629d3d24e9909c98693269e787d97d | 69e80d61ba5bfea7715e8698b63ca3984d66e85b | /src/methodsandencapsulation/lambdas/Lambda3.java | 6f07057ee831aaa93588edd2a5120cc3278495b4 | [] | no_license | Arasefe/ZeroToHero | 3b40195829f0f4179c73de31543fad0252ddaad4 | bd8aaa2633d24a1a60384a511503d6afb9f635cc | refs/heads/master | 2022-12-27T13:04:15.405591 | 2020-10-11T01:54:29 | 2020-10-11T01:54:29 | 284,329,327 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 174 | java | package methodsandencapsulation.lambdas;
public class Lambda3 {
public static void main(String[] args) {
String a="Lambda";
String b="Lambda1";
}
}
| [
"arasefe@users.noreply.github.com"
] | arasefe@users.noreply.github.com |
7695d1a89a687141f6fad2bf8ae9fb3f3d76f430 | 58d237dc70c9ef25746de85de7ada567e4d4f405 | /src/com/dante/learn/core/oop/Variables/MyMain.java | e01d1b2d692f78975a7ee5c23e0cd4fdfc90bf9c | [] | no_license | nguyentn298/Dawn | 38cca6a7cd6a23df229e0fb1da6a986d4c427380 | 64b4f2463e4d870811fefc4969fdad78ae4a9494 | refs/heads/master | 2021-01-12T05:51:20.138264 | 2018-07-13T07:37:47 | 2018-07-13T07:37:47 | 77,216,788 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 695 | java | package com.dante.learn.core.oop.Variables;
public class MyMain {
public static void main(String[] args) {
// TestAllVarbiale test = new TestAllVarbiale();
// String b = TestAllVarbiale.name;
// System.out.println("b: " + b);
// TestAllVarbiale.name = "nguyen222";
// b = TestAllVarbiale.name;
// System.out.println("b: " + b);
//
//
// Double a = 1.4e-2;
// System.out.println(a);
//
// char c = ')';
// System.out.println(c);
String a = "test";
String b = a;
a = "test222";
b = a;
System.out.println(b);
String c = new String("abc");
String d = c;
System.out.println(d);
}
public void getVariable() {
String id = TestAllVarbiale.name;
}
}
| [
"kid2981@gmail.com"
] | kid2981@gmail.com |
a6c08f1ea23561d7193d82805c9d58c05399d2d1 | ed5159d056e98d6715357d0d14a9b3f20b764f89 | /test/irvine/oeis/a021/A021555Test.java | 5b2f88fad7ff5ae4595b69f2ce51e5296cabd926 | [] | no_license | flywind2/joeis | c5753169cf562939b04dd246f8a2958e97f74558 | e5efd6971a0062ac99f4fae21a7c78c9f9e74fea | refs/heads/master | 2020-09-13T18:34:35.080552 | 2019-11-19T05:40:55 | 2019-11-19T05:40:55 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 195 | java | package irvine.oeis.a021;
import irvine.oeis.AbstractSequenceTest;
/**
* Tests the corresponding class.
* @author Sean A. Irvine
*/
public class A021555Test extends AbstractSequenceTest {
}
| [
"sean.irvine@realtimegenomics.com"
] | sean.irvine@realtimegenomics.com |
f1486cf9ae79a0ca02ada28e5d80c3a1fb4a390e | 3ef79180a5cb4b4b2e68aa67e0144641a4518001 | /ssh_crm/src/dao/impl/LinkManDaoImpl.java | 48f6dfe324a0b8e435e9c0be969b7f20c5fd0f11 | [] | no_license | llCnll/crm | 3f7d018111bda1c87dab50647b346932794acfd3 | 507f225fe2ee9b530b384869d6f661b1aaddad3b | refs/heads/master | 2022-04-14T03:27:31.170611 | 2018-06-12T14:18:35 | 2018-06-12T14:18:35 | 256,789,955 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 158 | java | package dao.impl;
import dao.LinkManDao;
import domain.LinkMan;
public class LinkManDaoImpl extends BaseDaoImpl<LinkMan> implements LinkManDao {
}
| [
"972581592@qq.com"
] | 972581592@qq.com |
69b3f9b76b2560419b1146daadd0a679b40b3adb | de101b04abfbd850e502756622c8e77fb1fcea97 | /StudentProjects/2015/Group/TI_EF/KELOMPOK_4/src/androidTest/java/com/example/setiadidarmawan/widgetadiozh/ApplicationTest.java | 6624b56a30df9b9588d8359af93aab16b945f014 | [] | no_license | ivankusuma07/UNS_D3TI_ANDROID_CLASS | be5babf16db533ac3af0b7286d36ed5ecd218809 | 297392ed03d7e5675104970a9035273eb0a0589c | refs/heads/master | 2022-11-18T20:44:21.259809 | 2016-01-05T03:01:09 | 2016-01-05T03:01:09 | 41,787,680 | 0 | 0 | null | 2015-09-02T07:51:35 | 2015-09-02T07:51:35 | null | UTF-8 | Java | false | false | 371 | java | package com.example.setiadidarmawan.widgetadiozh;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | [
"adiozh@gmail.com"
] | adiozh@gmail.com |
9dea7424b6dd18a6ccc9d5e116e0c15952e63b7f | ed3d4bdf95443ebc321c62ff4d74ab095f2de43a | /src/main/java/com/neu/arithmeticproblemsolver/featureextractor/PublicKeys.java | 798297263b574ca65ffdee3dc5ac2dab42c8ddd8 | [] | no_license | niyatia/Thesis | ba32d61e298782f24d71a4367da8bfb9027829d0 | 597863b25f06e8ab1a9b58fcc961b22fec9c1824 | refs/heads/master | 2021-08-27T20:28:11.191821 | 2017-11-28T07:28:25 | 2017-11-28T07:28:25 | 112,299,844 | 1 | 0 | null | null | null | null | UTF-8 | Java | false | false | 3,203 | java | package com.neu.arithmeticproblemsolver.featureextractor;
import static com.neu.arithmeticproblemsolver.featureextractor.PublicKeys.ADDITION_LABEL;
import static com.neu.arithmeticproblemsolver.featureextractor.PublicKeys.EQUALS_LABEL;
import static com.neu.arithmeticproblemsolver.featureextractor.PublicKeys.IRRELEVANT_LABEL;
import static com.neu.arithmeticproblemsolver.featureextractor.PublicKeys.LABEL_STRINGS;
import static com.neu.arithmeticproblemsolver.featureextractor.PublicKeys.QUESTION_LABEL;
import static com.neu.arithmeticproblemsolver.featureextractor.PublicKeys.SUBTRACTION_LABEL;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
public class PublicKeys {
/** Dataset Path*/
public static final String DATASET_DIRECTORY = "dataset/";
public static final String DATASET_DIRECTORY_ESCAPED_PATH = URLDecoder
.decode(Thread.currentThread().getContextClassLoader().getResource(DATASET_DIRECTORY).getPath());
public static final String ADD_SUB_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "AdditionSubtraction.json";
public static final String TRAINING_DATA_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "TrainingData.json";
public static final String TEST_DATA_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "TestData.json";
public static final String TRAINING_FEATURES_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "TrainingFeatures.csv";
public static final String TEST_FEATURES_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "TestFeatures.csv";
public static final String VERB_FREQUENCY_TRAINING_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "VerbFrequencyTraining.csv";
public static final String VERB_FEATURES_TRAINING_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "VerbFeaturesTraining.csv";
public static final String VERB_FREQUENCY_TEST_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "VerbFrequencyTest.csv";
public static final String VERB_FEATURES_TEST_FILE_PATH = DATASET_DIRECTORY_ESCAPED_PATH + "VerbFeaturesTest.csv";
/** JSON Keys */
public static final String KEY_PARENT_INDEX = "ParentIndex";
public static final String KEY_S_QUESTION = "sQuestion";
public static final String KEY_SENTENCE = "Sentence";
public static final String KEY_LABEL = "label";
public static final String KEY_SENTENCES = "Sentences";
public static final String KEY_SYNTACTIC_PATTERN = "SyntacticPattern";
public static final String KEY_SIMPLIFIED_SENTENCES = "SimplifiedSentences";
/** Classification Labels. */
public final static String ADDITION_LABEL = "+";
public final static String SUBTRACTION_LABEL = "-";
public final static String QUESTION_LABEL = "?";
public final static String EQUALS_LABEL = "=";
public final static String IRRELEVANT_LABEL = "i";
/** String corresponding to labels. */
public final static Map<String, String> LABEL_STRINGS = new HashMap<>();
static {
LABEL_STRINGS.put(ADDITION_LABEL, "Addition");
LABEL_STRINGS.put(SUBTRACTION_LABEL, "Subtraction");
LABEL_STRINGS.put(QUESTION_LABEL, "Question");
LABEL_STRINGS.put(IRRELEVANT_LABEL, "Irrelevant");
LABEL_STRINGS.put(EQUALS_LABEL, "Equals");
}
}
| [
"vishalarajpal@gmail.com"
] | vishalarajpal@gmail.com |
20459935ec6c3ae72911cb4d5548edc217197c9f | 1cfe4c3bb61c1929c297c164166dfa16265840f9 | /workplace/strutstest/src/lh/xiaoyu/LoginAction.java | 19a773212599da8b397c2883e6d0469fb463b23b | [] | no_license | runfish/fishcode | 0e16c2ba2aee9385be978442cc940626eb9548dd | f2505741f602c30d7c0cf9665cf8072f29578a90 | refs/heads/master | 2018-12-28T09:44:58.253284 | 2013-04-05T08:59:24 | 2013-04-05T08:59:24 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 801 | java | package lh.xiaoyu;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class LoginAction extends Action {
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse httpservletresponse)
throws Exception {
// TODO Auto-generated method stub
LoginForm loginForm = (LoginForm)form;
System.out.println(loginForm.getUesrName());
if(loginForm.getUesrName().equals("xiaoyu"))
return mapping.findForward("loginSuccess");
else
return mapping.findForward("loginFailure");
}
}
| [
"pingdongyu@gmail.com"
] | pingdongyu@gmail.com |
2564c11ac02d1b8ce4ff40aa60c246bc51f4d800 | 1e11797fb4878670b69d65773787d6fe2a283b2d | /app/src/main/java/com/example/user/dependencyinjectiondemo/Person.java | 222162ee008fd61ca33159257ccd036edf8d9b17 | [] | no_license | oyeleke/dependencyinjection | a998b704bc058e4ac12f6764df865aef5f160937 | de9d1529134a6e4d7f37b6df47065717618cb7e7 | refs/heads/master | 2020-03-12T12:35:50.390291 | 2018-04-23T01:29:12 | 2018-04-23T01:29:12 | 130,621,634 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 690 | java | package com.example.user.dependencyinjectiondemo;
public class Person {
private String firstName;
private String lastName;
public Person() {
}
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getName() {
return firstName + " " + lastName;
}
}
| [
"oyelekeogunsola@gmail.com"
] | oyelekeogunsola@gmail.com |
1c5769312d07a3f5119b16fdb70f2755540ee9d5 | da46be8e8f04efed7d455d4b619395fe294b9afe | /app-run-first-version/src/main/java/it/mcella/jcr/oak/upgrade/apprun/firstversion/action/NodesSetup.java | 23eb60eec451eb9e70f34173b72dc1981fcbe8a3 | [
"MIT"
] | permissive | sitMCella/Jackrabbit-Oak-repository-upgrade | d424ac61b09ba1b0b4fdd29f637e992991545eca | 8d987aa2edea358c14129f9f2250d146e761e47c | refs/heads/master | 2022-09-06T16:29:40.363801 | 2022-08-19T19:57:13 | 2022-08-19T19:57:13 | 155,085,000 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 4,048 | java | package it.mcella.jcr.oak.upgrade.apprun.firstversion.action;
import it.mcella.jcr.oak.upgrade.repository.JcrRepository;
import it.mcella.jcr.oak.upgrade.repository.firstversion.node.file.FileNode;
import it.mcella.jcr.oak.upgrade.repository.firstversion.node.file.OakFileNodeFactory;
import it.mcella.jcr.oak.upgrade.repository.firstversion.node.file.OakFileVersionNodeFactory;
import it.mcella.jcr.oak.upgrade.repository.firstversion.node.folder.FolderNode;
import it.mcella.jcr.oak.upgrade.repository.firstversion.node.folder.OakFolderNodeFactory;
import it.mcella.jcr.oak.upgrade.repository.firstversion.persistence.file.FilePersistence;
import it.mcella.jcr.oak.upgrade.repository.firstversion.persistence.file.FilePersistenceException;
import it.mcella.jcr.oak.upgrade.repository.firstversion.persistence.file.FileVersionPersistence;
import it.mcella.jcr.oak.upgrade.repository.firstversion.persistence.file.FileVersionPersistenceException;
import it.mcella.jcr.oak.upgrade.repository.firstversion.persistence.folder.FolderPersistence;
import it.mcella.jcr.oak.upgrade.repository.firstversion.persistence.folder.FolderPersistenceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
public class NodesSetup implements Action {
private static final Logger LOGGER = LoggerFactory.getLogger(NodesSetup.class);
private final JcrRepository jcrRepository;
public NodesSetup(JcrRepository jcrRepository) {
this.jcrRepository = jcrRepository;
}
@Override
public ActionType getType() {
return ActionType.SETUP;
}
@Override
public void execute() throws ActionException {
Path firstImage = null;
Path secondImage = null;
try (InputStream foxImageStream = ClassLoader.getSystemResourceAsStream("fox.jpg");
InputStream crocusImageStream = ClassLoader.getSystemResourceAsStream("crocus.jpg")) {
FolderPersistence folderPersistence = new FolderPersistence(jcrRepository, new OakFolderNodeFactory());
FolderNode folderNode = folderPersistence.createIntoRoot("awesome folder", false);
FolderNode subFolderNode = folderPersistence.createInto(folderNode, "subFolder", false);
FilePersistence filePersistence = new FilePersistence(jcrRepository, new OakFileNodeFactory());
firstImage = Files.createTempFile("fox", ".jpg");
Files.copy(foxImageStream, firstImage, StandardCopyOption.REPLACE_EXISTING);
boolean hidden = false;
boolean deletable = true;
FileNode imageNode = filePersistence.createInto(subFolderNode, "image", hidden, deletable, firstImage);
FileVersionPersistence fileVersionPersistence = new FileVersionPersistence(jcrRepository, new OakFileVersionNodeFactory());
secondImage = Files.createTempFile("crocus", ".jpg");
Files.copy(crocusImageStream, secondImage, StandardCopyOption.REPLACE_EXISTING);
fileVersionPersistence.createNewVersion(imageNode, "second version", secondImage);
} catch (FolderPersistenceException | FilePersistenceException | FileVersionPersistenceException | IOException e) {
throw new ActionException("Cannot setup nodes", e);
} finally {
if (firstImage != null && Files.exists(firstImage)) {
try {
Files.delete(firstImage);
} catch (IOException e) {
LOGGER.warn(String.format("Cannot remove file \"s\"", firstImage.toString()));
}
}
if (secondImage != null && Files.exists(secondImage)) {
try {
Files.delete(secondImage);
} catch (IOException e) {
LOGGER.warn(String.format("Cannot remove file \"s\"", secondImage.toString()));
}
}
}
}
}
| [
"marco.cella.tv@gmail.com"
] | marco.cella.tv@gmail.com |
0e7eabd0924c374be88e5d5a206a562910a272d6 | 4052e087fec60c5073764fdb4ff873ec548a6e2b | /SqlRender/java/org/ohdsi/sql/SqlSplit.java | 746ac035c83ba215f686fd0b412064aa01f37b77 | [
"Apache-2.0"
] | permissive | amazon-archives/aws-ohdsi-automated-deployment | 1350dcd1d1f5fce0287e0c2f673b0ca0bbb539f2 | 8deb86143a967b32cb55caab624aec526df11a40 | refs/heads/master | 2022-04-01T02:26:35.043472 | 2019-09-12T14:10:11 | 2019-09-12T14:10:11 | 124,141,866 | 3 | 1 | null | null | null | null | UTF-8 | Java | false | false | 2,881 | java | /*******************************************************************************
* Copyright 2018 Observational Health Data Sciences and Informatics
*
* 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.ohdsi.sql;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class SqlSplit {
/**
* Splits a string containing multiple SQL statements into a vector of SQL statements
*
* @param sql
* The SQL string to split into separate statements
* @return An array of strings, one for each SQL statement
*/
public static String[] splitSql(String sql) {
List<String> parts = new ArrayList<String>();
List<StringUtils.Token> tokens = StringUtils.tokenizeSql(sql.toLowerCase());
Stack<String> nestStack = new Stack<String>();
String lastPop = "";
int start = 0;
int cursor;
boolean quote = false;
boolean bracket = false;
String quoteText = "";
for (cursor = start; cursor < tokens.size(); cursor++) {
StringUtils.Token token = tokens.get(cursor);
if (quote) {
if (token.text.equals(quoteText)) {
quote = false;
}
} else if (bracket) {
if (token.text.equals("]"))
bracket = false;
} else if (token.text.equals("'") || token.text.equals("\"")) {
quote = true;
quoteText = token.text;
} else if (token.text.equals("[")) {
bracket = true;
} else if (token.text.equals("begin") || token.text.equals("case")) {
nestStack.push(token.text);
} else if (token.text.equals("end") && (cursor == tokens.size() - 1 || !tokens.get(cursor + 1).text.equals("if"))) {
lastPop = nestStack.pop();
} else if (nestStack.size() == 0 && token.text.equals(";")) {
if (cursor == 0 || (tokens.get(cursor - 1).text.equals("end") && lastPop.equals("begin"))) { // oracle: must have ; after end belonging to a
// begin
parts.add(sql.substring(tokens.get(start).start, token.end));
} else { // oracle: cannot have ; after anything but end
parts.add(sql.substring(tokens.get(start).start, token.end - 1));
}
start = cursor + 1;
}
}
if (start < cursor) {
parts.add(sql.substring(tokens.get(start).start, tokens.get(cursor - 1).end));
start = cursor + 1;
}
return parts.toArray(new String[parts.size()]);
}
}
| [
"james.s.wiggins@gmail.com"
] | james.s.wiggins@gmail.com |
1064abccdb60b9b44e7553242aea29589b6e5624 | bcb8a590dd91c5e2f4aa363cddd9fd50a71c0e7e | /src/ro/ase/csie/cts/g1087/dp/factorymethod/FactoryTemaUniversala.java | 9c6e2de839a982541c68bd61ffc9531fdc9f68d3 | [] | no_license | daianatabirca/CTS | 4997af2a3f77be9c40e014910bfa7148e7fde30e | 0a966823cc98d3538cfb69f190e7d233a7813402 | refs/heads/master | 2023-05-11T04:27:29.758394 | 2021-06-04T20:46:21 | 2021-06-04T20:46:21 | 342,822,416 | 1 | 1 | null | null | null | null | UTF-8 | Java | false | false | 932 | java | package ro.ase.csie.cts.g1087.dp.factorymethod;
import ro.ase.csie.cts.g1087.dp.simplefactory.CaracterDCComics;
import ro.ase.csie.cts.g1087.dp.simplefactory.CaracterDisney;
import ro.ase.csie.cts.g1087.dp.simplefactory.CaracterMarvel;
import ro.ase.csie.cts.g1087.dp.simplefactory.SuperErouAbstract;
import ro.ase.csie.cts.g1087.dp.simplefactory.TipErou;
public class FactoryTemaUniversala extends FactoryAbstract {
@Override
public SuperErouAbstract getSuperErou(TipErou tip, String nume) { //Factory pentru clasele cu Tema OBISNUITA (clasele din simple)
SuperErouAbstract superErou = null;
switch(tip) {
case DISNEY:
superErou = new CaracterDisney(nume, 100, false);
break;
case MARVEL:
superErou = new CaracterMarvel(nume, 500, 0);
break;
case DC:
superErou = new CaracterDCComics(nume, 500, 100);
break;
default:
throw new UnsupportedOperationException();
}
return superErou;
}
}
| [
"daiana.tabirca@gmail.com"
] | daiana.tabirca@gmail.com |
c118d34d7a606f71123c8b7398ec1a7d9435b2c9 | 5e2d87829db1fd971fdaf96ef7f1ecb9999cb5d5 | /biblioteca-quadrinho-java/src/model/Usuario.java | 42289d889a7a0e698b9a757f6de015716b88e3d3 | [] | no_license | emanuel71jo/projetos-curso-CC-UEPB | 37c37616bfa3c9ae323e09cf5a9acfea6b218f89 | 08675b79eab2690ac18c66695ee1a6422c5fb114 | refs/heads/master | 2021-07-01T06:18:04.193009 | 2021-05-29T15:48:41 | 2021-05-29T15:48:41 | 236,749,930 | 1 | 0 | null | 2020-12-18T20:21:13 | 2020-01-28T14:09:42 | Jupyter Notebook | UTF-8 | Java | false | false | 2,158 | java | package model;
import java.util.ArrayList;
import java.util.List;
public class Usuario extends Pessoa{
private String login;
private String senha;
private boolean permissao;
private List<Leitura> leituras;
public Usuario() {
}
public Usuario(String login, String senha) {
super();
this.login = login;
this.senha = senha;
}
public Usuario(String cpf) {
super(cpf);
}
public Usuario(String cpf, String nome, boolean tipoPessoa, String login, String senha, boolean permissao) {
super(cpf, nome, tipoPessoa);
this.login = login;
this.senha = senha;
this.permissao = permissao;
this.leituras = new ArrayList<Leitura>();
}
public Usuario(String cpf, String nome, boolean tipoPessoa, String login, String senha, boolean permissao,
List<Leitura> leitura) {
super(cpf, nome, tipoPessoa);
this.login = login;
this.senha = senha;
this.permissao = permissao;
this.leituras = leitura;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getSenha() {
return senha;
}
public void setSenha(String senha) {
this.senha = senha;
}
public boolean isPermissao() {
return permissao;
}
public void setPermissao(boolean permissao) {
this.permissao = permissao;
}
public List<Leitura> getLeituras() {
return leituras;
}
public void setLeituras(List<Leitura> leituras) {
this.leituras = leituras;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((login == null) ? 0 : login.hashCode());
result = prime * result + ((senha == null) ? 0 : senha.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Usuario other = (Usuario) obj;
if (login == null) {
if (other.login != null)
return false;
} else if (!login.equals(other.login))
return false;
if (senha == null) {
if (other.senha != null)
return false;
} else if (!senha.equals(other.senha))
return false;
return true;
}
}
| [
"emanuel71jo@gmail.com"
] | emanuel71jo@gmail.com |
c950b5c23c3aa61f55be08c1e43f200b99457d4c | 3a9bbcc4ba319c389ea60d6ed365e8185f886baa | /src/strategy/game/version/StrategyGameControllerImpl.java | 3bf56fd1c18e82087b0482e571200fd00e2fdfa5 | [] | no_license | ahchen/Strategy | 44dc18d221d33481207449de50f726c0fb083252 | 05c643a1aa2608fce46fb72aa019c762a029da6f | refs/heads/master | 2020-06-03T11:58:36.372054 | 2013-10-16T05:23:43 | 2013-10-16T05:23:43 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 13,199 | java | /**
*
*/
package strategy.game.version;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
import strategy.common.PlayerColor;
import strategy.common.StrategyException;
import strategy.common.StrategyRuntimeException;
import strategy.game.StrategyGameController;
import strategy.game.common.Location;
import strategy.game.common.Location2D;
import strategy.game.common.MoveResult;
import strategy.game.common.MoveResultStatus;
import strategy.game.common.Piece;
import strategy.game.common.PieceLocationDescriptor;
import strategy.game.common.PieceType;
/**
* @author Alex C
* @version September 14, 2013
*/
public abstract class StrategyGameControllerImpl implements StrategyGameController {
protected boolean gameStarted;
protected boolean gameOver;
protected PlayerColor lastPlayerColor;
protected Collection<PieceLocationDescriptor> redSetup, blueSetup;
protected Map<Location, Piece> board;
protected PieceLocationDescriptor lastRedPieceLocation, lastBluePieceLocation;
protected boolean redRepetitionFlag, blueRepetitionFlag;
protected int numRedMovablePieces, numBlueMovablePieces;
protected int numMoves;
protected static int NUM_PIECES = 0;
protected static final Piece CHOKE_POINT = new Piece(PieceType.CHOKE_POINT, null);
protected static Location[] CHOKE_POINT_LOCATIONS = null;
protected static int BOARD_WIDTH = 0;
protected static int BOARD_HEIGHT = 0;
// based on simple formula for translating locations( (0,0) = 1, (1,1) = 2 ... (4,5) = 35, (5,5) = 36)
// when pieces are located at their correct locations, their location total should equal these numbers
protected static int RED_SPACE_TOTAL = 0;
protected static int BLUE_SPACE_TOTAL = 0;
/**
* constructor for creating a strategy game
* @param redPieces collection of red pieces and locations
* @param bluePieces collection of blue pieces and locations
* @throws StrategyException
*/
protected StrategyGameControllerImpl(Collection<PieceLocationDescriptor> redPieces,
Collection<PieceLocationDescriptor> bluePieces) throws StrategyException {
setVariables(redPieces, bluePieces);
validatePiecesAndLocations(redPieces);
validatePiecesAndLocations(bluePieces);
initializeBoard();
}
/**
* Sets necessary variables for the given type of game being created
* @param redPieces collection of red pieces
* @param bluePieces collection of blue pieces
*/
protected abstract void setVariables(Collection<PieceLocationDescriptor> redPieces,
Collection<PieceLocationDescriptor> bluePieces);
/**
* Validates that the collection given only contains
* piece/location combinations that are ok for type of game created
* @param pieces the collection of pieces to validate
* @throws StrategyException thrown if the collection is deemed invalid
*/
protected abstract void validatePiecesAndLocations(Collection<PieceLocationDescriptor> pieces) throws StrategyException;
/*
* @see strategy.game.StrategyGameController#startGame()
*/
public void startGame() throws StrategyException {
if(gameStarted) {
throw new StrategyException("Game Already In Progress, Make a New Game");
}
gameStarted = true;
gameOver = false;
lastPlayerColor = null;
}
/**
* Initializes the board to contain all the spaces of the board
* Adds the validated red and blue pieces to the board
*/
protected void initializeBoard()
{
final Iterator<PieceLocationDescriptor> redIter, blueIter;
redIter = redSetup.iterator();
blueIter = blueSetup.iterator();
// add all spaces to board
for (int i = 0; i < BOARD_HEIGHT; i++) {
for (int j = 0; j < BOARD_WIDTH; j++) {
board.put(new Location2D(j, i), null);
}
}
PieceLocationDescriptor singleRedPiece, singleBluePiece;
while (redIter.hasNext()) {
singleRedPiece = redIter.next();
singleBluePiece = blueIter.next();
// fill board with pieces
board.put(singleRedPiece.getLocation(), singleRedPiece.getPiece());
board.put(singleBluePiece.getLocation(), singleBluePiece.getPiece());
}
}
/*
* @see strategy.game.StrategyGameController#move()
*/
public MoveResult move(PieceType piece, Location from, Location to)
throws StrategyException {
checkValidMoveRequest(piece, from, to);
MoveResult result;
final Piece fromPiece, toPiece;
fromPiece = getPieceAt(from);
toPiece = getPieceAt(to);
checkLocations(from, to);
result = checkRepetition(piece, from, to);
// if check repetition returned a MoveResult, then repetition rule is violated and
// we return the result
if (result != null) {
return result;
}
// if moving to an empty space
if (toPiece == null) {
board.put(from, null);
board.put(to, fromPiece);
result = new MoveResult(MoveResultStatus.OK, new PieceLocationDescriptor(fromPiece, to));
}
else if (toPiece.getType() == PieceType.CHOKE_POINT) {
throw new StrategyException("Cannot Move to a Choke Point");
}
else {
result = battle(new PieceLocationDescriptor(fromPiece, from),
new PieceLocationDescriptor(toPiece, to));
}
lastPlayerColor = fromPiece.getOwner();
result = checkMovablePieces(result);
// game over
if (result.getStatus() != MoveResultStatus.OK) {
gameOver = true;
}
return result;
}
/**
* Checks if the given move request is a valid one
* @param piece piece to be moved
* @param from location of the piece to be moved
* @param to location to move the given piece to
* @throws StrategyException if the move is deemed to be invalid
*/
private void checkValidMoveRequest(PieceType piece, Location from,
Location to) throws StrategyException {
if (gameOver) {
throw new StrategyException("The game is over, you cannot make a move");
}
if (!gameStarted) {
throw new StrategyException("You must start the game!");
}
if (piece == PieceType.FLAG) {
throw new StrategyException("You cannot move the flag");
}
if (piece == PieceType.BOMB) {
throw new StrategyException("You cannot move the bomb");
}
if (piece == PieceType.CHOKE_POINT) {
throw new StrategyException("You cannot move the choke point");
}
if (!board.containsKey(from) || !board.containsKey(to)) {
throw new StrategyException("Coordinates not on board");
}
if (getPieceAt(from) == null || getPieceAt(from).getType() != piece) {
throw new StrategyException("Specified piece is not located at given location");
}
final Piece fromPiece, toPiece;
fromPiece = getPieceAt(from);
toPiece = getPieceAt(to);
// if last player color is not set, this is the first move
if (lastPlayerColor == null && fromPiece.getOwner() == PlayerColor.BLUE) {
// first move cannot come from blue
throw new StrategyException("Blue cannot start the game");
}
if (lastPlayerColor == fromPiece.getOwner()) {
throw new StrategyException("Same player cannot move twice in a row");
}
if (toPiece != null && fromPiece.getOwner() == toPiece.getOwner()) {
throw new StrategyException("Cannot move to a space with your own piece on it already");
}
}
/**
* Determines if moving to the given to location is valid from the given from location
* @param from base location
* @param to location to go
* @throws StrategyException
*/
protected void checkLocations(Location from, Location to) throws StrategyException {
try {
if (from.distanceTo(to) > 1) {
throw new StrategyException("Locations are too far apart");
}
}
catch (StrategyRuntimeException e) {
throw new StrategyException(e.getMessage());
}
}
/**
* Handles battling and updates the board accordingly
* @param from piece being moved
* @param to piece being attacked
* @return move result after the battle
*/
protected MoveResult battle(PieceLocationDescriptor from,PieceLocationDescriptor to) {
final Piece fromPiece = from.getPiece();
final Piece toPiece = to.getPiece();
final Location fromLoc = from.getLocation();
final Location toLoc = to.getLocation();
final PieceLocationDescriptor newFrom = new PieceLocationDescriptor(fromPiece, toLoc);
final PieceLocationDescriptor newTo = new PieceLocationDescriptor(toPiece, fromLoc);
final PlayerColor fromColor = fromPiece.getOwner();
final PlayerColor toColor = toPiece.getOwner();
final PlayerColor winningColor;
final int pieceComparison = fromPiece.getType().compareTo(toPiece.getType());
// draw
if (pieceComparison == 0) {
board.put(fromLoc, null);
board.put(toLoc, null);
numRedMovablePieces--;
numBlueMovablePieces--;
return new MoveResult(MoveResultStatus.OK, null);
}
// if the piece being attacked is a flag, that player wins
if (toPiece.getType() == PieceType.FLAG) {
board.put(fromLoc, null);
board.put(toLoc, fromPiece);
if (fromColor == PlayerColor.BLUE) {
return new MoveResult(MoveResultStatus.BLUE_WINS, newFrom);
}
return new MoveResult(MoveResultStatus.RED_WINS, newFrom);
}
MoveResult battleMoveRes;
// from Wins (general case)
if (pieceComparison < 0) {
board.put(fromLoc, null);
board.put(toLoc, fromPiece);
winningColor = fromColor;
battleMoveRes = new MoveResult(MoveResultStatus.OK, newFrom);
}
// to Wins (general case)
else {
board.put(toLoc, null);
board.put(fromLoc, toPiece);
winningColor = toColor;
battleMoveRes = new MoveResult(MoveResultStatus.OK, newTo);
}
// Adjust the number of movable pieces
if (winningColor == PlayerColor.BLUE) {
numRedMovablePieces--;
}
else {
numBlueMovablePieces --;
}
return battleMoveRes;
}
/**
* Checks if the current piece + move will violate the move repetition rule
* @param piece piece being moved
* @param from location the piece is being moved from
* @param to location piece is being moved to
* @return MoveResult if the move results in a repetition violation and the other play wins
* otherwise returns null if move is valid
*/
private MoveResult checkRepetition(PieceType piece, Location from, Location to) {
final Piece fromPiece = board.get(from);
final PlayerColor pColor = fromPiece.getOwner();
if (pColor == PlayerColor.RED) {
// if last location is null, this is the first move.
// just set the last piece location
if (lastRedPieceLocation == null) {
lastRedPieceLocation = new PieceLocationDescriptor(fromPiece, from);
}
else {
// if the locations is equal to the previous location and the pieces are the same
if (lastRedPieceLocation.getPiece().equals(fromPiece) && lastRedPieceLocation.getLocation().equals(to)) {
// if the repetition flag is set, the rule is violated
if (redRepetitionFlag) {
return new MoveResult(MoveResultStatus.BLUE_WINS, null);
}
else {
// no violation yet. set the last piece and location and flag to true
lastRedPieceLocation = new PieceLocationDescriptor(fromPiece, from);
redRepetitionFlag = true;
}
}
else {
// different piece or location, reset the location and flag to false
lastRedPieceLocation = new PieceLocationDescriptor(fromPiece, from);
redRepetitionFlag = false;
}
}
}
else { // BLUE player
// if last location is null, this is the first move.
// just set the last piece location
if (lastBluePieceLocation == null) {
lastBluePieceLocation = new PieceLocationDescriptor(fromPiece, from);
}
else {
// if the locations is equal to the previous location and the pieces are the same
if (lastBluePieceLocation.getPiece().equals(fromPiece) && lastBluePieceLocation.getLocation().equals(to)) {
// if the repetition flag is set, the rule is violated
if (blueRepetitionFlag) {
return new MoveResult(MoveResultStatus.RED_WINS, null);
}
else {
// no violation yet. set the last piece and location and flag to true
lastBluePieceLocation = new PieceLocationDescriptor(fromPiece, from);
blueRepetitionFlag = true;
}
}
else {
// different piece or location, reset the location and flag to false
lastBluePieceLocation = new PieceLocationDescriptor(fromPiece, from);
blueRepetitionFlag = false;
}
}
}
return null;
}
/**
* Checks to see if either player (or both) have no remaining movable pieces
* @param result the move result from a given move
* @return a move result corresponding to a winner or draw if either player, or both
* don't have any movable pieces remaining. If both have movable pieces,
* the given MoveResult is returned.
*/
private MoveResult checkMovablePieces(MoveResult result) {
if (numRedMovablePieces == 0 && numBlueMovablePieces == 0) {
return new MoveResult(MoveResultStatus.DRAW, null);
}
else if (numRedMovablePieces == 0) {
return new MoveResult(MoveResultStatus.BLUE_WINS, result.getBattleWinner());
}
else if (numBlueMovablePieces == 0) {
return new MoveResult(MoveResultStatus.RED_WINS, result.getBattleWinner());
}
else {
return result;
}
}
/*
* @see strategy.game.StrategyGameController#getPieceAt()
*/
public Piece getPieceAt(Location location) {
return board.get(location);
}
}
| [
"ahchen@wpi.edu"
] | ahchen@wpi.edu |
fe91ef10c0dd2d276002fd8241e606e60d310804 | 882a1a28c4ec993c1752c5d3c36642fdda3d8fad | /proxies/com/microsoft/bingads/v12/campaignmanagement/GetNegativeSitesByAdGroupIdsRequest.java | 7017f4f1e81275b6c4631d2b1fcecc3a69f32ace | [
"MIT"
] | permissive | BazaRoi/BingAds-Java-SDK | 640545e3595ed4e80f5a1cd69bf23520754c4697 | e30e5b73c01113d1c523304860180f24b37405c7 | refs/heads/master | 2020-07-26T08:11:14.446350 | 2019-09-10T03:25:30 | 2019-09-10T03:25:30 | null | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 2,302 | java |
package com.microsoft.bingads.v12.campaignmanagement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="CampaignId" type="{http://www.w3.org/2001/XMLSchema}long" minOccurs="0"/>
* <element name="AdGroupIds" type="{http://schemas.microsoft.com/2003/10/Serialization/Arrays}ArrayOflong" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"campaignId",
"adGroupIds"
})
@XmlRootElement(name = "GetNegativeSitesByAdGroupIdsRequest")
public class GetNegativeSitesByAdGroupIdsRequest {
@XmlElement(name = "CampaignId")
protected Long campaignId;
@XmlElement(name = "AdGroupIds", nillable = true)
protected ArrayOflong adGroupIds;
/**
* Gets the value of the campaignId property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getCampaignId() {
return campaignId;
}
/**
* Sets the value of the campaignId property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setCampaignId(Long value) {
this.campaignId = value;
}
/**
* Gets the value of the adGroupIds property.
*
* @return
* possible object is
* {@link ArrayOflong }
*
*/
public ArrayOflong getAdGroupIds() {
return adGroupIds;
}
/**
* Sets the value of the adGroupIds property.
*
* @param value
* allowed object is
* {@link ArrayOflong }
*
*/
public void setAdGroupIds(ArrayOflong value) {
this.adGroupIds = value;
}
}
| [
"qitia@microsoft.com"
] | qitia@microsoft.com |
d30961bf9fe59fe88ad9ded61f0a5d4828e57326 | 2b4f61c97bd8967164f0dd6a904f920261646b30 | /app/src/main/java/com/novext/dietapp/ProfileActivity.java | 0609b259d26def95186610e3b75353c4aa172e2d | [] | no_license | Novext/Dietapplication | f05a36127c0509754076014a7b07fbc64dda585f | 4b340e80d79c909ab64ebdd958000b322e6eab62 | refs/heads/master | 2020-07-07T23:45:47.304086 | 2016-09-20T16:16:38 | 2016-09-20T16:16:38 | 66,902,236 | 0 | 0 | null | null | null | null | UTF-8 | Java | false | false | 1,744 | java | package com.novext.dietapp;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ProfileActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_profile);
setSupportActionBar(toolbar);
if (toolbar!=null){
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.vector));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onBackPressed();
}
});
}
final String MY_PREFS_NAME = "MyPrefsFile";
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
TextView first_name = (TextView) findViewById(R.id.firstname_profile);
TextView email = (TextView) findViewById(R.id.email_profile);
String first_name_pref = prefs.getString("name", "firstname");
String email_pref = prefs.getString("idName", "email");
Log.d(" OBTENIENDO EL NOMBRE DEL PREFERENCE",first_name_pref);
Log.d(" OBTENIENDO EL EMAIL DEL PREFERENCE ",email_pref);
first_name.setText(first_name_pref);
email.setText(email_pref);
}
}
}
| [
"julcsar13@gmail.com"
] | julcsar13@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.