repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
fnetworks/mcrconapi | src/main/java/org/fnet/mcrconapi/cli/CommandLineMain.java | 5397 | /*
* Copyright (c) 2021 Felix Solcher
* Licensed under the terms of the MIT license.
*/
package org.fnet.mcrconapi.cli;
import java.io.Console;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import org.fnet.mcrconapi.AuthenticationException;
import org.fnet.mcrconapi.RConClient;
public class CommandLineMain {
public static void main(String[] args) {
Map<String, String> arguments = parseArguments(args);
if (arguments.containsKey("help") || arguments.containsKey("h")) {
printVersion();
printUsage();
return;
} else if (arguments.containsKey("version") || arguments.containsKey("-v")) {
printVersion();
return;
}
String host = arguments.containsKey("host") ? arguments.get("host") : arguments.get("a");
boolean interactive = !arguments.containsKey("noninteractive") && !arguments.containsKey("n");
String password = arguments.containsKey("login") ? arguments.get("login") : arguments.get("l");
String command = arguments.containsKey("command") ? arguments.get("command") : arguments.get("c");
try (Scanner sc = new Scanner(System.in)) {
if (host == null) {
if (interactive) {
System.out.println("Enter host address: ");
host = sc.nextLine();
} else {
System.err.println("Need host address");
System.exit(1);
}
}
if (password == null) {
if (interactive) {
System.out.println("Enter password: ");
Console console = System.console();
if (console != null) {
password = new String(console.readPassword());
} else {
password = sc.nextLine();
}
} else {
System.err.println("Need password");
System.exit(1);
}
}
if (command == null) {
if (interactive) {
System.out.println("Enter command to send: ");
command = sc.nextLine();
} else {
System.err.println("Need command");
System.exit(1);
}
}
}
RConClient client;
try {
client = new RConClient(host);
} catch (IOException e) {
System.err.println("An exception occured while connecting to the server: ");
e.printStackTrace(System.err);
System.exit(1);
return;
}
try {
client.authenticate(password);
} catch (IOException | AuthenticationException e) {
System.err.println("An exception occured while authenticating: ");
e.printStackTrace(System.err);
try {
client.close();
} catch (IOException ex) {
System.err.println("Additionaly, an exception occured while closing the client: ");
ex.printStackTrace(System.err);
System.exit(1);
return;
}
System.exit(1);
return;
}
try {
System.out.println(client.sendCommand(command));
} catch (AuthenticationException | IOException e) {
System.err.println("An exception occured while sending command: ");
e.printStackTrace(System.err);
try {
client.close();
} catch (IOException ex) {
System.err.println("Additionaly, an exception occured while closing the client: ");
ex.printStackTrace(System.err);
System.exit(1);
return;
}
System.exit(1);
return;
}
try {
client.close();
} catch (IOException e) {
System.err.println("An exception occured while closing the client: ");
e.printStackTrace(System.err);
System.exit(1);
}
}
public static Map<String, String> parseArguments(String[] args) {
final Map<String, String> map = new HashMap<>();
for (int i = 0; i < args.length; i++) {
if (args[i].startsWith("--")) {
if (args.length > i + 1 && !args[i + 1].startsWith("--")) {
map.put(args[i].substring(2), args[i + 1]);
} else {
map.put(args[i].substring(2), null);
}
} else if (args[i].startsWith("-")) {
if (args.length > i + 1 && !args[i + 1].startsWith("-")) {
String keyname = args[i].substring(1);
if (keyname.length() > 1) {
for (int j = 0; j < keyname.length() - 1; j++) {
map.put(keyname.substring(j, j + 1), null);
}
map.put(keyname.substring(keyname.length() - 1, keyname.length()), args[i + 1]);
} else {
map.put(keyname, args[i + 1]);
}
} else {
String keyname = args[i].substring(1);
if (keyname.length() > 1) {
for (int j = 0; j < keyname.length(); j++) {
map.put(keyname.substring(j, j + 1), null);
}
map.put(keyname.substring(keyname.length() - 1, keyname.length()), null);
} else {
map.put(keyname, null);
}
}
}
}
return map;
}
public static void printVersion() {
System.out.println("MCRCONAPI v" + RConClient.API_VERSION);
System.out.println("Copyright (c) 2021 fnetworks");
}
public static void printUsage() {
System.out.println("Parameters: ");
System.out.println(" --host | -a <address> : Specify the host address");
System.out.println(" --login | -l <password> : Login at the server with the given password");
System.out.println(" --help | -h : Show this help message");
System.out.println(" --version | -v : Prints version information");
System.out.println(" --noninteractive | -n : "
+ "Non-Interactive mode (exit instead of asking for missing information and commands, "
+ "default is interactive mode)");
System.out.println(" --command | -c <command> : "
+ "Command that should be sent to the server (noninteractive mode)");
}
}
| mit |
trentech/ProjectPortals | src/main/java/com/gmail/trentech/pjp/Main.java | 10662 | package com.gmail.trentech.pjp;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandMapping;
import org.spongepowered.api.config.ConfigDir;
import org.spongepowered.api.data.DataRegistration;
import org.spongepowered.api.event.Listener;
import org.spongepowered.api.event.game.GameReloadEvent;
import org.spongepowered.api.event.game.state.GameInitializationEvent;
import org.spongepowered.api.event.game.state.GamePreInitializationEvent;
import org.spongepowered.api.event.game.state.GameStartedServerEvent;
import org.spongepowered.api.plugin.Dependency;
import org.spongepowered.api.plugin.Plugin;
import org.spongepowered.api.plugin.PluginContainer;
import com.gmail.trentech.pjc.core.ConfigManager;
import com.gmail.trentech.pjp.commands.CMDBack;
import com.gmail.trentech.pjp.data.Keys;
import com.gmail.trentech.pjp.data.immutable.ImmutableBedData;
import com.gmail.trentech.pjp.data.immutable.ImmutableHomeData;
import com.gmail.trentech.pjp.data.immutable.ImmutableLastLocationData;
import com.gmail.trentech.pjp.data.immutable.ImmutableSignPortalData;
import com.gmail.trentech.pjp.data.mutable.BedData;
import com.gmail.trentech.pjp.data.mutable.HomeData;
import com.gmail.trentech.pjp.data.mutable.LastLocationData;
import com.gmail.trentech.pjp.data.mutable.SignPortalData;
import com.gmail.trentech.pjp.effects.Effect;
import com.gmail.trentech.pjp.init.Commands;
import com.gmail.trentech.pjp.init.Common;
import com.gmail.trentech.pjp.listeners.ButtonListener;
import com.gmail.trentech.pjp.listeners.DoorListener;
import com.gmail.trentech.pjp.listeners.LeverListener;
import com.gmail.trentech.pjp.listeners.PlateListener;
import com.gmail.trentech.pjp.listeners.PortalListener;
import com.gmail.trentech.pjp.listeners.SignListener;
import com.gmail.trentech.pjp.listeners.TeleportListener;
import com.gmail.trentech.pjp.portal.Portal;
import com.gmail.trentech.pjp.portal.PortalService;
import com.gmail.trentech.pjp.portal.features.Command;
import com.gmail.trentech.pjp.portal.features.Coordinate;
import com.gmail.trentech.pjp.portal.features.Properties;
import com.gmail.trentech.pjp.utils.Resource;
import com.gmail.trentech.pjp.utils.Timings;
import com.google.inject.Inject;
import ninja.leaping.configurate.ConfigurationNode;
@Plugin(id = Resource.ID, name = Resource.NAME, version = Resource.VERSION, description = Resource.DESCRIPTION, authors = Resource.AUTHOR, url = Resource.URL, dependencies = { @Dependency(id = "pjc", optional = false) })
public class Main {
@Inject
@ConfigDir(sharedRoot = false)
private Path path;
@Inject
private Logger log;
private static PluginContainer plugin;
private static Main instance;
@Listener
public void onPreInitializationEvent(GamePreInitializationEvent event) {
plugin = Sponge.getPluginManager().getPlugin(Resource.ID).get();
instance = this;
try {
Files.createDirectories(path);
} catch (IOException e) {
e.printStackTrace();
}
new Keys();
DataRegistration.builder().dataClass(BedData.class).immutableClass(ImmutableBedData.class).builder(new BedData.Builder()).name("bed")
.id("pjp_bed").build();
DataRegistration.builder().dataClass(LastLocationData.class).immutableClass(ImmutableLastLocationData.class).builder(new LastLocationData.Builder()).name("last_location")
.id("pjp_last_location").build();
}
@Listener
public void onInitialization(GameInitializationEvent event) {
Common.initConfig();
ConfigurationNode config = ConfigManager.get(getPlugin()).getConfig();
Timings timings = new Timings();
Sponge.getDataManager().registerBuilder(Coordinate.class, new Coordinate.Builder());
Sponge.getDataManager().registerBuilder(Command.class, new Command.Builder());
Sponge.getDataManager().registerBuilder(Properties.class, new Properties.Builder());
Sponge.getDataManager().registerBuilder(Effect.class, new Effect.Builder());
Sponge.getDataManager().registerBuilder(Portal.Local.class, new Portal.Local.Builder());
Sponge.getDataManager().registerBuilder(Portal.Server.class, new Portal.Server.Builder());
Sponge.getEventManager().registerListeners(this, new TeleportListener(timings));
Sponge.getServiceManager().setProvider(getPlugin(), PortalService.class, new PortalService());
Common.initHelp();
ConfigurationNode modules = config.getNode("settings", "modules");
if (modules.getNode("back").getBoolean()) {
Sponge.getCommandManager().register(this, new CMDBack().cmdBack, "back");
}
if (modules.getNode("buttons").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new ButtonListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdButton, "button", "b");
getLog().info("Button module activated");
}
if (modules.getNode("doors").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new DoorListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdDoor, "door", "d");
getLog().info("Door module activated");
}
if (modules.getNode("plates").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new PlateListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdPlate, "plate", "pp");
getLog().info("Pressure plate module activated");
}
if (modules.getNode("signs").getBoolean()) {
DataRegistration<SignPortalData, ImmutableSignPortalData> signData = DataRegistration.builder().dataClass(SignPortalData.class).immutableClass(ImmutableSignPortalData.class)
.builder(new SignPortalData.Builder()).name("sign").id("pjp_sign").build();
Sponge.getDataManager().registerLegacyManipulatorIds("com.gmail.trentech.pjp.data.mutable.SignPortalData", signData);
Sponge.getEventManager().registerListeners(this, new SignListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdSign, "sign", "s");
getLog().info("Sign module activated");
}
if (modules.getNode("levers").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new LeverListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdLever, "lever", "l");
getLog().info("Lever module activated");
}
if (modules.getNode("portals").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new PortalListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdPortal, "portal", "p");
getLog().info("Portal module activated");
}
if (modules.getNode("homes").getBoolean()) {
DataRegistration<HomeData, ImmutableHomeData> homeData = DataRegistration.builder().dataClass(HomeData.class).immutableClass(ImmutableHomeData.class)
.builder(new HomeData.Builder()).name("home").id("pjp_home").build();
Sponge.getDataManager().registerLegacyManipulatorIds("com.gmail.trentech.pjp.data.mutable.HomeData", homeData);
Sponge.getCommandManager().register(this, new Commands().cmdHome, "home", "h");
getLog().info("Home module activated");
}
if (modules.getNode("warps").getBoolean()) {
Sponge.getCommandManager().register(this, new Commands().cmdWarp, "warp", "w");
getLog().info("Warp module activated");
}
Common.initData();
}
@Listener
public void onStartedServer(GameStartedServerEvent event) {
Sponge.getServiceManager().provide(PortalService.class).get().init();
}
@Listener
public void onReloadEvent(GameReloadEvent event) {
Sponge.getEventManager().unregisterPluginListeners(getPlugin());
for (CommandMapping mapping : Sponge.getCommandManager().getOwnedBy(getPlugin())) {
Sponge.getCommandManager().removeMapping(mapping);
}
Common.initConfig();
ConfigurationNode config = ConfigManager.get(getPlugin()).getConfig();
Timings timings = new Timings();
Sponge.getEventManager().registerListeners(this, new TeleportListener(timings));
ConfigurationNode modules = config.getNode("settings", "modules");
if (modules.getNode("back").getBoolean()) {
Sponge.getCommandManager().register(this, new CMDBack().cmdBack, "back");
}
if (modules.getNode("portals").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new PortalListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdPortal, "portal", "p");
getLog().info("Portal module activated");
}
if (modules.getNode("buttons").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new ButtonListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdButton, "button", "b");
getLog().info("Button module activated");
}
if (modules.getNode("doors").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new DoorListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdDoor, "door", "d");
getLog().info("Door module activated");
}
if (modules.getNode("plates").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new PlateListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdPlate, "plate", "pp");
getLog().info("Pressure plate module activated");
}
if (modules.getNode("signs").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new SignListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdSign, "sign", "s");
getLog().info("Sign module activated");
}
if (modules.getNode("levers").getBoolean()) {
Sponge.getEventManager().registerListeners(this, new LeverListener(timings));
Sponge.getCommandManager().register(this, new Commands().cmdLever, "lever", "l");
getLog().info("Lever module activated");
}
if (modules.getNode("homes").getBoolean()) {
Sponge.getCommandManager().register(this, new Commands().cmdHome, "home", "h");
getLog().info("Home module activated");
}
if (modules.getNode("warps").getBoolean()) {
Sponge.getCommandManager().register(this, new Commands().cmdWarp, "warp", "w");
getLog().info("Warp module activated");
}
Sponge.getServiceManager().provide(PortalService.class).get().init();
}
public Logger getLog() {
return log;
}
public Path getPath() {
return path;
}
public static PluginContainer getPlugin() {
return plugin;
}
public static Main instance() {
return instance;
}
} | mit |
osklyarenko/test-dsl-provider | src/test/java/morning/dsl/testclasses/Test4.java | 190 | package morning.dsl.testclasses;
import org.junit.Test;
/**
* Created by osklyarenko on 3/9/15.
*/
public class Test4 {
@Test
public void testName() throws Exception {
}
}
| mit |
DevMate/DevMateClientJava | src/main/java/com/devmate/pub/client/impl/CustomersQueryParams.java | 4660 | package com.devmate.pub.client.impl;
public class CustomersQueryParams {
private static final int DEFAULT_LIMIT = 10;
private static final int DEFAULT_OFFSET = 0;
private static final boolean DEFAULT_INCLUDE_LICENSE = false;
private String email;
private String firstName;
private String lastName;
private String company;
private String phone;
private String address;
private String key;
private String identifier;
private String invoice;
private Long orderId;
private Long activationId;
private int limit;
private int offset;
private boolean includeLicenses;
private CustomersQueryParams() {
this.limit = DEFAULT_LIMIT;
this.offset = DEFAULT_OFFSET;
this.includeLicenses = DEFAULT_INCLUDE_LICENSE;
}
public static CustomersQueryParams with() {
return new CustomersQueryParams();
}
public static CustomersQueryParams defaultParams() {
return new CustomersQueryParams();
}
public String getEmail() {
return email;
}
public CustomersQueryParams emailContains(String email) {
this.email = email;
return this;
}
public String getFirstName() {
return firstName;
}
public CustomersQueryParams firstNameContains(String firstName) {
this.firstName = firstName;
return this;
}
public String getLastName() {
return lastName;
}
public CustomersQueryParams lastNameContains(String lastName) {
this.lastName = lastName;
return this;
}
public String getCompany() {
return company;
}
public CustomersQueryParams companyContains(String company) {
this.company = company;
return this;
}
public String getPhone() {
return phone;
}
public CustomersQueryParams phoneContains(String phone) {
this.phone = phone;
return this;
}
public String getAddress() {
return address;
}
public CustomersQueryParams addressContains(String address) {
this.address = address;
return this;
}
public String getKey() {
return key;
}
public CustomersQueryParams key(String key) {
this.key = key;
return this;
}
public String getIdentifier() {
return identifier;
}
public CustomersQueryParams identifierContains(String identifier) {
this.identifier = identifier;
return this;
}
public String getInvoice() {
return invoice;
}
public CustomersQueryParams invoiceContains(String invoice) {
this.invoice = invoice;
return this;
}
public Long getOrderId() {
return orderId;
}
public CustomersQueryParams orderId(Long orderId) {
this.orderId = orderId;
return this;
}
public Long getActivationId() {
return activationId;
}
public CustomersQueryParams activationId(Long activationId) {
this.activationId = activationId;
return this;
}
public int getLimit() {
return limit;
}
public CustomersQueryParams limit(int limit) {
this.limit = limit;
return this;
}
public int getOffset() {
return offset;
}
public CustomersQueryParams offset(int offset) {
this.offset = offset;
return this;
}
public boolean includeLicenses() {
return includeLicenses;
}
public CustomersQueryParams includeLicenses(boolean includeLicenses) {
this.includeLicenses = includeLicenses;
return this;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("CustomersQueryParams{");
sb.append("email='").append(email).append('\'');
sb.append(", firstName='").append(firstName).append('\'');
sb.append(", lastName='").append(lastName).append('\'');
sb.append(", company='").append(company).append('\'');
sb.append(", phone='").append(phone).append('\'');
sb.append(", address='").append(address).append('\'');
sb.append(", key='").append(key).append('\'');
sb.append(", identifier='").append(identifier).append('\'');
sb.append(", invoice='").append(invoice).append('\'');
sb.append(", orderId=").append(orderId);
sb.append(", activationId=").append(activationId);
sb.append(", limit=").append(limit);
sb.append(", offset=").append(offset);
sb.append(", includeLicenses=").append(includeLicenses);
sb.append('}');
return sb.toString();
}
}
| mit |
abdullahallmehedi/augere | src/main/java/com/rhcloud/oldfish/augere/entity/User.java | 3652 | package com.rhcloud.oldfish.augere.entity;
import javax.persistence.*;
import java.sql.Date;
/**
* Created by hadi on 8/12/15.
*/
@Entity
public class User {
private int id;
private String email;
private String username;
private String password;
private String firstname;
private String lastname;
private Date dob;
private String salt;
private Role roleByRoleId;
@Id
@Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Basic
@Column(name = "email")
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Basic
@Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Basic
@Column(name = "password")
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Basic
@Column(name = "firstname")
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
@Basic
@Column(name = "lastname")
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
@Basic
@Column(name = "dob")
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
@Basic
@Column(name = "salt")
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (id != user.id) return false;
if (email != null ? !email.equals(user.email) : user.email != null) return false;
if (username != null ? !username.equals(user.username) : user.username != null) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false;
if (firstname != null ? !firstname.equals(user.firstname) : user.firstname != null) return false;
if (lastname != null ? !lastname.equals(user.lastname) : user.lastname != null) return false;
if (dob != null ? !dob.equals(user.dob) : user.dob != null) return false;
if (salt != null ? !salt.equals(user.salt) : user.salt != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (email != null ? email.hashCode() : 0);
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (firstname != null ? firstname.hashCode() : 0);
result = 31 * result + (lastname != null ? lastname.hashCode() : 0);
result = 31 * result + (dob != null ? dob.hashCode() : 0);
result = 31 * result + (salt != null ? salt.hashCode() : 0);
return result;
}
@ManyToOne
@JoinColumn(name = "role_id", referencedColumnName = "id", nullable = false)
public Role getRoleByRoleId() {
return roleByRoleId;
}
public void setRoleByRoleId(Role roleByRoleId) {
this.roleByRoleId = roleByRoleId;
}
}
| mit |
christianewillman/recursive-descent-calculator | src/test/java/ninja/willman/calculator/OperatorTest.java | 788 | package ninja.willman.calculator;
import static org.junit.Assert.*;
import org.junit.Test;
public class OperatorTest {
@Test
public void testParseOperator() {
assertEquals(Operator.parseOperator('+'), Operator.PLUS);
assertEquals(Operator.parseOperator('-'), Operator.MINUS);
assertEquals(Operator.parseOperator('/'), Operator.DIVIDE);
assertEquals(Operator.parseOperator('*'), Operator.MULTIPLY);
}
@Test
public void testIsOperator() {
assertTrue(Operator.isOperator('+'));
assertTrue(Operator.isOperator('-'));
assertTrue(Operator.isOperator('/'));
assertTrue(Operator.isOperator('*'));
assertFalse(Operator.isOperator('z'));
}
@Test(expected = IllegalArgumentException.class)
public void testParseInvalidOperator() {
Operator.parseOperator('z');
}
} | mit |
MatthijsKamstra/haxejava | 04lwjgl/code/lwjgl/org/lwjgl/opengles/EXTTextureCompressionS3TC.java | 1559 | /*
* Copyright LWJGL. All rights reserved.
* License terms: http://lwjgl.org/license.php
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opengles;
/**
* Native bindings to the <a href="https://www.khronos.org/registry/gles/extensions/EXT/texture_compression_s3tc.txt">EXT_texture_compression_s3tc</a> extension.
*
* <p>This extension provides additional texture compression functionality specific to S3's S3TC format (called DXTC in Microsoft's DirectX API), subject to
* all the requirements and limitations described by the extension GL_ARB_texture_compression.</p>
*
* <p>This extension supports DXT1, DXT3, and DXT5 texture compression formats. For the DXT1 image format, this specification supports an RGB-only mode and a
* special RGBA mode with single-bit "transparent" alpha.</p>
*/
public final class EXTTextureCompressionS3TC {
/**
* In extended OpenGL ES 2.0.25 these new tokens are accepted by the {@code internalformat} parameter of TexImage2D, CompressedTexImage2D and the
* {@code format} parameter of CompressedTexSubImage2D. In extended OpenGL ES 3.0.2 these new tokens are also accepted by the {@code internalformat}
* parameter of TexImage3D, CompressedTexImage3D, TexStorage2D, TexStorage3D and the {@code format} parameter of CompressedTexSubImage3D.
*/
public static final int
GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0,
GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83F1,
GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 0x83F2,
GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 0x83F3;
private EXTTextureCompressionS3TC() {}
} | mit |
SabreOSS/conf4j | conf4j-spring/src/test/java/com/sabre/oss/conf4j/spring/configscan/AbstractConfigurationScanTest.java | 1561 | /*
* MIT License
*
* Copyright 2017-2018 Sabre GLBL Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sabre.oss.conf4j.spring.configscan;
import com.sabre.oss.conf4j.spring.AbstractContextTest;
import com.sabre.oss.conf4j.spring.annotation.EnableConf4j;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@EnableConf4j
public abstract class AbstractConfigurationScanTest extends AbstractContextTest {
}
| mit |
atthehotcorner/coursework | prog-fund-java-COP3502/lab-quizzes/Quiz10.java | 1428 | /*
Abraham Yuen
1H38
Quiz 10
4/9/2013
*/
/* Problem 1
public int sum(int a[]) {
return sum(a, 0);
}
public int sum(int a[], int index) {
if (index > a.length - 1) {
return 0;
}
else {
return a[index] + sum(a, index + 1);
}
}
/* Problem 2
The base case is when the counter index is larger than the
length of the array, it returns 0.
The recursive case and step is when counter index is smaller than
the length of the array, it returns the number at the index added
to the called method with index + 1.
If the index is less than the array length, it moves on to adding
the next number, else it returns 0. When it reaches the base case
it adds all the numbers together.
/* Problem 3
public boolean greaterThan(int a[], int value) {
return greaterThan(a, value, 0);
}
public boolean greaterThan(int a[], int value, int index) {
if (index > a.length - 1) {
return true;
}
else if (a[index] > value) {
return greaterThan(a, value, index + 1);
}
else {
return false;
}
}
/* Problem 4
The base case is when the counter index is larger than the
length of the array, it returns true.
The recursive case and step is when the number in the array is
greater than the value, it calls the method again while increasing
the index.
If the value is greater than the number, it moves on to the next
number, else it returns false. Otherwise, when it reaches the end
of the array, it returns true.
*/
| mit |
kmchugh/Goliath.Graphics | src/Goliath/Graphics/Constants/Position.java | 2636 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Goliath.Graphics.Constants;
/**
*
* @author kenmchugh
*/
public final class Position extends Goliath.DynamicEnum
{
protected Position(String tcValue)
{
super(tcValue);
}
private static Position g_oTOPLEFT;
public static Position TOP_LEFT()
{
if (g_oTOPLEFT == null)
{
g_oTOPLEFT = createEnumeration(Position.class, "TOPLEFT");
}
return g_oTOPLEFT;
}
private static Position g_oTOPCENTER;
public static Position TOP_CENTER()
{
if (g_oTOPCENTER == null)
{
g_oTOPCENTER = createEnumeration(Position.class, "TOPCENTER");
}
return g_oTOPCENTER;
}
private static Position g_oTOPRIGHT;
public static Position TOP_RIGHT()
{
if (g_oTOPRIGHT == null)
{
g_oTOPRIGHT = createEnumeration(Position.class, "TOPRIGHT");
}
return g_oTOPRIGHT;
}
private static Position g_oMIDDLELEFT;
public static Position MIDDLE_LEFT()
{
if (g_oMIDDLELEFT == null)
{
g_oMIDDLELEFT = createEnumeration(Position.class, "MIDDLELEFT");
}
return g_oMIDDLELEFT;
}
private static Position g_oMIDDLECENTER;
public static Position MIDDLE_CENTER()
{
if (g_oMIDDLECENTER == null)
{
g_oMIDDLECENTER = createEnumeration(Position.class, "MIDDLECENTER");
}
return g_oMIDDLECENTER;
}
private static Position g_oMIDDLERIGHT;
public static Position MIDDLE_RIGHT()
{
if (g_oMIDDLERIGHT == null)
{
g_oMIDDLERIGHT = createEnumeration(Position.class, "MIDDLERIGHT");
}
return g_oMIDDLERIGHT;
}
private static Position g_oBOTTOMLEFT;
public static Position BOTTOM_LEFT()
{
if (g_oBOTTOMLEFT == null)
{
g_oBOTTOMLEFT = createEnumeration(Position.class, "BOTTOMLEFT");
}
return g_oBOTTOMLEFT;
}
private static Position g_oBOTTOMCENTER;
public static Position BOTTOM_CENTER()
{
if (g_oBOTTOMCENTER == null)
{
g_oBOTTOMCENTER = createEnumeration(Position.class, "BOTTOMCENTER");
}
return g_oBOTTOMCENTER;
}
private static Position g_oBOTTOMRIGHT;
public static Position BOTTOM_RIGHT()
{
if (g_oBOTTOMRIGHT == null)
{
g_oBOTTOMRIGHT = createEnumeration(Position.class, "BOTTOMRIGHT");
}
return g_oBOTTOMRIGHT;
}
}
| mit |
kcsl/immutability-benchmark | testcases/source/AGT/AGT011_ByteLiteral_ObjectInstanceVariable/src/testcase/AGT011_ByteLiteral_ObjectInstanceVariable.java | 483 | package testcase;
import annotations.MUTABLE;
public class AGT011_ByteLiteral_ObjectInstanceVariable {
@MUTABLE
public Test test = new Test();
public static void main(String[] args) {
new AGT011_ByteLiteral_ObjectInstanceVariable().foo();
}
public void foo(){
System.out.println(test);
test.f = (byte) 0x01;
System.out.println(test);
}
}
class Test {
public Object f = new Object();
@Override
public String toString() {
return "Test [f=" + f + "]";
}
} | mit |
EXASOL/virtual-schemas | src/main/java/com/exasol/adapter/dialects/athena/AthenaSqlDialect.java | 5888 | package com.exasol.adapter.dialects.athena;
import static com.exasol.adapter.AdapterProperties.CATALOG_NAME_PROPERTY;
import static com.exasol.adapter.AdapterProperties.SCHEMA_NAME_PROPERTY;
import static com.exasol.adapter.capabilities.AggregateFunctionCapability.*;
import static com.exasol.adapter.capabilities.LiteralCapability.*;
import static com.exasol.adapter.capabilities.MainCapability.*;
import static com.exasol.adapter.capabilities.PredicateCapability.*;
import static com.exasol.adapter.capabilities.ScalarFunctionCapability.*;
import java.sql.SQLException;
import java.util.Set;
import com.exasol.adapter.AdapterProperties;
import com.exasol.adapter.capabilities.Capabilities;
import com.exasol.adapter.dialects.*;
import com.exasol.adapter.jdbc.*;
/**
* This class implements the SQL dialect of Amazon's AWS Athena.
*
* @see <a href="https://aws.amazon.com/athena/">AWS Athena</a>
*/
public class AthenaSqlDialect extends AbstractSqlDialect {
static final String NAME = "ATHENA";
private static final Capabilities CAPABILITIES = createCapabilityList();
private static Capabilities createCapabilityList() {
return Capabilities //
.builder() //
.addMain(SELECTLIST_PROJECTION, SELECTLIST_EXPRESSIONS, FILTER_EXPRESSIONS, AGGREGATE_SINGLE_GROUP,
AGGREGATE_GROUP_BY_COLUMN, AGGREGATE_GROUP_BY_EXPRESSION, AGGREGATE_GROUP_BY_TUPLE,
AGGREGATE_HAVING, ORDER_BY_COLUMN, ORDER_BY_EXPRESSION, LIMIT) //
.addLiteral(NULL, BOOL, DATE, TIMESTAMP, TIMESTAMP_UTC, DOUBLE, EXACTNUMERIC, STRING, INTERVAL) //
.addPredicate(AND, OR, NOT, EQUAL, NOTEQUAL, LESS, LESSEQUAL, LIKE, REGEXP_LIKE, BETWEEN, IS_NULL,
IS_NOT_NULL) //
.addScalarFunction(CAST, ABS, CEIL, ACOS, ASIN, ATAN, ATAN2, COS, COSH, DEGREES, EXP, FLOOR, LN, LOG,
MOD, POWER, RADIANS, RAND, ROUND, SIGN, SIN, SQRT, TAN, TANH, TRUNC, BIT_AND, BIT_NOT, BIT_OR,
BIT_XOR, CHR, CONCAT, LENGTH, LOWER, LPAD, LTRIM, REPLACE, REVERSE, RPAD, RTRIM, SUBSTR, TRIM,
UPPER, CURRENT_DATE, CURRENT_TIMESTAMP, DATE_TRUNC, MINUTE, SECOND, DAY, MONTH, WEEK, YEAR,
REGEXP_REPLACE, HASH_MD5, HASH_SHA1) //
.addAggregateFunction(COUNT, COUNT_STAR, SUM, MIN, MAX, AVG, STDDEV, STDDEV_POP, STDDEV_SAMP, VARIANCE,
VAR_POP, VAR_SAMP, APPROXIMATE_COUNT_DISTINCT) //
.build();
}
/**
* Create a new instance of the {@link AthenaSqlDialect}.
*
* @param connectionFactory factory for the JDBC connection to the remote data source
* @param properties user-defined adapter properties
*/
public AthenaSqlDialect(final ConnectionFactory connectionFactory, final AdapterProperties properties) {
super(connectionFactory, properties, Set.of(CATALOG_NAME_PROPERTY, SCHEMA_NAME_PROPERTY));
}
@Override
public String getName() {
return NAME;
}
@Override
public Capabilities getCapabilities() {
return CAPABILITIES;
}
/**
* Get the type of support Athena has for catalogs.
* <p>
* While Athena itself does not use catalogs, the JDBC driver simulates a single catalog for a better compatibility
* with standard products like BI tools.
* <p>
*
* @return always {@link com.exasol.adapter.dialects.SqlDialect.StructureElementSupport#SINGLE}
*
* @see <a href=
* "https://s3.amazonaws.com/athena-downloads/drivers/JDBC/SimbaAthenaJDBC_2.0.7/docs/Simba+Athena+JDBC+Driver+Install+and+Configuration+Guide.pdf">
* Simba Athena JDBC Driver Install and Configuration Guide, section "Catalog and Schema Support"</a>
*/
@Override
public StructureElementSupport supportsJdbcCatalogs() {
return StructureElementSupport.SINGLE;
}
/**
* Get the type of support Athena has for schemas.
* <p>
* Athena knows schemas as a mirror of databases.
*
* @return always {@link com.exasol.adapter.dialects.SqlDialect.StructureElementSupport#MULTIPLE}
*
* @see <a href= "https://docs.aws.amazon.com/athena/latest/ug/show-databases.html">SHOW DATABASES documentation</a>
*/
@Override
public StructureElementSupport supportsJdbcSchemas() {
return StructureElementSupport.MULTIPLE;
}
@Override
public boolean requiresCatalogQualifiedTableNames(final SqlGenerationContext context) {
return false;
}
@Override
public boolean requiresSchemaQualifiedTableNames(final SqlGenerationContext context) {
return true;
}
@Override
// https://docs.aws.amazon.com/athena/latest/ug/tables-databases-columns-names.html
public String applyQuote(final String identifier) {
return AthenaIdentifier.of(identifier).quote();
}
@Override
public NullSorting getDefaultNullSorting() {
return NullSorting.NULLS_SORTED_AT_END;
}
@Override
// https://docs.aws.amazon.com/athena/latest/ug/select.html
public String getStringLiteral(final String value) {
return super.quoteLiteralStringWithSingleQuote(value);
}
@Override
protected RemoteMetadataReader createRemoteMetadataReader() {
try {
return new AthenaMetadataReader(this.connectionFactory.getConnection(), this.properties);
} catch (final SQLException exception) {
throw new RemoteMetadataReaderException(
"Unable to create Athena remote metadata reader. Caused by: " + exception.getMessage(), exception);
}
}
@Override
protected QueryRewriter createQueryRewriter() {
return new ImportIntoQueryRewriter(this, createRemoteMetadataReader(), this.connectionFactory);
}
} | mit |
LeandroPinheiroo/AppCarMovel | app/src/main/java/com/example/leandro/appcar/control/rest/Servico_OSJSON.java | 2099 | package com.example.leandro.appcar.control.rest;
import com.example.leandro.appcar.model.Servico_OS;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Servico_OSJSON {
public static Servico_OS getServico_OSJSON(JSONObject object) {
//instancia vetor de servico_os
Servico_OS servico_os = new Servico_OS();
try {
//pega do json os registros da tag servico_os
servico_os.setCod(object.getInt("cod"));
servico_os.setFuncionario(object.getInt("funcionario_codigo"));
servico_os.setOrdemservico(object.getInt("ordemservico_codigo"));
servico_os.setServico(object.getInt("servico_codigo"));
} catch (Exception x) {
}
return servico_os;
}
public static String geraJSONServico_OSs(ArrayList<Servico_OS> servico_os) {
ArrayList<JSONObject> tabelaServico_OSs = new ArrayList<>();
JSONObject registro;
//cria um registro primeiro
for (Servico_OS servico : servico_os) {
registro = preencheJSON(servico);
//adiciona registro à lista de registros
tabelaServico_OSs.add(registro);
}
//adiciona tabela
JSONObject bd = new JSONObject();
try {
bd.putOpt("servico_os", (Object) tabelaServico_OSs);
} catch (JSONException u) {
}
return UtilJSON.limpaJSON(bd);
}
public static String geraJSONServico_OS(Servico_OS servico_os) {
return UtilJSON.limpaJSON(preencheJSON(servico_os));
}
public static JSONObject preencheJSON(Servico_OS servico) {
JSONObject registro = new JSONObject();
try {
registro.put("cod", servico.getCod());
registro.put("funcionario_codigo", servico.getFuncionario());
registro.put("ordemservico_codigo", servico.getOrdemservico());
registro.put("servico_codigo", servico.getServico());
return registro;
} catch (JSONException k) {
}
return null;
}
}
| mit |
asciiCerebrum/neocortexEngine | src/main/java/org/asciicerebrum/neocortexengine/domain/core/particles/EventFact.java | 729 | package org.asciicerebrum.neocortexengine.domain.core.particles;
/**
*
* @author species8472
*/
public class EventFact extends StringParticle {
/**
* Creates an instance from a string.
*
* @param eventFactInput the string to create the instance from.
*/
public EventFact(final String eventFactInput) {
this.setValue(eventFactInput);
}
@Override
public final boolean equals(final Object obj) {
if (!(obj instanceof EventFact)) {
return false;
}
if (obj == this) {
return true;
}
return this.equalsHelper(obj);
}
@Override
public final int hashCode() {
return this.hashCodeHelper();
}
}
| mit |
theyavikteam/MonsterBoard | app/src/main/java/com/theyavikteam/monsterboard/model/vo/CellVO.java | 877 | package com.theyavikteam.monsterboard.model.vo;
import android.content.Context;
import android.widget.TableRow;
import android.widget.TextView;
import com.theyavikteam.monsterboard.R;
public class CellVO {
private TextView textView;
private TableRow tableRow;
private int cellIndex;
public CellVO(Context context, TextView textView, TableRow tableRow, int cellColor) {
this.textView = textView;
this.textView.setText("");
this.tableRow = tableRow;
this.tableRow.setBackgroundColor(context.getResources().getColor(cellColor));
}
public TextView getTextView() {
return textView;
}
public TableRow getTableRow() {
return tableRow;
}
public int getCellIndex() {
return cellIndex;
}
public void setCellIndex(int cellIndex) {
this.cellIndex = cellIndex;
}
}
| mit |
churichard/ru-direct | app/src/main/java/org/rudirect/android/fragment/DirectionsFragment.java | 10920 | package org.rudirect.android.fragment;
import android.Manifest;
import android.app.Fragment;
import android.content.Intent;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.style.ImageSpan;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.RelativeLayout;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import org.rudirect.android.R;
import org.rudirect.android.activity.DirectionsActivity;
import org.rudirect.android.activity.MainActivity;
import org.rudirect.android.activity.SettingsActivity;
import org.rudirect.android.data.constants.RUDirectApplication;
import org.rudirect.android.data.model.BusStop;
import org.rudirect.android.interfaces.NetworkCallFinishListener;
import org.rudirect.android.util.RUDirectUtil;
public class DirectionsFragment extends Fragment implements NetworkCallFinishListener,
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private static final int REQUEST_RESOLVE_ERROR = 5001;
private GoogleApiClient mGoogleApiClient;
private boolean mResolvingError = false;
private MainActivity mainActivity;
private RelativeLayout relativeLayout;
private AutoCompleteTextView originACTextView;
private AutoCompleteTextView destACTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mainActivity = (MainActivity) getActivity();
setHasOptionsMenu(true);
mGoogleApiClient = buildGoogleApiClient();
}
@Override
public void onStart() {
super.onStart();
if (!mResolvingError) {
mGoogleApiClient.connect();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_directions, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
originACTextView = (AutoCompleteTextView) mainActivity.findViewById(R.id.origin_ac_textview);
destACTextView = (AutoCompleteTextView) mainActivity.findViewById(R.id.dest_ac_textview);
// Hide the keyboard when the textviews are not in focus
relativeLayout = (RelativeLayout) mainActivity.findViewById(R.id.directions_layout);
relativeLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
RUDirectUtil.hideKeyboard(mainActivity.getCurrentFocus());
return true;
}
});
// Set up find route button
Button findRouteButton = (Button) mainActivity.findViewById(R.id.find_route_button);
if (findRouteButton != null) {
findRouteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
RUDirectUtil.hideKeyboard(view);
BusStop origin = null;
BusStop destination = null;
BusStop[] busStops = RUDirectApplication.getBusData().getAllBusStops();
if (busStops != null) {
for (BusStop stop : busStops) {
if (stop.getTitle().equalsIgnoreCase(originACTextView.getText().toString())) {
origin = stop;
}
if (stop.getTitle().equalsIgnoreCase(destACTextView.getText().toString())) {
destination = stop;
}
if (origin != null && destination != null) break;
}
if (origin == null) {
originACTextView.setError(getString(R.string.directions_textview_error));
}
if (destination == null) {
destACTextView.setError(getString(R.string.directions_textview_error));
}
if (origin != null && destination != null) {
Intent intent = new Intent(mainActivity, DirectionsActivity.class);
intent.putExtra(getString(R.string.origin_text_message), (Parcelable) origin);
intent.putExtra(getString(R.string.destination_text_message), (Parcelable) destination);
startActivity(intent);
mainActivity.overridePendingTransition(R.anim.abc_grow_fade_in_from_bottom, 0);
} else {
relativeLayout.requestFocus();
SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(" ");
builder.setSpan(new ImageSpan(mainActivity, android.R.drawable.stat_notify_error), 0, 1, 0);
builder.append("\t\t").append(getString(R.string.directions_snackbar_error));
Snackbar.make(relativeLayout, builder, Snackbar.LENGTH_SHORT).show();
}
} else {
View layout = mainActivity.findViewById(R.id.directions_layout);
if (layout != null)
Snackbar.make(layout, getString(R.string.unable_to_fetch_bus_stops_error),
Snackbar.LENGTH_SHORT).show();
}
}
});
}
initACTextViews();
}
// Initialize the autocomplete textviews
private void initACTextViews() {
BusStop[] busStopArray = RUDirectApplication.getBusData().getAllBusStops();
if (busStopArray != null) {
ArrayAdapter<BusStop> busStopArrayAdapter = new ArrayAdapter<>(mainActivity, R.layout.list_autocomplete_textview, busStopArray);
// Setup the autocomplete textviews
setupACTextView(originACTextView, busStopArrayAdapter);
setupACTextView(destACTextView, busStopArrayAdapter);
// Initialize origin and destination
setOriginToNearestBusStop();
}
}
// Set up the autocomplete textview
private void setupACTextView(AutoCompleteTextView textView, ArrayAdapter<BusStop> busStopArrayAdapter) {
textView.setThreshold(1); // Start autocompleting after 1 char is typed
textView.setAdapter(busStopArrayAdapter); // Set the array adapter
// Hide the keyboard when an autocomplete option is selected
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
RUDirectUtil.hideKeyboard(mainActivity.getCurrentFocus());
}
});
}
@Override
public void onBusStopsUpdated() {
initACTextViews();
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_settings, menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.settings) {
Intent intent = new Intent(mainActivity, SettingsActivity.class);
startActivity(intent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && isAdded()) {
RUDirectApplication.getTracker().send(new HitBuilders.EventBuilder()
.setCategory(getString(R.string.directions_selector_category))
.setAction(getString(R.string.view_action))
.build());
setOriginToNearestBusStop();
}
}
// Sets the origin autocomplete textview to the nearest bus stop
private void setOriginToNearestBusStop() {
Location location = null;
if (ContextCompat.checkSelfPermission(mainActivity,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
} else {
ActivityCompat.requestPermissions(mainActivity,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 0);
}
if (location != null) {
BusStop nearestStop = RUDirectApplication.getBusData().getNearestStop(location);
if (nearestStop != null) {
originACTextView.setText(nearestStop.getTitle());
originACTextView.dismissDropDown();
originACTextView.setError(null);
}
}
}
// Build Google Api Client
private synchronized GoogleApiClient buildGoogleApiClient() {
return new GoogleApiClient.Builder(mainActivity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
@Override
public void onConnected(Bundle bundle) { /* Do nothing */ }
@Override
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
// Connection to Google Play Services failed
@Override
public void onConnectionFailed(@NonNull ConnectionResult result) {
if (!mResolvingError && result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(mainActivity, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
mGoogleApiClient.connect();
}
}
}
} | mit |
sbellus/fitnesse-graphviz-plugin | src/main/java/com/github/sbellus/fitnesse/graphviz/graphics/GraphicsProperties.java | 3740 | package com.github.sbellus.fitnesse.graphviz.graphics;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import fitnesse.wikitext.parser.Symbol;
public class GraphicsProperties {
private Integer width;
private Integer height;
private String caption;
private String alignment;
private static final String SymbolPropertyWidht = "Width";
private static final String SymbolPropertyHeight = "Height";
private static final String SymbolPropertyCaption = "Caption";
private static final String SymbolPropertyAligment = "Aligment";
public GraphicsProperties() {
this.width = null;
this.height = null;
this.caption = null;
this.alignment = null;
}
public GraphicsProperties(GraphicsProperties p) {
this.width = p.width;
this.height = p.height;
this.caption = p.caption;
this.alignment = p.alignment;
}
public void setWidth(Integer width) {
this.width = width;
}
public void setHeight(Integer height) {
this.height = height;
}
public void setCaption(String caption) {
this.caption = caption;
}
public void setAlignment(String alignment) {
this.alignment = alignment;
}
public Integer getWidth() {
return width;
}
public Integer getHeight() {
return height;
}
public String getCaption() {
return caption;
}
public String getAlignment() {
return alignment;
}
public void readFromLine(String line) {
Pattern pattern = Pattern.compile("[ \t]*(\".*\")?[ \t]*(l|r|c)?[ \t]*([0-9]+)?[ \t]*([0-9]+)?");
Matcher matcher = pattern.matcher(line);
if (matcher.matches()) {
if (matcher.group(1) != null) {
Pattern patternTitle = Pattern.compile("\"[ \t]*(.*?)[ \t]*\"");
java.util.regex.Matcher matcherTitle = patternTitle.matcher(matcher.group(1));
if (matcherTitle.matches()) {
caption = matcherTitle.group(1);
}
}
if (matcher.group(2) != null) {
alignment = matcher.group(2);
}
if (matcher.group(3) != null) {
width = Integer.parseInt(matcher.group(3));
}
if (matcher.group(4) != null) {
height = Integer.parseInt(matcher.group(4));
}
}
}
public void readFromSymbol(Symbol symbol) {
if (symbol.hasProperty(SymbolPropertyWidht)) {
width = Integer.parseInt(symbol.getProperty(SymbolPropertyWidht));
}
if (symbol.hasProperty(SymbolPropertyHeight)) {
height = Integer.parseInt(symbol.getProperty(SymbolPropertyHeight));
}
if (symbol.hasProperty(SymbolPropertyCaption)) {
caption = symbol.getProperty(SymbolPropertyCaption);
}
if (symbol.hasProperty(SymbolPropertyAligment)) {
alignment = symbol.getProperty(SymbolPropertyAligment);
}
}
public void writeToSymbol(Symbol symbol) {
if (width != null) {
symbol.putProperty(SymbolPropertyWidht, width.toString());
}
if (height != null) {
symbol.putProperty(SymbolPropertyHeight, height.toString());
}
if (caption != null) {
symbol.putProperty(SymbolPropertyCaption, caption);
}
if (alignment != null) {
symbol.putProperty(SymbolPropertyAligment, alignment);
}
}
public void replaceVariables(GraphicsVariableReplacer replacer) {
caption = replacer.replaceVariablesIn(caption);
}
}
| mit |
Barzahlen/Barzahlen-Java | src/test/java/de/barzahlen/api/online/integration/notifications/TransactionExpiredTest.java | 3626 | package de.barzahlen.api.online.integration.notifications;
import de.barzahlen.api.online.BarzahlenNotificationHandler;
import de.barzahlen.api.online.Configuration;
import de.barzahlen.api.online.notifications.TransactionExpiredNotificationHandler;
import de.barzahlen.http.requests.DummyRequest;
import de.barzahlen.http.requests.HttpRequest;
import de.barzahlen.http.responses.DummyResponse;
import de.barzahlen.http.responses.HttpResponse;
import de.barzahlen.logger.Logger;
import de.barzahlen.logger.LoggerFactory;
import org.junit.Ignore;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
public class TransactionExpiredTest {
private static final String SHOP_ID = "";
private static final String PAYMENT_KEY = "";
private static final String NOTIFICATION_KEY = "";
private static final boolean SANDBOX_MODE = true;
@Ignore
@Test
public void test() {
final Logger logger = LoggerFactory.getLogger(LoggerFactory.LoggerType.CONSOLE);
Configuration configuration = new Configuration(SANDBOX_MODE, SHOP_ID, PAYMENT_KEY, NOTIFICATION_KEY);
BarzahlenNotificationHandler notificationRequestHandler = new BarzahlenNotificationHandler(configuration);
notificationRequestHandler.registerNotificationHandler(new TransactionExpiredNotificationHandler
(configuration) {
@Override
protected void onTransactionExpired(final String transactionId, final String shopId,
final String customerEmail, final String amount, final String currency,
final String orderId, final String customVar0, final String customVar1,
final String customVar2) {
logger.info("TransactionExpiredRefund.onTransactionExpired", "onTransactionExpired");
logger.info("TransactionExpiredRefund.onTransactionExpired", "transactionId: "
+ transactionId);
logger.info("TransactionExpiredRefund.onTransactionExpired", "shopId: " + shopId);
logger.info("TransactionExpiredRefund.onTransactionExpired",
"customerEmail: " + customerEmail);
logger.info("TransactionExpiredRefund.onTransactionExpired", "amount: " + amount);
logger.info("TransactionExpiredRefund.onTransactionExpired", "currency: " + currency);
logger.info("TransactionExpiredRefund.onTransactionExpired", "orderId: " + orderId);
logger.info("TransactionExpiredRefund.onTransactionExpired", "customVar0: " + customVar0);
logger.info("TransactionExpiredRefund.onTransactionExpired", "customVar1: " + customVar1);
logger.info("TransactionExpiredRefund.onTransactionExpired", "customVar2: " + customVar2);
}
});
Map<String, String> requestParameters = new HashMap<>();
requestParameters.put("state", "expired");
requestParameters.put("transaction_id", "123");
requestParameters.put("shop_id", SHOP_ID);
requestParameters.put("customer_email", "foo@example.com");
requestParameters.put("amount", "10.00");
requestParameters.put("currency", "EUR");
requestParameters.put("order_id", "123");
requestParameters.put("hash", "");
HttpRequest httpRequest = new DummyRequest(requestParameters);
HttpResponse httpResponse = new DummyResponse();
notificationRequestHandler.handleRequest(httpRequest, httpResponse);
}
}
| mit |
masterj63/Rooks3 | src/main/java/ru/samsu/mj/board/BoardMatrix.java | 1963 | package ru.samsu.mj.board;
/**
* Represents a bottom-left-cornered board in both <b>A<sub>n-1</sub></b> and <b>C<sub>n</sub></b> (where <b>n</b> is even).
* Encapsulates a boolean array of two dimensions which <b>[i][j]</b><sup>th</sup> element is <b>true</b> iff there is a rook in the board in <b>i</b><sup>th</sup> row and in <b>j</b><sup>th</sup> column.
*/
class BoardMatrix {
/**
* See class' description.
*/
private final boolean[][] MATRIX;
/**
* @param matrix the matrix to be encapsulated.
*/
private BoardMatrix(boolean[][] matrix) {
MATRIX = matrix;
}
/**
* A static factory.
*
* @param deflatedBoard a deflated board a new {@link BoardMatrix} to be constructed from.
* @return a new {@link BoardMatrix}.
*/
static BoardMatrix valueOfDeflatedBoard(int[] deflatedBoard) {
boolean[][] matrix = new boolean[deflatedBoard.length][];
for (int i = 0; i < matrix.length; i++) {
matrix[i] = new boolean[i];
if (deflatedBoard[i] >= 0)
matrix[i][deflatedBoard[i]] = true;
}
return new BoardMatrix(matrix);
}
/**
* A getter for the incapsulated field.
*
* @param i number of a row.
* @param j number of a column.
* @return <b>[i][j]</b><sup>th</sup> value requested.
*/
boolean get(int i, int j) {
return MATRIX[i][j];
}
/**
* @return the dimension of board. The number of rows, specifically.
*/
int length() {
return MATRIX.length;
}
//TODO see if the method below makes sense or just confuses.
/**
* Since the problem is set over the square boards, behaves exactly as <b>{@code ru.samsu.mj.board.length}</b> of zero arity does.
*
* @param i the number of row.
* @return the length of <b>i</b><sup>th</sup> row.
*/
int length(int i) {
return MATRIX[i].length;
}
} | mit |
aniediudo/forte-locator | src/com/audax/dev/forte/AssetLocator.java | 12295 | package com.audax.dev.forte;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnticipateInterpolator;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.audax.dev.forte.util.SystemUiHider;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.audax.dev.forte.maps.MapsClient;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class AssetLocator extends FragmentActivity implements MapsClient.ClientListener, View.OnClickListener {
/**
* Whether or not the system UI should be auto-hidden after
* {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {@link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
/**
* The instance of the {@link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
private MapsClient mapsClient;
//A background task to simulate 'busy'
// private static class DummyProgressTask extends AsyncTask<Integer, Integer, Void> {
// private Activity context;
// private ProgressBar progressBar;
// private Runnable onComplete;
//
// public DummyProgressTask(Activity context, Runnable onComplete) {
// super();
// this.context = context;
// this.onComplete = onComplete;
// this.progressBar = (ProgressBar) context.findViewById(R.id.progressBar1);
// }
//
// @Override
// protected Void doInBackground(Integer... params) {
// int cu = 0;
// while (cu < params[0]) {
// this.publishProgress(cu);
// cu += (Math.floor(Math.random() * 5));
// try {
// Thread.currentThread().sleep((int)(Math.floor(Math.random() * 100) % 10) + 5);
// } catch (InterruptedException e) {
// break;
// }
// }
// this.publishProgress(params[0]);
// return null;
// }
//
// @Override
// protected void onPostExecute(Void result) {
// // TODO Auto-generated method stub
// super.onPostExecute(result);
// this.context.findViewById(R.id.btn_home).setVisibility(View.VISIBLE);
// this.onComplete.run();
// }
//
// @Override
// protected void onProgressUpdate(Integer... values) {
// // TODO Auto-generated method stub
// super.onProgressUpdate(values);
// for (Integer i : values) {
// progressBar.setProgress(i);
// }
//
// }
// }
//
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_forte_mobile);
setContentView(R.layout.main);
// WebView webV = (WebView)this.findViewById(R.id.web_view);
// webV.loadUrl("file:///android_asset/landing.html");
//
//Simulate Progress
final ProgressBar pb = (ProgressBar)this.findViewById(R.id.progressBar1);
final View homeButton = findViewById(R.id.btn_home);
homeButton.setOnClickListener(this);
//Simulate 'loading'
ValueAnimator anim = ValueAnimator.ofInt(0, pb.getMax());
anim.setDuration(2000);
anim.setInterpolator(new AnticipateInterpolator());
anim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
homeButton.setVisibility(View.VISIBLE);
showNearestCenter();
}
});
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
pb.setProgress((Integer)animation.getAnimatedValue());
}});
anim.start();
//mapsClient = new MapsClient(this);
//mapsClient.setClientListener(this);
/*final View controlsView = findViewById(R.id.parent);
final View contentView = findViewById(R.id.container);
// final View controlsView =
// findViewById(R.id.fullscreen_content_controls);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView,
HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider
.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
@Override
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(
android.R.integer.config_shortAnimTime);
}
controlsView
.animate()
.translationY(visible ? 0 : mControlsHeight)
.setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE
: View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
*/
// Set up the user interaction to manually show or hide the system UI.
/*contentView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
*/
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
/*
* findViewById(R.id.dummy_button).setOnTouchListener(
* mDelayHideTouchListener);
*/
}
protected void showNearestCenter() {
View v = this.findViewById(R.id.lay_nearest);
v.setVisibility(View.VISIBLE);
}
protected void switchToMenuActivity() {
Intent itt = new Intent(this, MainMenuActivity.class);
this.startActivity(itt);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
//delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
@Override
public void run() {
// mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
/*int code = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (code == ConnectionResult.SUCCESS) {
Log.i("Google Play", "Service is available");
this.mapsClient.start();
} else {
GooglePlayServicesUtil.getErrorDialog(code, this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(
code,
this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
ErrorDialogFragment errorFragment =
new ErrorDialogFragment();
// Set the dialog in the DialogFragment
errorFragment.setDialog(errorDialog);
// Show the error dialog in the DialogFragment
errorFragment.show(getSupportFragmentManager(),
"Location Updates");
}
}*/
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
Intent itt = new Intent(this, MainMenuActivity.class);
this.startActivity(itt);
return true;
}
return super.onOptionsItemSelected(item);
}
// Define a DialogFragment that displays the error dialog
public static class ErrorDialogFragment extends DialogFragment {
// Global field to contain the error dialog
private Dialog mDialog;
// Default constructor. Sets the dialog field to null
public ErrorDialogFragment() {
super();
mDialog = null;
}
// Set the dialog to display
public void setDialog(Dialog dialog) {
mDialog = dialog;
}
// Return a Dialog to the DialogFragment.
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return mDialog;
}
}
public void showMaps(View v) {
Intent mapIntent = new Intent(this, MapActivity.class);
this.startActivity(mapIntent);
}
private Menu _menu;
private void showMenu(boolean show) {
if (_menu != null) {
int count = _menu.size();
for (int k = 0; k < count; k++) {
_menu.getItem(k).setVisible(show);
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
_menu = menu;
//Initially hide. Show when progress is complete
showMenu(false);
return true;
}
private boolean firstTime = true;
@Override
public void onLocationChanged(MapsClient client) {
//Location location = client.getCurrentLocation();
if (firstTime) {
firstTime = false;
this.findViewById(R.id.btn_goto_map).setVisibility(View.VISIBLE);
this.findViewById(R.id.progressBar1).setVisibility(View.GONE);
}
TextView status = (TextView)this.findViewById(R.id.next_station_label);
status.setText(String.format(this.getString(R.string.next_station), this.getString(R.string.demo_loc), "124Km"));
client.stop();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if (mapsClient != null) {
mapsClient.stop();
}
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.btn_home:
switchToMenuActivity();
break;
}
}
}
| mit |
opengl-8080/concurrent-update-samples | src/main/java/gl8080/web/pessimistic/MemoForm.java | 1336 | package gl8080.web.pessimistic;
import gl8080.logic.pessimistic.Memo;
import java.io.Serializable;
public class MemoForm implements Serializable {
private Long id;
private String title;
private String content;
public static MemoForm valueOf(Memo memo) {
MemoForm form = new MemoForm();
form.setId(memo.getId());
form.setTitle(memo.getTitle());
form.setContent(memo.getContent());
return form;
}
public Memo toMemo() {
Memo memo = new Memo();
memo.setId(this.id);
memo.setTitle(this.title);
memo.setContent(this.content);
return memo;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
@Override
public String toString() {
return "MemoForm{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}';
}
}
| mit |
archimatetool/archi | com.archimatetool.editor/src/com/archimatetool/editor/diagram/commands/CreateBendpointCommand.java | 1421 | /**
* This program and the accompanying materials
* are made available under the terms of the License
* which accompanies this distribution in the file LICENSE.txt
*/
package com.archimatetool.editor.diagram.commands;
import org.eclipse.draw2d.geometry.Dimension;
import com.archimatetool.model.IArchimateFactory;
import com.archimatetool.model.IDiagramModelBendpoint;
/**
* Description
*
* @author Phillip Beauvoir
*/
public class CreateBendpointCommand extends BendpointCommand implements IAnimatableCommand {
private IDiagramModelBendpoint fBendpoint;
public CreateBendpointCommand() {
super(Messages.CreateBendpointCommand_0);
}
@Override
public void execute() {
fBendpoint = IArchimateFactory.eINSTANCE.createDiagramModelBendpoint();
Dimension dim1 = getFirstRelativeDimension();
fBendpoint.setStartX(dim1.width);
fBendpoint.setStartY(dim1.height);
Dimension dim2 = getSecondRelativeDimension();
fBendpoint.setEndX(dim2.width);
fBendpoint.setEndY(dim2.height);
redo();
}
@Override
public void undo() {
getDiagramModelConnection().getBendpoints().remove(fBendpoint);
}
@Override
public void redo() {
getDiagramModelConnection().getBendpoints().add(getIndex(), fBendpoint);
}
}
| mit |
TulevaEE/onboarding-service | src/main/java/ee/tuleva/onboarding/fund/FundService.java | 1603 | package ee.tuleva.onboarding.fund;
import static java.util.stream.Collectors.toList;
import static java.util.stream.StreamSupport.stream;
import ee.tuleva.onboarding.fund.response.FundResponse;
import ee.tuleva.onboarding.fund.statistics.PensionFundStatistics;
import ee.tuleva.onboarding.fund.statistics.PensionFundStatisticsService;
import ee.tuleva.onboarding.locale.LocaleService;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@Service
@Slf4j
@RequiredArgsConstructor
public class FundService {
private final FundRepository fundRepository;
private final PensionFundStatisticsService pensionFundStatisticsService;
private final LocaleService localeService;
public List<FundResponse> getFunds(Optional<String> fundManagerName) {
return stream(fundsBy(fundManagerName).spliterator(), false)
.sorted()
.map(fund -> new FundResponse(fund, getStatistics(fund), localeService.getLanguage()))
.collect(toList());
}
private PensionFundStatistics getStatistics(Fund fund) {
return pensionFundStatisticsService.getCachedStatistics().stream()
.filter(statistic -> Objects.equals(statistic.getIsin(), fund.getIsin()))
.findFirst()
.orElse(PensionFundStatistics.getNull());
}
private Iterable<Fund> fundsBy(Optional<String> fundManagerName) {
return fundManagerName
.map(fundRepository::findAllByFundManagerNameIgnoreCase)
.orElse(fundRepository.findAll());
}
}
| mit |
ciaranj/java-memcached-client | src/main/java/net/spy/memcached/KetamaNodeLocator.java | 4658 | package net.spy.memcached;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import net.spy.memcached.compat.SpyObject;
import net.spy.memcached.ketama.DefaultKetamaNodeLocatorConfiguration;
import net.spy.memcached.ketama.KetamaNodeLocatorConfiguration;
/**
* This is an implementation of the Ketama consistent hash strategy from
* last.fm. This implementation may not be compatible with libketama as
* hashing is considered separate from node location.
*
* Note that this implementation does not currently supported weighted nodes.
*
* @see http://www.last.fm/user/RJ/journal/2007/04/10/392555/
*/
public final class KetamaNodeLocator extends SpyObject implements NodeLocator {
final SortedMap<Long, MemcachedNode> ketamaNodes;
final Collection<MemcachedNode> allNodes;
final HashAlgorithm hashAlg;
final KetamaNodeLocatorConfiguration config;
public KetamaNodeLocator(List<MemcachedNode> nodes, HashAlgorithm alg) {
this(nodes, alg, new DefaultKetamaNodeLocatorConfiguration());
}
public KetamaNodeLocator(List<MemcachedNode> nodes, HashAlgorithm alg, KetamaNodeLocatorConfiguration conf) {
super();
allNodes = nodes;
hashAlg = alg;
ketamaNodes=new TreeMap<Long, MemcachedNode>();
config= conf;
int numReps= config.getNodeRepetitions();
for(MemcachedNode node : nodes) {
// Ketama does some special work with md5 where it reuses chunks.
if(alg == HashAlgorithm.KETAMA_HASH) {
for(int i=0; i<numReps / 4; i++) {
byte[] digest=HashAlgorithm.computeMd5(config.getKeyForNode(node, i));
for(int h=0;h<4;h++) {
Long k = ((long)(digest[3+h*4]&0xFF) << 24)
| ((long)(digest[2+h*4]&0xFF) << 16)
| ((long)(digest[1+h*4]&0xFF) << 8)
| (digest[h*4]&0xFF);
ketamaNodes.put(k, node);
}
}
} else {
for(int i=0; i<numReps; i++) {
ketamaNodes.put(hashAlg.hash(config.getKeyForNode(node, i)), node);
}
}
}
assert ketamaNodes.size() == numReps * nodes.size();
}
private KetamaNodeLocator(SortedMap<Long, MemcachedNode> smn,
Collection<MemcachedNode> an, HashAlgorithm alg, KetamaNodeLocatorConfiguration conf) {
super();
ketamaNodes=smn;
allNodes=an;
hashAlg=alg;
config=conf;
}
public Collection<MemcachedNode> getAll() {
return allNodes;
}
public MemcachedNode getPrimary(final String k) {
MemcachedNode rv=getNodeForKey(hashAlg.hash(k));
assert rv != null : "Found no node for key " + k;
return rv;
}
long getMaxKey() {
return ketamaNodes.lastKey();
}
MemcachedNode getNodeForKey(long hash) {
final MemcachedNode rv;
if(!ketamaNodes.containsKey(hash)) {
// Java 1.6 adds a ceilingKey method, but I'm still stuck in 1.5
// in a lot of places, so I'm doing this myself.
SortedMap<Long, MemcachedNode> tailMap=ketamaNodes.tailMap(hash);
if(tailMap.isEmpty()) {
hash=ketamaNodes.firstKey();
} else {
hash=tailMap.firstKey();
}
}
rv=ketamaNodes.get(hash);
return rv;
}
public Iterator<MemcachedNode> getSequence(String k) {
return new KetamaIterator(k, allNodes.size());
}
public NodeLocator getReadonlyCopy() {
SortedMap<Long, MemcachedNode> smn=new TreeMap<Long, MemcachedNode>(
ketamaNodes);
Collection<MemcachedNode> an=
new ArrayList<MemcachedNode>(allNodes.size());
// Rewrite the values a copy of the map.
for(Map.Entry<Long, MemcachedNode> me : smn.entrySet()) {
me.setValue(new MemcachedNodeROImpl(me.getValue()));
}
// Copy the allNodes collection.
for(MemcachedNode n : allNodes) {
an.add(new MemcachedNodeROImpl(n));
}
return new KetamaNodeLocator(smn, an, hashAlg, config);
}
class KetamaIterator implements Iterator<MemcachedNode> {
final String key;
long hashVal;
int remainingTries;
int numTries=0;
public KetamaIterator(final String k, final int t) {
super();
hashVal=hashAlg.hash(k);
remainingTries=t;
key=k;
}
private void nextHash() {
// this.calculateHash(Integer.toString(tries)+key).hashCode();
long tmpKey=hashAlg.hash((numTries++) + key);
// This echos the implementation of Long.hashCode()
hashVal += (int)(tmpKey ^ (tmpKey >>> 32));
hashVal &= 0xffffffffL; /* truncate to 32-bits */
remainingTries--;
}
public boolean hasNext() {
return remainingTries > 0;
}
public MemcachedNode next() {
try {
return getNodeForKey(hashVal);
} finally {
nextHash();
}
}
public void remove() {
throw new UnsupportedOperationException("remove not supported");
}
}
}
| mit |
ZzJing/ugrad-algorithm-practice | hashing/TimeStringQueue.java | 979 | import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
public class TimeStringQueue {
public Queue<Timenode> getTimeStringQueue(Queue<Timenode> sortedTimeNodes) {
if (sortedTimeNodes == null || sortedTimeNodes.size() == 0) {
return new LinkedList<>();
}
Map<String, Double> strToTime = new HashMap<>();
Queue<Timenode> timeStrQueue = new LinkedList<>();
while (!sortedTimeNodes.isEmpty()) {
Timenode curNode = sortedTimeNodes.remove();
if (!strToTime.containsKey(curNode.label)) {
strToTime.put(curNode.label, curNode.time);
} else {
if (curNode.time - strToTime.get(curNode.label) > 10) {
timeStrQueue.offer(curNode);
strToTime.put(curNode.label, curNode.time);
}
}
}
return timeStrQueue;
}
}
| mit |
ITSFactory/itsfactory.siri.bindings.v13 | src/main/java/uk/org/ifopt/ifopt/InterchangeWeightingEnumeration.java | 2014 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.07.27 at 08:11:57 PM EEST
//
package uk.org.ifopt.ifopt;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for InterchangeWeightingEnumeration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="InterchangeWeightingEnumeration">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="noInterchange"/>
* <enumeration value="interchangeAllowed"/>
* <enumeration value="recommendedInterchange"/>
* <enumeration value="preferredInterchange"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "InterchangeWeightingEnumeration")
@XmlEnum
public enum InterchangeWeightingEnumeration {
@XmlEnumValue("noInterchange")
NO_INTERCHANGE("noInterchange"),
@XmlEnumValue("interchangeAllowed")
INTERCHANGE_ALLOWED("interchangeAllowed"),
@XmlEnumValue("recommendedInterchange")
RECOMMENDED_INTERCHANGE("recommendedInterchange"),
@XmlEnumValue("preferredInterchange")
PREFERRED_INTERCHANGE("preferredInterchange");
private final String value;
InterchangeWeightingEnumeration(String v) {
value = v;
}
public String value() {
return value;
}
public static InterchangeWeightingEnumeration fromValue(String v) {
for (InterchangeWeightingEnumeration c: InterchangeWeightingEnumeration.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| mit |
jonesd/abora-white | src/main/java/info/dgjones/abora/white/collection/tables/ActualIntegerTable.java | 34424 | /**
* The MIT License
* Copyright (c) 2003 David G Jones
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package info.dgjones.abora.white.collection.tables;
import java.io.PrintWriter;
import info.dgjones.abora.white.collection.arrays.PtrArray;
import info.dgjones.abora.white.collection.steppers.ITAscendingStepper;
import info.dgjones.abora.white.collection.steppers.IntegerTableStepper;
import info.dgjones.abora.white.collection.steppers.TableStepper;
import info.dgjones.abora.white.exception.AboraRuntimeException;
import info.dgjones.abora.white.rcvr.Rcvr;
import info.dgjones.abora.white.rcvr.Xmtr;
import info.dgjones.abora.white.spaces.basic.CoordinateSpace;
import info.dgjones.abora.white.spaces.basic.OrderSpec;
import info.dgjones.abora.white.spaces.basic.Position;
import info.dgjones.abora.white.spaces.basic.XnRegion;
import info.dgjones.abora.white.spaces.integers.IntegerPos;
import info.dgjones.abora.white.spaces.integers.IntegerRegion;
import info.dgjones.abora.white.spaces.integers.IntegerSpace;
import info.dgjones.abora.white.value.IntegerValue;
import info.dgjones.abora.white.xpp.basic.Heaper;
/**
* The IntegerTable class is intended to provide an integer indexed
* table which is not constrained to be zero based.
*/
public class ActualIntegerTable extends OberIntegerTable {
protected PtrArray elements;
protected IntegerValue start;
protected int elemCount;
protected int firstElem;
protected int lastElem;
protected int tally;
protected boolean domainIsSimple;
/*
udanax-top.st:49748:
OberIntegerTable subclass: #ActualIntegerTable
instanceVariableNames: '
elements {PtrArray}
start {IntegerVar}
elemCount {UInt32}
firstElem {UInt32}
lastElem {UInt32}
tally {UInt32}
domainIsSimple {BooleanVar}'
classVariableNames: ''
poolDictionaries: ''
category: 'Xanadu-Collection-Tables'!
*/
/*
udanax-top.st:49759:
ActualIntegerTable comment:
'The IntegerTable class is intended to provide an integer indexed
table which is not constrained to be zero based.'!
*/
/*
udanax-top.st:49762:
(ActualIntegerTable getOrMakeCxxClassDescription)
friends:
'/- friends for class ActualIntegerTable -/
friend class ITAscendingStepper;
friend class ITDescendingStepper;
friend class ITGenericStepper;';
attributes: ((Set new) add: #CONCRETE; add: #COPY; yourself)!
*/
public int fastHash() {
return (((start.asInt32() ^ firstElem) ^ tally) ^ lastElem) + getClass().hashCode();
/*
udanax-top.st:49772:ActualIntegerTable methodsFor: 'testing'!
{UInt32} fastHash
^(((start DOTasLong bitXor: firstElem) bitXor: tally) bitXor: lastElem) + #cat.U.ActualIntegerTable hashForEqual!
*/
}
public boolean includesIntKey(IntegerValue aKey) {
if (aKey.isLT(lowestIndex()) || (aKey.isGT(highestIndex()))) {
return false;
} else {
if (domainIsSimple) {
return true;
} else {
return (elements.fetch(aKey.asInt32() - start.asInt32())) != null;
}
}
/*
udanax-top.st:49775:ActualIntegerTable methodsFor: 'testing'!
{BooleanVar} includesIntKey: aKey {IntegerVar}
(aKey < self lowestIndex or: [aKey > self highestIndex])
ifTrue: [^false]
ifFalse: [domainIsSimple
ifTrue: [^true]
ifFalse: [^(elements fetch: aKey DOTasLong - start DOTasLong) ~~ NULL]]!
*/
}
public boolean isEmpty() {
return tally == 0;
/*
udanax-top.st:49782:ActualIntegerTable methodsFor: 'testing'!
{BooleanVar} isEmpty
^tally == UInt32Zero!
*/
}
public Heaper atIntStore(IntegerValue index, Heaper value) {
Heaper old;
if (value == null) {
throw new AboraRuntimeException(AboraRuntimeException.NULL_INSERTION);
}
if (tally == 0) {
start = index;
}
if (index.minus(start).isGE(IntegerValue.make(elemCount))) {
enlargeAfter(index);
} else {
if (index.isLT(start)) {
enlargeBefore(index);
}
}
int reali = (index.minus(start)).asInt32();
if ((old = elements.fetch(reali)) == null) {
tally = tally + 1;
}
if (reali < firstElem) {
if ((firstElem - reali) > 1) {
domainIsSimple = false;
}
firstElem = reali;
}
if (reali > lastElem) {
if ((reali - lastElem) > 1) {
domainIsSimple = false;
}
lastElem = reali;
}
elements.store(reali, value);
return old;
/*
udanax-top.st:49787:ActualIntegerTable methodsFor: 'accessing'!
{Heaper} atInt: index {IntegerVar} store: value {Heaper}
| reali {Int32} old {Heaper} |
value == NULL ifTrue: [Heaper BLAST: #NullInsertion].
tally == UInt32Zero ifTrue: [start _ index].
index - start >= elemCount
ifTrue: [self enlargeAfter: index]
ifFalse: [index < start ifTrue: [self enlargeBefore: index]].
reali _ (index - start) DOTasLong.
(old _ elements fetch: reali) == NULL ifTrue: [tally _ tally + 1].
reali < firstElem ifTrue: [
(firstElem - reali) > 1 ifTrue: [domainIsSimple _ false].
firstElem _ reali].
reali > lastElem ifTrue: [
(reali - lastElem) > 1 ifTrue: [domainIsSimple _ false].
lastElem _ reali].
elements at: reali store: value.
^ old!
*/
}
public CoordinateSpace coordinateSpace() {
return IntegerSpace.make();
/*
udanax-top.st:49805:ActualIntegerTable methodsFor: 'accessing'!
{CoordinateSpace} coordinateSpace
^IntegerSpace make!
*/
}
public IntegerValue count() {
return IntegerValue.make(tally);
/*
udanax-top.st:49809:ActualIntegerTable methodsFor: 'accessing'!
{IntegerVar} count
^tally!
*/
}
/**
*/
public XnRegion domain() {
/* The domainIsSimple flag is used as an optimization in this method. When it is True, I
stop looking after the first simple domain I find. Therefore, when True, it MUST BE
CORRECT. When it is False, I do a complete search, and set the flag if the domain
turns out to be simple. */
XnRegion newReg;
if (isEmpty()) {
return IntegerRegion.make();
} else {
if (domainIsSimple) {
return IntegerRegion.make(lowestIndex(), highestIndex().plus(IntegerValue.one()));
} else {
newReg = generateDomain();
if (newReg.isSimple()) {
domainIsSimple = true;
}
return newReg;
}
}
/*
udanax-top.st:49813:ActualIntegerTable methodsFor: 'accessing'!
{XnRegion} domain
""
"The domainIsSimple flag is used as an optimization in this method. When it is True, I
stop looking after the first simple domain I find. Therefore, when True, it MUST BE
CORRECT. When it is False, I do a complete search, and set the flag if the domain
turns out to be simple."
| newReg {XnRegion} |
self isEmpty
ifTrue: [^IntegerRegion make]
ifFalse: [domainIsSimple
ifTrue:
[^IntegerRegion make: self lowestIndex with: self highestIndex + 1]
ifFalse:
[newReg _ self generateDomain.
newReg isSimple ifTrue: [domainIsSimple _ true].
^newReg]]!
*/
}
public IntegerValue highestIndex() {
if (tally == 0) {
return start;
}
return start.plus(IntegerValue.make(lastElem));
/*
udanax-top.st:49831:ActualIntegerTable methodsFor: 'accessing'!
{IntegerVar} highestIndex
tally == UInt32Zero ifTrue: [^start].
^ start + lastElem!
*/
}
public Heaper intFetch(IntegerValue index) {
int idx;
if ((idx = (index.minus(start)).asInt32()) >= elemCount || (index.isLT(start))) {
return null;
} else {
return elements.fetch(idx);
}
/*
udanax-top.st:49835:ActualIntegerTable methodsFor: 'accessing'!
{Heaper} intFetch: index {IntegerVar}
| idx {UInt32}|
((idx _ (index-start) DOTasLong) >= elemCount or: [index < start])
ifTrue: [^NULL]
ifFalse: [^elements fetch: idx]!
*/
}
public boolean intWipe(IntegerValue index) {
int reali;
boolean wiped;
wiped = false;
reali = (index.minus(start)).asInt32();
if (!(reali > lastElem || (reali < firstElem))) {
if ((elements.fetch(reali)) != null) {
tally = tally - 1;
wiped = true;
}
elements.store(reali, null);
if (reali == firstElem) {
firstElem = firstElemAfter(reali);
} else {
if (reali == lastElem) {
lastElem = lastElemBefore(reali);
} else {
domainIsSimple = false;
}
}
}
return wiped;
/*
udanax-top.st:49842:ActualIntegerTable methodsFor: 'accessing'!
{BooleanVar} intWipe: index {IntegerVar}
| reali {UInt32} wiped {BooleanVar} |
wiped _ false.
reali _ (index - start) DOTasLong.
(reali > lastElem or: [reali < firstElem])
ifFalse:
[(elements fetch: reali) ~~ NULL ifTrue: [tally _ tally - 1. wiped _ true].
elements at: reali store: NULL.
reali == firstElem
ifTrue: [firstElem _ self firstElemAfter: reali]
ifFalse: [reali == lastElem
ifTrue: [lastElem _ self lastElemBefore: reali]
ifFalse: [domainIsSimple _ false]]].
^ wiped!
*/
}
public IntegerValue lowestIndex() {
if (tally == 0) {
return start;
}
return start.plus(IntegerValue.make(firstElem));
/*
udanax-top.st:49857:ActualIntegerTable methodsFor: 'accessing'!
{IntegerVar} lowestIndex
tally == UInt32Zero ifTrue: [^start].
^ start + firstElem!
*/
}
public ScruTable copy() {
return new ActualIntegerTable(((PtrArray) elements.copy()), start, elemCount, firstElem, lastElem, tally, domainIsSimple);
/*
udanax-top.st:49864:ActualIntegerTable methodsFor: 'creation'!
{ScruTable} copy
^ ActualIntegerTable
create: (elements copy cast: PtrArray)
with: start
with: elemCount
with: firstElem
with: lastElem
with: tally
with: domainIsSimple!
*/
}
/**
* The optional argument just hints at the number of elements
* to eventually be added. It makes no difference semantically.
*/
public ActualIntegerTable() {
super();
elements = PtrArray.make(8);
start = IntegerValue.zero();
firstElem = 7;
lastElem = 0;
elemCount = 8;
tally = 0;
domainIsSimple = true;
/*
udanax-top.st:49874:ActualIntegerTable methodsFor: 'creation'!
create
"The optional argument just hints at the number of elements
to eventually be added. It makes no difference semantically."
super create.
elements _ PtrArray nulls: 8.
start _ IntegerVar0.
firstElem _ 7.
lastElem _ UInt32Zero.
elemCount _ 8.
tally _ UInt32Zero.
domainIsSimple _ true.!
*/
}
/**
* The optional argument just hints at the number of elements
* to eventually be added. It makes no difference semantically.
*/
public ActualIntegerTable(IntegerValue size) {
super();
if (size.isGT(IntegerValue.zero())) {
elemCount = size.asInt32();
} else {
elemCount = 4;
}
elements = PtrArray.make(elemCount);
start = IntegerValue.zero();
tally = 0;
firstElem = elemCount - 1;
lastElem = 0;
domainIsSimple = true;
/*
udanax-top.st:49886:ActualIntegerTable methodsFor: 'creation'!
create.IntegerVar: size {IntegerVar}
"The optional argument just hints at the number of elements
to eventually be added. It makes no difference semantically."
super create.
size > IntegerVar0 ifTrue: [elemCount _ size DOTasLong] ifFalse: [elemCount _ 4].
elements _ PtrArray nulls: elemCount.
start _ IntegerVar0.
tally _ UInt32Zero.
firstElem _ elemCount - 1.
lastElem _ UInt32Zero.
domainIsSimple _ true.!
*/
}
/**
* Hint at the domain to be accessed (inclusive, exclusive).
*/
public ActualIntegerTable(IntegerValue begin, IntegerValue end) {
super();
start = begin;
elemCount = (end.minus(start)).asInt32();
if (elemCount < 4) {
elemCount = 4;
}
elements = PtrArray.make(elemCount);
firstElem = elemCount - 1;
lastElem = 0;
tally = 0;
domainIsSimple = true;
/*
udanax-top.st:49899:ActualIntegerTable methodsFor: 'creation'!
create: begin {IntegerVar} with: end {IntegerVar}
"Hint at the domain to be accessed (inclusive, exclusive)."
super create.
start _ begin.
elemCount _ (end - start) DOTasLong.
elemCount < 4 ifTrue: [elemCount _ 4].
elements _ PtrArray nulls: elemCount.
firstElem _ elemCount - 1.
lastElem _ UInt32Zero.
tally _ UInt32Zero.
domainIsSimple _ true!
*/
}
public ActualIntegerTable(PtrArray array, IntegerValue begin, int count, int first, int last, int aTally, boolean simple) {
super();
elements = array;
start = begin;
elemCount = count;
firstElem = first;
lastElem = last;
tally = aTally;
domainIsSimple = simple;
/*
udanax-top.st:49912:ActualIntegerTable methodsFor: 'creation'!
create: array {PtrArray} with: begin {IntegerVar} with: count {UInt32} with: first {UInt32} with: last {UInt32} with: aTally {UInt32} with: simple {BooleanVar}
super create.
elements := array.
start := begin.
elemCount := count.
firstElem := first.
lastElem := last.
tally := aTally.
domainIsSimple := simple!
*/
}
public void destroy() {
if (getNextCOW() == null) {
super.destroy();
}
/*
udanax-top.st:49922:ActualIntegerTable methodsFor: 'creation'!
{void} destroy
self getNextCOW == NULL ifTrue:
[super destroy]!
*/
}
public ScruTable emptySize(IntegerValue size) {
return IntegerTable.make((lowestIndex()), (highestIndex().plus(IntegerValue.one())));
/*
udanax-top.st:49926:ActualIntegerTable methodsFor: 'creation'!
{ScruTable} emptySize: size {IntegerVar unused}
^IntegerTable make.IntegerVar: (self lowestIndex) with: (self highestIndex + 1)!
*/
}
/**
* Copy the given range into a new IntegerTable.
* The range is startIndex (inclusive) to stopIndex (exclusive)
* The first element in the sub table will be at firstIndex
*/
public ScruTable offsetSubTableBetween(IntegerValue startIndex, IntegerValue stopIndex, IntegerValue firstIndex) {
IntegerTable table;
IntegerValue theEnd;
theEnd = firstIndex.plus(stopIndex).minus(startIndex).minus(IntegerValue.one());
table = IntegerTable.make(firstIndex, theEnd);
for (IntegerValue i = firstIndex; i.isLE(theEnd); i = i.plus(IntegerValue.one())) {
Heaper val = intFetch(i.plus(startIndex).minus(firstIndex));
if (val != null) {
table.atIntIntroduce(i, val);
}
}
return table;
/*
udanax-top.st:49930:ActualIntegerTable methodsFor: 'creation'!
{ScruTable} offsetSubTableBetween: startIndex {IntegerVar}
with: stopIndex {IntegerVar}
with: firstIndex {IntegerVar}
"Copy the given range into a new IntegerTable.
The range is startIndex (inclusive) to stopIndex (exclusive)
The first element in the sub table will be at firstIndex"
| table {IntegerTable} theEnd {IntegerVar} |
theEnd _ firstIndex + stopIndex - startIndex - 1.
table _ IntegerTable make.IntegerVar: firstIndex with: theEnd.
firstIndex to: theEnd do:
[:i {IntegerVar} |
| val {Heaper wimpy} |
val _ self intFetch: i + startIndex - firstIndex.
val == NULL ifFalse: [table atInt: i introduce: val]].
^table!
*/
}
public ScruTable subTable(XnRegion reg) {
IntegerRegion subRegion;
subRegion = (IntegerRegion) (reg.intersect(domain().asSimpleRegion()));
if (subRegion.isEmpty()) {
return emptySize((count().maximum(IntegerValue.one())));
}
return subTableBetween(subRegion.start(), subRegion.stop());
/*
udanax-top.st:49947:ActualIntegerTable methodsFor: 'creation'!
{ScruTable} subTable: reg {XnRegion}
| subRegion {IntegerRegion} |
subRegion _ (reg intersect: self domain asSimpleRegion)
cast: IntegerRegion.
subRegion isEmpty ifTrue: [^ self emptySize: (self count max: 1)].
^self subTableBetween: subRegion start with: subRegion stop!
*/
}
/**
* Hack for C++ overloading problem
*/
public ScruTable subTableBetween(IntegerValue startIndex, IntegerValue stopIndex) {
return offsetSubTableBetween(startIndex, stopIndex, startIndex);
/*
udanax-top.st:49955:ActualIntegerTable methodsFor: 'creation'!
{ScruTable} subTableBetween: startIndex {IntegerVar} with: stopIndex {IntegerVar}
"Hack for C++ overloading problem"
^self offsetSubTableBetween: startIndex with: stopIndex with: startIndex!
*/
}
public XnRegion runAtInt(IntegerValue anIdx) {
int idx;
Heaper lastObj;
boolean notDone;
idx = (anIdx.minus(start)).asInt32();
if (tally == 0) {
return IntegerRegion.make();
}
if (idx < firstElem || (idx > lastElem)) {
return IntegerRegion.make(anIdx, anIdx);
}
notDone = true;
if ((lastObj = elements.fetch(idx)) == null) {
while (idx <= lastElem && (notDone)) {
if ((elements.fetch(idx)) == null) {
idx = idx + 1;
} else {
notDone = false;
}
}
} else {
while (idx <= lastElem && (notDone)) {
if ((elements.fetch(idx)) != null) {
if ((elements.fetch(idx)).isEqual(lastObj)) {
idx = idx + 1;
} else {
notDone = false;
}
} else {
notDone = false;
}
}
}
return IntegerRegion.make(anIdx, (start.plus(IntegerValue.make(idx))));
/*
udanax-top.st:49961:ActualIntegerTable methodsFor: 'runs'!
{XnRegion} runAtInt: anIdx {IntegerVar}
| idx {UInt32} lastObj {Heaper} notDone {BooleanVar} |
idx _ (anIdx - start) DOTasLong.
tally == UInt32Zero ifTrue: [^ IntegerRegion make].
(idx < firstElem or: [idx > lastElem])
ifTrue: [^IntegerRegion make: anIdx with: anIdx].
notDone _ true.
(lastObj _ elements fetch: idx) == NULL
ifTrue: [[idx <= lastElem and: [notDone]]
whileTrue: [(elements fetch: idx) == NULL
ifTrue: [idx _ idx + 1]
ifFalse: [notDone _ false]]]
ifFalse: [[idx <= lastElem and: [notDone]]
whileTrue: [(elements fetch: idx) ~~ NULL
ifTrue: [((elements fetch: idx) isEqual: lastObj)
ifTrue: [idx _ idx + 1]
ifFalse: [notDone _ false]]
ifFalse: [notDone _ false]]].
^IntegerRegion make: anIdx with: (start + idx)!
*/
}
public void printOn(PrintWriter aStream) {
aStream.print(getClass().getName());
printOnWithSimpleSyntax(aStream, "[", ",", "]");
/*
udanax-top.st:49983:ActualIntegerTable methodsFor: 'printing'!
{void} printOn: aStream {ostream reference}
aStream << self getCategory name.
self printOnWithSimpleSyntax: aStream
with: '['
with: ','
with: ']'!
*/
}
/**
* ignore order spec for now
*/
public TableStepper stepper(OrderSpec order) {
/* Note that this method depends on the ITAscendingStepper NOT copying the table. */
if (order == null) {
if (tally == 0) {
return IntegerTableStepper.make(this, start, start);
} else {
return new ITAscendingStepper(((OberIntegerTable) copy()), start.plus(IntegerValue.make(firstElem))
/* self lowestIndex */
, start.plus(IntegerValue.make(lastElem))
/* self highestIndex */
);
}
} else {
return IntegerTableStepper.make(this, order);
}
/*
udanax-top.st:49992:ActualIntegerTable methodsFor: 'enumerating'!
{TableStepper} stepper: order {OrderSpec default: NULL}
"ignore order spec for now"
"Note that this method depends on the ITAscendingStepper NOT copying the table."
order == NULL
ifTrue: [tally == UInt32Zero
ifTrue: [^IntegerTableStepper
make: self
with: start
with: start]
ifFalse: [^ITAscendingStepper
create: (self copy cast: OberIntegerTable)
with: start + firstElem "self lowestIndex"
with: start + lastElem "self highestIndex"]]
ifFalse: [^IntegerTableStepper make: self with: order]!
*/
}
public Heaper theOne() {
if (!count().isEqual(IntegerValue.one())) {
throw new AboraRuntimeException(AboraRuntimeException.NOT_ONE_ELEMENT);
}
return intFetch(lowestIndex());
/*
udanax-top.st:50007:ActualIntegerTable methodsFor: 'enumerating'!
{Heaper} theOne
self count ~~ 1 ifTrue:
[ Heaper BLAST: #NotOneElement ].
^ self intFetch: self lowestIndex!
*/
}
public IntegerRegion contigDomainStarting(int anIdx) {
int begin;
int tIdx;
tIdx = begin = anIdx;
while (tIdx <= lastElem && ((elements.fetch(tIdx)) != null)) {
tIdx = tIdx + 1;
}
if (tIdx > begin) {
return IntegerRegion.make(start.plus(IntegerValue.make(begin)), start.plus(IntegerValue.make(tIdx)));
} else {
return IntegerRegion.make(IntegerValue.make(anIdx), IntegerValue.make(anIdx));
}
/*
udanax-top.st:50014:ActualIntegerTable methodsFor: 'private:'!
{IntegerRegion} contigDomainStarting: anIdx {UInt32}
| begin {UInt32} tIdx {UInt32} |
tIdx _ begin _ anIdx.
[tIdx <= lastElem and: [(elements fetch: tIdx) ~~ NULL]]
whileTrue: [tIdx _ tIdx + 1].
tIdx > begin
ifTrue: [^IntegerRegion make: start + begin with: start + tIdx]
ifFalse: [^IntegerRegion make: anIdx with: anIdx]!
*/
}
/**
* return the elements array for rapid processing
*/
public PtrArray elementsArray() {
return elements;
/*
udanax-top.st:50023:ActualIntegerTable methodsFor: 'private:'!
{PtrArray} elementsArray
"return the elements array for rapid processing"
^ elements!
*/
}
/**
* return the size of the elements array for rapid processing
*/
public int endOffset() {
return lastElem;
/*
udanax-top.st:50027:ActualIntegerTable methodsFor: 'private:'!
{UInt32} endOffset
"return the size of the elements array for rapid processing"
^ lastElem!
*/
}
/**
* Enlarge the receiver to contain more slots filled with nil.
*/
public void enlargeAfter(IntegerValue toMinimum) {
PtrArray oldElements;
int tmp;
int newSize = elemCount * 2;
if (newSize < 4) {
newSize = 4;
}
if (newSize < (tmp = (toMinimum.minus(start)).asInt32() + 1)) {
newSize = tmp;
}
PtrArray newElements = PtrArray.make(newSize);
for (int i = 0; i < elemCount; i++) {
newElements.store(i, (elements.fetch(i)));
}
/* Just for the hell of it, I make this robust for asynchronous readers... */
oldElements = elements;
elements = newElements;
oldElements.destroy();
elemCount = newSize;
if (tally == 0) {
firstElem = elements.count() - 1;
}
/*
udanax-top.st:50031:ActualIntegerTable methodsFor: 'private:'!
{void} enlargeAfter: toMinimum {IntegerVar}
"Enlarge the receiver to contain more slots filled with nil."
| newElements{PtrArray} oldElements {PtrArray wimpy} tmp {UInt32} newSize {UInt32} |
newSize _ elemCount * 2.
newSize < 4 ifTrue: [newSize _ 4].
(newSize < (tmp _ (toMinimum - start) DOTasLong + 1)) ifTrue: [newSize _ tmp].
newElements _ PtrArray nulls: newSize.
UInt32Zero almostTo: elemCount do: [:i {UInt32} |
newElements at: i store: (elements fetch: i)].
"Just for the hell of it, I make this robust for asynchronous readers..."
oldElements _ elements.
elements _ newElements.
oldElements destroy.
elemCount _ newSize.
tally == UInt32Zero ifTrue: [firstElem _ elements count - 1]!
*/
}
/**
* Enlarge the receiver to contain more slots filled with nil.
*/
public void enlargeBefore(IntegerValue toMinimum) {
int newSize;
PtrArray newElements;
PtrArray oldElements;
int offset;
int tmp;
IntegerValue stop;
stop = start.plus(IntegerValue.make(elemCount));
newSize = elemCount * 2;
if (newSize < 4) {
newSize = 4;
}
if (newSize < (tmp = (stop.minus(toMinimum)).asInt32() + 1)) {
newSize = tmp;
}
newElements = PtrArray.make(newSize);
offset = newSize - elemCount;
for (int i = 0; i < elemCount; i++) {
newElements.store(i + offset, (elements.fetch(i)));
}
oldElements = elements;
elements = newElements;
oldElements.destroy();
start = stop.minus(IntegerValue.make(newSize));
firstElem = firstElem + offset;
lastElem = lastElem + offset;
elemCount = newSize;
/*
udanax-top.st:50048:ActualIntegerTable methodsFor: 'private:'!
{void} enlargeBefore: toMinimum {IntegerVar}
"Enlarge the receiver to contain more slots filled with nil."
| newSize {UInt32} newElements {PtrArray} oldElements {PtrArray wimpy} offset {UInt32} tmp {UInt32} stop {IntegerVar} |
stop _ start + elemCount.
newSize _ elemCount * 2.
newSize < 4 ifTrue: [newSize _ 4].
newSize < (tmp _ (stop - toMinimum) DOTasLong + 1) ifTrue: [newSize _ tmp].
newElements _ PtrArray nulls: newSize.
offset _ newSize - elemCount.
UInt32Zero almostTo: elemCount do: [:i {UInt32} |
newElements at: i + offset store: (elements fetch: i)].
oldElements _ elements.
elements _ newElements.
oldElements destroy.
start _ stop - newSize.
firstElem _ firstElem + offset.
lastElem _ lastElem + offset.
elemCount _ newSize!
*/
}
/**
* This method returns the first table entry that is not NULL after index.
*/
public int firstElemAfter(int index) {
int idx;
if (tally == 0) {
return elemCount;
}
idx = index + 1;
while ((idx < lastElem) && ((elements.fetch(idx)) == null)) {
idx = idx + 1;
}
return idx;
/*
udanax-top.st:50068:ActualIntegerTable methodsFor: 'private:'!
{UInt32} firstElemAfter: index {UInt32}
"This method returns the first table entry that is not NULL after index."
| idx {UInt32} |
(tally == UInt32Zero) ifTrue: [^elemCount].
idx _ index + 1.
[(idx < lastElem) and: [(elements fetch: idx) == NULL]] whileTrue: [idx _ idx + 1].
^ idx!
*/
}
public IntegerRegion generateDomain() {
int begin;
IntegerRegion resReg;
IntegerRegion nextReg;
resReg = IntegerRegion.make();
if (tally == 0) {
return resReg;
}
begin = firstElem;
while (begin <= lastElem) {
nextReg = contigDomainStarting(begin);
if (nextReg.isEmpty()) {
nextReg = nullDomainStarting(begin);
} else {
resReg = (IntegerRegion) (resReg.unionWith(nextReg));
}
begin = (nextReg.stop().minus(start)).asInt32();
}
return resReg;
/*
udanax-top.st:50078:ActualIntegerTable methodsFor: 'private:'!
{IntegerRegion} generateDomain
| begin {UInt32} resReg {IntegerRegion} nextReg {IntegerRegion} |
resReg _ IntegerRegion make.
tally == UInt32Zero ifTrue: [^resReg].
begin _ firstElem.
[begin <= lastElem]
whileTrue:
[nextReg _ self contigDomainStarting: begin.
nextReg isEmpty
ifTrue: [nextReg _ self nullDomainStarting: begin]
ifFalse: [resReg _ (resReg unionWith: nextReg)
cast: IntegerRegion].
begin _ (nextReg stop - start) DOTasLong].
^resReg!
*/
}
/**
* This method returns the first table entry that is not NULL after index.
*/
public int lastElemBefore(int index) {
int idx;
if (tally == 0) {
return 0;
}
idx = index - 1;
while ((idx > firstElem) && ((elements.fetch(idx)) == null)) {
idx = idx - 1;
}
return idx;
/*
udanax-top.st:50093:ActualIntegerTable methodsFor: 'private:'!
{UInt32} lastElemBefore: index {UInt32}
"This method returns the first table entry that is not NULL after index."
| idx {UInt32} |
(tally == UInt32Zero) ifTrue: [^UInt32Zero].
idx _ index - 1.
[(idx > firstElem) and: [(elements fetch: idx) == NULL]] whileTrue: [idx _ idx - 1].
^ idx!
*/
}
/**
* return the size of the elements array for rapid processing
*/
public int maxElements() {
return elemCount;
/*
udanax-top.st:50103:ActualIntegerTable methodsFor: 'private:'!
{UInt32} maxElements
"return the size of the elements array for rapid processing"
^ elemCount!
*/
}
public IntegerRegion nullDomainStarting(int anIdx) {
int begin;
int tIdx;
tIdx = begin = anIdx;
while (tIdx <= lastElem && ((elements.fetch(tIdx)) == null)) {
tIdx = tIdx + 1;
}
if (tIdx > begin) {
return IntegerRegion.make(start.plus(IntegerValue.make(begin)), start.plus(IntegerValue.make(tIdx)));
} else {
return IntegerRegion.make(IntegerValue.make(anIdx), IntegerValue.make(anIdx));
}
/*
udanax-top.st:50107:ActualIntegerTable methodsFor: 'private:'!
{IntegerRegion} nullDomainStarting: anIdx {UInt32}
| begin {UInt32} tIdx {UInt32} |
tIdx _ begin _ anIdx.
[tIdx <= lastElem and: [(elements fetch: tIdx) == NULL]]
whileTrue: [tIdx _ tIdx + 1].
tIdx > begin
ifTrue: [^IntegerRegion make: start + begin with: start + tIdx]
ifFalse: [^IntegerRegion make: anIdx with: anIdx]!
*/
}
/**
* return the size of the elements array for rapid processing
*/
public IntegerValue startIndex() {
return start;
/*
udanax-top.st:50116:ActualIntegerTable methodsFor: 'private:'!
{IntegerVar} startIndex
"return the size of the elements array for rapid processing"
^ start!
*/
}
/**
* return the size of the elements array for rapid processing
*/
public int startOffset() {
return firstElem;
/*
udanax-top.st:50120:ActualIntegerTable methodsFor: 'private:'!
{UInt32} startOffset
"return the size of the elements array for rapid processing"
^ firstElem!
*/
}
// public void fixup() {
// super.fixup();
// while (((elements.fetch(lastElem)) == null) && (lastElem > 0)) {
// System.out.print("d");
// lastElem = lastElem - 1;
// }
// /*
// udanax-top.st:50126:ActualIntegerTable methodsFor: 'smalltalk: private:'!
// fixup
// super fixup.
// [((elements fetch: lastElem) == NULL) and: [lastElem > 0]] whileTrue: [
// Transcript show: 'd'.
// lastElem _ lastElem - 1]!
// */
// }
// public void inspect() {
// return InspectorView.open((IntegerTableInspector.inspect(this)));
// /*
// udanax-top.st:50132:ActualIntegerTable methodsFor: 'smalltalk: private:'!
// {void} inspect
// ^InspectorView open: (IntegerTableInspector inspect: self)!
// */
// }
public void destruct() {
elements.destroy();
elements = null;
super.destruct();
/*
udanax-top.st:50137:ActualIntegerTable methodsFor: 'protected: destruct'!
{void} destruct
elements destroy.
elements _ NULL.
super destruct!
*/
}
public void becomeCloneOnWrite(Heaper where) {
//TODO review new
IntegerTable tmp = new ActualIntegerTable(start, (start.plus(IntegerValue.make(lastElem))));
if (tally == 0) {
return;
}
TableStepper source = new ITAscendingStepper(this, start.plus(IntegerValue.make(firstElem)), start.plus(IntegerValue.make(lastElem)));
try {
Heaper tableElem;
while ((tableElem = (Heaper) source.fetch()) != null) {
tmp.atStore(source.position(), tableElem);
source.step();
}
} finally {
source.destroy();
}
/*
udanax-top.st:50144:ActualIntegerTable methodsFor: 'protected: COW stuff'!
{void} becomeCloneOnWrite: where {Heaper}
| tmp {IntegerTable} source {TableStepper} |
tmp _ (ActualIntegerTable new.Become: where) create: start with: (start + lastElem).
tally == UInt32Zero ifTrue: [^ VOID].
source _ ITAscendingStepper create: self with: start + firstElem with: start + lastElem.
source forEach: [ :tableElem {Heaper} |
tmp at: source position store: tableElem].!
*/
}
public Heaper atStore(Position key, Heaper value) {
return atIntStore(((IntegerPos) key).asIntegerVar(), value);
/*
udanax-top.st:50154:ActualIntegerTable methodsFor: 'overload junk'!
{Heaper} at: key {Position} store: value {Heaper}
^ self atInt: (key cast: IntegerPos) asIntegerVar store: value!
*/
}
public Heaper fetch(Position key) {
return intFetch((((IntegerPos) key).asIntegerVar()));
/*
udanax-top.st:50158:ActualIntegerTable methodsFor: 'overload junk'!
{Heaper} fetch: key {Position}
^ self intFetch: ((key cast: IntegerPos) asIntegerVar)!
*/
}
public boolean includesKey(Position aKey) {
return includesIntKey((((IntegerPos) aKey).asIntegerVar()));
/*
udanax-top.st:50162:ActualIntegerTable methodsFor: 'overload junk'!
{BooleanVar} includesKey: aKey {Position}
^ self includesIntKey: ((aKey cast: IntegerPos) asIntegerVar)!
*/
}
public XnRegion runAt(Position anIdx) {
return runAtInt((((IntegerPos) anIdx).asIntegerVar()));
/*
udanax-top.st:50165:ActualIntegerTable methodsFor: 'overload junk'!
{XnRegion} runAt: anIdx {Position}
^ self runAtInt: ((anIdx cast: IntegerPos) asIntegerVar)!
*/
}
public boolean wipe(Position key) {
return intWipe((((IntegerPos) key).asIntegerVar()));
/*
udanax-top.st:50168:ActualIntegerTable methodsFor: 'overload junk'!
{BooleanVar} wipe: key {Position}
^ self intWipe: ((key cast: IntegerPos) asIntegerVar)!
*/
}
public ActualIntegerTable(Rcvr receiver) {
super(receiver);
elements = (PtrArray) receiver.receiveHeaper();
start = receiver.receiveIntegerVar();
elemCount = receiver.receiveUInt32();
firstElem = receiver.receiveUInt32();
lastElem = receiver.receiveUInt32();
tally = receiver.receiveUInt32();
domainIsSimple = receiver.receiveBooleanVar();
/*
udanax-top.st:50173:ActualIntegerTable methodsFor: 'generated:'!
create.Rcvr: receiver {Rcvr}
super create.Rcvr: receiver.
elements _ receiver receiveHeaper.
start _ receiver receiveIntegerVar.
elemCount _ receiver receiveUInt32.
firstElem _ receiver receiveUInt32.
lastElem _ receiver receiveUInt32.
tally _ receiver receiveUInt32.
domainIsSimple _ receiver receiveBooleanVar.!
*/
}
public void sendSelfTo(Xmtr xmtr) {
super.sendSelfTo(xmtr);
xmtr.sendHeaper(elements);
xmtr.sendIntegerVar(start);
xmtr.sendUInt32(elemCount);
xmtr.sendUInt32(firstElem);
xmtr.sendUInt32(lastElem);
xmtr.sendUInt32(tally);
xmtr.sendBooleanVar(domainIsSimple);
/*
udanax-top.st:50183:ActualIntegerTable methodsFor: 'generated:'!
{void} sendSelfTo: xmtr {Xmtr}
super sendSelfTo: xmtr.
xmtr sendHeaper: elements.
xmtr sendIntegerVar: start.
xmtr sendUInt32: elemCount.
xmtr sendUInt32: firstElem.
xmtr sendUInt32: lastElem.
xmtr sendUInt32: tally.
xmtr sendBooleanVar: domainIsSimple.!
*/
}
}
| mit |
pixlepix/Aura-Cascade | src/main/java/pixlepix/auracascade/potions/PotionVioletCurse.java | 2035 | package pixlepix.auracascade.potions;
import net.minecraft.client.renderer.texture.TextureMap;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.potion.Potion;
import net.minecraft.potion.PotionEffect;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import pixlepix.auracascade.data.EnumRainbowColor;
import pixlepix.auracascade.item.ItemAngelsteelSword;
import java.util.List;
import java.util.Random;
/**
* Created by localmacaccount on 1/19/15.
*/
public class PotionVioletCurse extends Potion {
public PotionVioletCurse() {
super(true, EnumRainbowColor.VIOLET.color.getHex());
setPotionName("Violet Curse");
}
@Override
public boolean isReady(int p_76397_1_, int p_76397_2_) {
return new Random().nextInt(60) == 0;
}
@Override
@SideOnly(Side.CLIENT)
public void renderInventoryEffect(int x, int y, PotionEffect effect, net.minecraft.client.Minecraft mc) {
mc.renderEngine.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE);
mc.getRenderItem().renderItemIntoGUI(ItemAngelsteelSword.getStackFirstDegree(EnumRainbowColor.VIOLET), x + 8, y + 8);
}
@Override
public void performEffect(EntityLivingBase entity, int amplifier) {
List<EntityLivingBase> entities = entity.worldObj.getEntitiesWithinAABB(EntityLivingBase.class, new AxisAlignedBB(entity.posX - 15, entity.posY - 15, entity.posZ - 15, entity.posX + 15, entity.posY + 15, entity.posZ + 15));
EntityLivingBase entityLiving = entities.get(new Random().nextInt(entities.size()));
if (entityLiving != entity) {
//XOR, XOR, blah blah blah
double tempX = entity.posX;
double tempY = entity.posY;
double tempZ = entity.posZ;
entity.setPositionAndUpdate(entityLiving.posX, entityLiving.posY, entityLiving.posZ);
entityLiving.setPositionAndUpdate(tempX, tempY, tempZ);
}
}
} | mit |
rafabc/microservice-full-environment | microservice_eureka/src/main/java/com/micro/eureka/EurekaServerApp.java | 486 | package com.micro.eureka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
@SpringBootApplication
@EnableEurekaServer
@RefreshScope
public class EurekaServerApp {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApp.class, args);
}
}
| mit |
uber/nullaway | jar-infer/test-android-lib-jarinfer/src/main/java/com/uber/nullaway/jarinfer/toys/unannotated/Toys.java | 905 | package com.uber.nullaway.jarinfer.toys.unannotated;
public class Toys {
@ExpectNullable
public static String getString(boolean flag, String str) {
if (flag) {
return null;
}
return str;
}
public static void test(@ExpectNonnull String s, Foo f, @ExpectNonnull Bar b) {
if (s.length() >= 5) {
Foo f1 = new Foo(s);
f1.run(s);
} else {
f.run(s);
}
b.run(s);
}
public static void test1(@ExpectNonnull String s, String t, String u) {
if (s.length() >= 5) {
Foo fs = new Foo(s);
fs.run(u);
} else {
Foo ft = new Foo(t);
ft.run(u);
}
}
public static void main(String arg[]) throws java.io.IOException {
String s = "test string...";
Foo f = new Foo("let's");
Bar b = new Bar("try");
try {
test(s, f, b);
} catch (Error e) {
System.out.println(e.getMessage());
}
}
}
| mit |
xiaoysec/Youzi | youzi-portal/src/main/java/com/youzi/portal/service/impl/OrderServiceImpl.java | 1093 | package com.youzi.portal.service.impl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.youzi.http.response.entity.ResultEntity;
import com.youzi.portal.pojo.OrderInfo;
import com.youzi.portal.service.OrderService;
import com.youzi.utils.FastJsonUtils;
import com.youzi.utils.HttpClientUtils;
import com.youzi.utils.JsonUtils;
/**
* 订单service
*
* @author xiaoysec
*
*/
@Service
public class OrderServiceImpl implements OrderService {
@Value("${ORDER_BASE_URL}")
private String ORDER_BASE_URL;
@Value("${ORDER_CREATE_URL}")
private String ORDER_CREATE_URL;
@Override
public String createOrder(OrderInfo orderInfo) {
// 把OrderInfo转换成json
String json = JsonUtils.objectToJson(orderInfo);
// 提交订单数据
String jsonResult = HttpClientUtils.doPost(ORDER_BASE_URL + ORDER_CREATE_URL, json);
// 转换成java对象
ResultEntity result = FastJsonUtils.JsonToObject(jsonResult,ResultEntity.class);
// 取订单号
String orderId = result.getObj().toString();
return orderId;
}
}
| mit |
alect/Puzzledice | Tools/PuzzleMapEditor/src/puzzledice/ORBlock.java | 9826 | package puzzledice;
import gui.PuzzleEditPanel;
import gui.WindowMain;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.swing.BoxLayout;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import com.mxgraph.view.mxGraph;
public class ORBlock extends PuzzleBlock {
private PuzzleBlock _optionBlock1, _optionBlock2;
private static int nextIndex = 0;
public static void reset() {
nextIndex = 0;
}
private String _optionName1, _optionName2;
public void setOptionName1(String value) {
_optionName1 = value;
}
public void setOptionName2(String value) {
_optionName2 = value;
}
private JComboBox _optionSelect1, _optionSelect2;
public ORBlock()
{
_name = "OR-Block-" + ++nextIndex;
_type = "OR Block";
JPanel editPanel = new JPanel();
editPanel.setLayout(new BoxLayout(editPanel, BoxLayout.Y_AXIS));
JPanel optionPanel1 = new JPanel();
optionPanel1.setLayout(new BoxLayout(optionPanel1, BoxLayout.X_AXIS));
JLabel optionLabel1 = new JLabel("Option 1:");
optionPanel1.add(optionLabel1);
_optionSelect1 = new JComboBox();
_optionSelect1.setMaximumSize(new Dimension(Integer.MAX_VALUE, _optionSelect1.getPreferredSize().height));
optionPanel1.add(_optionSelect1);
editPanel.add(optionPanel1);
JPanel optionPanel2 = new JPanel();
optionPanel2.setLayout(new BoxLayout(optionPanel2, BoxLayout.X_AXIS));
JLabel optionLabel2 = new JLabel("Option 2:");
optionPanel2.add(optionLabel2);
_optionSelect2 = new JComboBox();
_optionSelect2.setMaximumSize(new Dimension(Integer.MAX_VALUE, _optionSelect2.getPreferredSize().height));
optionPanel2.add(_optionSelect2);
editPanel.add(optionPanel2);
_editUI = editPanel;
_optionSelect1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_optionBlock1 == _optionSelect1.getSelectedItem() || _optionBlock1 == null && _optionSelect1.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_optionSelect1.getSelectedItem() != null && !_optionSelect1.getSelectedItem().equals("None")) {
PuzzleBlock block = (PuzzleBlock)_optionSelect1.getSelectedItem();
if (block.canReachBlockBackwards(ORBlock.this)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_optionBlock1 != null)
_optionSelect1.setSelectedItem(_optionBlock1);
else
_optionSelect1.setSelectedIndex(0);
return;
}
}
// First, see if we need to remove a previous edge
if (_optionBlock1 != null) {
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_optionBlock1.getGraphCell(), _graphCell, false)); }
finally { puzzleGraph.getModel().endUpdate(); }
}
if (_optionSelect1.getSelectedItem() == null)
_optionSelect1.setSelectedIndex(0);
if (_optionSelect1.getSelectedItem().equals("None"))
_optionBlock1 = null;
else {
_optionBlock1 = (PuzzleBlock)_optionSelect1.getSelectedItem();
// Update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _optionBlock1.getGraphCell(), _graphCell); }
finally { puzzleGraph.getModel().endUpdate(); }
}
// Need to update our other option list
_optionSelect2.setModel(new DefaultComboBoxModel(makeComboBoxList2()));
// Update our selected values
if (_optionBlock2 == null)
_optionSelect2.setSelectedIndex(0);
else
_optionSelect2.setSelectedItem(_optionBlock2);
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
_optionSelect2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if(_optionBlock2 == _optionSelect2.getSelectedItem() || _optionBlock2 == null && _optionSelect2.getSelectedItem().equals("None"))
return;
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
// Before anything, check for a cycle
if (_optionSelect2.getSelectedItem() != null && !_optionSelect2.getSelectedItem().equals("None")) {
PuzzleBlock block = (PuzzleBlock)_optionSelect2.getSelectedItem();
if (block.canReachBlockBackwards(ORBlock.this)) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JOptionPane.showMessageDialog(null, "Error: Cannot add cycle to puzzle graph.");
}
});
if (_optionBlock2 != null)
_optionSelect2.setSelectedItem(_optionBlock2);
else
_optionSelect2.setSelectedIndex(0);
return;
}
}
// First, see if we need to remove a previous edge
if (_optionBlock2 != null) {
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.removeCells(puzzleGraph.getEdgesBetween(_optionBlock2.getGraphCell(), _graphCell, false)); }
finally { puzzleGraph.getModel().endUpdate(); }
}
if (_optionSelect2.getSelectedItem() == null)
_optionSelect2.setSelectedIndex(0);
if (_optionSelect2.getSelectedItem().equals("None"))
_optionBlock2 = null;
else {
_optionBlock2 = (PuzzleBlock)_optionSelect2.getSelectedItem();
// Update the graph with a new edge
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _optionBlock2.getGraphCell(), _graphCell); }
finally { puzzleGraph.getModel().endUpdate(); }
}
// Need to update our other option list
_optionSelect1.setModel(new DefaultComboBoxModel(makeComboBoxList1()));
// Update our selected values
if (_optionBlock1 == null)
_optionSelect1.setSelectedIndex(0);
else
_optionSelect1.setSelectedItem(_optionBlock1);
PuzzleEditPanel.resetTextualDescription();
WindowMain.updatePuzzleGraph();
}
});
}
@Override
public void update() {
// Update the UI comboBoxes
_optionSelect1.setModel(new DefaultComboBoxModel(makeComboBoxList1()));
// Update the selected values
if (_optionBlock1 == null)
_optionSelect1.setSelectedIndex(0);
else
_optionSelect1.setSelectedItem(_optionBlock1);
_optionSelect2.setModel(new DefaultComboBoxModel(makeComboBoxList2()));
if (_optionBlock2 == null)
_optionSelect2.setSelectedIndex(0);
else
_optionSelect2.setSelectedItem(_optionBlock2);
}
private Object[] makeComboBoxList1()
{
List<Object> retVal = new ArrayList<Object>();
PuzzleBlock[] blockList = PuzzleEditPanel.getBlockList();
retVal.add("None");
for (PuzzleBlock p : blockList) {
if (!p.equals(_optionSelect2.getSelectedItem()) && !p.equals(this))
retVal.add(p);
}
return retVal.toArray();
}
private Object[] makeComboBoxList2()
{
List<Object> retVal = new ArrayList<Object>();
PuzzleBlock[] blockList = PuzzleEditPanel.getBlockList();
retVal.add("None");
for (PuzzleBlock p : blockList) {
if (!p.equals(_optionSelect1.getSelectedItem()) && !p.equals(this))
retVal.add(p);
}
return retVal.toArray();
}
@Override
public void maybeRemoveRef(PuzzleBlock block)
{
if (block.equals(_optionBlock1)) {
_optionBlock1 = null;
_optionSelect1.setSelectedIndex(0);
}
if (block.equals(_optionBlock2)) {
_optionBlock2 = null;
_optionSelect2.setSelectedIndex(0);
}
}
@Override
public String getTextualDescription()
{
String retVal = "";
if (_optionBlock1 != null)
retVal += _optionBlock1.getTextualDescription();
if (_optionBlock2 != null)
retVal += _optionBlock2.getTextualDescription();
String input1 = (_optionBlock1 == null) ? "SOMETHING" : _optionBlock1.getOutputTempName();
String input2 = (_optionBlock2 == null) ? "SOMETHING" : _optionBlock2.getOutputTempName();
_outputTempName = "(" + input1 + " or " + input2 + ")";
return retVal;
}
@Override
public void attachBlocksToName(Map<String, AreaBlock> areas, Map<String, PuzzleBlock> puzzles)
{
mxGraph puzzleGraph = WindowMain.getPuzzleGraph();
if (_optionName1 != null) {
_optionBlock1 = puzzles.get(_optionName1);
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _optionBlock1.getGraphCell(), _graphCell); }
finally { puzzleGraph.getModel().endUpdate(); }
}
if (_optionName2 != null) {
_optionBlock2 = puzzles.get(_optionName2);
puzzleGraph.getModel().beginUpdate();
try { puzzleGraph.insertEdge(puzzleGraph.getDefaultParent(), null, null, _optionBlock2.getGraphCell(), _graphCell); }
finally { puzzleGraph.getModel().endUpdate(); }
}
this.update();
}
@Override
public PuzzleBlock[] getPuzzleInputs()
{
if (_optionBlock1 != null && _optionBlock2 != null)
return new PuzzleBlock[] { _optionBlock1, _optionBlock2 } ;
else if (_optionBlock1 != null)
return new PuzzleBlock[] { _optionBlock1 };
else if (_optionBlock2 != null)
return new PuzzleBlock[] { _optionBlock2 };
return new PuzzleBlock[0];
}
@Override
public String toXML()
{
String xml = "<ORBlock name=\"" + _name + "\" ";
if (_optionBlock1 != null)
xml += "option1=\"" + _optionBlock1.getName() + "\" ";
if (_optionBlock2 != null)
xml += "option2=\"" + _optionBlock2.getName() + "\" ";
xml += "/>";
return xml;
}
}
| mit |
horrorho/InflatableDonkey | src/main/java/com/github/horrorho/inflatabledonkey/cloudkitty/operations/RecordRetrieveRequestOperations.java | 3779 | /*
* The MIT License
*
* Copyright 2016 Ahseya.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.horrorho.inflatabledonkey.cloudkitty.operations;
import com.github.horrorho.inflatabledonkey.cloudkitty.CKProto;
import com.github.horrorho.inflatabledonkey.cloudkitty.CloudKitty;
import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.Operation;
import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.RecordRetrieveRequest;
import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.RecordRetrieveResponse;
import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.RequestOperation;
import com.github.horrorho.inflatabledonkey.protobuf.CloudKit.ResponseOperation;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.concurrent.Immutable;
import org.apache.http.client.HttpClient;
/**
* CloudKit M211 RecordRetrieveRequestOperation.
*
* @author Ahseya
*/
@Immutable
public final class RecordRetrieveRequestOperations {
public static List<RecordRetrieveResponse>
get(CloudKitty kitty, HttpClient httpClient, String zone, String... recordNames)
throws IOException {
return get(kitty, httpClient, zone, Arrays.asList(recordNames));
}
public static List<RecordRetrieveResponse>
get(CloudKitty kitty, HttpClient httpClient, String zone, Collection<String> recordNames)
throws IOException {
List<RequestOperation> operations = operations(zone, recordNames, kitty.cloudKitUserId());
return kitty.get(httpClient, API, KEY, operations, ResponseOperation::getRecordRetrieveResponse);
}
static List<RequestOperation>
operations(String zone, Collection<String> recordNames, String cloudKitUserId) {
return recordNames.stream()
.map(u -> operation(zone, u, cloudKitUserId))
.collect(Collectors.toList());
}
static RequestOperation operation(String zone, String recordName, String cloudKitUserId) {
return RequestOperation.newBuilder()
.setRequest(CKProto.operation(Operation.Type.RECORD_RETRIEVE_TYPE))
.setRecordRetrieveRequest(request(zone, recordName, cloudKitUserId))
.build();
}
static RecordRetrieveRequest request(String zone, String recordName, String cloudKitUserId) {
return RecordRetrieveRequest.newBuilder()
.setRecordIdentifier(CKProto.recordIdentifier(zone, recordName, cloudKitUserId))
.build();
}
private static final String KEY = "GetRecordsURLRequest";
private static final String API = "/record/retrieve";
}
| mit |
iotap-center/elis-platform | user service api/src/main/java/se/mah/elis/services/users/factory/UserFactory.java | 2573 | /**
*
*/
package se.mah.elis.services.users.factory;
import java.util.Properties;
import se.mah.elis.services.users.PlatformUser;
import se.mah.elis.services.users.User;
import se.mah.elis.services.users.exceptions.UserInitalizationException;
/**
* The UserFactory builds users. A UserProvider can register with a UserFactory
* so that the factory can produce the user types provided by the UserProvider.
*
* @author "Johan Holmberg, Malm\u00f6 University"
* @since 1.0
*/
public interface UserFactory {
/**
* Registers a user provider with this factory.
*
* @param provider The UserProvider to register.
* @since 1.0
*/
public void registerProvider(UserProvider provider);
/**
* Unregisters a user provider from this factory.
*
* @param provider The UserProvider to unregister.
* @since 1.0
*/
public void unregisterProvider(UserProvider provider);
/**
* Builds a user. As a user type can be provided by several different
* supporting services, we must also provide the name of the service that
* the user should target.
*
* @param userType The user type that we want to build. This should match
* the name of the implemented User interface.
* @param serviceName The name of the service that we want to target.
* @param properties The properties of the new user, as specified by its
* UserRecipe.
* @return The newly built User object.
* @throws UserInitalizationException if the user couldn't be built for
* whatever reason.
* @since 1.0
*/
public User build(String userType, String serviceName, Properties properties)
throws UserInitalizationException;
/**
* Builds a platform user.
*
* @param properties The properties of the new platform user, as specified
* by its UserRecipe.
* @return The newly built PlatformUser object.
* @throws UserInitalizationException if the user couldn't be built for
* whatever reason.
* @since 2.0
*/
public PlatformUser build(Properties properties)
throws UserInitalizationException;
/**
* Returns a list of all available user recipes.
*
* @return An array of user recipes. If no user recipes are available, the
* method returns an empty array.
* @since 1.0
*/
public UserRecipe[] getAvailableUserRecipes();
/**
* Returns a user recipe.
*
* @param userType The user type that we want a recipe for.
* @param systemName The name of the system providing the user.
* @return A user recipe.
* @since 1.0
*/
public UserRecipe getRecipe(String userType, String systemName);
}
| mit |
OblivionNW/Nucleus | src/main/java/io/github/nucleuspowered/nucleus/modules/warp/commands/CategoryCommand.java | 8538 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.warp.commands;
import com.google.common.collect.Lists;
import io.github.nucleuspowered.nucleus.Nucleus;
import io.github.nucleuspowered.nucleus.Util;
import io.github.nucleuspowered.nucleus.api.nucleusdata.WarpCategory;
import io.github.nucleuspowered.nucleus.argumentparsers.WarpCategoryArgument;
import io.github.nucleuspowered.nucleus.internal.annotations.RunAsync;
import io.github.nucleuspowered.nucleus.internal.annotations.command.NoModifiers;
import io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions;
import io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand;
import io.github.nucleuspowered.nucleus.internal.annotations.command.Scan;
import io.github.nucleuspowered.nucleus.internal.command.AbstractCommand;
import io.github.nucleuspowered.nucleus.modules.warp.services.WarpHandler;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.args.CommandElement;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.event.cause.Cause;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
import org.spongepowered.api.text.serializer.TextSerializers;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
@Scan
@Permissions(prefix = "warp")
@RegisterCommand(value = {"category"}, subcommandOf = WarpCommand.class, hasExecutor = false)
@NonnullByDefault
public class CategoryCommand extends AbstractCommand<CommandSource> {
private static final String key = "category";
private static final String displayname = "displayname";
private static final String description = "description";
@Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
return CommandResult.empty();
}
@Permissions(prefix = "warp.category", mainOverride = "list")
@RunAsync
@NoModifiers
@RegisterCommand(value = {"list"}, subcommandOf = CategoryCommand.class)
public static class ListCategoryCommand extends AbstractCommand<CommandSource> {
private final WarpHandler handler = getServiceUnchecked(WarpHandler.class);
@Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
// Get all the categories.
Util.getPaginationBuilder(src).contents(
this.handler.getWarpsWithCategories().keySet().stream().filter(Objects::nonNull)
.sorted(Comparator.comparing(WarpCategory::getId)).map(x -> {
List<Text> t = Lists.newArrayList();
t.add(Nucleus.getNucleus().getMessageProvider().getTextMessageWithTextFormat("command.warp.category.listitem.simple",
Text.of(x.getId()), x.getDisplayName()));
x.getDescription().ifPresent(y ->
t.add(Nucleus.getNucleus().getMessageProvider().getTextMessageWithTextFormat("command.warp.category.listitem.description", y)));
return t;
}).flatMap(Collection::stream).collect(Collectors.toList()))
.title(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.warp.category.listitem.title"))
.padding(Text.of("-", TextColors.GREEN))
.sendTo(src);
return CommandResult.success();
}
}
@Permissions(prefix = "warp.category", mainOverride = "displayname")
@RunAsync
@NoModifiers
@RegisterCommand(value = {"setdisplayname"}, subcommandOf = CategoryCommand.class)
public static class CategoryDisplayNameCommand extends AbstractCommand<CommandSource> {
private final WarpHandler handler = getServiceUnchecked(WarpHandler.class);
@Override public CommandElement[] getArguments() {
return new CommandElement[] {
new WarpCategoryArgument(Text.of(key), this.handler),
GenericArguments.onlyOne(GenericArguments.string(Text.of(displayname)))
};
}
@Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
WarpCategory category = args.<WarpCategory>getOne(key).get();
String displayName = args.<String>getOne(displayname).get();
this.handler.setWarpCategoryDisplayName(category.getId(), TextSerializers.FORMATTING_CODE.deserialize(args.<String>getOne(displayname).get()));
src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.warp.category.displayname.set", category.getId(),
displayName));
return CommandResult.success();
}
}
@Permissions(prefix = "warp.category", mainOverride = "displayname")
@RunAsync
@NoModifiers
@RegisterCommand(value = {"removedisplayname"}, subcommandOf = CategoryCommand.class)
public static class CategoryRemoveDisplayNameCommand extends AbstractCommand<CommandSource> {
private final WarpHandler handler = getServiceUnchecked(WarpHandler.class);
@Override public CommandElement[] getArguments() {
return new CommandElement[] {
new WarpCategoryArgument(Text.of(key), this.handler)
};
}
@Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
WarpCategory category = args.<WarpCategory>getOne(key).get();
this.handler.setWarpCategoryDisplayName(category.getId(), null);
src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.warp.category.displayname.removed", category.getId()));
return CommandResult.success();
}
}
@Permissions(prefix = "warp.category", mainOverride = "description")
@RunAsync
@NoModifiers
@RegisterCommand(value = {"setdescription"}, subcommandOf = CategoryCommand.class)
public static class CategoryDescriptionCommand extends AbstractCommand<CommandSource> {
private final WarpHandler handler = getServiceUnchecked(WarpHandler.class);
@Override public CommandElement[] getArguments() {
return new CommandElement[] {
new WarpCategoryArgument(Text.of(key), this.handler),
GenericArguments.onlyOne(GenericArguments.string(Text.of(description)))
};
}
@Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
WarpCategory category = args.<WarpCategory>getOne(key).get();
String d = args.<String>getOne(description).get();
this.handler.setWarpCategoryDescription(category.getId(), TextSerializers.FORMATTING_CODE.deserialize(d));
src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.warp.category.description.set", category.getId(), d));
return CommandResult.success();
}
}
@Permissions(prefix = "warp.category", mainOverride = "description")
@RunAsync
@NoModifiers
@RegisterCommand(value = {"removedescription"}, subcommandOf = CategoryCommand.class)
public static class CategoryRemoveDescriptionCommand extends AbstractCommand<CommandSource> {
private final WarpHandler handler = getServiceUnchecked(WarpHandler.class);
@Override public CommandElement[] getArguments() {
return new CommandElement[] {
new WarpCategoryArgument(Text.of(key), this.handler)
};
}
@Override protected CommandResult executeCommand(CommandSource src, CommandContext args, Cause cause) {
WarpCategory category = args.<WarpCategory>getOne(key).get();
this.handler.setWarpCategoryDescription(category.getId(), null);
src.sendMessage(Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.warp.category.description.removed", category.getId()));
return CommandResult.success();
}
}
}
| mit |
a7xr/studyJava | studyJava/src/StudyJava/StuffsTest.java | 875 | package StudyJava;
public class StuffsTest {
}
class NothingTest01 implements Runnable{
String txt = "this an object from nothingtest01";
int wait=500,
times =5;
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < this.times; i++) {
try {
System.out.println(this.txt);
Thread.sleep(this.wait);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class ThreadTest01 extends Thread{
String str = "";
int wait = 500, times = 5;
@Override
public void run() {
str = "this is a test";
try {
for (int i = 0; i < times; i++) {
System.out.println(this.str);
sleep(this.wait);
}
}catch (InterruptedException e) {
e.printStackTrace();
}
}
public void soping(String txt) {
System.out.println(txt);
}
} | mit |
gaborkolozsy/XChange | xchange-hitbtc/src/main/java/org/knowm/xchange/hitbtc/v2/service/HitbtcMarketDataServiceRaw.java | 1672 | package org.knowm.xchange.hitbtc.v2.service;
import java.io.IOException;
import java.util.List;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.currency.CurrencyPair;
import org.knowm.xchange.hitbtc.v2.dto.HitbtcOrderBook;
import org.knowm.xchange.hitbtc.v2.dto.HitbtcSort;
import org.knowm.xchange.hitbtc.v2.dto.HitbtcSymbol;
import org.knowm.xchange.hitbtc.v2.dto.HitbtcTicker;
import org.knowm.xchange.hitbtc.v2.dto.HitbtcTrade;
import org.knowm.xchange.hitbtc.v2.internal.HitbtcAdapters;
public class HitbtcMarketDataServiceRaw extends HitbtcBaseService {
public HitbtcMarketDataServiceRaw(Exchange exchange) {
super(exchange);
}
public List<HitbtcSymbol> getHitbtcSymbols() throws IOException {
return hitbtc.getSymbols();
}
public HitbtcTicker getHitbtcTicker(CurrencyPair currencyPair) throws IOException {
return hitbtc.getTicker(HitbtcAdapters.adaptCurrencyPair(currencyPair));
}
public HitbtcOrderBook getHitbtcOrderBook(CurrencyPair currencyPair) throws IOException {
return hitbtc.getOrderBook(HitbtcAdapters.adaptCurrencyPair(currencyPair));
}
public List<HitbtcTrade> getHitbtcTrades(CurrencyPair currencyPair) throws IOException {
return getHitbtcTrades(currencyPair, 100, HitbtcTrade.HitbtcTradesSortField.SORT_BY_TRADE_ID, HitbtcSort.SORT_ASCENDING, 0, 100);
}
//TODO add extra params in API
public List<HitbtcTrade> getHitbtcTrades(CurrencyPair currencyPair, long from, HitbtcTrade.HitbtcTradesSortField sortBy,
HitbtcSort sortDirection, long startIndex, long maxResults) throws IOException {
return hitbtc.getTrades(HitbtcAdapters.adaptCurrencyPair(currencyPair));
}
}
| mit |
bladestery/Sapphire | example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/alg/background/BackgroundModel.java | 2142 | /*
* Copyright (c) 2011-2015, Peter Abeles. All Rights Reserved.
*
* This file is part of BoofCV (http://boofcv.org).
*
* 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 boofcv.alg.background;
import boofcv.alg.misc.GImageMiscOps;
import boofcv.alg.misc.ImageMiscOps;
import boofcv.struct.image.ImageBase;
import boofcv.struct.image.ImageType;
/**
* Base class for background subtraction/motion detection.
*
* @author Peter Abeles
*/
public abstract class BackgroundModel<T extends ImageBase> {
// type of input image
protected ImageType<T> imageType;
// value assigned to pixels outside the image. Default to 0, which is background
protected byte unknownValue = 0;
public BackgroundModel(ImageType<T> imageType) {
this.imageType = imageType;
}
/**
* Resets model to its original state
*/
public abstract void reset(ImageMiscOps IMO, GImageMiscOps GIMO);
/**
* Returns the value that pixels in the segmented image are assigned if there is no background information.
*
* @return Value for unknown
*/
public int getUnknownValue() {
return unknownValue & 0xff;
}
/**
* Specify the value of a segmented pixel which has no corresponding pixel in the background image.
* @param unknownValue Value for pixels with out a background pixel. 2 to 255, inclusive.
*/
public void setUnknownValue(int unknownValue) {
if( unknownValue < 2 || unknownValue > 255 )
throw new IllegalArgumentException("out of range. 2 to 255");
this.unknownValue = (byte)unknownValue;
}
/**
* Type of input image it can process
*/
public ImageType<T> getImageType() {
return imageType;
}
}
| mit |
BoiseState/CS121-resources | examples/chap03/DiceRoll.java | 559 | import java.util.Random;
/**
* Demonstrates the creation of pseudo-random numbers using the Random class.
*
* @author CS121 Instructors
*/
public class DiceRoll
{
/**
* Generates a random dice roll
*/
public static void main(String[] args)
{
final int SIDES = 6;
// Try it with a seed: new Random(12345);
Random generator = new Random();
int roll1 = generator.nextInt(SIDES)+1;
int roll2 = generator.nextInt(SIDES)+1;
System.out.println("Roll 1: " + roll1);
System.out.println("Roll 2: " + roll2);
}
}
| mit |
aspose-pdf/Aspose.Pdf-for-Java | Examples/src/main/java/com/aspose/pdf/examples/AsposePdfExamples/Text/ExtractTextFromAnParticularPageRegion.java | 1069 | package com.aspose.pdf.examples.AsposePdfExamples.Text;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import com.aspose.pdf.Document;
import com.aspose.pdf.Rectangle;
import com.aspose.pdf.TextAbsorber;
public class ExtractTextFromAnParticularPageRegion {
public static void main(String[] args) throws IOException {
// open document
Document doc = new Document("page_0001.pdf");
// create TextAbsorber object to extract text
TextAbsorber absorber = new TextAbsorber();
absorber.getTextSearchOptions().setLimitToPageBounds(true);
absorber.getTextSearchOptions().setRectangle(new Rectangle(100, 200, 250, 350));
// accept the absorber for first page
doc.getPages().get_Item(1).accept(absorber);
// get the extracted text
String extractedText = absorber.getText();
// create a writer and open the file
BufferedWriter writer = new BufferedWriter(new FileWriter(new java.io.File("ExtractedText.txt")));
// write extracted contents
writer.write(extractedText);
// Close writer
writer.close();
}
}
| mit |
JeffRisberg/BING01 | examples/BingAdsDesktopApp/v9/AdExtensions.java | 23566 | package com.microsoft.bingads.examples.v9;
import java.rmi.*;
import java.util.ArrayList;
import com.microsoft.bingads.*;
import com.microsoft.bingads.campaignmanagement.*;
public class AdExtensions extends ExampleBaseV9 {
static AuthorizationData authorizationData;
static ServiceClient<ICampaignManagementService> CampaignService;
public static void main(java.lang.String[] args) {
try
{
authorizationData = new AuthorizationData();
authorizationData.setDeveloperToken(DeveloperToken);
authorizationData.setAuthentication(new PasswordAuthentication(UserName, Password));
authorizationData.setCustomerId(CustomerId);
authorizationData.setAccountId(AccountId);
CampaignService = new ServiceClient<ICampaignManagementService>(
authorizationData,
ICampaignManagementService.class);
// Specify one or more campaigns.
ArrayOfCampaign campaigns = new ArrayOfCampaign();
Campaign campaign = new Campaign();
campaign.setName("Winter Clothing " + System.currentTimeMillis());
campaign.setDescription("Winter clothing line.");
campaign.setBudgetType(BudgetLimitType.MONTHLY_BUDGET_SPEND_UNTIL_DEPLETED);
campaign.setMonthlyBudget(1000.00);
campaign.setTimeZone("PacificTimeUSCanadaTijuana");
campaign.setDaylightSaving(true);
campaigns.getCampaigns().add(campaign);
ArrayOflong campaignIds = addCampaigns(AccountId, campaigns);
printCampaignIdentifiers(campaignIds);
// Specify the extensions.
ArrayOfAdExtension adExtensions = new ArrayOfAdExtension();
AppAdExtension appAdExtension = new AppAdExtension();
appAdExtension.setAppPlatform("Windows");
appAdExtension.setAppStoreId("AppStoreIdGoesHere");
appAdExtension.setDestinationUrl("DestinationUrlGoesHere");
appAdExtension.setDisplayText("Contoso");
adExtensions.getAdExtensions().add(appAdExtension);
CallAdExtension callAdExtension = new CallAdExtension();
callAdExtension.setCountryCode("US");
callAdExtension.setPhoneNumber("2065550100");
callAdExtension.setIsCallOnly(false);
adExtensions.getAdExtensions().add(callAdExtension);
LocationAdExtension locationAdExtension = new LocationAdExtension();
locationAdExtension.setPhoneNumber("206-555-0100");
locationAdExtension.setCompanyName("Alpine Ski House");
locationAdExtension.setIconMediaId(null);
locationAdExtension.setImageMediaId(null);
Address address = new Address();
address.setStreetAddress("1234 Washington Place");
address.setStreetAddress2("Suite 1210");
address.setCityName("Woodinville");
address.setProvinceName("WA");
address.setCountryCode("US");
address.setPostalCode("98608");
locationAdExtension.setAddress(address);
adExtensions.getAdExtensions().add(locationAdExtension);
SiteLinksAdExtension siteLinksAdExtension = new SiteLinksAdExtension();
ArrayOfSiteLink siteLinks = new ArrayOfSiteLink();
SiteLink siteLink = new SiteLink();
siteLink.setDestinationUrl("AplineSkiHouse.com/WinterGloveSale");
siteLink.setDisplayText("Winter Glove Sale");
siteLinks.getSiteLinks().add(siteLink);
siteLinksAdExtension.setSiteLinks(siteLinks);
adExtensions.getAdExtensions().add(siteLinksAdExtension);
// Add all extensions to the account's ad extension library
ArrayOfAdExtensionIdentity adExtensionIdentities = addAdExtensions(
AccountId,
adExtensions
);
outputStatusMessage("Added ad extensions.\n");
// DeleteAdExtensionsAssociations, SetAdExtensionsAssociations, and GetAdExtensionsEditorialReasons
// operations each require a list of type AdExtensionIdToEntityIdAssociation.
ArrayOfAdExtensionIdToEntityIdAssociation adExtensionIdToEntityIdAssociations = new ArrayOfAdExtensionIdToEntityIdAssociation();
// GetAdExtensionsByIds requires a list of type long.
ArrayOflong adExtensionIds = new ArrayOflong();
// Loop through the list of extension IDs and build any required data structures
// for subsequent operations.
for (AdExtensionIdentity adExtensionIdentity : adExtensionIdentities.getAdExtensionIdentities()) {
AdExtensionIdToEntityIdAssociation adExtensionIdToEntityIdAssociation = new AdExtensionIdToEntityIdAssociation();
adExtensionIdToEntityIdAssociation.setAdExtensionId(adExtensionIdentity.getId());
adExtensionIdToEntityIdAssociation.setEntityId(campaignIds.getLongs().get(0));
adExtensionIdToEntityIdAssociations.getAdExtensionIdToEntityIdAssociations().add(adExtensionIdToEntityIdAssociation);
adExtensionIds.getLongs().add(adExtensionIdentity.getId());
}
// Associate the specified ad extensions with the respective campaigns or ad groups.
setAdExtensionsAssociations(
AccountId,
adExtensionIdToEntityIdAssociations,
AssociationType.CAMPAIGN
);
outputStatusMessage("Set ad extension associations.\n");
// Get editorial rejection reasons for the respective ad extension and entity associations.
ArrayOfAdExtensionEditorialReasonCollection adExtensionEditorialReasonCollection = getAdExtensionsEditorialReasons(
AccountId,
adExtensionIdToEntityIdAssociations,
AssociationType.CAMPAIGN
);
ArrayList<AdExtensionsTypeFilter> adExtensionsTypeFilter = new ArrayList<AdExtensionsTypeFilter>();
adExtensionsTypeFilter.add(AdExtensionsTypeFilter.APP_AD_EXTENSION);
adExtensionsTypeFilter.add(AdExtensionsTypeFilter.CALL_AD_EXTENSION);
adExtensionsTypeFilter.add(AdExtensionsTypeFilter.LOCATION_AD_EXTENSION);
adExtensionsTypeFilter.add(AdExtensionsTypeFilter.SITE_LINKS_AD_EXTENSION);
// Get the specified ad extensions from the accounts ad extension library.
adExtensions = getAdExtensionsByIds(
AccountId,
adExtensionIds,
adExtensionsTypeFilter
);
int index = 0;
for (AdExtension extension : adExtensions.getAdExtensions())
{
if (extension == null || extension.getId() == null)
{
outputStatusMessage("Extension is null or invalid.");
}
else
{
outputStatusMessage(String.format("Ad extension ID: %s\n", extension.getId()));
outputStatusMessage(String.format("Ad extension Type: %s\n", extension.getType()));
if (extension instanceof AppAdExtension)
{
outputStatusMessage(String.format("AppPlatform: %s\n", ((AppAdExtension)extension).getAppPlatform()));
outputStatusMessage(String.format("AppStoreId: %s\n", ((AppAdExtension)extension).getAppStoreId()));
outputStatusMessage(String.format("DestinationUrl: %s\n", ((AppAdExtension)extension).getDestinationUrl()));
outputStatusMessage(String.format("DevicePreference: %s\n", ((AppAdExtension)extension).getDevicePreference()));
outputStatusMessage(String.format("DisplayText: %s\n", ((AppAdExtension)extension).getDisplayText()));
outputStatusMessage(String.format("Id: %s\n", ((AppAdExtension)extension).getId()));
outputStatusMessage(String.format("Status: %s\n", ((AppAdExtension)extension).getStatus()));
outputStatusMessage(String.format("Version: %s\n", ((AppAdExtension)extension).getVersion()));
}
else if (extension instanceof CallAdExtension)
{
outputStatusMessage(String.format("Phone number: %s\n", ((CallAdExtension)extension).getPhoneNumber()));
outputStatusMessage(String.format("Country: %s\n", ((CallAdExtension)extension).getCountryCode()));
outputStatusMessage(String.format("Is only clickable item: %s\n", ((CallAdExtension)extension).getIsCallOnly()));
}
else if (extension instanceof LocationAdExtension)
{
if(((LocationAdExtension)extension).getAddress() != null){
outputStatusMessage(String.format("Street: %s\n", ((LocationAdExtension)extension).getAddress().getStreetAddress()));
outputStatusMessage(String.format("City: %s\n", ((LocationAdExtension)extension).getAddress().getCityName()));
outputStatusMessage(String.format("State: %s\n", ((LocationAdExtension)extension).getAddress().getProvinceName()));
outputStatusMessage(String.format("Country: %s\n", ((LocationAdExtension)extension).getAddress().getCountryCode()));
outputStatusMessage(String.format("Zip code: %s\n", ((LocationAdExtension)extension).getAddress().getPostalCode()));
}
outputStatusMessage(String.format("Company name: %s\n", ((LocationAdExtension)extension).getCompanyName()));
outputStatusMessage(String.format("Phone number: %s\n", ((LocationAdExtension)extension).getPhoneNumber()));
outputStatusMessage(String.format("Business coordinates determined?: %s\n", ((LocationAdExtension)extension).getGeoCodeStatus()));
if(((LocationAdExtension)extension).getGeoPoint() != null){
outputStatusMessage("GeoPoint: ");
outputStatusMessage(String.format("LatitudeInMicroDegrees: %s\n",
((LocationAdExtension)extension).getGeoPoint().getLatitudeInMicroDegrees()));
outputStatusMessage(String.format("LongitudeInMicroDegrees: %s\n",
((LocationAdExtension)extension).getGeoPoint().getLongitudeInMicroDegrees()));
}
outputStatusMessage(String.format("Map icon ID: %s\n", ((LocationAdExtension)extension).getIconMediaId()));
outputStatusMessage(String.format("Business image ID: %s\n", ((LocationAdExtension)extension).getImageMediaId()));
}
else if (extension instanceof SiteLinksAdExtension)
{
for (SiteLink sLink : ((SiteLinksAdExtension)extension).getSiteLinks().getSiteLinks())
{
outputStatusMessage(String.format(" Display URL: %s\n", sLink.getDisplayText()));
outputStatusMessage(String.format(" Destination URL: %s\n", sLink.getDestinationUrl()));
}
}
else
{
outputStatusMessage(" Unknown extension type");
}
if (adExtensionEditorialReasonCollection != null
&& adExtensionEditorialReasonCollection.getAdExtensionEditorialReasonCollections().size() > 0
&& adExtensionEditorialReasonCollection.getAdExtensionEditorialReasonCollections().get(index) != null)
{
outputStatusMessage("\n");
// Print any editorial rejection reasons for the corresponding extension. This sample
// assumes the same list index for adExtensions and adExtensionEditorialReasonCollection
// as defined above.
for (AdExtensionEditorialReason adExtensionEditorialReason :
adExtensionEditorialReasonCollection.getAdExtensionEditorialReasonCollections().get(index).getReasons().getAdExtensionEditorialReasons())
{
if (adExtensionEditorialReason != null &&
adExtensionEditorialReason.getPublisherCountries() != null)
{
outputStatusMessage("Editorial Rejection Location: " + adExtensionEditorialReason.getLocation());
outputStatusMessage("Editorial Rejection PublisherCountries: ");
for (java.lang.String publisherCountry : adExtensionEditorialReason.getPublisherCountries().getStrings())
{
outputStatusMessage(" " + publisherCountry);
}
outputStatusMessage("Editorial Rejection ReasonCode: " + adExtensionEditorialReason.getReasonCode());
outputStatusMessage("Editorial Rejection Term: " + adExtensionEditorialReason.getTerm());
outputStatusMessage("\n");
}
}
}
}
outputStatusMessage("\n");
index++;
}
// Remove the specified associations from the respective campaigns or ad groups.
// The extensions are still available in the account's extensions library.
deleteAdExtensionsAssociations(
AccountId,
adExtensionIdToEntityIdAssociations,
AssociationType.CAMPAIGN
);
outputStatusMessage("Deleted ad extension associations.\n");
// Deletes the ad extensions from the accounts ad extension library.
deleteAdExtensions(
AccountId,
adExtensionIds
);
outputStatusMessage("Deleted ad extensions.\n");
// Delete the campaign from the account.
deleteCampaigns(AccountId, campaignIds);
outputStatusMessage(String.format("Deleted CampaignId %d\n", campaignIds.getLongs().get(0)));
// Campaign Management service operations can throw AdApiFaultDetail.
} catch (AdApiFaultDetail_Exception ex) {
outputStatusMessage("The operation failed with the following faults:\n");
for (AdApiError error : ex.getFaultInfo().getErrors().getAdApiErrors())
{
outputStatusMessage("AdApiError\n");
outputStatusMessage(String.format("Code: %d\nError Code: %s\nMessage: %s\n\n",
error.getCode(), error.getErrorCode(), error.getMessage()));
}
// Campaign Management service operations can throw ApiFaultDetail.
} catch (ApiFaultDetail_Exception ex) {
outputStatusMessage("The operation failed with the following faults:\n");
for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors())
{
outputStatusMessage(String.format("BatchError at Index: %d\n", error.getIndex()));
outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
}
for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors())
{
outputStatusMessage("OperationError\n");
outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
}
// Some Campaign Management service operations such as SetAdExtensionsAssociations can throw EditorialApiFaultDetail.
} catch (EditorialApiFaultDetail_Exception ex) {
outputStatusMessage("The operation failed with the following faults:\n");
for (BatchError error : ex.getFaultInfo().getBatchErrors().getBatchErrors())
{
outputStatusMessage(String.format("BatchError at Index: %d\n", error.getIndex()));
outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
}
for (EditorialError error : ex.getFaultInfo().getEditorialErrors().getEditorialErrors())
{
outputStatusMessage(String.format("EditorialError at Index: %d\n\n", error.getIndex()));
outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
outputStatusMessage(String.format("Appealable: %s\nDisapproved Text: %s\nCountry: %s\n\n",
error.getAppealable(), error.getDisapprovedText(), error.getPublisherCountry()));
}
for (OperationError error : ex.getFaultInfo().getOperationErrors().getOperationErrors())
{
outputStatusMessage("OperationError\n");
outputStatusMessage(String.format("Code: %d\nMessage: %s\n\n", error.getCode(), error.getMessage()));
}
} catch (RemoteException ex) {
outputStatusMessage("Service communication error encountered: ");
outputStatusMessage(ex.getMessage());
ex.printStackTrace();
} catch (Exception ex) {
outputStatusMessage("Error encountered: ");
outputStatusMessage(ex.getMessage());
ex.printStackTrace();
}
}
// Adds one or more campaigns to the specified account.
static ArrayOflong addCampaigns(long accountId, ArrayOfCampaign campaigns) throws RemoteException, Exception
{
AddCampaignsRequest request = new AddCampaignsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setCampaigns(campaigns);
return CampaignService.getService().addCampaigns(request).getCampaignIds();
}
// Deletes one or more campaigns from the specified account.
static void deleteCampaigns(long accountId, ArrayOflong campaignIds) throws RemoteException, Exception
{
DeleteCampaignsRequest request = new DeleteCampaignsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setCampaignIds(campaignIds);
CampaignService.getService().deleteCampaigns(request);
}
// Adds one or more ad extensions to the account's ad extension library.
static ArrayOfAdExtensionIdentity addAdExtensions(long accountId, ArrayOfAdExtension adExtensions) throws RemoteException, Exception
{
AddAdExtensionsRequest request = new AddAdExtensionsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setAdExtensions(adExtensions);
return CampaignService.getService().addAdExtensions(request).getAdExtensionIdentities();
}
// Deletes one or more ad extensions from the accounts ad extension library.
static void deleteAdExtensions(long accountId, ArrayOflong adExtensionIds) throws RemoteException, Exception
{
DeleteAdExtensionsRequest request = new DeleteAdExtensionsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setAdExtensionIds(adExtensionIds);
CampaignService.getService().deleteAdExtensions(request);
}
// Associates one or more extensions with the corresponding campaign or ad group entities.
static void setAdExtensionsAssociations(long accountId, ArrayOfAdExtensionIdToEntityIdAssociation associations, AssociationType associationType) throws RemoteException, Exception
{
SetAdExtensionsAssociationsRequest request = new SetAdExtensionsAssociationsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setAdExtensionIdToEntityIdAssociations(associations);
request.setAssociationType(associationType);
CampaignService.getService().setAdExtensionsAssociations(request);
}
// Removes the specified association from the respective campaigns or ad groups.
static void deleteAdExtensionsAssociations(long accountId, ArrayOfAdExtensionIdToEntityIdAssociation associations, AssociationType associationType) throws RemoteException, Exception
{
DeleteAdExtensionsAssociationsRequest request = new DeleteAdExtensionsAssociationsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setAdExtensionIdToEntityIdAssociations(associations);
request.setAssociationType(associationType);
CampaignService.getService().deleteAdExtensionsAssociations(request);
}
// Gets the specified ad extensions from the account's extension library.
static ArrayOfAdExtension getAdExtensionsByIds(long accountId, ArrayOflong adExtensionIds, ArrayList<AdExtensionsTypeFilter> adExtensionsTypeFilter) throws RemoteException, Exception
{
GetAdExtensionsByIdsRequest request = new GetAdExtensionsByIdsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setAdExtensionIds(adExtensionIds);
request.setAdExtensionType(adExtensionsTypeFilter);
return CampaignService.getService().getAdExtensionsByIds(request).getAdExtensions();
}
// Gets the reasons why the specified extension failed editorial when
// in the context of an associated campaign or ad group.
private static ArrayOfAdExtensionEditorialReasonCollection getAdExtensionsEditorialReasons(
long accountId,
ArrayOfAdExtensionIdToEntityIdAssociation associations,
AssociationType associationType) throws RemoteException, Exception
{
GetAdExtensionsEditorialReasonsRequest request = new GetAdExtensionsEditorialReasonsRequest();
// Set the request information.
request.setAccountId(accountId);
request.setAdExtensionIdToEntityIdAssociations(associations);
request.setAssociationType(associationType);
return CampaignService.getService().getAdExtensionsEditorialReasons(request).getEditorialReasons();
}
// Prints the campaign identifiers for each campaign added.
static void printCampaignIdentifiers(ArrayOflong campaignIds)
{
if (campaignIds == null)
{
return;
}
for (long id : campaignIds.getLongs())
{
outputStatusMessage(String.format("Campaign successfully added and assigned CampaignId %d\n\n", id));
}
}
} | mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/compute/generated/VirtualMachineImagesGetSamples.java | 1949 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.compute.generated;
import com.azure.core.util.Context;
/** Samples for VirtualMachineImages Get. */
public final class VirtualMachineImagesGetSamples {
/*
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-11-01/examples/compute/VirtualMachineImages_Get_MinimumSet_Gen.json
*/
/**
* Sample code: VirtualMachineImages_Get_MinimumSet_Gen.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void virtualMachineImagesGetMinimumSetGen(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getVirtualMachineImages()
.getWithResponse(
"aaaaaaaaaaaa", "aaaaaaaaaaa", "aa", "aaaaaaaaa", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa", Context.NONE);
}
/*
* x-ms-original-file: specification/compute/resource-manager/Microsoft.Compute/stable/2021-11-01/examples/compute/VirtualMachineImages_Get_MaximumSet_Gen.json
*/
/**
* Sample code: VirtualMachineImages_Get_MaximumSet_Gen.
*
* @param azure The entry point for accessing resource management APIs in Azure.
*/
public static void virtualMachineImagesGetMaximumSetGen(com.azure.resourcemanager.AzureResourceManager azure) {
azure
.virtualMachines()
.manager()
.serviceClient()
.getVirtualMachineImages()
.getWithResponse(
"aaaaaa",
"aaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaaaaaaaaaa",
"aaaaaaaaaaaaaaaaaaa",
Context.NONE);
}
}
| mit |
miguelarauj1o/CalendarQuickStart | app/src/main/java/com/example/calendarquickstart/MainActivity.java | 11424 | package com.example.calendarquickstart;
import com.google.android.gms.common.ConnectionResult;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.util.ExponentialBackOff;
import com.google.api.services.calendar.CalendarScopes;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Arrays;
import java.util.List;
/**
* Created by miguel on 5/29/15.
*/
public class MainActivity extends Activity {
/**
* A Google Calendar API service object used to access the API.
* Note: Do not confuse this class with API library's model classes, which
* represent specific data structures.
*/
com.google.api.services.calendar.Calendar mService;
GoogleAccountCredential credential;
private TextView mStatusText;
private TextView mResultsText;
final HttpTransport transport = AndroidHttp.newCompatibleTransport();
final JsonFactory jsonFactory = GsonFactory.getDefaultInstance();
static final int REQUEST_ACCOUNT_PICKER = 1000;
static final int REQUEST_AUTHORIZATION = 1001;
static final int REQUEST_GOOGLE_PLAY_SERVICES = 1002;
private static final String PREF_ACCOUNT_NAME = "accountName";
private static final String[] SCOPES = { CalendarScopes.CALENDAR_READONLY };
/**
* Create the main activity.
* @param savedInstanceState previously saved instance data.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout activityLayout = new LinearLayout(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
activityLayout.setLayoutParams(lp);
activityLayout.setOrientation(LinearLayout.VERTICAL);
activityLayout.setPadding(16, 16, 16, 16);
ViewGroup.LayoutParams tlp = new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
mStatusText = new TextView(this);
mStatusText.setLayoutParams(tlp);
mStatusText.setTypeface(null, Typeface.BOLD);
mStatusText.setText("Retrieving data...");
activityLayout.addView(mStatusText);
mResultsText = new TextView(this);
mResultsText.setLayoutParams(tlp);
mResultsText.setPadding(16, 16, 16, 16);
mResultsText.setVerticalScrollBarEnabled(true);
mResultsText.setMovementMethod(new ScrollingMovementMethod());
activityLayout.addView(mResultsText);
setContentView(activityLayout);
// Initialize credentials and service object.
SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
credential = GoogleAccountCredential.usingOAuth2(
getApplicationContext(), Arrays.asList(SCOPES))
.setBackOff(new ExponentialBackOff())
.setSelectedAccountName(settings.getString(PREF_ACCOUNT_NAME, null));
mService = new com.google.api.services.calendar.Calendar.Builder(
transport, jsonFactory, credential)
.setApplicationName("Google Calendar API Android Quickstart")
.build();
}
/**
* Called whenever this activity is pushed to the foreground, such as after
* a call to onCreate().
*/
@Override
protected void onResume() {
super.onResume();
if (isGooglePlayServicesAvailable()) {
refreshResults();
} else {
mStatusText.setText("Google Play Services required: " +
"after installing, close and relaunch this app.");
}
}
/**
* Called when an activity launched here (specifically, AccountPicker
* and authorization) exits, giving you the requestCode you started it with,
* the resultCode it returned, and any additional data from it.
* @param requestCode code indicating which activity result is incoming.
* @param resultCode code indicating the result of the incoming
* activity result.
* @param data Intent (containing result data) returned by incoming
* activity result.
*/
@Override
protected void onActivityResult(
int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_GOOGLE_PLAY_SERVICES:
if (resultCode == RESULT_OK) {
refreshResults();
} else {
isGooglePlayServicesAvailable();
}
break;
case REQUEST_ACCOUNT_PICKER:
if (resultCode == RESULT_OK && data != null &&
data.getExtras() != null) {
String accountName =
data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
if (accountName != null) {
credential.setSelectedAccountName(accountName);
SharedPreferences settings =
getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(PREF_ACCOUNT_NAME, accountName);
editor.commit();
refreshResults();
}
} else if (resultCode == RESULT_CANCELED) {
mStatusText.setText("Account unspecified.");
}
break;
case REQUEST_AUTHORIZATION:
if (resultCode == RESULT_OK) {
refreshResults();
} else {
chooseAccount();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Attempt to get a set of data from the Google Calendar API to display. If the
* email address isn't known yet, then call chooseAccount() method so the
* user can pick an account.
*/
private void refreshResults() {
if (credential.getSelectedAccountName() == null) {
chooseAccount();
} else {
if (isDeviceOnline()) {
new ApiAsyncTask(this).execute();
} else {
mStatusText.setText("No network connection available.");
}
}
}
/**
* Clear any existing Google Calendar API data from the TextView and update
* the header message; called from background threads and async tasks
* that need to update the UI (in the UI thread).
*/
public void clearResultsText() {
runOnUiThread(new Runnable() {
@Override
public void run() {
mStatusText.setText("Retrieving data…");
mResultsText.setText("");
}
});
}
/**
* Fill the data TextView with the given List of Strings; called from
* background threads and async tasks that need to update the UI (in the
* UI thread).
* @param dataStrings a List of Strings to populate the main TextView with.
*/
public void updateResultsText(final List<String> dataStrings) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (dataStrings == null) {
mStatusText.setText("Error retrieving data!");
} else if (dataStrings.size() == 0) {
mStatusText.setText("No data found.");
} else {
mStatusText.setText("Data retrieved using" +
" the Google Calendar API:");
mResultsText.setText(TextUtils.join("\n\n", dataStrings));
}
}
});
}
/**
* Show a status message in the list header TextView; called from background
* threads and async tasks that need to update the UI (in the UI thread).
* @param message a String to display in the UI header TextView.
*/
public void updateStatus(final String message) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mStatusText.setText(message);
}
});
}
/**
* Starts an activity in Google Play Services so the user can pick an
* account.
*/
private void chooseAccount() {
startActivityForResult(
credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER);
}
/**
* Checks whether the device currently has a network connection.
* @return true if the device has a network connection, false otherwise.
*/
private boolean isDeviceOnline() {
ConnectivityManager connMgr =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected());
}
/**
* Check that Google Play services APK is installed and up to date. Will
* launch an error dialog for the user to update Google Play Services if
* possible.
* @return true if Google Play Services is available and up to
* date on this device; false otherwise.
*/
private boolean isGooglePlayServicesAvailable() {
final int connectionStatusCode =
GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (GooglePlayServicesUtil.isUserRecoverableError(connectionStatusCode)) {
showGooglePlayServicesAvailabilityErrorDialog(connectionStatusCode);
return false;
} else if (connectionStatusCode != ConnectionResult.SUCCESS ) {
return false;
}
return true;
}
/**
* Display an error dialog showing that Google Play Services is missing
* or out of date.
* @param connectionStatusCode code describing the presence (or lack of)
* Google Play Services on this device.
*/
void showGooglePlayServicesAvailabilityErrorDialog(
final int connectionStatusCode) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(
connectionStatusCode,
MainActivity.this,
REQUEST_GOOGLE_PLAY_SERVICES);
dialog.show();
}
});
}
} | mit |
magx2/jSupla | protocol-java/src/test/java/pl/grzeslowski/jsupla/protocoljava/common/GetVersionResultRandomizer.java | 1273 | package pl.grzeslowski.jsupla.protocoljava.common;
import io.github.benas.randombeans.api.EnhancedRandom;
import io.github.benas.randombeans.api.Randomizer;
import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.GetVersionResult;
import static pl.grzeslowski.jsupla.protocol.api.consts.JavaConsts.UNSIGNED_BYTE_MAX;
import static pl.grzeslowski.jsupla.protocol.api.consts.ProtoConsts.SUPLA_SOFTVER_MAXSIZE;
class GetVersionResultRandomizer implements Randomizer<GetVersionResult> {
private final EnhancedRandom random;
GetVersionResultRandomizer(final EnhancedRandom random) {
this.random = random;
}
@Override
public GetVersionResult getRandomValue() {
final int protoVersion = random.nextInt(UNSIGNED_BYTE_MAX - 2) + 1;
final int protoVersionMin = random.nextInt(protoVersion);
return new GetVersionResult(
protoVersionMin,
protoVersion,
generateSoftVer()
);
}
private String generateSoftVer() {
while (true) {
final String randomString = random.nextObject(String.class);
if (randomString.length() >= 1 && randomString.length() <= SUPLA_SOFTVER_MAXSIZE) {
return randomString;
}
}
}
}
| mit |
zhangjk4859/java-stuff | 管理合同项目/mybatis-generator/src/com/yuyanzhe/mybatis/numybeans/ConContract.java | 4852 | package com.yuyanzhe.mybatis.numybeans;
import java.math.BigDecimal;
import java.util.Date;
public class ConContract {
private Integer id;
private String mainCode;
private String mainName;
private String code;
private BigDecimal money;
private String moneyMax;
private String bankPop;
private String bankName;
private String bankCard;
private String regAddress;
private Date regDate;
private Date startDate;
private Date endDate;
private String linkeCustomer;
private String linkeAddress;
private String linkePhone;
private String createDate;
private String createUpdate;
private String remark;
private String remark2;
private String remark3;
private Integer status;
private Integer type;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMainCode() {
return mainCode;
}
public void setMainCode(String mainCode) {
this.mainCode = mainCode == null ? null : mainCode.trim();
}
public String getMainName() {
return mainName;
}
public void setMainName(String mainName) {
this.mainName = mainName == null ? null : mainName.trim();
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code == null ? null : code.trim();
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public String getMoneyMax() {
return moneyMax;
}
public void setMoneyMax(String moneyMax) {
this.moneyMax = moneyMax == null ? null : moneyMax.trim();
}
public String getBankPop() {
return bankPop;
}
public void setBankPop(String bankPop) {
this.bankPop = bankPop == null ? null : bankPop.trim();
}
public String getBankName() {
return bankName;
}
public void setBankName(String bankName) {
this.bankName = bankName == null ? null : bankName.trim();
}
public String getBankCard() {
return bankCard;
}
public void setBankCard(String bankCard) {
this.bankCard = bankCard == null ? null : bankCard.trim();
}
public String getRegAddress() {
return regAddress;
}
public void setRegAddress(String regAddress) {
this.regAddress = regAddress == null ? null : regAddress.trim();
}
public Date getRegDate() {
return regDate;
}
public void setRegDate(Date regDate) {
this.regDate = regDate;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getLinkeCustomer() {
return linkeCustomer;
}
public void setLinkeCustomer(String linkeCustomer) {
this.linkeCustomer = linkeCustomer == null ? null : linkeCustomer.trim();
}
public String getLinkeAddress() {
return linkeAddress;
}
public void setLinkeAddress(String linkeAddress) {
this.linkeAddress = linkeAddress == null ? null : linkeAddress.trim();
}
public String getLinkePhone() {
return linkePhone;
}
public void setLinkePhone(String linkePhone) {
this.linkePhone = linkePhone == null ? null : linkePhone.trim();
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate == null ? null : createDate.trim();
}
public String getCreateUpdate() {
return createUpdate;
}
public void setCreateUpdate(String createUpdate) {
this.createUpdate = createUpdate == null ? null : createUpdate.trim();
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark == null ? null : remark.trim();
}
public String getRemark2() {
return remark2;
}
public void setRemark2(String remark2) {
this.remark2 = remark2 == null ? null : remark2.trim();
}
public String getRemark3() {
return remark3;
}
public void setRemark3(String remark3) {
this.remark3 = remark3 == null ? null : remark3.trim();
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
} | mit |
blendee/blendee | src/main/java/org/blendee/internal/CollectionMap.java | 2203 | package org.blendee.internal;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Set;
/**
* 内部使用ユーティリティクラス
* @author 千葉 哲嗣
* @param <K> Key
* @param <V> Value
*/
@SuppressWarnings("javadoc")
public class CollectionMap<K, V> implements Cloneable {
private final Map<K, Collection<V>> map;
public static <V, K> CollectionMap<K, V> newInstance() {
return new CollectionMap<>();
}
public static <V, K> CollectionMap<K, V> newInstance(
@SuppressWarnings("rawtypes")
Class<? extends Map> mapClass) {
return new CollectionMap<>(mapClass);
}
public CollectionMap() {
map = new HashMap<>();
}
@SuppressWarnings("unchecked")
public CollectionMap(
@SuppressWarnings("rawtypes")
Class<? extends Map> mapClass) {
try {
this.map = mapClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void put(K key, V value) {
var collection = get(key);
collection.add(value);
}
public Collection<V> get(K key) {
Collection<V> collection = map.get(key);
if (collection == null) {
collection = createNewCollection();
map.put(key, collection);
}
return collection;
}
public Set<K> keySet() {
return map.keySet();
}
public Collection<V> remove(K key) {
Collection<V> collection = map.remove(key);
if (collection == null) return createNewCollection();
return collection;
}
public int size() {
return map.size();
}
public void clear() {
map.clear();
}
public boolean containsKey(K key) {
return map.containsKey(key);
}
public Map<K, Collection<V>> getInnerMap() {
return Collections.unmodifiableMap(map);
}
@Override
public CollectionMap<K, V> clone() {
CollectionMap<K, V> clone = newInstance(map.getClass());
for (var entry : map.entrySet()) {
var key = entry.getKey();
for (var value : entry.getValue()) {
clone.put(key, value);
}
}
return clone;
}
@Override
public String toString() {
return U.toString(this);
}
protected Collection<V> createNewCollection() {
return new LinkedList<>();
}
}
| mit |
NikitaKozlov/Pury | pury/src/main/java/com/nikitakozlov/pury/profile/StageError.java | 2034 | package com.nikitakozlov.pury.profile;
public class StageError {
public static StageError createError(String intendedStageName, Stage parentStage, Type type) {
return createError(intendedStageName, 0, parentStage, type);
}
public static StageError createError(String intendedStageName, int intendedStageOrder,
Stage parentStage, Type type) {
return new StageError(intendedStageName, intendedStageOrder, parentStage.getName(),
parentStage.getOrder(), type);
}
private final String intendedStageName;
private final int intendedStageOrder;
private final String parentStageName;
private final int parentStageOrder;
private final Type type;
private StageError(String intendedStageName, int intendedStageOrder, String parentStageName,
int parentStageOrder, Type type) {
this.intendedStageName = intendedStageName;
this.intendedStageOrder = intendedStageOrder;
this.parentStageName = parentStageName;
this.parentStageOrder = parentStageOrder;
this.type = type;
}
public Type getType() {
return type;
}
public String getIntendedStageName() {
return intendedStageName;
}
public int getIntendedStageOrder() {
return intendedStageOrder;
}
public String getParentStageName() {
return parentStageName;
}
public int getParentStageOrder() {
return parentStageOrder;
}
public boolean isInternal() {
return type.isInternal();
}
public enum Type {
START_TO_SMALL_ORDER,
START_PARENT_STAGE_IS_STOPPED(true),
START_PARENT_STAGE_NOT_STARTED(true),
STOP_NOT_STARTED_STAGE,
STOPPED_ALREADY;
private final boolean internal;
Type() {
internal = false;
}
Type(boolean internal) {
this.internal = internal;
}
public boolean isInternal() {
return internal;
}
}
}
| mit |
GammaAnalytics/dam | src/main/java/com/gamma/dam/db/wrapper/BaseDAO.java | 814 | /*
* **********************************************************************************************
* Copyright (C) 2015 Gamma Analytics, Inc. All rights reserved. *
* http://www.gammanalytics.com/ *
* --------------------------------------------------------------------------------------------*
* The software in this package is published under the terms of the EUL (End User license) *
* agreement a copy of which has been included with this distribution in the license.txt file. *
* **********************************************************************************************
*/
package com.gamma.dam.db.wrapper;
/**
* The Interface BaseDAO.
*
* @author abhijit
*/
public interface BaseDAO {
}
| mit |
arboliveira/steamside | webui/src/main/java/br/com/arbo/steamside/api/continues/ContinuesController.java | 506 | package br.com.arbo.steamside.api.continues;
import java.util.List;
import javax.inject.Inject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.arbo.steamside.api.app.AppDTO;
@RestController
@RequestMapping("continues")
public class ContinuesController {
@RequestMapping("continues.json")
public List<AppDTO> continues()
{
return this.continues.continues();
}
@Inject
private Continues continues;
}
| mit |
knotman90/IGPE2017 | code/src/Various/RandomString.java | 357 | package Various;
import java.util.Random;
public class RandomString {
private static final Random r = new Random(System.currentTimeMillis());
public static String randomAlphanumericString(int l){
StringBuilder sb = new StringBuilder();
for (int j = 0; j < l; j++) {
sb.append((char)('a'+r.nextInt('z'-'a')));
}
return sb.toString();
}
}
| mit |
felipepedroso/StarWarsCompanionApp | app/src/main/java/br/pedroso/starwars/StarWarsCompanionApplication.java | 855 | package br.pedroso.starwars;
import android.app.Application;
import br.pedroso.starwars.di.application.ApplicationComponent;
import br.pedroso.starwars.di.application.ApplicationModule;
import br.pedroso.starwars.di.application.DaggerApplicationComponent;
/**
* Created by felipe on 02/03/17.
*/
public class StarWarsCompanionApplication extends Application {
private ApplicationComponent applicationComponent;
@Override
public void onCreate() {
super.onCreate();
createApplicationComponent();
}
private void createApplicationComponent() {
applicationComponent = DaggerApplicationComponent.builder()
.applicationModule(new ApplicationModule(this))
.build();
}
public ApplicationComponent getApplicationComponent() {
return applicationComponent;
}
}
| mit |
phf/jb | examples/BasicOps.java | 3780 | import com.github.phf.jb.Bench;
import com.github.phf.jb.Bee;
/**
* Comparing basic operations on integers. The one thing that still seems to be
* true these days is that division/modulo is a LOT slower than anything else.
*/
public final class BasicOps {
private static final int COUNT = 1 << 21;
public static int x = 10, y = 20, z = 30;
public static int[] a = new int[COUNT];
public static boolean c = false;
@Bench
public void add(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y + i;
}
}
}
@Bench
public void subtract(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y - i;
}
}
}
@Bench
public void multiply(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y * i;
}
}
}
@Bench
public void divide(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y / i;
}
}
}
@Bench
public void modulo(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y % i;
}
}
}
@Bench
public void equals(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
c = x == i;
}
}
}
@Bench
public void less(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
c = x < i;
}
}
}
@Bench
public void and(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y & i;
}
}
}
@Bench
public void or(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = y | i;
}
}
}
@Bench
public void not(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = ~i;
}
}
}
@Bench
public void index(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 0; i < COUNT; i++) {
x = a[i];
}
}
}
@Bench
public void divideConstant(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y / 1037;
}
}
}
@Bench
public void divideConstantPowerOfTwo(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y / 1024;
}
}
}
@Bench
public void shiftRightConstant(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y >> 7;
}
}
}
@Bench
public void shiftLeftConstant(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y << 7;
}
}
}
@Bench
public void shiftRight(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y >> (i & 31);
}
}
}
@Bench
public void shiftLeft(Bee b) {
for (int n = 0; n < b.reps(); n++) {
for (int i = 1; i < COUNT+1; i++) {
x = y << (i & 31);
}
}
}
}
| mit |
wellenvogel/avnav | android/src/main/java/de/wellenvogel/avnav/aislib/messages/message/binary/BroadcastAreaNotice.java | 1329 | /* Copyright (c) 2011 Danish Maritime Authority.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.wellenvogel.avnav.aislib.messages.message.binary;
import de.wellenvogel.avnav.aislib.messages.binary.BinArray;
import de.wellenvogel.avnav.aislib.messages.binary.SixbitException;
/**
* Broadcast area notice ASM
*/
public class BroadcastAreaNotice extends AreaNotice {
public BroadcastAreaNotice() {
super(22);
}
public BroadcastAreaNotice(BinArray binArray) throws SixbitException {
super(22, binArray);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("BroadcastAreaNotice [");
builder.append(super.toString());
builder.append("]");
return builder.toString();
}
}
| mit |
alltiny/alltiny-chorus | chorus/src/main/java/org/alltiny/chorus/action/OpenFromFileAction.java | 2885 | package org.alltiny.chorus.action;
import org.alltiny.chorus.ApplicationProperties;
import org.alltiny.chorus.model.SongModel;
import org.alltiny.chorus.xml.XMLReader;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileInputStream;
import java.util.ResourceBundle;
import java.util.zip.GZIPInputStream;
/**
* This class represents
*
* @author <a href="mailto:ralf.hergert.de@gmail.com">Ralf Hergert</a>
* @version 04.02.2009 21:40:16
*/
public class OpenFromFileAction extends AbstractAction {
private static final String PROP_LAST_OPEN_DIR = "OpenFromFileAction.lastOpenDirectory";
private final SongModel model;
private final JFileChooser chooser;
private final ApplicationProperties properties;
public OpenFromFileAction(SongModel model, ApplicationProperties properties) {
putValue(Action.SMALL_ICON, new ImageIcon(getClass().getClassLoader().getResource("image/open.png")));
putValue(Action.SHORT_DESCRIPTION, ResourceBundle.getBundle("i18n.chorus").getString("OpenFromFileAction.ShortDescription"));
this.model = model;
this.properties = properties;
chooser = new JFileChooser();
chooser.setFileFilter(new FileFilter() {
public boolean accept(File f) {
return f.isDirectory() ||
f.getName().toLowerCase().endsWith(".xml") ||
f.getName().toLowerCase().endsWith(".xml.gz");
}
public String getDescription() {
return "*.xml, *.xml.gz";
}
});
// set the open path from the properties if existing.
if (properties.getProperty(PROP_LAST_OPEN_DIR) != null) {
chooser.setCurrentDirectory(new File(properties.getProperty(PROP_LAST_OPEN_DIR)));
}
}
public void actionPerformed(ActionEvent e) {
if (JFileChooser.APPROVE_OPTION == chooser.showOpenDialog(null)) {
try {
if (chooser.getSelectedFile().getName().toLowerCase().endsWith(".xml")) {
model.setSong(XMLReader.readSongFromXML(new FileInputStream(chooser.getSelectedFile())));
} else { // if (chooser.getSelectedFile().getName().toLowerCase().endsWith(".xml.gz"))
model.setSong(XMLReader.readSongFromXML(new GZIPInputStream(new FileInputStream(chooser.getSelectedFile()))));
}
// store the current directory in the properties.
properties.setProperty(PROP_LAST_OPEN_DIR, chooser.getCurrentDirectory().getAbsolutePath());
} catch (Exception ex) {
System.out.println("Error reading file '" + chooser.getSelectedFile().getAbsolutePath() + "':" + ex);
ex.printStackTrace();
}
}
}
}
| mit |
artsy/eigen | android/app/src/main/java/net/artsy/app/MainApplication.java | 3372 | package net.artsy.app;
import android.app.Application;
import android.content.Context;
import com.appboy.AppboyLifecycleCallbackListener;
import com.segment.analytics.android.integrations.adjust.AdjustIntegration;
import com.segment.analytics.Analytics;
import com.facebook.react.PackageList;
import com.facebook.react.ReactApplication;
import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.soloader.SoLoader;
import io.sentry.react.RNSentryPackage;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
public class MainApplication extends Application implements ReactApplication {
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
@Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
@SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
packages.add(new ArtsyNativePackage());
return packages;
}
@Override
protected String getJSMainModuleName() {
return "index";
}
};
@Override
public ReactNativeHost getReactNativeHost() {
return mReactNativeHost;
}
@Override
public void onCreate() {
super.onCreate();
SoLoader.init(this, /* native exopackage */ false);
initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
ArtsyNativeModule.didLaunch(
this.getSharedPreferences("launchConfig", MODE_PRIVATE));
String segmentWriteKey = BuildConfig.SEGMENT_PRODUCTION_WRITE_KEY_ANDROID;
if (BuildConfig.DEBUG) {
segmentWriteKey = BuildConfig.SEGMENT_STAGING_WRITE_KEY_ANDROID;
}
Analytics analytics = new Analytics.Builder(this, segmentWriteKey)
.use(AdjustIntegration.FACTORY)
.build();
Analytics.setSingletonInstance(analytics);
registerActivityLifecycleCallbacks(new AppboyLifecycleCallbackListener(true, true));
}
/**
* Loads Flipper in React Native templates. Call this in the onCreate method with something like
* initializeFlipper(this, getReactNativeHost().getReactInstanceManager());
*
* @param context
* @param reactInstanceManager
*/
private static void initializeFlipper(
Context context, ReactInstanceManager reactInstanceManager) {
if (BuildConfig.DEBUG) {
try {
/*
We use reflection here to pick up the class that initializes Flipper,
since Flipper library is not available in release mode
*/
Class<?> aClass = Class.forName("net.artsy.app.ReactNativeFlipper");
aClass
.getMethod("initializeFlipper", Context.class, ReactInstanceManager.class)
.invoke(null, context, reactInstanceManager);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
| mit |
AndyObtiva/collaborative-word-processor | src/test/java/samples/websocket/echo/SampleWebSocketsApplicationTests.java | 3891 | /*
* Copyright 2012-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package samples.websocket.echo;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import samples.websocket.client.GreetingService;
import samples.websocket.client.SimpleClientWebSocketHandler;
import samples.websocket.client.SimpleGreetingService;
import samples.websocket.config.SampleWebSocketsApplication;
import static org.junit.Assert.assertEquals;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SampleWebSocketsApplication.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
@DirtiesContext
public class SampleWebSocketsApplicationTests {
private static Log logger = LogFactory.getLog(SampleWebSocketsApplicationTests.class);
private static String WS_URI;
@Value("${local.server.port}")
private int port;
@Before
public void init() {
WS_URI = "ws://localhost:" + this.port + "/echo/websocket";
}
@Test
public void runAndWait() throws Exception {
ConfigurableApplicationContext context = SpringApplication.run(
ClientConfiguration.class, "--spring.main.web_environment=false");
long count = context.getBean(ClientConfiguration.class).latch.getCount();
context.close();
assertEquals(0, count);
}
@Configuration
static class ClientConfiguration implements CommandLineRunner {
private final CountDownLatch latch = new CountDownLatch(1);
@Override
public void run(String... args) throws Exception {
logger.info("Waiting for response: latch=" + this.latch.getCount());
this.latch.await(10, TimeUnit.SECONDS);
logger.info("Got response: latch=" + this.latch.getCount());
}
@Bean
public WebSocketConnectionManager wsConnectionManager() {
WebSocketConnectionManager manager = new WebSocketConnectionManager(client(),
handler(), WS_URI);
manager.setAutoStartup(true);
return manager;
}
@Bean
public StandardWebSocketClient client() {
return new StandardWebSocketClient();
}
@Bean
public SimpleClientWebSocketHandler handler() {
return new SimpleClientWebSocketHandler(greetingService(), this.latch);
}
@Bean
public GreetingService greetingService() {
return new SimpleGreetingService();
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/servicebus/azure-messaging-servicebus/src/main/java/com/azure/messaging/servicebus/administration/models/SqlRuleFilter.java | 3660 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.messaging.servicebus.administration.models;
import com.azure.core.util.logging.ClientLogger;
import com.azure.messaging.servicebus.ServiceBusMessage;
import java.util.HashMap;
import java.util.Map;
/**
* Represents a filter which is a composition of an expression and an action that is executed in the pub/sub pipeline.
* <p>
* A {@link SqlRuleFilter} holds a SQL-like condition expression that is evaluated in the broker against the arriving
* messages' user-defined properties and system properties. All system properties (which are all properties explicitly
* listed on the {@link ServiceBusMessage} class) must be prefixed with {@code sys.} in the condition expression. The
* SQL subset implements testing for existence of properties (EXISTS), testing for null-values (IS NULL), logical
* NOT/AND/OR, relational operators, numeric arithmetic, and simple text pattern matching with LIKE.
* </p>
*
* @see CreateRuleOptions#setFilter(RuleFilter)
* @see RuleProperties#setFilter(RuleFilter)
*/
public class SqlRuleFilter extends RuleFilter {
private final Map<String, Object> properties = new HashMap<>();
private final String sqlExpression;
private final String compatibilityLevel;
private final Boolean requiresPreprocessing;
/**
* Creates a new instance with the given SQL expression.
*
* @param sqlExpression SQL expression for the filter.
*
* @throws NullPointerException if {@code sqlExpression} is null.
* @throws IllegalArgumentException if {@code sqlExpression} is an empty string.
*/
public SqlRuleFilter(String sqlExpression) {
final ClientLogger logger = new ClientLogger(SqlRuleFilter.class);
if (sqlExpression == null) {
throw logger.logExceptionAsError(new NullPointerException("'sqlExpression' cannot be null."));
} else if (sqlExpression.isEmpty()) {
throw logger.logExceptionAsError(
new IllegalArgumentException("'sqlExpression' cannot be an empty string."));
}
this.sqlExpression = sqlExpression;
this.compatibilityLevel = null;
this.requiresPreprocessing = null;
}
/**
* Package private constructor for creating a model deserialised from the service.
*
* @param sqlExpression SQL expression for the filter.
* @param compatibilityLevel The compatibility level.
* @param requiresPreprocessing Whether or not it requires preprocessing
*/
SqlRuleFilter(String sqlExpression, String compatibilityLevel, Boolean requiresPreprocessing) {
this.sqlExpression = sqlExpression;
this.compatibilityLevel = compatibilityLevel;
this.requiresPreprocessing = requiresPreprocessing;
}
/**
* Gets the compatibility level.
*
* @return The compatibility level.
*/
String getCompatibilityLevel() {
return compatibilityLevel;
}
/**
* Gets whether or not requires preprocessing.
*
* @return Whether or not requires preprocessing.
*/
Boolean isPreprocessingRequired() {
return requiresPreprocessing;
}
/**
* Gets the value of a filter expression. Allowed types: string, int, long, bool, double
*
* @return Gets the value of a filter expression.
*/
public Map<String, Object> getParameters() {
return properties;
}
/**
* Gets the SQL expression.
*
* @return The SQL expression.
*/
public String getSqlExpression() {
return sqlExpression;
}
}
| mit |
jeremy8883/hamilton-heat-alert | shared/src/main/java/net/jeremycasey/hamiltonheatalert/utils/StackTrace.java | 345 | package net.jeremycasey.hamiltonheatalert.utils;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTrace {
public static String toString(Exception ex) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
ex.printStackTrace(pw);
return sw.toString();
}
} | mit |
owwlo/WebSearchEngine | src/edu/nyu/cs/cs2580/utils/FakeHttpExchange.java | 2692 | package edu.nyu.cs.cs2580.utils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sun.net.httpserver.Authenticator;
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpPrincipal;
import com.sun.net.httpserver.HttpServer;
public class FakeHttpExchange extends HttpExchange {
private Headers responseHeaders = new Headers();
private Headers requestHeaders = new Headers();
private String method = "GET";
private URI uri = null;
private OutputStream outputStream = new ByteArrayOutputStream();
private Map<String, Object> map = new HashMap<String, Object>();
public FakeHttpExchange(URI uri) {
super();
this.uri = uri;
}
@Override
public void close() {
}
public Map<String, Object> getAttributes() {
return map;
}
@Override
public Object getAttribute(String arg0) {
if (map.containsKey(arg0)) {
return map.get(arg0);
}
return null;
}
@Override
public HttpContext getHttpContext() {
return null;
}
@Override
public InetSocketAddress getLocalAddress() {
return null;
}
@Override
public HttpPrincipal getPrincipal() {
return null;
}
@Override
public String getProtocol() {
return null;
}
@Override
public InetSocketAddress getRemoteAddress() {
return null;
}
@Override
public InputStream getRequestBody() {
return null;
}
@Override
public Headers getRequestHeaders() {
return requestHeaders;
}
@Override
public String getRequestMethod() {
return method;
}
@Override
public URI getRequestURI() {
return uri;
}
@Override
public OutputStream getResponseBody() {
return outputStream;
}
@Override
public int getResponseCode() {
return 0;
}
@Override
public Headers getResponseHeaders() {
return responseHeaders;
}
@Override
public void sendResponseHeaders(int arg0, long arg1) throws IOException {
}
@Override
public void setAttribute(String arg0, Object arg1) {
map.put(arg0, arg1);
}
@Override
public void setStreams(InputStream arg0, OutputStream arg1) {
}
}
| mit |
turbo-xav/hello-world | my-diet/src/main/java/co/simplon/mydiet/model/entity/DietComponent.java | 1704 | package co.simplon.mydiet.model.entity;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "dietcomponent")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class DietComponent extends Commentable implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6345264871573285951L;
@Column(name = "description")
private String description;
@Column(name = "visual")
private String visual;
//@JsonBackReference
//@JsonIgnore
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "fk_category", nullable=true)
private Category category;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public DietComponent() {
}
public DietComponent(String name) {
super(name);
}
public DietComponent(String name,String description) {
this(name);
this.description = description;
}
public DietComponent(String name,String description,String visual) {
this(name,description);
this.visual = visual;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getVisual() {
return visual;
}
public void setVisual(String visual) {
this.visual = visual;
}
}
| mit |
Davids89/MyMoviesApp-Android | app/src/main/java/luque/david/mymoviesapp/models/MoviesWrapper.java | 410 | package luque.david.mymoviesapp.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by David on 10/1/16.
*/
public class MoviesWrapper {
@SerializedName("results")
private List<Movie> results;
public MoviesWrapper(List<Movie> results) {
this.results = results;
}
public List<Movie> getResults() {
return results;
}
}
| mit |
Neo-Desktop/Coleman-Code | COM107/Project1/Numbers.java | 2330 | /******************************************************************************
* Project: Project 1b *
* Class Name: Numbers *
* Author: Amrit Panesar -ASP ,o/ *
* Last Edited: 08/08/2012 *
* Hours: 0.25 Hours *
* Purpose: To declare variables, constant variables, explore promotions *
* explicit type casting, and display the results of these *
* activities. *
******************************************************************************/
public class Numbers // direction 1
{
public static void main(String[] args) // main
{
int iNumberTwo = 765, iNumberThree = (int) 4.75, iNumberFour = 17, iNumberFive = -2; // direction a + b
final int iNumberOne = 3; // as per directon a + c: iNumberOne must be constant
double dRealOne = 54.3, dRealTwo = 85, dRealThree = 67.56, dRealFour = 2, dRealFive = 3.3; // direction d + e
System.out.println("NumberOne stores " + iNumberOne); //direction f
System.out.println("NumberTwo stores " + iNumberTwo); //f
System.out.println("NumberThree stores " + iNumberThree); //f
System.out.println("NumberFour stores " + iNumberFour); //f
System.out.println("NumberFive stores " + iNumberFive); //f
System.out.println("RealOne stores " + dRealOne); //f
System.out.println("RealTwo stores " + dRealTwo); //f
System.out.println("RealThree stores " + dRealThree); //f
System.out.println("RealFour stores " + dRealFour); //f
System.out.println("RealFive stores " + dRealFive); //f
System.out.println("** Number Three is type casted as an integer"); // direction g
System.out.println("** Real Two is implicitly promoted as a double"); // direction h
}
}
/* Output:
E:\programs\Mod1\Project1>java Numbers
NumberOne stores 3
NumberTwo stores 765
NumberThree stores 4
NumberFour stores 17
NumberFive stores -2
RealOne stores 54.3
RealTwo stores 85.0
RealThree stores 67.56
RealFour stores 2.0
RealFive stores 3.3
** Number Three is type casted as an integer
** Real Two is implicitly promoted as a double
*/ | mit |
GeorgianB/DrHouseApp | app/src/main/java/ro/baratheon/doctorhouse/rendering/package-info.java | 742 | /*
* Copyright 2017 Google Inc. 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.
*/
/**
* This package contains classes that do the rendering for this example.
*/
package ro.baratheon.doctorhouse.rendering;
| mit |
aurus-nsk/world | src/main/java/com/world/repository/StreetRepository.java | 4436 | package com.world.repository;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import com.world.domain.Street;
@Repository
public class StreetRepository {
@Autowired
JdbcTemplate jdbcTemplate;
private static final Logger log = LoggerFactory.getLogger(StreetRepository.class);
public List<Street> findAll() {
List<Street> result = jdbcTemplate.query(
"SELECT id, name, extent FROM street",
(rs, rowNum) -> new Street(rs.getInt("id"), rs.getString("name"), rs.getInt("extent"))
);
result.forEach(street -> log.info("select: " + street.toString()));
return result;
}
public int save(Street input) {
String sql = "INSERT INTO street(name, extent) VALUES (?,?)";
KeyHolder holder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, input.getName());
ps.setInt(2, input.getExtent());
return ps;
}
}, holder);
Map<String, Object> map = holder.getKeys();
int id = (int) map.get("id");
log.info("insert: " + id + " " + input.toString());
return id;
}
public void saveAll(List<Street> list) {
String sql = "INSERT INTO street(name, extent) VALUES (?,?)";
jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Street item = list.get(i);
ps.setString(1, item.getName());
ps.setInt(2, item.getExtent());
}
@Override
public int getBatchSize() {
return list.size();
}
});
log.info("insert: " + Arrays.toString(list.toArray()));
}
public void updateFts() {
jdbcTemplate.update("UPDATE street SET streetfts=setweight( coalesce( to_tsvector('ru', name),''),'D');");
log.info("update street full text search index");
}
public Street findById(int id) {
Street result = jdbcTemplate.queryForObject(
"SELECT id, name, extent FROM street WHERE id = ?", new Object[] {id},
(rs, rowNum) -> new Street(rs.getInt("id"), rs.getString("name"), rs.getInt("extent"))
);
log.info("findById: " + result);
return result;
}
public void deleteById(int id) {
jdbcTemplate.update("DELETE from street WHERE id = ?", new Object[] {id});
log.info("deleteById: " + id);
}
public Map<Integer, Map<String,Object>> findStreet(int from, int to, String cityName, String query) {
final Map<Integer, Map<String,Object>> result = new HashMap<Integer, Map<String,Object>>();
String sql = "SELECT street.id, street.name as name, street.extent as extent, org.name as orgName "
+ "FROM street left join organization as org ON org.street_id = street.id left join city on org.city_id = city.id "
+ "WHERE street.extent >= ? AND street.extent <= ? AND city.name = ? "
+ "AND orgfts @@ to_tsquery(?)";
jdbcTemplate.query(sql, new RowCallbackHandler() {
@SuppressWarnings("unchecked")
@Override
public void processRow(ResultSet rs) throws SQLException {
result.putIfAbsent(rs.getInt("id"), new HashMap<String,Object>());
result.get(rs.getInt("id")).putIfAbsent("orgs", new ArrayList<String>());
result.get(rs.getInt("id")).putIfAbsent("name", rs.getString("name"));
result.get(rs.getInt("id")).putIfAbsent("extent", rs.getInt("extent"));
((List<String>)result.get(rs.getInt("id")).get("orgs")).add(rs.getString("orgName"));
}
}, new Object[]{from, to, cityName, query});
return result;
}
} | mit |
WillChen5/Study | Thread/src/main/java/will/study/thread/ScopeShareData.java | 1264 | package will.study.thread;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
/**
* Created by will on 16/8/29.
*/
public class ScopeShareData {
private static int data = 0;
private static Map<Thread, Integer> threadData = new HashMap<Thread, Integer>();
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
new Thread(new Runnable() {
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName() + " get data : " + data);
threadData.put(Thread.currentThread(), data);
new A().get();
new B().get();
}
}).start();
}
}
static class A{
public void get(){
int data = threadData.get(Thread.currentThread());
System.out.println("A from " + Thread.currentThread().getName() + " get data : " + data);
}
}
static class B{
public void get(){
int data = threadData.get(Thread.currentThread());
System.out.println("B from " + Thread.currentThread().getName() + " has put data : " + data);
}
}
}
| mit |
bacta/swg | game-server/src/main/java/com/ocdsoft/bacta/swg/server/chat/ChatNetworkConfiguration.java | 671 | package com.ocdsoft.bacta.swg.server.chat;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.ocdsoft.bacta.engine.conf.BactaConfiguration;
import com.ocdsoft.bacta.soe.io.udp.BaseNetworkConfiguration;
import com.ocdsoft.bacta.soe.io.udp.NetworkConfiguration;
import java.net.UnknownHostException;
/**
* Created by kyle on 4/12/2016.
*/
@Singleton
public final class ChatNetworkConfiguration extends BaseNetworkConfiguration implements NetworkConfiguration {
@Inject
public ChatNetworkConfiguration(final BactaConfiguration configuration) throws UnknownHostException {
super(configuration, "Bacta/ChatServer");
}
}
| mit |
isis-ammo/ammo-core | AmmoCore/src/main/java/edu/vu/isis/ammo/core/distributor/ResponseExecutor.java | 4142 | /* Copyright (c) 2010-2015 Vanderbilt University
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
*
*/
package edu.vu.isis.ammo.core.distributor;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.vu.isis.ammo.core.PLogger;
/**
* An executor which places request responses into the appropriate place.
* It does this by running RequestDeserializer runnable objects.
*
*/
public class ResponseExecutor extends ThreadPoolExecutor {
private static final Logger logger = LoggerFactory.getLogger("dist.resp.exec");
private static final Logger tlogger = LoggerFactory.getLogger("test.queue.insert");
private static final int N_THREADS = 1;
public static ResponseExecutor newInstance(final DistributorThread parent) {
final RequestDeserializer.Prioritizer prioritizer = new RequestDeserializer.Prioritizer();
final PriorityBlockingQueue<Runnable> responseQueue =
new PriorityBlockingQueue<Runnable>(200, prioritizer);
return new ResponseExecutor( parent, responseQueue );
}
private ResponseExecutor(final DistributorThread parent, final BlockingQueue<Runnable> responseQueue) {
super(N_THREADS, N_THREADS,
0L, TimeUnit.MILLISECONDS, responseQueue);
/** Saturation Policy */
this.setRejectedExecutionHandler( new ThreadPoolExecutor.CallerRunsPolicy() );
}
/**
* Print the log message indicating the status of the command.
*
* @parm runnable is the task which just completed.
* @parm throwable is the exception (null on success) thrown during the running of the runnable.
*/
@Override
protected void afterExecute(Runnable command, Throwable throwable) {
super.afterExecute(command, throwable);
if (throwable != null) {
logger.error("runnable failed", throwable);
return;
}
if (!(command instanceof RequestDeserializer)) {
logger.error("invalid runnable for response executor");
return;
}
final RequestDeserializer responseDeserializer = (RequestDeserializer)command;
final long currentTime = System.currentTimeMillis();
tlogger.info(PLogger.TEST_QUEUE_FORMAT,
currentTime,
"insert_queue",
this.getQueue().size(),
currentTime - responseDeserializer.item.timestamp);
}
@Override
public void execute(Runnable command) {
//super(new StringBuilder("Serializer-").append(Thread.activeCount()).toString());
if (!(command instanceof RequestDeserializer)) {
logger.error("unexpected command <{}>", command);
return;
}
final RequestDeserializer responseDeserializer= (RequestDeserializer)command;
super.execute(responseDeserializer);
}
}
| mit |
amitt03/spring-course-exercise-9 | exercise/src/main/java/springcourse/exercises/exercise9/controller/config/DocumentationConfig.java | 3509 | package springcourse.exercises.exercise9.controller.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.knappsack.swagger4springweb.controller.ApiDocumentationController;
import com.knappsack.swagger4springweb.util.ScalaObjectMapper;
import com.wordnik.swagger.model.ApiInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;
/**
* @author Amit Tal
* @since 1/8/14
*
* This configuration integrates with swagger in order to expose REST API documentation.
* The integration is done using swagger4spring-web plugin (site: https://github.com/wkennedy/swagger4spring-web).
* This plugin creates a controller under /api/resourceList.
* If called, the controller will scan the REST APIs and return a swagger json document readable by a swagger-ui.
*
* Notice, this configuration is under the "documentation" spring profile.
*/
@Configuration
@PropertySource({"classpath:documentation.properties"})
public class DocumentationConfig extends WebMvcConfigurerAdapter {
@Value("${documentation.services.basePath:@null}")
private String documentationServerBasePath;
@Value("${documentation.services.version:1.0}")
private String documentationVersion;
@Bean
public static PropertySourcesPlaceholderConfigurer configurer() {
return new PropertySourcesPlaceholderConfigurer();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters ) {
converters.add(converter());
}
@Bean
public HttpMessageConverter converter() {
MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
mappingJackson2HttpMessageConverter.setObjectMapper(scalaObjectMapper());
return mappingJackson2HttpMessageConverter;
}
@Bean
public ObjectMapper scalaObjectMapper() {
return new ScalaObjectMapper();
}
@Bean
public ApiDocumentationController apiDocumentationController() {
ApiDocumentationController apiDocumentationController = new ApiDocumentationController();
apiDocumentationController.setBasePath(documentationServerBasePath);
apiDocumentationController.setBaseControllerPackage("springcourse.exercises.exercise9.controller");
apiDocumentationController.setBaseModelPackage("springcourse.exercises.exercise9.model");
apiDocumentationController.setApiVersion(documentationVersion);
ApiInfo apiInfo = new ApiInfo("Spring Course Exercises",
"exercise 9",
null, null, null, null);
apiDocumentationController.setApiInfo(apiInfo);
return apiDocumentationController;
}
}
| mit |
jayhorn/jayhorn | soottocfg/src/main/java/soottocfg/ast/Absyn/Tint.java | 460 | package soottocfg.ast.Absyn; // Java Package generated by the BNF Converter.
public class Tint extends BasicType {
public Tint() { }
public <R,A> R accept(soottocfg.ast.Absyn.BasicType.Visitor<R,A> v, A arg) { return v.visit(this, arg); }
public boolean equals(Object o) {
if (this == o) return true;
if (o instanceof soottocfg.ast.Absyn.Tint) {
return true;
}
return false;
}
public int hashCode() {
return 37;
}
}
| mit |
simokhov/schemas44 | src/main/java/ru/gov/zakupki/oos/eptypes/_1/CriterionsScoringProtocolOKType.java | 9117 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2019.07.02 at 03:35:23 PM MSK
//
package ru.gov.zakupki.oos.eptypes._1;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import ru.gov.zakupki.oos.base._1.MeasurementOrderEnum;
/**
* Тип: Критерий оценки без показателей в протоколе в рамках проведения конкурсов в электронной форме
*
* <p>Java class for criterionsScoringProtocolOKType complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="criterionsScoringProtocolOKType">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="limit" type="{http://zakupki.gov.ru/oos/base/1}indicatorValueType" minOccurs="0"/>
* <element name="measurementOrder" type="{http://zakupki.gov.ru/oos/base/1}measurementOrderEnum"/>
* <element name="score" type="{http://zakupki.gov.ru/oos/base/1}valueType"/>
* <element name="normedScore" type="{http://zakupki.gov.ru/oos/base/1}valueType"/>
* <element name="offer" type="{http://zakupki.gov.ru/oos/base/1}indicatorValueType"/>
* <element name="offerText" type="{http://zakupki.gov.ru/oos/base/1}text2000Type" minOccurs="0"/>
* <element name="commissionMembersScoringInfo">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="commissionMemberScoringInfo" type="{http://zakupki.gov.ru/oos/EPtypes/1}scoringType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "criterionsScoringProtocolOKType", propOrder = {
"limit",
"measurementOrder",
"score",
"normedScore",
"offer",
"offerText",
"commissionMembersScoringInfo"
})
public class CriterionsScoringProtocolOKType {
protected BigDecimal limit;
@XmlElement(required = true)
@XmlSchemaType(name = "string")
protected MeasurementOrderEnum measurementOrder;
@XmlElement(required = true)
protected BigDecimal score;
@XmlElement(required = true)
protected BigDecimal normedScore;
@XmlElement(required = true)
protected BigDecimal offer;
protected String offerText;
@XmlElement(required = true)
protected CriterionsScoringProtocolOKType.CommissionMembersScoringInfo commissionMembersScoringInfo;
/**
* Gets the value of the limit property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getLimit() {
return limit;
}
/**
* Sets the value of the limit property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setLimit(BigDecimal value) {
this.limit = value;
}
/**
* Gets the value of the measurementOrder property.
*
* @return
* possible object is
* {@link MeasurementOrderEnum }
*
*/
public MeasurementOrderEnum getMeasurementOrder() {
return measurementOrder;
}
/**
* Sets the value of the measurementOrder property.
*
* @param value
* allowed object is
* {@link MeasurementOrderEnum }
*
*/
public void setMeasurementOrder(MeasurementOrderEnum value) {
this.measurementOrder = value;
}
/**
* Gets the value of the score property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getScore() {
return score;
}
/**
* Sets the value of the score property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setScore(BigDecimal value) {
this.score = value;
}
/**
* Gets the value of the normedScore property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getNormedScore() {
return normedScore;
}
/**
* Sets the value of the normedScore property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setNormedScore(BigDecimal value) {
this.normedScore = value;
}
/**
* Gets the value of the offer property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getOffer() {
return offer;
}
/**
* Sets the value of the offer property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setOffer(BigDecimal value) {
this.offer = value;
}
/**
* Gets the value of the offerText property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getOfferText() {
return offerText;
}
/**
* Sets the value of the offerText property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setOfferText(String value) {
this.offerText = value;
}
/**
* Gets the value of the commissionMembersScoringInfo property.
*
* @return
* possible object is
* {@link CriterionsScoringProtocolOKType.CommissionMembersScoringInfo }
*
*/
public CriterionsScoringProtocolOKType.CommissionMembersScoringInfo getCommissionMembersScoringInfo() {
return commissionMembersScoringInfo;
}
/**
* Sets the value of the commissionMembersScoringInfo property.
*
* @param value
* allowed object is
* {@link CriterionsScoringProtocolOKType.CommissionMembersScoringInfo }
*
*/
public void setCommissionMembersScoringInfo(CriterionsScoringProtocolOKType.CommissionMembersScoringInfo value) {
this.commissionMembersScoringInfo = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="commissionMemberScoringInfo" type="{http://zakupki.gov.ru/oos/EPtypes/1}scoringType" maxOccurs="unbounded"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"commissionMemberScoringInfo"
})
public static class CommissionMembersScoringInfo {
@XmlElement(required = true)
protected List<ScoringType> commissionMemberScoringInfo;
/**
* Gets the value of the commissionMemberScoringInfo property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the commissionMemberScoringInfo property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getCommissionMemberScoringInfo().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ScoringType }
*
*
*/
public List<ScoringType> getCommissionMemberScoringInfo() {
if (commissionMemberScoringInfo == null) {
commissionMemberScoringInfo = new ArrayList<ScoringType>();
}
return this.commissionMemberScoringInfo;
}
}
}
| mit |
sontx/chat-socket | src/main/java/com/blogspot/sontx/chatsocket/lib/bean/RegisterInfo.java | 429 | package com.blogspot.sontx.chatsocket.lib.bean;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class RegisterInfo implements Serializable {
private static final long serialVersionUID = -3586442439987010899L;
private String username;
private String password;
private String displayName;
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/reasonablespread/service/Send2.java | 11983 | /**
* Send2.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.reasonablespread.service;
public class Send2 implements java.io.Serializable {
private java.lang.String loginEmail;
private java.lang.String password;
private java.lang.String campaignName;
private java.lang.String from;
private java.lang.String fromName;
private java.lang.String to;
private java.lang.String subject;
private java.lang.String body;
public Send2() {
}
public Send2(
java.lang.String loginEmail,
java.lang.String password,
java.lang.String campaignName,
java.lang.String from,
java.lang.String fromName,
java.lang.String to,
java.lang.String subject,
java.lang.String body) {
this.loginEmail = loginEmail;
this.password = password;
this.campaignName = campaignName;
this.from = from;
this.fromName = fromName;
this.to = to;
this.subject = subject;
this.body = body;
}
/**
* Gets the loginEmail value for this Send2.
*
* @return loginEmail
*/
public java.lang.String getLoginEmail() {
return loginEmail;
}
/**
* Sets the loginEmail value for this Send2.
*
* @param loginEmail
*/
public void setLoginEmail(java.lang.String loginEmail) {
this.loginEmail = loginEmail;
}
/**
* Gets the password value for this Send2.
*
* @return password
*/
public java.lang.String getPassword() {
return password;
}
/**
* Sets the password value for this Send2.
*
* @param password
*/
public void setPassword(java.lang.String password) {
this.password = password;
}
/**
* Gets the campaignName value for this Send2.
*
* @return campaignName
*/
public java.lang.String getCampaignName() {
return campaignName;
}
/**
* Sets the campaignName value for this Send2.
*
* @param campaignName
*/
public void setCampaignName(java.lang.String campaignName) {
this.campaignName = campaignName;
}
/**
* Gets the from value for this Send2.
*
* @return from
*/
public java.lang.String getFrom() {
return from;
}
/**
* Sets the from value for this Send2.
*
* @param from
*/
public void setFrom(java.lang.String from) {
this.from = from;
}
/**
* Gets the fromName value for this Send2.
*
* @return fromName
*/
public java.lang.String getFromName() {
return fromName;
}
/**
* Sets the fromName value for this Send2.
*
* @param fromName
*/
public void setFromName(java.lang.String fromName) {
this.fromName = fromName;
}
/**
* Gets the to value for this Send2.
*
* @return to
*/
public java.lang.String getTo() {
return to;
}
/**
* Sets the to value for this Send2.
*
* @param to
*/
public void setTo(java.lang.String to) {
this.to = to;
}
/**
* Gets the subject value for this Send2.
*
* @return subject
*/
public java.lang.String getSubject() {
return subject;
}
/**
* Sets the subject value for this Send2.
*
* @param subject
*/
public void setSubject(java.lang.String subject) {
this.subject = subject;
}
/**
* Gets the body value for this Send2.
*
* @return body
*/
public java.lang.String getBody() {
return body;
}
/**
* Sets the body value for this Send2.
*
* @param body
*/
public void setBody(java.lang.String body) {
this.body = body;
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof Send2)) return false;
Send2 other = (Send2) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.loginEmail==null && other.getLoginEmail()==null) ||
(this.loginEmail!=null &&
this.loginEmail.equals(other.getLoginEmail()))) &&
((this.password==null && other.getPassword()==null) ||
(this.password!=null &&
this.password.equals(other.getPassword()))) &&
((this.campaignName==null && other.getCampaignName()==null) ||
(this.campaignName!=null &&
this.campaignName.equals(other.getCampaignName()))) &&
((this.from==null && other.getFrom()==null) ||
(this.from!=null &&
this.from.equals(other.getFrom()))) &&
((this.fromName==null && other.getFromName()==null) ||
(this.fromName!=null &&
this.fromName.equals(other.getFromName()))) &&
((this.to==null && other.getTo()==null) ||
(this.to!=null &&
this.to.equals(other.getTo()))) &&
((this.subject==null && other.getSubject()==null) ||
(this.subject!=null &&
this.subject.equals(other.getSubject()))) &&
((this.body==null && other.getBody()==null) ||
(this.body!=null &&
this.body.equals(other.getBody())));
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getLoginEmail() != null) {
_hashCode += getLoginEmail().hashCode();
}
if (getPassword() != null) {
_hashCode += getPassword().hashCode();
}
if (getCampaignName() != null) {
_hashCode += getCampaignName().hashCode();
}
if (getFrom() != null) {
_hashCode += getFrom().hashCode();
}
if (getFromName() != null) {
_hashCode += getFromName().hashCode();
}
if (getTo() != null) {
_hashCode += getTo().hashCode();
}
if (getSubject() != null) {
_hashCode += getSubject().hashCode();
}
if (getBody() != null) {
_hashCode += getBody().hashCode();
}
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(Send2.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://service.reasonablespread.com/", ">Send2"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("loginEmail");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "LoginEmail"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("password");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "Password"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("campaignName");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "CampaignName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("from");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "From"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("fromName");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "FromName"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("to");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "To"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("subject");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "Subject"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("body");
elemField.setXmlName(new javax.xml.namespace.QName("http://service.reasonablespread.com/", "Body"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(false);
typeDesc.addFieldDesc(elemField);
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| mit |
nindalf/smbc-droid | app/src/androidTest/java/com/smbc/droid/ApplicationTest.java | 345 | package com.smbc.droid;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2020_03_01/src/main/java/com/microsoft/azure/management/network/v2020_03_01/implementation/P2sVpnGatewaysImpl.java | 7218 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* def
*/
package com.microsoft.azure.management.network.v2020_03_01.implementation;
import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl;
import com.microsoft.azure.management.network.v2020_03_01.P2sVpnGateways;
import com.microsoft.azure.management.network.v2020_03_01.P2SVpnGateway;
import rx.Observable;
import rx.Completable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import com.microsoft.azure.arm.resources.ResourceUtilsCore;
import com.microsoft.azure.arm.utils.RXMapper;
import rx.functions.Func1;
import com.microsoft.azure.PagedList;
import com.microsoft.azure.Page;
import com.microsoft.azure.management.network.v2020_03_01.VpnProfileResponse;
import com.microsoft.azure.management.network.v2020_03_01.P2SVpnConnectionHealth;
import com.microsoft.azure.management.network.v2020_03_01.P2SVpnConnectionHealthRequest;
class P2sVpnGatewaysImpl extends GroupableResourcesCoreImpl<P2SVpnGateway, P2SVpnGatewayImpl, P2SVpnGatewayInner, P2sVpnGatewaysInner, NetworkManager> implements P2sVpnGateways {
protected P2sVpnGatewaysImpl(NetworkManager manager) {
super(manager.inner().p2sVpnGateways(), manager);
}
@Override
protected Observable<P2SVpnGatewayInner> getInnerAsync(String resourceGroupName, String name) {
P2sVpnGatewaysInner client = this.inner();
return client.getByResourceGroupAsync(resourceGroupName, name);
}
@Override
protected Completable deleteInnerAsync(String resourceGroupName, String name) {
P2sVpnGatewaysInner client = this.inner();
return client.deleteAsync(resourceGroupName, name).toCompletable();
}
@Override
public Observable<String> deleteByIdsAsync(Collection<String> ids) {
if (ids == null || ids.isEmpty()) {
return Observable.empty();
}
Collection<Observable<String>> observables = new ArrayList<>();
for (String id : ids) {
final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id);
final String name = ResourceUtilsCore.nameFromResourceId(id);
Observable<String> o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id);
observables.add(o);
}
return Observable.mergeDelayError(observables);
}
@Override
public Observable<String> deleteByIdsAsync(String...ids) {
return this.deleteByIdsAsync(new ArrayList<String>(Arrays.asList(ids)));
}
@Override
public void deleteByIds(Collection<String> ids) {
if (ids != null && !ids.isEmpty()) {
this.deleteByIdsAsync(ids).toBlocking().last();
}
}
@Override
public void deleteByIds(String...ids) {
this.deleteByIds(new ArrayList<String>(Arrays.asList(ids)));
}
@Override
public PagedList<P2SVpnGateway> listByResourceGroup(String resourceGroupName) {
P2sVpnGatewaysInner client = this.inner();
return this.wrapList(client.listByResourceGroup(resourceGroupName));
}
@Override
public Observable<P2SVpnGateway> listByResourceGroupAsync(String resourceGroupName) {
P2sVpnGatewaysInner client = this.inner();
return client.listByResourceGroupAsync(resourceGroupName)
.flatMapIterable(new Func1<Page<P2SVpnGatewayInner>, Iterable<P2SVpnGatewayInner>>() {
@Override
public Iterable<P2SVpnGatewayInner> call(Page<P2SVpnGatewayInner> page) {
return page.items();
}
})
.map(new Func1<P2SVpnGatewayInner, P2SVpnGateway>() {
@Override
public P2SVpnGateway call(P2SVpnGatewayInner inner) {
return wrapModel(inner);
}
});
}
@Override
public PagedList<P2SVpnGateway> list() {
P2sVpnGatewaysInner client = this.inner();
return this.wrapList(client.list());
}
@Override
public Observable<P2SVpnGateway> listAsync() {
P2sVpnGatewaysInner client = this.inner();
return client.listAsync()
.flatMapIterable(new Func1<Page<P2SVpnGatewayInner>, Iterable<P2SVpnGatewayInner>>() {
@Override
public Iterable<P2SVpnGatewayInner> call(Page<P2SVpnGatewayInner> page) {
return page.items();
}
})
.map(new Func1<P2SVpnGatewayInner, P2SVpnGateway>() {
@Override
public P2SVpnGateway call(P2SVpnGatewayInner inner) {
return wrapModel(inner);
}
});
}
@Override
public P2SVpnGatewayImpl define(String name) {
return wrapModel(name);
}
@Override
public Observable<VpnProfileResponse> generateVpnProfileAsync(String resourceGroupName, String gatewayName) {
P2sVpnGatewaysInner client = this.inner();
return client.generateVpnProfileAsync(resourceGroupName, gatewayName)
.map(new Func1<VpnProfileResponseInner, VpnProfileResponse>() {
@Override
public VpnProfileResponse call(VpnProfileResponseInner inner) {
return new VpnProfileResponseImpl(inner, manager());
}
});
}
@Override
public Observable<P2SVpnGateway> getP2sVpnConnectionHealthAsync(String resourceGroupName, String gatewayName) {
P2sVpnGatewaysInner client = this.inner();
return client.getP2sVpnConnectionHealthAsync(resourceGroupName, gatewayName)
.map(new Func1<P2SVpnGatewayInner, P2SVpnGateway>() {
@Override
public P2SVpnGateway call(P2SVpnGatewayInner inner) {
return new P2SVpnGatewayImpl(inner.name(), inner, manager());
}
});
}
@Override
public Observable<P2SVpnConnectionHealth> getP2sVpnConnectionHealthDetailedAsync(String resourceGroupName, String gatewayName, P2SVpnConnectionHealthRequest request) {
P2sVpnGatewaysInner client = this.inner();
return client.getP2sVpnConnectionHealthDetailedAsync(resourceGroupName, gatewayName, request)
.map(new Func1<P2SVpnConnectionHealthInner, P2SVpnConnectionHealth>() {
@Override
public P2SVpnConnectionHealth call(P2SVpnConnectionHealthInner inner) {
return new P2SVpnConnectionHealthImpl(inner, manager());
}
});
}
@Override
public Completable disconnectP2sVpnConnectionsAsync(String resourceGroupName, String p2sVpnGatewayName) {
P2sVpnGatewaysInner client = this.inner();
return client.disconnectP2sVpnConnectionsAsync(resourceGroupName, p2sVpnGatewayName).toCompletable();
}
@Override
protected P2SVpnGatewayImpl wrapModel(P2SVpnGatewayInner inner) {
return new P2SVpnGatewayImpl(inner.name(), inner, manager());
}
@Override
protected P2SVpnGatewayImpl wrapModel(String name) {
return new P2SVpnGatewayImpl(name, new P2SVpnGatewayInner(), this.manager());
}
}
| mit |
dachengxi/spring1.1.1_source | src/org/springframework/aop/framework/AdvisedSupportListener.java | 1026 | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.framework;
/**
*
* @author Rod Johnson
*/
public interface AdvisedSupportListener {
/**
* Invoked when first proxy is created
* @param advisedSupport
*/
void activated(AdvisedSupport advisedSupport);
/**
* Invoked when advice is changed after a proxy is created
* @param advisedSupport
*/
void adviceChanged(AdvisedSupport advisedSupport);
}
| mit |
joansmith/XChange | xchange-bitstamp/src/main/java/com/xeiam/xchange/bitstamp/BitstampAuthenticated.java | 4894 | package com.xeiam.xchange.bitstamp;
import com.xeiam.xchange.bitstamp.dto.BitstampException;
import com.xeiam.xchange.bitstamp.dto.account.*;
import com.xeiam.xchange.bitstamp.dto.trade.BitstampOrder;
import com.xeiam.xchange.bitstamp.dto.trade.BitstampUserTransaction;
import si.mazi.rescu.ParamsDigest;
import si.mazi.rescu.SynchronizedValueFactory;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.math.BigDecimal;
/**
* @author Benedikt Bünz See https://www.bitstamp.net/api/ for up-to-date docs.
*/
@Path("api")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public interface BitstampAuthenticated extends Bitstamp {
@POST
@Path("open_orders/")
public BitstampOrder[] getOpenOrders(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce) throws BitstampException, IOException;
@POST
@Path("buy/")
public BitstampOrder buy(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("amount") BigDecimal amount, @FormParam("price") BigDecimal price)
throws BitstampException, IOException;
@POST
@Path("sell/")
public BitstampOrder sell(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("amount") BigDecimal amount, @FormParam("price") BigDecimal price)
throws BitstampException, IOException;
/**
* @return true if order has been canceled.
*/
@POST
@Path("cancel_order/")
public boolean cancelOrder(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("id") int orderId) throws BitstampException, IOException;
@POST
@Path("balance/")
public BitstampBalance getBalance(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce) throws BitstampException, IOException;
@POST
@Path("user_transactions/")
public BitstampUserTransaction[] getUserTransactions(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("limit") long numberOfTransactions) throws BitstampException, IOException;
@POST
@Path("user_transactions/")
public BitstampUserTransaction[] getUserTransactions(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("limit") long numberOfTransactions, @FormParam("offset") long offset,
@FormParam("sort") String sort) throws BitstampException, IOException;
@POST
@Path("bitcoin_deposit_address/")
public BitstampDepositAddress getBitcoinDepositAddress(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce) throws BitstampException, IOException;
@POST
@Path("bitcoin_withdrawal/")
public BitstampWithdrawal withdrawBitcoin(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("amount") BigDecimal amount, @FormParam("address") String address)
throws BitstampException, IOException;
@POST
@Path("unconfirmed_btc/")
public DepositTransaction[] getUnconfirmedDeposits(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce) throws BitstampException, IOException;
@POST
@Path("withdrawal_requests/")
public WithdrawalRequest[] getWithdrawalRequests(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce) throws BitstampException, IOException;
/**
* Note that due to a bug on Bitstamp's side, withdrawal always fails if two-factor authentication is enabled for the account.
*/
@POST
@Path("ripple_withdrawal/")
public boolean withdrawToRipple(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce, @FormParam("amount") BigDecimal amount, @FormParam("currency") String currency,
@FormParam("address") String rippleAddress) throws BitstampException, IOException;
@POST
@Path("ripple_address/")
public BitstampRippleDepositAddress getRippleDepositAddress(@FormParam("key") String apiKey, @FormParam("signature") ParamsDigest signer,
@FormParam("nonce") SynchronizedValueFactory<Long> nonce) throws BitstampException, IOException;
}
| mit |
aisthesis/java-graph2013 | src/com/codemelon/graph/edge/EdgeTypeData.java | 566 | package com.codemelon.graph.edge;
/**
* Requires that an EdgeData object maintain an EdgeType (TREE, BACK, FORWARD, CROSS, UNKNOWN)
* @author Marshall Farrier
* @my.created Dec 16, 2012
* @my.edited Dec 16, 2012
*/
public interface EdgeTypeData {
/**
* Set the EdgeType contained in this EdgeData object
* @param edgeType value to which to set the edge type
*/
public void setEdgeType(EdgeType edgeType);
/**
* Retrieve the type of this EdgeData object
* @return the edge type stored in this EdgeData object
*/
public EdgeType getEdgeType();
}
| mit |
Daniel-Tilley/SimpleAndroidApps | MyActivity/app/src/test/java/myactivity/danieltilley/ie/myactivity/ExampleUnitTest.java | 330 | package myactivity.danieltilley.ie.myactivity;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
adorokhine/slf4j | slf4j-simple/src/test/java/org/slf4j/AutomaticallyNamedLoggerTest.java | 4425 | /**
* Copyright (c) 2004-2011 QOS.ch
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
package org.slf4j;
import static org.junit.Assert.assertEquals;
import java.io.PrintStream;
import java.lang.reflect.Method;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
/**
* Test whether the automatically named Logger implementation works.
*
* @author Alexander Dorokhine
*/
public class AutomaticallyNamedLoggerTest {
private static final Logger STATIC_LOGGER = LoggerFactory.getLogger();
// Static class used for testing logger names
private static class StaticNestedClass {
Logger logger = LoggerFactory.getLogger();
}
// Instance class used for testing logger names
private class InstanceNestedClass {
Logger logger = LoggerFactory.getLogger();
}
PrintStream old = System.err;
@Before
public void setUp() {
System.setErr(new SilentPrintStream(old));
}
@After
public void tearDown() {
System.setErr(old);
}
@Test
public void testSimpleClassNameFromInitializer() {
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest", STATIC_LOGGER.getName());
}
@Test
public void testSimpleClassNameFromMethod() {
Logger logger = LoggerFactory.getLogger();
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest", logger.getName());
}
@Test
public void testNamedInnerClassName() {
class MyTestInstanceClass {
Logger logger = LoggerFactory.getLogger();
}
MyTestInstanceClass instance = new MyTestInstanceClass();
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$1MyTestInstanceClass",
instance.logger.getName());
}
@Test
public void testAnonymousInnerClassName() {
new Runnable() {
Logger logger = LoggerFactory.getLogger();
public void run() {
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$1", logger.getName());
}
}.run();
}
@Test
public void testStaticInnerClassName() {
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$StaticNestedClass",
new StaticNestedClass().logger.getName());
}
@Test
public void testInstanceInnerClassName() {
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$InstanceNestedClass",
new InstanceNestedClass().logger.getName());
}
@Test
public void testNestedInnerClassName() {
new StaticNestedClass() {
Logger nestedLogger = LoggerFactory.getLogger();
public void run() {
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$StaticNestedClass",
logger.getName());
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$2", nestedLogger.getName());
}
}.run();
}
@Test
public void testLoggerThroughReflection() throws Exception {
Method getLoggerMethod = LoggerFactory.class.getMethod("getLogger");
Object logger = getLoggerMethod.invoke(null);
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest", ((Logger)logger).getName());
}
@Test
public void testLoggerFromThread() throws Exception {
Thread thread = new Thread() {
public void run() {
Logger logger = LoggerFactory.getLogger();
assertEquals("org.slf4j.AutomaticallyNamedLoggerTest$3", logger.getName());
}
};
thread.start();
thread.join();
}
}
| mit |
seanhold3n/sleep-analytics | src/test/java/model/DaySleepDurationMapTest.java | 4061 | package model;
import static org.junit.Assert.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;
import org.junit.Test;
public class DaySleepDurationMapTest {
private final String TEST_DATA_LOCATION = getClass().getResource("/data/map-test-data.csv").getPath();
// "/data/sean-sleep-data.csv"
// Max allowed delta for double precision operations
private final double DELTA = 0.01;
@Test
public void testGetInstance() {
// On very first run - should be empty
DaySleepDurationMap dsdm = DaySleepDurationMap.getInstance();
assertNotNull(dsdm);
// TODO guarantee that this test runs first
// assertTrue(dsdm.isEmpty());
// TODO more testing maybe
}
@Test
public void testAddToDay() {
// Create an arbitrary day
SimpleDay sd = new SimpleDay(2016, 03, 12);
// Add an entry to the map
DaySleepDurationMap dsdm = DaySleepDurationMap.getInstance();
dsdm.addToDay(sd, 6.0);
assertEquals(6.0, dsdm.get(sd), 0.05);
dsdm.addToDay(sd, 3.0);
assertEquals(9.0, dsdm.get(sd), 0.05);
}
@Test
public void testGetSimpleMovingAverage() {
// Load the map
loadMapWithTestData();
// System.out.println(DaySleepDurationMap.getInstance().toJSONArray());
// Populate the expected results
DayValuesMap expectedSMAs = new DayValuesMap();
expectedSMAs.put(new SimpleDay(2015, 12, 27), 7.83);
expectedSMAs.put(new SimpleDay(2015, 12, 28), 10.27);
expectedSMAs.put(new SimpleDay(2015, 12, 29), 8.076);
expectedSMAs.put(new SimpleDay(2015, 12, 30), 8.39);
expectedSMAs.put(new SimpleDay(2015, 12, 31), 9.07);
DayValuesMap actualSMAs = DaySleepDurationMap.getInstance().getSimpleMovingAverage(3);
System.out.println("DaySleepDurationMapTest - expected SMAs : " + expectedSMAs.toJSONArray());
System.out.println("DaySleepDurationMapTest - actual SMAa : " + actualSMAs.toJSONArray());
// Compare each value (this is to allow for a delta between double values)
// for (Map.Entry<SimpleDay, Double> e : actualSMAs.entrySet()){
// // Get the expected sma
// double expectedVal = expectedSMAs.get(e.getKey());
//
// // Compare against actual SMA
// assertEquals(expectedVal, e.getValue(), DELTA);
// }
for (Map.Entry<SimpleDay, Double> e : expectedSMAs.entrySet()){
// Get the expected sma
double actualVal = actualSMAs.get(e.getKey());
// Compare against actual SMA
assertEquals(actualVal, e.getValue(), DELTA);
}
}
/** Performs comprehensive data validation with the test set.
* @throws IOException
*/
@Test
public void testWithData() {
loadMapWithTestData();
// Make sure the data looks good
DaySleepDurationMap dsdm = DaySleepDurationMap.getInstance();
assertEquals(7, dsdm.size());
assertEquals(4.68, dsdm.get(new SimpleDay(2015, 12, 25)), DELTA);
assertEquals(13.08, dsdm.get(new SimpleDay(2015, 12, 26)), DELTA);
assertEquals(5.73, dsdm.get(new SimpleDay(2015, 12, 27)), DELTA);
assertEquals(12.0, dsdm.get(new SimpleDay(2015, 12, 28)), DELTA);
assertEquals(6.50, dsdm.get(new SimpleDay(2015, 12, 29)), DELTA);
assertEquals(6.67, dsdm.get(new SimpleDay(2015, 12, 30)), DELTA);
assertEquals(14.04, dsdm.get(new SimpleDay(2015, 12, 31)), DELTA);
}
private void loadMapWithTestData(){
// Empty map
DaySleepDurationMap.getInstance().clear();
// Get CSV file
try (BufferedReader br = new BufferedReader(new FileReader(new File(TEST_DATA_LOCATION)))){
String line = "";
// Ignore the first line (CSV header)
br.readLine();
while (((line = br.readLine()) != null)){
// Convert the line from CSV to a SleepEntry
SleepEntry se = SleepEntry.parseFromCSV(line);
// Add data from that to the map
DaySleepDurationMap.getInstance().addToDay(se.getEffectiveDate(), se.getDuration());
}
} catch (FileNotFoundException fnfe){
fail("File not found, dawg!");
} catch (IOException ioe){
ioe.printStackTrace();
fail("IOException, dawg!");
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/formrecognizer/azure-ai-formrecognizer/src/samples/java/com/azure/ai/formrecognizer/Authentication.java | 9042 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.formrecognizer;
import com.azure.ai.formrecognizer.administration.DocumentModelAdministrationClient;
import com.azure.ai.formrecognizer.administration.DocumentModelAdministrationClientBuilder;
import com.azure.ai.formrecognizer.administration.models.AccountProperties;
import com.azure.ai.formrecognizer.models.AnalyzeResult;
import com.azure.ai.formrecognizer.models.AnalyzedDocument;
import com.azure.ai.formrecognizer.models.DocumentField;
import com.azure.ai.formrecognizer.models.DocumentFieldType;
import com.azure.ai.formrecognizer.models.DocumentOperationResult;
import com.azure.core.credential.AzureKeyCredential;
import com.azure.core.util.polling.SyncPoller;
import com.azure.identity.AzureAuthorityHosts;
import com.azure.identity.DefaultAzureCredentialBuilder;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
/**
* Samples for two supported methods of authentication in Document Analysis and Document Model Administration clients:
* 1) Use a Form Recognizer API key with AzureKeyCredential from azure.core.credentials
* 2) Use a token credential from azure-identity to authenticate with Azure Active Directory
*/
public class Authentication {
/**
* Main method to invoke this demo.
*
* @param args Unused arguments to the program.
*/
public static void main(String[] args) {
/*
Set the environment variables with your own values before running the sample:
AZURE_CLIENT_ID - the client ID of your active directory application.
AZURE_TENANT_ID - the tenant ID of your active directory application.
AZURE_CLIENT_SECRET - the secret of your active directory application.
*/
// Document Analysis client: Key credential
authenticationWithKeyCredentialDocumentAnalysisClient();
// Document Analysis client: Azure Active Directory
authenticationWithAzureActiveDirectoryDocumentAnalysisClient();
// Document Analysis client: Azure Active Directory : China Cloud
authenticationWithAzureActiveDirectoryChinaCloud();
// Document Model Administration client: Key credential
authenticationWithKeyCredentialDocumentModelAdministrationClient();
// Document Model Administration client: Azure Active Directory
authenticationWithAzureActiveDirectoryDocumentModelAdministrationClient();
}
private static void authenticationWithKeyCredentialDocumentAnalysisClient() {
DocumentAnalysisClient documentAnalysisClient = new DocumentAnalysisClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
beginRecognizeCustomFormsFromUrl(documentAnalysisClient);
}
private static void authenticationWithAzureActiveDirectoryDocumentAnalysisClient() {
DocumentAnalysisClient documentAnalysisClient = new DocumentAnalysisClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("{endpoint}")
.buildClient();
beginRecognizeCustomFormsFromUrl(documentAnalysisClient);
}
private static void authenticationWithAzureActiveDirectoryChinaCloud() {
DocumentAnalysisClient documentAnalysisClient = new DocumentAnalysisClientBuilder()
.credential(new DefaultAzureCredentialBuilder().authorityHost(AzureAuthorityHosts.AZURE_CHINA).build())
.endpoint("https://{endpoint}.cognitiveservices.azure.cn/")
.buildClient();
beginRecognizeCustomFormsFromUrl(documentAnalysisClient);
}
private static void authenticationWithKeyCredentialDocumentModelAdministrationClient() {
DocumentModelAdministrationClient documentModelAdminClient = new DocumentModelAdministrationClientBuilder()
.credential(new AzureKeyCredential("{key}"))
.endpoint("{endpoint}")
.buildClient();
getAccountProperties(documentModelAdminClient);
}
private static void authenticationWithAzureActiveDirectoryDocumentModelAdministrationClient() {
DocumentModelAdministrationClient documentModelAdminClient = new DocumentModelAdministrationClientBuilder()
.credential(new DefaultAzureCredentialBuilder().build())
.endpoint("{endpoint}")
.buildClient();
getAccountProperties(documentModelAdminClient);
}
private static void beginRecognizeCustomFormsFromUrl(DocumentAnalysisClient documentAnalysisClient) {
String receiptUrl =
"https://raw.githubusercontent.com/Azure/azure-sdk-for-java/main/sdk/formrecognizer"
+ "/azure-ai-formrecognizer/src/samples/resources/sample-forms/receipts/contoso-allinone.jpg";
SyncPoller<DocumentOperationResult, AnalyzeResult> analyzeReceiptPoller =
documentAnalysisClient.beginAnalyzeDocumentFromUrl("prebuilt-receipt", receiptUrl);
AnalyzeResult receiptResults = analyzeReceiptPoller.getFinalResult();
for (int i = 0; i < receiptResults.getDocuments().size(); i++) {
AnalyzedDocument analyzedReceipt = receiptResults.getDocuments().get(i);
Map<String, DocumentField> receiptFields = analyzedReceipt.getFields();
System.out.printf("----------- Analyzing receipt info %d -----------%n", i);
DocumentField merchantNameField = receiptFields.get("MerchantName");
if (merchantNameField != null) {
if (DocumentFieldType.STRING == merchantNameField.getType()) {
String merchantName = merchantNameField.getValueString();
System.out.printf("Merchant Name: %s, confidence: %.2f%n",
merchantName, merchantNameField.getConfidence());
}
}
DocumentField transactionDateField = receiptFields.get("TransactionDate");
if (transactionDateField != null) {
if (DocumentFieldType.DATE == transactionDateField.getType()) {
LocalDate transactionDate = transactionDateField.getValueDate();
System.out.printf("Transaction Date: %s, confidence: %.2f%n",
transactionDate, transactionDateField.getConfidence());
}
}
DocumentField receiptItemsField = receiptFields.get("Items");
if (receiptItemsField != null) {
System.out.printf("Receipt Items: %n");
if (DocumentFieldType.LIST == receiptItemsField.getType()) {
List<DocumentField> receiptItems = receiptItemsField.getValueList();
receiptItems.stream()
.filter(receiptItem -> DocumentFieldType.MAP == receiptItem.getType())
.map(formField -> formField.getValueMap())
.forEach(formFieldMap -> formFieldMap.forEach((key, formField) -> {
if ("Name".equals(key)) {
if (DocumentFieldType.STRING == formField.getType()) {
String name = formField.getValueString();
System.out.printf("Name: %s, confidence: %.2fs%n",
name, formField.getConfidence());
}
}
if ("Quantity".equals(key)) {
if (DocumentFieldType.FLOAT == formField.getType()) {
Float quantity = formField.getValueFloat();
System.out.printf("Quantity: %f, confidence: %.2f%n",
quantity, formField.getConfidence());
}
}
if ("TotalPrice".equals(key)) {
if (DocumentFieldType.FLOAT == formField.getType()) {
Float totalPrice = formField.getValueFloat();
System.out.printf("Total Price: %f, confidence: %.2f%n",
totalPrice, formField.getConfidence());
}
}
}));
}
}
System.out.print("-----------------------------------");
}
}
private static void getAccountProperties(DocumentModelAdministrationClient documentModelAdminClient) {
AccountProperties accountProperties = documentModelAdminClient.getAccountProperties();
System.out.printf("Max number of models that can be trained for this account: %s%n",
accountProperties.getDocumentModelLimit());
System.out.printf("Current count of built custom models: %d%n", accountProperties.getDocumentModelCount());
}
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-containerregistry/src/main/java/com/azure/resourcemanager/containerregistry/fluent/models/AgentPoolPropertiesUpdateParameters.java | 1438 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.containerregistry.fluent.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;
/** The AgentPoolPropertiesUpdateParameters model. */
@Fluent
public final class AgentPoolPropertiesUpdateParameters {
@JsonIgnore private final ClientLogger logger = new ClientLogger(AgentPoolPropertiesUpdateParameters.class);
/*
* The count of agent machine
*/
@JsonProperty(value = "count")
private Integer count;
/**
* Get the count property: The count of agent machine.
*
* @return the count value.
*/
public Integer count() {
return this.count;
}
/**
* Set the count property: The count of agent machine.
*
* @param count the count value to set.
* @return the AgentPoolPropertiesUpdateParameters object itself.
*/
public AgentPoolPropertiesUpdateParameters withCount(Integer count) {
this.count = count;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
archimatetool/archi | org.eclipse.gef/src/org/eclipse/gef/ui/actions/ZoomOutRetargetAction.java | 1198 | /*******************************************************************************
* Copyright (c) 2000, 2010 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.gef.ui.actions;
import org.eclipse.ui.actions.RetargetAction;
import org.eclipse.gef.internal.GEFMessages;
import org.eclipse.gef.internal.InternalImages;
/**
* @author danlee
*/
public class ZoomOutRetargetAction extends RetargetAction {
/**
* Constructor for ZoomInRetargetAction
*/
public ZoomOutRetargetAction() {
super(null, null);
setText(GEFMessages.ZoomOut_Label);
setId(GEFActionConstants.ZOOM_OUT);
setToolTipText(GEFMessages.ZoomOut_Tooltip);
setImageDescriptor(InternalImages.DESC_ZOOM_OUT);
setActionDefinitionId(GEFActionConstants.ZOOM_OUT);
}
}
| mit |
Sylvain-Bugat/N-queens-puzzle-solvers | src/main/java/com/github/sbugat/nqueens/solvers/bruteforce/instrumentations/BruteForceNQueensSolverWithLists.java | 5820 | package com.github.sbugat.nqueens.solvers.bruteforce.instrumentations;
import java.util.ArrayList;
import java.util.List;
import com.github.sbugat.nqueens.GenericInstrumentedNQueensSolver;
/**
* Brute-force algorithm for the N queens puzzle solver with a variable containing the queen number constraint.
*
* @author Sylvain Bugat
*
*/
public final class BruteForceNQueensSolverWithLists extends GenericInstrumentedNQueensSolver {
/** Chessboard represented by a list of lists. */
private final List<List<Boolean>> chessboard;
/** Current number of queens on the chessboard. */
private int placedQueens;
public BruteForceNQueensSolverWithLists(final int chessboardSizeArg, final boolean printSolutionArg) {
super(chessboardSizeArg, printSolutionArg);
chessboard = new ArrayList<>();
for (int x = 0; x < chessboardSizeArg; x++) {
final List<Boolean> lineList = new ArrayList<>();
for (int y = 0; y < chessboardSizeArg; y++) {
lineList.add(Boolean.FALSE);
}
chessboard.add(lineList);
}
}
@Override
public long solve() {
// Start the algorithm at the first position
methodCallsCount++;
solve(0, 0);
// Return the number of solutions found
return solutionCount;
}
/**
* Solving recursive method, do a greedy algorithm by testing all combinations.
*
* @param x X position on the chessboard
* @param y Y position on the chessboard
*/
private void solve(final int x, final int y) {
// Put a queen on the current position
queenPlacementsCount++;
squareWritesCount++;
methodCallsCount += 2;
chessboard.get(x).set(y, Boolean.TRUE);
placedQueens++;
// All queens are sets on the chessboard then a solution may be present
explicitTestsCount++;
if (placedQueens >= chessboardSize) {
methodCallsCount++;
explicitTestsCount++;
if (checkSolutionChessboard()) {
solutionCount++;
methodCallsCount++;
print();
}
}
else {
// Recursive call to the next position
final int nextX = (x + 1) % chessboardSize;
// Switch to the next line
explicitTestsCount++;
if (0 == nextX) {
// End of the chessboard check
explicitTestsCount++;
if (y + 1 < chessboardSize) {
methodCallsCount++;
solve(nextX, y + 1);
}
}
else {
methodCallsCount++;
solve(nextX, y);
}
}
// Remove the queen on the current position
placedQueens--;
squareWritesCount++;
methodCallsCount += 2;
chessboard.get(x).set(y, Boolean.FALSE);
// Recursive call to the next position
final int nextX = (x + 1) % chessboardSize;
// Switch to the next line
explicitTestsCount++;
if (0 == nextX) {
// End of the chessboard check
explicitTestsCount++;
if (y + 1 < chessboardSize) {
methodCallsCount++;
solve(nextX, y + 1);
}
}
else {
methodCallsCount++;
solve(nextX, y);
}
}
/**
* Check if a chessboard with N queens is a solution (only one queens per lines, columns and diagnonals).
*
* @return true if the chessboard contain a solution, false otherwise
*/
private boolean checkSolutionChessboard() {
// Check if 2 queens are on the same line
implicitTestsCount++;
for (int y = 0; y < chessboardSize; y++) {
boolean usedLine = false;
implicitTestsCount++;
for (int x = 0; x < chessboardSize; x++) {
explicitTestsCount++;
methodCallsCount += 3;
squareReadsCount++;
if (chessboard.get(x).get(y).booleanValue()) {
explicitTestsCount++;
if (usedLine) {
return false;
}
usedLine = true;
}
implicitTestsCount++;
}
implicitTestsCount++;
}
// Check if 2 queens are on the same column
implicitTestsCount++;
for (int x = 0; x < chessboardSize; x++) {
boolean usedColumn = false;
implicitTestsCount++;
for (int y = 0; y < chessboardSize; y++) {
explicitTestsCount++;
methodCallsCount += 3;
squareReadsCount++;
if (chessboard.get(x).get(y).booleanValue()) {
explicitTestsCount++;
if (usedColumn) {
return false;
}
usedColumn = true;
}
implicitTestsCount++;
}
implicitTestsCount++;
}
// Check if 2 queens are on the same descending diagonal
implicitTestsCount++;
for (int diagonal = 0; diagonal < chessboardSize * 2 - 1; diagonal++) {
boolean usedDiagonal = false;
implicitTestsCount++;
for (int y = 0; y < chessboardSize; y++) {
final int x = diagonal - y;
explicitTestsCount++;
if (x >= 0) {
explicitTestsCount++;
if (x < chessboardSize) {
explicitTestsCount++;
methodCallsCount += 3;
squareReadsCount++;
if (chessboard.get(x).get(y).booleanValue()) {
explicitTestsCount++;
if (usedDiagonal) {
return false;
}
usedDiagonal = true;
}
}
}
implicitTestsCount++;
}
implicitTestsCount++;
}
// Check if 2 queens are on the same ascending diagonal
implicitTestsCount++;
for (int diagonal = 0; diagonal < chessboardSize * 2 - 1; diagonal++) {
boolean usedDiagonal = false;
implicitTestsCount++;
for (int y = 0; y < chessboardSize; y++) {
final int x = diagonal - chessboardSize + 1 + y;
explicitTestsCount++;
if (x >= 0) {
explicitTestsCount++;
if (x < chessboardSize) {
explicitTestsCount++;
methodCallsCount += 3;
squareReadsCount++;
if (chessboard.get(x).get(y).booleanValue()) {
explicitTestsCount++;
if (usedDiagonal) {
return false;
}
usedDiagonal = true;
}
}
}
implicitTestsCount++;
}
implicitTestsCount++;
}
return true;
}
@Override
public boolean getChessboardPosition(final int x, final int y) {
return chessboard.get(x).get(y).booleanValue();
}
@Override
public String getName() {
return "Queen constraint brute-force";
}
}
| mit |
motiz88/react-native-midi | android/react-native-midi/src/main/java/com/motiz88/rctmidi/webmidi/events/MIDIMessageListener.java | 145 | package com.motiz88.rctmidi.webmidi.events;
public interface MIDIMessageListener {
void onMIDIMessage(byte[] data, double timestampSeconds);
} | mit |
IsraeI/pontointeligente | src/main/java/net/sparkbox/pontointeligente/api/services/EmpresaService.java | 502 | /**
*
*/
package net.sparkbox.pontointeligente.api.services;
import java.util.Optional;
import net.sparkbox.pontointeligente.api.modelo.Empresa;
/**
* @author Israel
*
*/
public interface EmpresaService {
/**
* Retorna uma empresa dado um CNPJ.
*
* @param cnpj
* @return Optional<Empresa>
*/
Optional<Empresa> buscarPorCnpj(String cnpj);
/**
* Cadastra uma nova empresa na base de dados.
*
* @param empresa
* @return Empresa
*/
Empresa persistir(Empresa empresa);
}
| mit |
VDuda/SyncRunner-Pub | src/API/amazon/mws/xml/JAXB/ItemPitchType.java | 3811 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.05.03 at 03:15:27 PM EDT
//
package API.amazon.mws.xml.JAXB;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="value" minOccurs="0">
* <complexType>
* <simpleContent>
* <extension base="<>String100Type">
* </extension>
* </simpleContent>
* </complexType>
* </element>
* </sequence>
* <attribute name="delete" type="{}BooleanType" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "item_pitch_type")
public class ItemPitchType {
protected ItemPitchType.Value value;
@XmlAttribute(name = "delete")
protected BooleanType delete;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link ItemPitchType.Value }
*
*/
public ItemPitchType.Value getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link ItemPitchType.Value }
*
*/
public void setValue(ItemPitchType.Value value) {
this.value = value;
}
/**
* Gets the value of the delete property.
*
* @return
* possible object is
* {@link BooleanType }
*
*/
public BooleanType getDelete() {
return delete;
}
/**
* Sets the value of the delete property.
*
* @param value
* allowed object is
* {@link BooleanType }
*
*/
public void setDelete(BooleanType value) {
this.delete = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <simpleContent>
* <extension base="<>String100Type">
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
public static class Value {
@XmlValue
protected String value;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
}
| mit |
Kai-Qian/Leetcode | Tree/199. Binary Tree Right Side View.java | 1338 | /*
Given a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
For example:
Given the following binary tree,
1 <---
/ \
2 3 <---
\ \
5 4 <---
You should return [1, 3, 4].
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> rightSideView(TreeNode root) {
if(root == null) {
return new ArrayList<Integer>();
}
ArrayList<TreeNode> al = new ArrayList<TreeNode>();
ArrayList<Integer> ans = new ArrayList<Integer>();
al.add(root);
TreeNode tmp;
int cur = 0;
int last = 0;
while(last < al.size()) {
last = al.size();
while(cur < last) {
tmp = al.get(cur);
if(cur == last - 1) {
ans.add(tmp.val);
}
if(tmp.left != null) {
al.add(tmp.left);
}
if(tmp.right != null) {
al.add(tmp.right);
}
cur++;
}
}
return ans;
}
} | mit |
lmcgrath/snacks-lang | src/main/java/snacks/lang/ast/BooleanConstant.java | 985 | package snacks.lang.ast;
import static snacks.lang.Types.booleanType;
import java.util.Objects;
import snacks.lang.Type;
public class BooleanConstant extends AstNode {
private final boolean value;
public BooleanConstant(boolean value) {
this.value = value;
}
@Override
public void print(AstPrinter printer) {
printer.printBooleanConstant(this);
}
@Override
public boolean equals(Object o) {
return o == this || o instanceof BooleanConstant && value == ((BooleanConstant) o).value;
}
@Override
public void generate(Generator generator) {
generator.generateBooleanConstant(this);
}
@Override
public Type getType() {
return booleanType();
}
public boolean getValue() {
return value;
}
@Override
public int hashCode() {
return Objects.hash(value);
}
@Override
public String toString() {
return String.valueOf(value);
}
}
| mit |
gxtaillon/gxt.common | gxt.common/src/gxt/common/lispite/TokenGroup.java | 756 | package gxt.common.lispite;
public class TokenGroup {
String name;
TokenGroup[] group;
private TokenGroup() {
}
public String getName() {
return name;
}
public TokenGroup[] getGroup() {
return group;
}
public static TokenGroup Single(String name) {
TokenGroup r = new TokenGroup();
r.name = name;
r.group = new TokenGroup[0];
return r;
}
public static TokenGroup Group(String name, TokenGroup[] group) {
TokenGroup r = new TokenGroup();
r.name = name;
r.group = group;
return r;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("(");
sb.append(name);
for (TokenGroup g : group) {
sb.append(" ");
sb.append(g.toString());
}
sb.append(")");
return sb.toString();
}
}
| mit |
BackSpace47/main | java/net/RPower/RPowermod/item/itempjPink.java | 217 | package net.RPower.RPowermod.item;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
public class itempjPink extends Item{
public boolean hasEffect(ItemStack par1ItemStack){
return true;
}
}
| mit |
pjohansson77/Remote-Lock | Server/ServerGUI.java | 4488 | package lock;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
/**
* Class that handles the server sequence.
*
* @author Andree Höög, Peter Johansson, Jesper Hansen
*/
public class ServerGUI {
private HeartBeat heartBeat;
private ListenForClients server;
private JFrame frame;
private JPanel panel = new JPanel( new BorderLayout() );
private JPanel btnPanel = new JPanel( new GridLayout( 1, 2 ) );
private JPanel topPanel = new JPanel( new BorderLayout() );
private JButton btnStart = new JButton( "Start server" );
private JButton btnStop = new JButton( "Stop server" );
private JTextArea txtArea = new JTextArea();
private JScrollPane scroll = new JScrollPane( txtArea );
private JButton btnAdmin = new JButton( "Admin Settings" );
private JLabel ipLabel = new JLabel();
private String consoleText = "";
private int port;
private ServerGUI gui;
/**
* Constructor for ServerGUI class.
*
* @param port The port that the server listens on.
*/
public ServerGUI( int port ) {
frame = new JFrame( "Server - Remote Lock" );
this.port = port;
this.gui = this;
enableAdminButton( false );
DefaultCaret caret = ( DefaultCaret )txtArea.getCaret();
caret.setUpdatePolicy( DefaultCaret.ALWAYS_UPDATE );
btnPanel.add( btnStart );
btnPanel.add( btnStop );
btnPanel.add( btnAdmin );
topPanel.add( btnPanel, BorderLayout.CENTER );
topPanel.add( ipLabel, BorderLayout.SOUTH );
panel.add( topPanel, BorderLayout.NORTH );
panel.add( scroll, BorderLayout.CENTER );
panel.setPreferredSize( new Dimension( 425, 500 ) );
ipLabel.setHorizontalAlignment( SwingConstants.CENTER );
ipLabel.setPreferredSize( new Dimension(200, 20 ) );
btnPanel.setPreferredSize( new Dimension(125, 50 ) );
btnStop.setEnabled( false );
txtArea.setEditable( false );
btnStart.addActionListener( new ButtonListener() );
btnStop.addActionListener( new ButtonListener() );
btnAdmin.addActionListener( new ButtonListener() );
showServerGUI();
}
/**
* Function that activates ServerGUI.
*/
public void showServerGUI() {
frame.setVisible( true );
frame.setResizable( false );
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( panel, BorderLayout.CENTER );
frame.setLocation( 600, 100 );
frame.pack();
}
/**
* Function that sends the ip-address and port to the GUI.
*/
public void showServerInfo() {
try {
ipLabel.setText( "Server-IP: " + InetAddress.getLocalHost().getHostAddress() + " Port: " + port );
} catch ( UnknownHostException e ) {
e.printStackTrace();
}
}
/**
* Function that sends text to the GUI.
*
* @param txt Message in a String.
*/
public void showText( String str ) {
consoleText += str + "\n";
txtArea.setText( consoleText );
}
/**
* Function that enables or disables the admin button
* @param b boolean true or false
*/
public void enableAdminButton( boolean bool ) {
btnAdmin.setEnabled( bool );
}
/**
* Button listener that listens to all user inputs in ServerGUI.
*/
private class ButtonListener implements ActionListener {
public void actionPerformed( ActionEvent e ) {
if( e.getSource() == btnStart ) {
if( MySQL.checkDatabase() ) {
showText( "Server started: " + Time.getTime() + "\n" );
showServerInfo();
btnStart.setEnabled( false );
btnStop.setEnabled( true );
enableAdminButton( true );
Thread arduinoThread = new Thread( heartBeat = new HeartBeat() );
arduinoThread.start();
Thread connectThread = new Thread( server = new ListenForClients( port, gui ) );
connectThread.start();
} else {
gui.showText( "Database unreachable - Unable to start\n" + Time.getTime() + "\n" );
}
}
if( e.getSource() == btnStop ) {
heartBeat.stopArduinoCheck();
showText( "Server closed: " + Time.getTime() );
btnStart.setEnabled( true );
btnStop.setEnabled( false );
enableAdminButton( false );
server.terminate();
}
if (e.getSource() == btnAdmin ) {
enableAdminButton( false );
server.startAdminGUI();
server.showAdminFrame();
}
}
}
}
| mit |
rutgerkok/BlockLocker | src/main/java/nl/rutgerkok/blocklocker/impl/updater/Updater.java | 4697 | package nl.rutgerkok.blocklocker.impl.updater;
import java.io.IOException;
import java.util.Optional;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import org.bukkit.plugin.Plugin;
import org.bukkit.scheduler.BukkitRunnable;
import nl.rutgerkok.blocklocker.Translator;
import nl.rutgerkok.blocklocker.impl.updater.UpdateResult.Status;
/**
* Handles the complete update procedure.
*
*/
public final class Updater {
/**
* Every twelve hours.
*/
private static final long CHECK_INTERVAL = 20 * 60 * 60 * 12;
private final Plugin plugin;
private volatile UpdatePreference preference;
private final BukkitRunnable task = new BukkitRunnable() {
@Override
public void run() {
if (preference.checkForUpdates()) {
updateSync();
} else {
this.cancel();
}
}
};
private final Translator translator;
public Updater(UpdatePreference preference, Translator translator, Plugin plugin) {
this.preference = Preconditions.checkNotNull(preference);
this.translator = Preconditions.checkNotNull(translator);
this.plugin = Preconditions.checkNotNull(plugin);
}
private Optional<String> getMinecraftVersion() {
String serverVersion = plugin.getServer().getVersion();
String regex = "MC\\: *([A-Za-z0-9\\._\\-]+)";
Matcher matcher = Pattern.compile(regex).matcher(serverVersion);
if (matcher.find() && matcher.groupCount() == 1) {
return Optional.of(matcher.group(1));
} else {
return Optional.empty();
}
}
/**
* Notifies admins of the server of an updated version of the plugin. Can be
* called from any thread.
*
* @param result
* The update result.
*/
private void notifyServer(final UpdateResult result) {
if (!result.hasNotification()) {
return;
}
// Disable further update checks
preference = UpdatePreference.DISABLED;
// Notify admins of existing result
if (plugin.getServer().isPrimaryThread()) {
notifyServerFromServerThread(result);
} else {
plugin.getServer().getScheduler().runTask(plugin, new Runnable() {
@Override
public void run() {
notifyServerFromServerThread(result);
}
});
}
}
private void notifyServerFromServerThread(UpdateResult result) {
// Must be called from notifyServer
// Result must have a notification
UpdateNotifier notifier = new UpdateNotifier(translator, result);
// Notify players
plugin.getServer().getPluginManager().registerEvents(notifier, plugin);
// Notify console
notifier.sendNotification(plugin.getServer().getConsoleSender());
}
/**
* Starts the update process. Does nothing if updates have been disabled.
*
* @throws IllegalStateException
* If this method was called earlier.
*/
public void startUpdater() {
if (!preference.checkForUpdates()) {
return;
}
task.runTaskTimerAsynchronously(plugin, 1, CHECK_INTERVAL);
}
private void updateInstallSync(UpdateCheckResult result) throws IOException {
Optional<String> minecraftVersion = getMinecraftVersion();
if (result.getMinecraftVersions().containsAll(ImmutableSet.of(minecraftVersion.get()))) {
// Notify that an update is available
notifyServer(new UpdateResult(Status.MANUAL_UPDATE, result));
} else {
// Server version no longer supported
notifyServer(new UpdateResult(Status.UNSUPPORTED_SERVER, result));
}
}
/**
* Blocking update method, must <b>not</b> be called from the server thread.
*/
private void updateSync() {
try {
UpdateChecker checker = new UpdateChecker();
UpdateCheckResult result = checker.checkForUpdatesSync(plugin);
if (result.needsUpdate()) {
updateInstallSync(result);
} else {
notifyServer(new UpdateResult(Status.NO_UPDATE, result));
}
} catch (IOException e) {
plugin.getLogger().log(Level.WARNING, "Error during update check"
+ " (you can disable automatic updates in the config file)", e);
notifyServer(UpdateResult.failed());
}
}
}
| mit |
elancom/jvm.go | testclasses/src/main/java/java6/reflection/PrimitiveClassTest.java | 1167 | package java6.reflection;
import org.junit.Test;
import static org.junit.Assert.*;
import libs.junit.UnitTestRunner;
public class PrimitiveClassTest {
public static void main(String[] args) {
UnitTestRunner.run(PrimitiveClassTest.class);
}
@Test
public void test() {
testPrimitiveClass(void.class, "void");
testPrimitiveClass(boolean.class, "boolean");
testPrimitiveClass(byte.class, "byte");
testPrimitiveClass(char.class, "char");
testPrimitiveClass(short.class, "short");
testPrimitiveClass(int.class, "int");
testPrimitiveClass(long.class, "long");
testPrimitiveClass(float.class, "float");
testPrimitiveClass(double.class, "double");
}
private void testPrimitiveClass(Class<?> c, String name) {
assertEquals(name, c.getName());
assertEquals(null, c.getSuperclass());
assertEquals(0, c.getFields().length);
assertEquals(0, c.getDeclaredFields().length);
assertEquals(0, c.getMethods().length);
assertEquals(0, c.getDeclaredMethods().length);
}
}
| mit |
kkrull/javaspec | lambdas-and-fields/javaspec-runner/src/test/java/info/javaspec/context/FakeContext.java | 1491 | package info.javaspec.context;
import info.javaspec.spec.Spec;
import org.junit.runner.Description;
import org.junit.runner.notification.RunNotifier;
public final class FakeContext extends Context {
private final long numSpecs;
private final Description description;
public static FakeContext withDescription(Description description) {
return new FakeContext("withDescription", 1, description);
}
public static FakeContext withNoSpecs(String id) {
return new FakeContext(id, 0, suiteDescription(id));
}
public static FakeContext withNumSpecs(long numSpecs) {
return new FakeContext("withNumSpecs", numSpecs, suiteDescription("withNumSpecs"));
}
public static FakeContext withNumSpecs(String id, long numSpecs) {
return new FakeContext(id, numSpecs, suiteDescription(id));
}
private static Description suiteDescription(String id) {
return Description.createSuiteDescription(id, id);
}
private FakeContext(String id, long numSpecs, Description description) {
super(id);
this.numSpecs = numSpecs;
this.description = description;
}
@Override
public Description getDescription() { return description; }
@Override
public void addSpec(Spec spec) { throw new UnsupportedOperationException(); }
@Override
public boolean hasSpecs() { return numSpecs > 0; }
@Override
public long numSpecs() { return numSpecs; }
@Override
public void run(RunNotifier notifier) { throw new UnsupportedOperationException(); }
}
| mit |
tkesgar/felis | src/FelisEditor/src/com/felis/lib/CYKParseTree.java | 848 | package com.felis.lib;
public class CYKParseTree implements Comparable {
private String node;
private PairStringInt terminal;
private CYKParseTree left;
private CYKParseTree right;
public CYKParseTree(String n, PairStringInt t) {
node = n;
terminal = t;
left = null;
right = null;
}
public CYKParseTree(String n, CYKParseTree l, CYKParseTree r) {
node = n;
terminal = null;
left = l;
right = r;
}
@Override
public String toString() {
if (terminal == null) {
return node.toString();
} else {
return terminal.toString();
}
}
public String getNode() {
return node;
}
public CYKParseTree getLeft() {
return left;
}
public CYKParseTree getRight() {
return right;
}
@Override
public int compareTo(Object o) {
CYKParseTree tree = (CYKParseTree) o;
return node.compareTo(tree.node);
}
}
| mit |
phoenixz1/Lab2 | RobotClient.java | 4537 | /*
Copyright (C) 2004 Geoffrey Alan Washburn
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
USA.
*/
import java.util.Random;
import java.util.Vector;
import java.lang.Runnable;
/**
* A very naive implementation of a computer controlled {@link LocalClient}. Basically
* it stumbles about and shoots.
* @author Geoffrey Washburn <<a href="mailto:geoffw@cis.upenn.edu">geoffw@cis.upenn.edu</a>>
* @version $Id: RobotClient.java 345 2004-01-24 03:56:27Z geoffw $
*/
public class RobotClient extends LocalClient implements Runnable {
/**
* Random number generator so that the robot can be
* "non-deterministic".
*/
private final Random randomGen = new Random();
/**
* The {@link Thread} object we use to run the robot control code.
*/
private final Thread thread;
/**
* Flag to say whether the control thread should be
* running.
*/
private boolean active = false;
/**
* Create a computer controlled {@link LocalClient}.
* @param name The name of this {@link RobotClient}.
*/
public RobotClient(String name, int ctype, String host, int port) {
super(name, ctype, host, port);
assert(name != null);
// Create our thread
thread = new Thread(this);
}
/**
* Override the abstract {@link Client}'s registerMaze method so that we know when to start
* control thread.
* @param maze The {@link Maze} that we are begin registered with.
*/
public synchronized void registerMaze(Maze maze) {
assert(maze != null);
super.registerMaze(maze);
// Get the control thread going.
active = true;
thread.start();
}
/**
* Override the abstract {@link Client}'s unregisterMaze method so we know when to stop the
* control thread.
*/
public synchronized void unregisterMaze() {
// Signal the control thread to stop
active = false;
// Wait half a second for the thread to complete.
try {
thread.join(500);
} catch(Exception e) {
// Shouldn't happen
}
super.unregisterMaze();
}
/**
* This method is the control loop for an active {@link RobotClient}.
*/
public void run() {
// Put a spiffy message in the console
Mazewar.consolePrintLn("Robot client \"" + this.getName() + "\" activated.");
// Loop while we are active
while(active) {
// Try to move forward
if(!forward()) {
// If we fail...
if(randomGen.nextInt(3) == 1) {
// turn left!
turnLeft();
} else {
// or perhaps turn right!
turnRight();
}
}
// Shoot at things once and a while.
if(randomGen.nextInt(10) == 1) {
fire();
}
// Sleep so the humans can possibly compete.
try {
thread.sleep(200);
} catch(Exception e) {
// Shouldn't happen.
}
}
}
}
| mit |
dfcf93/RPICS | NaturalLanguageProcessing/src/graphics/basicShapes/Vector3D.java | 2402 | package graphics.basicShapes;
import graphics.genMath.Math3D;
import graphics.geoShapes.GeoLine;
import java.util.ArrayList;
public class Vector3D extends Point3D {
private double zen;
private double azi;
public Vector3D() {
}
public Vector3D(double x, double y, double z) {
super(x, y, z);
}
public Vector3D(double x, double y, double z, double zen, double azi) {
this(x, y, z);
this.setZenith(zen);
this.setAzimuth(azi);
}
public String toString() {
return "Vector3D[" + getX() + "," + getY() + "," + getZ() + ","
+ this.getZenith() + "," + this.getAzumith() + "]";
}
public GeoLine getPerpendicularLine() {
return new GeoLine(this, Math3D.rotatePoint(this, 100, 90, 0));
}
Polygon3D perpPlane;
public Polygon3D getPerpendicularPlane() {
if (perpPlane != null) {
return perpPlane;
}
Point3D r1 = Math3D.rotatePoint(this, 1000, getZenith() + 90, 0);
Point3D r2 = Math3D.rotatePoint(this, 1000, getZenith(),
-90 - this.getAzumith());
Point3D r3 = Math3D.rotatePoint(this, 1000, getZenith() - 90, 0);
Point3D r4 = Math3D.rotatePoint(this, 1000, getZenith(),
90 - this.getAzumith());
ArrayList<Point3D> rt = new ArrayList<Point3D>();
rt.add(r1);
rt.add(r2);
rt.add(r3);
rt.add(r4);
return new Polygon3D(rt);
}
public void turnToFace(Point3D p) {
this.setZenith(Math3D.getZenithFrom(this, p));
this.setAzimuth(Math3D.getAzimuthFrom(this, p));
}
public void putWithinBounds() {
// removed because it wasn't doing anything.
// double z = getZenith() % 360;
// if (maxZenithRot != 999 && maxZenithRot > 360 && z > maxZenithRot %
// 360) {
// z = maxZenithRot % 360;
// }
// this.zen = (Math.max(Math.min(z, maxZenithRot), minZenithRot));
// double a = getAzumith() % 360;
// if (maxAzumithRot != 999 && maxAzumithRot > 360 && z > maxAzumithRot
// % 360) {
// z = maxAzumithRot % 360;
// }
// this.azi = (Math.max(Math.min(a, maxAzumithRot), minAzumithRot));
}
public void rotateZenith(double degrees) {
this.setZenith(getZenith() + degrees);
}
public void rotateAzumith(double degrees) {
this.setAzimuth(getAzumith() + degrees);
}
public void setZenith(double xr) {
this.zen = xr;
putWithinBounds();
}
public double getZenith() {
return zen;
}
public void setAzimuth(double yr) {
this.azi = yr;
putWithinBounds();
}
public double getAzumith() {
return azi;
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/warehouse/web/EnterTransferStockKeepingUnitsController.java | 2647 | package com.swfarm.biz.warehouse.web;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import com.swfarm.biz.oa.bo.User;
import com.swfarm.biz.warehouse.bo.Warehouse;
import com.swfarm.biz.warehouse.dto.SearchWarehouseLogsCriteria;
import com.swfarm.biz.warehouse.srv.WarehouseService;
import com.swfarm.pub.framework.PaginationSupport;
public class EnterTransferStockKeepingUnitsController extends
AbstractController {
private WarehouseService warehouseService;
public void setWarehouseService(WarehouseService warehouseService) {
this.warehouseService = warehouseService;
}
protected ModelAndView handleRequestInternal(HttpServletRequest req,
HttpServletResponse res) throws Exception {
User user = (User) req.getSession().getAttribute("credential");
String startIndexStr = req.getParameter("startIndex");
int startIndex = 0;
int pageSize = 50;
if (StringUtils.isNotEmpty(startIndexStr)) {
startIndex = new Integer(startIndexStr).intValue();
} else {
String pageStr = req.getParameter("page");
if (StringUtils.isNotEmpty(pageStr)) {
startIndex = PaginationSupport.getPageStartIndex(new Integer(
pageStr), pageSize);
}
}
Map dataMap = new HashMap();
String warehouseIdStr = req.getParameter("warehouse");
Long warehouseId = null;
if (StringUtils.isNotEmpty(warehouseIdStr)) {
warehouseId = new Long(warehouseIdStr);
} else {
Warehouse defaultWarehouse = this.warehouseService
.findDefaultWarehouse();
warehouseId = defaultWarehouse.getId();
}
SearchWarehouseLogsCriteria criteria = new SearchWarehouseLogsCriteria();
criteria.setWarehouseId(warehouseId);
criteria.setActor(user.getUsername());
PaginationSupport pagination = this.warehouseService.searchWarehouseLogs(criteria, pageSize, startIndex);
int page = pagination.getPage(startIndex);
int[] pageRange = pagination.getPageRange(page);
List warehouses = this.warehouseService.findWarehouses();
List stockLocations = this.warehouseService.findStockLocations();
dataMap.put("pagination", pagination);
dataMap.put("currentPage", page);
dataMap.put("pageRange", pageRange);
dataMap.put("warehouses", warehouses);
dataMap.put("stockLocations", stockLocations);
return new ModelAndView("warehouse/transfer_stockkeepingunits", dataMap);
}
}
| mit |
zhangqiang110/my4j | pms/src/main/java/com/swfarm/biz/chain/bo/annotation/MongoTableAnnotation.java | 346 | package com.swfarm.biz.chain.bo.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MongoTableAnnotation {
public String value();
} | mit |