hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9241138e8b2c979d44ae808a37c9ada24a00e913 | 372 | java | Java | spring-boot-tc/src/main/java/pl/codeleak/samples/springboot/tc/SpringBootTestcontainersApplication.java | PatrickChenSe/codeTest | db58537ca37178377a2d875a3de2af4e336dffa2 | [
"Apache-2.0"
] | null | null | null | spring-boot-tc/src/main/java/pl/codeleak/samples/springboot/tc/SpringBootTestcontainersApplication.java | PatrickChenSe/codeTest | db58537ca37178377a2d875a3de2af4e336dffa2 | [
"Apache-2.0"
] | 11 | 2020-12-02T18:45:02.000Z | 2022-03-02T07:38:12.000Z | spring-boot-tc/src/main/java/pl/codeleak/samples/springboot/tc/SpringBootTestcontainersApplication.java | PatrickChenSe/codeTest | db58537ca37178377a2d875a3de2af4e336dffa2 | [
"Apache-2.0"
] | null | null | null | 31 | 79 | 0.817204 | 1,001,773 | package pl.codeleak.samples.springboot.tc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootTestcontainersApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootTestcontainersApplication.class, args);
}
}
|
924113e96da549742f1c66e5eeaf4059ca15c938 | 1,827 | java | Java | src/main/java/com/thetransactioncompany/jsonrpc2/server/accessfilter/AccessFilterResult.java | shangdawei/json-rpc-2.0-access-filter | 9185b8ad36a710ba99f018779394d7d3fcd215f8 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thetransactioncompany/jsonrpc2/server/accessfilter/AccessFilterResult.java | shangdawei/json-rpc-2.0-access-filter | 9185b8ad36a710ba99f018779394d7d3fcd215f8 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/thetransactioncompany/jsonrpc2/server/accessfilter/AccessFilterResult.java | shangdawei/json-rpc-2.0-access-filter | 9185b8ad36a710ba99f018779394d7d3fcd215f8 | [
"Apache-2.0"
] | null | null | null | 19.43617 | 82 | 0.671045 | 1,001,774 | package com.thetransactioncompany.jsonrpc2.server.accessfilter;
/**
* Access filter result.
*
* @author Vladimir Dzhuvinov
*/
public class AccessFilterResult {
/**
* Indicates whether access is allowed or denied.
*/
private boolean accessAllowed;
/**
* The matching access denied error message if access is denied.
*/
private AccessDeniedError error;
/**
* Constant access filter result indicating access is allowed.
*/
public static final AccessFilterResult ACCESS_ALLOWED = new AccessFilterResult();
/**
* Creates a new access filter result indicating access is allowed.
*/
public AccessFilterResult() {
accessAllowed = true;
error = null;
}
/**
* Creates a new access filter result indicating access is denied.
*
* @param error The matching access denied error message. Must not be
* {@code null}.
*/
public AccessFilterResult(final AccessDeniedError error) {
accessAllowed = false;
if (error == null)
throw new IllegalArgumentException("The access denied error must not be null");
this.error = error;
}
/**
* Returns {@code true} if access has been allowed.
*
* @see #accessDenied
*
* @return {@code true} if access has been allowed, else {@code false}.
*/
public boolean accessAllowed() {
return accessAllowed;
}
/**
* Returns {@code true} if access has been denied.
*
* @see #accessAllowed
*
* @return {@code true} if access has been denied, else {@code false}.
*/
public boolean accessDenied() {
return ! accessAllowed;
}
/**
* Gets the matching access denied error if access is denied.
*
* @return The matching access denied error if access is denied, else
* {@code null}.
*/
public AccessDeniedError getAccessDeniedError() {
return error;
}
}
|
9241148c5959e14cfdea7f266258818618cd9cb4 | 1,944 | java | Java | src/test/java/HW1.java | dbudonnyi/selenium-webdriver-java | 09239833015a3b0c7967b3b96277d24c4e491d65 | [
"MIT"
] | null | null | null | src/test/java/HW1.java | dbudonnyi/selenium-webdriver-java | 09239833015a3b0c7967b3b96277d24c4e491d65 | [
"MIT"
] | null | null | null | src/test/java/HW1.java | dbudonnyi/selenium-webdriver-java | 09239833015a3b0c7967b3b96277d24c4e491d65 | [
"MIT"
] | null | null | null | 36 | 148 | 0.673868 | 1,001,775 | import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.util.List;
public class HW1 {
static WebDriver driver;
@BeforeClass
public static void setupClass() {
WebDriverManager.chromedriver().setup();
// System.setProperty("webdriver.chrome.driver", "C:\\Users\\Dbudonny\\Desktop\\Workspace\\SeleniumWebDriver\\webdrivers\\chromedriver.exe");
}
@Before
public void setup(){
driver = new ChromeDriver();
driver.get("http://demo.litecart.net/admin/");
driver.findElement(By.cssSelector("button[name=login]")).click();
new WebDriverWait(driver, 10).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("img.center-block.img-responsive")));
}
@After
public void quit(){
driver.quit();
}
@Test
public void Test() {
String selectorApps = "#box-apps-menu > li.app";
String selectorDocs = "ul.docs > li.doc";
for (int i = 0; i < driver.findElements(By.cssSelector(selectorApps)).size(); i++) {
driver.findElements(By.cssSelector(selectorApps)).get(i).click();
Assert.assertTrue(areElementsPresent(driver, By.cssSelector("div.panel-heading")));
for (int j = 0; j < driver.findElements(By.cssSelector(selectorDocs)).size(); j++) {
driver.findElements(By.cssSelector(selectorDocs)).get(j).click();
Assert.assertTrue(areElementsPresent(driver, By.cssSelector("div.panel-heading")));
}
}
}
private boolean areElementsPresent(WebDriver driver, By locator){
return driver.findElements(locator).size() > 0;
}
}
|
924116052a8a658b62a4c466fc4c0f1ce86856a6 | 382 | java | Java | Beginner/OddOrEven_251701133.java | dkpro23/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | e5a82a84eaa47577c6f6b3d86e208ee07e7780f8 | [
"Apache-2.0"
] | 22 | 2019-10-02T16:48:10.000Z | 2020-11-14T23:28:41.000Z | Beginner/OddOrEven_251701133.java | dkpro23/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | e5a82a84eaa47577c6f6b3d86e208ee07e7780f8 | [
"Apache-2.0"
] | 46 | 2019-10-01T03:53:30.000Z | 2020-10-20T16:34:37.000Z | Beginner/OddOrEven_251701133.java | dkpro23/IOSD-UIETKUK-HacktoberFest-Meetup-2019 | e5a82a84eaa47577c6f6b3d86e208ee07e7780f8 | [
"Apache-2.0"
] | 415 | 2019-10-01T03:48:22.000Z | 2021-02-27T04:57:28.000Z | 23.875 | 49 | 0.536649 | 1,001,776 | import java.util.Scanner;
public class OddOrEven{
public static void main(String[] args)
{
System.out.println("enter the number");
Scanner in = new Scanner(System.in);
int x = in.nextInt();
if (x%2==0)
System.out.println("number is even");
else
System.out.println("number is odd");
}
}
|
9241166db0133cf2cba1c7f2e4e5183d5d9f2b22 | 1,930 | java | Java | study-note/study-java8/src/main/java/com/kongbig/java8/bean/Employee.java | kongbigliang/study-note | 3cb0599e0e2806528f761c9edf870b9191e68687 | [
"Apache-2.0"
] | null | null | null | study-note/study-java8/src/main/java/com/kongbig/java8/bean/Employee.java | kongbigliang/study-note | 3cb0599e0e2806528f761c9edf870b9191e68687 | [
"Apache-2.0"
] | 4 | 2019-12-07T06:34:02.000Z | 2020-06-04T05:40:20.000Z | study-note/study-java8/src/main/java/com/kongbig/java8/bean/Employee.java | kongbigliang/study-note | 3cb0599e0e2806528f761c9edf870b9191e68687 | [
"Apache-2.0"
] | null | null | null | 21.931818 | 87 | 0.510363 | 1,001,777 | package com.kongbig.java8.bean;
import lombok.*;
/**
* @Description:
* @author: lianggangda
* @date: 2020/5/2 10:25
*/
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Employee {
private int id;
private String name;
private int age;
private double salary;
private Status status;
public Employee(String name) {
this.name = name;
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public String show() {
return "测试方法引用!";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Employee other = (Employee) obj;
if (age != other.age) {
return false;
}
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary)) {
return false;
}
return true;
}
}
|
924118000ead10b5fd48588784ed85c0391f5802 | 10,583 | java | Java | WikipediaCleaner/src/org/wikipediacleaner/gui/swing/options/SortingOptionsPanel.java | RogueScholar/wpcleaner | b1f97221059ad2b4d5e09f1f220dddbe46ec3da9 | [
"Apache-2.0"
] | 38 | 2015-08-08T21:56:52.000Z | 2022-02-27T16:10:35.000Z | WikipediaCleaner/src/org/wikipediacleaner/gui/swing/options/SortingOptionsPanel.java | RogueScholar/wpcleaner | b1f97221059ad2b4d5e09f1f220dddbe46ec3da9 | [
"Apache-2.0"
] | 8 | 2015-08-23T03:53:17.000Z | 2020-07-28T09:22:39.000Z | WikipediaCleaner/src/org/wikipediacleaner/gui/swing/options/SortingOptionsPanel.java | RogueScholar/wpcleaner | b1f97221059ad2b4d5e09f1f220dddbe46ec3da9 | [
"Apache-2.0"
] | 16 | 2015-08-08T21:57:02.000Z | 2022-03-11T06:13:02.000Z | 35.996599 | 101 | 0.683644 | 1,001,778 | /*
* WPCleaner: A tool to help on Wikipedia maintenance tasks.
* Copyright (C) 2013 Nicolas Vervelle
*
* See README.txt file for licensing information.
*/
package org.wikipediacleaner.gui.swing.options;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionListener;
import java.beans.EventHandler;
import java.util.LinkedList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JToolBar;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.wikipediacleaner.api.data.CompositeComparator;
import org.wikipediacleaner.api.data.NamedComparator;
import org.wikipediacleaner.api.data.Page;
import org.wikipediacleaner.api.data.PageComparator;
import org.wikipediacleaner.gui.swing.basic.Utilities;
import org.wikipediacleaner.i18n.GT;
import org.wikipediacleaner.images.EnumImageSize;
/**
* A panel for sorting options.
*/
public class SortingOptionsPanel
extends OptionsPanel
implements ListSelectionListener {
/**
* Serialisation.
*/
private static final long serialVersionUID = 2014796573945564540L;
private JButton buttonSortAdd;
private JButton buttonSortDelete;
private JButton buttonSortUp;
private JButton buttonSortDown;
private JList<CompositeComparator<Page>> listSort;
private DefaultListModel<CompositeComparator<Page>> modelSort;
private JList<NamedComparator<Page>> listSortItem;
private DefaultListModel<NamedComparator<Page>> modelSortItem;
/**
* Construct a General Options panel.
*/
public SortingOptionsPanel() {
super(new GridBagLayout());
initialize();
}
/**
* Initialize the panel.
*/
private void initialize() {
// Initialize constraints
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.gridheight = 1;
constraints.gridwidth = 1;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.insets = new Insets(0, 0, 0, 0);
constraints.ipadx = 0;
constraints.ipady = 0;
constraints.weightx = 1;
constraints.weighty = 0;
// Sort orders
JPanel panelSortOrders = new JPanel(new GridBagLayout());
panelSortOrders.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), GT._T("Sort orders")));
constraints.fill = GridBagConstraints.BOTH;
constraints.weighty = 1;
modelSort = new DefaultListModel<>();
List<CompositeComparator<Page>> comparators = PageComparator.getComparators();
for (CompositeComparator<Page> comparator : comparators) {
modelSort.addElement(comparator);
}
listSort = new JList<>(modelSort);
listSort.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listSort.addListSelectionListener(this);
JScrollPane scrollSort = new JScrollPane(listSort);
scrollSort.setMinimumSize(new Dimension(100, 100));
scrollSort.setPreferredSize(new Dimension(150, 200));
scrollSort.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panelSortOrders.add(scrollSort, constraints);
JToolBar toolbarButtons = new JToolBar(SwingConstants.HORIZONTAL);
toolbarButtons.setFloatable(false);
buttonSortAdd = Utilities.createJButton(
"gnome-list-add.png", EnumImageSize.NORMAL, GT._T("Add"), false, null);
buttonSortAdd.addActionListener(EventHandler.create(
ActionListener.class, this, "actionSortAdd"));
toolbarButtons.add(buttonSortAdd);
buttonSortDelete = Utilities.createJButton(
"gnome-list-remove.png", EnumImageSize.NORMAL, GT._T("Delete"), false, null);
buttonSortDelete.addActionListener(EventHandler.create(
ActionListener.class, this, "actionSortDelete"));
toolbarButtons.add(buttonSortDelete);
constraints.gridy++;
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weighty = 0;
panelSortOrders.add(toolbarButtons, constraints);
constraints.gridy++;
// Sort description
JPanel panelSortDescription = new JPanel(new GridBagLayout());
panelSortDescription.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), GT._T("Details")));
constraints.gridy = 0;
constraints.fill = GridBagConstraints.BOTH;
constraints.weighty = 1;
modelSortItem = new DefaultListModel<>();
listSortItem = new JList<>(modelSortItem);
listSortItem.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollSortItem = new JScrollPane(listSortItem);
scrollSortItem.setMinimumSize(new Dimension(100, 100));
scrollSortItem.setPreferredSize(new Dimension(150, 200));
scrollSortItem.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
panelSortDescription.add(scrollSortItem, constraints);
constraints.gridy++;
toolbarButtons = new JToolBar(SwingConstants.HORIZONTAL);
toolbarButtons.setFloatable(false);
buttonSortUp = Utilities.createJButton(
"gnome-go-up.png", EnumImageSize.NORMAL, GT._T("Up"), false, null);
buttonSortUp.addActionListener(EventHandler.create(
ActionListener.class, this, "actionSortMoveUp"));
toolbarButtons.add(buttonSortUp);
buttonSortDown = Utilities.createJButton(
"gnome-go-down.png", EnumImageSize.NORMAL, GT._T("Down"), false, null);
buttonSortDown.addActionListener(EventHandler.create(
ActionListener.class, this, "actionSortMoveDown"));
toolbarButtons.add(buttonSortDown);
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weighty = 0;
panelSortDescription.add(toolbarButtons, constraints);
constraints.gridy++;
if (modelSort.getSize() > 0) {
listSort.setSelectedIndex(0);
}
// Adding panels
constraints.fill = GridBagConstraints.BOTH;
constraints.gridheight = 1;
constraints.gridwidth = 1;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
add(panelSortOrders, constraints);
constraints.gridx++;
add(panelSortDescription, constraints);
}
/**
* Restore all options to their default values.
*/
@Override
public void defaultValues() {
// Sorting orders
modelSort.clear();
List<CompositeComparator<Page>> comparators = PageComparator.getDefaultComparators();
for (CompositeComparator<Page> comparator : comparators) {
modelSort.addElement(comparator);
}
}
/**
* Apply new values to the options.
*/
@SuppressWarnings("unchecked")
@Override
public void apply() {
// Sorting orders
List<CompositeComparator<Page>> comparators = new LinkedList<>();
for (int i = modelSort.getSize(); i > 0; i--) {
Object sort = modelSort.get(i - 1);
if (sort instanceof CompositeComparator) {
comparators.add(0, (CompositeComparator<Page>) sort);
}
}
PageComparator.setComparators(comparators);
}
/**
* Action called when Sort Add button is pressed.
*/
public void actionSortAdd() {
String name = Utilities.askForValue(this.getParent(), "Input name :", "", null);
if (name != null) {
CompositeComparator<Page> comparator = PageComparator.createComparator(name);
modelSort.addElement(comparator);
listSort.setSelectedIndex(modelSort.size() - 1);
}
}
/**
* Action called when Sort Delete button is pressed.
*/
public void actionSortDelete() {
int selected = listSort.getSelectedIndex();
if (selected != -1) {
modelSort.remove(selected);
if (selected < modelSort.size()) {
listSort.setSelectedIndex(selected);
} else if (selected > 0) {
listSort.setSelectedIndex(selected - 1);
}
}
}
/**
* Action called when Sort Up button is pressed.
*/
public void actionSortMoveUp() {
actionSortMove(true);
}
/**
* Action called when Sort Down button is pressed.
*/
public void actionSortMoveDown() {
actionSortMove(false);
}
/**
* Action called when Sort Up / Down button is pressed.
* @param up Flag indicating if it's the Up button.
*/
private void actionSortMove(boolean up) {
CompositeComparator<Page> selectedSort = listSort.getSelectedValue();
NamedComparator<Page> selectedItem = listSortItem.getSelectedValue();
if ((selectedSort != null) &&
(selectedItem != null)) {
CompositeComparator<Page> comparators = selectedSort;
NamedComparator<Page> comparator = selectedItem;
comparators.moveComparator(comparator.getName(), up);
int selected = listSortItem.getSelectedIndex();
selected += up ? -1 : 1;
modelSortItem.clear();
for (int i = 0; i < comparators.getComparatorsCount(); i++) {
NamedComparator<Page> item = comparators.getComparator(i);
modelSortItem.addElement(item);
}
listSortItem.setSelectedIndex(Math.min(Math.max(0, selected), modelSortItem.size() - 1));
}
}
/* ====================================================================== */
/* ListSelectionListener implementation */
/* ====================================================================== */
/* (non-Javadoc)
* @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
*/
@SuppressWarnings("unchecked")
@Override
public void valueChanged(ListSelectionEvent e) {
if ((e == null) || (e.getSource() == null)) {
return;
}
if (e.getSource() == listSort) {
Object value = listSort.getSelectedValue();
if (value instanceof CompositeComparator) {
modelSortItem.clear();
CompositeComparator<Page> comparator = (CompositeComparator<Page>) value;
for (int i = 0; i < comparator.getComparatorsCount(); i++) {
NamedComparator<Page> item = comparator.getComparator(i);
modelSortItem.addElement(item);
}
}
}
}
}
|
924119baedc1643114de4605ed44bb20bb36d257 | 365 | java | Java | src/main/java/dao/NewsForDepartmentDao.java | Laurent-c4/IP-ORGANISATIONAL-API | b8ded8f82f8fc010452f870f8c5ff183c7902294 | [
"Unlicense"
] | null | null | null | src/main/java/dao/NewsForDepartmentDao.java | Laurent-c4/IP-ORGANISATIONAL-API | b8ded8f82f8fc010452f870f8c5ff183c7902294 | [
"Unlicense"
] | null | null | null | src/main/java/dao/NewsForDepartmentDao.java | Laurent-c4/IP-ORGANISATIONAL-API | b8ded8f82f8fc010452f870f8c5ff183c7902294 | [
"Unlicense"
] | null | null | null | 17.380952 | 67 | 0.734247 | 1,001,779 | package dao;
import models.NewsForDepartment;
import java.util.List;
public interface NewsForDepartmentDao {
//CREATE
void add(NewsForDepartment newsForDepartment);
//READ
List<NewsForDepartment> getAll();
NewsForDepartment findById(int id);
List<NewsForDepartment> getAllForADepartment(int departmentId);
//UPDATE
//DELETE
}
|
92411b2bfb3ae0b7da93143ebdced4f6485f01cc | 2,935 | java | Java | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/SqlTimestampComparator.java | aixuebo/flink-1.6 | 9c120d5619b22081b957feb0a3467cf30b0b6c20 | [
"BSD-3-Clause"
] | 80 | 2016-08-11T03:07:28.000Z | 2022-03-27T06:47:09.000Z | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/SqlTimestampComparator.java | aixuebo/flink-1.6 | 9c120d5619b22081b957feb0a3467cf30b0b6c20 | [
"BSD-3-Clause"
] | 204 | 2019-05-21T09:54:29.000Z | 2019-07-26T21:04:30.000Z | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/SqlTimestampComparator.java | aixuebo/flink-1.6 | 9c120d5619b22081b957feb0a3467cf30b0b6c20 | [
"BSD-3-Clause"
] | 40 | 2016-08-12T05:40:51.000Z | 2022-01-11T08:01:04.000Z | 29.646465 | 105 | 0.716865 | 1,001,780 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.api.common.typeutils.base;
import java.io.IOException;
import java.sql.Timestamp;
import org.apache.flink.annotation.Internal;
import org.apache.flink.core.memory.DataInputView;
import org.apache.flink.core.memory.MemorySegment;
/**
* Comparator for comparing Java SQL Timestamps.
*/
@Internal
public final class SqlTimestampComparator extends BasicTypeComparator<java.util.Date> {
private static final long serialVersionUID = 1L;
public SqlTimestampComparator(boolean ascending) {
super(ascending);
}
@Override
public int compareSerialized(DataInputView firstSource, DataInputView secondSource) throws IOException {
// compare Date part
final int comp = DateComparator.compareSerializedDate(firstSource, secondSource, ascendingComparison);
// compare nanos
if (comp == 0) {
final int i1 = firstSource.readInt();
final int i2 = secondSource.readInt();
final int comp2 = (i1 < i2 ? -1 : (i1 == i2 ? 0 : 1));
return ascendingComparison ? comp2 : -comp2;
}
return comp;
}
@Override
public boolean supportsNormalizedKey() {
return true;
}
@Override
public int getNormalizeKeyLen() {
return 12;
}
@Override
public boolean isNormalizedKeyPrefixOnly(int keyBytes) {
return keyBytes < 12;
}
@Override
public void putNormalizedKey(java.util.Date record, MemorySegment target, int offset, int numBytes) {
// put Date key
DateComparator.putNormalizedKeyDate(record, target, offset, numBytes > 8 ? 8 : numBytes);
numBytes -= 8;
offset += 8;
if (numBytes <= 0) {
// nothing to do
}
// put nanos
else if (numBytes < 4) {
final int nanos = ((Timestamp) record).getNanos();
for (int i = 0; numBytes > 0; numBytes--, i++) {
target.put(offset + i, (byte) (nanos >>> ((3-i)<<3)));
}
}
// put nanos with padding
else {
final int nanos = ((Timestamp) record).getNanos();
target.putIntBigEndian(offset, nanos);
for (int i = 4; i < numBytes; i++) {
target.put(offset + i, (byte) 0);
}
}
}
@Override
public SqlTimestampComparator duplicate() {
return new SqlTimestampComparator(ascendingComparison);
}
}
|
92411b30b8ea72ad9f3eb8841fe09d419174deaa | 367 | java | Java | src/main/java/com/example/application/data/entity/SensorGas.java | Burdis28/diplomka | f662a83a1e315541dbc7c253af2d74997b03be9d | [
"Unlicense"
] | 1 | 2021-08-09T23:58:25.000Z | 2021-08-09T23:58:25.000Z | src/main/java/com/example/application/data/entity/SensorGas.java | Burdis28/diplomka | f662a83a1e315541dbc7c253af2d74997b03be9d | [
"Unlicense"
] | 2 | 2021-08-09T22:26:52.000Z | 2021-08-21T23:23:07.000Z | src/main/java/com/example/application/data/entity/SensorGas.java | Burdis28/diplomka | f662a83a1e315541dbc7c253af2d74997b03be9d | [
"Unlicense"
] | null | null | null | 15.291667 | 45 | 0.66485 | 1,001,781 | package com.example.application.data.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class SensorGas {
@Id
private int sensor_id;
public SensorGas() {
}
public int getSensor_id() {
return sensor_id;
}
public void setSensor_id(int sensor_id) {
this.sensor_id = sensor_id;
}
}
|
92411da6d594caf1282b978a86b79a652fbf7912 | 5,340 | java | Java | src/main/java/com/overops/plugins/sonar/model/Event.java | takipi-field/sonar-plugin-overops | 19152e65e38512ade49c3246fa02bd67021c3747 | [
"MIT"
] | null | null | null | src/main/java/com/overops/plugins/sonar/model/Event.java | takipi-field/sonar-plugin-overops | 19152e65e38512ade49c3246fa02bd67021c3747 | [
"MIT"
] | 31 | 2019-09-19T15:03:50.000Z | 2021-06-04T02:29:11.000Z | src/main/java/com/overops/plugins/sonar/model/Event.java | takipi-field/sonar-plugin-overops | 19152e65e38512ade49c3246fa02bd67021c3747 | [
"MIT"
] | 1 | 2020-03-12T13:26:51.000Z | 2020-03-12T13:26:51.000Z | 29.666667 | 137 | 0.699625 | 1,001,782 | package com.overops.plugins.sonar.model;
import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.takipi.api.client.data.event.Location;
import com.takipi.api.client.functions.output.Series;
import com.takipi.api.client.functions.output.SeriesRow;
import com.takipi.api.client.util.regression.RegressionStringUtil;
import org.apache.commons.lang.StringUtils;
/**
* Represents OverOps Events
*
* This makes OverOps as Influx easier to work with
*/
public class Event {
public static final String FIELDS = "id,stack_frames,link,name,type,message,introduced_by,labels,source_file_path,original_line_number";
private int id;
private String link;
private String name;
private String type;
private String message;
private String introducedBy;
private String labels;
private String stackFrames;
private Location location;
private String filePath;
private String deployment;
private String criticalExceptionTypes;
private String sourceFilePath;
private Double originalLineNumber;
public Event(Series<SeriesRow> events, int index, String deployment, String criticalExceptionTypes, String appUrl) {
this.deployment = deployment;
this.criticalExceptionTypes = criticalExceptionTypes;
// order determined by Event.FIELDS: id,stack_frames,link,name,typeMessage,introduced_by
id = Integer.parseInt((String) events.getValue(0, index)); // id
stackFrames = (String) events.getValue(1, index); // stack_frames
link = (String) events.getValue(2, index); // link
name = (String) events.getValue(3, index); // name
type = (String) events.getValue(4, index); // type
message = ((String) events.getValue(5, index)).trim();// message (INTG-538: trim whitespace)
introducedBy = (String) events.getValue(6, index); // introduced_by
labels = (String) events.getValue(7, index); // labels
sourceFilePath = (String) events.getValue(8, index); // source_file_path
originalLineNumber = (Double) events.getValue(9, index); // original_line_number
// format link
link = appUrl + "/tale.html?snapshot=" + link + "&source=70";
// parse stackFrames
if (StringUtils.isBlank(stackFrames)) {
throw new IllegalArgumentException("Missing stack_frames for event id " + id);
}
Type listType = new TypeToken<ArrayList<Location>>(){}.getType();
List<Location> locationList = new Gson().fromJson(stackFrames, listType);
if (locationList.isEmpty()){
throw new IllegalArgumentException("Missing location for event id " + id);
}
// there is only one location in the list
// ----> with .NET apparently this doesn't hold true
location = locationList.get(0);
if (!sourceFilePath.isEmpty()) {
// use source file path if available (CS)
filePath = sourceFilePath;
// this cast makes me uncomfortable, but it's really an int to begin with...
location.original_line_number = (int) Math.round(originalLineNumber);
} else {
// compute file patch match pattern (Java)
// match **/com/example/path/ClassName.java
StringBuilder matchPattern = new StringBuilder("**");
matchPattern.append(File.separator);
matchPattern.append(location.class_name.replace(".", File.separator));
matchPattern.append(".java");
filePath = matchPattern.toString();
}
}
public int getId() {
return id;
}
public String getLink() {
return link;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
// friendly, formatted issue message
public String getMessage() {
StringBuilder sb = new StringBuilder();
if (isNew()) sb.append("New, ");
if (isCritical()) sb.append("Critical, ");
if (isResurfaced()) sb.append("Resurfaced, ");
sb.append(type);
sb.append(": ");
sb.append(message);
return sb.toString();
}
public String getIntroducedBy() {
return introducedBy;
}
public String getLabels() {
return labels;
}
public Location getLocation() {
return location;
}
public String getFilePath() {
return filePath;
}
public String getDeployment() {
return deployment;
}
// makes adding to hashmap more clear
public String getKey() {
return getFilePath();
}
// quality gates (see com.takipi.api.client.util.cicd.ProcessQualityGates)
public boolean isNew() {
return deployment.contains(introducedBy);
}
public boolean isCritical() {
return criticalExceptionTypes.contains(name);
}
public boolean isResurfaced() {
return labels.contains(RegressionStringUtil.RESURFACED_ISSUE);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj == null || obj.getClass() != this.getClass()) {
return false;
}
Event that = (Event) obj;
return this.id == that.getId();
}
@Override
public int hashCode() {
return this.id;
}
@Override
public String toString() {
return "Event [criticalExceptionTypes=" + criticalExceptionTypes + ", deployment=" + deployment + ", filePath="
+ filePath + ", id=" + id + ", introducedBy=" + introducedBy + ", labels=" + labels + ", link=" + link
+ ", location=" + location + ", message=" + message + ", name=" + name + ", stackFrames=" + stackFrames
+ ", type=" + type + "]";
}
}
|
92411e65a05432d969bf211419c5527f73a97dd8 | 5,395 | java | Java | src/main/java/com/publiccms/entities/sys/SysAppClient.java | 258506801/cms | 4b0f1a10100e32626dadebfeeffa14ea1eb4f513 | [
"MIT"
] | 5 | 2016-12-06T07:03:08.000Z | 2021-06-03T07:40:00.000Z | src/main/java/com/publiccms/entities/sys/SysAppClient.java | 258506801/cms | 4b0f1a10100e32626dadebfeeffa14ea1eb4f513 | [
"MIT"
] | null | null | null | src/main/java/com/publiccms/entities/sys/SysAppClient.java | 258506801/cms | 4b0f1a10100e32626dadebfeeffa14ea1eb4f513 | [
"MIT"
] | 1 | 2017-04-11T06:44:44.000Z | 2017-04-11T06:44:44.000Z | 27.247475 | 122 | 0.649676 | 1,001,783 | package com.publiccms.entities.sys;
// Generated 2016-3-1 16:21:35 by Hibernate Tools 4.3.1
import static javax.persistence.GenerationType.IDENTITY;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import com.sanluan.common.source.entity.MyColumn;
/**
* AppClient generated by hbm2java
*/
@Entity
@Table(name = "sys_app_client", uniqueConstraints = @UniqueConstraint(columnNames = { "site_id", "uuid", "channel" }))
public class SysAppClient implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@MyColumn(title = "ID")
private Long id;
@MyColumn(title = "站点", condition = true)
private int siteId;
@MyColumn(title = "渠道", condition = true)
private String channel;
@MyColumn(title = "唯一标识符")
private String uuid;
@MyColumn(title = "用户ID", condition = true)
private Long userId;
@MyColumn(title = "版本")
private String clientVersion;
@MyColumn(title = "允许推送", condition = true)
private boolean allowPush;
@MyColumn(title = "推送授权码")
private String pushToken;
@MyColumn(title = "上次登录日期", condition = true, order = true)
private Date lastLoginDate;
@MyColumn(title = "上次登陆IP")
private String lastLoginIp;
@MyColumn(title = "创建日期", condition = true, order = true)
private Date createDate;
@MyColumn(title = "已禁用", condition = true)
private boolean disabled;
public SysAppClient() {
}
public SysAppClient(int siteId, String channel, String uuid, String clientVersion, boolean allowPush, Date createDate,
boolean disabled) {
this.siteId = siteId;
this.channel = channel;
this.uuid = uuid;
this.clientVersion = clientVersion;
this.allowPush = allowPush;
this.createDate = createDate;
this.disabled = disabled;
}
public SysAppClient(int siteId, String channel, String uuid, Long userId, String clientVersion, boolean allowPush,
String pushToken, Date lastLoginDate, String lastLoginIp, Date createDate, boolean disabled) {
this.siteId = siteId;
this.channel = channel;
this.uuid = uuid;
this.userId = userId;
this.clientVersion = clientVersion;
this.allowPush = allowPush;
this.pushToken = pushToken;
this.lastLoginDate = lastLoginDate;
this.lastLoginIp = lastLoginIp;
this.createDate = createDate;
this.disabled = disabled;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
@Column(name = "site_id", nullable = false)
public int getSiteId() {
return this.siteId;
}
public void setSiteId(int siteId) {
this.siteId = siteId;
}
@Column(name = "channel", nullable = false, length = 20)
public String getChannel() {
return this.channel;
}
public void setChannel(String channel) {
this.channel = channel;
}
@Column(name = "uuid", nullable = false, length = 50)
public String getUuid() {
return this.uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Column(name = "user_id")
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
@Column(name = "client_version", nullable = false, length = 50)
public String getClientVersion() {
return this.clientVersion;
}
public void setClientVersion(String clientVersion) {
this.clientVersion = clientVersion;
}
@Column(name = "allow_push", nullable = false)
public boolean isAllowPush() {
return this.allowPush;
}
public void setAllowPush(boolean allowPush) {
this.allowPush = allowPush;
}
@Column(name = "push_token", length = 50)
public String getPushToken() {
return this.pushToken;
}
public void setPushToken(String pushToken) {
this.pushToken = pushToken;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "last_login_date", length = 19)
public Date getLastLoginDate() {
return this.lastLoginDate;
}
public void setLastLoginDate(Date lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
@Column(name = "last_login_ip", length = 64)
public String getLastLoginIp() {
return this.lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "create_date", nullable = false, length = 19)
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Column(name = "disabled", nullable = false)
public boolean isDisabled() {
return this.disabled;
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
}
|
92411f001d20a40aebf918bc4d56c7c175bffcec | 860 | java | Java | jxen-svg-core/src/main/java/com/github/jxen/svg/transform/SkewYHelper.java | jxen/jxen-svg | e998c21f5b7f0b6b1c055fd8b5de1b0caa6d6d7f | [
"Apache-2.0"
] | null | null | null | jxen-svg-core/src/main/java/com/github/jxen/svg/transform/SkewYHelper.java | jxen/jxen-svg | e998c21f5b7f0b6b1c055fd8b5de1b0caa6d6d7f | [
"Apache-2.0"
] | null | null | null | jxen-svg-core/src/main/java/com/github/jxen/svg/transform/SkewYHelper.java | jxen/jxen-svg | e998c21f5b7f0b6b1c055fd8b5de1b0caa6d6d7f | [
"Apache-2.0"
] | null | null | null | 26.875 | 99 | 0.684884 | 1,001,784 | package com.github.jxen.svg.transform;
import com.github.jxen.math.linear.Matrix;
import com.github.jxen.svg.format.FormatHelper;
import java.util.List;
class SkewYHelper implements TransformHelper {
@Override
public Transform create(List<Double> values) {
return Transform.skewY(values.get(0));
}
@Override
public boolean test(Matrix matrix) {
if (!matrix.isZero(0, 2) || !matrix.isZero(1, 2)) {
return false;
}
return matrix.isOne(0, 0) && matrix.isZero(0, 1) && !matrix.isZero(1, 0) && matrix.isOne(1, 1);
}
@Override
public String toString(Transform transform) {
Matrix m = transform.toMatrix();
double angle = Math.toDegrees(Math.atan(m.get(1, 0)));
FormatHelper helper = format();
StringBuilder builder = new StringBuilder();
helper.add(angle, builder);
return builder.toString();
}
}
|
92411f58b2a4ab247c3e452870fbdb58597f1a79 | 5,106 | java | Java | src/main/java/net/openhft/chronicle/hash/impl/stage/query/HashQuery.java | Cotton-Ben/Chronicle-Map | 65bfd79569ea4f341bdfc93607e45e5a24755507 | [
"Apache-2.0"
] | 2,421 | 2015-01-02T14:44:52.000Z | 2022-03-31T04:02:16.000Z | src/main/java/net/openhft/chronicle/hash/impl/stage/query/HashQuery.java | Cotton-Ben/Chronicle-Map | 65bfd79569ea4f341bdfc93607e45e5a24755507 | [
"Apache-2.0"
] | 331 | 2015-01-03T13:56:35.000Z | 2022-03-30T23:06:48.000Z | src/main/java/net/openhft/chronicle/hash/impl/stage/query/HashQuery.java | Cotton-Ben/Chronicle-Map | 65bfd79569ea4f341bdfc93607e45e5a24755507 | [
"Apache-2.0"
] | 499 | 2015-01-13T18:54:33.000Z | 2022-03-31T04:02:17.000Z | 34.04 | 95 | 0.661966 | 1,001,785 | /*
* Copyright 2012-2018 Chronicle Map Contributors
*
* 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 net.openhft.chronicle.hash.impl.stage.query;
import net.openhft.chronicle.hash.Data;
import net.openhft.chronicle.hash.impl.VanillaChronicleHashHolder;
import net.openhft.chronicle.hash.impl.stage.entry.HashEntryStages;
import net.openhft.chronicle.hash.impl.stage.entry.HashLookupPos;
import net.openhft.chronicle.hash.impl.stage.entry.HashLookupSearch;
import net.openhft.chronicle.hash.impl.stage.entry.SegmentStages;
import net.openhft.chronicle.hash.impl.stage.hash.CheckOnEachPublicOperation;
import net.openhft.chronicle.hash.serialization.DataAccess;
import net.openhft.chronicle.set.SetEntry;
import net.openhft.sg.Stage;
import net.openhft.sg.StageRef;
import net.openhft.sg.Staged;
import static net.openhft.chronicle.hash.impl.stage.query.KeySearch.SearchState.ABSENT;
@Staged
public abstract class HashQuery<K> implements SetEntry<K> {
@StageRef
public VanillaChronicleHashHolder<K> hh;
final DataAccess<K> innerInputKeyDataAccess = hh.h().keyDataAccess.copy();
@StageRef
public SegmentStages s;
@StageRef
public HashEntryStages<K> entry;
@StageRef
public HashLookupSearch hashLookupSearch;
@StageRef
public CheckOnEachPublicOperation checkOnEachPublicOperation;
@StageRef
public HashLookupPos hlp;
@StageRef
public KeySearch<K> ks;
/**
* This stage exists for hooking {@link #innerInputKeyDataAccess} usage, to trigger {@link
* DataAccess#uninit()} on context exit
*/
@Stage("InputKeyDataAccess")
private boolean inputKeyDataAccessInitialized = false;
@Stage("PresenceOfEntry")
private EntryPresence entryPresence = null;
void initInputKeyDataAccess() {
inputKeyDataAccessInitialized = true;
}
void closeInputKeyDataAccess() {
innerInputKeyDataAccess.uninit();
inputKeyDataAccessInitialized = false;
}
public DataAccess<K> inputKeyDataAccess() {
initInputKeyDataAccess();
return innerInputKeyDataAccess;
}
public void dropSearchIfNestedContextsAndPresentHashLookupSlotCheckFailed() {
if (s.locksInit()) {
if (s.nestedContextsLockedOnSameSegment &&
s.rootContextLockedOnThisSegment.latestSameThreadSegmentModCount() !=
s.contextModCount) {
if (ks.keySearchInit() && ks.searchStatePresent() &&
!hashLookupSearch.checkSlotContainsExpectedKeyAndValue(entry.pos)) {
hlp.closeHashLookupPos();
}
}
}
}
public Data<K> queriedKey() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
return ks.inputKey;
}
private void initPresenceOfEntry() {
if (ks.searchStatePresent() || tieredEntryPresent()) {
entryPresence = EntryPresence.PRESENT;
} else {
entryPresence = EntryPresence.ABSENT;
}
}
public void initPresenceOfEntry(EntryPresence entryPresence) {
this.entryPresence = entryPresence;
}
private boolean tieredEntryPresent() {
int firstTier = s.tier;
long firstTierBaseAddr = s.tierBaseAddr;
while (true) {
if (s.hasNextTier()) {
s.nextTier();
} else {
if (s.tier != 0)
s.initSegmentTier(); // loop to the root tier
}
if (s.tierBaseAddr == firstTierBaseAddr)
break;
if (ks.searchStatePresent())
return true;
}
// not found
if (firstTier != 0) {
// key is absent; probably are going to allocate a new entry;
// start trying from the root tier
s.initSegmentTier();
}
return false;
}
public boolean entryPresent() {
return entryPresence == EntryPresence.PRESENT;
}
@Override
public void doRemove() {
checkOnEachPublicOperation.checkOnEachPublicOperation();
s.innerWriteLock.lock();
if (ks.searchStatePresent()) {
entry.innerRemoveEntryExceptHashLookupUpdate();
hashLookupSearch.remove();
ks.setSearchState(ABSENT);
initPresenceOfEntry(EntryPresence.ABSENT);
} else {
throw new IllegalStateException(
hh.h().toIdentityString() + ": Entry is absent when doRemove() is called");
}
}
public enum EntryPresence {PRESENT, ABSENT}
}
|
92411fad400f7e50f19fc691a71d76c210857a9a | 2,587 | java | Java | sdsensor/src/main/java/at/ac/tuwien/infosys/sensor/DataProvider.java | tuwiendsg/SDM | 3bc2279399bc562999f1a2747759983fb1731df8 | [
"Apache-2.0"
] | 2 | 2016-03-20T08:55:26.000Z | 2016-03-20T08:56:52.000Z | sdsensor/src/main/java/at/ac/tuwien/infosys/sensor/DataProvider.java | tuwiendsg/SDM | 3bc2279399bc562999f1a2747759983fb1731df8 | [
"Apache-2.0"
] | null | null | null | sdsensor/src/main/java/at/ac/tuwien/infosys/sensor/DataProvider.java | tuwiendsg/SDM | 3bc2279399bc562999f1a2747759983fb1731df8 | [
"Apache-2.0"
] | null | null | null | 29.735632 | 130 | 0.555083 | 1,001,786 | package at.ac.tuwien.infosys.sensor;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import org.apache.log4j.Logger;
import at.ac.tuwien.infosys.sensor.GenericDataInstance.Record;
public class DataProvider implements Runnable {
public static DataProvider provider;
private static final Object lock = new Object();
private static Logger LOGGER = Logger.getLogger(DataProvider.class);
static {
provider = new DataProvider();
}
public static DataProvider getProvider() {
//// synchronized (lock) {
// if (provider == null) {
// provider = new DataProvider();
// }
return provider;
// }
}
private Stack<GenericDataInstance> dataInstances = new Stack<GenericDataInstance>();
public void run() {
if (dataInstances.size() == 0) {
LOGGER.info(String.format("Reading csv file"));
InputStreamReader reader = new InputStreamReader(DataProvider.class.getClassLoader().getResourceAsStream("data.csv"));
BufferedReader br = new BufferedReader(reader);
try {
String firstLine = br.readLine();
String headers[] = firstLine.split(",");
String line;
while ((line = br.readLine()) != null) {
String[] split = line.split(",");
List<Record> records = new ArrayList<Record>();
for (int i = 1; i < split.length; i++) {
Record r = new Record(headers[i], split[i]);
records.add(r);
}
GenericDataInstance ginst = new GenericDataInstance(split[0], records);
dataInstances.push(ginst);
}
br.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
e.printStackTrace();
}
} else {
LOGGER.info(String.format("Data stack not empty yet"));
}
// }
// };
// refreshDataTimer = new Timer(true);
// refreshDataTimer.schedule(task, 0, 1000);
}
private DataProvider() {
}
public GenericDataInstance getNextInstance() {
// FIXME: reading data in reverse order
if (this.dataInstances.isEmpty()) {
return null;
} else {
return this.dataInstances.pop();
}
}
}
|
924120cffe25bee4e68460a3de3ff8906c09d006 | 1,707 | java | Java | src/main/java/sgf/gateway/web/controllers/oai/ListRecordsRequest.java | NCAR/sage-gateway-archive | e6f4f3a7cd142efac143dd6a956c77a1a0856a6a | [
"Apache-2.0"
] | null | null | null | src/main/java/sgf/gateway/web/controllers/oai/ListRecordsRequest.java | NCAR/sage-gateway-archive | e6f4f3a7cd142efac143dd6a956c77a1a0856a6a | [
"Apache-2.0"
] | null | null | null | src/main/java/sgf/gateway/web/controllers/oai/ListRecordsRequest.java | NCAR/sage-gateway-archive | e6f4f3a7cd142efac143dd6a956c77a1a0856a6a | [
"Apache-2.0"
] | null | null | null | 25.863636 | 160 | 0.672525 | 1,001,787 | package sgf.gateway.web.controllers.oai;
import org.hibernate.validator.constraints.NotBlank;
import sgf.gateway.validation.data.ValidDate;
import sgf.gateway.validation.data.ValidTemporalBoundsDates;
import sgf.gateway.validation.groups.Type;
import java.util.Date;
@ValidTemporalBoundsDates(startDateField = "from", endDateField = "until", format = "yyyy-MM-dd'T'HH:mm:ss'Z'", message = "From Date must be before Until Date")
public class ListRecordsRequest extends OAIRequest implements ListRequest {
private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
@ValidDate(groups = Type.class, format = DATE_FORMAT, message = "From Date must use the following format: yyyy-MM-dd'T'HH:mm:ss'Z'")
private Date from;
@ValidDate(groups = Type.class, format = DATE_FORMAT, message = "Until Date must use the following format: yyyy-MM-dd'T'HH:mm:ss'Z'")
private Date until;
private String set;
@NotBlank(message = "metadataPrefix is required")
private String metadataPrefix;
public ListRecordsRequest() {
super();
}
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getUntil() {
return until;
}
public void setUntil(Date until) {
this.until = until;
}
public String getSet() {
return set;
}
public void setSet(String set) {
this.set = set;
}
public String getMetadataPrefix() {
return metadataPrefix;
}
public void setMetadataPrefix(String metadataPrefix) {
this.metadataPrefix = metadataPrefix;
}
public int getOffset() {
return 0;
}
}
|
924121bf7ca9005970cbc80b006e693f2d8673c8 | 1,270 | java | Java | integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/general/SnmpTypeEnum.java | chardon1/onap-sdc | b2370800befb9c7c557a0651717a8fd604736542 | [
"Apache-2.0"
] | 15 | 2018-10-02T14:54:35.000Z | 2022-03-01T18:27:14.000Z | integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/general/SnmpTypeEnum.java | chardon1/onap-sdc | b2370800befb9c7c557a0651717a8fd604736542 | [
"Apache-2.0"
] | 6 | 2021-12-14T21:00:42.000Z | 2022-02-27T17:07:08.000Z | integration-tests/src/test/java/org/onap/sdc/backend/ci/tests/utils/general/SnmpTypeEnum.java | chardon1/onap-sdc | b2370800befb9c7c557a0651717a8fd604736542 | [
"Apache-2.0"
] | 31 | 2018-05-30T19:18:29.000Z | 2022-03-01T06:16:47.000Z | 32.564103 | 83 | 0.534646 | 1,001,788 | /*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.onap.sdc.backend.ci.tests.utils.general;
enum SnmpTypeEnum{
SNMP_POLL ("snmp"),
SNMP_TRAP ("snmp-trap");
private String value;
public String getValue() {
return value;
}
private SnmpTypeEnum(String value) {
this.value = value;
}
}
|
924122ac48bd10b821153a2bc1d9043c4d363fb8 | 1,849 | java | Java | shared/communication/src/main/java/com/alibaba/otter/shared/communication/core/impl/connection/CommunicationConnectionPoolable.java | Delibit/otter | ac287f8225ced8dc9836a8991d493545c8ac92ac | [
"Apache-2.0"
] | 7,113 | 2015-01-04T02:49:19.000Z | 2022-03-31T08:23:20.000Z | shared/communication/src/main/java/com/alibaba/otter/shared/communication/core/impl/connection/CommunicationConnectionPoolable.java | stateIs0/otter | a939897df75ae8aafdcbbbce0205d13ac87d6fdb | [
"Apache-2.0"
] | 987 | 2015-01-05T04:40:43.000Z | 2022-03-30T11:12:19.000Z | shared/communication/src/main/java/com/alibaba/otter/shared/communication/core/impl/connection/CommunicationConnectionPoolable.java | stateIs0/otter | a939897df75ae8aafdcbbbce0205d13ac87d6fdb | [
"Apache-2.0"
] | 2,403 | 2015-01-05T09:24:38.000Z | 2022-03-31T06:43:37.000Z | 31.87931 | 120 | 0.737155 | 1,001,789 | /*
* Copyright (C) 2010-2101 Alibaba Group Holding Limited.
*
* 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.alibaba.otter.shared.communication.core.impl.connection;
import com.alibaba.otter.shared.communication.core.exception.CommunicationException;
import com.alibaba.otter.shared.communication.core.model.CommunicationParam;
import com.alibaba.otter.shared.communication.core.model.Event;
/**
* 可被链接池管理的对象, @see {@linkplain CommunicationConnectionPoolableFactory}
*
* @author jianghang 2011-9-9 下午05:01:14
*/
public class CommunicationConnectionPoolable implements CommunicationConnection {
private CommunicationConnectionPoolFactory pool;
private CommunicationConnection delegate;
public CommunicationConnectionPoolable(CommunicationConnection connection, CommunicationConnectionPoolFactory pool){
this.delegate = connection;
this.pool = pool;
}
public Object call(Event event) {
return getDelegate().call(event);
}
public void close() throws CommunicationException {
pool.releaseConnection(this);
}
public CommunicationParam getParams() {
return getDelegate().getParams();
}
/**
* @return 返回原始connection对象
*/
public CommunicationConnection getDelegate() {
return this.delegate;
}
}
|
924123f83ee602784708b8b94a73d66c834428df | 13,905 | java | Java | src/main/java/it/polito/tdp/TasteTrip/FXMLController.java | TdP-prove-finali/PalmisanoVito | 1c38ed84921f6dac8865955d7a330e6a69f44002 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/polito/tdp/TasteTrip/FXMLController.java | TdP-prove-finali/PalmisanoVito | 1c38ed84921f6dac8865955d7a330e6a69f44002 | [
"Apache-2.0"
] | null | null | null | src/main/java/it/polito/tdp/TasteTrip/FXMLController.java | TdP-prove-finali/PalmisanoVito | 1c38ed84921f6dac8865955d7a330e6a69f44002 | [
"Apache-2.0"
] | 2 | 2020-09-21T07:02:27.000Z | 2022-03-30T09:07:05.000Z | 35.837629 | 226 | 0.611938 | 1,001,790 | package it.polito.tdp.TasteTrip;
import java.net.URL;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import it.polito.tdp.TasteTrip.model.Comune;
import it.polito.tdp.TasteTrip.model.Model;
import it.polito.tdp.TasteTrip.model.Percorso;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
public class FXMLController {
private Model model;
@FXML
private ResourceBundle resources;
@FXML
private URL location;
@FXML
private ComboBox<String> cmbProvincia;
@FXML
private ComboBox<Comune> cmbComune;
@FXML
private CheckBox ckCitta;
@FXML
private CheckBox ckFormazione;
@FXML
private CheckBox ckNatura;
@FXML
private CheckBox ckStoria;
@FXML
private CheckBox ckMusei;
@FXML
private CheckBox ckCulto;
@FXML
private CheckBox ckSport;
@FXML
private CheckBox ckLocMare;
@FXML
private CheckBox ckLido;
@FXML
private DatePicker dpkAndata;
@FXML
private DatePicker dpkRitorno;
@FXML
private TextField txtBudget;
@FXML
private TextField txtDistanzaMax;
@FXML
private TextField txtNumPersone;
@FXML
private Button btnReset;
@FXML
private Button btnCalcola;
@FXML
private TextArea txtResult;
@FXML
void riempiComuni(ActionEvent event) {
cmbComune.getItems().clear();
if(cmbProvincia.getValue() != null) {
String sigla;
switch(cmbProvincia.getValue()){
case "Bari":
sigla = "BA";
break;
case "Barletta-Andria-Trani":
sigla = "BT";
break;
case "Brindisi":
sigla = "BR";
break;
case "Foggia":
sigla = "FG";
break;
case "Lecce":
sigla = "LE";
break;
case "Taranto":
sigla = "TA";
break;
default:
sigla = "";
}
cmbComune.getItems().addAll(model.getCommuniByProvincia(sigla));
}
}
@FXML
void doCalcolo(ActionEvent event) {
txtResult.clear();
// ----- Effettuo i controlli sui dati inseriti dall'utente -----
if(cmbProvincia.getValue()==null) {
txtResult.setText("Prima di effettuare una ricerca, selezionare la provincia che si vorrebbe visitare.");
return;
}
if(!ckCitta.isSelected() && !ckFormazione.isSelected() && !ckNatura.isSelected() &&
!ckStoria.isSelected() && !ckMusei.isSelected() && !ckCulto.isSelected() &&
!ckSport.isSelected() && !ckLocMare.isSelected() && !ckLido.isSelected()) {
txtResult.setText("Prima di effettuare una ricerca, selezionare almeno una delle attivita' disponibili.");
return;
}
if(dpkAndata.getValue()==null) {
txtResult.setText("Prima di effettuare una ricerca, selezionare la data di andata.");
return;
}
if(dpkRitorno.getValue()==null) {
txtResult.setText("Prima di effettuare una ricerca, selezionare la data di ritorno.");
return;
}
LocalDate andata = dpkAndata.getValue();
LocalDate ritorno = dpkRitorno.getValue();
if(andata.isBefore(LocalDate.now()) || andata.equals(LocalDate.now())) { // Imposto arbitrariamente che non sia possibile cercare un viaggio nello stesso giorno in cui si effettua la ricerca
txtResult.setText("Le date selezionate devono essere successive al giorno odierno.");
return;
}
if(ritorno.isBefore(andata)) { // Potrei decidere di fare un viaggio di un solo giorno, quindi avrei andata=ritorno
txtResult.setText("Il ritorno dev'essere uguale o seguente all'andata.");
return;
}
long numGiorni = ChronoUnit.DAYS.between(andata, ritorno)+1;
int numPersone;
double spesaMax;
int distanzaMax;
try {
numPersone = Integer.parseInt(txtNumPersone.getText());
}catch(NumberFormatException nfe) {
txtResult.appendText("Prima di effettuare una ricerca, impostare un valore numerico intero per il numero di viaggiatori.");
return;
}
try {
String s = txtBudget.getText();
if( s.matches("^0(\\.\\d{1,2})?$|^[1-9]\\d*(\\.\\d{1,2})?$") ) {
spesaMax = Double.parseDouble(s);
}
else {
txtResult.appendText("Prima di effettuare una ricerca, impostare un valore valido, in euro, per la spesa massima che si vorrebbee effettuare.\nUtilizzare il punto \".\" per separare le cifre intere dai decimali");
return;
}
}catch(NumberFormatException nfe) {
txtResult.appendText("Prima di effettuare una ricerca, impostare un valore valido, espresso in euro, per la spesa massima che si vorrebbe effettuare.\nUtilizzare il punto \".\" per separare le cifre intere dai decimali");
return;
}
try {
distanzaMax = Integer.parseInt(txtDistanzaMax.getText());
}catch(NumberFormatException nfe) {
txtResult.appendText("Prima di effettuare una ricerca, impostare un valore numerico intero, espresso in km, per la distanza massima che si e' disposti a percorrere.");
return;
}
// ----- Setto nel model le variabili inserite dall'utente -----
model.setVariabiliUtente(numGiorni, numPersone, spesaMax, distanzaMax);
// ----- Seleziono i comuni in base alle scelte dell'utente -----
if(cmbComune.getValue()==null) {
String sigla;
switch(cmbProvincia.getValue()){
case "Bari":
sigla = "BA";
break;
case "Barletta-Andria-Trani":
sigla = "BT";
break;
case "Brindisi":
sigla = "BR";
break;
case "Foggia":
sigla = "FG";
break;
case "Lecce":
sigla = "LE";
break;
case "Taranto":
sigla = "TA";
break;
default:
sigla = "";
}
model.addComuniBySelezioneProvincia(sigla);
}
else {
model.addComuniBySelezioneSpecificaComune(cmbComune.getValue());
}
// ----- Seleziono i B&B idonei -----
model.addBeBComune(cmbComune.getValue());
// ----- Raccolgo le scelte effettuate sulle attivita' -----
List<String> tipologieAttivitaTuristiche = new ArrayList<String>();
List<String> tipologieLuoghiInteresse = new ArrayList<String>();
if(ckCitta.isSelected()) {
tipologieLuoghiInteresse.add(ckCitta.getText());
tipologieAttivitaTuristiche.add(ckCitta.getText());
}
if(ckFormazione.isSelected()) {
tipologieAttivitaTuristiche.add(ckFormazione.getText());
}
if(ckNatura.isSelected()) {
tipologieLuoghiInteresse.add(ckNatura.getText());
tipologieAttivitaTuristiche.add(ckNatura.getText());
}
if(ckStoria.isSelected()) {
tipologieLuoghiInteresse.add(ckStoria.getText());
}
if(ckMusei.isSelected()) {
tipologieLuoghiInteresse.add(ckMusei.getText());
}
if(ckCulto.isSelected()) {
tipologieLuoghiInteresse.add(ckCulto.getText());
}
if(ckSport.isSelected()) {
tipologieLuoghiInteresse.add(ckSport.getText());
tipologieAttivitaTuristiche.add(ckSport.getText());
}
if(ckLocMare.isSelected()) {
tipologieLuoghiInteresse.add(ckLocMare.getText());
}
// ----- Richiamo i metodi del model per aggiungere le attivita' selezionate -----
if(ckLido.isSelected()) {
if( ( andata.isAfter(LocalDate.of(andata.getYear(), 4, 30))
&& andata.isBefore(LocalDate.of(andata.getYear(), 9, 30)) )
|| ( ritorno.isBefore(LocalDate.of(ritorno.getYear(), 9, 30))
&& ritorno.isAfter(LocalDate.of(ritorno.getYear(), 4, 30)) ) ) {
model.addStabilimentiBalneariComuni();
}
else {
txtResult.setText("Non e' possibile selezionare la voce 'Stabilimenti balneari' se non si rientra nel periodo 01/05 - 30/09");
return;
}
}
if(!tipologieAttivitaTuristiche.isEmpty()) {
model.addAttivitaTuristicheComuni(tipologieAttivitaTuristiche);
}
if(!tipologieLuoghiInteresse.isEmpty()) {
model.addLuoghiInteresseComuni(tipologieLuoghiInteresse);
}
// ----- Creo il grafo -----
// model.creaGrafo();
// ----- Cerco il viaggio più confortevole e 'lussuoso', rispettando i vincoli dell'utente -----
Percorso bestPercorso = model.ricorsione(cmbComune.getValue());
if( !bestPercorso.getAttivita().isEmpty() ) {
txtResult.setText("Il viaggio piu' confortevole e lussuoso che rispetta le caratteristiche volute e':\n\n");
}
txtResult.appendText(bestPercorso.toString());
if(!model.getAltriPercorsi().isEmpty()) {
if(model.getAltriPercorsi().size()<10) {
txtResult.appendText("\n\nDi seguito vengono elencati i "+model.getAltriPercorsi().size()+" percorsi migliori subito dopo quello già riportato:");
}
else {
txtResult.appendText("\n\nDi seguito vengono elencati i 10 percorsi migliori subito dopo quello già riportato:");
}
int i = 1;
for(Percorso p : model.getAltriPercorsi()) {
if(i<=10) {
txtResult.appendText("\n\n"+i+") "+p);
i++;
}
}
}
}
@FXML
void doReset(ActionEvent event) {
cmbProvincia.setValue(null);
cmbComune.getItems().clear();
ckCitta.setSelected(false);
ckFormazione.setSelected(false);
ckNatura.setSelected(false);
ckStoria.setSelected(false);
ckMusei.setSelected(false);
ckCulto.setSelected(false);
ckSport.setSelected(false);
ckLocMare.setSelected(false);
ckLido.setSelected(false);
dpkAndata.setValue(null);
dpkRitorno.setValue(null);
txtBudget.clear();
txtDistanzaMax.clear();
txtNumPersone.clear();
txtResult.setText("Selezionare la provincia che si vorrebbe visitare ed almeno una delle attivita' disponibili.\n"
+ "Il campo comune puo' essere lasciato deselezionato se non si vuole scendere cosi' nello specifico.\n"
+ "Tutti gli altri campi vanno invece riempiti obbligatoriamente secondo le proprie esigenze.");
}
@FXML
void initialize() {
assert cmbProvincia != null : "fx:id=\"cmbProvincia\" was not injected: check your FXML file 'Scene.fxml'.";
assert cmbComune != null : "fx:id=\"cmbComune\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckCitta != null : "fx:id=\"ckCitta\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckFormazione != null : "fx:id=\"ckFormazione\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckNatura != null : "fx:id=\"ckNatura\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckStoria != null : "fx:id=\"ckStoria\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckMusei != null : "fx:id=\"ckMusei\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckCulto != null : "fx:id=\"ckCulto\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckSport != null : "fx:id=\"ckSport\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckLocMare != null : "fx:id=\"ckLocMare\" was not injected: check your FXML file 'Scene.fxml'.";
assert ckLido != null : "fx:id=\"ckLido\" was not injected: check your FXML file 'Scene.fxml'.";
assert dpkAndata != null : "fx:id=\"dpkAndata\" was not injected: check your FXML file 'Scene.fxml'.";
assert dpkRitorno != null : "fx:id=\"dpkRitorno\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtBudget != null : "fx:id=\"txtBudget\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtDistanzaMax != null : "fx:id=\"txtDistanzaMax\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtNumPersone != null : "fx:id=\"txtNumPersone\" was not injected: check your FXML file 'Scene.fxml'.";
assert btnReset != null : "fx:id=\"btnReset\" was not injected: check your FXML file 'Scene.fxml'.";
assert btnCalcola != null : "fx:id=\"btnCalcola\" was not injected: check your FXML file 'Scene.fxml'.";
assert txtResult != null : "fx:id=\"txtResult\" was not injected: check your FXML file 'Scene.fxml'.";
}
public void setModel(Model model) {
this.model = model;
this.inizializzaScene();
}
private void inizializzaScene() {
cmbProvincia.getItems().addAll("Bari", "Barletta-Andria-Trani", "Brindisi", "Foggia", "Lecce", "Taranto");
txtResult.setText("Selezionare la provincia che si vorrebbe visitare ed almeno una delle attivita' disponibili.\n"
+ "Il campo comune puo' essere lasciato deselezionato se non si vuole scendere cosi' nello specifico.\n"
+ "Tutti gli altri campi vanno invece riempiti obbligatoriamente secondo le proprie esigenze.");
}
}
|
9241253cbcd82a934574584952953f870e1e12a8 | 3,052 | java | Java | src/main/java/duelistmod/cards/pools/naturia/CrystalRose.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 3 | 2019-06-20T08:52:04.000Z | 2020-06-17T19:32:05.000Z | src/main/java/duelistmod/cards/pools/naturia/CrystalRose.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 7 | 2019-04-22T12:26:08.000Z | 2021-01-18T02:45:58.000Z | src/main/java/duelistmod/cards/pools/naturia/CrystalRose.java | ascriptmaster/StS-DuelistMod | 251c29117779f0e75c3424263e669b720f35ed1a | [
"Unlicense"
] | 2 | 2019-12-06T14:30:34.000Z | 2020-03-29T15:43:02.000Z | 27.25 | 97 | 0.707733 | 1,001,791 | package duelistmod.cards.pools.naturia;
import com.megacrit.cardcrawl.cards.AbstractCard;
import com.megacrit.cardcrawl.characters.AbstractPlayer;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.localization.CardStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import duelistmod.DuelistMod;
import duelistmod.abstracts.DuelistCard;
import duelistmod.helpers.Util;
import duelistmod.patches.AbstractCardEnum;
import duelistmod.powers.SummonPower;
import duelistmod.variables.Tags;
public class CrystalRose extends DuelistCard
{
// TEXT DECLARATION
public static final String ID = DuelistMod.makeID("CrystalRose");
private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID);
public static final String IMG = DuelistMod.makeCardPath("CrystalRose.png");
public static final String NAME = cardStrings.NAME;
public static final String DESCRIPTION = cardStrings.DESCRIPTION;
public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION;
// /TEXT DECLARATION/
// STAT DECLARATION
private static final CardRarity RARITY = CardRarity.UNCOMMON;
private static final CardTarget TARGET = CardTarget.SELF;
private static final CardType TYPE = CardType.SKILL;
public static final CardColor COLOR = AbstractCardEnum.DUELIST_MONSTERS;
private static final int COST = 1;
// /STAT DECLARATION/
public CrystalRose() {
super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET);
this.summons = this.baseSummons = 2;
this.tags.add(Tags.MONSTER);
this.tags.add(Tags.ROCK);
this.tags.add(Tags.PLANT);
this.tags.add(Tags.ROSE);
this.originalName = this.name;
this.isSummon = true;
}
// Actions the card should do.
@Override
public void use(AbstractPlayer p, AbstractMonster m)
{
summon();
AbstractCard c = returnTrulyRandomFromSet(Tags.GEM_KNIGHT);
if (this.upgraded) { c.upgrade(); }
addCardToHand(c);
}
// Which card to return when making a copy of this card.
@Override
public AbstractCard makeCopy() {
return new CrystalRose();
}
// Upgraded stats.
@Override
public void upgrade() {
if (!this.upgraded) {
this.upgradeName();
this.upgradeSummons(1);
this.rawDescription = UPGRADE_DESCRIPTION;
this.initializeDescription();
}
}
@Override
public void onTribute(DuelistCard tributingCard)
{
}
@Override
public void onResummon(int summons) {
// TODO Auto-generated method stub
}
@Override
public void summonThis(int summons, DuelistCard c, int var)
{
}
@Override
public void summonThis(int summons, DuelistCard c, int var, AbstractMonster m)
{
}
@Override
public String getID() {
return ID;
}
@Override
public void optionSelected(AbstractPlayer arg0, AbstractMonster arg1, int arg2) {
// TODO Auto-generated method stub
}
}
|
9241266432e7de946c138603376d8f6ac7cc9294 | 412 | java | Java | src/custom_classes/NotANaturalNumberException.java | vctrop/article_manager | 70e6f73b8ea651be4645583e808396481d599693 | [
"MIT"
] | 1 | 2019-08-13T17:41:37.000Z | 2019-08-13T17:41:37.000Z | src/custom_classes/NotANaturalNumberException.java | vctrop/article_manager | 70e6f73b8ea651be4645583e808396481d599693 | [
"MIT"
] | null | null | null | src/custom_classes/NotANaturalNumberException.java | vctrop/article_manager | 70e6f73b8ea651be4645583e808396481d599693 | [
"MIT"
] | null | null | null | 20.6 | 59 | 0.616505 | 1,001,792 | package custom_classes;
public class NotANaturalNumberException extends Exception {
public NotANaturalNumberException(String message) {
super(message);
}
public static boolean isValid(String num) {
try {
int i = Integer.parseInt(num);
if (i < 0) {
return false;
}
} catch (NumberFormatException e) {
return false;
}
return true;
}
}
|
924126e60e5481492d23999f7a9fd9edb626da59 | 2,891 | java | Java | WebViewLib/src/main/java/com/ycbjie/webviewlib/cache/HttpCacheInterceptor.java | Tancy/YCWebView | 646c40d99bddbab12d4a4724b4f3c7eae04ff96c | [
"Apache-2.0"
] | 1,597 | 2017-10-10T11:18:48.000Z | 2022-03-30T03:22:16.000Z | WebViewLib/src/main/java/com/ycbjie/webviewlib/cache/HttpCacheInterceptor.java | Tancy/YCWebView | 646c40d99bddbab12d4a4724b4f3c7eae04ff96c | [
"Apache-2.0"
] | 117 | 2019-09-25T00:28:54.000Z | 2022-03-22T07:38:24.000Z | WebViewLib/src/main/java/com/ycbjie/webviewlib/cache/HttpCacheInterceptor.java | Tancy/YCWebView | 646c40d99bddbab12d4a4724b4f3c7eae04ff96c | [
"Apache-2.0"
] | 257 | 2019-09-23T06:47:08.000Z | 2022-03-29T10:15:02.000Z | 35.256098 | 91 | 0.637496 | 1,001,793 | package com.ycbjie.webviewlib.cache;
import android.text.TextUtils;
import com.ycbjie.webviewlib.utils.X5WebUtils;
import java.io.IOException;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
/**
* <pre>
* @author yangchong
* blog : https://github.com/yangchong211
* time : 2020/5/17
* desc : http缓存拦截起,主要是设置Cache-Control的这个属性
* revise:
* </pre>
*/
public class HttpCacheInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String cache = request.header(WebViewCacheWrapper.KEY_CACHE);
Response originResponse = chain.proceed(request);
if (!TextUtils.isEmpty(cache)&&cache.equals(WebCacheType.NORMAL.ordinal()+"")){
return originResponse;
}
//Cache-Control 是最重要的规则。常见的取值有private、public、no-cache、max-age、no-store、默认是private
//Cache-Control仅指定了max-age所以默认是private。
//缓存时间是31536000,也就是说这个时间段的再次请求这条数据,都会直接获取缓存数据库中的数据,直接使用。
//关于缓存原理,可以重点看一下这个类的源码:CacheInterceptor
//缓存,待测试。在响应头里添加
//Response response = chain.proceed(request);
//Response.Builder responseBuilder = response.newBuilder();
//setCacheBuilder(request,responseBuilder);
return originResponse.newBuilder()
.removeHeader("pragma")
.removeHeader("Cache-Control")
.header("Cache-Control","max-age=3153600000")
.build();
}
private void setCacheBuilder(Request originalRequest, Response.Builder builder) {
//清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
builder.removeHeader("Pragma");
if (!X5WebUtils.isConnected(X5WebUtils.getApplication())) {
//无网络下强制使用缓存,无论缓存是否过期,此时该请求实际上不会被发送出去。
originalRequest = originalRequest.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
}
if (X5WebUtils.isConnected(X5WebUtils.getApplication())) {
//有网络情况下,根据请求接口的设置,配置缓存。
// 这样在下次请求时,根据缓存决定是否真正发出请求。
String cacheControl = originalRequest.cacheControl().toString();
//当然如果你想在有网络的情况下都直接走网络,那么只需要
//将其超时时间这是为0即可:String cacheControl="Cache-Control:public,max-age=0"
int maxAge = 60 * 60;
// read from cache for 1 minute
builder.addHeader("Cache-Control", cacheControl);
builder.addHeader("Cache-Control", "public, max-age=" + maxAge);
} else {
//无网络
// tolerate 4-weeks stale
int maxStale = 60 * 60 * 24 * 28;
builder.header("Cache-Control", "public,only-if-cached,max-stale=360000");
builder.header("Cache-Control", "public,only-if-cached,max-stale=" + maxStale);
}
}
}
|
924127360eb79ed24c1a8b372623310546aa36ba | 5,553 | java | Java | Tenacity 4.0/src/minecraft/dev/client/tenacity/utils/objects/Dragging.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | 3 | 2022-02-28T17:34:51.000Z | 2022-03-06T21:55:16.000Z | Tenacity 4.0/src/minecraft/dev/client/tenacity/utils/objects/Dragging.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | 2 | 2022-02-25T20:10:14.000Z | 2022-03-03T14:25:03.000Z | Tenacity 4.0/src/minecraft/dev/client/tenacity/utils/objects/Dragging.java | 14ms/Minecraft-Disclosed-Source-Modifications | d3729ab0fb20c36da1732b2070d1cb5d1409ffbc | [
"Unlicense"
] | null | null | null | 30.344262 | 173 | 0.641635 | 1,001,794 | package dev.client.tenacity.utils.objects;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import dev.client.rose.utils.render.HoveringUtil;
import dev.client.tenacity.module.Module;
import dev.client.tenacity.module.impl.render.ArraylistMod;
import dev.client.tenacity.utils.misc.StringUtils;
import dev.client.tenacity.utils.render.ColorUtil;
import dev.client.tenacity.utils.render.RoundedUtil;
import dev.utils.Utils;
import dev.utils.animations.Animation;
import dev.utils.animations.Direction;
import dev.utils.animations.impl.DecelerateAnimation;
import dev.utils.font.FontUtil;
import net.minecraft.client.gui.ScaledResolution;
import java.awt.*;
import java.util.List;
public class Dragging implements Utils {
@Expose
@SerializedName("x")
private float xPos;
@Expose
@SerializedName("y")
private float yPos;
public float initialXVal;
public float initialYVal;
private float startX, startY;
private boolean dragging;
private float width, height;
@Expose
@SerializedName("name")
private String name;
private final Module module;
public Animation hoverAnimation = new DecelerateAnimation(250, 1, Direction.BACKWARDS);
public Dragging(Module module, String name, float initialXVal, float initialYVal) {
this.module = module;
this.name = name;
this.xPos = initialXVal;
this.yPos = initialYVal;
this.initialXVal = initialXVal;
this.initialYVal = initialYVal;
}
public Module getModule() {
return module;
}
public String getName() {
return name;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public float getX() {
return xPos;
}
public void setX(float x) {
this.xPos = x;
}
public float getY() {
return yPos;
}
public void setY(float y) {
this.yPos = y;
}
private String longestModule;
public final void onDraw(int mouseX, int mouseY) {
boolean hovering = HoveringUtil.isHovering(xPos, yPos, width, height, mouseX, mouseY);
if (dragging) {
xPos = (mouseX - startX);
yPos = (mouseY - startY);
}
hoverAnimation.setDirection(hovering ? Direction.FORWARDS : Direction.BACKWARDS);
if (!hoverAnimation.isDone() || hoverAnimation.finished(Direction.FORWARDS)) {
RoundedUtil.drawRoundOutline(xPos - 4, yPos - 4, width + 8, height + 8, 10, 2,
ColorUtil.applyOpacity(Color.WHITE, 0), ColorUtil.applyOpacity(Color.WHITE, (float) hoverAnimation.getOutput()));
}
}
public final void onDrawArraylist(ArraylistMod arraylistMod, int mouseX, int mouseY) {
ScaledResolution sr = new ScaledResolution(mc);
List<Module> modules = StringUtils.getToggledModules(arraylistMod.modules);
String longest = getLongestModule(arraylistMod);
width = (float) (FontUtil.tenacityFont20.getStringWidth(longest) + 5);
height = (float) ((arraylistMod.height.getValue() + 1) * modules.size());
float textVal = (float) FontUtil.tenacityFont20.getStringWidth(longest);
float xVal = sr.getScaledWidth() - (textVal + 8 + xPos);
if (sr.getScaledWidth() - xPos <= sr.getScaledWidth() / 2f) {
xVal += textVal - 2;
}
boolean hovering = HoveringUtil.isHovering(xVal, yPos, width, height, mouseX, mouseY);
if (dragging) {
xPos = -(mouseX - startX);
yPos = (mouseY - startY);
}
hoverAnimation.setDirection(hovering ? Direction.FORWARDS : Direction.BACKWARDS);
if (!hoverAnimation.isDone() || hoverAnimation.finished(Direction.FORWARDS)) {
RoundedUtil.drawRoundOutline(xVal, yPos - 8, width + 20, height + 16, 10, 2,
ColorUtil.applyOpacity(Color.BLACK, (float) (0f * hoverAnimation.getOutput())), ColorUtil.applyOpacity(Color.WHITE, (float) hoverAnimation.getOutput()));
}
}
public final void onClick(int mouseX, int mouseY, int button) {
boolean canDrag = HoveringUtil.isHovering(xPos, yPos, width, height, mouseX, mouseY);
if (button == 0 && canDrag) {
dragging = true;
startX = (int) (mouseX - xPos);
startY = (int) (mouseY - yPos);
}
}
public final void onClickArraylist(ArraylistMod arraylistMod, int mouseX, int mouseY, int button) {
ScaledResolution sr = new ScaledResolution(mc);
String longest = getLongestModule(arraylistMod);
float textVal = (float) FontUtil.tenacityFont20.getStringWidth(longest);
float xVal = sr.getScaledWidth() - (textVal + 8 + xPos);
if (sr.getScaledWidth() - xPos <= sr.getScaledWidth() / 2f) {
xVal += textVal - 16;
}
boolean canDrag = HoveringUtil.isHovering(xVal, yPos, width, height, mouseX, mouseY);
if (button == 0 && canDrag) {
dragging = true;
startX = (int) (mouseX + xPos);
startY = (int) (mouseY - yPos);
}
}
public final void onRelease(int button) {
if (button == 0) dragging = false;
}
private String getLongestModule(ArraylistMod arraylistMod) {
return arraylistMod.longest;
}
}
|
9241283ee8b260d07fe9820bf34550648078c3b5 | 1,599 | java | Java | jstorm-client/src/main/java/storm/trident/planner/Node.java | zhangjunfang/jstorm-0.9.6.3- | 0b9fb3c4905f605d508999d047f5f6ba3917f639 | [
"Apache-2.0"
] | 3 | 2015-05-05T08:17:33.000Z | 2015-09-21T09:08:36.000Z | jstorm-client/src/main/java/storm/trident/planner/Node.java | zhangjunfang/jstorm-0.9.6.3- | 0b9fb3c4905f605d508999d047f5f6ba3917f639 | [
"Apache-2.0"
] | null | null | null | jstorm-client/src/main/java/storm/trident/planner/Node.java | zhangjunfang/jstorm-0.9.6.3- | 0b9fb3c4905f605d508999d047f5f6ba3917f639 | [
"Apache-2.0"
] | null | null | null | 23.173913 | 71 | 0.722952 | 1,001,795 | package storm.trident.planner;
import backtype.storm.tuple.Fields;
import java.io.Serializable;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
public class Node implements Serializable {
/**
*
*/
private static final long serialVersionUID = -380698960249707895L;
private static AtomicInteger INDEX = new AtomicInteger(0);
private String nodeId;
public String name = null;
public Fields allOutputFields;
public String streamId;
public Integer parallelismHint = null;
public NodeStateInfo stateInfo = null;
public int creationIndex;
public Node(String streamId, String name, Fields allOutputFields) {
this.nodeId = UUID.randomUUID().toString();
this.allOutputFields = allOutputFields;
this.streamId = streamId;
this.name = name;
this.creationIndex = INDEX.incrementAndGet();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nodeId == null) ? 0 : nodeId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Node other = (Node) obj;
if (nodeId == null) {
if (other.nodeId != null)
return false;
} else if (!nodeId.equals(other.nodeId))
return false;
return true;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this,
ToStringStyle.MULTI_LINE_STYLE);
}
}
|
9241292817033a44d6336cd79b5709fc3467f962 | 60,535 | java | Java | src/test/java/mho/qbar/iterableProviders/QBarExhaustiveProviderProperties.java | mhogrefe/qbar | 06b283b09f1c53f511f46cf0ee8e3401023930c7 | [
"MIT"
] | 2 | 2016-04-01T06:00:52.000Z | 2016-04-08T15:56:26.000Z | src/test/java/mho/qbar/iterableProviders/QBarExhaustiveProviderProperties.java | mhogrefe/qbar | 06b283b09f1c53f511f46cf0ee8e3401023930c7 | [
"MIT"
] | 1 | 2016-04-08T15:46:28.000Z | 2016-04-13T02:23:44.000Z | src/test/java/mho/qbar/iterableProviders/QBarExhaustiveProviderProperties.java | mhogrefe/qbar | 06b283b09f1c53f511f46cf0ee8e3401023930c7 | [
"MIT"
] | null | null | null | 38.50827 | 119 | 0.592401 | 1,001,796 | package mho.qbar.iterableProviders;
import mho.qbar.objects.*;
import mho.qbar.testing.QBarTestProperties;
import mho.wheels.structures.Pair;
import mho.wheels.structures.Triple;
import org.jetbrains.annotations.NotNull;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Predicate;
import static mho.qbar.testing.QBarTesting.QEP;
import static mho.wheels.iterables.IterableUtils.*;
import static mho.wheels.ordering.Ordering.*;
import static mho.wheels.testing.Testing.*;
public class QBarExhaustiveProviderProperties extends QBarTestProperties {
public QBarExhaustiveProviderProperties() {
super("QBarExhaustiveProvider");
}
@Override
protected void testConstant() {
propertiesPositiveRationals();
propertiesNegativeRationals();
propertiesNonzeroRationals();
propertiesRationals();
propertiesNonNegativeRationalsLessThanOne();
propertiesFinitelyBoundedIntervals();
propertiesIntervals();
propertiesVectors();
propertiesRationalVectors();
propertiesReducedRationalVectors();
propertiesPolynomialVectors();
propertiesRationalPolynomialVectors();
propertiesMatrices();
propertiesSquareMatrices();
propertiesInvertibleMatrices();
propertiesRationalMatrices();
propertiesSquareRationalMatrices();
propertiesPolynomialMatrices();
propertiesSquarePolynomialMatrices();
propertiesInvertibleRationalMatrices();
propertiesRationalPolynomialMatrices();
propertiesSquareRationalPolynomialMatrices();
propertiesPolynomials();
propertiesPrimitivePolynomials();
propertiesPositivePrimitivePolynomials();
propertiesMonicPolynomials();
propertiesSquareFreePolynomials();
propertiesPositivePrimitiveSquareFreePolynomials();
propertiesIrreduciblePolynomials();
propertiesRationalPolynomials();
propertiesMonicRationalPolynomials();
propertiesVariables();
propertiesMonomialOrders();
propertiesMonomials();
propertiesMultivariatePolynomials();
propertiesRationalMultivariatePolynomials();
propertiesPositiveCleanReals();
propertiesPositiveReals();
propertiesNegativeCleanReals();
propertiesNegativeReals();
propertiesNonzeroCleanReals();
propertiesNonzeroReals();
propertiesCleanReals();
propertiesReals();
propertiesPositiveAlgebraics();
propertiesNegativeAlgebraics();
propertiesNonzeroAlgebraics();
propertiesAlgebraics();
propertiesNonNegativeAlgebraicsLessThanOne();
propertiesQBarRandomProvidersDefault();
propertiesQBarRandomProvidersDefaultSecondaryAndTertiaryScale();
propertiesQBarRandomProvidersDefaultTertiaryScale();
propertiesQBarRandomProviders();
}
@Override
protected void testBothModes() {
propertiesRangeUp_Rational();
propertiesRangeDown_Rational();
propertiesRange_Rational_Rational();
propertiesRationalsIn();
propertiesRationalsNotIn();
propertiesVectors_int();
propertiesVectorsAtLeast();
propertiesRationalVectors_int();
propertiesRationalVectorsAtLeast();
propertiesReducedRationalVectors_int();
propertiesReducedRationalVectorsAtLeast();
propertiesPolynomialVectors_int();
propertiesPolynomialVectorsAtLeast();
propertiesRationalPolynomialVectors_int();
propertiesRationalPolynomialVectorsAtLeast();
propertiesMatrices_int_int();
propertiesRationalMatrices_int_int();
propertiesPolynomialMatrices_int_int();
propertiesRationalPolynomialMatrices_int_int();
propertiesPolynomials_int();
propertiesPolynomialsAtLeast();
propertiesPrimitivePolynomials_int();
propertiesPrimitivePolynomialsAtLeast();
propertiesPositivePrimitivePolynomials_int();
propertiesPositivePrimitivePolynomialsAtLeast();
propertiesMonicPolynomials_int();
propertiesMonicPolynomialsAtLeast();
propertiesSquareFreePolynomials_int();
propertiesSquareFreePolynomialsAtLeast();
propertiesPositivePrimitiveSquareFreePolynomials_int();
propertiesPositivePrimitiveSquareFreePolynomialsAtLeast();
propertiesIrreduciblePolynomials_int();
propertiesIrreduciblePolynomialsAtLeast();
propertiesRationalPolynomials_int();
propertiesRationalPolynomialsAtLeast();
propertiesMonicRationalPolynomials_int();
propertiesMonicRationalPolynomialsAtLeast();
propertiesMonomials_List_Variable();
propertiesMultivariatePolynomials_List_Variable();
propertiesRationalMultivariatePolynomials_List_Variable();
propertiesCleanRealRangeUp();
propertiesRealRangeUp();
propertiesCleanRealRangeDown();
propertiesRealRangeDown();
propertiesCleanRealRange();
propertiesRealRange();
propertiesCleanRealsIn();
propertiesRealsIn();
propertiesCleanRealsNotIn();
propertiesRealsNotIn();
propertiesPositiveAlgebraics_int();
propertiesNegativeAlgebraics_int();
propertiesNonzeroAlgebraics_int();
propertiesAlgebraics_int();
propertiesNonNegativeAlgebraicsLessThanOne_int();
propertiesRangeUp_int_Algebraic();
propertiesRangeUp_Algebraic();
propertiesRangeDown_int_Algebraic();
propertiesRangeDown_Algebraic();
propertiesRange_int_Algebraic_Algebraic();
propertiesRange_Algebraic_Algebraic();
propertiesAlgebraicsIn_int_Interval();
propertiesAlgebraicsIn_Interval();
propertiesAlgebraicsNotIn_int_Interval();
propertiesAlgebraicsNotIn_Interval();
propertiesQBarRandomProvidersFixedScales();
}
private static <T> void test_helper(
int limit,
@NotNull Object message,
@NotNull Iterable<T> xs,
@NotNull Predicate<T> predicate
) {
Iterable<T> txs = take(limit, xs);
assertTrue(message, all(x -> x != null && predicate.test(x), txs));
testNoRemove(limit, txs);
assertTrue(message, unique(txs));
}
private static <T> void test_helperNoUnique(
int limit,
@NotNull Object message,
@NotNull Iterable<T> xs,
@NotNull Predicate<T> predicate
) {
Iterable<T> txs = take(limit, xs);
assertTrue(message, all(x -> x != null && predicate.test(x), txs));
testNoRemove(limit, txs);
}
private static <T> void simpleTest(
@NotNull Object message,
@NotNull Iterable<T> xs,
@NotNull Predicate<T> predicate
) {
test_helper(TINY_LIMIT, message, xs, predicate);
}
private static <T> void simpleTestNoUnique(
@NotNull Object message,
@NotNull Iterable<T> xs,
@NotNull Predicate<T> predicate
) {
test_helperNoUnique(TINY_LIMIT, message, xs, predicate);
}
private static <T> void biggerTest(
@NotNull Object message,
@NotNull Iterable<T> xs,
@NotNull Predicate<T> predicate
) {
test_helper(LARGE_LIMIT, message, xs, predicate);
}
private void propertiesPositiveRationals() {
initializeConstant("positiveRationals()");
biggerTest(QEP, QEP.positiveRationals(), r -> r.signum() == 1);
}
private void propertiesNegativeRationals() {
initializeConstant("negativeRationals()");
biggerTest(QEP, QEP.negativeRationals(), r -> r.signum() == -1);
}
private void propertiesNonzeroRationals() {
initializeConstant("nonzeroRationals()");
biggerTest(QEP, QEP.nonzeroRationals(), r -> r != Rational.ZERO);
}
private void propertiesRationals() {
initializeConstant("rationals()");
biggerTest(QEP, QEP.rationals(), r -> true);
}
private void propertiesNonNegativeRationalsLessThanOne() {
initializeConstant("nonNegativeRationalsLessThanOne()");
biggerTest(QEP, QEP.nonNegativeRationalsLessThanOne(), r -> r.signum() != -1 && lt(r, Rational.ONE));
}
private void propertiesRangeUp_Rational() {
initialize("rangeUp(Rational)");
for (Rational r : take(LIMIT, P.rationals())) {
Iterable<Rational> rs = QEP.rangeUp(r);
simpleTest(r, rs, s -> ge(s, r));
}
}
private void propertiesRangeDown_Rational() {
initialize("rangeDown(Rational)");
for (Rational r : take(LIMIT, P.rationals())) {
Iterable<Rational> rs = QEP.rangeDown(r);
simpleTest(r, rs, s -> le(s, r));
}
}
private void propertiesRange_Rational_Rational() {
initialize("range(Rational, Rational)");
for (Pair<Rational, Rational> p : take(LIMIT, P.bagPairs(P.rationals()))) {
Iterable<Rational> rs = QEP.range(p.a, p.b);
simpleTest(p, rs, r -> ge(r, p.a) && le(r, p.b));
assertEquals(p, gt(p.a, p.b), isEmpty(rs));
if (ge(p.a, p.b)) {
testHasNext(rs);
}
}
for (Rational r : take(LIMIT, P.rationals())) {
aeqit(r, QEP.range(r, r), Collections.singletonList(r));
}
for (Pair<Rational, Rational> p : take(LIMIT, P.subsetPairs(P.rationals()))) {
try {
QEP.range(p.b, p.a);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesFinitelyBoundedIntervals() {
initializeConstant("finitelyBoundedIntervals()");
biggerTest(QEP, QEP.finitelyBoundedIntervals(), Interval::isFinitelyBounded);
}
private void propertiesIntervals() {
initializeConstant("intervals()");
biggerTest(QEP, QEP.intervals(), a -> true);
}
private void propertiesRationalsIn() {
initialize("rationalsIn(Interval)");
for (Interval a : take(LIMIT, P.intervals())) {
Iterable<Rational> rs = QEP.rationalsIn(a);
simpleTest(a, rs, a::contains);
}
for (Rational r : take(LIMIT, P.rationals())) {
Iterable<Rational> rs = QEP.rationalsIn(Interval.of(r));
aeqit(r, rs, Collections.singletonList(r));
testHasNext(rs);
}
}
private void propertiesRationalsNotIn() {
initialize("rationalsNotIn(Interval)");
for (Interval a : take(LIMIT, P.intervals())) {
Iterable<Rational> rs = QEP.rationalsNotIn(a);
simpleTest(a, rs, r -> !a.contains(r));
}
}
private void propertiesVectors_int() {
initialize("vectors(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<Vector> vs = QEP.vectors(i);
simpleTest(i, vs, v -> v.dimension() == i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.vectors(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesVectors() {
initializeConstant("vectors()");
biggerTest(QEP, QEP.vectors(), v -> true);
}
private void propertiesVectorsAtLeast() {
initialize("vectorsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<Vector> vs = QEP.vectorsAtLeast(i);
simpleTest(i, vs, v -> v.dimension() >= i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.vectorsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalVectors_int() {
initialize("rationalVectors(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<RationalVector> vs = QEP.rationalVectors(i);
simpleTest(i, vs, v -> v.dimension() == i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.rationalVectors(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalVectors() {
initializeConstant("rationalVectors()");
biggerTest(QEP, QEP.rationalVectors(), v -> true);
}
private void propertiesRationalVectorsAtLeast() {
initialize("rationalVectorsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<RationalVector> vs = QEP.rationalVectorsAtLeast(i);
simpleTest(i, vs, v -> v.dimension() >= i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.rationalVectorsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesReducedRationalVectors_int() {
initialize("reducedRationalVectors(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<RationalVector> vs = QEP.reducedRationalVectors(i);
simpleTest(i, vs, v -> v.isReduced() && v.dimension() == i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.reducedRationalVectors(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesReducedRationalVectors() {
initializeConstant("reducedRationalVectors()");
biggerTest(QEP, QEP.reducedRationalVectors(), RationalVector::isReduced);
}
private void propertiesReducedRationalVectorsAtLeast() {
initialize("reducedRationalVectorsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<RationalVector> vs = QEP.reducedRationalVectorsAtLeast(i);
simpleTest(i, vs, v -> v.isReduced() && v.dimension() >= i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.reducedRationalVectorsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPolynomialVectors_int() {
initialize("polynomialVectors(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<PolynomialVector> vs = QEP.polynomialVectors(i);
simpleTest(i, vs, v -> v.dimension() == i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.polynomialVectors(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPolynomialVectors() {
initializeConstant("polynomialVectors()");
biggerTest(QEP, QEP.polynomialVectors(), v -> true);
}
private void propertiesPolynomialVectorsAtLeast() {
initialize("polynomialVectorsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<PolynomialVector> vs = QEP.polynomialVectorsAtLeast(i);
simpleTest(i, vs, v -> v.dimension() >= i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.polynomialVectorsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalPolynomialVectors_int() {
initialize("rationalPolynomialVectors(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<RationalPolynomialVector> vs = QEP.rationalPolynomialVectors(i);
simpleTest(i, vs, v -> v.dimension() == i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.rationalPolynomialVectors(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalPolynomialVectors() {
initializeConstant("rationalPolynomialVectors()");
biggerTest(QEP, QEP.rationalPolynomialVectors(), v -> true);
}
private void propertiesRationalPolynomialVectorsAtLeast() {
initialize("rationalPolynomialVectorsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.naturalIntegersGeometric())) {
Iterable<RationalPolynomialVector> vs = QEP.rationalPolynomialVectorsAtLeast(i);
simpleTest(i, vs, v -> v.dimension() >= i);
}
for (int i : take(LIMIT, P.negativeIntegers())) {
try {
QEP.rationalPolynomialVectorsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesMatrices_int_int() {
initialize("matrices(int, int)");
for (Pair<Integer, Integer> p : take(SMALL_LIMIT, P.pairs(P.naturalIntegersGeometric()))) {
Iterable<Matrix> ms = QEP.matrices(p.a, p.b);
simpleTest(p, ms, n -> n.height() == p.a && n.width() == p.b);
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.negativeIntegers(), P.positiveIntegers()))) {
try {
QEP.matrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.positiveIntegers(), P.negativeIntegers()))) {
try {
QEP.matrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesMatrices() {
initializeConstant("matrices()");
biggerTest(QEP, QEP.matrices(), m -> true);
}
private void propertiesSquareMatrices() {
initializeConstant("squareMatrices()");
biggerTest(QEP, QEP.squareMatrices(), Matrix::isSquare);
}
private void propertiesInvertibleMatrices() {
initializeConstant("invertibleMatrices()");
biggerTest(QEP, QEP.invertibleMatrices(), Matrix::isInvertible);
}
private void propertiesRationalMatrices_int_int() {
initialize("rationalMatrices(int, int)");
for (Pair<Integer, Integer> p : take(SMALL_LIMIT, P.pairs(P.naturalIntegersGeometric()))) {
Iterable<RationalMatrix> ms = QEP.rationalMatrices(p.a, p.b);
simpleTest(p, ms, n -> n.height() == p.a && n.width() == p.b);
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.negativeIntegers(), P.positiveIntegers()))) {
try {
QEP.rationalMatrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.positiveIntegers(), P.negativeIntegers()))) {
try {
QEP.rationalMatrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalMatrices() {
initializeConstant("rationalMatrices()");
biggerTest(QEP, QEP.rationalMatrices(), m -> true);
}
private void propertiesSquareRationalMatrices() {
initializeConstant("squareRationalMatrices()");
biggerTest(QEP, QEP.squareRationalMatrices(), RationalMatrix::isSquare);
}
private void propertiesInvertibleRationalMatrices() {
initializeConstant("invertibleRationalMatrices()");
biggerTest(QEP, QEP.invertibleRationalMatrices(), RationalMatrix::isInvertible);
}
private void propertiesPolynomialMatrices_int_int() {
initialize("polynomialMatrices(int, int)");
for (Pair<Integer, Integer> p : take(SMALL_LIMIT, P.pairs(P.naturalIntegersGeometric()))) {
Iterable<PolynomialMatrix> ms = QEP.polynomialMatrices(p.a, p.b);
simpleTest(p, ms, n -> n.height() == p.a && n.width() == p.b);
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.negativeIntegers(), P.positiveIntegers()))) {
try {
QEP.polynomialMatrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.positiveIntegers(), P.negativeIntegers()))) {
try {
QEP.polynomialMatrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPolynomialMatrices() {
initializeConstant("polynomialMatrices()");
biggerTest(QEP, QEP.polynomialMatrices(), m -> true);
}
private void propertiesSquarePolynomialMatrices() {
initializeConstant("squarePolynomialMatrices()");
biggerTest(QEP, QEP.squarePolynomialMatrices(), PolynomialMatrix::isSquare);
}
private void propertiesRationalPolynomialMatrices_int_int() {
initialize("rationalPolynomialMatrices(int, int)");
for (Pair<Integer, Integer> p : take(SMALL_LIMIT, P.pairs(P.naturalIntegersGeometric()))) {
Iterable<RationalPolynomialMatrix> ms = QEP.rationalPolynomialMatrices(p.a, p.b);
simpleTest(p, ms, n -> n.height() == p.a && n.width() == p.b);
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.negativeIntegers(), P.positiveIntegers()))) {
try {
QEP.rationalPolynomialMatrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
for (Pair<Integer, Integer> p : take(LIMIT, P.pairs(P.positiveIntegers(), P.negativeIntegers()))) {
try {
QEP.rationalPolynomialMatrices(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalPolynomialMatrices() {
initializeConstant("rationalPolynomialMatrices()");
biggerTest(QEP, QEP.rationalPolynomialMatrices(), m -> true);
}
private void propertiesSquareRationalPolynomialMatrices() {
initializeConstant("squareRationalPolynomialMatrices()");
biggerTest(QEP, QEP.squareRationalPolynomialMatrices(), RationalPolynomialMatrix::isSquare);
}
private void propertiesPolynomials_int() {
initialize("polynomials(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.polynomials(i);
simpleTest(i, ps, p -> p.degree() == i);
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.polynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPolynomials() {
initializeConstant("polynomials()");
biggerTest(QEP, QEP.polynomials(), p -> true);
}
private void propertiesPolynomialsAtLeast() {
initialize("polynomialsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.polynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i);
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.polynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPrimitivePolynomials_int() {
initialize("primitivePolynomials(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.primitivePolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.isPrimitive());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.primitivePolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPrimitivePolynomials() {
initializeConstant("primitivePolynomials()");
biggerTest(QEP, QEP.primitivePolynomials(), Polynomial::isPrimitive);
}
private void propertiesPrimitivePolynomialsAtLeast() {
initialize("primitivePolynomialsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.primitivePolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.isPrimitive());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.primitivePolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPositivePrimitivePolynomials_int() {
initialize("positivePrimitivePolynomials(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.positivePrimitivePolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.signum() == 1 && p.isPrimitive());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.positivePrimitivePolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPositivePrimitivePolynomials() {
initializeConstant("positivePrimitivePolynomials()");
biggerTest(QEP, QEP.positivePrimitivePolynomials(), p -> p.signum() == 1 && p.isPrimitive());
}
private void propertiesPositivePrimitivePolynomialsAtLeast() {
initialize("positivePrimitivePolynomialsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.positivePrimitivePolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.signum() == 1 && p.isPrimitive());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.positivePrimitivePolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesMonicPolynomials_int() {
initialize("monicPolynomials(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.monicPolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.isMonic());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.monicPolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesMonicPolynomials() {
initializeConstant("monicPolynomials()");
biggerTest(QEP, QEP.monicPolynomials(), Polynomial::isMonic);
}
private void propertiesMonicPolynomialsAtLeast() {
initialize("monicPolynomialsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.monicPolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.isMonic());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.monicPolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesSquareFreePolynomials_int() {
initialize("squareFreePolynomials(int)");
for (int i : take(TINY_LIMIT, P.withScale(4).rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.squareFreePolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.isSquareFree());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.squareFreePolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesSquareFreePolynomials() {
initializeConstant("squareFreePolynomials()");
biggerTest(QEP, QEP.withScale(4).squareFreePolynomials(), Polynomial::isSquareFree);
}
private void propertiesSquareFreePolynomialsAtLeast() {
initialize("squareFreePolynomialsAtLeast(int)");
for (int i : take(TINY_LIMIT, P.withScale(4).rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.squareFreePolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.isSquareFree());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.squareFreePolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPositivePrimitiveSquareFreePolynomials_int() {
initialize("positivePrimitiveSquareFreePolynomials(int)");
for (int i : take(TINY_LIMIT, P.withScale(4).rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.positivePrimitiveSquareFreePolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.signum() == 1 && p.isPrimitive() && p.isSquareFree());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.positivePrimitiveSquareFreePolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPositivePrimitiveSquareFreePolynomials() {
initializeConstant("positivePrimitiveSquareFreePolynomials()");
biggerTest(
QEP,
QEP.withScale(4).positivePrimitiveSquareFreePolynomials(),
p -> p.signum() == 1 && p.isPrimitive() && p.isSquareFree()
);
}
private void propertiesPositivePrimitiveSquareFreePolynomialsAtLeast() {
initialize("positivePrimitiveSquareFreePolynomialsAtLeast(int)");
for (int i : take(TINY_LIMIT, P.withScale(4).rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.positivePrimitiveSquareFreePolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.signum() == 1 && p.isPrimitive() && p.isSquareFree());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.positivePrimitiveSquareFreePolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesIrreduciblePolynomials_int() {
initialize("irreduciblePolynomials(int)");
for (int i : take(TINY_LIMIT, P.withScale(4).rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.irreduciblePolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.isIrreducible());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.irreduciblePolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesIrreduciblePolynomials() {
initializeConstant("irreduciblePolynomials()");
biggerTest(QEP, QEP.withScale(4).irreduciblePolynomials(), Polynomial::isIrreducible);
}
private void propertiesIrreduciblePolynomialsAtLeast() {
initialize("irreduciblePolynomialsAtLeast(int)");
for (int i : take(TINY_LIMIT, P.withScale(1).rangeUpGeometric(-1))) {
Iterable<Polynomial> ps = QEP.irreduciblePolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.isIrreducible());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.irreduciblePolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalPolynomials_int() {
initialize("rationalPolynomials(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<RationalPolynomial> ps = QEP.rationalPolynomials(i);
simpleTest(i, ps, p -> p.degree() == i);
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.rationalPolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRationalPolynomials() {
initializeConstant("rationalPolynomials()");
biggerTest(QEP, QEP.rationalPolynomials(), p -> true);
}
private void propertiesRationalPolynomialsAtLeast() {
initialize("rationalPolynomialsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<RationalPolynomial> ps = QEP.rationalPolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i);
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.rationalPolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesMonicRationalPolynomials_int() {
initialize("monicRationalPolynomials(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<RationalPolynomial> ps = QEP.monicRationalPolynomials(i);
simpleTest(i, ps, p -> p.degree() == i && p.isMonic());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.monicRationalPolynomials(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesMonicRationalPolynomials() {
initializeConstant("monicRationalPolynomials()");
biggerTest(QEP, QEP.monicRationalPolynomials(), RationalPolynomial::isMonic);
}
private void propertiesMonicRationalPolynomialsAtLeast() {
initialize("monicRationalPolynomialsAtLeast(int)");
for (int i : take(SMALL_LIMIT, P.rangeUpGeometric(-1))) {
Iterable<RationalPolynomial> ps = QEP.monicRationalPolynomialsAtLeast(i);
simpleTest(i, ps, p -> p.degree() >= i && p.isMonic());
}
for (int i : take(LIMIT, P.rangeDown(-2))) {
try {
QEP.monicRationalPolynomialsAtLeast(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesVariables() {
initializeConstant("variables()");
biggerTest(QEP, QEP.variables(), v -> true);
}
private void propertiesMonomialOrders() {
initializeConstant("monomialOrders()");
biggerTest(QEP, QEP.monomialOrders(), o -> true);
}
private void propertiesMonomials() {
initializeConstant("monomials()");
biggerTest(QEP, QEP.monomials(), m -> true);
}
private void propertiesMonomials_List_Variable() {
initialize("monomials(List<Variable>)");
for (List<Variable> vs : take(LIMIT, P.subsets(P.variables()))) {
Iterable<Monomial> ms = QEP.monomials(vs);
simpleTest(vs, ms, m -> isSubsetOf(m.variables(), vs));
}
for (List<Variable> vs : take(LIMIT, filterInfinite(us -> !increasing(us), P.lists(P.variables())))) {
try {
QEP.monomials(vs);
fail(vs);
} catch (IllegalArgumentException ignored) {}
}
Iterable<List<Variable>> vsFail = filterInfinite(
us -> increasing(filter(Objects::nonNull, us)),
P.listsWithElement(null, P.variables())
);
for (List<Variable> vs : take(LIMIT, vsFail)) {
try {
QEP.monomials(vs);
fail(vs);
} catch (NullPointerException ignored) {}
}
}
private void propertiesMultivariatePolynomials() {
initializeConstant("multivariatePolynomials()");
biggerTest(QEP, QEP.multivariatePolynomials(), p -> true);
}
private void propertiesMultivariatePolynomials_List_Variable() {
initialize("multivariatePolynomials(List<Variable>)");
for (List<Variable> vs : take(LIMIT, P.subsets(P.variables()))) {
Iterable<MultivariatePolynomial> ps = QEP.multivariatePolynomials(vs);
simpleTest(vs, ps, p -> isSubsetOf(p.variables(), vs));
}
for (List<Variable> vs : take(LIMIT, filterInfinite(us -> !increasing(us), P.lists(P.variables())))) {
try {
QEP.multivariatePolynomials(vs);
fail(vs);
} catch (IllegalArgumentException ignored) {}
}
Iterable<List<Variable>> vsFail = filterInfinite(
us -> increasing(filter(Objects::nonNull, us)),
P.listsWithElement(null, P.variables())
);
for (List<Variable> vs : take(LIMIT, vsFail)) {
try {
QEP.multivariatePolynomials(vs);
fail(vs);
} catch (NullPointerException ignored) {}
}
}
private void propertiesRationalMultivariatePolynomials() {
initializeConstant("rationalMultivariatePolynomials()");
biggerTest(QEP, QEP.rationalMultivariatePolynomials(), p -> true);
}
private void propertiesRationalMultivariatePolynomials_List_Variable() {
initialize("rationalMultivariatePolynomials(List<Variable>)");
for (List<Variable> vs : take(LIMIT, P.subsets(P.variables()))) {
Iterable<RationalMultivariatePolynomial> ps = QEP.rationalMultivariatePolynomials(vs);
simpleTest(vs, ps, p -> isSubsetOf(p.variables(), vs));
}
for (List<Variable> vs : take(LIMIT, filterInfinite(us -> !increasing(us), P.lists(P.variables())))) {
try {
QEP.rationalMultivariatePolynomials(vs);
fail(vs);
} catch (IllegalArgumentException ignored) {}
}
Iterable<List<Variable>> vsFail = filterInfinite(
us -> increasing(filter(Objects::nonNull, us)),
P.listsWithElement(null, P.variables())
);
for (List<Variable> vs : take(LIMIT, vsFail)) {
try {
QEP.rationalMultivariatePolynomials(vs);
fail(vs);
} catch (NullPointerException ignored) {}
}
}
private void propertiesPositiveCleanReals() {
initializeConstant("positiveCleanReals()");
simpleTestNoUnique(QEP, QEP.positiveCleanReals(), x -> x.signumUnsafe() == 1);
}
private void propertiesPositiveReals() {
initializeConstant("positiveReals()");
simpleTestNoUnique(QEP, QEP.positiveReals(), x -> x.signumUnsafe() == 1);
}
private void propertiesNegativeCleanReals() {
initializeConstant("negativeCleanReals()");
simpleTestNoUnique(QEP, QEP.negativeCleanReals(), x -> x.signumUnsafe() == -1);
}
private void propertiesNegativeReals() {
initializeConstant("negativeReals()");
simpleTestNoUnique(QEP, QEP.negativeReals(), x -> x.signumUnsafe() == -1);
}
private void propertiesNonzeroCleanReals() {
initializeConstant("nonzeroCleanReals()");
simpleTestNoUnique(QEP, QEP.nonzeroCleanReals(), x -> x.signumUnsafe() != 0);
}
private void propertiesNonzeroReals() {
initializeConstant("nonzeroReals()");
simpleTestNoUnique(QEP, QEP.nonzeroReals(), x -> x.signumUnsafe() != 0);
}
private void propertiesCleanReals() {
initializeConstant("cleanReals()");
simpleTestNoUnique(QEP, QEP.cleanReals(), x -> true);
}
private void propertiesReals() {
initializeConstant("reals()");
simpleTestNoUnique(QEP, QEP.reals(), x -> true);
}
private void propertiesCleanRealRangeUp() {
initialize("cleanRealRangeUp(Algebraic)");
for (Algebraic x : take(SMALL_LIMIT, P.withScale(4).algebraics())) {
Iterable<Real> xs = QEP.cleanRealRangeUp(x);
simpleTestNoUnique(x, xs, y -> {
//noinspection SuspiciousNameCombination
Optional<Boolean> oc = y.ge(x.realValue(), Real.DEFAULT_RESOLUTION);
return !oc.isPresent() || oc.get();
});
}
for (Rational r : take(SMALL_LIMIT, P.rationals())) {
Iterable<Real> xs = QEP.cleanRealRangeUp(Algebraic.of(r));
//noinspection SuspiciousNameCombination
simpleTestNoUnique(r, xs, y -> y.geUnsafe(r));
}
}
private void propertiesRealRangeUp() {
initialize("realRangeUp(Algebraic)");
for (Algebraic x : take(SMALL_LIMIT, P.withScale(4).algebraics())) {
Iterable<Real> xs = QEP.realRangeUp(x);
simpleTestNoUnique(x, xs, y -> {
//noinspection SuspiciousNameCombination
Optional<Boolean> oc = y.ge(x.realValue(), Real.DEFAULT_RESOLUTION);
return !oc.isPresent() || oc.get();
});
}
}
private void propertiesCleanRealRangeDown() {
initialize("cleanRealRangeDown(Algebraic)");
for (Algebraic x : take(SMALL_LIMIT, P.withScale(4).algebraics())) {
Iterable<Real> xs = QEP.cleanRealRangeDown(x);
simpleTestNoUnique(x, xs, y -> {
//noinspection SuspiciousNameCombination
Optional<Boolean> oc = y.le(x.realValue(), Real.DEFAULT_RESOLUTION);
return !oc.isPresent() || oc.get();
});
}
for (Rational r : take(SMALL_LIMIT, P.rationals())) {
Iterable<Real> xs = QEP.cleanRealRangeDown(Algebraic.of(r));
//noinspection SuspiciousNameCombination
simpleTestNoUnique(r, xs, y -> y.leUnsafe(r));
}
}
private void propertiesRealRangeDown() {
initialize("realRangeDown(Algebraic)");
for (Algebraic x : take(SMALL_LIMIT, P.withScale(4).algebraics())) {
Iterable<Real> xs = QEP.realRangeDown(x);
simpleTestNoUnique(x, xs, y -> {
//noinspection SuspiciousNameCombination
Optional<Boolean> oc = y.le(x.realValue(), Real.DEFAULT_RESOLUTION);
return !oc.isPresent() || oc.get();
});
}
}
private void propertiesCleanRealRange() {
initialize("cleanRealRange(Algebraic, Algebraic)");
for (Pair<Algebraic, Algebraic> p : take(SMALL_LIMIT, P.bagPairs(P.withScale(4).algebraics()))) {
Iterable<Real> xs = QEP.cleanRealRange(p.a, p.b);
simpleTestNoUnique(p, xs, y -> {
//noinspection SuspiciousNameCombination
Optional<Boolean> lower = y.ge(p.a.realValue(), Real.DEFAULT_RESOLUTION);
if (lower.isPresent() && !lower.get()) {
return false;
}
//noinspection SuspiciousNameCombination
Optional<Boolean> upper = y.le(p.b.realValue(), Real.DEFAULT_RESOLUTION);
return !upper.isPresent() || upper.get();
});
}
for (Pair<Rational, Rational> p : take(SMALL_LIMIT, P.bagPairs(P.rationals()))) {
Iterable<Real> xs = QEP.cleanRealRange(Algebraic.of(p.a), Algebraic.of(p.b));
//noinspection SuspiciousNameCombination
simpleTestNoUnique(p, xs, y -> y.geUnsafe(p.a) && y.leUnsafe(p.b));
}
for (Algebraic x : take(LIMIT, P.algebraics())) {
assertEquals(x, length(QEP.cleanRealRange(x, x)), 1);
}
for (Pair<Algebraic, Algebraic> p : take(LIMIT, P.subsetPairs(P.algebraics()))) {
try {
QEP.cleanRealRange(p.b, p.a);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRealRange() {
initialize("realRange(Algebraic, Algebraic)");
for (Pair<Algebraic, Algebraic> p : take(SMALL_LIMIT, P.bagPairs(P.withScale(4).algebraics()))) {
Iterable<Real> xs = QEP.realRange(p.a, p.b);
simpleTestNoUnique(p, xs, y -> {
//noinspection SuspiciousNameCombination
Optional<Boolean> lower = y.ge(p.a.realValue(), Real.DEFAULT_RESOLUTION);
if (lower.isPresent() && !lower.get()) {
return false;
}
//noinspection SuspiciousNameCombination
Optional<Boolean> upper = y.le(p.b.realValue(), Real.DEFAULT_RESOLUTION);
return !upper.isPresent() || upper.get();
});
}
for (Rational r : take(LIMIT, P.rationals())) {
Algebraic x = Algebraic.of(r);
assertEquals(r, length(QEP.realRange(x, x)), 4);
}
for (Algebraic x : take(LIMIT, filterInfinite(y -> !y.isRational(), P.algebraics()))) {
assertEquals(x, length(QEP.realRange(x, x)), 1);
}
for (Pair<Algebraic, Algebraic> p : take(LIMIT, P.subsetPairs(P.algebraics()))) {
try {
QEP.realRange(p.b, p.a);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesCleanRealsIn() {
initialize("cleanRealsIn(Interval)");
for (Interval a : take(SMALL_LIMIT, P.intervals())) {
Iterable<Real> xs = QEP.cleanRealsIn(a);
simpleTestNoUnique(a, xs, a::containsUnsafe);
}
}
private void propertiesRealsIn() {
initialize("realsIn(Interval)");
for (Interval a : take(SMALL_LIMIT, P.intervals())) {
Iterable<Real> xs = QEP.realsIn(a);
simpleTestNoUnique(a, xs, x -> {
Optional<Boolean> ob = a.contains(x, Real.DEFAULT_RESOLUTION);
return !ob.isPresent() || ob.get();
});
}
}
private void propertiesCleanRealsNotIn() {
initialize("cleanRealsNotIn(Interval)");
for (Interval a : take(SMALL_LIMIT, P.intervals())) {
Iterable<Real> xs = QEP.cleanRealsNotIn(a);
simpleTestNoUnique(a, xs, x -> !a.containsUnsafe(x));
}
}
private void propertiesRealsNotIn() {
initialize("realsNotIn(Interval)");
for (Interval a : take(SMALL_LIMIT, P.intervals())) {
Iterable<Real> xs = QEP.realsNotIn(a);
simpleTestNoUnique(a, xs, x -> {
Optional<Boolean> ob = a.contains(x, Real.DEFAULT_RESOLUTION).map(b -> !b);
return !ob.isPresent() || ob.get();
});
}
}
private void propertiesPositiveAlgebraics_int() {
initialize("positiveAlgebraics(int)");
for (int i : take(TINY_LIMIT, P.withScale(2).positiveIntegersGeometric())) {
Iterable<Algebraic> xs = QEP.positiveAlgebraics(i);
simpleTest(i, xs, x -> x.degree() == i && x.signum() == 1);
}
for (int i : take(LIMIT, P.rangeDown(0))) {
try {
QEP.positiveAlgebraics(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesPositiveAlgebraics() {
initializeConstant("positiveAlgebraics()");
simpleTest(QEP, QEP.positiveAlgebraics(), x -> x.signum() == 1);
}
private void propertiesNegativeAlgebraics_int() {
initialize("negativeAlgebraics(int)");
for (int i : take(TINY_LIMIT, P.withScale(2).positiveIntegersGeometric())) {
Iterable<Algebraic> xs = QEP.negativeAlgebraics(i);
simpleTest(i, xs, x -> x.degree() == i && x.signum() == -1);
}
for (int i : take(LIMIT, P.rangeDown(0))) {
try {
QEP.negativeAlgebraics(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesNegativeAlgebraics() {
initializeConstant("negativeAlgebraics()");
simpleTest(QEP, QEP.negativeAlgebraics(), x -> x.signum() == -1);
}
private void propertiesNonzeroAlgebraics_int() {
initialize("nonzeroAlgebraics(int)");
for (int i : take(TINY_LIMIT, P.withScale(2).positiveIntegersGeometric())) {
Iterable<Algebraic> xs = QEP.nonzeroAlgebraics(i);
simpleTest(i, xs, x -> x.degree() == i && x != Algebraic.ZERO);
}
for (int i : take(LIMIT, P.rangeDown(0))) {
try {
QEP.nonzeroAlgebraics(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesNonzeroAlgebraics() {
initializeConstant("nonzeroAlgebraics()");
simpleTest(QEP, QEP.nonzeroAlgebraics(), x -> x != Algebraic.ZERO);
}
private void propertiesAlgebraics_int() {
initialize("algebraics(int)");
for (int i : take(TINY_LIMIT, P.withScale(2).positiveIntegersGeometric())) {
Iterable<Algebraic> xs = QEP.nonzeroAlgebraics(i);
simpleTest(i, xs, x -> x.degree() == i);
}
for (int i : take(LIMIT, P.rangeDown(0))) {
try {
QEP.algebraics(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesAlgebraics() {
initializeConstant("algebraics()");
simpleTest(QEP, QEP.algebraics(), x -> true);
}
private void propertiesNonNegativeAlgebraicsLessThanOne_int() {
initialize("nonNegativeAlgebraicsLessThanOne(int)");
for (int i : take(TINY_LIMIT / 2, P.withScale(2).positiveIntegersGeometric())) {
Iterable<Algebraic> xs = QEP.nonNegativeAlgebraicsLessThanOne(i);
simpleTest(i, xs, x -> x.degree() == i && x.signum() != -1 && lt(x, Algebraic.ONE));
}
for (int i : take(LIMIT, P.rangeDown(0))) {
try {
QEP.nonNegativeAlgebraicsLessThanOne(i);
fail(i);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesNonNegativeAlgebraicsLessThanOne() {
initializeConstant("nonNegativeAlgebraicsLessThanOne()");
simpleTest(QEP, QEP.nonNegativeAlgebraicsLessThanOne(), x -> x.signum() != -1 && lt(x, Algebraic.ONE));
}
private void propertiesRangeUp_int_Algebraic() {
initialize("rangeUp(int, Algebraic)");
Iterable<Pair<Algebraic, Integer>> ps = P.pairsLogarithmicOrder(
P.withScale(4).algebraics(),
P.withScale(2).positiveIntegersGeometric()
);
for (Pair<Algebraic, Integer> p : take(MEDIUM_LIMIT, ps)) {
Iterable<Algebraic> xs = QEP.rangeUp(p.b, p.a);
simpleTest(p, xs, y -> y.degree() == p.b && ge(y, p.a));
}
for (Pair<Integer, Algebraic> p : take(LIMIT, P.pairs(P.rangeDown(0), P.algebraics()))) {
try {
QEP.rangeUp(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRangeUp_Algebraic() {
initialize("rangeUp(Algebraic)");
for (Algebraic x : take(MEDIUM_LIMIT, P.withScale(4).algebraics())) {
Iterable<Algebraic> xs = QEP.rangeUp(x);
simpleTest(x, xs, y -> ge(y, x));
}
}
private void propertiesRangeDown_int_Algebraic() {
initialize("rangeDown(int, Algebraic)");
Iterable<Pair<Algebraic, Integer>> ps = P.pairsLogarithmicOrder(
P.withScale(4).algebraics(),
P.withScale(2).positiveIntegersGeometric()
);
for (Pair<Algebraic, Integer> p : take(MEDIUM_LIMIT, ps)) {
Iterable<Algebraic> xs = QEP.rangeDown(p.b, p.a);
simpleTest(p, xs, y -> y.degree() == p.b && le(y, p.a));
}
for (Pair<Integer, Algebraic> p : take(LIMIT, P.pairs(P.rangeDown(0), P.algebraics()))) {
try {
QEP.rangeDown(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRangeDown_Algebraic() {
initialize("rangeDown(Algebraic)");
for (Algebraic x : take(MEDIUM_LIMIT, P.withScale(4).algebraics())) {
Iterable<Algebraic> xs = QEP.rangeDown(x);
simpleTest(x, xs, y -> le(y, x));
}
}
private void propertiesRange_int_Algebraic_Algebraic() {
initialize("range(int, Algebraic, Algebraic)");
Iterable<Triple<Integer, Algebraic, Algebraic>> ts = map(
p -> new Triple<>(p.b, p.a.a, p.a.b),
P.pairsLogarithmicOrder(
P.bagPairs(P.withScale(4).algebraics()),
P.withScale(2).positiveIntegersGeometric()
)
);
for (Triple<Integer, Algebraic, Algebraic> t : take(SMALL_LIMIT, ts)) {
Iterable<Algebraic> xs = QEP.range(t.a, t.b, t.c);
simpleTest(t, xs, x -> x.degree() == t.a && ge(x, t.b) && le(x, t.c));
}
for (Algebraic x : take(LIMIT, P.algebraics())) {
aeqit(x, QEP.range(x.degree(), x, x), Collections.singletonList(x));
}
Iterable<Pair<Integer, Algebraic>> psFail = filterInfinite(
q -> q.a != q.b.degree(),
P.pairs(P.positiveIntegersGeometric(), P.algebraics())
);
for (Pair<Integer, Algebraic> p : take(LIMIT, psFail)) {
assertTrue(p, isEmpty(QEP.range(p.a, p.b, p.b)));
}
Iterable<Triple<Integer, Algebraic, Algebraic>> tsFail = map(
p -> new Triple<>(p.b, p.a.a, p.a.b),
P.pairsLogarithmicOrder(P.bagPairs(P.algebraics()), P.withScale(-32).rangeDownGeometric(0))
);
for (Triple<Integer, Algebraic, Algebraic> t : take(SMALL_LIMIT, tsFail)) {
try {
QEP.range(t.a, t.b, t.c);
fail(t);
} catch (IllegalArgumentException ignored) {}
}
tsFail = map(
p -> new Triple<>(p.a, p.b.a, p.b.b),
P.pairs(P.positiveIntegersGeometric(), P.subsetPairs(P.algebraics()))
);
for (Triple<Integer, Algebraic, Algebraic> t : take(LIMIT, tsFail)) {
try {
QEP.range(t.a, t.c, t.b);
fail(t);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesRange_Algebraic_Algebraic() {
initialize("range(Algebraic, Algebraic)");
for (Pair<Algebraic, Algebraic> p : take(SMALL_LIMIT, P.bagPairs(P.withScale(4).algebraics()))) {
Iterable<Algebraic> xs = QEP.range(p.a, p.b);
simpleTest(p, xs, x -> ge(x, p.a) && le(x, p.b));
}
for (Algebraic x : take(LIMIT, P.algebraics())) {
aeqit(x, QEP.range(x, x), Collections.singletonList(x));
}
for (Pair<Algebraic, Algebraic> p : take(LIMIT, P.subsetPairs(P.algebraics()))) {
try {
QEP.range(p.b, p.a);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesAlgebraicsIn_int_Interval() {
initialize("algebraicsIn(int, Interval)");
Iterable<Pair<Interval, Integer>> ps = P.pairsLogarithmicOrder(
P.intervals(),
P.withScale(2).positiveIntegersGeometric()
);
for (Pair<Interval, Integer> p : take(SMALL_LIMIT, ps)) {
Iterable<Algebraic> xs = QEP.algebraicsIn(p.b, p.a);
simpleTest(p, xs, x -> x.degree() == p.b && p.a.contains(x));
}
for (Pair<Integer, Rational> p : take(LIMIT, P.pairs(P.rangeUpGeometric(2), P.rationals()))) {
assertTrue(p, isEmpty(QEP.algebraicsIn(p.a, Interval.of(p.b))));
}
for (Pair<Integer, Interval> p : take(LIMIT, P.pairs(P.withScale(-32).rangeDownGeometric(0), P.intervals()))) {
try {
QEP.algebraicsIn(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesAlgebraicsIn_Interval() {
initialize("algebraicsIn(Interval)");
for (Interval a : take(SMALL_LIMIT, P.intervals())) {
Iterable<Algebraic> xs = QEP.algebraicsIn(a);
simpleTest(a, xs, a::contains);
}
}
private void propertiesAlgebraicsNotIn_int_Interval() {
initialize("algebraicsNotIn(int, Interval)");
Iterable<Pair<Interval, Integer>> ps = P.pairsLogarithmicOrder(
P.intervals(),
P.withScale(2).positiveIntegersGeometric()
);
for (Pair<Interval, Integer> p : take(MEDIUM_LIMIT, ps)) {
Iterable<Algebraic> xs = QEP.algebraicsNotIn(p.b, p.a);
simpleTest(p, xs, x -> x.degree() == p.b && !p.a.contains(x));
}
for (int i : take(LIMIT, P.positiveIntegersGeometric())) {
assertTrue(i, isEmpty(QEP.algebraicsNotIn(i, Interval.ALL)));
}
for (Pair<Integer, Interval> p : take(LIMIT, P.pairs(P.withScale(-32).rangeDownGeometric(0), P.intervals()))) {
try {
QEP.algebraicsNotIn(p.a, p.b);
fail(p);
} catch (IllegalArgumentException ignored) {}
}
}
private void propertiesAlgebraicsNotIn_Interval() {
initialize("algebraicsNotIn(Interval)");
for (Interval a : take(SMALL_LIMIT, P.intervals())) {
Iterable<Algebraic> xs = QEP.algebraicsNotIn(a);
simpleTest(a, xs, x -> !a.contains(x));
}
}
private void propertiesQBarRandomProvidersFixedScales() {
initialize("qbarRandomProvidersFixedScales(int, int, int)");
for (Triple<Integer, Integer, Integer> t : take(MEDIUM_LIMIT, P.triples(P.integersGeometric()))) {
Iterable<QBarRandomProvider> rps = QEP.qbarRandomProvidersFixedScales(t.a, t.b, t.c);
testNoRemove(TINY_LIMIT, rps);
List<QBarRandomProvider> rpsList = toList(take(TINY_LIMIT, rps));
rpsList.forEach(QBarRandomProvider::validate);
take(TINY_LIMIT, rpsList).forEach(QBarRandomProvider::validate);
assertTrue(
t,
all(
rp -> rp.getScale() == t.a && rp.getSecondaryScale() == t.b &&
rp.getTertiaryScale() == t.c,
rpsList
)
);
assertTrue(t, unique(rpsList));
}
}
private void propertiesQBarRandomProvidersDefault() {
initializeConstant("qbarRandomProvidersDefault()");
biggerTest(
QEP,
QEP.qbarRandomProvidersDefault(),
rp -> rp.getScale() == 32 && rp.getSecondaryScale() == 8 && rp.getTertiaryScale() == 2
);
take(LARGE_LIMIT, QEP.qbarRandomProvidersDefault()).forEach(QBarRandomProvider::validate);
}
private void propertiesQBarRandomProvidersDefaultSecondaryAndTertiaryScale() {
initializeConstant("qbarRandomProvidersDefaulSecondaryAndTertiaryScale()");
biggerTest(
QEP,
QEP.qbarRandomProvidersDefaultSecondaryAndTertiaryScale(),
rp -> rp.getSecondaryScale() == 8 && rp.getTertiaryScale() == 2
);
take(LARGE_LIMIT, QEP.qbarRandomProvidersDefaultSecondaryAndTertiaryScale())
.forEach(QBarRandomProvider::validate);
}
private void propertiesQBarRandomProvidersDefaultTertiaryScale() {
initializeConstant("qbarRandomProvidersDefaulTertiaryScale()");
biggerTest(QEP, QEP.qbarRandomProvidersDefaultTertiaryScale(), rp -> rp.getTertiaryScale() == 2);
take(LARGE_LIMIT, QEP.qbarRandomProvidersDefaultTertiaryScale()).forEach(QBarRandomProvider::validate);
}
private void propertiesQBarRandomProviders() {
initializeConstant("qbarRandomProviders()");
biggerTest(QEP, QEP.qbarRandomProviders(), rp -> true);
take(LARGE_LIMIT, QEP.qbarRandomProviders()).forEach(QBarRandomProvider::validate);
}
}
|
92412966eaed67f5e6e9193d1dab6ba866ca91ec | 3,033 | java | Java | org/JMathStudio/MathToolkit/Utilities/Combinatric.java | bhavyaajani/jmathstudio | f284bf6fb8bca73994bf668dad2de2765837515f | [
"Apache-2.0"
] | 16 | 2018-05-01T17:36:51.000Z | 2021-11-19T05:04:02.000Z | org/JMathStudio/MathToolkit/Utilities/Combinatric.java | bhavyaajani/jmathstudio | f284bf6fb8bca73994bf668dad2de2765837515f | [
"Apache-2.0"
] | 1 | 2020-02-26T01:31:57.000Z | 2020-02-26T01:31:57.000Z | org/JMathStudio/MathToolkit/Utilities/Combinatric.java | bhavyaajani/jmathstudio | f284bf6fb8bca73994bf668dad2de2765837515f | [
"Apache-2.0"
] | 1 | 2019-11-23T02:05:39.000Z | 2019-11-23T02:05:39.000Z | 24.620968 | 88 | 0.671143 | 1,001,797 | package org.JMathStudio.MathToolkit.Utilities;
import org.JMathStudio.Exceptions.IllegalArgumentException;
/**
* This class provide various Combinatric operations.
* @author Ajani Bhavya - (dycjh@example.com)
*/
public final class Combinatric
{
/**
* This method computes the factorial of the integer number as given
* by the argument 'value'. The argument 'value' should not be less
* than 0 else this method will throw an IllegalArgument Exception.
* @param int value
* @return float
* @throws IllegalArgumentException
* @author Ajani Bhavya - (dycjh@example.com)
*/
public float factorial(int value) throws IllegalArgumentException
{
if(value <0)
{
throw new IllegalArgumentException();
}
if(value ==0)
{
return 1;
}
float fact =1;
for(int i= value;i>0;i--)
{
fact = fact*i;
}
return fact;
}
/**
* This method computes the nCk combinations possible for the given argument 'n' and
* 'k'.
* <p>The argument 'n' and 'k' should not be less than 0 and argument 'n'
* should not be less than 'k' else this method will throw an IllegalArgument
* Exception.
* @param int n
* @param int k
* @return float
* @throws IllegalArgumentException
* @author Ajani Bhavya - (dycjh@example.com)
*/
public float combination(int n,int k) throws IllegalArgumentException
{
if(n <0 || k< 0)
{
throw new IllegalArgumentException();
}
if(n < k)
{
throw new IllegalArgumentException();
}
return factorial(n)/(factorial(k)*factorial(n-k));
}
/**
* This method computes the nPk permutation possible for the given argument 'n' and
* 'k'.
* <p>The argument 'n' and 'k' should not be less than 0 and argument 'n'
* should not be less than 'k' else this method will throw an IllegalArgument
* Exception.
* @param int n
* @param int k
* @return float
* @throws IllegalArgumentException
* @author Ajani Bhavya - (dycjh@example.com)
*/
public float permutation(int n,int k) throws IllegalArgumentException
{
if(n <0 || k< 0)
{
throw new IllegalArgumentException();
}
if(n < k)
{
throw new IllegalArgumentException();
}
return factorial(n)/(factorial(n-k));
}
/**
* This method will compute the 2nd order Sterling number for the variable as given by
* the argument 'n' and 'k'.
* <p>The argument 'n' and 'k' should not be less than 0 and argument 'n' should not be
* less than 'k' else this method will throw an IllegalArgument Exception.
* @param int n
* @param int k
* @return float
* @throws IllegalArgumentException
* @author Ajani Bhavya - (dycjh@example.com)
*/
public float sterlingNumber2(int n,int k) throws IllegalArgumentException
{
if(n <0 || k< 0)
{
throw new IllegalArgumentException();
}
if(k > n)
{
throw new IllegalArgumentException();
}
float sterling =0;
for(int j=0;j<=k;j++)
{
float tmp = (float) (Math.pow(-1, k-j)*combination(k,j)*Math.pow(j, n));
sterling = sterling + tmp;
}
return sterling/factorial(k);
}
}
|
924129affc6aabcd32b5e85c9b824ef4d0f7c71e | 421 | java | Java | testfan/src/com/testfan/LoopTest.java | mikebin170/javaCode | 9bf802bfdc2a7d44097e9b1c23e8c44943a6d94a | [
"MIT"
] | 1 | 2018-12-19T15:03:49.000Z | 2018-12-19T15:03:49.000Z | testfan/src/com/testfan/LoopTest.java | mikexxb/testfan | 9bf802bfdc2a7d44097e9b1c23e8c44943a6d94a | [
"MIT"
] | 6 | 2020-04-23T17:15:41.000Z | 2021-01-20T23:21:50.000Z | testfan/src/com/testfan/LoopTest.java | litebin/javaCode | 9bf802bfdc2a7d44097e9b1c23e8c44943a6d94a | [
"MIT"
] | null | null | null | 14.033333 | 53 | 0.524941 | 1,001,798 | package com.testfan;
public class LoopTest {
public static void main(String[] args) {
//输出10到20之间数字
// for
for (int x = 10; x < 20; x++) {
System.out.println("for value of x : " + x);
}
// while
int x = 10;
while (x < 20) {
System.out.println("while value of x : " + x);
x++;
}
// do while
do {
System.out.println(" do while value of x : " + x);
x++;
} while (x < 20);
}
}
|
92412a2182b661f94c933596adb11610bc70428c | 358 | java | Java | QuickAdapter/app/src/main/java/com/heaven7/core/adapter/demo/TestMainActivity.java | LightSun/android-common-util-light | 6008027bc211f581930ae16a77383c5db3095f9e | [
"Apache-2.0"
] | 14 | 2016-03-01T10:07:54.000Z | 2018-09-06T03:33:48.000Z | QuickAdapter/app/src/main/java/com/heaven7/core/adapter/demo/TestMainActivity.java | LightSun/android-common-util-light | 6008027bc211f581930ae16a77383c5db3095f9e | [
"Apache-2.0"
] | null | null | null | QuickAdapter/app/src/main/java/com/heaven7/core/adapter/demo/TestMainActivity.java | LightSun/android-common-util-light | 6008027bc211f581930ae16a77383c5db3095f9e | [
"Apache-2.0"
] | null | null | null | 19.888889 | 57 | 0.706704 | 1,001,799 | package com.heaven7.core.adapter.demo;
import java.util.List;
/**
* Created by heaven7 on 2017/12/22.
*/
public class TestMainActivity extends AbsMainActivity {
@Override
protected void addDemos(List<ActivityInfo> list) {
list.add(new ActivityInfo(TestQtActivity.class));
list.add(new ActivityInfo(AudioFxDemo.class));
}
}
|
92412ac48367a4bb079ac1efbc1d780d878d6914 | 180 | java | Java | util/Point.java | starforever/leet-code | d38b4d8f11971e385c92191d586105ebb8ea8829 | [
"MIT"
] | null | null | null | util/Point.java | starforever/leet-code | d38b4d8f11971e385c92191d586105ebb8ea8829 | [
"MIT"
] | null | null | null | util/Point.java | starforever/leet-code | d38b4d8f11971e385c92191d586105ebb8ea8829 | [
"MIT"
] | null | null | null | 8.571429 | 29 | 0.45 | 1,001,800 | // Definition for a point.
public class Point
{
int x;
int y;
public Point ()
{
x = 0;
y = 0;
}
public Point (int a, int b)
{
x = a;
y = b;
}
}
|
92412b2adfa6d27f2f679d950dc6b84dc074747a | 2,012 | java | Java | app/src/main/java/com/xseec/eds/model/tags/EnergyTag.java | hawesome512/EDSOnline | 4115fc29640ad2992f2c53ffc7f167b4b9c3f2a9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/xseec/eds/model/tags/EnergyTag.java | hawesome512/EDSOnline | 4115fc29640ad2992f2c53ffc7f167b4b9c3f2a9 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/xseec/eds/model/tags/EnergyTag.java | hawesome512/EDSOnline | 4115fc29640ad2992f2c53ffc7f167b4b9c3f2a9 | [
"Apache-2.0"
] | null | null | null | 24.839506 | 67 | 0.597416 | 1,001,801 | package com.xseec.eds.model.tags;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
public class EnergyTag extends StoredTag{
private static final String NULL_TAG="*";
private static final String SPLIT="/";
public static final int VALID_INFOS_LENGTH=3;
private String alias;
private String level;
public EnergyTag(String tagName) {
super(tagName,DataType.MAX);
}
public EnergyTag(String[] infos){
super(infos[1],DataType.MAX);
level=infos[0];
alias=infos[2];
}
public boolean isNull(){
return getTagName().equals(NULL_TAG);
}
public String getAlias() {
return alias;
}
public String getLevel() {
return level;
}
public void setAlias(String alias) {
this.alias = alias;
}
public void setLevel(String level) {
this.level = level;
}
public static String[] getInfos(String information){
return information.split(SPLIT);
}
public List<EnergyTag> getParent(List<EnergyTag> energyTags){
List<EnergyTag> parent=new ArrayList<>();
for(int i=1;i<=level.length()-1;i++){
String parentLevel=level.substring(0,i);
for(EnergyTag energyTag:energyTags){
if (energyTag.getLevel().equals(parentLevel)){
parent.add(energyTag);
break;
}
}
}
//自身也包含进父级中
parent.add(this);
return parent;
}
public List<EnergyTag> getChildren(List<EnergyTag> energyTags){
List<EnergyTag> children=new ArrayList<>();
String regex=getLevel()+"\\d";
Pattern pattern=Pattern.compile(regex);
for(EnergyTag energyTag:energyTags){
if(pattern.matcher(energyTag.getLevel()).find()){
children.add(energyTag);
}
}
return children;
}
}
|
92412c000e86b734caba43343e8b76cfb3ce4595 | 39,107 | java | Java | camellia-redis-proxy/src/main/java/com/netease/nim/camellia/redis/proxy/command/async/AsyncCamelliaRedisClusterClient.java | xulunfan/camellia | ebcbd36bd6c2884b81eb1d9f6d5f0af65d529969 | [
"MIT"
] | null | null | null | camellia-redis-proxy/src/main/java/com/netease/nim/camellia/redis/proxy/command/async/AsyncCamelliaRedisClusterClient.java | xulunfan/camellia | ebcbd36bd6c2884b81eb1d9f6d5f0af65d529969 | [
"MIT"
] | null | null | null | camellia-redis-proxy/src/main/java/com/netease/nim/camellia/redis/proxy/command/async/AsyncCamelliaRedisClusterClient.java | xulunfan/camellia | ebcbd36bd6c2884b81eb1d9f6d5f0af65d529969 | [
"MIT"
] | null | null | null | 55.549716 | 192 | 0.522259 | 1,001,802 | package com.netease.nim.camellia.redis.proxy.command.async;
import com.netease.nim.camellia.redis.exception.CamelliaRedisException;
import com.netease.nim.camellia.redis.proxy.command.Command;
import com.netease.nim.camellia.redis.proxy.enums.RedisCommand;
import com.netease.nim.camellia.redis.proxy.enums.RedisKeyword;
import com.netease.nim.camellia.redis.proxy.reply.ErrorReply;
import com.netease.nim.camellia.redis.proxy.reply.MultiBulkReply;
import com.netease.nim.camellia.redis.proxy.reply.Reply;
import com.netease.nim.camellia.redis.proxy.util.ErrorLogCollector;
import com.netease.nim.camellia.redis.proxy.util.RedisClusterCRC16Utils;
import com.netease.nim.camellia.redis.proxy.util.Utils;
import com.netease.nim.camellia.redis.resource.RedisClusterResource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
/**
*
* Created by caojiajun on 2019/12/18.
*/
public class AsyncCamelliaRedisClusterClient implements AsyncClient {
private static final Logger logger = LoggerFactory.getLogger(AsyncCamelliaRedisClusterClient.class);
private final RedisClusterSlotInfo clusterSlotInfo;
private final RedisClusterResource redisClusterResource;
private final int maxAttempts;
public AsyncCamelliaRedisClusterClient(RedisClusterResource redisClusterResource, int maxAttempts) {
this.redisClusterResource = redisClusterResource;
this.maxAttempts = maxAttempts;
this.clusterSlotInfo = new RedisClusterSlotInfo(redisClusterResource);
Future<Boolean> future = this.clusterSlotInfo.renew();
try {
if (future == null || !future.get()) {
throw new CamelliaRedisException("RedisClusterSlotInfo init fail");
}
} catch (CamelliaRedisException e) {
throw e;
} catch (Exception e) {
throw new CamelliaRedisException("RedisClusterSlotInfo init fail", e);
}
}
@Override
public void preheat() {
logger.info("try preheat, url = {}", redisClusterResource.getUrl());
Set<RedisClusterSlotInfo.Node> nodes = this.clusterSlotInfo.getNodes();
for (RedisClusterSlotInfo.Node node : nodes) {
logger.info("try preheat, url = {}, node = {}", redisClusterResource.getUrl(), node.getAddr().getUrl());
boolean result = RedisClientHub.preheat(node.getHost(), node.getPort(), node.getPassword());
logger.info("preheat result = {}, url = {}, node = {}", result, redisClusterResource.getUrl(), node.getAddr().getUrl());
}
logger.info("preheat ok, url = {}", redisClusterResource.getUrl());
}
public void sendCommand(List<Command> commands, List<CompletableFuture<Reply>> futureList) {
if (commands.isEmpty()) return;
if (commands.size() == 1) {
Command command = commands.get(0);
if (isPassThroughCommand(command)) {
byte[][] args = command.getObjects();
byte[] key = args[1];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
if (client != null) {
client.sendCommand(commands, Collections.singletonList(new CompletableFutureWrapper(this, futureList.get(0), command)));
if (logger.isDebugEnabled()) {
logger.debug("sendCommand, command = {}, key = {}, slot = {}", command.getName(), Utils.bytesToString(key), slot);
}
return;
}
}
}
CommandFlusher commandFlusher = new CommandFlusher(commands.size());
for (int i=0; i<commands.size(); i++) {
Command command = commands.get(i);
CompletableFuture<Reply> future = futureList.get(i);
RedisCommand redisCommand = command.getRedisCommand();
RedisClient bindClient = command.getChannelInfo().getBindClient();
if (redisCommand.getSupportType() == RedisCommand.CommandSupportType.PARTIALLY_SUPPORT_1) {
if (redisCommand == RedisCommand.SUBSCRIBE || redisCommand == RedisCommand.PSUBSCRIBE) {
boolean first = false;
if (bindClient == null) {
int randomSlot = ThreadLocalRandom.current().nextInt(RedisClusterSlotInfo.SLOT_SIZE);
RedisClusterSlotInfo.Node node = clusterSlotInfo.getNode(randomSlot);
if (node == null) {
future.complete(ErrorReply.NOT_AVAILABLE);
continue;
}
bindClient = RedisClientHub.newClient(node.getAddr());
command.getChannelInfo().setBindClient(bindClient);
first = true;
}
if (bindClient != null) {
AsyncTaskQueue asyncTaskQueue = command.getChannelInfo().getAsyncTaskQueue();
commandFlusher.flush();
commandFlusher.clear();
PubSubUtils.sendByBindClient(bindClient, asyncTaskQueue, command, future, first);
byte[][] objects = command.getObjects();
if (objects != null && objects.length > 1) {
for (int j=1; j<objects.length; j++) {
byte[] channel = objects[j];
if (redisCommand == RedisCommand.SUBSCRIBE) {
command.getChannelInfo().addSubscribeChannels(channel);
} else {
command.getChannelInfo().addPSubscribeChannels(channel);
}
}
}
} else {
future.complete(ErrorReply.NOT_AVAILABLE);
}
continue;
}
if (bindClient != null && (redisCommand == RedisCommand.UNSUBSCRIBE || redisCommand == RedisCommand.PUNSUBSCRIBE)) {
byte[][] objects = command.getObjects();
if (objects != null && objects.length > 1) {
for (int j=1; j<objects.length; j++) {
byte[] channel = objects[j];
if (redisCommand == RedisCommand.UNSUBSCRIBE) {
command.getChannelInfo().removeSubscribeChannels(channel);
} else {
command.getChannelInfo().removePSubscribeChannels(channel);
}
if (!command.getChannelInfo().hasSubscribeChannels()) {
command.getChannelInfo().setBindClient(null);
bindClient.startIdleCheck();
}
}
}
}
}
if (bindClient != null) {
commandFlusher.flush();
commandFlusher.clear();
PubSubUtils.sendByBindClient(bindClient, command.getChannelInfo().getAsyncTaskQueue(), command, future, false);
continue;
}
if (redisCommand.getSupportType() == RedisCommand.CommandSupportType.RESTRICTIVE_SUPPORT) {
switch (redisCommand) {
case EVAL:
case EVALSHA:
evalOrEvalSha(command, commandFlusher, future);
break;
case PFCOUNT:
case SDIFF:
case SINTER:
case SUNION:
case PFMERGE:
case SINTERSTORE:
case SUNIONSTORE:
case SDIFFSTORE:
case RPOPLPUSH:
checkSlotCommandsAndSend(command, commandFlusher, future, 1, command.getObjects().length - 1);
break;
case RENAME:
case RENAMENX:
case SMOVE:
case LMOVE:
case GEOSEARCHSTORE:
case ZRANGESTORE:
checkSlotCommandsAndSend(command, commandFlusher, future, 1, 2);
break;
case ZINTERSTORE:
case ZUNIONSTORE:
case ZDIFFSTORE:
int keyCount = (int) Utils.bytesToNum(command.getObjects()[2]);
checkSlotCommandsAndSend(command, commandFlusher, future, 3, 3 + keyCount, command.getObjects()[1]);
break;
case ZDIFF:
case ZUNION:
case ZINTER:
int keyCount1 = (int) Utils.bytesToNum(command.getObjects()[1]);
checkSlotCommandsAndSend(command, commandFlusher, future, 2, 1 + keyCount1);
break;
case BITOP:
checkSlotCommandsAndSend(command, commandFlusher, future, 2, command.getObjects().length - 1);
break;
case MSETNX:
msetnx(command, commandFlusher, future);
break;
case BLPOP:
case BRPOP:
case BRPOPLPUSH:
case BZPOPMAX:
case BZPOPMIN:
int slot = checkSlot(command, 1, command.getObjects().length - 2);
blockingCommand(slot, command, commandFlusher, future);
break;
case BLMOVE:
int slot1 = checkSlot(command, 1, 2);
blockingCommand(slot1, command, commandFlusher, future);
break;
case XREAD:
case XREADGROUP:
xreadOrXreadgroup(command, commandFlusher, future);
break;
default:
future.complete(ErrorReply.NOT_SUPPORT);
break;
}
continue;
}
if (command.getRedisCommand().getCommandKeyType() != RedisCommand.CommandKeyType.SIMPLE_SINGLE) {
boolean continueOk = false;
switch (redisCommand) {
case MGET: {
if (command.getObjects().length > 2) {
mget(command, commandFlusher, future);
continueOk = true;
}
break;
}
case EXISTS:
case UNLINK:
case TOUCH:
case DEL: {
if (command.getObjects().length > 2) {
simpleIntegerReplyMerge(command, commandFlusher, future);
continueOk = true;
}
break;
}
case MSET: {
if (command.getObjects().length > 3) {
mset(command, commandFlusher, future);
continueOk = true;
}
break;
}
case XINFO:
case XGROUP:
xinfoOrXgroup(command, commandFlusher, future);
continueOk = true;
break;
}
if (continueOk) continue;
}
byte[][] args = command.getObjects();
byte[] key = args[1];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
if (logger.isDebugEnabled()) {
logger.debug("sendCommand, command = {}, key = {}, slot = {}", command.getName(), Utils.bytesToString(key), slot);
}
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
}
commandFlusher.flush();
}
private RedisClient getClient(int slot) {
RedisClient client = null;
int attempts = 0;
while (attempts < maxAttempts) {
attempts ++;
client = clusterSlotInfo.getClient(slot);
if (client != null && client.isValid()) {
break;
} else {
clusterSlotInfo.renew();
}
}
return client;
}
private static class CompletableFutureWrapper extends CompletableFuture<Reply> {
private static final Command ASKING = new Command(new byte[][]{RedisCommand.ASKING.raw()});
private final AsyncCamelliaRedisClusterClient clusterClient;
private final CompletableFuture<Reply> future;
private final Command command;
private int attempts = 0;
CompletableFutureWrapper(AsyncCamelliaRedisClusterClient clusterClient, CompletableFuture<Reply> future, Command command) {
this.clusterClient = clusterClient;
this.future = future;
this.command = command;
}
public boolean complete(Reply reply) {
try {
if (attempts < clusterClient.maxAttempts) {
if (reply instanceof ErrorReply) {
String error = ((ErrorReply) reply).getError();
if (error.startsWith("MOVED")) {
attempts++;
String log = "MOVED, command = " + command.getName() + ", attempts = " + attempts;
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class, log);
clusterClient.clusterSlotInfo.renew();
String[] strings = parseTargetHostAndSlot(error);
RedisClientAddr addr = new RedisClientAddr(strings[1], Integer.parseInt(strings[2]), clusterClient.redisClusterResource.getPassword());
if (command.isBlocking()) {
RedisClient redisClient = command.getChannelInfo().tryGetExistsRedisClientForBlockingCommand(addr);
if (redisClient != null && redisClient.isValid()) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [BlockingCommand] [RedisClient tryGet success], command = " + command.getName() + ", attempts = " + attempts);
redisClient.sendCommand(Collections.singletonList(command), Collections.singletonList(this));
redisClient.startIdleCheck();
command.getChannelInfo().addRedisClientForBlockingCommand(redisClient);
} else {
CompletableFuture<RedisClient> future = RedisClientHub.newAsync(addr.getHost(), addr.getPort(), addr.getPassword());
future.thenAccept(client -> {
try {
if (client == null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [BlockingCommand] [RedisClient newAsync fail], command = " + command.getName() + ", attempts = " + attempts);
clusterClient.clusterSlotInfo.renew();
CompletableFutureWrapper.this.future.complete(reply);
} else {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [BlockingCommand] [RedisClient newAsync success], command = " + command.getName() + ", attempts = " + attempts);
client.sendCommand(Collections.singletonList(command), Collections.singletonList(CompletableFutureWrapper.this));
client.startIdleCheck();
command.getChannelInfo().addRedisClientForBlockingCommand(client);
}
} catch (Exception e) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [BlockingCommand] [RedisClient newAsync error], command = " + command.getName() + ", attempts = " + attempts, e);
CompletableFutureWrapper.this.future.complete(reply);
}
});
}
} else {
RedisClient redisClient = RedisClientHub.tryGet(addr.getHost(), addr.getPort(), addr.getPassword());
if (redisClient != null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [RedisClient tryGet success], command = " + command.getName() + ", attempts = " + attempts);
redisClient.sendCommand(Collections.singletonList(command), Collections.singletonList(this));
} else {
CompletableFuture<RedisClient> future = RedisClientHub.getAsync(addr.getHost(), addr.getPort(), addr.getPassword());
future.thenAccept(client -> {
try {
if (client == null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [RedisClient getAsync fail], command = " + command.getName() + ", attempts = " + attempts);
clusterClient.clusterSlotInfo.renew();
CompletableFutureWrapper.this.future.complete(reply);
} else {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [RedisClient getAsync success], command = " + command.getName() + ", attempts = " + attempts);
client.sendCommand(Collections.singletonList(command), Collections.singletonList(CompletableFutureWrapper.this));
}
} catch (Exception e) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"MOVED, [RedisClient getAsync error], command = " + command.getName() + ", attempts = " + attempts, e);
CompletableFutureWrapper.this.future.complete(reply);
}
});
}
}
return true;
} else if (error.startsWith("ASK")) {
attempts++;
String log = "ASK, command = " + command.getName() + ", attempts = " + attempts;
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class, log);
String[] strings = parseTargetHostAndSlot(error);
RedisClientAddr addr = new RedisClientAddr(strings[1], Integer.parseInt(strings[2]), clusterClient.redisClusterResource.getPassword());
if (command.isBlocking()) {
RedisClient redisClient = command.getChannelInfo().tryGetExistsRedisClientForBlockingCommand(addr);
if (redisClient != null && redisClient.isValid()) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [BlockingCommand] [RedisClient tryGet success], command = " + command.getName() + ", attempts = " + attempts);
redisClient.sendCommand(Arrays.asList(ASKING, command), Arrays.asList(new CompletableFuture<>(), this));
redisClient.startIdleCheck();
command.getChannelInfo().addRedisClientForBlockingCommand(redisClient);
} else {
CompletableFuture<RedisClient> future = RedisClientHub.newAsync(addr.getHost(), addr.getPort(), addr.getPassword());
future.thenAccept(client -> {
try {
if (client == null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [BlockingCommand] [RedisClient newAsync fail], command = " + command.getName() + ", attempts = " + attempts);
clusterClient.clusterSlotInfo.renew();
CompletableFutureWrapper.this.future.complete(reply);
} else {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [BlockingCommand] [RedisClient newAsync success], command = " + command.getName() + ", attempts = " + attempts);
client.sendCommand(Arrays.asList(ASKING, command), Arrays.asList(new CompletableFuture<>(), CompletableFutureWrapper.this));
client.startIdleCheck();
command.getChannelInfo().addRedisClientForBlockingCommand(client);
}
} catch (Exception e) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [BlockingCommand] [RedisClient newAsync error], command = " + command.getName() + ", attempts = " + attempts, e);
CompletableFutureWrapper.this.future.complete(reply);
}
});
}
} else {
RedisClient redisClient = RedisClientHub.tryGet(strings[1], Integer.parseInt(strings[2]), clusterClient.redisClusterResource.getPassword());
if (redisClient != null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [RedisClient tryGet success], command = " + command.getName() + ", attempts = " + attempts);
redisClient.sendCommand(Arrays.asList(ASKING, command), Arrays.asList(new CompletableFuture<>(), this));
} else {
CompletableFuture<RedisClient> future = RedisClientHub.getAsync(strings[1], Integer.parseInt(strings[2]), clusterClient.redisClusterResource.getPassword());
future.thenAccept(client -> {
try {
if (client == null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [RedisClient getAsync fail], command = " + command.getName() + ", attempts = " + attempts);
clusterClient.clusterSlotInfo.renew();
CompletableFutureWrapper.this.future.complete(reply);
} else {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [RedisClient getAsync success], command = " + command.getName() + ", attempts = " + attempts);
client.sendCommand(Arrays.asList(ASKING, command), Arrays.asList(new CompletableFuture<>(), CompletableFutureWrapper.this));
}
} catch (Exception e) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class,
"ASK, [RedisClient getAsync error], command = " + command.getName() + ", attempts = " + attempts, e);
CompletableFutureWrapper.this.future.complete(reply);
}
});
}
}
return true;
}
}
}
} catch (Exception e) {
logger.error("CompletableFutureWrapper complete error, command = {}, errorReply = {}",
command.getName(), ((ErrorReply) reply).getError(), e);
}
future.complete(reply);
return true;
}
private static String[] parseTargetHostAndSlot(String clusterRedirectResponse) {
String[] response = new String[3];
String[] messageInfo = clusterRedirectResponse.split(" ");
String[] targetHostAndPort = extractParts(messageInfo[2]);
response[0] = messageInfo[1];
response[1] = targetHostAndPort[0];
response[2] = targetHostAndPort[1];
return response;
}
private static String[] extractParts(String from) {
int idx = from.lastIndexOf(":");
String host = idx != -1 ? from.substring(0, idx) : from;
String port = idx != -1 ? from.substring(idx + 1) : "";
return new String[] { host, port };
}
}
private boolean isPassThroughCommand(Command command) {
RedisClient bindClient = command.getChannelInfo().getBindClient();
if (bindClient != null) return false;
RedisCommand redisCommand = command.getRedisCommand();
RedisCommand.CommandSupportType supportType = redisCommand.getSupportType();
if (supportType == RedisCommand.CommandSupportType.PARTIALLY_SUPPORT_1
|| supportType == RedisCommand.CommandSupportType.RESTRICTIVE_SUPPORT) {
return false;
}
RedisCommand.CommandKeyType commandKeyType = redisCommand.getCommandKeyType();
return commandKeyType == RedisCommand.CommandKeyType.SIMPLE_SINGLE && !command.isBlocking();
}
private void msetnx(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[][] objects = command.getObjects();
int slot = -1;
for (int i=1; i<objects.length; i+=2) {
byte[] key = objects[i];
int nextSlot = RedisClusterCRC16Utils.getSlot(key);
if (slot > 0) {
if (slot != nextSlot) {
future.complete(new ErrorReply("CROSSSLOT Keys in request don't hash to the same slot"));
return;
}
}
slot = nextSlot;
}
RedisClient client = getClient(slot);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
}
private void checkSlotCommandsAndSend(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future, int start, int end, byte[]...otherKeys) {
int slot = checkSlot(command, start, end, otherKeys);
if (slot < 0) {
future.complete(new ErrorReply("CROSSSLOT Keys in request don't hash to the same slot"));
return;
}
RedisClient client = getClient(slot);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
}
private int checkSlot(Command command, int start, int end, byte[]...otherKeys) {
byte[][] objects = command.getObjects();
int slot = -1;
for (int i=start; i<=end; i++) {
byte[] key = objects[i];
int nextSlot = RedisClusterCRC16Utils.getSlot(key);
if (slot >= 0) {
if (slot != nextSlot) {
return -1;
}
}
slot = nextSlot;
}
if (otherKeys != null) {
for (byte[] key : otherKeys) {
int nextSlot = RedisClusterCRC16Utils.getSlot(key);
if (slot >= 0) {
if (slot != nextSlot) {
return -1;
}
}
slot = nextSlot;
}
}
return slot;
}
private void evalOrEvalSha(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[][] objects = command.getObjects();
long keyCount = Utils.bytesToNum(objects[2]);
if (keyCount == 0) {
RedisClient client = getClient(0);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
} else if (keyCount == 1) {
byte[] key = objects[3];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
} else {
byte[] key = objects[3];
int slot = RedisClusterCRC16Utils.getSlot(key);
for (int i=4; i<3+keyCount; i++) {
int nextSlot = RedisClusterCRC16Utils.getSlot(objects[i]);
if (slot != nextSlot) {
future.complete(new ErrorReply("CROSSSLOT Keys in request don't hash to the same slot"));
return;
}
}
RedisClient client = getClient(slot);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
}
}
private void mget(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[][] args = command.getObjects();
List<CompletableFuture<Reply>> futureList = new ArrayList<>();
for (int i=1; i<args.length; i++) {
byte[] key = args[i];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
Command subCommand = new Command(new byte[][]{RedisCommand.GET.raw(), key});
CompletableFuture<Reply> subFuture = new CompletableFuture<>();
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, subFuture, subCommand);
commandFlusher.sendCommand(client, subCommand, futureWrapper);
futureList.add(subFuture);
}
if (futureList.size() == 1) {
CompletableFuture<Reply> completableFuture = futureList.get(0);
completableFuture.thenAccept(reply -> {
if (reply instanceof ErrorReply) {
future.complete(reply);
} else {
future.complete(new MultiBulkReply(new Reply[]{reply}));
}
});
return;
}
AsyncUtils.allOf(futureList).thenAccept(replies -> {
Reply[] retRelies = new Reply[replies.size()];
for (int i=0; i<replies.size(); i++) {
retRelies[i] = replies.get(i);
if (retRelies[i] instanceof ErrorReply) {
future.complete(retRelies[i]);
return;
}
}
future.complete(new MultiBulkReply(retRelies));
});
}
private void mset(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[][] args = command.getObjects();
List<CompletableFuture<Reply>> futureList = new ArrayList<>();
for (int i=1; i<args.length; i++, i++) {
byte[] key = args[i];
byte[] value = args[i+1];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
Command subCommand = new Command(new byte[][]{RedisCommand.SET.raw(), key, value});
CompletableFuture<Reply> subFuture = new CompletableFuture<>();
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, subFuture, subCommand);
commandFlusher.sendCommand(client, subCommand, futureWrapper);
futureList.add(subFuture);
}
if (futureList.size() == 1) {
CompletableFuture<Reply> completableFuture = futureList.get(0);
completableFuture.thenAccept(future::complete);
return;
}
AsyncUtils.allOf(futureList).thenAccept(replies -> future.complete(Utils.mergeStatusReply(replies)));
}
private void simpleIntegerReplyMerge(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[][] args = command.getObjects();
List<CompletableFuture<Reply>> futureList = new ArrayList<>();
for (int i=1; i<args.length; i++) {
byte[] key = args[i];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
Command subCommand = new Command(new byte[][]{args[0], key});
CompletableFuture<Reply> subFuture = new CompletableFuture<>();
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, subFuture, subCommand);
commandFlusher.sendCommand(client, subCommand, futureWrapper);
futureList.add(subFuture);
}
if (futureList.size() == 1) {
CompletableFuture<Reply> completableFuture = futureList.get(0);
completableFuture.thenAccept(future::complete);
return;
}
AsyncUtils.allOf(futureList).thenAccept(replies -> future.complete(Utils.mergeIntegerReply(replies)));
}
private void blockingCommand(int slot, Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
if (slot < 0) {
future.complete(new ErrorReply("CROSSSLOT Keys in request don't hash to the same slot"));
return;
}
RedisClusterSlotInfo.Node node = clusterSlotInfo.getNode(slot);
if (node == null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class, "blockingCommand getNode, slot=" + slot + " fail");
future.complete(ErrorReply.NOT_AVAILABLE);
return;
}
RedisClient client = command.getChannelInfo().tryGetExistsRedisClientForBlockingCommand(node.getAddr());
if (client == null || !client.isValid()) {
client = RedisClientHub.newClient(node.getAddr());
if (client == null) {
ErrorLogCollector.collect(AsyncCamelliaRedisClusterClient.class, "blockingCommand newClient, node=" + node.getAddr() + " fail");
future.complete(ErrorReply.NOT_AVAILABLE);
return;
}
}
commandFlusher.flush();
commandFlusher.clear();
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
client.sendCommand(Collections.singletonList(command), Collections.singletonList(futureWrapper));
client.startIdleCheck();
command.getChannelInfo().addRedisClientForBlockingCommand(client);
}
private void xreadOrXreadgroup(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[][] objects = command.getObjects();
int index = -1;
for (int i=1; i<objects.length; i++) {
String string = new String(objects[i], Utils.utf8Charset);
if (string.equalsIgnoreCase(RedisKeyword.STREAMS.name())) {
index = i;
break;
}
}
int last = objects.length - index - 1;
int keyCount = last / 2;
int slot = checkSlot(command, index + 1, index + keyCount);
if (command.isBlocking()) {
blockingCommand(slot, command, commandFlusher, future);
} else {
if (slot < 0) {
future.complete(new ErrorReply("CROSSSLOT Keys in request don't hash to the same slot"));
return;
}
RedisClient client = getClient(slot);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
}
}
private void xinfoOrXgroup(Command command, CommandFlusher commandFlusher, CompletableFuture<Reply> future) {
byte[] key = command.getObjects()[2];
int slot = RedisClusterCRC16Utils.getSlot(key);
RedisClient client = getClient(slot);
CompletableFutureWrapper futureWrapper = new CompletableFutureWrapper(this, future, command);
commandFlusher.sendCommand(client, command, futureWrapper);
}
}
|
92412dc67fdc9457a06763d30da66fafdd41052e | 1,704 | java | Java | src/main/java/net/earthcomputer/multiconnect/packets/latest/SPacketCustomPayload_Latest.java | Earthcomputer/mutliconnect | 8317b092a2940bca6bf2a84a90b2df7e24ee97bb | [
"MIT"
] | null | null | null | src/main/java/net/earthcomputer/multiconnect/packets/latest/SPacketCustomPayload_Latest.java | Earthcomputer/mutliconnect | 8317b092a2940bca6bf2a84a90b2df7e24ee97bb | [
"MIT"
] | null | null | null | src/main/java/net/earthcomputer/multiconnect/packets/latest/SPacketCustomPayload_Latest.java | Earthcomputer/mutliconnect | 8317b092a2940bca6bf2a84a90b2df7e24ee97bb | [
"MIT"
] | null | null | null | 40.571429 | 105 | 0.773474 | 1,001,803 | package net.earthcomputer.multiconnect.packets.latest;
import net.earthcomputer.multiconnect.ap.Argument;
import net.earthcomputer.multiconnect.ap.FilledArgument;
import net.earthcomputer.multiconnect.ap.Handler;
import net.earthcomputer.multiconnect.ap.Length;
import net.earthcomputer.multiconnect.ap.MessageVariant;
import net.earthcomputer.multiconnect.ap.Polymorphic;
import net.earthcomputer.multiconnect.api.Protocols;
import net.earthcomputer.multiconnect.packets.SPacketCustomPayload;
import net.earthcomputer.multiconnect.protocols.generic.CustomPayloadHandler;
import net.minecraft.client.network.ClientPlayNetworkHandler;
import net.minecraft.util.Identifier;
@MessageVariant(minVersion = Protocols.V1_14)
@Polymorphic
public abstract class SPacketCustomPayload_Latest implements SPacketCustomPayload {
public Identifier channel;
@Polymorphic(stringValue = "brand")
@MessageVariant(minVersion = Protocols.V1_14)
public static class Brand extends SPacketCustomPayload_Latest implements SPacketCustomPayload.Brand {
public String brand;
}
@Polymorphic(otherwise = true)
@MessageVariant(minVersion = Protocols.V1_14)
public static class Other extends SPacketCustomPayload_Latest implements SPacketCustomPayload.Other {
@Length(remainingBytes = true)
public byte[] data;
@Handler
public static void handle(
@Argument("channel") Identifier channel,
@Argument("data") byte[] data,
@FilledArgument ClientPlayNetworkHandler networkHandler
) {
CustomPayloadHandler.handleClientboundIdentifierCustomPayload(networkHandler, channel, data);
}
}
}
|
92412ec8d57bad03367e5dccb502094748d21e2e | 6,971 | java | Java | MobileAndroid/finish_projek_kost-kita_4/volley/app/src/main/java/com/kos/KostKita/RegisterActivity.java | FitriaAziati999/framework_kos | 770078c59168c89bc1f95e465a5835a1f697fa59 | [
"MIT"
] | null | null | null | MobileAndroid/finish_projek_kost-kita_4/volley/app/src/main/java/com/kos/KostKita/RegisterActivity.java | FitriaAziati999/framework_kos | 770078c59168c89bc1f95e465a5835a1f697fa59 | [
"MIT"
] | null | null | null | MobileAndroid/finish_projek_kost-kita_4/volley/app/src/main/java/com/kos/KostKita/RegisterActivity.java | FitriaAziati999/framework_kos | 770078c59168c89bc1f95e465a5835a1f697fa59 | [
"MIT"
] | null | null | null | 41.005882 | 131 | 0.597619 | 1,001,804 | package com.kos.KostKita;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.kos.KostKita.config.ServerApi;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class RegisterActivity extends AppCompatActivity {
TextView Akun;
EditText FullName, Email, Username, alamat, NoHP, NikKtp, Password, Password2;
Button Register;
ProgressDialog progressDialog;
RequestQueue requestQueue;
ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Akun = (TextView) findViewById(R.id.textViewL);
FullName = (EditText) findViewById(R.id.EditTextFullName);
Email = (EditText) findViewById(R.id.EditTextEmail);
Username = (EditText) findViewById(R.id.EditTextUsername);
alamat = (EditText) findViewById(R.id.EditTextalamat);
NoHP = (EditText) findViewById(R.id.EditTextNoHp);
NikKtp =(EditText) findViewById(R.id.EditTextNikKtp);
Password = (EditText) findViewById(R.id.EditTextPassword);
Password2 = (EditText) findViewById(R.id.EditTextPassword2);
Register = (Button) findViewById(R.id.ButtonRegister);
requestQueue = Volley.newRequestQueue(RegisterActivity.this);
progressDialog = new ProgressDialog(this);
progressBar = new ProgressBar(RegisterActivity.this);
Akun.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent masuk = new Intent(RegisterActivity.this , LoginActivity.class);
startActivity(masuk);
}
});
Register.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
UserRegistration();
}
});
}
public void UserRegistration() {
final String namapem = this.FullName.getText().toString().trim();
final String emailpem = this.Email.getText().toString().trim();
final String userpem = this.Username.getText().toString().trim();
final String alamatpem = this.alamat.getText().toString().trim();
final String nopem = this.NoHP.getText().toString().trim();
final String nikpem = this.NikKtp.getText().toString().trim();
final String passpem = this.Password.getText().toString().trim();
if (namapem.matches("")){
Toast.makeText(this, "Masukkan Nama Anda", Toast.LENGTH_SHORT).show();
return;
}
if (emailpem.matches("")){
Toast.makeText(this, "Masukkan email Anda", Toast.LENGTH_SHORT).show();
return;
}
if (userpem.matches("")){
Toast.makeText(this, "Masukkan Username Anda", Toast.LENGTH_SHORT).show();
return;
}
if (alamatpem.matches("")){
Toast.makeText(this, "Masukkan alamat Anda", Toast.LENGTH_SHORT).show();
return;
}
if (nopem.matches("")){
Toast.makeText(this, "Masukkan nomor Anda", Toast.LENGTH_SHORT).show();
return;
}
if (nikpem.matches("")){
Toast.makeText(this, "Masukkan NIK Anda", Toast.LENGTH_SHORT).show();
return;
}
if (passpem.matches("")){
Toast.makeText(this, "Masukkan password Anda", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.GONE);
Akun.setVisibility(View.GONE);
StringRequest stringRequest = new StringRequest(Request.Method.POST, ServerApi.URL_REGIS, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String status = jsonObject.getString("status");
String error = jsonObject.getString("error");
String message = jsonObject.getString("message");
if (status.equals("200") && error.equals("false")) {
Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent2 = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent2);
}
}, 1500);
} else {
Toast.makeText(RegisterActivity.this, message, Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Akun.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
progressBar.setVisibility(View.GONE);
Intent intent3 = new Intent(RegisterActivity.this, LoginActivity.class);
startActivity(intent3);
Toast.makeText(RegisterActivity.this, "Registrasi Berhasil", Toast.LENGTH_SHORT).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(RegisterActivity.this, "Error! " + error.toString(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
Akun.setVisibility(View.VISIBLE);
}
})
{
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("namapem", namapem);
params.put("emailpem", emailpem);
params.put("userpem", userpem);
params.put("alamatpem", alamatpem);
params.put("nopem", nopem);
params.put("nikpem", nikpem);
params.put("passpem", passpem);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
} |
924131c19aee07a181c8b372bc9924b85f427104 | 277 | java | Java | src/main/java/com/yzy/demo/pattern/abstarctfactory/AdidasCoat.java | utf-24/java-summary | 13e8ee89383cfeb7d42c504d57c30512cf06c81d | [
"MIT"
] | null | null | null | src/main/java/com/yzy/demo/pattern/abstarctfactory/AdidasCoat.java | utf-24/java-summary | 13e8ee89383cfeb7d42c504d57c30512cf06c81d | [
"MIT"
] | null | null | null | src/main/java/com/yzy/demo/pattern/abstarctfactory/AdidasCoat.java | utf-24/java-summary | 13e8ee89383cfeb7d42c504d57c30512cf06c81d | [
"MIT"
] | null | null | null | 17.3125 | 50 | 0.66426 | 1,001,805 | package com.yzy.demo.pattern.abstarctfactory;
/**
* @author young
* @date 2019/7/5 9:14
*/
public class AdidasCoat implements Coat {
String description = "this is coat of adidas";
@Override
public String getDescription() {
return description;
}
}
|
924131ed86077984d32a1b50a84cb048d497286e | 1,090 | java | Java | projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/routing_policy/expr/SelfNextHop.java | kylehoferamzn/batfish | d905cd47a3afe63e6f51652d792473a42b2f3026 | [
"Apache-2.0"
] | 16 | 2015-07-20T07:33:32.000Z | 2016-10-27T20:25:19.000Z | projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/routing_policy/expr/SelfNextHop.java | kylehoferamzn/batfish | d905cd47a3afe63e6f51652d792473a42b2f3026 | [
"Apache-2.0"
] | 7 | 2019-03-08T19:55:37.000Z | 2021-11-10T08:44:08.000Z | projects/batfish-common-protocol/src/main/java/org/batfish/datamodel/routing_policy/expr/SelfNextHop.java | kylehoferamzn/batfish | d905cd47a3afe63e6f51652d792473a42b2f3026 | [
"Apache-2.0"
] | 9 | 2015-01-04T10:10:29.000Z | 2016-10-24T18:51:54.000Z | 27.25 | 99 | 0.747706 | 1,001,806 | package org.batfish.datamodel.routing_policy.expr;
import javax.annotation.Nullable;
import org.batfish.datamodel.BgpSessionProperties;
import org.batfish.datamodel.Ip;
import org.batfish.datamodel.routing_policy.Environment;
/** Implements BGP next-hop-self semantics */
public class SelfNextHop extends NextHopExpr {
private static final SelfNextHop _instance = new SelfNextHop();
public static SelfNextHop getInstance() {
return _instance;
}
private SelfNextHop() {}
@Override
public boolean equals(Object obj) {
return this == obj || obj instanceof NextHopExpr;
}
@Override
@Nullable
public Ip getNextHopIp(Environment environment) {
// BgpSessionProperties are for session directed toward the node with the policy being executed
BgpSessionProperties sessionProperties = environment.getBgpSessionProperties();
return sessionProperties == null ? null : sessionProperties.getHeadIp();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + 0x12345678;
return result;
}
}
|
92413285df85a666cbbdb31a19893e37822fba90 | 1,329 | java | Java | src/main/java/uk/gov/hmcts/reform/divorce/casemaintenanceservice/service/PetitionService.java | uk-gov-mirror/hmcts.div-case-maintenance-service | bdd9627dd889345ec3db16b97c109ea3b3611d18 | [
"MIT"
] | 2 | 2018-10-04T15:14:44.000Z | 2021-03-25T08:31:08.000Z | src/main/java/uk/gov/hmcts/reform/divorce/casemaintenanceservice/service/PetitionService.java | uk-gov-mirror/hmcts.div-case-maintenance-service | bdd9627dd889345ec3db16b97c109ea3b3611d18 | [
"MIT"
] | 405 | 2018-06-13T14:54:29.000Z | 2022-03-30T20:13:13.000Z | src/main/java/uk/gov/hmcts/reform/divorce/casemaintenanceservice/service/PetitionService.java | hmcts/div-case-management-service | 41e037acfc59c7d224a82ccea341a3f1a3589c6d | [
"MIT"
] | 1 | 2021-04-10T22:36:56.000Z | 2021-04-10T22:36:56.000Z | 39.088235 | 114 | 0.820166 | 1,001,807 | package uk.gov.hmcts.reform.divorce.casemaintenanceservice.service;
import uk.gov.hmcts.reform.ccd.client.model.CaseDetails;
import uk.gov.hmcts.reform.divorce.casemaintenanceservice.domain.model.CaseState;
import uk.gov.hmcts.reform.divorce.casemaintenanceservice.domain.model.CaseStateGrouping;
import uk.gov.hmcts.reform.divorce.casemaintenanceservice.draftstore.model.DraftList;
import java.util.List;
import java.util.Map;
public interface PetitionService {
CaseDetails retrievePetition(String authorisation, Map<CaseStateGrouping, List<CaseState>> caseStateGrouping);
CaseDetails retrievePetition(String authorisation);
CaseDetails retrievePetitionForAos(String authorisation);
CaseDetails retrievePetitionByCaseId(String authorisation, String caseId);
void saveDraft(String authorisation, Map<String, Object> data, boolean divorceFormat);
void createDraft(String authorisation, Map<String, Object> data, boolean divorceFormat);
DraftList getAllDrafts(String authorisation);
void deleteDraft(String authorisation);
Map<String, Object> createAmendedPetitionDraft(String authorisation);
Map<String, Object> createAmendedPetitionDraftRefusal(String authorisation);
Map<String, Object> createAmendedPetitionDraftRefusalFromCaseId(String authorisation, String caseId);
}
|
924132d23d24f52df237e10cfd5fe7b5643e99b9 | 4,505 | java | Java | corpus/class/eclipse.pde.ui/2221.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 15 | 2018-07-10T09:38:31.000Z | 2021-11-29T08:28:07.000Z | corpus/class/eclipse.pde.ui/2221.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 3 | 2018-11-16T02:58:59.000Z | 2021-01-20T16:03:51.000Z | corpus/class/eclipse.pde.ui/2221.java | masud-technope/ACER-Replication-Package-ASE2017 | cb7318a729eb1403004d451a164c851af2d81f7a | [
"MIT"
] | 6 | 2018-06-27T20:19:00.000Z | 2022-02-19T02:29:53.000Z | 37.857143 | 121 | 0.631521 | 1,001,808 | /*******************************************************************************
* Copyright (c) 2006, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.pde.internal.ua.ui.editor.cheatsheet.simple.actions;
import java.util.ArrayList;
import org.eclipse.jface.action.Action;
import org.eclipse.pde.internal.ua.core.cheatsheet.simple.ISimpleCSConstants;
import org.eclipse.pde.internal.ua.core.cheatsheet.simple.ISimpleCSItem;
import org.eclipse.pde.internal.ua.core.cheatsheet.simple.ISimpleCSModelFactory;
import org.eclipse.pde.internal.ua.core.cheatsheet.simple.ISimpleCSObject;
import org.eclipse.pde.internal.ua.core.cheatsheet.simple.ISimpleCSSubItem;
import org.eclipse.pde.internal.ua.core.cheatsheet.simple.ISimpleCSSubItemObject;
import org.eclipse.pde.internal.ui.util.PDELabelUtility;
/**
* SimpleCSAddStepAction
*
*/
public class SimpleCSAddSubStepAction extends Action {
private ISimpleCSItem fItem;
private ISimpleCSSubItem fSubitem;
/**
*
*/
public SimpleCSAddSubStepAction() {
setText(SimpleActionMessages.SimpleCSAddSubStepAction_actionText);
}
/**
* @param cheatsheet
*/
public void setDataObject(ISimpleCSObject csObject) {
// Determine input
if (csObject.getType() == ISimpleCSConstants.TYPE_ITEM) {
fSubitem = null;
fItem = (ISimpleCSItem) csObject;
} else if (csObject.getType() == ISimpleCSConstants.TYPE_SUBITEM) {
fSubitem = (ISimpleCSSubItem) csObject;
ISimpleCSObject parentObject = fSubitem.getParent();
// Determine input's parent object
if (parentObject.getType() == ISimpleCSConstants.TYPE_ITEM) {
fItem = (ISimpleCSItem) parentObject;
} else if (parentObject.getType() == ISimpleCSConstants.TYPE_CONDITIONAL_SUBITEM) {
// Not supported by editor, action will not run
fItem = null;
} else if (parentObject.getType() == ISimpleCSConstants.TYPE_REPEATED_SUBITEM) {
// Note supported by editor, action will not run
fItem = null;
}
} else {
// Invalid input, action will not run
fSubitem = null;
fItem = null;
}
}
/* (non-Javadoc)
* @see org.eclipse.jface.action.Action#run()
*/
public void run() {
// Ensure we have valid input
if (fItem == null) {
return;
}
// Create the new subitem
ISimpleCSSubItem newSubItem = createNewSubItem();
// Insert the new subitem
insertNewSubItem(newSubItem);
}
/**
* @return
*/
private ISimpleCSSubItem createNewSubItem() {
ISimpleCSModelFactory factory = fItem.getModel().getFactory();
// Element: subitem
ISimpleCSSubItem subitem = factory.createSimpleCSSubItem(fItem);
ISimpleCSSubItemObject[] subItems = fItem.getSubItems();
ArrayList subItemNames = new ArrayList(subItems.length);
for (int i = 0; i < subItems.length; ++i) {
if (subItems[i].getType() == ISimpleCSConstants.TYPE_SUBITEM) {
subItemNames.add(((ISimpleCSSubItem) subItems[i]).getLabel());
}
}
String[] names = (String[]) subItemNames.toArray(new String[subItemNames.size()]);
// Set on the proper parent object
subitem.setLabel(PDELabelUtility.generateName(names, SimpleActionMessages.SimpleCSAddSubStepAction_actionLabel));
return subitem;
}
/**
* @param newSubItem
*/
private void insertNewSubItem(ISimpleCSSubItem newSubItem) {
// Insert the new subitem depending on the input specfied
if (fSubitem != null) {
// Subitem input object
// Insert subitem right after the input item object
int index = fItem.indexOfSubItem(fSubitem) + 1;
fItem.addSubItem(index, newSubItem);
} else {
// Item input object
// Insert subitem as the last child subitem
fItem.addSubItem(newSubItem);
}
}
}
|
924133deec379cd847dec69dfe867fc28cb983a1 | 1,930 | java | Java | src/dhbw/antlr/calc/compiler/calcBaseVisitor.java | fidsusj/CustomCompiler | 9e4ca3166d71704dcdb2fb09014b862138cca80e | [
"BSD-3-Clause"
] | null | null | null | src/dhbw/antlr/calc/compiler/calcBaseVisitor.java | fidsusj/CustomCompiler | 9e4ca3166d71704dcdb2fb09014b862138cca80e | [
"BSD-3-Clause"
] | null | null | null | src/dhbw/antlr/calc/compiler/calcBaseVisitor.java | fidsusj/CustomCompiler | 9e4ca3166d71704dcdb2fb09014b862138cca80e | [
"BSD-3-Clause"
] | null | null | null | 34.464286 | 95 | 0.700518 | 1,001,809 | // Generated from calc.g4 by ANTLR 4.7.2
package dhbw.antlr.calc.compiler;
import org.antlr.v4.runtime.tree.AbstractParseTreeVisitor;
/**
* This class provides an empty implementation of {@link calcVisitor},
* which can be extended to create a visitor which only needs to handle a subset
* of the available methods.
*
* @param <T> The return type of the visit operation. Use {@link Void} for
* operations with no return type.
*/
public class calcBaseVisitor<T> extends AbstractParseTreeVisitor<T> implements calcVisitor<T> {
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitStart(calcParser.StartContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitDiv(calcParser.DivContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitNumber(calcParser.NumberContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMul(calcParser.MulContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitPlus(calcParser.PlusContext ctx) { return visitChildren(ctx); }
/**
* {@inheritDoc}
*
* <p>The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.</p>
*/
@Override public T visitMinus(calcParser.MinusContext ctx) { return visitChildren(ctx); }
} |
924133e2714f113e2444a79faa44aa6ceceea3f9 | 4,074 | java | Java | cymbal-service/src/main/java/com/dangdang/cymbal/service/monitor/service/impl/PrometheusAlertManagerServiceImpl.java | dangdangdotcom/cymbal | 0ebf81bd5c575222feb7f0e6a2adda5e626f16ce | [
"Apache-2.0"
] | 62 | 2019-12-31T05:55:58.000Z | 2022-03-02T07:09:33.000Z | cymbal-service/src/main/java/com/dangdang/cymbal/service/monitor/service/impl/PrometheusAlertManagerServiceImpl.java | dangdangdotcom/cymbal | 0ebf81bd5c575222feb7f0e6a2adda5e626f16ce | [
"Apache-2.0"
] | 2 | 2020-01-08T07:43:01.000Z | 2020-03-28T11:47:41.000Z | cymbal-service/src/main/java/com/dangdang/cymbal/service/monitor/service/impl/PrometheusAlertManagerServiceImpl.java | dangdangdotcom/cymbal | 0ebf81bd5c575222feb7f0e6a2adda5e626f16ce | [
"Apache-2.0"
] | 10 | 2020-01-02T03:00:13.000Z | 2022-02-02T06:27:16.000Z | 40.77 | 142 | 0.728477 | 1,001,810 | package com.dangdang.cymbal.service.monitor.service.impl;
import com.dangdang.cymbal.domain.po.Cluster;
import com.dangdang.cymbal.domain.po.ClusterPermission;
import com.dangdang.cymbal.service.auth.service.entity.ClusterPermissionEntityService;
import com.dangdang.cymbal.service.cluster.service.entity.ClusterEntityService;
import com.dangdang.cymbal.service.monitor.service.AlertManagerService;
import com.dangdang.cymbal.service.util.MailUtil;
import com.dangdang.cymbal.service.util.service.MailService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* Handle alert event from prometheus.
*
* @Author: GeZhen
*/
@Slf4j
@Service
public class PrometheusAlertManagerServiceImpl implements AlertManagerService {
private final static String KEY_COMMON_LABELS = "commonLabels";
private final static String KEY_COMMON_ANNOTATIONS = "commonAnnotations";
private final static String KEY_CLUSTER_ID = "alias";
private final static String KEY_ALERTS = "alerts";
private final static String KEY_SUMMARY = "summary";
private final static String KEY_DESCRIPTION = "description";
private final static String KEY_ADDR = "addr";
private final static String KEY_LABELS = "labels";
private final static String KEY_ANNOTATIONS = "annotations";
@Resource
private ClusterEntityService clusterEntityService;
@Resource
private ClusterPermissionEntityService clusterPermissionEntityService;
@Resource
private MailService mailService;
@Override
public void handleAlert(Object alertInfo) {
// prometheus的alert manager的报警结构体是一个map
Map<String, Object> alertInfoMap = (Map<String, Object>) alertInfo;
Map<String, String> commonLabels = (Map<String, String>) alertInfoMap.get(KEY_COMMON_LABELS);
String clusterId = commonLabels.get(KEY_CLUSTER_ID);
Cluster cluster = clusterEntityService.getByClusterId(clusterId);
Preconditions.checkNotNull(cluster, String.format("Can not find cluster with id %s.", clusterId));
Map<String, String> commonAnnotations = (Map<String, String>) alertInfoMap.get(KEY_COMMON_ANNOTATIONS);
String alertTitle = commonAnnotations.get(KEY_SUMMARY);
// 邮件内容,首先拼接集群描述
StringBuilder mailContent = new StringBuilder();
mailContent.append(MailUtil.getClusterInfoForHtmlMail(cluster));
// 拼接报警信息描述
List<Map<String, Object>> alerts = (List<Map<String, Object>>) alertInfoMap.get(KEY_ALERTS);
appendAlertInstancesToMailContent(alerts, mailContent);
// 收件人
List<ClusterPermission> permissions = clusterPermissionEntityService.queryByClusterId(clusterId);
List<String> receivers = permissions.stream().map(each -> String.format("anpch@example.com", each.getUserName()))
.collect(Collectors.toList());
receivers.add(0, String.format("anpch@example.com", cluster.getUserName()));
String mailTitle = String.format("[OPS平台报警] [Redis异常] [%s] [%s]", alertTitle, cluster.getDescription());
mailService.sendHtmlMail(mailTitle, mailContent.toString(), receivers.toArray(new String[receivers.size()]));
// 测试状态下的收件人
// mailService.sendMail(mailTitle, mailContent.toString(), new String[]{"hzdkv@example.com", "kenaa@example.com"}, null, true);
}
private void appendAlertInstancesToMailContent(List<Map<String, Object>> alerts, StringBuilder mailContent) {
mailContent.append("<p>").append("异常节点列表: ").append("</p>");
for (Map<String, Object> each : alerts) {
String addr = ((Map<String, String>) each.get(KEY_LABELS)).get(KEY_ADDR);
String description = ((Map<String, String>) each.get(KEY_ANNOTATIONS)).get(KEY_DESCRIPTION);
mailContent.append("<p>").append(" - ").append(addr).append(": ").append(description).append("</p>");
}
}
}
|
9241348787177bb29d662e82950cf08580f85ea4 | 2,072 | java | Java | chapter_005/src/test/java/ru/job4j/list/MyStackTest.java | alexander-pimenov/lessons-job4j | 5d25c130e8c26feb0be656ae98169922cb7a678f | [
"Apache-2.0"
] | 1 | 2019-01-10T16:51:27.000Z | 2019-01-10T16:51:27.000Z | chapter_005/src/test/java/ru/job4j/list/MyStackTest.java | VladimirZhdanov/job4j | 2d74da0f7118f5e3c8bd7f4e71c739f6ea8782b2 | [
"Apache-2.0"
] | 4 | 2021-12-10T01:13:38.000Z | 2022-02-16T00:56:31.000Z | chapter_005/src/test/java/ru/job4j/list/MyStackTest.java | alexander-pimenov/lessons-job4j | 5d25c130e8c26feb0be656ae98169922cb7a678f | [
"Apache-2.0"
] | null | null | null | 28.847222 | 65 | 0.657198 | 1,001,811 | package ru.job4j.list;
import org.hamcrest.MatcherAssert;
import org.junit.Test;
import org.junit.Before;
import java.util.Iterator;
import java.util.NoSuchElementException;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
/**
* MyStackTest
*
* @author Vladimir Zhdanov (mailto:anpch@example.com)
* @version $Id$
* @since 0.1
*/
public class MyStackTest {
private MyStack<Integer> list;
private Iterator<Integer> iterator;
@Before
public void beforeTest() {
list = new MyStack<>();
list.push(1);
list.push(2);
list.push(3);
iterator = list.iterator();
}
@Test
public void shouldSequentiallyReturnItems() {
MatcherAssert.assertThat(iterator.next(), is(3));
MatcherAssert.assertThat(iterator.next(), is(2));
MatcherAssert.assertThat(iterator.next(), is(1));
//iterator.next();
}
@Test(expected = NoSuchElementException.class)
public void shouldReturnItemsSequentially() {
MatcherAssert.assertThat(iterator.hasNext(), is(true));
MatcherAssert.assertThat(iterator.next(), is(3));
MatcherAssert.assertThat(iterator.hasNext(), is(true));
MatcherAssert.assertThat(iterator.next(), is(2));
MatcherAssert.assertThat(iterator.hasNext(), is(true));
MatcherAssert.assertThat(iterator.next(), is(1));
MatcherAssert.assertThat(iterator.hasNext(), is(false));
iterator.next();
}
@Test
public void shouldReturnFalseIfNoAnyItems() {
MyLinkedList<String> list = new MyLinkedList<>();
Iterator<String> iterator = list.iterator();
MatcherAssert.assertThat(iterator.hasNext(), is(false));
}
@Test
public void whenAddThreeElementsThenUseGetSizeResultThree() {
assertThat(list.size(), is(3));
}
@Test
public void whenPoll() {
assertThat(list.poll(), is(3));
assertThat(list.poll(), is(2));
assertThat(list.poll(), is(1));
}
} |
9241349e3f8a1d3844d369802969d24651c6119d | 501 | java | Java | src/test/java/uk/co/yourorg/yourpackage/junit/SeleniumTest.java | webcompere/selenium-junit5-spring-poc | c272db38abe97f1bb443eef627c5969a5bd8b009 | [
"MIT"
] | null | null | null | src/test/java/uk/co/yourorg/yourpackage/junit/SeleniumTest.java | webcompere/selenium-junit5-spring-poc | c272db38abe97f1bb443eef627c5969a5bd8b009 | [
"MIT"
] | null | null | null | src/test/java/uk/co/yourorg/yourpackage/junit/SeleniumTest.java | webcompere/selenium-junit5-spring-poc | c272db38abe97f1bb443eef627c5969a5bd8b009 | [
"MIT"
] | null | null | null | 31.3125 | 61 | 0.838323 | 1,001,812 | package uk.co.yourorg.yourpackage.junit;
import org.springframework.test.context.ContextConfiguration;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.ANNOTATION_TYPE, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@uk.co.webcompere.seleniumjunit5.annotations.SeleniumTest
@ContextConfiguration(classes = Config.class)
public @interface SeleniumTest {
}
|
92413516e62d1003b41f9bc97ec9ed0f55e49a42 | 1,480 | java | Java | app/src/main/java/android/room/play/com/nasadaily/util/Constants.java | Chexu/nasa-daily | 3e81fa38a26eb7056fd3cdcf43a7bcaf9433e9bb | [
"Apache-2.0"
] | null | null | null | app/src/main/java/android/room/play/com/nasadaily/util/Constants.java | Chexu/nasa-daily | 3e81fa38a26eb7056fd3cdcf43a7bcaf9433e9bb | [
"Apache-2.0"
] | null | null | null | app/src/main/java/android/room/play/com/nasadaily/util/Constants.java | Chexu/nasa-daily | 3e81fa38a26eb7056fd3cdcf43a7bcaf9433e9bb | [
"Apache-2.0"
] | null | null | null | 48 | 92 | 0.751344 | 1,001,813 | package android.room.play.com.nasadaily.util;
/**
* Created by Chirag Pc on 8/22/2015.
*/
public final class Constants {
public static final String NASA_APOD_URL = "https://api.nasa.gov/planetary/apod";
public static final String PARAM_API_KEY = "api_key";
public static final String PARAM_DATE = "date";
public static final String PARAM_API_VALUE = "74t3tndxag9o7h0890bnpfzh4olk2h9x";
public static final String PARAM_FORMAT = "format";
public static final String PARAM_JSON = "PARAM_JSON";
public static final String TRUE = "True";
public static final String TAG_URL = "url";
public static final String TAG_MEDIA_TYPE = "media_type";
public static final String TAG_EXPLANATION = "explanation";
public static final String TAG_CONCEPTS = "concept_tags";
public static final String TAG_TITLE = "title";
public static final String ERROR_CODE = "Error Code";
public static final int MSG_NETWORK_ERROR_CODE = 0;
public static final int MSG_SERVER_ERROR_CODE = 1;
public static final int DATE_DIFFERENCE = 6;
public static final String ARG_TITLE = "TITLE";
public static final String ARG_DESCRIPTION = "DESCRIPTION";
public static final String ARG_TRANSITION_NAME = "TRANSITION_NAME";
public static final String ARG_TRANSITION_TITLE = "TRANSITION_TITLE";
public static final String ARG_TRANSITION_DESC = "TRANSITION_DESC";
public static final String ARG_TRANSITION_CARD = "TRANSITION_CARD";
}
|
92413644205ccc498634ede8c9555c9c2c333599 | 1,026 | java | Java | src/main/java/io/prometheus/wls/rest/LogServlet.java | MrRothstein/weblogic-monitoring-exporter | 5587c3627020cb2f75a58989709f0e1a25ae2f63 | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | src/main/java/io/prometheus/wls/rest/LogServlet.java | MrRothstein/weblogic-monitoring-exporter | 5587c3627020cb2f75a58989709f0e1a25ae2f63 | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | src/main/java/io/prometheus/wls/rest/LogServlet.java | MrRothstein/weblogic-monitoring-exporter | 5587c3627020cb2f75a58989709f0e1a25ae2f63 | [
"UPL-1.0",
"Apache-2.0"
] | null | null | null | 38 | 113 | 0.731969 | 1,001,814 | // Copyright 2019, Oracle Corporation and/or its affiliates. All rights reserved.
// Licensed under the Universal Permissive License v 1.0 as shown at
// http://oss.oracle.com/licenses/upl.
package io.prometheus.wls.rest;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(value = "/" + ServletConstants.LOG_PAGE)
public class LogServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String errors = LiveConfiguration.getErrors();
if (errors == null || errors.trim().length() == 0)
resp.getOutputStream().println("No errors reported.");
else
resp.getOutputStream().println("<blockquote>" + errors + "</blockquote>");
resp.getOutputStream().close();
}
}
|
924137523084ff88d49118b011b60c7e604dbed5 | 706 | java | Java | src/test/resources/java/src/main/gen/melody/CanonMelody0Impl.java | bannmann/silverchain | c06b70083e47ac103177099cde1408d0a166ce89 | [
"MIT"
] | 8 | 2018-06-08T07:48:20.000Z | 2020-05-28T14:54:17.000Z | src/test/resources/java/src/main/gen/melody/CanonMelody0Impl.java | bannmann/silverchain | c06b70083e47ac103177099cde1408d0a166ce89 | [
"MIT"
] | null | null | null | src/test/resources/java/src/main/gen/melody/CanonMelody0Impl.java | bannmann/silverchain | c06b70083e47ac103177099cde1408d0a166ce89 | [
"MIT"
] | 1 | 2018-09-07T11:54:45.000Z | 2018-09-07T11:54:45.000Z | 23.533333 | 69 | 0.736544 | 1,001,815 | package melody;
@SuppressWarnings({"rawtypes", "unchecked"})
class CanonMelody0Impl implements melody.intermediates.CanonMelody0 {
melody.CanonMelodyAction action;
CanonMelody0Impl(melody.CanonMelodyAction action) {
this.action = action;
}
@Override
public melody.intermediates.CanonMelody1 a() {
this.action.state0$a();
return new melody.CanonMelody1Impl(this.action);
}
@Override
public melody.intermediates.CanonMelody1 d() {
this.action.state0$d();
return new melody.CanonMelody1Impl(this.action);
}
@Override
public melody.intermediates.CanonMelody1 fSharp() {
this.action.state0$fSharp();
return new melody.CanonMelody1Impl(this.action);
}
}
|
9241377415415b15339677b01379a42c4d7953c9 | 1,386 | java | Java | affirm/src/test/java/com/affirm/android/exception/InvalidRequestExceptionTest.java | nicolascapracredera/affirm-merchant-sdk-android | 85fbd8236a62d422f19b6e968dda8788ecdae804 | [
"BSD-3-Clause"
] | 1 | 2020-07-31T16:19:11.000Z | 2020-07-31T16:19:11.000Z | affirm/src/test/java/com/affirm/android/exception/InvalidRequestExceptionTest.java | nicolascapracredera/affirm-merchant-sdk-android | 85fbd8236a62d422f19b6e968dda8788ecdae804 | [
"BSD-3-Clause"
] | 49 | 2019-04-19T02:11:32.000Z | 2022-03-31T08:54:38.000Z | affirm/src/test/java/com/affirm/android/exception/InvalidRequestExceptionTest.java | nicolascapracredera/affirm-merchant-sdk-android | 85fbd8236a62d422f19b6e968dda8788ecdae804 | [
"BSD-3-Clause"
] | 4 | 2019-04-30T17:26:48.000Z | 2021-09-09T23:28:42.000Z | 32.232558 | 158 | 0.645743 | 1,001,816 | package com.affirm.android.exception;
import com.affirm.android.model.AbstractAddress;
import com.affirm.android.model.AddressSerializer;
import com.affirm.android.model.AffirmAdapterFactory;
import com.affirm.android.model.AffirmError;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class InvalidRequestExceptionTest {
private static final String affirmErrorJson = "{\"status_code\":400,\"type\":\"invalid-request\",\"code\":\"invalid_field\",\"message\":\"Bad request\"}";
private final Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(AffirmAdapterFactory.create())
.registerTypeAdapter(AbstractAddress.class, new AddressSerializer())
.create();
@Test
public void testWithOutThrowable() {
AffirmError affirmError = gson.fromJson(affirmErrorJson, AffirmError.class);
InvalidRequestException ex = new InvalidRequestException(
affirmError.message(),
affirmError.type(),
affirmError.fields(),
affirmError.field(),
"req_123",
affirmError.status(),
affirmError,
null
);
assertEquals(
"Bad request",
ex.getMessage()
);
}
}
|
9241398d7f447cfb7e876549e6384b538e641c79 | 2,520 | java | Java | src/main/java/com/freetymekiyan/algorithms/level/medium/SurroundedRegions.java | petercdcn/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 1,958 | 2015-01-30T01:19:03.000Z | 2022-03-17T03:34:47.000Z | src/main/java/com/freetymekiyan/algorithms/level/medium/SurroundedRegions.java | TechnoBlogger14o3/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 135 | 2016-03-03T04:53:10.000Z | 2022-03-03T21:14:37.000Z | src/main/java/com/freetymekiyan/algorithms/level/medium/SurroundedRegions.java | TechnoBlogger14o3/LeetCode-Sol-Res | 04621f21a76fab29909c1fa04a37417257a88f63 | [
"MIT"
] | 914 | 2015-01-27T22:27:22.000Z | 2022-03-05T04:25:10.000Z | 30.731707 | 91 | 0.553175 | 1,001,818 | package com.freetymekiyan.algorithms.level.medium;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
/**
* Given a 2D board containing 'X' and 'O', capture all regions surrounded by
* 'X'.
* <p>
* A region is captured by flipping all 'O's into 'X's in that surrounded
* region.
* <p>
* For example,
* X X X X
* X O O X
* X X O X
* X O X X
* <p>
* After running your function, the board should be:
* X X X X
* X X X X
* X X X X
* X O X X
* <p>
* Tags: BFS
*/
class SurroundedRegions {
/**
* Use a queue to store index to do BFS
* A 2d boolean array to remember whether a point is visited
* A 2d int array to represent 4-connectivity
* <p>
* Traverse through the board and BFS at where it's 'O' and not visited
* Set surround as true at first
* Create an integer list for points to change
* Check points around to see whether there is an 'O' point within the board
* and not visited
* If so, add it to queue, set visited true
* If not, it's not surrounded
*/
public static void solve(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0) return;
Queue<Integer> q = new LinkedList<Integer>();
int m = board.length;
int n = board[0].length;
boolean[][] visited = new boolean[m][n];
int[][] dir = {{1, 0}, {-1, 0}, {0, -1}, {0, 1}};
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'O' && !visited[i][j]) {
boolean surround = true;
List<Integer> pointsToChange = new ArrayList<Integer>();
q.add(i * n + j); // add root
visited[i][j] = true; // set root visited
while (q.size() > 0) { // BFS
int point = q.poll(); // get from queue
pointsToChange.add(point);
int x = point / n; // get coordinates
int y = point % n;
// try 4 direction
for (int k = 0; k < dir.length; k++) {
int nextX = x + dir[k][0];
int nextY = y + dir[k][1];
if (nextX >= 0 && nextX < m && nextY >= 0 && nextY < n) { // within board
if (board[nextX][nextY] == 'O' && !visited[nextX][nextY]) // add to queue
q.add(nextX * n + nextY);
visited[nextX][nextY] = true; // set visited
} else surround = false; // false if on the boundry
}
}
if (surround) for (int p : pointsToChange) board[p / n][p % n] = 'X'; // set to 'X'
}
}
}
}
}
|
924139aacdee8a64564ca6a4fe3bc422eeed3126 | 807 | java | Java | bootstrap-business/src/main/java/org/ligoj/bootstrap/core/resource/mapper/NoResultExceptionMapper.java | ligoj/bootstrap | 25c4c6c23a20a2aad114753f0aa1fa42785a6608 | [
"MIT"
] | 5 | 2017-03-19T19:47:55.000Z | 2021-04-22T05:09:49.000Z | bootstrap-business/src/main/java/org/ligoj/bootstrap/core/resource/mapper/NoResultExceptionMapper.java | ligoj/bootstrap | 25c4c6c23a20a2aad114753f0aa1fa42785a6608 | [
"MIT"
] | 22 | 2017-03-19T08:06:14.000Z | 2022-03-31T22:41:15.000Z | bootstrap-business/src/main/java/org/ligoj/bootstrap/core/resource/mapper/NoResultExceptionMapper.java | ligoj/bootstrap | 25c4c6c23a20a2aad114753f0aa1fa42785a6608 | [
"MIT"
] | null | null | null | 32.28 | 144 | 0.786865 | 1,001,819 | /*
* Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
*/
package org.ligoj.bootstrap.core.resource.mapper;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
import org.springframework.dao.EmptyResultDataAccessException;
/**
* Handles business exception (explicitly managed) {@link EmptyResultDataAccessException} (wrapping NoResultException)
* to a JSON string, and a 404 status code error.
*/
@Provider
public class NoResultExceptionMapper extends AbstractEntityNotFoundExceptionMapper implements ExceptionMapper<EmptyResultDataAccessException> {
@Override
public Response toResponse(final EmptyResultDataAccessException exception) {
return toResponseNotFound(exception.getCause());
}
}
|
92413aeeb125f4c1e811ce329c820297d94cf0e7 | 20,679 | java | Java | module/nuls-smart-contract/src/test/java/io/nuls/contract/tx/offline/ContractMultyAssetOfflineTest.java | tofchain/nuls-v2 | cd0eac6837ad8b85bc9d2dc6a63c8983790075e0 | [
"MIT"
] | 226 | 2019-05-13T07:17:22.000Z | 2022-02-13T02:08:23.000Z | module/nuls-smart-contract/src/test/java/io/nuls/contract/tx/offline/ContractMultyAssetOfflineTest.java | tofchain/nuls-v2 | cd0eac6837ad8b85bc9d2dc6a63c8983790075e0 | [
"MIT"
] | 31 | 2019-06-29T10:38:43.000Z | 2021-08-20T02:39:00.000Z | module/nuls-smart-contract/src/test/java/io/nuls/contract/tx/offline/ContractMultyAssetOfflineTest.java | lichao23/nuls_2.0 | 2972cbf5787dcd94635649fcd4be04a86c8e33a4 | [
"MIT"
] | 54 | 2019-05-17T07:29:52.000Z | 2022-03-20T18:10:37.000Z | 49.616471 | 179 | 0.678238 | 1,001,820 | /**
* MIT License
* <p>
* Copyright (c) 2017-2018 nuls.io
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.nuls.contract.tx.offline;
import io.nuls.base.RPCUtil;
import io.nuls.base.basic.AddressTool;
import io.nuls.base.basic.TransactionFeeCalculator;
import io.nuls.base.data.CoinData;
import io.nuls.base.data.CoinFrom;
import io.nuls.base.data.CoinTo;
import io.nuls.contract.model.bo.ContractBalance;
import io.nuls.contract.model.tx.CallContractTransaction;
import io.nuls.contract.model.txdata.CallContractData;
import io.nuls.contract.rpc.call.LedgerCall;
import io.nuls.contract.tx.base.BaseQuery;
import io.nuls.contract.util.ContractUtil;
import io.nuls.contract.util.Log;
import io.nuls.contract.vm.program.ProgramMultyAssetValue;
import io.nuls.core.basic.Result;
import io.nuls.core.crypto.HexUtil;
import io.nuls.core.exception.NulsException;
import io.nuls.core.model.LongUtils;
import io.nuls.core.model.StringUtils;
import io.nuls.core.parse.JSONUtils;
import io.nuls.core.rpc.model.ModuleE;
import io.nuls.core.rpc.model.message.Response;
import io.nuls.core.rpc.netty.processor.ResponseMessageProcessor;
import io.nuls.v2.NulsSDKBootStrap;
import io.nuls.v2.model.dto.SignDto;
import io.nuls.v2.util.NulsSDKTool;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.*;
import static io.nuls.contract.constant.ContractCmdConstant.CALL;
import static io.nuls.contract.constant.ContractCmdConstant.CREATE;
/**
* @author: PierreLuo
* @date: 2020-10-30
*/
public class ContractMultyAssetOfflineTest {
protected int chainId = 2;
protected int assetId = 1;
protected long gasLimit = 200000L;
protected long gasPrice = 25L;
protected long minutes_3 = 60 * 3;
protected String offlineContract = "kgfhvu9qnh3mr6eel97y6fq2hezzol8z";
// "http://localhost:18004/"
protected String apiURL = "http://beta.api.nuls.io/";
/**
* 多账户调用合约 - 转入
*/
@Test
public void transferInOfmanyAccountCall() throws Exception {
NulsSDKBootStrap.init(chainId, apiURL);
String feeAccount = "949d1u22cbffbrarjh182eig55721odj";
String feeAccountPri = "9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b";
String sender = "9jnerlff23u8ed01np9g6ysbhsh0dvcs";
String senderPri = "949d1u22cbffbrarjh182eig55721odj";
BigInteger value = new BigDecimal("6.6").movePointRight(8).toBigInteger();
String contractAddress = offlineContract;
String remark = "";
this.callTxOffline(feeAccount, feeAccountPri, sender, senderPri,
value,
contractAddress,
"_payable", "", remark, null, null, null, true);
}
/**
* 多账户调用合约 - 转入其他资产,如 2-2, 2-3
*/
@Test
public void transferInOfmanyAccountCallII() throws Exception {
NulsSDKBootStrap.init(chainId, apiURL);
String feeAccount = "949d1u22cbffbrarjh182eig55721odj";
String feeAccountPri = "9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b";
String sender = "9jnerlff23u8ed01np9g6ysbhsh0dvcs";
String senderPri = "949d1u22cbffbrarjh182eig55721odj";
BigInteger value = BigInteger.ZERO;
String contractAddress = offlineContract;
String remark = "";
ProgramMultyAssetValue[] multyAssetValues = new ProgramMultyAssetValue[]{
new ProgramMultyAssetValue(BigInteger.valueOf(2_0000_0000L), 5, 1),
new ProgramMultyAssetValue(BigInteger.valueOf(3_0000_0000L), 55, 1)
};
this.callTxOffline(feeAccount, feeAccountPri, sender, senderPri,
value,
contractAddress,
"_payableMultyAsset", "", remark, null, null, multyAssetValues, true);
}
/**
* 多账户调用合约 - 同时转入NULS资产和其他资产,如 2-1, 2-2, 2-3
*/
@Test
public void transferInOfmanyAccountCallIII() throws Exception {
NulsSDKBootStrap.init(chainId, apiURL);
String feeAccount = "949d1u22cbffbrarjh182eig55721odj";
String feeAccountPri = "9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b";
String sender = "9jnerlff23u8ed01np9g6ysbhsh0dvcs";
String senderPri = "949d1u22cbffbrarjh182eig55721odj";
BigInteger value = new BigDecimal("6.6").movePointRight(8).toBigInteger();
String contractAddress = offlineContract;
String remark = "";
ProgramMultyAssetValue[] multyAssetValues = new ProgramMultyAssetValue[]{
new ProgramMultyAssetValue(BigInteger.valueOf(2_0000_0000L), 5, 1),
new ProgramMultyAssetValue(BigInteger.valueOf(3_0000_0000L), 55, 1)
};
this.callTxOfflineII(feeAccount, feeAccountPri, sender, senderPri,
value,
contractAddress,
"receiveAllAssets", "", remark, null, null, multyAssetValues, true);
}
/**
* 多账户调用合约 - 转出
*/
@Test
public void transferOutOfmanyAccountCall() throws Exception {
NulsSDKBootStrap.init(chainId, apiURL);
//importPriKey("9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b", password);//25 949d1u22cbffbrarjh182eig55721odj
//importPriKey("949d1u22cbffbrarjh182eig55721odj", password);//26 9jnerlff23u8ed01np9g6ysbhsh0dvcs
String feeAccount = "949d1u22cbffbrarjh182eig55721odj";
String feeAccountPri = "9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b";
String sender = "9jnerlff23u8ed01np9g6ysbhsh0dvcs";
String senderPri = "949d1u22cbffbrarjh182eig55721odj";
BigInteger value = BigInteger.ZERO;
String contractAddress = offlineContract;
String methodName = "transferNuls";
String methodDesc = "";
String remark = "";
// 转出 0.1 NULS
Object[] args = new Object[]{"ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7", new BigDecimal("0.1").multiply(BigDecimal.TEN.pow(8)).toBigInteger()};
String[] argsType = new String[]{"Address", "BigInteger"};
this.callTxOffline(feeAccount, feeAccountPri, sender, senderPri, value, contractAddress, methodName, methodDesc, remark, args, argsType, null, true);
}
/**
* 多账户调用合约 - 转出其他资产
*/
@Test
public void transferOutOfmanyAccountOfOtherAssetCall() throws Exception {
NulsSDKBootStrap.init(chainId, apiURL);
//importPriKey("9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b", password);//25 949d1u22cbffbrarjh182eig55721odj
//importPriKey("949d1u22cbffbrarjh182eig55721odj", password);//26 9jnerlff23u8ed01np9g6ysbhsh0dvcs
String feeAccount = "949d1u22cbffbrarjh182eig55721odj";
String feeAccountPri = "9ce21dad67e0f0af2599b41b515a7f7018059418bab892a7b68f283d489abc4b";
String sender = "9jnerlff23u8ed01np9g6ysbhsh0dvcs";
String senderPri = "949d1u22cbffbrarjh182eig55721odj";
BigInteger value = BigInteger.ZERO;
String contractAddress = offlineContract;
String methodName = "transferDesignatedAsset";
String methodDesc = "";
String remark = "";
// 转出 0.1 NULS
Object[] args = new Object[]{"ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7", new BigDecimal("3").multiply(BigDecimal.TEN.pow(8)).toBigInteger(), 55, 1};
String[] argsType = new String[]{"Address", "BigInteger", "int", "int"};
this.callTxOffline(feeAccount, feeAccountPri, sender, senderPri, value, contractAddress, methodName, methodDesc, remark, args, argsType, null, true);
}
protected void callTxOffline(String feeAccount, String feeAccountPri,
String contractSender, String contractSenderPri,
BigInteger value, String contractAddress,
String methodName, String methodDesc,
String remark,
Object[] args, String[] argsType, ProgramMultyAssetValue[] multyAssetValues, boolean isBroadcastTx) throws Exception{
List<SignDto> txSingers = new ArrayList<>();
SignDto dto1 = new SignDto();
dto1.setAddress(contractSender);
dto1.setPriKey(contractSenderPri);
SignDto dto2 = new SignDto();
dto2.setAddress(feeAccount);
dto2.setPriKey(feeAccountPri);
txSingers.add(dto1);
txSingers.add(dto2);
//ContractBalance senderBalance = getUnConfirmedBalanceAndNonce(chainId, assetId, sender);
//byte[] senderBytes = AddressTool.getAddress(sender);
byte[] feeAccountBytes = AddressTool.getAddress(feeAccount);
byte[] contractAddressBytes = AddressTool.getAddress(contractAddress);
List<CoinFrom> froms = new ArrayList<>();
List<CoinTo> tos = new ArrayList<>();
if (value.compareTo(BigInteger.ZERO) > 0) {
String payAccount = feeAccount;
//String payAccount = contractSender;
ContractBalance payAccountBalance = getUnConfirmedBalanceAndNonce(chainId, assetId, payAccount);
CoinFrom coinFrom = new CoinFrom(AddressTool.getAddress(payAccount), chainId, assetId, value, RPCUtil.decode(payAccountBalance.getNonce()), (byte) 0);
froms.add(coinFrom);
CoinTo coinTo = new CoinTo(contractAddressBytes, chainId, assetId, value);
tos.add(coinTo);
}
if (multyAssetValues != null) {
for (ProgramMultyAssetValue multyAssetValue : multyAssetValues) {
int assetChainId = multyAssetValue.getAssetChainId();
int assetId = multyAssetValue.getAssetId();
BigInteger _value = multyAssetValue.getValue();
ContractBalance account = getUnConfirmedBalanceAndNonce(assetChainId, assetId, feeAccount);
CoinFrom coinFrom = new CoinFrom(feeAccountBytes, assetChainId, assetId, _value, RPCUtil.decode(account.getNonce()), (byte) 0);
froms.add(coinFrom);
CoinTo coinTo = new CoinTo(contractAddressBytes, assetChainId, assetId, _value);
tos.add(coinTo);
}
}
this.callTxOfflineBase(txSingers, froms, tos, feeAccount, contractSender, value, contractAddress, methodName, methodDesc, remark,
args, argsType, isBroadcastTx);
}
private ContractBalance getUnConfirmedBalanceAndNonce(int chainId, int assetId, String payAccount) {
Result accountBalance = NulsSDKTool.getAccountBalance(payAccount, chainId, assetId);
Map dataMap = (Map) accountBalance.getData();
ContractBalance contractBalance = ContractBalance.newInstance();
contractBalance.setBalance(new BigInteger(dataMap.get("available").toString()));
contractBalance.setFreeze(new BigInteger(dataMap.get("freeze").toString()));
contractBalance.setNonce(dataMap.get("nonce").toString());
return contractBalance;
}
/**
* 两个账户支出同一个资产
*/
protected void callTxOfflineII(String feeAccount, String feeAccountPri,
String contractSender, String contractSenderPri,
BigInteger value, String contractAddress,
String methodName, String methodDesc,
String remark,
Object[] args, String[] argsType, ProgramMultyAssetValue[] multyAssetValues, boolean isBroadcastTx) throws Exception{
List<SignDto> txSingers = new ArrayList<>();
SignDto dto1 = new SignDto();
dto1.setAddress(contractSender);
dto1.setPriKey(contractSenderPri);
SignDto dto2 = new SignDto();
dto2.setAddress(feeAccount);
dto2.setPriKey(feeAccountPri);
// importPriKey("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7", password);//27 ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7
SignDto dto3 = new SignDto();
dto3.setAddress("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7");
dto3.setPriKey("ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7");
txSingers.add(dto1);
txSingers.add(dto2);
txSingers.add(dto3);
//ContractBalance senderBalance = getUnConfirmedBalanceAndNonce(chainId, assetId, sender);
//byte[] senderBytes = AddressTool.getAddress(sender);
byte[] feeAccountBytes = AddressTool.getAddress(feeAccount);
byte[] contractAddressBytes = AddressTool.getAddress(contractAddress);
List<CoinFrom> froms = new ArrayList<>();
List<CoinTo> tos = new ArrayList<>();
if (value.compareTo(BigInteger.ZERO) > 0) {
String payAccount = feeAccount;
//String payAccount = contractSender;
ContractBalance payAccountBalance = getUnConfirmedBalanceAndNonce(chainId, assetId, payAccount);
CoinFrom coinFrom = new CoinFrom(AddressTool.getAddress(payAccount), chainId, assetId, value, RPCUtil.decode(payAccountBalance.getNonce()), (byte) 0);
froms.add(coinFrom);
CoinTo coinTo = new CoinTo(contractAddressBytes, chainId, assetId, value);
tos.add(coinTo);
}
if (multyAssetValues != null) {
String payAccount;
for (ProgramMultyAssetValue multyAssetValue : multyAssetValues) {
BigInteger _value = multyAssetValue.getValue();
BigInteger divide = _value.divide(BigInteger.valueOf(2));
int assetChainId = multyAssetValue.getAssetChainId();
int assetId = multyAssetValue.getAssetId();
payAccount = feeAccount;
ContractBalance account = getUnConfirmedBalanceAndNonce(assetChainId, assetId, payAccount);
CoinFrom coinFrom = new CoinFrom(AddressTool.getAddress(payAccount), assetChainId, assetId, _value.subtract(divide), RPCUtil.decode(account.getNonce()), (byte) 0);
froms.add(coinFrom);
payAccount = "ngw6fo1pu3tjgnp9jnlp7vnwvfqb9yn7";
account = getUnConfirmedBalanceAndNonce(assetChainId, assetId, payAccount);
coinFrom = new CoinFrom(AddressTool.getAddress(payAccount), assetChainId, assetId, divide, RPCUtil.decode(account.getNonce()), (byte) 0);
froms.add(coinFrom);
CoinTo coinTo = new CoinTo(contractAddressBytes, assetChainId, assetId, _value);
tos.add(coinTo);
}
}
this.callTxOfflineBase(txSingers, froms, tos, feeAccount, contractSender, value, contractAddress, methodName, methodDesc, remark,
args, argsType, isBroadcastTx);
}
protected void callTxOfflineBase(List<SignDto> txSingers, List<CoinFrom> froms, List<CoinTo> tos,
String feeAccount,
String contractSender,
BigInteger value, String contractAddress,
String methodName, String methodDesc,
String remark,
Object[] args, String[] argsType, boolean isBroadcastTx) throws Exception{
// 生成参数的二维数组
String[][] finalArgs = null;
if (args != null && args.length > 0) {
if(argsType == null || argsType.length != args.length) {
Assert.assertTrue("size of 'argsType' array not match 'args' array", false);
}
finalArgs = ContractUtil.twoDimensionalArray(args, argsType);
}
// 组装交易的txData
byte[] contractAddressBytes = AddressTool.getAddress(contractAddress);
byte[] senderBytes = AddressTool.getAddress(contractSender);
CallContractData callContractData = new CallContractData();
callContractData.setContractAddress(contractAddressBytes);
callContractData.setSender(senderBytes);
callContractData.setValue(value);
callContractData.setPrice(25);
callContractData.setGasLimit(gasLimit);
callContractData.setMethodName(methodName);
callContractData.setMethodDesc(methodDesc);
if (finalArgs != null) {
callContractData.setArgsCount((short) finalArgs.length);
callContractData.setArgs(finalArgs);
}
CallContractTransaction tx = new CallContractTransaction();
if (StringUtils.isNotBlank(remark)) {
tx.setRemark(remark.getBytes(StandardCharsets.UTF_8));
}
tx.setTime(System.currentTimeMillis() / 1000);
// 计算CoinData
CoinData coinData = new CoinData();
coinData.setFrom(froms);
coinData.setTo(tos);
long gasUsed = callContractData.getGasLimit();
BigInteger imputedValue = BigInteger.valueOf(LongUtils.mul(gasUsed, callContractData.getPrice()));
byte[] feeAccountBytes = AddressTool.getAddress(feeAccount);
BigInteger feeValue = imputedValue;
CoinFrom feeAccountFrom = null;
for (CoinFrom from : froms) {
int assetChainId = from.getAssetsChainId();
int assetId = from.getAssetsId();
if (Arrays.equals(from.getAddress(), feeAccountBytes) && assetChainId == this.chainId && assetId == this.assetId) {
from.setAmount(from.getAmount().add(feeValue));
feeAccountFrom = from;
break;
}
}
if (feeAccountFrom == null) {
ContractBalance feeAccountBalance = getUnConfirmedBalanceAndNonce(chainId, assetId, feeAccount);
feeAccountFrom = new CoinFrom(feeAccountBytes, chainId, assetId, feeValue, RPCUtil.decode(feeAccountBalance.getNonce()), (byte) 0);
coinData.addFrom(feeAccountFrom);
}
/*if (value.compareTo(BigInteger.ZERO) > 0) {
CoinFrom coinFrom = new CoinFrom(callContractData.getSender(), chainId, assetId, sendValue, RPCUtil.decode(senderBalance.getNonce()), (byte) 0);
coinData.addFrom(coinFrom);
CoinTo coinTo = new CoinTo(callContractData.getContractAddress(), chainId, assetId, value);
coinData.addTo(coinTo);
}*/
tx.setCoinData(coinData.serialize());
tx.setTxData(callContractData.serialize());
BigInteger txSizeFee = TransactionFeeCalculator.getNormalUnsignedTxFee(tx.getSize() + 130 * froms.size());
feeAccountFrom.setAmount(feeAccountFrom.getAmount().add(txSizeFee));
/*if (feeAccountBalance.getBalance().compareTo(feeValue) < 0) {
// Insufficient balance
throw new RuntimeException("Insufficient balance to pay fee");
}*/
tx.setCoinData(coinData.serialize());
// 签名
byte[] txBytes = tx.serialize();
String txHex = HexUtil.encode(txBytes);
Result<Map> signTxR = NulsSDKTool.sign(txSingers, txHex);
Assert.assertTrue(JSONUtils.obj2PrettyJson(signTxR), signTxR.isSuccess());
Map resultData = signTxR.getData();
String signedTxHex = (String) resultData.get("txHex");
System.out.println(String.format("signedTxHex: %s", signedTxHex));
// 在线接口 - 广播交易
if (!isBroadcastTx) {
return;
}
Result<Map> broadcaseTxR = NulsSDKTool.broadcast(signedTxHex);
Assert.assertTrue(JSONUtils.obj2PrettyJson(broadcaseTxR), broadcaseTxR.isSuccess());
Map data = broadcaseTxR.getData();
String hash = (String) data.get("hash");
System.out.println(String.format("hash: %s", hash));
}
}
|
92413af920b06cb788fbf35aecd6c2b9f8731680 | 2,362 | java | Java | library/src/androidTest/java/com/baasbox/android/test/SessionTests.java | baasbox/Android-SDK | 6bb2203246b885b2ad63a7bfaf37c83caf15e0d8 | [
"Apache-2.0"
] | 23 | 2015-01-02T19:39:36.000Z | 2017-07-12T11:33:49.000Z | library/src/androidTest/java/com/baasbox/android/test/SessionTests.java | michaelbukachi/Android-SDK | 6bb2203246b885b2ad63a7bfaf37c83caf15e0d8 | [
"Apache-2.0"
] | 21 | 2015-01-11T19:59:44.000Z | 2017-07-12T12:07:20.000Z | library/src/androidTest/java/com/baasbox/android/test/SessionTests.java | baasbox/Android-SDK | 6bb2203246b885b2ad63a7bfaf37c83caf15e0d8 | [
"Apache-2.0"
] | 23 | 2015-01-17T13:51:06.000Z | 2019-06-01T06:59:12.000Z | 31.493333 | 101 | 0.565199 | 1,001,821 | /*
* Copyright (C) 2014. BaasBox
*
* 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.baasbox.android.test;
import com.baasbox.android.*;
import com.baasbox.android.test.common.BaasTestBase;
import java.util.concurrent.TimeUnit;
/**
* Created by eto on 06/03/14.
*/
public class SessionTests extends BaasTestBase {
private static final boolean SKIP = true;
@Override
protected void beforeClass() throws Exception {
super.beforeClass();
resetDb();
}
public void testExpiration(){
if (!SKIP) {
BaasResult<BaasUser> user = BaasUser.withUserName("paolo")
.setPassword("paolo")
.signupSync();
if (user.isFailed()) {
fail("Unable to signup");
}
BaasUser.current().getScope(BaasUser.Scope.PRIVATE).put("KEY", true);
BaasResult<BaasUser> resup = BaasUser.current().saveSync();
if (resup.isFailed()) {
fail("Unable to modify self");
}
try {
TimeUnit.SECONDS.sleep(80);
} catch (InterruptedException e) {
}
BaasResult<BaasUser> resUs = BaasUser.current().refreshSync();
try {
resUs.get();
if (BaasBox.getDefault().config.sessionTokenExpires) {
fail();
} else {
assertTrue(true);
}
} catch (BaasInvalidSessionException e) {
if (BaasBox.getDefault().config.sessionTokenExpires) {
assertTrue(true);
} else {
fail("Should not refresh the token");
}
} catch (BaasException e) {
fail(e.getMessage());
}
}
}
}
|
92413b7980f1066ff0cc54af0f5111c75ba470b4 | 1,528 | java | Java | Chill Blog/chill-blog/src/main/java/portfolio/projects/chillblog/web/LoginController.java | jordanivanov147/PortfolioProjects | e20ba9806d457bb87e1f9f2f2d604ca55a1883eb | [
"MIT"
] | null | null | null | Chill Blog/chill-blog/src/main/java/portfolio/projects/chillblog/web/LoginController.java | jordanivanov147/PortfolioProjects | e20ba9806d457bb87e1f9f2f2d604ca55a1883eb | [
"MIT"
] | 3 | 2021-10-06T18:48:55.000Z | 2022-02-19T03:48:53.000Z | Chill Blog/chill-blog/src/main/java/portfolio/projects/chillblog/web/LoginController.java | jordanivanov147/PortfolioProjects | e20ba9806d457bb87e1f9f2f2d604ca55a1883eb | [
"MIT"
] | null | null | null | 38.2 | 111 | 0.780759 | 1,001,822 | package portfolio.projects.chillblog.web;
import portfolio.projects.chillblog.model.Credentials;
import portfolio.projects.chillblog.model.JwtResponse;
import portfolio.projects.chillblog.model.User;
import portfolio.projects.chillblog.service.UserService;
import portfolio.projects.chillblog.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/login")
@CrossOrigin("http://localhost:3000")
@Slf4j
public class LoginController {
@Autowired
private UserService userService;
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private JwtUtils jwtUtils;
@PostMapping
public ResponseEntity<JwtResponse> login(@RequestBody Credentials credentials) {
authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(credentials.getUsername(), credentials.getPassword()));
final User user = userService
.getUserByUsername(credentials.getUsername());
final String token = jwtUtils.generateToken(user);
log.info("Login successful for {}: {}", user.getUsername(), token);
return ResponseEntity.ok(new JwtResponse(token, user));
}
}
|
92413b7f1bcf7da87bc4c260fb6e04ea95bc3e75 | 1,191 | java | Java | modelservice/src/main/java/com/expedia/adaptivealerting/modelservice/service/DetectorService.java | haram-dev/adaptive-alerting | b3fc188e4ca80b1d9113f0cabe947d8debe5c9bd | [
"Apache-2.0"
] | null | null | null | modelservice/src/main/java/com/expedia/adaptivealerting/modelservice/service/DetectorService.java | haram-dev/adaptive-alerting | b3fc188e4ca80b1d9113f0cabe947d8debe5c9bd | [
"Apache-2.0"
] | null | null | null | modelservice/src/main/java/com/expedia/adaptivealerting/modelservice/service/DetectorService.java | haram-dev/adaptive-alerting | b3fc188e4ca80b1d9113f0cabe947d8debe5c9bd | [
"Apache-2.0"
] | null | null | null | 31.342105 | 75 | 0.767422 | 1,001,823 | /*
* Copyright 2018-2019 Expedia Group, Inc.
*
* 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.expedia.adaptivealerting.modelservice.service;
import com.expedia.adaptivealerting.anomdetect.source.DetectorDocument;
import java.util.List;
public interface DetectorService {
String createDetector(DetectorDocument document);
void deleteDetector(String uuid);
void updateDetector(String uuid, DetectorDocument document);
DetectorDocument findByUuid(String uuid);
List<DetectorDocument> findByCreatedBy(String user);
List<DetectorDocument> getLastUpdatedDetectors(long interval);
void toggleDetector(String uuid, Boolean enabled);
}
|
92413bd9cdb5dea9219e2b19df9fe3b0d221b1a3 | 2,830 | java | Java | sdk/dataprotection/azure-resourcemanager-dataprotection/src/main/java/com/azure/resourcemanager/dataprotection/models/PolicyInfo.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 1,350 | 2015-01-17T05:22:05.000Z | 2022-03-29T21:00:37.000Z | sdk/dataprotection/azure-resourcemanager-dataprotection/src/main/java/com/azure/resourcemanager/dataprotection/models/PolicyInfo.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 16,834 | 2015-01-07T02:19:09.000Z | 2022-03-31T23:29:10.000Z | sdk/dataprotection/azure-resourcemanager-dataprotection/src/main/java/com/azure/resourcemanager/dataprotection/models/PolicyInfo.java | liukun2634/azure-sdk-for-java | a42ba097eef284333c9befba180eea3cfed41312 | [
"MIT"
] | 1,586 | 2015-01-02T01:50:28.000Z | 2022-03-31T11:25:34.000Z | 28.3 | 108 | 0.657597 | 1,001,824 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.dataprotection.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** PolicyInfo Policy Info in backupInstance. */
@Fluent
public final class PolicyInfo {
@JsonIgnore private final ClientLogger logger = new ClientLogger(PolicyInfo.class);
/*
* The policyId property.
*/
@JsonProperty(value = "policyId", required = true)
private String policyId;
/*
* The policyVersion property.
*/
@JsonProperty(value = "policyVersion", access = JsonProperty.Access.WRITE_ONLY)
private String policyVersion;
/*
* Policy parameters for the backup instance
*/
@JsonProperty(value = "policyParameters")
private PolicyParameters policyParameters;
/**
* Get the policyId property: The policyId property.
*
* @return the policyId value.
*/
public String policyId() {
return this.policyId;
}
/**
* Set the policyId property: The policyId property.
*
* @param policyId the policyId value to set.
* @return the PolicyInfo object itself.
*/
public PolicyInfo withPolicyId(String policyId) {
this.policyId = policyId;
return this;
}
/**
* Get the policyVersion property: The policyVersion property.
*
* @return the policyVersion value.
*/
public String policyVersion() {
return this.policyVersion;
}
/**
* Get the policyParameters property: Policy parameters for the backup instance.
*
* @return the policyParameters value.
*/
public PolicyParameters policyParameters() {
return this.policyParameters;
}
/**
* Set the policyParameters property: Policy parameters for the backup instance.
*
* @param policyParameters the policyParameters value to set.
* @return the PolicyInfo object itself.
*/
public PolicyInfo withPolicyParameters(PolicyParameters policyParameters) {
this.policyParameters = policyParameters;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
if (policyId() == null) {
throw logger
.logExceptionAsError(
new IllegalArgumentException("Missing required property policyId in model PolicyInfo"));
}
if (policyParameters() != null) {
policyParameters().validate();
}
}
}
|
92413be0dc8db35753df019c35a03d85168d8bb2 | 2,669 | java | Java | src/main/java/com/conveyal/analysis/components/eventbus/Event.java | ipeaGIT/r5 | f71de5235a8ec773e91f3ddbec134bb5f5fecdb2 | [
"MIT"
] | 194 | 2015-10-26T00:17:08.000Z | 2022-03-28T04:28:21.000Z | src/main/java/com/conveyal/analysis/components/eventbus/Event.java | ipeaGIT/r5 | f71de5235a8ec773e91f3ddbec134bb5f5fecdb2 | [
"MIT"
] | 688 | 2015-10-26T17:24:45.000Z | 2022-03-29T01:34:09.000Z | src/main/java/com/conveyal/analysis/components/eventbus/Event.java | ipeaGIT/r5 | f71de5235a8ec773e91f3ddbec134bb5f5fecdb2 | [
"MIT"
] | 50 | 2015-12-10T08:41:56.000Z | 2022-03-11T17:12:35.000Z | 43.754098 | 118 | 0.716373 | 1,001,825 | package com.conveyal.analysis.components.eventbus;
import com.conveyal.analysis.UserPermissions;
import java.util.Date;
import java.util.Set;
/**
* This could extend BaseModel, but it's not a domain model class (describing transit or land use data or analysis).
* It's metadata about server operation and user activity. These are intended to be serialized into a database or log,
* so the field visibility and types of every subclass should take that into consideration.
*/
public abstract class Event {
/**
* The time at which this event happened. Note that this timestamp is distinct from (and more accurate than) the
* Mongo object ID creation time, as insertion into the database is deferred and Mongo ID timestamps have only
* one-second resolution. We could set the timestamp inside the synchronized block that adds the event to the
* FlightRecorder, in an effort to impose strict temporal ordering on threads coherent with the timestamp order.
* But the timestamp has only millisecond resolution so that might not be very effective.
*/
public Date timestamp = new Date();
public String user;
public String accessGroup;
public boolean success = true;
// Location fields for user city / lat / lon derived from IP address? Embed those in the UserPermissions?
// Could also include lat / lon for affected entities, to allow easy map visualization.
/**
* Set the user and groups from the supplied userPermissions object (if any) and return the modified instance.
* These fluent setter methods return this abstract supertype instead of the specific subtype, which can be a
* little awkward. But the alternative of declaring Event <S extends Event> and casting is more ugly.
* @param userPermissions if this is null, the call will have no effect.
*/
public Event forUser (UserPermissions userPermissions) {
if (userPermissions != null) {
this.user = userPermissions.email;
this.accessGroup = userPermissions.accessGroup;
}
return this;
}
public Event forUser (String user, String accessGroup) {
this.user = user;
this.accessGroup = accessGroup;
return this;
}
/**
* Serialize the specific subtype of event to facilitate filtering.
* Not using JsonSubtypes annotations because we do not currently anticipate deserializing these objects.
* Though I suppose it could be interesting to analyze historical events in Java code.
*/
public String getType () {
// Will resolve to specific subclass
return this.getClass().getSimpleName();
}
}
|
92413d6e2c35352949a91f32f36f501137a483b3 | 1,529 | java | Java | Mage.Sets/src/mage/cards/p/PackMastiff.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,444 | 2015-01-02T00:25:38.000Z | 2022-03-31T13:57:18.000Z | Mage.Sets/src/mage/cards/p/PackMastiff.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 6,180 | 2015-01-02T19:10:09.000Z | 2022-03-31T21:10:44.000Z | Mage.Sets/src/mage/cards/p/PackMastiff.java | dsenginr/mage | 94e9aeedc20dcb74264e58fd198f46215828ef5c | [
"MIT"
] | 1,001 | 2015-01-01T01:15:20.000Z | 2022-03-30T20:23:04.000Z | 30.58 | 127 | 0.712884 | 1,001,826 | package mage.cards.p;
import mage.MageInt;
import mage.abilities.common.SimpleActivatedAbility;
import mage.abilities.costs.mana.ManaCostsImpl;
import mage.abilities.effects.common.continuous.BoostControlledEffect;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.CardType;
import mage.constants.Duration;
import mage.constants.SubType;
import mage.filter.common.FilterCreaturePermanent;
import mage.filter.predicate.mageobject.NamePredicate;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class PackMastiff extends CardImpl {
private static final FilterCreaturePermanent filter = new FilterCreaturePermanent();
static {
filter.add(new NamePredicate("Pack Mastiff"));
}
public PackMastiff(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.CREATURE}, "{1}{R}");
this.subtype.add(SubType.DOG);
this.power = new MageInt(2);
this.toughness = new MageInt(2);
// {1}{R}: Each creature you control named Pack Mastiff gets +1/+0 until end of turn.
this.addAbility(new SimpleActivatedAbility(new BoostControlledEffect(
1, 0, Duration.EndOfTurn, filter
).setText("Each creature you control named Pack Mastiff gets +1/+0 until end of turn."), new ManaCostsImpl("{1}{R}")));
}
private PackMastiff(final PackMastiff card) {
super(card);
}
@Override
public PackMastiff copy() {
return new PackMastiff(this);
}
}
|
92413e7029f98c74e6e705cd1c1e002f5be6de94 | 1,218 | java | Java | gs-spring-cloud/gs-microservices/gs-bus-custom-events/src/main/java/com/tirthal/learning/bus/event/PrintDateTimeListener.java | akondasif/Learning-Spring | e13914a65a6fe623e88ec4a8394e6dccfe1c7c37 | [
"MIT"
] | 1 | 2018-05-28T02:42:55.000Z | 2018-05-28T02:42:55.000Z | gs-spring-cloud/gs-microservices/gs-bus-custom-events/src/main/java/com/tirthal/learning/bus/event/PrintDateTimeListener.java | akondasif/Learning-Spring | e13914a65a6fe623e88ec4a8394e6dccfe1c7c37 | [
"MIT"
] | 3 | 2021-01-21T01:06:19.000Z | 2022-01-21T23:19:30.000Z | gs-spring-cloud/gs-microservices/gs-bus-custom-events/src/main/java/com/tirthal/learning/bus/event/PrintDateTimeListener.java | akondasif/Learning-Spring | e13914a65a6fe623e88ec4a8394e6dccfe1c7c37 | [
"MIT"
] | 6 | 2017-12-14T08:05:29.000Z | 2021-03-23T05:44:58.000Z | 35.823529 | 112 | 0.758621 | 1,001,827 | package com.tirthal.learning.bus.event;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationListener;
/**
* @author tirthalp
*/
public class PrintDateTimeListener implements ApplicationListener<PrintDateTimeRemoteApplicationEvent> {
private static Log log = LogFactory.getLog(PrintDateTimeListener.class);
@Override
public void onApplicationEvent(PrintDateTimeRemoteApplicationEvent event) {
final String whatToPrint = event.getWhatToPrint().trim().toLowerCase();
// Custom logic to do something, when this event occurs
if (whatToPrint.equals("time"))
log.info("*** Received remote print request. Current time is: " + LocalTime.now());
else if (whatToPrint.equals("date"))
log.info("*** Received remote print request. Current date is: " + LocalDate.now());
else if (whatToPrint.equals("datetime"))
log.info("*** Received remote print request. Current date and time is: " + LocalDateTime.now());
else
log.info("*** Received remote print request. However '"+whatToPrint+"' is unsupported input for parameter.");
}
}
|
924141418a491646456c5b3109cc45d473ce1a7f | 593 | java | Java | AWS-VIRTUAL/src/main/java/org/edu/eci/aws/URLReader.java | andresflorezp/CONCURRENT-SERVER | 5a718e8b3ca148be33a5678ea30fffce798275f1 | [
"MIT"
] | null | null | null | AWS-VIRTUAL/src/main/java/org/edu/eci/aws/URLReader.java | andresflorezp/CONCURRENT-SERVER | 5a718e8b3ca148be33a5678ea30fffce798275f1 | [
"MIT"
] | null | null | null | AWS-VIRTUAL/src/main/java/org/edu/eci/aws/URLReader.java | andresflorezp/CONCURRENT-SERVER | 5a718e8b3ca148be33a5678ea30fffce798275f1 | [
"MIT"
] | null | null | null | 31.210526 | 63 | 0.544688 | 1,001,828 | package org.edu.eci.aws;
import java.io.*;
import java.net.*;
import java.util.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL(args[0]);
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()))) {
String inputLine = null;
while ((inputLine = reader.readLine()) != null) {
System.out.println(inputLine);
}
} catch (IOException x) {
System.err.println(x);
}
}
} |
92414150ecf6359855df6d9504ecb78e698a97da | 3,983 | java | Java | ICC/HighPriority-ActivityHijack-Lean/Testing/benign_app/src/androidTest/java/edu/ksu/cs/benign/Tests.java | vaginessa/android-app-vulnerability-benchmarks | 6289f39d394afe83f5e591dcfb01e913f7307a90 | [
"BSD-3-Clause"
] | 2 | 2019-02-08T21:32:25.000Z | 2020-06-29T06:59:22.000Z | ICC/HighPriority-ActivityHijack-Lean/Testing/benign_app/src/androidTest/java/edu/ksu/cs/benign/Tests.java | vaginessa/android-app-vulnerability-benchmarks | 6289f39d394afe83f5e591dcfb01e913f7307a90 | [
"BSD-3-Clause"
] | null | null | null | ICC/HighPriority-ActivityHijack-Lean/Testing/benign_app/src/androidTest/java/edu/ksu/cs/benign/Tests.java | vaginessa/android-app-vulnerability-benchmarks | 6289f39d394afe83f5e591dcfb01e913f7307a90 | [
"BSD-3-Clause"
] | null | null | null | 40.642857 | 116 | 0.705247 | 1,001,829 | package edu.ksu.cs.benign;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.LargeTest;
import android.support.test.filters.SdkSuppress;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.By;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@RunWith(AndroidJUnit4.class)
@LargeTest
@SdkSuppress(minSdkVersion = 22, maxSdkVersion = 27)
public class Tests {
private static final int LAUNCH_TIMEOUT = 5000;
private static final String MALICIOUS_APP_PACKAGE = "edu.ksu.cs.malicious";
private static final String BENIGN_APP_PACKAGE = "edu.ksu.cs.benign";
private UiDevice mDevice;
private void setupDevice() {
// Initialize UiDevice instance
mDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
}
private void startApp(final String appPackageName) {
// Start from the home screen
mDevice.pressHome();
// Wait for launcher
final String launcherPackage = mDevice.getLauncherPackageName();
assertThat(launcherPackage, notNullValue());
mDevice.wait(Until.hasObject(By.pkg(launcherPackage).depth(0)),
LAUNCH_TIMEOUT);
// Launch the app
Context context = InstrumentationRegistry.getContext();
final Intent intent = context.getPackageManager()
.getLaunchIntentForPackage(appPackageName);
// Clear out any previous instances
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
// Wait for the app to appear
mDevice.wait(Until.hasObject(By.pkg(appPackageName).depth(0)),
LAUNCH_TIMEOUT);
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
}
@Test
public void testPresenceOfVulnerability() throws UiObjectNotFoundException {
setupDevice();
startApp(BENIGN_APP_PACKAGE);
UiObject takePic_btn = mDevice.findObject(new UiSelector().resourceId(BENIGN_APP_PACKAGE + ":id/takePic"));
assertThat(takePic_btn, notNullValue());
UiObject result_tv = mDevice.findObject(new UiSelector().resourceId(BENIGN_APP_PACKAGE + ":id/result"));
assertThat(result_tv, notNullValue());
takePic_btn.click();
UiObject done_btn = mDevice.findObject(new UiSelector().resourceId(BENIGN_APP_PACKAGE + ":id/done_btn"));
assertThat(done_btn, notNullValue());
done_btn.click();
assertEquals("image", result_tv.getText());
result_tv.click();
UiObject activity = mDevice.findObject(new UiSelector().text("Malicious"));
assertThat(activity, notNullValue());
activity.click();
if(Build.VERSION.SDK_INT < 26){
UiObject justOnce = mDevice.findObject(new UiSelector().textMatches("(?i)just once(?-i)"));
assertThat(justOnce, notNullValue());
justOnce.click();
}
InstrumentationRegistry.getInstrumentation().waitForIdleSync();
if (Build.VERSION.SDK_INT > 21) {
UiObject dispText = mDevice.findObject(new UiSelector().resourceId(MALICIOUS_APP_PACKAGE + ":id/disp"));
assertThat(dispText, notNullValue());
assertEquals("image", dispText.getText());
} else {
UiObject dispText = mDevice.findObject(new UiSelector().text("Malicious"));
assertEquals("Malicious", dispText.getText().trim());
}
}
}
|
924141f6adea78426e3dd580bb30390031cb2da8 | 398 | java | Java | src/com/mlpinit/set/models/Color.java | mlpinit/GameOfSet | 8e39ae82fdf18068bddc7ab59d114626df6e8182 | [
"MIT"
] | 7 | 2017-04-04T08:36:28.000Z | 2021-12-25T17:09:34.000Z | src/com/mlpinit/set/models/Color.java | mlpinit/GameOfSet | 8e39ae82fdf18068bddc7ab59d114626df6e8182 | [
"MIT"
] | null | null | null | src/com/mlpinit/set/models/Color.java | mlpinit/GameOfSet | 8e39ae82fdf18068bddc7ab59d114626df6e8182 | [
"MIT"
] | null | null | null | 16.583333 | 35 | 0.487437 | 1,001,830 | package com.mlpinit.set;
public enum Color {
Red (0),
Green (1),
Mauve (2);
private int value;
private Color(int v) {
this.value = v;
}
public int getValue() {
return this.value;
}
public String initial() {
if (value == 0) return "R";
if (value == 1) return "G";
if (value == 2) return "M";
return "";
}
}
|
9241423a3ab0933f724403feea3bada70563ee4f | 5,163 | java | Java | xchange-stream-cryptofacilities/src/main/java/info/bitrich/xchangestream/cryptofacilities/CryptoFacilitiesStreamingExchange.java | MahiFX/XChange | 602ae74c85a56302ce503c2a0a86b0f835f40e6d | [
"MIT"
] | null | null | null | xchange-stream-cryptofacilities/src/main/java/info/bitrich/xchangestream/cryptofacilities/CryptoFacilitiesStreamingExchange.java | MahiFX/XChange | 602ae74c85a56302ce503c2a0a86b0f835f40e6d | [
"MIT"
] | null | null | null | xchange-stream-cryptofacilities/src/main/java/info/bitrich/xchangestream/cryptofacilities/CryptoFacilitiesStreamingExchange.java | MahiFX/XChange | 602ae74c85a56302ce503c2a0a86b0f835f40e6d | [
"MIT"
] | null | null | null | 37.963235 | 135 | 0.730583 | 1,001,831 | package info.bitrich.xchangestream.cryptofacilities;
import com.google.common.base.MoreObjects;
import info.bitrich.xchangestream.core.ProductSubscription;
import info.bitrich.xchangestream.core.StreamingExchange;
import info.bitrich.xchangestream.core.StreamingMarketDataService;
import info.bitrich.xchangestream.core.StreamingTradeService;
import info.bitrich.xchangestream.service.netty.ConnectionStateModel.State;
import io.reactivex.Completable;
import io.reactivex.Observable;
import org.apache.commons.lang3.StringUtils;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.cryptofacilities.CryptoFacilitiesExchange;
/**
* @author makarid
*/
public class CryptoFacilitiesStreamingExchange extends CryptoFacilitiesExchange implements StreamingExchange {
private static final String USE_BETA = "Use_Beta";
private static final String KRAKEN_API_URI = "wss://futures.kraken.com/ws/v1";
private static final String KRAKEN_API_BETA_URI = "wss://demo-futures.kraken.com/ws/v1";
private static final String CF_API_URI = "wss://www.cryptofacilities.com/ws/v1";
private static final String CF_API_BETA_URI = "wss://conformance.cryptofacilities.com/ws/v1";
private CryptoFacilitiesStreamingService streamingService, privateStreamingService;
private CryptoFacilitiesStreamingMarketDataService streamingMarketDataService;
private CryptoFacilitiesStreamingTradeService streamingTradeService;
public CryptoFacilitiesStreamingExchange() {
}
public static String pickUri(ExchangeSpecification exchangeSpecification, boolean useBeta) {
if (exchangeSpecification.getSslUri().contains("futures.kraken.com")) {
return useBeta ? KRAKEN_API_BETA_URI : KRAKEN_API_URI;
} else if (exchangeSpecification.getSslUri().contains("cryptofacilities.com")) {
return useBeta ? CF_API_BETA_URI : CF_API_URI;
} else {
throw new IllegalArgumentException("Unsupported URL " + exchangeSpecification.getSslUri());
}
}
@Override
protected void initServices() {
super.initServices();
Boolean useBeta =
MoreObjects.firstNonNull(
(Boolean) exchangeSpecification.getExchangeSpecificParametersItem(USE_BETA),
Boolean.FALSE);
String uri = pickUri(exchangeSpecification, useBeta);
this.streamingService =
new CryptoFacilitiesStreamingService(uri);
this.streamingMarketDataService = new CryptoFacilitiesStreamingMarketDataService(streamingService);
if (StringUtils.isNotEmpty(exchangeSpecification.getApiKey())) {
this.privateStreamingService =
new CryptoFacilitiesStreamingService(uri, exchangeSpecification.getApiKey(), exchangeSpecification.getSecretKey());
streamingTradeService = new CryptoFacilitiesStreamingTradeService(privateStreamingService);
}
}
@Override
public Completable connect(ProductSubscription... args) {
if (privateStreamingService != null)
return privateStreamingService.connect().mergeWith(streamingService.connect());
return streamingService.connect();
}
@Override
public Completable disconnect() {
if (privateStreamingService != null)
return privateStreamingService.disconnect().mergeWith(streamingService.disconnect());
return streamingService.disconnect();
}
@Override
public boolean isAlive() {
return streamingService.isSocketOpen()
&& (privateStreamingService == null || privateStreamingService.isSocketOpen());
}
@Override
public Observable<Object> connectionSuccess() {
return streamingService.subscribeConnectionSuccess();
}
@Override
public Observable<Throwable> reconnectFailure() {
return streamingService.subscribeReconnectFailure();
}
@Override
public Observable<State> connectionStateObservable() {
return streamingService.subscribeConnectionState();
}
@Override
public ExchangeSpecification getDefaultExchangeSpecification() {
ExchangeSpecification spec = super.getDefaultExchangeSpecification();
spec.setSslUri("https://futures.kraken.com/derivatives");
spec.setHost("futures.kraken.com/derivatives");
spec.setExchangeName("Kraken Futures");
spec.setShouldLoadRemoteMetaData(false);
return spec;
}
@Override
public StreamingMarketDataService getStreamingMarketDataService() {
return streamingMarketDataService;
}
@Override
public StreamingTradeService getStreamingTradeService() {
return streamingTradeService;
}
@Override
public void useCompressedMessages(boolean compressedMessages) {
streamingService.useCompressedMessages(compressedMessages);
}
@Override
public void resubscribeChannels() {
logger.debug("Resubscribing channels");
streamingService.resubscribeChannels();
if (privateStreamingService != null)
privateStreamingService.resubscribeChannels();
}
}
|
924142f3a0af46ee185db61ab1080beb40f0be09 | 498 | java | Java | java/src/test/java/com/yourtion/leetcode/easy/c0933/RecentCounterTest.java | yourtion/LeetCode | 61ee9fb1f97274e1621f8415dcdd8c7e424d20b3 | [
"MIT"
] | null | null | null | java/src/test/java/com/yourtion/leetcode/easy/c0933/RecentCounterTest.java | yourtion/LeetCode | 61ee9fb1f97274e1621f8415dcdd8c7e424d20b3 | [
"MIT"
] | null | null | null | java/src/test/java/com/yourtion/leetcode/easy/c0933/RecentCounterTest.java | yourtion/LeetCode | 61ee9fb1f97274e1621f8415dcdd8c7e424d20b3 | [
"MIT"
] | null | null | null | 27.666667 | 51 | 0.684739 | 1,001,832 | package com.yourtion.leetcode.easy.c0933;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
class RecentCounterTest {
@Test
void testRecentCounter() {
System.out.println("testRecentCounter");
RecentCounter obj = new RecentCounter();
Assertions.assertEquals(1, obj.ping(1));
Assertions.assertEquals(2, obj.ping(100));
Assertions.assertEquals(3, obj.ping(3001));
Assertions.assertEquals(3, obj.ping(3002));
}
} |
924143a7fa43cee44f897e61f5d590835e85fb3a | 1,855 | java | Java | src/main/java/org/lrospocher/commissioncalculator/service/TransactionService.java | spoonman01/commission-calculator | ca036ba0e2103b06457382457f94f29e2db2fe24 | [
"MIT"
] | null | null | null | src/main/java/org/lrospocher/commissioncalculator/service/TransactionService.java | spoonman01/commission-calculator | ca036ba0e2103b06457382457f94f29e2db2fe24 | [
"MIT"
] | null | null | null | src/main/java/org/lrospocher/commissioncalculator/service/TransactionService.java | spoonman01/commission-calculator | ca036ba0e2103b06457382457f94f29e2db2fe24 | [
"MIT"
] | null | null | null | 37.857143 | 121 | 0.760108 | 1,001,833 | package org.lrospocher.commissioncalculator.service;
import org.lrospocher.commissioncalculator.model.Transaction;
import org.lrospocher.commissioncalculator.repository.TransactionRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.util.List;
@Service
public class TransactionService {
private static final Logger LOG = LoggerFactory.getLogger(TransactionService.class);
public static final String EUR_CURRENCY = "EUR";
private final CommissionRulesService commissionRulesService;
private final TransactionRepository transactionRepository;
@Autowired
public TransactionService(CommissionRulesService commissionRulesService,
TransactionRepository transactionRepository) {
this.commissionRulesService = commissionRulesService;
this.transactionRepository = transactionRepository;
}
/**
* Gets the commission on a transaction and saves it.
* @param transaction without commission
* @return the transaction with commission specified
*/
public Transaction handleTransaction(Transaction transaction) {
// GET last month saved transactions for client
final List<Transaction> lastClientTransaction =
transactionRepository.findByClientIdWithDateAfter(transaction.getClientId(), LocalDate.now().minusMonths(1));
// Call rule-engine to get commission
transaction = commissionRulesService.setCommission(transaction, lastClientTransaction);
LOG.info("Transaction with commission {}", transaction.toString());
// Save finalized transaction on DB
transactionRepository.save(transaction);
return transaction;
}
}
|
9241443b93bd48f76c3de5f41ae521133ad33df9 | 2,038 | java | Java | src/main/java/com/lym/springboot/web/config/converter/StringToDateUtil.java | liuyanmin/spring-boot-web | ef62b33ff0228926b1c5fd9746159781fbd28bd8 | [
"Apache-2.0"
] | 2 | 2019-11-21T09:33:46.000Z | 2020-08-09T02:48:58.000Z | src/main/java/com/lym/springboot/web/config/converter/StringToDateUtil.java | liuyanmin/spring-boot-web | ef62b33ff0228926b1c5fd9746159781fbd28bd8 | [
"Apache-2.0"
] | 2 | 2021-12-10T01:26:02.000Z | 2021-12-14T21:35:59.000Z | src/main/java/com/lym/springboot/web/config/converter/StringToDateUtil.java | liuyanmin/spring-boot-web | ef62b33ff0228926b1c5fd9746159781fbd28bd8 | [
"Apache-2.0"
] | 1 | 2019-11-21T09:34:05.000Z | 2019-11-21T09:34:05.000Z | 24.261905 | 67 | 0.540726 | 1,001,834 | package com.lym.springboot.web.config.converter;
import org.apache.commons.lang3.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期转换器,将请求参数的日期字符串转换成java.util.Date类型
* 日期格式顺序:
* 1.yyyy-MM-dd HH:mm:ss:S
* 2.yyyy-MM-dd HH:mm:ss
* 3.yyyy-MM-dd HH:mm
* 4.yyyy-MM-dd HH
* 5.yyyy-MM-dd
*
* Created by liuyanmin on 2019/10/9.
*/
public class StringToDateUtil {
/**
* 日期格式化数组
*/
private static DateFormat[] dateFormats = {
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:S"),
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),
new SimpleDateFormat("yyyy-MM-dd HH:mm"),
new SimpleDateFormat("yyyy-MM-dd HH"),
new SimpleDateFormat("yyyy-MM-dd"),
new SimpleDateFormat("yyyy-MM")
};
/**
* <code>
* <pre>
* 1.如果日期字符串为空,则直接返回空
* 2.使用格式化组进行格式化,如果解析成功,则直接返回
* 4.否则,抛出非法参数异常
* @param source 请求的日期参数
* @return 解析后的日期类型:java.util.Date
* @exception IllegalArgumentException 非法参数异常
* </pre>
* </code>
*/
public static Date convert(String source) {
if (StringUtils.isBlank(source)) {
return null;
}
source = source.trim();
try {
int timeLength = source.length();
Long time = Long.parseLong(source);
if (timeLength == 10) {
time = time * 1000;
}
Date date = new Date(time);
return date;
} catch (Exception e) {
}
Date date = null;
boolean flag = false;
for (DateFormat dateFormat : dateFormats) {
try {
date = dateFormat.parse(source);
flag = true;
break;
} catch (ParseException e) {
}
}
if (flag) {
return date;
} else {
throw new IllegalArgumentException("不能解析日期:" + source);
}
}
}
|
92414503ec9fd1b801d0e7ff55cc2a809d3622ba | 458 | java | Java | gulimall-order/src/main/java/com/atguigu/gulimall/order/service/PaymentInfoService.java | HelingCode/Hmall | 9b9341ce5098ed0cae88e49310bf1bda8d865177 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/atguigu/gulimall/order/service/PaymentInfoService.java | HelingCode/Hmall | 9b9341ce5098ed0cae88e49310bf1bda8d865177 | [
"Apache-2.0"
] | null | null | null | gulimall-order/src/main/java/com/atguigu/gulimall/order/service/PaymentInfoService.java | HelingCode/Hmall | 9b9341ce5098ed0cae88e49310bf1bda8d865177 | [
"Apache-2.0"
] | null | null | null | 21.761905 | 73 | 0.770241 | 1,001,835 | package com.atguigu.gulimall.order.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import java.util.Map;
/**
* 支付信息表
*
* @author heling
* @email efpyi@example.com
* @date 2021-10-21 10:46:34
*/
public interface PaymentInfoService extends IService<PaymentInfoEntity> {
PageUtils queryPage(Map<String, Object> params);
}
|
924145a7d12ab7bb043e0799542b356ffba150ce | 924 | java | Java | xyz/icexmoon/java_notes/ch4/cast/Pointer.java | icexmoon/java-notebook | a9f20eee069c8d3e8cfc145f7c6ddb4d1192568b | [
"Apache-2.0"
] | null | null | null | xyz/icexmoon/java_notes/ch4/cast/Pointer.java | icexmoon/java-notebook | a9f20eee069c8d3e8cfc145f7c6ddb4d1192568b | [
"Apache-2.0"
] | null | null | null | xyz/icexmoon/java_notes/ch4/cast/Pointer.java | icexmoon/java-notebook | a9f20eee069c8d3e8cfc145f7c6ddb4d1192568b | [
"Apache-2.0"
] | null | null | null | 18.857143 | 61 | 0.487013 | 1,001,836 | package ch4.cast;
import util.Fmt;
public class Pointer extends Shape {
private int x;
private int y;
private int refCounter;
public Pointer(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void addReference() {
this.refCounter++;
}
public void display() {
Fmt.printf("Pointer(%s) is displayed.\n", this);
}
@Override
public String toString() {
return Fmt.sprintf("Pointer(%d,%d)", this.x, this.y);
}
public void destory() {
if (this.refCounter > 0) {
this.refCounter--;
if (this.refCounter == 0) {
String thisStr = this.toString();
this.x = 0;
this.y = 0;
Fmt.printf("%s is destroy.\n", thisStr);
}
}
}
}
|
924147cf3d2625610bff1bd21e1514ec3fe80553 | 1,244 | java | Java | src/edu/virginia/vcgr/genii/container/invoker/DebugInvoker.java | genesis-2/trunk | 9a6b34e8531ef0a1614ee48802b037df6e4fa2d7 | [
"Apache-2.0"
] | 1 | 2022-03-16T16:36:00.000Z | 2022-03-16T16:36:00.000Z | src/edu/virginia/vcgr/genii/container/invoker/DebugInvoker.java | genesis-2/trunk | 9a6b34e8531ef0a1614ee48802b037df6e4fa2d7 | [
"Apache-2.0"
] | 1 | 2021-06-04T02:05:42.000Z | 2021-06-04T02:05:42.000Z | src/edu/virginia/vcgr/genii/container/invoker/DebugInvoker.java | genesis-2/trunk | 9a6b34e8531ef0a1614ee48802b037df6e4fa2d7 | [
"Apache-2.0"
] | null | null | null | 31.1 | 129 | 0.71463 | 1,001,837 | package edu.virginia.vcgr.genii.container.invoker;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import edu.virginia.vcgr.genii.container.naming.NamingUtils;
public class DebugInvoker implements IAroundInvoker
{
static private Log _logger = LogFactory.getLog(DebugInvoker.class);
public Object invoke(InvocationContext invocationContext) throws Exception
{
String description =
"method " + invocationContext.getMethod().getName() + " on class " + invocationContext.getTarget().getClass().getName() + ".";
if (_logger.isTraceEnabled())
_logger.trace(
"Calling " + description + " from a " + (NamingUtils.isWSNamingAwareClient() ? "" : "non-") + "WS-Naming aware client.");
long start = System.currentTimeMillis();
try {
Object obj = invocationContext.proceed();
long stop = System.currentTimeMillis();
if (_logger.isDebugEnabled())
_logger.debug(String.format("Successfully called %s in %d ms.", description, (stop - start)));
return obj;
} catch (Exception e) {
long stop = System.currentTimeMillis();
if (_logger.isDebugEnabled())
_logger.debug(String.format("Failed to call %s in %d ms.", description, (stop - start)), e);
throw e;
}
}
} |
924147ed362cd11c66d1c392bd886ac75437457c | 1,805 | java | Java | src/com/adapter/MenuAdapter.java | zongyl/manniu | 886c13a10cfc86477cdadf0b66e9b57030d9cece | [
"Apache-2.0"
] | null | null | null | src/com/adapter/MenuAdapter.java | zongyl/manniu | 886c13a10cfc86477cdadf0b66e9b57030d9cece | [
"Apache-2.0"
] | null | null | null | src/com/adapter/MenuAdapter.java | zongyl/manniu | 886c13a10cfc86477cdadf0b66e9b57030d9cece | [
"Apache-2.0"
] | null | null | null | 27.348485 | 106 | 0.754571 | 1,001,838 | package com.adapter;
import java.util.List;
import android.content.Context;
import android.content.pm.PackageManager.NameNotFoundException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.manniu.manniu.R;
public class MenuAdapter extends BaseAdapter{
private Context context;
private List<Menu> items;
LayoutInflater inflater;
private boolean showV;
public MenuAdapter(Context _context, List<Menu> _items,boolean showV){
this.context = _context;
this.items = _items;
this.showV = showV;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = inflater.inflate(R.layout.new_more_item, null);
ImageView iv = (ImageView)rowView.findViewById(R.id.menu_img);
TextView tv = (TextView)rowView.findViewById(R.id.menu_txt);
TextView bor = (TextView) rowView.findViewById(R.id.divider);
TextView desc =(TextView) rowView.findViewById(R.id.menu_desc);
if(position == items.size()-1){
bor.setVisibility(View.INVISIBLE);
}
if(showV && position==1){
try {
desc.setText("V"+context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
iv.setBackgroundResource(items.get(position).getIconResid());
tv.setText(items.get(position).getText());
return rowView;
}
}
|
924148493553c6027fa1477f40715faead67969b | 1,136 | java | Java | herddb-core/src/main/java/herddb/model/planner/TableScanOp.java | lorenzobalzani/herddb | e434d7ae1abceaa6c3443074ace122b709f5e481 | [
"Apache-2.0"
] | 261 | 2016-05-17T10:06:14.000Z | 2022-03-21T04:45:18.000Z | herddb-core/src/main/java/herddb/model/planner/TableScanOp.java | lorenzobalzani/herddb | e434d7ae1abceaa6c3443074ace122b709f5e481 | [
"Apache-2.0"
] | 588 | 2016-04-13T12:46:29.000Z | 2022-03-22T11:31:58.000Z | herddb-core/src/main/java/herddb/model/planner/TableScanOp.java | lorenzobalzani/herddb | e434d7ae1abceaa6c3443074ace122b709f5e481 | [
"Apache-2.0"
] | 53 | 2016-03-31T15:08:30.000Z | 2022-02-24T06:40:16.000Z | 27.047619 | 65 | 0.738556 | 1,001,839 | /*
Licensed to Diennea S.r.l. under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. Diennea S.r.l. licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package herddb.model.planner;
import herddb.model.commands.ScanStatement;
/**
* Full table scan
*
* @author eolivelli
*/
public class TableScanOp extends SimpleScanOp {
public TableScanOp(ScanStatement statement) {
super(statement);
}
@Override
public String toString() {
return "TableScanOp{" + "statement=" + statement + '}';
}
}
|
924148c2f8d9b233feab290fd8a8dce81bc655e4 | 2,568 | java | Java | tensquare-recruit/src/main/java/com/tensquare/recruit/controller/EnterpriseController.java | EmmanuelHan/tenSquare | 7106563feb0ebcab5c9e14befbc64d85021d49c5 | [
"Apache-2.0"
] | null | null | null | tensquare-recruit/src/main/java/com/tensquare/recruit/controller/EnterpriseController.java | EmmanuelHan/tenSquare | 7106563feb0ebcab5c9e14befbc64d85021d49c5 | [
"Apache-2.0"
] | null | null | null | tensquare-recruit/src/main/java/com/tensquare/recruit/controller/EnterpriseController.java | EmmanuelHan/tenSquare | 7106563feb0ebcab5c9e14befbc64d85021d49c5 | [
"Apache-2.0"
] | null | null | null | 25.176471 | 83 | 0.658879 | 1,001,840 | package com.tensquare.recruit.controller;
import com.tensquare.recruit.entity.Enterprise;
import com.tensquare.recruit.service.IEnterpriseService;
import com.tensquare.common.entity.Result;
import com.tensquare.common.entity.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
/**
* @Author HanLei
* @Date 2020-03-12
*/
@Slf4j
@Controller
@RequestMapping("/mapper.recruit/enterprise")
public class EnterpriseController {
@Resource
private IEnterpriseService enterpriseServiceImpl;
/**
* list跳转
* @return
*/
@RequestMapping("/mainIndex")
public String mainIndex(){
return "enterprise/enterprise_list";
}
/**
* addOrUpdate 页面跳转
* @param mv
* @param enterprise
* @return
*/
@RequestMapping("/addOrUpdateIndex")
public ModelAndView addOrUpdateIndex(ModelAndView mv ,Enterprise enterprise){
mv.setViewName("enterprise/enterprise_addOrUpdate");
if(enterprise != null){
mv.addObject("obj",enterprise);
}
return mv;
}
/**
* 根据条件 分页查询
* @param enterprise
* @param page
* @param limit
* @return
*/
@ResponseBody
@RequestMapping("/findByParams")
public Result findByParams(Enterprise enterprise,Integer page , Integer limit){
return enterpriseServiceImpl.findByParam(enterprise, page, limit);
}
/**
* 新增or修改
* @param enterprise
* @return
*/
@ResponseBody
@RequestMapping("/addOrUpdate")
public Result addOrUpdate(Enterprise enterprise){
try {
enterpriseServiceImpl.saveOrUpdate(enterprise);
return new Result(ResultEnum.SUCCESS);
}catch (Exception e){
log.info("新增或修改失败",e);
return new Result(ResultEnum.ERROR);
}
}
/**
* 删除
* @param ids
* @return
*/
@ResponseBody
@RequestMapping("/delByIds")
public Result delByIds(@RequestParam("ids[]") List<Integer> ids){
try {
enterpriseServiceImpl.removeByIds(ids);
return new Result(ResultEnum.SUCCESS);
}catch (Exception e){
log.info("删除失败",e);
return new Result(ResultEnum.ERROR);
}
}
}
|
924148eefdc4ca224a1204467514e5acf314a81b | 447 | java | Java | src/main/java/cool/lijian/imageserver/NamingStrategy.java | webuilder/image-server | 158ed99bc90e728829d53db01ec27fd6da0cfa59 | [
"Apache-2.0"
] | 3 | 2017-07-05T21:05:52.000Z | 2021-01-19T01:19:13.000Z | src/main/java/cool/lijian/imageserver/NamingStrategy.java | webuilder/image-server | 158ed99bc90e728829d53db01ec27fd6da0cfa59 | [
"Apache-2.0"
] | null | null | null | src/main/java/cool/lijian/imageserver/NamingStrategy.java | webuilder/image-server | 158ed99bc90e728829d53db01ec27fd6da0cfa59 | [
"Apache-2.0"
] | 1 | 2018-03-06T14:03:28.000Z | 2018-03-06T14:03:28.000Z | 20.318182 | 64 | 0.612975 | 1,001,841 | package cool.lijian.imageserver;
/**
* The strategy of file's naming.
*
* @author Li Jian
*
*/
public interface NamingStrategy {
/**
* Create a fileId for input file.
*
* @param fileData
* the bytes of uploaded file.
* @param originalFileName
* the original name of uploaded file.
* @return a unique file id.
*/
String createFileId(byte[] fileData, String originalFileName);
}
|
92414a595ca777c36eda5ad4416cca40d495ce10 | 1,160 | java | Java | spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java | jawher/spring-cloud-netflix | 2ff40924a2d592a3c8fe598a48f676d559e501f2 | [
"Apache-2.0"
] | 12 | 2018-10-18T07:30:40.000Z | 2021-03-18T03:43:10.000Z | spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java | jawher/spring-cloud-netflix | 2ff40924a2d592a3c8fe598a48f676d559e501f2 | [
"Apache-2.0"
] | 1 | 2018-11-18T01:06:59.000Z | 2018-11-18T01:06:59.000Z | spring-cloud-netflix-turbine/src/main/java/org/springframework/cloud/netflix/turbine/ClusterInformation.java | jawher/spring-cloud-netflix | 2ff40924a2d592a3c8fe598a48f676d559e501f2 | [
"Apache-2.0"
] | 10 | 2018-10-30T11:03:24.000Z | 2019-12-16T03:29:44.000Z | 21.090909 | 66 | 0.566379 | 1,001,842 | package org.springframework.cloud.netflix.turbine;
import java.util.Objects;
public class ClusterInformation {
private String name;
private String link;
public ClusterInformation(){};
public ClusterInformation(String name, String link) {
this.name = name;
this.link = link;
}
public String getName() {
return name;
}
public String getLink() {
return link;
}
public void setName(String name) {
this.name = name;
}
public void setLink(String link) {
this.link = link;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ClusterInformation that = (ClusterInformation) o;
return Objects.equals(name, that.name) &&
Objects.equals(link, that.link);
}
@Override
public int hashCode() {
return Objects.hash(name, link);
}
@Override
public String toString() {
return "ClusterInformation{" +
"name='" + name + '\'' +
", link='" + link + '\'' +
'}';
}
}
|
92414cb2968a0ddbbb47fd55357e33ce3cfdcbc2 | 848 | java | Java | src/main/java/net/rithms/riot/api/endpoints/clash/dto/ClashTeamMember.java | KaluNight/riot-api-java | c3973d7c5441ad4d81d389ba89f43b7ed867477d | [
"Apache-2.0"
] | null | null | null | src/main/java/net/rithms/riot/api/endpoints/clash/dto/ClashTeamMember.java | KaluNight/riot-api-java | c3973d7c5441ad4d81d389ba89f43b7ed867477d | [
"Apache-2.0"
] | null | null | null | src/main/java/net/rithms/riot/api/endpoints/clash/dto/ClashTeamMember.java | KaluNight/riot-api-java | c3973d7c5441ad4d81d389ba89f43b7ed867477d | [
"Apache-2.0"
] | 2 | 2019-09-14T17:55:35.000Z | 2020-04-04T07:37:22.000Z | 22.918919 | 69 | 0.742925 | 1,001,843 | package net.rithms.riot.api.endpoints.clash.dto;
import java.io.Serializable;
import net.rithms.riot.api.Dto;
import net.rithms.riot.api.endpoints.clash.constant.TeamPosition;
import net.rithms.riot.api.endpoints.clash.constant.TeamRole;
/**
* This object contain an active team member of a clash team.
*/
public class ClashTeamMember extends Dto implements Serializable {
private static final long serialVersionUID = -6040664986162887640L;
private String summonerId;
private String teamId;
private String position;
private String role;
public String getSummonerId() {
return summonerId;
}
public String getTeamId() {
return teamId;
}
public TeamPosition getTeamPosition() {
return TeamPosition.valueOf(position);
}
public TeamRole getTeamRole() {
return TeamRole.valueOf(role);
}
}
|
92414cd9b85002ae4460639b3a17979e0c3ea69b | 1,734 | java | Java | src/noaf/CmdBase.java | nmaguiar/noAF | eb19e7f079e5fb6322418e0a9d9707ba9340d2ca | [
"Apache-2.0"
] | null | null | null | src/noaf/CmdBase.java | nmaguiar/noAF | eb19e7f079e5fb6322418e0a9d9707ba9340d2ca | [
"Apache-2.0"
] | null | null | null | src/noaf/CmdBase.java | nmaguiar/noAF | eb19e7f079e5fb6322418e0a9d9707ba9340d2ca | [
"Apache-2.0"
] | null | null | null | 29.372881 | 93 | 0.736295 | 1,001,844 | /*
* Copyright 2017 Nuno Aguiar <ychag@example.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package noaf;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
public class CmdBase {
final public static String noafVERSION = "";
final public static String noafLICENSE = "Apache 2.0";
public static String cmd = "CmdBase";
protected static String envString = "";
protected static String fileScript = "";
protected static ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
protected static Options getOptions() {
Options ops = new Options();
ops.addOption("f", true, "Reads and executes the provided script.");
ops.addOption("e", true, "Provide an environment string");
ops.addOption("s", false, "Execute the environment string");
return ops;
}
protected static void showHelp(String cmdLineSyntax) {
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp(cmdLineSyntax, getOptions());
}
protected static String getEnvString() {
return envString;
}
public static ScriptEngine getEngine() {
return engine;
}
}
|
92414d5f87962f36d0ccd2d18af079a08904de35 | 1,321 | java | Java | java/74.搜索二维矩阵.java | maoqitian/MyLeetCode | 78e831e47cde11eba071993e730a0b1bdefc6569 | [
"Apache-2.0"
] | 1 | 2020-03-16T15:00:07.000Z | 2020-03-16T15:00:07.000Z | java/74.搜索二维矩阵.java | maoqitian/MyLeetCode | 78e831e47cde11eba071993e730a0b1bdefc6569 | [
"Apache-2.0"
] | null | null | null | java/74.搜索二维矩阵.java | maoqitian/MyLeetCode | 78e831e47cde11eba071993e730a0b1bdefc6569 | [
"Apache-2.0"
] | null | null | null | 22.389831 | 70 | 0.453444 | 1,001,845 | /*
* @lc app=leetcode.cn id=74 lang=java
*
* [74] 搜索二维矩阵
*/
// @lc code=start
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
//想法一 暴力破解 将二维数组降为一维数组 时间复杂度 O(m*n)
// if(matrix.length ==0) return false;
// int row = matrix.length,columns = matrix[0].length;
// int []res = new int[row*columns];
// //遍历二维数组子数组index
// int index=0;
// for (int[] temps : matrix) {
// for (int i : temps) {
// res[index++] = i;
// }
// }
// for (int i : res) {
// if(i == target) return true;
// }
// return false;
//想法二 二分查找 时间复杂度 O(logmn)
if (matrix.length == 0 || matrix[0].length == 0) return false;
int row = matrix.length,columns = matrix[0].length;
int left = 0,right = row*columns-1;
while(left <=right){
int mid = left +(right-left)/2;
int midVal = matrix[mid/columns][mid%columns];
if(midVal < target){
left = mid+1;
}else if(midVal>target){
right = mid -1;
}else {
//mid 值等于 target
return true;
}
}
return false;
}
}
// @lc code=end
|
92414d7f85618401ba47ee2569a40f5998ab9144 | 53,299 | java | Java | tests/time/mosa/tests/s1026/62_dom4j/evosuite-tests/org/dom4j/io/OutputFormat_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | null | null | null | tests/time/mosa/tests/s1026/62_dom4j/evosuite-tests/org/dom4j/io/OutputFormat_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | 3 | 2020-11-16T20:40:56.000Z | 2021-03-23T00:18:04.000Z | tests/time/mosa/tests/s1026/62_dom4j/evosuite-tests/org/dom4j/io/OutputFormat_ESTest.java | sealuzh/termite-replication | 1636b1973c8692ed6a818e323cd1dd826cabbad3 | [
"MIT"
] | null | null | null | 37.272028 | 176 | 0.700595 | 1,001,846 | /*
* This file was automatically generated by EvoSuite
* Sat Nov 28 08:49:30 GMT 2020
*/
package org.dom4j.io;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.evosuite.runtime.EvoAssertions.*;
import org.dom4j.io.OutputFormat;
import org.evosuite.runtime.EvoRunner;
import org.evosuite.runtime.EvoRunnerParameters;
import org.junit.runner.RunWith;
@RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true)
public class OutputFormat_ESTest extends OutputFormat_ESTest_scaffolding {
/**
//Test case number: 0
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test00() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
assertFalse(outputFormat0.isXHTML());
outputFormat0.setXHTML(true);
boolean boolean0 = outputFormat0.isXHTML();
assertTrue(boolean0);
}
/**
//Test case number: 1
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test01() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
boolean boolean0 = outputFormat0.isTrimText();
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isPadText());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(boolean0);
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
}
/**
//Test case number: 2
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test02() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
boolean boolean0 = outputFormat0.isPadText();
assertFalse(outputFormat0.isSuppressDeclaration());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isNewlines());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertFalse(boolean0);
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isTrimText());
}
/**
//Test case number: 3
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test03() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat("sRVmVLj5,NgLMA", false);
assertFalse(outputFormat0.isOmitEncoding());
outputFormat0.setOmitEncoding(true);
boolean boolean0 = outputFormat0.isOmitEncoding();
assertTrue(boolean0);
}
/**
//Test case number: 4
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test04() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
boolean boolean0 = outputFormat0.isNewlines();
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isTrimText());
assertFalse(outputFormat0.isPadText());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(boolean0);
}
/**
//Test case number: 5
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test05() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setNewLineAfterNTags(16);
int int0 = outputFormat0.getNewLineAfterNTags();
assertEquals(16, int0);
}
/**
//Test case number: 6
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test06() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setNewLineAfterNTags((-4339));
int int0 = outputFormat0.getNewLineAfterNTags();
assertEquals((-4339), int0);
}
/**
//Test case number: 7
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test07() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
String string0 = outputFormat0.getIndent();
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isPadText());
assertNull(string0);
assertFalse(outputFormat0.isNewlines());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 8
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test08() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat("");
String string0 = outputFormat0.getIndent();
assertEquals("", string0);
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isXHTML());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isPadText());
assertFalse(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isNewlines());
}
/**
//Test case number: 9
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test09() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
outputFormat0.setXHTML(false);
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isTrimText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isNewlines());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isPadText());
}
/**
//Test case number: 10
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test10() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setTrimText(true);
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isPadText());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isXHTML());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isNewlines());
}
/**
//Test case number: 11
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test11() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
assertTrue(outputFormat0.isTrimText());
outputFormat0.setTrimText(false);
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
}
/**
//Test case number: 12
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test12() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
assertFalse(outputFormat0.isSuppressDeclaration());
outputFormat0.setSuppressDeclaration(true);
boolean boolean0 = outputFormat0.isSuppressDeclaration();
assertTrue(boolean0);
}
/**
//Test case number: 13
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test13() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setSuppressDeclaration(false);
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isPadText());
}
/**
//Test case number: 14
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test14() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
outputFormat0.setPadText(true);
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(" ", outputFormat0.getIndent());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
assertTrue(outputFormat0.isNewlines());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isXHTML());
}
/**
//Test case number: 15
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test15() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertTrue(outputFormat0.isPadText());
outputFormat0.setPadText(false);
assertEquals("\n", outputFormat0.getLineSeparator());
}
/**
//Test case number: 16
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test16() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
outputFormat0.setOmitEncoding(false);
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isXHTML());
assertEquals(" ", outputFormat0.getIndent());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isOmitEncoding());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals("\n", outputFormat0.getLineSeparator());
assertTrue(outputFormat0.isNewlines());
}
/**
//Test case number: 17
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test17() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
assertFalse(outputFormat0.isNewlines());
outputFormat0.setNewlines(true);
assertEquals("\n", outputFormat0.getLineSeparator());
}
/**
//Test case number: 18
/*Coverage entropy=1.6094379124341005
*/
@Test(timeout = 4000)
public void test18() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setNewlines(false);
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isPadText());
assertFalse(outputFormat0.isNewlines());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 19
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test19() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
outputFormat0.setNewLineAfterNTags(0);
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isPadText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isTrimText());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals("UTF-8", outputFormat0.getEncoding());
}
/**
//Test case number: 20
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test20() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
outputFormat0.setNewLineAfterDeclaration(true);
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isPadText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isTrimText());
}
/**
//Test case number: 21
/*Coverage entropy=2.0431918705451206
*/
@Test(timeout = 4000)
public void test21() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertEquals("\n", outputFormat0.getLineSeparator());
outputFormat0.setLineSeparator((String) null);
outputFormat0.getLineSeparator();
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isPadText());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewlines());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertEquals(" ", outputFormat0.getIndent());
}
/**
//Test case number: 22
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test22() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
outputFormat0.setLineSeparator("HI");
assertEquals("HI", outputFormat0.getLineSeparator());
}
/**
//Test case number: 23
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test23() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertEquals(" ", outputFormat0.getIndent());
outputFormat0.setIndentSize(0);
assertFalse(outputFormat0.isSuppressDeclaration());
}
/**
//Test case number: 24
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test24() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setIndentSize((-1795045032));
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isXHTML());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isPadText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isNewlines());
}
/**
//Test case number: 25
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test25() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertEquals(" ", outputFormat0.getIndent());
outputFormat0.setIndent(false);
assertEquals("\n", outputFormat0.getLineSeparator());
assertTrue(outputFormat0.isNewlines());
assertTrue(outputFormat0.isPadText());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 26
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test26() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertEquals(" ", outputFormat0.getIndent());
outputFormat0.setIndent((String) null);
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewlines());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertTrue(outputFormat0.isTrimText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals("\n", outputFormat0.getLineSeparator());
}
/**
//Test case number: 27
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test27() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
assertFalse(outputFormat0.isExpandEmptyElements());
outputFormat0.setExpandEmptyElements(true);
boolean boolean0 = outputFormat0.isExpandEmptyElements();
assertTrue(boolean0);
}
/**
//Test case number: 28
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test28() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
outputFormat0.setExpandEmptyElements(false);
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isXHTML());
assertEquals(" ", outputFormat0.getIndent());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewlines());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isPadText());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isExpandEmptyElements());
}
/**
//Test case number: 29
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test29() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
outputFormat0.setEncoding((String) null);
assertFalse(outputFormat0.isXHTML());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(" ", outputFormat0.getIndent());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isTrimText());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertTrue(outputFormat0.isNewlines());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isPadText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
}
/**
//Test case number: 30
/*Coverage entropy=1.0986122886681096
*/
@Test(timeout = 4000)
public void test30() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
assertEquals("UTF-8", outputFormat0.getEncoding());
outputFormat0.setEncoding("");
outputFormat0.getEncoding();
assertEquals("", outputFormat0.getEncoding());
}
/**
//Test case number: 31
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test31() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
// Undeclared exception!
try {
outputFormat0.setAttributeQuoteCharacter('4');
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Invalid attribute quote character (4)
//
verifyException("org.dom4j.io.OutputFormat", e);
}
}
/**
//Test case number: 32
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test32() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
// Undeclared exception!
try {
outputFormat0.setAttributeQuoteCharacter('z');
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Invalid attribute quote character (z)
//
verifyException("org.dom4j.io.OutputFormat", e);
}
}
/**
//Test case number: 33
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test33() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
String[] stringArray0 = new String[0];
int int0 = outputFormat0.parseOptions(stringArray0, 1487);
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isOmitEncoding());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isPadText());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isXHTML());
assertEquals(1487, int0);
}
/**
//Test case number: 34
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test34() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
// Undeclared exception!
try {
outputFormat0.parseOptions((String[]) null, (-1797849525));
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
//
// no message in exception (getMessage() returned null)
//
verifyException("org.dom4j.io.OutputFormat", e);
}
}
/**
//Test case number: 35
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test35() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
String[] stringArray0 = new String[0];
int int0 = outputFormat0.parseOptions(stringArray0, 0);
assertFalse(outputFormat0.isOmitEncoding());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isPadText());
assertEquals(" ", outputFormat0.getIndent());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertTrue(outputFormat0.isNewlines());
assertEquals(0, int0);
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
}
/**
//Test case number: 36
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test36() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
// Undeclared exception!
outputFormat0.setIndentSize(2147483645);
}
/**
//Test case number: 37
/*Coverage entropy=1.6987829895138007
*/
@Test(timeout = 4000)
public void test37() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
String[] stringArray0 = new String[7];
stringArray0[0] = "-indentSize";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: NumberFormatException");
} catch(NumberFormatException e) {
//
// null
//
verifyException("java.lang.Integer", e);
}
}
/**
//Test case number: 38
/*Coverage entropy=1.3020613918729727
*/
@Test(timeout = 4000)
public void test38() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
String[] stringArray0 = new String[1];
stringArray0[0] = "";
int int0 = outputFormat0.parseOptions(stringArray0, 0);
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isXHTML());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, int0);
assertEquals(" ", outputFormat0.getIndent());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewlines());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertTrue(outputFormat0.isPadText());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 39
/*Coverage entropy=0.5359610497090694
*/
@Test(timeout = 4000)
public void test39() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
String[] stringArray0 = new String[8];
stringArray0[0] = "-padText";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 40
/*Coverage entropy=0.5359610497090694
*/
@Test(timeout = 4000)
public void test40() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat("-trimText");
assertFalse(outputFormat0.isTrimText());
String[] stringArray0 = new String[1];
stringArray0[0] = "-trimText";
int int0 = outputFormat0.parseOptions(stringArray0, 0);
assertTrue(outputFormat0.isTrimText());
assertEquals(1, int0);
}
/**
//Test case number: 41
/*Coverage entropy=1.2265558156134033
*/
@Test(timeout = 4000)
public void test41() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
String[] stringArray0 = new String[1];
stringArray0[0] = "-lineSeparator";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: ArrayIndexOutOfBoundsException");
} catch(ArrayIndexOutOfBoundsException e) {
//
// 1
//
verifyException("org.dom4j.io.OutputFormat", e);
}
}
/**
//Test case number: 42
/*Coverage entropy=1.8891591637540215
*/
@Test(timeout = 4000)
public void test42() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
outputFormat0.setAttributeQuoteCharacter('\"');
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isPadText());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals(" ", outputFormat0.getIndent());
assertTrue(outputFormat0.isNewlines());
assertEquals("\n", outputFormat0.getLineSeparator());
}
/**
//Test case number: 43
/*Coverage entropy=1.8891591637540215
*/
@Test(timeout = 4000)
public void test43() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
// Undeclared exception!
try {
outputFormat0.setAttributeQuoteCharacter(' ');
fail("Expecting exception: IllegalArgumentException");
} catch(IllegalArgumentException e) {
//
// Invalid attribute quote character ( )
//
verifyException("org.dom4j.io.OutputFormat", e);
}
}
/**
//Test case number: 44
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test44() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setAttributeQuoteCharacter('\'');
assertEquals('\'', outputFormat0.getAttributeQuoteCharacter());
}
/**
//Test case number: 45
/*Coverage entropy=1.5607104090414063
*/
@Test(timeout = 4000)
public void test45() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setIndent(true);
assertFalse(outputFormat0.isSuppressDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isPadText());
assertEquals(" ", outputFormat0.getIndent());
assertFalse(outputFormat0.isXHTML());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isTrimText());
}
/**
//Test case number: 46
/*Coverage entropy=1.7478680974667573
*/
@Test(timeout = 4000)
public void test46() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
outputFormat0.setIndent("-expandEmpty-expandEpy-xhtmlF^I5Gr");
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isXHTML());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isNewlines());
assertEquals("-expandEmpty-expandEpy-xhtmlF^I5Gr", outputFormat0.getIndent());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isPadText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 47
/*Coverage entropy=1.8891591637540215
*/
@Test(timeout = 4000)
public void test47() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertEquals(" ", outputFormat0.getIndent());
outputFormat0.setIndent("");
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isPadText());
assertTrue(outputFormat0.isNewlines());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isXHTML());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isOmitEncoding());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isExpandEmptyElements());
}
/**
//Test case number: 48
/*Coverage entropy=1.9072839993213795
*/
@Test(timeout = 4000)
public void test48() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
String[] stringArray0 = new String[6];
stringArray0[0] = "-indent";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 49
/*Coverage entropy=0.6837389058487535
*/
@Test(timeout = 4000)
public void test49() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
String[] stringArray0 = new String[8];
stringArray0[0] = "-encoding";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 50
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test50() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat("sRVmVLj5,NgLMA", false);
outputFormat0.setEncoding("7[b`h)Y.&?");
assertEquals("7[b`h)Y.&?", outputFormat0.getEncoding());
}
/**
//Test case number: 51
/*Coverage entropy=1.7075391741350712
*/
@Test(timeout = 4000)
public void test51() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertFalse(outputFormat0.isExpandEmptyElements());
String[] stringArray0 = new String[1];
stringArray0[0] = "-expandEmpty-expandEpty-xhtmlF^IsGr";
int int0 = outputFormat0.parseOptions(stringArray0, 0);
assertTrue(outputFormat0.isExpandEmptyElements());
assertEquals(1, int0);
}
/**
//Test case number: 52
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test52() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
boolean boolean0 = outputFormat0.isSuppressDeclaration();
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isPadText());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(boolean0);
assertTrue(outputFormat0.isTrimText());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isXHTML());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
}
/**
//Test case number: 53
/*Coverage entropy=1.3906826278129532
*/
@Test(timeout = 4000)
public void test53() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertFalse(outputFormat0.isXHTML());
String[] stringArray0 = new String[1];
stringArray0[0] = "-xhtml'";
int int0 = outputFormat0.parseOptions(stringArray0, 0);
assertTrue(outputFormat0.isXHTML());
assertEquals(1, int0);
}
/**
//Test case number: 54
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test54() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
boolean boolean0 = outputFormat0.isOmitEncoding();
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewlines());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(" ", outputFormat0.getIndent());
assertFalse(boolean0);
assertFalse(outputFormat0.isXHTML());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertEquals("\n", outputFormat0.getLineSeparator());
assertTrue(outputFormat0.isTrimText());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isExpandEmptyElements());
}
/**
//Test case number: 55
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test55() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
String string0 = outputFormat0.getEncoding();
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isNewlines());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isPadText());
assertEquals("UTF-8", string0);
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 56
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test56() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
String string0 = outputFormat0.getLineSeparator();
assertEquals("\n", string0);
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isTrimText());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isNewlines());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isPadText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isOmitEncoding());
}
/**
//Test case number: 57
/*Coverage entropy=0.639031859650177
*/
@Test(timeout = 4000)
public void test57() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat("-newlines");
String[] stringArray0 = new String[6];
stringArray0[0] = "-newlines";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 58
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test58() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat();
boolean boolean0 = outputFormat0.isExpandEmptyElements();
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isTrimText());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isPadText());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isNewlines());
assertFalse(outputFormat0.isXHTML());
assertFalse(boolean0);
}
/**
//Test case number: 59
/*Coverage entropy=2.0431918705451206
*/
@Test(timeout = 4000)
public void test59() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
assertEquals("\n", outputFormat0.getLineSeparator());
outputFormat0.setLineSeparator("");
String string0 = outputFormat0.getLineSeparator();
assertEquals("", string0);
}
/**
//Test case number: 60
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test60() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
boolean boolean0 = outputFormat0.isNewlines();
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertEquals(" ", outputFormat0.getIndent());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertTrue(boolean0);
}
/**
//Test case number: 61
/*Coverage entropy=1.9722469794234416
*/
@Test(timeout = 4000)
public void test61() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
String[] stringArray0 = new String[9];
stringArray0[0] = "-omitEncoding";
// Undeclared exception!
try {
outputFormat0.parseOptions(stringArray0, 0);
fail("Expecting exception: NullPointerException");
} catch(NullPointerException e) {
}
}
/**
//Test case number: 62
/*Coverage entropy=0.6931471805599453
*/
@Test(timeout = 4000)
public void test62() throws Throwable {
OutputFormat outputFormat0 = new OutputFormat("", true, (String) null);
String string0 = outputFormat0.getEncoding();
assertEquals("", outputFormat0.getIndent());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertTrue(outputFormat0.isNewlines());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertFalse(outputFormat0.isTrimText());
assertNull(string0);
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isPadText());
}
/**
//Test case number: 63
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test63() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
String string0 = outputFormat0.getIndent();
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewlines());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isSuppressDeclaration());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals(" ", string0);
}
/**
//Test case number: 64
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test64() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
char char0 = outputFormat0.getAttributeQuoteCharacter();
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isXHTML());
assertTrue(outputFormat0.isPadText());
assertTrue(outputFormat0.isNewlines());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertEquals('\"', char0);
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals(" ", outputFormat0.getIndent());
}
/**
//Test case number: 65
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test65() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
boolean boolean0 = outputFormat0.isXHTML();
assertTrue(outputFormat0.isNewlines());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isOmitEncoding());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals(" ", outputFormat0.getIndent());
assertTrue(outputFormat0.isTrimText());
assertFalse(boolean0);
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
}
/**
//Test case number: 66
/*Coverage entropy=1.7917594692280547
*/
@Test(timeout = 4000)
public void test66() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
boolean boolean0 = outputFormat0.isNewLineAfterDeclaration();
assertFalse(outputFormat0.isPadText());
assertEquals("\n", outputFormat0.getLineSeparator());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isXHTML());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isNewlines());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(boolean0);
assertEquals("UTF-8", outputFormat0.getEncoding());
}
/**
//Test case number: 67
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test67() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
boolean boolean0 = outputFormat0.isPadText();
assertEquals("UTF-8", outputFormat0.getEncoding());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isXHTML());
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertFalse(outputFormat0.isSuppressDeclaration());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(boolean0);
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertFalse(outputFormat0.isExpandEmptyElements());
assertTrue(outputFormat0.isTrimText());
assertEquals(" ", outputFormat0.getIndent());
assertEquals("\n", outputFormat0.getLineSeparator());
assertTrue(outputFormat0.isNewlines());
}
/**
//Test case number: 68
/*Coverage entropy=1.8310204811135162
*/
@Test(timeout = 4000)
public void test68() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
assertFalse(outputFormat0.isSuppressDeclaration());
String[] stringArray0 = new String[1];
stringArray0[0] = "-suppressDeclaration";
int int0 = outputFormat0.parseOptions(stringArray0, 0);
assertTrue(outputFormat0.isSuppressDeclaration());
assertEquals(1, int0);
}
/**
//Test case number: 69
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test69() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
int int0 = outputFormat0.getNewLineAfterNTags();
assertEquals(0, int0);
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isXHTML());
assertEquals(" ", outputFormat0.getIndent());
assertTrue(outputFormat0.isNewlines());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertTrue(outputFormat0.isTrimText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isOmitEncoding());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isSuppressDeclaration());
}
/**
//Test case number: 70
/*Coverage entropy=1.945910149055313
*/
@Test(timeout = 4000)
public void test70() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createCompactFormat();
assertTrue(outputFormat0.isNewLineAfterDeclaration());
outputFormat0.setNewLineAfterDeclaration(false);
boolean boolean0 = outputFormat0.isNewLineAfterDeclaration();
assertFalse(boolean0);
}
/**
//Test case number: 71
/*Coverage entropy=1.9061547465398496
*/
@Test(timeout = 4000)
public void test71() throws Throwable {
OutputFormat outputFormat0 = OutputFormat.createPrettyPrint();
boolean boolean0 = outputFormat0.isTrimText();
assertEquals(0, outputFormat0.getNewLineAfterNTags());
assertEquals("\n", outputFormat0.getLineSeparator());
assertFalse(outputFormat0.isXHTML());
assertEquals("UTF-8", outputFormat0.getEncoding());
assertEquals('\"', outputFormat0.getAttributeQuoteCharacter());
assertEquals(" ", outputFormat0.getIndent());
assertTrue(boolean0);
assertTrue(outputFormat0.isNewlines());
assertTrue(outputFormat0.isNewLineAfterDeclaration());
assertTrue(outputFormat0.isPadText());
assertFalse(outputFormat0.isExpandEmptyElements());
assertFalse(outputFormat0.isOmitEncoding());
assertFalse(outputFormat0.isSuppressDeclaration());
}
}
|
92414e3572becce05d04a2b0c000741bfcc670ec | 4,763 | java | Java | src/org/sosy_lab/cpachecker/cfa/types/c/CArrayType.java | Po-Chun-Chien/cpachecker | 4e3b8babb9e98704363efe8bed109ac05f464678 | [
"Apache-2.0"
] | 16 | 2015-01-19T15:52:14.000Z | 2015-11-30T14:12:31.000Z | src/org/sosy_lab/cpachecker/cfa/types/c/CArrayType.java | teodorov/cpachecker | 16e37b76c5b9e3d203992c6c7bf96b64da6fbae1 | [
"Apache-2.0"
] | null | null | null | src/org/sosy_lab/cpachecker/cfa/types/c/CArrayType.java | teodorov/cpachecker | 16e37b76c5b9e3d203992c6c7bf96b64da6fbae1 | [
"Apache-2.0"
] | 18 | 2015-02-17T19:22:41.000Z | 2015-11-24T09:12:39.000Z | 29.583851 | 121 | 0.679194 | 1,001,847 | // This file is part of CPAchecker,
// a tool for configurable software verification:
// https://cpachecker.sosy-lab.org
//
// SPDX-FileCopyrightText: 2007-2020 Dirk Beyer <https://www.sosy-lab.org>
//
// SPDX-License-Identifier: Apache-2.0
package org.sosy_lab.cpachecker.cfa.types.c;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Objects;
import java.util.OptionalInt;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.sosy_lab.cpachecker.cfa.ast.c.CExpression;
import org.sosy_lab.cpachecker.cfa.ast.c.CIntegerLiteralExpression;
import org.sosy_lab.cpachecker.cfa.types.AArrayType;
public final class CArrayType extends AArrayType implements CType {
private static final long serialVersionUID = -6314468260643330323L;
private final @Nullable CExpression length;
private final boolean isConst;
private final boolean isVolatile;
public CArrayType(boolean pConst, boolean pVolatile,
CType pType, @Nullable CExpression pLength) {
super(pType);
isConst = pConst;
isVolatile = pVolatile;
length = pLength;
}
@Override
public CType getType() {
return (CType) super.getType();
}
public @Nullable CExpression getLength() {
return length;
}
/** Return the length of this array if statically known and small enough for an int. */
public OptionalInt getLengthAsInt() {
return length instanceof CIntegerLiteralExpression
? OptionalInt.of(((CIntegerLiteralExpression) length).getValue().intValueExact())
: OptionalInt.empty();
}
/**
* Convert this array type to a pointer type with the same target type. Note that in most cases
* the method {@link CTypes#adjustFunctionOrArrayType(CType)} should be used instead, which
* implements this conversion properly and also the similar conversion for function types.
*/
public CPointerType asPointerType() {
return new CPointerType(isConst, isVolatile, getType());
}
@Override
public String toASTString(String pDeclarator) {
return toASTString(pDeclarator, false);
}
private String toASTString(String pDeclarator, boolean pQualified) {
checkNotNull(pDeclarator);
return (isConst() ? "const " : "")
+ (isVolatile() ? "volatile " : "")
+ getType()
.toASTString(
pDeclarator + ("[" + (length != null ? length.toASTString(pQualified) : "") + "]"));
}
public String toQualifiedASTString(String pDeclarator) {
return toASTString(pDeclarator, true);
}
@Override
public boolean isConst() {
return isConst;
}
@Override
public boolean isVolatile() {
return isVolatile;
}
@Override
public boolean isIncomplete() {
return length == null; // C standard § 6.2.5 (22)
}
@Override
public String toString() {
return (isConst() ? "const " : "")
+ (isVolatile() ? "volatile " : "")
+ "("
+ getType()
+ (")[" + (length != null ? length.toASTString() : "") + "]");
}
@Override
public <R, X extends Exception> R accept(CTypeVisitor<R, X> pVisitor) throws X {
return pVisitor.visit(this);
}
@Override
public int hashCode() {
return Objects.hash(length, isConst, isVolatile) * 31 + super.hashCode();
}
/**
* Be careful, this method compares the CType as it is to the given object,
* typedefs won't be resolved. If you want to compare the type without having
* typedefs in it use #getCanonicalType().equals()
*/
@Override
public boolean equals(@Nullable Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CArrayType) || !super.equals(obj)) {
return false;
}
CArrayType other = (CArrayType) obj;
if (length instanceof CIntegerLiteralExpression && other.length instanceof CIntegerLiteralExpression) {
if (!((CIntegerLiteralExpression)length).getValue().equals(((CIntegerLiteralExpression)other.length).getValue())) {
return false;
}
} else {
if (!Objects.equals(length, other.length)) {
return false;
}
}
return isConst == other.isConst && isVolatile == other.isVolatile;
}
@Override
public CArrayType getCanonicalType() {
return getCanonicalType(false, false);
}
@Override
public CArrayType getCanonicalType(boolean pForceConst, boolean pForceVolatile) {
// C11 standard 6.7.3 (9) specifies that qualifiers like const and volatile
// on an array type always refer to the element type, not the array type.
// So we push these modifiers down to the element type here.
return new CArrayType(false, false,
getType().getCanonicalType(isConst || pForceConst,
isVolatile || pForceVolatile),
length);
}
}
|
92414e76a97d9ba61471ed3850bcb5483f4c9eaa | 629 | java | Java | dc-cudami-client/src/main/java/de/digitalcollections/cudami/client/identifiable/entity/geo/location/CudamiHumanSettlementsClient.java | dbmdz/digitalcollections-cms | 7366e42131a555e2efb941fb118a33e2807f02c3 | [
"MIT"
] | null | null | null | dc-cudami-client/src/main/java/de/digitalcollections/cudami/client/identifiable/entity/geo/location/CudamiHumanSettlementsClient.java | dbmdz/digitalcollections-cms | 7366e42131a555e2efb941fb118a33e2807f02c3 | [
"MIT"
] | null | null | null | dc-cudami-client/src/main/java/de/digitalcollections/cudami/client/identifiable/entity/geo/location/CudamiHumanSettlementsClient.java | dbmdz/digitalcollections-cms | 7366e42131a555e2efb941fb118a33e2807f02c3 | [
"MIT"
] | null | null | null | 44.928571 | 100 | 0.844197 | 1,001,848 | package de.digitalcollections.cudami.client.identifiable.entity.geo.location;
import com.fasterxml.jackson.databind.ObjectMapper;
import de.digitalcollections.cudami.client.identifiable.entity.CudamiEntitiesClient;
import de.digitalcollections.model.identifiable.entity.geo.location.HumanSettlement;
import java.net.http.HttpClient;
public class CudamiHumanSettlementsClient extends CudamiEntitiesClient<HumanSettlement> {
public CudamiHumanSettlementsClient(HttpClient http, String serverUrl, ObjectMapper mapper) {
super(http, serverUrl, HumanSettlement.class, mapper, API_VERSION_PREFIX + "/humansettlements");
}
}
|
92414eb2eeb0e43f879e87792d5874bb6ab7c7c1 | 1,844 | java | Java | src/main/java/ru/fusionsoft/database/snapshot/data/ColumnOfDbdColumnMapping.java | HarlyJune/dbmss | 394131aca79255c817725c45c527dcde3c88bceb | [
"Apache-2.0"
] | 3 | 2021-09-02T00:16:11.000Z | 2021-09-03T14:08:54.000Z | src/main/java/ru/fusionsoft/database/snapshot/data/ColumnOfDbdColumnMapping.java | HarlyJune/dbmss | 394131aca79255c817725c45c527dcde3c88bceb | [
"Apache-2.0"
] | 125 | 2021-09-02T00:15:40.000Z | 2022-02-05T20:43:34.000Z | src/main/java/ru/fusionsoft/database/snapshot/data/ColumnOfDbdColumnMapping.java | HarlyJune/dbmss | 394131aca79255c817725c45c527dcde3c88bceb | [
"Apache-2.0"
] | 1 | 2021-10-04T08:44:14.000Z | 2021-10-04T08:44:14.000Z | 32.350877 | 85 | 0.612798 | 1,001,849 | /*
* Copyright (C) 2018-2022 FusionSoft
*
* 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 ru.fusionsoft.database.snapshot.data;
import org.cactoos.scalar.NumberOf;
import ru.fusionsoft.database.mapping.dbd.DbdColumnMapping;
import ru.fusionsoft.database.mapping.fields.DbdColumnFields;
import ru.fusionsoft.lib.yaml.artefacts.TextOfMappingValue;
/**
* The type of {@link Column} can be constructed of {@link DbdColumnMapping}.
* @since 0.1
*/
public class ColumnOfDbdColumnMapping extends ColumnOfScalar {
/**
* Instantiates a new Column of dbd column mapping.
* @param column The DbdColumnMapping to be encapsulated.
*/
public ColumnOfDbdColumnMapping(final DbdColumnMapping column) {
super(
() -> new ColumnSimple(
new TextOfMappingValue(
column,
DbdColumnFields.DBNAME
),
new NumberOf(
new TextOfMappingValue(
column,
DbdColumnFields.ORDER
)
),
new ValueFormatOfIuType(
new TextOfMappingValue(
column,
DbdColumnFields.IUTYPE
)
)
)
);
}
}
|
924150344e28acbeb2288db015891fc14f75b541 | 650 | java | Java | src/tasks/quest1javasyntax/level2/task0208/Solution.java | LSVDnepr/JavaRush | 14205d8db66202a403da447d04a24e77f3d169e6 | [
"MIT"
] | null | null | null | src/tasks/quest1javasyntax/level2/task0208/Solution.java | LSVDnepr/JavaRush | 14205d8db66202a403da447d04a24e77f3d169e6 | [
"MIT"
] | null | null | null | src/tasks/quest1javasyntax/level2/task0208/Solution.java | LSVDnepr/JavaRush | 14205d8db66202a403da447d04a24e77f3d169e6 | [
"MIT"
] | null | null | null | 22.413793 | 60 | 0.707692 | 1,001,850 | package tasks.quest1javasyntax.level2.task0208;
public class Solution {
/*
Задача: Одного кота нам мало
Создать объект типа Cat 2 раза.
Сохрани каждый экземпляр в свою переменную.
Имена переменных должны быть разные.
Требования:
1. Программа не должна выводить текст на экран.
2. В методе main должно быть только две переменные типа Cat.
3. Переменным сразу должны быть присвоены значения.
4. В классе Cat не должно быть переменных.
5. В классе Cat не должно быть методов.
*/
public static void main(String[] args) {
Cat barsik=new Cat();
Cat murchik=new Cat();
}
public static class Cat {
}
}
|
92415082f7edab36f760fda11cf6e1eaecf1ff06 | 254 | java | Java | lava-core/src/edu/ucsf/lava/core/dao/LavaDaoPositionalParam.java | UCSFMemoryAndAging/lava | 534f03769cd770a57fa1f11c7f0ba61654d73127 | [
"BSD-2-Clause"
] | 1 | 2022-02-26T02:59:31.000Z | 2022-02-26T02:59:31.000Z | lava-core/src/edu/ucsf/lava/core/dao/LavaDaoPositionalParam.java | UCSFMemoryAndAging/lava | 534f03769cd770a57fa1f11c7f0ba61654d73127 | [
"BSD-2-Clause"
] | null | null | null | lava-core/src/edu/ucsf/lava/core/dao/LavaDaoPositionalParam.java | UCSFMemoryAndAging/lava | 534f03769cd770a57fa1f11c7f0ba61654d73127 | [
"BSD-2-Clause"
] | null | null | null | 25.4 | 63 | 0.775591 | 1,001,851 | package edu.ucsf.lava.core.dao;
public interface LavaDaoPositionalParam extends LavaDaoParam {
public int getParamPos();
public Object getParamValue();
public void setParamPos(int paramPos);
public void setParamValue(Object paramValue);
}
|
924150d24e9c28ecea5ce17da3758f28248c000f | 3,688 | java | Java | src/main/java/dn/bms3/service/interfac/IPaymentProofService.java | DarkusNightstalker/dn.bms3 | 28f50e8d3e4f38ffdd407a39031226afe8336afa | [
"Apache-2.0"
] | null | null | null | src/main/java/dn/bms3/service/interfac/IPaymentProofService.java | DarkusNightstalker/dn.bms3 | 28f50e8d3e4f38ffdd407a39031226afe8336afa | [
"Apache-2.0"
] | null | null | null | src/main/java/dn/bms3/service/interfac/IPaymentProofService.java | DarkusNightstalker/dn.bms3 | 28f50e8d3e4f38ffdd407a39031226afe8336afa | [
"Apache-2.0"
] | null | null | null | 36.156863 | 85 | 0.54718 | 1,001,852 | package dn.bms3.service.interfac;
import dn.bms3.model.PaymentProof;
import dn.core3.hibernate.generic.interfac.IGenericService;
import java.util.Date;
import java.util.List;
/**
*
* @author Darkus Nightmare
* @version 1.0
*/
public interface IPaymentProofService extends IGenericService<PaymentProof, Short> {
/**
*
* @param code
* @param exception
* @return
*/
public boolean existCode(String code, Short exception);
/**
*
* @param abbr
* @return
*/
public Short getIdByAbbr(String abbr);
/**
*
* @param date
* @return Lista de datos de los comprobantes de pago creados desde la fecha
* especifica <br/>
* <b>FORMATO : </b><br/>
* <code>[0]</code> - <b>Tipo : </b>{@link java.lang.Short} - Identificador
* único de registro<br/>
* <code>[1]</code> - <b>Tipo : </b>{@link java.lang.String} - Codigo<br/>
* <code>[2]</code> - <b>Tipo : </b>{@link java.lang.String} -
* Abreviatura<br/>
* <code>[3]</code> - <b>Tipo : </b>{@link java.lang.String} - Nombre<br/>
* <code>[4]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* vender<br/>
* <code>[5]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* comprar<br/>
* <code>[6]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* movimiento interno<br/>
* <code>[7]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* devoluciones<br/>
* <code>[8]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Esta
* activo<br/>
* <code>[9]</code> - <b>Tipo : </b>{@link java.lang.Integer} -
* Identificador de usuario creador<br/>
* <code>[10]</code> - <b>Tipo : </b>{@link java.util.Date} - Fecha de
* creación<br/>
*/
public List<Object[]> getCreateByAfterDate(Date date);
/**
*
* @param date
* @param withCreateds
* @return Lista de datos de los comprobantes de pago editados desde la
* fecha especifica <br/>
* <b>FORMATO : </b><br/>
* <code>[0]</code> - <b>Tipo : </b>{@link java.lang.Short} - Identificador
* único de registro<br/>
* <code>[1]</code> - <b>Tipo : </b>{@link java.lang.String} - Codigo<br/>
* <code>[2]</code> - <b>Tipo : </b>{@link java.lang.String} -
* Abreviatura<br/>
* <code>[3]</code> - <b>Tipo : </b>{@link java.lang.String} - Nombre<br/>
* <code>[4]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* vender<br/>
* <code>[5]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* comprar<br/>
* <code>[6]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* movimiento interno<br/>
* <code>[7]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Sirve para
* devoluciones<br/>
* <code>[8]</code> - <b>Tipo : </b>{@link java.lang.Boolean} - Esta
* activo<br/>
* <code>[9]</code> - <b>Tipo : </b>{@link java.lang.Integer} -
* Identificador de usuario creador<br/>
* <code>[10]</code> - <b>Tipo : </b>{@link java.util.Date} - Fecha de
* creación<br/>
* <code>[11]</code> - <b>Tipo : </b>{@link java.lang.Integer} -
* Identificador de usuario editor<br/>
* <code>[12]</code> - <b>Tipo : </b>{@link java.util.Date} - Ultima fecha
* de edición<br/>
*/
public List<Object[]> getEditedByAfterDate(Date date, boolean withCreateds);
/**
*
* @param code
* @return
*/
public Short getIdByCode(String code);
public List<Object[]> getForReturn();
}
|
924151195c33da4d5d0eb708854563045a820d6a | 498 | java | Java | luo-modules/luo-system/src/main/java/org/luo/system/user/service/impl/UserRoleServiceImpl.java | lsay-git/recallspace | 42fb6c7dd461f94ac46935dd4de381c1706f39d8 | [
"Apache-2.0"
] | null | null | null | luo-modules/luo-system/src/main/java/org/luo/system/user/service/impl/UserRoleServiceImpl.java | lsay-git/recallspace | 42fb6c7dd461f94ac46935dd4de381c1706f39d8 | [
"Apache-2.0"
] | null | null | null | luo-modules/luo-system/src/main/java/org/luo/system/user/service/impl/UserRoleServiceImpl.java | lsay-git/recallspace | 42fb6c7dd461f94ac46935dd4de381c1706f39d8 | [
"Apache-2.0"
] | null | null | null | 24.9 | 111 | 0.783133 | 1,001,853 | package org.luo.system.user.service.impl;
import org.luo.mp.base.BaseServiceImpl;
import org.luo.system.user.entity.UserRole;
import org.luo.system.user.mapper.UserRoleMapper;
import org.luo.system.user.service.UserRoleService;
import org.springframework.stereotype.Service;
/**
* @Date 14:38 2021/5/6
* @Description {
* UserRoleServiceImpl
* }
* @Author lsay
**/
@Service
public class UserRoleServiceImpl extends BaseServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
}
|
9241523c6b3340a0f6a59935ed589355125b8aa4 | 944 | java | Java | app/src/main/java/science/zxc/walkin/util/BitmapUtil.java | Taosky/Walkin | f968009e8c723efce5cf3a8031fc8c9bd9aafd43 | [
"Apache-2.0"
] | 2 | 2019-03-12T02:35:00.000Z | 2022-01-03T08:31:59.000Z | app/src/main/java/science/zxc/walkin/util/BitmapUtil.java | Taosky/Walkin | f968009e8c723efce5cf3a8031fc8c9bd9aafd43 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/science/zxc/walkin/util/BitmapUtil.java | Taosky/Walkin | f968009e8c723efce5cf3a8031fc8c9bd9aafd43 | [
"Apache-2.0"
] | 1 | 2022-01-03T08:32:01.000Z | 2022-01-03T08:32:01.000Z | 24.789474 | 80 | 0.610403 | 1,001,854 | package science.zxc.walkin.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* AUTH: Taosky
* TIME: 2017/5/11 0011:下午 10:48.
* MAIL: kenaa@example.com
* DESC:
*/
public class BitmapUtil {
//二进制转bitmap
public static Bitmap getBitmapFromByte(byte[] temp) {
if (temp != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
return bitmap;
} else {
return null;
}
}
//bitmap转二进制
public static byte[] getBitmapByte(Bitmap bitmap){
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
try {
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
return out.toByteArray();
}
} |
92415246a5c7c636843c5017e9f296a74d9b25d7 | 788 | java | Java | src/test/test/lee/codetest/code_753__Cracking_the_Safe/CodeTest.java | code543/leetcodequestions | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | [
"MIT"
] | 1 | 2019-02-23T06:47:17.000Z | 2019-02-23T06:47:17.000Z | src/test/test/lee/codetest/code_753__Cracking_the_Safe/CodeTest.java | code543/leetcodequestions | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | [
"MIT"
] | null | null | null | src/test/test/lee/codetest/code_753__Cracking_the_Safe/CodeTest.java | code543/leetcodequestions | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | [
"MIT"
] | null | null | null | 21.297297 | 72 | 0.717005 | 1,001,855 |
package lee.codetest.code_753__Cracking_the_Safe;
import org.junit.Test;
/**
testcase:1
1
*/
public class CodeTest
{
@Test
public void testSolution() throws Exception
{
//new Solution()
lee.code.code_753__Cracking_the_Safe.C753_MainClass.main(null);;
}
}
/**
*
*
* 753.Cracking the Safe
*
* difficulty: Hard
* @see https://leetcode.com/problems/cracking-the-safe/description/
* @see description_753.md
* @Similiar Topics
* -->Math https://leetcode.com//tag/math
* -->Depth-first Search https://leetcode.com//tag/depth-first-search
* @Similiar Problems
* Run solution from Unit Test:
* @see lee.codetest.code_753__Cracking_the_Safe.CodeTest
* Run solution from Main Judge Class:
* @see lee.code.code_753__Cracking_the_Safe.C753_MainClass
*
*/
|
92415288f6cec52ce74f0a183c86293fb45dbc60 | 970 | java | Java | GatherDiscounts/src/main/java/com/gathermall/discounts/service/impl/SkuLadderServiceImpl.java | 1334712251/GatherMall | 95be618faa799cb4866a7537de0e6780da27acbd | [
"Apache-2.0"
] | 5 | 2021-07-30T15:14:32.000Z | 2022-03-05T08:10:05.000Z | GatherDiscounts/src/main/java/com/gathermall/discounts/service/impl/SkuLadderServiceImpl.java | 1334712251/GatherMall | 95be618faa799cb4866a7537de0e6780da27acbd | [
"Apache-2.0"
] | 3 | 2021-11-19T08:25:43.000Z | 2022-03-10T10:52:37.000Z | GatherDiscounts/src/main/java/com/gathermall/discounts/service/impl/SkuLadderServiceImpl.java | 1334712251/GatherMall | 95be618faa799cb4866a7537de0e6780da27acbd | [
"Apache-2.0"
] | 1 | 2021-09-02T07:54:01.000Z | 2021-09-02T07:54:01.000Z | 33.448276 | 108 | 0.769072 | 1,001,856 | package com.gathermall.discounts.service.impl;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gathermall.common.utils.PageUtils;
import com.gathermall.common.utils.Query;
import com.gathermall.discounts.dao.SkuLadderDao;
import com.gathermall.discounts.entity.SkuLadder;
import com.gathermall.discounts.service.SkuLadderService;
@Service("skuLadderService")
public class SkuLadderServiceImpl extends ServiceImpl<SkuLadderDao, SkuLadder> implements SkuLadderService {
@Override
public PageUtils queryPage(Map<String, Object> params) {
IPage<SkuLadder> page = this.page(
new Query<SkuLadder>().getPage(params),
new QueryWrapper<SkuLadder>()
);
return new PageUtils(page);
}
} |
92415309af06bad1a773d779e7dad7ddec0e0531 | 8,007 | java | Java | modules/activiti-ui/activiti-app-rest/src/main/java/org/activiti/app/rest/runtime/RelatedContentResource.java | wjlc/rd-bpm | dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5 | [
"Apache-1.1"
] | 15 | 2018-09-06T07:57:49.000Z | 2021-02-28T07:40:39.000Z | modules/activiti-ui/activiti-app-rest/src/main/java/org/activiti/app/rest/runtime/RelatedContentResource.java | wjlc/rd-bpm | dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5 | [
"Apache-1.1"
] | 8 | 2019-11-13T08:32:36.000Z | 2022-01-27T16:19:19.000Z | modules/activiti-ui/activiti-app-rest/src/main/java/org/activiti/app/rest/runtime/RelatedContentResource.java | wjlc/rd-bpm | dece217fc9fe9c16e6b12e8ce1de5c98e2ba9fc5 | [
"Apache-1.1"
] | 16 | 2018-09-07T07:56:35.000Z | 2021-11-12T03:09:18.000Z | 50.04375 | 160 | 0.756088 | 1,001,857 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.app.rest.runtime;
import javax.servlet.http.HttpServletResponse;
import org.activiti.app.model.common.ResultListDataRepresentation;
import org.activiti.app.model.runtime.RelatedContentRepresentation;
import org.activiti.app.service.exception.InternalServerErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author Frederik Heremans
*/
@RestController
public class RelatedContentResource extends AbstractRelatedContentResource {
private static final Logger logger = LoggerFactory.getLogger(AbstractRelatedContentResource.class);
protected ObjectMapper objectMapper = new ObjectMapper();
@RequestMapping(value = "/rest/tasks/{taskId}/content", method = RequestMethod.GET)
public ResultListDataRepresentation getRelatedContentForTask(@PathVariable("taskId") String taskId) {
return super.getRelatedContentForTask(taskId);
}
@RequestMapping(value = "/rest/process-instances/{processInstanceId}/content", method = RequestMethod.GET)
public ResultListDataRepresentation getRelatedContentForProcessInstance(@PathVariable("processInstanceId") String processInstanceId) {
return super.getRelatedContentForProcessInstance(processInstanceId);
}
@RequestMapping(value = "/rest/content/{source}/{sourceId}/process-instances", method = RequestMethod.GET)
public ResultListDataRepresentation getRelatedProcessInstancesForContent(@PathVariable("source") String source, @PathVariable("sourceId") String sourceId) {
return super.getRelatedProcessInstancesForContent(source, sourceId);
}
@RequestMapping(value = "/rest/tasks/{taskId}/raw-content", method = RequestMethod.POST)
public RelatedContentRepresentation createRelatedContentOnTask(@PathVariable("taskId") String taskId, @RequestParam("file") MultipartFile file) {
return super.createRelatedContentOnTask(taskId, file);
}
/*
* specific endpoint for IE9 flash upload component
*/
@RequestMapping(value = "/rest/tasks/{taskId}/raw-content/text", method = RequestMethod.POST)
public String createRelatedContentOnTaskText(@PathVariable("taskId") String taskId, @RequestParam("file") MultipartFile file) {
RelatedContentRepresentation relatedContentRepresentation = super.createRelatedContentOnTask(taskId, file);
String relatedContentJson = null;
try {
relatedContentJson = objectMapper.writeValueAsString(relatedContentRepresentation);
} catch (Exception e) {
logger.error("Error while processing RelatedContent representation json", e);
throw new InternalServerErrorException("Related Content on task could not be saved");
}
return relatedContentJson;
}
@RequestMapping(value = "/rest/tasks/{taskId}/content", method = RequestMethod.POST)
public RelatedContentRepresentation createRelatedContentOnTask(@PathVariable("taskId") String taskId,
@RequestBody RelatedContentRepresentation relatedContent) {
return super.createRelatedContentOnTask(taskId, relatedContent);
}
@RequestMapping(value = "/rest/processes/{processInstanceId}/content", method = RequestMethod.POST)
public RelatedContentRepresentation createRelatedContentOnProcessInstance(@PathVariable("processInstanceId") String processInstanceId,
@RequestBody RelatedContentRepresentation relatedContent) {
return super.createRelatedContentOnProcessInstance(processInstanceId, relatedContent);
}
@RequestMapping(value = "/rest/process-instances/{processInstanceId}/raw-content", method = RequestMethod.POST)
public RelatedContentRepresentation createRelatedContentOnProcessInstance(@PathVariable("processInstanceId") String processInstanceId,
@RequestParam("file") MultipartFile file) {
return super.createRelatedContentOnProcessInstance(processInstanceId, file);
}
/*
* specific endpoint for IE9 flash upload component
*/
@RequestMapping(value = "/rest/process-instances/{processInstanceId}/raw-content/text", method = RequestMethod.POST)
public String createRelatedContentOnProcessInstanceText(@PathVariable("processInstanceId") String processInstanceId,
@RequestParam("file") MultipartFile file) {
RelatedContentRepresentation relatedContentRepresentation = super.createRelatedContentOnProcessInstance(processInstanceId, file);
String relatedContentJson = null;
try {
relatedContentJson = objectMapper.writeValueAsString(relatedContentRepresentation);
} catch (Exception e) {
logger.error("Error while processing RelatedContent representation json", e);
throw new InternalServerErrorException("Related Content on process instance could not be saved");
}
return relatedContentJson;
}
@RequestMapping(value = "/rest/content/raw", method = RequestMethod.POST)
public RelatedContentRepresentation createTemporaryRawRelatedContent(@RequestParam("file") MultipartFile file) {
return super.createTemporaryRawRelatedContent(file);
}
/*
* specific endpoint for IE9 flash upload component
*/
@RequestMapping(value = "/rest/content/raw/text", method = RequestMethod.POST)
public String createTemporaryRawRelatedContentText(@RequestParam("file") MultipartFile file) {
RelatedContentRepresentation relatedContentRepresentation = super.createTemporaryRawRelatedContent(file);
String relatedContentJson = null;
try {
relatedContentJson = objectMapper.writeValueAsString(relatedContentRepresentation);
} catch (Exception e) {
logger.error("Error while processing RelatedContent representation json", e);
throw new InternalServerErrorException("Related Content could not be saved");
}
return relatedContentJson;
}
@RequestMapping(value = "/rest/content", method = RequestMethod.POST)
public RelatedContentRepresentation createTemporaryRelatedContent(@RequestBody RelatedContentRepresentation relatedContent) {
return addRelatedContent(relatedContent, null, null, false);
}
@RequestMapping(value = "/rest/content/{contentId}", method = RequestMethod.DELETE)
public void deleteContent(@PathVariable("contentId") Long contentId, HttpServletResponse response) {
super.deleteContent(contentId, response);
}
@RequestMapping(value = "/rest/content/{contentId}", method = RequestMethod.GET)
public RelatedContentRepresentation getContent(@PathVariable("contentId") Long contentId) {
return super.getContent(contentId);
}
@RequestMapping(value = "/rest/content/{contentId}/raw", method = RequestMethod.GET)
public void getRawContent(@PathVariable("contentId") Long contentId, HttpServletResponse response) {
super.getRawContent(contentId, response);
}
}
|
924154b08fc4936028c08ce6cc7304ef6f5e792c | 419 | java | Java | modules-services/prov-service-core/src/main/java/org/openprovenance/prov/service/core/memory/LRUHashMap.java | YunLemon/ProvToolbox | fadf6195ca8e9081b2ec64c5a86db394ec682ef9 | [
"MIT"
] | 37 | 2015-02-17T23:28:52.000Z | 2022-01-12T13:00:04.000Z | modules-services/prov-service-core/src/main/java/org/openprovenance/prov/service/core/memory/LRUHashMap.java | YunLemon/ProvToolbox | fadf6195ca8e9081b2ec64c5a86db394ec682ef9 | [
"MIT"
] | 66 | 2015-01-05T09:07:12.000Z | 2022-01-17T14:57:50.000Z | modules-services/prov-service-core/src/main/java/org/openprovenance/prov/service/core/memory/LRUHashMap.java | YunLemon/ProvToolbox | fadf6195ca8e9081b2ec64c5a86db394ec682ef9 | [
"MIT"
] | 26 | 2015-04-09T00:14:08.000Z | 2021-11-14T06:06:49.000Z | 22.052632 | 64 | 0.665871 | 1,001,858 | package org.openprovenance.prov.service.core.memory;
import java.util.LinkedHashMap;
import java.util.Map;
public class LRUHashMap<K, V> extends LinkedHashMap<K, V> {
private final int limit;
public LRUHashMap(int limit) {
super(16, 0.75f, true);
this.limit = limit;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return size() > limit;
}
}
|
924154c093744a7699381f7fe7c4d3a26b02700c | 2,438 | java | Java | plugins/decide/template_decider/src/eu/larkc/plugin/decider/template_decider.java | TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | 31ce724b21468bee0693dfc1d0ca4bc861c58e2b | [
"Apache-2.0"
] | 10 | 2016-09-03T18:41:14.000Z | 2020-01-17T16:29:19.000Z | plugins/decide/template_decider/src/eu/larkc/plugin/decider/template_decider.java | TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | 31ce724b21468bee0693dfc1d0ca4bc861c58e2b | [
"Apache-2.0"
] | 3 | 2016-09-01T19:15:27.000Z | 2016-10-12T16:28:48.000Z | plugins/decide/template_decider/src/eu/larkc/plugin/decider/template_decider.java | TeamSPoon/CYC_JRTL_with_CommonLisp_OLD | 31ce724b21468bee0693dfc1d0ca4bc861c58e2b | [
"Apache-2.0"
] | 1 | 2017-11-21T13:29:31.000Z | 2017-11-21T13:29:31.000Z | 25.134021 | 92 | 0.7621 | 1,001,859 | package eu.larkc.plugin.decider;
import java.util.logging.Logger;
import org.openrdf.model.URI;
import org.openrdf.model.impl.URIImpl;
import eu.larkc.core.Workflow;
import eu.larkc.core.data.BooleanInformationSet;
import eu.larkc.core.data.SetOfStatements;
import eu.larkc.core.data.VariableBinding;
import eu.larkc.core.metadata.PluginRegistry;
import eu.larkc.core.qos.QoSInformation;
import eu.larkc.core.qos.QoSParameters;
import eu.larkc.core.query.SPARQLQuery;
import eu.larkc.plugin.decide.Decider;
import eu.larkc.plugin.Context;
/**
* This is a decider template, based on CycGateDecider
* @author Luka Bradesko, Alexey Cheptsov
*
*/
public class template_decider implements Decider {
private static Logger logger = Logger.getLogger(template_decider.class.getCanonicalName());
@Override
public BooleanInformationSet sparqlAsk(SPARQLQuery theQuery,
QoSParameters theQoSParameters) {
// TODO Auto-generated method stub
return null;
}
@Override
public SetOfStatements sparqlConstruct(SPARQLQuery theQuery,
QoSParameters theQoSParameters) {
// TODO Auto-generated method stub
return null;
}
@Override
public SetOfStatements sparqlDescribe(SPARQLQuery theQuery,
QoSParameters theQoSParameters) {
// TODO Auto-generated method stub
return null;
}
@Override
public VariableBinding sparqlSelect(SPARQLQuery theQuery,
QoSParameters theQoSParameters) {
//here a workflow is composed
System.out.println("Composing workflow ...");
Workflow workflow = new Workflow();
workflow.addPlugIn(new URIImpl("urn:eu.larkc.plugin.identify.template_identifier"));
workflow.addPlugIn(new URIImpl("urn:eu.larkc.plugin.transform.template_transformer"));
workflow.addPlugIn(new URIImpl("urn:eu.larkc.plugin.select.template_selecter"));
workflow.addPlugIn(new URIImpl("urn:eu.larkc.plugin.reason.template_reasoner"));
System.out.println("Starting workflow ...");
try {
workflow.start(theQuery);
} catch (Exception e) {
logger.severe(e.getMessage());
return null;
}
return (VariableBinding)workflow.take();
}
@Override
public Context createContext() {
return null;
}
@Override
public void initialise() {
}
@Override
public void shutdown() {
}
@Override
public URI getIdentifier() {
// TODO Auto-generated method stub
return null;
}
@Override
public QoSInformation getQoSInformation() {
// TODO Auto-generated method stub
return null;
}
}
|
924155672eab70824278f64b0cab434eecf710d6 | 19,491 | java | Java | src/test/java/com/google/devtools/build/lib/blackbox/tests/manageddirs/ManagedDirectoriesBlackBoxTest.java | patryk-kozak/bazel | e0e589658463beb9605030b4820dcc97e6a36f48 | [
"Apache-2.0"
] | 1 | 2022-03-22T11:55:06.000Z | 2022-03-22T11:55:06.000Z | src/test/java/com/google/devtools/build/lib/blackbox/tests/manageddirs/ManagedDirectoriesBlackBoxTest.java | patryk-kozak/bazel | e0e589658463beb9605030b4820dcc97e6a36f48 | [
"Apache-2.0"
] | null | null | null | src/test/java/com/google/devtools/build/lib/blackbox/tests/manageddirs/ManagedDirectoriesBlackBoxTest.java | patryk-kozak/bazel | e0e589658463beb9605030b4820dcc97e6a36f48 | [
"Apache-2.0"
] | null | null | null | 38.443787 | 100 | 0.686779 | 1,001,860 | // Copyright 2019 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package com.google.devtools.build.lib.blackbox.tests.manageddirs;
import static com.google.common.truth.Truth.assertThat;
import com.google.devtools.build.lib.blackbox.framework.BuilderRunner;
import com.google.devtools.build.lib.blackbox.framework.PathUtils;
import com.google.devtools.build.lib.blackbox.framework.ProcessResult;
import com.google.devtools.build.lib.blackbox.junit.AbstractBlackBoxTest;
import com.google.devtools.build.lib.util.OS;
import com.google.devtools.build.lib.util.ResourceFileLoader;
import com.google.testing.junit.testparameterinjector.TestParameter;
import com.google.testing.junit.testparameterinjector.TestParameterInjector;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Assume;
import org.junit.Test;
import org.junit.runner.RunWith;
/** Tests for managed directories. */
@RunWith(TestParameterInjector.class)
public final class ManagedDirectoriesBlackBoxTest extends AbstractBlackBoxTest {
// Flip to true to use --host_jvm_debug for all bazel commands.
private static final boolean DEBUG = false;
private final Random random = new Random(17);
private Integer currentDebugId;
@Test
public void testBuildProject(@TestParameter boolean trackIncrementalState) throws Exception {
generateProject();
buildExpectRepositoryRuleCalled(/*watchFs=*/ false, trackIncrementalState);
checkProjectFiles();
}
@Test
public void testNodeModulesDeleted(@TestParameter boolean watchFs) throws Exception {
generateProject();
buildExpectRepositoryRuleCalled();
checkProjectFiles();
Path nodeModules = context().getWorkDir().resolve("node_modules");
assertThat(nodeModules.toFile().isDirectory()).isTrue();
PathUtils.deleteTree(nodeModules);
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles();
}
@Test
public void testNodeModulesDeletedAndRecreated() throws Exception {
generateProject();
buildExpectRepositoryRuleCalled();
checkProjectFiles();
Path nodeModules = context().getWorkDir().resolve("node_modules");
assertThat(nodeModules.toFile().isDirectory()).isTrue();
Path nodeModulesBackup = context().getWorkDir().resolve("node_modules_backup");
PathUtils.copyTree(nodeModules, nodeModulesBackup);
PathUtils.deleteTree(nodeModules);
PathUtils.copyTree(nodeModulesBackup, nodeModules);
buildExpectRepositoryRuleNotCalled();
checkProjectFiles();
}
@Test
public void testBuildProjectFetchNotRecalled() throws Exception {
generateProject();
buildExpectRepositoryRuleCalled();
checkProjectFiles();
buildExpectRepositoryRuleNotCalled();
checkProjectFiles();
}
private BuilderRunner bazel() {
return bazel(/*watchFs=*/ false);
}
private BuilderRunner bazel(boolean watchFs) {
return bazel(watchFs, /*trackIncrementalState=*/ true);
}
private BuilderRunner bazel(boolean watchFs, boolean trackIncrementalState) {
currentDebugId = random.nextInt();
BuilderRunner bazel =
context()
.bazel()
.withEnv("DEBUG_ID", String.valueOf(currentDebugId))
.withFlags("--noincompatible_disable_managed_directories")
.withFlags(
"--watchfs=" + watchFs, "--track_incremental_state=" + trackIncrementalState);
if (DEBUG) {
bazel.enableDebug();
}
return bazel;
}
@Test
public void testChangeOfFileTextUnderNodeModules() throws Exception {
generateProject();
buildExpectRepositoryRuleCalled();
checkProjectFiles();
Path nodeModules = context().getWorkDir().resolve("node_modules");
Path modulePackageJson = nodeModules.resolve("example-module/package.json");
assertThat(modulePackageJson.toFile().exists()).isTrue();
// Assert that non-structural changes are not detected.
PathUtils.append(modulePackageJson, "# comment");
buildExpectRepositoryRuleNotCalled();
checkProjectFiles();
}
@Test
public void testLoadIsNotCalledForManagedDirectories() throws Exception {
generateProject();
Path workspaceFile = context().getWorkDir().resolve(WORKSPACE);
PathUtils.append(workspaceFile, "load('@non_existing//:target.bzl', 'some_symbol')");
// Test that there is error when loading, so we parsed managed directories successfully.
ProcessResult result = bazel().shouldFail().build("//...");
assertThat(findPattern(result, "ERROR: Failed to load Starlark extension")).isTrue();
}
@Test
public void testWithBazelTools() throws Exception {
generateProject();
Path workspaceFile = context().getWorkDir().resolve(WORKSPACE);
PathUtils.append(
workspaceFile,
"load(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\", \"http_file\")");
buildExpectRepositoryRuleCalled();
checkProjectFiles();
}
@Test
public void testAddManagedDirectoriesLater() throws Exception {
// Start the server, have things cached.
context().write("BUILD", "");
bazel().build("//...");
// Now that we generate the project and have managed directories updated, we are also testing,
// that managed directories are re-read correctly from the changed file.
generateProject();
buildExpectRepositoryRuleCalled();
checkProjectFiles();
// Test everything got cached.
buildExpectRepositoryRuleNotCalled();
checkProjectFiles();
}
@Test
public void testFilesUnderManagedDirectoriesRefreshed(@TestParameter boolean watchFs)
throws Exception {
generateProject();
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles();
// Now remove the ManagedDirectories, and change the package version - it should still work.
List<String> properWorkspaceText = context().read("WORKSPACE");
context()
.write(
"WORKSPACE",
"workspace(name = \"fine_grained_user_modules\")",
"load(\":use_node_modules.bzl\", \"generate_fine_grained_node_modules\")",
"generate_fine_grained_node_modules(name = \"generated_node_modules\",",
"package_json = \"//:package.json\",)");
Path packageJson =
PathUtils.resolve(context().getWorkDir(), "node_modules", "example-module", "package.json");
assertThat(packageJson.toFile().exists()).isTrue();
// Now we are building it without managed directories, both managed directories and
// RepositoryDirectoryValue will be dirty - we expect repository rule to be called again.
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles();
// Now change files directly in generated area, and build.
PathUtils.writeFile(
packageJson,
"{",
" \"license\": \"MIT\",",
" \"main\": \"example-module.js\",",
" \"name\": \"example-module\",",
" \"repository\": {",
" \"type\": \"git\",",
" \"url\": \"aaa\",",
" },",
" \"version\": \"7.7.7\"",
"}");
Path build = context().getWorkDir().resolve("BUILD");
List<String> oldBuild = PathUtils.readFile(build);
PathUtils.writeFile(
build,
"load(\":test_rule.bzl\", \"test_rule\")",
"test_rule(",
" name = \"test_generated_deps\",",
" module_source = \"@generated_node_modules//:example-module\",",
" version = \"7.7.7\"",
")");
// Test rule inputs has changed, so the build is not cached; however, the repository rule
// is not rerun, since it's inputs (including managed directories settings) were not changed,
// so debug_id is the same.
buildExpectRepositoryRuleNotCalled();
checkProjectFiles("7.7.7");
// And is cached.
buildExpectRepositoryRuleNotCalled();
// Now change just the managed directories and see the generated version comes up.
PathUtils.writeFile(
context().getWorkDir().resolve(WORKSPACE), properWorkspaceText.toArray(new String[0]));
PathUtils.writeFile(build, oldBuild.toArray(new String[0]));
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles("0.2.0");
}
@Test
public void testManagedDirectoriesSettingsAndManagedDirectoriesFilesChangeSimultaneously(
@TestParameter boolean watchFs) throws Exception {
generateProject();
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles();
// Modify managed directories somehow.
context()
.write(
"WORKSPACE",
"workspace(name = \"fine_grained_user_modules\",",
"managed_directories = {'@generated_node_modules': ['node_modules', 'something']})",
"load(\":use_node_modules.bzl\", \"generate_fine_grained_node_modules\")",
"generate_fine_grained_node_modules(name = \"generated_node_modules\",",
"package_json = \"//:package.json\",)");
Path packageJson =
PathUtils.resolve(context().getWorkDir(), "node_modules", "example-module", "package.json");
assertThat(packageJson.toFile().exists()).isTrue();
// Modify generated package.json under the managed directory.
PathUtils.writeFile(
packageJson,
"{",
" \"license\": \"MIT\",",
" \"main\": \"example-module.js\",",
" \"name\": \"example-module\",",
" \"repository\": {",
" \"type\": \"git\",",
" \"url\": \"aaa\",",
" },",
" \"version\": \"7.7.7\"",
"}");
// Expect files under managed directories be regenerated
// and changes under managed directories be lost.
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles();
}
@Test
public void testRepositoryOverrideWithManagedDirectories() throws Exception {
generateProject();
Path override = context().getTmpDir().resolve("override");
PathUtils.writeFile(override.resolve(WORKSPACE));
// Just define some similar target.
PathUtils.writeFile(
override.resolve("BUILD"),
"genrule(",
" name = \"example-module\",",
" srcs = [],",
" cmd = \"touch $(location package.json)\",",
" outs = [\"package.json\"],",
" visibility = ['//visibility:public'],",
")");
BuilderRunner bazel =
bazel().withFlags("--override_repository=generated_node_modules=" + override);
ProcessResult result = bazel.shouldFail().build("@generated_node_modules//:example-module");
assertThat(result.errString())
.contains(
"ERROR: Overriding repositories is not allowed"
+ " for the repositories with managed directories."
+ "\nThe following overridden external repositories"
+ " have managed directories: @generated_node_modules");
// Assert the result stays the same even when managed directories has not changed.
result = bazel.shouldFail().build("@generated_node_modules//:example-module");
assertThat(result.errString())
.contains(
"ERROR: Overriding repositories is not allowed"
+ " for the repositories with managed directories."
+ "\nThe following overridden external repositories"
+ " have managed directories: @generated_node_modules");
}
@Test
public void testRepositoryOverrideChangeToConflictWithManagedDirectories() throws Exception {
generateProject();
buildExpectRepositoryRuleCalled();
checkProjectFiles();
Path override = context().getTmpDir().resolve("override");
PathUtils.writeFile(override.resolve(WORKSPACE));
// Just define some similar target.
PathUtils.writeFile(
override.resolve("BUILD"),
"genrule(",
" name = \"example-module\",",
" srcs = [],",
" cmd = \"touch $(location package.json)\",",
" outs = [\"package.json\"],",
" visibility = ['//visibility:public'],",
")");
// Now the overrides change.
BuilderRunner bazel =
bazel().withFlags("--override_repository=generated_node_modules=" + override);
ProcessResult result = bazel.shouldFail().build("@generated_node_modules//:example-module");
assertThat(result.errString())
.contains(
"ERROR: Overriding repositories is not allowed"
+ " for the repositories with managed directories."
+ "\nThe following overridden external repositories"
+ " have managed directories: @generated_node_modules");
}
/**
* The test to verify that WORKSPACE file can not be a symlink when managed directories are used.
*
* <p>The test of the case, when WORKSPACE file is a symlink, but not managed directories are
* used, is in {@link WorkspaceBlackBoxTest#testWorkspaceFileIsSymlink()}
*/
@Test
public void testWorkspaceSymlinkThrowsWithManagedDirectories() throws Exception {
generateProject();
Path workspaceFile = context().getWorkDir().resolve(WORKSPACE);
assertThat(workspaceFile.toFile().delete()).isTrue();
Path tempWorkspace = Files.createTempFile(context().getTmpDir(), WORKSPACE, "");
PathUtils.writeFile(
tempWorkspace,
"workspace(name = \"fine_grained_user_modules\",",
"managed_directories = {'@generated_node_modules': ['node_modules']})",
"",
"load(\":use_node_modules.bzl\", \"generate_fine_grained_node_modules\")",
"",
"generate_fine_grained_node_modules(",
" name = \"generated_node_modules\",",
" package_json = \"//:package.json\",",
")");
Files.createSymbolicLink(workspaceFile, tempWorkspace);
ProcessResult result = bazel().shouldFail().build("//...");
assertThat(
findPattern(
result,
"WORKSPACE file can not be a symlink if incrementally updated directories are"
+ " used."))
.isTrue();
}
@Test
public void testNoCheckFiles(@TestParameter boolean allSkips, @TestParameter boolean watchFs)
throws Exception {
// On Darwin CI, --watchfs is nondeterministic if this passes or fails
Assume.assumeFalse(OS.DARWIN.equals(OS.getCurrent()));
generateProject();
buildExpectRepositoryRuleCalled(watchFs);
checkProjectFiles();
Path nodeModules = context().getWorkDir().resolve("node_modules");
assertThat(nodeModules.toFile().isDirectory()).isTrue();
PathUtils.deleteTree(nodeModules);
assertThat(nodeModules.toFile().isDirectory()).isFalse();
// As compared to testNodeModulesDeleted, we don't check that the external file disappeared with
// this flag so the build is broken
BuilderRunner bazel =
bazel(watchFs).withFlags("--noexperimental_check_external_repository_files");
if (allSkips) {
bazel = bazel.withFlags("--noexperimental_check_output_files");
}
ProcessResult result = bazel.shouldFail().build("//...");
assertThat(findPattern(result, "Not found package.json")).isTrue();
// it doesn't make the file on disk
assertThat(nodeModules.toFile().isDirectory()).isFalse();
// In a perfect world we would be able to fix the build by rebuilding here without the flags,
// but we don't
// invalidate the cache correctly so the server would have to shut down
}
private void generateProject() throws IOException {
writeProjectFile("BUILD.test", "BUILD");
writeProjectFile("WORKSPACE.test", "WORKSPACE");
writeProjectFile("bazelignore.test", ".bazelignore");
writeProjectFile("package.json", "package.json");
writeProjectFile("test_rule.bzl", "test_rule.bzl");
writeProjectFile("use_node_modules.bzl", "use_node_modules.bzl");
}
private void writeProjectFile(String oldName, String newName) throws IOException {
String text = ResourceFileLoader.loadResource(ManagedDirectoriesBlackBoxTest.class, oldName);
assertThat(text).isNotNull();
assertThat(text).isNotEmpty();
context().write(newName, text);
}
private void checkProjectFiles() throws IOException {
checkProjectFiles("0.2.0");
}
private void checkProjectFiles(String version) throws IOException {
Path nodeModules = context().getWorkDir().resolve("node_modules");
assertThat(nodeModules.toFile().exists()).isTrue();
assertThat(nodeModules.toFile().isDirectory()).isTrue();
Path exampleModule = nodeModules.resolve("example-module");
assertThat(exampleModule.toFile().exists()).isTrue();
assertThat(exampleModule.toFile().isDirectory()).isTrue();
Path packageJson = exampleModule.resolve("package.json");
assertThat(packageJson.toFile().exists()).isTrue();
assertThat(packageJson.toFile().isDirectory()).isFalse();
List<String> text = PathUtils.readFile(packageJson);
assertThat(text.stream().anyMatch(s -> s.trim().equals("\"name\": \"example-module\",")))
.isTrue();
String versionString = String.format("\"version\": \"%s\"", version);
assertThat(text.stream().anyMatch(s -> s.trim().equals(versionString))).isTrue();
}
private String getDebugId(BuilderRunner bazel) throws Exception {
Path path = context().resolveExecRootPath(bazel, "external/generated_node_modules/debug_id");
List<String> lines = PathUtils.readFile(path);
assertThat(lines.size()).isEqualTo(1);
return lines.get(0);
}
private void buildExpectRepositoryRuleCalled() throws Exception {
buildExpectRepositoryRuleCalled(/*watchFs=*/ false);
}
private void buildExpectRepositoryRuleCalled(boolean watchFs) throws Exception {
buildExpectRepositoryRuleCalled(watchFs, /*trackIncrementalState=*/ true);
}
private void buildExpectRepositoryRuleCalled(boolean watchFs, boolean trackIncrementalState)
throws Exception {
BuilderRunner bazel = bazel(watchFs, trackIncrementalState);
ProcessResult result = bazel.build("//...");
buildSucceeded(result);
debugIdShouldBeUpdated(bazel);
}
private void buildExpectRepositoryRuleNotCalled() throws Exception {
BuilderRunner bazel = bazel();
ProcessResult result = bazel.build("//...");
buildSucceeded(result);
debugIdShouldNotBeUpdated(bazel);
}
private void debugIdShouldBeUpdated(BuilderRunner bazel) throws Exception {
assertThat(getDebugId(bazel)).isEqualTo(String.valueOf(currentDebugId));
}
private void debugIdShouldNotBeUpdated(BuilderRunner bazel) throws Exception {
assertThat(getDebugId(bazel)).isNotEqualTo(String.valueOf(currentDebugId));
}
private static void buildSucceeded(ProcessResult result) {
assertThat(findPattern(result, "INFO: Build completed successfully")).isTrue();
}
private static boolean findPattern(ProcessResult result, String pattern) {
String[] lines = result.errString().split("\n");
return Arrays.stream(lines).anyMatch(s -> s.contains(pattern));
}
}
|
924155880c3dae92635821fdd684812ac33e64c6 | 1,914 | java | Java | src/main/java/com/zhixin/rd/memory/web/service/zaiti/SpServiceImpl.java | Hexiaojiao0732/htgl | e17bf8e79abe00b112e00fd3560022d0a708b32b | [
"MIT"
] | null | null | null | src/main/java/com/zhixin/rd/memory/web/service/zaiti/SpServiceImpl.java | Hexiaojiao0732/htgl | e17bf8e79abe00b112e00fd3560022d0a708b32b | [
"MIT"
] | null | null | null | src/main/java/com/zhixin/rd/memory/web/service/zaiti/SpServiceImpl.java | Hexiaojiao0732/htgl | e17bf8e79abe00b112e00fd3560022d0a708b32b | [
"MIT"
] | null | null | null | 21.505618 | 62 | 0.741902 | 1,001,861 | package com.zhixin.rd.memory.web.service.zaiti;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zhixin.rd.memory.web.dao.zaiti.ISpMapper;
import com.zhixin.rd.memory.web.entity.SpEntity;
@Service
public class SpServiceImpl implements ISpService {
@Autowired
private ISpMapper spMapper;
@Override
public List<SpEntity> queryAllSp(Map<String, Object> map) {
// TODO Auto-generated method stub
return spMapper.querySp(map);
}
@Override
public int countSp() {
// TODO Auto-generated method stub
return spMapper.countSp();
}
@Override
public void insertSp(SpEntity entity) {
// TODO Auto-generated method stub
spMapper.insertSp(entity);
}
@Override
public void updateSp(SpEntity entity) {
// TODO Auto-generated method stub
spMapper.updateSp(entity);
}
@Override
public void deleteSpById(Long id) {
// TODO Auto-generated method stub
spMapper.deleteSpById(id);
}
@Override
public void updateShSp(SpEntity entity) {
// TODO Auto-generated method stub
spMapper.updateShSp(entity);
}
@Override
public List<SpEntity> queryAllSp2(Map<String, Object> map) {
// TODO Auto-generated method stub
return spMapper.queryAllSp2(map);
}
@Override
public int countSp2() {
// TODO Auto-generated method stub
return spMapper.countSp2();
}
@Override
public List<SpEntity> queryAllSp3(Map<String, Object> map) {
// TODO Auto-generated method stub
return spMapper.queryAllSp3(map);
}
@Override
public int countSp3() {
// TODO Auto-generated method stub
return spMapper.countSp3();
}
@Override
public void updateSpTp(SpEntity entity) {
// TODO Auto-generated method stub
spMapper.updateSpTp(entity);
}
@Override
public List<SpEntity> querySpList() {
// TODO Auto-generated method stub
return spMapper.querySpList();
}
}
|
924155bd9d55ed7f538c896924a352c818c063ee | 1,669 | java | Java | xlsx-dmn-converter/src/main/java/org/camunda/bpm/dmn/xlsx/DmnConversionContext.java | Tenjirou/camunda-dmn-xlsx | b32bcd71f4268be72938920e188e52b1a4fa6242 | [
"Apache-2.0"
] | 30 | 2016-01-19T09:39:17.000Z | 2021-04-12T09:27:34.000Z | xlsx-dmn-converter/src/main/java/org/camunda/bpm/dmn/xlsx/DmnConversionContext.java | Tenjirou/camunda-dmn-xlsx | b32bcd71f4268be72938920e188e52b1a4fa6242 | [
"Apache-2.0"
] | 33 | 2016-11-09T08:52:51.000Z | 2021-02-04T13:32:30.000Z | xlsx-dmn-converter/src/main/java/org/camunda/bpm/dmn/xlsx/DmnConversionContext.java | Tenjirou/camunda-dmn-xlsx | b32bcd71f4268be72938920e188e52b1a4fa6242 | [
"Apache-2.0"
] | 27 | 2016-10-05T12:45:37.000Z | 2021-03-29T16:14:13.000Z | 32.72549 | 116 | 0.767525 | 1,001,862 | /* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.camunda.bpm.dmn.xlsx;
import java.util.List;
import org.camunda.bpm.dmn.xlsx.api.SpreadsheetCell;
import org.camunda.bpm.dmn.xlsx.elements.IndexedDmnColumns;
/**
* @author Thorben Lindhauer
*
*/
public class DmnConversionContext {
protected final List<CellContentHandler> cellContentHandlers;
protected final XlsxWorksheetContext worksheetContext;
protected IndexedDmnColumns indexedDmnColumns = new IndexedDmnColumns();
public DmnConversionContext(XlsxWorksheetContext worksheetContext, List<CellContentHandler> cellContentHandlers) {
this.worksheetContext = worksheetContext;
this.cellContentHandlers = cellContentHandlers;
}
public String resolveCellValue(SpreadsheetCell cell) {
for (CellContentHandler contentHandler : cellContentHandlers) {
if (contentHandler.canConvert(cell, worksheetContext)) {
return contentHandler.convert(cell, worksheetContext);
}
}
throw new RuntimeException("cannot parse cell content, unsupported format");
}
public IndexedDmnColumns getIndexedDmnColumns() {
return indexedDmnColumns;
}
}
|
92415680f188bc68b2293cb09ed420e5aeb4b4bf | 968 | java | Java | Library22 (2)/app/src/main/java/com/cafe24/kye1898/library/BasicInfo.java | MobileSeoul/2017seoul-46 | 831f0e043fc30f0755b6ee632621820cdbdaea01 | [
"MIT"
] | null | null | null | Library22 (2)/app/src/main/java/com/cafe24/kye1898/library/BasicInfo.java | MobileSeoul/2017seoul-46 | 831f0e043fc30f0755b6ee632621820cdbdaea01 | [
"MIT"
] | null | null | null | Library22 (2)/app/src/main/java/com/cafe24/kye1898/library/BasicInfo.java | MobileSeoul/2017seoul-46 | 831f0e043fc30f0755b6ee632621820cdbdaea01 | [
"MIT"
] | null | null | null | 21.511111 | 64 | 0.657025 | 1,001,863 | package com.cafe24.kye1898.library;
import android.Manifest;
/**
* Created by YeEun on 2017-08-31.
*/
public class BasicInfo {
/**
* 외장 메모리 패스
*/
public static String ExternalPath ="sdcard/";
/**
* 외장 메모리 패스 체크 여부
*/
public static boolean ExternalChecked = false;
/**
* 사진 저장 위치
*/
public static String FOLDER_PHOTO = "Library/photo/";
//public static String DATABASE_NAME = "Library/book.db";
public static final int REQ_PHOTO_CAPTURE_ACTIVITY = 1501;
public static final int REQ_PHOTO_SELECTION_ACTIVITY = 1502;
public static final int CONTENT_PHOTO = 2001;
public static final int CONTENT_PHOTO_EX = 2005;
public static final int CONFIRM_TEXT_INPUT = 3002;
public static final int IMAGE_CANNOT_BE_STORED = 1002;
public static final int DATE_DIALOG_ID = 1000;
//========== 메모 모드 상수 ==========//
public static final String MODE_MODIFY = "MODE_MODIFY";
}
|
924156c039990559e93684b53e26303c80fb05a2 | 9,301 | java | Java | sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java | Lucky-Microservices/tars | 786bc718d844653d9ab22cad9ce47b1ac6b85ae4 | [
"Apache-2.0"
] | 2 | 2019-09-02T06:15:35.000Z | 2019-09-02T09:21:41.000Z | sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java | Lucky-Microservices/tars | 786bc718d844653d9ab22cad9ce47b1ac6b85ae4 | [
"Apache-2.0"
] | 4 | 2020-02-21T19:01:28.000Z | 2022-03-31T18:32:46.000Z | sentinel-dashboard/src/main/java/com/alibaba/csp/sentinel/dashboard/controller/ParamFlowRuleController.java | Lucky-Microservices/tars | 786bc718d844653d9ab22cad9ce47b1ac6b85ae4 | [
"Apache-2.0"
] | null | null | null | 33.456835 | 107 | 0.732609 | 1,001,864 | /*
* Copyright 1999-2018 Alibaba Group Holding 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.alibaba.csp.sentinel.dashboard.controller;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.AuthUser;
import com.alibaba.csp.sentinel.dashboard.auth.AuthService.PrivilegeType;
import com.alibaba.csp.sentinel.dashboard.client.CommandNotFoundException;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.SentinelVersion;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.ParamFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppManagement;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.dashboard.domain.Result;
import com.alibaba.csp.sentinel.dashboard.repository.rule.RuleRepository;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRuleProvider;
import com.alibaba.csp.sentinel.dashboard.rule.DynamicRulePublisher;
import com.alibaba.csp.sentinel.dashboard.util.VersionUtils;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.util.StringUtil;
/**
* @author Eric Zhao
* @since 0.2.1
*/
@RestController
@RequestMapping(value = "/paramFlow")
public class ParamFlowRuleController {
private final Logger logger = LoggerFactory.getLogger(ParamFlowRuleController.class);
@Autowired
private AppManagement appManagement;
@Autowired
private RuleRepository<ParamFlowRuleEntity, Long> repository;
@Autowired
private DynamicRuleProvider<List<ParamFlowRuleEntity>> ruleProvider;
@Autowired
private DynamicRulePublisher<List<ParamFlowRuleEntity>> rulePublisher;
@Autowired
private AuthService<HttpServletRequest> authService;
private boolean checkIfSupported(String app) {
try {
return Optional.ofNullable(appManagement.getDetailApp(app))
.flatMap(e -> e.getMachines().stream().filter(MachineInfo::isHealthy)
.findFirst())
.flatMap(m -> VersionUtils.parseVersion(m.getVersion())
.map(v -> v.greaterOrEqual(version020)))
.orElse(true);
// If error occurred or cannot retrieve machine info, return true.
}
catch (Exception ex) {
return true;
}
}
@GetMapping("/rules")
public Result<List<ParamFlowRuleEntity>> apiQueryAllRulesForMachine(
HttpServletRequest request, @RequestParam String app) {
AuthUser authUser = authService.getAuthUser(request);
authUser.authTarget(app, PrivilegeType.READ_RULE);
if (StringUtil.isEmpty(app)) {
return Result.ofFail(-1, "app cannot be null or empty");
}
if (!checkIfSupported(app)) {
return unsupportedVersion();
}
try {
List<ParamFlowRuleEntity> rules = ruleProvider.getRules(app);
repository.saveAll(rules);
return Result.ofSuccess(rules);
}
catch (ExecutionException ex) {
logger.error("Error when querying parameter flow rules", ex.getCause());
if (isNotSupported(ex.getCause())) {
return unsupportedVersion();
}
else {
return Result.ofThrowable(-1, ex.getCause());
}
}
catch (Throwable throwable) {
logger.error("Error when querying parameter flow rules", throwable);
return Result.ofFail(-1, throwable.getMessage());
}
}
private boolean isNotSupported(Throwable ex) {
return ex instanceof CommandNotFoundException;
}
@PostMapping("/rule")
public Result<ParamFlowRuleEntity> apiAddParamFlowRule(HttpServletRequest request,
@RequestBody ParamFlowRuleEntity entity) {
AuthUser authUser = authService.getAuthUser(request);
authUser.authTarget(entity.getApp(), PrivilegeType.WRITE_RULE);
Result<ParamFlowRuleEntity> checkResult = checkEntityInternal(entity);
if (checkResult != null) {
return checkResult;
}
if (!checkIfSupported(entity.getApp())) {
return unsupportedVersion();
}
entity.setId(null);
entity.getRule().setResource(entity.getResource().trim());
Date date = new Date();
entity.setGmtCreate(date);
entity.setGmtModified(date);
try {
entity = repository.save(entity);
publishRules(entity.getApp());
return Result.ofSuccess(entity);
}
catch (ExecutionException ex) {
logger.error("Error when adding new parameter flow rules", ex.getCause());
if (isNotSupported(ex.getCause())) {
return unsupportedVersion();
}
else {
return Result.ofThrowable(-1, ex.getCause());
}
}
catch (Throwable throwable) {
logger.error("Error when adding new parameter flow rules", throwable);
return Result.ofFail(-1, throwable.getMessage());
}
}
private <R> Result<R> checkEntityInternal(ParamFlowRuleEntity entity) {
if (entity == null) {
return Result.ofFail(-1, "bad rule body");
}
if (StringUtil.isBlank(entity.getApp())) {
return Result.ofFail(-1, "app can't be null or empty");
}
if (entity.getRule() == null) {
return Result.ofFail(-1, "rule can't be null");
}
if (StringUtil.isBlank(entity.getResource())) {
return Result.ofFail(-1, "resource name cannot be null or empty");
}
if (entity.getCount() < 0) {
return Result.ofFail(-1, "count should be valid");
}
if (entity.getGrade() != RuleConstant.FLOW_GRADE_QPS) {
return Result.ofFail(-1,
"Unknown mode (blockGrade) for parameter flow control");
}
if (entity.getParamIdx() == null || entity.getParamIdx() < 0) {
return Result.ofFail(-1, "paramIdx should be valid");
}
if (entity.getDurationInSec() <= 0) {
return Result.ofFail(-1, "durationInSec should be valid");
}
if (entity.getControlBehavior() < 0) {
return Result.ofFail(-1, "controlBehavior should be valid");
}
return null;
}
@PutMapping("/rule/{id}")
public Result<ParamFlowRuleEntity> apiUpdateParamFlowRule(HttpServletRequest request,
@PathVariable("id") Long id, @RequestBody ParamFlowRuleEntity entity) {
AuthUser authUser = authService.getAuthUser(request);
if (id == null || id <= 0) {
return Result.ofFail(-1, "Invalid id");
}
ParamFlowRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofFail(-1, "id " + id + " does not exist");
}
authUser.authTarget(oldEntity.getApp(), PrivilegeType.WRITE_RULE);
Result<ParamFlowRuleEntity> checkResult = checkEntityInternal(entity);
if (checkResult != null) {
return checkResult;
}
if (!checkIfSupported(entity.getApp())) {
return unsupportedVersion();
}
entity.setId(id);
Date date = new Date();
entity.setGmtCreate(oldEntity.getGmtCreate());
entity.setGmtModified(date);
try {
entity = repository.save(entity);
publishRules(entity.getApp());
return Result.ofSuccess(entity);
}
catch (ExecutionException ex) {
logger.error("Error when updating parameter flow rules, id=" + id,
ex.getCause());
if (isNotSupported(ex.getCause())) {
return unsupportedVersion();
}
else {
return Result.ofThrowable(-1, ex.getCause());
}
}
catch (Throwable throwable) {
logger.error("Error when updating parameter flow rules, id=" + id, throwable);
return Result.ofFail(-1, throwable.getMessage());
}
}
@DeleteMapping("/rule/{id}")
public Result<Long> apiDeleteRule(HttpServletRequest request,
@PathVariable("id") Long id) {
AuthUser authUser = authService.getAuthUser(request);
if (id == null) {
return Result.ofFail(-1, "id cannot be null");
}
ParamFlowRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
authUser.authTarget(oldEntity.getApp(), PrivilegeType.DELETE_RULE);
try {
repository.delete(id);
publishRules(oldEntity.getApp());
return Result.ofSuccess(id);
}
catch (ExecutionException ex) {
logger.error("Error when deleting parameter flow rules", ex.getCause());
if (isNotSupported(ex.getCause())) {
return unsupportedVersion();
}
else {
return Result.ofThrowable(-1, ex.getCause());
}
}
catch (Throwable throwable) {
logger.error("Error when deleting parameter flow rules", throwable);
return Result.ofFail(-1, throwable.getMessage());
}
}
private void publishRules(String app) throws Exception {
List<ParamFlowRuleEntity> rules = repository.findAllByApp(app);
rulePublisher.publish(app, rules);
}
private <R> Result<R> unsupportedVersion() {
return Result.ofFail(4041,
"Sentinel client not supported for parameter flow control (unsupported version or dependency absent)");
}
private final SentinelVersion version020 = new SentinelVersion().setMinorVersion(2);
}
|
924156e0d2cfb1498e949d86033d62f933ff4ff3 | 1,421 | java | Java | exec/vector/src/main/java/org/apache/drill/exec/vector/UntypedReaderImpl.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 1,510 | 2015-01-04T01:35:19.000Z | 2022-03-28T23:36:02.000Z | exec/vector/src/main/java/org/apache/drill/exec/vector/UntypedReaderImpl.java | idvp-project/drill | 94e86d19407b0a66cfe432f45fb91a880eae4ea9 | [
"Apache-2.0"
] | 1,979 | 2015-01-28T03:18:38.000Z | 2022-03-31T13:49:32.000Z | exec/vector/src/main/java/org/apache/drill/exec/vector/UntypedReaderImpl.java | zhangxiangyang/drill | 97a321d8dc7430d8840fb4e0ee805b9fd2a0c329 | [
"Apache-2.0"
] | 940 | 2015-01-01T01:39:39.000Z | 2022-03-25T08:46:59.000Z | 28.42 | 75 | 0.740324 | 1,001,865 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.drill.exec.vector;
import org.apache.drill.common.types.TypeProtos;
import org.apache.drill.exec.vector.complex.impl.AbstractFieldReader;
public class UntypedReaderImpl extends AbstractFieldReader {
@Override
public TypeProtos.MajorType getType() {
return UntypedNullHolder.TYPE;
}
@Override
public boolean isSet() {
return false;
}
@Override
public int size() {
return 0;
}
@Override
public void read(UntypedNullHolder holder) {
holder.isSet = 0;
}
@Override
public void read(int arrayIndex, UntypedNullHolder holder) {
holder.isSet = 0;
}
}
|
92415831b27f368cf54d8e40eacd8dda3173fcd6 | 8,959 | java | Java | src/ch/muriz/gaface/Utils.java | Murgio/GA-Face-Generator | 79faef249662997d79a58ebb337bca277034e1dd | [
"Apache-2.0"
] | 103 | 2017-01-07T16:10:27.000Z | 2022-03-18T09:16:00.000Z | src/ch/muriz/gaface/Utils.java | Murgio/GA-Face-Generator | 79faef249662997d79a58ebb337bca277034e1dd | [
"Apache-2.0"
] | 3 | 2016-10-13T13:42:41.000Z | 2018-04-13T15:03:09.000Z | src/ch/muriz/gaface/Utils.java | Murgio/GA-Face-Generator | 79faef249662997d79a58ebb337bca277034e1dd | [
"Apache-2.0"
] | 10 | 2017-03-04T21:48:44.000Z | 2021-11-04T09:26:36.000Z | 37.485356 | 118 | 0.561447 | 1,001,866 | package ch.muriz.gaface;
import java.awt.*;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.util.List;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Random;
public final class Utils {
// Generates an array with numbers from 0 to 100 (100 excluded)
public static int[] range(int start, int stop) {
int[] result = new int[stop-start];
for(int i=0;i<stop-start;i++)
result[i] = start+i;
return result;
}
// = random.choice()
public static int getRandomInt(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
// chops a list into sublists of length L
public static <T> List<List<T>> choppedList(List<T> list, final int L) {
List<List<T>> parts = new ArrayList<List<T>>();
final int N = list.size();
for (int i = 0; i < N; i += L) {
parts.add(new ArrayList<T>(
list.subList(i, Math.min(N, i + L)))
);
}
return parts;
}
/**
* Resizes an image using a Graphics2D object backed by a BufferedImage.
* @param src - source image to scale
* @param w - desired width
* @param h - desired height
* @return - the new resized image
*/
public static BufferedImage getScaledImage(BufferedImage src, int w, int h) {
int finalw = w;
int finalh = h;
double factor = 1.0d;
if(src.getWidth() > src.getHeight()){
factor = ((double)src.getHeight()/(double)src.getWidth());
finalh = (int)(finalw * factor);
}else{
factor = ((double)src.getWidth()/(double)src.getHeight());
finalw = (int)(finalh * factor);
}
BufferedImage resizedImg = new BufferedImage(finalw, finalh, BufferedImage.TRANSLUCENT);
Graphics2D g = resizedImg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(src, 0, 0, finalw, finalh, null);
g.dispose();
return resizedImg;
}
// TODO Change setRGB and getRGB, it is now too slow :(
// @see http://stackoverflow.com/questions/8218072/faster-way-to-extract-histogram-from-an-image
public static BufferedImage imageAbsoluteDifference(BufferedImage img1, BufferedImage img2) {
BufferedImage result = new BufferedImage(img1.getWidth(), img1.getHeight(), BufferedImage.TYPE_INT_RGB);
int width1 = img1.getWidth();
int width2 = img2.getWidth();
int height1 = img1.getHeight();
int height2 = img2.getHeight();
if ((width1 != width2) || (height1 != height2)) {
System.err.println("Error: Images dimensions are not same");
}
for (int y = 0; y < height1; y++) {
for (int x = 0; x < width1; x++) {
int argb0 = img1.getRGB(x, y);
int argb1 = img2.getRGB(x, y);
int a0 = (argb0 >> 24) & 0xFF;
int r0 = (argb0 >> 16) & 0xFF;
int g0 = (argb0 >> 8) & 0xFF;
int b0 = (argb0 ) & 0xFF;
int a1 = (argb1 >> 24) & 0xFF;
int r1 = (argb1 >> 16) & 0xFF;
int g1 = (argb1 >> 8) & 0xFF;
int b1 = (argb1 ) & 0xFF;
int aDiff = Math.abs(a1 - a0);
int rDiff = Math.abs(r1 - r0);
int gDiff = Math.abs(g1 - g0);
int bDiff = Math.abs(b1 - b0);
int diff =
(aDiff << 24) | (rDiff << 16) | (gDiff << 8) | bDiff;
result.setRGB(x, y, diff);
}
}
return result;
}
// Return an ArrayList containing histogram values for separate R, G, B channels
public static int[] imageHistogram(BufferedImage input) {
int[] rhistogram = new int[256];
int[] ghistogram = new int[256];
int[] bhistogram = new int[256];
for(int i=0; i<rhistogram.length; i++)
rhistogram[i] = ghistogram[i] = bhistogram[i] = 0;
for(int j=0; j<input.getHeight(); j++) {
for(int i=0; i<input.getWidth(); i++) {
int rgb = input.getRGB(i, j);
int r = (rgb >> 16) & 0xFF;
int g = (rgb >> 8) & 0xFF;
int b = (rgb ) & 0xFF;
// Increase the values of colors
rhistogram[r]++; ghistogram[g]++; bhistogram[b]++;
}
}
return joinArray(rhistogram, ghistogram, bhistogram);
}
/*
* This method merges any number of arrays of any count.
*/
private static int[] joinArray(int[]... arrays) {
int length = 0;
for (int[] array : arrays) {
length += array.length;
}
final int[] result = new int[length];
int offset = 0;
for (int[] array : arrays) {
System.arraycopy(array, 0, result, offset, array.length);
offset += array.length;
}
return result;
}
/*
* It reads all the pixels into an array at the beginning,
* thus requiring only one for-loop.
* Also, it directly shifts the blue byte to the alpha (of the mask color).
* Like the other methods, it assumes both images have the same dimensions.
*/
public static BufferedImage applyGrayscaleMaskToAlpha(BufferedImage image, BufferedImage mask) {
BufferedImage result = new BufferedImage(image.getWidth(), image.getHeight(), image.getType());
int width = image.getWidth();
int height = image.getHeight();
int[] imagePixels = image.getRGB(0, 0, width, height, null, 0, width);
int[] maskPixels = mask.getRGB(0, 0, width, height, null, 0, width);
for (int i = 0; i < imagePixels.length; i++) {
int color = imagePixels[i] & 0x00ffffff; // Mask preexisting alpha
int alpha = maskPixels[i] << 24; // Shift blue to alpha
imagePixels[i] = color | alpha;
}
result.setRGB(0, 0, width, height, imagePixels, 0, width);
return result;
}
/*
* Converts the source image into negative
*/
public static BufferedImage createNegativeImage(BufferedImage original) {
BufferedImage negativImage = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
//get image width and height
int width = original.getWidth();
int height = original.getHeight();
//convert to negative
for(int y = 0; y < height; y++) for(int x = 0; x < width; x++) {
int p = original.getRGB(x,y);
int a = (p>>24)&0xff;
int r = (p>>16)&0xff;
int g = (p>>8)&0xff;
int b = p&0xff;
//subtract RGB from 255
r = 255 - r;
g = 255 - g;
b = 255 - b;
//set new RGB value
p = (a<<24) | (r<<16) | (g<<8) | b;
negativImage.setRGB(x, y, p);
}
return negativImage;
}
/*
* Rotates an image
*/
public static BufferedImage rotateImage(BufferedImage img, double angle) {
double sin = Math.abs(Math.sin(Math.toRadians(angle))), cos = Math
.abs(Math.cos(Math.toRadians(angle)));
int w = img.getWidth(null), h = img.getHeight(null);
int neww = (int) Math.floor(w * cos + h * sin), newh = (int) Math
.floor(h * cos + w * sin);
BufferedImage bimg = new BufferedImage(neww, newh,
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = bimg.createGraphics();
g.translate((neww - w) / 2, (newh - h) / 2);
g.rotate(Math.toRadians(angle), w / 2, h / 2);
g.drawRenderedImage(img, null);
g.dispose();
return bimg;
}
public static BufferedImage makeImageTranslucent(BufferedImage source, float alpha) {
BufferedImage target = new BufferedImage(source.getWidth(),
source.getHeight(), java.awt.Transparency.TRANSLUCENT);
// Get the images graphics
Graphics2D g = target.createGraphics();
// Set the Graphics composite to Alpha
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
// Draw the image into the prepared reciver image
g.drawImage(source, null, 0, 0);
// let go of all system resources in this Graphics
g.dispose();
// Return the image
return target;
}
public static BufferedImage deepCopy(BufferedImage bi) {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(bi.getRaster().createCompatibleWritableRaster());
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
}
|
92415893f9b8e17b35eb46825768cd7f3d47f552 | 193 | java | Java | src/main/java/com/app/ca/product/tracker/service/product/ProductRemoval.java | AsuSoftware/MarketX-Back-end | bebbf6e513884fa72846eae541bd6a62ad2b9201 | [
"MIT"
] | null | null | null | src/main/java/com/app/ca/product/tracker/service/product/ProductRemoval.java | AsuSoftware/MarketX-Back-end | bebbf6e513884fa72846eae541bd6a62ad2b9201 | [
"MIT"
] | null | null | null | src/main/java/com/app/ca/product/tracker/service/product/ProductRemoval.java | AsuSoftware/MarketX-Back-end | bebbf6e513884fa72846eae541bd6a62ad2b9201 | [
"MIT"
] | null | null | null | 21.444444 | 55 | 0.756477 | 1,001,867 | package com.app.ca.product.tracker.service.product;
import java.util.UUID;
/** product-tracker Created by Catalin on 10/31/2020 */
public interface ProductRemoval {
void delete(UUID id);
}
|
9241589be55f35b4a50878f1e4ec2864718581bb | 1,276 | java | Java | session-support/src/main/java/com/joindata/inf/common/support/session/ConfigHub.java | bizwell/Pangu | fbc6ced0b39c718b2a2048a133b1a55deb04e48c | [
"Apache-2.0"
] | 7 | 2018-02-28T05:46:38.000Z | 2021-12-09T08:50:40.000Z | session-support/src/main/java/com/joindata/inf/common/support/session/ConfigHub.java | Rayeee/Pangu | c1bf7f30414e78b26ba96e2ec270a068e6ed3c8f | [
"Apache-2.0"
] | null | null | null | session-support/src/main/java/com/joindata/inf/common/support/session/ConfigHub.java | Rayeee/Pangu | c1bf7f30414e78b26ba96e2ec270a068e6ed3c8f | [
"Apache-2.0"
] | 7 | 2018-02-28T05:36:07.000Z | 2021-07-05T09:45:43.000Z | 37.676471 | 190 | 0.794692 | 1,001,868 | package com.joindata.inf.common.support.session;
import javax.servlet.annotation.WebFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;
import org.springframework.web.filter.DelegatingFilterProxy;
import com.joindata.inf.common.basic.annotation.FilterConfig;
import com.joindata.inf.common.basic.annotation.WebAppFilterItem;
import com.joindata.inf.common.basic.stereotype.AbstractConfigHub;
import com.joindata.inf.common.support.disconf.EnableDisconf;
import com.joindata.inf.common.support.redis.EnableRedis;
import com.joindata.inf.common.support.session.bootconfig.SpringSessionConfig;
/**
* HTTP 会话支持配置器
*
* @author <a href="mailto:ychag@example.com">宋翔</a>
* @date Dec 19, 2016 3:38:12 PM
*/
@Configuration
@Import(SpringSessionConfig.class)
@FilterConfig({@WebAppFilterItem(filter = DelegatingFilterProxy.class, config = @WebFilter(filterName = AbstractHttpSessionApplicationInitializer.DEFAULT_FILTER_NAME, urlPatterns = "/*"))})
@EnableDisconf
@EnableRedis
public class ConfigHub extends AbstractConfigHub
{
@Override
protected void check()
{
}
} |
924158ad85ba9eae9fac781ae420ed2e3af41ffb | 1,027 | java | Java | testcase-writer/generators/src/main/java/ch/skymarshall/tcwriter/generators/model/persistence/IModelPersister.java | sebastiencaille/sky-lib | b8d01c5b90e1f234d1a202b9313e3241656a0275 | [
"BSD-3-Clause"
] | null | null | null | testcase-writer/generators/src/main/java/ch/skymarshall/tcwriter/generators/model/persistence/IModelPersister.java | sebastiencaille/sky-lib | b8d01c5b90e1f234d1a202b9313e3241656a0275 | [
"BSD-3-Clause"
] | 2 | 2020-02-07T21:02:03.000Z | 2020-12-17T21:30:19.000Z | testcase-writer/generators/src/main/java/ch/skymarshall/tcwriter/generators/model/persistence/IModelPersister.java | sebastiencaille/sky-lib | b8d01c5b90e1f234d1a202b9313e3241656a0275 | [
"BSD-3-Clause"
] | null | null | null | 29.342857 | 92 | 0.828627 | 1,001,869 | package ch.skymarshall.tcwriter.generators.model.persistence;
import java.io.IOException;
import java.nio.file.Path;
import ch.skymarshall.tcwriter.generators.GeneratorConfig;
import ch.skymarshall.tcwriter.generators.model.testapi.TestDictionary;
import ch.skymarshall.tcwriter.generators.model.testcase.TestCase;
/**
* Methods used to load/save the configurations, models and test cases
*
* @author scaille
*
*/
public interface IModelPersister {
void setConfiguration(GeneratorConfig config);
TestDictionary readTestDictionary() throws IOException;
void writeTestDictionary(TestDictionary tm) throws IOException;
void writeTestDictionary(Path target, TestDictionary model) throws IOException;
TestCase readTestCase(String identifier, TestDictionary testDictionary) throws IOException;
void writeTestCase(String identifier, TestCase tc) throws IOException;
GeneratorConfig readConfiguration(String identifier) throws IOException;
void writeConfiguration(GeneratorConfig config) throws IOException;
}
|
92415985f930c3f108bff00dac2cc7269dccae64 | 106 | java | Java | src/main/java/com/flowyun/cornerstone/db/mybatis/mapper/BasicMapper.java | stoneforever/econagebatis | d732c1896a35f7d39ab242abe6cfed728b8b4c28 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/flowyun/cornerstone/db/mybatis/mapper/BasicMapper.java | stoneforever/econagebatis | d732c1896a35f7d39ab242abe6cfed728b8b4c28 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/flowyun/cornerstone/db/mybatis/mapper/BasicMapper.java | stoneforever/econagebatis | d732c1896a35f7d39ab242abe6cfed728b8b4c28 | [
"Apache-2.0"
] | null | null | null | 13.25 | 50 | 0.735849 | 1,001,870 | package com.flowyun.cornerstone.db.mybatis.mapper;
/*
* 方便扫描时,指定接口
* */
public interface BasicMapper {
}
|
92415a274c73b5faa33bb9e9e4f62d55f923fc19 | 4,530 | java | Java | src/main/java/com/radioctivetacoo/worldsalad/world/biomes/AcidOceanBiome.java | RealYusufIsmail/WorldSalad | 88376de55838dd8c18895ae967e3330699841e3a | [
"MIT"
] | null | null | null | src/main/java/com/radioctivetacoo/worldsalad/world/biomes/AcidOceanBiome.java | RealYusufIsmail/WorldSalad | 88376de55838dd8c18895ae967e3330699841e3a | [
"MIT"
] | 1 | 2021-07-27T15:13:54.000Z | 2021-07-27T15:13:54.000Z | src/main/java/com/radioctivetacoo/worldsalad/world/biomes/AcidOceanBiome.java | RealYusufIsmail/WorldSalad | 88376de55838dd8c18895ae967e3330699841e3a | [
"MIT"
] | 1 | 2021-07-27T14:24:32.000Z | 2021-07-27T14:24:32.000Z | 55.243902 | 221 | 0.819868 | 1,001,871 | package com.radioctivetacoo.worldsalad.world.biomes;
import com.radioctivetacoo.worldsalad.init.BlockInit;
import com.radioctivetacoo.worldsalad.world.gen.carvers.HyphaeAcidOceanCarver;
import net.minecraft.block.BlockState;
import net.minecraft.block.Blocks;
import net.minecraft.block.pattern.BlockMatcher;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.blockplacer.DoublePlantBlockPlacer;
import net.minecraft.world.gen.blockplacer.SimpleBlockPlacer;
import net.minecraft.world.gen.blockstateprovider.SimpleBlockStateProvider;
import net.minecraft.world.gen.feature.BlockClusterFeatureConfig;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.feature.ProbabilityConfig;
import net.minecraft.world.gen.placement.ConfiguredPlacement;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.placement.FrequencyConfig;
import net.minecraft.world.gen.placement.HeightWithChanceConfig;
import net.minecraft.world.gen.placement.Placement;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraftforge.api.distmarker.OnlyIn;
public class AcidOceanBiome extends Biome {
@Override
@OnlyIn(Dist.CLIENT)
public int getSkyColor() {
return 0x26144f;
}
@Override
public float getSpawningChance() {
return 1F;
}
private static final BlockState TOADSTOOLBLOCK = BlockInit.TOADSTOOL.get().getDefaultState();
private static final BlockState FUNGRASS = BlockInit.FUNGRASS.get().getDefaultState();
private static final BlockState TALL_FUNGRASS = BlockInit.TALL_FUNGRASS.get().getDefaultState();
public static final BlockClusterFeatureConfig TALL_FUNGRASS_CONFIG = (new BlockClusterFeatureConfig.Builder(new SimpleBlockStateProvider(TALL_FUNGRASS), new DoublePlantBlockPlacer())).tries(164).func_227317_b_().build();
BlockClusterFeatureConfig TOADSTOOL = (new BlockClusterFeatureConfig.Builder(new SimpleBlockStateProvider(TOADSTOOLBLOCK), new SimpleBlockPlacer())).tries(12).func_227317_b_().build();
BlockClusterFeatureConfig FUNGRASS_CONFIG = (new BlockClusterFeatureConfig.Builder(new SimpleBlockStateProvider(FUNGRASS), new SimpleBlockPlacer())).tries(32).build();
public AcidOceanBiome(Builder biomeBuilder) {
super(biomeBuilder);
this.addCarver(GenerationStage.Carving.LIQUID, Biome.createCarver(
new HyphaeAcidOceanCarver(ProbabilityConfig::deserialize), new ProbabilityConfig(0.2f)));
@SuppressWarnings("rawtypes")
ConfiguredPlacement customConfig4 = Placement.COUNT_RANGE.configure(new CountRangeConfig(5, 30, 5, 50));
this.addFeature(GenerationStage.Decoration.UNDERGROUND_ORES, Feature.ORE.withConfiguration(new OreFeatureConfig(
OreFeatureConfig.FillerBlockType.create("MUD", null, new BlockMatcher(BlockInit.MUD.get())),
BlockInit.GLOWING_CORAL.get().getDefaultState(), 40)).withPlacement(customConfig4));
this.addFeature(GenerationStage.Decoration.VEGETAL_DECORATION, Feature.RANDOM_PATCH.withConfiguration(TOADSTOOL).withPlacement(Placement.COUNT_CHANCE_HEIGHTMAP.configure(new HeightWithChanceConfig(9, 0.37F))));
this.addFeature(GenerationStage.Decoration.VEGETAL_DECORATION,
Feature.RANDOM_PATCH.withConfiguration(FUNGRASS_CONFIG)
.withPlacement(Placement.COUNT_HEIGHTMAP_DOUBLE.configure(new FrequencyConfig(5))));
this.addFeature(GenerationStage.Decoration.VEGETAL_DECORATION,
Feature.RANDOM_PATCH.withConfiguration(TALL_FUNGRASS_CONFIG)
.withPlacement(Placement.COUNT_HEIGHTMAP_32.configure(new FrequencyConfig(7))));
@SuppressWarnings("rawtypes")
ConfiguredPlacement customConfig0 = Placement.COUNT_RANGE.configure(new CountRangeConfig(150, 10, 5, 230));
this.addFeature(GenerationStage.Decoration.UNDERGROUND_ORES,
Feature.ORE.withConfiguration(new OreFeatureConfig(
OreFeatureConfig.FillerBlockType.create("DIRT", null,
new BlockMatcher(Blocks.DIRT)),
BlockInit.FUNGAL_DIRT.get().getDefaultState(), 100)).withPlacement(customConfig0));
@SuppressWarnings("rawtypes")
ConfiguredPlacement customConfigIslands = Placement.COUNT_RANGE.configure(new CountRangeConfig(150, 180, 0, 250));
this.addFeature(GenerationStage.Decoration.UNDERGROUND_ORES,
Feature.ORE.withConfiguration(new OreFeatureConfig(
OreFeatureConfig.FillerBlockType.create("AIR", null,
new BlockMatcher(Blocks.AIR)),
BlockInit.FUNGAL_DIRT.get().getDefaultState(), 100)).withPlacement(customConfigIslands));
}
}
|
92415a2b40c7cbcc2eca62334935d025ad77bd57 | 434 | java | Java | netty/netty-simple/src/main/java/my/suveng/netty/learn/broadcast/BroadcastClientHandler.java | suveng/demo | 0691274d0e0c27942d136c70e33946425be0c7df | [
"MIT"
] | 1 | 2020-08-17T09:54:32.000Z | 2020-08-17T09:54:32.000Z | netty/netty-simple/src/main/java/my/suveng/netty/learn/broadcast/BroadcastClientHandler.java | suveng/demo | 0691274d0e0c27942d136c70e33946425be0c7df | [
"MIT"
] | 46 | 2019-12-19T02:23:47.000Z | 2021-08-09T20:46:08.000Z | netty/netty-simple/src/main/java/my/suveng/netty/learn/broadcast/BroadcastClientHandler.java | suveng/demo | 0691274d0e0c27942d136c70e33946425be0c7df | [
"MIT"
] | null | null | null | 22.842105 | 89 | 0.741935 | 1,001,872 | package my.suveng.netty.learn.broadcast;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
/**
*
* @author suwenguang
*
* @version 1.0.0
**/
public class BroadcastClientHandler extends SimpleChannelInboundHandler<String> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
System.out.println(msg + "\n");
}
}
|
92415a7e34c4c684fe383b300219ac39b6b4368d | 1,716 | java | Java | core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSetting.java | yanaspaula/rdf4j | e75f8940c48caf9847dd775fd6a67866dc9b9dcd | [
"BSD-3-Clause"
] | 312 | 2016-01-14T20:04:24.000Z | 2022-03-30T22:21:41.000Z | core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSetting.java | yanaspaula/rdf4j | e75f8940c48caf9847dd775fd6a67866dc9b9dcd | [
"BSD-3-Clause"
] | 2,611 | 2016-01-18T22:32:22.000Z | 2022-03-31T17:38:43.000Z | core/rio/api/src/main/java/org/eclipse/rdf4j/rio/helpers/BooleanRioSetting.java | yanaspaula/rdf4j | e75f8940c48caf9847dd775fd6a67866dc9b9dcd | [
"BSD-3-Clause"
] | 186 | 2016-01-14T21:18:37.000Z | 2022-03-22T12:32:33.000Z | 38.133333 | 119 | 0.667832 | 1,001,873 | /*******************************************************************************
* Copyright (c) 2018 Eclipse RDF4J contributors.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Distribution License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*******************************************************************************/
package org.eclipse.rdf4j.rio.helpers;
import org.eclipse.rdf4j.rio.RioSetting;
/**
* A {@link RioSetting} with a {@link Boolean} value. The given default for the setting can be overridden by means of a
* System property with a name equal to the setting key, and a string value of "true" or "false" (ignoring case).
*
* @author Jeen Broekstra
*/
public class BooleanRioSetting extends AbstractRioSetting<Boolean> {
private static final long serialVersionUID = 2732349679294063815L;
/**
* Creates a new boolean {@link RioSetting}.
*
* @param key A unique key to use for this setting.
* @param description A short human-readable description for this setting.
* @param defaultValue An immutable value specifying the default for this setting.
*/
public BooleanRioSetting(String key, String description, Boolean defaultValue) {
super(key, description, defaultValue);
}
/**
* Converts a String to a Boolean
*
* @return a Boolean representing the supplied string value. Iff the string value is "true" (ignoring case), the
* returned Boolean will be {@code true}, otherwise {@code false}.
*/
@Override
public Boolean convert(String stringValue) {
return Boolean.valueOf(stringValue);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.