code
stringlengths 5
1.04M
| repo_name
stringlengths 7
108
| path
stringlengths 6
299
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 5
1.04M
|
---|---|---|---|---|---|
/*
* "BSLib", Brainstorm Library.
* Copyright (C) 2015 by Serg V. Zhdanovskih (aka Alchemist, aka Norseman).
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package bslib.common;
/**
*
* @author Serg V. Zhdanovskih
*/
public class ParserException extends RuntimeException
{
public ParserException()
{
}
public ParserException(String message)
{
super(message);
}
}
| ruslangaripov/ChemLab | src/bslib/common/ParserException.java | Java | gpl-3.0 | 1,054 |
package codepoet.vaultmonkey.util;
import java.io.File;
import java.sql.Connection;
import org.junit.AfterClass;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import org.junit.Test;
public class SqliteConnectionUtilTest {
private static final String PATH = "src/test/resources/library/";
@AfterClass
public static void tearDown() {
File file = new File(PATH + "/Test.sqlite");
file.delete();
}
@Test
public void testInstantiate() {
assertNotNull(new SqliteConnectionUtil());
}
@Test
public void testNotFoundException() throws Exception {
try {
SqliteConnectionUtil.establishConnection("not-a-library/NotAFile.sqlite");
fail("Exception Expected");
} catch (Exception exception) {
assertNotNull(exception);
}
try {
SqliteConnectionUtil.establishConnectionInMemory("not-a-library/NotAFile.sqlite");
fail("Exception Expected");
} catch (Exception exception) {
assertNotNull(exception);
}
}
@Test
public void testEstablishConnectionInMemory() throws Exception {
Connection memory = SqliteConnectionUtil.establishConnectionInMemory(PATH + "Test.sqlite");
assertNotNull(memory);
}
@Test
public void testEstablishConnection() throws Exception {
Connection memory = SqliteConnectionUtil.establishConnection(PATH + "Test.sqlite");
assertNotNull(memory);
}
}
| sshookman/VaultMonkey | src/test/java/codepoet/vaultmonkey/util/SqliteConnectionUtilTest.java | Java | gpl-3.0 | 1,354 |
package com.github.cypher.sdk.api;
import com.google.gson.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides access to matrix endpoints trough
* ordinary java methods returning Json Objects.
*
* <p>Most endpoints require a session to
* have been successfully initiated as the data provided by the
* endpoint itself isn't publicly available.
*
* <p>A session can be initiated with {@link #login(String username, String password, String homeserver)}
* or via the constructor {@link #MatrixApiLayer(String username, String password, String homeserver)}
*
* @see <a href="http://matrix.org/docs/api/client-server/">matrix.org</a>
*/
public class MatrixApiLayer implements ApiLayer {
private Session session;
@Override
public Session getSession() {
return session;
}
@Override
public void setSession(Session session) {
this.session = session;
}
/**
* Creates a MatrixApiLayer with a session.
*
* <p> Session is created with {@link #login(String username, String password, String homeserver)}
*
* @param username Username
* @param password Password
* @param homeserver A homeserver to connect trough (e.g. example.org:8448 or matrix.org)
*/
public MatrixApiLayer(String username, String password, String homeserver) throws RestfulHTTPException, IOException {
login(username, password, homeserver);
}
/**
* Creates a new MatrixApiLayer without a session.
*
* <p> Use {@link #login(String username, String password, String homeserver)} to create a session.
*/
public MatrixApiLayer() { /*Used for javadoc*/}
@Override
public void login(String username, String password, String homeserver) throws RestfulHTTPException, IOException {
// Only run if session isn't already set
if (session != null){
return;
}
// Build URL
URL url = Util.UrlBuilder(homeserver, Endpoint.LOGIN, null, null);
// Build request body
JsonObject request = new JsonObject();
request.addProperty("type", "m.login.password");
request.addProperty("user", username);
request.addProperty("password", password);
// Send Request
JsonObject response = Util.makeJsonPostRequest(url, request).getAsJsonObject();
// Set Session
this.session = new Session(response);
}
@Override
public void refreshToken() throws RestfulHTTPException, IOException {
// Only run if session is set
if (session == null) {
return;
}
// Only run if refreshToken is available
if (session.getRefreshToken() == null) {
throw new IOException("Refresh token not available");
}
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.TOKEN_REFRESH, null, null);
// Build request body
JsonObject request = new JsonObject();
request.addProperty("refresh_token", session.getRefreshToken());
// Send Request
JsonObject response = Util.makeJsonPostRequest(url, request).getAsJsonObject();
// Check if response is valid
if (response.has("access_token")) {
// If refresh token is available, use it
String refreshToken = null;
if (response.has("refresh_token")) {
refreshToken = response.get("refresh_token").getAsString();
}
// Create new session object
session = new Session(
session.getUserId(),
response.get("access_token").getAsString(),
refreshToken,
session.getHomeServer(),
session.getDeviceId(),
0
);
} else {
// Something went wrong, force re-login
session = null;
}
}
public void logout() throws RestfulHTTPException, IOException {
// Only run if the session is set
if (session == null) {
return;
}
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.LOGOUT, null, parameters);
// Send request
JsonObject response = Util.makeJsonPostRequest(url, null).getAsJsonObject();
// Null session
this.session = null;
}
@Override
public void register(String username, String password, String homeserver) throws IOException {
// Only run if session isn't already set
if (session != null){
return;
}
// Build URL
URL url = Util.UrlBuilder(homeserver, Endpoint.REGISTER, null, null);
// Build request body
JsonObject request = new JsonObject();
request.addProperty("password", password);
if(username != null) {
request.addProperty("username", username);
}
// Send Request for session
JsonObject finalResponse;
try {
finalResponse = Util.makeJsonPostRequest(url, request).getAsJsonObject();
} catch (RestfulHTTPException e) {
if(e.getStatusCode() != 401) { throw e; }
JsonObject firstResponse = e.getErrorResponse();
// Create auth object
JsonObject auth = new JsonObject();
auth.addProperty("session", String.valueOf(firstResponse.get("session")));
auth.addProperty("type","m.login.dummy");
request.add("auth", auth.getAsJsonObject());
// Send Request for registering
finalResponse = Util.makeJsonPostRequest(url, request).getAsJsonObject();
}
// Set Session
this.session = new Session(finalResponse);
}
@Override
public JsonObject sync(String filter, String since, boolean fullState, Presence setPresence, int timeout) throws RestfulHTTPException, IOException{
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
if(filter != null && !filter.equals("")) {
parameters.put("filter", filter);
}
if(since != null && !since.equals("")) {
parameters.put("since", since);
}
if(setPresence != null) {
parameters.put("set_presence", setPresence == Presence.ONLINE ? "online" : "offline");
}
if(fullState) {
parameters.put("full_state", "true");
}
if(timeout > 0) {
parameters.put("timeout", Integer.toString(timeout));
}
parameters.put("access_token", session.getAccessToken());
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.SYNC, null, parameters);
// Send request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public JsonObject getPublicRooms(String server) throws RestfulHTTPException, IOException {
// Build URL
URL url = Util.UrlBuilder(server, Endpoint.PUBLIC_ROOMS, null, null);
// Send request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public JsonObject getRoomMessages(String roomId, String from, String to, boolean backward, Integer limit) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
if(from != null) {
parameters.put("from", from);
}
if(to != null) {
parameters.put("to", to);
}
if(limit != null) {
parameters.put("limit", limit.toString());
}
parameters.put("dir", backward ? "b" : "f");
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.ROOM_MESSAGES, new Object[] {roomId}, parameters);
// Send Request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public JsonObject getRoomMembers(String roomId) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.ROOM_MEMBERS, new Object[] {roomId}, parameters);
// Send Request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public JsonObject getUserProfile(String userId) throws RestfulHTTPException, IOException {
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.USER_PROFILE, new Object[] {userId}, null);
// Send Request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public JsonObject getUserAvatarUrl(String userId) throws RestfulHTTPException, IOException {
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.USER_AVATAR_URL, new Object[] {userId}, null);
// Send Request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public void setUserAvatarUrl(URL avatarUrl) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.USER_AVATAR_URL, new Object[] {session.getUserId()}, parameters);
// Build Json Object containing data
JsonObject json = new JsonObject();
json.addProperty("avatar_url", avatarUrl.toString());
// Send Request
Util.makeJsonPutRequest(url, json);
}
@Override
public JsonObject getUserDisplayName(String userId) throws RestfulHTTPException, IOException {
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.USER_DISPLAY_NAME, new Object[] {userId}, null);
// Send Request
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public void setUserDisplayName(String displayName) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.USER_DISPLAY_NAME, new Object[] {session.getUserId()}, parameters);
// Build Json Object containing data
JsonObject json = new JsonObject();
json.addProperty("displayname", displayName);
// Send Request
Util.makeJsonPutRequest(url, json);
}
//Bugged in current version of matrix, use with caution.
@Override
public JsonArray getUserPresence(String userId)throws RestfulHTTPException, IOException{
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
// Build URL
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.PRESENCE_LIST, new Object[] {userId}, parameters);
// Send Request
return Util.makeJsonGetRequest(url).getAsJsonArray();
}
@Override
public JsonObject roomSendEvent(String roomId, String eventType, JsonObject content) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
// Build URL, increment transactionId
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.ROOM_SEND_EVENT, new Object[] {roomId, eventType, session.transactionId++}, parameters);
// Send Request
return Util.makeJsonPutRequest(url, content).getAsJsonObject();
}
@Override
public JsonObject getRoomIDFromAlias(String roomAlias) throws RestfulHTTPException, IOException {
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.ROOM_DIRECTORY,new Object[] {roomAlias}, null);
//Send request URL.
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public JsonObject deleteRoomAlias(String roomAlias) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.ROOM_DIRECTORY,new Object[] {roomAlias}, parameters);
//Send request URL.
return Util.makeJsonDeleteRequest(url, null).getAsJsonObject();
}
@Override
public JsonObject putRoomAlias(String roomAlias, String roomId) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.ROOM_DIRECTORY,new Object[] {roomAlias}, parameters);
//Build JsonObject
JsonObject roomIdJsonObject = new JsonObject();
roomIdJsonObject.addProperty("room_id", roomId);
//Send request URL.
return Util.makeJsonPutRequest(url, roomIdJsonObject).getAsJsonObject();
}
@Override
public JsonObject postCreateRoom(JsonObject roomCreation) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(),Endpoint.ROOM_CREATE,null, parameters);
//Send request URL.
return Util.makeJsonPostRequest(url, roomCreation).getAsJsonObject();
}
@Override
public JsonObject postJoinRoomIdorAlias(String roomIdorAlias, JsonObject thirdPartySigned) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(),Endpoint.ROOM_JOIN_ID_OR_A,new Object[] {roomIdorAlias}, parameters);
//Send request URL.
return Util.makeJsonPostRequest(url, thirdPartySigned).getAsJsonObject();
}
@Override
public void postLeaveRoom(String roomId) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(),Endpoint.ROOM_LEAVE, new Object[] {roomId}, parameters);
//Send request URL.
Util.makeJsonPostRequest(url, null);
}
@Override
public void postKickFromRoom(String roomId, String reason, String userId) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(),Endpoint.ROOM_KICK, new Object[] {roomId}, parameters);
//Build JsonObject
JsonObject kick = new JsonObject();
kick.addProperty("reason", reason);
kick.addProperty("user_id",userId);
//Send request URL.
Util.makeJsonPostRequest(url, kick);
}
@Override
public void postInviteToRoom(String roomId, String address, String idServer, String medium) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(),Endpoint.ROOM_INVITE, new Object[] {roomId}, parameters);
//Build Json object
JsonObject invite = new JsonObject();
invite.addProperty("address", address);
invite.addProperty("id_server", idServer);
invite.addProperty("medium", medium);
//Send request URL.
Util.makeJsonPostRequest(url, invite);
}
@Override
public void postInviteToRoom(String roomId, String userId/*contains "id_server","medium" and "address", or simply "user_id"*/) throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(),Endpoint.ROOM_INVITE, new Object[] {roomId}, parameters);
//Build JsonObject
JsonObject invite = new JsonObject();
invite.addProperty("user_id", userId);
//Send request URL.
Util.makeJsonPostRequest(url, invite);
}
@Override
public JsonObject get3Pid() throws RestfulHTTPException, IOException {
// Build parameter Map
Map<String, String> parameters = new HashMap<>();
parameters.put("access_token", session.getAccessToken());
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.THIRD_PERSON_ID,null, parameters);
//Send request URL.
return Util.makeJsonGetRequest(url).getAsJsonObject();
}
@Override
public InputStream getMediaContent(URL mediaUrl) throws RestfulHTTPException, IOException {
//Build request URL.
URL url = Util.UrlBuilder(session.getHomeServer(), Endpoint.MEDIA_DOWNLOAD, new Object[] {mediaUrl.getHost(),mediaUrl.getPath().replaceFirst("/", "")}, null);
HttpURLConnection conn = null;
try {
// Setup the connection
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
return conn.getInputStream();
} catch (IOException e) {
Util.handleRestfulHTTPException(conn);
return null;
}
}
@Override
public InputStream getMediaContentThumbnail(URL mediaUrl, int size) throws RestfulHTTPException, IOException {
//Make parameter map
Map<String, String> parameters = new HashMap<>();
parameters.put("height", String.valueOf(size));
parameters.put("width", String.valueOf(size));
parameters.put("method", "crop");
URL url;
//Build request URL.
if (mediaUrl.getPort()==-1) {
url = Util.UrlBuilder(session.getHomeServer(), Endpoint.MEDIA_THUMBNAIL, new Object[]{mediaUrl.getHost(), mediaUrl.getPath().replaceFirst("/", "")}, parameters);
}
else {
url = Util.UrlBuilder(session.getHomeServer(), Endpoint.MEDIA_THUMBNAIL, new Object[]{mediaUrl.getHost()+":"+mediaUrl.getPort(), mediaUrl.getPath().replaceFirst("/", "")}, parameters);
}
HttpURLConnection conn = null;
try {
// Setup the connection
conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
return conn.getInputStream();
} catch (IOException e) {
Util.handleRestfulHTTPException(conn);
return null;
}
}
}
| Gurgy/Cypher | src/main/java/com/github/cypher/sdk/api/MatrixApiLayer.java | Java | gpl-3.0 | 17,603 |
package com.crossover.aws;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* The main Spring application
*
* @author [email protected]
*/
@SpringBootApplication
public class WeatherServer {
public static void main(String[] args) {
SpringApplication.run(WeatherServer.class, args);
}
}
| asaeles/airport-weather-server | src/main/java/com/crossover/aws/WeatherServer.java | Java | gpl-3.0 | 384 |
package net.innig.macker.event;
import org.apache.commons.lang.exception.NestableException;
public class ListenerException
extends NestableException
{
public ListenerException(MackerEventListener listener, String message)
{
super(createMessage(listener, message));
this.listener = listener;
}
public ListenerException(MackerEventListener listener, String message, Throwable cause)
{
super(createMessage(listener, message), cause);
this.listener = listener;
}
public MackerEventListener getListener()
{ return listener; }
private static String createMessage(MackerEventListener listener, String message)
{ return "Aborted by " + listener + ": " + message; }
private final MackerEventListener listener;
}
| MackerRuleChecker/Macker | macker/src/net/innig/macker/event/ListenerException.java | Java | gpl-3.0 | 837 |
package tr.org.linux.kamp.GameExamp;
import java.awt.Color;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Random;
import tr.org.linux.kamp.WindowBuilder.FirstPanel.Difficulty;
/**
* Controller class.Every gameObject movement and actions controlling here. sets
* game start and gameover
*
* @author atakan
*
*/
public class GameLogic {
private Player player;
private ArrayList<GameObject> gameObjects;
private GameFrame gameFrame;
private GamePanel gamePanel;
private boolean isGameRunning;
private int xTarget;
private int yTarget;
private ArrayList<GameObject> chipsToRemove;
private ArrayList<GameObject> minesToRemove;
private ArrayList<GameObject> enemiesToRemove;
private Random random;
/**
*
* @param name for game's name
* @param color
* @param dif for game's diffucilty.It changes mine,enemie and chip numbers.
*/
public GameLogic(String name, Color color, Difficulty dif) {
player = new Player(10, 10, 15, color, 4, name);
gameObjects = new ArrayList<GameObject>();
gameObjects.add(player);
gameFrame = new GameFrame();
gamePanel = new GamePanel(gameObjects);
chipsToRemove = new ArrayList<>();
enemiesToRemove = new ArrayList<>();
minesToRemove = new ArrayList<>();
random = new Random();
switch (dif) {
case EASY:
fillChips(40);
fillMines(3);
fillEnemies(2);
break;
case NORMAL:
fillChips(19);
fillMines(5);
fillEnemies(5);
break;
case HARD:
fillChips(17);
fillMines(8);
fillEnemies(5);
break;
}
addMouseEvent();
}
/**
* Checking gameObjects collision each other.For every gameObject it changes how to act.
*/
private synchronized void checkCollisions() {
for (GameObject gameObject : gameObjects) {
if (player.getRectangle().intersects(gameObject.getRectangle())) {
if (gameObject instanceof Chip) {
player.setRadius(player.getRadius() + gameObject.getRadius());
chipsToRemove.add(gameObject);
}
if (gameObject instanceof Mine) {
player.setRadius((int) player.getRadius() / 2);
minesToRemove.add(gameObject);
}
if (gameObject instanceof Enemy) {
if (player.getRadius() > gameObject.getRadius()) {
player.setRadius(player.getRadius() + gameObject.getRadius());
enemiesToRemove.add(gameObject);
} else if (player.getRadius() < gameObject.getRadius()) {
gameObject.setRadius(player.getRadius() + gameObject.getRadius());
/////// GAME OVER
isGameRunning = false;
}
}
}
if (gameObject instanceof Enemy) {
Enemy enemy = (Enemy) gameObject;
for (GameObject gameObject2 : gameObjects) {
if (enemy.getRectangle().intersects(gameObject2.getRectangle())) {
if (gameObject2 instanceof Chip) {
enemy.setRadius(enemy.getRadius() + gameObject2.getRadius());
chipsToRemove.add(gameObject2);
}
if (gameObject2 instanceof Mine) {
enemy.setRadius((int) enemy.getRadius() / 2);
minesToRemove.add(gameObject2);
}
}
}
}
}
gameObjects.removeAll(chipsToRemove);
gameObjects.removeAll(enemiesToRemove);
gameObjects.removeAll(minesToRemove);
}
/**
* when we eat chip,enemy or collision with mines.They remove and creating new one's in here.
*/
private synchronized void addNewObjects() {
fillChips(chipsToRemove.size());
fillMines(minesToRemove.size());
fillEnemies(enemiesToRemove.size());
enemiesToRemove.clear();
minesToRemove.clear();
chipsToRemove.clear();
}
/**
* Player's movement with mouse controller.If mouse on the right,Player goes right.
*/
private synchronized void movePlayer() {
if (xTarget > player.getX()) {
player.setX(player.getX() + player.getSpeed());
} else if (xTarget < player.getX()) {
player.setX(player.getX() - player.getSpeed());
}
if (yTarget > player.getY()) {
player.setY(player.getY() + player.getSpeed());
} else if (yTarget < player.getY()) {
player.setY(player.getY() - player.getSpeed());
}
}
/**
* Enemie's movement.If enemy radius higher then player,it chases player.Else it runs.
*/
private synchronized void moveEnemy() {
for (GameObject enemy : gameObjects) {
if (enemy instanceof Enemy) {
if (enemy.getRadius() < player.getRadius()) {
int distance = (int) Point.distance(player.getX(), player.getY(), enemy.getX(), enemy.getY());
int newX = enemy.getX() + enemy.getSpeed();
int newY = enemy.getY() + enemy.getSpeed();
if (CalculateNewDistanceToEnemy((Enemy) enemy, distance, newX, newY)) {
continue;
}
newX = enemy.getX() + enemy.getSpeed();
newY = enemy.getY() - enemy.getSpeed();
if (CalculateNewDistanceToEnemy((Enemy) enemy, distance, newX, newY)) {
continue;
}
newX = enemy.getX() - enemy.getSpeed();
newY = enemy.getY() + enemy.getSpeed();
if (CalculateNewDistanceToEnemy((Enemy) enemy, distance, newX, newY)) {
continue;
}
newX = enemy.getX() - enemy.getSpeed();
newY = enemy.getY() - enemy.getSpeed();
if (CalculateNewDistanceToEnemy((Enemy) enemy, distance, newX, newY)) {
continue;
}
} else {
if (player.getX() > enemy.getX()) {
enemy.setX(enemy.getX() + enemy.getSpeed());
} else if (player.getX() < enemy.getX()) {
enemy.setX(enemy.getX() - enemy.getSpeed());
}
if (player.getY() > enemy.getY()) {
enemy.setY(enemy.getY() + enemy.getSpeed());
} else if (player.getY() < enemy.getY()) {
enemy.setY(enemy.getY() - enemy.getSpeed());
}
}
}
}
}
/**
*
* @param enemy for moving enemy gameObject.
* @param distance for between distance with enemy and player
* @param X will be calculated X coordinate
* @param Y will be calculated Y coordinate
* @return
*/
private boolean CalculateNewDistanceToEnemy(Enemy enemy, int distance, int X, int Y) {
int newDistance = (int) Point.distance(player.getX(), player.getY(), X, Y);
if (newDistance > distance) {
enemy.setX(X);
enemy.setY(Y);
return true;
}
return false;
}
/**
* Adds chips into game
* @param n
*/
private synchronized void fillChips(int n) {
for (int i = 0; i < n; i++) {
gameObjects.add(new Chip(random.nextInt(1000), random.nextInt(1000), 10, Color.GREEN, 0));
}
}
/**
* Adds Enemies into game
* @param n
*/
private void fillEnemies(int n) {
for (int i = 0; i < n; i++) {
Enemy enemy = new Enemy(random.nextInt(1000), random.nextInt(1000), random.nextInt(10) + 10,
Color.DARK_GRAY, 1);
while (player.getRectangle().intersects(enemy.getRectangle())) {
enemy.setX(random.nextInt(750));
enemy.setY(random.nextInt(750));
}
gameObjects.add(enemy);
}
}
/**
* Adds mines into game
* @param n
*/
private void fillMines(int n) {
for (int i = 0; i < n; i++) {
Mine mine = new Mine(random.nextInt(1000), random.nextInt(1000), 14, Color.RED, 0);
while (player.getRectangle().intersects(mine.getRectangle())) {
mine.setX(random.nextInt(750));
mine.setY(random.nextInt(750));
}
gameObjects.add(mine);
}
}
/**
* Start game thread.It contains player movement,checkCollisions,Adds newObjects and Enemies movement
* Doing this with 50 ms delay.
*/
private void startGame() {
new Thread(new Runnable() {
@Override
public void run() {
while (isGameRunning) {
movePlayer();
checkCollisions();
addNewObjects();
moveEnemy();
gamePanel.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}).start();
}
/**
* Sets isGameRunning param to true for game start.
* set Visible our game window.
*/
public void startApp() {
gameFrame.setContentPane(gamePanel);
gameFrame.setVisible(true);
isGameRunning = true;
startGame();
}
/**
* Listens our mouse Actions for player movement.
*/
private void addMouseEvent() {
gameFrame.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseClicked(MouseEvent e) {
}
});
gamePanel.addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseMoved(MouseEvent e) {
xTarget = e.getX();
yTarget = e.getY();
}
@Override
public void mouseDragged(MouseEvent e) {
}
});
}
}
| AtakanSa/lyk17 | src/tr/org/linux/kamp/GameExamp/GameLogic.java | Java | gpl-3.0 | 8,688 |
package de.mat2095.my_slither;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.swing.*;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;
import javax.swing.table.DefaultTableCellRenderer;
final class MySlitherJFrame extends JFrame {
private static final String[] SNAKES = {
"00 - purple",
"01 - blue",
"02 - cyan",
"03 - green",
"04 - yellow",
"05 - orange",
"06 - salmon",
"07 - red",
"08 - violet",
"09 - flag: USA",
"10 - flag: Russia",
"11 - flag: Germany",
"12 - flag: Italy",
"13 - flag: France",
"14 - white/red",
"15 - rainbow",
"16 - blue/yellow",
"17 - white/blue",
"18 - red/white",
"19 - white",
"20 - green/purple",
"21 - flag: Brazil",
"22 - flag: Ireland",
"23 - flag: Romania",
"24 - cyan/yellow +extra",
"25 - purple/orange +extra",
"26 - grey/brown",
"27 - green with eye",
"28 - yellow/green/red",
"29 - black/yellow",
"30 - stars/EU",
"31 - stars",
"32 - EU",
"33 - yellow/black",
"34 - colorful",
"35 - red/white/pink",
"36 - blue/white/light-blue",
"37 - Kwebbelkop",
"38 - yellow",
"39 - PewDiePie",
"40 - green happy",
"41 - red with eyes",
"42 - Google Play",
"43 - UK",
"44 - Ghost",
"45 - Canada",
"46 - Swiss",
"47 - Moldova",
"48 - Vietnam",
"49 - Argentina",
"50 - Colombia",
"51 - Thailand",
"52 - red/yellow",
"53 - glowy-blue",
"54 - glowy-red",
"55 - glowy-yellow",
"56 - glowy-orange",
"57 - glowy-purple",
"58 - glowy-green",
"59 - yellow-M",
"60 - detailed UK",
"61 - glowy-colorful",
"62 - purple spiral",
"63 - red/black",
"64 - blue/black"
};
// TODO: skins, prey-size, snake-length/width, bot-layer, that-other-thing(?), show ping
private final JTextField server, name;
private final JComboBox<String> snake;
private final JCheckBox useRandomServer;
private final JToggleButton connect;
private final JLabel rank, kills;
private final JSplitPane rightSplitPane, fullSplitPane;
private final JTextArea log;
private final JScrollBar logScrollBar;
private final JTable highscoreList;
private final MySlitherCanvas canvas;
private final long startTime;
private final Timer updateTimer;
private Status status;
private URI[] serverList;
private MySlitherWebSocketClient client;
private final Player player;
MySlitherModel model;
final Object modelLock = new Object();
MySlitherJFrame() {
super("MySlither");
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
updateTimer.cancel();
if (status == Status.CONNECTING || status == Status.CONNECTED) {
disconnect();
}
canvas.repaintThread.shutdown();
try {
canvas.repaintThread.awaitTermination(1000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
});
getContentPane().setLayout(new BorderLayout());
canvas = new MySlitherCanvas(this);
player = canvas.mouseInput;
// === upper row ===
JPanel settings = new JPanel(new GridBagLayout());
server = new JTextField(18);
name = new JTextField("MySlitherEaterBot", 16);
snake = new JComboBox<>(SNAKES);
snake.setMaximumRowCount(snake.getItemCount());
useRandomServer = new JCheckBox("use random server", true);
useRandomServer.addActionListener(a -> {
setStatus(null);
});
connect = new JToggleButton();
connect.addActionListener(a -> {
switch (status) {
case DISCONNECTED:
connect();
break;
case CONNECTING:
case CONNECTED:
disconnect();
break;
case DISCONNECTING:
break;
}
});
connect.addAncestorListener(new AncestorListener() {
@Override
public void ancestorAdded(AncestorEvent event) {
connect.requestFocusInWindow();
connect.removeAncestorListener(this);
}
@Override
public void ancestorRemoved(AncestorEvent event) {
}
@Override
public void ancestorMoved(AncestorEvent event) {
}
});
rank = new JLabel();
kills = new JLabel();
settings.add(new JLabel("server:"),
new GridBagConstraints(0, 0, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(server,
new GridBagConstraints(1, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
settings.add(new JLabel("name:"),
new GridBagConstraints(0, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(name,
new GridBagConstraints(1, 1, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
settings.add(new JLabel("skin:"),
new GridBagConstraints(0, 2, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(snake,
new GridBagConstraints(1, 2, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, new Insets(2, 2, 2, 2), 0, 0));
settings.add(useRandomServer,
new GridBagConstraints(2, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(connect,
new GridBagConstraints(2, 1, 1, 2, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(2, 2, 2, 2), 0, 0));
settings.add(new JSeparator(SwingConstants.VERTICAL),
new GridBagConstraints(3, 0, 1, 3, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 6, 0, 6), 0, 0));
settings.add(new JLabel("kills:"),
new GridBagConstraints(4, 1, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(kills,
new GridBagConstraints(5, 1, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(new JLabel("rank:"),
new GridBagConstraints(4, 2, 1, 1, 0, 0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
settings.add(rank,
new GridBagConstraints(5, 2, 1, 1, 0, 0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(2, 2, 2, 2), 0, 0));
JComponent upperRow = new JPanel(new FlowLayout(FlowLayout.LEFT));
upperRow.add(settings);
getContentPane().add(upperRow, BorderLayout.NORTH);
// === center ===
log = new JTextArea("hi");
log.setEditable(false);
log.setLineWrap(true);
log.setFont(Font.decode("Monospaced 11"));
log.setTabSize(4);
log.getCaret().setSelectionVisible(false);
log.getInputMap().clear();
log.getActionMap().clear();
log.getInputMap().put(KeyStroke.getKeyStroke("END"), "gotoEnd");
log.getActionMap().put("gotoEnd", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(() -> {
logScrollBar.setValue(logScrollBar.getMaximum() - logScrollBar.getVisibleAmount());
});
}
});
log.getInputMap().put(KeyStroke.getKeyStroke("HOME"), "gotoStart");
log.getActionMap().put("gotoStart", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(() -> {
logScrollBar.setValue(logScrollBar.getMinimum());
});
}
});
highscoreList = new JTable(10, 2);
highscoreList.setEnabled(false);
highscoreList.getColumnModel().getColumn(0).setMinWidth(64);
highscoreList.getColumnModel().getColumn(1).setMinWidth(192);
highscoreList.getColumnModel().getColumn(0).setHeaderValue("length");
highscoreList.getColumnModel().getColumn(1).setHeaderValue("name");
highscoreList.getTableHeader().setReorderingAllowed(false);
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
highscoreList.getColumnModel().getColumn(0).setCellRenderer(rightRenderer);
highscoreList.setPreferredScrollableViewportSize(new Dimension(64 + 192, highscoreList.getPreferredSize().height));
// == split-panes ==
rightSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, canvas, new JScrollPane(highscoreList));
rightSplitPane.setDividerSize(rightSplitPane.getDividerSize() * 4 / 3);
rightSplitPane.setResizeWeight(0.99);
JScrollPane logScrollPane = new JScrollPane(log);
logScrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
logScrollPane.setPreferredSize(new Dimension(300, logScrollPane.getPreferredSize().height));
logScrollBar = logScrollPane.getVerticalScrollBar();
fullSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, true, logScrollPane, rightSplitPane);
fullSplitPane.setDividerSize(fullSplitPane.getDividerSize() * 4 / 3);
fullSplitPane.setResizeWeight(0.1);
getContentPane().add(fullSplitPane, BorderLayout.CENTER);
int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
setSize(screenWidth * 3 / 4, screenHeight * 4 / 5);
setLocation((screenWidth - getWidth()) / 2, (screenHeight - getHeight()) / 2);
setExtendedState(MAXIMIZED_BOTH);
validate();
startTime = System.currentTimeMillis();
setStatus(Status.DISCONNECTED);
updateTimer = new Timer();
updateTimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
synchronized (modelLock) {
if (status == Status.CONNECTED && model != null) {
model.update();
client.sendData(player.action(model));
}
}
}
}, 1, 10);
}
void onOpen() {
switch (status) {
case CONNECTING:
setStatus(Status.CONNECTED);
client.sendInitRequest(snake.getSelectedIndex(), name.getText());
break;
case DISCONNECTING:
disconnect();
break;
default:
throw new IllegalStateException("Connected while not connecting!");
}
}
void onClose() {
switch (status) {
case CONNECTED:
case DISCONNECTING:
setStatus(Status.DISCONNECTED);
client = null;
break;
case CONNECTING:
client = null;
trySingleConnect();
break;
default:
throw new IllegalStateException("Disconnected while not connecting, connected or disconnecting!");
}
}
private void connect() {
new Thread(() -> {
if (status != Status.DISCONNECTED) {
throw new IllegalStateException("Connecting while not disconnected");
}
setStatus(Status.CONNECTING);
setModel(null);
if (useRandomServer.isSelected()) {
log("fetching server-list...");
serverList = MySlitherWebSocketClient.getServerList();
log("received " + serverList.length + " servers");
if (serverList.length <= 0) {
log("no server found");
setStatus(Status.DISCONNECTED);
return;
}
}
if (status == Status.CONNECTING) {
trySingleConnect();
}
}).start();
}
private void trySingleConnect() {
if (status != Status.CONNECTING) {
throw new IllegalStateException("Trying single connection while not connecting");
}
if (useRandomServer.isSelected()) {
client = new MySlitherWebSocketClient(serverList[(int) (Math.random() * serverList.length)], this);
server.setText(client.getURI().toString());
} else {
try {
client = new MySlitherWebSocketClient(new URI(server.getText()), this);
} catch (URISyntaxException ex) {
log("invalid server");
setStatus(Status.DISCONNECTED);
return;
}
}
log("connecting to " + client.getURI() + " ...");
client.connect();
}
private void disconnect() {
if (status == Status.DISCONNECTED) {
throw new IllegalStateException("Already disconnected");
}
setStatus(Status.DISCONNECTING);
if (client != null) {
client.close();
}
}
private void setStatus(Status newStatus) {
if (newStatus != null) {
status = newStatus;
}
connect.setText(status.buttonText);
connect.setSelected(status.buttonSelected);
connect.setEnabled(status.buttonEnabled);
server.setEnabled(status.allowModifyData && !useRandomServer.isSelected());
useRandomServer.setEnabled(status.allowModifyData);
name.setEnabled(status.allowModifyData);
snake.setEnabled(status.allowModifyData);
}
void log(String text) {
print(String.format("%6d\t%s", System.currentTimeMillis() - startTime, text));
}
private void print(String text) {
SwingUtilities.invokeLater(() -> {
boolean scrollToBottom = !logScrollBar.getValueIsAdjusting() && logScrollBar.getValue() >= logScrollBar.getMaximum() - logScrollBar.getVisibleAmount();
log.append('\n' + text);
fullSplitPane.getLeftComponent().validate();
if (scrollToBottom) {
logScrollBar.setValue(logScrollBar.getMaximum() - logScrollBar.getVisibleAmount());
}
});
}
void setModel(MySlitherModel model) {
synchronized (modelLock) {
this.model = model;
rank.setText(null);
kills.setText(null);
}
}
void setMap(boolean[] map) {
canvas.setMap(map);
}
void setRank(int newRank, int playerCount) {
rank.setText(newRank + "/" + playerCount);
}
void setKills(int newKills) {
kills.setText(String.valueOf(newKills));
}
void setHighscoreData(int row, String name, int length, boolean highlighted) {
highscoreList.setValueAt(highlighted ? "<html><b>" + length + "</b></html>" : length, row, 0);
highscoreList.setValueAt(highlighted ? "<html><b>" + name + "</b></html>" : name, row, 1);
}
private enum Status {
DISCONNECTED("connect", false, true, true),
CONNECTING("connecting...", true, true, false),
CONNECTED("disconnect", true, true, false),
DISCONNECTING("disconnecting...", false, false, false);
private final String buttonText;
private final boolean buttonSelected, buttonEnabled;
private final boolean allowModifyData;
private Status(String buttonText, boolean buttonSelected, boolean buttonEnabled, boolean allowModifyData) {
this.buttonText = buttonText;
this.buttonSelected = buttonSelected;
this.buttonEnabled = buttonEnabled;
this.allowModifyData = allowModifyData;
}
}
}
| Mat2095/MySlither | src/main/java/de/mat2095/my_slither/MySlitherJFrame.java | Java | gpl-3.0 | 16,906 |
/*
* © Copyright DigitalByte Entertainment and Software Tech Pvt. Ltd. 2013. All rights reserved.
* This program is licensed under GNU GPL v3.0(https://gnu.org/licenses/gpl.txt)
*/
package org.jMEengine.text;
import javax.microedition.lcdui.Graphics;
/**
*
* @author Adarsha Saraff
*/
public final class Text {
private String text;
private int x, y;
private Font f;
int[][] rgbData;
public Text(String text, int x, int y, Font font) {
this.text = text;
this.x = x;
this.y = y;
this.f = font;
rgbData = f.getFont(text);
}
public void setText(String text) {
this.text = text;
rgbData = f.getFont(text);
}
public void paint(Graphics g) {
for (int i = 0; i < rgbData.length; i++) {
g.drawRGB(rgbData[i], 0, f.getWidth(), x + (i * f.getWidth()), y, f.getWidth(), f.getHeight(), true);
}
}
public void setPosition(int x, int y) {
this.x = x;
this.y = y;
}
public String getText() {
return this.text;
}
}
| saraffadarsha/jMEengine | org/jMEengine/text/Text.java | Java | gpl-3.0 | 1,078 |
package dvoraka.avservice.storage;
import dvoraka.avservice.common.data.FileMessage;
import dvoraka.avservice.common.data.MessageType;
import dvoraka.avservice.storage.exception.FileServiceException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* File service aspects.
*/
@Aspect
@Component
public class FileServiceAspect {
private static final Logger log = LogManager.getLogger(FileServiceAspect.class);
private static final String BAD_TYPE = "Bad message type!";
@Before("execution(public void dvoraka.avservice.storage..saveFile(..)) && args(message)")
public void checkSaveType(FileMessage message) {
if (message.getType() != MessageType.FILE_SAVE) {
log.warn(BAD_TYPE);
throw new IllegalArgumentException(BAD_TYPE);
}
}
@Before("execution(public * dvoraka.avservice.storage..loadFile(..)) && args(message)")
public void checkLoadType(FileMessage message) {
if (message.getType() != MessageType.FILE_LOAD) {
log.warn(BAD_TYPE);
throw new IllegalArgumentException(BAD_TYPE);
}
}
@Before("execution(public void dvoraka.avservice.storage..updateFile(..)) && args(message)")
public void checkUpdateType(FileMessage message) {
if (message.getType() != MessageType.FILE_UPDATE) {
log.warn(BAD_TYPE);
throw new IllegalArgumentException(BAD_TYPE);
}
}
@Before("execution(public void dvoraka.avservice.storage..deleteFile(..)) && args(message)")
public void checkDeleteType(FileMessage message) {
if (message.getType() != MessageType.FILE_DELETE) {
log.warn(BAD_TYPE);
throw new IllegalArgumentException(BAD_TYPE);
}
}
@Around("execution(public * dvoraka.avservice.storage..*File(..)) && args(message)")
public Object logInfo(ProceedingJoinPoint pjp, FileMessage message)
throws FileServiceException {
long start = System.currentTimeMillis();
String methodName = pjp.getSignature().getName();
String className = pjp.getSourceLocation().getWithinType().getSimpleName();
Object result = null;
try {
result = pjp.proceed();
} catch (FileServiceException | RuntimeException e) {
throw e;
} catch (Throwable throwable) {
log.warn("Method failed!", throwable);
}
long duration = System.currentTimeMillis() - start;
log.debug("{}.{}(), time: {} ms, result: {}",
className, methodName, duration, result);
return result;
}
}
| dvoraka/av-service | storage/src/main/java/dvoraka/avservice/storage/FileServiceAspect.java | Java | gpl-3.0 | 2,873 |
package com.gildedgames.aether.common.entities.living.mounts;
import com.gildedgames.aether.api.entity.IMount;
import com.gildedgames.aether.api.entity.IMountProcessor;
import com.gildedgames.aether.common.blocks.BlocksAether;
import com.gildedgames.aether.common.entities.living.passive.EntityAetherAnimal;
import com.gildedgames.aether.common.entities.util.mounts.FlyingMount;
import com.gildedgames.aether.common.entities.util.mounts.IFlyingMountData;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.datasync.DataParameter;
import net.minecraft.network.datasync.DataSerializers;
import net.minecraft.network.datasync.EntityDataManager;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
public abstract class EntityFlyingAnimal extends EntityAetherAnimal implements IMount, IFlyingMountData
{
private static final DataParameter<Boolean> SADDLED = EntityDataManager.createKey(EntityFlyingAnimal.class, DataSerializers.BOOLEAN);
private static final DataParameter<Float> AIRBORNE_TIME = EntityDataManager.createKey(EntityFlyingAnimal.class, DataSerializers.FLOAT);
private IMountProcessor mountProcessor = new FlyingMount(this);
@SideOnly(Side.CLIENT)
public float wingFold, wingAngle;
public EntityFlyingAnimal(World world)
{
super(world);
this.spawnableBlock = BlocksAether.aether_grass;
}
@Override
protected void entityInit()
{
super.entityInit();
this.dataManager.register(EntityFlyingAnimal.SADDLED, false);
this.dataManager.register(EntityFlyingAnimal.AIRBORNE_TIME, this.maxAirborneTime());
}
@Override
public void onUpdate()
{
this.fallDistance = 0;
boolean riderSneaking = !this.getPassengers().isEmpty() && this.getPassengers().get(0) != null && this.getPassengers().get(0).isSneaking();
if (this.motionY < 0.0D && !riderSneaking)
{
this.motionY *= 0.6D;
}
if (this.worldObj.isRemote)
{
float aimingForFold = 1.0F;
if (this.onGround)
{
this.wingAngle *= 0.8F;
aimingForFold = 0.1F;
}
this.wingAngle = this.wingFold * (float) Math.sin(this.ticksExisted / 31.83098862F);
this.wingFold += (aimingForFold - this.wingFold) / 5F;
}
super.onUpdate();
}
@Override
public boolean processInteract(EntityPlayer player, EnumHand hand, @Nullable ItemStack stack)
{
if (!super.processInteract(player, hand, stack))
{
if (!player.worldObj.isRemote)
{
if (!this.isSaddled() && stack != null && stack.getItem() == Items.SADDLE && !this.isChild())
{
this.setIsSaddled(true);
if (!player.capabilities.isCreativeMode)
{
stack.stackSize--;
}
return true;
}
else
{
return false;
}
}
}
return true;
}
@Override
public void writeEntityToNBT(NBTTagCompound compound)
{
super.writeEntityToNBT(compound);
compound.setBoolean("IsSaddled", this.isSaddled());
}
@Override
public void readEntityFromNBT(NBTTagCompound compound)
{
super.readEntityFromNBT(compound);
this.setIsSaddled(compound.getBoolean("IsSaddled"));
}
@Override
protected void dropFewItems(boolean p_70628_1_, int looting)
{
super.dropFewItems(p_70628_1_, looting);
if (this.isSaddled())
{
this.dropItem(Items.SADDLE, 1);
}
}
public boolean isSaddled()
{
return this.dataManager.get(SADDLED);
}
public void setIsSaddled(boolean isSaddled)
{
this.dataManager.set(SADDLED, isSaddled);
}
@Override
public IMountProcessor getMountProcessor()
{
return this.mountProcessor;
}
@Override
public void resetRemainingAirborneTime()
{
this.dataManager.set(EntityFlyingAnimal.AIRBORNE_TIME, this.maxAirborneTime());
}
@Override
public float getRemainingAirborneTime()
{
return this.dataManager.get(EntityFlyingAnimal.AIRBORNE_TIME);
}
@Override
public void setRemainingAirborneTime(float set)
{
this.dataManager.set(EntityFlyingAnimal.AIRBORNE_TIME, set);
}
@Override
public void addRemainingAirborneTime(float add)
{
this.setRemainingAirborneTime(this.getRemainingAirborneTime() + add);
}
@Override
public boolean canBeMounted()
{
return this.isSaddled();
}
@Override
public boolean canProcessMountInteraction(EntityPlayer rider, ItemStack stack)
{
return !this.isBreedingItem(stack) && (stack == null || stack.getItem() != Items.LEAD);
}
public abstract float maxAirborneTime();
}
| Better-Aether/Better-Aether | src/main/java/com/gildedgames/aether/common/entities/living/mounts/EntityFlyingAnimal.java | Java | gpl-3.0 | 4,589 |
/*
* Copyright 2015 Erwin Müller <[email protected]>
*
* This file is part of prefdialog-spreadsheetimportdialog.
*
* prefdialog-spreadsheetimportdialog is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* prefdialog-spreadsheetimportdialog 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 Lesser General Public License
* along with prefdialog-spreadsheetimportdialog. If not, see <http://www.gnu.org/licenses/>.
*/
package com.anrisoftware.prefdialog.spreadsheetimportdialog.dialog;
import com.anrisoftware.globalpom.spreadsheetimport.SpreadsheetImporterModule;
import com.anrisoftware.prefdialog.core.CoreFieldComponentModule;
import com.anrisoftware.prefdialog.miscswing.docks.dockingframes.core.DockingFramesModule;
import com.anrisoftware.prefdialog.simpledialog.SimpleDialogModule;
import com.anrisoftware.prefdialog.spreadsheetimportdialog.importpanel.SpreadsheetImportPanel;
import com.anrisoftware.prefdialog.spreadsheetimportdialog.importpanel.SpreadsheetImportPanelFactory;
import com.anrisoftware.prefdialog.spreadsheetimportdialog.importpanel.SpreadsheetImportPanelModule;
import com.anrisoftware.prefdialog.spreadsheetimportdialog.panelproperties.panelproperties.SpreadsheetPanelPropertiesFactory;
import com.anrisoftware.prefdialog.spreadsheetimportdialog.previewpanel.SpreadsheetPreviewPanelModule;
import com.anrisoftware.resources.images.images.ImagesResourcesModule;
import com.anrisoftware.resources.images.mapcached.ResourcesImagesCachedMapModule;
import com.anrisoftware.resources.images.scaling.ResourcesSmoothScalingModule;
import com.anrisoftware.resources.texts.defaults.TextsResourcesDefaultModule;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.assistedinject.FactoryModuleBuilder;
/**
* Installs CSV import dialog factory and dependent modules.
*
* @see SpreadsheetImportPanel
* @see SpreadsheetImportPanelFactory
* @see SpreadsheetImportDialogModule
*
* @author Erwin Mueller, [email protected]
* @since 3.0
*/
public class SpreadsheetImportDialogModule extends AbstractModule {
/**
* @see #getFactory()
*/
public static SpreadsheetImportDialogFactory getCsvImportDialogFactory() {
return getFactory();
}
/**
* Returns the CSV import dialog factory.
*
* @return the {@link SpreadsheetImportDialogFactory}.
*/
public static SpreadsheetImportDialogFactory getFactory() {
return SingletonHolder.factory;
}
/**
* @see #getInjector()
*/
public static Injector getCsvImportDialogInjector() {
return getInjector();
}
/**
* Returns the CSV import dialog Guice injector.
*
* @return the {@link Injector}.
*/
public static Injector getInjector() {
return SingletonHolder.injector;
}
/**
* @see #getPropertiesFactory()
*/
public static SpreadsheetPanelPropertiesFactory getCsvImportPropertiesFactory() {
return getPropertiesFactory();
}
/**
* Creates and returns the panel properties factory.
*
* @return the {@link SpreadsheetPanelPropertiesFactory}.
*/
public static SpreadsheetPanelPropertiesFactory getPropertiesFactory() {
return SingletonHolder.propertiesFactory;
}
private static class SingletonHolder {
public static final Injector injector = Guice.createInjector(
new SpreadsheetImporterModule(),
new SpreadsheetPreviewPanelModule(),
new SpreadsheetImportDialogModule(),
new CoreFieldComponentModule(), new SimpleDialogModule(),
new DockingFramesModule(), new TextsResourcesDefaultModule(),
new ImagesResourcesModule(),
new ResourcesImagesCachedMapModule(),
new ResourcesSmoothScalingModule());
public static final SpreadsheetImportDialogFactory factory = injector
.getInstance(SpreadsheetImportDialogFactory.class);
public static final SpreadsheetPanelPropertiesFactory propertiesFactory = injector
.getInstance(SpreadsheetPanelPropertiesFactory.class);
}
@Override
protected void configure() {
install(new SpreadsheetImportPanelModule());
install(new SpreadsheetPreviewPanelModule());
install(new FactoryModuleBuilder().implement(
SpreadsheetImportDialog.class, SpreadsheetImportDialog.class)
.build(SpreadsheetImportDialogFactory.class));
install(new FactoryModuleBuilder().implement(PropertiesWorker.class,
PropertiesWorker.class).build(PropertiesWorkerFactory.class));
}
}
| devent/prefdialog | prefdialog-spreadsheetimportdialog/src/main/java/com/anrisoftware/prefdialog/spreadsheetimportdialog/dialog/SpreadsheetImportDialogModule.java | Java | gpl-3.0 | 5,158 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Pair;
import com.android.internal.statusbar.IStatusBar;
import com.android.internal.statusbar.StatusBarIcon;
import com.android.internal.statusbar.StatusBarIconList;
/**
* This class takes the functions from IStatusBar that come in on
* binder pool threads and posts messages to get them onto the main
* thread, and calls onto Callbacks. It also takes care of
* coalescing these calls so they don't stack up. For the calls
* are coalesced, note that they are all idempotent.
*/
public class CommandQueue extends IStatusBar.Stub {
private static final int INDEX_MASK = 0xffff;
private static final int MSG_SHIFT = 16;
private static final int MSG_MASK = 0xffff << MSG_SHIFT;
private static final int OP_SET_ICON = 1;
private static final int OP_REMOVE_ICON = 2;
private static final int MSG_ICON = 1 << MSG_SHIFT;
private static final int MSG_DISABLE = 2 << MSG_SHIFT;
private static final int MSG_EXPAND_NOTIFICATIONS = 3 << MSG_SHIFT;
private static final int MSG_COLLAPSE_PANELS = 4 << MSG_SHIFT;
private static final int MSG_EXPAND_SETTINGS = 5 << MSG_SHIFT;
private static final int MSG_SET_SYSTEMUI_VISIBILITY = 6 << MSG_SHIFT;
private static final int MSG_TOP_APP_WINDOW_CHANGED = 7 << MSG_SHIFT;
private static final int MSG_SHOW_IME_BUTTON = 8 << MSG_SHIFT;
private static final int MSG_TOGGLE_RECENT_APPS = 9 << MSG_SHIFT;
private static final int MSG_PRELOAD_RECENT_APPS = 10 << MSG_SHIFT;
private static final int MSG_CANCEL_PRELOAD_RECENT_APPS = 11 << MSG_SHIFT;
private static final int MSG_SET_WINDOW_STATE = 12 << MSG_SHIFT;
private static final int MSG_SHOW_RECENT_APPS = 13 << MSG_SHIFT;
private static final int MSG_HIDE_RECENT_APPS = 14 << MSG_SHIFT;
private static final int MSG_BUZZ_BEEP_BLINKED = 15 << MSG_SHIFT;
private static final int MSG_NOTIFICATION_LIGHT_OFF = 16 << MSG_SHIFT;
private static final int MSG_NOTIFICATION_LIGHT_PULSE = 17 << MSG_SHIFT;
private static final int MSG_SHOW_SCREEN_PIN_REQUEST = 18 << MSG_SHIFT;
private static final int MSG_APP_TRANSITION_PENDING = 19 << MSG_SHIFT;
private static final int MSG_APP_TRANSITION_CANCELLED = 20 << MSG_SHIFT;
private static final int MSG_APP_TRANSITION_STARTING = 21 << MSG_SHIFT;
private static final int MSG_ASSIST_DISCLOSURE = 22 << MSG_SHIFT;
private static final int MSG_START_ASSIST = 23 << MSG_SHIFT;
public static final int FLAG_EXCLUDE_NONE = 0;
public static final int FLAG_EXCLUDE_SEARCH_PANEL = 1 << 0;
public static final int FLAG_EXCLUDE_RECENTS_PANEL = 1 << 1;
public static final int FLAG_EXCLUDE_NOTIFICATION_PANEL = 1 << 2;
public static final int FLAG_EXCLUDE_INPUT_METHODS_PANEL = 1 << 3;
public static final int FLAG_EXCLUDE_COMPAT_MODE_PANEL = 1 << 4;
private static final String SHOW_IME_SWITCHER_KEY = "showImeSwitcherKey";
private StatusBarIconList mList;
private Callbacks mCallbacks;
private Handler mHandler = new H();
/**
* These methods are called back on the main thread.
*/
public interface Callbacks {
public void addIcon(String slot, int index, int viewIndex, StatusBarIcon icon);
public void updateIcon(String slot, int index, int viewIndex,
StatusBarIcon old, StatusBarIcon icon);
public void removeIcon(String slot, int index, int viewIndex);
public void disable(int state1, int state2, boolean animate);
public void animateExpandNotificationsPanel();
public void animateCollapsePanels(int flags);
public void animateExpandSettingsPanel();
public void setSystemUiVisibility(int vis, int mask);
public void topAppWindowChanged(boolean visible);
public void setImeWindowStatus(IBinder token, int vis, int backDisposition,
boolean showImeSwitcher);
public void showRecentApps(boolean triggeredFromAltTab);
public void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHomeKey);
public void toggleRecentApps();
public void preloadRecentApps();
public void cancelPreloadRecentApps();
public void setWindowState(int window, int state);
public void buzzBeepBlinked();
public void notificationLightOff();
public void notificationLightPulse(int argb, int onMillis, int offMillis);
public void showScreenPinningRequest();
public void appTransitionPending();
public void appTransitionCancelled();
public void appTransitionStarting(long startTime, long duration);
public void showAssistDisclosure();
public void startAssist(Bundle args);
}
public CommandQueue(Callbacks callbacks, StatusBarIconList list) {
mCallbacks = callbacks;
mList = list;
}
public void setIcon(int index, StatusBarIcon icon) {
synchronized (mList) {
int what = MSG_ICON | index;
mHandler.removeMessages(what);
mHandler.obtainMessage(what, OP_SET_ICON, 0, icon.clone()).sendToTarget();
}
}
public void removeIcon(int index) {
synchronized (mList) {
int what = MSG_ICON | index;
mHandler.removeMessages(what);
mHandler.obtainMessage(what, OP_REMOVE_ICON, 0, null).sendToTarget();
}
}
public void disable(int state1, int state2) {
synchronized (mList) {
mHandler.removeMessages(MSG_DISABLE);
mHandler.obtainMessage(MSG_DISABLE, state1, state2, null).sendToTarget();
}
}
public void animateExpandNotificationsPanel() {
synchronized (mList) {
mHandler.removeMessages(MSG_EXPAND_NOTIFICATIONS);
mHandler.sendEmptyMessage(MSG_EXPAND_NOTIFICATIONS);
}
}
public void animateCollapsePanels() {
synchronized (mList) {
mHandler.removeMessages(MSG_COLLAPSE_PANELS);
mHandler.sendEmptyMessage(MSG_COLLAPSE_PANELS);
}
}
public void animateExpandSettingsPanel() {
synchronized (mList) {
mHandler.removeMessages(MSG_EXPAND_SETTINGS);
mHandler.sendEmptyMessage(MSG_EXPAND_SETTINGS);
}
}
public void setSystemUiVisibility(int vis, int mask) {
synchronized (mList) {
// Don't coalesce these, since it might have one time flags set such as
// STATUS_BAR_UNHIDE which might get lost.
mHandler.obtainMessage(MSG_SET_SYSTEMUI_VISIBILITY, vis, mask, null).sendToTarget();
}
}
public void topAppWindowChanged(boolean menuVisible) {
synchronized (mList) {
mHandler.removeMessages(MSG_TOP_APP_WINDOW_CHANGED);
mHandler.obtainMessage(MSG_TOP_APP_WINDOW_CHANGED, menuVisible ? 1 : 0, 0,
null).sendToTarget();
}
}
public void setImeWindowStatus(IBinder token, int vis, int backDisposition,
boolean showImeSwitcher) {
synchronized (mList) {
mHandler.removeMessages(MSG_SHOW_IME_BUTTON);
Message m = mHandler.obtainMessage(MSG_SHOW_IME_BUTTON, vis, backDisposition, token);
m.getData().putBoolean(SHOW_IME_SWITCHER_KEY, showImeSwitcher);
m.sendToTarget();
}
}
public void showRecentApps(boolean triggeredFromAltTab) {
synchronized (mList) {
mHandler.removeMessages(MSG_SHOW_RECENT_APPS);
mHandler.obtainMessage(MSG_SHOW_RECENT_APPS,
triggeredFromAltTab ? 1 : 0, 0, null).sendToTarget();
}
}
public void hideRecentApps(boolean triggeredFromAltTab, boolean triggeredFromHomeKey) {
synchronized (mList) {
mHandler.removeMessages(MSG_HIDE_RECENT_APPS);
mHandler.obtainMessage(MSG_HIDE_RECENT_APPS,
triggeredFromAltTab ? 1 : 0, triggeredFromHomeKey ? 1 : 0,
null).sendToTarget();
}
}
public void toggleRecentApps() {
synchronized (mList) {
mHandler.removeMessages(MSG_TOGGLE_RECENT_APPS);
mHandler.obtainMessage(MSG_TOGGLE_RECENT_APPS, 0, 0, null).sendToTarget();
}
}
public void preloadRecentApps() {
synchronized (mList) {
mHandler.removeMessages(MSG_PRELOAD_RECENT_APPS);
mHandler.obtainMessage(MSG_PRELOAD_RECENT_APPS, 0, 0, null).sendToTarget();
}
}
public void cancelPreloadRecentApps() {
synchronized (mList) {
mHandler.removeMessages(MSG_CANCEL_PRELOAD_RECENT_APPS);
mHandler.obtainMessage(MSG_CANCEL_PRELOAD_RECENT_APPS, 0, 0, null).sendToTarget();
}
}
public void setWindowState(int window, int state) {
synchronized (mList) {
// don't coalesce these
mHandler.obtainMessage(MSG_SET_WINDOW_STATE, window, state, null).sendToTarget();
}
}
public void buzzBeepBlinked() {
synchronized (mList) {
mHandler.removeMessages(MSG_BUZZ_BEEP_BLINKED);
mHandler.sendEmptyMessage(MSG_BUZZ_BEEP_BLINKED);
}
}
public void notificationLightOff() {
synchronized (mList) {
mHandler.sendEmptyMessage(MSG_NOTIFICATION_LIGHT_OFF);
}
}
public void notificationLightPulse(int argb, int onMillis, int offMillis) {
synchronized (mList) {
mHandler.obtainMessage(MSG_NOTIFICATION_LIGHT_PULSE, onMillis, offMillis, argb)
.sendToTarget();
}
}
public void showScreenPinningRequest() {
synchronized (mList) {
mHandler.sendEmptyMessage(MSG_SHOW_SCREEN_PIN_REQUEST);
}
}
public void appTransitionPending() {
synchronized (mList) {
mHandler.removeMessages(MSG_APP_TRANSITION_PENDING);
mHandler.sendEmptyMessage(MSG_APP_TRANSITION_PENDING);
}
}
public void appTransitionCancelled() {
synchronized (mList) {
mHandler.removeMessages(MSG_APP_TRANSITION_PENDING);
mHandler.sendEmptyMessage(MSG_APP_TRANSITION_PENDING);
}
}
public void appTransitionStarting(long startTime, long duration) {
synchronized (mList) {
mHandler.removeMessages(MSG_APP_TRANSITION_STARTING);
mHandler.obtainMessage(MSG_APP_TRANSITION_STARTING, Pair.create(startTime, duration))
.sendToTarget();
}
}
public void showAssistDisclosure() {
synchronized (mList) {
mHandler.removeMessages(MSG_ASSIST_DISCLOSURE);
mHandler.obtainMessage(MSG_ASSIST_DISCLOSURE).sendToTarget();
}
}
public void startAssist(Bundle args) {
synchronized (mList) {
mHandler.removeMessages(MSG_START_ASSIST);
mHandler.obtainMessage(MSG_START_ASSIST, args).sendToTarget();
}
}
private final class H extends Handler {
public void handleMessage(Message msg) {
final int what = msg.what & MSG_MASK;
switch (what) {
case MSG_ICON: {
final int index = msg.what & INDEX_MASK;
final int viewIndex = mList.getViewIndex(index);
switch (msg.arg1) {
case OP_SET_ICON: {
StatusBarIcon icon = (StatusBarIcon)msg.obj;
StatusBarIcon old = mList.getIcon(index);
if (old == null) {
mList.setIcon(index, icon);
mCallbacks.addIcon(mList.getSlot(index), index, viewIndex, icon);
} else {
mList.setIcon(index, icon);
mCallbacks.updateIcon(mList.getSlot(index), index, viewIndex,
old, icon);
}
break;
}
case OP_REMOVE_ICON:
if (mList.getIcon(index) != null) {
mList.removeIcon(index);
mCallbacks.removeIcon(mList.getSlot(index), index, viewIndex);
}
break;
}
break;
}
case MSG_DISABLE:
mCallbacks.disable(msg.arg1, msg.arg2, true /* animate */);
break;
case MSG_EXPAND_NOTIFICATIONS:
mCallbacks.animateExpandNotificationsPanel();
break;
case MSG_COLLAPSE_PANELS:
mCallbacks.animateCollapsePanels(0);
break;
case MSG_EXPAND_SETTINGS:
mCallbacks.animateExpandSettingsPanel();
break;
case MSG_SET_SYSTEMUI_VISIBILITY:
mCallbacks.setSystemUiVisibility(msg.arg1, msg.arg2);
break;
case MSG_TOP_APP_WINDOW_CHANGED:
mCallbacks.topAppWindowChanged(msg.arg1 != 0);
break;
case MSG_SHOW_IME_BUTTON:
mCallbacks.setImeWindowStatus((IBinder) msg.obj, msg.arg1, msg.arg2,
msg.getData().getBoolean(SHOW_IME_SWITCHER_KEY, false));
break;
case MSG_SHOW_RECENT_APPS:
mCallbacks.showRecentApps(msg.arg1 != 0);
break;
case MSG_HIDE_RECENT_APPS:
mCallbacks.hideRecentApps(msg.arg1 != 0, msg.arg2 != 0);
break;
case MSG_TOGGLE_RECENT_APPS:
mCallbacks.toggleRecentApps();
break;
case MSG_PRELOAD_RECENT_APPS:
mCallbacks.preloadRecentApps();
break;
case MSG_CANCEL_PRELOAD_RECENT_APPS:
mCallbacks.cancelPreloadRecentApps();
break;
case MSG_SET_WINDOW_STATE:
mCallbacks.setWindowState(msg.arg1, msg.arg2);
break;
case MSG_BUZZ_BEEP_BLINKED:
mCallbacks.buzzBeepBlinked();
break;
case MSG_NOTIFICATION_LIGHT_OFF:
mCallbacks.notificationLightOff();
break;
case MSG_NOTIFICATION_LIGHT_PULSE:
mCallbacks.notificationLightPulse((Integer) msg.obj, msg.arg1, msg.arg2);
break;
case MSG_SHOW_SCREEN_PIN_REQUEST:
mCallbacks.showScreenPinningRequest();
break;
case MSG_APP_TRANSITION_PENDING:
mCallbacks.appTransitionPending();
break;
case MSG_APP_TRANSITION_CANCELLED:
mCallbacks.appTransitionCancelled();
break;
case MSG_APP_TRANSITION_STARTING:
Pair<Long, Long> data = (Pair<Long, Long>) msg.obj;
mCallbacks.appTransitionStarting(data.first, data.second);
break;
case MSG_ASSIST_DISCLOSURE:
mCallbacks.showAssistDisclosure();
break;
case MSG_START_ASSIST:
mCallbacks.startAssist((Bundle) msg.obj);
break;
}
}
}
}
| syslover33/ctank | java/android-sdk-linux_r24.4.1_src/sources/android-23/com/android/systemui/statusbar/CommandQueue.java | Java | gpl-3.0 | 16,619 |
/*
* Copyright (c) 2010-2015, Isode Limited, London, England.
* All rights reserved.
*/
package com.isode.stroke.roster;
import com.isode.stroke.elements.ErrorPayload;
import com.isode.stroke.elements.IQ;
import com.isode.stroke.elements.Payload;
import com.isode.stroke.elements.RosterPayload;
import com.isode.stroke.jid.JID;
import com.isode.stroke.queries.IQRouter;
import com.isode.stroke.queries.Request;
import com.isode.stroke.signals.Signal1;
public class SetRosterRequest extends Request {
static SetRosterRequest create(RosterPayload payload, IQRouter router) {
return new SetRosterRequest(new JID(), payload, router);
}
static SetRosterRequest create(RosterPayload payload, final JID to, IQRouter router) {
return new SetRosterRequest(to, payload, router);
}
private SetRosterRequest(final JID to, RosterPayload payload, IQRouter router) {
super(IQ.Type.Set, to, payload, router);
}
public void handleResponse(Payload payload, ErrorPayload error) {
onResponse.emit(error);
}
final Signal1<ErrorPayload> onResponse = new Signal1<ErrorPayload>();
}
| swift/stroke | src/com/isode/stroke/roster/SetRosterRequest.java | Java | gpl-3.0 | 1,087 |
package com.github.bordertech.wcomponents.test.selenium.element;
import com.github.bordertech.wcomponents.util.SystemException;
import java.text.MessageFormat;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
/**
* Selenium WebElement class representing a WTable.
*
* @author Joshua Barclay
* @since 1.2.0
*/
public class SeleniumWTableWebElement extends SeleniumWComponentWebElement {
/**
* The table itself is a 'table' entity, but the element containing all the controls is the wrapper div.
*/
public static final String TABLE_TAG_NAME = "div";
/**
* The incorrect tag name that might be selected - the name of the child table element.
*/
public static final String TABLE_CHILD_TAG_NAME = "table";
/**
* The tag name for the header.
*/
public static final String TABLE_HEADER_TAG_NAME = "thead";
/**
* The div class representing the table.
*/
public static final String TABLE_DIV_CLASS = "wc-table";
/**
* The attribute on the table tag that records how many rows per page.
*/
public static final String ROWS_PER_PAGE_TABLE_ATTRIBUTE = "data-wc-rpp";
/**
* The CSS Selector for the table caption.
*/
public static final String SELECTOR_TABLE_CAPTION = "table caption";
/**
* The CSS Selector to find the first row index of page.
*/
public static final String SELECTOR_FIRST_ROW_INDEX_OF_PAGE = "span.wc_table_pag_rowstart";
/**
* The CSS Selector to find the last row index of page.
*/
public static final String SELECTOR_LAST_ROW_INDEX_OF_PAGE = "span.wc_table_pag_rowend";
/**
* The CSS Selector to find the last result of page.
*/
public static final String SELECTOR_TOTAL_ROWS = "span.wc_table_pag_total";
/**
* The CSS Selector to find the first page button.
*/
public static final String SELECTOR_FIRST_PAGE_BUTTON = "span.wc_table_pag_btns button:nth-of-type(1)";
/**
* The CSS Selector to find the previous page button.
*/
public static final String SELECTOR_PREVIOUS_PAGE_BUTTON = "span.wc_table_pag_btns button:nth-of-type(2)";
/**
* The CSS Selector to find the next page button.
*/
public static final String SELECTOR_NEXT_PAGE_BUTTON = "span.wc_table_pag_btns button:nth-of-type(3)";
/**
* The CSS Selector to find the last page button.
*/
public static final String SELECTOR_LAST_PAGE_BUTTON = "span.wc_table_pag_btns button:nth-of-type(4)";
/**
* The CSS Selector for the page select.
*/
public static final String SELECTOR_PAGE_SELECT = "select.wc_table_pag_select";
/**
* The CSS Selector for the rows per page select.
*/
public static final String SELECTOR_ROWS_PER_PAGE_SELECT = "select.wc_table_pag_rpp";
/**
* The CSS Selector to find a particular column header.
*/
public static final String SELECTOR_COLUMN_HEADER = "thead tr th[data-wc-columnidx=''{0}'']";
/**
* The CSS Selector to find a particular column header's text.
*/
public static final String SELECTOR_COLUMN_HEADER_TEXT = SELECTOR_COLUMN_HEADER + " div.wc-labelbody";
/**
* The CSS Selector to find the cell content.
*/
public static final String SELECTOR_CELL_CONTENT = "tbody tr[data-wc-rowindex=''{0}''] td:nth-of-type({1})";
/**
* Default constructor for this element.
*
* @param element the WebElement
* @param driver the driver.
*/
public SeleniumWTableWebElement(final WebElement element, final WebDriver driver) {
super(element, driver);
final String elementTag = element.getTagName();
final String elementClass = element.getAttribute("class");
if (!elementTag.equals(TABLE_TAG_NAME)) {
//Tag name is incorrect - error scenario
if (elementTag.equals(TABLE_CHILD_TAG_NAME)) {
throw new SystemException("Incorrect element selected for SeleniumWTableWebElement."
+ "Expected the wrapper div element containing the table and controls, but instead found the table element.");
} else {
throw new SystemException("Incorrect element selected for SeleniumWTableWebElement. Expected div but found: " + elementTag);
}
}
if (!elementClass.contains(TABLE_DIV_CLASS)) {
throw new SystemException("Incorrect element selected for SeleniumWTableWebElement. Expected div containing class " + TABLE_DIV_CLASS + " but found div with class " + elementClass);
}
}
/**
* @return the index of the first row displayed on the current page.
*/
public int getFirstRowIndexOfPage() {
SeleniumWComponentWebElement wrapper = findElement(By.cssSelector(SELECTOR_FIRST_ROW_INDEX_OF_PAGE));
return Integer.parseInt(wrapper.getText());
}
/**
* @return the index of the last row displayed on the current page.
*/
public int getLastRowIndexOfPage() {
SeleniumWComponentWebElement wrapper = findElement(By.cssSelector(SELECTOR_LAST_ROW_INDEX_OF_PAGE));
return Integer.parseInt(wrapper.getText());
}
/**
* @return the total number of rows in the table..
*/
public int getTotalRows() {
SeleniumWComponentWebElement wrapper = findElement(By.cssSelector(SELECTOR_TOTAL_ROWS));
return Integer.parseInt(wrapper.getText());
}
/**
* @return the actual table element within the elements that make up an advanced WComponent table.
*/
public SeleniumWComponentWebElement getTable() {
return findElement(By.tagName(TABLE_CHILD_TAG_NAME));
}
/**
* @return the first page button for pagination.
*/
public SeleniumWComponentWebElement getFirstPageButton() {
return findElement(By.cssSelector(SELECTOR_FIRST_PAGE_BUTTON));
}
/**
* @return the previous page button for pagination.
*/
public SeleniumWComponentWebElement getPreviousPageButton() {
return findElement(By.cssSelector(SELECTOR_PREVIOUS_PAGE_BUTTON));
}
/**
* @return the next page button for pagination.
*/
public SeleniumWComponentWebElement getNextPageButton() {
return findElement(By.cssSelector(SELECTOR_NEXT_PAGE_BUTTON));
}
/**
* @return the last page button for pagination.
*/
public SeleniumWComponentWebElement getLastPageButton() {
return findElement(By.cssSelector(SELECTOR_LAST_PAGE_BUTTON));
}
/**
* @return the page select.
*/
public SeleniumWSelectWebElement getPageSelect() {
return findSeleniumWSelectWebElement(By.cssSelector(SELECTOR_PAGE_SELECT));
}
/**
* @return the page select.
*/
public SeleniumWSelectWebElement getRowsPerPageSelect() {
return findSeleniumWSelectWebElement(By.cssSelector(SELECTOR_ROWS_PER_PAGE_SELECT));
}
/**
* @return the current page of the paginated data.
*/
public int getCurrentPage() {
return Integer.parseInt(getPageSelect().getSelectedOption().getText());
}
/**
* @return the total number of pages.
*/
public int getTotalPages() {
return Integer.parseInt(getPageSelect().getLastOption().getText());
}
/**
* @return the number of rows per page.
*/
public int getRowsPerPage() {
return Integer.parseInt(getTable().getAttribute(ROWS_PER_PAGE_TABLE_ATTRIBUTE));
}
/**
* @return the table caption.
*/
public String getTableCaption() {
return findElement(By.cssSelector(SELECTOR_TABLE_CAPTION)).getText();
}
/**
* @return the table header.
*/
public SeleniumWComponentWebElement getTableHeader() {
return findElement(By.tagName(TABLE_HEADER_TAG_NAME));
}
/**
* Get the TH element for the given column index.
*
* @param columnIndex the column index.
* @return the TH element.
*/
public SeleniumWComponentWebElement getHeaderForColumn(final int columnIndex) {
String selector = MessageFormat.format(SELECTOR_COLUMN_HEADER, columnIndex);
return findElement(By.cssSelector(selector));
}
/**
* Get the header text for the given column index.
*
* @param columnIndex the column index.
* @return the header text.
*/
public String getHeaderTextForColumn(final int columnIndex) {
String selector = MessageFormat.format(SELECTOR_COLUMN_HEADER_TEXT, columnIndex);
return findElement(By.cssSelector(selector)).getText();
}
/**
* Get the content of the cell.
*
* @param rowIndex the row index, 0-based.
* @param columnIndex the column index, 0-based.
* @return the cell's content.
*/
public SeleniumWComponentWebElement getCellContent(final int rowIndex, final int columnIndex) {
// The CSS selector for row is 0 based, but column is 1 based.
// Manually adjust the index to hide this inconsistency.
int adjustedColIndex = columnIndex + 1;
String selector = MessageFormat.format(SELECTOR_CELL_CONTENT, rowIndex, adjustedColIndex);
return findElement(By.cssSelector(selector));
}
/**
* Get the text of the cell.
*
* @param rowIndex the row index, 0-based.
* @param columnIndex the column index, 0-based.
* @return the text of the cell.
*/
public String getCellText(final int rowIndex, final int columnIndex) {
return getCellContent(rowIndex, columnIndex).getText();
}
}
| Joshua-Barclay/wcomponents | wcomponents-test-lib/src/main/java/com/github/bordertech/wcomponents/test/selenium/element/SeleniumWTableWebElement.java | Java | gpl-3.0 | 8,793 |
package com.basicer.parchment.tcl;
import com.basicer.parchment.Context;
import com.basicer.parchment.EvaluationResult;
import com.basicer.parchment.TCLCommand;
import com.basicer.parchment.TCLEngine;
import com.basicer.parchment.parameters.Parameter;
public class PutS extends TCLCommand {
@Override
public String[] getArguments() { return new String[] { "string" }; }
@Override
public EvaluationResult extendedExecute(Context ctx, TCLEngine e) {
Parameter s = ctx.get("string");
if ( s == null ) {
ctx.sendDebugMessage("null");
return EvaluationResult.OK;
}
ctx.sendDebugMessage(s.asString());
return EvaluationResult.makeOkay(s);
}
}
| basicer/parchment | src/main/java/com/basicer/parchment/tcl/PutS.java | Java | gpl-3.0 | 695 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* 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 3 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, see <http://www.gnu.org/licenses/>
*/
package com.github.mdsimmo.pixeldungeon.sprites;
import com.github.mdsimmo.noosa.TextureFilm;
import com.github.mdsimmo.pixeldungeon.Assets;
public class ThiefSprite extends MobSprite {
public ThiefSprite() {
super();
texture( Assets.THIEF );
TextureFilm film = new TextureFilm( texture, 12, 13 );
idle = new Animation( 1, true );
idle.frames( film, 0, 0, 0, 1, 0, 0, 0, 0, 1 );
run = new Animation( 15, true );
run.frames( film, 0, 0, 2, 3, 3, 4 );
die = new Animation( 10, false );
die.frames( film, 5, 6, 7, 8, 9 );
attack = new Animation( 12, false );
attack.frames( film, 10, 11, 12, 0 );
idle();
}
}
| mdsimmo/cake-dungeon | java/com/github/mdsimmo/pixeldungeon/sprites/ThiefSprite.java | Java | gpl-3.0 | 1,429 |
package com.sagereducation.robotescape.util;
public class MultipleVirtualViewportBuilder {
private final float minWidth;
private final float minHeight;
private final float maxWidth;
private final float maxHeight;
public MultipleVirtualViewportBuilder(float minWidth, float minHeight, float maxWidth, float maxHeight) {
this.minWidth = minWidth;
this.minHeight = minHeight;
this.maxWidth = maxWidth;
this.maxHeight = maxHeight;
}
public VirtualViewport getVirtualViewport(float width, float height) {
if (width >= minWidth && width <= maxWidth && height >= minHeight && height <= maxHeight)
return new VirtualViewport(width, height, true);
float aspect = width / height;
float scaleForMinSize = minWidth / width;
float scaleForMaxSize = maxWidth / width;
float virtualViewportWidth = width * scaleForMaxSize;
float virtualViewportHeight = virtualViewportWidth / aspect;
if (insideBounds(virtualViewportWidth, virtualViewportHeight))
return new VirtualViewport(virtualViewportWidth, virtualViewportHeight, false);
virtualViewportWidth = width * scaleForMinSize;
virtualViewportHeight = virtualViewportWidth / aspect;
if (insideBounds(virtualViewportWidth, virtualViewportHeight))
return new VirtualViewport(virtualViewportWidth, virtualViewportHeight, false);
return new VirtualViewport(minWidth, minHeight, true);
}
private boolean insideBounds(float width, float height) {
if (width < minWidth || width > maxWidth)
return false;
if (height < minHeight || height > maxHeight)
return false;
return true;
}
}
| cagewyt/RobotEscape | core/src/com/sagereducation/robotescape/util/MultipleVirtualViewportBuilder.java | Java | gpl-3.0 | 1,870 |
package es.unileon.ulebank.history;
import es.unileon.ulebank.handler.Handler;
/**
*
* @author roobre
*/
public class TransactionHandler implements Handler {
private final long id;
private final String timestamp;
/**
*
* @param id
* @param timestamp
*/
public TransactionHandler(long id, String timestamp) {
this.id = id;
this.timestamp = timestamp;
}
/**
*
* @return
*/
@Override
public String toString() {
return timestamp + "." + Long.toString(id);
}
@Override
public int compareTo(Handler another) {
return this.toString().compareTo(another.toString());
}
} | jalvarofa/ModifyPIN-Spring | bankapp/src/main/java/es/unileon/ulebank/history/TransactionHandler.java | Java | gpl-3.0 | 683 |
/*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Shattered Pixel Dungeon
* Copyright (C) 2014-2016 Evan Debenham
*
* Lovecraft Pixel Dungeon
* Copyright (C) 2016-2017 Leon Horn
*
* Plugin Pixel Dungeon
* Copyright (C) 2017 Leon Horn
*
* 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 3 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 eben the implied warranty of
* GNU General Public License for more details.
*
* You should have have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses>
*/
package com.pluginpixel.pluginpixeldungeon.levels.traps;
import com.pluginpixel.pluginpixeldungeon.Assets;
import com.pluginpixel.pluginpixeldungeon.actors.blobs.Blob;
import com.pluginpixel.pluginpixeldungeon.actors.blobs.Fire;
import com.pluginpixel.pluginpixeldungeon.effects.CellEmitter;
import com.pluginpixel.pluginpixeldungeon.effects.particles.FlameParticle;
import com.pluginpixel.pluginpixeldungeon.levels.Level;
import com.pluginpixel.pluginpixeldungeon.scenes.GameScene;
import com.pluginpixel.pluginpixeldungeon.utils.BArray;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.PathFinder;
public class BlazingTrap extends Trap {
{
color = ORANGE;
shape = STARS;
}
@Override
public void activate() {
PathFinder.buildDistanceMap( pos, BArray.not( Level.solid, null ), 2 );
for (int i = 0; i < PathFinder.distance.length; i++) {
if (PathFinder.distance[i] < Integer.MAX_VALUE) {
if (Level.pit[i] || Level.water[i])
GameScene.add(Blob.seed(i, 1, Fire.class));
else
GameScene.add(Blob.seed(i, 5, Fire.class));
CellEmitter.get(i).burst(FlameParticle.FACTORY, 5);
}
}
Sample.INSTANCE.play(Assets.SND_BURNING);
}
}
| TypedScroll/PluginPixelDungeon | core/src/main/java/com/pluginpixel/pluginpixeldungeon/levels/traps/BlazingTrap.java | Java | gpl-3.0 | 2,030 |
/*
* Copyright (C) 2010-2015 JPEXS
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.jpexs.browsers.cache.chrome;
import com.jpexs.browsers.cache.CacheEntry;
import com.jpexs.browsers.cache.CacheImplementation;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author JPEXS
*/
public class ChromeCache implements CacheImplementation {
private static ChromeCache instance;
private File tempDir;
private List<File> dataFiles;
private File indexFile;
private ChromeCache() {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
free();
}
});
}
public static ChromeCache getInstance() {
if (instance == null) {
synchronized (ChromeCache.class) {
if (instance == null) {
instance = new ChromeCache();
}
}
}
return instance;
}
private boolean loaded = false;
private Index index;
@Override
public List<CacheEntry> getEntries() {
if (!loaded) {
refresh();
}
if (!loaded) {
return null;
}
List<CacheEntry> ret = new ArrayList<>();
try {
List<EntryStore> entries = index.getEntries();
for (EntryStore en : entries) {
if (en.state == EntryStore.ENTRY_NORMAL) {
String key = en.getKey();
if (key != null && !key.trim().isEmpty()) {
ret.add(en);
}
}
}
} catch (IOException ex) {
Logger.getLogger(ChromeCache.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
return ret;
}
@Override
public void refresh() {
free();
File cacheDir = null;
try {
cacheDir = getCacheDirectory();
} catch (IOException ex) {
Logger.getLogger(ChromeCache.class.getName()).log(Level.SEVERE, null, ex);
}
if (cacheDir == null) {
return;
}
File systemTempDir = new File(System.getProperty("java.io.tmpdir"));
File originalIndexFile = new File(cacheDir + File.separator + "index");
tempDir = new File(systemTempDir, "cacheView" + System.identityHashCode(this));
tempDir.mkdir();
indexFile = new File(tempDir, "index");
try {
Files.copy(originalIndexFile.toPath(), indexFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
Logger.getLogger(ChromeCache.class.getName()).log(Level.SEVERE, null, ex);
return;
}
File originalDataFile;
dataFiles = new ArrayList<>();
for (int i = 0; (originalDataFile = new File(cacheDir, "data_" + i)).exists(); i++) {
File dataFile = new File(tempDir, "data_" + i);
dataFiles.add(dataFile);
try {
Files.copy(originalDataFile.toPath(), dataFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
Logger.getLogger(ChromeCache.class.getName()).log(Level.SEVERE, null, ex);
return;
}
}
try {
index = new Index(indexFile, cacheDir);
} catch (IOException ex) {
Logger.getLogger(ChromeCache.class.getName()).log(Level.SEVERE, null, ex);
}
loaded = true;
}
private enum OSId {
WINDOWS, OSX, UNIX
}
private static OSId getOSId() {
PrivilegedAction<String> doGetOSName = new PrivilegedAction<String>() {
@Override
public String run() {
return System.getProperty("os.name");
}
};
OSId id = OSId.UNIX;
String osName = AccessController.doPrivileged(doGetOSName);
if (osName != null) {
if (osName.toLowerCase().startsWith("mac os x")) {
id = OSId.OSX;
} else if (osName.contains("Windows")) {
id = OSId.WINDOWS;
}
}
return id;
}
public static File getCacheDirectory() throws IOException {
String userHome = null;
File ret = null;
try {
userHome = System.getProperty("user.home");
} catch (SecurityException ignore) {
}
if (userHome != null) {
OSId osId = getOSId();
if (osId == OSId.WINDOWS) {
ret = new File(userHome + "\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Cache\\");
if (!ret.exists()) {
ret = new File(userHome + "\\Local Settings\\Application Data\\Google\\Chrome\\User Data\\Default\\Cache");
}
} else if (osId == OSId.OSX) {
ret = new File(userHome + "/Library/Caches/Google/Chrome/Default/Cache");
} else {
ret = new File(userHome + "/.config/google-chrome/Default/Application Cache/Cache/");
if (!ret.exists()) {
ret = new File(userHome + "/.cache/chromium/Default/Cache");
}
}
}
if ((ret != null) && !ret.exists()) {
return null;
}
return ret;
}
private void free() {
if (loaded) {
index.free();
indexFile.delete();
for (File d : dataFiles) {
d.delete();
}
tempDir.delete();
}
}
}
| Laforeta/jpexs-decompiler | src/com/jpexs/browsers/cache/chrome/ChromeCache.java | Java | gpl-3.0 | 6,507 |
/*
* Copyright (C) 2019 Sun.Hao(https://www.crazy-coder.cn/)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package lodsve.mybatis.repository.bean;
/**
* 最新更新时间字段.
*
* @author <a href="mailto:[email protected]">sunhao([email protected])</a>
*/
public class LastModifiedDateColumn extends ColumnBean {
public LastModifiedDateColumn(ColumnBean column) {
super(column.getTable(), column.getProperty(), column.getColumn(), column.getJavaType());
}
}
| lodsve/lodsve-framework | lodsve-mybatis/src/main/java/lodsve/mybatis/repository/bean/LastModifiedDateColumn.java | Java | gpl-3.0 | 1,099 |
package com.novar.ui;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SpringLayout;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import java.awt.Rectangle;
import java.awt.Component;
import javax.swing.JButton;
import com.novar.util.ConnectionUtil;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
public class ProfilePanel extends JPanel
{
/**
* Create the panel.
*/
public ProfilePanel(ConnectedWindow frame)
{
setBounds(new Rectangle(0, 0, 980, 800));
SpringLayout springLayout = new SpringLayout();
setLayout(springLayout);
JLabel lblProfile = new JLabel("Profile");
lblProfile.setFont(new Font("Lucida Grande", Font.BOLD, 30));
springLayout.putConstraint(SpringLayout.NORTH, lblProfile, 20, SpringLayout.NORTH, this);
springLayout.putConstraint(SpringLayout.HORIZONTAL_CENTER, lblProfile, 0, SpringLayout.HORIZONTAL_CENTER, this);
lblProfile.setHorizontalAlignment(SwingConstants.CENTER);
add(lblProfile);
JLabel lblPseudo = new JLabel("Pseudo :");
springLayout.putConstraint(SpringLayout.NORTH, lblPseudo, 75, SpringLayout.NORTH, lblProfile);
springLayout.putConstraint(SpringLayout.EAST, lblPseudo, 0, SpringLayout.WEST, lblProfile);
add(lblPseudo);
JLabel lblFirstName = new JLabel("First name :");
springLayout.putConstraint(SpringLayout.NORTH, lblFirstName, 20, SpringLayout.SOUTH, lblPseudo);
springLayout.putConstraint(SpringLayout.EAST, lblFirstName, 0, SpringLayout.EAST, lblPseudo);
add(lblFirstName);
JLabel lblLastName = new JLabel("Last name :");
springLayout.putConstraint(SpringLayout.NORTH, lblLastName, 20, SpringLayout.SOUTH, lblFirstName);
springLayout.putConstraint(SpringLayout.EAST, lblLastName, 0, SpringLayout.EAST, lblPseudo);
add(lblLastName);
JLabel lblPhone = new JLabel("Phone :");
springLayout.putConstraint(SpringLayout.NORTH, lblPhone, 20, SpringLayout.SOUTH, lblLastName);
springLayout.putConstraint(SpringLayout.EAST, lblPhone, 0, SpringLayout.EAST, lblPseudo);
add(lblPhone);
JLabel lblEmail = new JLabel("Email :");
springLayout.putConstraint(SpringLayout.NORTH, lblEmail, 20, SpringLayout.SOUTH, lblPhone);
springLayout.putConstraint(SpringLayout.EAST, lblEmail, 0, SpringLayout.EAST, lblPseudo);
add(lblEmail);
JLabel lblStreet = new JLabel("Street :");
springLayout.putConstraint(SpringLayout.NORTH, lblStreet, 50, SpringLayout.SOUTH, lblEmail);
springLayout.putConstraint(SpringLayout.EAST, lblStreet, 0, SpringLayout.EAST, lblPseudo);
add(lblStreet);
JLabel lblTown = new JLabel("Town :");
springLayout.putConstraint(SpringLayout.NORTH, lblTown, 20, SpringLayout.SOUTH, lblStreet);
springLayout.putConstraint(SpringLayout.EAST, lblTown, 0, SpringLayout.EAST, lblPseudo);
add(lblTown);
JLabel lblZipCode = new JLabel("Zip code :");
springLayout.putConstraint(SpringLayout.NORTH, lblZipCode, 20, SpringLayout.SOUTH, lblTown);
springLayout.putConstraint(SpringLayout.EAST, lblZipCode, 0, SpringLayout.EAST, lblPseudo);
add(lblZipCode);
JLabel lblCountry = new JLabel("Country :");
springLayout.putConstraint(SpringLayout.NORTH, lblCountry, 20, SpringLayout.SOUTH, lblZipCode);
springLayout.putConstraint(SpringLayout.EAST, lblCountry, 0, SpringLayout.EAST, lblPseudo);
add(lblCountry);
JLabel lblPseudoDynamic = new JLabel("");
lblPseudoDynamic.setText(frame.getFacade().getUser().getPseudo());
springLayout.putConstraint(SpringLayout.NORTH, lblPseudoDynamic, 0, SpringLayout.NORTH, lblPseudo);
springLayout.putConstraint(SpringLayout.WEST, lblPseudoDynamic, 0, SpringLayout.EAST, lblProfile);
add(lblPseudoDynamic);
JLabel lblFirstNameDynamic = new JLabel("");
lblFirstNameDynamic.setText(frame.getFacade().getUser().getFirstName());
springLayout.putConstraint(SpringLayout.NORTH, lblFirstNameDynamic, 0, SpringLayout.NORTH, lblFirstName);
springLayout.putConstraint(SpringLayout.WEST, lblFirstNameDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblFirstNameDynamic);
JLabel lblLastNameDynamic = new JLabel("");
lblLastNameDynamic.setText(frame.getFacade().getUser().getLastName());
springLayout.putConstraint(SpringLayout.NORTH, lblLastNameDynamic, 0, SpringLayout.NORTH, lblLastName);
springLayout.putConstraint(SpringLayout.WEST, lblLastNameDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblLastNameDynamic);
JLabel lblPhoneDynamic = new JLabel("");
lblPhoneDynamic.setText(frame.getFacade().getUser().getPhone());
springLayout.putConstraint(SpringLayout.NORTH, lblPhoneDynamic, 0, SpringLayout.NORTH, lblPhone);
springLayout.putConstraint(SpringLayout.WEST, lblPhoneDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblPhoneDynamic);
JLabel lblEmailDynamic = new JLabel("");
lblEmailDynamic.setText(frame.getFacade().getUser().getEmail());
springLayout.putConstraint(SpringLayout.NORTH, lblEmailDynamic, 0, SpringLayout.NORTH, lblEmail);
springLayout.putConstraint(SpringLayout.WEST, lblEmailDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblEmailDynamic);
JLabel lblStreetDynamic = new JLabel("");
lblStreetDynamic.setText(frame.getFacade().getUser().getStreet());
springLayout.putConstraint(SpringLayout.NORTH, lblStreetDynamic, 0, SpringLayout.NORTH, lblStreet);
springLayout.putConstraint(SpringLayout.WEST, lblStreetDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblStreetDynamic);
JLabel lblTownDynamic = new JLabel("");
lblTownDynamic.setText(frame.getFacade().getUser().getTown());
springLayout.putConstraint(SpringLayout.NORTH, lblTownDynamic, 0, SpringLayout.NORTH, lblTown);
springLayout.putConstraint(SpringLayout.WEST, lblTownDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblTownDynamic);
JLabel lblZipCodeDynamic = new JLabel("");
lblZipCodeDynamic.setText(frame.getFacade().getUser().getZipCode());
springLayout.putConstraint(SpringLayout.NORTH, lblZipCodeDynamic, 0, SpringLayout.NORTH, lblZipCode);
springLayout.putConstraint(SpringLayout.WEST, lblZipCodeDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblZipCodeDynamic);
JLabel lblCountryDynamic = new JLabel("");
lblCountryDynamic.setText(frame.getFacade().getUser().getCountry());
springLayout.putConstraint(SpringLayout.NORTH, lblCountryDynamic, 0, SpringLayout.NORTH, lblCountry);
springLayout.putConstraint(SpringLayout.WEST, lblCountryDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblCountryDynamic);
if (frame.getFacade().getUser().isSpeaker())
{
JLabel lblShortDescription = new JLabel("Short description :");
springLayout.putConstraint(SpringLayout.NORTH, lblShortDescription, 50, SpringLayout.SOUTH, lblCountry);
springLayout.putConstraint(SpringLayout.EAST, lblShortDescription, 0, SpringLayout.EAST, lblPseudo);
add(lblShortDescription);
JLabel lblDetailedDescription = new JLabel("Detailed description :");
springLayout.putConstraint(SpringLayout.NORTH, lblDetailedDescription, 20, SpringLayout.SOUTH, lblShortDescription);
springLayout.putConstraint(SpringLayout.EAST, lblDetailedDescription, 0, SpringLayout.EAST, lblPseudo);
add(lblDetailedDescription);
JLabel lblShortDescriptionDynamic = new JLabel("");
lblShortDescriptionDynamic.setText(frame.getFacade().getUser().getSpeaker().getShortDescription());
springLayout.putConstraint(SpringLayout.NORTH, lblShortDescriptionDynamic, 0, SpringLayout.NORTH, lblShortDescription);
springLayout.putConstraint(SpringLayout.WEST, lblShortDescriptionDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblShortDescriptionDynamic);
JLabel lblDetailedDescriptionDynamic = new JLabel(frame.getFacade().getUser().getSpeaker().getDetailedDescription());
springLayout.putConstraint(SpringLayout.NORTH, lblDetailedDescriptionDynamic, 0, SpringLayout.NORTH, lblDetailedDescription);
springLayout.putConstraint(SpringLayout.WEST, lblDetailedDescriptionDynamic, 0, SpringLayout.WEST, lblPseudoDynamic);
add(lblDetailedDescriptionDynamic);
}
JButton btnUpdatePassword = new JButton("Update password");
btnUpdatePassword.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.changePanel(new UpdatePasswordPanel(frame));
}
});
springLayout.putConstraint(SpringLayout.SOUTH, btnUpdatePassword, -20, SpringLayout.SOUTH, this);
springLayout.putConstraint(SpringLayout.HORIZONTAL_CENTER, btnUpdatePassword, 0, SpringLayout.HORIZONTAL_CENTER, this);
add(btnUpdatePassword);
JButton btnUpdateProfile = new JButton("Update profile");
springLayout.putConstraint(SpringLayout.NORTH, btnUpdateProfile, 0, SpringLayout.NORTH, btnUpdatePassword);
springLayout.putConstraint(SpringLayout.EAST, btnUpdateProfile, -20, SpringLayout.WEST, btnUpdatePassword);
btnUpdateProfile.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
frame.changePanel(new UpdateProfilePanel(frame));
}
});
add(btnUpdateProfile);
JButton btnDelete = new JButton("Delete");
springLayout.putConstraint(SpringLayout.NORTH, btnDelete, 0, SpringLayout.NORTH, btnUpdatePassword);
springLayout.putConstraint(SpringLayout.WEST, btnDelete, 20, SpringLayout.EAST, btnUpdatePassword);
btnDelete.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int returnValue = JOptionPane.showConfirmDialog(frame, "Are you sure to delete your account ?", "Detete", JOptionPane.YES_NO_OPTION);
if (returnValue == JOptionPane.YES_OPTION)
{
try
{
frame.getFacade().deleteTheUser();
ConnectionUtil.stop();
LoginWindow loginWindow = new LoginWindow();
loginWindow.setVisible(true);
closeWindow(frame);
}
catch (SQLException e1)
{
e1.printStackTrace();
}
}
}
});
add(btnDelete);
}
private void closeWindow(ConnectedWindow frame)
{
frame.dispose();
}
}
| Polytech-NOVAR/GoFit | src/com/novar/ui/ProfilePanel.java | Java | gpl-3.0 | 10,057 |
package it.cnr.ilc.ga.utils;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class CustomCharacterEncodingFilter implements Filter {
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
}
| CoPhi/RGDA | src/it/cnr/ilc/ga/utils/CustomCharacterEncodingFilter.java | Java | gpl-3.0 | 844 |
/**
* This file is part of ankus.
*
* ankus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ankus 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 ankus. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ankus.web.job;
import org.ankus.model.rest.Engine;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public interface JobService {
/**
* Job을 등록한다.
*
* @param engineId Engine ID
* @param jobName Job Name
* @param workflowId Workflow ID
* @param cronExpression Cron Expression
* @param hashMap Job Variables
* @return Job ID
*/
String regist(long engineId, String jobName, long workflowId, String cronExpression, HashMap hashMap);
/**
* 지정한 워크플로우 엔진에 등록되어 있는 모든 작업을 반환한다.
*
* @param engine Workflow Engine
* @return 작업 목록
*/
List<Map> getJobs(Engine engine);
/**
* 현재 시간을 반환한다.
*
* @param engine Workflow Engine
* @return 현재 시간
*/
long getCurrentDate(Engine engine);
}
| onycom-ankus/ankus_analyzer_G | trunk_web/ankus-web-services/src/main/java/org/ankus/web/job/JobService.java | Java | gpl-3.0 | 1,613 |
/*
* $Id: Widget.java,v 1.2.2.1 2007/01/12 19:32:59 idegaweb Exp $
* Created on 14.10.2004
*
* Copyright (C) 2004 Idega Software hf. All Rights Reserved.
*
* This software is the proprietary information of Idega hf.
* Use is subject to license terms.
*/
package com.idega.idegaweb.widget;
import java.util.Locale;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWResourceBundle;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.PresentationObject;
/**
* The base object that all widgets should extend. Has the standard methods most of them need.
*
* Last modified: 14.10.2004 10:24:30 by laddi
*
* @author <a href="mailto:[email protected]">laddi</a>
* @version $Revision: 1.2.2.1 $
*/
public abstract class Widget extends Block {
private static final String IW_BUNDLE_IDENTIFIER = "com.idega.idegaweb.widget";
private IWBundle iwb;
private IWResourceBundle iwrb;
private Locale locale;
private String styleClass;
public void main(IWContext iwc) {
this.iwb = getBundle(iwc);
this.iwrb = getResourceBundle(iwc);
this.locale = iwc.getCurrentLocale();
PresentationObject widget = getWidget(iwc);
if (widget != null) {
if (this.styleClass != null) {
widget.setStyleClass(this.styleClass);
}
add(widget);
}
}
protected abstract PresentationObject getWidget(IWContext iwc);
protected IWBundle getBundle() {
return this.iwb;
}
protected IWResourceBundle getResourceBundle() {
return this.iwrb;
}
protected Locale getLocale() {
return this.locale;
}
public String getBundleIdentifier() {
return IW_BUNDLE_IDENTIFIER;
}
public void setStyleClass(String styleClass) {
this.styleClass = styleClass;
}
} | idega/platform2 | src/com/idega/idegaweb/widget/Widget.java | Java | gpl-3.0 | 1,757 |
/*
* Copyright (C) 2017 James Lean.
*
* This file is part of cassette-nibbler.
*
* cassette-nibbler is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* cassette-nibbler 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 cassette-nibbler. If not, see <http://www.gnu.org/licenses/>.
*/
package com.eightbitjim.cassettenibbler.Platforms.Acorn.FileExtraction;
import com.eightbitjim.cassettenibbler.DataSource.AudioInputLibrary.AudioInput;
import com.eightbitjim.cassettenibbler.FileStreamConsumer;
import com.eightbitjim.cassettenibbler.Platforms.Acorn.PulseExtraction.AcornPulseExtractor;
import com.eightbitjim.cassettenibbler.Platforms.General.Demodulation.ZeroCrossingIntervalExtractor;
import com.eightbitjim.cassettenibbler.Platforms.General.Filters.HighPass;
import com.eightbitjim.cassettenibbler.Platforms.General.Filters.LowPass;
import com.eightbitjim.cassettenibbler.TapeExtractionOptions;
import com.eightbitjim.cassettenibbler.TapeFile;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import static org.junit.Assert.assertTrue;
public class BBCFileTest implements FileStreamConsumer {
private BBCFileExtractor fileExtractor1200;
private BBCFileExtractor fileExtractor300;
private AcornPulseExtractor pulseExtractor;
private ZeroCrossingIntervalExtractor intervalExtractor;
private List<BBCTapeFile> results;
private LowPass lowPass;
private HighPass highPass;
private String channelName = "channel";
private static final String PATH_TO_TEST_FILES = "src/test/testFiles/";
private static final String ONE_FILE_FILENAME = PATH_TO_TEST_FILES + "bbcOneFile1200.wav";
private static final String TWO_FILE_FILENAME = PATH_TO_TEST_FILES + "bbcTwoFiles1200.wav";
private static final String ONE_FILE_300_BAUD_FILENAME = PATH_TO_TEST_FILES + "bbcOneFile300.wav";
private static final String VARIABLES_FILENAME = PATH_TO_TEST_FILES + "bbcVariables1200.wav";
private static final String MEMORY_FILENAME = PATH_TO_TEST_FILES + "bbcMemory.wav";
@Before
public void individualSetup() {
TapeExtractionOptions.getInstance().setLogging(TapeExtractionOptions.LoggingMode.NONE, null);
lowPass = new LowPass(4800, channelName);
highPass = new HighPass(200, channelName);
fileExtractor1200 = new BBCFileExtractor(true, channelName);
fileExtractor300 = new BBCFileExtractor(false, channelName);
pulseExtractor = new AcornPulseExtractor();
intervalExtractor = new ZeroCrossingIntervalExtractor();
lowPass.registerSampleStreamConsumer(highPass);
highPass.registerSampleStreamConsumer(intervalExtractor);
intervalExtractor.registerIntervalStreamConsumer(pulseExtractor);
pulseExtractor.registerPulseStreamConsumer(fileExtractor1200);
pulseExtractor.registerPulseStreamConsumer(fileExtractor300);
fileExtractor1200.registerFileStreamConsumer(this);
fileExtractor300.registerFileStreamConsumer(this);
results = new LinkedList<>();
}
@Test
public void testBBC1200baudOneFile() throws Throwable {
parseFile(ONE_FILE_FILENAME, 1);
checkFileResult(0,550, "JUNIT1200.basic", 203395942, 6400);
}
@Test
public void testTwoBBC1200baudFiles() throws Throwable {
parseFile(TWO_FILE_FILENAME, 2);
checkFileResult(0,550, "JUNIT1200.basic", 203395942, 6400);
checkFileResult(1,872, "FILE2.basic", -65476424, 6400);
}
@Test
public void testBBC300baudFile() throws Throwable {
parseFile(ONE_FILE_300_BAUD_FILENAME, 1);
checkFileResult(0,550, "JUNIT300.basic", 203395942, 6400);
}
@Test
public void testBBC1200variablesFile() throws Throwable {
parseFile(VARIABLES_FILENAME, 2);
checkFileResult(0,172, "PROG.basic", 1833671517, 6400);
checkFileResult(1,4040, "DATA.variables", -1409427906, BBCTapeFile.VARIABLES_LOAD_ADDRESS);
checkTextFileHash(1, -1601006811);
}
@Test
public void testBBCMemoryFile() throws Throwable {
parseFile(MEMORY_FILENAME, 1);
checkFileResult(0,512, "BYTES.bytes.6400.6400", 2146807500, 6400);
}
private void parseFile(String filename, int numberOfExpectedResults) throws Throwable {
AudioInput reader = new AudioInput(filename, channelName);
try {
reader.registerSampleStreamConsumer(lowPass);
pushStreamThroughSystem(reader);
assertTrue("Wrong number of files after extracting " + filename + ". Got " + results.size(), results.size() == numberOfExpectedResults);
} finally {
}
}
private void checkFileResult(int fileNumber, int expectedFileLength, String expectedFilename, int expectedContentHash, int expectedLoadAddress) {
assertTrue("File length incorrect: " + results.get(fileNumber).length(), results.get(fileNumber).length() == expectedFileLength);
assertTrue("File name incorrect: " + results.get(fileNumber).getFilename(), results.get(fileNumber).getFilename().equals(expectedFilename));
assertTrue("File content does not match expected hash: " + Arrays.hashCode(results.get(fileNumber).getDataBytesOfType(TapeFile.FormatType.EMULATOR)),
Arrays.hashCode(results.get(fileNumber).getDataBytesOfType(TapeFile.FormatType.EMULATOR)) == expectedContentHash);
assertTrue("Load address incorrect: " + results.get(fileNumber).getLoadAddress(),
results.get(fileNumber).getLoadAddress() == expectedLoadAddress);
}
private void checkTextFileHash(int fileNumber, int expectedStringHash) {
BBCTapeFile file = results.get(fileNumber);
int hash = Arrays.hashCode(file.getDataBytesOfType(TapeFile.FormatType.READABLE));
assertTrue("ASCII data hash incorrect: " + hash, hash == expectedStringHash);
}
private void pushStreamThroughSystem(AudioInput reader) throws Throwable {
reader.processFile();
}
@Override
public void pushFile(TapeFile file, long currentTimeIndex) {
if (file == null)
return;
assertTrue("Returned tape file is not Acorn format", file instanceof BBCTapeFile);
results.add((BBCTapeFile) file);
}
}
| eightbitjim/cassette-nibbler | src/test/java/com/eightbitjim/cassettenibbler/Platforms/Acorn/FileExtraction/BBCFileTest.java | Java | gpl-3.0 | 6,760 |
package com.nemezor.nemgine.misc;
public enum Data {
BYTE(Registry.BYTE_SUFFIX, Registry.ONE_BYTE_IN_BYTES), KILOBYTE(Registry.KILOBYTE_SUFFIX, Registry.ONE_KILOBYTE_IN_BYTES),
MEGABYTE(Registry.MEGABYTE_SUFFIX, Registry.ONE_MEGABYTE_IN_BYTES), GIGABYTE(Registry.GIGABYTE_SUFFIX, Registry.ONE_GIGABYTE_IN_BYTES),
TERABYTE(Registry.TERABYTE_SUFFIX, Registry.ONE_TERABYTE_IN_BYTES), PETABYTE(Registry.PETABYTE_SUFFIX, Registry.ONE_PETABYTE_IN_BYTES),
EXABYTE(Registry.EXABYTE_SUFFIX, Registry.ONE_EXABYTE_IN_BYTES), KIBIBYTE(Registry.KIBIBYTE_SUFFIX, Registry.ONE_KIBIBYTE_IN_BYTES),
MEBIBYTE(Registry.MEBIBYTE_SUFFIX, Registry.ONE_MEBIBYTE_IN_BYTES), GIBIBYTE(Registry.GIBIBYTE_SUFFIX, Registry.ONE_GIBIBYTE_IN_BYTES),
TEBIBYTE(Registry.TEBIBYTE_SUFFIX, Registry.ONE_TEBIBYTE_IN_BYTES), PEBIBYTE(Registry.PEBIBYTE_SUFFIX, Registry.ONE_PEBIBYTE_IN_BYTES),
EXBIBYTE(Registry.EXBIBYTE_SUFFIX, Registry.ONE_EXBIBYTE_IN_BYTES);
public final String suffix;
public final long amount;
Data(String suffix, long amount) {
this.suffix = suffix;
this.amount = amount;
}
}
| NEMESIS13cz/Nemgine | com/nemezor/nemgine/misc/Data.java | Java | gpl-3.0 | 1,080 |
package l2s.gameserver.network.l2.s2c;
import l2s.gameserver.model.Creature;
import l2s.gameserver.model.GameObject;
public class AttackPacket extends L2GameServerPacket
{
/*
* TODO: Aweking
* 0x00 >> обычный удар
* 0x02 >> увернулся
* 0x04 >> крит. удар
* 0x06 >> заблокирован удар
* 0x08 >> удар с соской
* 0x0a >> обычный удар с соской
* 0x0b >> промах
* 0x0c >> критический удар с соской
* 0x0d >> большая надпись, удара нет
* 0x0e >> тоже, что и 0x0a, но есть большая надпись
*/
public static final int HITFLAG_MISS = 0x01;
public static final int HITFLAG_SHLD = 0x02;
public static final int HITFLAG_CRIT = 0x04;
public static final int HITFLAG_USESS = 0x08;
private class Hit
{
int _targetId, _damage, _flags;
Hit(GameObject target, int damage, boolean miss, boolean crit, boolean shld)
{
_targetId = target.getObjectId();
_damage = damage;
if(miss)
{
_flags = HITFLAG_MISS;
return;
}
if(_soulshot)
_flags = HITFLAG_USESS;
if(crit)
_flags |= HITFLAG_CRIT;
if(shld)
_flags |= HITFLAG_SHLD;
}
}
public final int _attackerId;
public final boolean _soulshot;
private final int _grade;
private final int _x, _y, _z, _tx, _ty, _tz;
private Hit[] hits;
private final int _addShotEffect;
public AttackPacket(Creature attacker, Creature target, boolean ss, int grade)
{
_attackerId = attacker.getObjectId();
_soulshot = ss;
_grade = grade;
_addShotEffect = attacker.getAdditionalVisualSSEffect();
_x = attacker.getX();
_y = attacker.getY();
_z = attacker.getZ();
_tx = target.getX();
_ty = target.getY();
_tz = target.getZ();
hits = new Hit[0];
}
/**
* Add this hit (target, damage, miss, critical, shield) to the Server-Client packet Attack.<BR><BR>
*/
public void addHit(GameObject target, int damage, boolean miss, boolean crit, boolean shld)
{
// Get the last position in the hits table
int pos = hits.length;
// Create a new Hit object
Hit[] tmp = new Hit[pos + 1];
// Add the new Hit object to hits table
System.arraycopy(hits, 0, tmp, 0, hits.length);
tmp[pos] = new Hit(target, damage, miss, crit, shld);
hits = tmp;
}
/**
* Return True if the Server-Client packet Attack conatins at least 1 hit.<BR><BR>
*/
public boolean hasHits()
{
return hits.length > 0;
}
@Override
protected final void writeImpl()
{
writeD(_attackerId);
writeD(hits[0]._targetId);
writeD(_soulshot ? _addShotEffect : 0x00);
writeD(hits[0]._damage);
writeD(hits[0]._flags);
writeD(_soulshot ? _grade : 0x00);
writeD(_x);
writeD(_y);
writeD(_z);
writeH(hits.length - 1);
for(int i = 1; i < hits.length; i++)
{
writeD(hits[i]._targetId);
writeD(hits[i]._damage);
writeD(hits[i]._flags);
writeD(_soulshot ? _grade : 0x00);
}
writeD(_tx);
writeD(_ty);
writeD(_tz);
}
} | pantelis60/L2Scripts_Underground | gameserver/src/main/java/l2s/gameserver/network/l2/s2c/AttackPacket.java | Java | gpl-3.0 | 3,016 |
package org.esa.beam.coastcolour.glint.nn;
import org.esa.beam.coastcolour.glint.nn.util.FormattedStringReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
/**
* This class is for using a Neural Net (NN) of type ffbp in a Java program. The
* program for training such a NN "ffbp1.0" was written in C by
*
* @author H.Schiller. You can get this program (including documentation) <a
* href="http://gfesun1.gkss.de/software/ffbp/">here </a>. The class
* only works for NN's (i.e. ".net"-files) generated with "ffbp1.0".
* @author H. Schiller modified by K.Schiller Copyright GKSS/KOF Created on
* 04.11.2003
*/
public class NNffbpAlphaTabFast {
/**
* Specifies the cutting of the activation function. For values below
* alphaStart alphaTab[0] is used; for values greater (-alphaStart)
* alphaTab[nAlpha - 1] is used.
*/
private static final double ALPHA_START = -10.0;
/**
* Specifies the length of the table containing the tabulated activation
* function.
*/
private static final int NUM_ALPHA = 100000;
/**
* The vector contains the smallest value for each input varible to the NN
* seen during the training phase.
*/
private double[] inmin;
/**
* The vector contains the biggest value for each input varible to the NN
* seen during the training phase.
*/
private double[] inmax;
/**
* The vector contains the smallest value for each output varible to the NN
* seen during the training phase.
*/
private double[] outmin;
/**
* The vector contains the biggest value for each output varible to the NN
* seen during the training phase.
*/
private double[] outmax;
/**
* The number of planes of the NN.
*/
private int nplanes;
/**
* A vector of length {@link #nplanes}containing the number of neurons in
* each plane.
*/
private int[] size;
/**
* Contains the weight ("connection strength") between each pair of neurons
* when going from ine plane to the next.
*/
private double[][][] wgt;
/**
* A matrix containing the biases for each neuron in each plane.
*/
private double[][] bias;
/**
* A matrix containing the activation signal of each neuron in each plane.
*/
private double[][] act;
/**
* The number of input variables to the NN.
*/
private int nn_in;
/**
* The number of output variables of the NN.
*/
private int nn_out;
/**
* The table containing the tabulated activation function as used during the
* training of the NN.
*/
private double[] alphaTab = new double[NUM_ALPHA];
/**
* The reciprocal of the increment of the entries of {@link #alphaTab}.
*/
private double recDeltaAlpha;
private double[][][] dActDX;
private double[][] help;
private NNCalc NNresjacob;
/**
* Creates a neural net by reading the definition from the string.
*
* @param neuralNet the neural net definition as a string
*
* @throws java.io.IOException if the neural net could not be read
*/
public NNffbpAlphaTabFast(String neuralNet) throws IOException {
readNeuralNetFromString(neuralNet);
makeAlphaTab();
NNresjacob = new NNCalc();
declareArrays();
}
/**
* Creates a neural net by reading the definition from the input stream.
*
* @param neuralNetStream the neural net definition as a input stream
*
* @throws java.io.IOException if the neural net could not be read
*/
public NNffbpAlphaTabFast(InputStream neuralNetStream) throws IOException {
this(readNeuralNet(neuralNetStream));
}
public double[] getInmin() {
return inmin;
}
public void setInmin(double[] inmin) {
this.inmin = inmin;
}
public double[] getInmax() {
return inmax;
}
public void setInmax(double[] inmax) {
this.inmax = inmax;
}
public double[] getOutmin() {
return outmin;
}
public double[] getOutmax() {
return outmax;
}
/**
* Method makeAlphaTab When an instance of this class is initialized this
* method is called and fills the {@link #alphaTab}with the activation
* function used during the training of the NN.
*/
private void makeAlphaTab() {
double delta = (-2.0 * ALPHA_START) / (NUM_ALPHA - 1.0);
double sum = ALPHA_START + (0.5 * delta);
for (int i = 0; i < NUM_ALPHA; i++) {
this.alphaTab[i] = 1.0 / (1.0 + Math.exp(-sum));
sum += delta;
}
this.recDeltaAlpha = 1.0 / delta;
}
private static String readNeuralNet(InputStream neuralNetStream) throws IOException {
String neuralNet;
BufferedReader reader = new BufferedReader(new InputStreamReader(neuralNetStream));
try {
String line = reader.readLine();
final StringBuilder sb = new StringBuilder();
while (line != null) {
// have to append line terminator, cause it's not included in line
sb.append(line).append('\n');
line = reader.readLine();
}
neuralNet = sb.toString();
} finally {
reader.close();
}
return neuralNet;
}
private void readNeuralNetFromString(String net) throws IOException {
StringReader in = null;
try {
in = new StringReader(net);
FormattedStringReader inf = new FormattedStringReader(in);
double[] h;
inf.noComments();
char ch = '0';
while (ch != '#') {
ch = (char) in.read();
}
inf.rString(); //read the rest of the line which
// has the #
nn_in = (int) inf.rlong();
inmin = new double[nn_in];
inmax = new double[nn_in];
for (int i = 0; i < nn_in; i++) {
h = inf.rdouble(2);
inmin[i] = h[0];
inmax[i] = h[1];
}
nn_out = (int) inf.rlong();
outmin = new double[nn_out];
outmax = new double[nn_out];
for (int i = 0; i < nn_out; i++) {
h = inf.rdouble(2);
outmin[i] = h[0];
outmax[i] = h[1];
}
while (ch != '=') {
ch = (char) in.read();
}
in.mark(1000000);
nplanes = (int) inf.rlong();
in.reset();
long[] hh = inf.rlong(nplanes + 1);
size = new int[nplanes];
for (int i = 0; i < nplanes; i++) {
size[i] = (int) hh[i + 1];
}
wgt = new double[nplanes - 1][][];
for (int i = 0; i < nplanes - 1; i++) {
wgt[i] = new double[size[i + 1]][size[i]];
}
bias = new double[nplanes - 1][];
for (int i = 0; i < nplanes - 1; i++) {
bias[i] = new double[size[i + 1]];
}
act = new double[nplanes][];
for (int i = 0; i < nplanes; i++) {
act[i] = new double[size[i]];
}
for (int pl = 0; pl < nplanes - 1; pl++) {
inf.rString();
for (int i = 0; i < size[pl + 1]; i++) {
bias[pl][i] = inf.rdouble();
}
}
for (int pl = 0; pl < nplanes - 1; pl++) {
inf.rString();
for (int i = 0; i < size[pl + 1]; i++) {
for (int j = 0; j < size[pl]; j++) {
wgt[pl][i][j] = inf.rdouble();
}
}
}
} finally {
if (in != null) {
in.close();
}
}
}
/**
* Method activation The output signal is found by consulting
* {@link #alphaTab}for the index associated with incoming signal x.
*
* @param x The signal incoming to the neuron for which the response is
* calculated.
*
* @return The output signal.
*/
private double activation(double x) {
int index = (int) ((x - ALPHA_START) * recDeltaAlpha);
if (index < 0) {
index = 0;
}
if (index >= NUM_ALPHA) {
index = NUM_ALPHA - 1;
}
return this.alphaTab[index];
}
/**
* Method scp The scalar product of two vectors (same lengths) is
* calculated.
*
* @param x The first vector.
* @param y The second vector.
*
* @return The scalar product of these two vector.
*/
private static double scp(double[] x, double[] y) {
double sum = 0.0;
for (int i = 0; i < x.length; i++) {
sum += x[i] * y[i];
}
return sum;
}
/**
* Method calcJacobi The NN is used. For a given input vector the
* corresponding output vector together with the corresponding Jacobi matrix
* is returned as an instance of class {@link NNCalc}.
*
* @param nnInp The vector contains the {@link #nn_in}input parameters (must
* be in right order).
*
* @return The output and corresponding Jacobi matrix of the NN.
*/
public NNCalc calcJacobi(double[] nnInp) {
final NNCalc res = NNresjacob;
for (int i = 0; i < nn_in; i++) {
act[0][i] = (nnInp[i] - inmin[i]) / (inmax[i] - inmin[i]);
}
for (int pl = 0; pl < nplanes - 1; pl++) {
final double[] act_pl_1 = act[pl + 1];
final double[] help_pl = help[pl];
final double[][] wgt_pl = wgt[pl];
final double[] bias_pl = bias[pl];
final double[] act_pl = act[pl];
for (int i = 0; i < size[pl + 1]; i++) {
act_pl_1[i] = activation(bias_pl[i] + scp(wgt_pl[i], act_pl));
help_pl[i] = act_pl_1[i] * (1.0 - act_pl_1[i]);
}
final double[][] dActDX_pl = dActDX[pl];
final double[][] dActDX_pl1 = dActDX[pl + 1];
for (int i = 0; i < size[pl + 1]; i++) {
for (int j = 0; j < nn_in; j++) {
double sum = 0.0;
final double help_pl_i = help_pl[i];
final double[] wgt_pl_i = wgt_pl[i];
for (int k = 0; k < size[pl]; k++) {
sum += help_pl_i * wgt_pl_i[k] * dActDX_pl[k][j];
}
dActDX_pl1[i][j] = sum;
}
}
}
final double[] act_nplanes_1 = act[nplanes - 1];
final double[][] dActDX_nplanes_1 = dActDX[nplanes - 1];
final double[][] jacobiMatrix = res.getJacobiMatrix();
final double[] nnOutput = res.getNnOutput();
for (int i = 0; i < nn_out; i++) {
final double diff = outmax[i] - outmin[i];
nnOutput[i] = act_nplanes_1[i] * diff + outmin[i];
final double[] res_jacobiMatrix_i = jacobiMatrix[i];
final double[] dActDX_nplanes_1_i = dActDX_nplanes_1[i];
for (int k = 0; k < nn_in; k++) {
res_jacobiMatrix_i[k] = dActDX_nplanes_1_i[k] * diff;
}
}
return res;
}
private void declareArrays() {
NNresjacob.setNnOutput(new double[nn_out]);
NNresjacob.setJacobiMatrix(new double[nn_out][nn_in]);
dActDX = new double[nplanes][][];
dActDX[0] = new double[nn_in][nn_in];
for (int i = 0; i < nn_in; i++) {
for (int j = 0; j < nn_in; j++) {
dActDX[0][i][j] = 0.0;
}
dActDX[0][i][i] = 1.0 / (inmax[i] - inmin[i]);
}
help = new double[nplanes - 1][];
for (int pl = 0; pl < nplanes - 1; pl++) {
help[pl] = new double[size[pl + 1]];
dActDX[pl + 1] = new double[size[pl + 1]][nn_in];
}
}
/**
* Method calc The NN is used. For a given input vector the corresponding
* output vector is returned.
*
* @param nninp The vector contains the {@link #nn_in}input parameters (must
* be in right order).
*
* @return The {@link #nn_out}-long output vector.
*/
public double[] calc(double[] nninp) {
double[] res = new double[nn_out];
for (int i = 0; i < nn_in; i++) {
act[0][i] = (nninp[i] - inmin[i]) / (inmax[i] - inmin[i]);
}
for (int pl = 0; pl < nplanes - 1; pl++) {
final double[] bias_pl = bias[pl];
final double[][] wgt_pl = wgt[pl];
final double[] act_pl = act[pl];
final double[] act_pl1 = act[pl + 1];
final int size_pl1 = size[pl + 1];
for (int i = 0; i < size_pl1; i++) {
act_pl1[i] = activation(bias_pl[i] + scp(wgt_pl[i], act_pl));
}
}
final double[] act_nnplanes1 = act[nplanes - 1];
for (int i = 0; i < nn_out; i++) {
res[i] = act_nnplanes1[i] * (outmax[i] - outmin[i]) + outmin[i];
}
return res;
}
} | bcdev/coastcolour | coastcolour-processing/src/main/java/org/esa/beam/coastcolour/glint/nn/NNffbpAlphaTabFast.java | Java | gpl-3.0 | 13,416 |
package com.gregmcnew.android.pax;
public class Laser extends Projectile {
public static final int DAMAGE = 10;
public static final float DIAMETER = 3;
public static final float TURN_SPEED = 0;
public static final float[] ACCELERATIONLIMS = {0, 0};
public static final float MAX_VELOCITY = 1000;
public static final int MAX_LIFE_MS = 1000 * 1000 / (int)MAX_VELOCITY;
public static final int LENGTH = 20;
public static final float[] EXTRA_POINT_OFFSETS = { LENGTH / 2, LENGTH / 4, -LENGTH / 4, -LENGTH / 2 };
public static final int NUM_EXTRA_POINTS = EXTRA_POINT_OFFSETS.length;
public Laser(Ship parent) {
super(Entity.LASER, null, null, MAX_LIFE_MS, DAMAGE, DIAMETER, LENGTH, TURN_SPEED, ACCELERATIONLIMS, MAX_VELOCITY);
mExtraPoints = new Point2[NUM_EXTRA_POINTS];
for (int i = 0; i < NUM_EXTRA_POINTS; i++) {
mExtraPoints[i] = new Point2();
}
reset(parent);
}
@Override
public void reset(Ship parent) {
super.reset(parent);
// Parent may be null if this projectile is being preallocated (i.e.,
// created and instantly recycled).
if (parent != null) {
body.center.set(parent.body.center);
heading = parent.heading;
}
targetHeading = heading;
float headingX = (float) Math.cos(heading);
float headingY = (float) Math.sin(heading);
body.center.add(headingX * length / 2, headingY * length / 2);
setExtraPoints(NUM_EXTRA_POINTS, EXTRA_POINT_OFFSETS);
velocity.x = headingX * MAX_VELOCITY;
velocity.y = headingY * MAX_VELOCITY;
}
@Override
public void updateHeading(long dt) {
}
@Override
public void updateVelocity(long dt) {
}
}
| gmcnew/pax | src/com/gregmcnew/android/pax/Laser.java | Java | gpl-3.0 | 1,628 |
package blacksmith;
import java.util.UUID;
public class Item {
private UUID ID;
private ItemType ITEM_TYPE;
private ItemTier ITEM_TIER;
private ItemState ITEM_STATE;
Item() {
this(ItemType.NONE);
}
Item(ItemType ITEM_TYPE) {
this(ITEM_TYPE, ItemTier.NONE, ItemState.NONE);
}
Item(ItemType ITEM_TYPE, ItemTier ITEM_TIER, ItemState ITEM_STATE) {
this.ID = UUID.randomUUID();
this.ITEM_TYPE = ITEM_TYPE;
this.ITEM_TIER = ITEM_TIER;
this.ITEM_STATE = ITEM_STATE;
}
public UUID getID() {
return ID;
}
public ItemType getType() {
return ITEM_TYPE;
}
public ItemTier getTier() {
return ITEM_TIER;
}
public ItemState getState() {
return ITEM_STATE;
}
public void setState(ItemState ITEM_STATE) {
this.ITEM_STATE = ITEM_STATE;
}
public boolean itemCompare(Item i) {
if (i.getType().equals(ITEM_TYPE) && i.getTier().equals(ITEM_TIER) && i.getState().equals(ITEM_STATE)) {
return true;
} else {
return false;
}
}
@Override
public String toString() {
if (ITEM_TIER != ItemTier.NONE) {
return ITEM_TYPE.getFormattedName() + " (" + ITEM_TIER.getResource().getFormattedName() + ")" + " (" + ITEM_STATE.name().substring(0, 1) + ")";
} else {
return ITEM_TYPE.getFormattedName();
}
}
}
| jacojazz/Blacksmith | Blacksmith/src/blacksmith/Item.java | Java | gpl-3.0 | 1,314 |
package net.minecraft.Server1_7_10.block;
import net.minecraft.Server1_7_10.init.Items;
import net.minecraft.Server1_7_10.item.Item;
public class BlockCarrot extends BlockCrops
{
private static final String __OBFID = "CL_00000212";
protected Item func_149866_i()
{
return Items.carrot;
}
protected Item func_149865_P()
{
return Items.carrot;
}
}
| TheHecticByte/BananaJ1.7.10Beta | src/net/minecraft/Server1_7_10/block/BlockCarrot.java | Java | gpl-3.0 | 394 |
package com.megathirio.shinsei.block.ore;
import com.megathirio.shinsei.block.OreShinsei;
import com.megathirio.shinsei.init.ShinseiItems;
import com.megathirio.shinsei.reference.Names;
import net.minecraft.block.material.Material;
import net.minecraft.item.Item;
import java.util.Random;
public class BlockOpalOre extends OreShinsei {
int intQty = 1;
public BlockOpalOre(){
super(Material.rock);
this.setBlockName(Names.Ores.OPAL_ORE);
this.setHardness(6.0f);
this.setResistance(9.7f);
this.setHarvestLevel("pickaxe", 2);
}
@Override
public Item getItemDropped(int intX, Random random, int intY){ return ShinseiItems.opalGem; }
@Override
public int quantityDropped(Random random) {
int intWeight = random.nextInt(100) + 1;
if (intWeight <= 20){
intQty = 2;
}else {
intQty = 1;
}
return intQty;
}
} | Mrkwtkr/shinsei | src/main/java/com/megathirio/shinsei/block/ore/BlockOpalOre.java | Java | gpl-3.0 | 942 |
/***********************************************************************
This file is part of KEEL-software, the Data Mining tool for regression,
classification, clustering, pattern mining and so on.
Copyright (C) 2004-2010
F. Herrera ([email protected])
L. Sánchez ([email protected])
J. Alcalá-Fdez ([email protected])
S. García ([email protected])
A. Fernández ([email protected])
J. Luengo ([email protected])
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 3 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, see http://www.gnu.org/licenses/
**********************************************************************/
//
// Main.java
//
// Isaak Triguero
//
// Copyright (c) 2004 __MyCompanyName__. All rights reserved.
//
package keel.Algorithms.Semi_Supervised_Learning.ADE_CoForest;
import keel.Algorithms.Semi_Supervised_Learning.Basic.PrototypeSet;
import keel.Algorithms.Semi_Supervised_Learning.Basic.PrototypeGenerationAlgorithm;
import keel.Algorithms.Semi_Supervised_Learning.*;
import keel.Algorithms.Semi_Supervised_Learning.utilities.*;
import java.util.*;
/**
* ADE_CoForest algorithm calling.
* @author Isaac Triguero
*/
public class ADE_CoForestAlgorithm extends PrototypeGenerationAlgorithm<ADE_CoForestGenerator>
{
/**
* Builds a new ADE_CoForestGenerator.
* @param train Training data set.
* @param unlabeled unlabeled data set.
* @param test Test data set.
* @param params Parameters of the method.
* @return a new Generator object.
*/
protected ADE_CoForestGenerator buildNewPrototypeGenerator(PrototypeSet train, PrototypeSet unlabeled, PrototypeSet test, Parameters params)
{
return new ADE_CoForestGenerator(train, unlabeled, test, params);
}
/**
* Main method. Executes ADE_CoForest algorithm.
* @param args Console arguments of the method.
*/
public static void main(String args[])
{
ADE_CoForestAlgorithm isaak = new ADE_CoForestAlgorithm();
isaak.execute(args);
}
}
| SCI2SUGR/KEEL | src/keel/Algorithms/Semi_Supervised_Learning/ADE_CoForest/ADE_CoForestAlgorithm.java | Java | gpl-3.0 | 2,638 |
package nl.tue.declare.verification.impl;
import nl.tue.declare.verification.*;
/**
* <p>
* Title: DECLARE
* </p>
*
* <p>
* Description:
* </p>
*
* <p>
* Copyright: Copyright (c) 2006
* </p>
*
* <p>
* Company: TU/e
* </p>
*
* @author Maja Pesic
* @version 1.0
*/
public class HistoryError extends VerificationError {
/**
*
*/
private static final long serialVersionUID = 8893211536014281088L;
public HistoryError(ViolationGroup group) {
super(group);
}
public HistoryError() {
this(null);
}
public String toString() {
return "Instance history is violated";
}
}
| ijlalhussain/LogGenerator | DeclareDesigner/src/nl/tue/declare/verification/impl/HistoryError.java | Java | gpl-3.0 | 610 |
/*
* Copyright (C) 2018 Saxon State and University Library Dresden (SLUB)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package org.qucosa.xml;
import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import javax.xml.xpath.XPathFunctionResolver;
import javax.xml.xpath.XPathVariableResolver;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class XPathExpressionFactory {
private static final Pattern X_PATH_PARAMETER_PATTERN = Pattern.compile("\\$([a-zA-Z0-9]*)");
private NamespaceContext namespaceContext;
private XPathVariableResolver variableResolver;
private XPathFunctionResolver functionResolver;
public XPathExpressionFactory() {
namespaceContext = null;
variableResolver = null;
functionResolver = null;
}
public XPathExpressionFactory(XPathExpressionFactory original) {
this.variableResolver = original.variableResolver;
this.functionResolver = original.functionResolver;
this.namespaceContext = original.namespaceContext;
}
public XPathExpressionFactory variableResolver(XPathVariableResolver variableResolver) {
this.variableResolver = variableResolver;
return this;
}
public XPathExpressionFactory functionResolver(XPathFunctionResolver functionResolver) {
this.functionResolver = functionResolver;
return this;
}
public XPathExpressionFactory namespaceContext(NamespaceContext namespaceContext) {
this.namespaceContext = namespaceContext;
return this;
}
public XPathExpression create(String expression, Object... values) throws XPathExpressionException {
if (values.length > 0) {
Iterator<Object> paramsIterator = Arrays.asList(values).iterator();
Matcher xPathParameterMatcher = X_PATH_PARAMETER_PATTERN.matcher(expression);
HashMap<String, Object> variableMap = new HashMap<>();
while (xPathParameterMatcher.find()) {
String xPathVariable = xPathParameterMatcher.group(1);
if (paramsIterator.hasNext()) {
variableMap.put(xPathVariable, String.valueOf(paramsIterator.next()));
} else {
throw new IllegalArgumentException(String.format(
"No more values available for variable `%s`." +
" Number of XPath variables should match number of values.", xPathVariable));
}
}
variableResolver = (variableResolver == null) ?
qName -> variableMap.get(qName.toString()) :
qName -> {
Object result = variableMap.get(qName.toString());
return result == null ? variableResolver.resolveVariable(qName) : result;
};
}
XPathFactory xPathFactory = XPathFactory.newInstance();
if (variableResolver != null) xPathFactory.setXPathVariableResolver(variableResolver);
if (functionResolver != null) xPathFactory.setXPathFunctionResolver(functionResolver);
XPath xPath = xPathFactory.newXPath();
if (namespaceContext != null) xPath.setNamespaceContext(namespaceContext);
return xPath.compile(expression);
}
}
| qucosa/qucosa-fcrepo-repair | src/main/java/org/qucosa/xml/XPathExpressionFactory.java | Java | gpl-3.0 | 4,140 |
/*
* Curio - A simple puzzle platformer game.
* Copyright (C) 2014 Michael Swiger
*
* 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 3 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, see <http://www.gnu.org/licenses/>
*/
package com.wasome.curio.components;
import com.artemis.Component;
import com.wasome.curio.sprites.AnimationState;
public class Creature extends Component {
public static final int STATUS_IDLE = 0;
public static final int STATUS_WALKING = 1;
public static final int STATUS_JUMPING = 2;
public static final int STATUS_CLIMBING = 3;
public static final int STATUS_DEAD = 4;
private int status;
private AnimationState[] anims;
public Creature() {
status = STATUS_IDLE;
anims = new AnimationState[5];
}
public int getStatus() {
return status;
}
public void setStatus(int status) {
this.status = status;
}
public void setAnimation(int status, AnimationState anim) {
anims[status] = anim;
}
public AnimationState getAnimation(int status) {
return anims[status];
}
public AnimationState getCurrentAnimation() {
return anims[status];
}
}
| mokkan/curio | src/com/wasome/curio/components/Creature.java | Java | gpl-3.0 | 1,739 |
/*
* Copyright (C) 2013 Clemens Fuchslocher <[email protected]>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package de.vakuumverpackt.foul;
import android.os.Bundle;
public class YellowCardActivity extends CardActivity {
@Override
protected void onCreate(final Bundle bundle) {
super.onCreate(bundle, "Yellow Card", R.layout.activity_yellow_card);
}
}
| vakuum/foul-android | foul/src/main/java/de/vakuumverpackt/foul/YellowCardActivity.java | Java | gpl-3.0 | 979 |
import javax.swing.JFrame;
public class FlowLayoutDemo {
public static void main( String[] args ) {
FlowLayoutFrame flowLayoutFrame = new FlowLayoutFrame();
flowLayoutFrame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
flowLayoutFrame.setSize( 300, 75 );
flowLayoutFrame.setVisible( true );
}
} | chichunchen/Java-Programming | Java in Winter/GUI/FlowLayoutDemo.java | Java | gpl-3.0 | 328 |
package pl.mrugames.nucleus.common.io;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class LineWriter implements ClientWriter<String> {
private final ByteBuffer byteBuffer;
private final Charset charset = StandardCharsets.UTF_8;
private final String lineEnding = "\r\n";
private final OutputStream outputStream;
public LineWriter(ByteBuffer byteBuffer) {
this.byteBuffer = byteBuffer;
this.outputStream = null;
}
public LineWriter(OutputStream outputStream) {
this.byteBuffer = null;
this.outputStream = outputStream;
}
@Override
public void write(String frameToSend) throws Exception {
frameToSend += lineEnding;
if (byteBuffer != null) {
byteBuffer.put(frameToSend.getBytes(charset));
}
if (outputStream != null) {
outputStream.write(frameToSend.getBytes(charset));
}
}
public String getLineEnding() {
return lineEnding;
}
}
| Mariusz-v7/ClientServer | src/main/java/pl/mrugames/nucleus/common/io/LineWriter.java | Java | gpl-3.0 | 1,084 |
/**
*
* Copyright (c) 2014, Openflexo
*
* This file is part of Freemodellingeditor, a component of the software infrastructure
* developed at Openflexo.
*
*
* Openflexo is dual-licensed under the European Union Public License (EUPL, either
* version 1.1 of the License, or any later version ), which is available at
* https://joinup.ec.europa.eu/software/page/eupl/licence-eupl
* and the GNU General Public License (GPL, either version 3 of the License, or any
* later version), which is available at http://www.gnu.org/licenses/gpl.html .
*
* You can redistribute it and/or modify under the terms of either of these licenses
*
* If you choose to redistribute it and/or modify under the terms of the GNU GPL, you
* must include the following additional permission.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with software containing parts covered by the terms
* of EPL 1.0, the licensors of this Program grant you additional permission
* to convey the resulting work. *
*
* This software 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 http://www.openflexo.org/license.html for details.
*
*
* Please contact Openflexo ([email protected])
* or visit www.openflexo.org if you need additional information.
*
*/
package org.openflexo.fme.controller;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import org.openflexo.fme.FMEModule;
import org.openflexo.fme.controller.editor.FreeModelDiagramEditor;
import org.openflexo.fme.model.FMEFreeModel;
import org.openflexo.fme.model.FreeModellingProjectNature;
import org.openflexo.fme.view.FMEDiagramFreeModelModuleView;
import org.openflexo.foundation.FlexoProject;
import org.openflexo.foundation.fml.FlexoConcept;
import org.openflexo.foundation.fml.FlexoConceptInstanceRole;
import org.openflexo.gina.model.FIBComponent;
import org.openflexo.gina.view.GinaViewFactory;
import org.openflexo.icon.FMLIconLibrary;
import org.openflexo.localization.FlexoLocalization;
import org.openflexo.localization.LocalizedDelegate;
import org.openflexo.module.ModuleLoadingException;
import org.openflexo.view.controller.FlexoFIBController;
/**
* Represents the controller of a FIBComponent in FME graphical context
*
*
* @author sylvain
*
* @param <T>
*/
public class FMEFIBController extends FlexoFIBController {
private static final Logger logger = Logger.getLogger(FMEFIBController.class.getPackage().getName());
public FMEFIBController(FIBComponent component, GinaViewFactory<?> viewFactory) {
super(component, viewFactory);
// Default parent localizer is the main localizer
setParentLocalizer(FlexoLocalization.getMainLocalizer());
}
public final LocalizedDelegate getLocales() {
try {
return getServiceManager().getModuleLoader().getModuleInstance(FMEModule.class).getLocales();
} catch (ModuleLoadingException e) {
e.printStackTrace();
return null;
}
}
@Override
public FMEController getFlexoController() {
return (FMEController) super.getFlexoController();
}
public FreeModelDiagramEditor getDiagramEditor() {
if (getFlexoController().getCurrentModuleView() instanceof FMEDiagramFreeModelModuleView) {
return ((FMEDiagramFreeModelModuleView) getFlexoController().getCurrentModuleView()).getEditor();
}
return null;
}
public FreeModellingProjectNature getFreeModellingProjectNature() {
if (getEditor() != null) {
FlexoProject<?> project = getEditor().getProject();
if (project != null)
return project.getNature(FreeModellingProjectNature.class);
}
return null;
}
public String getFlexoConceptName(FlexoConcept concept) {
if (getFreeModellingProjectNature() != null) {
if (concept.getName().equals(FMEFreeModel.NONE_FLEXO_CONCEPT_NAME)) {
return getLocales().localizedForKey("unclassified");
}
FlexoConceptInstanceRole conceptRole = (FlexoConceptInstanceRole) concept.getAccessibleRole(FMEFreeModel.CONCEPT_ROLE_NAME);
if (conceptRole != null && conceptRole.getFlexoConceptType() != null) {
return conceptRole.getFlexoConceptType().getName();
}
}
return concept.getName();
}
@Override
protected ImageIcon retrieveIconForObject(Object object) {
if (object instanceof FlexoConcept && ((FlexoConcept) object).getName().equals(FMEFreeModel.NONE_FLEXO_CONCEPT_NAME)) {
return FMLIconLibrary.UNKNOWN_ICON;
}
return super.retrieveIconForObject(object);
}
public void createConcept(String name) {
// getDiagramEditor().createNewConcept(name);
}
public void removeConcept(FlexoConcept concept) {
// getDiagramEditor().removeConcept(concept);
}
public void renameConcept(FlexoConcept concept) {
// getDiagramEditor().renameConcept(concept);
}
/*public Icon getIcon(FMEModelObject object) {
if (object instanceof Concept) {
return FMEIconLibrary.CONCEPT_ICON;
} else if (object instanceof Instance) {
return FMEIconLibrary.INSTANCE_ICON;
}
return null;
}*/
}
| openflexo-team/openflexo-modules | freemodellingeditor/src/main/java/org/openflexo/fme/controller/FMEFIBController.java | Java | gpl-3.0 | 5,205 |
/*
* Copyright 2009 Harvard University Library
*
* This file is part of FITS (File Information Tool Set).
*
* FITS is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FITS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FITS. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.harvard.hul.ois.fits.junit;
import java.io.File;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import edu.harvard.hul.ois.fits.Fits;
import edu.harvard.hul.ois.fits.FitsOutput;
import edu.harvard.hul.ois.fits.tests.AbstractLoggingTest;
public class MixTest extends AbstractLoggingTest {
/*
* Only one Fits instance is needed to run all tests.
* This also speeds up the tests.
*/
private static Fits fits;
@BeforeClass
public static void beforeClass() throws Exception {
// Set up FITS for entire class.
File fitsConfigFile = new File("testfiles/properties/fits-full-with-tool-output.xml");
fits = new Fits(null, fitsConfigFile);
}
@AfterClass
public static void afterClass() {
fits = null;
}
@Test
public void testMIX() throws Exception {
String inputFilename = "topazscanner.tif";
File input = new File("testfiles/" + inputFilename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + inputFilename + "_Output.xml");
}
@Test
public void testUncompressedTif() throws Exception {
String inputFilename = "4072820.tif";
File input = new File("testfiles/" + inputFilename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat();
fitsOut.saveToDisk("test-generated-output/" + inputFilename + "_Output.xml");
}
@Test
public void testMixJpg() throws Exception {
String filename = "3426592.jpg";
File input = new File("testfiles/" + filename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + filename + "_Output.xml");
}
@Test
public void testJpgExif() throws Exception {
String filename = "ICFA.KC.BIA.1524-small.jpg";
File input = new File("testfiles/" + filename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + filename + "_Output.xml");
}
@Test
public void testJpgExif2() throws Exception {
String filename = "JPEGTest_20170591--JPEGTest_20170591.jpeg";
File input = new File("testfiles/" + filename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + filename + "_Output.xml");
}
@Test
public void testJpgJfif() throws Exception {
String filename = "gps.jpg";
File input = new File("testfiles/" + filename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + filename + "_Output.xml");
}
@Test
public void testTwoPageTiff() throws Exception {
String filename = "W00EGS1016782-I01JW30--I01JW300001__0001.tif";
File input = new File("testfiles/" + filename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + filename + "_Output.xml");
}
@Test
public void testJp2_1() throws Exception {
String inputFilename = "test.jp2";
File input = new File("testfiles/" + inputFilename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + inputFilename + "_Output.xml");
}
@Test
public void testJp2_2() throws Exception {
String inputFilename = "006607203_00018.jp2";
File input = new File("testfiles/" + inputFilename);
FitsOutput fitsOut = fits.examine(input);
fitsOut.addStandardCombinedFormat(); // output all data to file
fitsOut.saveToDisk("test-generated-output/" + inputFilename + "_Output.xml");
}
}
| nclarkekb/fits | src/test/java/edu/harvard/hul/ois/fits/junit/MixTest.java | Java | gpl-3.0 | 4,794 |
/*
* $Id: RendezvousListener.java,v 1.1 2007/01/16 11:01:28 thomas Exp $
*
* Copyright (c) 2001 Sun Microsystems, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Sun Microsystems, Inc. for Project JXTA."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Sun", "Sun Microsystems, Inc.", "JXTA" and "Project JXTA"
* must not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact Project JXTA at http://www.jxta.org.
*
* 5. Products derived from this software may not be called "JXTA",
* nor may "JXTA" appear in their name, without prior written
* permission of Sun.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL SUN MICROSYSTEMS OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of Project JXTA. For more
* information on Project JXTA, please see
* <http://www.jxta.org/>.
*
* This license is based on the BSD license adopted by the Apache Foundation.
*
* $Id: RendezvousListener.java,v 1.1 2007/01/16 11:01:28 thomas Exp $
*
*/
package net.jxta.rendezvous;
import java.util.EventListener;
/**
* The listener interface for receiving RendezVousService events.
*
* The following example illustrate how to implement a
* <code>RendezvousListener</code>:
*
* <pre><code>
* public class MyApp implements RendezvousListener {
* ..
* rendezvous = mygroup.getRendezVousService();
* rendezvous.addListener(this);
* ..
* ..
* ..
* public void rendezvousEvent ( RendezvousEvent event ){
* if( event.getType() == event.RDVCONNECT){
* ..
* }
* }
* }
* </code></pre>
**/
public interface RendezvousListener extends EventListener {
/**
* Called when an event occurs for the Rendezvous service
*
* @param event the rendezvous event
*/
void rendezvousEvent( RendezvousEvent event );
}
| idega/net.jxta | src/java/net/jxta/rendezvous/RendezvousListener.java | Java | gpl-3.0 | 3,659 |
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static java.util.stream.Collectors.toList;
public class Disk {
public static void main(String[] args) {
List<MHD> mhds = new ArrayList<MHD>();
List<Double> qx = IntStream
.rangeClosed(-5, 5)
.mapToDouble(i -> i)
.map(x -> x / 10.0)
.boxed()
.collect(toList());
List<Double> qy = IntStream
.rangeClosed(-5, 5)
.mapToDouble(i -> i)
.map(x -> x / 10.0)
.boxed()
.collect(toList());
List<Double> qz = IntStream
.rangeClosed(-5, 5)
.mapToDouble(i -> i)
.map(x -> x / 10.0)
.boxed()
.collect(toList());
qx.forEach( x -> {
qy.forEach( y -> {
qz.forEach( z -> {
Vector waveVector = new Vector(x, y, z);
Vector velocity = new Vector(1.0, 1.0, 0.0);
Vector magneticField = new Vector(1.0, 1.0, 0.0);
mhds.add(new MHD(waveVector, velocity, magneticField));
});
});
});
List<MHD> firstPass = mhds.stream()
.map(MHD::linearTerms)
.collect(Collectors.toList());
}
}
| zlatan/MHD | jdisk/src/main/java/Disk.java | Java | gpl-3.0 | 1,495 |
/*
* Copyright (C) 2017 SFINA Team
*
* 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.
*/
package networkGenerator;
import java.awt.BorderLayout;
import java.awt.Dimension;
import static java.lang.Integer.min;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BoxLayout;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
/**
*
* @author dinesh
*/
public class ValuesDialog extends JPanel{
ArrayList<String> fields;
ArrayList<String> valueList;
ArrayList<PropertyField> pFields;
JScrollPane scrollPane;
JPanel contentPane;
ValuesDialog(ArrayList<String> fields){
valueList = new ArrayList<String>();
this.fields = fields;
pFields = new ArrayList<PropertyField>();
//setPreferredSize(new Dimension(300,min(fields.size()*30+50,300)));
for (String s:fields){
PropertyField p = new PropertyField(s);
pFields.add(p);
}
contentPane = new JPanel();
//contentPane.setPreferredSize(new Dimension(250, min(fields.size()*30,300)));
//contentPane.setPreferredSize(new Dimension(300, 500));
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
for(PropertyField p : pFields){
contentPane.add(p);
}
scrollPane = new JScrollPane(contentPane);
//scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
//scrollPane.setBounds(20,20,250,250);
//setPreferredSize(new Dimension(350,300));
add(scrollPane);
}
public ArrayList<String> getValues(){
valueList.clear();
for(PropertyField p : pFields){
valueList.add(p.getValue());
}
return valueList;
}
public static void main(String [] args){
ArrayList<String> al = new ArrayList<>(Arrays.asList("v1","v2","v3","v4","v5","v6","v7","v8"));
ValuesDialog v = new ValuesDialog(al);
JScrollPane jsp = new JScrollPane(v,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
jsp.setPreferredSize(new Dimension(320,200));
JOptionPane.showConfirmDialog(null, jsp, "Enter Link Properties", JOptionPane.PLAIN_MESSAGE, JOptionPane.PLAIN_MESSAGE);
}
}
| SFINA/GUI | SFINAGUI/src/networkGenerator/ValuesDialog.java | Java | gpl-3.0 | 3,128 |
package com.example.patrick.myapplication.controller;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.content.res.Configuration;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.os.Bundle;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.patrick.myapplication.SettingsActivity;
import com.example.patrick.myapplication.bean.NodeBean;
import com.example.patrick.myapplication.view.ListaUtentiFragment;
import com.example.patrick.myapplication.view.ListaNodiFragment;
import com.example.patrick.myapplication.NsMenuAdapter;
import com.example.patrick.myapplication.R;
import com.example.patrick.myapplication.model.NsMenuItemModel;
import com.example.patrick.myapplication.view.MyDetailFragment;
import com.example.patrick.myapplication.view.MyMapFragment;
import com.example.patrick.myapplication.view.NearMeFragment;
public class MyActivity extends ActionBarActivity implements
SearchView.OnQueryTextListener, ListaNodiFragment.OnMyListaNodiItemClick {
private String[] menuItems;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private SearchView mSearchView;
private CustomActionBarDrawerToggle mDrawerToggle;
private CursorAdapter adapter;
private ListaNodiFragment nodiFragment;
private MyMapFragment myMapFragment;
private ListaNodiFragment listaNodiFragment;
private ListaUtentiFragment listaUtentiFragment;
private NearMeFragment nearMeFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Creazione dei fragment
nodiFragment = new ListaNodiFragment();
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
_initMenu();
mDrawerToggle = new CustomActionBarDrawerToggle(this, mDrawerLayout);
mDrawerLayout.setDrawerListener(mDrawerToggle);
// test shared preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String username = prefs.getString("edittext_username", "");
Log.i("MyACTIVITY", username);
//getSupportFragmentManager().beginTransaction().replace(R.id.frame_container, new ListaNodiFragment()).commit();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
setupSearchView();
// When using the support library, the setOnActionExpandListener() method is
// static and accepts the MenuItem object as an argument
MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
@Override
public boolean onMenuItemActionCollapse(MenuItem item) {
// Do something when collapsed
return true; // Return true to collapse action view
}
@Override
public boolean onMenuItemActionExpand(MenuItem item) {
// Do something when expanded
return true; // Return true to expand action view
}
});
return true;
}
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_search).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search: {
Toast.makeText(this, "Search selected", Toast.LENGTH_SHORT).show();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_container, nodiFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack("ts")
.commit();
return true;
}
case R.id.action_refresh: {
Toast.makeText(this, "Refresh selected", Toast.LENGTH_SHORT).show();
return true;
}
case R.id.action_settings: {
Toast.makeText(this, "Settings selected", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
private void _initMenu() {
NsMenuAdapter mAdapter = new NsMenuAdapter(this);
// Add Header
mAdapter.addHeader(R.string.ns_menu_main_header);
// Add first block
menuItems = getResources().getStringArray(
R.array.ns_menu_items);
String[] menuItemsIcon = getResources().getStringArray(
R.array.ns_menu_items_icon);
int res = 0;
for (String item : menuItems) {
int id_title = getResources().getIdentifier(item, "string",
this.getPackageName());
int id_icon = getResources().getIdentifier(menuItemsIcon[res],
"drawable", this.getPackageName());
NsMenuItemModel mItem = new NsMenuItemModel(id_title, id_icon);
if (res == 1) mItem.counter = 12;
if (res == 3) mItem.counter = 3;
mAdapter.addItem(mItem);
res++;
}
mAdapter.addHeader(R.string.ns_menu_main_header2);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
if (mDrawerList != null)
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener(getApplicationContext()));
}
@Override
public boolean onQueryTextSubmit(String s) {
return false;
}
@Override
public boolean onQueryTextChange(String s) {
// TODO Auto-generated method stub
s = s.isEmpty() ? "" : "Query: " + s;
Log.i("textchange", s);
return true;
}
private void setupSearchView() {
mSearchView.setIconifiedByDefault(false);
mSearchView.setOnQueryTextListener(this);
mSearchView.setSubmitButtonEnabled(true);
mSearchView.setQueryHint("Search Here");
}
private void fetchData() {
}
/**
* Implementazione dell'interfaccia onClick di ListaNodiFragment
*
* @param item NodeBean object selected from listview
*/
@Override
public void onClick(NodeBean item) {
// Preparo l'argomento da passare al Fragment o all'Activity. Questo argomento contiene l'oggetto cliccato.
Bundle arguments = new Bundle();
arguments.putParcelable("com.example.patrick.myapplication.NodeBean",item);
// Recupero la vista detailContainer
View detailView = findViewById(R.id.detail_container);
if (detailView == null) {
// Non esiste spazio per la visualizzazione del dattagli, quindi ho necessità di lanciare una nuova activity.
// Carico gli arguments nell'intent di chiamata.
//Intent intent = new Intent(this, DetailActivity.class);
new LoadDetailActivityTask().execute(arguments);
} else {
// Esiste lo spazio, procedo con la creazione del Fragment!
MyDetailFragment myDetailFragment = new MyDetailFragment();
// Imposto gli argument del fragment.
myDetailFragment.setArguments(arguments);
// Procedo con la sostituzione del fragment visualizzato.
FragmentManager fragmentManager = this.getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.detail_container, myDetailFragment)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.addToBackStack("ts")
.commit();
}
}
/**
* Classe innestata che implementa il listener per il drawer
*/
private class DrawerItemClickListener implements ListView.OnItemClickListener {
Context mContext;
public DrawerItemClickListener(Context context) {
mContext = context;
}
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// Highlight the selected item, update the title, and close the drawer
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
//setTitle("......");
//String text = "menu click... should be implemented";
//Toast.makeText(MyActivity.this, text, Toast.LENGTH_LONG).show();
Fragment rFragment = null;
switch (position) {
case 1:{
if (myMapFragment == null)
myMapFragment = new MyMapFragment();
rFragment = myMapFragment;
}
break;
case 2: {
if (listaUtentiFragment == null)
listaUtentiFragment = new ListaUtentiFragment();
rFragment = listaUtentiFragment;
}
break;
case 3:{
if( listaNodiFragment == null)
listaNodiFragment= new ListaNodiFragment();
rFragment = listaNodiFragment;
}
break;
case 4:{
if ( nearMeFragment == null)
nearMeFragment = new NearMeFragment();
rFragment = nearMeFragment;
}
}
// Getting reference to the FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// Creating a fragment transaction
FragmentTransaction ft = fragmentManager.beginTransaction();
// Adding a fragment to the fragment transaction
ft.replace(R.id.frame_container, rFragment);
// Committing the transaction
ft.commit();
// Closing the drawer
mDrawerLayout.closeDrawer(mDrawerList);
}
}
// Estendo ActionBarDrawerToggle
private class CustomActionBarDrawerToggle extends ActionBarDrawerToggle {
public CustomActionBarDrawerToggle(Activity mActivity, DrawerLayout mDrawerLayout) {
super(
mActivity, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.ns_menu_open, /* "open drawer" description */
R.string.ns_menu_close); /* "close drawer" description */
}
/**
* Called when a drawer has settled in a completely closed state.
*/
@Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(getString(R.string.ns_menu_close));
supportInvalidateOptionsMenu();
}
/**
* Called when a drawer has settled in a completely open state.
*/
@Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(getString(R.string.ns_menu_open));
supportInvalidateOptionsMenu();
}
}
/**
* Async task per avviare l'activity di detail
*
*/
class LoadDetailActivityTask extends AsyncTask<Bundle, Void, Void> {
@Override
protected Void doInBackground(Bundle...arguments) {
Intent intent = new Intent(MyActivity.this, DetailActivity.class);
intent.putExtras(arguments[0]);
startActivity(intent);
Log.i("LoadDetailActivityTask","doInBackground");
return (null);
}
@Override
protected void onPostExecute(Void unused) {
}
}
}
| patrickprn/ninuxmobile | app/src/main/java/com/example/patrick/myapplication/controller/MyActivity.java | Java | gpl-3.0 | 14,778 |
/*
* WANDORA
* Knowledge Extraction, Management, and Publishing Application
* http://wandora.org
*
* Copyright (C) 2004-2016 Wandora Team
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*
*
*
*
*/
package org.wandora.utils;
public class PriorityObject extends Object implements Comparable, java.io.Serializable {
public final static int HIGHEST_PRIORITY = 10000;
public final static int HIGHER_PRIORITY = 1000;
public final static int DEFAULT_PRIORITY = 100;
public final static int LOWER_PRIORITY = 10;
public final static int LOWEST_PRIORITY = 1;
protected int priority = DEFAULT_PRIORITY;
protected Object object = null;
public PriorityObject(Object object) {
this.object = object;
this.priority = DEFAULT_PRIORITY;
}
public PriorityObject(Object object, int priority) {
this.object = object;
this.priority = priority;
}
// -------------------------------------------------------------------------
public synchronized int getPriority() {
return priority;
}
public synchronized void setPriority(int newPriority) {
priority = newPriority;
}
public synchronized boolean isSuperior(PriorityObject priorityObject) {
if (priorityObject != null) {
if (priority > priorityObject.getPriority()) return true;
}
return false;
}
public int compareTo(Object o) {
if (o != null && o instanceof PriorityObject) {
if (priority > ((PriorityObject)o).getPriority())
return 1;
if (priority < ((PriorityObject)o).getPriority())
return -1;
return 0;
}
return 0;
}
// -------------------------------------------------------------------------
public synchronized Object getObject() { return object; }
public synchronized void setObject(Object newObject) { object = newObject; }
// -------------------------------------------------------------------------
public synchronized void adjustPriority( int amount ) {
this.priority += amount;
}
public String toString() {
if( null==object )
return "PriorityObject[null pri="+priority+"]";
else
return "PriorityObject["+object.toString()+" pri="+priority+"]";
}
}
| wandora-team/wandora | src/org/wandora/utils/PriorityObject.java | Java | gpl-3.0 | 3,038 |
package jsat.linear.distancemetrics;
import java.util.List;
import java.util.concurrent.ExecutorService;
import jsat.DataSet;
import jsat.classifiers.ClassificationDataSet;
import jsat.linear.Vec;
import jsat.regression.RegressionDataSet;
/**
* Some Distance Metrics require information that can be learned from the data set.
* Trainable Distance Metrics support this facility, and algorithms that rely on
* distance metrics should check if their metric needs training. This is needed
* priming the distance metric on the whole data set and then performing cross
* validation would bias the results, as the metric would have been trained on
* the testing set examples.
*
* @author Edward Raff
*/
abstract public class TrainableDistanceMetric implements DistanceMetric
{
private static final long serialVersionUID = 6356276953152869105L;
/**
* Trains this metric on the given data set
* @param <V> the type of vectors in the list
* @param dataSet the data set to train on
* @throws UnsupportedOperationException if the metric can not be trained from unlabeled data
*/
public <V extends Vec> void train(List<V> dataSet)
{
train(dataSet, false);
}
/**
* Trains this metric on the given data set
* @param <V> the type of vectors in the list
* @param dataSet the data set to train on
* @param parallel {@code true} if multiple threads should be used for
* training. {@code false} if it should be done in a single-threaded manner.
* @throws UnsupportedOperationException if the metric can not be trained from unlabeled data
*/
abstract public <V extends Vec> void train(List<V> dataSet, boolean parallel);
/**
* Trains this metric on the given data set
* @param dataSet the data set to train on
* @throws UnsupportedOperationException if the metric can not be trained from unlabeled data
*/
public void train(DataSet dataSet)
{
train(dataSet, false);
}
/**
* Trains this metric on the given data set
* @param dataSet the data set to train on
* @param parallel {@code true} if multiple threads should be used for
* training. {@code false} if it should be done in a single-threaded manner.
* @throws UnsupportedOperationException if the metric can not be trained from unlabeled data
*/
abstract public void train(DataSet dataSet, boolean parallel);
/**
* Trains this metric on the given classification problem data set
* @param dataSet the data set to train on
* @throws UnsupportedOperationException if the metric can not be trained from classification problems
*/
public void train(ClassificationDataSet dataSet)
{
train(dataSet, false);
}
/**
* Trains this metric on the given classification problem data set
*
* @param dataSet the data set to train on
* @param parallel {@code true} if multiple threads should be used for
* training. {@code false} if it should be done in a single-threaded manner.
* @throws UnsupportedOperationException if the metric can not be trained
* from classification problems
*/
abstract public void train(ClassificationDataSet dataSet, boolean parallel);
/**
* Some metrics might be special purpose, and not trainable for all types of data sets or tasks.
* This method returns <tt>true</tt> if this metric supports training for classification
* problems, and <tt>false</tt> if it does not. <br>
* If a metric can learn from unlabeled data, it must return <tt>true</tt>
* for this method.
*
* @return <tt>true</tt> if this metric supports training for classification
* problems, and <tt>false</tt> if it does not
*/
abstract public boolean supportsClassificationTraining();
/**
* Trains this metric on the given regression problem data set
* @param dataSet the data set to train on
* @throws UnsupportedOperationException if the metric can not be trained from regression problems
*/
abstract public void train(RegressionDataSet dataSet);
/**
* Trains this metric on the given regression problem data set
* @param dataSet the data set to train on
* @param parallel {@code true} if multiple threads should be used for
* training. {@code false} if it should be done in a single-threaded manner.
* @throws UnsupportedOperationException if the metric can not be trained from regression problems
*/
abstract public void train(RegressionDataSet dataSet, boolean parallel);
/**
* Some metrics might be special purpose, and not trainable for all types of data sets tasks.
* This method returns <tt>true</tt> if this metric supports training for regression
* problems, and <tt>false</tt> if it does not. <br>
* If a metric can learn from unlabeled data, it must return <tt>true</tt>
* for this method.
*
* @return <tt>true</tt> if this metric supports training for regression
* problems, and <tt>false</tt> if it does not
*/
abstract public boolean supportsRegressionTraining();
/**
* Returns <tt>true</tt> if the metric needs to be trained. This may be false if
* the metric allows the parameters to be specified beforehand. If the information
* was specified before hand, or does not need training, <tt>false</tt> is returned.
*
* @return <tt>true</tt> if the metric needs training, <tt>false</tt> if it does not.
*/
abstract public boolean needsTraining();
@Override
abstract public TrainableDistanceMetric clone();
/**
* Static helper method for training a distance metric only if it is needed.
* This method can be safely called for any Distance Metric.
*
* @param dm the distance metric to train
* @param dataset the data set to train from
*/
public static void trainIfNeeded(DistanceMetric dm, DataSet dataset)
{
trainIfNeeded(dm, dataset, false);
}
/**
* Static helper method for training a distance metric only if it is needed.
* This method can be safely called for any Distance Metric.
*
* @param dm the distance metric to train
* @param dataset the data set to train from
* @param parallel {@code true} if multiple threads should be used for
* training. {@code false} if it should be done in a single-threaded manner.
*/
public static void trainIfNeeded(DistanceMetric dm, DataSet dataset, boolean parallel)
{
if(!(dm instanceof TrainableDistanceMetric))
return;
TrainableDistanceMetric tdm = (TrainableDistanceMetric) dm;
if(!tdm.needsTraining())
return;
if(dataset instanceof RegressionDataSet)
tdm.train((RegressionDataSet) dataset, parallel);
else if(dataset instanceof ClassificationDataSet)
tdm.train((ClassificationDataSet) dataset, parallel);
else
tdm.train(dataset, parallel);
}
/**
* Static helper method for training a distance metric only if it is needed.
* This method can be safely called for any Distance Metric.
*
* @param dm the distance metric to train
* @param dataset the data set to train from
* @param threadpool the source of threads for parallel training. May be
* <tt>null</tt>, in which case {@link #trainIfNeeded(jsat.linear.distancemetrics.DistanceMetric, jsat.DataSet) }
* is used instead.
* @deprecated I WILL DELETE THIS METHOD SOON
*/
public static void trainIfNeeded(DistanceMetric dm, DataSet dataset, ExecutorService threadpool)
{
//TODO I WILL DELETE, JUST STUBBING FOR NOW TO MAKE LIFE EASY AS I DO ONE CODE SECTION AT A TIME
trainIfNeeded(dm, dataset);
}
/**
*
* @param <V>
* @param dm
* @param dataset
* @param threadpool
* @deprecated I WILL DELETE THIS METHOD SOON
*/
public static <V extends Vec> void trainIfNeeded(DistanceMetric dm, List<V> dataset, ExecutorService threadpool)
{
//TODO I WILL DELETE, JUST STUBBING FOR NOW TO MAKE LIFE EASY AS I DO ONE CODE SECTION AT A TIME
trainIfNeeded(dm, dataset, false);
}
/**
* Static helper method for training a distance metric only if it is needed.
* This method can be safely called for any Distance Metric.
*
* @param <V> the type of vectors in the list
* @param dm the distance metric to train
* @param dataset the data set to train from
*/
public static <V extends Vec> void trainIfNeeded(DistanceMetric dm, List<V> dataset)
{
trainIfNeeded(dm, dataset, false);
}
/**
*
* @param <V> the type of vectors in the list
* @param dm the distance metric to train
* @param dataset the data set to train from
* @param parallel {@code true} if multiple threads should be used for
* training. {@code false} if it should be done in a single-threaded manner.
*/
public static <V extends Vec> void trainIfNeeded(DistanceMetric dm, List<V> dataset, boolean parallel)
{
if(!(dm instanceof TrainableDistanceMetric))
return;
TrainableDistanceMetric tdm = (TrainableDistanceMetric) dm;
if(!tdm.needsTraining())
return;
if(dataset instanceof RegressionDataSet)
tdm.train((RegressionDataSet) dataset, parallel);
else if(dataset instanceof ClassificationDataSet)
tdm.train((ClassificationDataSet) dataset, parallel);
else
tdm.train(dataset, parallel);
}
}
| EdwardRaff/JSAT | JSAT/src/jsat/linear/distancemetrics/TrainableDistanceMetric.java | Java | gpl-3.0 | 9,780 |
package py.gov.senatics.asistente.util;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.hibernate.collection.PersistentBag;
import org.hibernate.collection.PersistentSet;
import py.gov.senatics.asistente.domain.BaseEntity;
import py.gov.senatics.asistente.exception.RegistroException;
public class ReflectionUtil {
static Logger log = Logger.getLogger(ReflectionUtil.class);
public static void main(String[] args) {
configuracionBasicaLog4j();
}
public static Object callGetter(Object bean, String fieldName)
throws IllegalStateException {
Method m = null;
Object ret = null;
try {
if (fieldName.indexOf(".") != -1) {
ret = PropertyUtils.getNestedProperty(bean, fieldName);
} else {
m = getReadMethod(bean.getClass(), fieldName);
ret = m.invoke(bean, new Object[] {});
}
} catch (Exception e) {
// por ahora s�lo me interesa el valor, cualquier otra excecpci�n la
// wrappeo
throw new IllegalStateException(e);
}
return ret;
}
public static String callGetterDynamic(Object bean, String campo,
List<Integer> parametros) {
String nombreMetodo = "get" + firstLetterToUppercase(campo);
String ret = "_SIN_VALOR_";
Class<?>[] parameterTypes = new Class<?>[parametros.size()];
Object[] paramsArray = parametros.toArray();
int i = 0;
for (Iterator<?> iterator = parametros.iterator(); iterator.hasNext();) {
Object object = iterator.next();
parameterTypes[i++] = object.getClass();
}
try {
Method m = bean.getClass().getMethod(nombreMetodo, parameterTypes);
// log.debug("A ejecutar: " + m.getName() + " (" + parametros +
// ")");
ret = (String) m.invoke(bean, paramsArray);
} catch (Exception e) {
throw new IllegalStateException("No se pudo obtener el m�todo : "
+ nombreMetodo, e);
}
return ret;
}
public static void callSetter(Object bean, String fieldName, Object valor)
throws IllegalStateException {
Method m = null;
try {
if (fieldName.indexOf(".") > 0) {
PropertyUtils.setNestedProperty(bean, fieldName, valor);
} else {
m = getWriteMethod(bean.getClass(), fieldName);
m.invoke(bean, new Object[] { valor });
}
} catch (Exception e) {
// por ahora s�lo me interesa llamar al getter, cualquier otra
// excepci�n la wrappeo
throw new IllegalStateException(e);
}
}
/**
*
*/
public static void configuracionBasicaLog4j() {
Properties conf = new Properties();
conf.put("log4j.rootLogger", "debug, myAppender");
conf.put("log4j.appender.myAppender",
"org.apache.log4j.ConsoleAppender");
conf.put("log4j.appender.myAppender.layout",
"org.apache.log4j.SimpleLayout");
PropertyConfigurator.configure(conf);
}
public static String describe(Object objeto) {
return describe(objeto, true);
}
/**
*
* Describe la clase y la instancia con el formato nombrePropiedad
* (tipoDeDato) : valor
*
* @param objeto
* @param conHash
* Indica si se imprimen el "de facto" toString ni los hashcodes
* @return
*/
public static String describe(Object objeto, Boolean conHash) {
String nombre = objeto.getClass().getSimpleName();
String nombreClase = objeto.getClass().getName();
StringBuffer ret = new StringBuffer();
StringBuffer sbNullValues = new StringBuffer("{");
PropertyDescriptor[] descs;
int i = 0;
try {
ret.append("<").append(nombre);
if (conHash)
ret.append(" hashCode:").append(objeto.hashCode());
ret.append(" >");
descs = obtenerPropertyDescriptors(objeto.getClass());
for (PropertyDescriptor pd : descs) {
i++;
if (!pd.getName().equalsIgnoreCase("class")) {
String stringValue = null;
String nombrePropiedad = pd.getName();
Method readMethod = pd.getReadMethod();
Method writeMethod = pd.getWriteMethod();
Object val = null;
if (readMethod != null && writeMethod != null)
val = readMethod.invoke(objeto, new Object[] {});
if (val != null) {
if (val instanceof BaseEntity) {
// Si la propiedad es de tipo Lazy no intentamos
// describir
// para evitar el LazyInitializationException...
if (objeto instanceof BaseEntity) {
ManyToOne m2o = getManyToOneAnnotation(
(BaseEntity) objeto, nombrePropiedad);
if (m2o != null
&& m2o.fetch() != FetchType.LAZY) {
stringValue = describeBaseEntity(conHash,
(BaseEntity) val);
} else {
stringValue = objeto.getClass()
.getSimpleName()
+ "."
+ nombrePropiedad + "(LAZY)";
}
} else {
stringValue = describeBaseEntity(conHash,
(BaseEntity) val);
}
} else if (val instanceof PersistentBag
|| val instanceof PersistentSet) {
// Esto daba un StackOverflow
// con los algunos mapeos ManyToMany
stringValue = val.getClass().getSimpleName()
+ " hascode: " + val.hashCode();
} else
stringValue = val.toString();
ret.append("{");
ret.append(nombrePropiedad);
ret.append("=");
ret.append(stringValue);
ret.append("}");
if (i < (descs.length - 1))
ret.append("; ");
} else {
sbNullValues.append(nombrePropiedad);
sbNullValues.append(",");
}
}
}
if (sbNullValues.length() > 1) { // quiere decir que hay valores
// nulos
sbNullValues.append(" = null}");
ret.append(sbNullValues);
}
ret.append("; Class: ").append(nombreClase);
ret.append("</").append(nombre).append(">");
} catch (Exception e) {
// Si pasa algo raro, se retorna el del super
ret = null;
}
if (ret == null) {
return null;
} else {
return ret.toString();
}
}
public static String firstLetterToUppercase(String campo) {
StringBuffer ret = new StringBuffer();
ret.append(campo.substring(0, 1).toUpperCase());
ret.append(campo.substring(1));
return ret.toString();
}
public static Class<?> getClassForField(Object bean, String fieldName) {
Class<?> ret = null;
try {
PropertyDescriptor pd = obtenerPropertyDescriptor(bean.getClass(),
fieldName);
ret = pd.getPropertyType();
} catch (Exception e) {
ret = Object.class;
}
return ret;
}
public static Field getDeclaredField(String fieldName, Class<?> resultClass) {
Field ret = null;
Class<?> clazz = resultClass;
if (clazz != null) {
while (!Object.class.equals(clazz) && ret == null) {
try {
ret = clazz.getDeclaredField(fieldName);
} catch (SecurityException e) {
ret = null;
break;
} catch (NoSuchFieldException e) {
ret = null;
clazz = clazz.getSuperclass();
} catch (NullPointerException npe) {
ret = null;
break;
}
}
}
return ret;
}
public static String[] getFieldList(Class<?> clazz)
throws IllegalStateException {
ArrayList<String> lista = new ArrayList<String>();
PropertyDescriptor[] descs = obtenerPropertyDescriptors(clazz);
for (PropertyDescriptor pd : descs) {
if (pd.getReadMethod() != null && pd.getWriteMethod() != null)
lista.add(pd.getName());
}
return lista.toArray(new String[0]);
}
/**
*
* Devuelve la lista de campos read/write del tipo elementType que no son de
* tipo Collection
*
* @param value
* @param elementType
* @return
*/
public static List<String> getFieldsType(Class<?> clazz,
Class<?> elementType) {
List<String> ret = new ArrayList<String>();
List<String> camposNoEncontrados = new ArrayList<String>();
String[] fields = getFieldList(clazz);
for (String fieldName : fields) {
try {
Field campo = clazz.getDeclaredField(fieldName);
if (!Collection.class.isAssignableFrom(campo.getType())) {
Method readMethod = getReadMethod(clazz, fieldName);
Method writeMethod = getWriteMethod(clazz, fieldName);
if (elementType.isAssignableFrom(campo.getType())
&& readMethod != null && writeMethod != null) {
// log.debug("agregando: " + fieldName);
ret.add(fieldName);
}
}
} catch (Exception e) {
camposNoEncontrados.add(fieldName);
// ret = new ArrayList<String>();
}
}
return ret;
}
public static List<String> getFieldsTypeCollection(Object value,
Class<?> elementType) {
List<String> ret = new ArrayList<String>();
String[] fields = getFieldList(value.getClass());
for (String fieldName : fields) {
try {
Field campo = value.getClass().getDeclaredField(fieldName);
if (Collection.class.isAssignableFrom(campo.getType())) {
ParameterizedType type = (ParameterizedType) campo
.getGenericType();
Class<?> tipo = (Class<?>) type.getActualTypeArguments()[0];
Object instanciaTipo = tipo.newInstance();
if (elementType.isAssignableFrom(instanciaTipo.getClass())) {
// log.debug("Es descendiente de: " +
// elementType.getName());
ret.add(fieldName);
}
}
} catch (Exception e) {
// log.error("No se pudo obtener la lista de campos.");
ret = new ArrayList<String>();
}
}
return ret;
}
public static String getGetterMethod(String fieldName) {
return "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1, fieldName.length());
}
public static Method getMethod(Object bean, String nombre,
Class<?> ... params) {
Method ret = null;
try {
ret = bean.getClass().getMethod(nombre, params);
} catch (Exception e) {
log.debug("No se pudo obtener el m�todo", e);
ret = null;
}
return ret;
}
/**
* Retorna el metodo solicitado, pero consume la excepcion.
*
* @param bean
* @param nombre
* @param params
* @return
*/
public static Method getMethodQuiet(Object bean, String nombre,
Class<?> ... params) {
Method m = null;
try {
m = bean.getClass().getMethod(nombre, params);
} catch (Exception e) {
// consumimos la excepcion
}
return m;
}
public static List<Method> getPublicMethods(Class<?> clazz) {
List<Method> ret = new ArrayList<Method>();
Method[] metodos = clazz.getDeclaredMethods();
for (int i = 0; i < metodos.length; i++) {
Method method = metodos[i];
int mods = method.getModifiers();
if (mods == Modifier.PUBLIC
|| (mods == (Modifier.PUBLIC | Modifier.ABSTRACT))) {
ret.add(method);
}
}
return ret;
}
public static List<String> getPublicMethodsName(Class<?> clazz,
boolean withParameters) {
List<String> ret = new ArrayList<String>();
List<Method> metodosPublicos = getPublicMethods(clazz);
for (Method method : metodosPublicos) {
int mods = method.getModifiers();
if (mods == Modifier.PUBLIC
|| (mods == (Modifier.PUBLIC | Modifier.ABSTRACT))) {
StringBuffer mDesc = new StringBuffer(method.getName());
if (withParameters) {
Class<?>[] params = method.getParameterTypes();
mDesc.append("(");
for (int j = 0; j < params.length; j++) {
Class<?> class1 = params[j];
mDesc.append(class1.getSimpleName());
if (j < (params.length - 1))
mDesc.append(",");
}
mDesc.append(")");
}
ret.add(mDesc.toString());
}
}
return ret;
}
public static Method getReadMethod(Class<?> clazz, String fieldName)
throws IllegalStateException, NoSuchFieldException {
PropertyDescriptor desc = obtenerPropertyDescriptor(clazz, fieldName);
return desc.getReadMethod();
}
/**
* Obtiene un valor para el tipo de dato. La clase debe tener un constructor
* que reciba un String como par�metro
*
* @param tipo
* @param valor
* @return
*/
public static Object getValue(String tipo, Object valor) {
Object ret = null;
try {
Constructor<?> constructor = Class.forName(tipo).getConstructor(
String.class);
ret = constructor.newInstance(valor);
} catch (Exception e) {
log.error("No se pudo instanciar: " + tipo + " con el valor: "
+ valor);
}
return ret;
}
public static Method getWriteMethod(Class<?> clazz, String fieldName)
throws IllegalStateException, NoSuchFieldException {
PropertyDescriptor desc = obtenerPropertyDescriptor(clazz, fieldName);
return desc.getWriteMethod();
}
public static Object invokeMethod(Method metodo, Object bean,
Object ... parametros) {
Object ret = null;
try {
ret = metodo.invoke(bean, parametros);
} catch (Exception e) {
ret = null;
log.debug("No se pudo invocar el metodo", e);
}
return ret;
}
public static PropertyDescriptor obtenerPropertyDescriptor(Class<?> clazz,
String fieldName) throws IllegalStateException,
NoSuchFieldException {
PropertyDescriptor ret = null;
PropertyDescriptor[] props = obtenerPropertyDescriptors(clazz);
for (PropertyDescriptor desc : props) {
if (desc.getName().equals(fieldName)) {
ret = desc;
}
}
if (ret == null) {
throw new NoSuchFieldException("No se encuentra el campo: "
+ fieldName + " en " + clazz.getName());
}
return ret;
}
/**
*
*
* @param destino
* @return
* @throws IntrospectionException
*/
public static PropertyDescriptor[] obtenerPropertyDescriptors(
Class<?> destino) throws IllegalStateException {
// Method ret = null;
BeanInfo info;
PropertyDescriptor[] ret;
Comparator<PropertyDescriptor> comparator = new Comparator<PropertyDescriptor>() {
@Override
public int compare(PropertyDescriptor o1, PropertyDescriptor o2) {
int ret = -1;
// hack para que siempre muestre primero el "id"
if (o1.getName().equals("id")) {
ret = -1;
} else if (o2.getName().equals("id")) {
ret = 1;
} else {
ret = o1.getName().compareTo(o2.getName());
}
return ret;
}
};
try {
info = Introspector.getBeanInfo(destino);
ret = info.getPropertyDescriptors();
Arrays.sort(ret, comparator);
return ret;
} catch (IntrospectionException e) {
throw new IllegalStateException(e);
}
}
public static Object read(Object fuente, String fieldName)
throws IllegalStateException {
try {
Method m = getReadMethod(fuente.getClass(), fieldName);
Object o = m.invoke(fuente, new Object[] {});
return o;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static Object read(PropertyDescriptor property, Object object)
throws IllegalStateException {
try {
return property.getReadMethod().invoke(object, new Object[] {});
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static Map<Integer, String> salidaComandoPorLinea(String cmdline) {
Map<Integer, String> ret = new HashMap<Integer, String>();
try {
Integer nroLinea = 1;
String line;
Process p = Runtime.getRuntime().exec(cmdline);
BufferedReader input = new BufferedReader(new InputStreamReader(
p.getInputStream()));
while ((line = input.readLine()) != null) {
ret.put(nroLinea, line);
nroLinea = new Integer(nroLinea + 1);
}
input.close();
} catch (Exception err) {
log.error("Fallo la ejecuci�n del comando:" + cmdline);
}
return ret;
}
/**
* Verifica que TODA la lista de campos tengan alg�n valor distinto de null
* cargado O si son String que no est�n vac�os
*
* @param oferente
* @param camposAControlar
* @return
*/
public static boolean tieneValoresNoVacios(Object entity,
String ... camposAControlar) {
boolean ret = false;
String[] campos = ReflectionUtil.getFieldList(entity.getClass());
for (String campo : campos) {
Object valorCargado = ReflectionUtil.callGetter(entity, campo);
if (valorCargado == null
|| ((valorCargado instanceof String && isBlank(valorCargado)))) {
ret = true;
}
if (ret)
break;
}
return ret;
}
public static boolean isBlank(Object valorCargado) {
boolean blank = false;
if (valorCargado != null)
blank = valorCargado.toString().trim().length() == 0;
return blank;
}
public static void write(PropertyDescriptor property, Object object,
Object value) throws IllegalStateException {
try {
property.getWriteMethod().invoke(object, value);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
public static String getCurrentMethodName() {
boolean doNext = false;
String ret = null;
StackTraceElement[] e = Thread.currentThread().getStackTrace();
for (StackTraceElement s : e) {
ret = s.getMethodName();
if (doNext) {
// log.logDebug(ret);
break;
}
doNext = ret.equals("getCurrentMethodName");
}
return ret;
}
/**
* @param conHash
* @param val
* @return
*/
private static String describeBaseEntity(Boolean conHash,
BaseEntity baseEBean) {
String stringValue;
if (conHash) {
stringValue = baseEBean.toString(true);
} else {
// Aca se supone que entra para obtener un
// cacheId
// entonces verifico que tenga algún valor y le
// pido su hash como "valor"
if (hasSomeValue(baseEBean)) {
stringValue = baseEBean.getClass().getSimpleName() + "-hash: "
+ describe(baseEBean, false);
} else {
stringValue = baseEBean.getClass().getName() + "-id: "
+ baseEBean.getId();
}
}
return stringValue;
}
/**
* Verifica que el bean tenga algún valor cargado distinto de null
*
* @param bean
* @return
*/
public static boolean hasSomeValue(Object bean) {
boolean ret = false;
if (bean != null) {
try {
String[] campos = getFieldList(bean.getClass());
for (String c : campos) {
Object obj = callGetter(bean, c);
if (obj instanceof BaseEntity) {
ret |= hasSomeValue(obj);
} else {
// TODO - afeltes : Ver esto cómo se trataría en las
// consultas
// por string vacío
// porque del form viene así, no viene null
// Si es un string y está vacío, considero que no tiene
// ningún
// valor
ret |= noEsNullVacioNiCollection(obj);
}
if (ret) // Si hay algún valor != null, ya retorno true
break;
}
} catch (Exception e) {
ret = false;
}
}
return ret;
}
public static boolean noEsNullVacioNiCollection(Object value) {
boolean ret = (value != null && !(value instanceof Collection) && !(value instanceof String))
|| (value instanceof String && !isBlank(value));
return ret;
}
public static ManyToOne getManyToOneAnnotation(BaseEntity entity,
String property) {
ManyToOne ret = null;
try {
Field field = entity.getClass().getDeclaredField(property);
Annotation[] anns = field.getAnnotations();
for (Annotation ann : anns) {
if (ann instanceof ManyToOne) {
ret = (ManyToOne) ann;
break;
}
}
} catch (NoSuchFieldException e) {
// log.debug("No se pudo obtener los annotations para la propiedad: "
// + property
// + " de la clase " + entity.getClass().getName());
ret = null;
}
return ret;
}
public static void camposVaciosANull(BaseEntity<Long> entity)
throws RegistroException {
List<String> camposString = ReflectionUtil.getFieldsType(
entity.getClass(), String.class);
for (String nombreCampo : camposString) {
String value = (String) ReflectionUtil.callGetter(entity,
nombreCampo);
if (BolsaUtil.isBlank(value)) {
ReflectionUtil.callSetter(entity, nombreCampo, null);
} else {// Convierto los campos String que tengan algun valor, a
// LATIN
value = BolsaUtil.convertToCharset(value, "UTF-8");
ReflectionUtil.callSetter(entity, nombreCampo, value);
}
}
}
}
| alefq/asistente-eventos | src/main/java/py/gov/senatics/asistente/util/ReflectionUtil.java | Java | gpl-3.0 | 20,962 |
package com.fansfoot.fansfoot.Adapters;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Debug;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Cache;
import com.android.volley.Network;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.BasicNetwork;
import com.android.volley.toolbox.DiskBasedCache;
import com.android.volley.toolbox.HurlStack;
import com.android.volley.toolbox.JsonObjectRequest;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.Profile;
import com.facebook.internal.WebDialog;
import com.fansfoot.fansfoot.API.ConstServer;
import com.fansfoot.fansfoot.API.FBLike;
import com.fansfoot.fansfoot.API.FacebookFansfoot;
import com.fansfoot.fansfoot.API.FacebookStatus;
import com.fansfoot.fansfoot.API.FansfootServer;
import com.fansfoot.fansfoot.API.Post;
import com.fansfoot.fansfoot.DefaultActivities.CommentPage;
import com.fansfoot.fansfoot.DefaultActivities.PostPage;
import com.fansfoot.fansfoot.DefaultActivities.YoutubePlayerActivity;
import com.fansfoot.fansfoot.DefaultPages.FbLikePage;
import com.fansfoot.fansfoot.MainActivity;
import com.fansfoot.fansfoot.R;
import com.fansfoot.fansfoot.models.LikeTransition;
import com.google.gson.Gson;
import com.squareup.picasso.Picasso;
import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
/**
* Created by kafir on 10-Dec-16.
*/
public class SearchHomeRecycleViewAdapter extends RecyclerView.Adapter<SearchHomeRecycleViewAdapter.SearchViewHolder> {
List<Post> UrlList;
Context context;
View mainView;
SharedPreferences sharedPreferencesBeta;
FBLike fblike;
RequestQueue mRequestQueue;
SearchHomeRecycleViewAdapter.SearchViewHolder viewHolders;
public SearchHomeRecycleViewAdapter( Context context,List<Post> urlList) {
UrlList = urlList;
this.context = context;
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(MainActivity.getContext().getCacheDir(), 1024 * 1024); // 1MB cap
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
}
@Override
public void onDetachedFromRecyclerView(RecyclerView recyclerView) {
super.onDetachedFromRecyclerView(recyclerView);
if (mRequestQueue != null) {
mRequestQueue.stop();
}
}
@Override
public SearchViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
mainView = LayoutInflater.from(context).inflate(R.layout.search_ls_elements,parent,false);
viewHolders = new SearchHomeRecycleViewAdapter.SearchViewHolder (mainView);
return viewHolders;
}
@Override
public void onBindViewHolder(final SearchViewHolder holder, final int position) {
holder.ImageDetail.setText(UrlList.get(position).getTital());
Log.d("picval",UrlList.get(position).getPic());
Log.d("width",""+UrlList.get(position).getHeight());
Log.d("height",""+UrlList.get(position).getWidth());
if(!UrlList.get(position).getPic().isEmpty() && UrlList.get(position).getWidth() !=0 && UrlList.get(position).getHeight() !=0) {
Picasso.with(context)
.load(UrlList.get(position).getPic())
.resize(UrlList.get(position).getWidth(), UrlList.get(position).getHeight())
.centerCrop()
.placeholder(R.drawable.post_img)
.into(holder.ViewImage);
}
holder.commentTextView.setText(UrlList.get(position).getComments().toString());
holder.likesTextView.setText(UrlList.get(position).getTotalLike().toString());
sharedPreferencesBeta =context.getSharedPreferences("FansFootPerfrence", Context.MODE_PRIVATE);
holder.likeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
String ModUrl = ConstServer._baseUrl +
ConstServer._type +
ConstServer._typePostLike +
ConstServer._ConCat +
ConstServer._PostID +
UrlList.get(position).getPostId() +
ConstServer._ConCat +
ConstServer._PostUserID +
sharedPreferencesBeta.getString("FbFFID", "") +
ConstServer._ConCat +
ConstServer.LikeStatus;
boolean fb_status = FacebookStatus.CheckFbLogin();
if (fb_status == true) {
JsonObjectRequest _JsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
ModUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("responceq", "" + response.toString());
Gson _Gson = new Gson();
fblike = _Gson.fromJson(response.toString(), FBLike.class);
String xVal = fblike.getMsg();
if (xVal.equals("like")) {
holder.dislikeBtn.setEnabled(true);
int vals = Integer.parseInt(holder.likesTextView.getText().toString());
Log.d("value", "" + vals);
int m = vals + 1;
Log.d("val", "" + m);
holder.likesTextView.setText(m + "");
view.setEnabled(false);
} else {
Toast.makeText(context, "Already Liked", Toast.LENGTH_SHORT).show();
}
Log.d("Text", xVal);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(_JsonObjectRequest);
} else {
boolean value = sharedPreferencesBeta.getString("FbFFID", "").isEmpty();
if(!value){
JsonObjectRequest _JsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
ModUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("responceq", "" + response.toString());
Gson _Gson = new Gson();
fblike = _Gson.fromJson(response.toString(), FBLike.class);
String xVal = fblike.getMsg();
if (xVal.equals("like")) {
holder.dislikeBtn.setEnabled(true);
int vals = Integer.parseInt(holder.likesTextView.getText().toString());
Log.d("value", "" + vals);
int m = vals + 1;
Log.d("val", "" + m);
holder.likesTextView.setText(m + "");
view.setEnabled(false);
} else {
Toast.makeText(context, "Already Liked", Toast.LENGTH_SHORT).show();
}
Log.d("Text", xVal);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(_JsonObjectRequest);
}
else{
Snackbar snackbar = Snackbar
.make(view, "Login using Facebook", Snackbar.LENGTH_SHORT)
.setAction("LOGIN", new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.JumpToFaceBookForLogin();
}
});
snackbar.show();
}
}
}
});
holder.dislikeBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(final View view) {
String ModUrl = ConstServer._baseUrl+
ConstServer._type+
ConstServer._typePostLike+
ConstServer._ConCat+
ConstServer._PostID+
UrlList.get(position).getPostId()+
ConstServer._ConCat+
ConstServer._PostUserID+
sharedPreferencesBeta.getString("FbFFID","")+
ConstServer._ConCat+
ConstServer.DisLikeStatus;
final boolean fb_status = FacebookStatus.CheckFbLogin();
if(fb_status == true) {
Log.d("valueMain", fb_status+"");
JsonObjectRequest _JsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
ModUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("responceq",""+response.toString());
Gson _Gson = new Gson();
fblike = _Gson.fromJson(response.toString(), FBLike.class);
String xVal = fblike.getMsg();
if(xVal.equals("unlike")){
holder.likeBtn.setEnabled(true);
int vals = Integer.parseInt(holder.likesTextView.getText().toString());
Log.d("value", "" + vals);
if(vals > 0) {
int m = vals - 1;
Log.d("val", "" + m);
holder.likesTextView.setText(m + "");
}
view.setEnabled(false);
}else{
Toast.makeText(context, "Already Disliked", Toast.LENGTH_SHORT).show();
}
Log.d("Text",xVal);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(_JsonObjectRequest);
}else {
boolean value = sharedPreferencesBeta.getString("FbFFID", "").isEmpty();
if(!value){
JsonObjectRequest _JsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
ModUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("responceq", "" + response.toString());
Gson _Gson = new Gson();
fblike = _Gson.fromJson(response.toString(), FBLike.class);
String xVal = fblike.getMsg();
if (xVal.equals("unlike")) {
holder.likeBtn.setEnabled(true);
int vals = Integer.parseInt(holder.likesTextView.getText().toString());
Log.d("value", "" + vals);
if(vals > 0) {
int m = vals - 1;
Log.d("val", "" + m);
holder.likesTextView.setText(m + "");
}
view.setEnabled(false);
} else {
Toast.makeText(context, "Already unliked", Toast.LENGTH_SHORT).show();
}
Log.d("Text", xVal);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(_JsonObjectRequest);
}
else{
Snackbar snackbar = Snackbar
.make(view, "Login using Facebook", Snackbar.LENGTH_SHORT)
.setAction("LOGIN", new View.OnClickListener() {
@Override
public void onClick(View view) {
holder.JumpToFaceBookForLogin();
}
});
snackbar.show();
}
}
}
});
}
@Override
public int getItemCount() {
return UrlList.size();
}
public class SearchViewHolder extends RecyclerView.ViewHolder {
RequestQueue mRequestQueue;
public TextView ImageDetail;
public ImageView ViewImage;
public TextView likesTextView;
public TextView commentTextView;
public ImageButton likeBtn;
public ImageButton dislikeBtn;
public ImageButton commentBtn;
SharedPreferences sharedPreferences;
SharedPreferences sharedPreferencesBeta;
FBLike fblike;
public boolean likeResponce = true;
public boolean DislikeResponce = true;
public void JumpToFaceBookForLogin(){
int x = getPosition();
LikeTransition likeTransition=new LikeTransition();
likeTransition.setPos(x);
likeTransition.setFragName("profile");
EventBus.getDefault().post(likeTransition);
}
public boolean JumpToAlterFacebookLikeAPI(String post_ID){
String userID = "";
if(FacebookStatus.CheckFbLogin()){
userID = AccessToken.getCurrentAccessToken().getUserId();
}
String ModUrl = ConstServer._baseUrl+
ConstServer._type+
ConstServer._typePostLike+
ConstServer._ConCat+
ConstServer._PostID+
post_ID+
ConstServer._ConCat+
ConstServer._PostUserID+
sharedPreferencesBeta.getString("FbFFID",userID)+
ConstServer._ConCat+
ConstServer.LikeStatus;
JsonObjectRequest _JsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
ModUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Gson _Gson = new Gson();
fblike = _Gson.fromJson(response.toString(), FBLike.class);
int x = fblike.getStatus();
if (x==1){
likeResponce = true;
}
Log.d("responceq",""+likeResponce);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
likeResponce = false;
Log.d("eresponce",""+likeResponce);
}
});
mRequestQueue.add(_JsonObjectRequest);
Log.d("responceq",""+likeResponce);
return likeResponce;
}
public boolean JumpToAlterFacebookDisLikeAPI(String post_ID){
String userID = "";
if(FacebookStatus.CheckFbLogin()){
userID = AccessToken.getCurrentAccessToken().getUserId();
}
String ModUrl = ConstServer._baseUrl+
ConstServer._type+
ConstServer._typePostLike+
ConstServer._ConCat+
ConstServer._PostID+
post_ID+
ConstServer._ConCat+
ConstServer._PostUserID+
sharedPreferencesBeta.getString("FbFFID",userID)+
ConstServer._ConCat+
ConstServer.DisLikeStatus;
Log.d("Makes",ModUrl);
JsonObjectRequest _JsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
ModUrl, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Makes",response.toString());
Gson _Gson = new Gson();
fblike = _Gson.fromJson(response.toString(), FBLike.class);
int x = fblike.getStatus();
if(x==1){
DislikeResponce = true;
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
DislikeResponce = false;
}
});
mRequestQueue.add(_JsonObjectRequest);
return DislikeResponce;
}
public SearchViewHolder(final View itemView) {
super(itemView);
sharedPreferences =MainActivity.getContext().getSharedPreferences("FacebookPrefrence", Context.MODE_PRIVATE);
sharedPreferencesBeta =MainActivity.getContext().getSharedPreferences("FansFootPerfrence", Context.MODE_PRIVATE);
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(MainActivity.getContext().getCacheDir(), 1024 * 1024); // 1MB cap
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
mRequestQueue.start();
}
ImageDetail = (TextView) itemView.findViewById(R.id.SearchTilteID);
ViewImage = (ImageView) itemView.findViewById(R.id.SearchMainImage);
likesTextView = (TextView) itemView.findViewById(R.id.SearchImagePointsValue);
commentTextView = (TextView) itemView.findViewById(R.id.SearchImageCommentPoints);
likeBtn = (ImageButton) itemView.findViewById(R.id.Searchlikebutton);
dislikeBtn = (ImageButton) itemView.findViewById(R.id.Searchdislikebutton);
commentBtn = (ImageButton) itemView.findViewById(R.id.Searchcommentbtn);
ImageDetail.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int x = getPosition();
String ImageURL = UrlList.get(x).getPic();
String ImageTitle = UrlList.get(x).getTital();
String ImageFBURL = UrlList.get(x).getFbCommnetUrl();
Intent intent = new Intent(MainActivity.getContext(), PostPage.class);
intent.putExtra("ImageTitle", ImageTitle);
intent.putExtra("ImageURL", ImageURL);
intent.putExtra("ImageFBURL", ImageFBURL);
MainActivity.getContext().startActivity(intent);
}
});
commentBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean fb_status = FacebookStatus.CheckFbLogin();
boolean value = sharedPreferencesBeta.getString("FbFFID","").isEmpty();
if(fb_status == true)
{
int x = getPosition();
String ImageFBURL = UrlList.get(x).getFbCommnetUrl();
Intent intent = new Intent(MainActivity.getContext(), CommentPage.class);
intent.putExtra("ImageFBURL", ImageFBURL);
MainActivity.getContext().startActivity(intent);
}else if(!value){
int x = getPosition();
String ImageFBURL = UrlList.get(x).getFbCommnetUrl();
Intent intent = new Intent(MainActivity.getContext(), CommentPage.class);
intent.putExtra("ImageFBURL", ImageFBURL);
MainActivity.getContext().startActivity(intent);
}else {
Snackbar snackbar = Snackbar
.make(view,R.string.LoginFacebookSnak,Snackbar.LENGTH_SHORT)
.setAction("LOGIN", new View.OnClickListener() {
@Override
public void onClick(View view) {
JumpToFaceBookForLogin();
}
});
snackbar.show();
}
}
});
}
}
}
| imxamarin/FansFoot | FansFoot/app/src/main/java/com/fansfoot/fansfoot/Adapters/SearchHomeRecycleViewAdapter.java | Java | gpl-3.0 | 23,103 |
package edu.princeton.cs.coursera.seamcarving;
/******************************************************************************
* Compilation: javac PrintSeams.java
* Execution: java PrintSeams input.png
* Dependencies: SeamCarver.java
*
* Read image from file specified as command-line argument. Print square
* of energies of pixels, a vertical seam, and a horizontal seam.
*
* % java PrintSeams 6x5.png
* 6x5.png (6-by-5 image)
*
* The table gives the dual-gradient energies of each pixel.
* The asterisks denote a minimum energy vertical or horizontal seam.
*
* Vertical seam: { 3 4 3 2 1 }
* 1000.00 1000.00 1000.00 1000.00* 1000.00 1000.00
* 1000.00 237.35 151.02 234.09 107.89* 1000.00
* 1000.00 138.69 228.10 133.07* 211.51 1000.00
* 1000.00 153.88 174.01* 284.01 194.50 1000.00
* 1000.00 1000.00* 1000.00 1000.00 1000.00 1000.00
* Total energy = 2414.973496
*
*
* Horizontal seam: { 2 2 1 2 1 2 }
* 1000.00 1000.00 1000.00 1000.00 1000.00 1000.00
* 1000.00 237.35 151.02* 234.09 107.89* 1000.00
* 1000.00* 138.69* 228.10 133.07* 211.51 1000.00*
* 1000.00 153.88 174.01 284.01 194.50 1000.00
* 1000.00 1000.00 1000.00 1000.00 1000.00 1000.00
* Total energy = 2530.681960
*
******************************************************************************/
import edu.princeton.cs.algs4.io.Picture;
import edu.princeton.cs.algs4.io.StdOut;
public class PrintSeams {
private static final boolean HORIZONTAL = true;
private static final boolean VERTICAL = false;
private static void printSeam(SeamCarver carver, int[] seam, boolean direction) {
double totalSeamEnergy = 0.0;
for (int row = 0; row < carver.height(); row++) {
for (int col = 0; col < carver.width(); col++) {
double energy = carver.energy(col, row);
String marker = " ";
if ((direction == HORIZONTAL && row == seam[col]) ||
(direction == VERTICAL && col == seam[row])) {
marker = "*";
totalSeamEnergy += energy;
}
StdOut.printf("%7.2f%s ", energy, marker);
}
StdOut.println();
}
// StdOut.println();
StdOut.printf("Total energy = %f\n", totalSeamEnergy);
StdOut.println();
StdOut.println();
}
public static void main(String[] args) {
Picture picture = new Picture(args[0]);
StdOut.printf("%s (%d-by-%d image)\n", args[0], picture.width(), picture.height());
StdOut.println();
StdOut.println("The table gives the dual-gradient energies of each pixel.");
StdOut.println("The asterisks denote a minimum energy vertical or horizontal seam.");
StdOut.println();
SeamCarver carver = new SeamCarver(picture);
StdOut.printf("Vertical seam: { ");
int[] verticalSeam = carver.findVerticalSeam();
for (int x : verticalSeam)
StdOut.print(x + " ");
StdOut.println("}");
printSeam(carver, verticalSeam, VERTICAL);
StdOut.printf("Horizontal seam: { ");
int[] horizontalSeam = carver.findHorizontalSeam();
for (int y : horizontalSeam)
StdOut.print(y + " ");
StdOut.println("}");
printSeam(carver, horizontalSeam, HORIZONTAL);
}
} | bramfoo/algorithms | src/main/java/edu/princeton/cs/coursera/seamcarving/PrintSeams.java | Java | gpl-3.0 | 3,482 |
package edu.mit.techscore.tscore;
import javax.swing.AbstractSpinnerModel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import edu.mit.techscore.regatta.Sail;
import javax.swing.JComponent;
import javax.swing.SpinnerModel;
/**
* Sail spinners allow changing the value of a sail intelligently,
* respecting the numerical portion of a sail, if one exists. This
* class goes out of its way to implement the obscure JSpinner API in
* order to make sure the editor and the model stay synced. For this
* reason, the model and the editor are both nested classes of this
* class, as they all work tightly together.
*
* This file is part of TechScore.
*
* TechScore is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TechScore 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 TechScore. If not, see <http://www.gnu.org/licenses/>.
*
*
* Created: Sun May 9 00:02:07 2010
*
* @author <a href="mailto:dayan@localhost">Dayan Paez</a>
* @version 1.0
*/
public class SailSpinner extends TSpinner {
private SailSpinnerModel model;
private SailFormattedField field;
/**
* Creates a new <code>SailSpinner</code> instance.
*
*/
public SailSpinner(Sail s) {
super();
this.model = new SailSpinnerModel(s);
this.setModel(model);
this.field = (SailFormattedField)this.getEditor();
this.field.setText(s.toString());
}
/**
* Creates and returns the SailFormattedField used for this
* spinner, as specified in the JSpinner documentation
*
* @param model ignored
* @return <code>SailFormattedField</code> object
*/
protected JComponent createEditor(SpinnerModel model) {
return new SailFormattedField();
}
public void setValue(Sail s) {
this.model.setValue(s);
this.fireStateChanged();
}
/**
* Sail spinner model
*
* This file is part of TechScore.
*
* TechScore is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* TechScore 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 TechScore. If not, see <http://www.gnu.org/licenses/>.
*
*
* Created: Sat May 8 16:46:01 2010
*
* @author <a href="mailto:dayan@localhost">Dayan Paez</a>
* @version 1.0
*/
private class SailSpinnerModel extends AbstractSpinnerModel {
private Sail currentSail;
/**
* Creates a new <code>SailSpinnerModel</code> instance.
*
*/
public SailSpinnerModel(Sail s) {
this.currentSail = s;
}
/**
* Sync up the value of this model with that of the spinner's
*
*/
private void sync() {
Sail s = new Sail(SailSpinner.this.field.getText());
if (!s.equals(this.currentSail))
this.setValue(s);
}
/**
* Get previous sail value, if numeric. Figure out what the value is
* from the spinner first.
*
*/
public Object getPreviousValue() {
Sail s1 = (Sail)this.getValue();
if (s1.getNumber() == 1)
return null;
Sail s2 = new Sail(s1.toString());
s2.add(-1);
return s2;
}
/**
* Get next sail value
*
*/
public Object getNextValue() {
Sail s1 = (Sail)this.getValue();
Sail s2 = new Sail(s1.toString());
s2.add(1);
return s2;
}
/**
* Set the current Sail value
*
*/
public void setValue(Object s) {
this.currentSail = (Sail)s;
SailSpinner.this.field.setText(this.currentSail.toString());
this.fireStateChanged();
}
/**
* Get the current sail
*
*/
public Object getValue() {
this.sync();
return this.currentSail;
}
}
/**
* A regular ol' text field. In the future, this might do some more
* damage.
*
* Created: Sat May 8 09:41:12 2010
*
* @author <a href="mailto:dayan@localhost">Dayan Paez</a>
* @version 1.0
*/
public class SailFormattedField extends JTextField {
/**
* Creates a new <code>SailFormattedField</code> instance.
*
*/
public SailFormattedField() {
super();
}
public SailFormattedField(Sail s) {
super(s.toString());
}
}
}
| RandomWidgets/TechScore | src/edu/mit/techscore/tscore/SailSpinner.java | Java | gpl-3.0 | 5,115 |
package meta;
import ast.StatementNull;
public class WrStatementNull extends WrStatement {
public WrStatementNull(StatementNull hidden) {
super(hidden);
}
@Override
StatementNull getHidden() { return (StatementNull ) hidden; }
@Override
public void accept(WrASTVisitor visitor, WrEnv env) {
}
}
| joseoliv/Cyan | meta/WrStatementNull.java | Java | gpl-3.0 | 312 |
package eu.faircode.netguard;
/*
This file is part of NetGuard.
NetGuard is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
NetGuard 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 NetGuard. If not, see <http://www.gnu.org/licenses/>.
Copyright 2015 by Marcel Bokhorst (M66B)
*/
import android.app.Notification;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.VpnService;
import android.os.PowerManager;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import java.util.Map;
public class Receiver extends BroadcastReceiver {
private static final String TAG = "NetGuard.Receiver";
@Override
public void onReceive(final Context context, Intent intent) {
Log.i(TAG, "Received " + intent);
Util.logExtras(intent);
if (Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())) {
// Application added
if (!intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
// Show notification
int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
notifyApplication(uid, context);
}
} else if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())) {
// Application removed
if (intent.getBooleanExtra(Intent.EXTRA_DATA_REMOVED, false)) {
// Remove settings
String packageName = intent.getData().getSchemeSpecificPart();
Log.i(TAG, "Deleting settings package=" + packageName);
context.getSharedPreferences("wifi", Context.MODE_PRIVATE).edit().remove(packageName).apply();
context.getSharedPreferences("other", Context.MODE_PRIVATE).edit().remove(packageName).apply();
context.getSharedPreferences("screen_wifi", Context.MODE_PRIVATE).edit().remove(packageName).apply();
context.getSharedPreferences("screen_other", Context.MODE_PRIVATE).edit().remove(packageName).apply();
context.getSharedPreferences("roaming", Context.MODE_PRIVATE).edit().remove(packageName).apply();
int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
if (uid > 0)
NotificationManagerCompat.from(context).cancel(uid);
}
} else {
// Upgrade settings
upgrade(true, context);
// Start service
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (prefs.getBoolean("enabled", false))
try {
if (VpnService.prepare(context) == null)
SinkholeService.start("receiver", context);
} catch (Throwable ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
Util.sendCrashReport(ex, context);
}
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (pm.isInteractive())
SinkholeService.reloadStats("receiver", context);
}
}
public static void notifyApplication(int uid, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
try {
// Get application info
PackageManager pm = context.getPackageManager();
String[] packages = pm.getPackagesForUid(uid);
if (packages.length < 1)
throw new PackageManager.NameNotFoundException(Integer.toString(uid));
ApplicationInfo info = pm.getApplicationInfo(packages[0], 0);
String name = (String) pm.getApplicationLabel(info);
// Check system application
boolean system = ((info.flags & (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0);
boolean manage_system = prefs.getBoolean("manage_system", false);
if (system && !manage_system)
return;
// Build notification
Intent main = new Intent(context, ActivityMain.class);
main.putExtra(ActivityMain.EXTRA_SEARCH, name);
PendingIntent pi = PendingIntent.getActivity(context, 999, main, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_security_white_24dp)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(R.string.msg_installed, name))
.setContentIntent(pi)
.setCategory(Notification.CATEGORY_STATUS)
.setVisibility(Notification.VISIBILITY_SECRET)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setAutoCancel(true);
// Get defaults
SharedPreferences prefs_wifi = context.getSharedPreferences("wifi", Context.MODE_PRIVATE);
SharedPreferences prefs_other = context.getSharedPreferences("other", Context.MODE_PRIVATE);
boolean wifi = prefs_wifi.getBoolean(packages[0], prefs.getBoolean("whitelist_wifi", true));
boolean other = prefs_other.getBoolean(packages[0], prefs.getBoolean("whitelist_other", true));
// Build Wi-Fi action
Intent riWifi = new Intent(context, SinkholeService.class);
riWifi.putExtra(SinkholeService.EXTRA_COMMAND, SinkholeService.Command.set);
riWifi.putExtra(SinkholeService.EXTRA_NETWORK, "wifi");
riWifi.putExtra(SinkholeService.EXTRA_UID, uid);
riWifi.putExtra(SinkholeService.EXTRA_PACKAGE, packages[0]);
riWifi.putExtra(SinkholeService.EXTRA_BLOCKED, !wifi);
PendingIntent piWifi = PendingIntent.getService(context, uid, riWifi, PendingIntent.FLAG_UPDATE_CURRENT);
notification.addAction(
wifi ? R.drawable.wifi_on : R.drawable.wifi_off,
context.getString(wifi ? R.string.title_allow : R.string.title_block),
piWifi
);
// Build mobile action
Intent riOther = new Intent(context, SinkholeService.class);
riOther.putExtra(SinkholeService.EXTRA_COMMAND, SinkholeService.Command.set);
riOther.putExtra(SinkholeService.EXTRA_NETWORK, "other");
riOther.putExtra(SinkholeService.EXTRA_UID, uid);
riOther.putExtra(SinkholeService.EXTRA_PACKAGE, packages[0]);
riOther.putExtra(SinkholeService.EXTRA_BLOCKED, !other);
PendingIntent piOther = PendingIntent.getService(context, uid + 10000, riOther, PendingIntent.FLAG_UPDATE_CURRENT);
notification.addAction(
other ? R.drawable.other_on : R.drawable.other_off,
context.getString(other ? R.string.title_allow : R.string.title_block),
piOther
);
// Show notification
NotificationManagerCompat.from(context).notify(uid, notification.build());
} catch (PackageManager.NameNotFoundException ex) {
Log.e(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
}
}
public static void upgrade(boolean initialized, Context context) {
synchronized (context.getApplicationContext()) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int oldVersion = prefs.getInt("version", -1);
int newVersion = Util.getSelfVersionCode(context);
if (oldVersion == newVersion)
return;
Log.i(TAG, "Upgrading from version " + oldVersion + " to " + newVersion);
SharedPreferences.Editor editor = prefs.edit();
if (initialized) {
if (oldVersion < 38) {
Log.i(TAG, "Converting screen wifi/mobile");
editor.putBoolean("screen_wifi", prefs.getBoolean("unused", false));
editor.putBoolean("screen_other", prefs.getBoolean("unused", false));
editor.remove("unused");
SharedPreferences unused = context.getSharedPreferences("unused", Context.MODE_PRIVATE);
SharedPreferences screen_wifi = context.getSharedPreferences("screen_wifi", Context.MODE_PRIVATE);
SharedPreferences screen_other = context.getSharedPreferences("screen_other", Context.MODE_PRIVATE);
Map<String, ?> punused = unused.getAll();
SharedPreferences.Editor edit_screen_wifi = screen_wifi.edit();
SharedPreferences.Editor edit_screen_other = screen_other.edit();
for (String key : punused.keySet()) {
edit_screen_wifi.putBoolean(key, (Boolean) punused.get(key));
edit_screen_other.putBoolean(key, (Boolean) punused.get(key));
}
edit_screen_wifi.apply();
edit_screen_other.apply();
// TODO: delete unused
}
} else {
editor.putBoolean("whitelist_wifi", false);
editor.putBoolean("whitelist_other", false);
}
editor.putInt("version", newVersion);
editor.apply();
}
}
} | marco-scavuzzo/NetGuard | app/src/main/java/eu/faircode/netguard/Receiver.java | Java | gpl-3.0 | 10,289 |
/*
* Copyright (C) 2010-2011 Steven Van Bael <[email protected]>
*
* 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 3 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
*/
package be.vbsteven.bmtodesk;
import android.content.Context;
import android.content.SharedPreferences;
/**
* global constants and a few utility methods used throughout the application
*
* @author steven
*/
public class Global {
public static final String TAG = "bookmarktodesktop"; // for logging
public static final String PREFS = "be.vbsteven.bmtodesk_preferences";
public static final String DOMAIN_PROD = "https://bookmarktodesktop.appspot.com";
public static final String DOMAIN_DEV = "https://bookmarktodesktopdev.appspot.com";
public static final boolean DEBUG = false;
// constants for preferences
public static final String USERNAME = "USERNAME";
public static final String PASSWORD = "PASSWORD";
public static final String FASTSHARING = "FASTSHARING";
public static final String HIDECONFIRMATION = "HIDECONFIRMATION";
private static final String SEENYOUTUBEVIDEO = "SEENYOUTUBEVIDEO";
// constants used for adding extras to intents (prefixed to avoid conflicts)
public static final String EXTRA_TITLE = "bmtodesk.TITLE";
public static final String EXTRA_URL = "bmtodesk.URL";
public static final String EXTRA_COUNT = "bmtodesk.COUNT";
/**
* utility method for retrieving the shared preferences for this app
*
* @param context
* @return the shared preferences object for this app
*/
public static SharedPreferences getPrefs(Context context) {
return context
.getSharedPreferences(PREFS, Context.MODE_WORLD_WRITEABLE);
}
/**
* @param context
* @return username of the user or "" if not found
*/
public static String getUsername(Context context) {
return getPrefs(context).getString(USERNAME, "");
}
/**
* @param context
* @return password of the user or "" if not found
*/
public static String getPassword(Context context) {
return getPrefs(context).getString(PASSWORD, "");
}
/**
* saves the user credentials to the preferences
*
* @param context
* @param username
* @param password
*/
public static void saveUsernameAndPassword(Context context,
String username, String password) {
getPrefs(context).edit().putString(USERNAME, username)
.putString(PASSWORD, password).commit();
}
/**
* checks if the user configured an account
*
* @param context
* @return true if we have user credentials
*/
public static boolean hasUserCredentials(Context context) {
String username = getUsername(context);
String password = getPassword(context);
return (!username.equals("") && !password.equals(""));
}
/**
* @param context
* @return true if the user has fast sharing enabled
*/
public static boolean isFastSharing(Context context) {
return getPrefs(context).getBoolean(FASTSHARING, false);
}
/**
* @param context
* @return true if the user does not want to see the sharing finished screen
*/
public static boolean isHideConfirmation(Context context) {
return getPrefs(context).getBoolean(HIDECONFIRMATION, false);
}
/**
* @param context
* @return true if the user has already seen the popup for the intro video
*/
public static boolean hasSeenYoutubeVideoPopup(Context context) {
return getPrefs(context).getBoolean(SEENYOUTUBEVIDEO, false);
}
/**
* sets if the user has seen the popup for the intro video
* @param context
*/
public static void setSeenYoutubeVideoPopup(Context context) {
getPrefs(context).edit().putBoolean(SEENYOUTUBEVIDEO, true).commit();
}
/**
* @param context
* @return true if the user wants sharing to happen in the background
*/
public static boolean isBackgroundSharing(Context context) {
return getPrefs(context).getBoolean("BACKGROUNDSHARING", false);
}
public static String getDomain() {
if (DEBUG) {
return DOMAIN_DEV;
} else {
return DOMAIN_PROD;
}
}
public static boolean isDebug() {
return DEBUG;
}
public static boolean isPaid(Context context) {
return Licensing.verify(context);
}
public static boolean hasSeenFreemiumMessage(Context context) {
return getPrefs(context).getBoolean("seenfreemiummessage", false);
}
public static void markFreemiumPopupSeen(Context context) {
getPrefs(context).edit().putBoolean("seenfreemiummessage", true).commit();
}
}
| vbsteven/bookmarktodesktop-android-application | src/be/vbsteven/bmtodesk/Global.java | Java | gpl-3.0 | 4,987 |
/*
* GNU GENERAL LICENSE
* Copyright (C) 2014 - 2021 Lobo Evolution
*
* 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
* verion 3 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 License for more details.
*
* You should have received a copy of the GNU General Public
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact info: [email protected]
*/
package org.loboevolution.html.node;
/**
* A Node containing a doctype.
*
*
*
*/
public interface DocumentType extends Node {
/**
* <p>getName.</p>
*
* @return a {@link java.lang.String} object.
*/
String getName();
/**
* <p>getPublicId.</p>
*
* @return a {@link java.lang.String} object.
*/
String getPublicId();
/**
* <p>getSystemId.</p>
*
* @return a {@link java.lang.String} object.
*/
String getSystemId();
}
| oswetto/LoboEvolution | LoboW3C/src/main/java/org/loboevolution/html/node/DocumentType.java | Java | gpl-3.0 | 1,208 |
/*
*
* This file is part of the SIRIUS library for analyzing MS and MS/MS data
*
* Copyright (C) 2013-2020 Kai Dührkop, Markus Fleischauer, Marcus Ludwig, Martin A. Hoffman and Sebastian Böcker,
* Chair of Bioinformatics, Friedrich-Schilller University.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with SIRIUS. If not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>
*/
package de.unijena.bioinf.sirius;
import org.jetbrains.annotations.Nullable;
@FunctionalInterface
public interface SiriusFactory {
Sirius sirius(@Nullable String profile);
default Sirius sirius() {
return sirius(null);
}
}
| kaibioinfo/sirius | sirius_api/src/main/java/de/unijena/bioinf/sirius/SiriusFactory.java | Java | gpl-3.0 | 1,189 |
/*
* Copyright (c) 2015 Brandon Lyon
*
* This file is part of Emerge Game Engine (Emerge)
*
* Emerge is free software: you can redistribute it and/or modify
* it under the terms of version 3 of the GNU General Public License as
* published by the Free Software Foundation.
*
* Emerge 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 Emerge. If not, see <http://www.gnu.org/licenses/>.
*/
package net.etherous.emerge;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import net.etherous.emerge.collection.ArrayIterator;
public class Launcher
{
public static void main (final String[] args)
{
final List<String> configFiles = new ArrayList<> ();
String gameId = null;
final Iterator<String> argIt = new ArrayIterator<> (args);
while (argIt.hasNext ())
{
try
{
final String arg = argIt.next ();
switch (arg.toLowerCase ())
{
case "-c":
case "-config":
configFiles.add (argIt.next ());
break;
case "-g":
case "-game":
gameId = argIt.next ();
break;
case "-debug":
System.setProperty (Game.EMERGE_DEBUG_ENV, "true");
break;
}
}
catch (final Throwable t)
{
t.printStackTrace ();
}
}
Game.launch (configFiles.toArray (new String[configFiles.size ()]), gameId);
}
}
| Etherous/Emerge | core/src/main/java/net/etherous/emerge/Launcher.java | Java | gpl-3.0 | 1,890 |
/*
* This file is part of Applied Energistics 2.
* Copyright (c) 2013 - 2014, AlgorithmX2, All rights reserved.
*
* Applied Energistics 2 is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Applied Energistics 2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Applied Energistics 2. If not, see <http://www.gnu.org/licenses/lgpl>.
*/
package appeng.crafting;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import cpw.mods.fml.common.FMLCommonHandler;
import appeng.api.AEApi;
import appeng.api.config.Actionable;
import appeng.api.networking.crafting.ICraftingGrid;
import appeng.api.networking.crafting.ICraftingPatternDetails;
import appeng.api.networking.security.BaseActionSource;
import appeng.api.storage.data.IAEItemStack;
import appeng.api.storage.data.IItemList;
import appeng.container.ContainerNull;
import appeng.me.cluster.implementations.CraftingCPUCluster;
import appeng.util.Platform;
public class CraftingTreeProcess
{
private final CraftingTreeNode parent;
final ICraftingPatternDetails details;
private final CraftingJob job;
private final Map<CraftingTreeNode, Long> nodes = new HashMap<CraftingTreeNode, Long>();
private final int depth;
boolean possible = true;
private World world;
private long crafts = 0;
private boolean containerItems;
private boolean limitQty;
private boolean fullSimulation;
private long bytes = 0;
public CraftingTreeProcess( final ICraftingGrid cc, final CraftingJob job, final ICraftingPatternDetails details, final CraftingTreeNode craftingTreeNode, final int depth )
{
this.parent = craftingTreeNode;
this.details = details;
this.job = job;
this.depth = depth;
final World world = job.getWorld();
if( details.isCraftable() )
{
final IAEItemStack[] list = details.getInputs();
final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
final IAEItemStack[] is = details.getInputs();
for( int x = 0; x < ic.getSizeInventory(); x++ )
{
ic.setInventorySlotContents( x, is[x] == null ? null : is[x].getItemStack() );
}
FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) world ), details.getOutput( ic, world ), ic );
for( int x = 0; x < ic.getSizeInventory(); x++ )
{
final ItemStack g = ic.getStackInSlot( x );
if( g != null && g.stackSize > 1 )
{
this.fullSimulation = true;
}
}
for( final IAEItemStack part : details.getCondensedInputs() )
{
final ItemStack g = part.getItemStack();
boolean isAnInput = false;
for( final IAEItemStack a : details.getCondensedOutputs() )
{
if( g != null && a != null && a.equals( g ) )
{
isAnInput = true;
}
}
if( isAnInput )
{
this.limitQty = true;
}
if( g.getItem().hasContainerItem( g ) )
{
this.limitQty = this.containerItems = true;
}
}
final boolean complicated = false;
if( this.containerItems || complicated )
{
for( int x = 0; x < list.length; x++ )
{
final IAEItemStack part = list[x];
if( part != null )
{
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() );
}
}
}
else
{
// this is minor different then below, this slot uses the pattern, but kinda fudges it.
for( final IAEItemStack part : details.getCondensedInputs() )
{
for( int x = 0; x < list.length; x++ )
{
final IAEItemStack comparePart = list[x];
if( part != null && part.equals( comparePart ) )
{
// use the first slot...
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, x, depth + 1 ), part.getStackSize() );
break;
}
}
}
}
}
else
{
for( final IAEItemStack part : details.getCondensedInputs() )
{
final ItemStack g = part.getItemStack();
boolean isAnInput = false;
for( final IAEItemStack a : details.getCondensedOutputs() )
{
if( g != null && a != null && a.equals( g ) )
{
isAnInput = true;
}
}
if( isAnInput )
{
this.limitQty = true;
}
}
for( final IAEItemStack part : details.getCondensedInputs() )
{
this.nodes.put( new CraftingTreeNode( cc, job, part.copy(), this, -1, depth + 1 ), part.getStackSize() );
}
}
}
boolean notRecursive( final ICraftingPatternDetails details )
{
return this.parent == null || this.parent.notRecursive( details );
}
long getTimes( final long remaining, final long stackSize )
{
if( this.limitQty || this.fullSimulation )
{
return 1;
}
return ( remaining / stackSize ) + ( remaining % stackSize != 0 ? 1 : 0 );
}
void request( final MECraftingInventory inv, final long i, final BaseActionSource src ) throws CraftBranchFailure, InterruptedException
{
this.job.handlePausing();
if( this.fullSimulation )
{
final InventoryCrafting ic = new InventoryCrafting( new ContainerNull(), 3, 3 );
for( final Entry<CraftingTreeNode, Long> entry : this.nodes.entrySet() )
{
final IAEItemStack item = entry.getKey().getStack( entry.getValue() );
final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize(), src );
ic.setInventorySlotContents( entry.getKey().getSlot(), stack.getItemStack() );
}
FMLCommonHandler.instance().firePlayerCraftingEvent( Platform.getPlayer( (WorldServer) this.world ), this.details.getOutput( ic, this.world ), ic );
for( int x = 0; x < ic.getSizeInventory(); x++ )
{
ItemStack is = ic.getStackInSlot( x );
is = Platform.getContainerItem( is );
final IAEItemStack o = AEApi.instance().storage().createItemStack( is );
if( o != null )
{
this.bytes++;
inv.injectItems( o, Actionable.MODULATE, src );
}
}
}
else
{
// request and remove inputs...
for( final Entry<CraftingTreeNode, Long> entry : this.nodes.entrySet() )
{
final IAEItemStack item = entry.getKey().getStack( entry.getValue() );
final IAEItemStack stack = entry.getKey().request( inv, item.getStackSize() * i, src );
if( this.containerItems )
{
final ItemStack is = Platform.getContainerItem( stack.getItemStack() );
final IAEItemStack o = AEApi.instance().storage().createItemStack( is );
if( o != null )
{
this.bytes++;
inv.injectItems( o, Actionable.MODULATE, src );
}
}
}
}
// assume its possible.
// add crafting results..
for( final IAEItemStack out : this.details.getCondensedOutputs() )
{
final IAEItemStack o = out.copy();
o.setStackSize( o.getStackSize() * i );
inv.injectItems( o, Actionable.MODULATE, src );
}
this.crafts += i;
}
void dive( final CraftingJob job )
{
job.addTask( this.getAmountCrafted( this.parent.getStack( 1 ) ), this.crafts, this.details, this.depth );
for( final CraftingTreeNode pro : this.nodes.keySet() )
{
pro.dive( job );
}
job.addBytes( 8 + this.crafts + this.bytes );
}
IAEItemStack getAmountCrafted( IAEItemStack what2 )
{
for( final IAEItemStack is : this.details.getCondensedOutputs() )
{
if( is.equals( what2 ) )
{
what2 = what2.copy();
what2.setStackSize( is.getStackSize() );
return what2;
}
}
// more fuzzy!
for( final IAEItemStack is : this.details.getCondensedOutputs() )
{
if( is.getItem() == what2.getItem() && ( is.getItem().isDamageable() || is.getItemDamage() == what2.getItemDamage() ) )
{
what2 = is.copy();
what2.setStackSize( is.getStackSize() );
return what2;
}
}
throw new IllegalStateException( "Crafting Tree construction failed." );
}
void setSimulate()
{
this.crafts = 0;
this.bytes = 0;
for( final CraftingTreeNode pro : this.nodes.keySet() )
{
pro.setSimulate();
}
}
void setJob( final MECraftingInventory storage, final CraftingCPUCluster craftingCPUCluster, final BaseActionSource src ) throws CraftBranchFailure
{
craftingCPUCluster.addCrafting( this.details, this.crafts );
for( final CraftingTreeNode pro : this.nodes.keySet() )
{
pro.setJob( storage, craftingCPUCluster, src );
}
}
void getPlan( final IItemList<IAEItemStack> plan )
{
for( IAEItemStack i : this.details.getOutputs() )
{
i = i.copy();
i.setCountRequestable( i.getStackSize() * this.crafts );
plan.addRequestable( i );
}
for( final CraftingTreeNode pro : this.nodes.keySet() )
{
pro.getPlan( plan );
}
}
}
| itachi1706/Applied-Energistics-2 | src/main/java/appeng/crafting/CraftingTreeProcess.java | Java | gpl-3.0 | 9,088 |
// Fig. 25.3: SliderFrame.java
// Using JSliders to size an oval.
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeListener;
import javax.swing.event.ChangeEvent;
public class SliderFrame extends JFrame
{
private JSlider diameterJSlider; // slider to select diameter
private OvalPanel myPanel; // panel to draw circle
// no-argument constructor
public SliderFrame()
{
super( "Slider Demo" );
myPanel = new OvalPanel(); // create panel to draw circle
myPanel.setBackground( Color.YELLOW ); // set background to yellow
// set up JSlider to control diameter value
diameterJSlider =
new JSlider( SwingConstants.HORIZONTAL, 0, 200, 10 );
diameterJSlider.setMajorTickSpacing( 10 ); // create tick every 10
diameterJSlider.setPaintTicks( true ); // paint ticks on slider
// register JSlider event listener
diameterJSlider.addChangeListener(
new ChangeListener() // anonymous inner class
{
// handle change in slider value
public void stateChanged( ChangeEvent e )
{
myPanel.setDiameter( diameterJSlider.getValue() );
} // end method stateChanged
} // end anonymous inner class
); // end call to addChangeListener
add( diameterJSlider, BorderLayout.SOUTH ); // add slider to frame
add( myPanel, BorderLayout.CENTER ); // add panel to frame
} // end SliderFrame constructor
} // end class SliderFrame
/**************************************************************************
* (C) Copyright 1992-2012 by Deitel & Associates, Inc. and *
* Pearson Education, Inc. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have used their *
* best efforts in preparing the book. These efforts include the *
* development, research, and testing of the theories and programs *
* to determine their effectiveness. The authors and publisher make *
* no warranty of any kind, expressed or implied, with regard to these *
* programs or to the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for incidental or *
* consequential damages in connection with, or arising out of, the *
* furnishing, performance, or use of these programs. *
*************************************************************************/ | obulpathi/java | deitel/ch25/fig25_02-04/SliderFrame.java | Java | gpl-3.0 | 2,742 |
/*
* Copyright (C) 2010-2014 Thialfihar <[email protected]>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain;
import android.os.Environment;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.File;
import java.net.Proxy;
public final class Constants {
public static final boolean DEBUG = BuildConfig.DEBUG;
public static final boolean DEBUG_LOG_DB_QUERIES = false;
public static final boolean DEBUG_EXPLAIN_QUERIES = false;
public static final boolean DEBUG_SYNC_REMOVE_CONTACTS = false;
public static final boolean DEBUG_KEYSERVER_SYNC = false;
public static final String TAG = DEBUG ? "Keychain D" : "Keychain";
public static final String PACKAGE_NAME = "org.sufficientlysecure.keychain";
public static final String ACCOUNT_NAME = DEBUG ? "OpenKeychain D" : "OpenKeychain";
public static final String ACCOUNT_TYPE = BuildConfig.ACCOUNT_TYPE;
public static final String CUSTOM_CONTACT_DATA_MIME_TYPE = "vnd.android.cursor.item/vnd.org.sufficientlysecure.keychain.key";
public static final String PROVIDER_AUTHORITY = BuildConfig.PROVIDER_CONTENT_AUTHORITY;
public static final String TEMP_FILE_PROVIDER_AUTHORITY = BuildConfig.APPLICATION_ID + ".tempstorage";
public static final String CLIPBOARD_LABEL = "Keychain";
// as defined in http://tools.ietf.org/html/rfc3156
public static final String MIME_TYPE_KEYS = "application/pgp-keys";
// NOTE: don't use application/pgp-encrypted It only holds the version number!
public static final String MIME_TYPE_ENCRYPTED = "application/octet-stream";
// NOTE: Non-standard alternative, better use this, because application/octet-stream is too unspecific!
// also see https://tools.ietf.org/html/draft-bray-pgp-message-00
public static final String MIME_TYPE_ENCRYPTED_ALTERNATE = "application/pgp-message";
public static final String MIME_TYPE_TEXT = "text/plain";
public static final String FILE_EXTENSION_PGP_MAIN = ".pgp";
public static final String FILE_EXTENSION_PGP_ALTERNATE = ".gpg";
public static final String FILE_EXTENSION_ASC = ".asc";
public static final String FILE_BACKUP_PREFIX = "backup_";
public static final String FILE_EXTENSION_BACKUP_SECRET = ".sec.asc";
public static final String FILE_EXTENSION_BACKUP_PUBLIC = ".pub.asc";
public static final String FILE_ENCRYPTED_BACKUP_PREFIX = "backup_";
// actually it is ASCII Armor, so .asc would be more accurate, but Android displays a nice icon for .pgp files!
public static final String FILE_EXTENSION_ENCRYPTED_BACKUP_SECRET = ".sec.pgp";
public static final String FILE_EXTENSION_ENCRYPTED_BACKUP_PUBLIC = ".pub.pgp";
// used by QR Codes (Guardian Project, Monkeysphere compatiblity)
public static final String FINGERPRINT_SCHEME = "openpgp4fpr";
public static final String BOUNCY_CASTLE_PROVIDER_NAME = BouncyCastleProvider.PROVIDER_NAME;
// prefix packagename for exported Intents
// as described in http://developer.android.com/guide/components/intents-filters.html
public static final String INTENT_PREFIX = PACKAGE_NAME + ".action.";
public static final String EXTRA_PREFIX = PACKAGE_NAME + ".";
public static final int TEMPFILE_TTL = 24 * 60 * 60 * 1000; // 1 day
// the maximal length of plaintext to read in encrypt/decrypt text activities
public static final int TEXT_LENGTH_LIMIT = 1024 * 50;
public static final String SAFESLINGER_SERVER = "safeslinger-openpgp.appspot.com";
public static final class Path {
public static final File APP_DIR = new File(Environment.getExternalStorageDirectory(), "OpenKeychain");
}
public static final class Notification {
public static final int PASSPHRASE_CACHE = 1;
public static final int KEYSERVER_SYNC_FAIL_ORBOT = 2;
}
public static final class Pref {
public static final String PASSPHRASE_CACHE_TTLS = "passphraseCacheTtls";
public static final String PASSPHRASE_CACHE_DEFAULT = "passphraseCacheDefault";
public static final String PASSPHRASE_CACHE_SUBS = "passphraseCacheSubs";
public static final String LANGUAGE = "language";
public static final String KEY_SERVERS = "keyServers";
public static final String PREF_DEFAULT_VERSION = "keyServersDefaultVersion";
public static final String FIRST_TIME = "firstTime";
public static final String CACHED_CONSOLIDATE = "cachedConsolidate";
public static final String SEARCH_KEYSERVER = "search_keyserver_pref";
public static final String SEARCH_KEYBASE = "search_keybase_pref";
public static final String USE_NUMKEYPAD_FOR_SECURITY_TOKEN_PIN = "useNumKeypadForYubikeyPin";
public static final String ENCRYPT_FILENAMES = "encryptFilenames";
public static final String FILE_USE_COMPRESSION = "useFileCompression";
public static final String TEXT_USE_COMPRESSION = "useTextCompression";
public static final String USE_ARMOR = "useArmor";
// proxy settings
public static final String USE_NORMAL_PROXY = "useNormalProxy";
public static final String USE_TOR_PROXY = "useTorProxy";
public static final String PROXY_HOST = "proxyHost";
public static final String PROXY_PORT = "proxyPort";
public static final String PROXY_TYPE = "proxyType";
public static final String THEME = "theme";
// keyserver sync settings
public static final String SYNC_CONTACTS = "syncContacts";
public static final String SYNC_KEYSERVER = "syncKeyserver";
public static final String ENABLE_WIFI_SYNC_ONLY = "enableWifiSyncOnly";
// other settings
public static final String EXPERIMENTAL_ENABLE_WORD_CONFIRM = "experimentalEnableWordConfirm";
public static final String EXPERIMENTAL_ENABLE_LINKED_IDENTITIES = "experimentalEnableLinkedIdentities";
public static final String EXPERIMENTAL_ENABLE_KEYBASE = "experimentalEnableKeybase";
public static final class Theme {
public static final String LIGHT = "light";
public static final String DARK = "dark";
public static final String DEFAULT = Constants.Pref.Theme.LIGHT;
}
public static final class ProxyType {
public static final String TYPE_HTTP = "proxyHttp";
public static final String TYPE_SOCKS = "proxySocks";
}
}
/**
* information to connect to Orbot's localhost HTTP proxy
*/
public static final class Orbot {
public static final String PROXY_HOST = "127.0.0.1";
public static final int PROXY_PORT = 8118;
public static final Proxy.Type PROXY_TYPE = Proxy.Type.HTTP;
}
public static final class Defaults {
public static final String KEY_SERVERS = "hkps://hkps.pool.sks-keyservers.net, hkps://pgp.mit.edu";
public static final int PREF_VERSION = 6;
}
public static final class key {
public static final long none = 0;
public static final long symmetric = -1;
public static final long backup_code = -2;
}
}
| nmikhailov/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/Constants.java | Java | gpl-3.0 | 7,786 |
/*
* Copyright (C) 2011 Whisper Systems
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package com.securecomcode.voice.signaling;
/**
* An exception that marks a login failure.
*
* @author Moxie Marlinspike
*
*/
public class LoginFailedException extends Exception {
public LoginFailedException() {
super();
}
public LoginFailedException(String detailMessage) {
super(detailMessage);
}
public LoginFailedException(Throwable throwable) {
super(throwable);
}
public LoginFailedException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}
}
| Securecom/Securecom-Voice | src/com/securecomcode/voice/signaling/LoginFailedException.java | Java | gpl-3.0 | 1,217 |
package z.math.term;
import z.math.Complex;
import z.math.Namespace;
import z.math.Symbol;
public abstract class Term {
public int getOpPrecendence() {
return 0;
}
public final Term getArg1() {
return getArg(0);
}
public final Term getArg2() {
return getArg(1);
}
public abstract int getArity();
public abstract Term getArg(int i);
public abstract double evaluate();
@Override
public abstract boolean equals(Object o);
@Override
public abstract String toString();
public abstract int compareTo(Term other);
public abstract Term simplify();
public abstract Term differentiate(Symbol var);
public abstract Complex createComplex(Namespace namespace, Symbol unitSymbol);
public final boolean equalsZero() {
return equals(Functor.num(0));
}
public final boolean equalsOne() {
return equals(Functor.num(1));
}
public final boolean equalsTwo() {
return equals(Functor.num(2));
}
public final boolean isReal() {
return this instanceof Real;
}
public final boolean isSymbolRef() {
return this instanceof Ref;
}
public final boolean isStruct() {
return this instanceof Struct;
}
public final boolean isNeg() {
return isStruct() && ((Struct) this).getFunctor() == Functor.NEG;
}
public final boolean isAdd() {
return isStruct() && ((Struct) this).getFunctor() == Functor.ADD;
}
public final boolean isSub() {
return isStruct() && ((Struct) this).getFunctor() == Functor.SUB;
}
public final boolean isMul() {
return isStruct() && ((Struct) this).getFunctor() == Functor.MUL;
}
public final boolean isPow() {
return isStruct() && ((Struct) this).getFunctor() == Functor.POW;
}
public final boolean isSqrt() {
return isStruct() && ((Struct) this).getFunctor() == Functor.SQRT;
}
/**
* Counts the number of occurences of {@code t2} in this term.
*
* @param pattern the expression to be found
* @return the number of occurences
*/
public int countOccurences(final Term pattern) {
if (equals(pattern)) {
return 1;
}
if (isStruct()) {
int count = 0;
for (int i = 0; i < getArity(); i++) {
count += getArg(i).countOccurences(pattern);
}
return count;
}
return 0;
}
/**
* Creates a new term in which all occurences of
* {@code t2} in this term are replaced by {@code expr3}.
*
* @param pattern the expression to be found
* @param replacement the replacement for <code>expr2</code>
* @return the modified expression
*/
public Term replaceOccurences(final Term pattern, final Term replacement) {
if (equals(pattern)) {
return replacement;
}
if (isStruct()) {
Term[] terms = new Term[getArity()];
for (int i = 0; i < terms.length; i++) {
terms[i] = getArg(i).replaceOccurences(pattern, replacement);
}
return ((Struct) this).createStruct(terms);
}
return this;
}
}
| forman/frex | src/main/java/z/math/term/Term.java | Java | gpl-3.0 | 3,276 |
package lu.kremi151.minamod.block;
import lu.kremi151.minamod.MinaCreativeTabs;
import lu.kremi151.minamod.block.tileentity.TileEntityEnergyToRedstone;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
public class BlockEnergyToRedstone extends BlockCustomDirectional{
public static final PropertyInteger OUTPUT = PropertyInteger.create("output", 0, 15);
private static final AxisAlignedBB AABB_H = new AxisAlignedBB(0, 0, 0, 1, 0.0625, 1);
private static final AxisAlignedBB AABB_V = new AxisAlignedBB(0.1785, 0, 0.1785, 0.8125, 1, 0.8125);
public BlockEnergyToRedstone() {
super(Material.IRON);
this.setCreativeTab(MinaCreativeTabs.TECHNOLOGY);
}
@Override
public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos){
if(state.getValue(FACING).getAxis() == EnumFacing.Axis.Y) {
return AABB_V;
}else {
return AABB_H;
}
}
@Override
public boolean isFullCube(IBlockState state)
{
return false;
}
@Override
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
@Override
public IBlockState getStateForPlacement(World worldIn, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer)
{
return this.getDefaultState().withProperty(FACING, getAdjustedFacing(pos, placer));
}
private static EnumFacing getAdjustedFacing(BlockPos pos, EntityLivingBase placer) {
EnumFacing face = EnumFacing.getDirectionFromEntityLiving(pos, placer);
if(face.getHorizontalIndex() != -1) {
return face.getOpposite();
}else {
return face;
}
}
@Override
public boolean hasTileEntity(IBlockState bs)
{
return true;
}
@Override
public TileEntity createTileEntity(World world, IBlockState bs)
{
return new TileEntityEnergyToRedstone();
}
@Override
public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return getStrongPower(blockState, blockAccess, pos, side);
}
@Override
public boolean canProvidePower(IBlockState state)
{
return true;
}
@Override
public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
return (blockState.getValue(FACING).getOpposite() == side) ? getActualState(blockState, blockAccess, pos).getValue(OUTPUT).intValue() : 0;
}
@Override
public IBlockState getActualState(IBlockState state, IBlockAccess world, BlockPos pos) {
TileEntity te = world.getTileEntity(pos);
int output = 0;
if(te instanceof TileEntityEnergyToRedstone) {
output = ((TileEntityEnergyToRedstone)te).getOutput();
}
return state.withProperty(OUTPUT, MathHelper.clamp(output, 0, 15));
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] {FACING, OUTPUT});
}
}
| kremi151/MinaMod | src/main/java/lu/kremi151/minamod/block/BlockEnergyToRedstone.java | Java | gpl-3.0 | 3,587 |
/**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify it under the terms of the
* GNU Affero General Public License as published by the Free Software Foundation, either version 3
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program.
* If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.operator.nio.model.xlsx;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import com.rapidminer.operator.nio.model.xlsx.XlsxUtilities.XlsxCellCoordinates;
/**
* Unit tests for methods from {@link XlsxUtilities} class.
*
* @author Nils Woehler
*
*/
public class XlsxUtiliesTest {
@Test
public void convertToColumnIndexTest() {
assertEquals(-1, XlsxUtilities.convertToColumnIndex(""));
assertEquals(0, XlsxUtilities.convertToColumnIndex("A"));
assertEquals(1, XlsxUtilities.convertToColumnIndex("B"));
assertEquals(2, XlsxUtilities.convertToColumnIndex("C"));
assertEquals(25, XlsxUtilities.convertToColumnIndex("Z"));
assertEquals(26, XlsxUtilities.convertToColumnIndex("AA"));
assertEquals(27, XlsxUtilities.convertToColumnIndex("AB"));
assertEquals(28, XlsxUtilities.convertToColumnIndex("AC"));
assertEquals(51, XlsxUtilities.convertToColumnIndex("AZ"));
assertEquals(52, XlsxUtilities.convertToColumnIndex("BA"));
assertEquals(16_383, XlsxUtilities.convertToColumnIndex("XFD"));
}
@Test
public void convertToColumnNameTest() {
assertEquals("A", XlsxUtilities.convertToColumnName(0));
assertEquals("B", XlsxUtilities.convertToColumnName(1));
assertEquals("C", XlsxUtilities.convertToColumnName(2));
assertEquals("Z", XlsxUtilities.convertToColumnName(25));
assertEquals("AA", XlsxUtilities.convertToColumnName(26));
assertEquals("AB", XlsxUtilities.convertToColumnName(27));
assertEquals("AC", XlsxUtilities.convertToColumnName(28));
assertEquals("AZ", XlsxUtilities.convertToColumnName(51));
assertEquals("BA", XlsxUtilities.convertToColumnName(52));
assertEquals("XFD", XlsxUtilities.convertToColumnName(16_383));
}
@Test(expected = IllegalArgumentException.class)
public void convertToColumnNameIllegalArgumentTest() {
XlsxUtilities.convertToColumnName(-1);
}
@Test
public void convertCellRefToCoordinatesTest() {
assertEquals(new XlsxCellCoordinates(0, 0), XlsxUtilities.convertCellRefToCoordinates("A1"));
assertEquals(new XlsxCellCoordinates(0, 1), XlsxUtilities.convertCellRefToCoordinates("A2"));
assertEquals(new XlsxCellCoordinates(1, 0), XlsxUtilities.convertCellRefToCoordinates("B1"));
assertEquals(new XlsxCellCoordinates(1, 1), XlsxUtilities.convertCellRefToCoordinates("B2"));
assertEquals(new XlsxCellCoordinates(26, 0), XlsxUtilities.convertCellRefToCoordinates("AA1"));
assertEquals(new XlsxCellCoordinates(52, 0), XlsxUtilities.convertCellRefToCoordinates("BA1"));
assertEquals(new XlsxCellCoordinates(26, 1), XlsxUtilities.convertCellRefToCoordinates("AA2"));
assertEquals(new XlsxCellCoordinates(52, 1), XlsxUtilities.convertCellRefToCoordinates("BA2"));
assertEquals(new XlsxCellCoordinates(16_383, 1_048_575), XlsxUtilities.convertCellRefToCoordinates("XFD1048576"));
}
@Test
public void convertToCellRefToCoordinatesIllegalArgumentNoDigitTest() {
assertEquals(new XlsxCellCoordinates(26, XlsxCellCoordinates.NO_ROW_NUMBER),
XlsxUtilities.convertCellRefToCoordinates("AA"));
}
@Test(expected = IllegalArgumentException.class)
public void convertToCellRefToCoordinatesIllegalArgumentNotLetterTest() {
XlsxUtilities.convertCellRefToCoordinates("1");
}
}
| transwarpio/rapidminer | rapidMiner/rapidminer-studio-core/src/test/java/com/rapidminer/operator/nio/model/xlsx/XlsxUtiliesTest.java | Java | gpl-3.0 | 4,043 |
package com.expper.security;
import org.junit.Test;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import java.util.ArrayList;
import java.util.Collection;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Test class for the SecurityUtils utility class.
*
* @see SecurityUtils
*/
public class SecurityUtilsTest {
@Test
public void testgetCurrentUserLogin() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
String login = SecurityUtils.getCurrentUserLogin();
assertThat(login).isEqualTo("admin");
}
@Test
public void testIsAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("admin", "admin"));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isTrue();
}
@Test
public void testAnonymousIsNotAuthenticated() {
SecurityContext securityContext = SecurityContextHolder.createEmptyContext();
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.ANONYMOUS));
securityContext.setAuthentication(new UsernamePasswordAuthenticationToken("anonymous", "anonymous", authorities));
SecurityContextHolder.setContext(securityContext);
boolean isAuthenticated = SecurityUtils.isAuthenticated();
assertThat(isAuthenticated).isFalse();
}
}
| Raysmond/expper | src/test/java/com/expper/security/SecurityUtilsTest.java | Java | gpl-3.0 | 2,083 |
/*
* eGov suite of products aim to improve the internal efficiency,transparency,
* accountability and the service delivery of the government organizations.
*
* Copyright (C) 2016 eGovernments Foundation
*
* The updated version of eGov suite of products as by eGovernments Foundation
* is available at http://www.egovernments.org
*
* 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 3 of the License, or
* 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, see http://www.gnu.org/licenses/ or
* http://www.gnu.org/licenses/gpl.html .
*
* In addition to the terms of the GPL license to be adhered to in using this
* program, the following additional terms are to be complied with:
*
* 1) All versions of this program, verbatim or modified must carry this
* Legal Notice.
*
* 2) Any misrepresentation of the origin of the material is prohibited. It
* is required that all modified versions of this material be marked in
* reasonable ways as different from the original version.
*
* 3) This license does not grant any rights to any user of the program
* with regards to rights under trademark law for use of the trade names
* or trademarks of eGovernments Foundation.
*
* In case of any queries, you can reach eGovernments Foundation at [email protected].
*/
package org.egov.infra.workflow.repository;
import org.egov.infra.workflow.entity.WorkflowAction;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface WorkflowActionRepository extends JpaRepository<WorkflowAction, Long> {
WorkflowAction findByNameAndType(String name, String type);
List<WorkflowAction> findAllByTypeAndNameIn(String type, List<String> names);
}
| egovernments/egov-playground | eGov/egov/egov-egi/src/main/java/org/egov/infra/workflow/repository/WorkflowActionRepository.java | Java | gpl-3.0 | 2,254 |
/**
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
*/
package com.itsa.traffic.handler;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
/**
* Update on: Jan 18, 2015.
*
* @author Alisson Oliveira
*
*/
public class LocationHandler implements LocationListener, ConnectionCallbacks, OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private Context context;
private LocationRequest mLocationRequest;
private Geocoder geocoder;
private TrafficManager manager;
private Location actualLocation;
public LocationHandler(Context context, TrafficManager trafficManager) {
this.context = context;
this.manager = trafficManager;
buildGoogleApiClient();
createLocationRequest();
geocoder = new Geocoder(context, Locale.getDefault());
}
protected void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(context)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(25000);
mLocationRequest.setFastestInterval(10000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
public void start() {
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(context) != 0) {
Log.e("LocationHandler", "GooglePlayServices isn't available");
}
if (!(mGoogleApiClient.isConnected() || mGoogleApiClient.isConnecting()))
mGoogleApiClient.connect();
}
public void stop() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
@Override
public void onLocationChanged(Location location) {
manager.handleChangePosition(location);
actualLocation = location;
requestLocalizationAddress(location);
}
public Location getActualLocation() {
return actualLocation;
}
@Override
public void onConnected(Bundle bundle) {
Log.i("PLAY SERVICE", "Connected");
startLocationUpdates();
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
@Override
public void onConnectionSuspended(int arg0) {
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
}
public void requestAddressFromLocation(final Location loc) {
requestAddressFromLocation(loc.getLatitude(), loc.getLongitude());
}
protected void requestLocalizationAddress(final Location location) {
(new Thread(new Runnable() {
@Override
public void run() {
try {
List<Address> address = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if(address.size() > 0)
manager.setLocAddress(address.get(0));
} catch (IOException e) {
}
}
})).start();
}
public void requestAddressFromName(final String location) {
Log.i("Location", "Requesting " + location);
(new Thread(new Runnable() {
@Override
public void run() {
try {
List<Address> address = geocoder.getFromLocationName(location, 5);
manager.onReceiveAddress(address);
} catch (IOException e) {
manager.onAddressRequestError();
}
}
})).start();
}
public void requestAddressFromLocation(final double latitude, final double longitude) {
(new Thread(new Runnable() {
@Override
public void run() {
try {
List<Address> address = geocoder.getFromLocation(latitude, longitude, 1);
manager.onReceiveAddress(address);
} catch (IOException e) {
manager.onAddressRequestError();
}
}
})).start();
}
}
| JoeAlisson/ITSA-Android | ITSA-Android/src/com/itsa/traffic/handler/LocationHandler.java | Java | gpl-3.0 | 4,936 |
/*
* Crafter Studio Web-content authoring solution
* Copyright (C) 2007-2016 Crafter Software Corporation.
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package org.craftercms.studio.api.v1.dal;
import java.util.List;
import java.util.Map;
/**
* @author Dejan Brkic
*/
public interface CopyToEnvironmentMapper {
List<CopyToEnvironment> getScheduledItems(Map params);
void insertItemForDeployment(CopyToEnvironment copyToEnvironment);
void cancelWorkflow(Map params);
List<CopyToEnvironment> getItemsReadyForDeployment(Map params);
void updateItemDeploymentState(CopyToEnvironment item);
void deleteDeploymentDataForSite(Map params);
List<CopyToEnvironment> getItemsBySiteAndStates(Map params);
void cancelDeployment(Map params);
}
| rart/studio2 | src/main/java/org/craftercms/studio/api/v1/dal/CopyToEnvironmentMapper.java | Java | gpl-3.0 | 1,385 |
package be.kuleuven.codes.tup.model;
import java.util.*;
public class Problem {
public final String name;
public final int q1, q2;
//basic info
public int nTeams; //number of teams
public int[][] dist; //distance matrix
public int[][] opponents; //game schedule, opponent of each team in each round
public int[][] distGames; //distance matrix [game]x[game]
//additional info
public int nUmpires; //number of umpires
public int nGames; //number of games
public int nRounds; //number of rounds
public int[][] games; //games [nGames][0=hometeam,1=awayteam]
public int[] gameToRound; //index=gameID, value=roundNr
public int[][] roundHomeTeamToGame, roundTeamToGame;
public boolean[][] possibleVisits;
public int teamTravelDistance;
public Problem(int nTeams, int[][] dist, int[][] opponents, int q1, int q2, String name) {
this.nTeams = nTeams;
this.dist = dist;
this.opponents = opponents;
this.q1 = q1;
this.q2 = q2;
this.name = name;
nUmpires = nTeams / 2;
nRounds = nTeams * 2 - 2;
nGames = nRounds * nTeams / 2;
games = new int[nGames][2];
gameToRound = new int[nGames];
roundHomeTeamToGame = new int[nRounds][nTeams];
roundTeamToGame = new int[nRounds][nTeams];
int game = 0;
for (int round = 0; round < nRounds; round++) {
for (int team = 1; team <= nTeams; team++) {
if (opponents[round][team - 1] > 0) {
games[game][0] = team;
games[game][1] = opponents[round][team - 1];
gameToRound[game] = round;
roundHomeTeamToGame[round][team - 1] = game;
game++;
}
else {
roundHomeTeamToGame[round][team - 1] = -1;
}
}
}
for (int round = 0; round < nRounds; round++) {
for (int team = 1; team <= nTeams; team++) {
if (opponents[round][team - 1] > 0)
roundTeamToGame[round][team - 1] = roundHomeTeamToGame[round][team - 1];
else
roundTeamToGame[round][team - 1] = roundHomeTeamToGame[round][-opponents[round][team - 1] - 1];
}
}
calcultateTeamTravelDistance();
possibleVisits = new boolean[nRounds][nTeams];
for (int i = nRounds - 1; i >= 0; i--) {
for (int j = 0; j < nTeams; j++) {
if (opponents[i][j] > 0 || (i < nRounds - 1 && possibleVisits[i + 1][j])) {
possibleVisits[i][j] = true;
}
}
}
distGames = new int[nGames][nGames];
for (int i = 0; i < nGames; i++)
for (int j = 0; j < nGames; j++)
distGames[i][j] = dist[games[i][0] - 1][games[j][0] - 1];
}
public void setTournament(int[][] opponents) {
games = new int[nGames][2];
gameToRound = new int[nGames];
roundHomeTeamToGame = new int[nRounds][nTeams];
this.opponents = opponents;
int m = 0;
for (int round = 0; round < nRounds; round++) {
for (int team = 1; team <= nTeams; team++) {
if (opponents[round][team - 1] > 0) {
games[m][0] = team;
games[m][1] = opponents[round][team - 1];
gameToRound[m] = round;
roundHomeTeamToGame[round][team - 1] = m;
m++;
}
else {
roundHomeTeamToGame[round][team - 1] = -1;
}
}
}
calcultateTeamTravelDistance();
possibleVisits = new boolean[nRounds][nTeams];
for (int i = nRounds - 1; i >= 0; i--) {
for (int j = 0; j < nTeams; j++) {
if (opponents[i][j] > 0 || (i < nRounds - 1 && possibleVisits[i + 1][j])) {
possibleVisits[i][j] = true;
}
}
}
}
@Override
public String toString() {
return "Problem [nTeams=" + nTeams + ",\n dist="
+ Arrays.deepToString(dist) + ",\n opponents="
+ Arrays.deepToString(opponents) + ",\n nUmpires=" + nUmpires
+ ",\n nGames=" + nGames + ",\n nRounds=" + nRounds
+ ",\n q1=" + q1
+ ",\n q2=" + q2
+ "]";
}
/**
* TTP distance
*/
private void calcultateTeamTravelDistance() {
teamTravelDistance = 0;
int prevLoc;
for (int team = 0; team < nTeams; team++) {
prevLoc = team;
for (int round = 0; round < nRounds; round++) {
if (prevLoc == team && opponents[round][team] < 0) {
int toLoc = (-opponents[round][team]) - 1;
teamTravelDistance += dist[team][toLoc];
prevLoc = toLoc;
}
if (prevLoc != team && opponents[round][team] < 0) {
int toLoc = (-opponents[round][team]) - 1;
teamTravelDistance += dist[prevLoc][toLoc];
prevLoc = toLoc;
}
if (prevLoc != team && opponents[round][team] > 0) {
teamTravelDistance += dist[prevLoc][team];
prevLoc = team;
}
}
if (prevLoc != team) {
teamTravelDistance += dist[prevLoc][team];
prevLoc = team;
}
}
}
}
| tuliotoffolo/tup | tup/src/be/kuleuven/codes/tup/model/Problem.java | Java | gpl-3.0 | 5,619 |
package br.com.vmbackup.dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import br.com.vmbackup.modelo.Schedule;
public class ScheduleDao {
public void addSchedule(Schedule schedule) {
EntityManager manager = VmbackupDao.getManager();
manager.getTransaction().begin();
manager.persist(schedule);
manager.getTransaction().commit();
VmbackupDao.closeManager();
}
public List<Schedule> getLista() {
EntityManager manager = VmbackupDao.getManager();
Query query = manager.createQuery("SELECT s FROM Schedule s ORDER BY sequence");
@SuppressWarnings("unchecked")
List<Schedule> schedule = query.getResultList();
VmbackupDao.closeManager();
return schedule;
}
public Schedule buscarPorId(int schedule_id) {
try {
EntityManager manager = VmbackupDao.getManager();
Query query = manager.createQuery("SELECT s FROM Schedule as s " + "where s.id = :paramId");
query.setParameter("paramId", schedule_id);
query.setMaxResults(1);
return (Schedule) query.getSingleResult();
} catch (NoResultException e) {
return null;
} finally {
VmbackupDao.closeManager();
}
}
public Schedule buscarPorSequence(int sequence) {
try {
EntityManager manager = VmbackupDao.getManager();
Query query = manager.createQuery("SELECT s FROM Schedule as s " + "where s.sequence = :paramSequence");
query.setParameter("paramSequence", sequence);
query.setMaxResults(1);
Schedule schedule = (Schedule) query.getSingleResult();
return schedule;
} catch (NoResultException e) {
return null;
} finally {
VmbackupDao.closeManager();
}
}
public int getLastSequence() {
try {
EntityManager manager = VmbackupDao.getManager();
Query query = manager.createQuery("FROM Schedule order by sequence DESC");
query.setMaxResults(1);
Schedule schedule = (Schedule) query.getSingleResult();
return schedule.getSequence();
} catch (NoResultException e) {
return 0;
} finally {
VmbackupDao.closeManager();
}
}
public void updateSchedule(Schedule schedule) {
EntityManager manager = VmbackupDao.getManager();
manager.getTransaction().begin();
Schedule mySchedule = manager.find(Schedule.class, schedule.getId());
mySchedule = schedule;
manager.merge(mySchedule);
manager.getTransaction().commit();
VmbackupDao.closeManager();
}
public void deleteSchedule(Schedule schedule) {
EntityManager manager = VmbackupDao.getManager();
manager.getTransaction().begin();
Schedule mySchedule = manager.find(Schedule.class, schedule.getId());
manager.remove(mySchedule);
manager.getTransaction().commit();
VmbackupDao.closeManager();
}
} | gnuvinicius/vmbackup | src/br/com/vmbackup/dao/ScheduleDao.java | Java | gpl-3.0 | 2,724 |
package com.zulucap.sheeeps.items;
import com.google.common.collect.Maps;
import com.zulucap.sheeeps.init.SheeepsBlocks;
import com.zulucap.sheeeps.init.SheeepsItems;
import net.minecraft.block.Block;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraftforge.oredict.OreDictionary;
import java.util.Map;
/**
* Created by Dan on 3/4/2016.
*/
public class SeparatorRegistry {
private static final SeparatorRegistry separatorBase = new SeparatorRegistry();
private Map<ItemStack, ItemStack> separatingList = Maps.<ItemStack, ItemStack>newHashMap();
private Map<ItemStack, Float> experienceList = Maps.<ItemStack, Float>newHashMap();
public static SeparatorRegistry instance()
{
return separatorBase;
}
public SeparatorRegistry(){
/* Vanilla Ores */
this.addSeparatorRecipeForBlock(SheeepsBlocks.coal_wool, new ItemStack(SheeepsItems.coal_residue), 0.5F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.iron_wool, new ItemStack(SheeepsItems.iron_residue), 0.7F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.diamond_wool, new ItemStack(SheeepsItems.diamond_residue), 1.0F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.emerald_wool, new ItemStack(SheeepsItems.emerald_residue), 1.0F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.gold_wool, new ItemStack(SheeepsItems.gold_residue), 0.7F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.glowstone_wool, new ItemStack(SheeepsItems.glowstone_residue), 0.85F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.redstone_wool, new ItemStack(SheeepsItems.redstone_residue), 0.85F);
this.addSeparatorRecipeForBlock(SheeepsBlocks.lapis_wool, new ItemStack(SheeepsItems.lapis_residue), 0.9F);
}
public void addModSeparatorRecipes(){
if(OreDictionary.getOres("ingotCopper").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.copper_wool, new ItemStack(SheeepsItems.copper_residue), 0.5F);
}
if(OreDictionary.getOres("ingotTin").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.tin_wool, new ItemStack(SheeepsItems.tin_residue), 0.7F);
}
if(OreDictionary.getOres("ingotNickel").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.nickel_wool, new ItemStack(SheeepsItems.nickel_residue), 1.0F);
}
if(OreDictionary.getOres("ingotLead").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.lead_wool, new ItemStack(SheeepsItems.lead_residue), 1.0F);
}
if(OreDictionary.getOres("ingotSilver").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.silver_wool, new ItemStack(SheeepsItems.silver_residue), 0.7F);
}
if(OreDictionary.getOres("ingotPlatinum").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.platinum_wool, new ItemStack(SheeepsItems.platinum_residue), 0.85F);
}
if(OreDictionary.getOres("ingotArdite").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.ardite_wool, new ItemStack(SheeepsItems.ardite_residue), 0.85F);
}
if(OreDictionary.getOres("ingotCobalt").size() > 0) {
this.addSeparatorRecipeForBlock(SheeepsBlocks.cobalt_wool, new ItemStack(SheeepsItems.cobalt_residue), 0.9F);
}
}
/**
* Adds a smelting recipe, where the input item is an instance of Block.
*/
public void addSeparatorRecipeForBlock(Block input, ItemStack stack, float experience)
{
this.addSeparating(Item.getItemFromBlock(input), stack, experience);
}
/**
* Adds a smelting recipe using an Item as the input item.
*/
public void addSeparating(Item input, ItemStack stack, float experience)
{
this.addSeparatingRecipe(new ItemStack(input, 1, 32767), stack, experience);
}
/**
* Adds a smelting recipe using an ItemStack as the input for the recipe.
*/
public void addSeparatingRecipe(ItemStack input, ItemStack stack, float experience)
{
if (getSeparatingResult(input) != null) { net.minecraftforge.fml.common.FMLLog.info("Ignored separating recipe with conflicting input: " + input + " = " + stack); return; }
this.separatingList.put(input, stack);
this.experienceList.put(stack, Float.valueOf(experience));
}
/**
* Returns the smelting result of an item.
*/
public ItemStack getSeparatingResult(ItemStack stack)
{
for (Map.Entry<ItemStack, ItemStack> entry : this.separatingList.entrySet())
{
if (this.compareItemStacks(stack, (ItemStack)entry.getKey()))
{
return (ItemStack)entry.getValue();
}
}
return null;
}
/**
* Compares two itemstacks to ensure that they are the same. This checks both the item and the metadata of the item.
*/
private boolean compareItemStacks(ItemStack stack1, ItemStack stack2)
{
return stack2.getItem() == stack1.getItem() && (stack2.getMetadata() == 32767 || stack2.getMetadata() == stack1.getMetadata());
}
}
| zulucap/Sheeeps | src/main/java/com/zulucap/sheeeps/items/SeparatorRegistry.java | Java | gpl-3.0 | 5,176 |
/*
*
* This file is part of the SIRIUS library for analyzing MS and MS/MS data
*
* Copyright (C) 2013-2020 Kai Dührkop, Markus Fleischauer, Marcus Ludwig, Martin A. Hoffman, Fleming Kretschmer and Sebastian Böcker,
* Chair of Bioinformatics, Friedrich-Schilller University.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with SIRIUS. If not, see <https://www.gnu.org/licenses/lgpl-3.0.txt>
*/
package de.unijena.bioinf.FragmentationTreeConstruction.computation.scoring;
import de.unijena.bioinf.ChemistryBase.algorithm.ParameterHelper;
import de.unijena.bioinf.ChemistryBase.chem.MolecularFormula;
import de.unijena.bioinf.ChemistryBase.chem.utils.MolecularFormulaScorer;
import de.unijena.bioinf.ChemistryBase.chem.utils.scoring.ChemicalCompoundScorer;
import de.unijena.bioinf.ChemistryBase.chem.utils.scoring.SupportVectorMolecularFormulaScorer;
import de.unijena.bioinf.ChemistryBase.data.DataDocument;
import de.unijena.bioinf.ChemistryBase.ms.ft.AbstractFragmentationGraph;
import de.unijena.bioinf.ChemistryBase.ms.ft.Loss;
import de.unijena.bioinf.sirius.ProcessedInput;
public class ChemicalPriorEdgeScorer implements LossScorer {
private MolecularFormulaScorer prior;
private double normalization;
private double minimalMass;
public ChemicalPriorEdgeScorer() {
this(ChemicalCompoundScorer.createDefaultCompoundScorer(true), 0d, 100d);
}
public ChemicalPriorEdgeScorer(MolecularFormulaScorer prior, double normalization, double minimalMass) {
this.prior = prior;
this.normalization = normalization;
this.minimalMass = minimalMass;
}
@Override
public Object prepare(ProcessedInput input, AbstractFragmentationGraph graph) {
return null;
}
@Override
public double score(Loss loss, ProcessedInput input, Object precomputed) {
return score(loss.getSource().getFormula(), loss.getTarget().getFormula());
}
public double score(MolecularFormula parentFormula, MolecularFormula childFormula) {
if (childFormula.getMass() < minimalMass) return 0d;
double child,parent;
if (prior instanceof SupportVectorMolecularFormulaScorer) {
// legacy
child = Math.min(1, prior.score(childFormula));
parent = Math.min(1, prior.score(parentFormula));
return Math.min(0,child-parent) - normalization;
} else {
child = Math.max(Math.log(0.0001), prior.score(childFormula));
parent = Math.max(Math.log(0.0001), prior.score(parentFormula));
}
return Math.min(0, child - parent) - normalization;
}
public MolecularFormulaScorer getPrior() {
return prior;
}
public void setPrior(MolecularFormulaScorer prior) {
this.prior = prior;
}
public double getMinimalMass() {
return minimalMass;
}
public void setMinimalMass(double minimalMass) {
this.minimalMass = minimalMass;
}
public double getNormalization() {
return normalization;
}
public void setNormalization(double normalization) {
this.normalization = normalization;
}
@Override
public <G, D, L> void importParameters(ParameterHelper helper, DataDocument<G, D, L> document, D dictionary) {
this.prior = (MolecularFormulaScorer) helper.unwrap(document, document.getFromDictionary(dictionary, "prior"));
this.normalization = document.getDoubleFromDictionary(dictionary, "normalization");
this.minimalMass = document.getDoubleFromDictionary(dictionary, "minimalMass");
}
@Override
public <G, D, L> void exportParameters(ParameterHelper helper, DataDocument<G, D, L> document, D dictionary) {
document.addToDictionary(dictionary, "prior", helper.wrap(document, prior));
document.addToDictionary(dictionary, "normalization", normalization);
document.addToDictionary(dictionary, "minimalMass", minimalMass);
}
}
| kaibioinfo/sirius | fragmentation_tree/fragmentation_tree_construction/src/main/java/de/unijena/bioinf/FragmentationTreeConstruction/computation/scoring/ChemicalPriorEdgeScorer.java | Java | gpl-3.0 | 4,521 |
package com.hawk.ecom.codegen.mall;
import com.hawk.framework.codegen.database.DbToDicService;
import com.hawk.framework.codegen.database.SynonymHelper;
/**
* 从数据库生成数据字典
* @author pzhang1
*
*/
public class DatabaseToDicForMallApp {
public static void main(String[] args){
try {
// SynonymHelper.addWord("user_code", "create_user_code", "创建用户编号");
// SynonymHelper.addWord("user_code", "update_user_code", "更新用户编号");
// SynonymHelper.addWord("user_code", "delete_user_code", "删除用户编号");
// SynonymHelper.addWord("id", "user_id", "用户id");
// SynonymHelper.addWord("id", "role_id", "角色id");
// SynonymHelper.addWord("id", "pid", "父id");
// SynonymHelper.addWord("id", "right_id", "权限id");
new DbToDicService("com.hawk.ecom.codegen.mall").execute();
} catch (Throwable e) {
e.printStackTrace();
}finally{
System.exit(0);
}
}
}
| zeatul/poc | e-commerce/e-commerce-code-gen/src/main/java/com/hawk/ecom/codegen/mall/DatabaseToDicForMallApp.java | Java | gpl-3.0 | 938 |
/**
*
*/
package org.betaconceptframework.astroboa.portal.managedbean;
import java.util.concurrent.ConcurrentHashMap;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.AutoCreate;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
* @author Gregory Chomatas ([email protected])
* @author Savvas Triantafyllou ([email protected])
*/
@AutoCreate
@Name("viewCountAggregator")
@Scope(ScopeType.APPLICATION)
public class ViewCountAggregator {
private ConcurrentHashMap<String, Integer> contentObjectViewCount = new ConcurrentHashMap<String, Integer>(100);
public ConcurrentHashMap<String, Integer> getContentObjectViewCount() {
return contentObjectViewCount;
}
public void increaseContentObjectViewCounter(String contentObjectId) {
Integer oldVal, newVal;
boolean success = false;
do {
oldVal = contentObjectViewCount.get(contentObjectId);
newVal = (oldVal == null) ? 1 : (oldVal + 1);
if (oldVal == null) {
success = (contentObjectViewCount.putIfAbsent(contentObjectId, newVal) == null)? true : false;
}
else {
success = contentObjectViewCount.replace(contentObjectId, oldVal, newVal);
}
} while (!success);
}
}
| BetaCONCEPT/astroboa | astroboa-portal-commons/src/main/java/org/betaconceptframework/astroboa/portal/managedbean/ViewCountAggregator.java | Java | gpl-3.0 | 1,297 |
/****************************************************************************
ePMC - an extensible probabilistic model checker
Copyright (C) 2017
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 3 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, see <http://www.gnu.org/licenses/>.
*****************************************************************************/
package epmc.value.operatorevaluator;
import epmc.operator.Operator;
import epmc.operator.OperatorAbs;
import epmc.operator.OperatorDistance;
import epmc.operator.OperatorMax;
import epmc.operator.OperatorSubtract;
import epmc.value.ContextValue;
import epmc.value.OperatorEvaluator;
import epmc.value.Type;
import epmc.value.TypeInteger;
import epmc.value.TypeInterval;
import epmc.value.TypeReal;
import epmc.value.Value;
import epmc.value.ValueInterval;
public final class OperatorEvaluatorDistanceInterval implements OperatorEvaluator {
public final static class Builder implements OperatorEvaluatorSimpleBuilder {
private boolean built;
private Operator operator;
private Type[] types;
@Override
public void setOperator(Operator operator) {
assert !built;
this.operator = operator;
}
@Override
public void setTypes(Type[] types) {
assert !built;
this.types = types;
}
@Override
public OperatorEvaluator build() {
assert !built;
assert operator != null;
assert types != null;
for (Type type : types) {
assert type != null;
}
built = true;
if (operator != OperatorDistance.DISTANCE) {
return null;
}
if (types.length != 2) {
return null;
}
if (!TypeInterval.is(types[0])
&& !TypeInterval.is(types[1])) {
return null;
}
for (Type type : types) {
if (!TypeReal.is(type)
&& !TypeInteger.is(type)
&& !TypeInterval.is(type)) {
return null;
}
}
return new OperatorEvaluatorDistanceInterval(this);
}
}
private final OperatorEvaluator subtract;
private final OperatorEvaluator abs;
private final OperatorEvaluator max;
private final Value resLower;
private final Value resUpper;
private OperatorEvaluatorDistanceInterval(Builder builder) {
subtract = ContextValue.get().getEvaluator(OperatorSubtract.SUBTRACT, TypeReal.get(), TypeReal.get());
abs = ContextValue.get().getEvaluator(OperatorAbs.ABS, TypeReal.get());
max = ContextValue.get().getEvaluator(OperatorMax.MAX, TypeReal.get(), TypeReal.get());
resLower = TypeReal.get().newValue();
resUpper = TypeReal.get().newValue();
}
@Override
public Type resultType() {
return TypeReal.get();
}
@Override
public void apply(Value result, Value... operands) {
assert result != null;
assert operands != null;
for (Value operand : operands) {
assert operand != null;
}
assert operands.length >= 2;
Value op1Lower = ValueInterval.getLower(operands[0]);
Value op1Upper = ValueInterval.getUpper(operands[0]);
Value op2Lower = ValueInterval.getLower(operands[1]);
Value op2Upper = ValueInterval.getUpper(operands[1]);
subtract.apply(resLower, op1Lower, op2Lower);
abs.apply(resLower, resLower);
subtract.apply(resUpper, op1Upper, op2Upper);
abs.apply(resUpper, resUpper);
max.apply(result, resLower, resUpper);
}
}
| liyi-david/ePMC | plugins/value-basic/src/main/java/epmc/value/operatorevaluator/OperatorEvaluatorDistanceInterval.java | Java | gpl-3.0 | 4,293 |
package com.jchart.model;
import com.jchart.util.FormatUtils;
public class QuoteString {
public String dt;
public String op;
public String hi;
public String lo;
public String cl;
public String vo;
public String chg;
public String curPos;
private Quote quote;
public QuoteString(boolean isIntraday, Quote quote, float priorCl) {
this.quote = quote;
Double f;
dt = "Dt: " + FormatUtils.formatDate(quote.getDate()) + " ";
f = new Double(quote.getOpen());
op = "Op: " + FormatUtils.formatDecimal(f.toString(), 3) + " ";
f = new Double(quote.getHi());
hi = "Hi: " + FormatUtils.formatDecimal(f.toString(), 3) + " ";
f = new Double(quote.getLow());
lo = "Low: " + FormatUtils.formatDecimal(f.toString(), 3) + " ";
f = new Double(quote.getClose());
cl = "Lst: " + FormatUtils.formatDecimal(f.toString(), 3) + " ";
f = new Double(quote.getVolume());
// vo = "Vol: " + FormatUtils.formatDecimal(f.toString(),0) + " ";
vo = "Vol: " + FormatUtils.formatVol(quote.getVolume()) + " ";
// FormatUtils.formatVol(f)
f = new Double(quote.getClose() - priorCl);
chg = "Chg: " + FormatUtils.formatDecimal(f.toString(), 3) + " ";
}
public long getVolume() {
return quote.getVolume();
}
public String toString() {
return dt + cl + chg + vo;
}
}
| jchart/jchart-chart | src/main/java/com/jchart/model/QuoteString.java | Java | gpl-3.0 | 1,389 |
/*
* Copyright (C) 2016 Riccardo De Benedictis <[email protected]>
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
package it.cnr.istc.sponsor.view;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
/**
*
* @author Riccardo De Benedictis <[email protected]>
*/
public class User {
public final StringProperty firstName = new SimpleStringProperty();
public final StringProperty lastName = new SimpleStringProperty();
public final IntegerProperty president = new SimpleIntegerProperty();
public final IntegerProperty structure = new SimpleIntegerProperty();
public final IntegerProperty brilliant = new SimpleIntegerProperty();
public final IntegerProperty evaluator = new SimpleIntegerProperty();
public final IntegerProperty concrete = new SimpleIntegerProperty();
public final IntegerProperty explorer = new SimpleIntegerProperty();
public final IntegerProperty worker = new SimpleIntegerProperty();
public final IntegerProperty objectivist = new SimpleIntegerProperty();
public final ObservableList<Activity> assigned_activities = FXCollections.observableArrayList();
public final ObservableList<Activity> negated_activities = FXCollections.observableArrayList();
@Override
public String toString() {
return firstName.getValue() + " " + lastName.getValue();
}
}
| riccardodebenedictis/SpONSOR | src/it/cnr/istc/sponsor/view/User.java | Java | gpl-3.0 | 2,253 |
package com.thunder.sky.GUI;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.TrueTypeFont;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;
public class Game extends BasicGameState {
Rectangle rect = new Rectangle(50, 50, 100,100);
public void init(GameContainer gc, StateBasedGame sbg) throws SlickException {
}
public void render(GameContainer gc, StateBasedGame sbg, Graphics g) throws SlickException {
g.draw(rect);
}
public void update(GameContainer gc, StateBasedGame sbg,int DELTA) throws SlickException {
}
@Override
public int getID() {
return 2;
}
}
| nitrodragon/ThunderingSky | src/com/thunder/sky/GUI/Game.java | Java | gpl-3.0 | 804 |
package org.bear.bookstore.test.jmx;
public interface IJmxTestBean {
public int add(int x, int y);
public long myOperation();
public int getAge();
public void setAge(int age);
public void setName(String name);
public String getName();
}
| zhougithui/bookstore-single | src/test/java/org/bear/bookstore/test/jmx/IJmxTestBean.java | Java | mpl-2.0 | 264 |
package org.controller.crawler.threads;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import org.batcher.batcher.duties.jobs.AtlasJob;
import org.batcher.batcher.duties.jobs.Job;
import org.batcher.batcher.duties.jobs.tasks.Task;
import org.controller.crawler.CrawlerCTRL;
import org.utils.JLogger;
import org.utils.Timer;
public class CrawlerThread extends Thread {
private static final int CONNECTION_TIMEOUT = 30;
CrawlerCTRL crawlerCTRL;
public CrawlerThread() {}
public CrawlerThread(String name, CrawlerCTRL crawlerCTRL) {
super(name);
this.crawlerCTRL = crawlerCTRL;
}
public void run() {
while (crawlerCTRL.peekInputJob() != null){
Job job = null;
if (crawlerCTRL.peekInputJob().isDone()){
crawlerCTRL.nextJob();
job = crawlerCTRL.peekInputJob();
}
else
job = crawlerCTRL.peekInputJob();
if (job == null)
break;
Task task = job.popInputStack();
if (task == null){
this.waitFor();
continue;
}
String urlStr = task.getUrl();
String schedDir = task.getFolderPath();
String filename = task.getFilename();
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
JLogger jLogger = new JLogger();
try {
crawlerCTRL.println_Crawler("++>" + filename + " Started @" + Timer.getTimeStamp());
crawlerCTRL.clrTxt();
new File(schedDir).mkdir();
jLogger.openHTMLLog(schedDir + org.Setup._S_ + org.Setup.CFG_LOGNAME);
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
urlConn.setConnectTimeout(CONNECTION_TIMEOUT * 1000);
bin = new BufferedInputStream(urlConn.getInputStream(), 256);
bout = new BufferedOutputStream(new FileOutputStream(schedDir + org.Setup._S_ + filename), 256);
while(true){
int data = bin.read();
if (data == -1)
break;
bout.write(data);
}
bout.flush();
jLogger.burnHTMLLog("==>" + filename + " Done @ " + Timer.getTimeStamp());
crawlerCTRL.println_Crawler("==>" + filename + " Done @" + Timer.getTimeStamp());
}
catch (Exception e) {
try {
crawlerCTRL.println_Crawler("% Error: " + e.getMessage() + " @ "+ Timer.getTimeStamp());
e.printStackTrace();
jLogger.openHTMLLog_Error(schedDir + org.Setup._S_ + org.Setup.CFG_ERRORLOGNAME);
jLogger.burnHTMLLog(filename + " % Error @ " + Timer.getTimeStamp());
jLogger.burnHTMLLog_Error(filename + " % Error @ "+ Timer.getTimeStamp());
jLogger.burnHTMLLog_ErrorStack(e);
jLogger.closeHTMLLog_Error();
} catch (IOException e1){
System.err.println("Exception 1-2");
e1.printStackTrace();
}
}
finally{
System.err.println("Finally 1");
try {
//////////////////////
/////////////////////
if (task.getExtension().equals(".html")){
task.setType(AtlasJob.J_HTML);
}
if (task.getExtension().equals(".pdf")){
task.setType(AtlasJob.J_PDF);
}
if (task.getExtension().equals(".xml")){
task.setType(AtlasJob.J_XML);
}
job.toOutputBus(task);
crawlerCTRL.incProgress();
if (bin != null)
bin.close();
if (bout != null)
bout.close();
jLogger.closeHTMLLog();
} catch (Exception e) {
System.err.println("Exception 2");
e.printStackTrace();}
finally{
if (crawlerCTRL.isPause()){
this.waitForever();
crawlerCTRL.wakeProcessThread();
}
else{
crawlerCTRL.wakeProcessThread();
this.waitFor();
}
}
}
}//ENDWHILE
crawlerCTRL.killRecord(this);
}
private void waitFor(){
try {
Thread.sleep(crawlerCTRL.getInterval() * 1000);
} catch (InterruptedException e) {e.printStackTrace();}
}
private void waitForever(){
try {
synchronized(this){
crawlerCTRL.println_Crawler(this.getName() + " paused @ " + Timer.getTimeStamp());
this.wait();
}
} catch (InterruptedException e) {e.printStackTrace();}
}
}
| k9m/jharvester | src/org/controller/crawler/threads/CrawlerThread.java | Java | mpl-2.0 | 4,196 |
package org.plast.reg.ui;
import com.vaadin.navigator.View;
import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent;
import com.vaadin.ui.Label;
import com.vaadin.ui.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
public class MainView extends PlastView implements View {
@Override
public void enter(ViewChangeEvent event) {
// TODO Auto-generated method stub
Notification.show("Entered the MainView");
buildLayout();
}
public MainView() {
buildLayout();
}
public void buildLayout(){
VerticalLayout layout = new VerticalLayout();
Label label = new Label ("Thisis a cool label");
layout.addComponent(label);
setContent(layout);
}
}
| linster/PlastRegSystem | src/org/plast/reg/ui/MainView.java | Java | mpl-2.0 | 700 |
/**
* Copyright (c) 2019, RTE (http://www.rte-france.com)
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package com.powsybl.triplestore.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.google.common.jimfs.Configuration;
import com.google.common.jimfs.Jimfs;
import com.powsybl.commons.datasource.DataSource;
import com.powsybl.commons.datasource.FileDataSource;
import com.powsybl.triplestore.api.PrefixNamespace;
import com.powsybl.triplestore.api.PropertyBag;
import com.powsybl.triplestore.api.PropertyBags;
import com.powsybl.triplestore.api.TripleStore;
import com.powsybl.triplestore.api.TripleStoreFactory;
/**
*
* @author Massimo Ferraro <[email protected]>
*/
public class ExportTest {
private final String networkId = "network-id";
private final String cimNamespace = "http://iec.ch/TC57/2013/CIM-schema-cim16#";
private final String baseNamespace = "http://" + networkId + "/#";
private final String bvName = "380kV";
private final double nominalVoltage = 380;
private final String vl1Name = "S1 380kV";
private final String vl2Name = "S2 380kV";
private final String substation1Id = "_af9a4ae3-ba2e-4c34-8e47-5af894ee20f4";
private final String substation2Id = "_d6056127-34f1-43a9-b029-23fddb913bd5";
private final String query = "SELECT ?voltageLevel ?vlName ?substation ?baseVoltage ?bvName ?nominalVoltage" + System.lineSeparator() +
"{" + System.lineSeparator() +
" ?voltageLevel" + System.lineSeparator() +
" a cim:VoltageLevel ;" + System.lineSeparator() +
" cim:IdentifiedObject.name ?vlName ;" + System.lineSeparator() +
" cim:VoltageLevel.Substation ?substation ;" + System.lineSeparator() +
" cim:VoltageLevel.BaseVoltage ?baseVoltage." + System.lineSeparator() +
" ?baseVoltage" + System.lineSeparator() +
" a cim:BaseVoltage ;" + System.lineSeparator() +
" cim:IdentifiedObject.name ?bvName ;" + System.lineSeparator() +
" cim:BaseVoltage.nominalVoltage ?nominalVoltage ." + System.lineSeparator() +
"}";
private final String exportFolderName = "/export";
private FileSystem fileSystem;
private Path exportFolder;
@Before
public void setUp() throws Exception {
fileSystem = Jimfs.newFileSystem(Configuration.unix());
exportFolder = Files.createDirectory(fileSystem.getPath(exportFolderName));
}
@After
public void tearDown() throws Exception {
fileSystem.close();
}
private PropertyBag createBaseVoltageProperties() {
PropertyBag baseVoltageProperties = new PropertyBag(Arrays.asList("IdentifiedObject.name", "nominalVoltage"));
baseVoltageProperties.setClassPropertyNames(Arrays.asList("IdentifiedObject.name"));
baseVoltageProperties.put("IdentifiedObject.name", bvName);
baseVoltageProperties.put("nominalVoltage", Double.toString(nominalVoltage));
return baseVoltageProperties;
}
private PropertyBag createVoltageLevelProperties(String baseVoltageId, String vlName, String substationId) {
PropertyBag voltageLevelProperties = new PropertyBag(Arrays.asList("IdentifiedObject.name", "Substation", "BaseVoltage"));
voltageLevelProperties.setResourceNames(Arrays.asList("Substation", "BaseVoltage"));
voltageLevelProperties.setClassPropertyNames(Arrays.asList("IdentifiedObject.name"));
voltageLevelProperties.put("IdentifiedObject.name", vlName);
voltageLevelProperties.put("Substation", substationId);
voltageLevelProperties.put("BaseVoltage", baseVoltageId);
return voltageLevelProperties;
}
@Test
public void test() throws IOException {
for (String implementation : TripleStoreFactory.allImplementations()) {
// create export triple store
TripleStore exportTripleStore = TripleStoreFactory.create(implementation);
// add namespaces to triple store
exportTripleStore.addNamespace("data", baseNamespace);
exportTripleStore.addNamespace("cim", cimNamespace);
// create context
String contextName = networkId + "_" + "EQ" + "_" + implementation + ".xml";
// add statements to triple stores
// add base voltage statements
String baseVoltageId = exportTripleStore.add(contextName, cimNamespace, "BaseVoltage", createBaseVoltageProperties());
// add voltage levels statements
PropertyBags voltageLevelsProperties = new PropertyBags();
voltageLevelsProperties.add(createVoltageLevelProperties(baseVoltageId, vl1Name, substation1Id));
voltageLevelsProperties.add(createVoltageLevelProperties(baseVoltageId, vl2Name, substation2Id));
exportTripleStore.add(contextName, cimNamespace, "VoltageLevel", voltageLevelsProperties);
checkRepository(exportTripleStore, baseVoltageId);
// export triple store
DataSource dataSource = new FileDataSource(exportFolder, networkId + "_" + implementation);
exportTripleStore.write(dataSource);
// create import triple store
TripleStore importTripleStore = TripleStoreFactory.create(implementation);
// import data into triple store
try (InputStream is = dataSource.newInputStream(contextName)) {
importTripleStore.read(is, "http://" + networkId, contextName);
}
checkRepository(importTripleStore, baseVoltageId);
}
}
private void checkRepository(TripleStore tripleStore, String baseVoltageId) {
// check namespaces
assertTrue(tripleStore.getNamespaces().contains(new PrefixNamespace("data", baseNamespace)));
assertTrue(tripleStore.getNamespaces().contains(new PrefixNamespace("cim", cimNamespace)));
// query import triple store
tripleStore.defineQueryPrefix("cim", cimNamespace);
PropertyBags results = tripleStore.query(query);
// check query results
assertEquals(2, results.size());
results.forEach(result -> {
assertTrue(Arrays.asList(vl1Name, vl2Name).contains(result.getId("vlName")));
assertTrue(Arrays.asList(baseNamespace + substation1Id, baseNamespace + substation2Id).contains(result.get("substation")));
assertTrue(Arrays.asList(substation1Id, substation2Id).contains(result.getId("substation")));
assertEquals(baseNamespace + baseVoltageId, result.get("baseVoltage"));
assertEquals(baseVoltageId, result.getId("baseVoltage"));
assertEquals(bvName, result.get("bvName"));
assertEquals(nominalVoltage, result.asDouble("nominalVoltage"), 0);
});
}
}
| powsybl/powsybl-core | triple-store/triple-store-test/src/test/java/com/powsybl/triplestore/test/ExportTest.java | Java | mpl-2.0 | 7,315 |
/**
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0, as well as to the Additional Term regarding proper
attribution. The latter is located in Term 11 of the License.
If a copy of the MPL with the Additional Term was not distributed
with this file, You can obtain one at http://static.fuzzhq.com/licenses/MPL
*/
package com.fuzz.android.limelight.recorder.widget.editor.operations;
import com.fuzz.android.limelight.recorder.widget.editor.ActEditor;
/**
* @author Leonard Collins (Fuzz)
*/
public class ChangeIconOperation extends BaseOperation {
public ChangeIconOperation(ActEditor actEditor) {
super(actEditor);
}
}
| fuzz-productions/LimeLight | src/main/java/com/fuzz/android/limelight/recorder/widget/editor/operations/ChangeIconOperation.java | Java | mpl-2.0 | 681 |
/**
* Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.security;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
/**
* Annotation that marks classes and methods which should be intercepted and checked for subject role ownership.
*
* @author [email protected]
*/
@Target({TYPE, METHOD})
@Retention(RUNTIME)
public @interface RequiresRoles {
/**
* @return the array of role names to check for.
*/
String[] value();
/**
* @return the logical operator to use between multiple roles.
*/
Logical logical() default Logical.AND;
}
| pith/seed | security/specs/src/main/java/org/seedstack/seed/security/RequiresRoles.java | Java | mpl-2.0 | 1,020 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.math.geometry;
import java.util.LinkedList;
import etomica.api.IVector;
/**
* Representation of a mathematical polyhedron, a 3-dimensional polytope. Contains
* all information needed to represent a polyhedron, methods to set its position
* and orientation, and methods that return an external representation of it.
* Provides no external means to change the polyhedron size and shape, as the form
* and capabilities of mutator methods are particular to the type of polyhedron
* defined by the subclass.
*/
public abstract class Polyhedron extends Polytope {
/**
* Constructs a polyhedron with the given faces for its sides. Faces
* should be constructed so they have the correct sharing of edges
* between adjacent faces, and sharing of vertices between intersecting
* edges.
*/
protected Polyhedron(Polygon[] faces) {
super(faces);
this.faces = faces;
this.edges = allEdges(faces);
}
/**
* Returns all faces defined by the polyhedron.
*/
public Polygon[] getFaces() {
return faces;
}
/**
* Returns all edges defined by the polyhedron.
*/
public LineSegment[] getEdges() {
return edges;
}
/**
* Returns the sum of the length of the edges of the polyhedron
*/
public double getPerimeter() {
double sum = 0.0;
for(int i=0; i<edges.length; i++) {
sum += edges[i].getLength();
}
return sum;
}
/**
* Returns the sum the area of the faces of the polyhedron
*/
public double getSurfaceArea() {
double sum = 0.0;
for(int i=0; i<faces.length; i++) {
sum += faces[i].getArea();
}
return sum;
}
/**
* Returns the perpendicular distance to the nearest face of the
* polyhedron. Assumes that given point is contained in polyhedron;
* if not, returns NaN.
* @param r
* @return
*/
public double distanceTo(IVector r) {
if(!contains(r)) return Double.NaN;
double d = Double.POSITIVE_INFINITY;
Plane plane = new Plane(embeddedSpace);
for(int i=0; i<faces.length; i++) {
Polygon f = faces[i];
plane.setThreePoints(vertices[0],
vertices[1], vertices[2]);
double d1 = Math.abs(plane.distanceTo(r));
if(d1 < d) d = d1;
}
return d;
}
/**
* Finds all edge instances in the given array of faces, and returns
* them in an array. Each edge appears in the array once, although it
* should be part of multiple faces. Used by constructor.
*/
private static LineSegment[] allEdges(Polygon[] faces) {
LinkedList list = new LinkedList();
for(int i=0; i<faces.length; i++) {
LineSegment[] edges= faces[i].getEdges();
for(int j=0; j<edges.length; j++) {
if(!list.contains(edges[j])) {
list.add(edges[j]);
}
}
}
return (LineSegment[])list.toArray(new LineSegment[0]);
}
protected final LineSegment[] edges;
protected final Polygon[] faces;
}
| ajschult/etomica | etomica-core/src/main/java/etomica/math/geometry/Polyhedron.java | Java | mpl-2.0 | 3,459 |
package io.github.plastix.forage.ui.map;
import dagger.Subcomponent;
import io.github.plastix.forage.ui.ActivityScope;
/**
* Dagger component to inject all required dependencies into {@link MapActivity}.
*/
@ActivityScope
@Subcomponent(
modules = {
MapModule.class
}
)
public interface MapComponent {
void injectTo(MapActivity mapActivity);
}
| Plastix/Forage | app/src/main/java/io/github/plastix/forage/ui/map/MapComponent.java | Java | mpl-2.0 | 383 |
package org.echocat.jomon.runtime.numbers;
import org.echocat.jomon.runtime.annotations.Excluding;
import org.echocat.jomon.runtime.annotations.Including;
import org.hamcrest.CoreMatchers;
import org.junit.Test;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import static javax.xml.bind.JAXBContext.newInstance;
import static javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT;
import static org.echocat.jomon.runtime.numbers.LongRangeUnitTest.XmlTest.testElement;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public class LongRangeUnitTest {
public static final String XML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
"<xmlTest>\n" +
" <longRange from=\"-666\" to=\"666\"/>\n" +
"</xmlTest>\n";
@Test
public void testMarshall() throws Exception {
try (final Writer writer = new StringWriter()) {
marshaller().marshal(testElement(), writer);
assertThat(writer.toString(), is(XML));
}
}
@Test
public void testUnmarshall() throws Exception {
try (final Reader reader = new StringReader(XML)) {
final Object element = unmarshaller().unmarshal(reader);
assertThat(element, CoreMatchers.<Object>is(testElement()));
}
}
@Nonnull
protected static Marshaller marshaller() throws JAXBException {
final JAXBContext context = context();
final Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(JAXB_FORMATTED_OUTPUT, true);
return marshaller;
}
@Nonnull
protected static Unmarshaller unmarshaller() throws JAXBException {
final JAXBContext context = context();
return context.createUnmarshaller();
}
@Nonnull
protected static JAXBContext context() throws JAXBException {
return newInstance(XmlTest.class);
}
@XmlRootElement(name = "xmlTest")
public static class XmlTest {
@Nonnull
public static XmlTest testElement() {
return testElement(-666L, 666L);
}
@Nonnull
public static XmlTest testElement(@Nullable @Including Long from, @Nullable @Excluding Long to) {
final LongRange range = new LongRange(from, to);
final XmlTest element = new XmlTest();
element.setRange(range);
return element;
}
private LongRange _range;
@XmlElement(name = "longRange")
public LongRange getRange() {
return _range;
}
public void setRange(LongRange range) {
_range = range;
}
@Override
public boolean equals(Object o) {
final boolean result;
if (this == o) {
result = true;
} else if (o == null || getClass() != o.getClass()) {
result = false;
} else {
final XmlTest that = (XmlTest) o;
result = _range != null ? _range.equals(that._range) : that._range == null;
}
return result;
}
@Override
public int hashCode() {
return _range != null ? _range.hashCode() : 0;
}
}
}
| echocat/jomon | runtime/src/test/java/org/echocat/jomon/runtime/numbers/LongRangeUnitTest.java | Java | mpl-2.0 | 3,622 |
package com.denimgroup.threadfix.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Properties;
import javax.net.SocketFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.multipart.FilePart;
import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity;
import org.apache.commons.httpclient.methods.multipart.Part;
import org.apache.commons.httpclient.methods.multipart.StringPart;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class HttpRestUtils {
public final String API_KEY_ERROR = "Authentication failed, check your API Key.";
private String url = null;
private String key = null;
private Properties properties;
public String httpPostFile(String request, String fileName, String[] paramNames,
String[] paramVals) {
File file = new File(fileName);
return httpPostFile(request, file, paramNames,
paramVals);
}
public String httpPostFile(String request, File file, String[] paramNames,
String[] paramVals) {
Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));
PostMethod filePost = new PostMethod(request);
filePost.setRequestHeader("Accept", "application/json");
try {
Part[] parts = new Part[paramNames.length + 1];
parts[paramNames.length] = new FilePart("file", file);
for (int i = 0; i < paramNames.length; i++) {
parts[i] = new StringPart(paramNames[i], paramVals[i]);
}
filePost.setRequestEntity(new MultipartRequestEntity(parts,
filePost.getParams()));
filePost.setContentChunked(true);
HttpClient client = new HttpClient();
int status = client.executeMethod(filePost);
if (status != 200) {
System.err.println("Status was not 200.");
}
InputStream responseStream = filePost.getResponseBodyAsStream();
if (responseStream != null) {
return IOUtils.toString(responseStream);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "There was an error and the POST request was not finished.";
}
public String httpPost(String request, String[] paramNames,
String[] paramVals) {
Protocol.registerProtocol("https", new Protocol("https", new HttpRestUtils.AcceptAllTrustFactory(), 443));
PostMethod post = new PostMethod(request);
post.setRequestHeader("Accept", "application/json");
try {
for (int i = 0; i < paramNames.length; i++) {
post.addParameter(paramNames[i], paramVals[i]);
}
HttpClient client = new HttpClient();
int status = client.executeMethod(post);
if (status != 200) {
System.err.println("Status was not 200.");
}
InputStream responseStream = post.getResponseBodyAsStream();
if (responseStream != null) {
return IOUtils.toString(responseStream);
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "There was an error and the POST request was not finished.";
}
public String httpGet(String urlStr) {
System.out.println("Requesting " + urlStr);
Protocol.registerProtocol("https", new Protocol("https", new AcceptAllTrustFactory(), 443));
GetMethod get = new GetMethod(urlStr);
get.setRequestHeader("Accept", "application/json");
HttpClient client = new HttpClient();
try {
int status = client.executeMethod(get);
if (status != 200) {
System.err.println("Status was not 200.");
}
InputStream responseStream = get.getResponseBodyAsStream();
if (responseStream != null) {
return IOUtils.toString(responseStream);
}
} catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "There was an error and the GET request was not finished.";
}
/**
* Convenience method to wrap the exception catching.
* @param responseContents
* @return
*/
public JSONObject getJSONObject(String responseContents) {
if (responseContents == null) {
return null;
}
try {
return new JSONObject(responseContents);
} catch (JSONException e) {
return null;
}
}
/**
* Convenience method to wrap the exception catching.
* @param object
* @return
*/
public Integer getId(JSONObject object) {
if (object == null) {
return null;
}
try {
return object.getInt("id");
} catch (JSONException e) {
return null;
}
}
public String getString(JSONObject object, String key) {
if (object == null || key == null) {
return null;
}
try {
return object.getString(key);
} catch (JSONException e) {
return null;
}
}
public JSONArray getJSONArray(String responseContents) {
if (responseContents == null) {
return null;
}
try {
return new JSONArray(responseContents);
} catch (JSONException e) {
return null;
}
}
/**
* This method is a wrapper for RandomStringUtils.random with a preset character set.
* @return random string
*/
protected static String getRandomString(int length) {
return RandomStringUtils.random(length,"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
}
// These methods help persist the URL and API Key so they don't have to be entered each time.
public void setUrl(String url) {
writeProperty("url", url);
}
public void setKey(String key) {
writeProperty("key", key);
}
public String getUrl() {
if (url == null) {
url = getProperty("url");
if (url == null) {
url = "http://localhost:8080/threadfix/rest";
}
}
return url;
}
public String getKey() {
if (key == null) {
key = getProperty("key");
if (key == null) {
System.out.println("Please set your API key with the command 's k {key}'");
}
}
return key;
}
private String getProperty(String propName) {
if (properties == null) {
readProperties();
if (properties == null) {
properties = new Properties();
writeProperties();
}
}
return properties.getProperty(propName);
}
private void writeProperty(String propName, String propValue) {
readProperties();
properties.setProperty(propName, propValue);
writeProperties();
}
private void readProperties() {
FileInputStream in = null;
try {
in = new FileInputStream("threadfix.properties");
if (properties == null) {
properties = new Properties();
}
properties.load(in);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
private void writeProperties() {
FileOutputStream out = null;
try {
out = new FileOutputStream("threadfix.properties");
properties.store(out, "Writing.");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
/**
* These two classes allow the self-signed SSL cert to work. We might be able to cut this down.
* @author mcollins
*
*/
public static class AcceptAllTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public X509Certificate[] getAcceptedIssuers() { return null; }
}
public class AcceptAllTrustFactory implements ProtocolSocketFactory {
private SSLContext sslContext = null;
private SSLContext createAcceptAllSSLContext() {
try {
AcceptAllTrustManager acceptAllTrustManager = new AcceptAllTrustManager();
SSLContext context = SSLContext.getInstance("TLS");
context.init(null,
new AcceptAllTrustManager[] { acceptAllTrustManager },
null);
return context;
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
private SSLContext getSSLContext() {
if(this.sslContext == null) {
this.sslContext = createAcceptAllSSLContext();
}
return this.sslContext;
}
public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException {
return getSSLContext().getSocketFactory().createSocket(host, port, clientHost, clientPort);
}
public Socket createSocket(final String host, final int port, final InetAddress localAddress, final int localPort, final HttpConnectionParams params) throws IOException {
if(params == null) {
throw new IllegalArgumentException("Parameters may not be null");
}
int timeout = params.getConnectionTimeout();
SocketFactory socketFactory = getSSLContext().getSocketFactory();
if(timeout == 0) {
return socketFactory.createSocket(host, port, localAddress, localPort);
}
else {
Socket socket = socketFactory.createSocket();
SocketAddress localAddr = new InetSocketAddress(localAddress, localPort);
SocketAddress remoteAddr = new InetSocketAddress(host, port);
socket.bind(localAddr);
socket.connect(remoteAddr, timeout);
return socket;
}
}
public Socket createSocket(String host, int port) throws IOException {
return getSSLContext().getSocketFactory().createSocket(host, port);
}
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
}
}
}
| jqxin2006/threadfixRack | util/command-line-interface/util/HttpRestUtils.java | Java | mpl-2.0 | 11,395 |
/*
* Software Name: OCARA
*
* SPDX-FileCopyrightText: Copyright (c) 2015-2020 Orange
* SPDX-License-Identifier: MPL v2.0
*
* This software is distributed under the Mozilla Public License v. 2.0,
* the text of which is available at http://mozilla.org/MPL/2.0/ or
* see the "license.txt" file for more details.
*/
package com.orange.ocara.data.cache.file;
import android.content.Context;
import com.orange.ocara.data.common.ConnectorException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import timber.log.Timber;
/** implementation of {@link ImageStorage} that reads images stored in assets */
public class AssetImageStorageImpl implements ImageStorage {
private final Context context;
private final String rootDirectory;
/**
* instantiate
*
* @param context an Android {@link Context}
* @param rootDirectory an assets subdirectory
*/
public AssetImageStorageImpl(Context context, String rootDirectory) {
this.context = context;
this.rootDirectory = rootDirectory;
}
@Override
public List<String> list(String directory) {
List<String> assets;
try {
String[] list = context.getAssets().list(rootDirectory + File.separator + directory);
assets = list == null ? Collections.emptyList() : Arrays.asList(list);
} catch (IOException e) {
Timber.w(e);
assets = Collections.emptyList();
}
return assets;
}
@Override
public InputStream read(String filename, String directory) {
try {
return context.getAssets().open(rootDirectory + File.separator + directory + File.separator + filename);
} catch (IOException e) {
throw ConnectorException.from(e);
}
}
@Override
public boolean fileExists(String filename, String directory) {
return list(directory).contains(filename);
}
@Override
public boolean isEmpty(String directory) {
return list(directory).isEmpty();
}
@Override
public void write(InputStream inputStream, String targetFilename, String targetSubDirectory) {
throw new ConnectorException("Writing in the assets is not allowed");
}
}
| Orange-OpenSource/ocara | app/src/main/java/com/orange/ocara/data/cache/file/AssetImageStorageImpl.java | Java | mpl-2.0 | 2,348 |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package br.com.syscontrol.dao;
import br.com.syscontrol.model.Colaborador;
import java.sql.SQLException;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
/**
*
* @author Diego
*/
public class ColaboradorDao implements IColaboradorDAO<Colaborador> {
private static final Logger LOG = Logger.getLogger("ColaboradorDao");
private final Session session;
public ColaboradorDao() {
this.session = HibernateFactory.getSession();
}
@Override
public Colaborador buscarPorNome(String nome) throws SQLException {
LOG.info("Iniciando busca de Colaborador por Nome [" + nome + "]");
Criteria criteria = session.createCriteria(Colaborador.class);
criteria.add(Restrictions.ilike("nome", nome)).addOrder(Order.asc("nome"));
try{
synchronized (this.session) {
List<Colaborador> listaObject = criteria.list();
if(listaObject.isEmpty()){
return new Colaborador();
}else{
return listaObject.get(0);
}
}
}catch(Exception ex){
LOG.error("Falha ao realizar consulta de Colaborador por Nome",ex);
throw new SQLException();
}
}
@Override
public void atualizar(Colaborador colaborador) throws SQLException {
LOG.info("Iniciando atualização do Colaborador Id [" + colaborador.getId() + "]");
try{
Transaction tx = session.beginTransaction();
session.update(colaborador);
tx.commit();
}catch(Exception ex){
LOG.error("Falha ao atualizar Colaborador",ex);
throw new SQLException();
}
}
@Override
public Colaborador buscarPorId(Long id) throws SQLException {
LOG.info("Iniciando busca de Colaborador por Id [" + id + "]");
Criteria criteria = session.createCriteria(Colaborador.class);
criteria.add(Restrictions.eq("id", id));
try{
synchronized (this.session) {
List<Colaborador> listaObject = criteria.list();
if(listaObject.isEmpty()){
return new Colaborador();
}else{
return listaObject.get(0);
}
}
}catch(Exception ex){
LOG.error("Falha ao realizar consulta de Colaborador por Id",ex);
throw new SQLException();
}
}
@Override
public List<Colaborador> buscarTodos() throws SQLException {
LOG.info("Iniciando busca de todos os Colaboradores");
Criteria criteria = session.createCriteria(Colaborador.class);
criteria.addOrder(Order.asc("nome"));
try{
synchronized (this.session) {
List<Colaborador> listaColaboradores = criteria.list();
LOG.info("Encontrados [" + listaColaboradores.size() + "] Colaboradores" ) ;
return listaColaboradores;
}
}catch(Exception ex){
LOG.error("Falha ao buscar todos os Colaboradores",ex);
throw new SQLException();
}
}
@Override
public void remover(Colaborador colaborador) throws SQLException {
LOG.info("Removendo o Colaborador Id [" + colaborador.getId() + "]");
try{
Transaction tx = session.beginTransaction();
session.delete(colaborador);
tx.commit();
}catch(Exception ex){
LOG.error("Falha ao remover o Colaborador",ex);
throw new SQLException();
}
}
@Override
public void salvar(Colaborador colaborador) throws SQLException {
LOG.info("Salvando o Colaborador Nome [" + colaborador.getNome() + "]");
try{
Transaction tx = session.beginTransaction();
session.save(colaborador);
tx.commit();
}catch(Exception ex){
LOG.error("Falha ao salvar o Colaborador",ex);
throw new SQLException();
}
}
}
| lemosadiego/syscontrol | src/br/com/syscontrol/dao/ColaboradorDao.java | Java | mpl-2.0 | 4,476 |
package org.openlca.app.ilcd_network;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.openlca.app.M;
import org.openlca.app.preferences.IoPreference;
import org.openlca.core.database.IDatabase;
import org.openlca.core.database.ProcessDao;
import org.openlca.core.database.ProductSystemDao;
import org.openlca.core.model.ModelType;
import org.openlca.core.model.Process;
import org.openlca.core.model.ProductSystem;
import org.openlca.core.model.descriptors.Descriptor;
import org.openlca.ilcd.io.SodaClient;
import org.openlca.io.ilcd.output.ExportConfig;
import org.openlca.io.ilcd.output.ProcessExport;
import org.openlca.io.ilcd.output.SystemExport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Export implements IRunnableWithProgress {
private Logger log = LoggerFactory.getLogger(this.getClass());
private List<Descriptor> descriptors;
private IProgressMonitor monitor;
private IDatabase database;
public Export(List<Descriptor> exportTupels, IDatabase database) {
this.descriptors = exportTupels;
this.database = database;
}
@Override
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
beginTask(monitor);
SodaClient client = tryCreateClient();
ExportConfig config = new ExportConfig(database, client);
config.lang = IoPreference.getIlcdLanguage();
Iterator<Descriptor> it = descriptors.iterator();
while (!monitor.isCanceled() && it.hasNext()) {
Descriptor d = it.next();
monitor.subTask(d.name);
createRunExport(config, d);
}
monitor.done();
}
private SodaClient tryCreateClient() throws InvocationTargetException {
try {
SodaClient client = IoPreference.createClient();
client.connect();
return client;
} catch (Exception e) {
throw new InvocationTargetException(e, "Could not connect.");
}
}
private void beginTask(IProgressMonitor monitor) {
this.monitor = monitor;
String taskName = M.ILCDNetworkExport;
monitor.beginTask(taskName, descriptors.size() + 1);
log.info(taskName);
}
private void createRunExport(ExportConfig config, Descriptor d) {
if (d.type == ModelType.PROCESS)
tryExportProcess(config, d);
else if (d.type == ModelType.PRODUCT_SYSTEM)
tryExportSystem(config, d);
}
private void tryExportProcess(ExportConfig config, Descriptor d) {
try {
Process p = new ProcessDao(database).getForId(d.id);
ProcessExport export = new ProcessExport(config);
export.run(p);
monitor.worked(1);
} catch (Exception e) {
log.error("Process export failed", e);
}
}
private void tryExportSystem(ExportConfig config, Descriptor d) {
try {
ProductSystem system = new ProductSystemDao(database).getForId(d.id);
SystemExport export = new SystemExport(config);
export.run(system);
monitor.worked(1);
} catch (Exception e) {
log.error("System export failed", e);
}
}
}
| GreenDelta/olca-app | olca-app/src/org/openlca/app/ilcd_network/Export.java | Java | mpl-2.0 | 3,054 |
package org.mozilla.taskcluster.client.queue;
/**
* Response to a request for the queue to reply `424` (Failed Dependency)
* with `reason` and `message` to any `GET` request for this artifact.
*
* See https://schemas.taskcluster.net/queue/v1/post-artifact-response.json#/oneOf[4]
*/
public class ErrorArtifactResponse {
/**
* Artifact storage type, in this case `error`
*
* Possible values:
* * "error"
*
* See https://schemas.taskcluster.net/queue/v1/post-artifact-response.json#/oneOf[4]/properties/storageType
*/
public String storageType;
}
| taskcluster/taskcluster-client-java | src/main/java/org/mozilla/taskcluster/client/queue/ErrorArtifactResponse.java | Java | mpl-2.0 | 599 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package etomica.models.nitrogen;
import etomica.api.IRandom;
import etomica.data.DataSourceScalar;
import etomica.data.meter.MeterPotentialEnergy;
import etomica.data.meter.MeterPotentialEnergyFromIntegrator;
import etomica.integrator.IntegratorBox;
import etomica.units.Null;
/**
* Meter used for overlap sampling in the target-sampled system. The meter
* measures the ratio of the Boltzmann factors for the reference and target
* potentials.
*
*
*
* @author Tai Boon Tan
*/
public class MeterDirectInitPert extends DataSourceScalar {
public MeterDirectInitPert(IntegratorBox integrator, MeterPotentialEnergy meterPotentialEnergy, CoordinateDefinitionNitrogen coordinateDef, IRandom random) {
super("Scaled Unit",Null.DIMENSION);
meterEnergy = new MeterPotentialEnergyFromIntegrator(integrator);
this.integrator = integrator;
this.meterPotentialEnergy = meterPotentialEnergy;
this.coordinateDef = coordinateDef;
this.random = random;
newU = new double[coordinateDef.getCoordinateDim()];
initU = new double[coordinateDef.getCoordinateDim()];
}
public double getDataAsScalar() {
double uTransOnly = meterEnergy.getDataAsScalar();
initU = coordinateDef.calcU(meterPotentialEnergy.getBox().getMoleculeList());
/*
* Generating random u3 and u4 values that satisfy the u_max value (constraint angle)
*
* u3^2 + u4^2 = 2[ 1- cos(theta) ]
* at small theta limit, the equation becomes:
* u3^2 + u4^2 = theta^2
*
* u3^2 + u4^2 = u_max^2
* u_max^2 = 2[ 1 - cos(theta) ] = theta^2
* u_max = sqrt(2[1-cos(theta)]) = theta
*
*/
for(int i=0; i<coordinateDef.getCoordinateDim(); i+=5){
for(int j=0; j<3; j++){
newU[i+j] = initU[i+j];
}
double u3 = 2.0;
double u4 = 2.0;
while ( (u3*u3+u4*u4) > 2*(1-Math.cos(constraintAngle))){
u3 = (2*random.nextDouble() - 1.0)*(constraintAngle/180.0) *Math.PI;
u4 = (2*random.nextDouble() - 1.0)*(constraintAngle/180.0) *Math.PI;
}
newU[i+3] = u3;
newU[i+4] = u4;
}
coordinateDef.setToU(meterPotentialEnergy.getBox().getMoleculeList(), newU);
double uTransAndRotate = meterPotentialEnergy.getDataAsScalar();
coordinateDef.setToU(meterPotentialEnergy.getBox().getMoleculeList(), initU);
if(Double.isNaN(uTransOnly) || Double.isNaN(uTransAndRotate)){
throw new RuntimeException("<MeterDirectInitPert> energy is NaN!!!!!!!!!!!!");
}
//System.out.println(uSampled + " " + uMeasured + " "+ (uMeasured-uSampled) + " " + Math.exp(-(uMeasured - uSampled) / integrator.getTemperature()));
return Math.exp(-(uTransAndRotate - uTransOnly) / integrator.getTemperature());
}
public double getConstraintAngle() {
return constraintAngle;
}
public void setConstraintAngle(double constraintAngle) {
this.constraintAngle = constraintAngle;
}
private static final long serialVersionUID = 1L;
protected final MeterPotentialEnergyFromIntegrator meterEnergy;
protected final MeterPotentialEnergy meterPotentialEnergy;
protected final IntegratorBox integrator;
protected double constraintAngle;
protected CoordinateDefinitionNitrogen coordinateDef;
protected IRandom random;
protected double[] newU, initU;
}
| ajschult/etomica | etomica-apps/src/main/java/etomica/models/nitrogen/MeterDirectInitPert.java | Java | mpl-2.0 | 3,504 |
/*
* Copyright (c) 2014 Faust Edition development team.
*
* This file is part of the Faust Edition.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.faustedition.transcript;
import com.google.common.collect.Sets;
import de.faustedition.FaustURI;
import de.faustedition.Runtime;
import de.faustedition.document.DocumentDescriptorHandler;
import de.faustedition.document.MaterialUnit;
import de.faustedition.graph.FaustGraph;
import de.faustedition.transcript.input.TranscriptInvalidException;
import de.faustedition.xml.XMLStorage;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.StopWatch;
import javax.xml.stream.XMLStreamException;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Set;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
@Service
public class TranscriptBatchReader extends Runtime implements Runnable {
@Autowired
private FaustGraph graph;
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private XMLStorage xml;
@Autowired
private Logger logger;
@Autowired
private TranscriptManager transcriptManager;
@Override
public void run() {
logger.debug("Reading transcripts in the background");
StopWatch stopWatch = new StopWatch();
stopWatch.start();
final Set<FaustURI> imported = Sets.<FaustURI>newHashSet();
final Deque<MaterialUnit> queue = new ArrayDeque<MaterialUnit>(graph.getMaterialUnits());
while (!queue.isEmpty()) {
final MaterialUnit mu = queue.pop();
final String source = mu.getMetadataValue(DocumentDescriptorHandler.internalKeyDocumentSource);
final FaustURI transcriptSource = mu.getTranscriptSource();
for (MaterialUnit child: mu) {
if (!imported.contains(transcriptSource)) {
imported.add(transcriptSource);
queue.add(child);
}
//queue.addAll(mu);
}
if (mu.getTranscriptSource() == null || DocumentDescriptorHandler.noneURI.equals(transcriptSource)) {
continue;
}
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
try {
logger.debug("Reading transcript {} referenced in {}", transcriptSource, source);
transcriptManager.find(mu);
} catch (IOException e) {
if (logger.isWarnEnabled()) {
logger.warn("I/O error while reading transcript from " + mu + ": "
+ source, e);
}
} catch (XMLStreamException e) {
if (logger.isWarnEnabled()) {
logger.warn("XML error while reading transcript from " + mu + ": "
+ source, e);
}
} catch (TranscriptInvalidException e) {
if (logger.isWarnEnabled()) {
logger.warn("Validation error while reading transcript from " + mu + ": "
+ source, e);
}
}
}
});
}
stopWatch.stop();
logger.debug("Read transcripts in the background: {} s", stopWatch.getTotalTimeSeconds());
}
public static void main(String... args) throws Exception {
main(TranscriptBatchReader.class, args);
System.exit(0);
}
}
| faustedition/faust-base | faust/src/main/java/de/faustedition/transcript/TranscriptBatchReader.java | Java | agpl-3.0 | 4,147 |
package jcog.constraint.continuous;
/**
* Created by alex on 30/01/15.
*/
public class DoubleTerm {
public final DoubleVar var;
double coefficient;
public DoubleTerm(DoubleVar var, double coefficient) {
this.var = var;
this.coefficient = coefficient;
}
public DoubleTerm(DoubleVar var) {
this(var, 1.0);
}
public void setCoefficient(double coefficient) {
this.coefficient = coefficient;
}
public double value() {
return coefficient * var.value();
}
@Override
public String toString() {
return "variable: (" + var + ") coefficient: " + coefficient;
}
}
| automenta/narchy | util/src/main/java/jcog/constraint/continuous/DoubleTerm.java | Java | agpl-3.0 | 662 |
/* Copyright (C) 2003-2016 Patrick G. Durand
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You may obtain a copy of the License at
*
* https://www.gnu.org/licenses/agpl-3.0.txt
*
* 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 Affero General Public License for more details.
*/
package bzh.plealog.bioinfo.ui.blast;
import java.awt.BorderLayout;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import bzh.plealog.bioinfo.api.data.searchresult.SRHsp;
import bzh.plealog.bioinfo.api.data.searchresult.SROutput;
import bzh.plealog.bioinfo.api.data.searchresult.SRRequestInfo;
import bzh.plealog.bioinfo.ui.blast.config.ConfigManager;
import bzh.plealog.bioinfo.ui.blast.core.BlastEntry;
import bzh.plealog.bioinfo.ui.blast.core.BlastHitHSP;
import bzh.plealog.bioinfo.ui.blast.event.BlastHitListSupport;
import bzh.plealog.bioinfo.ui.blast.hittable.BlastHitTable;
import bzh.plealog.bioinfo.ui.blast.nav.BlastNavigator;
import bzh.plealog.bioinfo.ui.blast.saviewer.SeqAlignViewer;
import bzh.plealog.bioinfo.ui.resources.SVMessages;
import com.plealog.genericapp.api.EZEnvironment;
import com.plealog.genericapp.ui.common.JHeadPanel;
/**
* This is the BlastViewer Main Module.
*
* It wraps within a single component the various
* elements required to displaye Blast data: a BlastNavigator, a Blast Hit Table,
* the pairwise sequence alignment viewer, etc.
*
* @author Patrick G. Durand
*/
public class BlastViewerPanelBase extends JPanel {
private static final long serialVersionUID = -2405089127382200483L;
protected BlastHitTable _hitListPane;
protected SeqAlignViewer _seqAlignViewer;
protected BlastNavigator _summaryPane;
protected JPanel _rightPane;
protected BlastHitListSupport _updateSupport;
protected static final String HITPANEL_HEADER = SVMessages.getString("BlastViewerPanel.0");
protected static final String HITPANEL_LIST = SVMessages.getString("BlastViewerPanel.1");
protected static final String HITPANEL_GRAPHIC = SVMessages.getString("BlastViewerPanel.2");
/**
* Default constructor.
*/
public BlastViewerPanelBase() {
super();
createGUI();
}
/**
* Set the data to display in this viewer.
*/
public void setContent(BlastEntry entry) {
_summaryPane.setContent(entry);
}
/**
* Set the data to display in this viewer.
*/
public void setContent(SROutput so, String soPath) {
_summaryPane.setContent(prepareEntry(so, soPath));
}
/**
* Set the data to display in this viewer.
*/
public void setContent(SROutput so) {
_summaryPane.setContent(prepareEntry(so, null));
}
/**
* Return the Hit currently selected in this BlastViewerPanel. Actually, the
* method returns the Hit that is currently displayed by the SeqAlignViewer
* panel.
*/
public BlastHitHSP getSelectedHit() {
return _seqAlignViewer.getCurrentHit();
}
/**
* Return the HSP currently selected in this BlastViewerPanel. Actually, the
* method returns the HSP that is currently displayed by the SeqAlignViewer
* panel.
*/
public SRHsp getSelectedHsp() {
return _seqAlignViewer.getCurrentHsp();
}
private BlastEntry prepareEntry(SROutput bo, String soPath) {
String val;
int pos;
// analyze SROutput object (i.e. a Blast result) to get:
// program name, query name and databank name
SRRequestInfo bri = bo.getRequestInfo();
Object obj = bri.getValue(SRRequestInfo.PRGM_VERSION_DESCRIPTOR_KEY);
if (obj != null) {
val = obj.toString();
if ((pos = val.indexOf('[')) > 0) {
val = val.substring(0, pos - 1);
} else {
val = obj.toString();
}
} else {
val = null;
}
String program = val != null ? val : "?";
obj = bri.getValue(SRRequestInfo.DATABASE_DESCRIPTOR_KEY);
String dbname = obj != null ? obj.toString() : "?";
obj = bri.getValue(SRRequestInfo.QUERY_DEF_DESCRIPTOR_KEY);
String queryName = obj != null ? obj.toString() : "?";
return new BlastEntry(program, queryName, soPath, bo, null, dbname, false);
}
private void createGUI() {
JHeadPanel headPanel;
ImageIcon icon;
_updateSupport = new BlastHitListSupport();
_summaryPane = new BlastNavigator();
_hitListPane = ConfigManager.getHitTableFactory().createViewer();
_seqAlignViewer = ConfigManager.getSeqAlignViewerFactory().createViewer();
icon = EZEnvironment.getImageIcon("hitTable.png");
if (icon != null) {
headPanel = new JHeadPanel(icon, HITPANEL_HEADER, _hitListPane);
} else {
headPanel = new JHeadPanel(null, HITPANEL_HEADER, _hitListPane);
}
headPanel.setToolPanel(_summaryPane);
_rightPane = new JPanel(new BorderLayout());
_rightPane.add(headPanel, BorderLayout.CENTER);
_rightPane.add(_seqAlignViewer, BorderLayout.SOUTH);
this.setLayout(new BorderLayout());
this.add(_rightPane, BorderLayout.CENTER);
// listeners to the selection of a new BIteration
_summaryPane.addIterationListener(_hitListPane);
// listeners to the change of data model
_hitListPane.addHitDataListener(_seqAlignViewer);
// listeners to selection within hit tables
_hitListPane.registerHitListSupport(_updateSupport);
_seqAlignViewer.registerHitListSupport(_updateSupport);
_updateSupport.addBlastHitListListener(_hitListPane);
_updateSupport.addBlastHitListListener(_seqAlignViewer);
this.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
}
}
| pgdurand/Bioinformatics-UI-API | src/bzh/plealog/bioinfo/ui/blast/BlastViewerPanelBase.java | Java | agpl-3.0 | 5,888 |
/**
* Copyright (C) 2009-2014 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.bimserver.models.ifc4.impl;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import org.bimserver.models.ifc4.Ifc4Package;
import org.bimserver.models.ifc4.IfcWasteTerminal;
import org.bimserver.models.ifc4.IfcWasteTerminalTypeEnum;
import org.eclipse.emf.ecore.EClass;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Ifc Waste Terminal</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link org.bimserver.models.ifc4.impl.IfcWasteTerminalImpl#getPredefinedType <em>Predefined Type</em>}</li>
* </ul>
*
* @generated
*/
public class IfcWasteTerminalImpl extends IfcFlowTerminalImpl implements IfcWasteTerminal {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected IfcWasteTerminalImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return Ifc4Package.Literals.IFC_WASTE_TERMINAL;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public IfcWasteTerminalTypeEnum getPredefinedType() {
return (IfcWasteTerminalTypeEnum) eGet(Ifc4Package.Literals.IFC_WASTE_TERMINAL__PREDEFINED_TYPE, true);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void setPredefinedType(IfcWasteTerminalTypeEnum newPredefinedType) {
eSet(Ifc4Package.Literals.IFC_WASTE_TERMINAL__PREDEFINED_TYPE, newPredefinedType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void unsetPredefinedType() {
eUnset(Ifc4Package.Literals.IFC_WASTE_TERMINAL__PREDEFINED_TYPE);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean isSetPredefinedType() {
return eIsSet(Ifc4Package.Literals.IFC_WASTE_TERMINAL__PREDEFINED_TYPE);
}
} //IfcWasteTerminalImpl
| opensourceBIM/BIMserver | PluginBase/generated/org/bimserver/models/ifc4/impl/IfcWasteTerminalImpl.java | Java | agpl-3.0 | 3,650 |
package com.tisawesomeness.minecord.command.admin;
import com.tisawesomeness.minecord.command.meta.CommandContext;
import com.tisawesomeness.minecord.command.meta.Result;
import lombok.NonNull;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ShutdownCommand extends AbstractAdminCommand {
public @NonNull String getId() {
return "shutdown";
}
public void run(String[] args, CommandContext ctx) {
if (args.length > 0 && "now".equals(args[0])) {
System.exit(0);
throw new AssertionError("System.exit() call failed.");
}
ctx.log(":x: **Bot shut down by " + ctx.getE().getAuthor().getName() + "**");
ctx.getE().getChannel().sendMessage(":wave: Goodbye!").complete();
ExecutorService exe = Executors.newSingleThreadExecutor();
exe.submit(ctx.getBot()::shutdown);
exe.shutdown();
ctx.commandResult(Result.SUCCESS); // Graceful shutdown, just wait...
}
}
| Tisawesomeness/Minecord | src/main/java/com/tisawesomeness/minecord/command/admin/ShutdownCommand.java | Java | agpl-3.0 | 1,019 |
package com.github.cstroe.turtletax.api.event;
import com.github.cstroe.turtletax.api.Cell;
import java.util.EventListener;
public interface CellValueChangeListener<V> extends EventListener {
void valueChanged(Cell<V> cell);
}
| cstroe/turtletax | src/main/java/com/github/cstroe/turtletax/api/event/CellValueChangeListener.java | Java | agpl-3.0 | 234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.