blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
392c555296a9bb7bee3a5527852f1b30c316353d
Java
wisetime-io/wisetime-patrawin-connector
/src/main/java/io/wisetime/connector/patrawin/ConnectorLauncher.java
UTF-8
4,494
1.8125
2
[ "Apache-2.0" ]
permissive
/* * Copyright (c) 2019 Practice Insight Pty Ltd. All Rights Reserved. */ package io.wisetime.connector.patrawin; import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import io.wisetime.connector.ConnectorController; import io.wisetime.connector.config.RuntimeConfig; import io.wisetime.connector.config.RuntimeConfigKey; import io.wisetime.connector.patrawin.util.MsSqlTimeDbFormatter; import io.wisetime.connector.patrawin.util.TimeDbFormatter; import java.util.concurrent.TimeUnit; /** * Connector application entry point. * * @author shane.xie@practiceinsight.io */ public class ConnectorLauncher { public static void main(final String... args) throws Exception { ConnectorController connectorController = buildConnectorController(); connectorController.start(); } public static ConnectorController buildConnectorController() { return ConnectorController.newBuilder() .withWiseTimeConnector(Guice.createInjector(new PatrawinDbModule()).getInstance(PatrawinConnector.class)) .build(); } /** * <pre> * Configuration keys for the WiseTime Patrawin Connector. * Refer to README.md file for documentation of each of the below config keys. * </pre> * @author shane.xie, dmitry.zatselyapin */ public enum PatrawinConnectorConfigKey implements RuntimeConfigKey { PATRAWIN_JDBC_URL("PATRAWIN_JDBC_URL"), PATRAWIN_DB_USER("PATRAWIN_DB_USER"), PATRAWIN_DB_PASSWORD("PATRAWIN_DB_PASSWORD"), TAG_UPSERT_PATH("TAG_UPSERT_PATH"), ADD_SUMMARY_TO_NARRATIVE("ADD_SUMMARY_TO_NARRATIVE"), TIMEZONE("TIMEZONE"), HEALTH_CHECK_INTERVAL("HEALTH_CHECK_INTERVAL"), TAG_UPSERT_BATCH_SIZE("TAG_UPSERT_BATCH_SIZE"), // Set ALERT_EMAIL_ENABLED to true if alert emails are required ALERT_EMAIL_ENABLED("ALERT_EMAIL_ENABLED"), // Alert email interval specify number of hours and minutes // to wait before the next alert email is sent. Provides as HH:MM // ie 01:10 is 1 hour and 10 minutes. ALERT_EMAIL_INTERVAL_HH_MM("ALERT_EMAIL_INTERVAL_HH_MM"), ALERT_RECIPIENT_EMAIL_ADDRESSES("ALERT_RECIPIENT_EMAIL_ADDRESSES"), ALERT_SENDER_EMAIL_ADDRESS("ALERT_SENDER_EMAIL_ADDRESS"), ALERT_MAIL_SMTP_HOST("ALERT_MAIL_SMTP_HOST"), ALERT_MAIL_SMTP_PORT("ALERT_MAIL_SMTP_PORT"), ALERT_EMAIL_SENDER_PASSWORD("ALERT_EMAIL_SENDER_PASSWORD"), ALERT_EMAIL_SENDER_USERNAME("ALERT_EMAIL_SENDER_USERNAME"), //Set ALERT_STARTTLS_ENABLE to true for email alerts smtp host that supports TLS ALERT_STARTTLS_ENABLE("ALERT_STARTTLS_ENABLE"), //Port for access via ssl will be defaulted to ALERT_MAIL_SMTP_PORT if not set ALERT_MAIL_SMTP_SOCKET_FACTORY_PORT("ALERT_MAIL_SMTP_SOCKET_FACTORY_PORT"), // Socket factory class is required for SSL. It will be defaulted to javax.net.ssl.SSLSocketFactory if not set ALERT_MAIL_SMTP_SOCKET_FACTORY_CLASS("ALERT_MAIL_SMTP_SOCKET_FACTORY_CLASS"), // Activity sync batch size ACTIVITY_TYPE_BATCH_SIZE("ACTIVITY_TYPE_BATCH_SIZE"); private final String configKey; PatrawinConnectorConfigKey(final String configKey) { this.configKey = configKey; } @Override public String getConfigKey() { return configKey; } } /** * Bind the Patrawin database connection via DI. */ public static class PatrawinDbModule extends AbstractModule { @Override protected void configure() { final HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl( RuntimeConfig.getString(PatrawinConnectorConfigKey.PATRAWIN_JDBC_URL) .orElseThrow(() -> new RuntimeException("Missing required PATRAWIN_JDBC_URL configuration")) ); hikariConfig.setUsername( RuntimeConfig.getString(PatrawinConnectorConfigKey.PATRAWIN_DB_USER) .orElseThrow(() -> new RuntimeException("Missing required PATRAWIN_DB_USER configuration")) ); hikariConfig.setPassword( RuntimeConfig.getString(PatrawinConnectorConfigKey.PATRAWIN_DB_PASSWORD) .orElseThrow(() -> new RuntimeException("Missing required PATRAWIN_JDBC_PASSWORD configuration")) ); hikariConfig.setConnectionTimeout(TimeUnit.MINUTES.toMillis(1)); hikariConfig.setMaximumPoolSize(10); bind(TimeDbFormatter.class).toInstance(new MsSqlTimeDbFormatter()); bind(HikariDataSource.class).toInstance(new HikariDataSource(hikariConfig)); } } }
true
c1d25c349c39899efeb0427ccdd744bbcf189ba4
Java
aaliusman/Mar-SelProject1
/Mafi_Batch/src/OOP_abstraction/TestCar.java
UTF-8
384
2.6875
3
[]
no_license
package OOP_abstraction; public class TestCar { public static void main(String[] args) { // TODO Auto-generated method stub Car car=new Toyota(); car.start(); car.stop(); car.carShape(); Toyota car2=new Toyota(); car2.bodyColor(); ModernCar modCar = new Toyota(); modCar.hydrolicBreak(); Car bmwCar = new BMW(); bmwCar.start(); } }
true
81c0fd7b981df15933a34978ebc97cdb7420ffc5
Java
Sofia-Ingl/L8
/src/main/java/server/util/constants/QueryConstants.java
UTF-8
9,589
2.46875
2
[]
no_license
package server.util.constants; public final class QueryConstants { /* CREATORS */ public static final String MOVIE_ID_SEQUENCE_CREATOR = "CREATE SEQUENCE IF NOT EXISTS " + DatabaseConstants.MOVIE_ID_SEQUENCE + " START 1;"; public static final String SCREENWRITER_ID_SEQUENCE_CREATOR = "CREATE SEQUENCE IF NOT EXISTS " + DatabaseConstants.SCREENWRITER_ID_SEQUENCE + " START 1;"; public static final String MOVIE_TABLE_CREATOR = "CREATE TABLE IF NOT EXISTS " + DatabaseConstants.MOVIE_TABLE + " (\n" + DatabaseConstants.MOVIE_ID_COLUMN_IN_MOVIES + " INTEGER PRIMARY KEY CHECK(" + DatabaseConstants.MOVIE_ID_COLUMN_IN_MOVIES + " > 0) DEFAULT nextval('" + DatabaseConstants.MOVIE_ID_SEQUENCE + "'),\n" + DatabaseConstants.MOVIE_NAME_COLUMN_IN_MOVIES + " TEXT NOT NULL,\n" + DatabaseConstants.X_COORDINATE_COLUMN_IN_MOVIES + " FLOAT CHECK(" + DatabaseConstants.X_COORDINATE_COLUMN_IN_MOVIES + " <= 326),\n" + DatabaseConstants.Y_COORDINATE_COLUMN_IN_MOVIES + " INTEGER NOT NULL CHECK(" + DatabaseConstants.Y_COORDINATE_COLUMN_IN_MOVIES + " <= 281),\n" + DatabaseConstants.OSCARS_COUNT_COLUMN_IN_MOVIES + " INTEGER NOT NULL CHECK(" + DatabaseConstants.OSCARS_COUNT_COLUMN_IN_MOVIES + " > 0),\n" + DatabaseConstants.PALMS_COUNT_COLUMN_IN_MOVIES + " BIGINT NOT NULL CHECK (" + DatabaseConstants.PALMS_COUNT_COLUMN_IN_MOVIES + " > 0),\n" + DatabaseConstants.TAGLINE_COLUMN_IN_MOVIES + " TEXT NOT NULL,\n" + DatabaseConstants.CREATION_DATE_COLUMN_IN_MOVIES + " TIMESTAMP NOT NULL,\n" + DatabaseConstants.CREATION_DATE_ZONE_COLUMN_IN_MOVIES + " TEXT NOT NULL,\n" + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " INTEGER NOT NULL REFERENCES " + DatabaseConstants.SCREENWRITER_TABLE + "(" + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + "),\n" + DatabaseConstants.GENRE_COLUMN_IN_MOVIES + " TEXT,\n" + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + " TEXT NOT NULL REFERENCES " + DatabaseConstants.USER_TABLE + "(" + DatabaseConstants.USER_NAME_COLUMN_IN_USERS + ")\n" + ")"; public static final String SCREENWRITER_TABLE_CREATOR = "CREATE TABLE IF NOT EXISTS " + DatabaseConstants.SCREENWRITER_TABLE + " (\n" + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + " INTEGER PRIMARY KEY DEFAULT nextval('" + DatabaseConstants.SCREENWRITER_ID_SEQUENCE + "'),\n" + DatabaseConstants.SCREENWRITER_NAME_COLUMN_IN_SCREENWRITERS + " TEXT NOT NULL CHECK(" + DatabaseConstants.SCREENWRITER_NAME_COLUMN_IN_SCREENWRITERS + " NOT LIKE ''),\n" + DatabaseConstants.HEIGHT_COLUMN_IN_SCREENWRITERS + " BIGINT NOT NULL CHECK(" + DatabaseConstants.HEIGHT_COLUMN_IN_SCREENWRITERS + ">0),\n" + DatabaseConstants.EYE_COLOR_COLUMN_IN_SCREENWRITERS + " TEXT,\n" + DatabaseConstants.NATION_COLUMN_IN_SCREENWRITERS + " TEXT\n" + ")"; public static final String USER_TABLE_CREATOR = "CREATE TABLE IF NOT EXISTS " + DatabaseConstants.USER_TABLE + " (\n" + DatabaseConstants.USER_NAME_COLUMN_IN_USERS + " TEXT PRIMARY KEY,\n" + DatabaseConstants.USER_PASSWORD_COLUMN_IN_USERS + " TEXT NOT NULL\n" + ")"; /* INSERTS */ public static final String INSERT_SCREENWRITER = "INSERT INTO " + DatabaseConstants.SCREENWRITER_TABLE + " (" + DatabaseConstants.SCREENWRITER_NAME_COLUMN_IN_SCREENWRITERS + ", " + DatabaseConstants.HEIGHT_COLUMN_IN_SCREENWRITERS + ", " + DatabaseConstants.EYE_COLOR_COLUMN_IN_SCREENWRITERS + ", " + DatabaseConstants.NATION_COLUMN_IN_SCREENWRITERS + ") " + "VALUES (?, ?, ?, ?)"; public static final String INSERT_MOVIE = "INSERT INTO " + DatabaseConstants.MOVIE_TABLE + " (" + DatabaseConstants.MOVIE_NAME_COLUMN_IN_MOVIES + ", " + DatabaseConstants.X_COORDINATE_COLUMN_IN_MOVIES + ", " + DatabaseConstants.Y_COORDINATE_COLUMN_IN_MOVIES + ", " + DatabaseConstants.CREATION_DATE_COLUMN_IN_MOVIES + ", " + DatabaseConstants.CREATION_DATE_ZONE_COLUMN_IN_MOVIES + ", " + DatabaseConstants.OSCARS_COUNT_COLUMN_IN_MOVIES + ", " + DatabaseConstants.PALMS_COUNT_COLUMN_IN_MOVIES + ", " + DatabaseConstants.TAGLINE_COLUMN_IN_MOVIES + ", " + DatabaseConstants.GENRE_COLUMN_IN_MOVIES + ", " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + ", " + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + ") " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; public static final String INSERT_USER = "INSERT INTO " + DatabaseConstants.USER_TABLE + " VALUES (?, ?)"; /* SELECTS */ public static final String SELECT_ALL_MOVIES = "SELECT * FROM " + DatabaseConstants.MOVIE_TABLE; public static final String SELECT_USER_BY_NAME = "SELECT * FROM " + DatabaseConstants.USER_TABLE + " WHERE " + DatabaseConstants.USER_NAME_COLUMN_IN_USERS + " = ?"; public static final String SELECT_USER_BY_NAME_AND_PASSWORD = "SELECT * FROM " + DatabaseConstants.USER_TABLE + " WHERE " + DatabaseConstants.USER_NAME_COLUMN_IN_USERS + " = ? AND " + DatabaseConstants.USER_PASSWORD_COLUMN_IN_USERS + " = ?"; public static final String SELECT_SCREENWRITER_BY_ID = "SELECT * FROM " + DatabaseConstants.SCREENWRITER_TABLE + " WHERE " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + " = ?"; public static final String SELECT_SCREENWRITER_ID_BY_NAME = "SELECT " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + " FROM " + DatabaseConstants.SCREENWRITER_TABLE + " WHERE LOWER(" + DatabaseConstants.SCREENWRITER_NAME_COLUMN_IN_SCREENWRITERS + ") LIKE LOWER(?)"; public static final String SELECT_SCREENWRITER_ID_BY_MOVIE_ID_AND_USER = " SELECT " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE " + DatabaseConstants.MOVIE_ID_COLUMN_IN_MOVIES + " = ? AND " + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + " = ?"; /* DELETES */ public static final String DELETE_MOVIES_BY_USER = "DELETE FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE " + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + " = ?"; public static final String DELETE_SCREENWRITERS_WHICH_ARE_NOT_USED = "DELETE FROM " + DatabaseConstants.SCREENWRITER_TABLE + " WHERE ( SELECT COUNT(*) FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE " + DatabaseConstants.MOVIE_TABLE + "." + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " = " + DatabaseConstants.SCREENWRITER_TABLE + "." + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + ") = 0"; /* public static final String DELETE_MOVIES_BY_SCREENWRITER_NAME = "DELETE FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE LOWER( SELECT " + DatabaseConstants.SCREENWRITER_NAME_COLUMN_IN_SCREENWRITERS + " FROM " + DatabaseConstants.SCREENWRITER_TABLE + " WHERE " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + " = " + DatabaseConstants.MOVIE_TABLE + "." + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " ) LIKE LOWER( ? )"; */ public static final String DELETE_MOVIES_BY_SCREENWRITER_ID_AND_USER = "DELETE FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " = ? AND " + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + " = ?"; public static final String DELETE_MOVIES_BY_ID_AND_USER = "DELETE FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE " + DatabaseConstants.MOVIE_ID_COLUMN_IN_MOVIES + " = ? AND " + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + " = ?"; /* UPDATES */ public static final String UPDATE_MOVIE_BY_ID = "UPDATE " + DatabaseConstants.MOVIE_TABLE + " SET " + DatabaseConstants.MOVIE_NAME_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.X_COORDINATE_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.Y_COORDINATE_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.OSCARS_COUNT_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.PALMS_COUNT_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.TAGLINE_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " = ?, " + DatabaseConstants.GENRE_COLUMN_IN_MOVIES + " = ?" + " WHERE " + DatabaseConstants.MOVIE_ID_COLUMN_IN_MOVIES + " = ? AND " + DatabaseConstants.USER_NAME_COLUMN_IN_MOVIES + " = ?"; public static final String UPDATE_SCREENWRITER_BY_ID = "UPDATE " + DatabaseConstants.SCREENWRITER_TABLE + " SET " + DatabaseConstants.SCREENWRITER_NAME_COLUMN_IN_SCREENWRITERS + " = ?, " + DatabaseConstants.HEIGHT_COLUMN_IN_SCREENWRITERS + " = ?, " + DatabaseConstants.EYE_COLOR_COLUMN_IN_SCREENWRITERS + " = ?, " + DatabaseConstants.NATION_COLUMN_IN_SCREENWRITERS + " = ?" + " WHERE " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_SCREENWRITERS + " = ?"; /* COUNTS */ public static final String COUNT_SCREENWRITER_USAGES = "SELECT COUNT(*) FROM " + DatabaseConstants.MOVIE_TABLE + " WHERE " + DatabaseConstants.SCREENWRITER_ID_COLUMN_IN_MOVIES + " = ?"; private QueryConstants() {} }
true
f2f16ea3d2bac5fa12e5677d08f0e6cd8fd56bdd
Java
vaadin/flow
/flow-data/src/main/java/com/vaadin/flow/data/provider/hierarchy/TreeDataProvider.java
UTF-8
5,030
2.546875
3
[ "Apache-2.0" ]
permissive
/* * Copyright 2000-2023 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.flow.data.provider.hierarchy; import java.util.Comparator; import java.util.Objects; import java.util.Optional; import java.util.stream.Stream; import com.vaadin.flow.data.provider.InMemoryDataProvider; import com.vaadin.flow.function.SerializableComparator; import com.vaadin.flow.function.SerializablePredicate; /** * An in-memory data provider for listing components that display hierarchical * data. Uses an instance of {@link TreeData} as its source of data. * * @author Vaadin Ltd * @since 1.2 * * @param <T> * data type */ public class TreeDataProvider<T> extends AbstractHierarchicalDataProvider<T, SerializablePredicate<T>> implements InMemoryDataProvider<T> { private final TreeData<T> treeData; private SerializablePredicate<T> filter = null; private SerializableComparator<T> sortOrder = null; /** * Constructs a new TreeDataProvider. * <p> * This data provider should be refreshed after making changes to the * underlying {@link TreeData} instance. * * @param treeData * the backing {@link TreeData} for this provider, not * {@code null} */ public TreeDataProvider(TreeData<T> treeData) { Objects.requireNonNull(treeData, "treeData cannot be null"); this.treeData = treeData; } /** * Return the underlying hierarchical data of this provider. * * @return the underlying data of this provider */ public TreeData<T> getTreeData() { return treeData; } @Override public boolean hasChildren(T item) { if (!treeData.contains(item)) { // The item might be dropped from the tree already return false; } return !treeData.getChildren(item).isEmpty(); } @Override public int getChildCount( HierarchicalQuery<T, SerializablePredicate<T>> query) { Stream<T> items; if (query.getParent() != null) { items = treeData.getChildren(query.getParent()).stream(); } else { items = treeData.getRootItems().stream(); } return (int) getFilteredStream(items, query.getFilter()) .skip(query.getOffset()).limit(query.getLimit()).count(); } @Override public Stream<T> fetchChildren( HierarchicalQuery<T, SerializablePredicate<T>> query) { if (!treeData.contains(query.getParent())) { throw new IllegalArgumentException("The queried item " + query.getParent() + " could not be found in the backing TreeData. " + "Did you forget to refresh this data provider after item removal?"); } Stream<T> childStream = getFilteredStream( treeData.getChildren(query.getParent()).stream(), query.getFilter()); Optional<Comparator<T>> comparing = Stream .of(query.getInMemorySorting(), sortOrder) .filter(Objects::nonNull) .reduce((c1, c2) -> c1.thenComparing(c2)); if (comparing.isPresent()) { childStream = childStream.sorted(comparing.get()); } return childStream.skip(query.getOffset()).limit(query.getLimit()); } @Override public SerializablePredicate<T> getFilter() { return filter; } @Override public void setFilter(SerializablePredicate<T> filter) { this.filter = filter; refreshAll(); } @Override public SerializableComparator<T> getSortComparator() { return sortOrder; } @Override public void setSortComparator(SerializableComparator<T> comparator) { sortOrder = comparator; refreshAll(); } private Stream<T> getFilteredStream(Stream<T> stream, Optional<SerializablePredicate<T>> queryFilter) { final Optional<SerializablePredicate<T>> combinedFilter = filter != null ? Optional.of(queryFilter.map(filter::and).orElse(filter)) : queryFilter; return combinedFilter.map( f -> stream.filter(element -> flatten(element).anyMatch(f))) .orElse(stream); } private Stream<T> flatten(T element) { return Stream.concat(Stream.of(element), getTreeData() .getChildren(element).stream().flatMap(this::flatten)); } }
true
6f180c60635d1225dd25fa45e09402f02932a981
Java
wangjianhua1/springBootDemo
/src/main/java/com/example/demo/sort/BubbleSort.java
UTF-8
3,347
4.25
4
[ "Apache-2.0" ]
permissive
package com.example.demo.sort; /** * 不稳定算法:排序过程中可以改变2个相同值得位置,或者对象的index的排序即为不稳定排序 */ public class BubbleSort { public static void swap(int A[], int i, int j) { int temp = A[i]; A[i] = A[j]; A[j] = temp; } /** * 冒泡排序方法 * 分类 -------------- 内部比较排序 * 数据结构 ---------- 数组 * 最差时间复杂度 ---- O(n^2) * 最优时间复杂度 ---- 如果能在内部循环第一次运行时,使用一个旗标来表示有无需要交换的可能,可以把最优时间复杂度降低到O(n) * 平均时间复杂度 ---- O(n^2) * 所需辅助空间 ------ O(1) * 稳定性 ------------ 稳定 * * @param A */ public static void BubbleSort(int[] A) { for (int j = 0; j < A.length; j++) {//只做一个循环排序 for (int i = 0; i < A.length - 1; i++) {//冒泡,2个值作比较并且交换 if (A[i] > A[i + 1]) {//mark 如果条件改成A[i] >= A[i + 1],则变为不稳定的排序算法 swap(A, i, i + 1); } } } } /** * 鸡尾酒冒泡排序 * 分类 -------------- 内部比较排序 * 数据结构 ---------- 数组 * 最差时间复杂度 ---- O(n^2) * 最优时间复杂度 ---- 如果序列在一开始已经大部分排序过的话,会接近O(n) * 平均时间复杂度 ---- O(n^2) * 所需辅助空间 ------ O(1) * 稳定性 ------------ 稳定 */ public static void CocktailSort(int[] A) { int left = 0; int right = A.length - 1; while (left < right) { for (int i = left; i < right; i++) { if (A[i] > A[i + 1]) { swap(A, i, i + 1); } } for (int i = right; i > left; i--) { if (A[i - 1] > A[i]) { swap(A, i - 1, i); } } right--; left++; } } /** * 选择排序 * 分类 -------------- 内部比较排序 * 数据结构 ---------- 数组 * 最差时间复杂度 ---- O(n^2) * 最优时间复杂度 ---- O(n^2) * 平均时间复杂度 ---- O(n^2) * 所需辅助空间 ------ O(1) * 稳定性 ------------ 不稳定 * * @param A */ public static void SelectionSort(int[] A) { for (int i = 0; i < A.length; i++) { int min = i; for (int k = i + 1; k < A.length; k++) { if (A[min] > A[k]) { min = k; } } if (min != i) { swap(A, min, i); } } } /** * 插入排序 * @param A */ public static void InsertionSort(int A[]){ int[] get=A; for (int i=0;i<A.length;i++){ int temp=A[i]; } } public static void main(String[] args) { int A[] = {6, 5, 3, 1, 5, 8, 7, 2, 4}; // BubbleSort(A); // CocktailSort(A); SelectionSort(A); System.out.print("从小到大冒泡排序结果:"); for (int i : A) { System.out.printf("%n" + i); } } }
true
d49cd438ed97e4507a946678aa0aff4d58b796f1
Java
antoniodanielbf-isep/LAPR3-2020
/src/main/java/lapr/project/ui/ParkUI.java
UTF-8
5,862
2.828125
3
[]
no_license
package lapr.project.ui; import lapr.project.controller.ParkController; import lapr.project.model.Park; import lapr.project.model.ParkPlace; import lapr.project.model.files.ReadFiles; import lapr.project.model.utils.Utils; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.List; /** * The type Park ui. */ public class ParkUI { public static void readAllScenarios() { try { ArrayList<String[]> list = ReadFiles.readFileScenario(Utils.getPath() + "ReadParkScenario.txt"); if (list.isEmpty()) { Logger.log("Could't load desired scene..."); } else { for (String[] op : list) { if (op[0].charAt(0) == '#') { continue; } switch (op[0]) { case "c": createPark(new Park(Integer.parseInt(op[1]), Integer.parseInt(op[2]), Integer.parseInt(op[3]), Integer.parseInt(op[4]), Integer.parseInt(op[5]))); break; case "s": showParks(); break; case "u": updatePark(new Park(Integer.parseInt(op[1]), Integer.parseInt(op[2]), Integer.parseInt(op[3]), Integer.parseInt(op[4]), Integer.parseInt(op[5]))); break; case "r": removePark(Integer.parseInt(op[1])); break; case "cp": createParkPlace( new ParkPlace( Integer.parseInt(op[1]), Integer.parseInt(op[2]) == 1), Integer.parseInt(op[3]) == 1); break; } } } } catch (FileNotFoundException e) { Logger.log(" Couldn't open the scene file..."); } } /** * Show parks. */ public static void showParks() { ParkController parkController = new ParkController(); Logger.log("/--------------------------------------------------------\\%n"); Logger.log(" Parks currently open: %n"); List<Park> parkList = parkController.showParks(); Utils.listar(parkList); Logger.log("\\--------------------------------------------------------/%n"); } /** * Create park. * * @param park the park */ public static void createPark(Park park) { ParkController parkController = new ParkController(); StringBuilder builder = new StringBuilder(); boolean created = parkController.createPark(park); String message = created ? " Created successfully.\n" : "There was a problem.\n"; builder.append("----------------------------------------------------------------------------\n"); builder.append(" Creating park in pharmacy with ID: \n"); builder.append(park.getPharmacyID()).append("\n"); builder.append(message); builder.append("--------------------------------------------------------------------------------\n"); Logger.log(builder.toString()); } /** * Update park. * * @param park the park */ public static void updatePark(Park park) { ParkController parkController = new ParkController(); StringBuilder builder = new StringBuilder(); boolean updated = parkController.updatePark(park); String message = updated ? " Updated successfully." : "There was a problem."; builder.append("/--------------------------------------------------------\\"); builder.append(" Updating park in pharmacy with ID: "); builder.append(park.getPharmacyID()).append("\n"); builder.append(message); builder.append("\\--------------------------------------------------------/"); Logger.log(builder.toString()); } /** * Remove park. * * @param parkId the park id */ public static void removePark(int parkId) { ParkController parkController = new ParkController(); StringBuilder builder = new StringBuilder(); boolean removed = parkController.removePark(parkId); String message = removed ? " Removed successfully." : "There was a problem."; builder.append("/--------------------------------------------------------\\"); builder.append(" Removing park with ID: "); builder.append(parkId).append("\n"); builder.append(message); builder.append("\\--------------------------------------------------------/"); Logger.log(builder.toString()); } public static void createParkPlace(ParkPlace place, boolean isCharging) { ParkController parkController = new ParkController(); StringBuilder builder = new StringBuilder(); boolean created = parkController.createParkPlace(place, isCharging); String message = created ? " Created successfully." : "There was a problem."; builder.append("/--------------------------------------------------------\\\n"); builder.append(" Creating place with ID: \n"); builder.append(place.getId()).append("\n"); builder.append(message); builder.append("\\--------------------------------------------------------/\n"); Logger.log(builder.toString()); } }
true
089bda03cc431dcb3a1acad88beed8d136a96a2a
Java
1357189884/petMetting
/src/main/java/cn/tedu/controller/LoginController.java
UTF-8
2,959
2.25
2
[]
no_license
package cn.tedu.controller; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import cn.tedu.pojo.User; import cn.tedu.service.UserService; import cn.tedu.utils.Md5Utils; @Controller public class LoginController { @Autowired private UserService userService; /** * 转向到登录界面 * @return */ @RequestMapping("/tologin") public String tologin(){ return "/sysadmin/login/login"; } /** * 登录功能实现 * @param username 用户名 * @param password 密码 * @param model * @param response * @param request * @return * @throws UnsupportedEncodingException */ @RequestMapping("/login") public String login(String username,String password,Model model,HttpServletResponse response,HttpServletRequest request) throws UnsupportedEncodingException{ if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){ model.addAttribute("msg", "用户名或密码不能为空!"); return "/sysadmin/login/login"; } //进行md5加密 password = Md5Utils.getMd5(password, username); User user = userService.login(username,password); if(user==null){ model.addAttribute("msg", "用户名或密码不正确!"); return "/sysadmin/login/login"; } else { if ("true".equals(request.getParameter("remname"))) { Cookie cookie = new Cookie("remname", URLEncoder.encode( username, "utf-8")); cookie.setMaxAge(3600 * 24 * 30); cookie.setPath(request.getContextPath() + "/"); response.addCookie(cookie); } else { Cookie cookie = new Cookie("remname", ""); cookie.setMaxAge(0); cookie.setPath(request.getContextPath() + "/"); response.addCookie(cookie); } if ("true".equals(request.getParameter("autologin"))) { Cookie autoCk = new Cookie("autologin", URLEncoder.encode( username + ":" + password, "utf-8")); autoCk.setPath(request.getContextPath() + "/"); autoCk.setMaxAge(3600 * 24 * 30); response.addCookie(autoCk); } else { Cookie autoCk = new Cookie("autologin", ""); autoCk.setPath(request.getContextPath() + "/"); autoCk.setMaxAge(0); response.addCookie(autoCk); } //登录成功,将其存到session中 request.getSession().setAttribute("_CURRENT_USER", user); return "redirect:/home"; } } /** * 注销 * @param session */ @RequestMapping("/logout.action") public void logouot(HttpSession session) { session.invalidate(); } }
true
ba570b23fd34e8fcf32ceb9126dbd6d91fdd4bda
Java
williamfeng91/chord_cloud
/Parse-Starter-Project-1.8.2/ParseStarterProject/src/com/parse/starter/ParseStarterProjectActivity.java
UTF-8
1,448
2.125
2
[ "LicenseRef-scancode-unicode-mappings", "BSD-3-Clause", "Apache-2.0" ]
permissive
package com.parse.starter; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import com.parse.ParseAnalytics; public class ParseStarterProjectActivity extends Activity { /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); ParseAnalytics.trackAppOpenedInBackground(getIntent()); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the options menu from XML MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.options_menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { if (item.getTitle().equals("Search")) { return onSearchRequested(); } else { return false; } } private void hideKeyboard() { View view = getCurrentFocus(); if (view != null) { InputMethodManager inputManager = (InputMethodManager) getSystemService( Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } }
true
32ad65381dc4c55420fb21294403323ec0b9c468
Java
jonesbusy/killerbox
/Sources/Client/Client/src/killerbox/game/Tir.java
ISO-8859-1
4,524
2.65625
3
[]
no_license
package killerbox.game; import java.awt.Color; import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import java.awt.geom.Line2D; import killerbox.network.KillerBoxController; public class Tir { private static final int DEGATS = 3; private Point position; private Double angle; private TypeTir tir; private int FPS = 25; private ModelGame modelGame; private char delim = '#'; private Tir thisTir = this; // pour les thread anonyme private KillerBoxController controllerReseau; private boolean fin = false; private Joueur joueur; private Thread gestionTir = new Thread(new Runnable() { public void run() { int waitTime = 1000 / FPS; Point posFutur = new Point(); while(!fin) { try { Thread.sleep(waitTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Rcuprer la position futur posFutur.x = position.x + (int)(Math.cos(angle) * tir.getVitesse()); posFutur.y = position.y + (int)(Math.sin(angle) * tir.getVitesse()); // Vrifier que le tir n'entre pas en collision avec une personne // ou un objet for (Rectangle mur : modelGame.getCarte().getMurs()) { if (intersectionLigneRectangle(position,posFutur,mur)) fin = true; } for (Joueur joueurTouche : modelGame.getJoueurs()) { if (joueurTouche != joueur && intersectionLigneRectangle(position,posFutur,joueurTouche.getRectangle())) { // Si le joueur est le joueur actif, on peut dcrmenter la vide du joueur touch if (modelGame.getJoueurActif() == joueur) { joueurTouche.setPv(joueurTouche.getPv() - DEGATS); // Indiquer aux autres joueurs qu'un joueur a t touch controllerReseau.sendInfosGameOtherPlayers("positionJoueur#"+joueurTouche.toString()); // Indiquer aux autres joueurs que le joueur est mort if (joueurTouche.getPv() <= 0) { modelGame.incrementerScore(joueur.getNom(), ScoreJoueur.SCORE_TUE); controllerReseau.sendInfosGameOtherPlayers("joueurMort#"+joueurTouche.getNom() + "#" + modelGame.getJoueurActif().getNom()); modelGame.addMessage(new Message("Vous avez tu " + joueurTouche.getNom() + "!", Color.RED)); modelGame.removeJoueur(joueurTouche); } else { controllerReseau.sendInfosGameMessage(modelGame.getJoueurActif().getNom() + " a touch " + joueurTouche.getNom()); modelGame.incrementerScore(joueur.getNom(), ScoreJoueur.SCORE_TOUCHE); } controllerReseau.sendInfosGameOtherPlayers("score#"+modelGame.getJoueurActif().getNom() + "#" + modelGame.getScore(joueur.getNom())); } fin = true; } } position.setLocation(posFutur); } // TODO peut mettre une animation de fin du tir (explosion) // Supprimer le tir de la liste modelGame.removeTir(thisTir); } private boolean intersectionLigneRectangle(Point source, Point position, Rectangle mur) { if (Line2D.linesIntersect(source.x, source.y, position.x, position.y, mur.x, mur.y, mur.x+mur.width, mur.y)) return true; else if (Line2D.linesIntersect(source.x, source.y, position.x, position.y, mur.x+mur.width, mur.y, mur.x, mur.y+mur.height)) return true; else if (Line2D.linesIntersect(source.x, source.y, position.x, position.y, mur.x, mur.y + mur.height, mur.x + mur.width, mur.y+mur.height)) return true; else if (Line2D.linesIntersect(source.x, source.y, position.x, position.y, mur.x, mur.y, mur.x, mur.y+mur.height)) return true; return false; } }); public void dessiner(Graphics g) { g.setColor(Color.ORANGE); g.fillOval(position.x, position.y, 6, 6); } public Tir(Joueur joueur, Double angle, TypeTir tir, ModelGame modelGame, KillerBoxController controllerReseau) { super(); this.joueur = joueur; this.angle = angle; this.tir = tir; this.modelGame = modelGame; this.position = new Point(joueur.getPosX(),joueur.getPosY()); this.controllerReseau = controllerReseau; gestionTir.start(); } public Point getPosition() { return new Point(position); } public String toString() { return joueur.getNom() + delim + angle.toString() + delim + tir.toString(); } public void arreter() { fin = true; } }
true
8502b270d826b6d682ec6867a8f16fece0b64b40
Java
woshizuimeili/onlineTest
/app/src/main/java/com/example/niyali/onlinetest/db/OnlineTestOpenHelper.java
UTF-8
1,328
2.34375
2
[ "Apache-2.0" ]
permissive
package com.example.niyali.onlinetest.db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /** * Created by niyali on 17/4/8. */ public class OnlineTestOpenHelper extends SQLiteOpenHelper { public static final String CREATE_PROVINCE="create table Province(id integer primary key" + " autoincrement,province_name text,province_code integer)"; public static final String CREATE_YEAR="create table Year(id integer primary key" + " autoincrement,year_name text,year_code integer,province_code integer)"; public static final String CREATE_EXAM="create table Exam(id integer" + " ,exam_context text,choose_A text,choose_B text,choose_C text,choose_D text," + "correct_answer text,year_code integer,explain text)"; public OnlineTestOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context,name,factory,version); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_PROVINCE); db.execSQL(CREATE_YEAR); db.execSQL(CREATE_EXAM); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
true
c8c1dc0b8af7c60c674c7bede1f6462d3a34900a
Java
Louiswang86/Aria
/PublicComponent/src/main/java/com/arialyy/aria/core/loader/LoaderStructure.java
UTF-8
1,354
2.15625
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2016 AriaLyy(https://github.com/AriaLyy/Aria) * * 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.arialyy.aria.core.loader; import com.arialyy.aria.core.inf.IThreadStateManager; import java.util.ArrayList; import java.util.List; public class LoaderStructure { private List<ILoaderComponent> parts = new ArrayList<>(); public void accept(ILoaderVisitor visitor) { for (ILoaderComponent part : parts) { part.accept(visitor); } } /** * 将组件加入到集合,必须添加以下集合: * 1 {@link IRecordHandler} * 2 {@link IInfoTask} * 3 {@link IThreadStateManager} * 4 {@link IThreadTaskBuilder} * * @param component 待添加的组件 */ public LoaderStructure addComponent(ILoaderComponent component) { parts.add(component); return this; } }
true
028d8635aae79bb0d707b4d7380d767ab78a108a
Java
ojmakhura/andromda
/andromda-core/src/main/java/org/andromda/core/transformation/XslTransformer.java
UTF-8
5,817
2.3125
2
[ "Apache-1.1", "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
package org.andromda.core.transformation; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.URIResolver; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.andromda.core.common.AndroMDALogger; import org.andromda.core.common.ResourceUtils; import org.andromda.core.configuration.Transformation; import org.apache.commons.lang3.StringUtils; /** * An implementation of Transformer that provides * XSLT transformations. The {@link #transform(String, Transformation[])} * operation will apply the given XSLT files to the model * in the order which they are found. * * @author Chad Brandon */ public class XslTransformer implements Transformer { /** * Applies the given XSLT files to the model in the order in which they are found. * * @see org.andromda.core.transformation.Transformer#transform(String, org.andromda.core.configuration.Transformation[]) */ public InputStream transform( final String modelUri, final Transformation[] xsltTransformations) { try { InputStream stream = null; if (StringUtils.isNotBlank(modelUri)) { final URL modelUrl = new URL(modelUri); if (xsltTransformations != null && xsltTransformations.length > 0) { Source modelSource = new StreamSource(modelUrl.openStream()); final Collection<Transformation> xslts = Arrays.asList(xsltTransformations); final TransformerFactory factory = TransformerFactory.newInstance(); final TransformerURIResolver resolver = new TransformerURIResolver(); factory.setURIResolver(resolver); for (final Iterator<Transformation> xsltIterator = xslts.iterator(); xsltIterator.hasNext();) { final Transformation transformation = xsltIterator.next(); final URL xslt = new URL(transformation.getUri()); resolver.setLocation(xslt); AndroMDALogger.info("Applying transformation --> '" + xslt + '\''); final Source xsltSource = new StreamSource(xslt.openStream()); final javax.xml.transform.Transformer transformer = factory.newTransformer(xsltSource); final ByteArrayOutputStream output = new ByteArrayOutputStream(); final Result result = new StreamResult(output); transformer.transform(modelSource, result); final byte[] outputResult = output.toByteArray(); stream = new ByteArrayInputStream(outputResult); // if we have an output location specified, write the result final String outputLocation = transformation.getOutputLocation(); if (StringUtils.isNotBlank(outputLocation)) { final File fileOutput = new File(outputLocation); final File parent = fileOutput.getParentFile(); if (parent != null) { parent.mkdirs(); } FileOutputStream outputStream = new FileOutputStream(fileOutput); AndroMDALogger.info("Transformation output: '" + outputLocation + '\''); outputStream.write(outputResult); outputStream.flush(); outputStream.close(); } if (xsltIterator.hasNext()) { modelSource = new StreamSource(stream); } } } else { stream = modelUrl.openStream(); } } return stream; } catch (final Exception exception) { throw new XslTransformerException(exception); } } /** * Provides the URI resolving capabilities for the * {@link XslTransformer} */ static final class TransformerURIResolver implements URIResolver { /** * @see javax.xml.transform.URIResolver#resolve(String, String) */ public Source resolve( final String href, final String base) throws TransformerException { Source source = null; if (this.location != null) { String locationUri = ResourceUtils.normalizePath(this.location.toString()); locationUri = locationUri.substring(0, locationUri.lastIndexOf('/') + 1); source = new StreamSource(locationUri + href); } return source; } /** * The current transformation location. */ private URL location; /** * Sets the location of the current transformation. * * @param location the transformation location as a URI. */ public void setLocation(URL location) { this.location = location; } } }
true
6d2c2ed3fd20cf6054702dd3e1d6058ee89013b5
Java
Anthonyyma/PhenoCount
/code/pheno_count/app/src/main/java/com/cmput301w21t36/phenocount/controller/ExpManager.java
UTF-8
17,224
2.046875
2
[]
no_license
package com.cmput301w21t36.phenocount; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.android.gms.tasks.Task; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.DocumentReference; import com.google.firebase.firestore.DocumentSnapshot; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; /** * This Class acts as an controller class for Experiments */ public class ExpManager { private final String TAG = "PhenoCount"; /** * This method populates the list of current user's experiments in the MainActivity * @param db * @param expDataList * @param expAdapter * @param UUID * @see MainActivity */ public void getExpData(FirebaseFirestore db, ArrayList<com.cmput301w21t36.phenocount.Experiment> expDataList, ArrayAdapter<com.cmput301w21t36.phenocount.Experiment> expAdapter, String UUID, int mode, ListView expListView){ //Google Developers, 2021-02-11, CCA 4.0/ Apache 2.0, https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Query db.collection("Experiment") .whereEqualTo("owner",UUID).orderBy("status") .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException error) { if(queryDocumentSnapshots.isEmpty()){ expListView.setBackgroundResource(R.drawable.hint_main); }else{ expListView.setBackgroundResource(R.drawable.hint_white); } getdata(db, expDataList, expAdapter, mode, queryDocumentSnapshots, error); } }); } /** * This method populates the list of current user's subcribed experiments * in the ShowSubscribedListActivity * @param db * @param expDataList * @param expAdapter * @param UUID * @param mode * @param subListView */ public void getSubExpData(FirebaseFirestore db, ArrayList<com.cmput301w21t36.phenocount.Experiment> expDataList, ArrayAdapter<com.cmput301w21t36.phenocount.Experiment> expAdapter, String UUID, int mode, ListView subListView){ db.collection("Experiment") .whereArrayContains("sub_list",UUID) .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException error) { if(queryDocumentSnapshots.isEmpty()){ subListView.setBackgroundResource(R.drawable.hint_sub); }else{ subListView.setBackgroundResource(R.drawable.hint_white); } getdata(db, expDataList, expAdapter, mode, queryDocumentSnapshots, error); } }); } /** * This method is called to update trial data received from the respective trial classes * to firebase * it creates a hash map object and adds the data to the collection * @param db * the Firestore Database * @param exp * the updated experiment object */ public void updateTrialData(FirebaseFirestore db, com.cmput301w21t36.phenocount.Experiment exp, String username){ if (exp != null) { final CollectionReference collectionReference = db.collection("Trials"); HashMap<String, String> fdata = new HashMap<>(); String id = collectionReference.document().getId(); //common attributes if(exp.getTrials().size()!=0) { com.cmput301w21t36.phenocount.Trial trial = exp.getTrials().get(exp.getTrials().size() - 1); fdata.put("Latitude", "" + trial.getLatitude()); fdata.put("Longitude", "" + trial.getLongitude()); fdata.put("type", exp.getExpType()); fdata.put("owner", username); fdata.put("userID", trial.getOwner().getUID()); fdata.put("status",Boolean.toString(trial.getStatus())); fdata.put("date",trial.getDate()); if (exp.getExpType().equals("Binomial")) { com.cmput301w21t36.phenocount.Binomial btrial = (com.cmput301w21t36.phenocount.Binomial) exp.getTrials().get(exp.getTrials().size() - 1); fdata.put("result", String.valueOf(btrial.getResult())); } else if (exp.getExpType().equals("Count")) { com.cmput301w21t36.phenocount.Count ctrial = (com.cmput301w21t36.phenocount.Count) exp.getTrials().get(exp.getTrials().size() - 1); fdata.put("result", String.valueOf(ctrial.getCount())); } else if (exp.getExpType().equals("Measurement")) { com.cmput301w21t36.phenocount.Measurement mtrial = (com.cmput301w21t36.phenocount.Measurement) exp.getTrials().get(exp.getTrials().size() - 1); fdata.put("result", String.valueOf(mtrial.getMeasurement())); } else if (exp.getExpType().equals("NonNegativeCount")) { com.cmput301w21t36.phenocount.NonNegativeCount ntrial = (com.cmput301w21t36.phenocount.NonNegativeCount) exp.getTrials().get(exp.getTrials().size() - 1); fdata.put("result", String.valueOf(ntrial.getValue())); } //adding data to firebase db.collection("Experiment") .document(exp.getExpID()).collection("Trials") .add(fdata) .addOnSuccessListener(new OnSuccessListener<DocumentReference>() { @Override public void onSuccess(DocumentReference documentReference) { Log.d(TAG, "Data added successfully!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // These are a method which gets executed if there’s any problem Log.d(TAG, "Data could not be added!" + e.toString()); } }); } } } /** * Method for ignoring the trials * @param exp */ public void ignoreTrial(com.cmput301w21t36.phenocount.Experiment exp){ com.cmput301w21t36.phenocount.DatabaseManager dm = new com.cmput301w21t36.phenocount.DatabaseManager(); FirebaseFirestore db = dm.getDb(); for (com.cmput301w21t36.phenocount.Trial trial: exp.getTrials()){ if (!trial.getStatus()){ String UUID = trial.getOwner().getUID(); db.collection("Experiment").document(exp.getExpID()) .collection("Trials") .whereEqualTo("userID",UUID) .addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { for (QueryDocumentSnapshot document : value) { if(error ==null){ db.collection("Experiment") .document(exp.getExpID()).collection("Trials") .document(document.getId()) .update("status","false"); } } } }); } } } /** * General method for querying the Experiment collection in fireStore * @param db * @param expDataList * @param expAdapter * @param queryDocumentSnapshots * @param error */ public void getdata(FirebaseFirestore db, ArrayList<com.cmput301w21t36.phenocount.Experiment> expDataList, ArrayAdapter<com.cmput301w21t36.phenocount.Experiment> expAdapter, int mode, QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException error){ expDataList.clear(); for (QueryDocumentSnapshot doc : queryDocumentSnapshots) { if (error == null) { Log.d("pheno", String.valueOf(doc.getId())); String expID = doc.getId(); String name = (String) doc.getData().get("name"); String description = (String) doc.getData().get("description"); String region = (String) doc.getData().get("region"); String type = (String) doc.getData().get("type"); String minInt = (String) doc.getData().get("minimum_trials"); String reqGeo = (String) doc.getData().get("require_geolocation"); String mStat = (String) doc.getData().get("status"); String owner = (String) doc.getData().get("owner"); ArrayList sList = (ArrayList) doc.getData().get("sub_list"); boolean reqLoc; if (reqGeo.equals("YES")) { reqLoc = true; } else { reqLoc = false; } int minTrial = 1; if (!minInt.isEmpty()) { minTrial = Integer.parseInt(minInt); } int expStatus = 0; if (!mStat.isEmpty()) { expStatus = Integer.parseInt(mStat); } com.cmput301w21t36.phenocount.Experiment newExp = new com.cmput301w21t36.phenocount.Experiment(name, description, region, type, minTrial, reqLoc, expStatus, expID); Profile newProfile = new Profile(); User currentUser = new User(owner, newProfile); newExp.setOwner(currentUser); newExp.setSubscribers(sList); Task<DocumentSnapshot> userDocument = db.collection("User") .document(newExp.getOwner().getUID()) .get() .addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() { @Override public void onComplete(@NonNull Task<DocumentSnapshot> task) { if (task.getResult().getData()!=null) { String phoneNumber = (String) task.getResult().getData().get("ContactInfo"); String username = (String) task.getResult().getData().get("Username"); newExp.getOwner().getProfile().setUsername(username); newExp.getOwner().getProfile().setPhone(phoneNumber); expAdapter.notifyDataSetChanged(); } } }); //adding the list of trials to each exp object db.collection("Experiment").document(newExp.getExpID()).collection("Trials").addSnapshotListener(new EventListener<QuerySnapshot>() { @Override public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException error) { ArrayList<com.cmput301w21t36.phenocount.Trial> trials = new ArrayList<>(); for (QueryDocumentSnapshot doc : queryDocumentSnapshots) { Log.d("pheno", String.valueOf(doc.getId())); String username = (String) doc.getData().get("owner"); String userID = (String) doc.getData().get("userID"); String latitude = (String) doc.getData().get("Latitude"); String longitude = (String) doc.getData().get("Longitude"); String status = (String) doc.getData().get("status"); String date = (String) doc.getData().get("date"); String ttype = newExp.getExpType(); Profile profile = new Profile(); profile.setUsername(username); User user = new User(userID,profile); //retrieving result from firebase String result = (String) doc.getData().get("result"); if (result != null) { if (ttype.equals("Count")) { com.cmput301w21t36.phenocount.Count ctrial = new com.cmput301w21t36.phenocount.Count(user); ctrial.setType(ttype); ctrial.setDate(date); ctrial.setStatus(Boolean.parseBoolean(status)); ctrial.setLatitude(Float.parseFloat(latitude)); ctrial.setLongitude(Float.parseFloat(longitude)); ctrial.setCount(Integer.parseInt(result)); trials.add(ctrial); } else if (ttype.equals("Binomial")) { com.cmput301w21t36.phenocount.Binomial btrial = new com.cmput301w21t36.phenocount.Binomial(user); btrial.setType(ttype); btrial.setDate(date); btrial.setStatus(Boolean.parseBoolean(status)); btrial.setLatitude(Float.parseFloat(latitude)); btrial.setLongitude(Float.parseFloat(longitude)); btrial.setResult(Boolean.parseBoolean(result)); trials.add(btrial); } else if (ttype.equals("Measurement")) { com.cmput301w21t36.phenocount.Measurement mtrial = new com.cmput301w21t36.phenocount.Measurement(user); mtrial.setType(ttype); mtrial.setDate(date); mtrial.setStatus(Boolean.parseBoolean(status)); mtrial.setLatitude(Float.parseFloat(latitude)); mtrial.setLongitude(Float.parseFloat(longitude)); mtrial.setMeasurement(Float.parseFloat(result)); trials.add(mtrial); } else if (ttype.equals("NonNegativeCount")) { com.cmput301w21t36.phenocount.NonNegativeCount ntrial = new com.cmput301w21t36.phenocount.NonNegativeCount(user); ntrial.setType(ttype); ntrial.setDate(date); ntrial.setStatus(Boolean.parseBoolean(status)); ntrial.setLatitude(Float.parseFloat(latitude)); ntrial.setLongitude(Float.parseFloat(longitude)); ntrial.setValue(Integer.parseInt(result)); trials.add(ntrial); } } } newExp.setTrials(trials); } }); // To remove the unpublished experiments from the subscribed experiment list // mode 0 for search and owner's experiment list // mode 1 for subscribed experiment list if (mode == 1){ if (!(expStatus == 3)){ expDataList.add(newExp); } }else if (mode == 0) { expDataList.add(newExp); } } } expAdapter.notifyDataSetChanged(); } }
true
228285445a584435f5692db1d76033fe93339277
Java
ronlik26/CatchTheParachutist
/vehicle/VehiclesFactory.java
UTF-8
1,403
3.25
3
[]
no_license
package game.vehicle; /** * This class implement the factory pattern but not in the full capacity because * at the moment there is only one type of parachute but by using the factory pattern * it gives the opportunity to extend the software in the future * @author Ron * */ public class VehiclesFactory { private static String BOAT_IMG_PATH = "images/boat.png"; private static String PARACHUT_IMG_PATH = "images/parachutist.png"; private static String PLANE_IMG_PATH = "images/plane.png"; /** * The method get number of parachutes * and according to that create the ComputerParachutes * * @param number of parachutes, parachute difficulty * @return an array of parachutes */ public static ComputerParachute[] createParachutes(int numOfPara, String difficulty) { ComputerParachute [] parachuts = new ComputerParachute[numOfPara]; for(int i = 0; i < numOfPara; i++){ parachuts[i] = new ComputerParachute(PARACHUT_IMG_PATH, difficulty); } return parachuts; } /** * The method create boat * * * @param * @return a plane */ public static UserBoat createBoat() { return new UserBoat(BOAT_IMG_PATH); } /** * The method create plane * * * @param * @return a plane */ public static ComputerPlane createPlane() { return new ComputerPlane(PLANE_IMG_PATH); } }
true
2eda7d54e858d662057861902770ce23de905b33
Java
noragalvin/java-corba-manage-library
/QuanLyThuVien/src/ObjectInterface/BillModule/BillInterfaceOperations.java
UTF-8
929
2
2
[]
no_license
package ObjectInterface.BillModule; /** * ObjectInterface/BillModule/BillInterfaceOperations.java . * Generated by the IDL-to-Java compiler (portable), version "3.2" * from Module/Bill.idl * Thursday, December 5, 2019 9:25:24 PM ICT */ public interface BillInterfaceOperations { int id (); void id (int newId); int status (); void status (int newStatus); int readerID (); void readerID (int newReaderID); String createdAt (); void createdAt (String newCreatedAt); String deadline (); void deadline (String newDeadline); String readerName (); void readerName (String newReaderName); String bookName (); void bookName (String newBookName); ObjectInterface.BillModule.Bill getSingle (int id); ObjectInterface.BillModule.Bill[] list (int readerID); void borrowBook (int readerID, int[] bookIDs, String deadline); boolean payBook (int[] ids, int billID); } // interface BillInterfaceOperations
true
f6d24b8077a4fd6ab3f8e129b8db5223cdf18060
Java
toannguyen1109/Project1_toannvph06277
/app/src/main/java/com/fpoly/dell/project/model/VatNuoi.java
UTF-8
1,674
2.140625
2
[]
no_license
package com.fpoly.dell.project.model; public class VatNuoi { private String mavatnuoi; private String Machungloai; private String Soluong; private String Loaithucan; private String Suckhoe; public VatNuoi(){} public VatNuoi(String mavatnuoi, String machungloai, String soluong, String loaithucan, String suckhoe) { this.mavatnuoi = mavatnuoi; this.Machungloai = machungloai; this.Soluong = soluong; this.Loaithucan = loaithucan; this.Suckhoe = suckhoe; } public String getMavatnuoi() { return mavatnuoi; } public void setMavatnuoi(String mavatnuoi) { this.mavatnuoi = mavatnuoi; } public String getMachungloai() { return Machungloai; } public void setMachungloai(String machungloai) { Machungloai = machungloai; } public String getSoluong() { return Soluong; } public void setSoluong(String soluong) { Soluong = soluong; } public String getLoaithucan() { return Loaithucan; } public void setLoaithucan(String loaithucan) { Loaithucan = loaithucan; } public String getSuckhoe() { return Suckhoe; } public void setSuckhoe(String suckhoe) { Suckhoe = suckhoe; } @Override public String toString() { return "VatNuoi{" + "mavatnuoi='" + mavatnuoi + '\'' + ", Machungloai='" + Machungloai + '\'' + ", Soluong='" + Soluong + '\'' + ", Loaithucan='" + Loaithucan + '\'' + ", Suckhoe='" + Suckhoe + '\'' + '}'; } }
true
adac3c31507adb9570d72987f4062c5428aae036
Java
Molsbee/movie
/src/main/java/org/molsbee/movie/model/security/AccountAuthority.java
UTF-8
466
2.03125
2
[]
no_license
package org.molsbee.movie.model.security; import lombok.Data; import javax.persistence.*; import java.io.Serializable; @Data @Entity @Table(name = "account_authorities") public class AccountAuthority implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @Column(name = "authority") @Enumerated(EnumType.STRING) private Authority authority; }
true
2366050205f47c9620c3ef72695a20a050a3af30
Java
AndileGumada/interfaces
/src/com/oca/animals/MyInterface.java
UTF-8
221
2.296875
2
[]
no_license
package com.oca.animals; public interface MyInterface extends BaseInterface1, BaseInterface2 { @Override default void saySomething() { // TODO Auto-generated method stub BaseInterface1.super.saySomething(); } }
true
0b3e6853fc1f59309c1d5e95bf89bfea0b9b6d52
Java
jenson2000/JENWEB
/JENWEB/src/test/java/spring/TestDao.java
UTF-8
763
2.171875
2
[]
no_license
package spring; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.jen.sen.persistence.dao.system.IUserDao; import com.jen.sen.persistence.pojo.system.TUser; import baset.BaseTest; public class TestDao extends BaseTest { @Autowired private IUserDao iUserDao; @Test public void testUser() { TUser tu = iUserDao.findById(TUser.class, 1L); TUser tu1 = iUserDao.findById(TUser.class, 1L); TUser tu2 = iUserDao.findById(TUser.class, 1L); System.out.println("user"+tu.getUserAccount()+"--"+tu.getUserName()); System.out.println("user"+tu1.getUserAccount()+"--"+tu1.getUserName()); System.out.println("user"+tu2.getUserAccount()+"--"+tu2.getUserName()); } }
true
2f2d69a9061f366f5b94bf45b4874fd111c12153
Java
Miloosz/projektTestowy
/src/main/java/presentationExercises/Modulo.java
UTF-8
338
3.125
3
[]
no_license
package presentationExercises; public class Modulo { public static void main(String[] args) { double a = 10; double b = 9; double wynik = a/b; System.out.println("Wynik dzielenia to " + wynik); double roznica = a-b; System.out.println("Reszta z dzielenia to " + roznica); } }
true
ea1aa3c312a9968fd3b2887efb73ee10fc2ab83c
Java
BokoEnos/jmxfetch
/src/main/java/org/datadog/jmxfetch/JMXAttribute.java
UTF-8
9,400
1.953125
2
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
package org.datadog.jmxfetch; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.management.AttributeNotFoundException; import javax.management.InstanceNotFoundException; import javax.management.MBeanAttributeInfo; import javax.management.MBeanException; import javax.management.ObjectInstance; import javax.management.ReflectionException; public abstract class JMXAttribute { protected MBeanAttributeInfo attribute; protected Connection connection; protected ObjectInstance jmxInstance; protected double value; protected String domain; protected String beanName; protected String attributeName; protected LinkedHashMap<Object,Object> valueConversions; protected String[] tags; protected Configuration matching_conf; private static final String[] EXCLUDED_BEAN_PARAMS = {"domain", "bean_name", "bean", "attribute"}; private static final String FIRST_CAP_PATTERN = "(.)([A-Z][a-z]+)"; private static final String ALL_CAP_PATTERN = "([a-z0-9])([A-Z])"; private static final String METRIC_REPLACEMENT = "([^a-zA-Z0-9_.]+)|(^[^a-zA-Z]+)"; private static final String DOT_UNDERSCORE = "_*\\._*"; public JMXAttribute(MBeanAttributeInfo a, ObjectInstance jmxInstance, String instanceName, Connection connection, HashMap<String, String> instanceTags) { this.attribute = a; this.jmxInstance = jmxInstance; this.matching_conf = null; this.connection = connection; this.beanName = jmxInstance.getObjectName().toString(); // A bean name is formatted like that: org.apache.cassandra.db:type=Caches,keyspace=system,cache=HintsColumnFamilyKeyCache // i.e. : domain:bean_parameter1,bean_parameter2 String[] split = this.beanName.split(":"); this.domain = split[0]; this.attributeName = a.getName(); // We add the instance name as a tag. We need to convert the Array of strings to List in order to do that LinkedList<String> beanTags = new LinkedList<String>(Arrays.asList(split[1].replace("=",":").split(","))); beanTags.add("instance:"+instanceName); beanTags.add("jmx_domain:"+domain); if (instanceTags != null) { for (Map.Entry<String, String> tag : instanceTags.entrySet()) { beanTags.add(tag.getKey()+":"+tag.getValue()); } } this.tags = new String[beanTags.size()]; beanTags.toArray(this.tags); } @Override public String toString() { return "Bean name: " + this.beanName + " - Attribute name: " + this.attributeName + " - Attribute type: " + this.attribute.getType(); } public abstract LinkedList<HashMap<String, Object>> getMetrics() throws AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException; /** * An abstract function implemented in the inherited classes JMXSimpleAttribute and JMXComplexAttribute * * @param Configuration , a Configuration object that will be used to check if the JMX Attribute match this configuration * @return a boolean that tells if the attribute matches the configuration or not */ public abstract boolean match(Configuration conf); public int getMetricsCount() { try { return this.getMetrics().size(); } catch (Exception e) { return 0; } } protected Object getJmxValue() throws AttributeNotFoundException, InstanceNotFoundException, MBeanException, ReflectionException, IOException { return this.connection.getAttribute(this.jmxInstance.getObjectName(), this.attribute.getName()); } protected boolean matchDomain(Configuration conf) { return conf.include.get("domain") == null || ((String)(conf.include.get("domain"))).equals(this.domain); } protected boolean excludeMatchDomain(Configuration conf) { return conf.exclude.get("domain") != null && ((String)(conf.exclude.get("domain"))).equals(this.domain); } protected boolean excludeMatchBean(Configuration conf) { String bean = (String) conf.exclude.get("bean"); String confBeanName = (String) conf.exclude.get("bean_name"); if (this.beanName.equals(bean) || this.beanName.equals(confBeanName)) { return true; } for (String bean_attr: conf.exclude.keySet()) { if (Arrays.asList(EXCLUDED_BEAN_PARAMS).contains(bean_attr)) { continue; } HashMap<String, String> beanParams = new HashMap<String, String>(); for (String param : this.tags) { String[] paramSplit = param.split(":"); beanParams.put(paramSplit[0], paramSplit[1]); } if(conf.exclude.get(bean_attr).equals(beanParams.get(bean_attr))) { return true; } } return false; } protected static String convertMetricName(String metricName) { metricName = metricName.replaceAll(FIRST_CAP_PATTERN, "$1_$2"); metricName = metricName.replaceAll(ALL_CAP_PATTERN, "$1_$2").toLowerCase(); metricName = metricName.replaceAll(METRIC_REPLACEMENT, "_"); metricName = metricName.replaceAll(DOT_UNDERSCORE, ".").trim(); return metricName; } protected Object convertMetricValue(Object metricValue) { Object converted = metricValue; if (!getValueConversions().isEmpty()) { converted = this.getValueConversions().get(metricValue); if (converted == null && this.getValueConversions().get("default") != null) { converted = this.getValueConversions().get("default"); } } return converted; } protected double _getValueAsDouble(Object metricValue) { Object value = convertMetricValue(metricValue); if (value instanceof String) { return Double.parseDouble((String)value); } else if (value instanceof Integer) { return new Double((Integer)(value)); } else if (value instanceof AtomicInteger) { return new Double(((AtomicInteger)(value)).get()); } else if (value instanceof AtomicLong) { Long l = ((AtomicLong)(value)).get(); return l.doubleValue(); } else if (value instanceof Double) { return (Double)value; } else if (value instanceof Boolean) { return ((Boolean)value ? 1.0 : 0.0); } else if (value instanceof Long) { Long l = new Long((Long) value); return l.doubleValue(); } else if (value instanceof Number) { return ((Number)value).doubleValue(); } else { try{ return new Double((Double) value); } catch (Exception e) { throw new NumberFormatException(); } } } protected boolean matchBean(Configuration configuration) { boolean matchBeanName = false; if (configuration.include.get("bean") == null && configuration.include.get("bean_name") == null) { matchBeanName = true; } else if (configuration.include.get("bean") != null) { matchBeanName = ((String)(configuration.include.get("bean"))).equals(this.beanName); } else if (configuration.include.get("bean_name") != null) { matchBeanName = ((String)(configuration.include.get("bean_name"))).equals(this.beanName); } if (!matchBeanName) { return false; } for (String bean_attr: configuration.include.keySet()) { if (Arrays.asList(EXCLUDED_BEAN_PARAMS).contains(bean_attr)) { continue; } HashMap<String, String> beanParams = new HashMap<String, String>(); for (String param : this.tags) { String[] paramSplit = param.split(":"); beanParams.put(paramSplit[0], paramSplit[1]); } if (beanParams.get(bean_attr) == null || !((String)beanParams.get(bean_attr)).equals((String)configuration.include.get(bean_attr))) { return false; } } return true; } @SuppressWarnings("unchecked") protected HashMap<Object, Object> getValueConversions() { if (this.valueConversions == null) { if (this.matching_conf.include.get("attribute") instanceof LinkedHashMap<?, ?>) { LinkedHashMap<String, LinkedHashMap<Object, Object>> attribute = ((LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<Object, Object>>>)(this.matching_conf.include.get("attribute"))).get(this.attribute.getName()); if (attribute != null) { this.valueConversions = attribute.get("values"); } } if (this.valueConversions == null) { this.valueConversions = new LinkedHashMap<Object, Object>(); } } return this.valueConversions; } }
true
be8766ca0bd616701bb4961626f004ced09fb3a6
Java
GIacial/MenuAchat
/app/src/main/java/merejy/menuachat/ui/Button/OnClickListenerCreator/OnClickListenerCreator.java
UTF-8
282
1.984375
2
[]
no_license
package merejy.menuachat.ui.Button.OnClickListenerCreator; import android.view.View; import merejy.menuachat.ui.Activity.AbstractActivity; public interface OnClickListenerCreator <T> { View.OnClickListener createListener (final T item, final AbstractActivity activity); }
true
dce3b886315bcef841707b75387eaa5cb5247267
Java
mustafa-dev-repos/development-leaf-framework
/src/main/java/com/baselib/bean/metatype/MetaAnnotationType.java
UTF-8
547
1.898438
2
[]
no_license
package com.baselib.bean.metatype; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target( {ElementType.ANNOTATION_TYPE} ) @Retention( RetentionPolicy.RUNTIME ) @Documented /** * MetaMetaMeta layer information * * @Auhtor: Mustafa */ public @interface MetaAnnotationType { Class<? extends MetaAnnotationProcessor> handler() ; int order() default 1000; }
true
9cfdb2984e8057a6c9d7b560f0041b683bbcc071
Java
qinfuji/mn
/src/main/java/com/mn/modules/api/service/impl/ChancePointServiceImpl.java
UTF-8
16,271
1.820313
2
[ "Apache-2.0" ]
permissive
package com.mn.modules.api.service.impl; import com.alibaba.fastjson.JSONArray; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.baomidou.mybatisplus.core.metadata.IPage; import com.mn.modules.api.dao.AnalysisResultDao; import com.mn.modules.api.dao.ChancePointDao; import com.mn.modules.api.entity.AnalysisResult; import com.mn.modules.api.entity.ChancePoint; import com.mn.modules.api.remote.ChancePointEstimateService; import com.mn.modules.api.remote.ShopService; import com.mn.modules.api.service.ChancePointService; import com.mn.modules.api.vo.EstimateResult; import com.mn.modules.api.vo.Quota; import com.mn.modules.api.vo.QuotaItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; @Service public class ChancePointServiceImpl implements ChancePointService { private Logger logger = LoggerFactory.getLogger(ChancePointServiceImpl.class); @Autowired private ChancePointDao chancePointDao; @Autowired private ChancePointEstimateService chancePointEstimateService; @Autowired private ShopService shopService; @Autowired private AnalysisResultDao analysisResultDao; public ChancePointServiceImpl() { } public ChancePointServiceImpl(ChancePointDao chancePointDao,AnalysisResultDao analysisResultDao, ChancePointEstimateService chancePointEstimateService, ShopService shopService) { this.chancePointDao = chancePointDao; this.chancePointEstimateService = chancePointEstimateService; this.shopService = shopService; this.analysisResultDao = analysisResultDao; } @Override public ChancePoint createChancePoint(ChancePoint chancePoint) { chancePointDao.insert(chancePoint); return chancePoint; } @Override public ChancePoint updateChancePoint(ChancePoint chancePoint) { chancePointDao.updateById(chancePoint); return chancePoint; } @Override public IPage<ChancePoint> getChancePointList(String scope, String adCode, String appId, IPage pageParam, String userAccount) { QueryWrapper<ChancePoint> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("appId", appId); //无效状态的不显示 queryWrapper.ne("status" , CHANCE_STATUS_INVALID); if (AREA_SCOPE_PROVINCE.equals(scope)) { queryWrapper.eq("province", adCode); } else if (AREA_SCOPE_CITY.equals(scope)) { queryWrapper.eq("city", adCode); } else if (AREA_SCOPE_DISTRICT.equals(scope)) { queryWrapper.eq("district", adCode); } IPage page = chancePointDao.selectPage(pageParam, queryWrapper); List<ChancePoint> records = page.getRecords(); if (records.size() == 0) { return page; } List<ChancePoint> newrecords = new ArrayList<>(); records.forEach((record) -> { if (record.getShopId() == null) { String shopId = shopService.getChancePointShopId(userAccount, record); if (shopId != null) { record.setShopId(shopId); chancePointDao.updateById(record); } } newrecords.add(record); }); page.setRecords(newrecords); return page; } @Override public List<EstimateResult> getChanceEstimateResult(ChancePoint chancePoint, String userAccount, Date data) { //如果shopid为null 则需要先获取shopid if (chancePoint.getShopId() == null) { String shopId = shopService.getChancePointShopId(userAccount, chancePoint); if (shopId == null) { return null; } else { //更新 ChancePoint updateChancePoint = new ChancePoint(); updateChancePoint.setShopId(shopId); chancePointDao.updateById(updateChancePoint); chancePoint.setShopId(shopId); } } List<EstimateResult> result = new ArrayList<>(); if (chancePoint.getShopId() != null && !"".equals(chancePoint.getShopId())) { //商圈评估 //商圈人口体量. EstimateResult circleEstimateResult = new EstimateResult(); circleEstimateResult.setLabel("商圈评估"); Quota circlePopulation = chancePointEstimateService.getBusinessCirclePopulation(userAccount, chancePoint, new Date()); circlePopulation.setRuleName("circlePopulation"); //商圈活跃度 Quota circleActive = chancePointEstimateService.getBusinessCircleActive(userAccount, chancePoint, new Date()); circleActive.setRuleName("circleActive"); Quota circleCreateYear = new Quota(); circleCreateYear.setLabel("商圈形成年限"); circleCreateYear.setRemark("主要商业设施、居民小区建成时间"); circleCreateYear.setValues(new ArrayList<>()); circleCreateYear.setRuleName("circleCreateYear"); circleEstimateResult.add(circleCreateYear); Quota circleDevelopingTrend = new Quota(); circleDevelopingTrend.setLabel("商圈发展趋势"); circleDevelopingTrend.setRemark("政府发展规划"); circleDevelopingTrend.setValues(new ArrayList<>()); circleDevelopingTrend.setRuleName("circleDevelopingTrend"); circleEstimateResult.add(circleDevelopingTrend); if (circlePopulation != null) { circleEstimateResult.add(circlePopulation); } if (circleActive != null) { circleEstimateResult.add(circleActive); } result.add(circleEstimateResult); //商区评估 EstimateResult districtEstimateResult = new EstimateResult(); districtEstimateResult.setLabel("商区评估"); //商区人口体量 Quota districtPopulation = chancePointEstimateService.getBusinessDistrictPopulation(userAccount, chancePoint, new Date()); districtPopulation.setRuleName("districtPopulation"); //政府规划3年内小区人口体量 Quota districtPopulationIn3Year = new Quota(); districtPopulationIn3Year.setLabel("政府规划3年内小区人口体量"); districtPopulationIn3Year.setRemark("市政府规划数据"); districtPopulationIn3Year.setValues(new ArrayList<>()); districtPopulationIn3Year.setRuleName("districtPopulationIn3Year"); districtEstimateResult.add(districtPopulationIn3Year); //商区当前人口活跃度(入住率) Quota districtPopulationActive = new Quota(); districtPopulationActive.setLabel("商区当前人口活跃度-入住率"); districtPopulationActive.setRemark("周边主要小区的平均入住率"); districtPopulationActive.setValues(new ArrayList<>()); districtPopulationActive.setRuleName("districtPopulationActive"); districtEstimateResult.add(districtPopulationActive); //商区活跃度 Quota districtActive = chancePointEstimateService.getBusinessDistrictActive(userAccount, chancePoint, new Date()); districtActive.setRuleName("districtActive"); //商区公交路线数量、公交站点数 Quota districtBusNum = chancePointEstimateService.getBusinessDistrictBusNum(userAccount, chancePoint, new Date()); //需要将路线数量、公交站数拆分为两个指标 List<QuotaItem> items = districtBusNum.getValues(); if(items != null && items.size()>0){ items.forEach((item)->{ if("公交线".equals(item.getLabel())){ Quota districtBusLineNum = new Quota(); districtBusLineNum.setLabel("商区公交路线数量"); districtBusLineNum.setRemark("方圆500m内的交通枢纽数量"); districtBusLineNum.add(item); districtBusLineNum.setRuleName("districtBusLineNum"); districtEstimateResult.add(districtBusLineNum); }else if("公交站".equals(item.getLabel())){ Quota districtBusStopNum = new Quota(); districtBusStopNum.setLabel("商区公交路线数量"); districtBusStopNum.setRemark("以500m为半径"); districtBusStopNum.add(item); districtBusStopNum.setRuleName("districtBusStopNum"); districtEstimateResult.add(districtBusStopNum); } }); } //消费者活跃度 Quota districtCustomerActive = chancePointEstimateService.getBusinessDistrictCustomerActive(userAccount, chancePoint, new Date()); districtCustomerActive.setRuleName("districtCustomerActive"); //商区消费者有子女占比 Quota districtCustomerChildrenProportion = chancePointEstimateService.getBusinessDistrictCustomerChildrenProportion(userAccount, chancePoint, new Date()); districtCustomerChildrenProportion.setRuleName("districtCustomerChildrenProportion"); //商区关键配套 Quota districtMating = chancePointEstimateService.getBusinessDistrictMating(userAccount, chancePoint, new Date()); districtMating.setRuleName("districtMating"); //商区定位 Quota districtLevel = new Quota(); districtLevel.setLabel("商区定位"); districtLevel.setRemark("是否是城市核心商区"); districtLevel.setValues(new ArrayList<>()); districtLevel.setRuleName("districtLevel"); districtEstimateResult.add(districtLevel); if (districtPopulation != null) { districtEstimateResult.add(districtPopulation); } if (districtActive != null) { districtEstimateResult.add(districtActive); } if (districtCustomerActive != null) { districtEstimateResult.add(districtCustomerActive); } if (districtCustomerChildrenProportion != null) { districtEstimateResult.add(districtCustomerChildrenProportion); } if (districtMating != null) { districtEstimateResult.add(districtMating); } result.add(districtEstimateResult); //街道评估 EstimateResult streeEstimateResult = new EstimateResult(); streeEstimateResult.setLabel("街道评估"); //街道关键配套 Quota streetMating = chancePointEstimateService.getStreetMating(userAccount, chancePoint, new Date()); streetMating.setRuleName("streetMating"); if (streetMating != null) { streeEstimateResult.add(streetMating); } //落位街道主路口客流 Quota districtMainRoadRate = new Quota(); districtMainRoadRate.setLabel("落位街道主路口客流"); districtMainRoadRate.setRemark("日均客流"); districtMainRoadRate.setValues(new ArrayList<>()); districtMainRoadRate.setRuleName("districtMainRoadRate"); streeEstimateResult.add(districtMainRoadRate); result.add(streeEstimateResult); //席位评估 EstimateResult seatEstimateResult = new EstimateResult(); seatEstimateResult.setLabel("席位评估"); seatEstimateResult.setType("seatEstimateResult"); Quota seatDayPersonFlow = new Quota(); seatDayPersonFlow.setLabel("席位日均客流"); seatDayPersonFlow.setRemark (""); seatDayPersonFlow.setRuleName("seatDayPersonFlow"); seatEstimateResult.add(seatDayPersonFlow); Quota seatPositionFlow = new Quota(); seatPositionFlow.setLabel("落位位置-是否人流同侧"); seatPositionFlow.setRemark ("主干道人流方向,适用于双向4车道以上街道"); seatPositionFlow.setRuleName("seatPositionFlow"); seatEstimateResult.add(seatPositionFlow); Quota seatPositionDistance = new Quota(); seatPositionDistance.setLabel("落位位置-主路口距离"); seatPositionDistance.setRemark ("落位与街道两边路口距离"); seatPositionDistance.setRuleName("seatPositionDistance"); seatEstimateResult.add(seatPositionDistance); Quota seatDoorHeaderLen = new Quota(); seatDoorHeaderLen.setLabel("门头长度(米)"); seatDoorHeaderLen.setRemark (""); seatDoorHeaderLen.setRuleName("seatDoorheaderLen"); seatEstimateResult.add(seatDoorHeaderLen); Quota seatLeaseTerm = new Quota(); seatLeaseTerm.setLabel("签约年限"); seatLeaseTerm.setRemark (""); seatLeaseTerm.setRuleName("seatLeaseTerm"); seatEstimateResult.add(seatLeaseTerm); result.add(seatEstimateResult); //席位评估 EstimateResult competitorEstimateResult = new EstimateResult(); competitorEstimateResult.setLabel("竞品分布"); competitorEstimateResult.setType("competitorEstimateResult"); Quota competitorNum = new Quota(); competitorNum.setLabel("竞品店数量"); competitorNum.setRemark ("1km内竞品店面数量"); competitorNum.setRuleName("competitorNum"); competitorEstimateResult.add(competitorNum); Quota competitorDistance = new Quota(); competitorDistance.setLabel("最近竞品距离(米)"); competitorDistance.setRemark ("单位米"); competitorDistance.setRuleName("competitorDistance"); competitorEstimateResult.add(competitorDistance); result.add(competitorEstimateResult); return result; } return null; } @Override public ChancePoint queryChance(String id) { return chancePointDao.selectById(id); } @Override public AnalysisResult saveAnalysisResult(ChancePoint chancePoint, List<EstimateResult> estimateResultList) { AnalysisResult analysisResult = getAnalysisResult(chancePoint.getId()); String analysisResultString = JSONArray.toJSONString(estimateResultList); if(analysisResult != null){ //更新数据 analysisResult.setResult(analysisResultString); analysisResult.setUpdatedTime(new Date()); analysisResultDao.updateById(analysisResult); }else{ Date currentDate = new Date(); analysisResult = new AnalysisResult(); analysisResult.setResult(analysisResultString); analysisResult.setUpdatedTime(currentDate); analysisResult.setCreatedTime(currentDate); analysisResult.setChanceId(chancePoint.getId()); analysisResult.setTitle(""); analysisResult.setChanceId(chancePoint.getId()); analysisResultDao.insert(analysisResult); } return analysisResult; } @Override public AnalysisResult getAnalysisResult(String chanceId){ QueryWrapper<AnalysisResult> queryWrapper = new QueryWrapper<>(); queryWrapper.eq("chance_id" , chanceId); AnalysisResult analysisResult = analysisResultDao.selectOne(queryWrapper); return analysisResult; } @Override public boolean invalidChancePoint(String id) { ChancePoint cp = new ChancePoint(); cp.setStatus(CHANCE_STATUS_INVALID); cp.setId(id); chancePointDao.updateById(cp); return true; } }
true
a28ebfed7a6ae9f13d5ca458aed785bc7e7d6ad9
Java
pablocarle/AD-1C-2016
/trucoserver/src/main/java/org/uade/ad/trucoserver/business/PartidaMatcher.java
UTF-8
213
1.820313
2
[]
no_license
package org.uade.ad.trucoserver.business; import org.uade.ad.trucoserver.entities.Pareja; public abstract class PartidaMatcher { public PartidaMatcher() { super(); } public abstract Pareja[] match(); }
true
adce29fa8172711d43da16fd4296dda95f54894b
Java
ylinzhu/LeetCode
/src/medium/treeAndGraphs/BuildTree.java
UTF-8
1,358
3.296875
3
[]
no_license
package medium.treeAndGraphs; /** * @Designation:需要改进 * @Author: Ylz * @Date: 2019/5/29 * @Version: 1.0 */ public class BuildTree { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } // TODO 确定二叉树需要改进 public TreeNode construcBinaTree(int [] pre ,int preStart,int preEnd,int [] ino,int inoStart,int inoEnd){ if (preStart >preEnd || inoStart>inoEnd) return null; //找到根节点 TreeNode root = new TreeNode(pre[preStart]); for (int i = inoStart; i <= inoEnd; i++) { if (root.val == ino[i]){ //左子树构建 root.left = construcBinaTree(pre,preStart+1,i-inoStart+preStart,ino,inoStart,i-1); //右子树构建 root.right = construcBinaTree(pre,i-inoStart+preStart+1,preEnd,ino,i+1,inoEnd); break; } } return root; } public TreeNode buildTree(int[] preorder, int[] inorder) { if (preorder.length == 0 || inorder.length == 0 || preorder.length != inorder.length) { return null; } TreeNode root = construcBinaTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1); return root; } }
true
1a154cfe4ca14fec5be21000ede9872e9823b490
Java
SnekTech/leetcode-java
/leetcode/task409/Solution.java
UTF-8
497
3.078125
3
[]
no_license
package leetcode.task409; /** * @see https://leetcode-cn.com/problems/longest-palindrome/ */ public class Solution { public int longestPalindrome(String s) { int[] count = new int[128]; for (char c : s.toCharArray()) { count[c]++; } int result = 0; for (int n : count) { result += n / 2 * 2; if (n % 2 == 1 && result % 2 == 0) { result++; } } return result; } }
true
5ca43d0a642238b4da9ece31eddaa8e1162c00ba
Java
KazuharuFukui/originalApp
/BooKFindApp/src/com/kazu/bookfindapp/MyhistoryActivity.java
SHIFT_JIS
2,839
2.3125
2
[]
no_license
/**myhistory.xml̍ŏ̈*/ package com.kazu.bookfindapp; import java.util.ArrayList; import java.util.List; import com.parse.FindCallback; import com.parse.GetCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseQueryAdapter; import android.app.Activity; import android.graphics.BitmapFactory; import android.os.Bundle; import android.view.View; import android.widget.Adapter; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; public class MyhistoryActivity extends Activity { private ListView listView; private EditText editText; private Button button; private ArrayAdapter<String> adapter; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.myhistory); ParseQuery<ParseObject> query = ParseQuery.getQuery("Review"); // query.whereEqualTo("userName", ""); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> reviewList, ParseException e) { ParseObject review = new ParseObject("Review"); if (e == null) { review.put("bookReview", "Retrieved " + reviewList.size() + " review"); } else { review.put("bookReview", "Error: " + e.getMessage()); } } }); // ListViewU񋳉ȏ ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>( this, "Review"); adapter.setTextKey("bookReview"); adapter.setTextKey("userName"); listView = (ListView) findViewById(R.id.listView); listView.setAdapter(adapter); // eXgp /* * ArrayList<ParseObject> reviews = new ArrayList<ParseObject>(); Review * review1 = ParseObject.create(Review.class); review1.bookTitle = * ""; Review review2 = ParseObject.create(Review.class); * review2.bookTitle = ""; reviews.add(review1); * reviews.add(review2); */ // for (ParseObject bookReview: reviews) { // System.out.println(bookReview); } /** Integer[] imgList = { R.drawable.a, R.drawable.b, R.drawable.c }; String[] msgList = { "a摜", "b摜", "c摜" }; List<MyCustomListData> objects = new ArrayList<MyCustomListData>(); for (int i = 0; i < imgList.length; i++) { MyCustomListData tmpItem = new MyCustomListData(); tmpItem.setBitmap(BitmapFactory.decodeResource(getResources(), imgList[i])); tmpItem.setName(msgList[i]); objects.add(tmpItem); } MyCustomListAdapter myCustomListAdapter = new MyCustomListAdapter(this, 0, objects); ListView listView = (ListView) findViewById(R.id.listView); listView.setAdapter(myCustomListAdapter);*/ } }
true
1844a42d0055e4639610439b957166430397648b
Java
carlosmaniero/usjt-projeto-integrado-2013
/src/sisvoo/bibliotecas/BancoDeDados.java
ISO-8859-1
3,115
2.8125
3
[]
no_license
package sisvoo.bibliotecas; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; public class BancoDeDados { private ConfiguracoesBancoDeDados config; private static Connection conexao; private int numeroLinhas; public BancoDeDados(ConfiguracoesBancoDeDados config) { this.config = config; } public BancoDeDados() { try { config = new ConfiguracoesBancoDeDados(); } catch (Exception e) { e.printStackTrace(); System.exit(0); } } /** * Retorna a conexo com o banco de dados * @return * @throws Exception */ public Connection getConexao() throws Exception { if(conexao == null) try { Class.forName("com.mysql.jdbc.Driver").newInstance(); } catch (Exception e) { throw(new Exception("No foi possvel localizar o Driver do Mysql")); } try { conexao = (Connection) DriverManager.getConnection("jdbc:mysql://" + config.getDbHost() + "/" + config.getDbNome(), config.getDbUsuario(),config.getDbSenha()); } catch (SQLException e) { throw(new Exception("No foi possvel conectar com o banco de dados")); } return conexao; } /** * Seleciona todos os registros de uma tabela condicionalmente * @param table Nome da tabela * @param where Condies para a consulta <br>Null caso no haja condies. * @return ResultSet * @throws Exception */ public ResultSet selectAll(String table, String where) throws Exception { String query = "SELECT * FROM " + table; if(where != null) query += " where " + where; return executar(query); } /** * Seleciona todos registros de uma tabela * @param table * @return * @throws Exception */ public ResultSet selectAll(String table) throws Exception { return selectAll(table, null); } /** * Executa um comando SQL * @param query * @return ResultSet * @throws Exception */ public ResultSet executar(String query) throws Exception { Statement st = null; try { st = (Statement) getConexao().createStatement(); } catch (Exception e) { throw(new Exception("Sem conexo com o banco.")); } ResultSet rs; System.out.println("Executando: " + query); try { rs = st.executeQuery(query); } catch (SQLException e) { throw(new Exception("Ops! Erro na consulta <br>NerdInfo: " + query)); } rs.last(); numeroLinhas = rs.getRow(); rs.beforeFirst(); return rs; } public Statement alterar(String query) throws Exception { Statement st = null; try { st = (Statement) getConexao().createStatement(); } catch (Exception e) { throw(new Exception("Sem conexo com o banco.")); } System.out.println("Executando: " + query); try { st.executeUpdate(query, Statement.RETURN_GENERATED_KEYS); return st; } catch (SQLException e) { throw(new Exception("Ops! Erro na consulta <br>NerdInfo: " + query)); } } public int getNumeroLinhas() { return numeroLinhas; } }
true
68d781a296ede2514986991165eb4048380332ef
Java
nstanogias/dateapp-backend
/src/main/java/com/nstanogias/dateapp/domain/MessagePK.java
UTF-8
366
1.765625
2
[]
no_license
package com.nstanogias.dateapp.domain; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.io.Serializable; import java.util.Date; @Data @AllArgsConstructor @NoArgsConstructor public class MessagePK implements Serializable { protected Date messageSent; protected User sender; protected User recipient; }
true
c5435faa1d0d103abbced4dbe3c66e4a7bb94066
Java
Yangyuyangyu/CountryECBuyer
/app/src/main/java/com/countryecbuyer/activity/me/meHaveBuyActivity.java
UTF-8
2,215
2.03125
2
[]
no_license
package com.countryecbuyer.activity.me; import android.os.Bundle; import android.support.design.widget.TabLayout; import android.support.v4.view.ViewPager; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.countryecbuyer.R; import com.countryecbuyer.activity.base.BaseActivity; import com.countryecbuyer.adapter.me.me_have_buyAdapter; /** * 我购买过 */ public class meHaveBuyActivity extends BaseActivity implements View.OnClickListener { private ImageView back; private TextView top_title; private TabLayout mTabLayout; private ViewPager viewPager; @Override protected int setLayoutResourceID() { return R.layout.activity_me_have_buy; } @Override protected void initView() { mTabLayout = customFindViewById(R.id.have_buy_tablayout); viewPager = customFindViewById(R.id.have_buy_viewPager); mTabLayout.addTab(mTabLayout.newTab().setText("商品")); mTabLayout.addTab(mTabLayout.newTab().setText("店铺")); back = customFindViewById(R.id.my_top_actionbar_back); top_title = customFindViewById(R.id.my_top_actionbar_title); top_title.setText("我买过的"); me_have_buyAdapter adapter = new me_have_buyAdapter(this, getSupportFragmentManager()); viewPager.setAdapter(adapter); mTabLayout.setupWithViewPager(viewPager); mTabLayout.getTabAt(0).select(); back.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.my_top_actionbar_back: finish(); break; } } /** * 保存选中状态 */ @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("POSITION", mTabLayout.getSelectedTabPosition()); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); viewPager.setCurrentItem(savedInstanceState.getInt("POSITION")); } }
true
6beae687c1ee987f89dffe36df0fb844db1270cf
Java
mkhodachnyk/cursova
/src/view/NonConstantFormulaTextField.java
UTF-8
426
2.484375
2
[]
no_license
package view; import exceptions.*; import formula.implementation.*; class NonConstantFormulaTextField extends FormulaTextField { NonConstantFormulaTextField(String content, int size, View view) { super(content, size, view); } boolean isCorrect() { try { new Expression(this.getText()); } catch(MyException e){ return false; } return true; } }
true
87feead8f57dcfa43219c28e0ffcb7d5e948b7e9
Java
maxprofs-llcio/trello-to-markdown
/src/main/java/com/efoy/eboard/utils/MarkdownUtils.java
UTF-8
2,251
2.578125
3
[ "MIT" ]
permissive
package com.efoy.eboard.utils; import com.qkyrie.markdown2pdf.internal.exceptions.ConversionException; import com.qkyrie.markdown2pdf.internal.exceptions.Markdown2PdfLogicException; import freemarker.template.Template; import freemarker.template.TemplateException; import org.pegdown.Extensions; import org.pegdown.LinkRenderer; import org.pegdown.PegDownProcessor; import java.io.*; import java.util.HashMap; import java.util.Map; /** * Created by eamon on 5/28/2016. */ public class MarkdownUtils { /** * Have a look here http://stackoverflow.com/questions/19784525/markdown-to-html-with-java-scala * * @param markdownFile * @param HtmlFile * @throws IOException * @throws FileNotFoundException * @throws UnsupportedEncodingException * @throws Markdown2PdfLogicException * @throws ConversionException */ public static void saveMarkDownToHtml(File markdownFile, File HtmlFile) throws IOException, FileNotFoundException, UnsupportedEncodingException, Markdown2PdfLogicException, ConversionException { StringBuffer sb = EBoardUtils.readFile(markdownFile); PegDownProcessor pd = new PegDownProcessor(Extensions.ALL); String html = pd.markdownToHtml(sb.toString(), new LinkRenderer()); freemarker.template.Configuration cfg = new freemarker.template.Configuration(); try { //Load template from source folder cfg.setDirectoryForTemplateLoading(Configuration.getInstance().getTemplateDir()); // find a freemarker template for the board. Template template = cfg.getTemplate("trello_html_to_pdf.ftl"); Map<String, Object> model = new HashMap<>(); model.put("html", html); // File output Writer file = new FileWriter(HtmlFile); EBoardUtils.log.info("Saving board as html: " + HtmlFile.getAbsolutePath()); template.process(model, file); file.flush(); file.close(); } catch (IOException e) { EBoardUtils.log.trace("MarkdownService:execute:exception", e); } catch (TemplateException e) { EBoardUtils.log.trace("MarkdownService:execute:exception", e); } } }
true
bd2628b03e1d470518672b6026b7e3cc1379a47d
Java
dreamfighter/Apps-SI3805
/app/src/main/java/com/example/zeger/apps_si3005/AsyncTaskActivity.java
UTF-8
4,517
2.140625
2
[]
no_license
package com.example.zeger.apps_si3005; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.app.AppCompatActivity; import android.text.style.LocaleSpan; import android.util.Log; import android.widget.ListView; import com.example.zeger.apps_si3005.adapter.AdapterListView; import com.example.zeger.apps_si3005.entity.Contact; import com.example.zeger.apps_si3005.service.DownloadIntentService; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by zeger on 08/04/17. */ public class AsyncTaskActivity extends AppCompatActivity{ private String url = "http://dreamfighter.id/android/data.json"; private AdapterListView adapterListView; DownloadJsonReceiver receiver = new DownloadJsonReceiver(); public class DownloadJsonReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String json = intent.getExtras().getString("json"); adapterListView.refresh(decodeJson(json)); Log.d("JSON_RECEIVER","Data json from Download service is receive"); } } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView)findViewById(R.id.contact_listview); adapterListView = new AdapterListView(this); listView.setAdapter(adapterListView); IntentFilter intentFilter = new IntentFilter("DOWNLOAD_JSON"); registerReceiver(receiver,intentFilter); Intent intent = new Intent(this, DownloadIntentService.class); startService(intent); //DownloadJsonTask task = new DownloadJsonTask(); //task.execute(url); } @Override protected void onPause() { super.onPause(); unregisterReceiver(receiver); } private class DownloadJsonTask extends AsyncTask<String, Integer, String>{ @Override protected String doInBackground(String... params) { return requestJson(params[0]); } @Override protected void onProgressUpdate(Integer... values) { } @Override protected void onPostExecute(String s) { Log.d("JSON","S=" + s); adapterListView.refresh(decodeJson(s)); } } public List<Contact> decodeJson(String json){ List<Contact> contacts = new ArrayList<>(); try { JSONObject jsonObjectRoot = new JSONObject(json); JSONArray jsonArrayData = jsonObjectRoot.getJSONArray("data"); for (int i=0;i<jsonArrayData.length();i++){ JSONObject jsonObjectContact = jsonArrayData.getJSONObject(i); Contact c = new Contact(); c.setNama(jsonObjectContact.getString("name")); c.setNoHp(jsonObjectContact.getString("phone")); c.setAvatarUrl(jsonObjectContact.getString("avatarUrl")); contacts.add(c); } } catch (JSONException e) { e.printStackTrace(); } return contacts; } public String requestJson(String urlWeb){ StringBuilder sb = new StringBuilder(); try { // conect to server URL url = new URL(urlWeb); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // get data Reader r = new InputStreamReader(connection.getInputStream()); char[] chars = new char[4*1024]; int len; while((len = r.read(chars))>=0) { sb.append(chars, 0, len); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sb.toString(); } }
true
7880e6ad495df901f1c5b27dca68b26450bdac50
Java
isolhameli/desafio-spring
/src/main/java/com/mercadolibre/desafiospring/repositories/SellerRepository.java
UTF-8
375
1.914063
2
[]
no_license
package com.mercadolibre.desafiospring.repositories; import com.mercadolibre.desafiospring.models.Seller; import org.springframework.data.domain.Sort; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface SellerRepository extends JpaRepository<Seller,Integer> { List<Seller> findByFollowersId(Integer id, Sort sort); }
true
12fa12f1eb7213e43d58c0fbb799e2ddbb90357c
Java
betera/logviewer
/src/main/java/com/betera/logviewer/ui/fileviewer/JTextPaneLogfile.java
UTF-8
37,245
1.570313
2
[]
no_license
package com.betera.logviewer.ui.fileviewer; import com.betera.logviewer.Icons; import com.betera.logviewer.LogViewer; import com.betera.logviewer.file.Logfile; import com.betera.logviewer.file.LogfileConfiguration; import com.betera.logviewer.file.LogfileStateChangedListener; import com.betera.logviewer.file.LogfilesContainer; import com.betera.logviewer.file.column.LogfileColumn; import com.betera.logviewer.file.column.LogfileColumnConfig; import com.betera.logviewer.file.column.LogfileParser; import com.betera.logviewer.file.column.LogfileRowConfig; import com.betera.logviewer.file.highlight.HighlightEntry; import com.betera.logviewer.file.highlight.HighlightManager; import com.betera.logviewer.ui.JVerticalButton; import com.betera.logviewer.ui.bookmark.BookmarkManager; import com.betera.logviewer.ui.bookmark.DefaultBookmark; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.StringSelection; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.ArrayList; import java.util.List; import java.util.Vector; import java.util.stream.Stream; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollBar; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSplitPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextPane; import javax.swing.JToggleButton; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.border.EmptyBorder; import javax.swing.border.LineBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.text.AbstractDocument; import javax.swing.text.BadLocationException; import javax.swing.text.BoxView; import javax.swing.text.ComponentView; import javax.swing.text.DefaultHighlighter; import javax.swing.text.DefaultStyledDocument; import javax.swing.text.Element; import javax.swing.text.IconView; import javax.swing.text.LabelView; import javax.swing.text.MutableAttributeSet; import javax.swing.text.ParagraphView; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.StyledEditorKit; import javax.swing.text.View; import javax.swing.text.ViewFactory; import org.apache.commons.io.input.Tailer; import org.apache.commons.io.input.TailerListener; import org.apache.commons.io.input.TailerListenerAdapter; import org.jdesktop.swingx.JXTable; import org.jdesktop.swingx.table.DefaultTableColumnModelExt; public class JTextPaneLogfile extends MouseAdapter implements Logfile, TableCellRenderer { private File file; private JScrollPane scrollPane; private JTextPane textPane; private LogfileConfiguration config; private String newLine; private StyledDocument doc; private LinePainter selectPainter = null; private Object selectHighlightInfo; private boolean followTail; private Color selectionColor; private JPanel toolsPanel; private LogfilesContainer container; private BookmarkManager bookmarkManager; private JSplitPane splitter; private ButtonGroup toolWindowButtonGroup; private JPanel toolBarContentPanel; private JXTable docTable; private LogfileRowConfig columnConfig; private float minLabelSpan; private boolean lineWrap = false; private List<LogfileStateChangedListener> listener; private WatchService watcher; private WatchKey register; private JLabel waitLabel; private boolean isTextView = true; private JToolBar contextToolBar; private JPanel leftTBPanel; public JTextPaneLogfile(LogfilesContainer container, File aFile, LogfileConfiguration config) { selectionColor = new Color(51, 153, 255, 255); listener = new ArrayList<>(); file = aFile; followTail = true; this.container = container; this.config = config; bookmarkManager = new BookmarkManager(this); initTextPane(); initHighlighting(); initTable(); initToolWindows(); initSplitterAndScrollPane(); initReaderThread(); } private MouseWheelListener createScrollListener() { return new MouseWheelListener() // NOSONAR { @Override public void mouseWheelMoved(MouseWheelEvent e) { boolean scrolledDown = e.getPreciseWheelRotation() > 0; JScrollBar vsb = scrollPane.getVerticalScrollBar(); int value = vsb.getValue() + vsb.getModel().getExtent(); int max = vsb.getMaximum(); if ( !scrolledDown ) { if ( followTail ) { updateFollowTailCheckbox(false); } followTail = false; } else if ( value >= max ) { if ( !followTail ) { updateFollowTailCheckbox(true); } followTail = true; } } }; } private void initReaderThread() { Thread readerThread = new Thread(createReaderThreadRunnable()); readerThread.setDaemon(true); readerThread.start(); } private void initSplitterAndScrollPane() { scrollPane = new JScrollPane() { public JScrollBar createVerticalScrollBar() { ScrollBar scrollBar = new ScrollBar(JScrollBar.VERTICAL); return scrollBar; } }; scrollPane.setViewportView(textPane); scrollPane.addMouseWheelListener(createScrollListener()); JPanel logRoot = new JPanel(); logRoot.setLayout(new BorderLayout()); logRoot.add(createLogfileToolbar(), BorderLayout.NORTH); logRoot.add(scrollPane, BorderLayout.CENTER); splitter = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, logRoot, toolsPanel); splitter.setBorder(new LineBorder(Color.GRAY)); splitter.setDividerSize(8); splitter.setResizeWeight(0.8); scrollPane.setViewportView(textPane); } private void initToolWindows() { JToolBar toolsToolbar = new JToolBar(); toolBarContentPanel = new JPanel(); toolBarContentPanel.setLayout(new GridBagLayout()); toolsToolbar.setLayout(new BorderLayout()); toolsToolbar.add(toolBarContentPanel, BorderLayout.NORTH); toolsToolbar.add(new JPanel(), BorderLayout.CENTER); toolsToolbar.setOrientation(JToolBar.VERTICAL); toolsToolbar.setBorderPainted(true); toolsPanel = new JPanel(); toolsPanel.setVisible(false); JPanel taskContainer = new JPanel(); taskContainer.setLayout(new BorderLayout()); toolsPanel.setLayout(new BorderLayout()); toolsPanel.add(toolsToolbar, BorderLayout.EAST); toolsPanel.add(taskContainer, BorderLayout.CENTER); createToolWindowButton(taskContainer, bookmarkManager.getComponent(), "Bookmarks"); createToolWindowButton(taskContainer, new JPanel(), "Test"); toolsToolbar.setFloatable(false); toolsToolbar.setBorder(BorderFactory.createRaisedSoftBevelBorder()); taskContainer.add(bookmarkManager.getComponent()); } private void initTable() { docTable = new JXTable(); docTable.setSortable(false); docTable.setGridColor(Color.lightGray); docTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); columnConfig = LogfileParser.getInstance().findMatchingConfig(this); createTableModelFromColumnConfig(); } private void initHighlighting() { DefaultHighlighter highlighter = new DefaultHighlighter(); highlighter.setDrawsLayeredHighlights(false); textPane.setHighlighter(highlighter); selectPainter = new LinePainter(textPane, selectionColor, 0, null); } private DocumentListener createDocumentScrollListener() { return new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { if ( followTail && textPane.getDocument().equals(doc) ) { scrollToEnd(); } } @Override public void removeUpdate(DocumentEvent e) { } @Override public void changedUpdate(DocumentEvent e) { } }; } private void initTextPane() { textPane = new JTextPane() { @Override public void scrollRectToVisible(Rectangle aRect) { if ( followTail ) { if ( aRect != null ) { super.scrollRectToVisible(aRect); } } } }; textPane.setBorder(BorderFactory.createEtchedBorder()); textPane.setEditable(false); textPane.addMouseListener(this); textPane.setEditorKit(new WrapEditorKit()); textPane.setBackground(HighlightManager.getInstance().getDefaultEntry().getBackgroundColor()); doc = textPane.getStyledDocument(); doc.addDocumentListener(createDocumentScrollListener()); textPane.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE); textPane.setFont(new Font("Consolas", Font.PLAIN, 18)); } private JToolBar createTextViewToolbar() { JToolBar tb = new JToolBar(); tb.setFloatable(false); return tb; } private int getMaxWidthForColumn(TableColumn col) { for ( LogfileColumnConfig entry : columnConfig.getEntries() ) { if ( col.getIdentifier().equals(entry.getColumnName()) ) { return entry.getMaxColumnSize(); } } return 0; } private JToolBar createTableViewToolbar() { JToolBar tb = new JToolBar(); tb.setFloatable(false); tb.add(createSeparator()); tb.add(new AbstractAction("Pack table", Icons.packIcon) { @Override public void actionPerformed(ActionEvent e) { if ( lineWrap ) { docTable.setHorizontalScrollEnabled(true); } docTable.packAll(); if ( lineWrap ) { docTable.setHorizontalScrollEnabled(false); } } }); tb.add(new AbstractAction("Toggle Line-Wrap", Icons.wrapOnIcon) { @Override public void actionPerformed(ActionEvent e) { if ( lineWrap ) { lineWrap = false; docTable.setHorizontalScrollEnabled(true); putValue(Action.SMALL_ICON, Icons.wrapOnIcon); } else { lineWrap = true; docTable.setHorizontalScrollEnabled(false); putValue(Action.SMALL_ICON, Icons.wrapOffIcon); } if ( followTail ) { scrollToEnd(); } } }); return tb; } private JToolBar createSharedToolbar() { JToolBar tb = new JToolBar(); tb.setLayout(new FlowLayout(FlowLayout.LEADING, 4, 0)); tb.setFloatable(false); tb.add(new AbstractAction("Table view", Icons.tableIcon) { @Override public void actionPerformed(ActionEvent e) { Component comp = scrollPane.getViewport().getView(); if ( comp instanceof JXTable ) { scrollPane.setViewportView(textPane); isTextView = true; leftTBPanel.remove(contextToolBar); contextToolBar = createTextViewToolbar(); leftTBPanel.add(contextToolBar); putValue(Action.SMALL_ICON, Icons.tableIcon); } else { scrollPane.setViewportView(docTable); isTextView = false; leftTBPanel.remove(contextToolBar); contextToolBar = createTableViewToolbar(); leftTBPanel.add(contextToolBar); putValue(Action.SMALL_ICON, Icons.textPaneIcon); } leftTBPanel.revalidate(); leftTBPanel.repaint(); } }); tb.add(new AbstractAction("Refresh", Icons.refreshIcon) { @Override public void actionPerformed(ActionEvent e) { initReaderThread(); } }); tb.add(createSeparator()); tb.add(new AbstractAction("Clear file", Icons.clearFileIcon) { @Override public void actionPerformed(ActionEvent e) { try { RandomAccessFile raf = new RandomAccessFile(file, "rws"); raf.setLength(0); raf.close(); clearModel(); } catch ( IOException e1 ) { file.delete(); try { file.createNewFile(); clearModel(); } catch ( IOException e2 ) { LogViewer.handleException(e2); } } } }); return tb; } private JSeparator createSeparator() { JSeparator sep = new JSeparator(JSeparator.VERTICAL); sep.setPreferredSize(new Dimension(4, 32)); return sep; } private JToolBar createLogfileToolbar() { contextToolBar = createTextViewToolbar(); JToolBar logRootToolBar = new JToolBar(); logRootToolBar.setLayout(new BorderLayout()); JToolBar rightTB = new JToolBar(); rightTB.setFloatable(false); leftTBPanel = new JPanel(); leftTBPanel.setLayout(new FlowLayout()); leftTBPanel.add(createSharedToolbar()); leftTBPanel.add(contextToolBar); logRootToolBar.add(leftTBPanel, BorderLayout.WEST); logRootToolBar.add(rightTB, BorderLayout.EAST); rightTB.add(new AbstractAction("Toggle tool panel", Icons.expandIcon) { int divider = -1; @Override public void actionPerformed(ActionEvent e) { int value = scrollPane.getVerticalScrollBar().getValue(); if ( toolsPanel.isVisible() ) { divider = splitter.getDividerLocation(); } toolsPanel.setVisible(!toolsPanel.isVisible()); putValue(Action.SMALL_ICON, toolsPanel.isVisible() ? Icons.collapseIcon : Icons.expandIcon); if ( toolsPanel.isVisible() ) { if ( divider == -1 ) { divider = (int) (splitter.getVisibleRect().width * splitter.getResizeWeight()); } splitter.setDividerLocation(divider); } scrollPane.getVerticalScrollBar().setValue(value); } }); logRootToolBar.setFloatable(false); return logRootToolBar; } private void createTableModelFromColumnConfig() { docTable.setDefaultRenderer(Object.class, this); docTable.setEditable(false); docTable.setHorizontalScrollEnabled(true); docTable.setColumnControlVisible(true); if ( columnConfig == null ) { ((DefaultTableModel) docTable.getModel()).setColumnIdentifiers(new String[] { "Line", "Text" }); return; } String[] cols = new String[1 + columnConfig.getEntries().length]; cols[0] = "Line"; for ( int i = 0; i < columnConfig.getEntries().length; i++ ) { cols[i + 1] = columnConfig.getEntries()[i].getColumnName(); } ((DefaultTableModel) docTable.getModel()).setColumnIdentifiers(cols); DefaultTableColumnModelExt mdl = (DefaultTableColumnModelExt) docTable.getColumnModel(); mdl.getColumnExt("Line").setMaxWidth(10 * 10); List<TableColumn> columns = mdl.getColumns(true); for ( TableColumn column : columns ) { String identifier = (String) column.getIdentifier(); { for ( LogfileColumnConfig entry : columnConfig.getEntries() ) { if ( entry.getColumnName().equals(identifier) ) { int maxWidth = entry.getMaxColumnSize() * 10; mdl.getColumnExt(identifier).setPreferredWidth(maxWidth); if ( entry.isInitiallyHidden() ) { mdl.getColumnExt(identifier).setVisible(false); break; } } } } } } private void createToolWindowButton(JPanel container, JComponent aComp, String aTitle) { JToggleButton btn = new JVerticalButton(); btn.setText(aTitle); aComp.setBorder(new EmptyBorder(1, 1, 1, 1)); btn.addActionListener(e -> { container.removeAll(); container.add(aComp, BorderLayout.CENTER); container.revalidate(); container.repaint(); }); btn.setBorderPainted(true); btn.setMargin(new Insets(4, 4, 4, 4)); if ( toolWindowButtonGroup == null ) { toolWindowButtonGroup = new ButtonGroup(); } toolWindowButtonGroup.add(btn); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.NORTH; c.gridx = GridBagConstraints.REMAINDER; c.weightx = 1.0; c.fill = GridBagConstraints.BOTH; toolBarContentPanel.add(btn, c); } @Override public String toString() { return getDisplayName(); } @Override public void scrollTo(int offset, int row, boolean setSelection) { if ( isTextView && textPane.getDocument().equals(doc) ) { textPane.setCaretPosition(offset); try { if ( doc.getLength() > 0 ) { textPane.scrollRectToVisible(textPane.modelToView(offset - 1)); } } catch ( BadLocationException e ) { LogViewer.handleException(e); } } else { docTable.getSelectionModel().setSelectionInterval(row + 1, row + 1); docTable.scrollRowToVisible(row + 1); } if ( setSelection ) { mouseClicked(null); } } private void setStyle(HighlightEntry entry, int start, int end) { Font font = entry.getFont(); Color c = entry.getForegroundColor(); MutableAttributeSet attrs = textPane.getInputAttributes(); if ( font != null ) { StyleConstants.setFontFamily(attrs, font.getFamily()); StyleConstants.setFontSize(attrs, font.getSize()); StyleConstants.setItalic(attrs, (font.getStyle() & Font.ITALIC) != 0); StyleConstants.setBold(attrs, (font.getStyle() & Font.BOLD) != 0); } if ( c != null ) { StyleConstants.setForeground(attrs, c); } doc.setCharacterAttributes(start, end, attrs, false); } @Override public void defaultFontChanged(Font aNewFont) { if ( textPane != null ) { textPane.setFont(aNewFont); } if ( docTable != null ) { docTable.setFont(aNewFont); } } @Override public LogfilesContainer getContainer() { return null; } @Override public LogfileConfiguration getConfiguration() { return config; } @Override public JComponent getComponent() { return splitter; } @Override public void followTailChanged(boolean doFollowTail) { followTail = doFollowTail; if ( followTail ) { scrollToEnd(); fireContentChanged(false); } } @Override public void updateFollowTailCheckbox(boolean doFollowTail) { container.updateFollowTailCheckbox(doFollowTail, this); } @Override public void addLogfileStateChangedListener(LogfileStateChangedListener listener) { if ( !this.listener.contains(listener) ) { this.listener.add(listener); } } public void fireContentChanged(boolean hasNew) { for ( LogfileStateChangedListener list : listener ) { list.contentChanged(hasNew, this); } } public void destroy() { listener.clear(); listener = null; if ( register != null ) { register.cancel(); try { watcher.close(); } catch ( IOException e ) { LogViewer.handleException(e); } } } @Override public byte[] getBytes() { return textPane.getText().getBytes(); } @Override public String getName() { return file.getAbsolutePath(); } public String getDisplayName() { return file.getName(); } @Override public String getAbsolutePath() { return file.getAbsolutePath(); } @Override public void dispose() { // nothing } private Runnable createReaderThreadRunnable() { return () -> { try { readFileFully(); Tailer.create(file, Charset.defaultCharset(), createTailListener(), 500, true, true, 4096); } catch ( Exception e ) { LogViewer.handleException(e); } }; } private void clearModel() { textPane.getHighlighter().removeAllHighlights(); bookmarkManager.deleteAllBookmarks(); try { doc.remove(0, doc.getLength()); } catch ( BadLocationException e ) { LogViewer.handleException(e); } ((DefaultTableModel) docTable.getModel()).setRowCount(0); } private void scrollToEnd() { scrollTo(doc.getLength(), docTable.getRowCount(), false); } private void readFileFully() { JLabel waitLabel = new JLabel("Please wait...."); try { SwingUtilities.invokeAndWait(() -> { clearModel(); textPane.setDocument(new DefaultStyledDocument()); textPane.setLayout(new BorderLayout()); waitLabel.setBackground(new Color(230, 230, 230)); waitLabel.setHorizontalAlignment(SwingConstants.CENTER); waitLabel.setOpaque(true); waitLabel.setFont(new Font("Segoe UI, Arial", Font.BOLD, 36)); textPane.add(waitLabel, BorderLayout.CENTER); }); } catch ( Exception e ) { e.printStackTrace(); } SwingUtilities.invokeLater(() -> { try (Stream<String> stream = Files.lines(Paths.get(file.getAbsolutePath()))) { stream.forEach(this::processLine); } catch ( IOException e ) { LogViewer.handleException(e); } finally { textPane.remove(waitLabel); textPane.setDocument(doc); docTable.packAll(); fireContentChanged(true); if ( followTail ) { scrollToEnd(); } } }); } private String nl() { if ( newLine == null ) { newLine = System.getProperty("line.separator"); } return newLine; } private TailerListener createTailListener() { return new TailerListenerAdapter() { int i = 0; @Override public void fileRotated() { try { readFileFully(); } catch ( Exception e ) { LogViewer.handleException(e); } } @Override public void handle(String s) { SwingUtilities.invokeLater(() -> { processLine(s); fireContentChanged(true); }); } @Override public void handle(Exception e) { LogViewer.handleException(e); } }; } private void processLine(final String line) { try { DefaultTableModel tableModel = ((DefaultTableModel) docTable.getModel()); int docLen = doc.getLength(); final int start = docLen; StringBuilder builder = new StringBuilder(); builder.append(line); builder.append(nl()); String content = builder.toString(); doc.insertString(docLen, content, null); final int end = doc.getLength(); final HighlightEntry entry = HighlightManager.getInstance().findHighlightEntry(line); if ( entry != null ) { addHighlightToLine(start, entry.getBackgroundColor(), false); setStyle(entry, start, end); if ( entry.isAddBookmark() ) { bookmarkManager.addBookmark(new DefaultBookmark(this, start, tableModel.getRowCount() - 1, entry, line)); } } LogfileColumn[] columns = LogfileParser.getInstance().parseLine(columnConfig, line); Vector<CellInfos> vector = new Vector<>(); vector.add(new CellInfos(entry, (tableModel.getRowCount() + 1) + "")); for ( LogfileColumn col : columns ) { vector.add(new CellInfos(entry, col.getContent())); } tableModel.addRow(vector); } catch ( Exception e ) { LogViewer.handleException(e); } } private int getNewlineBefore(int offset) { int preOffset = Math.max(0, offset - 100); try { String text = doc.getText(preOffset, offset - preOffset); int lastIndex = text.lastIndexOf(nl()); if ( lastIndex >= 0 ) { return preOffset + lastIndex + 1; } if ( preOffset == 0 ) { return 0; } return getNewlineBefore(preOffset); } catch ( BadLocationException e ) { LogViewer.handleException(e); } return -1; } private Object addHighlightToLine(int offset, Color color, boolean isMaster) { int start = getNewlineBefore(offset); if ( start < 0 ) { return null; } start += 1; if ( isMaster ) { selectPainter.setOffset(start); } try { return textPane.getHighlighter().addHighlight(offset, offset, isMaster ? selectPainter : new LinePainter(textPane, color, start, selectPainter)); } catch ( BadLocationException e ) { LogViewer.handleException(e); } return null; } private void copySelectedLineToClipboard() { Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); try { String text = doc.getText(selectPainter.getOffset(), Math.min(doc.getLength() - selectPainter.getOffset(), 1000)); int idxNextNL = text.indexOf(nl()) + 1; if ( idxNextNL <= 0 ) { idxNextNL = doc.getLength() - selectPainter.getOffset(); } String theString = doc.getText(getNewlineBefore(selectPainter.getOffset()), idxNextNL); if ( theString.startsWith(nl()) ) { theString = theString.substring(nl().length()); } else if ( theString.startsWith("\n") ) { theString = theString.substring(1); } StringSelection selection = new StringSelection(theString); systemClipboard.setContents(selection, selection); } catch ( BadLocationException e1 ) { LogViewer.handleException(e1); } } @Override public void mouseClicked(MouseEvent e) { if ( e != null && (e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3) ) { copySelectedLineToClipboard(); return; } if ( selectHighlightInfo != null ) { textPane.getHighlighter().removeHighlight(selectHighlightInfo); } selectHighlightInfo = addHighlightToLine(textPane.getCaretPosition(), selectionColor, true); textPane.repaint(); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { CustomSelectionPaintLabel label = new CustomSelectionPaintLabel(); CellInfos ci = (CellInfos) value; label.setText(ci.content); label.isFocused = hasFocus; label.isSelected = isSelected; Color fgColor = Color.BLACK; Color bgColor = Color.WHITE; Font font = textPane.getFont(); if ( ci.entry != null ) { fgColor = ci.entry.getForegroundColor(); bgColor = ci.entry.getBackgroundColor(); font = ci.entry.getFont(); } label.setFont(font); label.setForeground(fgColor); label.setBackground(bgColor); label.setOpaque(true); label.setWrapStyleWord(false); label.setLineWrap(lineWrap); FontMetrics fontMetrics = label.getFontMetrics(label.getFont()); int newHeight = fontMetrics.getHeight() + 3; if ( label.getLineWrap() ) { int fontHeight = fontMetrics.getHeight(); Rectangle2D stringBounds = fontMetrics.getStringBounds(label.getText(), label.getGraphics()); int textWidth = (int) ((stringBounds.getWidth() + 10) * 1.05); int colWidth = table.getColumnModel().getColumn(column).getWidth(); newHeight = (textWidth / colWidth + 1) * (fontHeight + 1); if ( column > 0 ) { newHeight = Math.max(table.getRowHeight(row), newHeight); } } table.setRowHeight(row, newHeight); label.setToolTipText(label.getText()); return label; } private class CustomSelectionPaintLabel // NOSONAR extends JTextArea { boolean isSelected = false; boolean isFocused = false; @Override public void paint(Graphics g) { super.paint(g); if ( isSelected ) { int middleBG = (getBackground().getRed() + getBackground().getGreen() + getBackground().getBlue()) / 3; if ( middleBG < 80 ) { g.setColor(new Color(160, 210, 255, 160)); } else { g.setColor(new Color(63, 72, 255, 160)); } g.fillRect(0, 0, getSize().width, getSize().height); } } } private class CellInfos { private HighlightEntry entry; private String content; public CellInfos(HighlightEntry entry, String content) { this.entry = entry; this.content = content; } public HighlightEntry getEntry() { return entry; } public String getContent() { return content; } @Override public String toString() { return content; } } private class WrapEditorKit extends StyledEditorKit { transient ViewFactory defaultFactory = new WrapColumnFactory(); @Override public ViewFactory getViewFactory() { return defaultFactory; } } private class WrapColumnFactory implements ViewFactory { public View create(Element elem) { String kind = elem.getName(); if ( kind != null ) { if ( kind.equals(AbstractDocument.ContentElementName) ) { return new WrapLabelView(elem); } else if ( kind.equals(AbstractDocument.ParagraphElementName) ) { return new ParagraphView(elem); } else if ( kind.equals(AbstractDocument.SectionElementName) ) { return new BoxView(elem, View.Y_AXIS); } else if ( kind.equals(StyleConstants.ComponentElementName) ) { return new ComponentView(elem); } else if ( kind.equals(StyleConstants.IconElementName) ) { return new IconView(elem); } } return new LabelView(elem); } } private class WrapLabelView extends LabelView { public WrapLabelView(Element elem) { super(elem); } @Override public float getMinimumSpan(int axis) { switch ( axis ) { case View.X_AXIS: return minLabelSpan; case View.Y_AXIS: return super.getMinimumSpan(axis); default: throw new IllegalArgumentException("Invalid axis: " + axis); } } } }
true
cd18db184c242569a5adc864afaec6f930c9cc8b
Java
luciendgolden/swp-java-design-patterns
/command_composition/src/at/technikum/state/Started.java
UTF-8
1,515
2.609375
3
[ "MIT" ]
permissive
package at.technikum.state; import at.technikum.dto.Person; import sun.reflect.generics.reflectiveObjects.NotImplementedException; public class Started implements GameState { private static Started INSTANCE = null; private Started() { } public static Started getInstance() { if (INSTANCE == null) { INSTANCE = new Started(); } return INSTANCE; } @Override public void purchase(GameControl control, Person person) { throw new UnsupportedOperationException(); } @Override public void download(GameControl control) { throw new UnsupportedOperationException(); } @Override public void install(GameControl control) { throw new UnsupportedOperationException(); } @Override public void start(GameControl control) { System.out.println("Game is already started"); } @Override public void play(GameControl control) { System.out.println("Game will be played.."); control.setGameState(Played.getInstance()); } @Override public void update(GameControl control) { throw new UnsupportedOperationException(); } @Override public void readyForPlaying(GameControl control) { throw new UnsupportedOperationException(); } @Override public void block(GameControl control) { throw new UnsupportedOperationException(); } @Override public void uninstall(GameControl control) { throw new UnsupportedOperationException(); } @Override public String toString() { return "Game is in start state"; } }
true
38852990982a0d9507846e20266be487ce72b144
Java
venkatesh010/JavaLearning
/src/Arrays/DeclarationOfArray.java
UTF-8
239
2.546875
3
[]
no_license
package Arrays; import java.time.LocalDate; import java.util.ArrayList; public class DeclarationOfArray { public static void main(String[] args) { int[] arr = new int[]{2,4,5}; System.out.println(arr.length); } }
true
fd2f75c6ed4ac9475c2392f6fd854cfb92b0a567
Java
MariaYakubova/JavaProgramming2020_B21
/src/day20_ForLoop/BreakContinue.java
UTF-8
939
4.03125
4
[]
no_license
package day20_ForLoop; import java.util.Scanner; public class BreakContinue { public static void main(String[] args) { for (int i = 1; i <= 10; i--) {//i: 1,0 if (i < 1) { break; // exits the loop immediatly } System.out.println("Hello Batch 21"); } System.out.println("======================="); Scanner scan = new Scanner(System.in); for (int i = 0; i == 0; ) { System.out.println("Enter two numbers: "); int n1 = scan.nextInt(); int n2 = scan.nextInt(); System.out.println("Sum is: " + (n1 + n2)); System.out.println("would you like to continue? Yes,No"); String answer = scan.next(); if (answer.equalsIgnoreCase("no")) { System.out.println("Thank you for using our calculator"); break; } } } }
true
94c513df3be6253703425401aead7fcacf62f3db
Java
TimBlokker/CastleGame
/src/logic/Player.java
UTF-8
24,621
3.578125
4
[]
no_license
package logic; import java.util.InputMismatchException; import java.util.Random; import java.util.Scanner; import javax.swing.JOptionPane; /* * This abstract class is used to choose the ratio of the player's skill versus the player's energy, the player's name and also implements an abstract representation of the * method which is used to choose the character. The chooseCharacter method is then overridden in the Character class. * Additionally the most important method of this game are implemented in this class. * - The two methods to print (text-based) or store(GUI) the map, hereby determining the visible part of the map; * - The two methods moving the player (text-based); * - the method analysing the impact of each tilevalue the player is standing on. * Other important methods are: * - chooseEnergy() (text-based) and chooseEnergy(int i) (GUI) * - chooseName() (text-based) and setName(String) (GUI) */ public abstract class Player { /* * Variable setting the level of chance that is involved in the skill needed to * beat an opponent or win a tournament. */ private final static int LEVEL_OF_CHANCE = 8; /* * Generating a random number. */ public static Random r = new Random(); /* * The Scanner used for the text-based version to register user input. */ public static Scanner scan = new Scanner(System.in); /* * The name of the player. */ private String name; /* * The amount of prices the player has won (by winning tournaments or beating * opponents). */ private int wonPrices = 0; /* * Energy of the player. */ private int energy; /* * Skill of the player. */ private int skill; /* * Current column the player is located in. */ private int column; /* * current row the player is located in. */ private int row; /* * The skill required to win at a tournament. This is set by random. */ private int requiredSkillTournament; /* * The skill required to win against an opponent. This is set by random. */ private int requiredSkillOpponent; /* * Number of moves made by the player. */ private int numberOfMoves; /* * Number of keys found by the player. */ private int numberOfKeys; /* * Boolean keeping track of whether the player has won. */ private boolean won; private int[][] finalMapWithTiles; /* * Instance of the class Map, which is instantiated in the constructor when a * player instance is created and a map instance is passed to the player class. */ private Map map; /* * this is the constructor for the the objects inheriting from player, the class * Player itself is set to abstract and does not have any objects instantiated * this constructor is called when an archer, monk or warrior object is created * this constructor then calls the setName, setColumn, setRow, setEnergy and * chooseSkill methods as well as the super constructor Map */ public Player(int r, int c, Map map) { this.map = map; this.row = r; this.column = c; } /* * Abstract representation of the method which is implemented in the Character * class. The abstract representation is necessary because the getCharacter * method in the subclass is bound dynamically and thus is not available until * run-time. */ public abstract String getCharacter(); /* * This method prints the map to the console and indicates the location of the * player using brackets. The visibility is set depending on the character * chosen. This method is used in the text-based version. */ public void printMap() { switch (this.getCharacter()) { case "Monk": case "Archer": for (int r = 0; r < map.getNumberOfRows(); r++) { for (int c = 0; c < map.getNumberOfColumns(); c++) { // position of player if (r == this.getRow() & c == this.getColumn()) { System.out.print("(" + map.getTileValue(r, c) + ")"); // this is the range of visibility for archer and monk, thus the actual values // of the tiles are printed } else if ((r == this.getRow() - 2 | r == this.getRow() - 1) & c == this.getColumn() | (r == this.getRow() + 2 | r == this.getRow() + 1) & c == this.getColumn() | (c == this.getColumn() - 2 | c == this.getColumn() - 1) & r == this.getRow() | (c == this.getColumn() + 2 | c == this.getColumn() + 1) & r == this.getRow()) { System.out.print(" " + map.getTileValue(r, c) + " "); // this is the visibility unique to the Archer character and also here the // actual values are printed } else if (this.getCharacter().equals("Archer") & ((c == this.getColumn() + 1 | c == this.getColumn() - 1) & (r == this.getRow() + 1 | r == this.getRow() - 1))) { System.out.print(" " + map.getTileValue(r, c) + " "); // if a tile is out of the range of the visibility a x is printed instead } else { System.out.print(" x "); } } System.out.print("\n"); } break; case "Warrior": for (int r = 0; r < map.getNumberOfRows(); r++) { for (int c = 0; c < map.getNumberOfColumns(); c++) { if (r == this.getRow() & c == this.getColumn()) { // position of the player when being a Warrior System.out.print("(" + map.getTileValue(r, c) + ")"); // visible part of map } else if (r == this.getRow() - 1 & c == this.getColumn() | r == this.getRow() + 1 & c == this.getColumn() | c == this.getColumn() - 1 & r == this.getRow() | c == this.getColumn() + 1 & r == this.getRow()) { System.out.print(" " + map.getTileValue(r, c) + " "); // part of the map that is not visible } else { System.out.print(" x "); } } System.out.print("\n"); } break; } } /* * For the GUI method. This method stores the map, with implemented visibility * radius in a new variable: finalMapWithTiles. The location of the player does * not need to be indicated here, this is done later by assigning the image of * the player to the correct tile. The visibility is set to according to the * character being played. */ public int[][] storeMap() { this.finalMapWithTiles = new int[map.getMapWithTiles().length][map.getMapWithTiles()[0].length]; switch (this.getCharacter()) { case "Monk": case "Archer": for (int r = 0; r < map.getNumberOfRows(); r++) { for (int c = 0; c < map.getNumberOfColumns(); c++) { // Position of player:this is actually not required in the GUI version but we // kept it to have it similar to the text-based version, // and keep the extra maintenance to a minimum if (r == this.getRow() & c == this.getColumn()) { this.finalMapWithTiles[r][c] = map.getTileValue(r, c); // visible part of the map for Archer and Monk } else if ((r == this.getRow() - 2 | r == this.getRow() - 1) & c == this.getColumn() | (r == this.getRow() + 2 | r == this.getRow() + 1) & c == this.getColumn() | (c == this.getColumn() - 2 | c == this.getColumn() - 1) & r == this.getRow() | (c == this.getColumn() + 2 | c == this.getColumn() + 1) & r == this.getRow()) { this.finalMapWithTiles[r][c] = map.getTileValue(r, c); // visible part of the map when being an Archer } else if (this.getCharacter().equals("Archer") & ((c == this.getColumn() + 1 | c == this.getColumn() - 1) & (r == this.getRow() + 1 | r == this.getRow() - 1))) { this.finalMapWithTiles[r][c] = map.getTileValue(r, c); // invisible part of the map } else { this.finalMapWithTiles[r][c] = 50; } } } break; case "Warrior": for (int r = 0; r < map.getNumberOfRows(); r++) { for (int c = 0; c < map.getNumberOfColumns(); c++) { // Position of player:this is actually not required in the GUI version but we // kept it to have it similar to the text-based version, // and keep the extra maintenance to a minimum if (r == this.getRow() & c == this.getColumn()) { this.finalMapWithTiles[r][c] = map.getTileValue(r, c); // visible part of the map for Warriors } else if (r == this.getRow() - 1 & c == this.getColumn() | r == this.getRow() + 1 & c == this.getColumn() | c == this.getColumn() - 1 & r == this.getRow() | c == this.getColumn() + 1 & r == this.getRow()) { this.finalMapWithTiles[r][c] = map.getTileValue(r, c); // invisible part of the map } else { this.finalMapWithTiles[r][c] = 50; } } } break; } return finalMapWithTiles; } /* * Getter to return the finalMapWithTiles. */ public int[][] getFinalMapWithTiles() { return this.finalMapWithTiles; } /* * 4 cases to move the player UP, DOWN, LEFT and RIGHT. This is implemented * using a switch. At every move one energy point is deducted, this is also * printed to the console. The number of moves is counted here to be used in the * score calculation. The new position of the Player is printed to the console * after being updated via the setRow() and setColumn() method. This method also * throws an ArrayOutOfBoundsException if the player reaches the end of the map. * All exception are caught and handled in the main method for the text based * version. InputMismatchExceptions are thrown when the user enters invalid * input. 1 extra case is written to allow for the special abilities of the * Monk. */ public void movePlayer() throws InputMismatchException, ArrayIndexOutOfBoundsException { System.out.println("Move..."); String move = scan.nextLine(); switch (move) { // Down case "5": if (this.getRow() == map.getNumberOfRows() - 1) { throw new ArrayIndexOutOfBoundsException(); } else { this.setRow(this.getRow() + 1); this.setEnergy(this.getEnergy() - 1); System.out.println("Energy: " + this.getEnergy() + " Skill: " + this.getSkill()); break; } // UP case "8": if (this.getRow() == 0) { throw new ArrayIndexOutOfBoundsException(); } else { this.setRow(this.getRow() - 1); this.setEnergy(this.getEnergy() - 1); System.out.println("Energy: " + this.getEnergy() + " Skill: " + this.getSkill()); break; } // right case "6": if (this.getColumn() == map.getNumberOfColumns() - 1) { throw new ArrayIndexOutOfBoundsException(); } else { this.setColumn(this.getColumn() + 1); this.setEnergy(this.getEnergy() - 1); System.out.println("Energy: " + this.getEnergy() + " Skill: " + this.getSkill()); break; } // left case "4": if (this.getColumn() == 0) { throw new ArrayIndexOutOfBoundsException(); } else { this.setColumn(this.getColumn() - 1); this.setEnergy(this.getEnergy() - 1); System.out.println("Energy: " + this.getEnergy() + " Skill: " + this.getSkill()); break; } // special ability of the Monk case "99": if (this.getCharacter().equals("Monk")) { System.out.println("Do you want to transfer skill to energy or energy to skill?" + "If you want to trade 1 skill point for Energy press E if you want more Skill press S." + " It is a 1:1 trade always."); System.out.println("Please enter S or E or any other key if you do ot want to trade"); String s = scan.nextLine(); if (s.equals("S")) { this.setEnergy(getEnergy() - 1); this.setSkill(this.getSkill() + 1); System.out.println("Energy: " + this.getEnergy() + "Skill: " + this.getSkill()); break; } else if (s.equals("E")) { this.setEnergy(getEnergy() + 1); this.setSkill(this.getSkill() - 1); System.out.println("Energy: " + this.getEnergy() + ", Skill: " + this.getSkill()); break; } else { System.out.println("Please enter either S or E"); } } else { System.out.println("You need to dedicate your life to god if you want to use this power." + "\nConsider to choose the life of a Monk next time. "); break; } default: throw new InputMismatchException(); } } /* * 4 cases to move the player UP, DOWN, LEFT and RIGHT. This is implemented * using a switch. At every move one energy point is deducted, this is also * visible in the GUI. Also the number of moves is counted here. The new * position of the Player is updated via the setRow() and setColumn() methods. * This method also throws an ArrayOutOfBoundsException if the player reaches * the end of the map. All exception are caught and handled in the MapPanel * class where the movePlayer(int i) method is called. 2 extra cases are written * to allow for the special abilities of the Monk. */ public void movePlayer(int i) throws InputMismatchException, ArrayIndexOutOfBoundsException { switch (i) { // Down case 5: if (this.getRow() == map.getNumberOfRows() - 1) { throw new ArrayIndexOutOfBoundsException(); } else { this.setRow(this.getRow() + 1); this.setEnergy(this.getEnergy() - 1); this.setNumberOfMoves(this.getNumberOfMoves() + 1); break; } // UP case 8: if (this.getRow() == 0) { throw new ArrayIndexOutOfBoundsException(); } else { this.setRow(this.getRow() - 1); this.setEnergy(this.getEnergy() - 1); this.setNumberOfMoves(this.getNumberOfMoves() + 1); break; } // right case 6: if (this.getColumn() == map.getNumberOfColumns() - 1) { throw new ArrayIndexOutOfBoundsException(); } else { this.setColumn(this.getColumn() + 1); this.setEnergy(this.getEnergy() - 1); this.setNumberOfMoves(this.getNumberOfMoves() + 1); break; } // left case 4: if (this.getColumn() == 0) { throw new ArrayIndexOutOfBoundsException(); } else { this.setColumn(this.getColumn() - 1); this.setEnergy(this.getEnergy() - 1); this.setNumberOfMoves(this.getNumberOfMoves() + 1); break; } // Secial ability of the monk to trade energy for skill points case 1: if (this.getCharacter().equals("Monk") & this.getEnergy() > 1) { this.setEnergy(getEnergy() - 1); this.setSkill(this.getSkill() + 1); } else { if (this.getCharacter().equals("Monk")) { JOptionPane.showMessageDialog(null, "You do not have enough energy to trade, this would kill you."); } else { JOptionPane.showMessageDialog(null, "You need to dedicate your life to god if you want to use this power." + "\nConsider to choose the life of a Monk next time."); } } break; // special ability of the monk to trade skill points for energy case 2: if (this.getCharacter().equals("Monk") & this.getSkill() > 0) { this.setEnergy(getEnergy() + 1); this.setSkill(this.getSkill() - 1); } else { if (this.getCharacter().equals("Monk")) { JOptionPane.showMessageDialog(null, "You do not have skill to trade."); } else { JOptionPane.showMessageDialog(null, "<html><div>You need to dedicate your life to god if you want to use this power." + "<br>Consider to choose the life of a Monk next time</div></html>"); } } break; default: throw new InputMismatchException(); } } /* * This method links the impact of the tiles to the players attributes, like the * skill and the energy, also prices can be won when tournament is won or a * opponent is beaten. The amount of prices won is also counted and can be used * to calculate the score in the end. To get the current location the getRow() * and getColumn() methods are called and these values are given to the * getMapWithTiles() method to get the value of the tile the player is standing * on. If the map is also updated in case of book, potion, beaten opponent, won * tournament and found key, so that each of these items can only be gathered * once. */ public void tileImpact() { int tileValue = map.getTileValue(this.getRow(), this.getColumn()); switch (tileValue) { // normal tile case 0: break; // stony ground case 1: this.setSkill(this.getSkill() - 2); JOptionPane.showMessageDialog(null, "Stony ground" + " -> Skill -2\n Your new skill level is " + this.getSkill() + "."); break; // Book case 2: this.setSkill(this.getSkill() + 3); JOptionPane.showMessageDialog(null, "A long lost book full of wisdom" + " -> Skill + 3"); map.setTileValueZero(this.getRow(), this.getColumn()); break; // tournament case 3: this.setRequiredSkillTournament(); JOptionPane.showMessageDialog(null, "A tournament, good luck!\n" + "The Skill needed to win is " + this.getRequiredSkillTournament() + "."); if (this.getSkill() > this.getRequiredSkillTournament()) { this.setWonPrices(this.getWonPrices() + 1); JOptionPane.showMessageDialog(null, "Congratulation! You were the best.\n" + "You won a price, you won " + this.getWonPrices() + " price(s) so far."); map.setTileValueZero(this.getRow(), this.getColumn()); break; } else { JOptionPane.showMessageDialog(null, "You lost. The laughter of the crowd still rings in your ears, learn to ride a horse " + this.name + "."); this.energy = this.getEnergy() - 2; break; } // opponent case 4: this.setRequiredSkillOpponent(); JOptionPane.showMessageDialog(null, "You met an opponent!" + "Required skill: " + this.getRequiredSkillOpponent()); if (this.getSkill() > this.getRequiredSkillOpponent()) { this.setWonPrices(this.getWonPrices() + 1); JOptionPane.showMessageDialog(null, "Congratulation! Your opponent did not stand a chance.\n" + "You won a price, Total price(s) =" + this.getWonPrices() + "."); map.setTileValueZero(this.getRow(), this.getColumn()); break; } else { JOptionPane.showMessageDialog(null, "You lost, Energy -2"); this.energy = this.getEnergy() - 2; break; } case 5: // Potion this.energy = this.getEnergy() + 3; JOptionPane.showMessageDialog(null, "A potion" + " -> Energy + 3 :-)"); map.setTileValueZero(this.getRow(), this.getColumn()); break; case 6: // Key this.setNumberOfKeys(getNumberOfKeys() + 1); JOptionPane.showMessageDialog(null, "A Key. You found this amount of keys so far:" + this.getNumberOfKeys()); map.setTileValueZero(this.getRow(), this.getColumn()); break; case 7: // Castle if (this.getNumberOfKeys() == map.getNUMBER_OF_REQUIRED_KEYS()) { JOptionPane.showMessageDialog(null, "You won! Congratulations!"); setWon(true); } else { JOptionPane.showMessageDialog(null, "You have not found all keys yet. Continue on your quest"); break; } } } /* * Sets the boolean won to either true or false. If the player has won the game * won is set to true */ public void setWon(boolean won) { this.won = won; } /* * Returns the value of won. */ public boolean getWon() { return this.won; } /* * Returns the number of keys the player has found. */ public int getNumberOfKeys() { return this.numberOfKeys; } /* * Sets the number of keys the player has found. */ public void setNumberOfKeys(int numberOfKeys) { this.numberOfKeys = numberOfKeys; } /* * This method is invoked in the MainGame class for the text-based version. * Exceptions are handled in this method directly. */ public void chooseName() { System.out.println("What should I call you?"); try { this.name = scan.nextLine(); } catch (InputMismatchException ime) { System.out.println("Something went wrong."); } } /* * Returns the name of the player. */ public String getName() { return this.name; } /* * This method sets the name of the player. This method is called from an * actionlistener in the SelectionGui class to set the name of the player, when * playing the GUI version. */ public void setName(String name) { this.name = name; } /* * Sets the energy of the player. */ public void setEnergy(int energy) { this.energy = energy; } /* * Returns the energy of the player. */ public int getEnergy() { return energy; } /* * this method is called from the MainGame class and asks for user input to set * the energy for the user to begin the game with. the energy can be set between * 0 and the current allowed maximum. Exceptions are handled in this method and * the user informed if the input was illegal and a default energy level is * selected. Also sets the skill without user input by making a tradeoff between * energy and skill */ public void chooseEnergy() { try { System.out.println("Please choose the energy you would like to start with. " + "It will be a tradeoff between Energy and Skill and the sum will be " + map.getAllowedSkillEnergy() + "."); int i = scan.nextInt(); if (i <= map.getAllowedSkillEnergy() & i >= 0) { this.energy = i; } else { throw new InputMismatchException(); } } catch (InputMismatchException ime) { System.out.println("Only values between 0 and " + map.getAllowedSkillEnergy() + " are allowed. " + "The default was set to:" + this.getDefaultEnergy() + "."); this.energy = this.getDefaultEnergy(); scan.nextLine(); } this.skill = map.getAllowedSkillEnergy() - this.getEnergy(); if (this.getCharacter().equals("Warrior")) { System.out.println("Your training as a Warrior made you powerful." + "\nEnergy +4."); this.energy = this.energy + 4; } scan.nextLine(); } /* * This method is called from the Actionlisteners in the SelectionGui class and * asks for user input to set the energy for the user to begin the game with. * the energy can be set between 0 and the current allowed * maximum(ALLOWED_SKILL_ENERGY). IllegalArgument exceptions do not need to be * handled when using a JSlider for input. Also sets the skill without user * input by making a tradeoff between energy and skill. */ public void chooseEnergy(int i) { try { if (i <= map.getAllowedSkillEnergy() & i >= 0) { this.energy = i; } else { throw new IllegalArgumentException(); } } catch (IllegalArgumentException iae) { } this.skill = map.getAllowedSkillEnergy() - this.getEnergy(); if (this.getCharacter().equals("Warrior")) { this.energy = this.energy + 4; } } /* * Method for the default energy in case the user gives illegal input * (text-based). */ public int getDefaultEnergy() { return map.getAllowedSkillEnergy() / 2; } /* * Returns the skill of the player. */ public int getSkill() { return this.skill; } /* * Sets the skill of the player.In order to prevent the skill becoming negative * during game play (e.g. when walking over stony ground) negative numbers are * handled here and 0 is set a value if negative values would be calculated. */ public void setSkill(int skill) { if (skill >= 0) { this.skill = skill; } else { this.skill = 0; } } /* * Returns the column of the players current location. */ public int getColumn() { return column; } /* * Sets the column of the players location. */ public void setColumn(int column) { this.column = column; } /* * Returns the row of the players current location. */ public int getRow() { return row; } /* * Sets the row of the players location. */ public void setRow(int row) { this.row = row; } /* * Returns the amount of prices the player has won (by beating oponents or * winning battles) */ public int getWonPrices() { return wonPrices; } /* * Method used to set the amount of prices a player has won. */ public void setWonPrices(int wonPrices) { this.wonPrices = wonPrices; } /* * Returns the skill that is required to beat a juror. */ public int getRequiredSkillTournament() { return requiredSkillTournament; } /* * The skill a juror requires is set here. the amount of chance can be set via a * variable. */ public void setRequiredSkillTournament() { this.requiredSkillTournament = map.getAllowedSkillEnergy() / 2 - LEVEL_OF_CHANCE / 2 + r.nextInt(LEVEL_OF_CHANCE); } /* * The skill that is required to win against an opponent is returned by this * method. */ public int getRequiredSkillOpponent() { return this.requiredSkillOpponent; } /* * The skill that is required to win against an opponent is set here. */ public void setRequiredSkillOpponent() { this.requiredSkillOpponent = map.getAllowedSkillEnergy() / 2 - LEVEL_OF_CHANCE / 3 + r.nextInt(LEVEL_OF_CHANCE); } /* * tThis method is returning the number of moves a player has made. */ public int getNumberOfMoves() { return this.numberOfMoves; } /* * Sets the number of moves a player has made. */ public void setNumberOfMoves(int numberOfMoves) { this.numberOfMoves = numberOfMoves; } }
true
041d74e7ccc69b532cde3e12d6a8bb5936676a05
Java
heiscoming2/KH_FINAL1
/src/main/java/com/itpro/model/dto/note/NoteDto.java
UTF-8
608
2.015625
2
[]
no_license
package com.itpro.model.dto.note; import java.util.Date; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class NoteDto { private int n_no;//쪽지 번호 private int n_sender;//보낸사람회원번호 private int n_receiver;//받는사람 회원번호 private String n_title;//쪽지 제목 private String n_content;//내용 private Date n_sendDate;//보낸 시간 private Date n_readDate; //읽은 시간 // member private String m_nickname; // 닉네임 // noteSend private String n_receiver_nickname; // 받는사람 닉네임 }
true
72469bfea4912054d71ad8cfd0580b0e3de6dfcb
Java
SmileAlfred/CollectionsFramework
/opendanmaku-sample/src/main/java/com/opendanmaku/sample/MainActivity.java
UTF-8
3,879
2.28125
2
[ "Apache-2.0" ]
permissive
package com.opendanmaku.sample; import android.os.Bundle; import android.text.Spannable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ImageSpan; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import com.opendanmaku.DanmakuItem; import com.opendanmaku.DanmakuView; import com.opendanmaku.IDanmakuItem; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private DanmakuView mDanmakuView; private Button switcherBtn; private Button sendBtn; private EditText textEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mDanmakuView = (DanmakuView) findViewById(R.id.danmakuView); switcherBtn = (Button) findViewById(R.id.switcher); sendBtn = (Button) findViewById(R.id.send); textEditText = (EditText) findViewById(R.id.text); List<IDanmakuItem> list = initItems(); Collections.shuffle(list); mDanmakuView.addItem(list, true); switcherBtn.setOnClickListener(this); sendBtn.setOnClickListener(this); } private List<IDanmakuItem> initItems() { List<IDanmakuItem> list = new ArrayList<>(); for (int i = 0; i < 100; i++) { IDanmakuItem item = new DanmakuItem(this, i + " : plain text danmuku", mDanmakuView.getWidth()); list.add(item); } String msg = " : text with image "; for (int i = 0; i < 100; i++) { ImageSpan imageSpan = new ImageSpan(this, R.drawable.em); SpannableString spannableString = new SpannableString(i + msg); spannableString.setSpan(imageSpan, spannableString.length() - 2, spannableString.length() - 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); IDanmakuItem item = new DanmakuItem(this, spannableString, mDanmakuView.getWidth(), 0, 0, 0, 1.5f); list.add(item); } return list; } @Override protected void onResume() { super.onResume(); mDanmakuView.show(); } @Override protected void onPause() { super.onPause(); mDanmakuView.hide(); } @Override protected void onDestroy() { super.onDestroy(); mDanmakuView.clear(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.switcher: if (mDanmakuView.isPaused()) { switcherBtn.setText(R.string.hide); mDanmakuView.show(); } else { switcherBtn.setText(R.string.show); mDanmakuView.hide(); } break; case R.id.send: String input = textEditText.getText().toString(); if (TextUtils.isEmpty(input)) { Toast.makeText(MainActivity.this, R.string.empty_prompt, Toast.LENGTH_SHORT).show(); } else { IDanmakuItem item = new DanmakuItem(this, new SpannableString(input), mDanmakuView.getWidth(),0,R.color.my_item_color,0,1); // IDanmakuItem item = new DanmakuItem(this, input, mDanmakuView.getWidth()); // item.setTextColor(getResources().getColor(R.color.my_item_color)); // item.setTextSize(14); // item.setTextColor(textColor); mDanmakuView.addItemToHead(item); } textEditText.setText(""); break; default: break; } } }
true
131751c03088edae0cbfb67ff0a3d89e87c85018
Java
johnperry/MIRC1
/source/java/org/rsna/filesender/CmdLineSender.java
UTF-8
10,875
2.625
3
[]
no_license
/*--------------------------------------------------------------- * Copyright 2005 by the Radiological Society of North America * * This source software is released under the terms of the * RSNA Public License (http://mirc.rsna.org/rsnapubliclicense) *----------------------------------------------------------------*/ package org.rsna.filesender; import java.io.*; import java.net.*; import java.security.SecureRandom; import java.security.cert.X509Certificate; import java.util.*; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import org.apache.log4j.*; import org.rsna.dicom.DicomSender; /** * The CmdLineSender program provides a command line * File Sender that transmits a single file. This * program is built in the same package as FileSender and * is installed in the same directory with it by the * FileSender-installer.jar program. It uses the same * library jars as FileSender. */ public class CmdLineSender { static final Logger logger = Logger.getLogger(CmdLineSender.class); /** * The main method to start the program. * <p> * If the args array contains two or more parameters, the program * attempts to send the file identified by the first parameter * to the destination identified by the second parameter. If there * are other parameters, they are interpreted as switches: * <ol> * <li>-d forces the Content-Type to DICOM for HTTP and HTTPS</li> * </ol> * @param args the list of arguments from the command line. */ public static void main(String args[]) { Logger.getRootLogger().addAppender( new ConsoleAppender( new PatternLayout("%d{HH:mm:ss} %-5p [%c{1}] %m%n"))); Logger.getRootLogger().setLevel(Level.WARN); if (args.length >= 2) { //Get the file to be transmitted. File file = new File(args[0]); if (!file.exists() || !file.isFile()) { System.out.println("The file is not a data file."); return; } //Get the destination URL String url = args[1]; //Get the swtiches String switches = ""; for (int i=2; i<args.length; i++) switches += args[i]; //Transmit the file CmdLineSender sender = new CmdLineSender(file,url, (switches.indexOf("-d") != -1) ); } else { //Wrong number of arguments, just display some help. printHelp(); } } //Transmit a file. public CmdLineSender(File file, String urlString, boolean forceDicomContentType) { String urlLC = urlString.toLowerCase().trim(); boolean http = (urlLC.indexOf("http://") != -1); boolean https = (urlLC.indexOf("https://") != -1); boolean dicom = (urlLC.indexOf("dicom://") != -1); try { if (http || https) { sendFileUsingHttp(file,urlString,forceDicomContentType); } else if (dicom) { DicomURL dest = new DicomURL(urlString); sendFileUsingDicom(file,dest); } } catch (Exception e) { System.out.println("Exception:\n" + e.getMessage()); } } //Send one file using HTTP or HTTPS. private void sendFileUsingHttp(File file, String urlString, boolean forceDicomContentType) { URLConnection conn; OutputStream svros; FileInputStream fis; BufferedReader svrrdr; System.out.println("Send " + file.getAbsolutePath() + " to " + urlString); //Make the connection try { URL url = new URL(urlString); if (url.getProtocol().toLowerCase().startsWith("https")) { TrustManager[] trustAllCerts = new TrustManager[] { new AcceptAllX509TrustManager() }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null,trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection(); httpsConn.setHostnameVerifier(new AcceptAllHostnameVerifier()); httpsConn.setUseCaches(false); httpsConn.setDefaultUseCaches(false); conn = httpsConn; } else conn = url.openConnection(); conn.setDoOutput(true); //Set the content type String contentType = null; if (forceDicomContentType || file.getName().matches("[\\d\\.]+")) contentType = "application/x-mirc-dicom"; else { try { Properties contentTypes; InputStream is = this.getClass().getResource("/content-types.properties").openStream(); contentTypes = new Properties(); contentTypes.load(is); String ext = file.getName(); ext = ext.substring(ext.lastIndexOf(".")+1).toLowerCase(); contentType = (String)contentTypes.getProperty(ext); } catch (Exception e) { System.out.println( "Unable to load the content-types.properties resource:\n" + e.getMessage()); return; } } if (contentType == null) contentType = "application/default"; conn.setRequestProperty("Content-Type",contentType); //Set the content disposition conn.setRequestProperty( "Content-Disposition","attachment; filename=\"" + file.getName() + "\""); //Make the connection conn.connect(); svros = conn.getOutputStream(); } catch (Exception e) { System.out.println("Unable to establish a URLConnection to " + urlString); return; } //Get the stream to read the file try { fis = new FileInputStream(file);} catch (IOException e) { System.out.println( "Unable to obtain an input stream to read the file:\n" + e.getMessage()); return; } //Send the file to the server try { int n; byte[] bbuf = new byte[1024]; while ((n=fis.read(bbuf,0,bbuf.length)) > 0) svros.write(bbuf,0,n); svros.flush(); svros.close(); fis.close(); } catch (IOException e) { System.out.println("Error sending the file:\n" + e.getMessage()); return; } //Get the response and report it try { svrrdr = new BufferedReader(new InputStreamReader(conn.getInputStream())); } catch (IOException e) { System.out.println( "Unable to obtain an input stream to read the response:\n" + e.getMessage()); return; } try { StringWriter svrsw = new StringWriter(); int n; char[] cbuf = new char[1024]; while ((n = svrrdr.read(cbuf,0,cbuf.length)) != -1) svrsw.write(cbuf,0,n); svrrdr.close(); String response = svrsw.toString(); //Try to make a nice response without knowing anything about the receiving application. String responseLC = response.toLowerCase(); if (!forceDicomContentType) { //See if we got an html page back if (responseLC.indexOf("<html>") != -1) { //We did, see if it looks like a successful submit service response if (responseLC.indexOf("was received and unpacked successfully") != -1) { //It does, just display OK System.out.println("OK"); } else if ((responseLC.indexOf("unsupported") != -1) || (responseLC.indexOf("failed") != -1) || (responseLC.indexOf("error") != -1)) { //This looks like an error System.out.println("Error received from the server:\n" + response); } else { //It's not clear what this is; return the whole text without comment. System.out.println(response); } } else { //It's not an html page; return the whole text without comment. System.out.println(response); } } //If it was a forced DICOM content type send, then look for "error" else if (responseLC.indexOf("error") != -1) { System.out.println("Error received from the server:\n" + response); } else System.out.println(response); } catch (IOException e) { System.out.println( "Unable to obtain the response:\n" + e.getMessage()); } } //Send one file using DICOM. private void sendFileUsingDicom(File file, DicomURL dest) { System.out.println( "Sending " +file.getAbsolutePath() + " to " + dest.urlString); try { DicomSender dicomSender = new DicomSender( dest.host, dest.port, dest.calledAET, dest.callingAET); int result = dicomSender.send(file); if (result != 0) { System.out.println("DicomSend Error: [result=" + result + "]"); return; } } catch (Exception e) { String message = "DicomSend Exception:"; if (e.getMessage() != null) message += e.getMessage() + "\n"; else message += " [no error message]\n"; System.out.println(message); return; } System.out.println("OK"); } //All-accepting X509 Trust Manager class AcceptAllX509TrustManager implements X509TrustManager { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } //All-verifying HostnameVerifier class AcceptAllHostnameVerifier implements HostnameVerifier { public boolean verify(String urlHost, SSLSession ssls) { return true; } } //Decode a DICOM URL into its component pieces and encapsulate them. class DicomURL { public String calledAET; public String callingAET; public String host; public int port; public String urlString; public DicomURL(String urlString) throws Exception { this.urlString = urlString; int k = urlString.indexOf("://") + 3; int kk = urlString.indexOf(":",k); if (kk == -1) throw new Exception("Missing separator [:] for AE Titles"); calledAET = urlString.substring(k,kk).trim(); k = ++kk; kk = urlString.indexOf("@",k); if (kk == -1) throw new Exception("Missing terminator [@] for CallingAET"); callingAET = urlString.substring(k,kk).trim(); k = ++kk; kk = urlString.indexOf(":",k); if (kk == -1) throw new Exception("Missing separator [:] for Host and Port"); host = urlString.substring(k,kk).trim(); k = ++kk; String portString = urlString.substring(k).trim(); try { port = Integer.parseInt(portString); } catch (Exception e) { throw new Exception("Unparseable port number ["+portString+"]"); } } } //Some help text private static void printHelp() { System.out.println( "\nUsage:\n" + "------\n\n" + "java -jar programdir/fs.jar path/file url switches\n\n" + "where:\n" + " path/file = the path to the file to be transmitted\n" + " url = the URL of the destination:\n" + " http://host:port/trial/import/doc\n" + " https://host:port/trial/import/doc\n" + " dicom://destinationAET:senderAET@host:port\n" + " switches:\n" + " -dicom (or just -d) forces the Content-Type\n\n" + "Notes:\n" + " The senderAET is optional in a DICOM transmission.\n\n" + " The -dicom switch only applies to the http or https protocols.\n" + " It can be used to force the Content-Type when the file being\n" + " transmitted is a DICOM file but the extension is not \".dcm\".\n" + "Example:\n" + " java -jar /bin/FileSender/fs.jar /path/filename.dcm url -d\n" ); } }
true
4f10b4674aac9803467f1e126fe5f887546bcadd
Java
shynkariuk/study
/src/main/java/com/shink/model/entity/Customer.java
UTF-8
113
1.71875
2
[]
no_license
package com.shink.model.entity; public class Customer { Long id; String name; String phoneNumber; }
true
f830fc7228f9b76f52e3184818a959c739f36533
Java
sicef-hakaton-4/codeline
/hakatonJava/Hakaton/src/main/java/net/sytes/codeline/entities/RecommendationInfo.java
UTF-8
1,924
2.515625
3
[]
no_license
package net.sytes.codeline.entities; public class RecommendationInfo { private String firstName1; private String lastName1; private String firstName2; private String lastName2; private String companyName; private String jobTitle; private String email; public RecommendationInfo() { super(); } public RecommendationInfo(String firstName1, String lastName1, String firstName2, String lastName2, String companyName, String jobTitle, String email) { super(); this.firstName1 = firstName1; this.lastName1 = lastName1; this.firstName2 = firstName2; this.lastName2 = lastName2; this.companyName = companyName; this.jobTitle = jobTitle; this.email = email; } public String getFirstName1() { return firstName1; } public void setFirstName1(String firstName1) { this.firstName1 = firstName1; } public String getLastName1() { return lastName1; } public void setLastName1(String lastName1) { this.lastName1 = lastName1; } public String getFirstName2() { return firstName2; } public void setFirstName2(String firstName2) { this.firstName2 = firstName2; } public String getLastName2() { return lastName2; } public void setLastName2(String lastName2) { this.lastName2 = lastName2; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getJobTitle() { return jobTitle; } public void setJobTitle(String jobTitle) { this.jobTitle = jobTitle; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "RecommendationInfo [firstName1=" + firstName1 + ", lastName1=" + lastName1 + ", firstName2=" + firstName2 + ", lastName2=" + lastName2 + ", companyName=" + companyName + ", jobTitle=" + jobTitle + ", email=" + email + "]"; } }
true
a840baf1fb85bbd76a7169ea2d4bdb1bc217b001
Java
GalaxyTrainingSupport/selenium-testng
/session_6/src/test/java/pe/edu/galaxy/tests/PropertyOrangeXml.java
UTF-8
1,675
2.125
2
[]
no_license
package pe.edu.galaxy.tests; import org.testng.annotations.Test; import org.testng.annotations.BeforeClass; import java.io.File; import org.dom4j.Document; import org.dom4j.io.SAXReader; import org.junit.Assert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.BeforeTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; public class PropertyOrangeXml { static WebDriver driver = null; static SAXReader saxReader = new SAXReader(); static String path = System.getProperty("user.dir"); static Document document = null; // pre-conditions before run test @BeforeSuite public void Setup() throws Exception { System.out.println("Setup system properties for chrome"); File inputFile = new File(System.getProperty("user.dir") +"/data/properties.xml"); document = saxReader.read(inputFile); } @BeforeTest public void lauchBrowser() { driver = new FirefoxDriver(); } @BeforeClass public void setURL() { String url = document.selectSingleNode("//login/url").getText(); System.out.println(url); driver.get(document.selectSingleNode("//login/url").getText()); } // running test @Test public void doLogin() { driver.findElement(By.id("txtUsername")).sendKeys(document.selectSingleNode("//login/user").getText()); driver.findElement(By.id("txtPassword")).sendKeys(document.selectSingleNode("//login/pass").getText()); driver.findElement(By.name("Submit")); Assert.assertEquals("Test completed", "OrangeHRM", driver.getTitle()); } @AfterSuite public void tearDown() { driver.quit(); } }
true
2b5e05c7b8d9e9699f23ebc2d4a64cd837230f17
Java
jesp010/stomc-cliente
/src/main/MenuSucursalesController.java
UTF-8
7,083
2.21875
2
[]
no_license
package main; import comm.Conexion; import dominio.CatalogueBranch; import dominio.LysingInformation; import dominio.Message; import gui_elements.Toast; import javafx.application.Platform; import javafx.beans.property.SimpleStringProperty; import javafx.beans.value.ObservableValue; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.control.*; import javafx.scene.layout.AnchorPane; import javafx.scene.text.Text; import javafx.util.Callback; import java.io.IOException; import java.util.List; import java.util.Optional; public class MenuSucursalesController implements IController { AccionSucursalController accionSucursalController; @FXML public AnchorPane rootPane; @FXML public Button btnAniadir; @FXML public Button btnEditar; @FXML public Button btnEliminar; @FXML public TableView<CatalogueBranch> tblCatalagoSucursales; @FXML public TableColumn colFolioCatalagoSucursales; @FXML public TableColumn colNombreCatalagoSucursales; @FXML public TableColumn colDireccion; public void initialize(){ System.out.println("MenuSucursalesController did initialize"); Conexion.getInstance().setController(this); colFolioCatalagoSucursales.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<CatalogueBranch, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<CatalogueBranch, String> cellDataFeatures) { if (cellDataFeatures.getValue().getFolio() != null) { return new SimpleStringProperty(cellDataFeatures.getValue().getFolio().toString()); } return new SimpleStringProperty(""); } }); colNombreCatalagoSucursales.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<CatalogueBranch, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<CatalogueBranch, String> cellDataFeatures) { if (cellDataFeatures.getValue().getBranchName() != null) { return new SimpleStringProperty(cellDataFeatures.getValue().getBranchName()); } return new SimpleStringProperty(""); } }); colDireccion.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<CatalogueBranch, String>, ObservableValue<String>>() { @Override public ObservableValue<String> call(TableColumn.CellDataFeatures<CatalogueBranch, String> cellDataFeatures) { if (cellDataFeatures.getValue().getAddress() != null) { return new SimpleStringProperty(cellDataFeatures.getValue().getAddress()); } return new SimpleStringProperty(""); } }); // Wrap text en la columna de los procesos. colDireccion.setCellFactory(tc -> { TableCell<LysingInformation, String> cell = new TableCell<>(); Text text = new Text(); cell.setGraphic(text); cell.setPrefHeight(Control.USE_COMPUTED_SIZE); text.wrappingWidthProperty().bind(colDireccion.widthProperty()); text.textProperty().bind(cell.itemProperty()); return cell ; }); try { Conexion.getInstance().sendMessage(new Message(Message.MessageType.GET_MANY_CATALOGUE_BRANCH, "test_user")); } catch (IOException e) { e.printStackTrace(); } } @FXML public void didClickAniadirSucursalButton(ActionEvent actionEvent) { loadContent(actionEvent, "Añadir"); } @FXML public void didClickEditarSucursalButton(ActionEvent actionEvent) { if (tblCatalagoSucursales.getSelectionModel().getSelectedItem() != null) { loadContent(actionEvent, "Editar"); } else { makeToast("Seleccione una sucursal para editarlo"); } } @FXML public void didClickEliminarSucursalButton(ActionEvent actionEvent) { if (tblCatalagoSucursales.getSelectionModel().getSelectedItem() != null) { deleteCatalogueBranch(); } else { makeToast("Selecciona una sucursal del catalago para eliminarlo"); } } private void deleteCatalogueBranch() { Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setHeaderText(null); alert.setTitle("Confirmación"); alert.setContentText("¿Estas seguro de eliminar esta sucursal del catalago?"); Optional<ButtonType> action = alert.showAndWait(); if (action.get() == ButtonType.OK) { Message msg = new Message(Message.MessageType.DELETE_CATALOGUE_BRANCH, "test_user"); msg.setObject(tblCatalagoSucursales.getSelectionModel().getSelectedItem().getId()); try { Conexion.getInstance().sendMessage(msg); } catch (IOException e) { e.printStackTrace(); } } } public void loadContent(ActionEvent actionEvent, String accion) { try { FXMLLoader loader = new FXMLLoader(getClass().getResource("accionSucursal.fxml")); Parent root = loader.load(); accionSucursalController = loader.getController(); if (accion.equalsIgnoreCase("Editar")) { accionSucursalController.setSucursal(tblCatalagoSucursales.getSelectionModel().getSelectedItem()); } accionSucursalController.setAccion(accion); rootPane.getChildren().setAll(root); } catch (IOException e) { e.printStackTrace(); } } public void makeToast(String mensaje) { Toast.makeText(null, mensaje, 3500,100,300); } @Override public void handleMessage(Message message) { switch (message.getType()) { case GET_MANY_CATALOGUE_BRANCH: ObservableList<CatalogueBranch> lista1 = FXCollections.observableList((List<CatalogueBranch>) message.getObject()); Platform.runLater(new Runnable() { @Override public void run() { tblCatalagoSucursales.setItems(lista1); } }); break; case DELETE_CATALOGUE_BRANCH: ObservableList<CatalogueBranch> lista2 = FXCollections.observableList((List<CatalogueBranch>) message.getObject()); Platform.runLater(new Runnable() { @Override public void run() { tblCatalagoSucursales.setItems(lista2); makeToast("La sucursal ha sido eliminado correctamente"); } }); break; } } }
true
37a1dbc8a22e4eda0fe17cf2a91565cc50ef1788
Java
jtlai0921/PB1412--Java-
/PB1218/Codes/CH11/274/src/ColorChooser.java
BIG5
4,797
2.875
3
[]
no_license
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JColorChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridLayout; import javax.swing.JLabel; import javax.swing.JButton; import java.awt.Color; import javax.swing.SwingConstants; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.UIManager; public class ColorChooser extends JFrame { private JPanel contentPane; private JLabel label1; private JLabel label2; private JLabel label3; private JLabel label4; /** * Launch the application. */ public static void main(String[] args) { try { UIManager .setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); } catch (Throwable e) { e.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { ColorChooser frame = new ColorChooser(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public ColorChooser() { setTitle("Cܹܮ"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 348, 162); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(new GridLayout(0, 3, 0, 0)); JLabel label = new JLabel("jCG"); label.setHorizontalAlignment(SwingConstants.RIGHT); contentPane.add(label); label1 = new JLabel(""); label1.setOpaque(true); label1.setBackground(Color.WHITE); contentPane.add(label1); JButton button1 = new JButton(""); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button1_actionPerformed(e); } }); contentPane.add(button1); JLabel label_2 = new JLabel("𸭪CG"); label_2.setHorizontalAlignment(SwingConstants.RIGHT); contentPane.add(label_2); label2 = new JLabel(""); label2.setBackground(Color.WHITE); label2.setOpaque(true); contentPane.add(label2); JButton button2 = new JButton(""); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button2_actionPerformed(e); } }); contentPane.add(button2); JLabel label_4 = new JLabel("CG"); label_4.setHorizontalAlignment(SwingConstants.RIGHT); contentPane.add(label_4); label3 = new JLabel(""); label3.setBackground(Color.WHITE); label3.setOpaque(true); contentPane.add(label3); JButton button3 = new JButton(""); button3.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button3_actionPerformed(e); } }); contentPane.add(button3); JLabel label_6 = new JLabel("ڪG"); label_6.setHorizontalAlignment(SwingConstants.RIGHT); contentPane.add(label_6); label4 = new JLabel(""); label4.setBackground(Color.WHITE); label4.setOpaque(true); contentPane.add(label4); JButton button4 = new JButton(""); button4.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_button4_actionPerformed(e); } }); contentPane.add(button4); } protected void do_button1_actionPerformed(ActionEvent e) { setColor(label1);// wҪC]w } private void setColor(JLabel label) { Color color = label.getBackground();// oӪCﹳ // Cܥ͵ Color newColor = JColorChooser.showDialog(this, "C", color); label.setBackground(newColor);// oC]wҪI } protected void do_button2_actionPerformed(ActionEvent e) { setColor(label2); } protected void do_button3_actionPerformed(ActionEvent e) { setColor(label3); } protected void do_button4_actionPerformed(ActionEvent e) { setColor(label4); } } 
true
fa8b676e32fb6e6167aaf333881c0610ed4a1c26
Java
caesarcheng1226/MenuRecommendation2
/app/src/main/java/com/example/menurecommendation/RecipeFragment.java
UTF-8
2,229
2.09375
2
[]
no_license
package com.example.menurecommendation; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListAdapter; import android.widget.ExpandableListView; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; public class RecipeFragment extends Fragment { ExpandableListView expandableListView; ExpandableListAdapter expandableListAdapter; List<String> expandableListTitle; LinkedHashMap<String, List<String>> expandableListDetail; DataPassListener mCallback; public interface DataPassListener{ public void passData(String data); } int[] listviewImage = new int[]{ R.drawable.meat_banner, R.drawable.vegetable_banner, R.drawable.soup_banner, R.drawable.seafood_banner, R.drawable.fruit_banner, }; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_recipe, container, false); expandableListView = rootView.findViewById(R.id.expandableListView); expandableListDetail = RecipeData.getData(); expandableListTitle = new ArrayList<>(expandableListDetail.keySet()); expandableListAdapter = new CustomExpandableListAdapter(getContext(), expandableListTitle, expandableListDetail, listviewImage); expandableListView.setAdapter(expandableListAdapter); expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { mCallback.passData(parent.getExpandableListAdapter().getChild(groupPosition, childPosition).toString()); return false; } }); return rootView; } }
true
27ccdd72f66a43c5ed661d4dd36b0fba55adf4b1
Java
UCDAyoung/Algorithm
/Bagjun/src/sort/Insertion_sort.java
UTF-8
1,151
3.9375
4
[]
no_license
/* 작성 : 21.06.10 * 수정 : * 확인 : * * 삽입정렬 * 타겟과 이전 원소들을 비교해가며 정렬 * 타겟보다 작은게 나올 때까지 계속 이전 원소들과 비교 * * */ package sort; public class Insertion_sort { public void sort(int[] data) { for(int i=1 ; i < data.length; i++) { int target = data[i]; //타겟 저장 int prev = i-1; //타겟 이전 요소 while(prev >= 0 && target < data[prev]){ data[prev+1] = data[prev]; // 계속 뒤로 덮어쓰기 prev--; } data[prev+1] = target; //마지막에 바꾸기 // 코드 리뷰 : 아래와 같이 swap을 쓰면 버블소트랑 다른게 없잖아 // target 저장해놓았다가, 쭉 민다음에 나중에 바꾸는거 // if(data[i]<data[prev]) { // int temp = data[i]; // data[i] = data[prev]; // data[prev] = temp; // prev--; // } // else break; } } public static void main(String[] args) { Insertion_sort Insert = new Insertion_sort(); int[] data = {6,7,3,4,1,4}; Insert.sort(data); for(int i : data) System.out.print(i + " "); } }
true
4a0dadc15c83e6862ded8c742a5096f3f2b37583
Java
flipkart-incubator/hbase-orm
/src/test/java/com/flipkart/hbaseobjectmapper/testcases/entities/ClassWithTwoHBColumnAnnotations.java
UTF-8
563
2.359375
2
[ "Apache-2.0" ]
permissive
package com.flipkart.hbaseobjectmapper.testcases.entities; import com.flipkart.hbaseobjectmapper.*; @HBTable(name = "blah", families = {@Family(name = "f")}) public class ClassWithTwoHBColumnAnnotations implements HBRecord<String> { protected String key = "key"; @HBColumn(family = "f", column = "c1") @HBColumnMultiVersion(family = "f", column = "c1") private Float c1; @Override public String composeRowKey() { return key; } @Override public void parseRowKey(String rowKey) { this.key = rowKey; } }
true
c32df3dd60a4c8249fcb26bc9ae966ff0d97f78a
Java
cloudshop/service-product
/src/test/java/com/eyun/product/web/rest/CategoryResourceIntTest.java
UTF-8
40,335
1.671875
2
[]
no_license
package com.eyun.product.web.rest; import com.eyun.product.ProductApp; import com.eyun.product.config.SecurityBeanOverrideConfiguration; import com.eyun.product.domain.Category; import com.eyun.product.repository.CategoryRepository; import com.eyun.product.service.CategoryService; import com.eyun.product.service.dto.CategoryDTO; import com.eyun.product.service.mapper.CategoryMapper; import com.eyun.product.web.rest.errors.ExceptionTranslator; import com.eyun.product.service.dto.CategoryCriteria; import com.eyun.product.service.CategoryQueryService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; import static com.eyun.product.web.rest.TestUtil.createFormattingConversionService; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the CategoryResource REST controller. * * @see CategoryResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = {ProductApp.class, SecurityBeanOverrideConfiguration.class}) public class CategoryResourceIntTest { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final Long DEFAULT_PARENT_ID = 1L; private static final Long UPDATED_PARENT_ID = 2L; private static final Boolean DEFAULT_IS_PARENT = false; private static final Boolean UPDATED_IS_PARENT = true; private static final String DEFAULT_TARGET = "AAAAAAAAAA"; private static final String UPDATED_TARGET = "BBBBBBBBBB"; private static final Integer DEFAULT_TARGET_TYPE = 1; private static final Integer UPDATED_TARGET_TYPE = 2; private static final Instant DEFAULT_CREATED_TIME = Instant.ofEpochMilli(0L); private static final Instant UPDATED_CREATED_TIME = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Instant DEFAULT_UPDATED_TIME = Instant.ofEpochMilli(0L); private static final Instant UPDATED_UPDATED_TIME = Instant.now().truncatedTo(ChronoUnit.MILLIS); private static final Boolean DEFAULT_DELETED = false; private static final Boolean UPDATED_DELETED = true; private static final Integer DEFAULT_CATEGORY_GRADE = 1; private static final Integer UPDATED_CATEGORY_GRADE = 2; private static final String DEFAULT_IMAGE = "AAAAAAAAAA"; private static final String UPDATED_IMAGE = "BBBBBBBBBB"; private static final Integer DEFAULT_RANK = 1; private static final Integer UPDATED_RANK = 2; @Autowired private CategoryRepository categoryRepository; @Autowired private CategoryMapper categoryMapper; @Autowired private CategoryService categoryService; @Autowired private CategoryQueryService categoryQueryService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restCategoryMockMvc; private Category category; @Before public void setup() { MockitoAnnotations.initMocks(this); final CategoryResource categoryResource = new CategoryResource(categoryService, categoryQueryService); this.restCategoryMockMvc = MockMvcBuilders.standaloneSetup(categoryResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setConversionService(createFormattingConversionService()) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Category createEntity(EntityManager em) { Category category = new Category() .name(DEFAULT_NAME) .parentId(DEFAULT_PARENT_ID) .isParent(DEFAULT_IS_PARENT) .target(DEFAULT_TARGET) .targetType(DEFAULT_TARGET_TYPE) .createdTime(DEFAULT_CREATED_TIME) .updatedTime(DEFAULT_UPDATED_TIME) .deleted(DEFAULT_DELETED) .categoryGrade(DEFAULT_CATEGORY_GRADE) .image(DEFAULT_IMAGE) .rank(DEFAULT_RANK); return category; } @Before public void initTest() { category = createEntity(em); } @Test @Transactional public void createCategory() throws Exception { int databaseSizeBeforeCreate = categoryRepository.findAll().size(); // Create the Category CategoryDTO categoryDTO = categoryMapper.toDto(category); restCategoryMockMvc.perform(post("/api/categories") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(categoryDTO))) .andExpect(status().isCreated()); // Validate the Category in the database List<Category> categoryList = categoryRepository.findAll(); assertThat(categoryList).hasSize(databaseSizeBeforeCreate + 1); Category testCategory = categoryList.get(categoryList.size() - 1); assertThat(testCategory.getName()).isEqualTo(DEFAULT_NAME); assertThat(testCategory.getParentId()).isEqualTo(DEFAULT_PARENT_ID); assertThat(testCategory.isIsParent()).isEqualTo(DEFAULT_IS_PARENT); assertThat(testCategory.getTarget()).isEqualTo(DEFAULT_TARGET); assertThat(testCategory.getTargetType()).isEqualTo(DEFAULT_TARGET_TYPE); assertThat(testCategory.getCreatedTime()).isEqualTo(DEFAULT_CREATED_TIME); assertThat(testCategory.getUpdatedTime()).isEqualTo(DEFAULT_UPDATED_TIME); assertThat(testCategory.isDeleted()).isEqualTo(DEFAULT_DELETED); assertThat(testCategory.getCategoryGrade()).isEqualTo(DEFAULT_CATEGORY_GRADE); assertThat(testCategory.getImage()).isEqualTo(DEFAULT_IMAGE); assertThat(testCategory.getRank()).isEqualTo(DEFAULT_RANK); } @Test @Transactional public void createCategoryWithExistingId() throws Exception { int databaseSizeBeforeCreate = categoryRepository.findAll().size(); // Create the Category with an existing ID category.setId(1L); CategoryDTO categoryDTO = categoryMapper.toDto(category); // An entity with an existing ID cannot be created, so this API call must fail restCategoryMockMvc.perform(post("/api/categories") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(categoryDTO))) .andExpect(status().isBadRequest()); // Validate the Category in the database List<Category> categoryList = categoryRepository.findAll(); assertThat(categoryList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void checkParentIdIsRequired() throws Exception { int databaseSizeBeforeTest = categoryRepository.findAll().size(); // set the field null category.setParentId(null); // Create the Category, which fails. CategoryDTO categoryDTO = categoryMapper.toDto(category); restCategoryMockMvc.perform(post("/api/categories") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(categoryDTO))) .andExpect(status().isBadRequest()); List<Category> categoryList = categoryRepository.findAll(); assertThat(categoryList).hasSize(databaseSizeBeforeTest); } @Test @Transactional public void getAllCategories() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList restCategoryMockMvc.perform(get("/api/categories?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(category.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].parentId").value(hasItem(DEFAULT_PARENT_ID.intValue()))) .andExpect(jsonPath("$.[*].isParent").value(hasItem(DEFAULT_IS_PARENT.booleanValue()))) .andExpect(jsonPath("$.[*].target").value(hasItem(DEFAULT_TARGET.toString()))) .andExpect(jsonPath("$.[*].targetType").value(hasItem(DEFAULT_TARGET_TYPE))) .andExpect(jsonPath("$.[*].createdTime").value(hasItem(DEFAULT_CREATED_TIME.toString()))) .andExpect(jsonPath("$.[*].updatedTime").value(hasItem(DEFAULT_UPDATED_TIME.toString()))) .andExpect(jsonPath("$.[*].deleted").value(hasItem(DEFAULT_DELETED.booleanValue()))) .andExpect(jsonPath("$.[*].categoryGrade").value(hasItem(DEFAULT_CATEGORY_GRADE))) .andExpect(jsonPath("$.[*].image").value(hasItem(DEFAULT_IMAGE.toString()))) .andExpect(jsonPath("$.[*].rank").value(hasItem(DEFAULT_RANK))); } @Test @Transactional public void getCategory() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get the category restCategoryMockMvc.perform(get("/api/categories/{id}", category.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(category.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.parentId").value(DEFAULT_PARENT_ID.intValue())) .andExpect(jsonPath("$.isParent").value(DEFAULT_IS_PARENT.booleanValue())) .andExpect(jsonPath("$.target").value(DEFAULT_TARGET.toString())) .andExpect(jsonPath("$.targetType").value(DEFAULT_TARGET_TYPE)) .andExpect(jsonPath("$.createdTime").value(DEFAULT_CREATED_TIME.toString())) .andExpect(jsonPath("$.updatedTime").value(DEFAULT_UPDATED_TIME.toString())) .andExpect(jsonPath("$.deleted").value(DEFAULT_DELETED.booleanValue())) .andExpect(jsonPath("$.categoryGrade").value(DEFAULT_CATEGORY_GRADE)) .andExpect(jsonPath("$.image").value(DEFAULT_IMAGE.toString())) .andExpect(jsonPath("$.rank").value(DEFAULT_RANK)); } @Test @Transactional public void getAllCategoriesByNameIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where name equals to DEFAULT_NAME defaultCategoryShouldBeFound("name.equals=" + DEFAULT_NAME); // Get all the categoryList where name equals to UPDATED_NAME defaultCategoryShouldNotBeFound("name.equals=" + UPDATED_NAME); } @Test @Transactional public void getAllCategoriesByNameIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where name in DEFAULT_NAME or UPDATED_NAME defaultCategoryShouldBeFound("name.in=" + DEFAULT_NAME + "," + UPDATED_NAME); // Get all the categoryList where name equals to UPDATED_NAME defaultCategoryShouldNotBeFound("name.in=" + UPDATED_NAME); } @Test @Transactional public void getAllCategoriesByNameIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where name is not null defaultCategoryShouldBeFound("name.specified=true"); // Get all the categoryList where name is null defaultCategoryShouldNotBeFound("name.specified=false"); } @Test @Transactional public void getAllCategoriesByParentIdIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where parentId equals to DEFAULT_PARENT_ID defaultCategoryShouldBeFound("parentId.equals=" + DEFAULT_PARENT_ID); // Get all the categoryList where parentId equals to UPDATED_PARENT_ID defaultCategoryShouldNotBeFound("parentId.equals=" + UPDATED_PARENT_ID); } @Test @Transactional public void getAllCategoriesByParentIdIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where parentId in DEFAULT_PARENT_ID or UPDATED_PARENT_ID defaultCategoryShouldBeFound("parentId.in=" + DEFAULT_PARENT_ID + "," + UPDATED_PARENT_ID); // Get all the categoryList where parentId equals to UPDATED_PARENT_ID defaultCategoryShouldNotBeFound("parentId.in=" + UPDATED_PARENT_ID); } @Test @Transactional public void getAllCategoriesByParentIdIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where parentId is not null defaultCategoryShouldBeFound("parentId.specified=true"); // Get all the categoryList where parentId is null defaultCategoryShouldNotBeFound("parentId.specified=false"); } @Test @Transactional public void getAllCategoriesByParentIdIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where parentId greater than or equals to DEFAULT_PARENT_ID defaultCategoryShouldBeFound("parentId.greaterOrEqualThan=" + DEFAULT_PARENT_ID); // Get all the categoryList where parentId greater than or equals to UPDATED_PARENT_ID defaultCategoryShouldNotBeFound("parentId.greaterOrEqualThan=" + UPDATED_PARENT_ID); } @Test @Transactional public void getAllCategoriesByParentIdIsLessThanSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where parentId less than or equals to DEFAULT_PARENT_ID defaultCategoryShouldNotBeFound("parentId.lessThan=" + DEFAULT_PARENT_ID); // Get all the categoryList where parentId less than or equals to UPDATED_PARENT_ID defaultCategoryShouldBeFound("parentId.lessThan=" + UPDATED_PARENT_ID); } @Test @Transactional public void getAllCategoriesByIsParentIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where isParent equals to DEFAULT_IS_PARENT defaultCategoryShouldBeFound("isParent.equals=" + DEFAULT_IS_PARENT); // Get all the categoryList where isParent equals to UPDATED_IS_PARENT defaultCategoryShouldNotBeFound("isParent.equals=" + UPDATED_IS_PARENT); } @Test @Transactional public void getAllCategoriesByIsParentIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where isParent in DEFAULT_IS_PARENT or UPDATED_IS_PARENT defaultCategoryShouldBeFound("isParent.in=" + DEFAULT_IS_PARENT + "," + UPDATED_IS_PARENT); // Get all the categoryList where isParent equals to UPDATED_IS_PARENT defaultCategoryShouldNotBeFound("isParent.in=" + UPDATED_IS_PARENT); } @Test @Transactional public void getAllCategoriesByIsParentIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where isParent is not null defaultCategoryShouldBeFound("isParent.specified=true"); // Get all the categoryList where isParent is null defaultCategoryShouldNotBeFound("isParent.specified=false"); } @Test @Transactional public void getAllCategoriesByTargetIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where target equals to DEFAULT_TARGET defaultCategoryShouldBeFound("target.equals=" + DEFAULT_TARGET); // Get all the categoryList where target equals to UPDATED_TARGET defaultCategoryShouldNotBeFound("target.equals=" + UPDATED_TARGET); } @Test @Transactional public void getAllCategoriesByTargetIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where target in DEFAULT_TARGET or UPDATED_TARGET defaultCategoryShouldBeFound("target.in=" + DEFAULT_TARGET + "," + UPDATED_TARGET); // Get all the categoryList where target equals to UPDATED_TARGET defaultCategoryShouldNotBeFound("target.in=" + UPDATED_TARGET); } @Test @Transactional public void getAllCategoriesByTargetIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where target is not null defaultCategoryShouldBeFound("target.specified=true"); // Get all the categoryList where target is null defaultCategoryShouldNotBeFound("target.specified=false"); } @Test @Transactional public void getAllCategoriesByTargetTypeIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where targetType equals to DEFAULT_TARGET_TYPE defaultCategoryShouldBeFound("targetType.equals=" + DEFAULT_TARGET_TYPE); // Get all the categoryList where targetType equals to UPDATED_TARGET_TYPE defaultCategoryShouldNotBeFound("targetType.equals=" + UPDATED_TARGET_TYPE); } @Test @Transactional public void getAllCategoriesByTargetTypeIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where targetType in DEFAULT_TARGET_TYPE or UPDATED_TARGET_TYPE defaultCategoryShouldBeFound("targetType.in=" + DEFAULT_TARGET_TYPE + "," + UPDATED_TARGET_TYPE); // Get all the categoryList where targetType equals to UPDATED_TARGET_TYPE defaultCategoryShouldNotBeFound("targetType.in=" + UPDATED_TARGET_TYPE); } @Test @Transactional public void getAllCategoriesByTargetTypeIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where targetType is not null defaultCategoryShouldBeFound("targetType.specified=true"); // Get all the categoryList where targetType is null defaultCategoryShouldNotBeFound("targetType.specified=false"); } @Test @Transactional public void getAllCategoriesByTargetTypeIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where targetType greater than or equals to DEFAULT_TARGET_TYPE defaultCategoryShouldBeFound("targetType.greaterOrEqualThan=" + DEFAULT_TARGET_TYPE); // Get all the categoryList where targetType greater than or equals to UPDATED_TARGET_TYPE defaultCategoryShouldNotBeFound("targetType.greaterOrEqualThan=" + UPDATED_TARGET_TYPE); } @Test @Transactional public void getAllCategoriesByTargetTypeIsLessThanSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where targetType less than or equals to DEFAULT_TARGET_TYPE defaultCategoryShouldNotBeFound("targetType.lessThan=" + DEFAULT_TARGET_TYPE); // Get all the categoryList where targetType less than or equals to UPDATED_TARGET_TYPE defaultCategoryShouldBeFound("targetType.lessThan=" + UPDATED_TARGET_TYPE); } @Test @Transactional public void getAllCategoriesByCreatedTimeIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where createdTime equals to DEFAULT_CREATED_TIME defaultCategoryShouldBeFound("createdTime.equals=" + DEFAULT_CREATED_TIME); // Get all the categoryList where createdTime equals to UPDATED_CREATED_TIME defaultCategoryShouldNotBeFound("createdTime.equals=" + UPDATED_CREATED_TIME); } @Test @Transactional public void getAllCategoriesByCreatedTimeIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where createdTime in DEFAULT_CREATED_TIME or UPDATED_CREATED_TIME defaultCategoryShouldBeFound("createdTime.in=" + DEFAULT_CREATED_TIME + "," + UPDATED_CREATED_TIME); // Get all the categoryList where createdTime equals to UPDATED_CREATED_TIME defaultCategoryShouldNotBeFound("createdTime.in=" + UPDATED_CREATED_TIME); } @Test @Transactional public void getAllCategoriesByCreatedTimeIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where createdTime is not null defaultCategoryShouldBeFound("createdTime.specified=true"); // Get all the categoryList where createdTime is null defaultCategoryShouldNotBeFound("createdTime.specified=false"); } @Test @Transactional public void getAllCategoriesByUpdatedTimeIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where updatedTime equals to DEFAULT_UPDATED_TIME defaultCategoryShouldBeFound("updatedTime.equals=" + DEFAULT_UPDATED_TIME); // Get all the categoryList where updatedTime equals to UPDATED_UPDATED_TIME defaultCategoryShouldNotBeFound("updatedTime.equals=" + UPDATED_UPDATED_TIME); } @Test @Transactional public void getAllCategoriesByUpdatedTimeIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where updatedTime in DEFAULT_UPDATED_TIME or UPDATED_UPDATED_TIME defaultCategoryShouldBeFound("updatedTime.in=" + DEFAULT_UPDATED_TIME + "," + UPDATED_UPDATED_TIME); // Get all the categoryList where updatedTime equals to UPDATED_UPDATED_TIME defaultCategoryShouldNotBeFound("updatedTime.in=" + UPDATED_UPDATED_TIME); } @Test @Transactional public void getAllCategoriesByUpdatedTimeIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where updatedTime is not null defaultCategoryShouldBeFound("updatedTime.specified=true"); // Get all the categoryList where updatedTime is null defaultCategoryShouldNotBeFound("updatedTime.specified=false"); } @Test @Transactional public void getAllCategoriesByDeletedIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where deleted equals to DEFAULT_DELETED defaultCategoryShouldBeFound("deleted.equals=" + DEFAULT_DELETED); // Get all the categoryList where deleted equals to UPDATED_DELETED defaultCategoryShouldNotBeFound("deleted.equals=" + UPDATED_DELETED); } @Test @Transactional public void getAllCategoriesByDeletedIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where deleted in DEFAULT_DELETED or UPDATED_DELETED defaultCategoryShouldBeFound("deleted.in=" + DEFAULT_DELETED + "," + UPDATED_DELETED); // Get all the categoryList where deleted equals to UPDATED_DELETED defaultCategoryShouldNotBeFound("deleted.in=" + UPDATED_DELETED); } @Test @Transactional public void getAllCategoriesByDeletedIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where deleted is not null defaultCategoryShouldBeFound("deleted.specified=true"); // Get all the categoryList where deleted is null defaultCategoryShouldNotBeFound("deleted.specified=false"); } @Test @Transactional public void getAllCategoriesByCategoryGradeIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where categoryGrade equals to DEFAULT_CATEGORY_GRADE defaultCategoryShouldBeFound("categoryGrade.equals=" + DEFAULT_CATEGORY_GRADE); // Get all the categoryList where categoryGrade equals to UPDATED_CATEGORY_GRADE defaultCategoryShouldNotBeFound("categoryGrade.equals=" + UPDATED_CATEGORY_GRADE); } @Test @Transactional public void getAllCategoriesByCategoryGradeIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where categoryGrade in DEFAULT_CATEGORY_GRADE or UPDATED_CATEGORY_GRADE defaultCategoryShouldBeFound("categoryGrade.in=" + DEFAULT_CATEGORY_GRADE + "," + UPDATED_CATEGORY_GRADE); // Get all the categoryList where categoryGrade equals to UPDATED_CATEGORY_GRADE defaultCategoryShouldNotBeFound("categoryGrade.in=" + UPDATED_CATEGORY_GRADE); } @Test @Transactional public void getAllCategoriesByCategoryGradeIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where categoryGrade is not null defaultCategoryShouldBeFound("categoryGrade.specified=true"); // Get all the categoryList where categoryGrade is null defaultCategoryShouldNotBeFound("categoryGrade.specified=false"); } @Test @Transactional public void getAllCategoriesByCategoryGradeIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where categoryGrade greater than or equals to DEFAULT_CATEGORY_GRADE defaultCategoryShouldBeFound("categoryGrade.greaterOrEqualThan=" + DEFAULT_CATEGORY_GRADE); // Get all the categoryList where categoryGrade greater than or equals to UPDATED_CATEGORY_GRADE defaultCategoryShouldNotBeFound("categoryGrade.greaterOrEqualThan=" + UPDATED_CATEGORY_GRADE); } @Test @Transactional public void getAllCategoriesByCategoryGradeIsLessThanSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where categoryGrade less than or equals to DEFAULT_CATEGORY_GRADE defaultCategoryShouldNotBeFound("categoryGrade.lessThan=" + DEFAULT_CATEGORY_GRADE); // Get all the categoryList where categoryGrade less than or equals to UPDATED_CATEGORY_GRADE defaultCategoryShouldBeFound("categoryGrade.lessThan=" + UPDATED_CATEGORY_GRADE); } @Test @Transactional public void getAllCategoriesByImageIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where image equals to DEFAULT_IMAGE defaultCategoryShouldBeFound("image.equals=" + DEFAULT_IMAGE); // Get all the categoryList where image equals to UPDATED_IMAGE defaultCategoryShouldNotBeFound("image.equals=" + UPDATED_IMAGE); } @Test @Transactional public void getAllCategoriesByImageIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where image in DEFAULT_IMAGE or UPDATED_IMAGE defaultCategoryShouldBeFound("image.in=" + DEFAULT_IMAGE + "," + UPDATED_IMAGE); // Get all the categoryList where image equals to UPDATED_IMAGE defaultCategoryShouldNotBeFound("image.in=" + UPDATED_IMAGE); } @Test @Transactional public void getAllCategoriesByImageIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where image is not null defaultCategoryShouldBeFound("image.specified=true"); // Get all the categoryList where image is null defaultCategoryShouldNotBeFound("image.specified=false"); } @Test @Transactional public void getAllCategoriesByRankIsEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where rank equals to DEFAULT_RANK defaultCategoryShouldBeFound("rank.equals=" + DEFAULT_RANK); // Get all the categoryList where rank equals to UPDATED_RANK defaultCategoryShouldNotBeFound("rank.equals=" + UPDATED_RANK); } @Test @Transactional public void getAllCategoriesByRankIsInShouldWork() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where rank in DEFAULT_RANK or UPDATED_RANK defaultCategoryShouldBeFound("rank.in=" + DEFAULT_RANK + "," + UPDATED_RANK); // Get all the categoryList where rank equals to UPDATED_RANK defaultCategoryShouldNotBeFound("rank.in=" + UPDATED_RANK); } @Test @Transactional public void getAllCategoriesByRankIsNullOrNotNull() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where rank is not null defaultCategoryShouldBeFound("rank.specified=true"); // Get all the categoryList where rank is null defaultCategoryShouldNotBeFound("rank.specified=false"); } @Test @Transactional public void getAllCategoriesByRankIsGreaterThanOrEqualToSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where rank greater than or equals to DEFAULT_RANK defaultCategoryShouldBeFound("rank.greaterOrEqualThan=" + DEFAULT_RANK); // Get all the categoryList where rank greater than or equals to UPDATED_RANK defaultCategoryShouldNotBeFound("rank.greaterOrEqualThan=" + UPDATED_RANK); } @Test @Transactional public void getAllCategoriesByRankIsLessThanSomething() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); // Get all the categoryList where rank less than or equals to DEFAULT_RANK defaultCategoryShouldNotBeFound("rank.lessThan=" + DEFAULT_RANK); // Get all the categoryList where rank less than or equals to UPDATED_RANK defaultCategoryShouldBeFound("rank.lessThan=" + UPDATED_RANK); } /** * Executes the search, and checks that the default entity is returned */ private void defaultCategoryShouldBeFound(String filter) throws Exception { restCategoryMockMvc.perform(get("/api/categories?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(category.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].parentId").value(hasItem(DEFAULT_PARENT_ID.intValue()))) .andExpect(jsonPath("$.[*].isParent").value(hasItem(DEFAULT_IS_PARENT.booleanValue()))) .andExpect(jsonPath("$.[*].target").value(hasItem(DEFAULT_TARGET.toString()))) .andExpect(jsonPath("$.[*].targetType").value(hasItem(DEFAULT_TARGET_TYPE))) .andExpect(jsonPath("$.[*].createdTime").value(hasItem(DEFAULT_CREATED_TIME.toString()))) .andExpect(jsonPath("$.[*].updatedTime").value(hasItem(DEFAULT_UPDATED_TIME.toString()))) .andExpect(jsonPath("$.[*].deleted").value(hasItem(DEFAULT_DELETED.booleanValue()))) .andExpect(jsonPath("$.[*].categoryGrade").value(hasItem(DEFAULT_CATEGORY_GRADE))) .andExpect(jsonPath("$.[*].image").value(hasItem(DEFAULT_IMAGE.toString()))) .andExpect(jsonPath("$.[*].rank").value(hasItem(DEFAULT_RANK))); } /** * Executes the search, and checks that the default entity is not returned */ private void defaultCategoryShouldNotBeFound(String filter) throws Exception { restCategoryMockMvc.perform(get("/api/categories?sort=id,desc&" + filter)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$").isArray()) .andExpect(jsonPath("$").isEmpty()); } @Test @Transactional public void getNonExistingCategory() throws Exception { // Get the category restCategoryMockMvc.perform(get("/api/categories/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateCategory() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); int databaseSizeBeforeUpdate = categoryRepository.findAll().size(); // Update the category Category updatedCategory = categoryRepository.findOne(category.getId()); // Disconnect from session so that the updates on updatedCategory are not directly saved in db em.detach(updatedCategory); updatedCategory .name(UPDATED_NAME) .parentId(UPDATED_PARENT_ID) .isParent(UPDATED_IS_PARENT) .target(UPDATED_TARGET) .targetType(UPDATED_TARGET_TYPE) .createdTime(UPDATED_CREATED_TIME) .updatedTime(UPDATED_UPDATED_TIME) .deleted(UPDATED_DELETED) .categoryGrade(UPDATED_CATEGORY_GRADE) .image(UPDATED_IMAGE) .rank(UPDATED_RANK); CategoryDTO categoryDTO = categoryMapper.toDto(updatedCategory); restCategoryMockMvc.perform(put("/api/categories") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(categoryDTO))) .andExpect(status().isOk()); // Validate the Category in the database List<Category> categoryList = categoryRepository.findAll(); assertThat(categoryList).hasSize(databaseSizeBeforeUpdate); Category testCategory = categoryList.get(categoryList.size() - 1); assertThat(testCategory.getName()).isEqualTo(UPDATED_NAME); assertThat(testCategory.getParentId()).isEqualTo(UPDATED_PARENT_ID); assertThat(testCategory.isIsParent()).isEqualTo(UPDATED_IS_PARENT); assertThat(testCategory.getTarget()).isEqualTo(UPDATED_TARGET); assertThat(testCategory.getTargetType()).isEqualTo(UPDATED_TARGET_TYPE); assertThat(testCategory.getCreatedTime()).isEqualTo(UPDATED_CREATED_TIME); assertThat(testCategory.getUpdatedTime()).isEqualTo(UPDATED_UPDATED_TIME); assertThat(testCategory.isDeleted()).isEqualTo(UPDATED_DELETED); assertThat(testCategory.getCategoryGrade()).isEqualTo(UPDATED_CATEGORY_GRADE); assertThat(testCategory.getImage()).isEqualTo(UPDATED_IMAGE); assertThat(testCategory.getRank()).isEqualTo(UPDATED_RANK); } @Test @Transactional public void updateNonExistingCategory() throws Exception { int databaseSizeBeforeUpdate = categoryRepository.findAll().size(); // Create the Category CategoryDTO categoryDTO = categoryMapper.toDto(category); // If the entity doesn't have an ID, it will be created instead of just being updated restCategoryMockMvc.perform(put("/api/categories") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(categoryDTO))) .andExpect(status().isCreated()); // Validate the Category in the database List<Category> categoryList = categoryRepository.findAll(); assertThat(categoryList).hasSize(databaseSizeBeforeUpdate + 1); } @Test @Transactional public void deleteCategory() throws Exception { // Initialize the database categoryRepository.saveAndFlush(category); int databaseSizeBeforeDelete = categoryRepository.findAll().size(); // Get the category restCategoryMockMvc.perform(delete("/api/categories/{id}", category.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Category> categoryList = categoryRepository.findAll(); assertThat(categoryList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Category.class); Category category1 = new Category(); category1.setId(1L); Category category2 = new Category(); category2.setId(category1.getId()); assertThat(category1).isEqualTo(category2); category2.setId(2L); assertThat(category1).isNotEqualTo(category2); category1.setId(null); assertThat(category1).isNotEqualTo(category2); } @Test @Transactional public void dtoEqualsVerifier() throws Exception { TestUtil.equalsVerifier(CategoryDTO.class); CategoryDTO categoryDTO1 = new CategoryDTO(); categoryDTO1.setId(1L); CategoryDTO categoryDTO2 = new CategoryDTO(); assertThat(categoryDTO1).isNotEqualTo(categoryDTO2); categoryDTO2.setId(categoryDTO1.getId()); assertThat(categoryDTO1).isEqualTo(categoryDTO2); categoryDTO2.setId(2L); assertThat(categoryDTO1).isNotEqualTo(categoryDTO2); categoryDTO1.setId(null); assertThat(categoryDTO1).isNotEqualTo(categoryDTO2); } @Test @Transactional public void testEntityFromId() { assertThat(categoryMapper.fromId(42L).getId()).isEqualTo(42); assertThat(categoryMapper.fromId(null)).isNull(); } }
true
cea2e9bfd83ad3f20f7c4370d31d3379cdcaa69c
Java
xiaopang750/chorhair
/lucene/src/com/rockstar/o2o/lucene/IndexSearch.java
UTF-8
11,458
2.015625
2
[]
no_license
package com.rockstar.o2o.lucene; import java.io.File; import java.io.IOException; import java.util.ArrayList; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.lucene.document.Document; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanClause.Occur; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.Sort; import org.apache.lucene.search.SortField; import org.apache.lucene.search.TopDocs; import org.apache.lucene.search.TopFieldCollector; import org.apache.lucene.search.TopScoreDocCollector; import org.apache.lucene.search.WildcardQuery; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import com.rockstar.o2o.util.RedisUtils; public class IndexSearch { private static String pathFile=System.getenv("CHORHAIR")==null?"d:/lucene/index": (System.getenv("NEWLUCENEPATH")==null?"/application/tomcat-6.0.41/server_50002/lucene/index":(System.getenv("NEWLUCENEPATH"))); private static ReturnPojo pojo=new ReturnPojo(); /** * 根据关键字,当前页数,每页显示条数 * @param keyword * @param curpage * @param pageSize * @return * @throws Exception */ @SuppressWarnings("unchecked") public static ReturnPojo search(String openid,String keyword,String combotype,String contenttype,String fairtype,String pkShop,int curpage ,int pageSize) { IndexReader reader=null; try{ String errlog=System.getenv("NEWLUCENEPATH"); if(errlog==null){ System.out.println("未设置lucene的系统变量"); } int start = (curpage - 1) * pageSize; Directory dir=FSDirectory.open(new File(pathFile)); reader=DirectoryReader.open(dir); BooleanQuery bQuery = new BooleanQuery(); IndexSearcher searcher=new IndexSearcher(reader); if(keyword!=null&&!keyword.equals("")){ if(contenttype!=null&&!contenttype.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("contenttype", contenttype)); bQuery.add(topic,Occur.MUST); } if(pkShop!=null&&!pkShop.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("pkShop", pkShop)); bQuery.add(topic,Occur.MUST); } if(combotype!=null&&!combotype.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("combotype", combotype)); bQuery.add(topic,Occur.MUST); } if(fairtype!=null&&!fairtype.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("fairtype", fairtype)); bQuery.add(topic,Occur.MUST); } WildcardQuery topic = new WildcardQuery(new Term("topic", "*"+keyword+"*")); bQuery.add(topic,Occur.SHOULD); for(int i=0;i<10;i++){ WildcardQuery tag = new WildcardQuery(new Term("tag"+i, keyword)); bQuery.add(tag,Occur.SHOULD); } }else{ if(contenttype!=null&&!contenttype.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("contenttype", contenttype)); bQuery.add(topic,Occur.MUST); } if(combotype!=null&&!combotype.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("combotype", combotype)); bQuery.add(topic,Occur.MUST); } if(fairtype!=null&&!fairtype.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("fairtype", fairtype)); bQuery.add(topic,Occur.MUST); } if(pkShop!=null&&!pkShop.equals("")){ WildcardQuery topic = new WildcardQuery(new Term("pkShop", pkShop)); bQuery.add(topic,Occur.MUST); } WildcardQuery tag = new WildcardQuery(new Term("all", "")); bQuery.add(tag,Occur.SHOULD); } int hm = start + pageSize; Sort sort=null; TopFieldCollector res=null; if(contenttype!=null&&contenttype.equals("combo")){ sort = new Sort(); SortField f1 = new SortField("fairtype", SortField.Type.STRING, false); SortField f2 = new SortField("comboprice", SortField.Type.DOUBLE, false); sort.setSort(new SortField[] { f1, f2 }); res = TopFieldCollector.create(sort, hm, false, false, false, false); }else{ sort = new Sort(); SortField f = new SortField("ts", SortField.Type.STRING, false); sort.setSort(f); res = TopFieldCollector.create(sort, hm, false, false, false, false); } //TopScoreDocCollector res = TopScoreDocCollector.create(hm, false); searcher.search(bQuery, res); // int rowCount = res.getTotalHits(); //所有的条数 // // System.out.println(rowCount); // // int pages = (rowCount - 1) / pageSize + 1; //计算总页数 // // System.out.println(pages); TopDocs tds = res.topDocs(start, pageSize); ScoreDoc[] scoreDocs = tds.scoreDocs; ArrayList<JSONObject> objlist=new ArrayList<JSONObject>(); for(int i=0; i < scoreDocs.length; i++) { int doc = scoreDocs[i].doc; Document document = searcher.doc(doc); JSONObject obj=new JSONObject(); obj.accumulate("id", document.get("id")); obj.accumulate("praisecount",document.get("praisecount")==null?"0":document.get("praisecount")); obj.accumulate("url", document.get("url")); obj.accumulate("topic", document.get("topic")); obj.accumulate("firstpage", document.get("firstpage")); obj.accumulate("ts", document.get("ts")); obj.accumulate("width", document.get("width")); obj.accumulate("height", document.get("height")); if(document.get("taglist")!=null&&!document.get("taglist").equals("")){ obj.accumulate("taglist", document.get("taglist")); } //查询该内容页的收藏次数,以及查询的人是否收藏过此内容 try { Integer count=RedisUtils.getObject("collect:id:"+document.get("id"))==null?0:(Integer)RedisUtils.getObject("collect:id:"+document.get("id")); obj.accumulate("collectcount", count); if(openid!=null&&!openid.equals("")){ Object oldobj=RedisUtils.getObject("collect:id:"+document.get("id")+":"+"totalcount")==null?null:RedisUtils.getObject("collect:id:"+document.get("id")+":"+"totalcount"); if(oldobj!=null&&!oldobj.equals("")){ ArrayList<Object> oldlist=(ArrayList<Object>) oldobj; if(oldlist.size()>0){ if(oldlist.contains(openid)){ obj.accumulate("iscollect", "Y"); }else{ obj.accumulate("iscollect", "N"); } } } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); System.out.println("redis报错"); } if(contenttype!=null&&contenttype.equals("combo")){ obj.accumulate("comboname", document.get("comboname"));//套餐名称 obj.accumulate("comboprice", document.get("comboprice"));//套餐价格 Integer combocount=Integer.parseInt(RedisUtils.getObject("comment:"+"combo:"+document.get("pk"))==null?"0":RedisUtils.getObject("comment:"+"combo:"+document.get("pk")).toString()); obj.accumulate("commentcount", combocount);//次数 } if(contenttype!=null&&contenttype.equals("fairer")){ obj.accumulate("fairername", document.get("fairername") ); //理发师名称 obj.accumulate("pkShop", document.get("pkShop") ); //店铺 obj.accumulate("rankname", document.get("rankname") ); //职称 obj.accumulate("skills", document.get("skills") ); //技能 Integer fairercount=Integer.parseInt(RedisUtils.getObject("comment:"+"fairer:"+document.get("pk"))==null?"0":RedisUtils.getObject("comment:"+"fairer:"+document.get("pk")).toString()); obj.accumulate("commentcount", fairercount);//次数 } if(contenttype!=null&&contenttype.equals("shop")){ obj.accumulate("pkShop", document.get("pkShop") ); //店铺 obj.accumulate("shopname", document.get("shopname") ); //店铺名称 obj.accumulate("fixphone", document.get("fixphone") ); //固定电话 obj.accumulate("cellphone", document.get("cellphone") ); //手机号 obj.accumulate("businessour", document.get("businessour") ); //营业时间 obj.accumulate("addr", document.get("addr") ); //地址 obj.accumulate("location", document.get("location") ); //坐标 Integer fairercount=Integer.parseInt(RedisUtils.getObject("comment:"+"shop:"+document.get("pk"))==null?"0":RedisUtils.getObject("comment:"+"shop:"+document.get("pk")).toString()); obj.accumulate("commentcount", fairercount);//次数 } objlist.add(obj); } if(objlist.size()>0){ pojo.setData(JSONArray.fromObject(objlist).toString()); pojo.setIssuccess(true); pojo.setMsg("查询成功"); }else{ pojo.setData(""); pojo.setIssuccess(true); pojo.setMsg("没有结果"); } }catch (Exception e) { // TODO: handle exception e.printStackTrace(); pojo.setIssuccess(false); pojo.setMsg("没有结果"); }finally{ if(reader!=null){ try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return pojo; } }
true
9d380cea5dfa613872fa12ad01ddac6a1b202cd2
Java
Mars-GZ/MDO
/src/djj/node/cae/CAENode.java
UTF-8
630
1.875
2
[]
no_license
package djj.node.cae; import djj.main.tab.workflow.model.NodeModel; import djj.node.NodeConstant; import djj.node.NodeJPanel; import javax.swing.*; /** * Created by mesmers on 2017/5/21. */ public class CAENode extends NodeJPanel { public CAENode(ImageIcon icon){ super(icon); } public CAENode(){ super(); } @Override public void initView() { model.setType(NodeConstant.CAE_TYPE); super.initView(); } @Override public void option() { } @Override public void ok(NodeModel model) { } @Override public void cancel() { } }
true
901d9f20da77d89e936e93a2148cc41a4f16885c
Java
steppat/argentum-web
/src/test/java/br/com/caelum/argentum/reader/LeitorXMLTest.java
UTF-8
789
2.5
2
[]
no_license
package br.com.caelum.argentum.reader; import java.io.StringReader; import java.util.List; import org.junit.Assert; import org.junit.Test; import br.com.caelum.argentum.modelo.Negocio; import br.com.caelum.argentum.reader.LeitorXML; public class LeitorXMLTest { @Test public void testCarregarListaDeNegocios() { // StringReader xml = new StringReader( // "<list>" + // "<negocio>" + // "<preco>45.5</preco>" + // "<quantidade>10</quantidade>" + // "</negocio>" + // "</list>"); // System.out.println(xml); // List<Negocio> negocios = new LeitorXML().carrega(xml); // // Assert.assertEquals(negocios.get(0).getPreco(), 45.5, 0.0001); // Assert.assertEquals(negocios.get(0).getQuantidade(), 10); // Assert.assertEquals(negocios.size(), 1); } }
true
a2583268ea5b27c89038df2b3cce80898f6d7554
Java
bellmit/zycami-ded
/src/main/java/d/v/c/v0/f.java
UTF-8
882
1.515625
2
[]
no_license
/* * Decompiled with CFR 0.151. */ package d.v.c.v0; import com.zhiyun.cama.data.database.AppDatabase; import com.zhiyun.cama.data.database.DatabaseHelper; import com.zhiyun.cama.data.me.remote.CommunityManager; import d.v.c.v0.u.b0.b; import d.v.c.v0.u.b0.d; import d.v.c.v0.u.v; import d.v.c.v0.w.b.h; import d.v.c.v0.w.c.a; import d.v.e.l.c1; public class f { public static v a() { c1 c12 = c1.b(); CommunityManager communityManager = CommunityManager.getInstance(); b b10 = b.g(); d d10 = d.a(); return v.M(c12, communityManager, b10, d10); } public static d.v.c.v0.w.a b() { Object object = DatabaseHelper.getInstance().getDataBase(); Object object2 = c1.b(); object = h.c((AppDatabase)object, (c1)object2); object2 = a.a(); return d.v.c.v0.w.a.b((h)object, (a)object2); } }
true
2ba17b7f8fa5af8b9a3d5f4675685463a8d0fc16
Java
ShawnLeeLXY/JavaStudy
/myStudentManager/src/stumngpack/StudentManager.java
UTF-8
4,597
3.421875
3
[]
no_license
package stumngpack; import java.util.ArrayList; import java.util.Scanner; public class StudentManager { public static void main(String[] args) { ArrayList<Student> arr = new ArrayList<Student>(); Scanner sc = new Scanner(System.in); String funcLine; while (true) { System.out.println("--------欢迎来到学生管理系统--------"); System.out.println("1 添加学生信息"); System.out.println("2 删除学生信息"); System.out.println("3 修改学生信息"); System.out.println("4 查看学生信息"); System.out.println("5 退出"); System.out.println("请选择一个功能并输入对应数字:"); funcLine = sc.nextLine(); switch (funcLine) { case "1": System.out.println("添加学生信息"); addStu(arr); break; case "2": System.out.println("删除学生信息"); delStu(arr); break; case "3": System.out.println("修改学生信息"); updateStu(arr); break; case "4": System.out.println("查看所有学生信息"); findStu(arr); break; case "5": System.out.println("谢谢使用"); System.exit(0); default: System.out.println("无效的输入!请重新输入(1~5)"); } } } public static void addStu(ArrayList<Student> arr) { Scanner sc = new Scanner(System.in); Student stu = new Student(); String sid; while (true) { System.out.print("请输入学号:"); sid = sc.nextLine(); if (isUsed(arr, sid)) { System.out.println("你输入的学号已被占用!"); } else { stu.setSid(sid); System.out.print("请输入姓名:"); stu.setName(sc.nextLine()); System.out.print("请输入年龄:"); stu.setAge(sc.nextLine()); System.out.print("请输入地址:"); stu.setAddress(sc.nextLine()); System.out.println("添加成功"); arr.add(stu); break; } } } public static void delStu(ArrayList<Student> arr) { Scanner sc = new Scanner(System.in); System.out.println("请输入要删除的学生的学号:"); String sid = sc.nextLine(); int i; for (i = 0; i < arr.size(); i++) { if (sid.equals(arr.get(i).getSid())) { arr.remove(i); System.out.println("删除成功"); break; } } if (i == arr.size()) System.out.println("无此学号!"); } public static void updateStu(ArrayList<Student> arr) { Scanner sc = new Scanner(System.in); System.out.println("请输入要修改的学生的学号:"); String sid = sc.nextLine(); int i; for (i = 0; i < arr.size(); i++) { if (sid.equals(arr.get(i).getSid())) { System.out.print("请输入姓名:"); arr.get(i).setName(sc.nextLine()); System.out.print("请输入年龄:"); arr.get(i).setAge(sc.nextLine()); System.out.print("请输入地址:"); arr.get(i).setAddress(sc.nextLine()); System.out.println("修改成功"); break; } } if (i == arr.size()) System.out.println("无此学号!"); } public static void findStu(ArrayList<Student> arr) { if (arr.size() == 0) { System.out.println("没有信息!"); return; } System.out.println("学号\t\t\t姓名\t\t\t年龄\t\t\t地址"); for (int i = 0; i < arr.size(); i++) { Student stu = arr.get(i); System.out.println(stu.getSid() + "\t\t" + stu.getName() + "\t\t\t" + stu.getAge() + "岁\t\t" + stu.getAddress()); } } public static boolean isUsed(ArrayList<Student> arr, String sid) { for (int i = 0; i < arr.size(); i++) { if (sid.equals(arr.get(i).getSid())) { return true; } } return false; } }
true
22a551e8babe95f721774735765874b7e9d7eee2
Java
JeffreyRiggle/textadventurecreator
/src/main/java/ilusr/textadventurecreator/views/layout/LayoutComponentProvider.java
UTF-8
7,953
2.375
2
[ "MIT" ]
permissive
package ilusr.textadventurecreator.views.layout; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import ilusr.logrunner.LogRunner; import ilusr.textadventurecreator.views.assets.AssetLoader; import javafx.scene.image.Image; import textadventurelib.persistence.LayoutNodePersistenceObject; import textadventurelib.persistence.StylePropertyPersistenceObject; import textadventurelib.persistence.StyleSelectorPersistenceObject; import textadventurelib.persistence.StyleType; /** * * @author Jeff Riggle * */ public class LayoutComponentProvider { private Map<String, LayoutComponent> components; /** * Creates a LayoutComponentProvider. */ public LayoutComponentProvider() { components = new HashMap<String, LayoutComponent>(); initialize(); } private void initialize() { try { LogRunner.logger().info("Initializing layout components."); LayoutStyle contentViewStyle = new LayoutStyle("ContentView", new StyleSelectorPersistenceObject()); contentViewStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); LayoutStyle textInputStyle = new LayoutStyle("TextInput", new StyleSelectorPersistenceObject()); textInputStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); textInputStyle.addProperty("Foreground Color", new StylePropertyPersistenceObject(StyleType.Color, "")); textInputStyle.addProperty("Font Family", new StylePropertyPersistenceObject(StyleType.FontFamily, "Arial")); textInputStyle.addProperty("Font Size", new StylePropertyPersistenceObject(StyleType.FontSize, "10")); textInputStyle.addProperty("Font Type", new StylePropertyPersistenceObject(StyleType.FontStyle, "normal")); LayoutStyle buttonInputStyle = new LayoutStyle("Button Input", new StyleSelectorPersistenceObject()); buttonInputStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); LayoutStyle buttonStyle = new LayoutStyle("Button", new StyleSelectorPersistenceObject()); buttonStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); buttonStyle.addProperty("Foreground Color", new StylePropertyPersistenceObject(StyleType.Color, "")); buttonStyle.addProperty("Font Family", new StylePropertyPersistenceObject(StyleType.FontFamily, "Arial")); buttonStyle.addProperty("Font Size", new StylePropertyPersistenceObject(StyleType.FontSize, "10")); buttonStyle.addProperty("Font Type", new StylePropertyPersistenceObject(StyleType.FontStyle, "normal")); buttonStyle.setSelector(".button"); LayoutStyle buttonHoverStyle = new LayoutStyle("Button Hover", new StyleSelectorPersistenceObject()); buttonHoverStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); buttonHoverStyle.addProperty("Foreground Color", new StylePropertyPersistenceObject(StyleType.Color, "")); buttonHoverStyle.addProperty("Font Family", new StylePropertyPersistenceObject(StyleType.FontFamily, "Arial")); buttonHoverStyle.addProperty("Font Size", new StylePropertyPersistenceObject(StyleType.FontSize, "10")); buttonHoverStyle.addProperty("Font Type", new StylePropertyPersistenceObject(StyleType.FontStyle, "normal")); buttonHoverStyle.setSelector(".button:hover"); buttonInputStyle.addChild(buttonStyle); buttonInputStyle.addChild(buttonHoverStyle); LayoutStyle textOnlyStyle = new LayoutStyle("TextOnly", new StyleSelectorPersistenceObject()); textOnlyStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); textOnlyStyle.addProperty("Foreground Color", new StylePropertyPersistenceObject(StyleType.Color, "")); textOnlyStyle.addProperty("Font Family", new StylePropertyPersistenceObject(StyleType.FontFamily, "Arial")); textOnlyStyle.addProperty("Font Size", new StylePropertyPersistenceObject(StyleType.FontSize, "10")); textOnlyStyle.addProperty("Font Type", new StylePropertyPersistenceObject(StyleType.FontStyle, "normal")); LayoutStyle consoleStyle = new LayoutStyle("Console", new StyleSelectorPersistenceObject()); consoleStyle.addProperty("Background Color", new StylePropertyPersistenceObject(StyleType.Background, "")); consoleStyle.addProperty("Foreground Color", new StylePropertyPersistenceObject(StyleType.Color, "")); consoleStyle.addProperty("Font Family", new StylePropertyPersistenceObject(StyleType.FontFamily, "Arial")); consoleStyle.addProperty("Font Size", new StylePropertyPersistenceObject(StyleType.FontSize, "10")); consoleStyle.addProperty("Font Type", new StylePropertyPersistenceObject(StyleType.FontStyle, "normal")); LayoutNodePersistenceObject contentView = new LayoutNodePersistenceObject(); contentView.setLayoutValue("MultiTypeContentView"); contentView.addProperty("contentResource", ""); LayoutNodePersistenceObject textInput = new LayoutNodePersistenceObject(); textInput.setLayoutValue("TextInputView"); LayoutNodePersistenceObject buttonInput = new LayoutNodePersistenceObject(); buttonInput.setLayoutValue("ButtonInput"); buttonInput.addProperty("maxColumns", "10"); LayoutNodePersistenceObject textOnly = new LayoutNodePersistenceObject(); textOnly.setLayoutValue("TextOnlyView"); LayoutNodePersistenceObject console = new LayoutNodePersistenceObject(); console.setLayoutValue("ConsoleView"); console.addProperty("prefix", ">"); components.put("MultiTypeContentView", new LayoutComponent("Content View", contentView, new Image(AssetLoader.getResourceURL("contentviewimage.png").toExternalForm(), 32, 32, true, true), contentViewStyle)); components.put("TextInputView", new LayoutComponent("Text Input", textInput, new Image(AssetLoader.getResourceURL("textinputview.png").toExternalForm(), 32, 32, true, true), textInputStyle)); components.put("ButtonInput", new LayoutComponent("Button Input", buttonInput, new Image(AssetLoader.getResourceURL("buttoninputview.png").toExternalForm(), 32, 32, true, true), buttonInputStyle)); components.put("TextOnlyView", new LayoutComponent("Text Only", textOnly, new Image(AssetLoader.getResourceURL("textonlyview.png").toExternalForm(), 32, 32, true, true), textOnlyStyle)); components.put("ConsoleView", new LayoutComponent("Console", console, new Image(AssetLoader.getResourceURL("consoleview.png").toExternalForm(), 32, 32, true, true), consoleStyle)); } catch (Exception e) { LogRunner.logger().severe(e); } } /** * * @param persistence The @see LayoutNodePersistenceObject to use. * @return The associated @see LayoutComponent. */ public LayoutComponent getLayoutFromPersistence(LayoutNodePersistenceObject persistence) { return components.get(persistence.getLayoutValue()); } /** * * @return The @see LayoutComponent for content views. */ public LayoutComponent getContentView() { return components.get("MultiTypeContentView"); } /** * * @return The @see LayoutComponent for text input views. */ public LayoutComponent getTextInput() { return components.get("TextInputView"); } /** * * @return The @see LayoutComponent for button input views. */ public LayoutComponent getButtonInput() { return components.get("ButtonInput"); } /** * * @return The @see LayoutComponent for text only views. */ public LayoutComponent getTextOnly() { return components.get("TextOnlyView"); } /** * * @return The @see LayoutComponent for console views. */ public LayoutComponent getConsole() { return components.get("ConsoleView"); } /** * * @return All registered @see LayoutComponet 's. */ public List<LayoutComponent> getComponents() { return new ArrayList<LayoutComponent>(components.values()); } }
true
7b1c9c992a2523d0f575e2b91b50bce5b766bc25
Java
wull2think/DineWithUs
/DineWithUs/app/src/main/java/cmu/andrew/htay/dinewithus/DBLayout/DBUpdate.java
UTF-8
809
2.046875
2
[]
no_license
package cmu.andrew.htay.dinewithus.DBLayout; import android.content.ContentValues; import android.content.Context; import java.util.ArrayList; import cmu.andrew.htay.dinewithus.entities.Appointment; import cmu.andrew.htay.dinewithus.entities.Profile; import cmu.andrew.htay.dinewithus.entities.ScheduleBlock; /** * Created by HuiJun on 4/14/16. */ public class DBUpdate extends DatabaseConnector { public DBUpdate(Context context) { super(context); } public void updateProfile(int id, Profile profile) { } public void updateAppointment(int id, Appointment appointment) { } public void updateSchedule(int id, ScheduleBlock schedule) { } public void storeUserName(String userName) { } public void storePassword(String password) { } }
true
9072664235769b5e783959342d0d04ac29db7921
Java
xiongshiyan/httpclient
/src/test/java/top/jfunc/common/http/ConfigSettingTest.java
UTF-8
1,808
2.234375
2
[ "Apache-2.0" ]
permissive
package top.jfunc.common.http; import org.junit.Test; import top.jfunc.common.http.base.Config; import top.jfunc.common.http.smart.*; import java.io.IOException; /** * @author xiongshiyan at 2019/4/3 , contact me with email yanshixiong@126.com or phone 15208384257 */ public class ConfigSettingTest { @Test public void testGetOkHttp3(){ SmartHttpClient http = new OkHttp3SmartHttpClient(); testGet(http); } @Test public void testGetApacheHttp(){ ApacheSmartHttpClient http = new ApacheSmartHttpClient(); testGet(http); } @Test public void testGetNativeHttp(){ NativeSmartHttpClient http = new NativeSmartHttpClient(); testGet(http); } @Test public void testGetJoddHttp(){ JoddSmartHttpClient http = new JoddSmartHttpClient(); testGet(http); } private void testGet(SmartHttpClient http){ Config config = Config.defaultConfig() .setBaseUrl("https://fanyi.baidu.com/") .setDefaultBodyCharset("UTF-8") .setDefaultResultCharset("UTF-8") .setDefaultConnectionTimeout(15000) .setDefaultReadTimeout(15000); config.headerHolder().add("xx" , "xx"); http.setConfig(config); String url = "?aldtype=85#zh/en/%E5%AE%8C%E6%95%B4%E7%9A%84%E6%88%91"; try { Request request = Request.of(url).setResultCharset("UTF-8"); request.headerHolder().add("saleType" , "2"); Response response = http.get(request); System.out.println(response); System.out.println(response.getHeaders()); String s = http.get(url); System.out.println(s); }catch (IOException e){ e.printStackTrace(); } } }
true
5aca2aa03d9f627ceee574c3c56cb7134856af52
Java
fengwfe/algorithm
/src/com/fuwu/good/tree/HelloTree.java
UTF-8
4,695
3.859375
4
[]
no_license
package com.fuwu.good.tree; import com.fuwu.good.common.TreeNode; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; /** * 中序遍历 * 特点: 二叉搜索树的话,遍历的结果是从小到大排序 * */ /** * 1.判断二叉树是否是二叉搜索树 * 2.构建二叉树 * 3.树的所有路径 * 4.树的所有路径的和 * 5.树的最小深度 * 6.是否存在root节点到叶子节点的path 满足节点的和为target sum * 7.按层级遍历,BFS * */ public class HelloTree { /** * 1.判断二叉树是否是二叉搜索树 * */ public static boolean isBinarySearchTree(TreeNode root, Integer min, Integer max ){ if(null == root){ return true; } if(null != max && root.val >= max){ return false; } if(null != min && root.val <= min){ return false; } return isBinarySearchTree(root.left, min, root.val) && isBinarySearchTree(root.right, root.val, max); } /** * 2.构建二叉树 *数组中没有重复元素 * @param inOrder * @param l1 * @param h1 * @param preOrder * @param l2 * @param h2 * @return */ public static TreeNode build(int[] inOrder, int l1, int h1, int[] preOrder, int l2, int h2){ if(l1 > h1){ return null; } int rootVal = preOrder[l2]; TreeNode root = new TreeNode(rootVal); int i = l1; while (inOrder[i] != rootVal){ i++; } int leftSize = i - l1; TreeNode left = build(inOrder, l1, i -1, preOrder, l2 + 1, l2 + leftSize - 1); TreeNode right = build(inOrder, i + 1, h1, preOrder, l2 + leftSize + 1, h2); root.left = left; root.right = right; return root; } /** * 3.树的所有路径 */ public static void allPath(TreeNode root, List<Integer> path, List<List<Integer>> result){ if(null == root){ return; } path.add(root.val); if(null == root.left && null == root.right){ result.add(new ArrayList<>(path)); return; } allPath(root.left, new ArrayList<>(path), result); allPath(root.right, new ArrayList<>(path), result); } /** * 4.树的所有路径的和 */ public static void allPath(TreeNode root, int sum, List<Integer> result){ if(null == root){ return; } if(null == root.left && null == root.right){ sum += root.val; result.add(sum); return; } allPath(root.left, sum + root.val, result); allPath(root.right, sum + root.val , result); } /** * 5.树的最小深度 * @param root * @return */ public static int minDepth(TreeNode root){ if(null == root){ return 0; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int depth = 0; while (! queue.isEmpty()){ depth++; int size = queue.size(); while(size > 0){ TreeNode node = queue.poll(); if(null == node.left && null == node.right){ return depth; } if(null != node.left){ queue.offer(node.left); } if(null != node.right){ queue.offer(node.right); } size--; } } return depth; } /** * 6.是否存在root节点到叶子节点的path 满足节点的和为target sum * */ public static boolean hasPath(TreeNode root, int sum){ if(null == root){ return false; } if(null == root.left && null == root.right){ if(sum == root.val){ return true; }else{ return false; } } return hasPath(root.left, sum - root.val) || hasPath(root.right, sum - root.val); } /** * 7.按层级遍历,BFS */ public static void levelPrint(TreeNode root){ if(null == root){ return; } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); while (!queue.isEmpty()){ TreeNode node = queue.poll(); TreeNode left = node.left; TreeNode right = node.right; System.out.println(node.val); if(null != left) queue.offer(left); if(null != right) queue.offer(right); } } }
true
5b6f9b168b69b58ff0e4df89813885e898cbecf9
Java
Iamskt/ACM
/JavaEE/PersonInfoManagement/src/org/njust/Action/DelDeclaretionAction.java
UTF-8
777
2.109375
2
[]
no_license
package org.njust.Action; import org.njust.Handle.DeclaretionHandle; import com.opensymphony.xwork2.ActionSupport; public class DelDeclaretionAction extends ActionSupport { private String jsonData; private String declaretionid; /** * @return */ public String execute() { // TODO Auto-generated method stub DeclaretionHandle handle = new DeclaretionHandle(); Integer id = Integer.parseInt(declaretionid); handle.Delete(handle.GetDeclaretionByID(id)); return SUCCESS; } public String getJsonData() { return jsonData; } public void setJsonData(String jsonData) { this.jsonData = jsonData; } public String getDeclaretionid() { return declaretionid; } public void setDeclaretionid(String declaretionid) { this.declaretionid = declaretionid; } }
true
1de05ec99eb2513619321d30bf30a851142ba327
Java
booky10/BungeeSecurity
/Bungee/src/tk/t11e/bungeesecurity/bungee/main/Main.java
UTF-8
4,560
2.34375
2
[]
no_license
package tk.t11e.bungeesecurity.bungee.main; // Created by booky10 in BungeeSecurity (20:38 05.05.20) import com.google.common.io.ByteArrayDataInput; import com.google.common.io.ByteStreams; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.event.PluginMessageEvent; import net.md_5.bungee.api.plugin.Listener; import net.md_5.bungee.api.plugin.Plugin; import net.md_5.bungee.config.Configuration; import net.md_5.bungee.config.ConfigurationProvider; import net.md_5.bungee.config.YamlConfiguration; import net.md_5.bungee.event.EventHandler; import tk.t11e.bungeesecurity.AES; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.IOException; import java.util.UUID; @SuppressWarnings({"ResultOfMethodCallIgnored", "UnstableApiUsage"}) public final class Main extends Plugin implements Listener { private final File configFile = new File(getDataFolder(), "config.yml"); private Configuration config; private final ConfigurationProvider provider = ConfigurationProvider.getProvider(YamlConfiguration.class); @Override public final void onEnable() { createConfig(); register(); } private void register() { //Plugin Messages getProxy().registerChannel("bungee:security"); //Listener getProxy().getPluginManager().registerListener(this, this); } private void createConfig() { try { //Creating config file/folder if (!getDataFolder().exists()) getDataFolder().mkdirs(); if (!configFile.exists()) configFile.createNewFile(); //Initial loading reloadConfig(); } catch (IOException exception) { throw new IllegalStateException(exception); } //Setting default values if (!config.contains("secret")) config.set("secret", UUID.randomUUID().toString()); if (!config.contains("key")) config.set("key", UUID.randomUUID().toString()); //Save and reload saveConfig(); reloadConfig(); } private void saveConfig() { try { provider.save(config, configFile); } catch (IOException exception) { throw new IllegalStateException(exception); } } private void reloadConfig() { try { config = provider.load(configFile); } catch (IOException exception) { throw new IllegalStateException(exception); } } @EventHandler public final void onPluginMessage(PluginMessageEvent event) { if (!event.getTag().equals("bungee:security")) return; ByteArrayDataInput dataInput = ByteStreams.newDataInput(event.getData()); if (!dataInput.readUTF().equals("request")) return; UUID requested = UUID.fromString(dataInput.readUTF()); ProxiedPlayer target = getProxy().getPlayer(requested); if (target != null && target.isConnected()) { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataOutputStream outputStream = new DataOutputStream(byteArrayOutputStream); AES aes = new AES(); try { outputStream.writeUTF("verification"); outputStream.writeUTF(requested.toString()); outputStream.writeUTF(aes.encrypt(getSecret(), getKey())); } catch (IOException exception) { getLogger().severe("Error while writing plugin message!"); } catch (Exception exception) { getLogger().severe("An Error happened, while encrypting secret!"); return; } target.sendData("bungee:security", byteArrayOutputStream.toByteArray()); target.getServer().sendData("bungee:security", byteArrayOutputStream.toByteArray()); getLogger().info("Send secret to player " + requested + " (" + target.getName() + ")!"); } else { getLogger().severe("Received invalid verification request for an unknown player!"); getLogger().severe("Maybe one of your bukkit servers is getting hacked!"); getLogger().severe("UUID: " + requested); } } private String getSecret() { //Reloading config reloadConfig(); //Getting secret return config.getString("secret"); } private String getKey() { //Reloading config reloadConfig(); //Getting Key return config.getString("key"); } }
true
e06b7a4fe939fa67e6f5441ae1955a65270a49a6
Java
pablozagnoli/ProjetoCorreiosGerson
/ProjetoCorreiosGerson/src/projetocorreiosgerson/ProjetoCorreiosGerson.java
UTF-8
1,378
2.96875
3
[ "Apache-2.0" ]
permissive
package projetocorreiosgerson; import java.util.Scanner; public class ProjetoCorreiosGerson { public static void main(String[] args) { Scanner teclado = new Scanner(System.in); int categoria; int preco, peso, altura, largura; int bronze, prata, platina; peso =0; altura = 0; System.out.println("Digite a sua categoria"); categoria = teclado.nextInt(); bronze = 1; prata = 2; if (categoria == bronze ){ System.out.println("Digite o peso do produto"); peso = teclado.nextInt(); System.out.println("Digite a altura do produto"); altura = teclado.nextInt(); System.out.println("Digite a largura do produto"); largura = teclado.nextInt(); } if (categoria == prata){ System.out.println("Digite o peso do produto"); peso = teclado.nextInt(); System.out.println("Digite a altura do produto"); altura = teclado.nextInt(); System.out.println("Digite a largura do produto"); largura = teclado.nextInt(); } System.out.println("O valor da sua tarifa é" + " " + ((peso) * (altura ))); } }
true
77cfbd27db2f3a8cb76b0b6f174ec6e9741bc0bb
Java
dnjiao/Java-algorithms
/src/number/AddTwoBinary.java
UTF-8
557
3.40625
3
[]
no_license
package number; import java.io.*; public class AddTwoBinary { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String s; while ((s = in.readLine()) != null) { String[] array = s.split(" "); System.out.println(sumBinary(array[0], array[1])); } } public static int sumBinary(String s1, String s2) { int bin1 = Integer.parseInt(s1, 2); int bin2 = Integer.parseInt(s2, 2); int sum = bin1 + bin2; return sum; } }
true
407808c1a71ac0b5caef42c44eeb7e6f7d902e3c
Java
andrewagrahamhodges/ovd_sources
/ovd-android/src/org/ulteo/ovd/sm/Properties.java
UTF-8
4,267
1.804688
2
[]
no_license
/* * Copyright (C) 2009-2012 Ulteo SAS * http://www.ulteo.com * Author Julien LANGLOIS <julien@ulteo.com> 2010, 2011 * Author Thomas MOUTON <thomas@ulteo.com> 2011 * Author David PHAM-VAN <d.pham-van@ulteo.com> 2012 * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.ulteo.ovd.sm; public class Properties { public static final int MODE_ANY = 0; public static final int MODE_DESKTOP = 1; public static final int MODE_REMOTEAPPS = 2; public static final int REDIRECT_DRIVES_NO = 0; public static final int REDIRECT_DRIVES_PARTIAL = 1; public static final int REDIRECT_DRIVES_FULL = 2; private int mode = 0; private String lang = null; private String username = null; private String timeZone = null; private int duration = 0; private boolean multimedia = false; private boolean printers = false; private boolean persistent = false; private int drives = REDIRECT_DRIVES_NO; private boolean desktop_icons = false; private boolean desktop_effects = false; private Integer applicationID = null; private boolean showdesktop = true; private String login = null; private String password = null; private String token = null; public Properties(int mode) { this.mode = mode; } public int getMode() { return this.mode; } public void setMode(int mode) { this.mode = mode; } public String getLang() { return lang; } public void setLang(String lang) { this.lang = lang; } public String getTimeZone() { return this.timeZone; } public void setTimeZone(String timeZone) { this.timeZone = timeZone; } public String getUsername() { return this.username; } public void setUsername(String username_) { this.username = username_; } public boolean isMultimedia() { return multimedia; } public void setMultimedia(boolean multimedia) { this.multimedia = multimedia; } public boolean isPrinters() { return printers; } public void setPrinters(boolean printers) { this.printers = printers; } public int isDrives() { return this.drives; } public void setDrives(int drives) { this.drives = drives; } public int getDuration() { return this.duration; } public void setPersistent(boolean value) { this.persistent = value; } public boolean isPersistent() { return this.persistent; } public void setDuration(int duration_) { this.duration = duration_; } public boolean isDesktopIcons() { return this.desktop_icons; } public void setDesktopIcons(boolean desktop_icons_) { this.desktop_icons = desktop_icons_; } public boolean isDesktopEffectsEnabled() { return this.desktop_effects; } public void setDesktopEffects(boolean desktop_effects_) { this.desktop_effects = desktop_effects_; } public void setApplicationId(int applicationID) { this.applicationID = applicationID; } public Integer getApplicationId() { return this.applicationID; } public boolean hasApplicationId() { return this.applicationID != null; } public void setShowDesktop(boolean showdesktop) { this.showdesktop = showdesktop; } public boolean showDesktop() { return this.showdesktop; } public void setLogin(String login) { this.login = login; } public String getLogin() { return this.login; } public void setPassword(String password) { this.password = password; } public String getPassword() { return this.password; } public void setToken(String token) { this.token = token; } public String getToken() { return this.token; } }
true
b47ce7b529a0b45b034f44e47fd88e7334862223
Java
bachmeb/sudoku-maker-solver
/src/main/java/algorithms/SolveSetsOfEight.java
UTF-8
4,438
3.515625
4
[]
no_license
package algorithms; import model.SudokuGrid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.SudokuGridObserver; import service.SudokuGridSolver; public class SolveSetsOfEight extends SudokuGridSolver implements SudokuGridSolverAlgorithms { static final Logger logger = LoggerFactory.getLogger(SolveSetsOfEight.class); SudokuGridObserver observer; public static int[] addTheLastNumberToTheSet(int[] set) { // make sure the set is not null if (set == null) { throw new RuntimeException(); } // make sure the set has a length of 9 if (set.length != 9) { throw new RuntimeException("There are only 9 squares in every set"); } // make sure the set has 8 numbers int countOfNumbers = 0; for (int i = 0; i < set.length; i++) { if (set[i] > 0) { countOfNumbers++; } } if (countOfNumbers != 8) { throw new RuntimeException("there are supposed to be 8 squares with a number"); } // find the missing number int missingNumber = 0; int sumOfNumbersInSet = 0; for (int i = 0; i < set.length; i++) { sumOfNumbersInSet += set[i]; } int sumOfAllNumbers = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9; missingNumber = sumOfAllNumbers - sumOfNumbersInSet; // add the missing number to the set for (int i = 0; i < set.length; i++) { if (set[i] == 0) { set[i] = missingNumber; logger.debug("Added missing number " + missingNumber + " to the set"); break; } } return set; } @Override public SudokuGrid solve(SudokuGrid grid) { solveSetsOfEight(grid); return grid; } private SudokuGrid solveSetsOfEight(SudokuGrid grid) { logger.info("solve by looking for sets of eight"); grid = fillLastEmptySquareInAnyBox(grid); grid = fillLastEmptySquareInAnyRow(grid); grid = fillLastEmptySquareInAnyColumn(grid); return grid; } private SudokuGrid fillLastEmptySquareInAnyColumn(SudokuGrid grid) { observer = new SudokuGridObserver(grid); observer.reCountNumbersInSquares(); // if the number of numbers in a given column is 8 then add the last number for (int i = 0; i < observer.getCountOfFilledSquaresIndexedByColumnNumber().length; i++) { if (observer.getCountOfFilledSquaresIndexedByColumnNumber()[i] == 8) { logger.info("There are 8 squares filled in column number " + i); int set[] = addTheLastNumberToTheSet(grid.getColumns()[i]); int[][] columns = grid.getColumns(); columns[i] = set; grid.setColumns(columns); } } return grid; } private SudokuGrid fillLastEmptySquareInAnyRow(SudokuGrid grid) { observer = new SudokuGridObserver(grid); observer.reCountNumbersInSquares(); // if the number of numbers in a given row is 8 then add the last number for (int i = 0; i < observer.getCountOfFilledSquaresIndexedByRowNumber().length; i++) { if (observer.getCountOfFilledSquaresIndexedByRowNumber()[i] == 8) { logger.info("There are 8 squares filled in row number " + i); int set[] = addTheLastNumberToTheSet(grid.getRows()[i]); int[][] rows = grid.getRows(); rows[i] = set; grid.setRows(rows); } } return grid; } private SudokuGrid fillLastEmptySquareInAnyBox(SudokuGrid grid) { observer = new SudokuGridObserver(grid); observer.reCountNumbersInSquares(); // if the number of numbers in a given box is 8 then add the last number for (int i = 0; i < observer.getCountOfFilledSquaresIndexedByBoxNumber().length; i++) { if (observer.getCountOfFilledSquaresIndexedByBoxNumber()[i] == 8) { logger.info("There are 8 squares filled in box number " + i); int set[] = addTheLastNumberToTheSet(grid.getBoxes()[i]); int[][] boxes = grid.getBoxes(); boxes[i] = set; grid.setBoxes(boxes); } } return grid; } }
true
57f69bb3e6fef3cf19cdaee8d143f4cadbf114e5
Java
elascano/ESPE202105-OOP-SW-3682
/workshops/escobari/unit2/WS25UnitTest/addandsubtract/src/add/and/subtract/AddAndSubtract.java
UTF-8
474
1.585938
2
[]
no_license
/* * 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 add.and.subtract; import java.util.Scanner; /** * * @author Isaac Escobar InnovaCode ESPE-DCCO */ public class AddAndSubtract { /** * @param args the command line arguments */ public static void main(String[] args) { } }
true
0eb03d74b194d62e0320cdd0a6171f724ad889c4
Java
rivercomsci09/spring-reactjs
/devicesmanagement-app-server/src/main/java/com/river/devicesmanagement/service/RoleService.java
UTF-8
199
1.851563
2
[]
no_license
package com.river.devicesmanagement.service; import com.river.devicesmanagement.model.Role; import java.util.Optional; public interface RoleService { Optional<Role> findByName(String name); }
true
3936940594529531747763b247c294f4fb622927
Java
nberkutov/Contacts
/Contacts/task/src/contacts/AddPersonCommand.java
UTF-8
1,136
3.515625
4
[]
no_license
package contacts; import java.util.Scanner; public class AddPersonCommand implements Command { private PhoneBook phoneBook; public AddPersonCommand(PhoneBook phoneBook) { this.phoneBook = phoneBook; } @Override public void execute() { Scanner scanner = new Scanner(System.in); String name, surname, number, birthDate, gender; PersonRecord person = new PersonRecord(); System.out.print("Enter the name: "); name = scanner.nextLine(); person.setName(name); System.out.print("Enter the surname: "); surname = scanner.nextLine(); person.setSurname(surname); System.out.print("Enter the birth date: "); birthDate = scanner.nextLine(); person.setBirthDate(birthDate); System.out.print("Enter the gender (M, F): "); gender = scanner.nextLine(); person.setGender(gender); System.out.print("Enter the number: "); number = scanner.nextLine(); person.setNumber(number); phoneBook.addRecord(person); System.out.println("The record added."); } }
true
8bac2ef01bfb95c68e8b1c7724388006bd52abb6
Java
assandra/AdvancedProgAE1
/Species2.java
UTF-8
10,867
3.125
3
[]
no_license
public class Species2 extends Creature implements Runnable { /** Constructor */ public Species2(int x, int y, Cell [][] grid, int worldType) { super(x,y, grid, worldType); setMaxLifeSpan(5); setFitnessLevel(0.4); findLifeSpan(); setIsAlive(true); } /** Identifier for Species 2*/ public int identifier() { return 2; } /** Run method for Species 2 */ public void run() { try{ long sleep =(long) this.getLifeSpan() * 1000; Thread.sleep(sleep); if (isAlive == true) { if (this.getWorldType()==1) { Cell [] neighbours1 = this.getNeighboursW1(); this.reproduce(neighbours1); } else if (this.getWorldType()==2) { Cell [] neighbours2 = this.getNeighboursW2(); this.reproduce(neighbours2); } grid[x][y] = new Cell (x,y); Thread.currentThread().interrupt(); } else if (isAlive == false) { Thread.currentThread().interrupt(); } } catch (InterruptedException e){ } } // public void reproducegfhj() { // try { // if (((x-1) >= 0) && ((y-1) >=0)){ // if (grid[x-1][y-1].getOccupation() == false) { // //if (Math.random() <= 0) { // Species2 newspecies = new Species2(x-1, y-1, grid, worldType); // //System.out.println("THis happened instead 2"); // grid[x-1][y-1] = new Cell (x-1,y-1, newspecies); // Thread t = new Thread(newspecies); // t.start(); // //} // } // else if (grid[x-1][y-1].getOccupation() == true) { // if ( Math.random() <= this.getFitnessLevel() - grid[x-1][y-1].getSpecies().getFitnessLevel()) // { // Species2 newspecies = new Species2(x-1, y-1, grid, worldType); // grid[x-1][y-1].getSpecies().setIsAlive(false); // //System.out.println("Ive been killed at location" +(x-1) + (y-1)); // grid[x-1][y-1] = new Cell (x-1,y-1, newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // if ((x-1) >=0) { // if (grid[x-1][y].getOccupation() == false) { // // if (Math.random() <= 0) { // Species2 newspecies = new Species2(x-1, y, grid, worldType); // //System.out.println("THis happened instead 2"); // grid[x-1][y] = new Cell (x-1,y, newspecies); // Thread t = new Thread(newspecies); // t.start(); // //} // } // else if (grid[x-1][y].getOccupation() == true) { // if ( Math.random() <= this.getFitnessLevel() - grid[x-1][y].getSpecies().getFitnessLevel()) // { // Species2 newspecies = new Species2(x-1, y, grid, worldType); // grid[x-1][y].getSpecies().setIsAlive(false); // //System.out.println("Ive been killed at location" +(x-1) + y); // grid[x-1][y] = new Cell (x-1,y,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // if (((x-1) >= 0) && ((y+1) < grid[0].length)){ // if (grid[x-1][y+1].getOccupation() == false) { // Species2 newspecies = new Species2(x-1, y+1,grid, worldType); // //System.out.println("THis happened instead 2"); // grid[x-1][y+1] = new Cell(x-1,y+1,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // else if (grid[x-1][y+1].getOccupation() ==true) { // if (Math.random() <= this.getFitnessLevel() - grid[x-1][y+1].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(x-1, y+1,grid, worldType); // grid[x-1][y+1].getSpecies().setIsAlive(false); // //System.out.println("2----Ive been killed at location" +(x-1) + (y+1)); // grid[x-1][y+1] = new Cell(x-1,y+1,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // if ((y-1) >=0) { // if (grid[x][y-1].getOccupation() == false) { // // if (Math.random() <= 0) { // Species2 newspecies = new Species2(x, y-1,grid, worldType); // grid[x][y-1] = new Cell(x,y-1,newspecies); // //System.out.println("THis happened instead 2"); // Thread t = new Thread(newspecies); // t.start(); // } // else if (grid[x][y-1].getOccupation() == true) { // if (Math.random() <= this.getFitnessLevel() - grid[x][y-1].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(x, y-1, grid, worldType); // grid[x][y-1].getSpecies().setIsAlive(false); // //System.out.println("2----Ive been killed at location" +(x) + (y+1)); // grid[x][y-1] = new Cell(x, y-1,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // if ((y+1)< grid[0].length){ // if (grid[x][y+1].getOccupation() == false) { // // if (Math.random() <= 0) { // Species2 newspecies = new Species2(x, y+1, grid, worldType); // grid[x][y+1]= new Cell(x,y+1,newspecies); // //System.out.println("THis happened instead 2"); // Thread t = new Thread(newspecies); // t.start(); // // } // } // else if (grid[x][y+1].getOccupation() == true) { // if (Math.random() <= this.getFitnessLevel() - grid[x][y+1].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(x, y+1, grid, worldType); // grid[x][y+1].getSpecies().setIsAlive(false); // //System.out.println("2--Ive been killed at location" +(x) + (y+1)); // grid[x][y+1] = new Cell(x,y+1,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // if (((x+1) <grid[0].length) && ((y-1)>= 0)) { // if (grid[x+1][y-1].getOccupation() == false) { // // if (Math.random() <= 0) { // Species2 newspecies = new Species2(x+1, y-1, grid, worldType); // grid[x+1][y-1] = new Cell(x+1,y-1,newspecies); // //System.out.println("THis happened instead 2"); // Thread t = new Thread(newspecies); // t.start(); // } // else if (grid[x+1][y-1].getOccupation() == true) { // if (Math.random() <= this.getFitnessLevel() - grid[x+1][y-1].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(x+1, y-1,grid, worldType); // grid[x+1][y-1].getSpecies().setIsAlive(false); // //System.out.println("2--Ive been killed at location" +(x+1) + (y-1)); // grid[x+1][y-1] = new Cell (x+1,y-1,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // if ((x+1) < grid[0].length) { // if (grid[x+1][y].getOccupation() == false) { // //if (Math.random() <= 0) { // Species2 newspecies = new Species2(x+1, y,grid, worldType); // grid[x+1][y] = new Cell (x+1,y,newspecies); // //System.out.println("2---THis happened instead 2"); // Thread t = new Thread(newspecies); // t.start(); // } // else if (grid[x+1][y].getOccupation() == true) { // if (Math.random() <= this.getFitnessLevel() - grid[x+1][y].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(x+1, y,grid, worldType); // grid[x+1][y].getSpecies().setIsAlive(false); // //System.out.println("2---Ive been killed at location" +(x+1) + y); // grid[x+1][y] = new Cell(x+1,y, newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // //} // } // } // if (((x+1) < grid[0].length) && ((y+1) < grid[0].length)) { // if (grid[x+1][y+1].getOccupation() == false) { // //if (Math.random() <= 0) { // Species2 newspecies = new Species2(x+1, y+1, grid, worldType); // grid[x+1][y+1] = new Cell (x+1,y+1,newspecies); // //System.out.println("THis happened instead 2"); // Thread t = new Thread(newspecies); // t.start(); // } // else if (grid[x+1][y+1].getOccupation() == true) { // if (Math.random() <= this.getFitnessLevel() - grid[x+1][y+1].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(x+1, y+1, grid, worldType); // grid[x+1][y+1].getSpecies().setIsAlive(false); // //System.out.println("2--Ive been killed at location" +(x+1) + (y+1)); // grid[x+1][y+1] = new Cell (x+1,y+1,newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // } // catch(NullPointerException e) { // } // } /** * The species2 reproduces depending on the state of * its neighbours * @param neighbours - neighbours array which is different depending on what world is active */ public synchronized void reproduce(Cell [] neighbours) { Cell [] myNeighbours = neighbours; try { for (int i=0; i<myNeighbours.length; i++) { if (myNeighbours[i].getOccupation() == false) { if (Math.random() <= this.getFitnessLevel()) { Species2 newspecies = new Species2(myNeighbours[i].getX(),myNeighbours[i].getY(), grid, worldType); grid[myNeighbours[i].getX()][myNeighbours[i].getY()] = new Cell (myNeighbours[i].getX(),myNeighbours[i].getY(), newspecies); Thread t = new Thread(newspecies); t.start(); } } else if (myNeighbours[i].getOccupation() == true) { if (Math.random() <= this.getFitnessLevel() - myNeighbours[i].getSpecies().getFitnessLevel()) { Species2 newspecies = new Species2(myNeighbours[i].getX(),myNeighbours[i].getY(),grid, worldType); myNeighbours[i].getSpecies().setIsAlive(false); grid[myNeighbours[i].getX()][myNeighbours[i].getY()] = new Cell (myNeighbours[i].getX(),myNeighbours[i].getY(), newspecies); Thread t = new Thread(newspecies); t.start(); } } } } catch (NullPointerException e) { } } // public void reproduce2() { // //Cell [] myNeighbours = n; // Cell [] myNeighbours = getNeighbours(); // for (int i=0; i<myNeighbours.length; i++) { // try { // if (myNeighbours[i].getOccupation() == false) { // Species2 newspecies = new Species2(myNeighbours[i].getX(),myNeighbours[i].getY(), grid, worldType); // grid[myNeighbours[i].getX()][myNeighbours[i].getY()] = new Cell (myNeighbours[i].getX(),myNeighbours[i].getY(), newspecies); // //System.out.println("THis happened instead 1"); // Thread t = new Thread(newspecies); // t.start(); // } // else if (myNeighbours[i].getOccupation() == true) { // if (Math.random() <= this.getFitnessLevel() - myNeighbours[i].getSpecies().getFitnessLevel()) { // Species2 newspecies = new Species2(myNeighbours[i].getX(),myNeighbours[i].getY(),grid, worldType); // myNeighbours[i].getSpecies().setIsAlive(false); // //System.out.println("1 ---I was killed at location" + (x+1) + (y+1)); // grid[myNeighbours[i].getX()][myNeighbours[i].getY()] = new Cell (myNeighbours[i].getX(),myNeighbours[i].getY(), newspecies); // Thread t = new Thread(newspecies); // t.start(); // } // } // } // catch (NullPointerException e) { // } // } // } }
true
f184341c1ddb43afd4ceacdf6af7347dca8fcf58
Java
duanjisi/MeetBusiness
/app/src/main/java/com/atgc/cotton/activity/VerifyPhoneActivity.java
UTF-8
5,019
2.078125
2
[]
no_license
package com.atgc.cotton.activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.atgc.cotton.App; import com.atgc.cotton.R; import com.atgc.cotton.activity.base.BaseActivity; import com.atgc.cotton.entity.AccountEntity; import com.atgc.cotton.http.BaseDataRequest; import com.atgc.cotton.http.request.PhoneUnBindRequest; import com.atgc.cotton.http.request.PhoneVerifyRequest; import org.json.JSONException; import org.json.JSONObject; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; /** * Created by Johnny on 2017-08-21. */ public class VerifyPhoneActivity extends BaseActivity { private static final String TAG = VerifyPhoneActivity.class.getSimpleName(); private static final int DELAY_MILlIS = 1000; @Bind(R.id.iv_back) ImageView ivBack; @Bind(R.id.tv_option) TextView tvOption; @Bind(R.id.tv_num) TextView tvNum; @Bind(R.id.et_code) EditText etCode; @Bind(R.id.tv_qrCode) TextView tvQrCode; private AccountEntity account; private int interval = 0; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 0: if (interval != 0) { interval--; tvQrCode.setText(String.valueOf(interval) + "秒"); handler.sendEmptyMessageDelayed(0, DELAY_MILlIS); } else { tvQrCode.setText("发送验证码"); tvQrCode.setEnabled(true); handler.removeMessages(0); } break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_verify_phone); ButterKnife.bind(this); initDatas(); } private void initDatas() { account = App.getInstance().getAccountEntity(); String mbilePhone = account.getMobilePhone(); if (!TextUtils.isEmpty(mbilePhone)) { tvNum.setText(mbilePhone); } } @OnClick({R.id.iv_back, R.id.tv_option, R.id.tv_qrCode}) public void onViewClicked(View view) { switch (view.getId()) { case R.id.iv_back: finish(); break; case R.id.tv_option: verifyRequest(); break; case R.id.tv_qrCode: sendCode(); break; } } private void sendCode() { showLoadingDialog(); PhoneUnBindRequest request = new PhoneUnBindRequest(TAG); request.send(new BaseDataRequest.RequestCallback<String>() { @Override public void onSuccess(String pojo) { cancelLoadingDialog(); BindData(pojo); } @Override public void onFailure(String msg) { cancelLoadingDialog(); showToast(msg, true); } }); } private void BindData(String string) { try { Log.i("info", "=====json:" + string); JSONObject obj = new JSONObject(string); interval = obj.getInt("Interval"); Log.i("info", "=====Interval:" + interval); tvQrCode.setEnabled(false); handler.sendEmptyMessageDelayed(0, DELAY_MILlIS); } catch (JSONException e) { e.printStackTrace(); } } private void verifyRequest() { String code = getText(etCode); if (TextUtils.isEmpty(code)) { showToast("验证码为空!", true); return; } showLoadingDialog(); PhoneVerifyRequest request = new PhoneVerifyRequest(TAG, code); request.send(new BaseDataRequest.RequestCallback<String>() { @Override public void onSuccess(String pojo) { cancelLoadingDialog(); initData(pojo); } @Override public void onFailure(String msg) { cancelLoadingDialog(); showToast(msg, true); } }); } private void initData(String string) { try { Log.i("info", "=====json:" + string); JSONObject obj = new JSONObject(string); boolean isOk = obj.getBoolean("IsRight"); if (isOk) { showToast("验证成功!", true); openActivity(ChangePhoneActivity.class); finish(); } } catch (JSONException e) { e.printStackTrace(); } } }
true
21446f87a53d0a02610203f7ca49a19b93bbfccf
Java
WilliamRen/DragonFlow
/src/me/notimplementedexception/dragonflow/Question.java
UTF-8
1,547
2.46875
2
[]
no_license
package me.notimplementedexception.dragonflow; import java.util.ArrayList; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.os.Parcel; import android.os.Parcelable; import android.text.Html; public class Question { private Integer id; private Integer score; private Integer answerCount; private String title; private ArrayList<String> tags; private User owner; private Boolean answered; private String body; public Question(JSONObject question) throws JSONException { this.id = question.getInt("question_id"); this.score = question.getInt("score"); this.answerCount = question.getInt("answer_count"); this.title = Html.fromHtml(question.getString("title")).toString(); this.answered = question.getBoolean("is_answered"); this.tags = new ArrayList<String>(); // parse array of tags JSONArray tagsJson = question.getJSONArray("tags"); for(int i = 0; i < tagsJson.length(); i++) { String tag = tagsJson.getString(i); this.tags.add(tag); } // parse user JSONObject userJson = question.getJSONObject("owner"); User user = new User(userJson); this.owner = user; } public void addDetails(JSONObject detailsJson) throws JSONException { JSONArray array = detailsJson.getJSONArray("items"); JSONObject queDetails = array.getJSONObject(0); this.body = queDetails.getString("body"); } public Integer getId() { return this.id; } public String getTitle() { return this.title; } public String getBody() { return this.body; } }
true
784ee2202c2605f75cc6753f41feae9cf3a23677
Java
SamGG/mev-tm4
/source/org/tigr/microarray/mev/cluster/gui/impl/attract/ATTRACTResultTable.java
UTF-8
28,802
1.648438
2
[ "Artistic-2.0", "Artistic-1.0" ]
permissive
package org.tigr.microarray.mev.cluster.gui.impl.attract; import java.awt.*; import java.awt.event.*; import java.awt.datatransfer.Clipboard; import java.awt.image.BufferedImage; import java.beans.Expression; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import javax.swing.*; import javax.swing.table.*; import javax.swing.tree.DefaultMutableTreeNode; import org.tigr.microarray.mev.TMEV; import org.tigr.microarray.mev.cluster.gui.IViewer; import org.tigr.microarray.mev.cluster.gui.Experiment; import org.tigr.microarray.mev.cluster.gui.IDisplayMenu; import org.tigr.microarray.mev.cluster.gui.IData; import org.tigr.microarray.mev.cluster.gui.IFramework; import org.tigr.microarray.mev.cluster.gui.LeafInfo; import org.tigr.microarray.mev.cluster.gui.helpers.ExperimentUtil; import org.tigr.microarray.mev.cluster.gui.helpers.ExperimentViewer; import org.tigr.microarray.mev.cluster.gui.impl.GUIFactory; import org.tigr.util.QSort; /** * * @author dschlauch */ public class ATTRACTResultTable implements IViewer { protected static final String STORE_CLUSTER_CMD = "store-cluster-cmd"; protected static final String STORE_SELECTED_ROWS_CMD = "store-selected-rows-cmd"; protected static final String SET_DEF_COLOR_CMD = "set-def-color-cmd"; protected static final String SAVE_CLUSTER_CMD = "save-cluster-cmd"; protected static final String SAVE_ALL_CLUSTERS_CMD = "save-all-clusters-cmd"; protected static final String LAUNCH_NEW_SESSION_CMD = "launch-new-session-cmd"; protected static final String LAUNCH_NEW_SESSION_WITH_SEL_ROWS_CMD = "launch-new-session-with-sel-rows-cmd"; protected static final String SEARCH_CMD = "search-cmd"; protected static final String CLEAR_ALL_CMD = "clear-all-cmd"; protected static final String COPY_CMD = "copy-cells"; protected static final String SELECT_ALL_CMD = "select-all-cmd"; protected static final String SORT_ORIG_ORDER_CMD = "sort-orig-order-cmd"; protected static final String BROADCAST_MATRIX_GAGGLE_CMD = "broadcast-matrix-to-gaggle"; protected static final String BROADCAST_SELECTED_MATRIX_GAGGLE_CMD = "broadcast-selected-matrix-to-gaggle"; protected static final String BROADCAST_NAMELIST_GAGGLE_CMD = "broadcast-namelist-to-gaggle"; private static final String SAVE_TABLE_COMMAND ="save_pvalues_table_command"; private static final String STORE_CLUSTER_COMMAND="store_cluster_command"; private static final String CLEAR_ALL_COMMAND = "clear-all-cmd"; private static final String SELECT_ALL_COMMAND = "select-all-cmd"; private static final String LAUNCH_EXPRESSION_GRAPH_COMMAND = "launch-expression-graph-command"; private static final String TABLE_VIEW_COMMAND = "table-view-command"; private static final String LAUNCH_CENTROID_GRAPH_COMMAND = "launch-centroid-graph-command"; private static final String LAUNCH_EXPRESSION_IMAGE_COMMAND = "launch-expression-image-command"; private static final String LAUNCH_EXPRESSION_CHART_COMMAND = "launch-expression-chart-command"; public static final String BROADCAST_MATRIX_GENOME_BROWSER_CMD = "broadcast-matrix-to-genome-browser"; public static final int INTEGER_TYPE = 10; public static final int FLOAT_TYPE = 11; public static final int DOUBLE_TYPE = 12; public static final int STRING_TYPE = 13; public static final int BOOLEAN_TYPE = 14; private JComponent header; private JPopupMenu popup; private Object[][] data; private int[] indices; private int[] sortedIndices; private String[] columnTitles; private boolean[] sortedAscending; private JTable clusterTable; private ClusterTableModel clusterModel; private int exptID = 0; private DefaultMutableTreeNode rootNode; IFramework framework; int nodeOffset = 0; public ATTRACTResultTable(Object[][] data, DefaultMutableTreeNode analysisNode, IFramework framework, String[] auxTitles, String title) { this.framework = framework; this.rootNode = analysisNode; this.data = data; indices = new int[data.length]; this.sortedIndices = new int[data.length]; for (int i=0; i<data.length; i++){ indices[i]=i; sortedIndices[i]=i; } if (title.contains("Correlated")) nodeOffset = 7; this.columnTitles = auxTitles; this.clusterModel = new ClusterTableModel(); this.clusterTable = new JTable(clusterModel); clusterTable.setCellSelectionEnabled(true); TableColumn column = null; for (int i = 0; i < clusterModel.getColumnCount(); i++) { column = clusterTable.getColumnModel().getColumn(i); column.setMinWidth(30); } this.sortedAscending = new boolean[clusterModel.getColumnCount()]; for (int j = 0; j < sortedAscending.length; j++) { sortedAscending[j] = false; } addMouseListenerToHeaderInTable(clusterTable); header = clusterTable.getTableHeader(); setMaxWidth(getContentComponent(), getHeaderComponent()); Listener listener = new Listener(); this.popup = createJPopupMenu(listener); clusterTable.addMouseListener(listener); } public JTable getTable(){ return clusterTable; } public Expression getExpression(){ return new Expression(this, this.getClass(), "new", new Object[]{data, columnTitles}); } protected String[] getAuxTitles() { return columnTitles; } public void setExperiment(Experiment e) { this.exptID = e.getId(); } public int getExperimentID() { return this.exptID; } public void setExperimentID(int id) { this.exptID = id; } /** * Returns a component to be inserted into scroll pane view port. * */ public JComponent getContentComponent() { JPanel panel = new JPanel(); panel.setBackground(Color.gray); GridBagConstraints constraints = new GridBagConstraints(); GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.NORTH; buildConstraints(constraints, 0, 0, 1, 1, 100, 100); gridbag.setConstraints(clusterTable, constraints); panel.add(clusterTable); return panel; } /** * Returns the corner component corresponding to the indicated corner, * * possibly null * */ public JComponent getCornerComponent(int cornerIndex) { return null; } /** * Returns a component to be inserted into scroll pane header. * */ public JComponent getHeaderComponent() { JPanel panel = new JPanel(); panel.setBackground(Color.white); GridBagConstraints constraints = new GridBagConstraints(); GridBagLayout gridbag = new GridBagLayout(); panel.setLayout(gridbag); constraints.fill = GridBagConstraints.HORIZONTAL; buildConstraints(constraints, 0, 0, 1, 1, 100, 100); gridbag.setConstraints(header, constraints); panel.add(header); return panel; } void buildConstraints(GridBagConstraints gbc, int gx, int gy, int gw, int gh, int wx, int wy) { gbc.gridx = gx; gbc.gridy = gy; gbc.gridwidth = gw; gbc.gridheight = gh; gbc.weightx = wx; gbc.weighty = wy; } /** * Invoked by the framework to save or to print viewer image. * */ public BufferedImage getImage() { return null; } /** * Returns a component to be inserted into the scroll pane row header * */ public JComponent getRowHeaderComponent() { return null; } /** * Invoked when the framework is going to be closed. * */ public void onClosed() { } /** * Invoked by the framework when data is changed, * * if this viewer is selected. * * @see IData * */ public void onDataChanged(IData data) { } /** * Invoked by the framework when this viewer was deselected. * */ public void onDeselected() { } /** * Invoked by the framework when display menu is changed, * * if this viewer is selected. * * @see IDisplayMenu * */ public void onMenuChanged(IDisplayMenu menu) { } /** * Invoked by the framework when this viewer is selected. * */ public void onSelected(IFramework framework) { } /** * Sets cluster index to be displayed. */ public void setClusterIndex(int clusterIndex) { } /** * Returns index of current cluster. */ public int getClusterIndex() { return 0; } /** * Returns indices of current cluster. */ public int[] getCluster() { return indices; } /** * Returns all the clusters. */ public int[][] getClusters() { int[][] cls = new int[1][]; cls[0] = indices; return cls; } public int[] getSortedCluster() { return sortedIndices; } /** * Returns index of a gene in the current cluster. */ protected int getProbe(int row) { return this.indices[row]; } /** * Returns wrapped experiment. */ public Experiment getExperiment() { return null; } /** * Returns the data. */ public IData getData() { return null; } class ClusterTableModel extends AbstractTableModel { /** * */ private static final long serialVersionUID = 1L; String[] columnNames; boolean hasAnnotation = true; public ClusterTableModel() { columnNames = new String[columnTitles.length]; for (int i = 0; i < columnNames.length; i++) { columnNames[i] = columnTitles[i]; } } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return getCluster().length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return String.valueOf(data[getSortedCluster()[row]][col]); } public Class getColumnClass(int c) { return getValueAt(0, c).getClass(); } } private int[] reverse(int[] arr) { int[] revArr = new int[arr.length]; int revCount = 0; int count = arr.length - 1; for (int i=0; i < arr.length; i++) { revArr[revCount] = arr[count]; revCount++; count--; } return revArr; } public void addMouseListenerToHeaderInTable(JTable table) { final JTable tableView = table; tableView.setColumnSelectionAllowed(true); MouseAdapter listMouseListener = new MouseAdapter() { public void mouseClicked(MouseEvent e) { TableColumnModel columnModel = tableView.getColumnModel(); int viewColumn = columnModel.getColumnIndexAtX(e.getX()); int column = tableView.convertColumnIndexToModel(viewColumn); if (e.getClickCount() == 1 && column != -1) { int controlPressed = e.getModifiers()&InputEvent.CTRL_MASK; boolean originalOrder = (controlPressed != 0); sortByColumn(column, !(sortedAscending[column]), originalOrder); sortedAscending[column] = !(sortedAscending[column]); if (originalOrder) { for (int i = 0; i < clusterModel.getColumnCount(); i++) sortedAscending[i] = false; } } } }; JTableHeader th = tableView.getTableHeader(); th.addMouseListener(listMouseListener); } public void sortByColumn(int column, boolean ascending, boolean originalOrder) { if (originalOrder) { for (int i = 0; i < getSortedCluster().length; i++) { sortedIndices[i] = getCluster()[i]; } clusterTable.repaint(); clusterTable.clearSelection(); return; } int[] sortedArray = new int[getCluster().length]; int obType = getObjectType(data[0][column]); if ((obType == ExperimentUtil.DOUBLE_TYPE) || (obType == ExperimentUtil.FLOAT_TYPE) || (obType == ExperimentUtil.INTEGER_TYPE)) { double[] origArray = new double[getCluster().length]; for (int i = 0; i < origArray.length; i++) { if ((data[getCluster()[i]][column])==null) continue; if (obType == ExperimentUtil.DOUBLE_TYPE) { origArray[i] = ((Double)(data[getCluster()[i]][column])).doubleValue(); } else if (obType == ExperimentUtil.FLOAT_TYPE) { origArray[i] = ((Float)(data[getCluster()[i]][column ])).doubleValue(); } else if (obType == ExperimentUtil.INTEGER_TYPE) { origArray[i] = ((Integer)(data[getCluster()[i]][column])).doubleValue(); } } QSort sortArray = new QSort(origArray); int[] sortedPrimaryIndices = sortArray.getOrigIndx(); for (int i = 0; i < sortedPrimaryIndices.length; i++) { sortedArray[i] = getCluster()[sortedPrimaryIndices[i]]; } } else if (obType == ExperimentUtil.STRING_TYPE) { SortableField[] sortFields = new SortableField[getCluster().length]; for (int i = 0; i < sortFields.length; i++) { int currIndex = getCluster()[i]; String currField = (String)(data[getCluster()[i]][column]); sortFields[i] = new SortableField(currIndex, currField); } Arrays.sort(sortFields); for (int i = 0; i < sortFields.length; i++) { sortedArray[i] = sortFields[i].getIndex(); } } if (!ascending) { sortedArray = reverse(sortedArray); } for (int i = 0; i < getSortedCluster().length; i++) { sortedIndices[i] = sortedArray[i]; } clusterTable.repaint(); clusterTable.removeRowSelectionInterval(0, clusterTable.getRowCount() - 1); } private class SortableField implements Comparable { private String field; private int index; SortableField(int index, String field) { this.index = index; this.field = field; } public int compareTo(Object other) { SortableField otherField = (SortableField)other; return this.field.compareTo(otherField.getField()); } public int getIndex() { return this.index; } public String getField() { return this.field; } } private static int getObjectType(Object obj) { int obType = -1; if (obj instanceof Boolean) { return ExperimentUtil.BOOLEAN_TYPE; } else if (obj instanceof Double) { return ExperimentUtil.DOUBLE_TYPE; } else if (obj instanceof Float) { return ExperimentUtil.FLOAT_TYPE; } else if (obj instanceof Integer) { return ExperimentUtil.INTEGER_TYPE; } else if (obj instanceof String) { return ExperimentUtil.STRING_TYPE; } else { return obType; } } /** * Synchronize content and header sizes. */ private void setMaxWidth(JComponent content, JComponent header) { int c_width = content.getPreferredSize().width; int h_width = header.getPreferredSize().width; if (c_width > h_width) { header.setPreferredSize(new Dimension(c_width, header.getPreferredSize().height)); } else { content.setPreferredSize(new Dimension(h_width, content.getPreferredSize().height)); } } /** * Launches a new <code>MultipleExperimentViewer</code> containing the current cluster */ public void launchNewSession(){ } public void launchNewSessionWithSelectedRows() { } public void copyCells(){ TransferHandler th = clusterTable.getTransferHandler(); if (th != null) { Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard(); th.exportToClipboard(clusterTable, cb, TransferHandler.COPY); } } public void sortInOrigOrder() { for (int i = 0; i < getSortedCluster().length; i++) { sortedIndices[i] = getCluster()[i]; } clusterTable.repaint(); clusterTable.clearSelection(); for (int i = 0; i < clusterModel.getColumnCount(); i++) sortedAscending[i] = false; } /** * Creates a popup menu. */ private JPopupMenu createJPopupMenu(Listener listener) { JPopupMenu popup = new JPopupMenu(); addMenuItems(popup, listener); return popup; } protected void addMenuItems(JPopupMenu menu, ActionListener listener) { JMenuItem menuItem; menu.addSeparator(); menuItem = new JMenuItem("Search...", GUIFactory.getIcon("ClusterInformationResult.gif")); menuItem.setActionCommand(SEARCH_CMD); menuItem.addActionListener(listener); menu.add(menuItem); menuItem.addActionListener(listener); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Copy", GUIFactory.getIcon("TableViewerResult.gif")); menuItem.setActionCommand(COPY_CMD); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem("Select all rows...", GUIFactory.getIcon("TableViewerResult.gif")); menuItem.setActionCommand(SELECT_ALL_CMD); menuItem.addActionListener(listener); menu.add(menuItem); menuItem.addActionListener(listener); menu.add(menuItem); menuItem = new JMenuItem("Clear all selections...", GUIFactory.getIcon("TableViewerResult.gif")); menuItem.setActionCommand(CLEAR_ALL_CMD); menuItem.addActionListener(listener); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Sort table in original gene order...", GUIFactory.getIcon("TableViewerResult.gif")); menuItem.setActionCommand(SORT_ORIG_ORDER_CMD); menuItem.addActionListener(listener); menu.add(menuItem); menu.addSeparator(); menuItem = new JMenuItem("Store Selection as Cluster"); menuItem.setActionCommand(STORE_CLUSTER_COMMAND); menuItem.addActionListener(listener); menu.add(menuItem); menu.addSeparator(); JMenu launchMenu = new JMenu("Open Viewer"); menuItem = new JMenuItem("Expression Image"); menuItem.setActionCommand(LAUNCH_EXPRESSION_IMAGE_COMMAND); menuItem.addActionListener(listener); launchMenu.add(menuItem); menuItem = new JMenuItem("Expression Chart"); menuItem.setActionCommand(LAUNCH_EXPRESSION_CHART_COMMAND); menuItem.addActionListener(listener); launchMenu.add(menuItem); menuItem = new JMenuItem("Centroid Graph"); menuItem.setActionCommand(LAUNCH_CENTROID_GRAPH_COMMAND); menuItem.addActionListener(listener); launchMenu.add(menuItem); menuItem = new JMenuItem("Expression Graph"); menuItem.setActionCommand(LAUNCH_EXPRESSION_GRAPH_COMMAND); menuItem.addActionListener(listener); launchMenu.add(menuItem); menuItem = new JMenuItem("Table Viewer"); menuItem.setActionCommand(TABLE_VIEW_COMMAND); menuItem.addActionListener(listener); launchMenu.add(menuItem); menu.add(launchMenu); menu.addSeparator(); menuItem = new JMenuItem("Save Table"); menuItem.setActionCommand(SAVE_TABLE_COMMAND); menuItem.addActionListener(listener); menu.add(menuItem); menu.addSeparator(); } /** Handles opening cluster viewers. */ protected void onOpenViewer(String viewerType){ int index = this.clusterTable.getSelectedRow(); if(index == -1 || rootNode==null) return; String nodeTitle = (String)clusterTable.getModel().getValueAt(index, 1); DefaultMutableTreeNode node = null; if(viewerType.equals("expression image")){ node = (DefaultMutableTreeNode)(rootNode.getChildAt(1+nodeOffset)); } else if(viewerType.equals("expression chart")){ node = (DefaultMutableTreeNode)(rootNode.getChildAt(2+nodeOffset)); } else if(viewerType.equals("centroid graph")){ node = (DefaultMutableTreeNode)(rootNode.getChildAt(3+nodeOffset)); } else if(viewerType.equals("expression graph")){ node = (DefaultMutableTreeNode)(rootNode.getChildAt(4+nodeOffset)); } else if(viewerType.equals("table view")){ node = (DefaultMutableTreeNode)(rootNode.getChildAt(5+nodeOffset)); } if(framework != null){ for (int i=0; i<node.getChildCount(); i++){ if ((((DefaultMutableTreeNode)node.getChildAt(i)).toString()).contains(nodeTitle)){ framework.setTreeNode((DefaultMutableTreeNode)node.getChildAt(i)); return; } } //check not enough genes node for (int i=0; i<rootNode.getChildCount(); i++){ if ("Not Enough Significant Genes".equals(((DefaultMutableTreeNode)rootNode.getChildAt(i)).toString())){ node = (DefaultMutableTreeNode)rootNode.getChildAt(i); for (int j=0; j<node.getChildCount(); j++){ if ((((DefaultMutableTreeNode)node.getChildAt(j)).toString()).contains(nodeTitle)){ framework.setTreeNode((DefaultMutableTreeNode)node.getChildAt(j)); return; } } } } } System.out.println("node '"+nodeTitle+"' not found."); } /** Saves the pvalues table to file */ protected void onSaveTable(){ JFileChooser chooser = new JFileChooser(TMEV.getFile("/Data")); String fileName = ""; if(chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION){ File file = chooser.getSelectedFile(); fileName = file.getName(); try{ PrintWriter pw = new PrintWriter(new FileOutputStream(file)); int rows = clusterTable.getRowCount(); int cols = clusterTable.getColumnCount(); for(int row = 0; row < rows; row++){ for(int col = 0; col < cols; col++){ pw.print(((String)(clusterTable.getValueAt(row, col))) + "\t"); } pw.print("\n"); } pw.flush(); pw.close(); } catch ( IOException ioe) { ioe.printStackTrace(); javax.swing.JOptionPane.showMessageDialog(null, ("Error Saving Table to file: "+fileName), "Output Error", JOptionPane.WARNING_MESSAGE); } } } /** * Handles the storage of selected rows from the * table. * */ protected void onStoreSelectedRows(){ int [] tableIndices = clusterTable.getSelectedRows(); if(tableIndices == null || tableIndices.length == 0||rootNode==null) return; for (int cluster=0; cluster<tableIndices.length; cluster++){ String nodeTitle = (String)clusterTable.getModel().getValueAt(tableIndices[cluster], 1); DefaultMutableTreeNode node = null; node = (DefaultMutableTreeNode)(rootNode.getChildAt(1+nodeOffset)); for (int i=0; i<node.getChildCount(); i++){ if (nodeTitle.equals(((DefaultMutableTreeNode)node.getChildAt(i)).toString())){ ExperimentViewer ev = (ExperimentViewer)((LeafInfo)((DefaultMutableTreeNode)node.getChildAt(i)).getUserObject()).getViewer(); ev.storeCluster(); break; } } } } /** * The class to listen to mouse and action events. */ private class Listener extends MouseAdapter implements ActionListener { public void actionPerformed(ActionEvent e) { String command = e.getActionCommand(); if(command.equals(LAUNCH_NEW_SESSION_WITH_SEL_ROWS_CMD)){ } else if (command.equals(SEARCH_CMD)) { } else if (command.equals(CLEAR_ALL_CMD)) { } else if (command.equals(COPY_CMD)) { copyCells(); } else if (command.equals(SELECT_ALL_CMD)) { clusterTable.selectAll(); } else if (command.equals(SORT_ORIG_ORDER_CMD)) { sortInOrigOrder(); } else if (command.equals(BROADCAST_MATRIX_GAGGLE_CMD)) { } else if (command.equals(BROADCAST_SELECTED_MATRIX_GAGGLE_CMD)) { } else if (command.equals(BROADCAST_NAMELIST_GAGGLE_CMD)) { } else if (command.equals(BROADCAST_MATRIX_GENOME_BROWSER_CMD)) { } else if(command.equals(STORE_CLUSTER_COMMAND)){ onStoreSelectedRows(); } else if(command.equals(CLEAR_ALL_COMMAND)){ clusterTable.clearSelection(); } else if(command.equals(SELECT_ALL_COMMAND)){ clusterTable.selectAll(); } else if(command.equals(LAUNCH_EXPRESSION_IMAGE_COMMAND)){ onOpenViewer("expression image"); } else if(command.equals(LAUNCH_EXPRESSION_CHART_COMMAND)){ onOpenViewer("expression chart"); } else if(command.equals(LAUNCH_CENTROID_GRAPH_COMMAND)){ onOpenViewer("centroid graph"); } else if(command.equals(LAUNCH_EXPRESSION_GRAPH_COMMAND)){ onOpenViewer("expression graph"); } else if(command.equals(TABLE_VIEW_COMMAND)){ onOpenViewer("table view"); } else if(command.equals(SAVE_TABLE_COMMAND)){ onSaveTable(); } } public void mouseReleased(MouseEvent event) { maybeShowPopup(event); } public void mousePressed(MouseEvent event) { maybeShowPopup(event); } // /** Creates the context menu // * @return */ // protected JPopupMenu createPopupMenu(){ // Listener listener = new Listener(); // JPopupMenu menu = new JPopupMenu(); // JMenuItem menuItem; // // // // // return menu; // } private void maybeShowPopup(MouseEvent e) { if (!e.isPopupTrigger() || getCluster() == null || getCluster().length == 0) { return; } popup.show(e.getComponent(), e.getX(), e.getY()); } } /** Returns int value indicating viewer type * Cluster.GENE_CLUSTER, Cluster.EXPERIMENT_CLUSTER, or -1 for both or unspecified */ public int getViewerType() { return -1; } protected void broadcastClusterGaggle() { } protected void broadcastSelectedClusterGaggle() { } protected void broadcastNamelistGaggle() { } public void broadcastGeneClusterToGenomeBrowser() { } }
true
71049648039e7c801e846d2d9eac20fca14da450
Java
yamato8/Android
/SimpleLoggerGps/src/com/example/simpleloggergps/SettingPreferenceActivity.java
UTF-8
3,523
2.265625
2
[]
no_license
package com.example.simpleloggergps; import android.annotation.TargetApi; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.util.Log; import android.view.Menu; public class SettingPreferenceActivity extends PreferenceActivity implements OnSharedPreferenceChangeListener { private static final String TAG = "";// 8 private SummarySetting summarySetting11; private boolean virsionFlag; //(11) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, "onCreate"); // version3.0 より前 <11 if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) { virsionFlag = true; Log.i(TAG, "3.0より前"); PriorToo11(); } else { // version3.0 以降 virsionFlag = false; Log.i(TAG, "以降"); than11(); } } @SuppressWarnings("deprecation") @Override protected void onResume() { super.onResume(); if( virsionFlag ){ getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener( this ); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } /* * 13以前 */ @SuppressWarnings("deprecation") private void PriorToo11() { // TODO 自動生成されたメソッド・スタブ addPreferencesFromResource(R.xml.setting_preference); summarySetting11 = new SummarySetting(); summarySetting11.printOut(getPreferenceScreen()); } @TargetApi(11) private void than11() { // TODO 自動生成されたメソッド・スタブ getFragmentManager().beginTransaction().replace(android.R.id.content, new prefFragment()).commit(); } @TargetApi(11) public static class prefFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { private SummarySetting summarySetting; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.setting_preference); //Preference exercisesPref = findPreference("transmit"); //exercisesPref.setSummary(R.string.hello_world); summarySetting = new SummarySetting(); //com.example.simpleloggergps.Pref.this.summarySetting(); //summarySetting.printOut(); try{ summarySetting.printOut( getPreferenceScreen() ); }catch(Exception e){ Log.e("Hello", "例外出力", e); } } @Override public void onResume() { super.onResume(); getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this); } /* * 概要:設定値が変更された時の処理 */ @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO 自動生成されたメソッド・スタブ summarySetting.printOut( getPreferenceScreen() ); } } // 11 以前のリスナー @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { // TODO 自動生成されたメソッド・スタブ summarySetting11.printOut( getPreferenceScreen() ); } }
true
91e56aac09baff1fa19745bc05236553acf37107
Java
DylanRedfield/SPFPE
/app/src/main/java/me/dylanredfield/spfpe/ui/ClassListAdapter.java
UTF-8
1,829
2.28125
2
[]
no_license
package me.dylanredfield.spfpe.ui; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.parse.ParseObject; import java.util.ArrayList; import java.util.List; import me.dylanredfield.spfpe.R; import me.dylanredfield.spfpe.fragment.teacher.ClassListFragment; import me.dylanredfield.spfpe.util.Keys; public class ClassListAdapter extends BaseAdapter { private List<ParseObject> mClassList = new ArrayList<>(); private ClassListFragment mFragment; @Override public int getCount() { return mClassList.size(); } @Override public Object getItem(int i) { return mClassList.get(i); } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { if (view == null) { view = mFragment.getActivity().getLayoutInflater().inflate(R.layout.row_two_line, null, false); } TextView topLine = (TextView) view.findViewById(R.id.bottom_line); //topLine.setText(Helpers.getTeacherName(mClassList.get(i).getParseObject(Keys.TEACHER_POINT))); TextView bottomLine = (TextView) view.findViewById(R.id.top_line); topLine.setText("MP" + mClassList.get(i).getInt(Keys.MARKING_PERIOD_NUM) + "," + " Period: " + mClassList.get(i).getParseObject(Keys.PERIOD_POINT).getString(Keys.PERIOD_NAME_STR)); bottomLine.setText(mClassList.get(i).getParseObject(Keys.SCHOOL_YEAR_POINT).getString(Keys.YEAR_STR)); return view; } public ClassListAdapter(ClassListFragment fragment) { mFragment = fragment; } public void setList(List<ParseObject> list) { mClassList = list; notifyDataSetChanged(); } }
true
f9584bc9f22d8c8edcacc33562d30e5f58a961f9
Java
rajneeshgautam75/Z_Project
/src/main/java/com/zephyr_batch_2/stepdefinition/Create_Cycle_868155.java
UTF-8
53,580
1.859375
2
[]
no_license
package com.zephyr_batch_2.stepdefinition; import org.testng.asserts.SoftAssert; import com.zephyr.common.LaunchBrowser; import com.zephyr.generic.Excel_Lib; import com.zephyr.generic.Property_Lib; import com.zephyr.reusablemethods.BasePage; import com.zephyr.reusablemethods.CreateTestCasePage; import com.zephyr.reusablemethods.ExecutionPage; import com.zephyr.reusablemethods.ExportPage; import com.zephyr.reusablemethods.LoginPage; import com.zephyr.reusablemethods.ProjectPage; import com.zephyr.reusablemethods.ReleasePage; import com.zephyr.reusablemethods.TestPlanningPage; import com.zephyr.reusablemethods.TestRepositoryPage; import cucumber.api.java.en.Given; import cucumber.api.java.en.Then; import cucumber.api.java.en.When; public class Create_Cycle_868155 extends LaunchBrowser { LaunchBrowser lb; LoginPage lp; ProjectPage pp; ReleasePage rp; TestRepositoryPage tr; ExportPage ep; BasePage bp; CreateTestCasePage ctc; TestPlanningPage tp; ExecutionPage exep; boolean[] actual=new boolean[191]; SoftAssert soft=new SoftAssert(); String fileName="Create_Cycle_868155"; @Given("^User is in a page of an test repository$") public void user_is_in_a_page_of_an_test_repository() throws Throwable { try { lb=new LaunchBrowser(); pp=new ProjectPage(driver); String projectName=Property_Lib.getPropertyValue(CONFIG_PATH+CONFIG_FILE_TPE,"Normal_Project_1"); String releaseName=Excel_Lib.getData(INPUT_PATH_3,"Releases",6,0); actual[0]=pp.selectProject(projectName); actual[1]=pp.selectRelease(releaseName); rp= new ReleasePage(driver); actual[2]=rp.clickOnTestRep(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @Given("^User Creates a Phase and creates a testcase under the phase$") public void user_Creates_a_Phase_and_creates_a_testcase_under_the_phase() throws Throwable { try { String releaseName=Excel_Lib.getData(INPUT_PATH_3, "Releases", 6, 0); String p_Name1=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 7); String p_Desc1=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 14, 15); tr=new TestRepositoryPage(driver); bp=new BasePage(); bp.waitForElement(); actual[3]=tr.doubleClickOnRelease(releaseName); // bp.waitForElement(); bp.waitForElement(); actual[4]= tr.addNode(p_Name1,p_Desc1); tr.doubleClickOnRelease(releaseName); String[] phase=new String[1]; phase[0]=p_Name1; tr.navigateToNode(releaseName, phase); bp.waitForElement(); actual[5]=tr.addTestCase(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @Given("^User performs the edit operation for the testcase$") public void user_performs_the_edit_operation_for_the_testcase() throws Throwable { try { tr=new TestRepositoryPage(driver); bp.waitForElement(); bp.waitForElement(); actual[6]=tr.clickDetailButton(); ctc=new CreateTestCasePage(driver); String tcName=Excel_Lib.getData(INPUT_PATH_3, "TestCases", 1, 0); String tcDesc=Excel_Lib.getData(INPUT_PATH_3,"TestCases" , 2, 0); actual[7]=ctc.enterTestCaseNameAndDesc(tcName, tcDesc); bp.waitForElement(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @Given("^User enters the step details and save$") public void user_enters_the_step_details_and_save() throws Throwable { try { String[] stepDetail=new String[9]; stepDetail[0]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 1, 0); stepDetail[1]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 1, 1); stepDetail[2]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 1, 2); stepDetail[3]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 2, 0); stepDetail[4]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 2, 1); stepDetail[5]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 2, 2); stepDetail[6]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 2, 0); stepDetail[7]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 2, 1); stepDetail[8]=Excel_Lib.getData(INPUT_PATH_3, "StepDetails", 2, 2); ctc=new CreateTestCasePage(driver); bp.waitForElement(); actual[8]=ctc.enterTestCaseStepDetail(stepDetail); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @Given("^User performs the clone operation of a testcase$") public void user_performs_the_clone_operation_of_a_testcase() throws Throwable { try { tr=new TestRepositoryPage(driver); bp.waitForElement(); bp.waitForElement(); actual[9]=tr.clickOnList(); bp.waitForElement(); actual[10]=tr.selectallTestCase(); bp.waitForElement(); actual[11]=tr.cloneTestCase(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a cycle in TestPlanning and enters the available fields$") public void user_creates_a_cycle_in_TestPlanning_and_enters_the_available_fields() throws Throwable { try { bp.waitForElement(); rp= new ReleasePage(driver); bp.waitForElement(); actual[12]=rp.clickOnTestPlanning(); bp=new BasePage(); tp=new TestPlanningPage(driver); //String[] str=new String[4]; String cycle=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 6); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 2, 0); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 3, 0); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 100, 100); tp.clickOnAddTestCycleSymbol(); bp.waitForElement(); bp.waitForElement(); actual[13]=tp.CreateCycle(cycle, Build, environ, hide); String syear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 23)); String smonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 10, 22); String sday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 21)); String eyear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 26)); String emonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 8, 25); String eday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 24)); bp.waitForElement(); actual[14]=tp.enterStartDatAndEndDate(syear, smonth, sday, eyear, emonth, eday); bp.waitForElement(); actual[15]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a phase by choosing an existing Phase and save$") public void user_creates_a_phase_by_choosing_an_existing_Phase_and_save() throws Throwable { try { String[] cycle=new String[1]; cycle[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 6); bp.waitForElement(); actual[16]=tp.navigateToCycle(cycle); String phase=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 7); bp.waitForElement(); actual[17]=tp.addPhaseToCycle(phase); String Bulk_Type=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[18]=tp.bulkAssignment(Bulk_Type); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User individually assigns the testcase to anyone$") public void user_individually_assigns_the_testcase_to_anyone() throws Throwable { try { String[] phaseName=new String[1]; phaseName[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",1 ,7 ); bp.waitForElement(); actual[19]=tp.navigateToCycle(phaseName); int[] TestCaseNo=new int[1]; TestCaseNo[0]=Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning",1 ,8); String Assignee=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",6 ,9 ); bp.waitForElement(); actual[20]=tp.individualAssinTo(TestCaseNo, Assignee); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User navigates to testPlanning and selects a cycle and clicks edit and check hide button$") public void user_navigates_to_testPlanning_and_selects_a_cycle_and_clicks_edit_and_check_hide_button() throws Throwable { try { tp.goBackToCycle(); bp.waitForElement(); actual[21]=rp.clickOnTestPlanning(); String[] cycleName=new String[1]; cycleName[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",1 ,6 ); bp.waitForElement(); actual[22]=tp.navigateToCycle(cycleName); String cycle=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",1 ,27 ); bp.waitForElement(); bp.waitForElement(); actual[23]=tp.editCycle(cycle, Build, environ, hide); bp.waitForElement(); actual[24]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a phase and creates a testcase and performs the edit operation$") public void user_creates_a_phase_and_creates_a_testcase_and_performs_the_edit_operation() throws Throwable { try { rp= new ReleasePage(driver); bp.waitForElement(); actual[25]=rp.clickOnTestRep(); String releaseName=Excel_Lib.getData(INPUT_PATH_3, "Releases", 6, 0); String p_Name2=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 7); String p_Desc2=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 14, 15); tr=new TestRepositoryPage(driver); bp=new BasePage(); bp.waitForElement(); actual[26]=tr.doubleClickOnRelease(releaseName); // bp.waitForElement(); bp.waitForElement(); actual[27]= tr.addNode(p_Name2,p_Desc2); tr.doubleClickOnRelease(releaseName); String[] phase2=new String[1]; phase2[0]=p_Name2; tr.navigateToNode(releaseName, phase2); bp.waitForElement(); actual[28]=tr.addTestCase(); bp.waitForElement(); actual[29]=tr.clickDetailButton(); ctc=new CreateTestCasePage(driver); String tcName=Excel_Lib.getData(INPUT_PATH_3, "TestCases", 1, 0); String tcDesc=Excel_Lib.getData(INPUT_PATH_3,"TestCases" , 2, 0); actual[30]=ctc.enterTestCaseNameAndDesc(tcName, tcDesc); bp.waitForElement(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User performs the clone operation for the testcase$") public void user_performs_the_clone_operation_for_the_testcase() throws Throwable { try { tr=new TestRepositoryPage(driver); bp.waitForElement(); bp.waitForElement(); actual[31]=tr.clickOnList(); bp.waitForElement(); actual[32]=tr.selectallTestCase(); bp.waitForElement(); actual[33]=tr.cloneTestCase(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a second cycle and enters the available fields and save$") public void user_creates_a_second_cycle_and_enters_the_available_fields_and_save() throws Throwable { try { bp.waitForElement(); rp= new ReleasePage(driver); bp.waitForElement(); actual[34]=rp.clickOnTestPlanning(); bp=new BasePage(); tp=new TestPlanningPage(driver); //String[] str=new String[4]; String cycle=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 6); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 2, 0); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 3, 0); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 100, 100); actual[35]=tp.clickOnAddTestCycleSymbol(); bp.waitForElement(); bp.waitForElement(); actual[36]=tp.CreateCycle(cycle, Build, environ, hide); String syear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 23)); String smonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 10, 22); String sday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 21)); String eyear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 26)); String emonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 8, 25); String eday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 24)); bp.waitForElement(); actual[37]=tp.enterStartDatAndEndDate(syear, smonth, sday, eyear, emonth, eday); bp.waitForElement(); actual[38]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a phase by choosing an existing phase and click on save$") public void user_creates_a_phase_by_choosing_an_existing_phase_and_click_on_save() throws Throwable { try { String[] cycle=new String[1]; cycle[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 6); actual[39]=tp.navigateToCycle(cycle); String phase=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 7); bp.waitForElement(); actual[40]=tp.addPhaseToCycle(phase); /*String Bulk_Type=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[41]=tp.bulkAssignment(Bulk_Type);*/ } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User cancels the bulk assignment popup$") public void user_cancels_the_bulk_assignment_popup() throws Throwable { try { bp.waitForElement(); actual[41]=tp.cancelBulkAssign(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User selects few testcases and assigns to anyone$") public void user_selects_few_testcases_and_assigns_to_anyone() throws Throwable { try { String[] phaseName=new String[1]; phaseName[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",2 ,7 ); //cycleName[1]=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",6 ,0 ); bp.waitForElement(); bp.waitForElement(); actual[42]=tp.navigateToCycle(phaseName); bp.waitForElement(); bp.waitForElement(); int tcNo[]=new int[2]; tcNo[0]=Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning",1 ,8 ); tcNo[1]=Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning",2 ,8 ); bp.waitForElement(); actual[43]=tp.selectSingleMultipleTestcase(tcNo); bp.waitForElement(); String assignee=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",6 ,9 ); actual[44]=tp.assignAllSelected(assignee); tp.goBackToCycle(); // rp.clickOnTestPlanning(); //////tp.navigateBacktoTestPlanning(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User is in a page TestExecution and execute few testcases by selecting status drop down$") public void user_is_in_a_page_TestExecution_and_execute_few_testcases_by_selecting_status_drop_down() throws Throwable { try { bp.waitForElement(); rp= new ReleasePage(driver); bp.waitForElement(); actual[45]=rp.clickOnTestExecution(); String[] cycleName=new String[3]; cycleName[0]=Excel_Lib.getData(INPUT_PATH_3, "Releases",6 ,0 ); cycleName[1]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",2 ,6 ); cycleName[2]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",2 ,7 ); bp.waitForElement(); tp=new TestPlanningPage(driver); bp.waitForElement(); bp.waitForElement(); bp.waitForElement(); // bp.waitForElement(); actual[46]=tp.navigateToCycle(cycleName); bp.waitForElement(); /*int[] testCaseNo=new int[1]; ; testCaseNo[0]=Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning",1 ,5 ); tp.selectSingleMultipleTestcase(testCaseNo);*/ //status selection method should be implement here int[] tcNo1=new int[1]; tcNo1[0]=Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning",1 ,19 ); String statusType1=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",1 ,18 ); bp.waitForElement(); bp.waitForElement(); exep=new ExecutionPage(driver); actual[47]=exep.executeStatus(tcNo1[0], statusType1); int[] tcNo2=new int[1]; tcNo2[0]=Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning",2 ,19 ); String statusType2=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",1 ,18 ); bp.waitForElement(); bp.waitForElement(); exep=new ExecutionPage(driver); actual[48]=exep.executeStatus(tcNo2[0], statusType2); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User navigates to TestPlanning and selects second cycle and select edit and check hide option and save$") public void user_navigates_to_TestPlanning_and_selects_second_cycle_and_select_edit_and_check_hide_option_and_save() throws Throwable { try { bp.waitForElement(); actual[49]=rp.clickOnTestPlanning(); String[] cycleName=new String[1]; cycleName[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",2 ,6 ); actual[50]=tp.navigateToCycle(cycleName); String cycle=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",2 ,6 ); String Build=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",2 ,0 ); String environ=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",3 ,0 ); String hide=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",1 ,27 ); bp.waitForElement(); bp.waitForElement(); actual[51]=tp.editCycle(cycle, Build, environ, hide); bp.waitForElement(); actual[52]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a twenty phases with few testcases each phase$") public void user_creates_a_twenty_phases_with_few_testcases_each_phase() throws Throwable { try { bp.waitForElement(); bp.waitForElement(); actual[53]=rp.clickOnTestRep(); String releaseName=Excel_Lib.getData(INPUT_PATH_3, "Releases", 6, 0); String p_Name1=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 0); String p_Desc1=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 1); tr=new TestRepositoryPage(driver); bp=new BasePage(); bp.waitForElement(); actual[54]=tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[55]= tr.addNode(p_Name1,p_Desc1); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[56]=tr.selectPhase(p_Name1); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name2=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 0); String p_Desc2=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 1); actual[57]=tr.addNode(p_Name2, p_Desc2); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[58]=tr.selectPhase(p_Name2); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); String p_Name3=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 0); String p_Desc3=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 1); actual[59]=tr.addNode(p_Name3, p_Desc3); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[60]=tr.selectPhase(p_Name3); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name4=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 0); String p_Desc4=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 1); actual[61]=tr.addNode(p_Name4, p_Desc4); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[62]=tr.selectPhase(p_Name4); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name5=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 5, 0); String p_Desc5=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 5, 1); actual[63]=tr.addNode(p_Name5, p_Desc5); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[64]=tr.selectPhase(p_Name5); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name6=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 6, 0); String p_Desc6=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 6, 1); actual[65]=tr.addNode(p_Name6, p_Desc6); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[66]=tr.selectPhase(p_Name6); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name7=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 7, 0); String p_Desc7=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 7, 1); actual[67]=tr.addNode(p_Name7, p_Desc7); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[68]=tr.selectPhase(p_Name7); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name8=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 8, 0); String p_Desc8=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 8, 1); actual[69]=tr.addNode(p_Name8, p_Desc8); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[70]=tr.selectPhase(p_Name8); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name9=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 9, 0); String p_Desc9=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 9, 1); actual[71]=tr.addNode(p_Name9, p_Desc9); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[72]=tr.selectPhase(p_Name9); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name10=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 10, 0); String p_Desc10=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 10, 1); actual[73]=tr.addNode(p_Name10, p_Desc10); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[74]=tr.selectPhase(p_Name10); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name11=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 11, 0); String p_Desc11=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 11, 1); actual[75]=tr.addNode(p_Name11, p_Desc11); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[76]=tr.selectPhase(p_Name11); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name12=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 12, 0); String p_Desc12=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 12, 1); actual[77]=tr.addNode(p_Name12, p_Desc12); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[78]=tr.selectPhase(p_Name12); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name13=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 13, 0); String p_Desc13=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 13, 1); actual[79]=tr.addNode(p_Name13, p_Desc13); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[80]=tr.selectPhase(p_Name13); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name14=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 14, 0); String p_Desc14=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 14, 1); actual[81]=tr.addNode(p_Name14, p_Desc14); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[82]=tr.selectPhase(p_Name14); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name15=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 15, 0); String p_Desc15=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 15, 1); actual[83]=tr.addNode(p_Name15, p_Desc15); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[84]=tr.selectPhase(p_Name15); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name16=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 16, 0); String p_Desc16=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 16, 1); actual[85]=tr.addNode(p_Name16, p_Desc16); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[86]=tr.selectPhase(p_Name16); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name17=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 17, 0); String p_Desc17=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 17, 1); actual[87]=tr.addNode(p_Name17, p_Desc17); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[88]=tr.selectPhase(p_Name17); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name18=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 18, 0); String p_Desc18=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 18, 1); actual[89]=tr.addNode(p_Name18, p_Desc18); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[90]=tr.selectPhase(p_Name18); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name19=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 19, 0); String p_Desc19=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 19, 1); actual[91]=tr.addNode(p_Name19, p_Desc19); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[92]=tr.selectPhase(p_Name19); tr.addTestCase(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); String p_Name20=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 20, 0); String p_Desc20=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 20, 1); actual[93]=tr.addNode(p_Name20, p_Desc20); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); bp.waitForElement(); actual[94]=tr.selectPhase(p_Name20); tr.addTestCase(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a third cycle with all the available fields and save$") public void user_creates_a_third_cycle_with_all_the_available_fields_and_save() throws Throwable { try { bp.waitForElement(); actual[95]=rp.clickOnTestPlanning(); bp=new BasePage(); tp=new TestPlanningPage(driver); //String[] str=new String[4]; String cycle=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 2, 0); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 3, 0); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 100, 100); actual[96]=tp.clickOnAddTestCycleSymbol(); bp.waitForElement(); bp.waitForElement(); actual[97]=tp.CreateCycle(cycle, Build, environ, hide); String syear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 23)); String smonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 10, 22); String sday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 21)); String eyear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 26)); String emonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 8, 25); String eday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 24)); bp.waitForElement(); actual[98]=tp.enterStartDatAndEndDate(syear, smonth, sday, eyear, emonth, eday); bp.waitForElement(); actual[99]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a twenty phases by choosing an existing phases$") public void user_creates_a_twenty_phases_by_choosing_an_existing_phases() throws Throwable { try { String[] cycle1=new String[1]; cycle1[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[100]=tp.navigateToCycle(cycle1); String phase1=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 0); bp.waitForElement(); actual[101]=tp.addPhaseToCycle(phase1); String Bulk_Type1=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[102]=tp.bulkAssignment(Bulk_Type1); bp.waitForElement(); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); //////tp.navigateBacktoTestPlanning(); String[] cycle2=new String[1]; cycle2[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[103]=tp.navigateToCycle(cycle2); String phase2=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 0); bp.waitForElement(); actual[104]=tp.addPhaseToCycle(phase2); String Bulk_Type2=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[105]=tp.bulkAssignment(Bulk_Type2); bp.waitForElement(); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); //////tp.navigateBacktoTestPlanning(); String[] cycle3=new String[1]; cycle3[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[106]=tp.navigateToCycle(cycle3); String phase3=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 0); bp.waitForElement(); actual[107]=tp.addPhaseToCycle(phase3); String Bulk_Type3=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[108]=tp.bulkAssignment(Bulk_Type3); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); //////tp.navigateBacktoTestPlanning(); String[] cycle4=new String[1]; cycle4[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[109]=tp.navigateToCycle(cycle4); String phase4=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 0); bp.waitForElement(); actual[110]=tp.addPhaseToCycle(phase4); String Bulk_Type4=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[111]=tp.bulkAssignment(Bulk_Type4); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); //////tp.navigateBacktoTestPlanning(); String[] cycle5=new String[1]; cycle5[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[112]=tp.navigateToCycle(cycle5); String phase5=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 5, 0); bp.waitForElement(); bp.waitForElement(); actual[113]=tp.addPhaseToCycle(phase5); String Bulk_Type5=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[114]=tp.bulkAssignment(Bulk_Type5); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); //////tp.navigateBacktoTestPlanning(); String[] cycle6=new String[1]; cycle6[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[115]=tp.navigateToCycle(cycle6); String phase6=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 6, 0); bp.waitForElement(); actual[116]=tp.addPhaseToCycle(phase6); String Bulk_Type6=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[117]=tp.bulkAssignment(Bulk_Type6); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle7=new String[1]; cycle7[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[118]=tp.navigateToCycle(cycle7); String phase7=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 7, 0); bp.waitForElement(); actual[119]=tp.addPhaseToCycle(phase7); String Bulk_Type7=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[120]=tp.bulkAssignment(Bulk_Type7); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle8=new String[1]; cycle8[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[121]=tp.navigateToCycle(cycle8); String phase8=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 8, 0); bp.waitForElement(); actual[122]=tp.addPhaseToCycle(phase8); String Bulk_Type8=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[123]=tp.bulkAssignment(Bulk_Type8); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle9=new String[1]; cycle9[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[124]=tp.navigateToCycle(cycle9); String phase9=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 9, 0); bp.waitForElement(); actual[125]=tp.addPhaseToCycle(phase9); String Bulk_Type9=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[126]=tp.bulkAssignment(Bulk_Type9); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle10=new String[1]; cycle10[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[127]=tp.navigateToCycle(cycle10); String phase10=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 10, 0); bp.waitForElement(); actual[128]=tp.addPhaseToCycle(phase10); String Bulk_Type10=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[129]=tp.bulkAssignment(Bulk_Type10); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle11=new String[1]; cycle11[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[130]=tp.navigateToCycle(cycle11); String phase11=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 11, 0); bp.waitForElement(); actual[131]=tp.addPhaseToCycle(phase11); String Bulk_Type11=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[132]=tp.bulkAssignment(Bulk_Type11); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle12=new String[1]; cycle12[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[133]=tp.navigateToCycle(cycle12); String phase12=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 12, 0); bp.waitForElement(); actual[134]=tp.addPhaseToCycle(phase12); String Bulk_Type12=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[135]=tp.bulkAssignment(Bulk_Type12); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle13=new String[1]; cycle13[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[136]=tp.navigateToCycle(cycle13); String phase13=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 13, 0); bp.waitForElement(); actual[137]=tp.addPhaseToCycle(phase13); String Bulk_Type13=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[138]=tp.bulkAssignment(Bulk_Type13); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle14=new String[1]; cycle14[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[139]=tp.navigateToCycle(cycle14); String phase14=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 14, 0); bp.waitForElement(); actual[140]=tp.addPhaseToCycle(phase14); String Bulk_Type14=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[141]=tp.bulkAssignment(Bulk_Type14); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle15=new String[1]; cycle15[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[142]=tp.navigateToCycle(cycle15); String phase15=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 15, 0); bp.waitForElement(); actual[143]=tp.addPhaseToCycle(phase15); String Bulk_Type15=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[144]=tp.bulkAssignment(Bulk_Type15); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle16=new String[1]; cycle16[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[145]=tp.navigateToCycle(cycle16); String phase16=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 16, 0); bp.waitForElement(); actual[146]=tp.addPhaseToCycle(phase16); String Bulk_Type16=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[147]=tp.bulkAssignment(Bulk_Type16); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle17=new String[1]; cycle17[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[148]=tp.navigateToCycle(cycle17); String phase17=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 17, 0); bp.waitForElement(); actual[149]=tp.addPhaseToCycle(phase17); String Bulk_Type17=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[150]=tp.bulkAssignment(Bulk_Type17); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle18=new String[1]; cycle18[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[151]=tp.navigateToCycle(cycle18); String phase18=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 18, 0); bp.waitForElement(); actual[152]=tp.addPhaseToCycle(phase18); String Bulk_Type18=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[153]=tp.bulkAssignment(Bulk_Type18); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle19=new String[1]; cycle19[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[154]=tp.navigateToCycle(cycle19); String phase19=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 19, 0); bp.waitForElement(); actual[155]=tp.addPhaseToCycle(phase19); String Bulk_Type19=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[156]=tp.bulkAssignment(Bulk_Type19); tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycle20=new String[1]; cycle20[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 6); actual[157]=tp.navigateToCycle(cycle20); String phase20=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 20, 0); bp.waitForElement(); actual[158]=tp.addPhaseToCycle(phase20); String Bulk_Type20=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[159]=tp.bulkAssignment(Bulk_Type20); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User navigates to TestPlanning and selects third cycle and select edit and check hide$") public void user_navigates_to_TestPlanning_and_selects_third_cycle_and_select_edit_and_check_hide() throws Throwable { try { tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycleName=new String[1]; cycleName[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",3 ,6 ); actual[160]=tp.navigateToCycle(cycleName); String cycle=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",1 ,27 ); bp.waitForElement(); bp.waitForElement(); actual[161]=tp.editCycle(cycle, Build, environ, hide); bp.waitForElement(); bp.waitForElement(); actual[162]=tp.saveTestCycle(); bp.waitForElement(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a phase within a phase upto (\\d+)th leavel$") public void user_creates_a_phase_within_a_phase_upto_th_leavel(int arg1) throws Throwable { try { bp.waitForElement(); driver.navigate().refresh(); bp.waitForElement(); bp.waitForElement(); bp.waitForElement(); //rp=new ReleasePage(driver); actual[163]=rp.clickOnTestRep(); String releaseName=Excel_Lib.getData(INPUT_PATH_3, "Releases", 6, 0); String p_Name1=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 3); String p_Desc1=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 4); tr=new TestRepositoryPage(driver); bp=new BasePage(); bp.waitForElement(); actual[164]=tr.doubleClickOnRelease(releaseName); // bp.waitForElement(); bp.waitForElement(); actual[165]= tr.addNode(p_Name1,p_Desc1); //tr.doubleClickOnRelease(releaseName); /*String[] phase=new String[1]; phase[0]=p_Name1; tr.navigateToNode(releaseName, phase); tr.doubleClickOnRelease(releaseName);*/ bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[166]=tr.selectPhase(p_Name1); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name2=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 3); String p_Desc2=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 2, 4); actual[167]=tr.addNode(p_Name2, p_Desc2); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[168]=tr.selectPhase(p_Name2); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name3=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 3); String p_Desc3=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 3, 4); actual[169]=tr.addNode(p_Name3, p_Desc3); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[170]=tr.selectPhase(p_Name3); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name4=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 3); String p_Desc4=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 4); actual[171]=tr.addNode(p_Name4, p_Desc4); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[172]=tr.selectPhase(p_Name4); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name5=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 5, 3); String p_Desc5=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 5, 4); actual[173]=tr.addNode(p_Name5, p_Desc5); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[174]=tr.selectPhase(p_Name5); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name6=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 6, 3); String p_Desc6=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 6, 4); actual[175]=tr.addNode(p_Name6, p_Desc6); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[176]=tr.selectPhase(p_Name6); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name7=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 7, 3); String p_Desc7=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 7, 4); actual[177]=tr.addNode(p_Name7, p_Desc7); tr.doubleClickOnRelease(releaseName); actual[178]=tr.selectPhase(p_Name7); tr.addTestCase(); tr.clickOnRelease(releaseName); String p_Name8=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 8, 3); String p_Desc8=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 8, 4); actual[179]=tr.addNode(p_Name8, p_Desc8); bp.waitForElement(); tr.doubleClickOnRelease(releaseName); actual[180]=tr.selectPhase(p_Name8); tr.addTestCase(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a cycle with all the available fields and save$") public void user_creates_a_cycle_with_all_the_available_fields_and_save() throws Throwable { try { bp.waitForElement(); rp.clickOnTestPlanning(); bp=new BasePage(); tp=new TestPlanningPage(driver); //String[] str=new String[4]; String cycle=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 6); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 2, 0); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 3, 0); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 100, 100); actual[181]=tp.clickOnAddTestCycleSymbol(); bp.waitForElement(); bp.waitForElement(); actual[182]=tp.CreateCycle(cycle, Build, environ, hide); String syear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 23)); String smonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 10, 22); String sday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 21)); String eyear=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 26)); String emonth=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning", 8, 25); String eday=Integer.toString(Excel_Lib.getNumberData(INPUT_PATH_3, "TestPlanning", 1, 24)); bp.waitForElement(); actual[183]=tp.enterStartDatAndEndDate(syear, smonth, sday, eyear, emonth, eday); bp.waitForElement(); actual[184]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User creates a phase by choosing an existing phase with upto (\\d+)th level$") public void user_creates_a_phase_by_choosing_an_existing_phase_with_upto_th_level(int arg1) throws Throwable { try { String[] cycle=new String[1]; cycle[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 4, 6); actual[185]=tp.navigateToCycle(cycle); String phase=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155", 1, 3); bp.waitForElement(); actual[186]=tp.addPhaseToCycle(phase); String Bulk_Type=Excel_Lib.getData(INPUT_PATH_3, "BulkAssignment", 1, 0); bp.waitForElement(); actual[187]=tp.bulkAssignment(Bulk_Type); } catch(Exception e) { e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @When("^User navigates to TestPlanning and selects a third cycle and select edit and check hide and save$") public void user_navigates_to_TestPlanning_and_selects_a_third_cycle_and_select_edit_and_check_hide_and_save() throws Throwable { try { tp.goBackToCycle(); bp.waitForElement(); rp.clickOnTestPlanning(); ////tp.navigateBacktoTestPlanning(); String[] cycleName=new String[1]; cycleName[0]=UNIQUE+Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",3 ,6 ); actual[188]=tp.navigateToCycle(cycleName); String cycle=Excel_Lib.getData(INPUT_PATH_3, "CreateCycle_868155",100 ,100 ); String Build=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String environ=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",100 ,100 ); String hide=Excel_Lib.getData(INPUT_PATH_3, "TestPlanning",1 ,27 ); bp.waitForElement(); bp.waitForElement(); actual[189]=tp.editCycle(cycle, Build, environ, hide); bp.waitForElement(); actual[190]=tp.saveTestCycle(); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } @Then("^User successfully edit and hidden a cycle$") public void user_successfully_edit_and_hidden_a_cycle() throws Throwable { try { for(int k=0;k<=actual.length-1;k++) { System.out.println(actual[k]); soft.assertEquals(actual[k], true); } soft.assertAll(); log.info("User successfully edit and hidden a cycle"); } catch(Exception e) { lb.getScreenShot(fileName); e.printStackTrace(); driver.close(); Relogin_TPE rl=new Relogin_TPE(); rl.reLogin(); throw e; } } }
true
713d6caeeb0ac6f91f28a66464f067e85fecfa0b
Java
Jafa-R/programming
/nameprint/src/nameprint/NamePrint.java
UTF-8
9,170
3.1875
3
[]
no_license
package nameprint; import java.util.Scanner; public class NamePrint { public static void main(String[] args) { Scanner scan = new Scanner(System.in); System.out.print("please enter your name:"); String name = scan.next(); System.out.print("please enter the sympol:"); String sympol = scan.next(); char arr[] = name.toCharArray(); for (int i = 0; i < name.length(); i++) { char x = arr[i]; switch (x) { case 'a': case 'A': A(sympol); break; case 'b': case 'B': B(sympol); break; case 'c': case 'C': C(sympol); break; case 'd': case 'D': D(sympol); break; case 'e': case 'E': E(sympol); break; case 'f': case 'F': F(sympol); break; case 'g': case 'G': G(sympol); break; case 'h': case 'H': H(sympol); break; case 'i': case 'I': I(sympol); break; case 'j': case 'J': J(sympol); break; case 'k': case 'K': K(sympol); break; case 'l': case 'L': L(sympol); break; case 'm': case 'M': M(sympol); break; case 'n': case 'N': N(sympol); break; case 'o': case 'O': O(sympol); break; case 'p': case 'P': P(sympol); break; case 'q': case 'Q': Q(sympol); break; case 'r': case 'R': R(sympol); break; case 's': case 'S': S(sympol); break; case 't': case 'T': T(sympol); break; case 'u': case 'U': U(sympol); break; case 'v': case 'V': V(sympol); break; case 'w': case 'W': W(sympol); break; case 'x': case 'X': X(sympol); break; case 'y': case 'Y': Y(sympol); break; case 'z': case 'Z': Z(sympol); break; } } } public static void A(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 3) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void B(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 3 || row == 5) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void C(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 5) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol); } System.out.println(); } System.out.println("============================"); } public static void D(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 5) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void E(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 3 || row == 5) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol); } System.out.println(); } System.out.println("============================"); } public static void F(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 3) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol); } System.out.println(); } System.out.println("============================"); } public static void G(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 5) { System.out.print(" "); for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } } else if (row == 3) { System.out.print(sympol + " " + sympol + sympol + sympol); } else if (row == 2) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void H(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 3) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void I(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 5) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(" " + sympol); } System.out.println(); } System.out.println("============================"); } public static void J(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 5) { System.out.print(" "); for (int c = 1; c <= 3; c++) { System.out.print(sympol); } } else if (row == 4) { System.out.print(sympol + " " + sympol); } else { System.out.print(" " + sympol); } System.out.println(); } System.out.println("============================"); } public static void K(String sympol) { System.out.println("============================"); } public static void L(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 5) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol); } System.out.println(); } System.out.println("============================"); } public static void M(String sympol) { System.out.println("============================"); } public static void N(String sympol) { System.out.println("============================"); } public static void O(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 5) { System.out.print(" "); for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void P(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 3) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else if (row == 4 || row == 5) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void Q(String sympol) { System.out.println("============================"); } public static void R(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1 || row == 3) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void S(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1) { System.out.print(" "); for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } } else if (row == 2) { System.out.print(sympol); } else if (row == 3) { System.out.print(" "); for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } System.out.print(" "); } else if (row == 4) { System.out.print(" " + sympol); } else if (row == 5) { System.out.print(" "); for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } } System.out.println(); } System.out.println("============================"); } public static void T(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 1) for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } else { System.out.print(" " + sympol); } System.out.println(); } System.out.println("============================"); } public static void U(String sympol) { for (int row = 1; row <= 5; row++) { if (row == 5) { System.out.print(" "); for (int colum = 1; colum <= 5; colum++) { System.out.print(sympol); } } else { System.out.print(sympol + " " + sympol); } System.out.println(); } System.out.println("============================"); } public static void V(String sympol) { System.out.println("============================"); } public static void W(String sympol) { System.out.println("============================"); } public static void X(String sympol) { System.out.println("============================"); } public static void Y(String sympol) { System.out.println("============================"); } public static void Z(String sympol) { System.out.println("============================"); } }
true
64b411621745ee6a70ad1ef197c0941eb95faf8f
Java
uustudy/myFirstAppHelloWorld
/app/src/main/java/com/example/administrator/helloworld/LocationActivity.java
UTF-8
4,870
2.25
2
[]
no_license
package com.example.administrator.helloworld; import android.Manifest; import android.content.Context; import android.content.pm.PackageManager; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class LocationActivity extends BaseActivity { private TextView positionTextView; private LocationManager locationManager; private String provider; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.location_layout); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时 //判断是否具有权限 if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //判断是否需要向用户解释为什么需要申请该权限 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) { Toast.makeText(this, "自Android 6.0开始需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_SHORT).show(); } //请求权限 ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1); } }else{ setLocation(); } } public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 1) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //用户允许改权限,0表示允许,-1表示拒绝 PERMISSION_GRANTED = 0, PERMISSION_DENIED = -1 //permission was granted, yay! Do the contacts-related task you need to do. //这里进行授权被允许的处理 setLocation(); } else { //permission denied, boo! Disable the functionality that depends on this permission. //这里进行权限被拒绝的处理 Toast.makeText(this, "permission denied", Toast.LENGTH_SHORT).show(); } } else { super.onRequestPermissionsResult(requestCode, permissions, grantResults); } } public void setLocation(){ positionTextView = (TextView) findViewById(R.id.position_text_view); locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); // 获取所有可用的位置提供器 List<String> providerList = locationManager.getProviders(true); if (providerList.contains(LocationManager.GPS_PROVIDER)) { provider = LocationManager.GPS_PROVIDER; } else if (providerList.contains(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else { // 当没有可用的位置提供器时,弹出Toast提示用户 Toast.makeText(this, "No location provider to use",Toast.LENGTH_SHORT).show(); return; } Location location = locationManager.getLastKnownLocation(provider); if (location != null) { // 显示当前设备的位置信息 showLocation(location); } locationManager.requestLocationUpdates(provider, 5000, 1,locationListener); } protected void onDestroy() { super.onDestroy(); if (locationManager != null) { // 关闭程序时将监听器移除 locationManager.removeUpdates(locationListener); } } LocationListener locationListener = new LocationListener() { @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public void onProviderEnabled(String provider) { } @Override public void onProviderDisabled(String provider) { } @Override public void onLocationChanged(Location location) { // 更新当前设备的位置信息 showLocation(location); } }; private void showLocation(Location location) { String currentPosition = "latitude is " + location.getLatitude() + "\n" + "longitude is " + location.getLongitude(); positionTextView.setText(currentPosition); } }
true
284bc041d620293043b51c73bc097b3113d3243f
Java
oiyio/Dagger2-Tutorials
/Tutorial4-8LayerLibrary/src/main/java/com/test/tutorial4_8layerlibrary/viewmodel/BaseViewModel.java
UTF-8
450
1.828125
2
[]
no_license
package com.test.tutorial4_8layerlibrary.viewmodel; import android.arch.lifecycle.MutableLiveData; import android.arch.lifecycle.ViewModel; import com.test.tutorial4_8layerlibrary.model.User; public class BaseViewModel extends ViewModel { private MutableLiveData<String> stringMutableLiveData = new MutableLiveData<>(); private MutableLiveData<User> userMutableLiveData = new MutableLiveData<>(); public BaseViewModel() { } }
true
88bca0aa71f5f7f0a8e9ea3896130ded9d2bf0f7
Java
vixir/BePrepared
/src/com/vixir/beprepared/array/SmallestUnSortedArray.java
UTF-8
1,319
3.90625
4
[]
no_license
package com.vixir.beprepared.array; /** * Subarray Sort * Return start and end indices of the smalled subarray in the input array that needs to be sorted in place in order * for entire array to be sorted */ public class SmallestUnSortedArray { public static int[] subarraySort(int[] array) { int n = array.length; int minUnSort = Integer.MAX_VALUE; int maxUnSort = Integer.MIN_VALUE; for (int i = 0; i < n; i++) { if (isOutOfOrder(i, array)) { minUnSort = Math.min(array[i], minUnSort); maxUnSort = Math.max(array[i], maxUnSort); } } if (minUnSort == Integer.MAX_VALUE) { return new int[]{-1, -1}; } int left = 0; int right = array.length - 1; while (minUnSort >= array[left]) { left++; } while (maxUnSort <= array[right]) { right--; } return new int[]{left, right}; } private static boolean isOutOfOrder(int i, int[] array) { if (i == 0) { return array[i] > array[i + 1]; } else if (i == array.length - 1) { return array[i] < array[i - 1]; } else { return (array[i] > array[i + 1]) || (array[i] < array[i - 1]); } } }
true
384687608b1e27a95caa5b3ad6e4a4e9be07e1ce
Java
SorasoQ/algorithmPractice
/src/com/zjl/linkedlist/LinkedListNode.java
UTF-8
545
3
3
[]
no_license
package com.zjl.linkedlist; /** * @author zjl */ public class LinkedListNode { int val; LinkedListNode preNode; LinkedListNode nextNode; public LinkedListNode(){} public LinkedListNode(int val){ this.val = val; } public LinkedListNode(int val, LinkedListNode node){ this.val = val; this.nextNode = node; node.preNode = this; } public LinkedListNode(LinkedListNode node, int val){ this.val = val; this.preNode = node; node.nextNode = this; } }
true
95256d7bafe548f63b00b2ed1030d2c2a098071d
Java
anbu-github/ziPro
/app/src/main/java/com/purplefront/jiro_dev/parsers/CustomerVisitDisplay_JSONParser.java
UTF-8
2,042
2.34375
2
[]
no_license
package com.purplefront.jiro_dev.parsers; import com.purplefront.jiro_dev.model.MemberModel; import com.purplefront.jiro_dev.model.VisitCustomerDisplayModal; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by pf-05 on 11/29/2016. */ public class CustomerVisitDisplay_JSONParser { public static List<VisitCustomerDisplayModal> parserFeed(String content) { try { JSONArray ar = new JSONArray(content); List<VisitCustomerDisplayModal> feedslist = new ArrayList<>(); for (int i = 0; i < ar.length(); i++) { JSONObject obj = ar.getJSONObject(i); VisitCustomerDisplayModal flower = new VisitCustomerDisplayModal(); flower.setId(obj.getString("id")); flower.setCustomer(obj.getString("customer")); flower.setCustomer_contact(obj.getString("customer_contact")); flower.setVisit_date(obj.getString("visit_date")); flower.setAddress_line1(obj.getString("address_line1")); flower.setAddress_line2(obj.getString("address_line2")); flower.setAddress_line3(obj.getString("address_line3")); flower.setCity(obj.getString("city")); flower.setZipcode(obj.getString("zipcode")); flower.setState(obj.getString("state")); flower.setCountry(obj.getString("country")); flower.setNotes(obj.getString("notes")); flower.setAssign_to(obj.getString("assigned_to")); flower.setCheckin_date(obj.getString("checkin_date")); feedslist.add(flower); } return feedslist; } catch (JSONException e) { //Log.d("error in json", "l " + e); return null; } catch (Exception e) { //Log.d("json connection", "No internet access" + e); return null; } } }
true
ea3bfc331edf39e2b55e7dc4ab07329eea936ce0
Java
gregmazur/cost-locator
/src/main/java/org/open/budget/costlocator/api/TenderListItem.java
UTF-8
798
2.125
2
[]
no_license
package org.open.budget.costlocator.api; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.Builder; import org.open.budget.costlocator.entity.Item; import java.util.Date; @Builder public class TenderListItem implements Item { @SerializedName("id") @Expose private String id; @SerializedName("dateModified") @Expose private Date dateModified; public TenderListItem(String id, Date dateModified) { this.id = id; this.dateModified = dateModified; } /** * No args constructor for use in serialization * */ public TenderListItem() { } public String getId() { return id; } public Date getDateModified() { return dateModified; } }
true
8027f984c2258806ca7799a8cc79523fc1caeadf
Java
toni-stepanov/leetcode
/src/array/range_module_715/Main.java
UTF-8
400
2.21875
2
[]
no_license
package array.range_module_715; public class Main { public static void main(String[] args) { RangeModule rm = new RangeModule(); rm.addRange(5,8); rm.queryRange(3,4); rm.removeRange(5, 6); rm.removeRange(3, 6); rm.addRange(1,3); rm.queryRange(2,3); rm.addRange(4,8); rm.queryRange(2,3); rm.removeRange(4,9); } }
true
7f5e0e7e05494a5c923d7061a67813b1c21e62d9
Java
Christina-7443/JagScoutApp3_1
/app/src/main/java/info/scoutApp/jagscoutapp3_1/DatabaseHelper.java
UTF-8
4,323
2.40625
2
[]
no_license
//doing everything from video youtube.com/watch?v=cp2rL3AFmI&t=315s Android SQLite Database Tutorial package info.scoutApp.jagscoutapp3_1; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { public static final String DATABASE_NAME = "scoutdata.db"; public static final String TABLE_NAME = "scouttable"; public static final String COL_1 = "ID"; public static final String COL_3 = "stRobot"; public static final String COL_5 = "inner_goals"; public static final String COL_6 = "upper_goals"; public static final String COL_7 = "lower_goals"; public static final String COL_8 = "missed_goals"; public static final String COL_9 = "penalty_count"; public static final String COL_4 = "st"; public static final String COL_2 = "stMatch"; public static final String COL_10 = "stDrive"; public static final String COL_11 = "stAuto"; public static final String COL_12 = "stRotation"; public static final String COL_13 = "stPosition"; public static final String COL_14 = "stClimb"; public static final String COL_15 = "stLevel"; public static final String COL_16 = "stPark"; public static final String COL_17 = "stNone"; public static final String COL_18 = "stNotes"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + TABLE_NAME +" (" + "ID INTEGER PRIMARY KEY AUTOINCREMENT, " + "stMatch STRING, " + "stRobot STRING, " + "st STRING, " + "inner_goals STRING, " + "upper_goals INTEGER, " + "lower_goals INTEGER, " + "missed_goals INTEGER, " + "penalty_count INTEGER, " + "stDrive STRING," + "stAuto STRING, " + "stRotation STRING, " + "stPosition STRING, " + "stClimb STRING, " + "stLevel STRING, " + "stPark STRING, " + "stNone STRING, " + "stNotes STRING)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME); onCreate(db); } public boolean insertData( String stRobot, String inner_goals, Integer upper_goals, Integer lower_goals, Integer missed_goals, Integer penalty_count, String st, String stMatch, String stDrive, String stAuto, String stRotation, String stPosition, String stClimb, String stLevel, String stPark, String stNone, String stNotes){ SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(COL_3, stRobot); contentValues.put(COL_5, inner_goals); contentValues.put(COL_6, upper_goals); contentValues.put(COL_7, lower_goals); contentValues.put(COL_8, missed_goals); contentValues.put(COL_9, penalty_count); contentValues.put(COL_4, st); contentValues.put(COL_2, stMatch); contentValues.put(COL_10, stDrive); contentValues.put(COL_11, stAuto); contentValues.put(COL_12, stRotation); contentValues.put(COL_13, stPosition); contentValues.put(COL_14, stClimb); contentValues.put(COL_15, stLevel); contentValues.put(COL_16, stPark); contentValues.put(COL_17, stNone); contentValues.put(COL_18, stNotes); long result = db.insert(TABLE_NAME, null,contentValues); if (result == -1) return false; else return true; } public Cursor getAllData() { SQLiteDatabase db = this.getWritableDatabase(); Cursor result = db.rawQuery("select * from "+TABLE_NAME, null); return result; } }
true
ec8b9d38c31edeb5f78246813147bcf1aa3da5eb
Java
AlexTryjan/CollegeProjects
/P2/src/HuffmanCode.java
UTF-8
3,518
3.0625
3
[]
no_license
import java.util.LinkedList; import java.util.ListIterator; public class HuffmanCode { LinkedList<HuffmanNode> list; public int complete = 0; byte[] source; byte[] orderDec; public HuffmanCode(byte[] b) { HuffmanList List = new HuffmanList(b); this.source = List.source; //These will help us with the Huffman Coder functions this.orderDec = List.orderDec; list = List.getList(); while(list.size() > 1) {//The list.remove() method returns the node removed. Thought that was a neat interaction for below HuffmanNode nodeToAdd = new HuffmanNode(list.get(0).count + list.get(1).count, list.remove(), list.remove()); for(int i = 0; i <= list.size(); i++) { if(i == list.size()) {list.add(nodeToAdd); break;} if(nodeToAdd.count <= list.get(i).count) {list.add(i,nodeToAdd); break;} } } } public HuffmanCode(String inputFile) { HuffmanList List = new HuffmanList(inputFile); this.source = List.source; //These will help us with HuffmanCoder Functions this.orderDec = List.orderDec; list = List.getList(); while(list.size() > 1) { HuffmanNode nodeToAdd = new HuffmanNode(list.get(0).count + list.get(1).count, list.remove(), list.remove()); for(int i = 0; i <= list.size(); i++) { if(i == list.size()) {list.add(nodeToAdd); break;} if(nodeToAdd.count <= list.get(i).count) {list.add(i,nodeToAdd); break;} } } } public HuffmanCode(byte[] b, int[] counts) { HuffmanList List = new HuffmanList(b, counts); this.orderDec = List.orderDec; //no such thing as source text for this type, so we only need orderDec. list = List.getList(); while(list.size() > 1) { HuffmanNode nodeToAdd = new HuffmanNode(list.get(0).count + list.get(1).count, list.remove(), list.remove()); for(int i = 0; i <= list.size(); i++) { if(i == list.size()) {list.add(nodeToAdd); break;} if(nodeToAdd.count <= list.get(i).count) {list.add(i,nodeToAdd); break;} } } } public boolean[] code(byte b) { if(list.get(0).left == null && list.get(0).right == null) //check weird cases if(list.get(0).b == b) return new boolean[] {};//desired byte is root else throw new IllegalArgumentException("BYTE NOT FOUND"); else { LinkedList<Boolean> code = new LinkedList<Boolean>(); complete=0; traverse(b, list.get(0), code); int size = code.size(); if(size == 0) throw new IllegalArgumentException("BYTE NOT FOUND"); boolean[] result = new boolean[size]; ListIterator<Boolean> listIterator = code.listIterator(); int count = 0; while(listIterator.hasNext()) { result[count] = listIterator.next(); count++; } return result; } } private void traverse(byte b, HuffmanNode loc, LinkedList<Boolean> code) { if(loc.left == null && loc.right == null) { if(b == loc.b) complete = 1; return; } code.add(false); traverse(b,loc.left,code); if(complete==1) return; //must remove any true/false that doesn't get us to desired node code.removeLast(); code.add(true); traverse(b,loc.right,code); if(complete==1) return; code.removeLast(); } public String codeString(byte b) { boolean[] binary = code(b); String result = ""; for(int i = 0; i < binary.length; i++) { if(binary[i] == true) result += "1"; else result += "0"; } return result; } public String toString() { String result = ""; int check = 1; for(int i = 0; i < orderDec.length; i++) { if(check == 0) result += '\n'; result += orderDec[i] + ": " + codeString(orderDec[i]); check = 0; } return result; } }
true
c2052f1d128fa94d5cc803f50871320a0430c624
Java
msampolwal/adminhouse
/src/main/java/com/marianowal/adminhouse/repository/ItemDiaRepository.java
UTF-8
409
1.851563
2
[]
no_license
package com.marianowal.adminhouse.repository; import com.marianowal.adminhouse.domain.ItemDia; import org.springframework.data.jpa.repository.*; import org.springframework.stereotype.Repository; /** * Spring Data repository for the ItemDia entity. */ @SuppressWarnings("unused") @Repository public interface ItemDiaRepository extends JpaRepository<ItemDia, Long>, JpaSpecificationExecutor<ItemDia> { }
true
0638685b560faf1ac52f3a578b81051be6395192
Java
luckey007/harbinger-merchantmindcraft
/src/com/bcus/util/SQLiteConnection.java
UTF-8
939
2.875
3
[]
no_license
package com.bcus.util; import java.sql.*; public class SQLiteConnection { private Connection connection = null; { try { Class.forName("org.sqlite.JDBC"); } catch (ClassNotFoundException e) { e.printStackTrace(); } try { connection = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\Ashish\\Desktop\\sqlite.db"); } catch (SQLException e) { e.printStackTrace(); } } public ResultSet executeQuery(String query) throws SQLException { Statement statement = connection.createStatement(); return statement.executeQuery(query); } public boolean updateQuery(String query) throws SQLException { Statement statement = connection.createStatement(); return statement.executeUpdate(query) == 1; } public void close() throws SQLException { connection.close(); } }
true
d1dc66a3e898310177d7cd9f7c7e970c63c6cb18
Java
zirami/DoAnChoThue
/src/main/java/com/nhom2/controller/CT_PhieuMuonController.java
UTF-8
1,643
2.109375
2
[]
no_license
package com.nhom2.controller; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.nhom2.entity.CT_PHIEUMUON; @Transactional @Controller @RequestMapping("/") public class CT_PhieuMuonController { @Autowired SessionFactory factory; @RequestMapping("ct_phieumuon") public String index(ModelMap model) { Session session = factory.getCurrentSession(); String hql = "FROM CT_PHIEUMUON"; Query <CT_PHIEUMUON> query = session.createQuery(hql); List <CT_PHIEUMUON> list = query.list(); model.addAttribute("listCT_Phieumuon",list); model.addAttribute("ct_phieumuon_moi",new CT_PHIEUMUON()); return "ct_phieumuon"; } @RequestMapping("ct_phieumuon/insert") public String insert(ModelMap model, @ModelAttribute("ct_phieumuon_moi") CT_PHIEUMUON ct_phieumuon_moi) { Session session = factory.openSession(); Transaction t = session.beginTransaction(); try { session.save(ct_phieumuon_moi); t.commit(); model.addAttribute("message","Thành công!"); } catch(Exception e) { t.rollback(); model.addAttribute("message","Thất bại!"); } finally { session.close(); } return index(model); } }
true
c21125da7df84ad0b1db5083c58abf92d1eeca54
Java
babu4826/git_June29
/Git_Demo_2/src/src/classesAndObjects/Student.java
UTF-8
1,198
3.40625
3
[]
no_license
package classesAndObjects; // requirement is to carry the information regarding all male employees who joined for same course public class Student { private int rollNo; private String name; private String email; private static char gender; private static String course; public static void main(String[] args) { Student.setGender('M'); Student.setCourse("java"); Student st = new Student(); st.setRollNo(50); st.setName("harsha"); st.setEmail("harsha@gmail.com"); Student st2 = new Student(); st2.setRollNo(60); st2.setName("babu"); st2.setEmail("babu@gmail.com"); } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public static char getGender() { return gender; } public static void setGender(char gender) { Student.gender = gender; } public static String getCourse() { return course; } public static void setCourse(String course) { Student.course = course; } }
true
2fa97ac06a8a909e0df2a6cb9dcf3cdb4b256bdd
Java
zafrul-ust/tcmISDev
/src/main/java/com/tcmis/client/aerojet/process/PoXmlSubmitWorkerProcess.java
UTF-8
11,889
2.046875
2
[]
no_license
package com.tcmis.client.aerojet.process; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.Vector; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.tcmis.client.aerojet.beans.AddressBean; import com.tcmis.client.aerojet.beans.LineItemBean; import com.tcmis.client.aerojet.beans.PurchaseOrderBean; import com.tcmis.client.aerojet.beans.ScheduleLineItemBean; import com.tcmis.client.order.beans.CustomerPoPreStageBean; import com.tcmis.common.exceptions.BaseException; import com.tcmis.common.util.BeanHandler; import com.tcmis.common.util.StringHandler; public class PoXmlSubmitWorkerProcess implements Runnable { Log log = LogFactory.getLog(this.getClass()); PurchaseOrderBean bean; BigDecimal personnelId; BigDecimal nextupLoadSeq; String client = null; //String url = null; public PoXmlSubmitWorkerProcess(PurchaseOrderBean bean, String client){ this.bean = bean; this.client = client; } public void run() { Collection customerPoPreStageBeanCol; PoXmlSubmitProcess process = new PoXmlSubmitProcess(client); try { BigDecimal loadId = process.getNextLoadIdSeq(); log.debug("Load id for customerPoPreStage :" + loadId); String errorMessage = ""; //flatten the bean to insert into the customer_po_pre_stage table customerPoPreStageBeanCol = generateCustomerPoPreStageBean(bean, loadId, process); if (log.isDebugEnabled()) log.debug("Flat collection size:" + customerPoPreStageBeanCol.size()); if ( bean.getVerb().equalsIgnoreCase("PROCESS") && bean.getRevision().equalsIgnoreCase("007")) errorMessage = process.processData(customerPoPreStageBeanCol, loadId); else if (bean.getVerb().equalsIgnoreCase("CHANGE") && bean.getRevision().equalsIgnoreCase("006")) errorMessage = process.processChangeData(customerPoPreStageBeanCol, loadId); log.debug("errorMessage from processData - " + errorMessage); } catch(Exception ex){ ex.printStackTrace(); log.error(ex); } } private Collection generateCustomerPoPreStageBean(PurchaseOrderBean poBean, BigDecimal loadId, PoXmlSubmitProcess process) throws BaseException { //DbManager dbManager = new DbManager(this.client); //BigDecimal loadId = new BigDecimal(dbManager.getOracleSequence("CUSTOMER_PO_LOAD_SEQ")); SimpleDateFormat formatDateTime = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); SimpleDateFormat formatDate = new SimpleDateFormat("MM/dd/yyyy"); Collection collection = new Vector(); //since I need to "flatten" this bean into multiple "flat" beans I'll add the beans //to the collection in the iteraton of the schedule at the bottom of this method CustomerPoPreStageBean customerPoPreStageBean = new CustomerPoPreStageBean(); //set the data related to new order (850) and change order (860) if (poBean.getVerb().equalsIgnoreCase("PROCESS") && poBean.getRevision().equalsIgnoreCase("007")) { customerPoPreStageBean.setTransactionType("850"); customerPoPreStageBean.setStatus("NEW"); } else if (poBean.getVerb().equalsIgnoreCase("CHANGE") && poBean.getRevision().equalsIgnoreCase("006")) { customerPoPreStageBean.setTransactionType("860"); customerPoPreStageBean.setStatus("IGNORE"); customerPoPreStageBean.setProcessingComments("XML UPLOAD - We do not process 860-change orders for Aerojet."); } //first copy the "header" bean customerPoPreStageBean.setCustomerPoNo(poBean.getPoId()); customerPoPreStageBean.setDateIssued(poBean.getDateTime("CREATION", formatDate)); //customerPoPreStageBean.setPoTypeCode(poBean.getPoType()); customerPoPreStageBean.setCurrencyId(poBean.getOperAmtBean().getCurrency()); //soldto AddressBean buyer = poBean.getAddressBean("SoldTo"); customerPoPreStageBean.setBuyerPartyName(buyer.getPartnerName()); customerPoPreStageBean.setBuyerNameOnPo(process.getApplicationLogonId(buyer.getContactPerson().getName())); //customerPoPreStageBean.setBuyerNameOnPo(buyer.getPartnerName()); customerPoPreStageBean.setBuyerAddress1(buyer.getAddress1()); customerPoPreStageBean.setBuyerAddress2(buyer.getAddress2()); customerPoPreStageBean.setBuyerAddress3(buyer.getAddress3()); customerPoPreStageBean.setBuyerZip(buyer.getZip()); customerPoPreStageBean.setBuyerCity(buyer.getCity()); customerPoPreStageBean.setBuyerState(buyer.getState()); customerPoPreStageBean.setBuyerRegion(buyer.getRegion()); customerPoPreStageBean.setBuyerCountry(buyer.getCountry()); AddressBean seller = poBean.getAddressBean("Supplier"); //customerPoPreStageBean.setCustomerHaasContractId(poBean.getSellerIdent()); customerPoPreStageBean.setCustomerHaasAccountNo(seller.getPartnerId()); customerPoPreStageBean.setSellerIdOnPo(seller.getPartnerId()); customerPoPreStageBean.setSellerPartyName(seller.getPartnerName()); customerPoPreStageBean.setSellerNameOnPo(seller.getPartnerName()); customerPoPreStageBean.setSellerAddress1(seller.getAddress1()); customerPoPreStageBean.setSellerAddress2(seller.getAddress2()); customerPoPreStageBean.setSellerZip(seller.getZip()); customerPoPreStageBean.setSellerCity(seller.getCity()); customerPoPreStageBean.setSellerState(seller.getState()); customerPoPreStageBean.setSellerRegion(seller.getRegion()); customerPoPreStageBean.setSellerCountry(seller.getCountry()); //shipto only at schedule line level and not at the header level //billto AddressBean billto = poBean.getAddressBean("BillTo"); customerPoPreStageBean.setBilltoPartyId(billto.getPartnerId()); customerPoPreStageBean.setBilltoParty(billto.getPartnerName()); customerPoPreStageBean.setBilltoAddress1(billto.getAddress1()); customerPoPreStageBean.setBilltoAddress2(billto.getAddress2()); customerPoPreStageBean.setBilltoAddress3(billto.getAddress3()); customerPoPreStageBean.setBilltoZip(billto.getZip()); customerPoPreStageBean.setBilltoCity(billto.getCity()); customerPoPreStageBean.setBilltoState(billto.getState()); customerPoPreStageBean.setBilltoRegion(billto.getRegion()); customerPoPreStageBean.setBilltoCountry(billto.getCountry()); //customerPoPreStageBean.setFreightOnBoardNotes(poBean.getFobDescription()); //customerPoPreStageBean.setFreightOnBoard(poBean.getFobId()); //customerPoPreStageBean.setPaymentTerms(poBean.getPaymentTermsId()); //customerPoPreStageBean.setPaymentTermsNotes(poBean.getPaymentTermsDesc()); customerPoPreStageBean.setCustomerPoNote(poBean.getHeaderDescription()); customerPoPreStageBean.setTotalAmountOnPo(poBean.getOperAmtBean().getDecimalValue()); customerPoPreStageBean.setLoadId(loadId); customerPoPreStageBean.setDateInserted(new Date()); //this is for a constraint on the customer_po_pre_stage table customerPoPreStageBean.setTransport("XML"); customerPoPreStageBean.setTransporterAccount("Aerojet"); customerPoPreStageBean.setTradingPartner("Aerojet"); customerPoPreStageBean.setTradingPartnerId("Aerojet"); customerPoPreStageBean.setPre860("N"); customerPoPreStageBean.setCompanyId("AEROJET"); customerPoPreStageBean.setChangeOrderSequence(new BigDecimal("0")); //customerPoPreStageBean.setOrderDate(poBean.getDateTime("DOCUMENT", formatDate)); //copy detail int loadLine = 1; //int lineSequence = 1; Iterator detailIterator = poBean.getLineItemBeanCollection().iterator(); while (detailIterator.hasNext()) { LineItemBean detailBean = (LineItemBean) detailIterator.next(); customerPoPreStageBean.setCustomerPoLineNo(detailBean.getPoLineNumber()); customerPoPreStageBean.setManufacturerPartNum(detailBean.getSupplierItemNumber()); customerPoPreStageBean.setHaasItemNo(detailBean.getSupplierItemNumber()); customerPoPreStageBean.setItemDescription(detailBean.getItemDescription()); customerPoPreStageBean.setQuantity(detailBean.getLineOrderedQuantityBean().getDecimalValue()); customerPoPreStageBean.setUom(detailBean.getLineOrderedQuantityBean().getUom()); customerPoPreStageBean.setUnitPrice(detailBean.getLineItemAmtBean().getDecimalValue()); customerPoPreStageBean.setCurrencyId(detailBean.getLineItemAmtBean().getCurrency()); customerPoPreStageBean.setCustomerPoLineNote(detailBean.getFullNotetoSupplier()); customerPoPreStageBean.setLoadLine(new BigDecimal(loadLine)); //customerPoPreStageBean.setLineSequence(new BigDecimal(lineSequence)); //customerPoPreStageBean.setCustomerHaasContractId(detailBean.getContractNumber()); customerPoPreStageBean.setCatPartNo(detailBean.getItemNumber()); //copy schedule int lineSequence = 1; //int loadLine = 1; Iterator scheduleIterator = detailBean.getScheduleLineItemBeanCollection().iterator(); while (scheduleIterator.hasNext()) { //this is the last iterator so I need to copy the attributes to a different bean //and add that bean to the collection CustomerPoPreStageBean flatBean = new CustomerPoPreStageBean(); BeanHandler.copyAttributes(customerPoPreStageBean, flatBean); ScheduleLineItemBean scheduleBean = (ScheduleLineItemBean)scheduleIterator.next(); flatBean.setLineSequence(new BigDecimal(lineSequence)); //flatBean.setLoadLine(new BigDecimal(loadLine)); flatBean.setScheduleQuantity(scheduleBean.getScheduleQuantityBean().getDecimalValue()); flatBean.setScheduleUom(scheduleBean.getScheduleQuantityBean().getUom()); flatBean.setRequestedDeliveryDate(scheduleBean.getDateTime("NEEDDELV", formatDate)); //--populating the need date in both the columns flatBean.setDesiredDeliveryDate(scheduleBean.getDateTime("NEEDDELV", formatDateTime)); flatBean.setDesiredShipDate(scheduleBean.getDateTime("PROMSHIP", formatDateTime)); AddressBean shipTo = scheduleBean.getAddressBean("ShipTo"); flatBean.setShiptoPartyId(shipTo.getZip()); flatBean.setShiptoPartyName(shipTo.getPartnerName()); flatBean.setShiptoAddress1(shipTo.getAddress1()); flatBean.setShiptoAddress2(shipTo.getAddress2()); flatBean.setShiptoAddress3(shipTo.getAddress3()); flatBean.setShiptoZip(shipTo.getZip()); flatBean.setShiptoCity(shipTo.getCity()); flatBean.setShiptoState(shipTo.getState()); flatBean.setShiptoRegion(shipTo.getRegion()); flatBean.setShiptoCountry(shipTo.getCountry()); //flatBean.setShiptoContactName(shipTo.getContactPerson().getName()); //flatBean.setChargeNumber1(scheduleBean.getProjectNumber()); //flatBean.setChargeNumber2(scheduleBean.getProjectType()); flatBean.setChargeNumber1("PO XML"); flatBean.setChargeNumber2(scheduleBean.getProjectNumber()); flatBean.setChargeNumber3(scheduleBean.getProjectTask()); if (StringHandler.isBlankString(scheduleBean.getApplication())) flatBean.setApplication("WAREHOUSE"); else flatBean.setApplication(scheduleBean.getApplication()); flatBean.setOwnerSegmentId(scheduleBean.getOwnerSegmentId()); flatBean.setRequestorName(scheduleBean.getProjectRequestorName()); flatBean.setBuyerEmail(scheduleBean.getProjectRequestorEmail()); collection.add(flatBean); lineSequence++; //loadLine++; } loadLine++; //lineSequence++; } //In case there are no line items or schedule line items in the po received from aerojet if(collection.size() == 0) { collection.add(customerPoPreStageBean); } return collection; } }
true
2df3698b6bbc45971378c3242a368e80df8275de
Java
Shen-hub/Room
/app/src/main/java/com/example/room/SimpleAdapter.java
UTF-8
1,615
2.15625
2
[]
no_license
package com.example.room; import android.app.Activity; import android.content.Context; import android.database.Cursor; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.view.View; import android.widget.AdapterView; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class SimpleAdapter { SimpleCursorAdapter adapter; Context c; Activity activity; SimpleAdapter(Context context, Activity MainActivity){ this.c = context; this.activity = MainActivity; } SimpleCursorAdapter productsAdapter(Cursor cursor) { adapter = new SimpleCursorAdapter(c, R.layout.item, cursor, cursor.getColumnNames(), new int[]{ R.id._id, R.id.product_name, R.id.count, R.id.category_id}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); return adapter; } SimpleCursorAdapter categoryProductsAdapter(Cursor cursor) { adapter = new SimpleCursorAdapter(c, R.layout.item, cursor, cursor.getColumnNames(), new int[]{ R.id._id, R.id.product_name, R.id.count, R.id.category_id}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); return adapter; } SimpleCursorAdapter categoryAdapter(Cursor cursor) { adapter = new SimpleCursorAdapter(c, R.layout.item, cursor, cursor.getColumnNames(), new int[]{ R.id.sec_category_id, R.id.category_name}, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); return adapter; } }
true
2a0f72e670f99f21deff3301b45cd63c74ae1cf0
Java
xingqinggele/Personnel_contorl
/app/src/main/java/com/zhhl/personnel_contorl/di/component/PetitionComponent.java
UTF-8
479
1.65625
2
[]
no_license
package com.zhhl.personnel_contorl.di.component; import com.zhhl.personnel_contorl.di.ActivityScope; import com.zhhl.personnel_contorl.di.module.PetitionModule; import com.zhhl.personnel_contorl.mvp.view.activities.PetitionActivity; import dagger.Component; /** * Created by miao on 2019/2/28. */ @ActivityScope @Component(modules = PetitionModule.class, dependencies = AppComponent.class) public interface PetitionComponent { void inject(PetitionActivity activity); }
true
933e2491062add4cf4dd6cd6a692622a4459b106
Java
jerzyjankowski/ParserSQL
/DataGenerator/src/pl/put/tpd/datagenerator/structures/output/OutputRow.java
UTF-8
531
2.84375
3
[]
no_license
package pl.put.tpd.datagenerator.structures.output; import java.util.ArrayList; import java.util.List; public class OutputRow { private List<String> nodes; public OutputRow() { nodes = new ArrayList<>(); } public List<String> getNodes() { return nodes; } public void setNodes(List<String> nodes) { this.nodes = nodes; } public void addNode(String node) { this.nodes.add(node); } @Override public String toString() { return "\n Row [nodes=" + nodes + "]"; } }
true
72e50cc634cdfc71e08cb9a1128ba35f99b9b352
Java
endrjust/communicator2
/src/udemy/designpatterns/observer_komunikator/CommApp.java
UTF-8
2,067
3.15625
3
[]
no_license
package udemy.designpatterns.observer_komunikator; import java.io.IOException; import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class CommApp { public static Scanner scanner = new Scanner(System.in); public static void main(String[] args) throws IOException { User user1 = new User("and@o2.pl", "Andrzej"); User user2 = new User("kas@gmail.com", "Kasia"); User user3 = new User("paw@o2.pl", "Pawel"); Channel channel1 = new Channel("ZDJAVApol17", "JAVA", false); Channel channel2 = new Channel("tajemne", "JAVA", true); Channel channel3 = new Channel("luzneRozmowy", "wszystko", false); List<Channel> channels = List.of(channel1, channel2, channel3); System.out.println(getPublicChannels(channels)); // channel1.addUser(user1); // channel1.addUser(user2); // channel1.addUser(user3); // channel1.sendMessage(user1, "To ja"); // channel1.unregisterUSer(user3); // channel1.sendMessage(user2,"I ja"); // user1.joinToChannel(channel1); user1.joinToChannel(channel1); user2.joinToChannel(channel1); user1.sendMessage("To ja",channel1); user1.sendMessage("To ja 2",channel2); } public static List<Channel> getPublicChannels(List<Channel> channels) { List<Channel> publicsCh = new ArrayList<>(); for (Channel ch : channels) { if (!ch.isPrivateChannel()) { publicsCh.add(ch); } } return publicsCh; } public static Channel addChannel() { System.out.println("Podaj nazwę"); String name = scanner.nextLine(); System.out.println("Podaj tematyke"); String theme = scanner.nextLine(); System.out.println("Czy kanał ma być prywatny t/n"); boolean status = false; if (scanner.nextLine().equals("t")) { status = true; } return new Channel(name, theme, status); } }
true
6b2015705bb97a407815279086db712a24c2db4f
Java
NayarBEP1/PifPoliscan
/src/main/java/com/poliscan/domain/model/entity/Area.java
UTF-8
1,155
2.734375
3
[]
no_license
package com.poliscan.domain.model.entity; public class Area { private String id; private String name; private String description; private final String ERROR_NAME_IS_MANDATORY = "Error: Area name is mandatory"; private final String ERROR_DESCRIPTION_IS_MANDATORY = "Error: Description is mandatory"; public Area(String id, String name, String description) { dataValidator(name, description); this.id = id; this.name = name; this.description = description; } public Area(String name, String description) { dataValidator(name, description); this.name = name; this.description = description; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public String getDescription() { return description; } private void dataValidator(String name, String description){ DataValidator.isMandatory(name, ERROR_NAME_IS_MANDATORY); DataValidator.isMandatory(description, ERROR_DESCRIPTION_IS_MANDATORY); } }
true
295f5828d8d54338f9d680cb594624ac8a560968
Java
widmofazowe/cyfronoid-core
/src/eu/cyfronoid/core/interceptor/ValidationInterceptor.java
UTF-8
2,008
2.5
2
[ "MIT" ]
permissive
package eu.cyfronoid.core.interceptor; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import eu.cyfronoid.core.validator.AnnotationValidator; import eu.cyfronoid.core.validator.ValidationRegistry; @SuppressWarnings("rawtypes") public class ValidationInterceptor implements MethodInterceptor { private final ValidationRegistry validationRegistry = new ValidationRegistry(); @Override public Object invoke(MethodInvocation methodInvocation) throws Throwable { checkMethod(methodInvocation.getMethod(), methodInvocation.getArguments()); return methodInvocation.proceed(); } private void checkMethod(Method method, Object[] arguments) { for(int i=0 ; i<arguments.length ; i++) { List<Annotation> annotations = Arrays.asList(method.getParameterAnnotations()[i]); validateArgument(annotations, method, arguments[i]); } } @SuppressWarnings("unchecked") private void validateArgument(List<Annotation> annotations, Method method, Object argument) { for(Annotation annotation : annotations) { AnnotationValidator builderValidator = getBuilderValidator(annotation); if(!builderValidator.isValid(argument, annotation)) { throw new IllegalArgumentException(builderValidator.getMessage(method.getDeclaringClass(), method.getName(), argument, annotation)); } } } private AnnotationValidator getBuilderValidator(Annotation annotation) { AnnotationValidator builderValidator = validationRegistry.getValidator(annotation.annotationType()); if(builderValidator == null) { throw new IllegalStateException("Cannot find AnnotationValidator for annotation: " + annotation.annotationType().getName()); } return builderValidator; } }
true
2dd720c9e78841caf0947ddb29b10e5661f1580c
Java
Yaenwe/JavaWeb
/FAOUZI/Exercice_IMC/src/adelium/cours/java/Personne.java
ISO-8859-1
2,493
3.21875
3
[]
no_license
package adelium.cours.java; public class Personne { private String Nom; private String Prenom ; private float Poids ; private float Taille ; private Genre sexe ; public String getNom() { return Nom; } public void setNom(String nom) { Nom = nom; } public String getPrenom() { return Prenom; } public void setPrenom(String prenom) { Prenom = prenom; } public float getPoids() { return Poids; } public void setPoids(float poids) { Poids = poids; } public float getTaille() { return Taille; } public void setTaille(float taille) { Taille = taille; } public Genre getSexe() { return sexe; } public void setSexe(Genre sexe) { this.sexe = sexe; } public Personne(String nom, String prenom, float poids, float taille, Genre sexe) { super(); Nom = nom; Prenom = prenom; Poids = poids; Taille = taille; this.sexe = sexe; } public float IMC() { return this.Poids / (this.Taille * this.Taille) ; } public float PoidsMin() { return (19 * this.Taille * this.Taille) ; } public float PoidsMax() { return (25 * this.Taille * this.Taille) ; } public float PoidsIdeal() { if (this.sexe == Genre.MASCULIN) return (22 * this.Taille * this.Taille) ; else // Ce else est maintenu pour la clart du code return (21 * this.Taille * this.Taille) ; } public String Diagnostic() { float imc = this.IMC(); if (imc < 17) return "Anorexique" ; if (imc < 19) return "Magre" ; if (imc < 25) return "Super forme" ; if (imc < 30) return "Kilos +" ; if (imc < 40) return "Obse lger" ; return "Obse morbide" ; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Nom = "); builder.append(Nom); builder.append("\nPrenom ="); builder.append(Prenom); builder.append("\nPoids = "); builder.append(Poids); builder.append("\nTaille = "); builder.append(Taille); builder.append("\nsexe = "); builder.append(sexe); builder.append("\nIMC = "); builder.append(IMC()); builder.append("\nPoidsMin = "); builder.append(PoidsMin()); builder.append("\nPoidsMax = "); builder.append(PoidsMax()); builder.append("\nPoidsIdeal = "); builder.append(PoidsIdeal()); builder.append("\nDiagnostic = "); builder.append(Diagnostic()); return builder.toString(); } }
true
c71cbf36223fafac6aaad9b159bb6f667ab122be
Java
ouniali/WSantipatterns
/WebServiceArtifacts/FlightBookingService/org/datacontract/schemas/_2004/_07/goquo_dp/ArrayOfPackageSummary.java
UTF-8
2,111
2.046875
2
[]
no_license
package org.datacontract.schemas._2004._07.goquo_dp; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ArrayOfPackageSummary complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="ArrayOfPackageSummary"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="PackageSummary" type="{http://schemas.datacontract.org/2004/07/GoQuo.DP.BAL}PackageSummary" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ArrayOfPackageSummary", namespace = "http://schemas.datacontract.org/2004/07/GoQuo.DP.BAL", propOrder = { "packageSummary" }) public class ArrayOfPackageSummary { @XmlElement(name = "PackageSummary", nillable = true) protected List<PackageSummary> packageSummary; /** * Gets the value of the packageSummary 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 packageSummary property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPackageSummary().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PackageSummary } * * */ public List<PackageSummary> getPackageSummary() { if (packageSummary == null) { packageSummary = new ArrayList<PackageSummary>(); } return this.packageSummary; } }
true