hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
2a6385162721ae0c941a1841654ea669a88620ba
926
/* * 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 services; import java.util.List; import models.SignatureRequestDto; import models.SignatureRequestUserDto; /** * * @author USUARIO */ public interface SignatureRequestUserService { List<SignatureRequestUserDto> getRequest() throws Exception; List<SignatureRequestUserDto> getRequestUser(int id) throws Exception; List<SignatureRequestUserDto> getRequest(int id) throws Exception; SignatureRequestUserDto getRequestId(int id) throws Exception; SignatureRequestUserDto saveRequest(SignatureRequestUserDto user) throws Exception; SignatureRequestUserDto updateRequest(SignatureRequestUserDto user) throws Exception; void deleteRequest(int id) throws Exception; }
28.060606
89
0.763499
21e6c13e597435175f7025efdb9d289c52772f1f
164
package org.github.yassine.samples.domain.model; public interface ValueObject<T> { default boolean sameAs(T valueObject) { return equals(valueObject); } }
20.5
48
0.75
f6fe1b0f899fbd582c4385b1fdcc1a573d6eeaf9
365
package com.zou.gulimall.order.dao; import com.zou.gulimall.order.entity.RefundInfoEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 退款信息 * * @author zou * @email [email protected] * @date 2021-01-04 21:00:32 */ @Mapper public interface RefundInfoDao extends BaseMapper<RefundInfoEntity> { }
20.277778
69
0.758904
2b33e7ff0fcf28fb9441e6aff829bf7f0470bf8b
2,465
package constants; public interface SpikeDetectionConstants extends BaseConstants { String PREFIX = "sd"; int max_hz = 80000; interface Conf extends BaseConf { String PARSER_VALUE_FIELD = "sd.parser.value_field"; String GENERATOR_COUNT = "sd.generator.count"; String MOVING_AVERAGE_THREADS = "sd.moving_average.threads"; String MOVING_AVERAGE_WINDOW = "sd.moving_average.window"; String SPIKE_DETECTOR_THREADS = "sd.spike_detector.threads"; String SPIKE_DETECTOR_THRESHOLD = "sd.spike_detector.threshold"; } interface Field extends BaseField { String DEVICE_ID = "deviceID"; String TIMESTAMP = "timestamp"; String VALUE = "value"; String MOVING_AVG = "movingAverage"; String MESSAGE = "message"; } interface Component extends BaseComponent { String MOVING_AVERAGE = "movingAverageBolt"; String SPIKE_DETECTOR = "spikeDetectorBolt"; } interface TunedConfiguration { int MOVING_AVERAGE_THREADS_core1 = 1; int SPIKE_DETECTOR_THREADS_core1 = 1; int MOVING_AVERAGE_THREADS_core2 = 1; int SPIKE_DETECTOR_THREADS_core2 = 1; int MOVING_AVERAGE_THREADS_core4 = 1; int SPIKE_DETECTOR_THREADS_core4 = 1; int MOVING_AVERAGE_THREADS_core8 = 2; int SPIKE_DETECTOR_THREADS_core8 = 1; int MOVING_AVERAGE_THREADS_core16 = 1; int SPIKE_DETECTOR_THREADS_core16 = 1; int MOVING_AVERAGE_THREADS_core32 = 1; int SPIKE_DETECTOR_THREADS_core32 = 8; int MOVING_AVERAGE_THREADS_core8_HP = 2; int SPIKE_DETECTOR_THREADS_core8_HP = 1; int MOVING_AVERAGE_THREADS_core8_Batch2 = 2; int SPIKE_DETECTOR_THREADS_core8_Batch2 = 1; int MOVING_AVERAGE_THREADS_core8_Batch4 = 4; int SPIKE_DETECTOR_THREADS_core8_Batch4 = 1; int MOVING_AVERAGE_THREADS_core8_Batch8 = 8; int SPIKE_DETECTOR_THREADS_core8_Batch8 = 1; int acker_core8_Batch2 = 4; int acker_core8_Batch4 = 4; int acker_core8_Batch8 = 1; int MOVING_AVERAGE_THREADS_core32_HP_Batch = 16; int SPIKE_DETECTOR_THREADS_core32_HP_Batch = 1; int acker_core1 = 1; int acker_core2 = 1; int acker_core4 = 1; int acker_core8 = 2; int acker_core16 = 1; int acker_core32 = 2; int acker_core8_HP = 1; int acker_core32_HP_Batch = 1; } }
34.236111
72
0.679513
bfa4832e8e08da00183ef1dc1bc2259e0fca48c1
3,373
package io.jans.ca.server.op; import com.google.common.base.Strings; import com.google.inject.Injector; import io.jans.ca.common.ExpiredObjectType; import io.jans.ca.server.HttpException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import io.jans.as.client.OpenIdConfigurationResponse; import io.jans.ca.common.Command; import io.jans.ca.common.ErrorResponseCode; import io.jans.ca.common.params.GetLogoutUrlParams; import io.jans.ca.common.response.IOpResponse; import io.jans.ca.common.response.GetLogoutUriResponse; import io.jans.ca.server.service.ConfigurationService; import io.jans.ca.server.service.Rp; import java.net.URLEncoder; /** * @author Yuriy Zabrovarnyy * @version 0.9, 17/11/2015 */ public class GetLogoutUrlOperation extends BaseOperation<GetLogoutUrlParams> { private static final String GOOGLE_OP_HOST = "https://accounts.google.com"; private static final Logger LOG = LoggerFactory.getLogger(GetLogoutUrlOperation.class); /** * Base constructor * * @param command command */ protected GetLogoutUrlOperation(Command command, final Injector injector) { super(command, injector, GetLogoutUrlParams.class); } @Override public IOpResponse execute(GetLogoutUrlParams params) throws Exception { final Rp rp = getRp(); OpenIdConfigurationResponse discoveryResponse = getDiscoveryService().getConnectDiscoveryResponse(rp); String endSessionEndpoint = discoveryResponse.getEndSessionEndpoint(); String postLogoutRedirectUrl = params.getPostLogoutRedirectUri(); if (Strings.isNullOrEmpty(postLogoutRedirectUrl)) { postLogoutRedirectUrl = rp.getPostLogoutRedirectUri(); } if (Strings.isNullOrEmpty(postLogoutRedirectUrl)) { postLogoutRedirectUrl = ""; } if (Strings.isNullOrEmpty(endSessionEndpoint)) { if (rp.getOpHost().startsWith(GOOGLE_OP_HOST) && getInstance(ConfigurationService.class).get().getSupportGoogleLogout()) { String logoutUrl = "https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=" + postLogoutRedirectUrl; return new GetLogoutUriResponse(logoutUrl); } LOG.error("Failed to get end_session_endpoint at: " + getDiscoveryService().getConnectDiscoveryUrl(rp)); throw new HttpException(ErrorResponseCode.FAILED_TO_GET_END_SESSION_ENDPOINT); } String uri = endSessionEndpoint; if (!Strings.isNullOrEmpty(postLogoutRedirectUrl)) { uri += separator(uri) + "post_logout_redirect_uri=" + URLEncoder.encode(postLogoutRedirectUrl, "UTF-8"); } if (!Strings.isNullOrEmpty(params.getState())) { uri += separator(uri) + "state=" + getStateService().encodeExpiredObject(params.getState(), ExpiredObjectType.STATE); } if (!Strings.isNullOrEmpty(params.getSessionState())) { uri += separator(uri) + "session_state=" + params.getSessionState(); } if (!Strings.isNullOrEmpty(params.getIdTokenHint())) { uri += separator(uri) + "id_token_hint=" + params.getIdTokenHint(); } return new GetLogoutUriResponse(uri); } private static String separator(String uri) { return uri.contains("?") ? "&" : "?"; } }
39.22093
159
0.702342
0ebfaacec92f0fa4ac9387dd3a2b6bf9303691a1
5,549
/** * Copyright 2016 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.dyno.connectionpool.impl; import java.util.Collection; import java.util.HashSet; import java.util.Set; import org.junit.Assert; import org.junit.Test; import com.netflix.dyno.connectionpool.Host; import com.netflix.dyno.connectionpool.impl.utils.CollectionUtils; import com.netflix.dyno.connectionpool.impl.utils.CollectionUtils.Transform; public class HostStatusTrackerTest { @Test public void testMutuallyExclusive() throws Exception { Set<Host> up = getHostSet("A", "B", "D", "E"); Set<Host> down = getHostSet("C", "F", "H"); new HostStatusTracker(up, down); up = getHostSet(); down = getHostSet("C", "F", "H"); new HostStatusTracker(up, down); up = getHostSet("A", "C", "D"); down = getHostSet(); new HostStatusTracker(up, down); } @Test (expected=RuntimeException.class) public void testNotMutuallyExclusive() throws Exception { Set<Host> up = getHostSet("A", "B", "D", "E"); Set<Host> down = getHostSet("C", "F", "H", "E"); new HostStatusTracker(up, down); } @Test public void testEurekaUpdates() throws Exception { Set<Host> up = getHostSet("A", "B", "D", "E"); Set<Host> down = getHostSet("C", "F", "H"); // First time update HostStatusTracker tracker = new HostStatusTracker(up, down); verifySet(tracker.getActiveHosts(), "A", "E", "D" ,"B"); verifySet(tracker.getInactiveHosts(), "C", "H" ,"F"); // Round 2. New server 'J' shows up tracker = tracker.computeNewHostStatus(getHostSet("A", "B", "E", "D", "J"), getHostSet("C", "H" ,"F")); verifySet(tracker.getActiveHosts(), "A", "E", "D", "J", "B"); verifySet(tracker.getInactiveHosts(), "C", "H" ,"F"); // Round 3. server 'A' goes from active to inactive tracker = tracker.computeNewHostStatus(getHostSet("B", "E", "D", "J"), getHostSet("A", "C", "H", "F")); verifySet(tracker.getActiveHosts(), "E", "D", "J", "B"); verifySet(tracker.getInactiveHosts(), "C", "A", "H" ,"F"); // Round 4. New servers 'X' and 'Y' show up and "D" goes from active to inactive tracker = tracker.computeNewHostStatus(getHostSet("X", "Y", "B", "E", "J"), getHostSet("A", "C", "D", "H", "F")); verifySet(tracker.getActiveHosts(), "X", "Y", "B", "E", "J"); verifySet(tracker.getInactiveHosts(), "C", "A", "H", "D", "F"); // Round 5. server "B" goes MISSING tracker = tracker.computeNewHostStatus(getHostSet("X", "Y", "E", "J"), getHostSet("A", "C", "D", "H", "F")); verifySet(tracker.getActiveHosts(), "X", "Y", "E", "J"); verifySet(tracker.getInactiveHosts(), "C", "A", "H", "D", "F", "B"); // Round 6. server "E" and "J" go MISSING and new server "K" shows up and "A" and "C" go from inactive to active tracker = tracker.computeNewHostStatus(getHostSet("X", "Y", "A", "K", "C"), getHostSet("D", "H", "F")); verifySet(tracker.getActiveHosts(), "X", "Y", "A", "C", "K"); verifySet(tracker.getInactiveHosts(), "H", "D", "F", "E", "J"); // Round 7. all active hosts go from active to inactive tracker = tracker.computeNewHostStatus(getHostSet(), getHostSet("D", "H", "F", "X", "Y", "A", "K", "C")); verifySet(tracker.getActiveHosts(), ""); verifySet(tracker.getInactiveHosts(), "H", "D", "F", "X", "Y", "A", "K", "C"); // Round 8. 'X' 'Y' 'A' and 'C' go from inactive to active and 'K' disappears from down list tracker = tracker.computeNewHostStatus(getHostSet("X", "Y", "A", "C"), getHostSet("D", "H", "F")); verifySet(tracker.getActiveHosts(), "X", "Y", "A", "C"); verifySet(tracker.getInactiveHosts(), "H", "D", "F"); // Round 9. All inactive hosts disappear tracker = tracker.computeNewHostStatus(getHostSet("X", "Y", "A", "C"), getHostSet()); verifySet(tracker.getActiveHosts(), "X", "Y", "A", "C"); verifySet(tracker.getInactiveHosts(), ""); // Round 9. All active hosts disappear tracker = tracker.computeNewHostStatus(getHostSet(), getHostSet("K", "J")); verifySet(tracker.getActiveHosts(), ""); verifySet(tracker.getInactiveHosts(), "J", "K", "X", "Y", "A", "C"); // Round 10. All hosts disappear tracker = tracker.computeNewHostStatus(getHostSet(), getHostSet()); verifySet(tracker.getActiveHosts(), ""); verifySet(tracker.getInactiveHosts(), ""); } private Set<Host> getHostSet(String ...names) { Set<Host> set = new HashSet<Host>(); if (names != null && names.length > 0) { for (String name : names) { if (!name.isEmpty()) { set.add(new Host(name, 1234, "r1")); } } } return set; } private void verifySet(Collection<Host> hosts, String ... names) { Set<String> expected = new HashSet<String>(); if (names != null && names.length > 0) { for (String n : names) { if (n != null && !n.isEmpty()) { expected.add(n); } } } Set<String> result = new HashSet<String>( CollectionUtils.transform(hosts, new Transform<Host, String>() { @Override public String get(Host x) { return x.getHostAddress(); } })); Assert.assertEquals(expected, result); } }
33.029762
115
0.638313
6ed4dd24f1cc6f8cc8b5c38c9e2d81924163e2fb
9,671
package com.example.qingyangdemo.net; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.Map; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.httpclient.methods.PostMethod; import org.apache.commons.httpclient.methods.multipart.FilePart; import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; import org.apache.commons.httpclient.methods.multipart.Part; import org.apache.commons.httpclient.methods.multipart.StringPart; import org.apache.commons.httpclient.params.HttpMethodParams; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import com.example.qingyangdemo.base.AppException; import com.example.qingyangdemo.base.BaseApplication; import com.example.qingyangdemo.bean.Update; import com.example.qingyangdemo.bean.User; /** * 访问网络公共类 * * @author 赵庆洋 * */ public class NetClient { public static final String UTF_8 = "UTF-8"; // 连接超时时间 private static final int TIMEOUT_CONNECTION = 2000; // 重新操作次数 private static final int RETRY_TIME = 3; private static String userAgent; private static String getUserAgent(BaseApplication application) { if (userAgent == null || userAgent.equals("")) { StringBuffer sb = new StringBuffer("qingyang"); // app版本 sb.append('/' + application.getPackageInfo().versionName + '_' + application.getPackageInfo().versionCode); // andorid 平台 sb.append("/Android"); // 手机系统版本 sb.append("/" + android.os.Build.VERSION.RELEASE); // 手机型号 sb.append("/" + android.os.Build.MODEL); // 客户端唯一标识 sb.append("/" + application.getAppId()); userAgent = sb.toString(); } return userAgent; } private static HttpClient getHttpClient() { HttpClient httpClient = new HttpClient(); // 设置默认的超时重试处理策略 httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); // 设置连接超时时间 httpClient.getHttpConnectionManager().getParams() .setConnectionTimeout(TIMEOUT_CONNECTION); httpClient.getParams().setContentCharset(UTF_8); return httpClient; } /** * get方法url * * @param p_url * @param params * @return */ private static String _MakeURL(String p_url, Map<String, Object> params) { StringBuilder url = new StringBuilder(); if (url.indexOf("?") < 0) url.append("?"); for (String name : params.keySet()) { url.append('&'); url.append(name); url.append('='); url.append(String.valueOf(params.get(name))); // 不做URLEncoder处理 // url.append(URLEncoder.encode(String.valueOf(params.get(name)), // UTF_8)); } return url.toString().replace("?&", "?"); } private static GetMethod getHttpGet(String url, String userAgent) { GetMethod httpGet = new GetMethod(url); // 设置请求超时时间 httpGet.getParams().setSoTimeout(TIMEOUT_CONNECTION); httpGet.setRequestHeader("Host", URL.HOST); httpGet.setRequestHeader("Connection", "Keep_Alive"); httpGet.setRequestHeader("User_Agent", userAgent); return httpGet; } private static PostMethod getHttpPost(String url, String userAgent) { PostMethod httpPost = new PostMethod(url); // 设置请求超时时间 httpPost.getParams().setSoTimeout(TIMEOUT_CONNECTION); httpPost.setRequestHeader("Host", URL.HOST); httpPost.setRequestHeader("Connection", "Keep_Alive"); httpPost.setRequestHeader("User_Agent", userAgent); return httpPost; } /** * 公共用的get方法 * * @param application * @param url * @return * @throws AppException */ private static String http_get(BaseApplication application, String url) throws AppException { String userAgent = getUserAgent(application); HttpClient httpClient = null; GetMethod httpGet = null; String responseBody = ""; int time = 0; do { try { httpClient = getHttpClient(); httpGet = getHttpGet(url, userAgent); int statusCode = httpClient.executeMethod(httpGet); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } responseBody = httpGet.getResponseBodyAsString(); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } e.printStackTrace(); throw AppException.network(e); } finally { // 释放连接 httpGet.releaseConnection(); httpClient = null; } } while (time < RETRY_TIME); return responseBody; } /** * 公用的post方法 * * @param application * @param url * @param params * @param files * @return * @throws AppException */ private static String http_post(BaseApplication application, String url, Map<String, Object> params, Map<String, File> files) throws AppException { String userAgent = getUserAgent(application); HttpClient httpClient = null; PostMethod httpPost = null; // post表单参数处理 int length = (params == null ? 0 : params.size()) + (files == null ? 0 : files.size()); Part[] parts = new Part[length]; int i = 0; if (params != null) { for (String name : params.keySet()) { parts[i++] = new StringPart(name, String.valueOf(params .get(name)), UTF_8); } } if (files != null) { for (String fileName : files.keySet()) { try { parts[i++] = new FilePart(fileName, files.get(fileName)); } catch (FileNotFoundException e) { e.printStackTrace(); } } } String responseBody = ""; int time = 0; do { try { httpClient = getHttpClient(); httpPost = getHttpPost(url, userAgent); httpPost.setRequestEntity(new MultipartRequestEntity(parts, httpPost.getParams())); int statusCode = httpClient.executeMethod(httpPost); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } responseBody = httpPost.getResponseBodyAsString(); // 做临时数据 if (responseBody.equals("登录成功")) { responseBody = "{\"response\":{\"isErr\":false,\"uid\":1,\"username\":\"xgxx\",\"password\":1234}}"; } else { responseBody = "{\"response\":{\"isErr\":true,\"msg\":\"用户名密码错误!\"}}"; } break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生网络异常 e.printStackTrace(); throw AppException.network(e); } finally { // 释放连接 httpPost.releaseConnection(); httpClient = null; } } while (time < RETRY_TIME); return responseBody; } public static Bitmap getNetBitmap(String url) throws AppException { HttpClient httpClient = null; GetMethod httpGet = null; Bitmap bitmap = null; int time = 0; do { try { httpClient = getHttpClient(); httpGet = getHttpGet(url, null); int statusCode = httpClient.executeMethod(httpGet); if (statusCode != HttpStatus.SC_OK) { throw AppException.http(statusCode); } InputStream inStream = httpGet.getResponseBodyAsStream(); bitmap = BitmapFactory.decodeStream(inStream); inStream.close(); break; } catch (HttpException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生致命的异常,可能是协议不对或者返回的内容有问题 e.printStackTrace(); throw AppException.http(e); } catch (IOException e) { time++; if (time < RETRY_TIME) { try { Thread.sleep(1000); } catch (InterruptedException e1) { } continue; } // 发生网络异常 e.printStackTrace(); throw AppException.network(e); } finally { // 释放连接 httpGet.releaseConnection(); httpClient = null; } } while (time < RETRY_TIME); return bitmap; } /** * 登陆验证 * * @param application * @param account * @param password * @return * @throws AppException */ public static User login(BaseApplication application, String account, String password) throws AppException { Map<String, Object> params = new HashMap<String, Object>(); params.put("username", account); params.put("password", password); return User.parse(http_post(application, URL.LOGIN_URL, params, null)); } /** * 检查版本更新(做的假数据) * * @param application * @return * @throws AppException */ public static Update checkVersion(BaseApplication application) throws AppException { // try { // return Update.parse(http_get(application, URL.UPDATE_VERSOIN)); // } catch (Exception e) { // if (e instanceof AppException) { // throw (AppException) e; // } // throw AppException.network(e); // } Update update = new Update(); update.setVersionName("qingyang"); update.setVersionCode(2); update.setUpdateLog("版本信息:qingyang for android 2.0版更新日志:1.增加了新版本检测功能。2.修复了网络连接的问题。如果是升级失败,请到http://www.xxx.com/app下载最新版本。"); update.setDownloadUrl("http://down.angeeks.com/c/d2/d10100/10100520.apk"); return update; } }
24.1775
126
0.672113
8351456d598796da2994b70623a1475f303b4c24
855
package dne.eiim.xjam; public abstract class Op { protected final String name; public Op(final String name) { this.name = name; } public abstract void run(XJam x); @Override public String toString() { return name; } protected RuntimeException fail(final Object a) { return new RuntimeException(a.getClass().getSimpleName() + ' ' + name + " not implemented"); } protected RuntimeException fail(final Object a, final Object b) { return new RuntimeException(a.getClass().getSimpleName() + ' ' + b.getClass().getSimpleName() + ' ' + name + " not implemented"); } protected RuntimeException fail(final Object a, final Object b, final Object c) { return new RuntimeException(a.getClass().getSimpleName() + ' ' + b.getClass().getSimpleName() + ' ' + c.getClass().getSimpleName() + ' ' + name + " not implemented"); } }
27.580645
95
0.680702
71e592f63272b34f622460a93ab9753f190016a5
4,855
/** * CPM API * Public API for CPM * * OpenAPI spec version: V1.0 * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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 instantreports.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import instantreports.model.AddressdataApi; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; /** * Employee */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2018-05-03T09:33:53.199+02:00") public class Employee { @SerializedName("firstName") private String firstName = null; @SerializedName("addresses") private List<AddressdataApi> addresses = new ArrayList<AddressdataApi>(); @SerializedName("name") private String name = null; @SerializedName("id") private String id = null; @SerializedName("title") private String title = null; public Employee firstName(String firstName) { this.firstName = firstName; return this; } /** * * @return firstName **/ @ApiModelProperty(example = "null", required = true, value = "") public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public Employee addresses(List<AddressdataApi> addresses) { this.addresses = addresses; return this; } public Employee addAddressesItem(AddressdataApi addressesItem) { this.addresses.add(addressesItem); return this; } /** * Get addresses * @return addresses **/ @ApiModelProperty(example = "null", value = "") public List<AddressdataApi> getAddresses() { return addresses; } public void setAddresses(List<AddressdataApi> addresses) { this.addresses = addresses; } public Employee name(String name) { this.name = name; return this; } /** * * @return name **/ @ApiModelProperty(example = "null", required = true, value = "") public String getName() { return name; } public void setName(String name) { this.name = name; } public Employee id(String id) { this.id = id; return this; } /** * * @return id **/ @ApiModelProperty(example = "f4206901-c9b2-4e6e-8119-f7d623626060", value = "") public String getId() { return id; } public void setId(String id) { this.id = id; } public Employee title(String title) { this.title = title; return this; } /** * * @return title **/ @ApiModelProperty(example = "null", value = "") public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Employee employee = (Employee) o; return Objects.equals(this.firstName, employee.firstName) && Objects.equals(this.addresses, employee.addresses) && Objects.equals(this.name, employee.name) && Objects.equals(this.id, employee.id) && Objects.equals(this.title, employee.title); } @Override public int hashCode() { return Objects.hash(firstName, addresses, name, id, title); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Employee {\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" addresses: ").append(toIndentedString(addresses)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" title: ").append(toIndentedString(title)).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(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
24.275
131
0.661174
cc413f2fbb20ce12f561aad0563eaf88bc13327a
478
package firstPackage; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; public class SecurityRandom { public static void main(String[] args) { SecureRandom sr = null; try { sr = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } byte[] b = new byte[2]; sr.nextBytes(b); for(byte a:b){ System.out.println(a); } sr.setSeed(b); System.out.println(sr.nextInt()); } }
19.916667
46
0.694561
02755502303e3a8054cf0339c6cde27fb0d18f76
4,067
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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 io.smallrye.metrics; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.microprofile.metrics.MetricID; import org.eclipse.microprofile.metrics.MetricType; import io.smallrye.metrics.elementdesc.MemberInfo; /** * This class represents mappings between Java methods and the set of metric IDs * associated with them. This is computed once at boot/build time to avoid having to * do runtime reflection on every invocation of the relevant methods. * * This class does NOT use thread-safe map implementations, so populating the mappings * must only be performed by one thread. Querying the mappings later at runtime can be done * concurrently. */ public class MemberToMetricMappings { MemberToMetricMappings() { counters = new HashMap<>(); concurrentGauges = new HashMap<>(); meters = new HashMap<>(); timers = new HashMap<>(); simpleTimers = new HashMap<>(); } private final Map<MemberInfo, Set<MetricID>> counters; private final Map<MemberInfo, Set<MetricID>> concurrentGauges; private final Map<MemberInfo, Set<MetricID>> meters; private final Map<MemberInfo, Set<MetricID>> timers; private final Map<MemberInfo, Set<MetricID>> simpleTimers; public Set<MetricID> getCounters(MemberInfo member) { return counters.get(member); } public Set<MetricID> getConcurrentGauges(MemberInfo member) { return concurrentGauges.get(member); } public Set<MetricID> getMeters(MemberInfo member) { return meters.get(member); } public Set<MetricID> getTimers(MemberInfo member) { return timers.get(member); } public Set<MetricID> getSimpleTimers(MemberInfo member) { return simpleTimers.get(member); } public void addMetric(MemberInfo member, MetricID metricID, MetricType metricType) { switch (metricType) { case COUNTER: counters.computeIfAbsent(member, id -> new HashSet<>()).add(metricID); break; case CONCURRENT_GAUGE: concurrentGauges.computeIfAbsent(member, id -> new HashSet<>()).add(metricID); break; case METERED: meters.computeIfAbsent(member, id -> new HashSet<>()).add(metricID); break; case TIMER: timers.computeIfAbsent(member, id -> new HashSet<>()).add(metricID); break; case SIMPLE_TIMER: simpleTimers.computeIfAbsent(member, id -> new HashSet<>()).add(metricID); break; default: throw SmallRyeMetricsMessages.msg.unknownMetricType(); } SmallRyeMetricsLogging.log.matchingMemberToMetric(member, metricID, metricType); } public void removeMappingsFor(MemberInfo member, MetricID metricID) { removeMapping(counters, member, metricID); removeMapping(concurrentGauges, member, metricID); removeMapping(meters, member, metricID); removeMapping(timers, member, metricID); removeMapping(simpleTimers, member, metricID); } private void removeMapping(Map<MemberInfo, Set<MetricID>> map, MemberInfo member, MetricID metricID) { if (map.containsKey(member)) { map.get(member).remove(metricID); } } }
36.3125
106
0.676912
4ed1344bf0510228f3cdc6c9f348bbe5c17230af
689
/* * Copyright (c) 2017. All rights reserved. Used by permission. * * Author: Wen Hao * Date: 2017-05-16 17:34:12 * Gtihub: https://github.com/wenhao * */ package com.github.wenhao.functional; import com.github.wenhao.helper.RemoteConfigHelper; import org.junit.Test; import static io.restassured.RestAssured.given; import static org.hamcrest.core.IsEqual.equalTo; public class UserApiFunctionalTest { @Test public void should_get_user_information() { String url = RemoteConfigHelper.getInstance().get("douban-user-get-url"); given(). when(). get(url + "ahbei"). then(). body("title", equalTo("阿北")); } }
21.53125
81
0.656023
a3cbd5badf996fa2733b8e4df1ee8870205a509e
4,715
package meme.busoton; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.support.v7.util.SortedList; import android.support.v7.widget.CardView; import android.support.v7.widget.RecyclerView; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.GridLayout; import android.widget.GridLayout.LayoutParams; import android.widget.TextView; import android.widget.Toast; import java.time.LocalTime; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.TreeSet; import meme.busoton.comms.data.BusTime; import meme.busoton.comms.data.NextBus; import meme.busoton.notify.MyReceiver; /** * Created by hb on 19/03/18. */ public class RVAdapter extends RecyclerView.Adapter<RVAdapter.TimesViewAdapter>{ ArrayList<NextBus> buses; Context context; public RVAdapter (ArrayList<NextBus> buses, Context context){ this.buses = buses; Collections.sort(this.buses); this.context = context; } @Override public TimesViewAdapter onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.bus_card, parent, false); return new TimesViewAdapter(v, parent); } @Override public void onBindViewHolder(TimesViewAdapter holder, int position) { NextBus bus = buses.get(position); holder.serviceName.setText(bus.serviceName); holder.operatorName.setText(bus.getPrettyOperator()); for(int i=0; i<bus.times.size(); i++){ Button button = new Button(holder.vg.getContext()); String time = bus.times.get(i).time; button.setText(time); button.setOnClickListener(ev -> setupNotification(bus, time)); holder.times.addView(button); } } @Override public void onAttachedToRecyclerView(RecyclerView recyclerView) { super.onAttachedToRecyclerView(recyclerView); } @Override public int getItemCount() { return buses.size(); } public class TimesViewAdapter extends RecyclerView.ViewHolder { CardView cv; TextView serviceName; TextView operatorName; GridLayout times; ViewGroup vg; public TimesViewAdapter(View itemView, ViewGroup vg) { super(itemView); this.vg = vg; cv = itemView.findViewById(R.id.cardview); serviceName = itemView.findViewById(R.id.serviceName); operatorName = itemView.findViewById(R.id.operatorName); times = itemView.findViewById(R.id.timeGrid); } } public void setupNotification(NextBus bus, String time){ if(time.equals("Due")){ Toast.makeText(context, "You can't make a reminder for a bus that's due.", Toast.LENGTH_SHORT).show(); return; } int busHour = Integer.parseInt(time.split(":")[0]); int busMinute = Integer.parseInt(time.split(":")[1]); new TimePickerDialog( context, (tp, hour, minute) -> setNotification(bus, hour, minute, time), busHour, busMinute, true ).show(); } public void setNotification(NextBus bus, int hour, int minute, String time) { Calendar alarmTime = Calendar.getInstance(); alarmTime.set(Calendar.HOUR_OF_DAY, hour); alarmTime.set(Calendar.MINUTE, minute); alarmTime.set(Calendar.SECOND, 0); long possibleTime = alarmTime.getTimeInMillis(); if(possibleTime < System.currentTimeMillis()){ //alarmTime.roll(Calendar.DATE, 1); possibleTime = alarmTime.getTimeInMillis(); } Intent notifyIntent = new Intent(context,MyReceiver.class); notifyIntent.putExtra("stopName", bus.stopName); notifyIntent.putExtra("serviceName", bus.serviceName); notifyIntent.putExtra("operator", bus.operator); notifyIntent.putExtra("time", time); PendingIntent pendingIntent = PendingIntent.getBroadcast (context, 12343, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, possibleTime, pendingIntent); System.out.println("Alarm set for " + alarmTime.getTime().toString()); } }
32.743056
114
0.674443
6071fcd8cf38e9d542e25050f19a57f6c5aee9aa
1,727
package com.github.zhgxun.leetcode.string; import java.util.ArrayList; import java.util.List; /** * 438. 找到字符串中所有字母异位词 * <p> * https://leetcode-cn.com/problems/find-all-anagrams-in-a-string/ * <p> * https://www.bilibili.com/video/BV1WC4y1a7hq?from=search&seid=6464771871012239601 */ public class FindAnagrams { public static void main(String[] args) { System.out.println(new FindAnagrams().findAnagrams("cbaebabacd", "abc")); } public List<Integer> findAnagrams(String s, String p) { List<Integer> result = new ArrayList<>(); // 记录目标字符的计数 char[] pCharList = p.toCharArray(); int[] needs = new int[26]; for (char ch : pCharList) { needs[ch - 'a']++; } // 目标单词的数量 int targetLen = 0; for (int i = 0; i < 26; i++) { if (needs[i] > 0) { targetLen++; } } // 遍历原始字符串 char[] sCharList = s.toCharArray(); int haveLen = 0; int[] windows = new int[26]; for (int left = 0, right = 0; right < sCharList.length; right++) { // 保存原始字符 int num = sCharList[right] - 'a'; windows[num]++; // 如果找到相等的字符则记录有效字符数量 if (windows[num] == needs[num]) haveLen++; // 滑动窗口字符长度跟目标字符长度相同则需要处理窗口 while (right - left + 1 == pCharList.length) { // 此时该窗口是否为有效的答案 if (haveLen == targetLen) result.add(left); int leftNum = sCharList[left] - 'a'; if (windows[leftNum] == needs[leftNum]) haveLen--; windows[leftNum]--; left++; } } return result; } }
28.311475
83
0.517082
f48300465c383cc1f2ca69d7ca2cf7d799a142e6
741
package com.chen.spring.action.c4.aop.advice; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * @author 陈添明 * @date 2019/2/24 */ @Aspect @Component public class Audience { @Pointcut("execution(* com.chen.spring.action.c4.aop.Performance.perform(..))") public void perform(){} @Before("perform()") public void silenceCellphone(){ System.out.println("手机静音"); } @Before("perform()") public void takeSeats(){ System.out.println("就坐"); } @AfterReturning("perform()") public void applause(){ System.out.println("鼓掌"); } @AfterThrowing("perform()") public void demandRefund(){ System.out.println("退款"); } }
20.027027
83
0.62888
f1d32cd4fb9717277fd5401c9212ddd514093515
998
package org.firebears.betaTestRobot2.commands; import java.nio.ByteBuffer; import edu.wpi.first.wpilibj.I2C; import edu.wpi.first.wpilibj.command.Command; /** * Write the given byte array out to an I2C address. * Typically, this writes a sequence of bytes to an Arduino. */ public class I2cWriteCommand extends Command { private final I2C i2c; private final ByteBuffer dataToSend; private final int sendSize; private final ByteBuffer dataReceived; private final int receiveSize; public I2cWriteCommand(I2C i2c, byte[] bytes) { this.i2c = i2c; sendSize = bytes.length; dataToSend = ByteBuffer.allocateDirect(sendSize); for (int i=0; i<sendSize; i++) { dataToSend.put(i, bytes[i]); } receiveSize = 0; dataReceived = ByteBuffer.allocateDirect(0); } @Override protected void execute() { i2c.transaction(dataToSend, sendSize, dataReceived, receiveSize); } @Override protected boolean isFinished() { return true; } }
24.341463
68
0.709419
bd3a6e9e2c0d1d47cb91a7790f35958faaa25e0b
5,639
package com.bitmovin.api.sdk.encoding.encodings.inputStreams.subtitles.dvbSubtitle; import java.util.Date; import java.util.List; import java.util.Map; import java.util.HashMap; import feign.Param; import feign.QueryMap; import feign.RequestLine; import feign.Body; import feign.Headers; import com.bitmovin.api.sdk.model.*; import com.bitmovin.api.sdk.common.BitmovinException; import static com.bitmovin.api.sdk.common.BitmovinExceptionFactory.buildBitmovinException; import com.bitmovin.api.sdk.common.BitmovinDateExpander; import com.bitmovin.api.sdk.common.QueryMapWrapper; import com.bitmovin.api.sdk.common.BitmovinApiBuilder; import com.bitmovin.api.sdk.common.BitmovinApiClientFactory; public class DvbSubtitleApi { private final DvbSubtitleApiClient apiClient; public DvbSubtitleApi(BitmovinApiClientFactory clientFactory) { if (clientFactory == null) { throw new IllegalArgumentException("Parameter 'clientFactory' may not be null."); } this.apiClient = clientFactory.createApiClient(DvbSubtitleApiClient.class); } /** * Fluent builder for creating an instance of DvbSubtitleApi */ public static BitmovinApiBuilder<DvbSubtitleApi> builder() { return new BitmovinApiBuilder<>(DvbSubtitleApi.class); } /** * Add DVB Subtitle Input Stream * * @param encodingId Id of the encoding. (required) * @param dvbSubtitleInputStream The DVB Subtitle Input Stream to be created (required) * @return DvbSubtitleInputStream * @throws BitmovinException if fails to make API call */ public DvbSubtitleInputStream create(String encodingId, DvbSubtitleInputStream dvbSubtitleInputStream) throws BitmovinException { try { return this.apiClient.create(encodingId, dvbSubtitleInputStream).getData().getResult(); } catch (Exception ex) { throw buildBitmovinException(ex); } } /** * Delete DVB Subtitle Input Stream * * @param encodingId Id of the encoding. (required) * @param inputStreamId Id of the DVB Subtitle Input Stream. (required) * @return BitmovinResponse * @throws BitmovinException if fails to make API call */ public BitmovinResponse delete(String encodingId, String inputStreamId) throws BitmovinException { try { return this.apiClient.delete(encodingId, inputStreamId).getData().getResult(); } catch (Exception ex) { throw buildBitmovinException(ex); } } /** * DVB Subtitle Input Stream Details * * @param encodingId Id of the encoding. (required) * @param inputStreamId Id of the DVB Subtitle Input Stream. (required) * @return DvbSubtitleInputStream * @throws BitmovinException if fails to make API call */ public DvbSubtitleInputStream get(String encodingId, String inputStreamId) throws BitmovinException { try { return this.apiClient.get(encodingId, inputStreamId).getData().getResult(); } catch (Exception ex) { throw buildBitmovinException(ex); } } /** * List DVB Subtitle Input Streams * * @param encodingId Id of the encoding. (required) * @return List&lt;DvbSubtitleInputStream&gt; * @throws BitmovinException if fails to make API call */ public PaginationResponse<DvbSubtitleInputStream> list(String encodingId) throws BitmovinException { try { return this.apiClient.list(encodingId, new QueryMapWrapper()).getData().getResult(); } catch (Exception ex) { throw buildBitmovinException(ex); } } /** * List DVB Subtitle Input Streams * * @param encodingId Id of the encoding. (required) * @param queryParams The query parameters for sorting, filtering and paging options (optional) * @return List&lt;DvbSubtitleInputStream&gt; * @throws BitmovinException if fails to make API call */ public PaginationResponse<DvbSubtitleInputStream> list(String encodingId, DvbSubtitleInputStreamListQueryParams queryParams) throws BitmovinException { try { return this.apiClient.list(encodingId, new QueryMapWrapper(queryParams)).getData().getResult(); } catch (Exception ex) { throw buildBitmovinException(ex); } } interface DvbSubtitleApiClient { @RequestLine("POST /encoding/encodings/{encoding_id}/input-streams/subtitles/dvb-subtitle") ResponseEnvelope<DvbSubtitleInputStream> create(@Param(value = "encoding_id") String encodingId, DvbSubtitleInputStream dvbSubtitleInputStream) throws BitmovinException; @RequestLine("DELETE /encoding/encodings/{encoding_id}/input-streams/subtitles/dvb-subtitle/{input_stream_id}") ResponseEnvelope<BitmovinResponse> delete(@Param(value = "encoding_id") String encodingId, @Param(value = "input_stream_id") String inputStreamId) throws BitmovinException; @RequestLine("GET /encoding/encodings/{encoding_id}/input-streams/subtitles/dvb-subtitle/{input_stream_id}") ResponseEnvelope<DvbSubtitleInputStream> get(@Param(value = "encoding_id") String encodingId, @Param(value = "input_stream_id") String inputStreamId) throws BitmovinException; @RequestLine("GET /encoding/encodings/{encoding_id}/input-streams/subtitles/dvb-subtitle") ResponseEnvelope<PaginationResponse<DvbSubtitleInputStream>> list(@Param(value = "encoding_id") String encodingId, @QueryMap QueryMapWrapper queryParams) throws BitmovinException; } }
41.463235
187
0.710055
60813da29e04ed314ec6848981248112b5460549
4,522
package com.fmall.content.service.impl; import com.fmall.common.jedis.JedisClient; import com.fmall.common.pojo.EasyUIDataGridResult; import com.fmall.common.pojo.FmResult; import com.fmall.common.utils.JsonUtils; import com.fmall.content.service.ContentService; import com.fmall.mapper.TbContentMapper; import com.fmall.pojo.TbContent; import com.fmall.pojo.TbContentExample; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Created by jack.zhang * email:[email protected] * 2017/5/3 18:14 */ @Service public class ContentServiceImpl implements ContentService { @Autowired private TbContentMapper contentMapper; @Autowired private JedisClient jedisClient; @Value("${CONTENT_LIST}") private String CONTENT_LIST; @Override public FmResult addContent(TbContent content) { //补全属性 content.setCreated(new Date()); content.setUpdated(new Date()); //插入数据 contentMapper.insert(content); try { //缓存同步 jedisClient.hdel(CONTENT_LIST, content.getCategoryId().toString()); } catch (Exception e) { } return FmResult.ok(); } @Override public FmResult deleteContent(String ids) { String[] strings = ids.split(","); List<Long> idList = new ArrayList<>(); for (String id : strings) { if (StringUtils.isNumeric(id)) { idList.add(Long.valueOf(id)); } } TbContentExample contentExample = new TbContentExample(); contentExample.createCriteria() .andIdIn(idList); //缓存同步 try { //获取将要删除的数据 List<TbContent> contentList = contentMapper.selectByExample(contentExample); for (TbContent content : contentList) { jedisClient.hdel(CONTENT_LIST, content.getCategoryId().toString()); } } catch (Exception e) { e.printStackTrace(); } contentMapper.deleteByExample(contentExample); return FmResult.ok(); } @Override public FmResult updateContent(TbContent content) { //补全数据 content.setUpdated(new Date()); //插入数据 contentMapper.updateByPrimaryKeySelective(content); //缓存同步 jedisClient.hdel(CONTENT_LIST, content.getCategoryId().toString()); return FmResult.ok(); } @Override public List<TbContent> getContentListByCid(long cid) { try { String json = jedisClient.hget(CONTENT_LIST, cid + ""); if (StringUtils.isNotBlank(json)) { List<TbContent> contentList = JsonUtils.jsonToList(json, TbContent.class); return contentList; } } catch (Exception e) { e.printStackTrace(); } //根据id查询内容列表 TbContentExample contentExample = new TbContentExample(); contentExample.createCriteria() .andCategoryIdEqualTo(cid); List<TbContent> contentList = contentMapper.selectByExample(contentExample); //把查询结果添加到缓存 try { jedisClient.hset(CONTENT_LIST, cid + "", JsonUtils.objectToJson(contentList)); } catch (Exception e) { e.printStackTrace(); } return contentList; } @Override public EasyUIDataGridResult getContentPage(long cid, int page, int rows) { //设置分页信息 PageHelper.startPage(page, rows); //查询数据 TbContentExample contentExample = new TbContentExample(); if (cid != 0) { contentExample.createCriteria() .andCategoryIdEqualTo(cid); } List<TbContent> contentList = contentMapper.selectByExample(contentExample); //获取分页信息 PageInfo<TbContent> pageInfo = new PageInfo<>(contentList); //创建返回结果对象 EasyUIDataGridResult result = new EasyUIDataGridResult(); result.setTotal(pageInfo.getTotal()); result.setRows(contentList); return result; } @Override public FmResult getContentById(long id) { TbContent content = contentMapper.selectByPrimaryKey(id); return FmResult.ok(content); } }
30.348993
90
0.638434
2113e5c7002093f1219e14fe01ddf599cd33db37
3,849
/* * Copyright 2004,2005 The Apache Software Foundation. * * 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.wso2.micro.tomcat.jndi; import org.apache.naming.SelectorContext; import org.wso2.micro.core.Constants; import java.util.Hashtable; import javax.naming.Context; import javax.naming.Name; import javax.naming.NamingException; public class CarbonSelectorContext extends SelectorContext { private Context carbonInitialContext; public CarbonSelectorContext(Hashtable<String, Object> env, boolean initialContext, Context carbonInitialContext) { super(env, initialContext); this.carbonInitialContext = carbonInitialContext; } public Object lookup(Name name) throws NamingException { //If lookup request is for tenant sub context //return the tenantCarbonSelectorContext if(isSubTenantRequest(name)){ return getTenantCarbonSelectorContext(name); } //Overrides lookup and lookupLink methods //Fist looking up in tomcat level JNDI context //If it is not available in tomcat level JNDI context //then perform lookup in carbon JNDI context try { return super.lookup(name); } catch (NamingException ex) { return carbonInitialContext.lookup(name); } } public Object lookup(String name) throws NamingException { if(isSubTenantRequest(name)){ return getTenantCarbonSelectorContext(name); } try { return super.lookup(name); } catch (NamingException ex) { if (carbonInitialContext != null) { return carbonInitialContext.lookup(name); } throw ex; } } public Object lookupLink(Name name) throws NamingException { if(isSubTenantRequest(name)){ return getTenantCarbonSelectorContext(name); } try { return super.lookupLink(name); } catch (NamingException ex) { return carbonInitialContext.lookupLink(name); } } public Object lookupLink(String name) throws NamingException { if(isSubTenantRequest(name)){ return getTenantCarbonSelectorContext(name); } try { return super.lookupLink(name); } catch (NamingException ex) { return carbonInitialContext.lookupLink(name); } } private boolean isSubTenantRequest(Name name){ return isSubTenantRequest(name.get(0)); } // Check weather the look up request is for tenant sub context private boolean isSubTenantRequest(String name){ int tID = Constants.SUPER_TENANT_ID; if((tID>0) && name.equals(String.valueOf(tID))){ return true; } return false; } private Object getTenantCarbonSelectorContext(Name name) throws NamingException{ return getTenantCarbonSelectorContext(name.get(0)); } //create the CarbonSelectorContext with tenant sub context private Object getTenantCarbonSelectorContext(String name) throws NamingException{ Context tenantSubContext = (Context)carbonInitialContext.lookup(name); return new CarbonSelectorContext(env, initialContext, tenantSubContext); } }
30.792
87
0.668485
a87cf9c00b4590e5e5950cac19006b4f5181a062
1,856
package it.santagati.pizzeria; import it.santagati.pizzeria.dao.PizzaDao; import it.santagati.pizzeria.dao.PrenotazioneDao; import it.santagati.pizzeria.models.PrenotazioneElement; import org.json.JSONArray; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import java.util.ArrayList; /** * Created by Francesco on 16/06/2014. */ public class Common { public static final String applicationBasePath = "/pizzeria"; private static ApplicationContext getContext() { return new ClassPathXmlApplicationContext("spring-module.xml"); } private static Authentication getSecurityContext() { return SecurityContextHolder.getContext().getAuthentication(); } public static String getCurrentUsername() { return getSecurityContext().getName(); } public static PizzaDao getPizzaDao() { return (PizzaDao) getContext().getBean("pizzaDAO"); } public static PrenotazioneDao getPrenotazioneDao() { return (PrenotazioneDao) getContext().getBean("prenotazioneDAO"); } public static ArrayList<PrenotazioneElement> getPizzeListByJsonString(String jsonPizze) { ArrayList<PrenotazioneElement> pizzaList = new ArrayList<PrenotazioneElement>(); JSONArray pizzaArray = new JSONArray(jsonPizze); for (int i=0; i < pizzaArray.length(); i++){ pizzaList.add(new PrenotazioneElement( pizzaArray.getJSONObject(i).getString("pizza"), pizzaArray.getJSONObject(i).getInt("costo"), pizzaArray.getJSONObject(i).getInt("quantita") )); } return pizzaList; } }
34.37037
93
0.715517
ff7fe6d00319d9917762be78cf0de9eba3086554
801
package org.nd4j.linalg.dataset.api.iterator.enums; /** * This enum describes different handling options for situations once one of producer runs out of data * * @author [email protected] */ public enum InequalityHandling { /** * Parallel iterator will stop everything once one of producers runs out of data */ STOP_EVERYONE, /** * Parallel iterator will keep returning true on hasNext(), but next() will return null instead of DataSet */ PASS_NULL, /** * Parallel iterator will silently reset underlying producer */ RESET, /** * Parallel iterator will ignore this producer, and will use other producers. * * PLEASE NOTE: This option will invoke cross-device relocation in multi-device systems. */ RELOCATE, }
25.83871
110
0.679151
8472c887af709b98297bc27ac091fdca256e6421
5,694
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.datav_outer.model.v20190402; import com.aliyuncs.RpcAcsRequest; import java.util.List; import com.aliyuncs.http.MethodType; import com.aliyuncs.datav_outer.Endpoint; /** * @author auto create * @version */ public class BatchCreateScreensByTemplatesRequest extends RpcAcsRequest<BatchCreateScreensByTemplatesResponse> { private String product; private List<Screens> screenss; private String domain; private String version; public BatchCreateScreensByTemplatesRequest() { super("datav-outer", "2019-04-02", "BatchCreateScreensByTemplates", "datav"); setMethod(MethodType.POST); try { com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointMap").set(this, Endpoint.endpointMap); com.aliyuncs.AcsRequest.class.getDeclaredField("productEndpointRegional").set(this, Endpoint.endpointRegionalType); } catch (Exception e) {} } public String getProduct() { return this.product; } public void setProduct(String product) { this.product = product; if(product != null){ putBodyParameter("Product", product); } } public List<Screens> getScreenss() { return this.screenss; } public void setScreenss(List<Screens> screenss) { this.screenss = screenss; if (screenss != null) { for (int depth1 = 0; depth1 < screenss.size(); depth1++) { putBodyParameter("Screens." + (depth1 + 1) + ".DataSourceJSON" , screenss.get(depth1).getDataSourceJSON()); if (screenss.get(depth1).getDataSources() != null) { for (int depth2 = 0; depth2 < screenss.get(depth1).getDataSources().size(); depth2++) { putBodyParameter("Screens." + (depth1 + 1) + ".DataSource." + (depth2 + 1) + ".Name" , screenss.get(depth1).getDataSources().get(depth2).getName()); putBodyParameter("Screens." + (depth1 + 1) + ".DataSource." + (depth2 + 1) + ".Type" , screenss.get(depth1).getDataSources().get(depth2).getType()); putBodyParameter("Screens." + (depth1 + 1) + ".DataSource." + (depth2 + 1) + ".Config" , screenss.get(depth1).getDataSources().get(depth2).getConfig()); } } putBodyParameter("Screens." + (depth1 + 1) + ".Name" , screenss.get(depth1).getName()); putBodyParameter("Screens." + (depth1 + 1) + ".Association" , screenss.get(depth1).getAssociation()); putBodyParameter("Screens." + (depth1 + 1) + ".TemplateId" , screenss.get(depth1).getTemplateId()); putBodyParameter("Screens." + (depth1 + 1) + ".ProjectId" , screenss.get(depth1).getProjectId()); putBodyParameter("Screens." + (depth1 + 1) + ".WorkspaceId" , screenss.get(depth1).getWorkspaceId()); } } } public String getDomain() { return this.domain; } public void setDomain(String domain) { this.domain = domain; if(domain != null){ putBodyParameter("Domain", domain); } } public String getVersion() { return this.version; } public void setVersion(String version) { this.version = version; if(version != null){ putBodyParameter("Version", version); } } public static class Screens { private String dataSourceJSON; private List<DataSource> dataSources; private String name; private String association; private Integer templateId; private Integer projectId; private Integer workspaceId; public String getDataSourceJSON() { return this.dataSourceJSON; } public void setDataSourceJSON(String dataSourceJSON) { this.dataSourceJSON = dataSourceJSON; } public List<DataSource> getDataSources() { return this.dataSources; } public void setDataSources(List<DataSource> dataSources) { this.dataSources = dataSources; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getAssociation() { return this.association; } public void setAssociation(String association) { this.association = association; } public Integer getTemplateId() { return this.templateId; } public void setTemplateId(Integer templateId) { this.templateId = templateId; } public Integer getProjectId() { return this.projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Integer getWorkspaceId() { return this.workspaceId; } public void setWorkspaceId(Integer workspaceId) { this.workspaceId = workspaceId; } public static class DataSource { private String name; private String type; private String config; public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public String getConfig() { return this.config; } public void setConfig(String config) { this.config = config; } } } @Override public Class<BatchCreateScreensByTemplatesResponse> getResponseClass() { return BatchCreateScreensByTemplatesResponse.class; } }
26.483721
159
0.680365
6378061a4dcb1377fc9a4e8266a50e48b9275404
1,340
package de.quinscape.automaton.runtime.filter.impl; import de.quinscape.automaton.runtime.filter.ConfigurableFilter; import de.quinscape.automaton.runtime.filter.Filter; import de.quinscape.automaton.runtime.filter.FilterEvaluationContext; import de.quinscape.automaton.runtime.scalar.ConditionBuilder; import de.quinscape.automaton.runtime.scalar.NodeType; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.Function; /** * ToString() implementation for Java filter */ public class ToStringFilter implements ConfigurableFilter { private Filter wrapped; public ToStringFilter() { this(null); } public ToStringFilter(ConfigurableFilter wrapped) { this.wrapped = wrapped; } @Override public void configure( Function<Map<String, Object>, Filter> transform, Map<String, Object> node ) { final List<Map<String, Object>> operands = ConditionBuilder.getOperands(node); this.wrapped = transform.apply(operands.get(0)); } @Override public Object evaluate(FilterEvaluationContext ctx) { return Objects.toString(wrapped.evaluate(ctx)); } public String toString() { return toString(this, Collections.singletonList(wrapped)); } }
24.814815
86
0.720896
27889242cbc1ba9f39b9d08d239a96b9b3f8a0f0
1,823
/* * * Citrus - A object-oriented, interpreted language that is designed to simplify * the creation of dynamic, immediate feedback graphical desktop applications. * * Copyright (c) 2005 Andrew Jensen Ko * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ package edu.cmu.hcii.citrus.views; import edu.cmu.hcii.citrus.*; public class Point extends BaseElement<Point> { public static final Dec<Real> x = new Dec<Real>(new Real(0.0)); public static final Dec<Real> y = new Dec<Real>(new Real(0.0)); public Point(Namespace subtype, ArgumentList arguments) { super(subtype, arguments); } public Point(double newX, double newY) { super(null); set(x, new Real(newX)); set(y, new Real(newY)); } public double getX() { return real(x); } public double getY() { return real(y); } public String toString() { return "(" + getX() + ", " + getY() + ")"; } public int hashCode() { int code = 1; code = code * 31 + (new Double(getPropertyByDeclaration(x).getVisible().value)).hashCode(); code = code * 31 + (new Double(getPropertyByDeclaration(y).getVisible().value)).hashCode(); return code; } }
36.46
104
0.704882
ec4c77a9ed586817f50c13aeee1acbbd2b76a1d7
3,673
// Copyright (C) 2004-2009 Peter Luschny, MIT License applies. // See http://en.wikipedia.org/wiki/MIT_License // Visit http://www.luschny.de/math/factorial/FastFactorialFunctions.htm // Comments mail to: peter(at)luschny.de package de.luschny.math.factorial; import de.luschny.math.Xmath; import de.luschny.math.arithmetic.Xint; import de.luschny.math.primes.IPrimeIteration; import de.luschny.math.primes.PrimeSieve; import java.util.HashMap; public class FactorialPrimeSwingCache implements IFactorialFunction { private PrimeSieve sieve; private int[] primeList; private HashMap<Integer, CachedPrimorial> cache; public FactorialPrimeSwingCache() { } @Override public String getName() { return "PrimeSwingCache "; } @Override public Xint factorial(int n) { // For very small n the 'NaiveFactorial' is OK. if (n < 20) { return Xmath.smallFactorial(n); } cache = new HashMap<>(); sieve = new PrimeSieve(n); int piN = sieve.getIteration().getNumberOfPrimes(); primeList = new int[piN]; return recFactorial(n).shiftLeft(n - Integer.bitCount(n)); } private Xint recFactorial(int n) { if (n < 2) { return Xint.ONE; } return swing(n).multiply(recFactorial(n / 2).square()); } private Xint swing(int n) { if (n < 33) { return Xint.valueOf(smallOddSwing[n]); } int rootN = (int) Math.floor(Math.sqrt(n)); int count = 0, j = 1, low, high; Xint prod = Xint.ONE; while (true) { high = n / j++; low = n / j++; if (low < rootN) { low = rootN; } if (high - low < 32) { break; } Xint primorial = getPrimorial(low + 1, high); if (!primorial.isONE()) { prod = prod.multiply(primorial); } } // multiList and primeList initialized in function 'factorial'! IPrimeIteration pIter = sieve.getIteration(3, high); for (int prime : pIter) { int q = n, p = 1; while ((q /= prime) > 0) { if ((q & 1) == 1) { p *= prime; } } if (p > 1) { primeList[count++] = p; } } return prod.multiply(primeList, count); } private Xint getPrimorial(int low, int high) { // System.out.print("Primorial [" + low + "," + high + "] " ); Xint primorial; CachedPrimorial cachedPrimorial = cache.get(low); if (null != cachedPrimorial) { // System.out.println(" <- from Cache"); int low1 = cachedPrimorial.high + 1; Xint p = sieve.getPrimorial(low1, high); primorial = p.multiply(cachedPrimorial.value); } else { // System.out.println(" <- from Sieve"); primorial = sieve.getPrimorial(low, high); } cache.put(low, new CachedPrimorial(high, primorial)); return primorial; } private static final int[] smallOddSwing = {1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395, 12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075, 35102025, 5014575, 145422675, 9694845, 300540195, 300540195}; } class CachedPrimorial { public final int high; public final Xint value; CachedPrimorial(int highBound, Xint val) { high = highBound; value = val; } } // endOfFactorialPrimeSwingCache
27.616541
113
0.553771
661d3846c1b537ffb90916ada27b9f6e2b88ab78
13,310
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * This is not the original file distributed by the Apache Software Foundation * It has been modified by the Hipparchus project */ package org.hipparchus.analysis.polynomials; import org.hipparchus.CalculusFieldElement; import org.hipparchus.exception.MathIllegalArgumentException; import org.hipparchus.random.RandomDataGenerator; import org.hipparchus.util.Decimal64; import org.hipparchus.util.FastMath; import org.junit.Assert; import org.junit.Test; /** * Tests the FieldPolynomialFunction implementation of a UnivariateFunction. * */ public final class FieldPolynomialFunctionTest { /** Error tolerance for tests */ protected double tolerance = 1e-12; /** * tests the value of a constant polynomial. * * <p>value of this is 2.5 everywhere.</p> */ @Test public void testConstants() { double c0 = 2.5; FieldPolynomialFunction<Decimal64> f = buildD64(c0); // verify that we are equal to c[0] at several (nonsymmetric) places Assert.assertEquals(c0, f.value(0).getReal(), tolerance); Assert.assertEquals(c0, f.value(-1).getReal(), tolerance); Assert.assertEquals(c0, f.value(-123.5).getReal(), tolerance); Assert.assertEquals(c0, f.value(3).getReal(), tolerance); Assert.assertEquals(c0, f.value(new Decimal64(456.89)).getReal(), tolerance); Assert.assertEquals(0, f.degree()); Assert.assertEquals(0, f.polynomialDerivative().value(0).getReal(), tolerance); Assert.assertEquals(0, f.polynomialDerivative().polynomialDerivative().value(0).getReal(), tolerance); } /** * tests the value of a linear polynomial. * * <p>This will test the function f(x) = 3*x - 1.5</p> * <p>This will have the values * <tt>f(0) = -1.5, f(-1) = -4.5, f(-2.5) = -9, * f(0.5) = 0, f(1.5) = 3</tt> and {@code f(3) = 7.5} * </p> */ @Test public void testLinear() { FieldPolynomialFunction<Decimal64> f = buildD64(-1.5, 3); // verify that we are equal to c[0] when x=0 Assert.assertEquals(-1.5, f.value(new Decimal64(0)).getReal(), tolerance); // now check a few other places Assert.assertEquals(-4.5, f.value(new Decimal64(-1)).getReal(), tolerance); Assert.assertEquals(-9, f.value(new Decimal64(-2.5)).getReal(), tolerance); Assert.assertEquals(0, f.value(new Decimal64(0.5)).getReal(), tolerance); Assert.assertEquals(3, f.value(new Decimal64(1.5)).getReal(), tolerance); Assert.assertEquals(7.5, f.value(new Decimal64(3)).getReal(), tolerance); Assert.assertEquals(1, f.degree()); Assert.assertEquals(0, f.polynomialDerivative().polynomialDerivative().value(0).getReal(), tolerance); } /** * Tests a second order polynomial. * <p> This will test the function f(x) = 2x^2 - 3x -2 = (2x+1)(x-2)</p> */ @Test public void testQuadratic() { FieldPolynomialFunction<Decimal64> f = buildD64(-2, -3, 2); // verify that we are equal to c[0] when x=0 Assert.assertEquals(-2, f.value(0).getReal(), tolerance); // now check a few other places Assert.assertEquals(0, f.value(-0.5).getReal(), tolerance); Assert.assertEquals(0, f.value(2).getReal(), tolerance); Assert.assertEquals(-2, f.value(1.5).getReal(), tolerance); Assert.assertEquals(7, f.value(-1.5).getReal(), tolerance); Assert.assertEquals(265.5312, f.value(12.34).getReal(), tolerance); } /** * This will test the quintic function * f(x) = x^2(x-5)(x+3)(x-1) = x^5 - 3x^4 -13x^3 + 15x^2</p> */ @Test public void testQuintic() { FieldPolynomialFunction<Decimal64> f = buildD64(0, 0, 15, -13, -3, 1); // verify that we are equal to c[0] when x=0 Assert.assertEquals(0, f.value(0).getReal(), tolerance); // now check a few other places Assert.assertEquals(0, f.value(5).getReal(), tolerance); Assert.assertEquals(0, f.value(1).getReal(), tolerance); Assert.assertEquals(0, f.value(-3).getReal(), tolerance); Assert.assertEquals(54.84375, f.value(-1.5).getReal(), tolerance); Assert.assertEquals(-8.06637, f.value(1.3).getReal(), tolerance); Assert.assertEquals(5, f.degree()); } /** * tests the firstDerivative function by comparison * * <p>This will test the functions * {@code f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6} * and {@code h(x) = 6x - 4} */ @Test public void testfirstDerivativeComparison() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; FieldPolynomialFunction<Decimal64> f = buildD64(f_coeff); FieldPolynomialFunction<Decimal64> g = buildD64(g_coeff); FieldPolynomialFunction<Decimal64> h = buildD64(h_coeff); // compare f' = g Assert.assertEquals(f.polynomialDerivative().value(0).getReal(), g.value(0).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(1).getReal(), g.value(1).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(100).getReal(), g.value(100).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(4.1).getReal(), g.value(4.1).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(-3.25).getReal(), g.value(-3.25).getReal(), tolerance); // compare g' = h Assert.assertEquals(g.polynomialDerivative().value(FastMath.PI).getReal(), h.value(FastMath.PI).getReal(), tolerance); Assert.assertEquals(g.polynomialDerivative().value(FastMath.E).getReal(), h.value(FastMath.E).getReal(), tolerance); } @Test public void testAddition() { FieldPolynomialFunction<Decimal64> p1 = buildD64( -2, 1 ); FieldPolynomialFunction<Decimal64> p2 = buildD64( 2, -1, 0 ); checkNullPolynomial(p1.add(p2)); p2 = p1.add(p1); checkCoeffs(Double.MIN_VALUE, p2, -4, 2); p1 = buildD64( 1, -4, 2 ); p2 = buildD64( -1, 3, -2 ); p1 = p1.add(p2); Assert.assertEquals(1, p1.degree()); checkCoeffs(Double.MIN_VALUE, p1, 0, -1); } @Test public void testSubtraction() { FieldPolynomialFunction<Decimal64> p1 = buildD64( -2, 1 ); checkNullPolynomial(p1.subtract(p1)); FieldPolynomialFunction<Decimal64> p2 = buildD64( -2, 6 ); p2 = p2.subtract(p1); checkCoeffs(Double.MIN_VALUE, p2, 0, 5); p1 = buildD64( 1, -4, 2 ); p2 = buildD64( -1, 3, 2 ); p1 = p1.subtract(p2); Assert.assertEquals(1, p1.degree()); checkCoeffs(Double.MIN_VALUE, p1, 2, -7); } @Test public void testMultiplication() { FieldPolynomialFunction<Decimal64> p1 = buildD64( -3, 2 ); FieldPolynomialFunction<Decimal64> p2 = buildD64( 3, 2, 1 ); checkCoeffs(Double.MIN_VALUE, p1.multiply(p2), -9, 0, 1, 2); p1 = buildD64( 0, 1 ); p2 = p1; for (int i = 2; i < 10; ++i) { p2 = p2.multiply(p1); double[] c = new double[i + 1]; c[i] = 1; checkCoeffs(Double.MIN_VALUE, p2, c); } } /** * tests the firstDerivative function by comparison * * <p>This will test the functions * {@code f(x) = x^3 - 2x^2 + 6x + 3, g(x) = 3x^2 - 4x + 6} * and {@code h(x) = 6x - 4} */ @Test public void testMath341() { double[] f_coeff = { 3, 6, -2, 1 }; double[] g_coeff = { 6, -4, 3 }; double[] h_coeff = { -4, 6 }; FieldPolynomialFunction<Decimal64> f = buildD64(f_coeff); FieldPolynomialFunction<Decimal64> g = buildD64(g_coeff); FieldPolynomialFunction<Decimal64> h = buildD64(h_coeff); // compare f' = g Assert.assertEquals(f.polynomialDerivative().value(0).getReal(), g.value(0).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(1).getReal(), g.value(1).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(100).getReal(), g.value(100).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(4.1).getReal(), g.value(4.1).getReal(), tolerance); Assert.assertEquals(f.polynomialDerivative().value(-3.25).getReal(), g.value(-3.25).getReal(), tolerance); // compare g' = h Assert.assertEquals(g.polynomialDerivative().value(FastMath.PI).getReal(), h.value(FastMath.PI).getReal(), tolerance); Assert.assertEquals(g.polynomialDerivative().value(FastMath.E).getReal(), h.value(FastMath.E).getReal(), tolerance); } @Test public void testAntiDerivative() { // 1 + 2x + 3x^2 final double[] coeff = {1, 2, 3}; final FieldPolynomialFunction<Decimal64> p = buildD64(coeff); // x + x^2 + x^3 checkCoeffs(Double.MIN_VALUE, p.antiDerivative(), 0, 1, 1, 1); } @Test public void testAntiDerivativeConstant() { final double[] coeff = {2}; final FieldPolynomialFunction<Decimal64> p = buildD64(coeff); checkCoeffs(Double.MIN_VALUE, p.antiDerivative(), 0, 2); } @Test public void testAntiDerivativeZero() { final double[] coeff = {0}; final FieldPolynomialFunction<Decimal64> p = buildD64(coeff); checkCoeffs(Double.MIN_VALUE, p.antiDerivative(), 0); } @Test public void testAntiDerivativeRandom() { final RandomDataGenerator ran = new RandomDataGenerator(1000); double[] coeff = null; FieldPolynomialFunction<Decimal64> p = null; int d = 0; for (int i = 0; i < 20; i++) { d = ran.nextInt(1, 50); coeff = new double[d]; for (int j = 0; j < d; j++) { coeff[j] = ran.nextUniform(-100, 1000); } p = buildD64(coeff); checkInverseDifferentiation(p); } } @Test public void testIntegrate() { // -x^2 final double[] coeff = {0, 0, -1}; final FieldPolynomialFunction<Decimal64> p = buildD64(coeff); Assert.assertEquals(-2d/3d, p.integrate(-1, 1).getReal(),Double.MIN_VALUE); // x(x-1)(x+1) - should integrate to 0 over [-1,1] final FieldPolynomialFunction<Decimal64> p2 = buildD64(0, 1). multiply(buildD64(-1, 1)). multiply(buildD64(1, 1)); Assert.assertEquals(0, p2.integrate(-1, 1).getReal(), Double.MIN_VALUE); } @Test(expected = MathIllegalArgumentException.class) public void testIntegrateInfiniteBounds() { final FieldPolynomialFunction<Decimal64> p = buildD64(1); p.integrate(0, Double.POSITIVE_INFINITY); } @Test(expected = MathIllegalArgumentException.class) public void testIntegrateBadInterval() { final FieldPolynomialFunction<Decimal64> p = buildD64(1); p.integrate(0, -1); } private <T extends CalculusFieldElement<T>> void checkInverseDifferentiation(FieldPolynomialFunction<T> p) { final T[] c0 = p.getCoefficients(); final T[] c1 = p.antiDerivative().polynomialDerivative().getCoefficients(); Assert.assertEquals(c0.length, c1.length); for (int i = 0; i < c0.length; ++i) { Assert.assertEquals(c0[i].getReal(), c1[i].getReal(), 1e-12); } } private <T extends CalculusFieldElement<T>> void checkCoeffs(final double tolerance, final FieldPolynomialFunction<T> p, final double... ref) { final T[] c = p.getCoefficients(); Assert.assertEquals(ref.length, c.length); for (int i = 0; i < ref.length; ++i) { Assert.assertEquals(ref[i], c[i].getReal(), tolerance); } } private <T extends CalculusFieldElement<T>> void checkNullPolynomial(FieldPolynomialFunction<T> p) { for (T coefficient : p.getCoefficients()) { Assert.assertEquals(0, coefficient.getReal(), 1e-15); } } private FieldPolynomialFunction<Decimal64> buildD64(double...c) { Decimal64[] array = new Decimal64[c.length]; for (int i = 0; i < c.length; ++i) { array[i] = new Decimal64(c[i]); } return new FieldPolynomialFunction<>(array); } }
39.731343
126
0.612998
16c2ddd4f20e399c982b5c599dec441a4e36b952
202
package umm3601.todo; import java.util.Comparator; public class sortByBody implements Comparator<Todo> { @Override public int compare(Todo a, Todo b) { return a.body.compareTo(b.body); } }
16.833333
53
0.722772
0ec405d041e7d649e6f92654efd61c96ff015799
759
package com.lcwork.multimall.sysadmin; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication(scanBasePackages = { "com.lcwork.multimall.db", "com.lcwork.multimall.core", "com.lcwork.multimall.sysadmin" }) @MapperScan("com.lcwork.multimall.db.dao") @EnableTransactionManagement @EnableScheduling public class SysadminApplication { public static void main(String[] args) { SpringApplication.run(SysadminApplication.class, args); } }
31.625
78
0.794466
08262eab989819d72ca61f2d81575c5d174a5a9c
1,397
/* Copyright (c) 2013 OpenPlans. All rights reserved. * This code is licensed under the BSD New License, available at the root * application directory. */ package org.geogit.storage; import org.geogit.api.Platform; import org.geogit.repository.RepositoryConnectionException; import com.google.inject.Inject; import com.tinkerpop.blueprints.impls.tg.TinkerGraph; /** * Provides an implementation of a GeoGit Graph Database using TinkerGraph. */ public class TinkerGraphDatabase extends BlueprintsGraphDatabase<TinkerGraph> { private final ConfigDatabase configDB; /** * Constructs a new {@code TinkerGraphDatabase} using the given platform. * * @param platform the platform to use. */ @Inject public TinkerGraphDatabase(final Platform platform, final ConfigDatabase configDB) { super(platform); this.configDB = configDB; } @Override protected TinkerGraph getGraphDatabase() { return new TinkerGraph(dbPath, TinkerGraph.FileType.GML); } @Override public void configure() throws RepositoryConnectionException { RepositoryConnectionException.StorageType.GRAPH.configure(configDB, "tinkergraph", "0.1"); } @Override public void checkConfig() throws RepositoryConnectionException { RepositoryConnectionException.StorageType.GRAPH.verify(configDB, "tinkergraph", "0.1"); } }
31.044444
98
0.732999
218ac2b6ea43cdb664f877fadd16b458010cf150
1,512
/* * Copyright 2014 Alexey Andreev. * * 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.teavm.debugging; import java.util.ArrayList; import java.util.List; import org.teavm.debugging.information.SourceLocation; import org.teavm.debugging.javascript.JavaScriptBreakpoint; public class Breakpoint { private Debugger debugger; volatile List<JavaScriptBreakpoint> jsBreakpoints = new ArrayList<>(); private SourceLocation location; boolean valid; Breakpoint(Debugger debugger, SourceLocation location) { this.debugger = debugger; this.location = location; } public SourceLocation getLocation() { return location; } public void destroy() { debugger.destroyBreakpoint(this); debugger = null; } public boolean isValid() { return valid; } public boolean isDestroyed() { return debugger == null; } public Debugger getDebugger() { return debugger; } }
27.490909
76
0.696429
123f8b9ff23fb7da4c0468daa8e53ea6fcc1b042
24,240
/* * Copyright (c) 2018 Qualcomm Technologies, Inc. * All Rights Reserved. * Confidential and Proprietary - Qualcomm Technologies, Inc. */ package com.qualcomm.qti.qca40xx.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.wifi.ScanResult; import android.net.wifi.WifiConfiguration; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.text.InputType; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.qualcomm.qti.qca40xx.Interface.IMessageRecieved; import com.qualcomm.qti.qca40xx.Interface.IWiFiDeviceList; import com.qualcomm.qti.qca40xx.Manager.WiFiScanManager; import com.qualcomm.qti.qca40xx.Util.Constants; import com.qualcomm.qti.qca40xx.Util.Logger; import com.qualcomm.qti.qca40xx.Util.MainApplication; import com.qualcomm.qti.qca40xx.Util.TCPComm; import com.qualcomm.qti.qca40xx.Util.Util; import com.qualcomm.qti.qca40xx.R; import org.json.JSONObject; import java.net.InetAddress; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * WifiOnboardingViaWifiActivity is an Activity class for showing the Qualcomm Board details after connecting via SAP. */ public class WifiOnboardingViaWifiActivity extends AppCompatActivity implements IWiFiDeviceList, View.OnClickListener, IMessageRecieved { private static final String TAG = "WifiOnboardingDetailActivity"; private static int val; private String jsonData; private TextView name, macAddr, onboardMode, powerMode, fwversion, chipset; private EditText password; private TextView passwordTextView; private Button onBoard, cancel, ok; private String ssidTxt, passwordTxt; private Toolbar toolbar; private String ip, deviceName, mac; private Spinner wifiScanListSpinner; private ArrayList<String> ssidList; private WiFiScanManager wiFiScanManager; private List<ScanResult> mWifiBleFilteredList; private LinearLayout onBoardLayout, buttonLayout, credentialsLayout; private int netId; private SharedPreferences settings; private JSONObject json; private TCPComm tcpComm; private Context mContext; private String mCallingActivity = ""; private CheckBox chk_paswd; private String onBoardTxt; private String mode; private MainApplication application; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.wifi_onboarding_details_layout); initialize(); getDeviceDataFromSP(); Logger.d(TAG, "Ip Address " + ip); if (ip != null) { if (ip.equals("")) { Toast.makeText(this, R.string.toastTcpConnectionError, Toast.LENGTH_LONG).show(); Util.disconnectWifiNetwork(mContext, netId); finish(); } else { try { JSONObject json = new JSONObject(); json.put(Constants.JSON_KEY_ACTION, Constants.TCP_FIRST_DATA); int state = checkAPState(); if (state == 1) { tcpComm = new TCPComm(InetAddress.getByName(ip), WifiOnboardingViaWifiActivity.this, this, json.toString()); } else { onBackPressed(); } } catch (Exception e) { e.printStackTrace(); Logger.d(TAG, " Exception in onCreate() -> " + e); } } } else { Toast.makeText(this, R.string.toastTcpConnectionError, Toast.LENGTH_LONG).show(); Util.disconnectWifiNetwork(mContext, netId); finish(); } } @Override public boolean onOptionsItemSelected(MenuItem item) { //tool bar button click if (item.getItemId() == android.R.id.home) { Util.disconnectWifiNetwork(mContext, netId); onBackPressed(); } return super.onOptionsItemSelected(item); } @Override protected void onResume() { super.onResume(); try { mWifiBleFilteredList = new ArrayList<ScanResult>(); wiFiScanManager.wifiScan(); wifiScanListSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { ssidTxt = parent.getItemAtPosition(position).toString(); for (int i = 0; i < mWifiBleFilteredList.size(); i++) { ScanResult device = mWifiBleFilteredList.get(i); String configuredDevice = device.SSID; if (configuredDevice.contains("\"")) { configuredDevice = configuredDevice.replace("\"", ""); } if (configuredDevice.equalsIgnoreCase(ssidTxt)) { if (device.capabilities.contains(Constants.WIFI_SECURITY_WEP) || device.capabilities.contains(Constants.WIFI_SECURITY_WPA)) { password.setVisibility(View.VISIBLE); passwordTextView.setVisibility(View.VISIBLE); chk_paswd.setVisibility(View.VISIBLE); } else { password.setVisibility(View.GONE); passwordTextView.setVisibility(View.GONE); chk_paswd.setVisibility(View.GONE); } } } } public void onNothingSelected(AdapterView<?> parent) { } }); } catch (Exception e) { e.printStackTrace(); Logger.d(TAG, " Exception in onResume() -> " + e); } } private void initialize() { toolbar = (Toolbar) findViewById(R.id.tool_bar); mContext = this; toolbar.setTitle(Constants.TITLE_ONBOARDING_DETAILS); setSupportActionBar(toolbar); // toolbar navigation icon setup getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); application = (MainApplication) getApplicationContext(); settings = WifiOnboardingViaWifiActivity.this.getSharedPreferences(Constants.IP_ADDRESS, Context.MODE_PRIVATE); //1 Bundle bundle = this.getIntent().getExtras(); if (bundle != null) { mCallingActivity = bundle.getString(Constants.CALLING_ACTIVITY); } name = (TextView) findViewById(R.id.textViewDeviceName); macAddr = (TextView) findViewById(R.id.textViewMacAddress); onboardMode = (TextView) findViewById(R.id.textViewOnboardingMode); powerMode = (TextView) findViewById(R.id.textViewBatteryMode); chipset = (TextView) findViewById(R.id.textViewChipset); fwversion = (TextView) findViewById(R.id.textViewFversion); chk_paswd = (CheckBox) findViewById(R.id.chk_paswd_wifi); wifiScanListSpinner = (Spinner) findViewById(R.id.spinnerWifiScanList); password = (EditText) findViewById(R.id.editTextPassword); onBoard = (Button) findViewById(R.id.btnOnboard); passwordTextView = (TextView) findViewById(R.id.textviewWifiPassword); cancel = (Button) findViewById(R.id.btnCancel); tcpComm = new TCPComm(this); ok = (Button) findViewById(R.id.ButtonOnBoardOk); onBoardLayout = (LinearLayout) findViewById(R.id.linearLayoutOnBoarded); credentialsLayout = (LinearLayout) findViewById(R.id.linearLayoutCredentials); buttonLayout = (LinearLayout) findViewById(R.id.linearLayoutButtons); json = new JSONObject(); wiFiScanManager = new WiFiScanManager(WifiOnboardingViaWifiActivity.this); onBoard.setOnClickListener(this); cancel.setOnClickListener(this); ok.setOnClickListener(this); chk_paswd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) { if (!isChecked) { password.setInputType(129); } else { password.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD); } } }); } private void enableViews(boolean flag) { onBoard.setEnabled(flag); password.setEnabled(flag); wifiScanListSpinner.setEnabled(flag); chk_paswd.setEnabled(flag); } private void parseJson(String data) { try { jsonData = data; JSONObject jsonObject = new JSONObject(data); String fVersionTxt = jsonObject.getString(Constants.JSON_FW_VER); String chipSetTxt = jsonObject.getString(Constants.JSON_CHIPSET); String batModeTxt = jsonObject.getString(Constants.JSON_BAT_MODE); String operationModeTxt = jsonObject.getString(Constants.JSON_OPERATION_MODE); mode = operationModeTxt; String onBoarded = jsonObject.getString(Constants.JSON_ONBOARDED); onBoardTxt = onBoarded.toLowerCase(); name.setText(": " + deviceName); macAddr.setText(": " + mac); fwversion.setText(": " + fVersionTxt); chipset.setText(": " + chipSetTxt); powerMode.setText(": " + batModeTxt); if (operationModeTxt.contains(";")) { val = splitDataByDelimiter(operationModeTxt); } else if (operationModeTxt.toLowerCase().equalsIgnoreCase(Constants.ZIGBEE)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (operationModeTxt.toLowerCase().equalsIgnoreCase(Constants.THREAD)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ThreadOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else { val = Constants.WIFI_SINGLE_MODE_ONBOARDING; } if (val == Constants.WIFI_SINGLE_MODE_ONBOARDING) { if (onBoardTxt.equalsIgnoreCase(Constants.NONE)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.VISIBLE); credentialsLayout.setVisibility(View.GONE); buttonLayout.setVisibility(View.GONE); Util.disconnectWifiNetwork(mContext, netId); } } else if (val == Constants.WIFI_DOUBLE_MODE_ONBOARDING) { if (onBoardTxt.equalsIgnoreCase(Constants.NONE)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else if (onBoardTxt.equalsIgnoreCase(Constants.THREAD)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else if (onBoardTxt.equalsIgnoreCase(Constants.ZIGBEE)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else { if (onBoardTxt.contains(Constants.SPLIT_STRING) || onBoardTxt.equalsIgnoreCase(Constants.WIFI)) { String mode = operationModeTxt.toLowerCase(); if (mode.contains(Constants.THREAD)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ThreadOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } } } } else if (val == Constants.WIFI_TRIPLE_MODE_ONBOARDING) { if (onBoardTxt.equals(Constants.WIFI)) { onboardMode.setText(": " + onBoardTxt); Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (onBoardTxt.equals(Constants.NONE)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else if (onBoardTxt.equals(Constants.THREAD)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else if (onBoardTxt.equals(Constants.ZIGBEE)) { onboardMode.setText(": " + onBoardTxt); onBoardLayout.setVisibility(View.GONE); } else if (onBoardTxt.equals(Constants.WIFI_THREAD)) { onboardMode.setText(": " + onBoardTxt); Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ThreadOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (onBoardTxt.equals(Constants.WIFI_ZIGBEE)) { onboardMode.setText(": " + onBoardTxt); Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } } } catch (Exception e) { e.printStackTrace(); Logger.d(TAG, " Exception in onResume() -> " + e); } } private int splitDataByDelimiter(String result) { String[] data = result.split(Constants.SPLIT_STRING); if (data.length == Constants.WIFI_DOUBLE_MODE_ONBOARDING) { cancel.setText("SKIP"); val = Constants.WIFI_DOUBLE_MODE_ONBOARDING; } if (data.length == Constants.WIFI_TRIPLE_MODE_ONBOARDING) { cancel.setText("SKIP"); val = Constants.WIFI_TRIPLE_MODE_ONBOARDING; } return val; } @Override public void tcpMessageRecieved(String message) { if (message != null) { if (message.isEmpty()) { Toast.makeText(this, R.string.toastNoBoardInfo, Toast.LENGTH_SHORT).show(); Util.disconnectWifiNetwork(mContext, netId); finish(); } else { parseJson(message); enableViews(true); } } else { Toast.makeText(this, R.string.toastNoBoardInfo, Toast.LENGTH_SHORT).show(); Util.disconnectWifiNetwork(mContext, netId); finish(); } } private void getDeviceDataFromSP() { ip = settings.getString(Constants.IP, null); deviceName = settings.getString(Constants.DEVICE_NAME, null); mac = settings.getString(Constants.MAC_ADDRESS, null); netId = settings.getInt(Constants.NETWORK_ID, -1); } private int checkAPState() { int state = 0; WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); WifiInfo info = wifiManager.getConnectionInfo(); if (mac.equalsIgnoreCase(info.getBSSID())) { state = 1; } else { state = 0; Toast.makeText(WifiOnboardingViaWifiActivity.this, R.string.toastConnectionLoss, Toast.LENGTH_SHORT).show(); } return state; } @Override public void onWifiDeviceList(List<ScanResult> data) { try { if (data.size() != 0) { System.out.println(data); for (int i = 0; i < data.size(); i++) { if (!data.get(i).SSID.contains(Constants.WIFI_BLE_FILTER_KEYWORD)) { mWifiBleFilteredList.add(data.get(i)); } } List<WifiConfiguration> configuredWifiList = application.getWifiManager().getConfiguredNetworks(); ssidList = new ArrayList<String>(); ssidList.add(0, getResources().getString(R.string.ssid_select)); HashSet<String> uniqueSsid = new HashSet(); if (configuredWifiList.size() != 0) { for (int i = 0; i < configuredWifiList.size(); i++) { WifiConfiguration device = configuredWifiList.get(i); String name = device.SSID; if (name.contains("\"")) { name = name.replace("\"", ""); } if (!(name.contains(Constants.WIFI_BLE_FILTER_KEYWORD))) { if (!(name.equals(""))) { if (name.length() < Constants.VALIDATION_SSID) for (int j = 0; j < mWifiBleFilteredList.size(); j++) { if (name.equals(mWifiBleFilteredList.get(j).SSID)) { uniqueSsid.add(name); } } } } } } ssidList.addAll(uniqueSsid); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, ssidList); wifiScanListSpinner.setAdapter(adapter); } else { Toast.makeText(WifiOnboardingViaWifiActivity.this, getResources().getString(R.string.no_wifi_device), Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnOnboard: String data; passwordTxt = password.getText().toString(); if (ssidTxt.equalsIgnoreCase(getString(R.string.ssid_select))) { Toast.makeText(WifiOnboardingViaWifiActivity.this, R.string.no_ssid, Toast.LENGTH_SHORT).show(); } else { if (passwordTxt.isEmpty()) { try { json.put("Action", "ConfigWifi"); json.put("SSID", ssidTxt); json.put("Password", ""); } catch (Exception e) { e.printStackTrace(); } data = json.toString(); } else { try { json.put("Action", "ConfigWifi"); json.put("SSID", ssidTxt); json.put("Password", passwordTxt); } catch (Exception e) { e.printStackTrace(); } data = json.toString(); } if (password.getVisibility() == View.VISIBLE) { passwordTxt = password.getText().toString(); if (passwordTxt.length() >= Constants.VALIDATION_MIN_PASSWORD) { if (passwordTxt.length() < Constants.VALIDATION_MAX_PASSWORD) { try { int state = checkAPState(); if (state == 1) { tcpComm = new TCPComm(InetAddress.getByName(ip), WifiOnboardingViaWifiActivity.this, this, data); } else { onBackPressed(); } } catch (Exception e) { e.printStackTrace(); } } else { Toast.makeText(WifiOnboardingViaWifiActivity.this, getResources().getString(R.string.passwd_is_big), Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(WifiOnboardingViaWifiActivity.this, getResources().getString(R.string.passwd_min_char), Toast.LENGTH_SHORT).show(); } } else { try { int state = checkAPState(); if (state == 1) { tcpComm = new TCPComm(InetAddress.getByName(ip), WifiOnboardingViaWifiActivity.this, this, data); } else { onBackPressed(); } } catch (Exception e) { e.printStackTrace(); } } } break; case R.id.btnCancel: if (val == Constants.WIFI_SINGLE_MODE_ONBOARDING) { Util.disconnectWifiNetwork(mContext, netId); onBackPressed(); } if (val == Constants.WIFI_DOUBLE_MODE_ONBOARDING) { String operationMode = mode.toLowerCase(); if (operationMode.contains(Constants.THREAD)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ThreadOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } } else if (onBoardTxt.equals(Constants.WIFI) || onBoardTxt.equals(Constants.NONE) && val > Constants.WIFI_SINGLE_MODE_ONBOARDING) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (onBoardTxt.equals(Constants.THREAD)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ThreadOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (onBoardTxt.equals(Constants.ZIGBEE)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (onBoardTxt.equals(Constants.WIFI_THREAD)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ThreadOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } else if (onBoardTxt.equals(Constants.WIFI_ZIGBEE)) { Util.gotoScreenWithData(WifiOnboardingViaWifiActivity.this, ZigbeeOnboardingViaWifiActivity.class, mCallingActivity, jsonData); } break; case R.id.ButtonOnBoardOk: Util.disconnectWifiNetwork(mContext, netId); onBackPressed(); break; } } }
45.223881
160
0.565223
6409f7b1280a1082a8e10466a2ae6688b2a84285
403
package org.incode.example.docfragment.fixture.teardown; import org.apache.isis.applib.fixturescripts.teardown.TeardownFixtureAbstract2; import org.incode.example.docfragment.dom.impl.DocFragment; public class DocFragmentModule_tearDown extends TeardownFixtureAbstract2 { @Override protected void execute(ExecutionContext executionContext) { deleteFrom(DocFragment.class); } }
25.1875
79
0.806452
2f78a0775bfad8cde830c09999bf16fd279230b1
49
package parameters.a; public class TheType { }
8.166667
22
0.734694
e160f2751454f358d1d53503b81e5ef0360e7aeb
37,798
/* * 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 Visao; import java.text.NumberFormat; import Modelo.ModeloRefeicoes; import javax.swing.ImageIcon; /** * * @author Alex */ public class FrmRefeicoes extends javax.swing.JFrame { FrmRelatorio relatorio; ModeloRefeicoes Refeicao; /** * Creates new form FrmRefeiçõews */ public FrmRefeicoes() { // this.setIconImage(new ImageIcon(getClass().getResource("/imagem/icone.png")).getImage()); relatorio = new FrmRelatorio(); initComponents(); Refeicao = new ModeloRefeicoes(); } FrmRelatorio rel = new FrmRelatorio(); /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { btnCalcular = new javax.swing.JButton(); lblLogo = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); chkAlacarteInfantil = new javax.swing.JCheckBox(); chkCafeAdulto = new javax.swing.JCheckBox(); chkCafeInfantil = new javax.swing.JCheckBox(); chkExecutivoAdulto = new javax.swing.JCheckBox(); chkExecutivoInfantil = new javax.swing.JCheckBox(); chkAlacarteAdulto = new javax.swing.JCheckBox(); txtAlacarteInfantil = new javax.swing.JTextField(); txtCafeAdulto = new javax.swing.JTextField(); txtCafeInfantil = new javax.swing.JTextField(); txtExecutivoAdulto = new javax.swing.JTextField(); txtExecutivoInfantil = new javax.swing.JTextField(); txtAlacarteAdulto = new javax.swing.JTextField(); PanelCafe = new javax.swing.JPanel(); lblTotalCafe = new javax.swing.JLabel(); PanelAlacarte = new javax.swing.JPanel(); lblTotalAlacarte = new javax.swing.JLabel(); jLabel10 = new javax.swing.JLabel(); PanelExecutivo = new javax.swing.JPanel(); lblTotalExec = new javax.swing.JLabel(); rdSelfServiceInfantil = new javax.swing.JRadioButton(); rdSerlServiceAdulto = new javax.swing.JRadioButton(); txtSelfServiceInfantil = new javax.swing.JTextField(); txtSelfServiceAdulto = new javax.swing.JTextField(); PanelSelf = new javax.swing.JPanel(); lblTotalSelf = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); lblTotalQuantidadesRefeicao = new javax.swing.JLabel(); lblQuantidadeCafe = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); lblTotalGeral = new javax.swing.JLabel(); jTextField1 = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); jButton1 = new javax.swing.JButton(); lblFundo = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } }); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btnCalcular.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N btnCalcular.setText("Calcular"); btnCalcular.setOpaque(false); btnCalcular.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btnCalcularActionPerformed(evt); } }); getContentPane().add(btnCalcular, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 820, 80, 30)); lblLogo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblLogo.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); getContentPane().add(lblLogo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 550, 170)); jButton2.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N jButton2.setText("Limpar"); jButton2.setOpaque(false); getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 820, 80, 30)); jLabel3.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N jLabel3.setText("Totais por Refeição"); getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 240, -1, -1)); jLabel4.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N jLabel4.setText("Tipo de Refeições"); getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 240, -1, -1)); chkAlacarteInfantil.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N chkAlacarteInfantil.setText("A LaCarte Infantil"); chkAlacarteInfantil.setOpaque(false); chkAlacarteInfantil.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { chkAlacarteInfantilItemStateChanged(evt); } }); chkAlacarteInfantil.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chkAlacarteInfantilActionPerformed(evt); } }); getContentPane().add(chkAlacarteInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 530, -1, -1)); chkCafeAdulto.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N chkCafeAdulto.setText("Café Adulto"); chkCafeAdulto.setOpaque(false); chkCafeAdulto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chkCafeAdultoActionPerformed(evt); } }); getContentPane().add(chkCafeAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 280, -1, -1)); chkCafeInfantil.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N chkCafeInfantil.setText("Café Infantil"); chkCafeInfantil.setOpaque(false); chkCafeInfantil.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { chkCafeInfantilActionPerformed(evt); } }); getContentPane().add(chkCafeInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 330, -1, -1)); chkExecutivoAdulto.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N chkExecutivoAdulto.setText("Executivo Adulto"); chkExecutivoAdulto.setOpaque(false); chkExecutivoAdulto.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { chkExecutivoAdultoItemStateChanged(evt); } }); getContentPane().add(chkExecutivoAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 380, -1, -1)); chkExecutivoInfantil.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N chkExecutivoInfantil.setText("Executivo Infantil"); chkExecutivoInfantil.setOpaque(false); chkExecutivoInfantil.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { chkExecutivoInfantilItemStateChanged(evt); } }); getContentPane().add(chkExecutivoInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 430, -1, -1)); chkAlacarteAdulto.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N chkAlacarteAdulto.setText("A LaCarte Adulto"); chkAlacarteAdulto.setOpaque(false); chkAlacarteAdulto.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { chkAlacarteAdultoItemStateChanged(evt); } }); getContentPane().add(chkAlacarteAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 480, -1, -1)); getContentPane().add(txtAlacarteInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 520, 60, -1)); getContentPane().add(txtCafeAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 270, 60, -1)); getContentPane().add(txtCafeInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 320, 60, -1)); txtExecutivoAdulto.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtExecutivoAdultoActionPerformed(evt); } }); getContentPane().add(txtExecutivoAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 370, 60, -1)); getContentPane().add(txtExecutivoInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 420, 60, -1)); getContentPane().add(txtAlacarteAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 470, 60, -1)); PanelCafe.setBorder(javax.swing.BorderFactory.createEtchedBorder()); PanelCafe.setOpaque(false); lblTotalCafe.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N lblTotalCafe.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTotalCafe.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout PanelCafeLayout = new javax.swing.GroupLayout(PanelCafe); PanelCafe.setLayout(PanelCafeLayout); PanelCafeLayout.setHorizontalGroup( PanelCafeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelCafeLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalCafe, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE) .addContainerGap()) ); PanelCafeLayout.setVerticalGroup( PanelCafeLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelCafeLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalCafe, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(PanelCafe, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 280, 120, 50)); PanelAlacarte.setBorder(javax.swing.BorderFactory.createEtchedBorder()); PanelAlacarte.setOpaque(false); PanelAlacarte.setPreferredSize(new java.awt.Dimension(112, 54)); lblTotalAlacarte.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N lblTotalAlacarte.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTotalAlacarte.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout PanelAlacarteLayout = new javax.swing.GroupLayout(PanelAlacarte); PanelAlacarte.setLayout(PanelAlacarteLayout); PanelAlacarteLayout.setHorizontalGroup( PanelAlacarteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelAlacarteLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalAlacarte, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); PanelAlacarteLayout.setVerticalGroup( PanelAlacarteLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelAlacarteLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalAlacarte, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(PanelAlacarte, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 490, 120, 50)); jLabel10.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N jLabel10.setText("Quantidade"); getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 240, -1, -1)); PanelExecutivo.setBorder(javax.swing.BorderFactory.createEtchedBorder()); PanelExecutivo.setOpaque(false); PanelExecutivo.setPreferredSize(new java.awt.Dimension(112, 54)); lblTotalExec.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N lblTotalExec.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTotalExec.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout PanelExecutivoLayout = new javax.swing.GroupLayout(PanelExecutivo); PanelExecutivo.setLayout(PanelExecutivoLayout); PanelExecutivoLayout.setHorizontalGroup( PanelExecutivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelExecutivoLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalExec, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); PanelExecutivoLayout.setVerticalGroup( PanelExecutivoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelExecutivoLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalExec, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(PanelExecutivo, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 390, 120, 50)); rdSelfServiceInfantil.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N rdSelfServiceInfantil.setText("Self Service Infantil:"); rdSelfServiceInfantil.setOpaque(false); rdSelfServiceInfantil.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { rdSelfServiceInfantilItemStateChanged(evt); } }); getContentPane().add(rdSelfServiceInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 630, -1, -1)); rdSerlServiceAdulto.setFont(new java.awt.Font("Comic Sans MS", 1, 11)); // NOI18N rdSerlServiceAdulto.setText("Self Service Adulto:"); rdSerlServiceAdulto.setOpaque(false); rdSerlServiceAdulto.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { rdSerlServiceAdultoItemStateChanged(evt); } }); getContentPane().add(rdSerlServiceAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 580, -1, -1)); getContentPane().add(txtSelfServiceInfantil, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 630, 60, -1)); getContentPane().add(txtSelfServiceAdulto, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 580, 60, -1)); PanelSelf.setBorder(javax.swing.BorderFactory.createEtchedBorder()); PanelSelf.setOpaque(false); PanelSelf.setPreferredSize(new java.awt.Dimension(112, 54)); lblTotalSelf.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N lblTotalSelf.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); lblTotalSelf.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER); javax.swing.GroupLayout PanelSelfLayout = new javax.swing.GroupLayout(PanelSelf); PanelSelf.setLayout(PanelSelfLayout); PanelSelfLayout.setHorizontalGroup( PanelSelfLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, PanelSelfLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalSelf, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE) .addContainerGap()) ); PanelSelfLayout.setVerticalGroup( PanelSelfLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(PanelSelfLayout.createSequentialGroup() .addContainerGap() .addComponent(lblTotalSelf, javax.swing.GroupLayout.DEFAULT_SIZE, 24, Short.MAX_VALUE) .addContainerGap()) ); getContentPane().add(PanelSelf, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 590, 120, 50)); jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); jPanel1.setOpaque(false); jLabel2.setFont(new java.awt.Font("Comic Sans MS", 1, 13)); // NOI18N jLabel2.setText("Quantidade de Refeições:"); jLabel1.setFont(new java.awt.Font("Comic Sans MS", 1, 13)); // NOI18N jLabel1.setText("Quantidade de Cafés:"); lblTotalQuantidadesRefeicao.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N lblQuantidadeCafe.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N jLabel5.setFont(new java.awt.Font("Comic Sans MS", 1, 13)); // NOI18N jLabel5.setText("Total Geral:"); lblTotalGeral.setFont(new java.awt.Font("Comic Sans MS", 1, 14)); // NOI18N javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addGap(28, 28, 28) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2) .addComponent(jLabel1)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lblTotalQuantidadesRefeicao, javax.swing.GroupLayout.DEFAULT_SIZE, 59, Short.MAX_VALUE) .addComponent(lblQuantidadeCafe, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(18, 18, 18) .addComponent(jLabel5) .addGap(18, 18, 18) .addComponent(lblTotalGeral, javax.swing.GroupLayout.DEFAULT_SIZE, 134, Short.MAX_VALUE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel2) .addComponent(lblTotalQuantidadesRefeicao, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(lblQuantidadeCafe, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(lblTotalGeral, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 700, 530, 80)); jTextField1.setText("jTextField1"); getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 200, 90, -1)); jLabel6.setText("Quantidade de pessoas"); getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 210, -1, -1)); jButton1.setText("jButton1"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 190, -1, -1)); getContentPane().add(lblFundo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, -20, 570, 890)); setSize(new java.awt.Dimension(567, 905)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void txtExecutivoAdultoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtExecutivoAdultoActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtExecutivoAdultoActionPerformed private void chkCafeAdultoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCafeAdultoActionPerformed if (chkCafeAdulto.isSelected()) { CafeAdulto = 14.50; txtCafeAdulto.setVisible(true); } else { CafeAdulto = 0; txtCafeAdulto.setVisible(false); txtCafeAdulto.setText("0"); } }//GEN-LAST:event_chkCafeAdultoActionPerformed private void chkCafeInfantilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkCafeInfantilActionPerformed if (chkCafeInfantil.isSelected()) { CafeInfantil = 7.00; txtCafeInfantil.setVisible(true); } else { CafeInfantil = 0; txtCafeInfantil.setVisible(false); txtCafeInfantil.setText("0"); } }//GEN-LAST:event_chkCafeInfantilActionPerformed private void chkAlacarteInfantilActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_chkAlacarteInfantilActionPerformed }//GEN-LAST:event_chkAlacarteInfantilActionPerformed private void btnCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalcularActionPerformed if (rdSerlServiceAdulto.isSelected()) { Refeicao.setQuantidadeCafeAdulto(QuantidadeCafeAdulto); QuantidadeExecutivoAdulto =0;QuantidadeExecutivoInfantil = 0;QuantidadeExecutivoTotal =0;RelTotalExecutivo =0; QuantidadeAlacarteAdulto =0; QuantidadeAlacarteInfantil =0;QuantidadeAlacarteTotal = 0; RelTotalAlacarte = 0; QuantidadeSelfServiceAdult = Integer.parseInt(txtSelfServiceAdulto.getText()); QuantidadeSelfServiceInfantil = Integer.parseInt(txtSelfServiceInfantil.getText()); QuantidadeSelfServiceTotal = QuantidadeSelfServiceAdult+QuantidadeSelfServiceInfantil; QuantidadeCafeAdulto = Integer.parseInt(txtCafeAdulto.getText()); QuantidadeCafeInfantil = Integer.parseInt(txtCafeInfantil.getText()); QuantidadeCafeTotal = QuantidadeCafeAdulto+QuantidadeCafeInfantil; QuantidadeTotal = QuantidadeSelfServiceTotal+QuantidadeCafeTotal; RelTotalGeral = (QuantidadeSelfServiceAdult * selfServiceAdulto) + (QuantidadeSelfServiceInfantil * SelfServiceInfantil) + (QuantidadeCafeAdulto * CafeAdulto) + (QuantidadeCafeInfantil * CafeInfantil); RelTotalCafe = (QuantidadeCafeAdulto * CafeAdulto); RelTotalSelfService = (QuantidadeSelfServiceAdult * selfServiceAdulto) + (QuantidadeSelfServiceInfantil * SelfServiceInfantil); lblTotalQuantidadesRefeicao.setText(QuantidadeSelfServiceAdult + QuantidadeSelfServiceInfantil + ""); lblQuantidadeCafe.setText(QuantidadeCafeAdulto + QuantidadeCafeInfantil + ""); lblTotalCafe.setText(z.format(RelTotalCafe)); lblTotalSelf.setText(z.format(RelTotalSelfService)); lblTotalGeral.setText(z.format(RelTotalGeral)); RelTotalSelfService = (QuantidadeSelfServiceAdult * selfServiceAdulto) + (QuantidadeSelfServiceInfantil * SelfServiceInfantil); } else { Refeicao.setQuantidadeCafeAdulto(QuantidadeCafeAdulto); QuantidadeSelfServiceAdult =0; QuantidadeSelfServiceInfantil =0; QuantidadeSelfServiceTotal =0; RelTotalSelfService =0; QuantidadeCafeAdulto = Integer.parseInt(txtCafeAdulto.getText()); QuantidadeCafeInfantil = Integer.parseInt(txtCafeInfantil.getText()); QuantidadeCafeTotal = QuantidadeCafeAdulto+QuantidadeCafeInfantil; QuantidadeExecutivoAdulto = Integer.parseInt(txtExecutivoAdulto.getText()); QuantidadeExecutivoInfantil = Integer.parseInt(txtExecutivoInfantil.getText()); QuantidadeExecutivoTotal = QuantidadeExecutivoAdulto+QuantidadeExecutivoInfantil; QuantidadeAlacarteAdulto = Integer.parseInt(txtAlacarteAdulto.getText()); QuantidadeAlacarteInfantil = Integer.parseInt(txtAlacarteInfantil.getText()); QuantidadeAlacarteTotal = QuantidadeAlacarteAdulto+QuantidadeAlacarteInfantil; QuantidadeTotal = QuantidadeCafeTotal+QuantidadeExecutivoTotal+QuantidadeAlacarteTotal; RelTotalGeral = (QuantidadeAlacarteAdulto * AlacarteAdulto) + (QuantidadeAlacarteInfantil * AlacarteInfantil) + (QuantidadeCafeAdulto * CafeAdulto) + (QuantidadeCafeInfantil * CafeInfantil) + (QuantidadeExecutivoAdulto * ExecutivoAdulto) + (QuantidadeExecutivoInfantil * ExecutivoInfantil); lblTotalQuantidadesRefeicao.setText (QuantidadeExecutivoAdulto + QuantidadeExecutivoInfantil + QuantidadeAlacarteAdulto + QuantidadeAlacarteInfantil + ""); lblQuantidadeCafe.setText(QuantidadeCafeAdulto + QuantidadeCafeInfantil + ""); lblTotalGeral.setText(z.format(RelTotalGeral)); RelTotalCafe = (QuantidadeCafeAdulto * CafeAdulto) + (QuantidadeCafeInfantil * CafeInfantil); RelTotalExecutivo = (QuantidadeExecutivoAdulto * ExecutivoAdulto) + (QuantidadeExecutivoInfantil * ExecutivoInfantil); RelTotalAlacarte = (QuantidadeAlacarteAdulto * AlacarteAdulto) + (QuantidadeAlacarteInfantil * AlacarteInfantil); lblTotalCafe.setText(z.format(RelTotalCafe)); lblTotalExec.setText(z.format(RelTotalExecutivo)); lblTotalAlacarte.setText(z.format(RelTotalAlacarte)); } rel.AtualizaRELL(this,1); }//GEN-LAST:event_btnCalcularActionPerformed private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened Rikimaru(); }//GEN-LAST:event_formWindowOpened private void rdSelfServiceInfantilItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rdSelfServiceInfantilItemStateChanged if (rdSelfServiceInfantil.isSelected()) { SelfServiceInfantil = 13.50; txtSelfServiceInfantil.setVisible(true); rdSerlServiceAdulto.setSelected(true); } else { SelfServiceInfantil = 0; rdSerlServiceAdulto.setSelected(false); txtSelfServiceInfantil.setVisible(false); txtSelfServiceInfantil.setText("0"); } }//GEN-LAST:event_rdSelfServiceInfantilItemStateChanged private void rdSerlServiceAdultoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rdSerlServiceAdultoItemStateChanged if (rdSerlServiceAdulto.isSelected()) { txtSelfServiceInfantil.setEnabled(true); chkAlacarteAdulto.setEnabled(false); chkExecutivoAdulto.setEnabled(false); chkAlacarteAdulto.setSelected(false); chkExecutivoAdulto.setSelected(false); chkAlacarteInfantil.setSelected(false); chkExecutivoInfantil.setSelected(false); chkAlacarteInfantil.setEnabled(false); chkExecutivoInfantil.setEnabled(false); rdSelfServiceInfantil.setSelected(true); selfServiceAdulto = 27.50; txtSelfServiceAdulto.setVisible(true); PanelAlacarte.setVisible(false); PanelExecutivo.setVisible(false); PanelSelf.setVisible(true); } else { txtSelfServiceInfantil.setEnabled(false); chkAlacarteAdulto.setEnabled(true); chkExecutivoAdulto.setEnabled(true); chkAlacarteInfantil.setEnabled(true); chkExecutivoInfantil.setEnabled(true); selfServiceAdulto = 0; txtSelfServiceAdulto.setVisible(false); PanelAlacarte.setVisible(true); PanelExecutivo.setVisible(true); PanelSelf.setVisible(false); txtSelfServiceAdulto.setText("0"); rdSelfServiceInfantil.setSelected(false); } }//GEN-LAST:event_rdSerlServiceAdultoItemStateChanged private void chkExecutivoAdultoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_chkExecutivoAdultoItemStateChanged if (chkExecutivoAdulto.isSelected()) { ExecutivoAdulto = 13.00; txtExecutivoAdulto.setVisible(true); } else { ExecutivoAdulto = 0; txtExecutivoAdulto.setVisible(false); txtExecutivoAdulto.setText("0"); } }//GEN-LAST:event_chkExecutivoAdultoItemStateChanged private void chkExecutivoInfantilItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_chkExecutivoInfantilItemStateChanged if (chkExecutivoInfantil.isSelected()) { ExecutivoInfantil = 6.50; txtExecutivoInfantil.setVisible(true); } else { ExecutivoInfantil = 0; txtExecutivoInfantil.setVisible(false); txtExecutivoInfantil.setText("0"); } }//GEN-LAST:event_chkExecutivoInfantilItemStateChanged private void chkAlacarteAdultoItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_chkAlacarteAdultoItemStateChanged if (chkAlacarteAdulto.isSelected()) { AlacarteAdulto = 21.00; txtAlacarteAdulto.setVisible(true); } else { AlacarteAdulto = 0; txtAlacarteAdulto.setVisible(false); txtAlacarteAdulto.setText("0"); } }//GEN-LAST:event_chkAlacarteAdultoItemStateChanged private void chkAlacarteInfantilItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_chkAlacarteInfantilItemStateChanged if (chkAlacarteInfantil.isSelected()) { AlacarteInfantil = 10.50; txtAlacarteInfantil.setVisible(true); } else { AlacarteInfantil = 0; txtAlacarteInfantil.setVisible(false); txtAlacarteInfantil.setText("0"); } }//GEN-LAST:event_chkAlacarteInfantilItemStateChanged private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed FrmRelatorio Rel = new FrmRelatorio(); Rel.AtualizaRelatorio(); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(FrmRefeicoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(FrmRefeicoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(FrmRefeicoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(FrmRefeicoes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new FrmRefeicoes().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel PanelAlacarte; private javax.swing.JPanel PanelCafe; private javax.swing.JPanel PanelExecutivo; private javax.swing.JPanel PanelSelf; private javax.swing.JButton btnCalcular; private javax.swing.JCheckBox chkAlacarteAdulto; private javax.swing.JCheckBox chkAlacarteInfantil; private javax.swing.JCheckBox chkCafeAdulto; private javax.swing.JCheckBox chkCafeInfantil; private javax.swing.JCheckBox chkExecutivoAdulto; private javax.swing.JCheckBox chkExecutivoInfantil; private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JPanel jPanel1; private javax.swing.JTextField jTextField1; private javax.swing.JLabel lblFundo; private javax.swing.JLabel lblLogo; private javax.swing.JLabel lblQuantidadeCafe; private javax.swing.JLabel lblTotalAlacarte; private javax.swing.JLabel lblTotalCafe; private javax.swing.JLabel lblTotalExec; private javax.swing.JLabel lblTotalGeral; private javax.swing.JLabel lblTotalQuantidadesRefeicao; private javax.swing.JLabel lblTotalSelf; private javax.swing.JRadioButton rdSelfServiceInfantil; private javax.swing.JRadioButton rdSerlServiceAdulto; private javax.swing.JTextField txtAlacarteAdulto; private javax.swing.JTextField txtAlacarteInfantil; private javax.swing.JTextField txtCafeAdulto; private javax.swing.JTextField txtCafeInfantil; private javax.swing.JTextField txtExecutivoAdulto; private javax.swing.JTextField txtExecutivoInfantil; private javax.swing.JTextField txtSelfServiceAdulto; private javax.swing.JTextField txtSelfServiceInfantil; // End of variables declaration//GEN-END:variables NumberFormat z = NumberFormat.getCurrencyInstance(); double ExecutivoAdulto = 0, ExecutivoInfantil = 0, AlacarteAdulto = 0, AlacarteInfantil = 0, CafeAdulto = 0, CafeInfantil = 0, selfServiceAdulto = 0, SelfServiceInfantil = 0; double total = 0; public static int QuantidadeTotal, QuantidadeExecutivoAdulto, QuantidadeExecutivoInfantil, QuantidadeAlacarteAdulto, QuantidadeAlacarteInfantil, QuantidadeCafeAdulto, QuantidadeCafeInfantil, QuantidadeSelfServiceAdult, QuantidadeSelfServiceInfantil, QuantidadeSelfServiceTotal, QuantidadeAlacarteTotal, QuantidadeExecutivoTotal,QuantidadeRefeicoesTotal, QuantidadeCafeTotal, teste; public static double RelTotalCafe, RelTotalAlacarte, RelTotalSelfService, RelTotalExecutivo, RelTotalGeral; public void Rikimaru() { txtAlacarteAdulto.setVisible(false); txtAlacarteInfantil.setVisible(false); txtCafeAdulto.setVisible(false); txtCafeInfantil.setVisible(false); txtExecutivoAdulto.setVisible(false); txtExecutivoInfantil.setVisible(false); txtSelfServiceAdulto.setVisible(false); txtSelfServiceInfantil.setVisible(false); PanelSelf.setVisible(false); txtAlacarteAdulto.setText("0"); txtAlacarteInfantil.setText("0"); txtCafeAdulto.setText("0"); txtCafeInfantil.setText("0"); txtExecutivoAdulto.setText("0"); txtExecutivoInfantil.setText("0"); txtSelfServiceAdulto.setText("0"); txtSelfServiceInfantil.setText("0"); } }
50.599732
155
0.685698
a3c9fffb2366cece0bea815d030557ce816192b5
9,185
package com.apptitive.beautytips; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.WindowCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.webkit.WebView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.FrameLayout; import android.widget.ListView; import android.widget.TextView; import com.android.volley.VolleyError; import com.android.volley.toolbox.ImageLoader; import com.apptitive.beautytips.helper.DbManager; import com.apptitive.beautytips.model.Content; import com.apptitive.beautytips.model.DbContent; import com.apptitive.beautytips.model.DetailType; import com.apptitive.beautytips.utilities.Config; import com.apptitive.beautytips.utilities.Constants; import com.apptitive.beautytips.utilities.HttpHelper; import com.apptitive.beautytips.utilities.Utilities; import java.util.ArrayList; import java.util.List; public class DetailsActivity extends BaseActionBar implements DetailsFragment.DetailProvider { private String menuId; private Content content; private List<Content> contents; private ArrayAdapter<Content> drawerListAdapter; private ActionBar actionBar; private DrawerLayout drawerLayout; private FrameLayout fragmentContainer; private ListView listViewDrawer; private WebView webViewDetails; private DetailsFragment detailsFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); DbManager.init(this); supportRequestWindowFeature(WindowCompat.FEATURE_ACTION_BAR_OVERLAY); Bundle extras = getIntent().getExtras(); if (extras != null) { menuId = extras.getString(Constants.menu.EXTRA_MENU_ID); content = extras.getParcelable(Constants.content.EXTRA_CONTENT); } if (savedInstanceState != null) { content = savedInstanceState.getParcelable(Constants.content.EXTRA_CONTENT); menuId = savedInstanceState.getString(Constants.menu.EXTRA_MENU_ID); } actionBar = getSupportActionBar(); actionBar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.ActionBarInnerBg))); actionBar.setTitle(Utilities.getBanglaSpannableString(content.getHeader(), this)); ImageLoader imageLoader = HttpHelper.getInstance(this).getImageLoader(); imageLoader.get(Config.getImageUrl(this) + menuId + "_ab_title.png", new ImageLoader.ImageListener() { @Override public void onErrorResponse(VolleyError error) { } @Override public void onResponse(ImageLoader.ImageContainer response, boolean arg1) { if (response.getBitmap() != null) { actionBar.setIcon(new BitmapDrawable(getResources(), response.getBitmap())); } } }); actionBar.setDisplayShowHomeEnabled(true); setContentView(R.layout.activity_details); drawerLayout = (DrawerLayout) findViewById(R.id.layout_drawer); listViewDrawer = (ListView) findViewById(R.id.listView_drawer); webViewDetails = (WebView) findViewById(R.id.webView_details); fragmentContainer = (FrameLayout) findViewById(R.id.fragment_container); if (content.getDetailType().equals(DetailType.HTML)) { webViewDetails.setVisibility(View.VISIBLE); webViewDetails.loadData(content.getDetails(), "text/html", "utf-8"); } else if (content.getDetailType().equals(DetailType.NATIVE)) { showHideFragment(true); } contents = dbResultToContent(DbManager.getInstance().getDbContentForMenu(menuId)); drawerListAdapter = new ArrayAdapter<Content>(this, R.layout.list_item_nav_drawer, contents) { @Override public int getViewTypeCount() { if (getCount() != 0) return getCount(); return 1; } @Override public int getItemViewType(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView tvHeader; Content content = getItem(position); if (convertView == null) { convertView = getLayoutInflater().inflate(R.layout.list_item_nav_drawer, parent, false); } tvHeader = (TextView) convertView.findViewById(R.id.btv_nav); tvHeader.setText(Utilities.getBanglaSpannableString(getItem(position).getHeader(), DetailsActivity.this)); if (content.getContentId().equals(DetailsActivity.this.content.getContentId())) convertView.setBackgroundColor(getResources().getColor(R.color.NavDrawerListItemSelected)); return convertView; } }; listViewDrawer.setAdapter(drawerListAdapter); listViewDrawer.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View item, int position, long id) { content = contents.get(position); actionBar.setTitle(Utilities.getBanglaSpannableString(content.getHeader(), DetailsActivity.this)); if (content.getDetailType().equals(DetailType.HTML)) { showHideFragment(false); webViewDetails.setVisibility(View.VISIBLE); webViewDetails.loadData(content.getDetails(), "text/html", "utf-8"); } else if (content.getDetailType().equals(DetailType.NATIVE)) { webViewDetails.setVisibility(View.GONE); showHideFragment(true); } listViewDrawer.setAdapter(drawerListAdapter); drawerLayout.closeDrawer(listViewDrawer); } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(Constants.menu.EXTRA_MENU_ID, menuId); outState.putParcelable(Constants.content.EXTRA_CONTENT, content); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); content = savedInstanceState.getParcelable(Constants.content.EXTRA_CONTENT); menuId = savedInstanceState.getString(Constants.menu.EXTRA_MENU_ID); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.details, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_drawer: if (drawerLayout.isDrawerOpen(listViewDrawer)) drawerLayout.closeDrawer(listViewDrawer); else drawerLayout.openDrawer(listViewDrawer); break; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { if (drawerLayout.isDrawerOpen(listViewDrawer)) drawerLayout.closeDrawer(listViewDrawer); else super.onBackPressed(); } private void showHideFragment(boolean show) { if (detailsFragment == null) { detailsFragment = new DetailsFragment(); } FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); if (show) { if (detailsFragment.isAdded()) { detailsFragment.switchContent(); } else { fragmentContainer.setVisibility(View.VISIBLE); Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (fragment instanceof DetailsFragment) { ft.replace(fragmentContainer.getId(), detailsFragment); ft.commit(); } else { ft.add(fragmentContainer.getId(), detailsFragment); ft.commit(); } } } else { fragmentContainer.setVisibility(View.GONE); ft.remove(detailsFragment); ft.commit(); } } private List<Content> dbResultToContent(List<DbContent> dbContents) { List<Content> contents = new ArrayList<Content>(); for (DbContent dbContent : dbContents) { Content content = new Content(); content.populateFrom(dbContent); contents.add(content); } return contents; } public Content getContent() { return content; } }
39.761905
122
0.657485
61a48cf13750c44d1d6fa7f13cf15dbfd9f3e56d
5,795
package br.com.zup.nossocartao.proposta.associacarteiradigital; import br.com.zup.nossocartao.proposta.associacartao.CartaoEntity; import br.com.zup.nossocartao.proposta.associacartao.CartaoRepository; import br.com.zup.nossocartao.proposta.compartilhado.exceptionhandler.ApiErrorException; import br.com.zup.nossocartao.proposta.outrossistemas.CartaoFeign; import feign.FeignException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.core.annotation.AuthenticationPrincipal; import org.springframework.security.oauth2.jwt.Jwt; import org.springframework.transaction.support.TransactionTemplate; import org.springframework.web.bind.annotation.*; import org.springframework.web.util.UriComponentsBuilder; import javax.validation.Valid; import java.net.URI; import java.util.Map; import java.util.Optional; import java.util.UUID; @RestController @RequestMapping(path = "/carteiras_digitais", produces = MediaType.APPLICATION_JSON_VALUE) public class AssociaCarteirasDigitaisController { private final CartaoFeign cartaoFeign; private final CartaoRepository cartaoRepository; private final CarteiraDigitalRepository carteiraDigitalRepository; private final TransactionTemplate transactionTemplate; private Logger logger = LoggerFactory.getLogger(AssociaCarteirasDigitaisController.class); public AssociaCarteirasDigitaisController(CartaoFeign cartaoFeign, CartaoRepository cartaoRepository, CarteiraDigitalRepository carteiraDigitalRepository, TransactionTemplate transactionTemplate) { this.cartaoFeign = cartaoFeign; this.cartaoRepository = cartaoRepository; this.carteiraDigitalRepository = carteiraDigitalRepository; this.transactionTemplate = transactionTemplate; } @PostMapping(path = "/{cartaoId}/associa_carteiras_digitais/{provedor}") public ResponseEntity<?> registerWallet(@PathVariable(name = "cartaoId") UUID cartaoId, @PathVariable(name = "provedor") String provedor, @RequestBody @Valid NovaCarteiraDigitalRequest novaCarteiraDigitalRequest, UriComponentsBuilder uriComponentsBuilder, @AuthenticationPrincipal Jwt jwt){ ProvedorCarteiraDigital provedorCarteiraDigital = ProvedorCarteiraDigital.toEnum(provedor); if(provedorCarteiraDigital == null){ throw new ApiErrorException(HttpStatus.NOT_FOUND, "Provedor de carteira digital inválida."); } Optional<CartaoEntity> optionalCreditCard = cartaoRepository.findById(cartaoId); CartaoEntity cartao = optionalCreditCard.orElseThrow(() -> { throw new ApiErrorException(HttpStatus.NOT_FOUND, "Nenhum cartão de credito encontrado para esse Id"); }); Optional<CarteiraDigitalEntity> cartaoJaAssociado = carteiraDigitalRepository.findByCartao_CartaoIdAndProvedor(cartaoId, provedorCarteiraDigital); if(cartaoJaAssociado.isPresent()){ throw new ApiErrorException(HttpStatus.UNPROCESSABLE_ENTITY, "Esse cartão de credito já foi associado a esse provedor"); } if(!cartao.pertenceAoUsuario(jwt.getClaimAsString("email"))){ throw new ApiErrorException(HttpStatus.FORBIDDEN, "Esse cartão de credito não pertence a esse usuário"); } boolean success = informaAssociacaoCartaoCarteiraDigital(cartao, novaCarteiraDigitalRequest, provedorCarteiraDigital); if(success){ CarteiraDigitalEntity carteiraDigital = novaCarteiraDigitalRequest.toModel(provedorCarteiraDigital, cartao); transactionTemplate.execute(status -> { carteiraDigitalRepository.save(carteiraDigital); return true; }); URI uri = uriComponentsBuilder.path("/{id}/wallets/{wallet}/{id}") .buildAndExpand(cartaoId, provedorCarteiraDigital.name().toLowerCase(), carteiraDigital.getCarteiraDigitalId()) .toUri(); return ResponseEntity.created(uri).build(); } else { throw new ApiErrorException(HttpStatus.INTERNAL_SERVER_ERROR, "Erro ao processar essa requisição"); } } public boolean informaAssociacaoCartaoCarteiraDigital(CartaoEntity cartao, @Valid NovaCarteiraDigitalRequest novaCarteiraDigitalRequest, ProvedorCarteiraDigital provedorCarteiraDigital) { InformaCarteiraDigitalRequest informaCarteiraDigitalRequest = new InformaCarteiraDigitalRequest(novaCarteiraDigitalRequest.getEmail(), provedorCarteiraDigital); try { Map<String, String> response = cartaoFeign.informaCarteiraDigital(cartao.getNumero(), informaCarteiraDigitalRequest); if(response.get("resultado").equalsIgnoreCase("ASSOCIADA")){ return true; } else { logger.error("Retorno inválido na API Informa Associção Cartão de Credito Carteira Digital - Body: {}", response); return false; } } catch (FeignException feignException){ logger.error("Erro na API Informa Associção Cartão de Credito Carteira Digital - Status code: {}, Body: {}, Message: {}", feignException.status(), feignException.contentUTF8(), feignException.getMessage()); return false; } } }
51.741071
168
0.699914
7694cb3e6d6d546d076b70cbc3a5744567e33e8d
2,069
package com.alisls.demo.springcloud.service.order.web; import com.alisls.demo.springcloud.service.order.client.ProductClient; import com.alisls.demo.springcloud.service.order.dto.OrderDTO; import com.alisls.demo.springcloud.service.order.service.OrderService; import com.springcloud.common.model.dto.Result; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiOperation; import lombok.AllArgsConstructor; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * 订单管理 * * @author Ke Wang */ @Api(tags = "订单管理") @RestController @RequestMapping("/order") @AllArgsConstructor public class OrderController { /** * 订单服务 */ private final OrderService orderService; /** * 商品客户端 */ private final ProductClient productClient; /** * 根据订单标识查询订单 */ @ApiOperation(value = "查询订单", notes = "根据订单标识查询订单") @ApiImplicitParam( name = "id", required = true, paramType = "path", dataType = "Long", example = "1234567890123456789" ) @GetMapping("/getOrderById/{id}") public OrderDTO getOrderById(@PathVariable Long id) { OrderDTO orderDTO = orderService.getOrder(id); return orderDTO; } /** * 根据订单标识查询订单商品 */ @ApiOperation(value = "查询订单商品", notes = "根据订单标识查询订单商品") @ApiImplicitParam( name = "orderId", required = true, paramType = "path", dataType = "Long", example = "1234567890123456789" ) @GetMapping("/getOrderProducts/{orderId}") public ResponseEntity<Result> getOrderProducts(@PathVariable Long orderId) { //DataResult<ProductDTO> dataResult = productClient.listProducts(); //return ResponseEntity.ok(dataResult); return null; } }
27.959459
77
0.691638
9e2c1346605ad7aa73db265ebc307a37f3e1a1ea
877
package io.rtcore.sip.message.parsers.core.terminal; import com.google.common.primitives.Bytes; import io.rtcore.sip.message.parsers.api.Parser; import io.rtcore.sip.message.parsers.api.ParserContext; import io.rtcore.sip.message.parsers.api.ValueListener; /** * * * */ public class OneOf implements Parser<CharSequence> { private final byte[] bytes; public OneOf(final byte[] bytes) { this.bytes = bytes; } @Override public boolean find(final ParserContext context, final ValueListener<CharSequence> value) { final int pos = context.position(); if (context.remaining() > 0 && Bytes.contains(this.bytes, context.get())) { return true; } context.position(pos); return false; } @Override public String toString() { return new StringBuilder().append("oneOf(").append(this.bytes).append(")").toString(); } }
19.931818
93
0.694413
96583adab2802a0f884d637bbb1e16a4d62983d6
723
package org.nuclearfog.twidda.model; /** * interface for relation implementations * * @author nuclearfog */ public interface Relation { /** * @return true if the relation points to the current user */ boolean isHome(); /** * @return true if current user is following this user */ boolean isFollowing(); /** * @return true if this user is a follower */ boolean isFollower(); /** * @return true if this user is blocked */ boolean isBlocked(); /** * @return true if this user is muted */ boolean isMuted(); /** * @return true if this user accepts direct messages from the current user */ boolean canDm(); }
18.075
78
0.591978
3a0a2ca588bc0db6f801ed02551ef1e6dfb79abf
420
package com.cjxch.supermybatis.core.enu; import com.cjxch.supermybatis.core.provider.GetSqlProvider; import java.lang.annotation.*; /** * 自定义sql解析器注解 * @Author: 菜鸡小彩虹 * @Date: 2020/09/22/15:52 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target( {ElementType.TYPE}) public @interface SuperMybatisSqlProvider { /** * 解析器名称 * @return */ Class value() default GetSqlProvider.class; }
17.5
59
0.702381
01d57041682bdecf6e34452739fb9ac0652c72fb
435
package com.thoughtworks.sql; import org.junit.Test; import static com.thoughtworks.sql.Field.field; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class FieldTest { @Test public void should_return_true_if_field_has_alias_name() { Field field = field("t.ss"); assertFalse(field.hasAlias()); field.as("s"); assertTrue(field.hasAlias()); } }
22.894737
62
0.701149
1d356d7628283eeaca0e3cd5967e8acacbc9899f
732
package costfunction; import state.State; /** * @author Nikhil Chakravartula ([email protected]) ([email protected]) * Approximate distance between two adjacent states. Diagonal : 14 Non-diagonal : 10 */ public class MoveCostFunction implements CostFunction { static final int DIAGONALCOST = 14; static final int NONDIAGONALCOST = 10; @Override public long cost(State currentState, State nextState) { long cost = 0; if (Math.abs(nextState.getX() - currentState.getX()) == 1 && Math.abs(nextState.getY() - currentState.getY()) == 1) { //currentState lies digoanally adjacent to nextState cost = DIAGONALCOST; } else cost = NONDIAGONALCOST; return cost; } }
26.142857
84
0.692623
ac75269efdccaed02c868b0f5029acba9e59e4ad
1,047
package com.dingmouren.example.layoutmanagergroup.widget; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.RelativeLayout; /** * Created by dingmouren * email: [email protected] * github: https://github.com/DingMouRen */ public class InterceptRelativeLayout extends RelativeLayout { private boolean mIntercept = true; public InterceptRelativeLayout(Context context) { super(context); } public InterceptRelativeLayout(Context context, AttributeSet attrs) { super(context, attrs); } public InterceptRelativeLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean dispatchTouchEvent(MotionEvent ev) { if (mIntercept){ return true; }else { return super.dispatchTouchEvent(ev); } } public void setIntercept(boolean intercept){ this.mIntercept = intercept; } }
24.348837
91
0.700096
d7012e40ef207545ec5bda6a9e2de685aacb851b
1,602
package com.lyl.db.sub_db; import android.util.Log; import com.lyl.db.db.BaseDao; import java.util.List; /** * Created by dds on 2019/7/15. * [email protected] */ public class UserDao extends BaseDao<User> { private final static String TAG = "dds_UserDao"; @Override public long insert(User entity) { List<User> list = query(new User()); User where; for (User user : list) { if (entity.getId().equals(user.getId())) { continue; } if (user.getState() == State.Default.ordinal()) { continue; } // 设置之前用户为未登录 where = new User(); where.setId(user.getId()); user.setState(State.Default.ordinal()); update(user, where); Log.i(TAG, user.getName() + "-->logout"); } // 设置当前用户为登录状态 entity.setState(State.Login.ordinal()); where = new User(); where.setId(entity.getId()); int result = update(entity, where); if (result > 0) { Log.i(TAG, entity.getName() + "-->reLogin"); return result; } else { Log.i(TAG, entity.getName() + "-->first login"); return super.insert(entity); } } // 获取当前登录的用户信息 public User getCurrentUser() { User user = new User(); user.setState(State.Login.ordinal()); List<User> list = query(user); if (list.size() > 0) { return list.get(0); } return null; } enum State {Default, Login} }
24.646154
61
0.516854
ffa3ac6a73e6e8531d1fe1d2193432982856c75f
9,315
package de.viadee.xai.anchor.algorithm; import de.viadee.xai.anchor.algorithm.util.ParameterValidation; import java.io.Serializable; import java.util.*; /** * Representation of an Anchor candidate. * <p> * An Anchor is defined by the features is comprises. * <p> * This class is not completely immutable but thread-safe! */ public class AnchorCandidate implements Serializable { private static final long serialVersionUID = 3193512500527138686L; /* * Immutable fields */ private final List<Integer> orderedFeatures; private final SortedSet<Integer> canonicalFeatures; private final AnchorCandidate parentCandidate; /* * Mutable fields. Write-access only allowed by synchronized registerSamples! */ private Double coverage; private int sampledSize = 0; private int positiveSamples = 0; private double precision = 0; /** * Constructs the candidate and sets its immutable features and coverage. * * @param features the features the candidate comprises * @param parentCandidate the parent candidate this rule has been derived from */ public AnchorCandidate(final Collection<Integer> features, final AnchorCandidate parentCandidate) { if (features == null) throw new IllegalArgumentException("Features" + ParameterValidation.NULL_MESSAGE); if (parentCandidate == null && features.size() > 1) throw new IllegalArgumentException("No parent candidate specified"); if (parentCandidate != null && (features.size() != parentCandidate.canonicalFeatures.size() + 1)) throw new IllegalArgumentException("Parent candidate must have n-1 features"); // Candidates get "normalized" as treeSet is automatically sorted this.orderedFeatures = Collections.unmodifiableList(new ArrayList<>(features)); this.canonicalFeatures = Collections.unmodifiableSortedSet(new TreeSet<>(features)); this.parentCandidate = parentCandidate; } /** * Constructs the candidate and sets its immutable features and coverage. * <p> * Does not check for correctly added parents. * * @param features the features the candidate comprises */ public AnchorCandidate(final Collection<Integer> features) { this(features, fakeParent(features)); } private static AnchorCandidate fakeParent(final Collection<Integer> features) { if (features.size() <= 1) { return null; } else { final Collection<Integer> parentFeatures = new ArrayList<>(features).subList(0, features.size() - 1); return new AnchorCandidate(parentFeatures, fakeParent(parentFeatures)); } } /** * Updates the precision of the candidate when new samples were taken. * <p> * Synchronized access to mutable variables! * * @param sampleSize the amount of performed evaluations * @param positiveSamples the amount of correctly identified evaluations */ public synchronized void registerSamples(final int sampleSize, final int positiveSamples) { if (!ParameterValidation.isUnsigned(sampleSize)) throw new IllegalArgumentException("Sampled size" + ParameterValidation.NEGATIVE_VALUE_MESSAGE); if (!ParameterValidation.isUnsigned(positiveSamples)) throw new IllegalArgumentException("Positive" + ParameterValidation.NEGATIVE_VALUE_MESSAGE); if (positiveSamples > sampleSize) throw new IllegalArgumentException("Positive samples must be smaller or equal to sample size"); this.sampledSize += sampleSize; this.positiveSamples += positiveSamples; this.precision = (this.sampledSize == 0) ? 0 : this.positiveSamples / (double) this.sampledSize; } /** * @return an UnmodifiableList of the contained features * in the order they were constructed */ public List<Integer> getOrderedFeatures() { // Is immutable anyways return orderedFeatures; } /** * @return an UnmodifiableSortedSet of the canonical features */ public SortedSet<Integer> getCanonicalFeatures() { // Immutable too return canonicalFeatures; } /** * @return current precision of the anchor */ public double getPrecision() { return precision; } /** * @return coverage of the anchor. May be null if not already set. */ public Double getCoverage() { return coverage; } /** * Sets the coverage of the anchor. * <p> * Its coverage may only be set once as it makes no sense of recalculating it. * <p> * It makes sense not to calculate the coverage at construction time, as some anchors' coverage will never need to * be calculated at all. * <p> * Furthermore, in some scenarios, calculating coverage is expensive. * <p> * As this method is only being called from synchronous methods, no synchronization is needed. * * @param coverage the coverage */ public void setCoverage(double coverage) { if (this.coverage != null) throw new IllegalArgumentException("Coverage has already been set!"); if (!ParameterValidation.isPercentage(coverage)) throw new IllegalArgumentException("Coverage" + ParameterValidation.NOT_PERCENTAGE_MESSAGE); this.coverage = coverage; } /** * Returns the feature that has been added during the creation of this instance * * @return the added feature */ public Integer getAddedFeature() { return orderedFeatures.get(orderedFeatures.size() - 1); } /** * May be used to lazily evaluate a candidate's coverage * * @return true, if coverage has not yet been calculated */ boolean isCoverageUndefined() { return coverage == null; } /** * @return samples taken so far */ public int getSampledSize() { return sampledSize; } /** * @return amount of correct predictions so far */ public int getPositiveSamples() { return positiveSamples; } public boolean hasParentCandidate() { return this.parentCandidate != null; } /** * May be used to get the parent this rule has been derived from. * <p> * Useful to get the added feature precision this anchor provides. * * @return the parent this rule has been derived from */ public AnchorCandidate getParentCandidate() { return parentCandidate; } /** * When adding features to a rule, the precision usually increases (due to random sampling it might decrease). * * @return the increased precision value this candidate provides over his parent. */ public double getAddedPrecision() { final double parentPrecision = hasParentCandidate() ? parentCandidate.getPrecision() : 0; return precision - parentPrecision; } /** * When adding a feature to a rule, the precision usually decreases. * <p> * This method returns this as a negative value. * * @return the reduced coverage in comparison to this candidate's parent */ public double getAddedCoverage() { final double parentCoverage = hasParentCandidate() ? parentCandidate.getCoverage() : 1; return coverage - parentCoverage; } /** * When adding a feature to a rule, the precision usually decreases. * <p> * However, coverage shouldn't be compared in absolutes. * <p> * This method returns this as a negative value. * * @return the reduced coverage in comparison to this candidate's parent */ public double getAddedCoverageInPercent() { final double parentCoverage = hasParentCandidate() ? parentCandidate.getCoverage() : 1; // Prevent NaN as result return (parentCoverage == 0) ? 0 : ((coverage - parentCoverage) / parentCoverage); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; AnchorCandidate that = (AnchorCandidate) o; return sampledSize == that.sampledSize && positiveSamples == that.positiveSamples && Double.compare(that.precision, precision) == 0 && Objects.equals(orderedFeatures, that.orderedFeatures) && Objects.equals(canonicalFeatures, that.canonicalFeatures) && Objects.equals(parentCandidate, that.parentCandidate) && Objects.equals(coverage, that.coverage); } @Override public int hashCode() { return Objects.hash(orderedFeatures, canonicalFeatures, parentCandidate, coverage, sampledSize, positiveSamples, precision); } @Override public String toString() { return "AnchorCandidate {" + "features=" + canonicalFeatures + ", ordering=" + orderedFeatures + ", precision=" + precision + ", coverage=" + coverage + ", sampledSize=" + sampledSize + ", positiveSamples=" + positiveSamples + '}'; } }
35.150943
132
0.650349
a694705ce03935026da560e8c74440ce4979945d
4,247
package com.yyxnb.what.core.file; import java.io.File; import java.util.regex.Pattern; import cn.hutool.core.util.CharUtil; import cn.hutool.core.util.ReUtil; import cn.hutool.core.util.StrUtil; public class FileNameUtils { public static final String EXT_JAVA = ".java"; public static final String EXT_CLASS = ".class"; public static final String EXT_JAR = ".jar"; public static final char UNIX_SEPARATOR = '/'; public static final char WINDOWS_SEPARATOR = '\\'; private static final Pattern FILE_NAME_INVALID_PATTERN_WIN = Pattern.compile("[\\\\/:*?\"<>|]"); /**校验文件名不含特殊字符*/ private static final String FILE_NAME_CHECK = "[`~!@#$%^&-+=\\?:\"|,/;'\\[\\]·~!@#¥%……&*()+=\\{\\}\\|《》?:“”【】、;‘',。\\、\\-]"; public static String getName(File file) { return null != file ? file.getName() : null; } public static String getName(String filePath) { if (null == filePath) { return null; } else { int len = filePath.length(); if (0 == len) { return filePath; } else { if (CharUtil.isFileSeparator(filePath.charAt(len - 1))) { --len; } int begin = 0; for (int i = len - 1; i > -1; --i) { char c = filePath.charAt(i); if (CharUtil.isFileSeparator(c)) { begin = i + 1; break; } } return filePath.substring(begin, len); } } } public static String getSuffix(File file) { return extName(file); } public static String getSuffix(String fileName) { return extName(fileName); } public static String getPrefix(File file) { return mainName(file); } public static String getPrefix(String fileName) { return mainName(fileName); } public static String mainName(File file) { return file.isDirectory() ? file.getName() : mainName(file.getName()); } public static String mainName(String fileName) { if (null == fileName) { return null; } else { int len = fileName.length(); if (0 == len) { return fileName; } else { if (CharUtil.isFileSeparator(fileName.charAt(len - 1))) { --len; } int begin = 0; int end = len; for (int i = len - 1; i >= 0; --i) { char c = fileName.charAt(i); if (len == end && '.' == c) { end = i; } if (CharUtil.isFileSeparator(c)) { begin = i + 1; break; } } return fileName.substring(begin, end); } } } public static String extName(File file) { if (null == file) { return null; } else { return file.isDirectory() ? null : extName(file.getName()); } } public static String extName(String fileName) { if (fileName == null) { return null; } else { int index = fileName.lastIndexOf("."); if (index == -1) { return ""; } else { String ext = fileName.substring(index + 1); return StrUtil.containsAny(ext, new char[]{'/', '\\'}) ? "" : ext; } } } public static String cleanInvalid(String fileName) { return StrUtil.isBlank(fileName) ? fileName : ReUtil.delAll(FILE_NAME_INVALID_PATTERN_WIN, fileName); } public static boolean containsInvalid(String fileName) { return !StrUtil.isBlank(fileName) && ReUtil.contains(FILE_NAME_INVALID_PATTERN_WIN, fileName); } public static boolean isType(String fileName, String... extNames) { return StrUtil.equalsAnyIgnoreCase(extName(fileName), extNames); } /**fm文件名称*/ public static boolean checkFileName(String fm) { return ReUtil.isMatch(FILE_NAME_CHECK,fm); } }
29.908451
128
0.504121
2fdf7af9592da5101e0d5cdad32948abc14a67de
1,713
package com.zjb.loader.core.display; import android.graphics.Bitmap; import android.graphics.ComposeShader; import android.graphics.Matrix; import android.graphics.PorterDuff.Mode; import android.graphics.RadialGradient; import android.graphics.Rect; import android.graphics.Shader.TileMode; import com.zjb.loader.internal.core.assist.LoadedFrom; import com.zjb.loader.internal.core.imageaware.ImageAware; /** * time: 15/6/11 * description:带阴影(LOMO)效果的圆角矩形 * * @author sunjianfei */ public class RoundedLomoBitmapDisplayer extends RoundedBitmapDisplayer { public RoundedLomoBitmapDisplayer(int cornerRadiusPixels) { super(cornerRadiusPixels); } public RoundedLomoBitmapDisplayer(int cornerRadiusPixels, int marginPixels) { super(cornerRadiusPixels, marginPixels); } public void display(Bitmap bitmap, ImageAware imageAware, LoadedFrom loadedFrom) { imageAware.setImageDrawable(new RoundedVignetteDrawable(bitmap, this.cornerRadius, this.margin)); } protected static class RoundedVignetteDrawable extends RoundedDrawable { RoundedVignetteDrawable(Bitmap bitmap, int cornerRadius, int margin) { super(bitmap, cornerRadius, margin); } protected void onBoundsChange(Rect bounds) { super.onBoundsChange(bounds); RadialGradient vignette = new RadialGradient(this.mRect.centerX(), this.mRect.centerY() * 1.0F / 0.7F, this.mRect.centerX() * 1.3F, new int[]{0, 0, 2130706432}, new float[]{0.0F, 0.7F, 1.0F}, TileMode.CLAMP); Matrix oval = new Matrix(); oval.setScale(1.0F, 0.7F); vignette.setLocalMatrix(oval); this.paint.setShader(new ComposeShader(this.bitmapShader, vignette, Mode.SRC_OVER)); } } }
34.26
217
0.749562
82079e2972d53a32d36095b3ddb1906bde6d1e5b
2,160
package io.hassaan.configs; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; public final class ConfigurationManager { private static final ConfigurationManager _instance = new ConfigurationManager(); public String MSSQLConnectionString; public String MSSQLUsername; public String MSSQLPassword; public List<String> CorsDomains; public List<String> CorsHeaders; public List<String> CorsMethods; public List<String> CorsExposedHeaders; public boolean CorsAllowCredentials; public long CorsMaxAge; private ConfigurationManager() { try { getPropValues(); } catch (Exception e) { } } public static ConfigurationManager Instance() { return _instance; } private void getPropValues() throws IOException { InputStream inputStream = null; try { Properties prop = new Properties(); String propFileName = "config.properties"; inputStream = getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream != null) { prop.load(inputStream); } else { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } MSSQLConnectionString = prop.getProperty("mssql.connectionString"); MSSQLUsername = prop.getProperty("mssql.username"); MSSQLPassword = prop.getProperty("mssql.password"); CorsDomains = new ArrayList<String>(Arrays.asList(prop.getProperty("cors.domains").split(","))); CorsHeaders = new ArrayList<String>(Arrays.asList(prop.getProperty("cors.headers").split(","))); CorsMethods = new ArrayList<String>(Arrays.asList(prop.getProperty("cors.methods").split(","))); CorsExposedHeaders = new ArrayList<String>(Arrays.asList(prop.getProperty("cors.exposedHeaders").split(","))); CorsAllowCredentials = Boolean.parseBoolean(prop.getProperty("cors.allowCredentials", "false")); CorsMaxAge = Long.parseLong(prop.getProperty("cors.maxAge", "3600")); } catch (Exception e) { System.out.println("Exception: " + e); } finally { inputStream.close(); } } }
30.857143
113
0.74213
5ec411369de1c9e28a09173582a3a1c478bd9eeb
17,216
/** * JBoss, Home of Professional Open Source. * Copyright 2014 Red Hat, Inc., and individual contributors * as indicated by the @author tags. * * 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.jboss.pnc.auth.keycloakutil.util; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.apache.http.HeaderIterator; import org.apache.http.HttpHeaders; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.apache.http.client.methods.HttpOptions; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.entity.InputStreamEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.ssl.SSLContexts; import org.jboss.pnc.auth.keycloakutil.httpcomponents.HttpDelete; import org.jboss.pnc.auth.keycloakutil.operations.LocalSearch; import org.jboss.pnc.auth.keycloakutil.operations.RoleOperations; import org.keycloak.util.JsonSerialization; import javax.net.ssl.SSLContext; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.security.KeyManagementException; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import static org.keycloak.common.util.ObjectUtil.capitalize; /** * @author <a href="mailto:[email protected]">Marko Strukelj</a> */ public class HttpUtil { public static final String APPLICATION_XML = "application/xml"; public static final String APPLICATION_JSON = "application/json"; public static final String APPLICATION_FORM_URL_ENCODED = "application/x-www-form-urlencoded"; public static final String UTF_8 = "utf-8"; private static HttpClient httpClient; private static SSLConnectionSocketFactory sslsf; public static InputStream doGet(String url, String acceptType, String authorization) { try { HttpGet request = new HttpGet(url); request.setHeader(HttpHeaders.ACCEPT, acceptType); return doRequest(authorization, request); } catch (IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } public static InputStream doPost(String url, String contentType, String acceptType, String content, String authorization) { try { return doPostOrPut(contentType, acceptType, content, authorization, new HttpPost(url)); } catch (IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } public static InputStream doPut(String url, String contentType, String acceptType, String content, String authorization) { try { return doPostOrPut(contentType, acceptType, content, authorization, new HttpPut(url)); } catch (IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } public static void doDelete(String url, String authorization) { try { HttpDelete request = new HttpDelete(url); doRequest(authorization, request); } catch (IOException e) { throw new RuntimeException("Failed to send request - " + e.getMessage(), e); } } public static HeadersBodyStatus doGet(String url, HeadersBody request) throws IOException { return doRequest("get", url, request); } public static HeadersBodyStatus doPost(String url, HeadersBody request) throws IOException { return doRequest("post", url, request); } public static HeadersBodyStatus doPut(String url, HeadersBody request) throws IOException { return doRequest("put", url, request); } public static HeadersBodyStatus doDelete(String url, HeadersBody request) throws IOException { return doRequest("delete", url, request); } public static HeadersBodyStatus doRequest(String type, String url, HeadersBody request) throws IOException { HttpRequestBase req; switch (type) { case "get": req = new HttpGet(url); break; case "post": req = new HttpPost(url); break; case "put": req = new HttpPut(url); break; case "delete": req = new HttpDelete(url); break; case "options": req = new HttpOptions(url); break; case "head": req = new HttpHead(url); break; default: throw new RuntimeException("Method not supported: " + type); } addHeaders(req, request.getHeaders()); if (request.getBody() != null) { if (req instanceof HttpEntityEnclosingRequestBase == false) { throw new RuntimeException("Request type does not support body: " + type); } ((HttpEntityEnclosingRequestBase) req).setEntity(new InputStreamEntity(request.getBody())); } HttpResponse res = getHttpClient().execute(req); InputStream responseStream = null; if (res.getEntity() != null) { responseStream = res.getEntity().getContent(); } else { responseStream = new InputStream() { @Override public int read () throws IOException { return -1; } }; } Headers headers = new Headers(); HeaderIterator it = res.headerIterator(); while (it.hasNext()) { org.apache.http.Header header = it.nextHeader(); headers.add(header.getName(), header.getValue()); } return new HeadersBodyStatus(res.getStatusLine().toString(), headers, responseStream); } private static void addHeaders(HttpRequestBase request, Headers headers) { for (Header header: headers) { request.setHeader(header.getName(), header.getValue()); } } private static InputStream doPostOrPut(String contentType, String acceptType, String content, String authorization, HttpEntityEnclosingRequestBase request) throws IOException { request.setHeader(HttpHeaders.CONTENT_TYPE, contentType); request.setHeader(HttpHeaders.ACCEPT, acceptType); if (content != null) { request.setEntity(new StringEntity(content)); } return doRequest(authorization, request); } private static InputStream doRequest(String authorization, HttpRequestBase request) throws IOException { addAuth(request, authorization); HttpResponse response = getHttpClient().execute(request); InputStream responseStream = null; if (response.getEntity() != null) { responseStream = response.getEntity().getContent(); } int code = response.getStatusLine().getStatusCode(); if (code >= 200 && code < 300) { return responseStream; } else { Map<String, String> error = null; try { org.apache.http.Header header = response.getEntity().getContentType(); if (header != null && APPLICATION_JSON.equals(header.getValue())) { error = JsonSerialization.readValue(responseStream, Map.class); } } catch (Exception e) { throw new RuntimeException("Failed to read error response - " + e.getMessage(), e); } finally { responseStream.close(); } String message = null; if (error != null) { message = error.get("error_description") + " [" + error.get("error") + "]"; } throw new RuntimeException(message != null ? message : response.getStatusLine().getStatusCode() + " " + response.getStatusLine().getReasonPhrase()); } } private static void addAuth(HttpRequestBase request, String authorization) { if (authorization != null) { request.setHeader(HttpHeaders.AUTHORIZATION, authorization); } } public static HttpClient getHttpClient() { if (httpClient == null) { if (sslsf != null) { httpClient = HttpClientBuilder.create().useSystemProperties().setSSLSocketFactory(sslsf).build(); } else { httpClient = HttpClientBuilder.create().useSystemProperties().build(); } } return httpClient; } public static String urlencode(String value) { try { return URLEncoder.encode(value, UTF_8); } catch (UnsupportedEncodingException e) { throw new RuntimeException("Failed to urlencode", e); } } public static void setTruststore(File file, String password) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException { if (!file.isFile()) { throw new RuntimeException("Truststore file not found: " + file.getAbsolutePath()); } SSLContext theContext = SSLContexts.custom() .useProtocol("TLS") .loadTrustMaterial(file, password == null ? null : password.toCharArray()) .build(); sslsf = new SSLConnectionSocketFactory(theContext); } public static String extractIdFromLocation(String location) { int last = location.lastIndexOf("/"); if (last != -1) { return location.substring(last + 1); } return null; } public static String addQueryParamsToUri(String uri, String ... queryParams) { if (queryParams == null) { return uri; } if (queryParams.length % 2 != 0) { throw new RuntimeException("Value missing for query parameter: " + queryParams[queryParams.length-1]); } Map<String, String> params = new LinkedHashMap<>(); for (int i = 0; i < queryParams.length; i += 2) { params.put(queryParams[i], queryParams[i+1]); } return addQueryParamsToUri(uri, params); } public static String addQueryParamsToUri(String uri, Map<String, String> queryParams) { if (queryParams.size() == 0) { return uri; } StringBuilder query = new StringBuilder(); for (Map.Entry<String, String> params: queryParams.entrySet()) { try { if (query.length() > 0) { query.append("&"); } query.append(params.getKey()).append("=").append(URLEncoder.encode(params.getValue(), "utf-8")); } catch (Exception e) { throw new RuntimeException("Failed to encode query params: " + params.getKey() + "=" + params.getValue()); } } return uri + (uri.indexOf("?") == -1 ? "?" : "&") + query; } public static String composeResourceUrl(String adminRoot, String realm, String uri) { if (!uri.startsWith("http:") && !uri.startsWith("https:")) { if ("realms".equals(uri) || uri.startsWith("realms/")) { uri = normalize(adminRoot) + uri; } else if ("serverinfo".equals(uri)) { uri = normalize(adminRoot) + uri; } else { uri = normalize(adminRoot) + "realms/" + realm + "/" + uri; } } return uri; } public static String normalize(String value) { return value.endsWith("/") ? value : value + "/"; } public static void checkSuccess(String url, HeadersBodyStatus response) { try { response.checkSuccess(); } catch (HttpResponseException e) { if (e.getStatusCode() == 404) { throw new RuntimeException("Resource not found for url: " + url, e); } throw e; } } public static <T> T doGetJSON(Class<T> type, String resourceUrl, String auth) { Headers headers = new Headers(); if (auth != null) { headers.add("Authorization", auth); } headers.add("Accept", "application/json"); HeadersBodyStatus response; try { response = HttpUtil.doRequest("get", resourceUrl, new HeadersBody(headers)); } catch (IOException e) { throw new RuntimeException("HTTP request failed: GET " + resourceUrl, e); } checkSuccess(resourceUrl, response); T result; try { result = JsonSerialization.readValue(response.getBody(), type); } catch (IOException e) { throw new RuntimeException("Failed to read JSON response", e); } return result; } public static void doPostJSON(String resourceUrl, String auth, Object content) { Headers headers = new Headers(); if (auth != null) { headers.add("Authorization", auth); } headers.add("Content-Type", "application/json"); HeadersBodyStatus response; byte[] body; try { body = JsonSerialization.writeValueAsBytes(content); } catch (IOException e) { throw new RuntimeException("Failed to serialize JSON", e); } try { response = HttpUtil.doRequest("post", resourceUrl, new HeadersBody(headers, new ByteArrayInputStream(body))); } catch (IOException e) { throw new RuntimeException("HTTP request failed: POST " + resourceUrl + "\n" + new String(body), e); } checkSuccess(resourceUrl, response); } public static void doDeleteJSON(String resourceUrl, String auth, Object content) { Headers headers = new Headers(); if (auth != null) { headers.add("Authorization", auth); } headers.add("Content-Type", "application/json"); HeadersBodyStatus response; byte[] body; try { body = JsonSerialization.writeValueAsBytes(content); } catch (IOException e) { throw new RuntimeException("Failed to serialize JSON", e); } try { response = HttpUtil.doRequest("delete", resourceUrl, new HeadersBody(headers, new ByteArrayInputStream(body))); } catch (IOException e) { throw new RuntimeException("HTTP request failed: DELETE " + resourceUrl + "\n" + new String(body), e); } checkSuccess(resourceUrl, response); } public static String getIdForType(String rootUrl, String realm, String auth, String resourceEndpoint, String attrName, String attrValue) { return getAttrForType(rootUrl, realm, auth, resourceEndpoint, attrName, attrValue, "id"); } public static String getAttrForType(String rootUrl, String realm, String auth, String resourceEndpoint, String attrName, String attrValue, String returnAttrName) { String resourceUrl = composeResourceUrl(rootUrl, realm, resourceEndpoint); resourceUrl = HttpUtil.addQueryParamsToUri(resourceUrl, attrName, attrValue, "first", "0", "max", "2"); List<ObjectNode> users = doGetJSON(RoleOperations.LIST_OF_NODES.class, resourceUrl, auth); ObjectNode user; try { user = new LocalSearch(users).exactMatchOne(attrValue, attrName); } catch (Exception e) { throw new RuntimeException("Multiple " + resourceEndpoint + " found for " + attrName + ": " + attrValue, e); } String typeName = singularize(resourceEndpoint); if (user == null) { throw new RuntimeException(capitalize(typeName) + " not found for " + attrName + ": " + attrValue); } JsonNode attr = user.get(returnAttrName); if (attr == null) { throw new RuntimeException("Returned " + typeName + " info has no '" + returnAttrName + "' attribute"); } return attr.asText(); } public static String singularize(String value) { return value.substring(0, value.length()-1); } }
38.088496
180
0.625349
18d2fe9ca5cdfd9f85967b5a4288771e696b985c
241
// // ExtraUtilities decompiled and fixed by Robotia https://github.com/Robotia // package cofh.api.item; import net.minecraft.item.ItemStack; public interface IInventoryContainerItem { int getSizeInventory(final ItemStack p0); }
16.066667
76
0.763485
ba7288a29b99932e1b2faa02430139260c5723db
5,978
package com.yacl4j.core.util; import java.io.InputStream; import java.util.Iterator; import java.util.Map; import java.util.Optional; import yacl4j.repackaged.com.fasterxml.jackson.core.JsonFactory; import yacl4j.repackaged.com.fasterxml.jackson.core.JsonPointer; import yacl4j.repackaged.com.fasterxml.jackson.databind.DeserializationFeature; import yacl4j.repackaged.com.fasterxml.jackson.databind.JsonNode; import yacl4j.repackaged.com.fasterxml.jackson.databind.ObjectMapper; import yacl4j.repackaged.com.fasterxml.jackson.databind.node.ObjectNode; import yacl4j.repackaged.com.fasterxml.jackson.databind.node.TextNode; import yacl4j.repackaged.com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import yacl4j.repackaged.com.fasterxml.jackson.datatype.jdk8.Jdk8Module; import yacl4j.repackaged.com.fasterxml.jackson.module.mrbean.MrBeanModule; public class ConfigurationUtils { private ConfigurationUtils() { } private static ObjectMapper defaultObjectMapper() { return Yaml.YAML_OBJECT_MAPPER; } private static ObjectMapper buildObjectMapper(JsonFactory jsonFactory) { return new ObjectMapper(jsonFactory) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) .registerModule(new MrBeanModule()) .registerModule(new Jdk8Module()); } public static JsonNode emptyConfiguration() { return defaultObjectMapper().createObjectNode(); } public static JsonNode fromString(String configuration) { try { return defaultObjectMapper().readValue(configuration, JsonNode.class); } catch (Exception exception) { return TextNode.valueOf(configuration); } } public static <T> T toValue(JsonNode configuration, Class<T> configurationClass) { try { return defaultObjectMapper().treeToValue(configuration, configurationClass); } catch (Exception exception) { throw new IllegalStateException(exception); } } public static JsonNode merge(JsonNode mainNode, JsonNode updateNode) { Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); JsonNode jsonNode = mainNode.get(fieldName); if (jsonNode != null && jsonNode.isObject()) { merge(jsonNode, updateNode.get(fieldName)); } else { if (mainNode instanceof ObjectNode) { JsonNode value = updateNode.get(fieldName); ((ObjectNode) mainNode).set(fieldName, value); } } } return mainNode; } public static class Yaml { private Yaml() { } private static final ObjectMapper YAML_OBJECT_MAPPER = buildObjectMapper(new YAMLFactory()); public static JsonNode fromInputStream(InputStream configuration) { try { // we need to use this ugly syntax because ObjectMapper::readTree throws in case of empty files (https://github.com/FasterXML/jackson-databind/issues/1406) return Optional.<JsonNode> ofNullable(YAML_OBJECT_MAPPER.getFactory().createParser(configuration).readValueAsTree()) .orElseGet(ConfigurationUtils::emptyConfiguration); } catch (Exception exception) { throw new IllegalStateException(exception); } } public static JsonNode fromString(String configuration) { try { return (configuration.isEmpty()) ? emptyConfiguration() : YAML_OBJECT_MAPPER.readTree(configuration); } catch (Exception exception) { throw new IllegalStateException(exception); } } } public static class Json { private Json() { } private static final ObjectMapper JSON_OBJECT_MAPPER = buildObjectMapper(null); public static JsonNode fromInputStream(InputStream configuration) { try { // we need to use this ugly syntax because ObjectMapper::readTree throws in case of empty files (https://github.com/FasterXML/jackson-databind/issues/1406) return Optional.<JsonNode> ofNullable(JSON_OBJECT_MAPPER.getFactory().createParser(configuration).readValueAsTree()) .orElseGet(ConfigurationUtils::emptyConfiguration); } catch (Exception exception) { throw new IllegalStateException(exception); } } public static JsonNode fromString(String configuration) { try { return (configuration.isEmpty()) ? emptyConfiguration() : JSON_OBJECT_MAPPER.readTree(configuration); } catch (Exception exception) { throw new IllegalStateException(exception); } } } public static class Properties { private Properties() { } public static JsonNode fromInputStream(InputStream configuration) { return fromProperties(PropertiesUtils.fromInputStream(configuration)); } public static JsonNode fromString(String configuration) { return fromProperties(PropertiesUtils.fromString(configuration)); } public static JsonNode fromMap(Map<String, String> map) { return fromProperties(PropertiesUtils.fromMap(map)); } public static JsonNode fromProperties(java.util.Properties properties) { ObjectNode configuration = (ObjectNode) ConfigurationUtils.emptyConfiguration(); for (String propertyKey : properties.stringPropertyNames()) { JsonPointer propertyKeyAsJsonPointer = JsonPointerUtils.fromProperty(propertyKey); addNode(configuration, propertyKeyAsJsonPointer, properties.getProperty(propertyKey)); } return configuration; } private static void addNode(ObjectNode root, JsonPointer keyAsJsonPointer, String valueAsString) { ObjectNode currentNode = root; for (JsonPointer head : JsonPointerUtils.heads(keyAsJsonPointer)) { JsonNode headAsJsonNode = root.at(head); if (headAsJsonNode.isMissingNode() || headAsJsonNode.isValueNode()) { currentNode = currentNode.putObject(head.last().getMatchingProperty()); } else { currentNode = (ObjectNode) headAsJsonNode; } } if (!currentNode.has(keyAsJsonPointer.last().getMatchingProperty())) { JsonNode propertyValueAsJsonNode = ConfigurationUtils.fromString(valueAsString); currentNode.set(keyAsJsonPointer.last().getMatchingProperty(), propertyValueAsJsonNode); } } } }
34.959064
159
0.758615
99243fc6832d84fe69cb00b1df82c1c1522aa51e
2,887
package org.nutz.lang.util; import static org.junit.Assert.*; import org.junit.Test; public class LinkedIntArrayTest { static LinkedIntArray LIA(int... es) { LinkedIntArray lia = new LinkedIntArray(2); for (int e : es) lia.push(e); return lia; } @Test public void test_re_push() { LinkedIntArray lia = new LinkedIntArray(); lia.push(5); lia.popLast(); lia.push(9); assertEquals(9, lia.last()); assertEquals(1, lia.size()); } @Test public void testPush() { LinkedIntArray lia = new LinkedIntArray(); assertEquals(0, lia.size()); lia.push(25).push(16); assertEquals(2, lia.size()); } @Test public void testPopFirst() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(3, lia.size()); assertEquals(23, lia.popFirst()); assertEquals(2, lia.size()); } @Test public void testPopLast() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(3, lia.size()); assertEquals(67, lia.popLast()); assertEquals(2, lia.size()); } @Test public void testFirst() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(3, lia.size()); assertEquals(23, lia.first()); assertEquals(3, lia.size()); } @Test public void testLast() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(3, lia.size()); assertEquals(67, lia.last()); assertEquals(3, lia.size()); } @Test public void testSet() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(3, lia.size()); lia.set(2, 80); assertEquals(80, lia.last()); lia.set(0, 20); assertEquals(20, lia.first()); lia.set(1, 60); assertEquals(60, lia.get(1)); assertEquals(3, lia.size()); } @Test public void testClear() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(3, lia.size()); lia.clear(); assertEquals(0, lia.size()); } @Test public void testGet() { LinkedIntArray lia = LIA(23, 45, 67); assertEquals(23, lia.get(0)); assertEquals(45, lia.get(1)); assertEquals(67, lia.get(2)); } @Test public void testIsEmpty() { LinkedIntArray lia = LIA(23, 45, 67); assertFalse(lia.isEmpty()); lia.clear(); assertTrue(lia.isEmpty()); } @Test public void testToArray() { LinkedIntArray lia = LIA(23, 45, 67); int[] arr = lia.toArray(); assertEquals(3, arr.length); assertEquals(23, arr[0]); assertEquals(45, arr[1]); assertEquals(67, arr[2]); } }
25.104348
52
0.519917
da5dce6606ba8c86c4ab93776688477c6d329aad
385
package com.zhuangxiaoyan.athena.coupon.dao; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.zhuangxiaoyan.athena.coupon.entity.SkuLadderEntity; import org.apache.ibatis.annotations.Mapper; /** * 商品阶梯价格 * * @author xjl * @email [email protected] * @date 2022-03-10 11:14:46 */ @Mapper public interface SkuLadderDao extends BaseMapper<SkuLadderEntity> { }
21.388889
67
0.776623
e7c510acd0eaf3c18357a4cd3fe5c559b6d75d89
11,472
package edu.villanova.ece.inv.activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import android.widget.ViewSwitcher; import com.breadtech.breadinterface.BIActivity; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; import java.text.SimpleDateFormat; import java.util.Date; import edu.villanova.ece.inv.R; import edu.villanova.ece.inv.manager.AuthManager; import edu.villanova.ece.inv.manager.DataManager; import edu.villanova.ece.inv.model.Asset; import edu.villanova.ece.inv.model.Inventory; import edu.villanova.ece.inv.model.Location; import edu.villanova.ece.inv.model.User; /** * Created by bk on 8/6/15. */ public class InvInfoActivity extends BIActivity implements DataManager.ModificationDelegate, AdapterView.OnItemSelectedListener { // // constants private static final String TAG = "InvInfoActivity"; private static final String DEFAULT_BUTTON_TEXT = "Select from list"; // // state private boolean editing; private boolean showingAssets; // // ui private ViewSwitcher who_switcher; private ViewSwitcher what_switcher; /* when is only a text view */ private ViewSwitcher where_switcher; private ViewSwitcher how_switcher; private TextView who_tv; private TextView what_tv; private TextView when_tv; private TextView where_tv; private TextView how_tv; private Spinner who_spinner; private EditText what_et; /* when is only a text view */ private Spinner where_spinner; private Spinner how_spinner; private SimpleDateFormat df; // // model Inventory inv; // // interface @Override public int tl_icon() { return this.editing ? R.drawable.ic_close_white_36dp : R.drawable.ic_keyboard_backspace_white_36dp; } @Override public String tm_label() { return this.editing ? this.inv == null ? "Add Inventory Record" : "Edit Inventory Record" : "Inventory Record"; } @Override public int tr_icon() { return AuthManager.checkAuth(AuthManager.EntityModifyWorld) || (AuthManager.userCanModifyEntity() && this.editing) ? this.editing ? R.drawable.ic_done_white_36dp : R.drawable.ic_edit_white_36dp : 0; } @Override public int bl_icon() { return AuthManager.userCanModifyEntityWorld() ? R.drawable.ic_delete_white_36dp : 0; } // // functionality @Override public void tl_clicked() { if (this.editing && this.inv != null) { this.setEditing(false); } else finish(); } @Override public void tr_clicked() { if (AuthManager.userCanModifyEntityWorld() || (AuthManager.userCanModifyEntity() && this.editing) ) if (this.editing) this.save(); else this.setEditing(true); } @Override public void bl_clicked() { if (AuthManager.userCanModifyEntityWorld()) new AlertDialog.Builder(this) .setIcon(R.drawable.ic_delete_white_36dp) .setTitle("Delete") .setMessage("Are you sure that you want to delete this inventory record?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { DataManager.sharedManager().rmInv(inv); } }) .setNegativeButton("No", null) .show(); } public void setEditing( boolean editing ) { this.editing = editing; who_switcher.showNext(); what_switcher.showNext(); where_switcher.showNext(); how_switcher.showNext(); this.update(); } @Override public void init() { super.init(); this.setContentView(R.layout.activity_inv_info); // initialize ui references who_spinner = (Spinner) findViewById(R.id.who_spinner); what_et = (EditText) findViewById(R.id.what_et); where_spinner = (Spinner) findViewById(R.id.where_spinner); how_spinner = (Spinner) findViewById(R.id.how_spinner); who_tv = (TextView) findViewById(R.id.who_tv); what_tv = (TextView) findViewById(R.id.what_tv); when_tv = (TextView) findViewById(R.id.when_tv); where_tv = (TextView) findViewById(R.id.where_tv); how_tv = (TextView) findViewById(R.id.how_tv); who_switcher = (ViewSwitcher) findViewById(R.id.who_switcher); what_switcher = (ViewSwitcher) findViewById(R.id.what_switcher); where_switcher = (ViewSwitcher) findViewById(R.id.where_switcher); how_switcher = (ViewSwitcher) findViewById(R.id.how_switcher); // initialize spinner data ArrayAdapter<User> who_arrayAdapter = new ArrayAdapter<User>(this, android.R.layout.simple_spinner_item, DataManager.sharedManager().getUsers()); ArrayAdapter<Location> where_arrayAdapter = new ArrayAdapter<Location>(this, android.R.layout.simple_spinner_item, DataManager.sharedManager().getLocations()); ArrayAdapter<String> how_arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Asset.Status.all); who_spinner.setAdapter(who_arrayAdapter); where_spinner.setAdapter(where_arrayAdapter); how_spinner.setAdapter(how_arrayAdapter); // set on click what_et.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator scanner = new IntentIntegrator(InvInfoActivity.this); scanner.initiateScan(); } }); df = new SimpleDateFormat("MM/dd/yyyy hh:mm"); } public void onActivityResult(int requestCode, int resultCode, Intent intent) { // // returning from the barcode scanner IntentResult scanner = IntentIntegrator.parseActivityResult(requestCode,resultCode,intent); if (scanner != null) { String ece_tag = scanner.getContents(); if (ece_tag == null || ece_tag.length() == 0) return; this.what_et.setText(ece_tag); this.setEditing(true); } } @Override public void start() { super.start(); // check if an item was specified Intent i = getIntent(); int id = i.getIntExtra("Inv", 0); // initialize ui fields if item exists if (id != 0) { this.inv = DataManager.sharedManager().getInv(id); } else { this.setEditing(true); } } public boolean checkFields() { // check user input String ece_tag = what_et.getText().toString(); Asset a = DataManager.sharedManager().getAsset(ece_tag); if (a == null) { new AlertDialog.Builder(this) .setIcon(R.drawable.abc_ic_clear_mtrl_alpha) .setTitle("Not Found") .setMessage("This asset was not found.") .setNegativeButton("OK", null) .show(); return false; } return true; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { } @Override public void onNothingSelected(AdapterView<?> parent) { } @Override public void update() { super.update(); if (this.inv != null) { DataManager dm = DataManager.sharedManager(); who_spinner.setSelection(dm.getUsers().indexOf(inv.getWho().getUid())); who_tv.setText(inv.getWho().toString()); what_et.setText(inv.getWhat().getTag_ece()); what_tv.setText(inv.getWhat().getTag_ece()); when_tv.setText(df.format(inv.getWhen())); where_spinner.setSelection(dm.getLocations().indexOf(inv.getWhere())); where_tv.setText(inv.getWhere().toString()); how_spinner.setSelection(Asset.Status.all.indexOf(inv.getHow().toString())); how_tv.setText(inv.getHow().toString()); } else { // // initialize add inv fields // who: the logged in user, when: now, how: available who_spinner.setSelection(DataManager.sharedManager().getUsers().indexOf(AuthManager.getUser())); when_tv.setText(df.format(new Date())); how_spinner.setSelection(1); // initialize what and where if the ecetag was supplied to the activity Intent i = getIntent(); String ece_tag = i.getStringExtra("Asset"); if (ece_tag != null) { Asset a = DataManager.sharedManager().getAsset(ece_tag); what_et.setText(ece_tag); where_spinner.setSelection( DataManager.sharedManager().getLocations().indexOf(a)); } } // disable the who spinner if the user does not have permission to modify all invs if (!AuthManager.checkAuth(AuthManager.EntityModifyWorld)) { who_spinner.setEnabled(false); } } public void showEditPrompt() { Toast t = Toast.makeText(this,"Click the top-right button to edit this Inventory Record",Toast.LENGTH_SHORT); t.show(); } private void save() { if (this.checkFields()) { try { // get ui fields User who = (User) who_spinner.getSelectedItem(); Asset what = DataManager.sharedManager().getAsset(what_et.getText().toString()); Date when = df.parse(when_tv.getText().toString()); Location where = (Location) where_spinner.getSelectedItem(); Asset.Status how = Asset.Status.valueOf((String) how_spinner.getSelectedItem()); // set the item Inventory y = this.inv != null ? this.inv : new Inventory(); y.setWho(who.getUid()); y.setWhat(what.getTag_ece()); y.setWhen(when.getTime() / 1000); y.setWhere(where.getId()); y.setHow(how); // post it to the datamanager DataManager.sharedManager().setModDelegate(this); DataManager.sharedManager().saveInv(y); } catch (Exception e) { e.printStackTrace(); } } } @Override public void saveSuccess(Object i) { this.inv = (Inventory)i; this.setEditing(false); } @Override public void deleteSuccess(String msg) { (Toast.makeText(this,msg,Toast.LENGTH_SHORT)).show(); finish(); } @Override public void saveFailure(int code, String reason) { Log.w(TAG, "An error occured while saving " + code + " " + reason); } }
33.348837
122
0.610007
a852ef0d0d4175cca26a7fcbd4df06528470563b
19,741
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * This generated bean class SchemaTypeMappingType * matches the schema element 'schemaTypeMappingType'. * The root bean class is BeanGraph * * =============================================================== * * Map between schema types and java types. * * =============================================================== * @Generated */ package org.netbeans.modules.schema2beansdev.beangraph; public class SchemaTypeMappingType implements org.netbeans.modules.schema2beansdev.beangraph.CommonBean { public static final String SCHEMA_TYPE_NAMESPACE = "SchemaTypeNamespace"; // NOI18N public static final String SCHEMA_TYPE_NAME = "SchemaTypeName"; // NOI18N public static final String JAVA_TYPE = "JavaType"; // NOI18N public static final String ROOT = "Root"; // NOI18N public static final String BEAN = "Bean"; // NOI18N public static final String CAN_BE_EMPTY = "CanBeEmpty"; // NOI18N private java.lang.String _SchemaTypeNamespace; private java.lang.String _SchemaTypeName; private java.lang.String _JavaType; private boolean _Root; private boolean _isSet_Root = false; private boolean _Bean; private boolean _isSet_Bean = false; private boolean _CanBeEmpty; private boolean _isSet_CanBeEmpty = false; private static final java.util.logging.Logger _logger = java.util.logging.Logger.getLogger("org.netbeans.modules.schema2beansdev.beangraph.SchemaTypeMappingType"); /** * Normal starting point constructor. */ public SchemaTypeMappingType() { _SchemaTypeName = ""; _JavaType = ""; } /** * Required parameters constructor */ public SchemaTypeMappingType(java.lang.String schemaTypeName, java.lang.String javaType) { _SchemaTypeName = schemaTypeName; _JavaType = javaType; } /** * Deep copy */ public SchemaTypeMappingType(org.netbeans.modules.schema2beansdev.beangraph.SchemaTypeMappingType source) { this(source, false); } /** * Deep copy * @param justData just copy the XML relevant data */ public SchemaTypeMappingType(org.netbeans.modules.schema2beansdev.beangraph.SchemaTypeMappingType source, boolean justData) { _SchemaTypeNamespace = source._SchemaTypeNamespace; _SchemaTypeName = source._SchemaTypeName; _JavaType = source._JavaType; _Root = source._Root; _isSet_Root = source._isSet_Root; _Bean = source._Bean; _isSet_Bean = source._isSet_Bean; _CanBeEmpty = source._CanBeEmpty; _isSet_CanBeEmpty = source._isSet_CanBeEmpty; } // This attribute is optional public void setSchemaTypeNamespace(java.lang.String value) { _SchemaTypeNamespace = value; } public java.lang.String getSchemaTypeNamespace() { return _SchemaTypeNamespace; } // This attribute is mandatory public void setSchemaTypeName(java.lang.String value) { _SchemaTypeName = value; } public java.lang.String getSchemaTypeName() { return _SchemaTypeName; } // This attribute is mandatory public void setJavaType(java.lang.String value) { _JavaType = value; } public java.lang.String getJavaType() { return _JavaType; } // This attribute is optional public void setRoot(boolean value) { _Root = value; _isSet_Root = true; } public boolean isRoot() { return _Root; } // This attribute is optional public void setBean(boolean value) { _Bean = value; _isSet_Bean = true; } public boolean isBean() { return _Bean; } // This attribute is optional public void setCanBeEmpty(boolean value) { _CanBeEmpty = value; _isSet_CanBeEmpty = true; } public boolean isCanBeEmpty() { return _CanBeEmpty; } public void writeNode(java.io.Writer out) throws java.io.IOException { String myName; myName = "schemaTypeMappingType"; writeNode(out, myName, ""); // NOI18N } public void writeNode(java.io.Writer out, String nodeName, String indent) throws java.io.IOException { writeNode(out, nodeName, null, indent, new java.util.HashMap()); } /** * It's not recommended to call this method directly. */ public void writeNode(java.io.Writer out, String nodeName, String namespace, String indent, java.util.Map namespaceMap) throws java.io.IOException { out.write(indent); out.write("<"); if (namespace != null) { out.write((String)namespaceMap.get(namespace)); out.write(":"); } out.write(nodeName); writeNodeAttributes(out, nodeName, namespace, indent, namespaceMap); out.write(">\n"); writeNodeChildren(out, nodeName, namespace, indent, namespaceMap); out.write(indent); out.write("</"); if (namespace != null) { out.write((String)namespaceMap.get(namespace)); out.write(":"); } out.write(nodeName); out.write(">\n"); } protected void writeNodeAttributes(java.io.Writer out, String nodeName, String namespace, String indent, java.util.Map namespaceMap) throws java.io.IOException { } protected void writeNodeChildren(java.io.Writer out, String nodeName, String namespace, String indent, java.util.Map namespaceMap) throws java.io.IOException { String nextIndent = indent + " "; if (_SchemaTypeNamespace != null) { out.write(nextIndent); out.write("<schema-type-namespace"); // NOI18N out.write(">"); // NOI18N org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.writeXML(out, _SchemaTypeNamespace, false); out.write("</schema-type-namespace>\n"); // NOI18N } if (_SchemaTypeName != null) { out.write(nextIndent); out.write("<schema-type-name"); // NOI18N out.write(">"); // NOI18N org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.writeXML(out, _SchemaTypeName, false); out.write("</schema-type-name>\n"); // NOI18N } if (_JavaType != null) { out.write(nextIndent); out.write("<java-type"); // NOI18N out.write(">"); // NOI18N org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.writeXML(out, _JavaType, false); out.write("</java-type>\n"); // NOI18N } if (_isSet_Root) { out.write(nextIndent); out.write("<root"); // NOI18N out.write(">"); // NOI18N out.write(_Root ? "true" : "false"); out.write("</root>\n"); // NOI18N } if (_isSet_Bean) { out.write(nextIndent); out.write("<bean"); // NOI18N out.write(">"); // NOI18N out.write(_Bean ? "true" : "false"); out.write("</bean>\n"); // NOI18N } if (_isSet_CanBeEmpty) { out.write(nextIndent); out.write("<can-be-empty"); // NOI18N out.write(">"); // NOI18N out.write(_CanBeEmpty ? "true" : "false"); out.write("</can-be-empty>\n"); // NOI18N } } public void readNode(org.w3c.dom.Node node) { readNode(node, new java.util.HashMap()); } public void readNode(org.w3c.dom.Node node, java.util.Map namespacePrefixes) { if (node.hasAttributes()) { org.w3c.dom.NamedNodeMap attrs = node.getAttributes(); org.w3c.dom.Attr attr; java.lang.String attrValue; boolean firstNamespaceDef = true; for (int attrNum = 0; attrNum < attrs.getLength(); ++attrNum) { attr = (org.w3c.dom.Attr) attrs.item(attrNum); String attrName = attr.getName(); if (attrName.startsWith("xmlns:")) { if (firstNamespaceDef) { firstNamespaceDef = false; // Dup prefix map, so as to not write over previous values, and to make it easy to clear out our entries. namespacePrefixes = new java.util.HashMap(namespacePrefixes); } String attrNSPrefix = attrName.substring(6, attrName.length()); namespacePrefixes.put(attrNSPrefix, attr.getValue()); } } readNodeAttributes(node, namespacePrefixes, attrs); } readNodeChildren(node, namespacePrefixes); } protected void readNodeAttributes(org.w3c.dom.Node node, java.util.Map namespacePrefixes, org.w3c.dom.NamedNodeMap attrs) { org.w3c.dom.Attr attr; java.lang.String attrValue; } protected void readNodeChildren(org.w3c.dom.Node node, java.util.Map namespacePrefixes) { org.w3c.dom.NodeList children = node.getChildNodes(); for (int i = 0, size = children.getLength(); i < size; ++i) { org.w3c.dom.Node childNode = children.item(i); if (!(childNode instanceof org.w3c.dom.Element)) { continue; } String childNodeName = (childNode.getLocalName() == null ? childNode.getNodeName().intern() : childNode.getLocalName().intern()); String childNodeValue = ""; if (childNode.getFirstChild() != null) { childNodeValue = childNode.getFirstChild().getNodeValue(); } boolean recognized = readNodeChild(childNode, childNodeName, childNodeValue, namespacePrefixes); if (!recognized) { if (childNode instanceof org.w3c.dom.Element) { _logger.info("Found extra unrecognized childNode '"+childNodeName+"'"); } } } } protected boolean readNodeChild(org.w3c.dom.Node childNode, String childNodeName, String childNodeValue, java.util.Map namespacePrefixes) { // assert childNodeName == childNodeName.intern() if ("schema-type-namespace".equals(childNodeName)) { _SchemaTypeNamespace = childNodeValue; } else if ("schema-type-name".equals(childNodeName)) { _SchemaTypeName = childNodeValue; } else if ("java-type".equals(childNodeName)) { _JavaType = childNodeValue; } else if ("root".equals(childNodeName)) { if (childNode.getFirstChild() == null) _Root = true; else _Root = ("true".equalsIgnoreCase(childNodeValue) || "1".equals(childNodeValue)); _isSet_Root = true; } else if ("bean".equals(childNodeName)) { if (childNode.getFirstChild() == null) _Bean = true; else _Bean = ("true".equalsIgnoreCase(childNodeValue) || "1".equals(childNodeValue)); _isSet_Bean = true; } else if ("can-be-empty".equals(childNodeName)) { if (childNode.getFirstChild() == null) _CanBeEmpty = true; else _CanBeEmpty = ("true".equalsIgnoreCase(childNodeValue) || "1".equals(childNodeValue)); _isSet_CanBeEmpty = true; } else { return false; } return true; } public void validate() throws org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.ValidateException { boolean restrictionFailure = false; boolean restrictionPassed = false; // Validating property schemaTypeNamespace // Validating property schemaTypeName if (getSchemaTypeName() == null) { throw new org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.ValidateException("getSchemaTypeName() == null", org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.ValidateException.FailureType.NULL_VALUE, "schemaTypeName", this); // NOI18N } // Validating property javaType if (getJavaType() == null) { throw new org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.ValidateException("getJavaType() == null", org.netbeans.modules.schema2beansdev.beangraph.BeanGraph.ValidateException.FailureType.NULL_VALUE, "javaType", this); // NOI18N } // Validating property root // Validating property bean // Validating property canBeEmpty } public void changePropertyByName(String name, Object value) { if (name == null) return; name = name.intern(); if ("schemaTypeNamespace".equals(name)) setSchemaTypeNamespace((java.lang.String)value); else if ("schemaTypeName".equals(name)) setSchemaTypeName((java.lang.String)value); else if ("javaType".equals(name)) setJavaType((java.lang.String)value); else if ("root".equals(name)) setRoot(((java.lang.Boolean)value).booleanValue()); else if ("bean".equals(name)) setBean(((java.lang.Boolean)value).booleanValue()); else if ("canBeEmpty".equals(name)) setCanBeEmpty(((java.lang.Boolean)value).booleanValue()); else throw new IllegalArgumentException(name+" is not a valid property name for SchemaTypeMappingType"); } public Object fetchPropertyByName(String name) { if ("schemaTypeNamespace".equals(name)) return getSchemaTypeNamespace(); if ("schemaTypeName".equals(name)) return getSchemaTypeName(); if ("javaType".equals(name)) return getJavaType(); if ("root".equals(name)) return (isRoot() ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE); if ("bean".equals(name)) return (isBean() ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE); if ("canBeEmpty".equals(name)) return (isCanBeEmpty() ? java.lang.Boolean.TRUE : java.lang.Boolean.FALSE); throw new IllegalArgumentException(name+" is not a valid property name for SchemaTypeMappingType"); } public String nameSelf() { return "SchemaTypeMappingType"; } public String nameChild(Object childObj) { return nameChild(childObj, false, false); } /** * @param childObj The child object to search for * @param returnSchemaName Whether or not the schema name should be returned or the property name * @return null if not found */ public String nameChild(Object childObj, boolean returnConstName, boolean returnSchemaName) { return nameChild(childObj, returnConstName, returnSchemaName, false); } /** * @param childObj The child object to search for * @param returnSchemaName Whether or not the schema name should be returned or the property name * @return null if not found */ public String nameChild(Object childObj, boolean returnConstName, boolean returnSchemaName, boolean returnXPathName) { if (childObj instanceof java.lang.Boolean) { java.lang.Boolean child = (java.lang.Boolean) childObj; if (((java.lang.Boolean)child).booleanValue() == _Root) { if (returnConstName) { return ROOT; } else if (returnSchemaName) { return "root"; } else if (returnXPathName) { return "root"; } else { return "Root"; } } if (((java.lang.Boolean)child).booleanValue() == _Bean) { if (returnConstName) { return BEAN; } else if (returnSchemaName) { return "bean"; } else if (returnXPathName) { return "bean"; } else { return "Bean"; } } if (((java.lang.Boolean)child).booleanValue() == _CanBeEmpty) { if (returnConstName) { return CAN_BE_EMPTY; } else if (returnSchemaName) { return "can-be-empty"; } else if (returnXPathName) { return "can-be-empty"; } else { return "CanBeEmpty"; } } } if (childObj instanceof java.lang.String) { java.lang.String child = (java.lang.String) childObj; if (child.equals(_SchemaTypeNamespace)) { if (returnConstName) { return SCHEMA_TYPE_NAMESPACE; } else if (returnSchemaName) { return "schema-type-namespace"; } else if (returnXPathName) { return "schema-type-namespace"; } else { return "SchemaTypeNamespace"; } } if (child.equals(_SchemaTypeName)) { if (returnConstName) { return SCHEMA_TYPE_NAME; } else if (returnSchemaName) { return "schema-type-name"; } else if (returnXPathName) { return "schema-type-name"; } else { return "SchemaTypeName"; } } if (child.equals(_JavaType)) { if (returnConstName) { return JAVA_TYPE; } else if (returnSchemaName) { return "java-type"; } else if (returnXPathName) { return "java-type"; } else { return "JavaType"; } } } return null; } /** * Return an array of all of the properties that are beans and are set. */ public org.netbeans.modules.schema2beansdev.beangraph.CommonBean[] childBeans(boolean recursive) { java.util.List children = new java.util.LinkedList(); childBeans(recursive, children); org.netbeans.modules.schema2beansdev.beangraph.CommonBean[] result = new org.netbeans.modules.schema2beansdev.beangraph.CommonBean[children.size()]; return (org.netbeans.modules.schema2beansdev.beangraph.CommonBean[]) children.toArray(result); } /** * Put all child beans into the beans list. */ public void childBeans(boolean recursive, java.util.List beans) { } public boolean equals(Object o) { return o instanceof org.netbeans.modules.schema2beansdev.beangraph.SchemaTypeMappingType && equals((org.netbeans.modules.schema2beansdev.beangraph.SchemaTypeMappingType) o); } public boolean equals(org.netbeans.modules.schema2beansdev.beangraph.SchemaTypeMappingType inst) { if (inst == this) { return true; } if (inst == null) { return false; } if (!(_SchemaTypeNamespace == null ? inst._SchemaTypeNamespace == null : _SchemaTypeNamespace.equals(inst._SchemaTypeNamespace))) { return false; } if (!(_SchemaTypeName == null ? inst._SchemaTypeName == null : _SchemaTypeName.equals(inst._SchemaTypeName))) { return false; } if (!(_JavaType == null ? inst._JavaType == null : _JavaType.equals(inst._JavaType))) { return false; } if (_isSet_Root != inst._isSet_Root) { return false; } if (_isSet_Root) { if (!(_Root == inst._Root)) { return false; } } if (_isSet_Bean != inst._isSet_Bean) { return false; } if (_isSet_Bean) { if (!(_Bean == inst._Bean)) { return false; } } if (_isSet_CanBeEmpty != inst._isSet_CanBeEmpty) { return false; } if (_isSet_CanBeEmpty) { if (!(_CanBeEmpty == inst._CanBeEmpty)) { return false; } } return true; } public int hashCode() { int result = 17; result = 37*result + (_SchemaTypeNamespace == null ? 0 : _SchemaTypeNamespace.hashCode()); result = 37*result + (_SchemaTypeName == null ? 0 : _SchemaTypeName.hashCode()); result = 37*result + (_JavaType == null ? 0 : _JavaType.hashCode()); result = 37*result + (_isSet_Root ? 0 : (_Root ? 0 : 1)); result = 37*result + (_isSet_Bean ? 0 : (_Bean ? 0 : 1)); result = 37*result + (_isSet_CanBeEmpty ? 0 : (_CanBeEmpty ? 0 : 1)); return result; } public String toString() { java.io.StringWriter sw = new java.io.StringWriter(); try { writeNode(sw); } catch (java.io.IOException e) { // How can we actually get an IOException on a StringWriter? throw new RuntimeException(e); } return sw.toString(); } } /* The following schema file has been used for generation: <?xml version="1.0" ?> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <xsd:element name="bean-graph"> <xsd:complexType> <xsd:sequence> <xsd:element name="schema-type-mapping" type="schemaTypeMappingType" minOccurs="0" maxOccurs="unbounded"/> </xsd:sequence> </xsd:complexType> </xsd:element> <xsd:complexType name="schemaTypeMappingType"> <xsd:annotation> <xsd:documentation> Map between schema types and java types. </xsd:documentation> </xsd:annotation> <xsd:sequence> <xsd:element name="schema-type-namespace" type="xsd:string" minOccurs="0"/> <xsd:element name="schema-type-name" type="xsd:string"> <xsd:annotation> <xsd:documentation> The schema type; for instance, "string" </xsd:documentation> </xsd:annotation> </xsd:element> <xsd:element name="java-type" type="xsd:string"> <xsd:annotation> <xsd:documentation> The java type; for instance, "java.lang.String", or "int" </xsd:documentation> </xsd:annotation> </xsd:element> <xsd:element name="root" type="xsd:boolean" minOccurs="0"/> <xsd:element name="bean" type="xsd:boolean" minOccurs="0"/> <xsd:element name="can-be-empty" type="xsd:boolean" minOccurs="0"/> </xsd:sequence> </xsd:complexType> </xsd:schema> */
32.522241
252
0.697634
8a02ec9376ee07bfc8f3c3b8b4b554aa6d65c062
355
package fracciones; /** * * @author José Javier Flores López */ public class Fracciones { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println(TraductorFraccion.fromString("cuarenta y ocho doceavos").numerador); // TODO code application logic here } }
19.722222
95
0.642254
b102c66a09376fc0436626984696489cb1787b8b
498
package com.tinkerpop.gremlin.structure.io; /** * Represents a low-level serialization class that can be used to map classes to serializers. These implementation * create instances of serializers from other libraries (e.g. creating a {@code Kryo} instance). * * @author Stephen Mallette (http://stephen.genoprime.com) */ public interface Mapper<T> { /** * Create a new instance of the internal object mapper that an implementation represents. */ public T createMapper(); }
33.2
115
0.726908
70dddb43f7832aeb25148dd433da91441dc82968
2,519
package org.bottombar.widget; import android.content.Context; import android.support.annotation.Nullable; import android.text.TextUtils; import android.util.AttributeSet; import android.view.LayoutInflater; import android.widget.RelativeLayout; import android.widget.TextView; import org.bottombar.R; /** * Created by macpro on 2017/12/18. */ public class Badge extends RelativeLayout { // Badge文字 private TextView badge_tv; private RelativeLayout layout; public Badge(Context context) { this(context, null); } public Badge(Context context, @Nullable AttributeSet attrs) { super(context, attrs); // 加载布局 LayoutInflater.from(context).inflate(R.layout.badge, this, true); this.badge_tv = findViewById(R.id.badge); this.layout = findViewById(R.id.layout_badge); this.layout.setVisibility(GONE); } // 设置Badge样式 public void setCircleStyle(CircleStyle style) { switch (style) { // 红底白字 case REDSOLID: this.layout.setBackgroundResource(R.drawable.notice1); this.badge_tv.setTextColor(getResources().getColor(R.color.badge_white)); break; // 白底红字+描边红 case WHITESOLID: this.layout.setBackgroundResource(R.drawable.notice2); this.badge_tv.setTextColor(getResources().getColor(R.color.badge_red)); break; } } // 设置提醒数字(int) public void setBadge_Num_ByInt(int num) { if (num == 0) { this.layout.setVisibility(GONE); } else if (num > 0 && num <= 99) { this.layout.setVisibility(VISIBLE); this.badge_tv.setText(String.valueOf(num)); } else if (num > 99) { this.layout.setVisibility(VISIBLE); this.badge_tv.setText(R.string.max_badge); } } // 设置提醒数字(String) public void setBadge_Num_ByString(String num) { if (TextUtils.isEmpty(num)) { this.layout.setVisibility(GONE); return; } if (Integer.parseInt(num) == 0) { this.layout.setVisibility(GONE); } else if (Integer.parseInt(num) > 0 && Integer.parseInt(num) <= 99) { this.layout.setVisibility(VISIBLE); this.badge_tv.setText(num); } else if (Integer.parseInt(num) > 99) { this.layout.setVisibility(VISIBLE); this.badge_tv.setText(R.string.max_badge); } } }
27.086022
89
0.60659
26bdce93d0d178f3760b7046bf489d97988bb6ac
2,080
package com.mygdx.game.client; import com.badlogic.gdx.ApplicationListener; import com.badlogic.gdx.backends.gwt.GwtApplication; import com.badlogic.gdx.backends.gwt.GwtApplicationConfiguration; import com.guy.WebSocketInterface; import com.mygdx.game.MyGdxGame; public class HtmlLauncher extends GwtApplication { // USE THIS CODE FOR A FIXED SIZE APPLICATION @Override public GwtApplicationConfiguration getConfig () { return new GwtApplicationConfiguration(480, 320); } // END CODE FOR FIXED SIZE APPLICATION // UNCOMMENT THIS CODE FOR A RESIZABLE APPLICATION // PADDING is to avoid scrolling in iframes, set to 20 if you have problems // private static final int PADDING = 0; // private GwtApplicationConfiguration cfg; // // @Override // public GwtApplicationConfiguration getConfig() { // int w = Window.getClientWidth() - PADDING; // int h = Window.getClientHeight() - PADDING; // cfg = new GwtApplicationConfiguration(w, h); // Window.enableScrolling(false); // Window.setMargin("0"); // Window.addResizeHandler(new ResizeListener()); // cfg.preferFlash = false; // return cfg; // } // // class ResizeListener implements ResizeHandler { // @Override // public void onResize(ResizeEvent event) { // int width = event.getWidth() - PADDING; // int height = event.getHeight() - PADDING; // getRootPanel().setWidth("" + width + "px"); // getRootPanel().setHeight("" + height + "px"); // getApplicationListener().resize(width, height); // Gdx.graphics.setWindowedMode(width, height); // } // } // END OF CODE FOR RESIZABLE APPLICATION @Override public ApplicationListener createApplicationListener () { return new MyGdxGame(new WebSocketInterface()); } }
40
83
0.600962
2bbaea7d460acace523b4e14b65e8dd8147af3f5
120
package a; public class Two { public static void main(String[] args) { One.epibrate(); One.denature(); } }
13.333333
42
0.616667
93c3b08a1508d26d4134e1e2c78a1ffb28953ac7
993
package osc.gobaby.octopus.controller.mv; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import osc.gobaby.octopus.service.admin.db.DbConnectUtils; import osc.gobaby.octopus.interceptor.DbConnectionInterceptor; import javax.servlet.http.HttpServletResponse; /** * Created by ShinHyun.Kang on 2018. 9. 9.. */ @Controller public class IndexViewController { private static final Logger LOG = Logger.getLogger(DbConnectionInterceptor.class); @RequestMapping(value = {"/", "/gate"}, method = RequestMethod.GET) public String indexView(HttpServletResponse response) { if (DbConnectUtils.isCreatedDbConnectMetaFile()) { try { response.sendRedirect("/user/login"); } catch (Exception e) { LOG.error(e); } } return "gate"; } }
31.03125
86
0.705942
5a6404e7ecd8dc53a92f93745c931748196ca9f0
332
package com.inti.service.interfaces; import java.util.List; import com.inti.entities.Fournisseur; public interface IFournisseurService { public List <Fournisseur> findAll(); public Fournisseur findOne(Long id_Fournisseur); public Fournisseur save(Fournisseur Fournisseur); public void delete (Long id_Fournisseur); }
18.444444
50
0.789157
b89f3424844e453a7e5cc9b5bff97fa712118c5e
2,143
/* * 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 framework; import static com.jogamp.opengl.GL.GL_FALSE; import static com.jogamp.opengl.GL.GL_TRUE; import com.jogamp.opengl.GL2ES2; import static com.jogamp.opengl.GL2ES2.GL_COMPILE_STATUS; import static com.jogamp.opengl.GL2ES2.GL_INFO_LOG_LENGTH; import static com.jogamp.opengl.GL2ES2.GL_LINK_STATUS; /** * * @author GBarbieri */ public class Compiler { public static boolean check(GL2ES2 gl2es2, int shaderName) { boolean success = true; { int[] result = {GL_FALSE}; gl2es2.glGetShaderiv(shaderName, GL_COMPILE_STATUS, result, 0); if (result[0] == GL_FALSE) { return false; } int[] infoLogLength = {0}; gl2es2.glGetShaderiv(shaderName, GL_INFO_LOG_LENGTH, infoLogLength, 0); if (infoLogLength[0] > 0) { byte[] infoLog = new byte[infoLogLength[0]]; gl2es2.glGetShaderInfoLog(shaderName, infoLogLength[0], null, 0, infoLog, 0); System.out.println(new String(infoLog)); } success = success && result[0] == GL_TRUE; } return success; } public static boolean checkProgram(GL2ES2 gl2, int programName) { if (programName == 0) { return false; } int[] result = {GL_FALSE}; gl2.glGetProgramiv(programName, GL_LINK_STATUS, result, 0); if (result[0] == GL_TRUE) { return true; } int[] infoLogLength = {0}; gl2.glGetProgramiv(programName, GL_INFO_LOG_LENGTH, infoLogLength, 0); if (infoLogLength[0] > 0) { byte[] buffer = new byte[infoLogLength[0]]; gl2.glGetProgramInfoLog(programName, infoLogLength[0], null, 0, buffer, 0); System.out.println(new String(buffer)); } return result[0] == GL_TRUE; } }
30.183099
94
0.591227
7fa016701938eb3554ac038a610bb6741c82a780
3,091
package com.znsio.e2e.tools; import com.context.SessionContext; import com.context.TestExecutionContext; import com.epam.reportportal.service.ReportPortal; import com.znsio.e2e.entities.TEST_CONTEXT; import io.appium.java_client.AppiumDriver; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.apache.log4j.Logger; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import java.io.File; import java.io.IOException; import java.util.Date; import static com.znsio.e2e.tools.Driver.WEB_DRIVER; public class ScreenShotManager { private static final Logger LOGGER = Logger.getLogger(ScreenShotManager.class.getName()); private final TestExecutionContext context; private final String directoryPath; private int counter; public ScreenShotManager () { context = SessionContext.getTestExecutionContext(Thread.currentThread().getId()); directoryPath = context.getTestStateAsString(TEST_CONTEXT.SCREENSHOT_DIRECTORY); counter = 0; File file = new File(directoryPath); file.getParentFile().mkdirs(); } public void takeScreenShot (String fileName) { Driver driver = (Driver) context.getTestState(TEST_CONTEXT.CURRENT_DRIVER); if (null != driver) { fileName = normaliseScenarioName(getPrefix() + "-" + fileName); File destinationFile = createScreenshotFile(directoryPath, fileName); LOGGER.info("The screenshot will be placed here : " + destinationFile.getAbsolutePath()); try { File screenshot = ((TakesScreenshot) driver.getInnerDriver()).getScreenshotAs(OutputType.FILE); LOGGER.info("Original screenshot : " + screenshot.getAbsolutePath()); FileUtils.copyFile(screenshot, destinationFile); LOGGER.info("The screenshot is available here : " + destinationFile.getAbsolutePath()); ReportPortal.emitLog(fileName, "DEBUG", new Date(), destinationFile); } catch (IOException | RuntimeException e) { LOGGER.info("ERROR: Unable to save or upload screenshot: '" + destinationFile.getAbsolutePath() + "' or upload screenshot to ReportPortal\n"); LOGGER.info(ExceptionUtils.getStackTrace(e)); } } else { LOGGER.info("Driver is not instantiated for this test"); } } private String normaliseScenarioName (String scenarioName) { return scenarioName.replaceAll("[`~ !@#$%^&*()\\-=+\\[\\]{}\\\\|;:'\",<.>/?]", "_") .replaceAll("__", "_") .replaceAll("__", "_"); } private int getPrefix () { return ++counter; } private File createScreenshotFile (String dirName, String fileName) { fileName = fileName.endsWith(".png") ? fileName : fileName + ".png"; return new File(System.getProperty("user.dir") + dirName + File.separator + fileName); } }
40.671053
158
0.663863
381870bda572d6cc73d8ea8c06dd0a3f4d436ab0
960
package sample; import akka.actor.AbstractLoggingActor; import akka.japi.pf.ReceiveBuilder; import javax.inject.Inject; import javax.inject.Named; import org.springframework.context.annotation.Scope; import sample.CountingActor.Count; import sample.CountingActor.Get; /** * An actor that can count using an injected CountingService. * * @note The scope here is prototype since we want to create a new actor * instance for use of this bean. */ @Named("CountingLambdaActor") @Scope("prototype") class CountingLambdaActor extends AbstractLoggingActor { @Inject private CountingService countingService; private int count = 0; public CountingLambdaActor() { receive(ReceiveBuilder. match(Count.class, c -> { count = countingService.increment(count); }). match(Get.class, g -> { sender().tell(count, self()); }). matchAny(o -> log().info("received unknown message: " + o)). build()); } }
24
72
0.704167
43a1e63a6e2c927f217820fa5448b6dff4113ed1
3,241
package com.taxisurfr.servlet; import java.io.IOException; import java.io.InputStream; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.googlecode.objectify.ObjectifyService; import com.taxisurfr.server.AgentManager; import com.taxisurfr.server.RouteServiceManager; import com.taxisurfr.server.entity.Agent; import com.taxisurfr.server.entity.ArugamImage; import com.taxisurfr.server.entity.Booking; import com.taxisurfr.server.entity.Route; import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.google.common.io.ByteStreams; import com.taxisurfr.server.BookingServiceManager; import com.taxisurfr.server.ContractorManager; import com.taxisurfr.server.ImageManager; import com.taxisurfr.server.RatingManager; import com.taxisurfr.server.entity.Contractor; import com.taxisurfr.server.entity.Rating; public class DatasetUploadServlet extends HttpServlet { public static final Logger log = Logger.getLogger(LoginServlet.class.getName()); private static final long serialVersionUID = 1L; ImageManager imageManager = new ImageManager(); BookingServiceManager bookingServiceManager = new BookingServiceManager(); RouteServiceManager routeServiceManager = new RouteServiceManager(); ContractorManager contractorManager = new ContractorManager(); AgentManager agentManager = new AgentManager(); RatingManager ratingManager = new RatingManager(); @Override public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { ObjectifyService.begin(); ServletFileUpload upload = new ServletFileUpload(); res.setContentType("text/plain"); FileItemIterator iterator = upload.getItemIterator(req); while (iterator.hasNext()) { FileItemStream item = iterator.next(); InputStream stream = item.openStream(); if (item.isFormField()) { log.warning("Got a form field: " + item.getFieldName()); } else { log.warning("Got an uploaded file: " + item.getFieldName() + ", name = " + item.getName()); String dataset = new String(ByteStreams.toByteArray(stream)); // // bookingServiceManager.importDataset(dataset, Booking.class); // ratingManager.importDataset(dataset, Rating.class); // imageManager.importDataset(dataset, ArugamImage.class); routeServiceManager.importDataset(dataset, Route.class); contractorManager.importDataset(dataset, Contractor.class); agentManager.importDataset(dataset, Agent.class); } } } catch (Exception ex) { throw new ServletException(ex); } } }
38.583333
84
0.682197
a7f640ab80d063e2a96640759714833ae309ad4b
2,061
package com.humanharvest.organz.commands.modify; import java.io.File; import java.io.IOException; import java.io.PrintStream; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import com.humanharvest.organz.Client; import com.humanharvest.organz.HistoryItem; import com.humanharvest.organz.state.ClientManager; import com.humanharvest.organz.state.State; import com.humanharvest.organz.utilities.serialisation.JSONFileWriter; import picocli.CommandLine.Command; /** * Command line to save the current information of the Clients onto a JSON file using the GSON API. */ @Command(name = "save", description = "Save clients to file", sortOptions = false) public class Save implements Runnable { private static final Logger LOGGER = Logger.getLogger(Save.class.getName()); private static final File FILE = new File("savefile.json"); private final ClientManager manager; private final PrintStream outputStream; public Save() { manager = State.getClientManager(); outputStream = System.out; } public Save(ClientManager manager) { this.manager = manager; outputStream = System.out; } @Override public void run() { List<Client> clients = manager.getClients(); if (clients.isEmpty()) { outputStream.println("No clients exist, nothing to save"); } else { try (JSONFileWriter<Client> clientWriter = new JSONFileWriter<>(FILE, Client.class)) { clientWriter.overwriteWith(clients); LOGGER.log(Level.INFO, String.format("Saved %s clients to file", clients.size())); HistoryItem historyItem = new HistoryItem("SAVE", String.format("The system's current state was saved to '%s'.", FILE.getName())); //TODO: State.getSession().addToSessionHistory(historyItem); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not save to file: " + FILE.getName(), e); } } } }
34.932203
104
0.672004
01acfde58bea88df9ab5de633a3f7fefae203402
5,797
package com.github.sormuras.beethoven.unit; import com.github.sormuras.beethoven.Compilation; import com.github.sormuras.beethoven.Listing; import com.github.sormuras.beethoven.Name; import com.github.sormuras.beethoven.Style; import java.net.URI; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.function.Supplier; import javax.lang.model.element.Modifier; import javax.tools.JavaFileObject; /** * Java compilation unit. * * <pre> * CompilationUnit: * [PackageDeclaration] {ImportDeclaration} {TypeDeclaration} * [ModuleDeclaration] * </pre> * * @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.3">JLS 7.3</a> */ public class CompilationUnit implements DeclarationContainer { public static CompilationUnit of(String packageName) { CompilationUnit unit = new CompilationUnit(); unit.setPackageName(packageName); return unit; } private List<TypeDeclaration> declarations = new ArrayList<>(); private ImportDeclarations importDeclarations = new ImportDeclarations(); private PackageDeclaration packageDeclaration = new PackageDeclaration(); private Map<Name, Style> nameStyleMap = Collections.emptyMap(); @Override public Listing apply(Listing listing) { listing.add(getPackageDeclaration()); listing.add(getImportDeclarations()); getDeclarations().forEach(declaration -> declaration.apply(listing)); return listing; } /** Compile and return {@link Class} instance. */ public Class<?> compile() throws ClassNotFoundException { ClassLoader loader = Compilation.compile(toJavaFileObject()); TypeDeclaration declaration = getEponymousDeclaration().orElseThrow(IllegalStateException::new); return loader.loadClass(getPackageDeclaration().resolve(declaration.getName())); } /** Compile and create new instance. */ public <T> T compile(Class<T> clazz, Object... args) { try { return clazz.cast(compile().getDeclaredConstructors()[0].newInstance(args)); } catch (Exception exception) { throw new AssertionError("compiling or instantiating failed", exception); } } /** Compile and create new instance. */ public <T> T compile(Class<T> clazz, Supplier<Class<?>[]> typesProvider, Object... args) { try { Class<? extends T> subClass = compile().asSubclass(clazz); return subClass.getConstructor(typesProvider.get()).newInstance(args); } catch (Exception exception) { throw new AssertionError("compiling or instantiating failed", exception); } } /** Compile and invoke "public static void main(String[] args)". */ public void launch(String... args) { try { Object[] arguments = {args}; compile().getMethod("main", String[].class).invoke(null, arguments); } catch (Exception cause) { throw new RuntimeException("launching " + this + " failed!", cause); } } @Override public <T extends TypeDeclaration> T declare(T declaration, String name, Modifier... modifiers) { DeclarationContainer.super.declare(declaration, name, modifiers); declaration.setEnclosingDeclaration(null); declaration.setCompilationUnit(this); return declaration; } @Override public List<TypeDeclaration> getDeclarations() { return declarations; } /** * @return file name defining type declaration * @see <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-7.html#jls-7.6-510">JLS * 7.6</a> */ public Optional<TypeDeclaration> getEponymousDeclaration() { List<TypeDeclaration> types = getDeclarations(); // trivial case: no type present if (types.isEmpty()) { return Optional.empty(); } // trivial case: only one type present TypeDeclaration declaration = types.get(0); // if multiple types are present, find first public one if (types.size() > 1) { return types.stream().filter(TypeDeclaration::isPublic).findFirst(); } return Optional.of(declaration); } public ImportDeclarations getImportDeclarations() { return importDeclarations; } public PackageDeclaration getPackageDeclaration() { return packageDeclaration; } public String getPackageName() { if (getPackageDeclaration().isUnnamed()) { return ""; } return getPackageDeclaration().getName().packageName(); } @Override public String list() { return list(new Listing(this::style)); } @Override public String list(String lineSeparator) { return list(new Listing(" ", lineSeparator, this::style)); } @Override public boolean isEmpty() { return getDeclarations().isEmpty() && getPackageDeclaration().isEmpty() && getImportDeclarations().isEmpty(); } public void setNameStyleMap(Map<Name, Style> map) { this.nameStyleMap = Objects.requireNonNull(map, "name-to-style map is null"); } public void setPackageName(String packageName) { List<String> names = Arrays.asList(Name.DOT.split(packageName)); getPackageDeclaration().setName(Name.name(names.size(), names)); } public Style style(Name name) { if (nameStyleMap != Collections.EMPTY_MAP) { return nameStyleMap.getOrDefault(name, Style.CANONICAL); } Style style = getImportDeclarations().style(name); if (style == Style.CANONICAL) { style = Style.auto(getPackageName(), name); } return style; } public URI toURI() { TypeDeclaration declaration = getEponymousDeclaration().orElseThrow(IllegalStateException::new); return getPackageDeclaration().toUri(declaration.getName() + ".java"); } public JavaFileObject toJavaFileObject() { return Compilation.source(toURI(), list()); } }
32.027624
100
0.706745
8ede7d1bfcb8250f4673d62717eb8bf0baed5aa4
612
package apiServer.controllers.Module1.JSONRequestSpec; public class FloorRequest { private Integer buildingId; private Integer storey; private String floorPlanURL; public FloorRequest(Integer buildingId, Integer storey, String floorPlanURL) { this.buildingId = buildingId; this.storey = storey; this.floorPlanURL = floorPlanURL; } public Integer getBuildingId() { return buildingId; } public Integer getStorey() { return storey; } public String getFloorPlanURL() { return floorPlanURL; } }
23.538462
83
0.647059
3590f2012f71b2dfc80937945127d05e36224950
1,453
package org.moebuff.magi.util; import org.apache.commons.codec.binary.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; /** * AES-128 * * @author MuTo */ public class AESAlg { public static final String ALGORITHM = "AES"; private static final SecretKeySpec KEY = kgen(ALGORITHM); //加密 public static String encrypt(String val) { try { Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.ENCRYPT_MODE, KEY); return Base64.encodeBase64String(c.doFinal(val.getBytes(Encoding.DEFAULT))); } catch (Exception e) { throw new RuntimeException(e); } } //解密 public static String decrypt(String val) { try { Cipher c = Cipher.getInstance(ALGORITHM); c.init(Cipher.DECRYPT_MODE, KEY); return new String(c.doFinal(Base64.decodeBase64(val)), Encoding.DEFAULT); } catch (Exception e) { throw new RuntimeException(e); } } //生成密封 private static SecretKeySpec kgen(String seed) { try { byte[] k = new byte[16],//key b = MD5Alg.encrypt32(seed).getBytes(Encoding.DEFAULT); for (int i = 0; i < k.length && i < b.length; i++) k[i] = b[i]; return new SecretKeySpec(k, ALGORITHM); } catch (Exception e) { throw new RuntimeException(e); } } }
27.942308
88
0.580179
dc038843baea6efe09a1e966086a39cf35378713
2,448
package com.ragas.serviceImpl; import java.util.concurrent.CopyOnWriteArrayList; import org.codehaus.jackson.map.ObjectMapper; import com.ragas.model.Model; import com.ragas.service.Service; public class ServiceImpl implements Service{ CopyOnWriteArrayList<Model> datas; // if we use arraylist then possibility of occurrence of concurrent modification exception so use CopyOnWriteArrayList Model data1,data2,data3,data4; String msg = null; ObjectMapper obj; public ServiceImpl() { datas = new CopyOnWriteArrayList<Model>(); data1 = new Model(101, "Sagar Bhardwaj", 987654321); data2 = new Model(102, "Deepak Thakur", 123456789); data3 = new Model(103, "Akshay Jaiswal", 999999999); datas.add(data1); datas.add(data2); datas.add(data3); } public String getData() { obj = new ObjectMapper(); //convert java object to json string try { msg = obj.writeValueAsString(datas); } catch (Exception e) { e.printStackTrace(); } return msg; } public String getDataById(int id) { int i = 0; while (i < datas.size()) { if (datas.get(i).getId() == id) { data4 = datas.get(i); break; } i++; } obj = new ObjectMapper(); try { msg = obj.writeValueAsString(data4); System.out.println(msg); } catch (Exception e) { e.printStackTrace(); } return msg; } public String delData(int id) { for (Model data : datas) { if (data.getId() == id) { System.out.println("inside if"); datas.remove(data); msg = "{ \"status\":true }"; break; } else msg = "{ \"status\":false }"; } return msg; } public String addData(Model m) { int flag=0; for(Model data: datas) { if(m.getId() == data.getId()) { msg = "{ \"status\":false }"; // data with same id already present flag=1; break; } } if(flag==0) { Model data4 =new Model(); data4.setContact(m.getContact()); data4.setId(m.getId()); data4.setName(m.getName()); datas.add(data4); msg = "{ \"status\":true }"; System.out.println(data4); } return msg; } public String updateData(Model m) { int flag=0; for(Model data: datas) { if(m.getId() == data.getId()) { datas.set(flag, m); } flag++; } if (flag>0) msg = "{ \"status\":true }"; else msg = "{ \"status\":false }"; return msg; } }
21.663717
120
0.593546
0dc24da8a07295015797cfa4aed0f5a5504b59df
929
package eu.okaeri.sdk.aicensor.model; import eu.okaeri.sdk.aicensor.error.AiCensorException; import kong.unirest.HttpResponse; import lombok.Data; import java.io.Serializable; import java.util.function.Consumer; @Data public class AiCensorError implements Serializable { public static final Consumer<HttpResponse<AiCensorError>> CONSUMER = response -> { AiCensorError error = (response.getBody() == null) ? new AiCensorError("UNKNOWN", response.getStatus() + " " + response.getStatusText()) : response.getBody(); String message = "Error handling request (" + error.type + " - " + error.message + ")"; throw new AiCensorException(error, message); }; private final String type; private final String message; public enum ErrorType { UNKNOWN, PARSE_ERROR, AUTHORIZATION_FAILED, ELEMENT_NOT_FOUND, INVALID_INPUT } }
29.03125
97
0.679225
26a7885a28864131bb29e521bae7d60e73bc9140
197
package com.github.tomokinakamaru.protocool.context; import com.github.javaparser.ast.CompilationUnit; import java.util.HashMap; public class AstBases extends HashMap<Object, CompilationUnit> {}
28.142857
65
0.832487
f88470e4565b2d655fbc1d8b8e7f5487f99a34c3
11,232
package org.sagebionetworks.repo.web.controller; import org.sagebionetworks.auth.DeprecatedUtils; import org.sagebionetworks.repo.model.AuthorizationConstants; import org.sagebionetworks.repo.model.auth.LoginResponse; import org.sagebionetworks.repo.model.auth.NewUser; import org.sagebionetworks.repo.model.auth.Session; import org.sagebionetworks.repo.model.auth.Username; import org.sagebionetworks.repo.model.principal.*; import org.sagebionetworks.repo.web.NotFoundException; import org.sagebionetworks.repo.web.UrlHelpers; import org.sagebionetworks.repo.web.rest.doc.ControllerInfo; import org.sagebionetworks.repo.web.service.ServiceProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; /** * A <a href="http://en.wikipedia.org/wiki/Principal_%28computer_security%29"> * Principal</a> in Synapse can be a User, Group, or a Team. This is a set of * services that provides the means to look-up principals by their various * attributes and also to test unique names such as USER_NAME, USER_EMAIL, or * TEAM_NAME are available for use. */ @Controller @ControllerInfo(displayName = "Principal Services", path = "repo/v1") @RequestMapping(UrlHelpers.REPO_PATH) public class PrincipalController extends BaseController { @Autowired ServiceProvider serviceProvider; /** * <p> * This call is used to determine if an alias is currently available. * </p> * <p>A session token is not required for this call.</p> * Each value of each <a * href="${org.sagebionetworks.repo.model.principal.AliasType}" * >AliasType</a> must have a unique string representation. While some * AliasTypes allow white-space and punctuation, only letters and numbers * contribute to the uniqueness of the alias. Also while an alias can have * both upper and lower case letters, the uniqueness test is * case-insensitive. Here are some examples: * <ul> * <li>'foo-bar', 'foo bar', and 'foo.bar' are all the same as 'foobar'</li> * <li>'FooBar' and 'FOOBAR' are the same as 'foobar'</li> * <li>'foo', 'foo1', and 'foo2' are each distinct</li> * </ul> * Note: This method will NOT reserve the passed alias. So it is possible * that an alias, could be available during a pre-check, but then consumed * before the caller has a chance to reserve it. * * @param check * The request should include both the type and alias. * @return */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { UrlHelpers.PRINCIPAL_AVAILABLE }, method = RequestMethod.POST) public @ResponseBody AliasCheckResponse checkAlias( @RequestBody AliasCheckRequest check) { return serviceProvider.getPrincipalService().checkAlias(check); } /** * This service starts the process of creating a new account by sending a 'validation email' message to the provided * email address. The email contains a link back to the application calling the service which the user follows to * complete the account creation process. * * @param user the first name, last name and email address for the user * @param portalEndpoint the beginning of the URL included in the email verification message. When concatenated with * a list of ampersand (&) separated request parameters, must become a well formed URL. The concatenated * string must be included with the <a href="${POST.account}">POST /account</a> request. */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { UrlHelpers.ACCOUNT_EMAIL_VALIDATION }, method = RequestMethod.POST) public void newAccountEmailValidation( @RequestBody NewUser user, @RequestParam(value = AuthorizationConstants.PORTAL_ENDPOINT_PARAM, required = true) String portalEndpoint ) { serviceProvider.getPrincipalService().newAccountEmailValidation(user, portalEndpoint); } /** * This service completes the email validation process for setting up a new account. The client must provide the * validation token which was sent by email. The request will be rejected if the validation token is missing or * invalid or if the requested user name is not available. After successful account creation the user is logged in * and a session token returned to the client. * * @param accountSetupInfo user's first name, last name, requested user name, password, and validation token * @return a session token, allowing the client to begin making authenticated requests * @throws NotFoundException */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { UrlHelpers.ACCOUNT }, method = RequestMethod.POST) @ResponseBody public Session createNewAccount( @RequestBody AccountSetupInfo accountSetupInfo) throws NotFoundException { LoginResponse response = serviceProvider.getPrincipalService().createNewAccount(accountSetupInfo); return DeprecatedUtils.createSession(response); } /** * This service starts the process of adding a new email address to an existing account by sending a 'validation * email' message to the provided email address. The email contains a link back to the application calling the * service which the user follows to complete the process * * @param id the ID of the user account to which the email address is to be added. Must match the ID of the user * making the request. * @param userId * @param email the email address to be added to the account * @param portalEndpoint the beginning of the URL included in the email verification message. When concatenated with * a list of ampersand (&) separated request parameters, must become a well formed URL. The concatenated * string must be included with the <a href="${POST.email}">POST /email</a> request. * @throws NotFoundException */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { UrlHelpers.ACCOUNT_ID_EMAIL_VALIDATION }, method = RequestMethod.POST) public void additionalEmailValidation( @PathVariable(value = UrlHelpers.ID_PATH_VARIABLE) String id, @RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @RequestBody Username email, @RequestParam(value = AuthorizationConstants.PORTAL_ENDPOINT_PARAM, required = true) String portalEndpoint ) throws NotFoundException { if (userId==null || !id.equals(userId.toString())) throw new IllegalArgumentException("user id in URL must match that of the authenticated user."); serviceProvider.getPrincipalService().additionalEmailValidation(userId, email, portalEndpoint); } /** * This service completes the email validation process for adding a new email address to an existing account. * The client must provide the validation token which was sent by email. The request * will be rejected if the validation token is missing or invalid, if the email * address is already used or if the user making the request is not the one who initiated * the email validation process. * * @param userId * @param setAsNotificationEmail if true then the newly added email address becomes the address * used by the system for sending messages to the user. * @param emailValidationSignedToken the validation token sent by email * @throws NotFoundException */ @ResponseStatus(HttpStatus.CREATED) @RequestMapping(value = { UrlHelpers.EMAIL }, method = RequestMethod.POST) public void addEmail( @RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @RequestParam(value = AuthorizationConstants.SET_AS_NOTIFICATION_EMAIL_PARM) Boolean setAsNotificationEmail, @RequestBody EmailValidationSignedToken emailValidationSignedToken ) throws NotFoundException { serviceProvider.getPrincipalService().addEmail(userId, emailValidationSignedToken, setAsNotificationEmail); } /** * This service removes an email address from an account. The request is rejected * if the email address is not currently owned by the user or if the email is * the <i>notification address</i> for the user. * * @param userId * @param email the email address to remove * @throws NotFoundException */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { UrlHelpers.EMAIL }, method = RequestMethod.DELETE) public void removeEmail( @RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @RequestParam(value = AuthorizationConstants.EMAIL_PARAM) String email ) throws NotFoundException { serviceProvider.getPrincipalService().removeEmail(userId, email); } /** * This service sets the email used for user notifications, i.e. when a Synapse message is * sent and if the user has elected to receive messages by email, then this is the email * address at which the user will receive the message. Note: The given email address * must already be established as being owned by the user. * * @param userId * @param email the email address to use for notifications * @throws NotFoundException */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { UrlHelpers.NOTIFICATION_EMAIL }, method = RequestMethod.PUT) public void setNotificationEmail( @RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId, @RequestBody Username email ) throws NotFoundException { serviceProvider.getPrincipalService().setNotificationEmail(userId, email.getEmail()); } /** * This service returns the email used for user notifications, i.e. when a Synapse message is * sent and if the user has elected to receive messages by email, then this is the email * address at which the user will receive the message. * * @param userId * @return the email address to use for notifications * @throws NotFoundException */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { UrlHelpers.NOTIFICATION_EMAIL }, method = RequestMethod.GET) public @ResponseBody Username getNotificationEmail( @RequestParam(value = AuthorizationConstants.USER_ID_PARAM) Long userId) throws NotFoundException { return serviceProvider.getPrincipalService().getNotificationEmail(userId); } /** * Lookup a principal ID using an alias and alias type. * * @param request * @throws NotFoundException * If the given alias is not assigned to a principal. */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { UrlHelpers.PRINCIPAL_ALIAS }, method = RequestMethod.POST) public @ResponseBody PrincipalAliasResponse getPrincipalAlias( @RequestBody PrincipalAliasRequest request) throws NotFoundException{ return serviceProvider.getPrincipalService().getPrincipalAlias(request); } }
48.623377
118
0.753917
51566fe19be830b5ff6b1273ae9e1e4b0c6abf19
4,039
/** * Copyright 2018 BlazeMeter Inc. * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.blaze.runner; import jetbrains.buildServer.serverSide.SBuild; import jetbrains.buildServer.serverSide.SBuildServer; import jetbrains.buildServer.serverSide.artifacts.BuildArtifact; import jetbrains.buildServer.web.openapi.PagePlaces; import jetbrains.buildServer.web.openapi.PluginDescriptor; import jetbrains.buildServer.web.openapi.ViewLogTab; import jetbrains.buildServer.web.reportTabs.ReportTabUtil; import org.apache.commons.io.IOUtils; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.servlet.http.HttpServletRequest; import java.io.BufferedReader; import java.io.FileDescriptor; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.HashMap; import java.util.Map; /** * Present BlazeMeter report tab in Build results */ public class BlazeReportTab extends ViewLogTab { private Logger logger = LoggerFactory.getLogger("com.blazemeter"); /** * Creates and registers tab for Build Results pages * * @param pagePlaces used to register the tab * @param server server object */ public BlazeReportTab(@NotNull PagePlaces pagePlaces, @NotNull SBuildServer server, @NotNull final PluginDescriptor pluginDescriptor) { super("BlazeMeter Report", "bzm", pagePlaces, server); setIncludeUrl(pluginDescriptor.getPluginResourcesPath("reportTab.jsp")); } @Override protected void fillModel(@NotNull Map<String, Object> model, @NotNull HttpServletRequest request, @NotNull SBuild build) { BuildArtifact artifact = ReportTabUtil.getArtifact(build, Constants.RUNNER_DISPLAY_NAME + "/" + Constants.BZM_REPORTS_FILE); if(artifact != null) { try { final Map<String, String> links = getReports(artifact.getInputStream()); if (!links.isEmpty()) { model.put("bzmReports", links); } else { model.put("bzmMsg", "There is no report for this build"); } } catch (IOException e) { logger.error("Failed to get the report: ", e); model.put("bzmMsg", "Failed to get the report: " + e.getMessage()); } } else { logger.info("No BlazeMeter artifacts for this build"); model.put("bzmMsg", "No BlazeMeter artifacts for this build"); } } private Map<String, String> getReports(InputStream inputStream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); final Map<String, String> links = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { String key = line; logger.debug("Get key: " + key); if ((line = reader.readLine()) != null) { logger.debug("Get address: " + line); links.put(key, line); } else { logger.warn("Key " + key + " has not url"); links.put(key, ""); } } return links; } @Override protected boolean isAvailable(@NotNull HttpServletRequest request, @NotNull SBuild build) { return super.isAvailable(request, build) && ReportTabUtil.isAvailable(build, Constants.RUNNER_DISPLAY_NAME + "/" + Constants.BZM_REPORTS_FILE); } }
39.213592
151
0.672939
fc370c6d55ba0e49902b6f4fcddef69471577b19
12,179
/* Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.devtools.build.wireless.testing.java.injector.coverage; import com.google.devtools.build.wireless.testing.java.injector.InclusionSelector; import org.objectweb.asm.ClassAdapter; import org.objectweb.asm.ClassVisitor; import org.objectweb.asm.Label; import org.objectweb.asm.MethodAdapter; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.util.regex.Pattern; /** * This class adapter injects coverage collection calls at the beginning of each * method invocation. Methods are mapped with an integer which represents the * position of a bit within a bitmask. At runtime the same integer value will * be used to collect the coverage data. * * @author Michele Sama * */ public class CodeCoverageClassAdapter extends ClassAdapter { /** * Defines the pattern of anonymous classes as defined in the JVM * specifications. It looks like "...ClassName$1.methodName(..." */ private final static Pattern ANONYMOUS_CLASS_PATTERN = Pattern.compile("\\$\\d+"); private final CoverageStatisticContainer statisticContainer; /** * Selects which classes to instrument for coverage. */ private final InclusionSelector inclusionSelector = new InclusionSelector(Boolean.FALSE); /** * Specify which level of coverage will be used for the instrumentation. */ private final CoverageMode coverageMode; private String owner; private boolean shouldInstrumentClass = true; private boolean isAutoGeneratedClass = false; private int classOpcode; private String filename; /** * File identifier obtained from the {@link CoverageStatisticContainer}. */ private int fileIndex; /** * Creates an instance which will use a specified Statistic container. * * @param cv the nested ClassVisitor. * @param container The specified container. */ public CodeCoverageClassAdapter(ClassVisitor cv, CoverageStatisticContainer container, String[] coverageInclusion, CoverageMode coverageMode) { super(cv); statisticContainer = container; if (coverageInclusion != null) { inclusionSelector.loadInclusionList(coverageInclusion); } this.coverageMode = coverageMode; } //TODO: make distinction between anonymous and generated classes. private boolean isGeneratedClass(String clazz) { if (clazz == null) { return false; } return ANONYMOUS_CLASS_PATTERN.matcher(clazz).find(); } /** * Selects which class to map for coverage. At runtime mapped methods of * mapped classes will have a position in the bitmask used for method * coverage. * * <p> If the current classname points to an interface it has to be skipped * because interfaces are not marked for coverage. * * <p> If the current class is synthetic it also has to be discarded because * synthetic classes do not correspond to any source class and they would * be a useless overhead. * * @return <code>true</code> if the class has to be mapped for coverage. */ protected boolean isIncluded() { if ((classOpcode & Opcodes.ACC_INTERFACE) > 0 || (classOpcode & Opcodes.ACC_SYNTHETIC) > 0 || isAutoGeneratedClass) { return false; } return shouldInstrumentClass; } /** * Adds the method into the {@link CoverageStatisticContainer} and obtains * the index which will be injected. That index is used to create a new * instance of the method adapter used to inject the coverage behavior. * * <p>Abstract methods must be skipped, because they do not contains code and * the JVM will execute only their overriding implementation. If a method is * abstract {@code opcode} contains {@link Opcodes#ACC_ABSTRACT}. * * @param opcode The type associated with the method. * @param desc the method's descriptor. * @param signature the method's signature. May be null if the method * parameters, return type and exceptions do not use generic types. * @param exceptions The internal names of the method's exception classes. * May be null. * @return The method visitor which must be used to process the method. */ @Override public MethodVisitor visitMethod(int opcode, String name, String desc, String signature, String[] exceptions) { MethodVisitor mv = cv.visitMethod(opcode, name, desc, signature, exceptions); if (isIncluded() && (opcode & Opcodes.ACC_ABSTRACT) == 0) { // TODO: idName should be an integer and not a string. String idName = owner + "." + name + desc; mv = new MethodCoverage(mv, statisticContainer.includeMethod(idName)); } return mv; } /** * Checks if the user requested the given class to be instrumented. */ boolean shouldInstrumentClass(String clazz) { return inclusionSelector.getMostSpecificAction(clazz); } /** * Visits a specific class and pass it to the statistic container. * * @param version The class version. * @param access the class's access flags. * This parameter also indicates if the class is deprecated. * @param name The class' name. * @param signature The signature of this class. May be null if the class is * not a generic one, and does not extend or implement generic classes * or interfaces. * @param superName The name of the super class. * @param interfaces The internal names of the class's interfaces. * May be null. */ @Override public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) { owner = name; classOpcode = access; shouldInstrumentClass = shouldInstrumentClass(owner); isAutoGeneratedClass = isGeneratedClass(owner); if (isIncluded()) { statisticContainer.includeClass(name); } cv.visit(version, access, name, signature, superName, interfaces); } /** * Visits a source file name and passes it to the statistic container. * * @param name The source file name. * @param debug Additional debug information to compute the correspondence * between source and compiled elements of the class. May be null. */ @Override public void visitSource(String name, String debug) { filename = owner.substring(0, owner.lastIndexOf('/') + 1) + name.substring(0, name.lastIndexOf(".java")); if (isIncluded()) { fileIndex = statisticContainer.includeFile(filename); } cv.visitSource(name, debug); } /** * For each method of each class which is going to be mapped for coverage this * {@link MethodAdapter} injects code that will record the line has been * executed at runtime. * * <p>If the Method is visited and * <code>coverageMode == CoverageMode.SUMMARY</code> * some code will be injected as shown below: * * <p><pre>public void foo() { * bar(); * }</pre> * into: * <pre>public void foo() { * CoverageManager.setCovered(m); * bar(); * }</pre> * * <p>where <code>m</code> is {@link #methodIndex}, the unique index for * this method. * * <p>If the Method is visited and * <code>coverageMode == CoverageMode.LINE</code> * some code will be injected as shown below: * * <p><pre>public void foo() { * bar(); * bar(); * }</pre> * into: * <pre>public void foo() { * CoverageManager.setLineCovered(c,l); * bar(); * CoverageManager.setLineCovered(c,l); * bar(); * }</pre> * * <p>where <code>c</code> and <code>l</code> are the classId and the lineId * used to map the lines. * * <p> Please note that injected methods or methods from external libraries * which do not provide line numbers will be skipped from line coverage. * * @author Michele Sama */ protected class MethodCoverage extends MethodAdapter { /** * The index to use when flagging the method. This represent the position * in the bitmask which will be used at runtime. */ private int methodIndex = -1; /** * Creates an instance with a fixed index. * * <p>That index is going to be the method position in the bitmask which at * runtime will be used to mark the method as covered. * * @param mv The nested MethodVisitor. * @param index The position of the index in the bitmask. This is a unique * descriptive String which is identifying the method. * * TODO: this should be an incremental integer to minimize memory on * the client. */ public MethodCoverage(MethodVisitor mv, int index) { super(mv); if (filename == null) { throw new IllegalStateException("Filename is null in class: " + owner + ". /nYou are trying to instrument code which was not compiled " + "in debug mode. Please exclude it from the coverage inclusion, " + "or recompile it with debugging enabled."); } methodIndex = index; } /** * Visits each method invocation and as a first instruction inject a call to * flag the method as covered. */ @Override public void visitCode() { if (coverageMode == CoverageMode.SUMMARY) { mv.visitIntInsn(Opcodes.SIPUSH, methodIndex); mv.visitMethodInsn(Opcodes.INVOKESTATIC, CoverageClassNames.COVERAGE_MANAGER, "setCovered", "(I)V"); } mv.visitCode(); /* TODO: increase the count for profiling and start counting the * time but in a different method visitor. */ } /** * Instruments the code by marking as covered the line identified by the * indexes of the current class and of the current line. The following code * is added by the instrumentor: * * <p><code> * CoverageManager.setLineCovered(int fileIndex, int lineIndex) * </code> * * <p>Note that the line is flagged as instrumented when the line number * is visited. If in the compiled code the line number is inserted before * the instructions then the line is flagged as covered also if it throws * an exception (which is the correct behavior). If a compile puts the line * information after the execution then lines throwing exceptions will * not be covered. */ @Override public void visitLineNumber(int value, Label label) { if (coverageMode == CoverageMode.LINE) { // Use the same key for all the classes of the same java file. When we // display the coverage information, the line numbers are relative to // the java file, not the class files. try { int lineIndex = statisticContainer.addInstrumentedLineAndGetLineIndex(filename, value); // Call LineCoverage.setLineCovered(int fileIndex, int lineIndex). mv.visitIntInsn(Opcodes.SIPUSH, fileIndex); mv.visitIntInsn(Opcodes.SIPUSH, lineIndex); mv.visitMethodInsn(Opcodes.INVOKESTATIC, CoverageClassNames.COVERAGE_MANAGER, "setLineCovered", "(II)V"); //lineNumberInClass++; } catch(Exception e) { /* * The line containing a for loop compiled with the OpenJDK 1.6 * appears twice in the bytecode, when the condition is checked and * when the counter is incremented. Code compiled like that raises * this exception for each for loop. */ } } mv.visitLineNumber(value, label); } } }
35.611111
97
0.671566
f246151259261eafa181f991194ed7b06bdd881a
1,003
package co.mitoo.sashimi.services; import android.os.Handler; import co.mitoo.sashimi.network.DataPersistanceService; import co.mitoo.sashimi.network.ServiceBuilder; import co.mitoo.sashimi.network.SteakApi; import co.mitoo.sashimi.utils.BusProvider; import co.mitoo.sashimi.utils.MitooConstants; import co.mitoo.sashimi.views.activities.MitooActivity; import rx.Observable; import rx.Subscriber; /** * Created by david on 15-04-23. */ public abstract class BaseService { private SteakApi steakApiService; public BaseService() { BusProvider.register(this); } public SteakApi getSteakApiService() { if (steakApiService == null) steakApiService = ServiceBuilder.getSingleTonInstance().getSteakApiService(); return steakApiService; } public void setSteakApiService(SteakApi steakApiService) { this.steakApiService = steakApiService; } protected void removeReferences() { BusProvider.unregister(this); } }
23.880952
89
0.734796
46142067bb6cee787d9176c4c0f24fff2d148c14
559
package com.github.adelinor.messaging.mapper; /** * Similar to the JPA AttributeConverter, this defines * a strategy for converting a header value to an object * property value. * * @author Adelino Rodrigues (created by) * @since 5 Mar 2019 (creation date) */ public interface HeaderConverter<X, Y> { /** * @param value Header value * @return Converted value to assign to object */ Y convertToHeaderValue(X value); /** * @param value Object value * @return Converted value to assign to header */ X convertToObjectValue(Y value); }
22.36
56
0.708408
49659008ce1e9ff13fce533abe22c809528626bc
1,573
package piapro.github.io.instax.view.fliter_lib; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.ColorMatrix; import android.graphics.ColorMatrixColorFilter; import android.graphics.Paint; import android.util.AttributeSet; import android.widget.ImageView; import piapro.github.io.instax.R; public class ColorView extends ImageView { private Paint myPaint = null; private Bitmap bitmap = null; private ColorMatrix myColorMatrix = null; private float[] colorArray = { 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0,}; public ColorView(Context context, AttributeSet attrs) { super(context, attrs); bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher); invalidate(); } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); myPaint = new Paint(); canvas.drawBitmap(bitmap, 0, 0, myPaint); myColorMatrix = new ColorMatrix(); myColorMatrix.set(colorArray); myPaint.setColorFilter(new ColorMatrixColorFilter(myColorMatrix)); canvas.drawBitmap(bitmap, 0, 0, myPaint); invalidate(); } public void setColorArray(float[] colorArray) { this.colorArray = colorArray; } public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; } public Bitmap getBitmap() { return bitmap; } }
24.578125
92
0.661157
1080ab8cf1e29b82475f29af415f7c9bb3bf06ee
634
package com.sxu.commonbusiness.login.bean; import java.io.Serializable; /******************************************************************************* * Description: 微信用户的信息 * * Author: Freeman * * Date: 2018/8/31 *******************************************************************************/ public class WXUserInfoBean implements Serializable { /** * 性别:1表示男性,2表示女性 */ public int sex; /** * 用户统一标识,针对一个微信开放平台帐号下的应用,同一用户的unionid是唯一的。 */ public String unionid; public String openid; public String nickname; public String city; public String province; public String country; public String headimgurl; }
21.133333
81
0.544164
4410dad1dda85f3a6472f638b8b9b734ce66a986
6,406
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ package com.sun.star.wizards.db; import java.util.Vector; import com.sun.star.sdbc.SQLException; import com.sun.star.sdbc.XResultSet; import com.sun.star.sdbc.XRow; import com.sun.star.uno.UnoRuntime; import com.sun.star.wizards.common.JavaTools; import com.sun.star.wizards.common.PropertyNames; /** * @author bc93774 * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class RelationController extends CommandName { private int PKTABLE_CAT = 1; private int PKTABLE_SCHEM = 2; private int PKTABLE_NAME = 3; private int PKCOLUMN_NAME = 4; private int FKTABLE_CAT = 5; private int FKTABLE_SCHEM = 6; private int FKTABLE_NAME = 7; private int FKCOLUMN_NAME = 8; public RelationController(CommandMetaData _CommandMetaData, String _CatalogName, String _SchemaName, String _TableName, boolean _baddQuotation) { super(_CommandMetaData, _CatalogName, _SchemaName, _TableName, _baddQuotation); } public RelationController(CommandMetaData _CommandMetaData, String _DisplayName) { super(_CommandMetaData, _DisplayName); } public String[] getExportedKeys() { String[] sReferencedTableNames = new String[] { }; try { String[] sTableNames = super.getCommandMetaData().getTableNames(); Vector aReferencedTableVector = new Vector(); XResultSet xResultSet = super.getCommandMetaData().xDBMetaData.getExportedKeys((getCatalogName(this)), getSchemaName(), getTableName()); XRow xRow = UnoRuntime.queryInterface(XRow.class, xResultSet); while (xResultSet.next()) { String sForeignCatalog = xRow.getString(FKTABLE_CAT); String sForeignScheme = xRow.getString(FKTABLE_SCHEM); String sForeignTableName = xRow.getString(FKTABLE_NAME); CommandName oCommandName = new CommandName(getCommandMetaData(), sForeignCatalog, sForeignScheme, sForeignTableName, false); aReferencedTableVector.add(oCommandName.getComposedName()); } sReferencedTableNames = new String[aReferencedTableVector.size()]; aReferencedTableVector.toArray(sReferencedTableNames); } catch (SQLException e) { e.printStackTrace(System.out); } return sReferencedTableNames; } private Object getCatalogName(CommandName _oCommandName) { String sLocCatalog = _oCommandName.getCatalogName(); if (sLocCatalog.equals(PropertyNames.EMPTY_STRING)) { return null; } else { return sLocCatalog; } } public String[][] getImportedKeyColumns(String _sreferencedtablename) { String[][] sKeyColumnNames = new String[][] { }; try { CommandName oLocCommandName = new CommandName(super.getCommandMetaData(), _sreferencedtablename); XResultSet xResultSet = super.getCommandMetaData().xDBMetaData.getImportedKeys(getCatalogName(oLocCommandName), oLocCommandName.getSchemaName(), oLocCommandName.getTableName()); XRow xRow = UnoRuntime.queryInterface(XRow.class, xResultSet); boolean bleaveLoop = false; Vector aMasterFieldNamesVector = new Vector(); Vector aSlaveFieldNamesVector = new Vector(); while (xResultSet.next() && !bleaveLoop) { String sPrimaryCatalog = null; String sPrimarySchema = null; if (super.getCommandMetaData().xDBMetaData.supportsCatalogsInDataManipulation()) { sPrimaryCatalog = xRow.getString(PKTABLE_CAT); } if (super.getCommandMetaData().xDBMetaData.supportsSchemasInDataManipulation()) { sPrimarySchema = xRow.getString(PKTABLE_SCHEM); } String sPrimaryTableName = xRow.getString(PKTABLE_NAME); String sPrimaryColumnName = xRow.getString(PKCOLUMN_NAME); String sForeignColumnName = xRow.getString(FKCOLUMN_NAME); if (JavaTools.isSame(getTableName(), sPrimaryTableName)) { if (sPrimarySchema == null || JavaTools.isSame(getSchemaName(), sPrimarySchema)) { if (JavaTools.isSame(getCatalogName(), sPrimaryCatalog)) { aSlaveFieldNamesVector.add(sForeignColumnName); aMasterFieldNamesVector.add(sPrimaryColumnName); bleaveLoop = true; //Only one relation may exist between two tables... } } } } sKeyColumnNames = new String[2][aMasterFieldNamesVector.size()]; sKeyColumnNames[0] = new String[aSlaveFieldNamesVector.size()]; sKeyColumnNames[1] = new String[aMasterFieldNamesVector.size()]; aSlaveFieldNamesVector.toArray(sKeyColumnNames[0]); aMasterFieldNamesVector.toArray(sKeyColumnNames[1]); } catch (Exception e) { e.printStackTrace(System.out); } return sKeyColumnNames; } }
40.289308
189
0.62379
4f17102c078b23221de04472d6695fdb6bf388ec
129
package org.ovirt.engine.extensions.aaa.builtin.kerberosldap.utils.kerberos; public enum LdapModeEnum { LOCAL, REMOTE }
18.428571
76
0.767442
1ad07abf717ada29bbe7393f49074ed3f15471ec
9,073
package ca.bc.gov.open.jag.efilingaccountclient; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RegisteredRole; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.RoleRegistryPortType; import brooks.roleregistry_source_roleregistry_ws_provider.roleregistry.UserRoles; import ca.bc.gov.ag.csows.accounts.*; import ca.bc.gov.open.jag.efilingaccountclient.mappers.AccountDetailsMapper; import ca.bc.gov.open.jag.efilingcommons.exceptions.CSOHasMultipleAccountException; import ca.bc.gov.open.jag.efilingcommons.exceptions.EfilingAccountServiceException; import ca.bc.gov.open.jag.efilingcommons.model.AccountDetails; import ca.bc.gov.open.jag.efilingcommons.model.CreateAccountRequest; import ca.bc.gov.open.jag.efilingcommons.service.EfilingAccountService; import ca.bceid.webservices.client.v9.*; import org.apache.commons.lang3.StringUtils; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.ws.WebServiceException; import java.util.*; public class CsoAccountServiceImpl implements EfilingAccountService { private final AccountFacadeBean accountFacadeBean; private final RoleRegistryPortType roleRegistryPortType; private final BCeIDServiceSoap bCeIDServiceSoap; private final AccountDetailsMapper accountDetailsMapper; private static final Map<String, BCeIDAccountTypeCode> accountTypeLookup; static { Map<String, BCeIDAccountTypeCode> tempMap = new HashMap<String, BCeIDAccountTypeCode>(); tempMap.put("business", BCeIDAccountTypeCode.BUSINESS); tempMap.put("individual", BCeIDAccountTypeCode.INDIVIDUAL); tempMap.put("verified individual", BCeIDAccountTypeCode.VERIFIED_INDIVIDUAL); tempMap.put("eds", BCeIDAccountTypeCode.EDS); tempMap.put("internal", BCeIDAccountTypeCode.INTERNAL); tempMap.put("ldb", BCeIDAccountTypeCode.LDB); tempMap.put("ths", BCeIDAccountTypeCode.THS); accountTypeLookup = Collections.unmodifiableMap(tempMap); } public CsoAccountServiceImpl(AccountFacadeBean accountFacadeBean, RoleRegistryPortType roleRegistryPortType, BCeIDServiceSoap bCeIDServiceSoap, AccountDetailsMapper accountDetailsMapper) { this.accountFacadeBean = accountFacadeBean; this.roleRegistryPortType = roleRegistryPortType; this.bCeIDServiceSoap = bCeIDServiceSoap; this.accountDetailsMapper = accountDetailsMapper; } @Override public AccountDetails getAccountDetails(UUID userGuid, String bceidAccountType) { AccountDetails accountDetails = getCsoDetails(userGuid); if (null == accountDetails) { accountDetails = getBCeIDDetails(userGuid, bceidAccountType); } return accountDetails; } @Override public AccountDetails createAccount(CreateAccountRequest createAccountRequest) { // Validate the incoming data if (StringUtils.isEmpty(createAccountRequest.getFirstName()) || StringUtils.isEmpty(createAccountRequest.getLastName()) || StringUtils.isEmpty(createAccountRequest.getEmail()) || StringUtils.isEmpty(createAccountRequest.getUniversalId().toString())) { throw new IllegalArgumentException("First Name, Last Name, Email, and Universal ID are required"); } AccountDetails accountDetails = null; try { Account account = setCreateAccountDetails(createAccountRequest); Client client = setCreateAccountClientDetails(createAccountRequest); List<RoleAssignment> roles = setCreateAccountRoles(); ClientProfile clientProfile = accountFacadeBean.createAccount(account, client, roles); if (null != clientProfile) { accountDetails = accountDetailsMapper.toAccountDetails( createAccountRequest.getUniversalId(), clientProfile, hasFileRole(CsoHelpers.formatUserGuid(createAccountRequest.getUniversalId()))); } } catch (DatatypeConfigurationException | NestedEjbException_Exception | WebServiceException e) { throw new EfilingAccountServiceException("Exception while creating CSO account", e.getCause()); } return accountDetails; } private AccountDetails getCsoDetails(UUID userGuid) { AccountDetails accountDetails = null; List<ClientProfile> profiles = new ArrayList<>(); try { profiles.addAll(accountFacadeBean.findProfiles(CsoHelpers.formatUserGuid(userGuid))); } catch (NestedEjbException_Exception | WebServiceException e) { throw new EfilingAccountServiceException("Exception while fetching account details", e); } // An account must have only one profile associated with it to proceed if (profiles.size() == 1) { accountDetails = accountDetailsMapper.toAccountDetails(userGuid, profiles.get(0), hasFileRole(CsoHelpers.formatUserGuid(userGuid))); } else if (profiles.size() > 1) { throw new CSOHasMultipleAccountException(profiles.get(0).getClientId().toString()); } return accountDetails; } private AccountDetails getBCeIDDetails(UUID userGuid, String accountType) { AccountDetails accountDetails = null; BCeIDAccountTypeCode accountTypeCode = getBCeIDAccountType(accountType); if (accountTypeCode != BCeIDAccountTypeCode.VOID) { AccountDetailRequest request = new AccountDetailRequest(); request.setOnlineServiceId("62B2-5550-4376-4DA7"); request.setRequesterUserGuid(CsoHelpers.formatUserGuid(userGuid)); request.setRequesterAccountTypeCode(accountTypeCode); request.setUserGuid(CsoHelpers.formatUserGuid(userGuid)); request.setAccountTypeCode(accountTypeCode); AccountDetailResponse response = bCeIDServiceSoap.getAccountDetail(request); if (response.getCode() == ResponseCode.SUCCESS) { accountDetails = accountDetailsMapper.toAccountDetails(userGuid, response.getAccount()); } } return accountDetails; } public boolean hasFileRole(String userGuid) { UserRoles userRoles = roleRegistryPortType.getRolesForIdentifier("Courts", "CSO", userGuid, "CAP"); List<RegisteredRole> roles = userRoles.getRoles(); return roles != null && roles.stream().anyMatch(r -> r.getCode().equals("FILE")); } private BCeIDAccountTypeCode getBCeIDAccountType(String bceidAccountType) { String lookUp = bceidAccountType.toLowerCase(); BCeIDAccountTypeCode code = accountTypeLookup.get(lookUp); return code == null? BCeIDAccountTypeCode.VOID : code; } private Account setCreateAccountDetails(CreateAccountRequest createAccountRequest) throws DatatypeConfigurationException { Account account = new Account(); String accountName = createAccountRequest.getFirstName() + " " + createAccountRequest.getLastName(); account.setAccountNm(accountName); account.setAccountPrefixTxt("SA"); account.setAccountStatusCd("ACT"); account.setAuthenticatedAccountGuid(CsoHelpers.formatUserGuid(createAccountRequest.getUniversalId())); account.setEmailTxt(createAccountRequest.getEmail()); account.setEntDtm(CsoHelpers.date2XMLGregorian(new Date())); account.setFeeExemptYnBoolean(false); account.setRegisteredCreditCardYnBoolean(false); return account; } private Client setCreateAccountClientDetails(CreateAccountRequest createAccountRequest) throws DatatypeConfigurationException { Client client = new Client(); XMLGregorianCalendar date = CsoHelpers.date2XMLGregorian(new Date()); client.setAuthenticatedClientGuid(CsoHelpers.formatUserGuid(createAccountRequest.getUniversalId())); client.setClientPrefixTxt("CS"); client.setClientStatusCd("ACT"); client.setEmailTxt(createAccountRequest.getEmail()); client.setEntDtm(date); client.setGivenNm(createAccountRequest.getFirstName()); client.setMiddleNm(createAccountRequest.getMiddleName()); client.setRegisteredCreditCardYnBoolean(false); client.setServiceConditionsAcceptDtm(date); client.setSurnameNm(createAccountRequest.getLastName()); return client; } private List<RoleAssignment> setCreateAccountRoles() { List<RoleAssignment> roles = new ArrayList<>(); RoleAssignment role = new RoleAssignment(); role.setActiveYn(true); role.setRegisteredClientRoleCd("IND"); roles.add(role); role.setRegisteredClientRoleCd("CAEF"); roles.add(role); role.setRegisteredClientRoleCd("FILE"); roles.add(role); return roles; } }
43.830918
144
0.714979
564eea755caf719f207fa11818e5e9030d056941
2,766
package no.agens.cassowarylayout.util; import org.pybee.cassowary.Constraint; import org.pybee.cassowary.ConstraintNotFound; import org.pybee.cassowary.Expression; import org.pybee.cassowary.SimplexSolver; import org.pybee.cassowary.Strength; import org.pybee.cassowary.Variable; /** * Created by alex on 08/10/2014. */ public class CassowaryUtil { public static Constraint createWeakEqualityConstraint() { return new Constraint(new Expression(null, -1.0, 0), Strength.WEAK); } public static Constraint createWeakInequalityConstraint(Variable variable, Constraint.Operator op, double value) { Expression expression = new Expression(value); return new Constraint(variable, op, expression, Strength.STRONG); } public static void updateConstraint(Constraint constraint, Variable variable, double value) { Expression expression = constraint.expression(); expression.set_constant(value); expression.setVariable(variable, -1); } public static Constraint createOrUpdateLeqInequalityConstraint(Variable variable, Constraint constraint, double value, SimplexSolver solver) { if (constraint != null) { double currentValue = constraint.expression().constant(); // This will not detect if the variable or strength has changed. if (currentValue != value) { try { solver.removeConstraint(constraint); } catch (ConstraintNotFound constraintNotFound) { constraintNotFound.printStackTrace(); } constraint = null; } } if (constraint == null) { constraint = new Constraint(variable, Constraint.Operator.LEQ, value, Strength.STRONG); solver.addConstraint(constraint); } return constraint; } public static Constraint createOrUpdateLinearEquationConstraint(Variable variable, Constraint constraint, double value, SimplexSolver solver) { if (constraint != null) { double currentValue = constraint.expression().constant(); // This will not detect if the variable, strength or operation has changed if (currentValue != value) { try { solver.removeConstraint(constraint); } catch (ConstraintNotFound constraintNotFound) { constraintNotFound.printStackTrace(); } constraint = null; } } if (constraint == null) { constraint = new Constraint(variable, Constraint.Operator.EQ, value, Strength.STRONG); solver.addConstraint(constraint); } return constraint; } }
36.394737
147
0.644613
7e9cc8b0bd6b9a0896ad4490f3ef066f5665f301
420
/* * Copyright 2015, Yahoo Inc. * Copyrights licensed under the Apache License. * See the accompanying LICENSE file for terms. */ package com.yahoo.dba.perf.myperf.db; import com.yahoo.dba.perf.myperf.common.*; /** * Process ResultList after query returned and returns a modified ResultList * @author xrao * */ public interface PostQueryResultProcessor { ResultList process(ResultList rs); }
23.333333
77
0.719048
95f9b706f29c6204ddd469b0195455229243ea8e
650
package com.pux0r3.bionicbeth.physics; import com.badlogic.ashley.core.Component; import com.badlogic.gdx.math.Vector3; /** * Created by pux19 on 1/5/2016. */ public class PhysicsComponent implements Component { Vector3 _velocity = new Vector3(); Vector3 _acceleration = new Vector3(); public void getVelocity(Vector3 outVelocity) { outVelocity.set(_velocity); } public void setVelocity(Vector3 inVelocity) { _velocity.set(inVelocity); } public void getAcceleration(Vector3 outAcceleration) { outAcceleration.set(_acceleration); } public void setAcceleration(Vector3 inAcceleration) { _acceleration.set(inAcceleration); } }
22.413793
55
0.769231
1c59ac75a407bcb5db3610527d7eea64b240098c
10,658
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jclouds.googlecomputeengine.domain; import static com.google.common.base.Objects.equal; import static com.google.common.base.Objects.toStringHelper; import static com.google.common.base.Optional.fromNullable; import static com.google.common.base.Preconditions.checkNotNull; import java.beans.ConstructorProperties; import java.net.URI; import java.util.Date; import java.util.List; import org.jclouds.javax.annotation.Nullable; import com.google.common.annotations.Beta; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.ImmutableList; /** * Represents a machine type used to host an instance. * * @see <a href="https://developers.google.com/compute/docs/reference/v1/machineTypes"/> */ @Beta public final class MachineType extends Resource { private final Integer guestCpus; private final Integer memoryMb; private final Integer imageSpaceGb; private final List<ScratchDisk> scratchDisks; private final Integer maximumPersistentDisks; private final Long maximumPersistentDisksSizeGb; private final String zone; private final Optional<Deprecated> deprecated; @ConstructorProperties({ "id", "creationTimestamp", "selfLink", "name", "description", "guestCpus", "memoryMb", "imageSpaceGb", "scratchDisks", "maximumPersistentDisks", "maximumPersistentDisksSizeGb", "zone", "deprecated" }) private MachineType(String id, Date creationTimestamp, URI selfLink, String name, String description, int guestCpus, int memoryMb, int imageSpaceGb, List<ScratchDisk> scratchDisks, int maximumPersistentDisks, long maximumPersistentDisksSizeGb, String zone, @Nullable Deprecated deprecated) { super(Kind.MACHINE_TYPE, id, creationTimestamp, selfLink, name, description); this.guestCpus = checkNotNull(guestCpus, "guestCpus of %s", name); this.memoryMb = checkNotNull(memoryMb, "memoryMb of %s", name); this.imageSpaceGb = checkNotNull(imageSpaceGb, "imageSpaceGb of %s", name); this.scratchDisks = scratchDisks == null ? ImmutableList.<ScratchDisk>of() : scratchDisks; this.maximumPersistentDisks = checkNotNull(maximumPersistentDisks, "maximumPersistentDisks of %s", name); this.maximumPersistentDisksSizeGb = maximumPersistentDisksSizeGb; this.zone = checkNotNull(zone, "zone of %s", name); this.deprecated = fromNullable(deprecated); } /** * @return count of CPUs exposed to the instance. */ public int getGuestCpus() { return guestCpus; } /** * @return physical memory assigned to the instance, defined in MB. */ public int getMemoryMb() { return memoryMb; } /** * @return space allotted for the image, defined in GB. */ public int getImageSpaceGb() { return imageSpaceGb; } /** * @return extended scratch disks assigned to the instance. */ public List<ScratchDisk> getScratchDisks() { return scratchDisks; } /** * @return maximum persistent disks allowed. */ public int getMaximumPersistentDisks() { return maximumPersistentDisks; } /** * @return maximum total persistent disks size (GB) allowed. */ public long getMaximumPersistentDisksSizeGb() { return maximumPersistentDisksSizeGb; } /** * @return the zones that this machine type can run in. */ public String getZone() { return zone; } /** * @return the deprecation information for this machine type */ public Optional<Deprecated> getDeprecated() { return deprecated; } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; MachineType that = MachineType.class.cast(obj); return equal(this.kind, that.kind) && equal(this.name, that.name) && equal(this.zone, that.zone); } /** * {@inheritDoc} */ protected Objects.ToStringHelper string() { return super.string() .add("guestCpus", guestCpus) .add("memoryMb", memoryMb) .add("imageSpaceGb", imageSpaceGb) .add("scratchDisks", scratchDisks) .add("maximumPersistentDisks", maximumPersistentDisks) .add("maximumPersistentDisksSizeGb", maximumPersistentDisksSizeGb) .add("zone", zone) .add("deprecated", deprecated.orNull()); } /** * {@inheritDoc} */ @Override public String toString() { return string().toString(); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return new Builder().fromMachineType(this); } public static final class Builder extends Resource.Builder<Builder> { private Integer guestCpus; private Integer memoryMb; private Integer imageSpaceGb; private ImmutableList.Builder<ScratchDisk> scratchDisks = ImmutableList.builder(); private Integer maximumPersistentDisks; private Long maximumPersistentDisksSizeGb; private String zone; private Deprecated deprecated; /** * @see MachineType#getGuestCpus() */ public Builder guestCpus(int guesCpus) { this.guestCpus = guesCpus; return this; } /** * @see MachineType#getMemoryMb() */ public Builder memoryMb(int memoryMb) { this.memoryMb = memoryMb; return this; } /** * @see MachineType#getImageSpaceGb() */ public Builder imageSpaceGb(int imageSpaceGb) { this.imageSpaceGb = imageSpaceGb; return this; } /** * @see MachineType#getScratchDisks() */ public Builder addScratchDisk(int diskGb) { this.scratchDisks.add(ScratchDisk.builder().diskGb(diskGb).build()); return this; } /** * @see MachineType#getScratchDisks() */ public Builder scratchDisks(List<ScratchDisk> scratchDisks) { this.scratchDisks.addAll(scratchDisks); return this; } /** * @see MachineType#getMaximumPersistentDisks() */ public Builder maximumPersistentDisks(int maximumPersistentDisks) { this.maximumPersistentDisks = maximumPersistentDisks; return this; } /** * @see MachineType#getMaximumPersistentDisksSizeGb() */ public Builder maximumPersistentDisksSizeGb(long maximumPersistentDisksSizeGb) { this.maximumPersistentDisksSizeGb = maximumPersistentDisksSizeGb; return this; } /** * @see MachineType#getZone() */ public Builder zone(String zone) { this.zone = zone; return this; } /** * @see MachineType#getDeprecated() */ public Builder deprecated(Deprecated deprecated) { this.deprecated = deprecated; return this; } @Override protected Builder self() { return this; } public MachineType build() { return new MachineType(id, creationTimestamp, selfLink, name, description, guestCpus, memoryMb, imageSpaceGb, scratchDisks.build(), maximumPersistentDisks, maximumPersistentDisksSizeGb, zone, deprecated); } public Builder fromMachineType(MachineType in) { return super.fromResource(in).memoryMb(in.getMemoryMb()).imageSpaceGb(in.getImageSpaceGb()).scratchDisks(in .getScratchDisks()).maximumPersistentDisks(in.getMaximumPersistentDisks()) .maximumPersistentDisksSizeGb(in.getMaximumPersistentDisksSizeGb()).zone(in.getZone()) .deprecated(in.getDeprecated().orNull()); } } /** * An scratch disk of a MachineType */ public static final class ScratchDisk { private final int diskGb; @ConstructorProperties({ "diskGb" }) private ScratchDisk(int diskGb) { this.diskGb = diskGb; } /** * @return size of the scratch disk, defined in GB. */ public int getDiskGb() { return diskGb; } /** * {@inheritDoc} */ @Override public int hashCode() { return Objects.hashCode(diskGb); } /** * {@inheritDoc} */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; ScratchDisk that = ScratchDisk.class.cast(obj); return equal(this.diskGb, that.diskGb); } /** * {@inheritDoc} */ protected Objects.ToStringHelper string() { return toStringHelper(this) .add("diskGb", diskGb); } /** * {@inheritDoc} */ @Override public String toString() { return string().toString(); } public static Builder builder() { return new Builder(); } public Builder toBuilder() { return builder().fromScratchDisk(this); } public static class Builder { private int diskGb; /** * @see org.jclouds.googlecomputeengine.domain.MachineType.ScratchDisk#getDiskGb() */ public Builder diskGb(int diskGb) { this.diskGb = diskGb; return this; } public ScratchDisk build() { return new ScratchDisk(diskGb); } public Builder fromScratchDisk(ScratchDisk in) { return new Builder().diskGb(in.getDiskGb()); } } } }
29.523546
116
0.633796
804baa1b57db4a948add8630ec50e20f1613fbcc
13,207
/* * Copyright © 2020 Mark Raynsford <[email protected]> http://io7m.com * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package com.io7m.oxicoco.server.vanilla.internal; import com.io7m.oxicoco.errors.OxIRCErrorCommandUnknown; import com.io7m.oxicoco.errors.OxIRCErrorType; import com.io7m.oxicoco.errors.OxIRCReply; import com.io7m.oxicoco.messages.OxIRCMessage; import com.io7m.oxicoco.messages.OxIRCMessageParserFactoryType; import com.io7m.oxicoco.messages.OxIRCMessageParserType; import com.io7m.oxicoco.names.OxNickName; import com.io7m.oxicoco.names.OxUserName; import com.io7m.oxicoco.server.api.OxServerConfiguration; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ConcurrentLinkedQueue; import static java.nio.charset.StandardCharsets.UTF_8; /** * A single client connected to the server. */ public final class OxServerClient implements Closeable { private static final Logger LOG = LoggerFactory.getLogger(OxServerClient.class); private final OxServerControllerType serverController; private final OxServerClientID clientId; private final OxServerConfiguration configuration; private final Socket socket; private final SocketAddress address; private final OxIRCMessageParserFactoryType parsers; private final Map<String, OxServerClientCommandHandlerType> handlers; private final ConcurrentLinkedQueue<OxIRCMessage> serverMessages; private OxServerClientCommandContextType context; private volatile OxUserName user; /** * A single client connected to the server. * * @param inConfiguration The server configuration * @param inParsers A message parser factory * @param inServerController The server controller * @param inClientId The client ID * @param inSocket The client socket */ public OxServerClient( final OxServerConfiguration inConfiguration, final OxIRCMessageParserFactoryType inParsers, final OxServerControllerType inServerController, final OxServerClientID inClientId, final Socket inSocket) { this.serverController = Objects.requireNonNull(inServerController, "serverController"); this.clientId = Objects.requireNonNull(inClientId, "clientId"); this.configuration = Objects.requireNonNull(inConfiguration, "configuration"); this.parsers = Objects.requireNonNull(inParsers, "inParsers"); this.socket = Objects.requireNonNull(inSocket, "socket"); this.address = this.socket.getRemoteSocketAddress(); this.serverMessages = new ConcurrentLinkedQueue<>(); this.user = OxUserName.of("anonymous"); this.handlers = Map.ofEntries( Map.entry("CAP", new OxServerClientCommandCAP()), Map.entry("JOIN", new OxServerClientCommandJOIN()), Map.entry("MODE", new OxServerClientCommandMODE()), Map.entry("MOTD", new OxServerClientCommandMOTD()), Map.entry("NICK", new OxServerClientCommandNICK()), Map.entry("PART", new OxServerClientCommandPART()), Map.entry("PING", new OxServerClientCommandPING()), Map.entry("PRIVMSG", new OxServerClientCommandPRIVMSG()), Map.entry("QUIT", new OxServerClientCommandQUIT()), Map.entry("STATS", new OxServerClientCommandSTATS()), Map.entry("TOPIC", new OxServerClientCommandTOPIC()), Map.entry("USER", new OxServerClientCommandUSER()), Map.entry("VERSION", new OxServerClientCommandVERSION()) ); } @Override public void close() throws IOException { this.socket.close(); } /** * @return The client ID */ public OxServerClientID id() { return this.clientId; } /** * Start executing the client, returning when the client disconnects. */ public void run() { try { this.info("starting"); this.socket.setSoTimeout(16 * 10); final var input = this.socket.getInputStream(); final var output = this.socket.getOutputStream(); final var parser = this.parsers.create(); this.runLoop(input, output, parser); } catch (final IOException e) { this.error("i/o error: ", e); } finally { this.serverController.clientDestroy(this); this.info("finished"); } } private void info( final String message, final Object... arguments) { LOG.info( "[{}] {}", this.address, String.format(message, arguments) ); } private void traceInput( final String message) { if (LOG.isTraceEnabled()) { LOG.trace( "[{}] → {}", this.address, message ); } } private void traceOutput( final String message) { if (LOG.isTraceEnabled()) { LOG.trace( "[{}] ← {}", this.address, message ); } } private void error( final String message, final Exception exception) { LOG.error( "[{}] {}", this.address, message, exception ); } private void error( final String message, final Object... parameters) { LOG.error( "[{}] {}", this.address, String.format(message, parameters) ); } private void runLoop( final InputStream input, final OutputStream output, final OxIRCMessageParserType parser) { final var lineReader = new BufferedReader(new InputStreamReader(input, UTF_8)); final var lineWriter = new BufferedWriter(new OutputStreamWriter(output, UTF_8)); this.context = new Context(this, lineWriter); try { while (!this.socket.isClosed()) { try { final var line = lineReader.readLine(); if (line == null) { return; } this.traceInput(line); final var message = parser.parse(line); if (message.isPresent()) { this.handleMessage(lineWriter, message.get()); } } catch (final SocketTimeoutException e) { // Expected } while (!this.socket.isClosed()) { final var serverMessage = this.serverMessages.poll(); if (serverMessage == null) { break; } this.sendMessage(lineWriter, serverMessage); } } } catch (final SocketException e) { if (this.socket.isClosed()) { return; } this.error("socket error: ", e); } catch (final IOException e) { this.error("i/o error: ", e); } } private void handleMessage( final BufferedWriter lineWriter, final OxIRCMessage message) throws IOException { final var handler = this.handlers.get(message.command()); if (handler != null) { handler.execute(this.context, message); } else { this.sendError( lineWriter, OxIRCErrorCommandUnknown.of(message.command())); } } private void sendError( final BufferedWriter lineWriter, final OxIRCErrorType error) throws IOException { final var message = error.toMessage(Optional.of(this.configuration.serverName())); this.sendMessage(lineWriter, message); } private void sendMessage( final BufferedWriter lineWriter, final OxIRCMessage message) throws IOException { final var text = message.format(); this.traceOutput(text); lineWriter.append(text); lineWriter.append('\r'); lineWriter.append('\n'); lineWriter.flush(); } private void sendCommandFromUser( final BufferedWriter lineWriter, final OxUserID userID, final String commandName, final List<String> parameters, final String trailing) throws IOException { final var builder = OxIRCMessage.builder(); builder.setCommand(commandName); builder.setParameters(parameters); builder.setRawText(""); builder.setPrefix(":" + userID.format()); builder.setTrailing(trailing); this.sendMessage(lineWriter, builder.build()); } private void sendReply( final BufferedWriter lineWriter, final OxIRCReply reply, final List<String> parameters, final String trailing) throws IOException { final var builder = OxIRCMessage.builder(); builder.setCommand(reply.format()); builder.setParameters(parameters); builder.setRawText(""); builder.setPrefix(":" + this.configuration.serverName().value()); builder.setTrailing(trailing); this.sendMessage(lineWriter, builder.build()); } private void sendCommand( final BufferedWriter lineWriter, final String commandName, final List<String> parameters, final String trailing) throws IOException { final var builder = OxIRCMessage.builder(); builder.setCommand(commandName); builder.setParameters(parameters); builder.setRawText(""); builder.setPrefix(":" + this.configuration.serverName().value()); builder.setTrailing(trailing); this.sendMessage(lineWriter, builder.build()); } /** * @return The client nick name * * @throws OxNameNotRegisteredException If the client has not specified a nick */ public OxNickName nick() throws OxNameNotRegisteredException { return this.serverController.clientNick(this); } /** * @return The client user ID * * @throws OxNameNotRegisteredException If the client has not specified a nick */ public OxUserID userId() throws OxNameNotRegisteredException { return this.serverController.clientUserId(this); } /** * @return The client user name */ public OxUserName user() { return this.user; } /** * @return The client host */ public String host() { return this.clientId.format(); } /** * Enqueue a message to the client. * * @param message The message */ public void enqueueMessage( final OxIRCMessage message) { this.serverMessages.add(message); } /** * Set the client user name. * * @param name The name */ public void setUser( final OxUserName name) { this.user = Objects.requireNonNull(name, "name"); } private static final class Context implements OxServerClientCommandContextType { private final OxServerClient client; private final BufferedWriter lineWriter; private Context( final OxServerClient inClient, final BufferedWriter inLineWriter) { this.client = Objects.requireNonNull(inClient, "client"); this.lineWriter = Objects.requireNonNull(inLineWriter, "lineWriter"); } @Override public void sendError( final OxIRCErrorType error) throws IOException { this.client.sendError(this.lineWriter, error); } @Override public void sendCommand( final String command, final List<String> parameters, final String trailing) throws IOException { this.client.sendCommand( this.lineWriter, command, parameters, trailing ); } @Override public void sendCommandFromUser( final OxUserID userId, final String command, final List<String> parameters, final String trailing) throws IOException { this.client.sendCommandFromUser( this.lineWriter, userId, command, parameters, trailing ); } @Override public OxServerControllerType serverController() { return this.client.serverController; } @Override public OxServerClient client() { return this.client; } @Override public void sendReply( final OxIRCReply reply, final List<String> parameters, final String trailing) throws IOException { this.client.sendReply(this.lineWriter, reply, parameters, trailing); } @Override public OxServerConfiguration configuration() { return this.client.configuration; } @Override public void error( final String pattern, final Exception e) { this.client.error(pattern, e); } } }
25.398077
80
0.669418
74c14803f032fccfbdd3bd1714bd708edd677bdb
1,680
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package graphene.web.model; import java.io.Serializable; // A handy holder for an (id, version). public class IdVersion implements Serializable { private static final long serialVersionUID = 1L; private Long id; private Integer version; public IdVersion(Long id, Integer version) { super(); id = id; version = version; } public Long getId() { return id; } public Integer getVersion() { return version; } public void setId(Long id) { id = id; } public void setVersion(Integer version) { version = version; } @Override public String toString() { final String DIVIDER = ", "; final StringBuilder buf = new StringBuilder(); buf.append(this.getClass().getSimpleName() + ": "); buf.append("["); buf.append("id=" + id + DIVIDER); buf.append("version=" + version); buf.append("]"); return buf.toString(); } }
25.074627
76
0.702976
6c331b20111a0b11f644b4a45e3173f09e8ec057
337
/* * synopsys-detect * * Copyright (c) 2021 Synopsys, Inc. * * Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide. */ package com.synopsys.integration.detect.workflow.airgap; public enum AirGapInspectors { DOCKER, GRADLE, NUGET }
22.466667
142
0.735905
7bc8d4983761e31006f0a56b20b916645624118b
1,416
package Run; import Base.Base; import com.relevantcodes.extentreports.ExtentReports; import com.relevantcodes.extentreports.ExtentTest; import org.apache.log4j.Logger; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterSuite; import org.testng.annotations.BeforeSuite; /** * @author celik.gumusdag */ public class Run extends Base { public static Logger logger=Logger.getLogger(Run.class.getName()); public static WebDriver driver; protected static ExtentReports extentReports; protected static ExtentTest extentTest; protected static String methodName=""; @BeforeSuite public static void a() throws Exception { logger.info("Before Suite"); System.setProperty("webdriver.chrome.driver", "chromedriver.exe"); driver = new ChromeDriver(); //pencereyi oluşturur driver.manage().window().maximize(); //pencereyi fullscreen yapar } @AfterClass public static void b() throws Exception { Thread.sleep(3000); //3 saniye bekleme süresi } @AfterSuite public static void c() throws Exception { logger.info("After Suite"); Thread.sleep(5000); //5 saniye bekleme süresi driver.close(); //chromedriveri kapatır driver.quit(); //chromedriveri uçurur } }
28.32
76
0.704096
e92f8a57984f34be3877902c795cca146b8a7c0a
1,440
/* * Copyright 2021 WILIX LLC * * 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 dev.wilix.ldap.facade.file; import java.util.List; import java.util.Map; /** * Results of parsing file. * <p> * The class intended to store and issue results of FileParser */ class ParseResult { private final List<Map<String, List<String>>> users; private final List<Map<String, List<String>>> groups; public ParseResult(List<Map<String, List<String>>> users, List<Map<String, List<String>>> groups) { this.users = users; this.groups = groups; } public List<Map<String, List<String>>> getUsers() { return users; } public List<Map<String, List<String>>> getGroups() { return groups; } @Override public String toString() { return "ParseResult{" + "users=" + users + ", groups=" + groups + '}'; } }
27.169811
103
0.651389
26fdf5cd6c883beaa688bc36b788f60aedc4e247
56,511
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.opensearch.painless; public class DefCastTests extends ScriptTestCase { public void testdefTobooleanImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; boolean b = d;")); assertEquals(true, exec("def d = true; boolean b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (byte)0; boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; boolean b = d;")); assertEquals(false, exec("def d = Boolean.valueOf(false); boolean b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Byte.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); boolean b = d;")); } public void testdefTobyteImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; byte b = d;")); assertEquals((byte)0, exec("def d = (byte)0; byte b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); byte b = d;")); assertEquals((byte)0, exec("def d = Byte.valueOf(0); byte b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); byte b = d;")); } public void testdefToshortImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; short b = d;")); assertEquals((short)0, exec("def d = (byte)0; short b = d; b")); assertEquals((short)0, exec("def d = (short)0; short b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); short b = d;")); assertEquals((short)0, exec("def d = Byte.valueOf(0); short b = d; b")); assertEquals((short)0, exec("def d = Short.valueOf(0); short b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); short b = d;")); } public void testdefTocharImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 's'; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (byte)0; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; char b = d;")); assertEquals((char)0, exec("def d = (char)0; char b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Byte.valueOf(0); char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); char b = d;")); assertEquals((char)0, exec("def d = Character.valueOf(0); char b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); char b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); char b = d;")); } public void testdefTointImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; int b = d;")); assertEquals(0, exec("def d = (byte)0; int b = d; b")); assertEquals(0, exec("def d = (short)0; int b = d; b")); assertEquals(0, exec("def d = (char)0; int b = d; b")); assertEquals(0, exec("def d = 0; int b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); int b = d;")); assertEquals(0, exec("def d = Byte.valueOf(0); int b = d; b")); assertEquals(0, exec("def d = Short.valueOf(0); int b = d; b")); assertEquals(0, exec("def d = Character.valueOf(0); int b = d; b")); assertEquals(0, exec("def d = Integer.valueOf(0); int b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); int b = d;")); } public void testdefTolongImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; long b = d;")); assertEquals((long)0, exec("def d = (byte)0; long b = d; b")); assertEquals((long)0, exec("def d = (short)0; long b = d; b")); assertEquals((long)0, exec("def d = (char)0; long b = d; b")); assertEquals((long)0, exec("def d = 0; long b = d; b")); assertEquals((long)0, exec("def d = (long)0; long b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); long b = d;")); assertEquals((long)0, exec("def d = Byte.valueOf(0); long b = d; b")); assertEquals((long)0, exec("def d = Short.valueOf(0); long b = d; b")); assertEquals((long)0, exec("def d = Character.valueOf(0); long b = d; b")); assertEquals((long)0, exec("def d = Integer.valueOf(0); long b = d; b")); assertEquals((long)0, exec("def d = Long.valueOf(0); long b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); long b = d;")); } public void testdefTodoubleImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; double b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; double b = d;")); assertEquals((double)0, exec("def d = (byte)0; double b = d; b")); assertEquals((double)0, exec("def d = (short)0; double b = d; b")); assertEquals((double)0, exec("def d = (char)0; double b = d; b")); assertEquals((double)0, exec("def d = 0; double b = d; b")); assertEquals((double)0, exec("def d = (long)0; double b = d; b")); assertEquals((double)0, exec("def d = (float)0; double b = d; b")); assertEquals((double)0, exec("def d = (double)0; double b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); double b = d;")); assertEquals((double)0, exec("def d = Byte.valueOf(0); double b = d; b")); assertEquals((double)0, exec("def d = Short.valueOf(0); double b = d; b")); assertEquals((double)0, exec("def d = Character.valueOf(0); double b = d; b")); assertEquals((double)0, exec("def d = Integer.valueOf(0); double b = d; b")); assertEquals((double)0, exec("def d = Long.valueOf(0); double b = d; b")); assertEquals((double)0, exec("def d = Float.valueOf(0); double b = d; b")); assertEquals((double)0, exec("def d = Double.valueOf(0); double b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); double b = d;")); } public void testdefTobooleanExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; boolean b = (boolean)d;")); assertEquals(true, exec("def d = true; boolean b = (boolean)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (byte)0; boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; boolean b = (boolean)d;")); assertEquals(false, exec("def d = Boolean.valueOf(false); boolean b = (boolean)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Byte.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); boolean b = (boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); boolean b = (boolean)d;")); } public void testdefTobyteExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; byte b = (byte)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; byte b = (byte)d;")); assertEquals((byte)0, exec("def d = (byte)0; byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = (short)0; byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = (char)0; byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = 0; byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = (long)0; byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = (float)0; byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = (double)0; byte b = (byte)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); byte b = d;")); assertEquals((byte)0, exec("def d = Byte.valueOf(0); byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = Short.valueOf(0); byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = Character.valueOf(0); byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = Integer.valueOf(0); byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = Long.valueOf(0); byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = Float.valueOf(0); byte b = (byte)d; b")); assertEquals((byte)0, exec("def d = Double.valueOf(0); byte b = (byte)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); byte b = (byte)d;")); } public void testdefToshortExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; short b = (short)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; short b = (short)d;")); assertEquals((short)0, exec("def d = (byte)0; short b = (short)d; b")); assertEquals((short)0, exec("def d = (short)0; short b = (short)d; b")); assertEquals((short)0, exec("def d = (char)0; short b = (short)d; b")); assertEquals((short)0, exec("def d = 0; short b = (short)d; b")); assertEquals((short)0, exec("def d = (long)0; short b = (short)d; b")); assertEquals((short)0, exec("def d = (float)0; short b = (short)d; b")); assertEquals((short)0, exec("def d = (double)0; short b = (short)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); short b = d;")); assertEquals((short)0, exec("def d = Byte.valueOf(0); short b = (short)d; b")); assertEquals((short)0, exec("def d = Short.valueOf(0); short b = (short)d; b")); assertEquals((short)0, exec("def d = Character.valueOf(0); short b = (short)d; b")); assertEquals((short)0, exec("def d = Integer.valueOf(0); short b = (short)d; b")); assertEquals((short)0, exec("def d = Long.valueOf(0); short b = (short)d; b")); assertEquals((short)0, exec("def d = Float.valueOf(0); short b = (short)d; b")); assertEquals((short)0, exec("def d = Double.valueOf(0); short b = (short)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); short b = (short)d;")); } public void testdefTocharExplicit() { assertEquals('s', exec("def d = 's'; char b = (char)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; char b = (char)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; char b = (char)d;")); assertEquals((char)0, exec("def d = (byte)0; char b = (char)d; b")); assertEquals((char)0, exec("def d = (short)0; char b = (char)d; b")); assertEquals((char)0, exec("def d = (char)0; char b = (char)d; b")); assertEquals((char)0, exec("def d = 0; char b = (char)d; b")); assertEquals((char)0, exec("def d = (long)0; char b = (char)d; b")); assertEquals((char)0, exec("def d = (float)0; char b = (char)d; b")); assertEquals((char)0, exec("def d = (double)0; char b = (char)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); char b = d;")); assertEquals((char)0, exec("def d = Byte.valueOf(0); char b = (char)d; b")); assertEquals((char)0, exec("def d = Short.valueOf(0); char b = (char)d; b")); assertEquals((char)0, exec("def d = Character.valueOf(0); char b = (char)d; b")); assertEquals((char)0, exec("def d = Integer.valueOf(0); char b = (char)d; b")); assertEquals((char)0, exec("def d = Long.valueOf(0); char b = (char)d; b")); assertEquals((char)0, exec("def d = Float.valueOf(0); char b = (char)d; b")); assertEquals((char)0, exec("def d = Double.valueOf(0); char b = (char)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); char b = (char)d;")); } public void testdefTointExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; int b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; int b = (int)d;")); assertEquals(0, exec("def d = (byte)0; int b = (int)d; b")); assertEquals(0, exec("def d = (short)0; int b = (int)d; b")); assertEquals(0, exec("def d = (char)0; int b = (int)d; b")); assertEquals(0, exec("def d = 0; int b = (int)d; b")); assertEquals(0, exec("def d = (long)0; int b = (int)d; b")); assertEquals(0, exec("def d = (float)0; int b = (int)d; b")); assertEquals(0, exec("def d = (double)0; int b = (int)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); int b = d;")); assertEquals(0, exec("def d = Byte.valueOf(0); int b = (int)d; b")); assertEquals(0, exec("def d = Short.valueOf(0); int b = (int)d; b")); assertEquals(0, exec("def d = Character.valueOf(0); int b = (int)d; b")); assertEquals(0, exec("def d = Integer.valueOf(0); int b = (int)d; b")); assertEquals(0, exec("def d = Long.valueOf(0); int b = (int)d; b")); assertEquals(0, exec("def d = Float.valueOf(0); int b = (int)d; b")); assertEquals(0, exec("def d = Double.valueOf(0); int b = (int)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); int b = (int)d;")); } public void testdefTolongExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; long b = (long)d;")); assertEquals((long)0, exec("def d = (byte)0; long b = (long)d; b")); assertEquals((long)0, exec("def d = (short)0; long b = (long)d; b")); assertEquals((long)0, exec("def d = (char)0; long b = (long)d; b")); assertEquals((long)0, exec("def d = 0; long b = (long)d; b")); assertEquals((long)0, exec("def d = (long)0; long b = (long)d; b")); assertEquals((long)0, exec("def d = (float)0; long b = (long)d; b")); assertEquals((long)0, exec("def d = (double)0; long b = (long)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); long b = d;")); assertEquals((long)0, exec("def d = Byte.valueOf(0); long b = (long)d; b")); assertEquals((long)0, exec("def d = Short.valueOf(0); long b = (long)d; b")); assertEquals((long)0, exec("def d = Character.valueOf(0); long b = (long)d; b")); assertEquals((long)0, exec("def d = Integer.valueOf(0); long b = (long)d; b")); assertEquals((long)0, exec("def d = Long.valueOf(0); long b = (long)d; b")); assertEquals((long)0, exec("def d = Float.valueOf(0); long b = (long)d; b")); assertEquals((long)0, exec("def d = Double.valueOf(0); long b = (long)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); long b = (long)d;")); } public void testdefTofloatExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; float b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; float b = (float)d;")); assertEquals((float)0, exec("def d = (byte)0; float b = (float)d; b")); assertEquals((float)0, exec("def d = (short)0; float b = (float)d; b")); assertEquals((float)0, exec("def d = (char)0; float b = (float)d; b")); assertEquals((float)0, exec("def d = 0; float b = (float)d; b")); assertEquals((float)0, exec("def d = (long)0; float b = (float)d; b")); assertEquals((float)0, exec("def d = (float)0; float b = (float)d; b")); assertEquals((float)0, exec("def d = (double)0; float b = (float)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); float b = d;")); assertEquals((float)0, exec("def d = Byte.valueOf(0); float b = (float)d; b")); assertEquals((float)0, exec("def d = Short.valueOf(0); float b = (float)d; b")); assertEquals((float)0, exec("def d = Character.valueOf(0); float b = (float)d; b")); assertEquals((float)0, exec("def d = Integer.valueOf(0); float b = (float)d; b")); assertEquals((float)0, exec("def d = Long.valueOf(0); float b = (float)d; b")); assertEquals((float)0, exec("def d = Float.valueOf(0); float b = (float)d; b")); assertEquals((float)0, exec("def d = Double.valueOf(0); float b = (float)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); float b = (float)d;")); } public void testdefTodoubleExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; double b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; double b = (double)d;")); assertEquals((double)0, exec("def d = (byte)0; double b = (double)d; b")); assertEquals((double)0, exec("def d = (short)0; double b = (double)d; b")); assertEquals((double)0, exec("def d = (char)0; double b = (double)d; b")); assertEquals((double)0, exec("def d = 0; double b = (double)d; b")); assertEquals((double)0, exec("def d = (long)0; double b = (double)d; b")); assertEquals((double)0, exec("def d = (float)0; double b = (double)d; b")); assertEquals((double)0, exec("def d = (double)0; double b = (double)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); double b = d;")); assertEquals((double)0, exec("def d = Byte.valueOf(0); double b = (double)d; b")); assertEquals((double)0, exec("def d = Short.valueOf(0); double b = (double)d; b")); assertEquals((double)0, exec("def d = Character.valueOf(0); double b = (double)d; b")); assertEquals((double)0, exec("def d = Integer.valueOf(0); double b = (double)d; b")); assertEquals((double)0, exec("def d = Long.valueOf(0); double b = (double)d; b")); assertEquals((double)0, exec("def d = Float.valueOf(0); double b = (double)d; b")); assertEquals((double)0, exec("def d = Double.valueOf(0); double b = (double)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); double b = (double)d;")); } public void testdefToBooleanImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Boolean b = d;")); assertEquals(true, exec("def d = true; Boolean b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (byte)0; Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Boolean b = d;")); assertEquals(false, exec("def d = Boolean.valueOf(false); Boolean b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Byte.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Boolean b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Boolean b = d;")); } public void testdefToByteImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Byte b = d;")); assertEquals((byte)0, exec("def d = (byte)0; Byte b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Byte b = d;")); assertEquals((byte)0, exec("def d = Byte.valueOf(0); Byte b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Byte b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Byte b = d;")); } public void testdefToShortImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Short b = d;")); assertEquals((short)0, exec("def d = (byte)0; Short b = d; b")); assertEquals((short)0, exec("def d = (short)0; Short b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Short b = d;")); assertEquals((short)0, exec("def d = Byte.valueOf(0); Short b = d; b")); assertEquals((short)0, exec("def d = Short.valueOf(0); Short b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Short b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Short b = d;")); } public void testdefToCharacterImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 's'; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (byte)0; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; Character b = d;")); assertEquals((char)0, exec("def d = (char)0; Character b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Byte.valueOf(0); Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); Character b = d;")); assertEquals((char)0, exec("def d = Character.valueOf(0); Character b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Character b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Character b = d;")); } public void testdefToIntegerImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Integer b = d;")); assertEquals(0, exec("def d = (byte)0; Integer b = d; b")); assertEquals(0, exec("def d = (short)0; Integer b = d; b")); assertEquals(0, exec("def d = (char)0; Integer b = d; b")); assertEquals(0, exec("def d = 0; Integer b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Integer b = d;")); assertEquals(0, exec("def d = Byte.valueOf(0); Integer b = d; b")); assertEquals(0, exec("def d = Short.valueOf(0); Integer b = d; b")); assertEquals(0, exec("def d = Character.valueOf(0); Integer b = d; b")); assertEquals(0, exec("def d = Integer.valueOf(0); Integer b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Integer b = d;")); } public void testdefToLongImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Long b = d;")); assertEquals((long)0, exec("def d = (byte)0; Long b = d; b")); assertEquals((long)0, exec("def d = (short)0; Long b = d; b")); assertEquals((long)0, exec("def d = (char)0; Long b = d; b")); assertEquals((long)0, exec("def d = 0; Long b = d; b")); assertEquals((long)0, exec("def d = (long)0; Long b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Long b = d;")); assertEquals((long)0, exec("def d = Byte.valueOf(0); Long b = d; b")); assertEquals((long)0, exec("def d = Short.valueOf(0); Long b = d; b")); assertEquals((long)0, exec("def d = Character.valueOf(0); Long b = d; b")); assertEquals((long)0, exec("def d = Integer.valueOf(0); Long b = d; b")); assertEquals((long)0, exec("def d = Long.valueOf(0); Long b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Long b = d;")); } public void testdefToFloatImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Float b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Float b = d;")); assertEquals((float)0, exec("def d = (byte)0; Float b = d; b")); assertEquals((float)0, exec("def d = (short)0; Float b = d; b")); assertEquals((float)0, exec("def d = (char)0; Float b = d; b")); assertEquals((float)0, exec("def d = 0; Float b = d; b")); assertEquals((float)0, exec("def d = (long)0; Float b = d; b")); assertEquals((float)0, exec("def d = (float)0; Float b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Float b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Float b = d;")); assertEquals((float)0, exec("def d = Byte.valueOf(0); Float b = d; b")); assertEquals((float)0, exec("def d = Short.valueOf(0); Float b = d; b")); assertEquals((float)0, exec("def d = Character.valueOf(0); Float b = d; b")); assertEquals((float)0, exec("def d = Integer.valueOf(0); Float b = d; b")); assertEquals((float)0, exec("def d = Long.valueOf(0); Float b = d; b")); assertEquals((float)0, exec("def d = Float.valueOf(0); Float b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Float b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Float b = d;")); } public void testdefToDoubleImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Double b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Double b = d;")); assertEquals((double)0, exec("def d = (byte)0; Double b = d; b")); assertEquals((double)0, exec("def d = (short)0; Double b = d; b")); assertEquals((double)0, exec("def d = (char)0; Double b = d; b")); assertEquals((double)0, exec("def d = 0; Double b = d; b")); assertEquals((double)0, exec("def d = (long)0; Double b = d; b")); assertEquals((double)0, exec("def d = (float)0; Double b = d; b")); assertEquals((double)0, exec("def d = (double)0; Double b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Double b = d;")); assertEquals((double)0, exec("def d = Byte.valueOf(0); Double b = d; b")); assertEquals((double)0, exec("def d = Short.valueOf(0); Double b = d; b")); assertEquals((double)0, exec("def d = Character.valueOf(0); Double b = d; b")); assertEquals((double)0, exec("def d = Integer.valueOf(0); Double b = d; b")); assertEquals((double)0, exec("def d = Long.valueOf(0); Double b = d; b")); assertEquals((double)0, exec("def d = Float.valueOf(0); Double b = d; b")); assertEquals((double)0, exec("def d = Double.valueOf(0); Double b = d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Double b = d;")); } public void testdefToBooleanExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Boolean b = (Boolean)d;")); assertEquals(true, exec("def d = true; Boolean b = (Boolean)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (byte)0; Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (short)0; Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)0; Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (int)0; Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (long)0; Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (float)0; Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = (double)0; Boolean b = (Boolean)d;")); assertEquals(false, exec("def d = Boolean.valueOf(false); Boolean b = (Boolean)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Byte.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Short.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Character.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Integer.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Long.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Float.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Double.valueOf(0); Boolean b = (Boolean)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Boolean b = (Boolean)d;")); } public void testdefToByteExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Byte b = (Byte)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Byte b = (Byte)d;")); assertEquals((byte)0, exec("def d = (byte)0; Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = (short)0; Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = (char)0; Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = 0; Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = (long)0; Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = (float)0; Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = (double)0; Byte b = (Byte)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Byte b = d;")); assertEquals((byte)0, exec("def d = Byte.valueOf(0); Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = Short.valueOf(0); Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = Character.valueOf(0); Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = Integer.valueOf(0); Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = Long.valueOf(0); Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = Float.valueOf(0); Byte b = (Byte)d; b")); assertEquals((byte)0, exec("def d = Double.valueOf(0); Byte b = (Byte)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Byte b = (Byte)d;")); } public void testdefToShortExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Short b = (Short)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Short b = (Short)d;")); assertEquals((short)0, exec("def d = (byte)0; Short b = (Short)d; b")); assertEquals((short)0, exec("def d = (short)0; Short b = (Short)d; b")); assertEquals((short)0, exec("def d = (char)0; Short b = (Short)d; b")); assertEquals((short)0, exec("def d = 0; Short b = (Short)d; b")); assertEquals((short)0, exec("def d = (long)0; Short b = (Short)d; b")); assertEquals((short)0, exec("def d = (float)0; Short b = (Short)d; b")); assertEquals((short)0, exec("def d = (double)0; Short b = (Short)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Short b = d;")); assertEquals((short)0, exec("def d = Byte.valueOf(0); Short b = (Short)d; b")); assertEquals((short)0, exec("def d = Short.valueOf(0); Short b = (Short)d; b")); assertEquals((short)0, exec("def d = Character.valueOf(0); Short b = (Short)d; b")); assertEquals((short)0, exec("def d = Integer.valueOf(0); Short b = (Short)d; b")); assertEquals((short)0, exec("def d = Long.valueOf(0); Short b = (Short)d; b")); assertEquals((short)0, exec("def d = Float.valueOf(0); Short b = (Short)d; b")); assertEquals((short)0, exec("def d = Double.valueOf(0); Short b = (Short)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Short b = (Short)d;")); } public void testdefToCharacterExplicit() { assertEquals('s', exec("def d = 's'; Character b = (Character)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Character b = (Character)d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Character b = (Character)d;")); assertEquals((char)0, exec("def d = (byte)0; Character b = (Character)d; b")); assertEquals((char)0, exec("def d = (short)0; Character b = (Character)d; b")); assertEquals((char)0, exec("def d = (char)0; Character b = (Character)d; b")); assertEquals((char)0, exec("def d = 0; Character b = (Character)d; b")); assertEquals((char)0, exec("def d = (long)0; Character b = (Character)d; b")); assertEquals((char)0, exec("def d = (float)0; Character b = (Character)d; b")); assertEquals((char)0, exec("def d = (double)0; Character b = (Character)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Character b = d;")); assertEquals((char)0, exec("def d = Byte.valueOf(0); Character b = (Character)d; b")); assertEquals((char)0, exec("def d = Short.valueOf(0); Character b = (Character)d; b")); assertEquals((char)0, exec("def d = Character.valueOf(0); Character b = (Character)d; b")); assertEquals((char)0, exec("def d = Integer.valueOf(0); Character b = (Character)d; b")); assertEquals((char)0, exec("def d = Long.valueOf(0); Character b = (Character)d; b")); assertEquals((char)0, exec("def d = Float.valueOf(0); Character b = (Character)d; b")); assertEquals((char)0, exec("def d = Double.valueOf(0); Character b = (Character)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Character b = (Character)d;")); } public void testdefToIntegerExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Integer b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Integer b = (Integer)d;")); assertEquals(0, exec("def d = (byte)0; Integer b = (Integer)d; b")); assertEquals(0, exec("def d = (short)0; Integer b = (Integer)d; b")); assertEquals(0, exec("def d = (char)0; Integer b = (Integer)d; b")); assertEquals(0, exec("def d = 0; Integer b = (Integer)d; b")); assertEquals(0, exec("def d = (long)0; Integer b = (Integer)d; b")); assertEquals(0, exec("def d = (float)0; Integer b = (Integer)d; b")); assertEquals(0, exec("def d = (double)0; Integer b = (Integer)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Integer b = d;")); assertEquals(0, exec("def d = Byte.valueOf(0); Integer b = (Integer)d; b")); assertEquals(0, exec("def d = Short.valueOf(0); Integer b = (Integer)d; b")); assertEquals(0, exec("def d = Character.valueOf(0); Integer b = (Integer)d; b")); assertEquals(0, exec("def d = Integer.valueOf(0); Integer b = (Integer)d; b")); assertEquals(0, exec("def d = Long.valueOf(0); Integer b = (Integer)d; b")); assertEquals(0, exec("def d = Float.valueOf(0); Integer b = (Integer)d; b")); assertEquals(0, exec("def d = Double.valueOf(0); Integer b = (Integer)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Integer b = (Integer)d;")); } public void testdefToLongExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Long b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Long b = (Long)d;")); assertEquals((long)0, exec("def d = (byte)0; Long b = (Long)d; b")); assertEquals((long)0, exec("def d = (short)0; Long b = (Long)d; b")); assertEquals((long)0, exec("def d = (char)0; Long b = (Long)d; b")); assertEquals((long)0, exec("def d = 0; Long b = (Long)d; b")); assertEquals((long)0, exec("def d = (long)0; Long b = (Long)d; b")); assertEquals((long)0, exec("def d = (float)0; Long b = (Long)d; b")); assertEquals((long)0, exec("def d = (double)0; Long b = (Long)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Long b = d;")); assertEquals((long)0, exec("def d = Byte.valueOf(0); Long b = (Long)d; b")); assertEquals((long)0, exec("def d = Short.valueOf(0); Long b = (Long)d; b")); assertEquals((long)0, exec("def d = Character.valueOf(0); Long b = (Long)d; b")); assertEquals((long)0, exec("def d = Integer.valueOf(0); Long b = (Long)d; b")); assertEquals((long)0, exec("def d = Long.valueOf(0); Long b = (Long)d; b")); assertEquals((long)0, exec("def d = Float.valueOf(0); Long b = (Long)d; b")); assertEquals((long)0, exec("def d = Double.valueOf(0); Long b = (Long)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Long b = (Long)d;")); } public void testdefToFloatExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Float b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Float b = (Float)d;")); assertEquals((float)0, exec("def d = (byte)0; Float b = (Float)d; b")); assertEquals((float)0, exec("def d = (short)0; Float b = (Float)d; b")); assertEquals((float)0, exec("def d = (char)0; Float b = (Float)d; b")); assertEquals((float)0, exec("def d = 0; Float b = (Float)d; b")); assertEquals((float)0, exec("def d = (long)0; Float b = (Float)d; b")); assertEquals((float)0, exec("def d = (float)0; Float b = (Float)d; b")); assertEquals((float)0, exec("def d = (double)0; Float b = (Float)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Float b = d;")); assertEquals((float)0, exec("def d = Byte.valueOf(0); Float b = (Float)d; b")); assertEquals((float)0, exec("def d = Short.valueOf(0); Float b = (Float)d; b")); assertEquals((float)0, exec("def d = Character.valueOf(0); Float b = (Float)d; b")); assertEquals((float)0, exec("def d = Integer.valueOf(0); Float b = (Float)d; b")); assertEquals((float)0, exec("def d = Long.valueOf(0); Float b = (Float)d; b")); assertEquals((float)0, exec("def d = Float.valueOf(0); Float b = (Float)d; b")); assertEquals((float)0, exec("def d = Double.valueOf(0); Float b = (Float)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Float b = (Float)d;")); } public void testdefToDoubleExplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = 'string'; Double b = d;")); expectScriptThrows(ClassCastException.class, () -> exec("def d = true; Double b = (Double)d;")); assertEquals((double)0, exec("def d = (byte)0; Double b = (Double)d; b")); assertEquals((double)0, exec("def d = (short)0; Double b = (Double)d; b")); assertEquals((double)0, exec("def d = (char)0; Double b = (Double)d; b")); assertEquals((double)0, exec("def d = 0; Double b = (Double)d; b")); assertEquals((double)0, exec("def d = (long)0; Double b = (Double)d; b")); assertEquals((double)0, exec("def d = (float)0; Double b = (Double)d; b")); assertEquals((double)0, exec("def d = (double)0; Double b = (Double)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = Boolean.valueOf(true); Double b = d;")); assertEquals((double)0, exec("def d = Byte.valueOf(0); Double b = (Double)d; b")); assertEquals((double)0, exec("def d = Short.valueOf(0); Double b = (Double)d; b")); assertEquals((double)0, exec("def d = Character.valueOf(0); Double b = (Double)d; b")); assertEquals((double)0, exec("def d = Integer.valueOf(0); Double b = (Double)d; b")); assertEquals((double)0, exec("def d = Long.valueOf(0); Double b = (Double)d; b")); assertEquals((double)0, exec("def d = Float.valueOf(0); Double b = (Double)d; b")); assertEquals((double)0, exec("def d = Double.valueOf(0); Double b = (Double)d; b")); expectScriptThrows(ClassCastException.class, () -> exec("def d = new ArrayList(); Double b = (Double)d;")); } public void testdefToStringImplicit() { expectScriptThrows(ClassCastException.class, () -> exec("def d = (char)'s'; String b = d;")); } public void testdefToStringExplicit() { assertEquals("s", exec("def d = (char)'s'; String b = (String)d; b")); } public void testConstFoldingDefCast() { assertFalse((boolean)exec("def chr = 10; return (chr == (char)'x');")); assertFalse((boolean)exec("def chr = 10; return (chr >= (char)'x');")); assertTrue((boolean)exec("def chr = (char)10; return (chr <= (char)'x');")); assertTrue((boolean)exec("def chr = 10; return (chr < (char)'x');")); assertFalse((boolean)exec("def chr = (char)10; return (chr > (char)'x');")); assertFalse((boolean)exec("def chr = 10L; return (chr > (char)'x');")); assertFalse((boolean)exec("def chr = 10F; return (chr > (char)'x');")); assertFalse((boolean)exec("def chr = 10D; return (chr > (char)'x');")); assertFalse((boolean)exec("def chr = (char)10L; return (chr > (byte)10);")); assertFalse((boolean)exec("def chr = (char)10L; return (chr > (double)(byte)(char)10);")); } // TODO: remove this when the transition from Joda to Java datetimes is completed public void testdefToZonedDateTime() { assertEquals(0L, exec( "Instant instant = Instant.ofEpochMilli(434931330000L);" + "def d = new JodaCompatibleZonedDateTime(instant, ZoneId.of('Z'));" + "def x = new HashMap(); x.put('dt', d);" + "ZonedDateTime t = x['dt'];" + "def y = t;" + "t = y;" + "return ChronoUnit.MILLIS.between(d, t);" )); } }
79.258065
122
0.605298
36b43c8d4ff36c153bd3c1662cb1b1db3ea5c092
13,552
/* * Copyright (c) 2015, salesforce.com, inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided * that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of salesforce.com, inc. nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package com.salesforce.omakase.ast.declaration; import static com.google.common.base.Preconditions.checkNotNull; import static com.salesforce.omakase.broadcast.BroadcastRequirement.REFINED_DECLARATION; import java.io.IOException; import java.util.Optional; import com.google.common.collect.ImmutableList; import com.salesforce.omakase.ast.AbstractSyntax; import com.salesforce.omakase.ast.Status; import com.salesforce.omakase.ast.collection.LinkedSyntaxCollection; import com.salesforce.omakase.ast.collection.SyntaxCollection; import com.salesforce.omakase.broadcast.Broadcaster; import com.salesforce.omakase.broadcast.annotation.Description; import com.salesforce.omakase.broadcast.annotation.Subscribable; import com.salesforce.omakase.writer.StyleAppendable; import com.salesforce.omakase.writer.StyleWriter; /** * The value of a property in a {@link Declaration}. * <p> * This contains a list of {@link Term}s, for example numbers, keywords, functions, hex colors, etc... * <p> * You can add new members to this via {@link #append(PropertyValueMember)}, or by utilizing the {@link SyntaxCollection} returned * by the {@link #members()} method. * <p> * In the CSS 2.1 spec this is called "expr", which is obviously shorthand for "expression", however "expression" is name now * given to multiple syntax units within different CSS3 modules! So that's why this is not called expression. * * @author nmcwilliams * @see Term * @see PropertyValueParser * @see PropertyValueMember */ @Subscribable @Description(value = "interface for all property values", broadcasted = REFINED_DECLARATION) public final class PropertyValue extends AbstractSyntax { private final SyntaxCollection<PropertyValue, PropertyValueMember> members; private transient Declaration declaration; private boolean important; /** Creates a new instance with no line or number specified (used for dynamically created {@link Syntax} units). */ public PropertyValue() { this(-1, -1); } /** * Constructs a new {@link PropertyValue} instance. * @param line * The line number. * @param column * The column number. */ public PropertyValue(int line, int column) { super(line, column); members = new LinkedSyntaxCollection<>(this); } /** * Adds a new {@link PropertyValueMember} to this {@link PropertyValue}. * * @param member * The member to add. * * @return this, for chaining. */ public PropertyValue append(PropertyValueMember member) { members.append(member); return this; } /** * Adds a new {@link Operator} with the given {@link OperatorType}. * * @param type * The {@link OperatorType}. * * @return this, for chaining. */ public PropertyValue append(OperatorType type) { append(new Operator(type)); return this; } /** * Gets the {@link SyntaxCollection} of {@link PropertyValueMember}s. Use this to append, prepend or otherwise reorganize the * terms and operators in this {@link PropertyValue}. * * @return The {@link SyntaxCollection} instance. */ public SyntaxCollection<PropertyValue, PropertyValueMember> members() { return members; } /** * Gets the list of {@link Term}s currently in this {@link PropertyValue} (as opposed to {@link #members()} which returns both * terms and operators). * * @return List of all {@link Term}s. */ public ImmutableList<Term> terms() { ImmutableList.Builder<Term> builder = ImmutableList.builder(); for (PropertyValueMember member : members) { if (member instanceof Term) builder.add((Term)member); } return builder.build(); } /** * Does a quick count of the number of {@link Term}s (does not include operators) within this {@link PropertyValue}. * * @return The number of {@link Term}s. */ public long countTerms() { return members.stream().filter(PropertyValueMember::isTerm).count(); } /** * Gets the <em>textual</em> content of the only {@link Term} within this {@link PropertyValue}. The returned {@link Optional} * will only be present if this {@link PropertyValue} contains exactly one {@link Term}! * <p> * This method may be useful as a generic way of getting the value of unknown or potentially varying term types. * <p> * <b>Important:</b> this is not a substitute or a replica of how the term or this property value will actually be written to * a stylesheet. The textual content returned may not include certain tokens and outer symbols such as hashes, quotes, * parenthesis, etc... . To get the textual content as it would be written to a stylesheet see {@link StyleWriter#writeSingle * (Writable)} instead. However note that you should rarely have need for doing that outside of actually creating stylesheet * output. * <p> * {@link KeywordValue}s will simply return the keyword, {@link StringValue}s will return the contents of the string <b>not * including quotes</b>, functions will return the content of the function not including the parenthesis, {@link * HexColorValue} will return the hex value without the leading '#' , and so on... See each specific {@link Term} * implementation for more details. * <p> * <b>Important:</b> if this property value has more than one term then this method will return an empty {@link Optional}. It * will not concatenate term values. * * @return The textual content, or an empty {@link Optional} if there is more than one or no terms present. * * @see Term#textualValue() */ public Optional<String> singleTextualValue() { ImmutableList<Term> terms = terms(); return terms.size() == 1 ? Optional.of(terms.get(0).textualValue()) : Optional.empty(); } /** * Gets whether this {@link PropertyValue} is marked as "!important". * * @return True if this property value is marked as important. */ public boolean isImportant() { return important; } /** * Sets whether this {@link PropertyValue} is marked as "!important". * * @param important * Whether the value is "!important". * * @return this, for chaining. */ public PropertyValue important(boolean important) { this.important = important; return this; } /** * Sets the parent {@link Declaration}. Generally this is handled automatically when this property value is set on the {@link * Declaration}, so it is not recommended to call this method manually. If you do, results may be unexpected. * * @param parent * The {@link Declaration} that contains this property. */ public void declaration(Declaration parent) { this.declaration = parent; } /** * Gets the parent {@link Declaration} that owns this property. This will not be set for dynamically created property values * not yet added to a {@link Declaration} instance. * * @return The parent {@link Declaration}. If working with this term before it has been properly linked then this may return * null. This is not the case for normal subscription methods. */ public Declaration declaration() { return declaration; } @Override public void propagateBroadcast(Broadcaster broadcaster, Status status) { if (status() == status) { members.propagateBroadcast(broadcaster, status); if (!members.isEmpty()) { super.propagateBroadcast(broadcaster, status); } } } @Override public boolean isWritable() { return super.isWritable() && !members.isEmptyOrNoneWritable(); } @Override public void write(StyleWriter writer, StyleAppendable appendable) throws IOException { PropertyValueMember previous = null; for (PropertyValueMember member : members) { appendable.spaceIf(previous instanceof Term && member instanceof Term); writer.writeInner(member, appendable); previous = member; } if (important) { appendable.spaceIf(writer.isVerbose()).append("!important"); } } @Override public PropertyValue copy() { PropertyValue copy = new PropertyValue().important(important).copiedFrom(this); for (PropertyValueMember member : members) { copy.append(member.copy()); } return copy; } /** * Creates a new {@link PropertyValue} with the given {@link Term} as the only member. * <p> * Example: * <pre> * <code>PropertyValue.of(NumericalValue.of(10, "px"));</code> * </pre> * * @param term * The term. * * @return The new {@link PropertyValue} instance. */ public static PropertyValue of(Term term) { return new PropertyValue().append(checkNotNull(term, "term cannot be null")); } /** * Creates a new {@link PropertyValue} with multiple terms. No operators will be placed between the terms. * <p> * Example: * <pre> * <code>NumericalValue px10 = NumericalValue.of(10, "px"); * NumericalValue em5 = NumericalValue.of(5, "em"); * PropertyValue value = PropertyValue.of(px10, em5); * </code> * </pre> * * @param term * The first term. * @param terms * Additional terms. * * @return The new {@link PropertyValue} instance. */ public static PropertyValue of(Term term, Term... terms) { PropertyValue value = new PropertyValue(); value.append(checkNotNull(term, "the first term cannot be null")); for (Term t : terms) { value.append(checkNotNull(t, "terms cannot be null")); } return value; } /** * Creates a new {@link PropertyValue} with multiple terms separated by the given {@link OperatorType}. * <p> * Example: * <pre> * <code>NumericalValue px10 = NumericalValue.of(10, "px"); * NumericalValue em5 = NumericalValue.of(5, "em"); * PropertyValue value = PropertyValue.of(OperatorType.SLASH, px10, em5); * </code> * </pre> * * @param separator * The {@link OperatorType} to place in between each {@link Term}. * @param term * The first term. * @param terms * Additional terms. * * @return The new {@link PropertyValue} instance. */ public static PropertyValue of(OperatorType separator, Term term, Term... terms) { PropertyValue value = new PropertyValue(); value.append(checkNotNull(term, "the first term cannot be null")); for (Term t : terms) { value.append(separator); value.append(checkNotNull(t, "terms cannot be null")); } return value; } /** * <p> * Creates a new {@link PropertyValue} with one or more terms and operators. * Example: * <pre> * <code>NumericalValue px10 = NumericalValue.of(10, "px"); * NumericalValue em5 = NumericalValue.of(5, "em"); * PropertyValue value = PropertyValue.of(px10, OperatorType.SLASH, em5); * </code> * </pre> * * @param term * The first term. * @param members * The additional terms and operators. * * @return The new {@link PropertyValue} instance. */ public static PropertyValue of(Term term, PropertyValueMember... members) { PropertyValue value = new PropertyValue(); value.append(checkNotNull(term, "the first term cannot be null")); for (PropertyValueMember member : members) { value.append(checkNotNull(member, "members cannot be null")); } return value; } }
37.128767
130
0.659091
6bfb6dc41638e95c3785a3ceabd3177bc547904a
2,649
package com.linkedin.dagli.fasttext; import com.linkedin.dagli.fasttext.anonymized.io.LineReader; import com.linkedin.dagli.fasttext.anonymized.io.BufferedCompressedAndEncryptedLineReader; import com.linkedin.dagli.fasttext.anonymized.io.BufferedCompressedLineReader; import com.linkedin.dagli.fasttext.anonymized.io.BufferedEncryptedLineReader; import com.linkedin.dagli.fasttext.anonymized.io.BufferedLineReader; /** * Determines whether temporary data files created for the FastText model will be compressed and/or encrypted. * * Compression can make sense for slower, spinning disks, where disk I/O across many threads on high-core count * machines becomes a bottleneck. It also reduces the space required on disk. * * Encryption adds computational cost and is only warranted in circumstances where training examples being written to * disk in plaintext poses a security concern. */ public enum FastTextDataSerializationMode { /** * The default behavior. Currently this is identical to NORMAL. */ DEFAULT(false, false), /** * No compression or encryption is used. Recommended if: * (1) You have an SSD or the temporary files are otherwise being written to fast storage (e.g. RAM disk) * (2) You have a small or medium datasets where the data is likely to simply get stored in the RAM disk cache. * (3) Your machine has a relatively low number of cores (the cost of compression would outweigh the reduction in * disk I/O). */ NORMAL(false, false), /** * Data will be compressed. Recommended if you have a very large data set, a spinning disk, and many cores. */ COMPRESSED(true, false), /** * Data will be encrypted using {@link com.linkedin.dagli.util.cryptography.Cryptography}. */ ENCRYPTED(false, true), /** * Data will be both compressed and encrypted. */ COMPRESSED_AND_ENCRYPTED(true, true); private boolean _compressed; private boolean _encrypted; private Class<? extends LineReader> _lineReaderClass; FastTextDataSerializationMode(boolean compressed, boolean encrypted) { _compressed = compressed; _encrypted = encrypted; } public boolean isCompressed() { return _compressed; } public boolean isEncrypted() { return _encrypted; } Class<? extends LineReader> getLineReaderClass() { if (isCompressed() && isEncrypted()) { return BufferedCompressedAndEncryptedLineReader.class; } else if (isCompressed()) { return BufferedCompressedLineReader.class; } else if (isEncrypted()) { return BufferedEncryptedLineReader.class; } else { return BufferedLineReader.class; } } }
33.961538
117
0.739902
ae0c4bccf5e08377c2ccc4c0d720a39d61cbd6f0
6,000
/* * Copyright 2017 huxizhijian * * 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.huxizhijian.hhcomicviewer.adapter; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import org.huxizhijian.hhcomicviewer.model.ComicChapter; import org.huxizhijian.hhcomicviewer.ui.entry.GalleryActivity; import org.huxizhijian.hhcomicviewer.utils.CommonUtils; import org.huxizhijian.hhcomicviewer.utils.Constants; import org.huxizhijian.hhcomicviewer.view.ZoomImageView; import org.huxizhijian.hhcomicviewer.view.listener.OnCenterTapListener; import org.huxizhijian.hhcomicviewer.view.listener.OnLeftOrRightTapListener; import org.huxizhijian.sdk.imageloader.ImageLoaderOptions; import org.huxizhijian.sdk.imageloader.listener.ImageLoaderManager; import java.io.File; import java.util.LinkedList; /** * Gallery的ViewPagerAdapter * Created by wei on 2017/1/21. */ public class GalleryViewPagerAdapter extends PagerAdapter { private GalleryActivity mContext; private ComicChapter mComicChapter; private LinkedList<ZoomImageView> mRecyclerImageViews; private boolean mLoadOnLineFullSizeImage; private OnCenterTapListener onCenterTapListener; private OnLeftOrRightTapListener onLeftOrRightTapListener; //图片加载工具类 private ImageLoaderManager mImageLoader = ImageLoaderOptions.getImageLoaderManager(); public GalleryViewPagerAdapter(GalleryActivity context, boolean loadOnLineFullSizeImage) { mContext = context; mLoadOnLineFullSizeImage = loadOnLineFullSizeImage; } public void setComicChapter(ComicChapter comicChapter) { mComicChapter = comicChapter; } public void setOnLeftOrRightTapListener(OnLeftOrRightTapListener onLeftOrRightTapListener) { this.onLeftOrRightTapListener = onLeftOrRightTapListener; } public void setOnCenterTapListener(OnCenterTapListener onCenterTapListener) { this.onCenterTapListener = onCenterTapListener; } @Override public Object instantiateItem(ViewGroup container, final int position) { ZoomImageView imageView = null; if (mRecyclerImageViews == null) { mRecyclerImageViews = new LinkedList<>(); } if (mRecyclerImageViews.size() > 0) { //复用ImageView imageView = mRecyclerImageViews.removeFirst(); } else { //获得新的ImageView imageView = getImageView(); } //为不同的imageView设置不同图片 setImageViewRecycler(imageView, position); container.addView(imageView); return imageView; } private void setImageViewRecycler(final ZoomImageView imageView, int position) { if (mComicChapter != null && mComicChapter.getDownloadStatus() == Constants.DOWNLOAD_FINISHED) { //如果是下载的章节 File file = new File(mComicChapter.getSavePath(), CommonUtils.getPageName(position)); if (file.exists()) { mImageLoader.displayGallery(mContext, file, imageView); } else { Toast.makeText(mContext, "好像下载错误了~", Toast.LENGTH_SHORT).show(); } } else { //判断用户设置 if (mLoadOnLineFullSizeImage) { //加载全尺寸 if (mComicChapter != null) { mImageLoader.displayGalleryFull(mContext, mComicChapter.getPicList().get(position), imageView); } } else { //图片尺寸匹配屏幕 if (mComicChapter != null) { mImageLoader.displayGalleryFit(mContext, mComicChapter.getPicList().get(position), imageView); } } } } @Override public void destroyItem(ViewGroup container, int position, Object object) { ZoomImageView imageView = (ZoomImageView) object; //设置缩放将图片居中缩放 // imageView.setImageInCenter(); //回收图片 imageView.setImageDrawable(null); imageView.setImageBitmap(null); releaseImageViewResource(imageView); //移除页面 container.removeView(imageView); //回收页面 mRecyclerImageViews.addLast(imageView); } private void releaseImageViewResource(ZoomImageView imageView) { if (imageView == null) return; Drawable drawable = imageView.getDrawable(); if (drawable != null && drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; Bitmap bitmap = bitmapDrawable.getBitmap(); if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); bitmap = null; } } System.gc(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getCount() { return mComicChapter.getPageCount(); } private ZoomImageView getImageView() { ZoomImageView imageView = new ZoomImageView(mContext); if (onCenterTapListener != null) { imageView.setOnCenterTapListener(onCenterTapListener); } if (onLeftOrRightTapListener != null) { imageView.setOnLeftOrRightTapListener(onLeftOrRightTapListener); } return imageView; } }
35.294118
115
0.679
7957c6d7466a1b001420824e86d11d4fcdac5d77
1,425
package com.redescooter.ses.mobile.rps.service.base.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.redescooter.ses.mobile.rps.dao.base.OpeProductionPartsMapper; import com.redescooter.ses.mobile.rps.dm.OpeProductionParts; import org.springframework.stereotype.Service; import javax.annotation.Resource; import com.redescooter.ses.mobile.rps.dao.base.OpeProductionCombinBomMapper; import com.redescooter.ses.mobile.rps.dm.OpeProductionCombinBom; import com.redescooter.ses.mobile.rps.service.base.OpeProductionCombinBomService; import java.util.Collection; /** *@author assert *@date 2021/1/8 13:48 */ @Service public class OpeProductionCombinBomServiceImpl extends ServiceImpl<OpeProductionCombinBomMapper, OpeProductionCombinBom> implements OpeProductionCombinBomService{ @Override public int deleteByPrimaryKey(Long id) { return 0; } @Override public int insert(OpeProductionCombinBom record) { return 0; } @Override public int insertSelective(OpeProductionCombinBom record) { return 0; } @Override public OpeProductionCombinBom selectByPrimaryKey(Long id) { return null; } @Override public int updateByPrimaryKeySelective(OpeProductionCombinBom record) { return 0; } @Override public int updateByPrimaryKey(OpeProductionCombinBom record) { return 0; } }
27.403846
162
0.762807
098121dfeffd5974a9f2477eb3c086ba0530c676
17,561
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.hardware; import static android.view.Display.DEFAULT_DISPLAY; import android.os.RemoteException; import android.os.ServiceManager; import android.view.IRotationWatcher; import android.view.IWindowManager; import android.view.Surface; import java.util.HashMap; import java.util.List; /** * Helper class for implementing the legacy sensor manager API. * @hide */ @SuppressWarnings("deprecation") final class LegacySensorManager { private static boolean sInitialized; private static IWindowManager sWindowManager; private static int sRotation = Surface.ROTATION_0; private final SensorManager mSensorManager; // List of legacy listeners. Guarded by mLegacyListenersMap. private final HashMap<SensorListener, LegacyListener> mLegacyListenersMap = new HashMap<SensorListener, LegacyListener>(); public LegacySensorManager(SensorManager sensorManager) { mSensorManager = sensorManager; synchronized (SensorManager.class) { if (!sInitialized) { sWindowManager = IWindowManager.Stub.asInterface( ServiceManager.getService("window")); if (sWindowManager != null) { // if it's null we're running in the system process // which won't get the rotated values try { sRotation = sWindowManager.watchRotation( new IRotationWatcher.Stub() { public void onRotationChanged(int rotation) { LegacySensorManager.onRotationChanged(rotation); } }, DEFAULT_DISPLAY); } catch (RemoteException e) { } } } } } public int getSensors() { int result = 0; final List<Sensor> fullList = mSensorManager.getFullSensorList(); for (Sensor i : fullList) { switch (i.getType()) { case Sensor.TYPE_ACCELEROMETER: result |= SensorManager.SENSOR_ACCELEROMETER; break; case Sensor.TYPE_MAGNETIC_FIELD: result |= SensorManager.SENSOR_MAGNETIC_FIELD; break; case Sensor.TYPE_ORIENTATION: result |= SensorManager.SENSOR_ORIENTATION | SensorManager.SENSOR_ORIENTATION_RAW; break; } } return result; } public boolean registerListener(SensorListener listener, int sensors, int rate) { if (listener == null) { return false; } boolean result = false; result = registerLegacyListener(SensorManager.SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, listener, sensors, rate) || result; result = registerLegacyListener(SensorManager.SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD, listener, sensors, rate) || result; result = registerLegacyListener(SensorManager.SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION, listener, sensors, rate) || result; result = registerLegacyListener(SensorManager.SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION, listener, sensors, rate) || result; result = registerLegacyListener(SensorManager.SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE, listener, sensors, rate) || result; return result; } private boolean registerLegacyListener(int legacyType, int type, SensorListener listener, int sensors, int rate) { boolean result = false; // Are we activating this legacy sensor? if ((sensors & legacyType) != 0) { // if so, find a suitable Sensor Sensor sensor = mSensorManager.getDefaultSensor(type); if (sensor != null) { // We do all of this work holding the legacy listener lock to ensure // that the invariants around listeners are maintained. This is safe // because neither registerLegacyListener nor unregisterLegacyListener // are called reentrantly while sensors are being registered or unregistered. synchronized (mLegacyListenersMap) { // If we don't already have one, create a LegacyListener // to wrap this listener and process the events as // they are expected by legacy apps. LegacyListener legacyListener = mLegacyListenersMap.get(listener); if (legacyListener == null) { // we didn't find a LegacyListener for this client, // create one, and put it in our list. legacyListener = new LegacyListener(listener); mLegacyListenersMap.put(listener, legacyListener); } // register this legacy sensor with this legacy listener if (legacyListener.registerSensor(legacyType)) { // and finally, register the legacy listener with the new apis result = mSensorManager.registerListener(legacyListener, sensor, rate); } else { result = true; // sensor already enabled } } } } return result; } public void unregisterListener(SensorListener listener, int sensors) { if (listener == null) { return; } unregisterLegacyListener(SensorManager.SENSOR_ACCELEROMETER, Sensor.TYPE_ACCELEROMETER, listener, sensors); unregisterLegacyListener(SensorManager.SENSOR_MAGNETIC_FIELD, Sensor.TYPE_MAGNETIC_FIELD, listener, sensors); unregisterLegacyListener(SensorManager.SENSOR_ORIENTATION_RAW, Sensor.TYPE_ORIENTATION, listener, sensors); unregisterLegacyListener(SensorManager.SENSOR_ORIENTATION, Sensor.TYPE_ORIENTATION, listener, sensors); unregisterLegacyListener(SensorManager.SENSOR_TEMPERATURE, Sensor.TYPE_TEMPERATURE, listener, sensors); } private void unregisterLegacyListener(int legacyType, int type, SensorListener listener, int sensors) { // Are we deactivating this legacy sensor? if ((sensors & legacyType) != 0) { // if so, find the corresponding Sensor Sensor sensor = mSensorManager.getDefaultSensor(type); if (sensor != null) { // We do all of this work holding the legacy listener lock to ensure // that the invariants around listeners are maintained. This is safe // because neither registerLegacyListener nor unregisterLegacyListener // are called re-entrantly while sensors are being registered or unregistered. synchronized (mLegacyListenersMap) { // do we know about this listener? LegacyListener legacyListener = mLegacyListenersMap.get(listener); if (legacyListener != null) { // unregister this legacy sensor and if we don't // need the corresponding Sensor, unregister it too if (legacyListener.unregisterSensor(legacyType)) { // corresponding sensor not needed, unregister mSensorManager.unregisterListener(legacyListener, sensor); // finally check if we still need the legacyListener // in our mapping, if not, get rid of it too. if (!legacyListener.hasSensors()) { mLegacyListenersMap.remove(listener); } } } } } } } static void onRotationChanged(int rotation) { synchronized (SensorManager.class) { sRotation = rotation; } } static int getRotation() { synchronized (SensorManager.class) { return sRotation; } } private static final class LegacyListener implements SensorEventListener { private float[] mValues = new float[6]; private SensorListener mTarget; private int mSensors; private final LmsFilter mYawfilter = new LmsFilter(); LegacyListener(SensorListener target) { mTarget = target; mSensors = 0; } boolean registerSensor(int legacyType) { if ((mSensors & legacyType) != 0) { return false; } boolean alreadyHasOrientationSensor = hasOrientationSensor(mSensors); mSensors |= legacyType; if (alreadyHasOrientationSensor && hasOrientationSensor(legacyType)) { return false; // don't need to re-register the orientation sensor } return true; } boolean unregisterSensor(int legacyType) { if ((mSensors & legacyType) == 0) { return false; } mSensors &= ~legacyType; if (hasOrientationSensor(legacyType) && hasOrientationSensor(mSensors)) { return false; // can't unregister the orientation sensor just yet } return true; } boolean hasSensors() { return mSensors != 0; } private static boolean hasOrientationSensor(int sensors) { return (sensors & (SensorManager.SENSOR_ORIENTATION | SensorManager.SENSOR_ORIENTATION_RAW)) != 0; } public void onAccuracyChanged(Sensor sensor, int accuracy) { try { mTarget.onAccuracyChanged(getLegacySensorType(sensor.getType()), accuracy); } catch (AbstractMethodError e) { // old app that doesn't implement this method // just ignore it. } } public void onSensorChanged(SensorEvent event) { final float[] v = mValues; v[0] = event.values[0]; v[1] = event.values[1]; v[2] = event.values[2]; int type = event.sensor.getType(); int legacyType = getLegacySensorType(type); mapSensorDataToWindow(legacyType, v, LegacySensorManager.getRotation()); if (type == Sensor.TYPE_ORIENTATION) { if ((mSensors & SensorManager.SENSOR_ORIENTATION_RAW) != 0) { mTarget.onSensorChanged(SensorManager.SENSOR_ORIENTATION_RAW, v); } if ((mSensors & SensorManager.SENSOR_ORIENTATION) != 0) { v[0] = mYawfilter.filter(event.timestamp, v[0]); mTarget.onSensorChanged(SensorManager.SENSOR_ORIENTATION, v); } } else { mTarget.onSensorChanged(legacyType, v); } } /* * Helper function to convert the specified sensor's data to the windows's * coordinate space from the device's coordinate space. * * output: 3,4,5: values in the old API format * 0,1,2: transformed values in the old API format * */ private void mapSensorDataToWindow(int sensor, float[] values, int orientation) { float x = values[0]; float y = values[1]; float z = values[2]; switch (sensor) { case SensorManager.SENSOR_ORIENTATION: case SensorManager.SENSOR_ORIENTATION_RAW: z = -z; break; case SensorManager.SENSOR_ACCELEROMETER: x = -x; y = -y; z = -z; break; case SensorManager.SENSOR_MAGNETIC_FIELD: x = -x; y = -y; break; } values[0] = x; values[1] = y; values[2] = z; values[3] = x; values[4] = y; values[5] = z; if ((orientation & Surface.ROTATION_90) != 0) { // handles 90 and 270 rotation switch (sensor) { case SensorManager.SENSOR_ACCELEROMETER: case SensorManager.SENSOR_MAGNETIC_FIELD: values[0] = -y; values[1] = x; values[2] = z; break; case SensorManager.SENSOR_ORIENTATION: case SensorManager.SENSOR_ORIENTATION_RAW: values[0] = x + ((x < 270) ? 90 : -270); values[1] = z; values[2] = y; break; } } if ((orientation & Surface.ROTATION_180) != 0) { x = values[0]; y = values[1]; z = values[2]; // handles 180 (flip) and 270 (flip + 90) rotation switch (sensor) { case SensorManager.SENSOR_ACCELEROMETER: case SensorManager.SENSOR_MAGNETIC_FIELD: values[0] = -x; values[1] = -y; values[2] = z; break; case SensorManager.SENSOR_ORIENTATION: case SensorManager.SENSOR_ORIENTATION_RAW: values[0] = (x >= 180) ? (x - 180) : (x + 180); values[1] = -y; values[2] = -z; break; } } } private static int getLegacySensorType(int type) { switch (type) { case Sensor.TYPE_ACCELEROMETER: return SensorManager.SENSOR_ACCELEROMETER; case Sensor.TYPE_MAGNETIC_FIELD: return SensorManager.SENSOR_MAGNETIC_FIELD; case Sensor.TYPE_ORIENTATION: return SensorManager.SENSOR_ORIENTATION_RAW; case Sensor.TYPE_TEMPERATURE: return SensorManager.SENSOR_TEMPERATURE; } return 0; } } private static final class LmsFilter { private static final int SENSORS_RATE_MS = 20; private static final int COUNT = 12; private static final float PREDICTION_RATIO = 1.0f / 3.0f; private static final float PREDICTION_TIME = (SENSORS_RATE_MS * COUNT / 1000.0f) * PREDICTION_RATIO; private float[] mV = new float[COUNT * 2]; private long[] mT = new long[COUNT * 2]; private int mIndex; public LmsFilter() { mIndex = COUNT; } public float filter(long time, float in) { float v = in; final float ns = 1.0f / 1000000000.0f; float v1 = mV[mIndex]; if ((v - v1) > 180) { v -= 360; } else if ((v1 - v) > 180) { v += 360; } /* Manage the circular buffer, we write the data twice spaced * by COUNT values, so that we don't have to copy the array * when it's full */ mIndex++; if (mIndex >= COUNT * 2) { mIndex = COUNT; } mV[mIndex] = v; mT[mIndex] = time; mV[mIndex - COUNT] = v; mT[mIndex - COUNT] = time; float A, B, C, D, E; float a, b; int i; A = B = C = D = E = 0; for (i = 0; i < COUNT - 1; i++) { final int j = mIndex - 1 - i; final float Z = mV[j]; final float T = (mT[j] / 2 + mT[j + 1] / 2 - time) * ns; float dT = (mT[j] - mT[j + 1]) * ns; dT *= dT; A += Z * dT; B += T * (T * dT); C += (T * dT); D += Z * (T * dT); E += dT; } b = (A * B + C * D) / (E * B + C * C); a = (E * b - A) / C; float f = b + PREDICTION_TIME * a; // Normalize f *= (1.0f / 360.0f); if (((f >= 0) ? f : -f) >= 0.5f) { f = f - (float) Math.ceil(f + 0.5f) + 1.0f; } if (f < 0) { f += 1.0f; } f *= 360.0f; return f; } } }
40.002278
97
0.526678
ebe9f49208e0684095b2f540bbc95b082c084a9c
2,560
package org.oagi.score.repo.component.acc; import org.oagi.score.service.common.data.OagisComponentType; import org.oagi.score.data.RepositoryRequest; import org.springframework.security.core.AuthenticatedPrincipal; import java.math.BigInteger; import java.time.LocalDateTime; public class UpdateAccPropertiesRepositoryRequest extends RepositoryRequest { private final BigInteger accManifestId; private String objectClassTerm; private String definition; private String definitionSource; private OagisComponentType componentType; private boolean isAbstract; private boolean deprecated; private BigInteger namespaceId; public UpdateAccPropertiesRepositoryRequest(AuthenticatedPrincipal user, BigInteger accManifestId) { super(user); this.accManifestId = accManifestId; } public UpdateAccPropertiesRepositoryRequest(AuthenticatedPrincipal user, LocalDateTime localDateTime, BigInteger accManifestId) { super(user, localDateTime); this.accManifestId = accManifestId; } public BigInteger getAccManifestId() { return accManifestId; } public String getObjectClassTerm() { return objectClassTerm; } public void setObjectClassTerm(String objectClassTerm) { this.objectClassTerm = objectClassTerm; } public String getDefinition() { return definition; } public void setDefinition(String definition) { this.definition = definition; } public String getDefinitionSource() { return definitionSource; } public void setDefinitionSource(String definitionSource) { this.definitionSource = definitionSource; } public OagisComponentType getComponentType() { return componentType; } public void setComponentType(OagisComponentType componentType) { this.componentType = componentType; } public boolean isAbstract() { return isAbstract; } public void setAbstract(boolean isAbstract) { this.isAbstract = isAbstract; } public boolean isDeprecated() { return deprecated; } public void setDeprecated(boolean deprecated) { this.deprecated = deprecated; } public BigInteger getNamespaceId() { return namespaceId; } public void setNamespaceId(BigInteger namespaceId) { this.namespaceId = namespaceId; } }
26.947368
77
0.677344
5271a85dec70566da298091ff5c80dfa18ff25fd
9,006
// Copyright (C) 2002 IAIK // http://jce.iaik.at // // Copyright (C) 2003 - 2015 Stiftung Secure Information and // Communication Technologies SIC // http://www.sic.st // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. package demo.pkcs.pkcs11.provider.utils; import iaik.asn1.ObjectID; import iaik.asn1.structures.AlgorithmID; import iaik.asn1.structures.Name; import iaik.x509.X509Certificate; import iaik.x509.ocsp.BasicOCSPResponse; import iaik.x509.ocsp.CertStatus; import iaik.x509.ocsp.OCSPException; import iaik.x509.ocsp.OCSPRequest; import iaik.x509.ocsp.OCSPResponse; import iaik.x509.ocsp.Request; import iaik.x509.ocsp.ResponderID; import iaik.x509.ocsp.SingleResponse; import iaik.x509.ocsp.UnknownInfo; import iaik.x509.ocsp.extensions.ServiceLocator; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SignatureException; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class CreateOCSPResponse { /** * Creates an ocsp response answering the given ocsp request. * * @param is * the encoded OCSP request supplied from an input stream * @param requestorKey * the signing key of the requestor (may be supplied for allowing to verify a signed * request with no certificates included) * @param includeExtensions * if extensions shall be included * @return the DER encoded OCSPResponse */ public static OCSPResponse createOCSPResponse(OCSPRequest ocspRequest, PublicKey requestorKey, X509Certificate[] responderCerts) { OCSPResponse ocspResponse = null; // first parse the request int responseStatus = OCSPResponse.successful; System.out.println("Parsing request..."); try { if (ocspRequest.containsSignature()) { System.out.println("Request is signed."); boolean signatureOk = false; if (requestorKey != null) { System.out.println("Verifying signature using supplied requestor key."); try { ocspRequest.verify(requestorKey); signatureOk = true; System.out.println("Signature ok"); } catch (Exception ex) { } } if (!signatureOk && ocspRequest.containsCertificates()) { System.out.println("Verifying signature with included signer cert..."); X509Certificate signerCert = ocspRequest.verify(); System.out.println("Signature ok from request signer " + signerCert.getSubjectDN()); signatureOk = true; } if (!signatureOk) { System.out .println("Request signed but cannot verify signature since missing signer key. Sending malformed request!"); responseStatus = OCSPResponse.malformedRequest; } } else { System.out.println("Unsigned request!"); } } catch (NoSuchAlgorithmException ex) { System.out.println("Cannot verify; sending internalError: " + ex.getMessage()); responseStatus = OCSPResponse.internalError; } catch (OCSPException ex) { System.out .println("Included certs do not belong to signer; sending malformedRequest : " + ex.getMessage()); responseStatus = OCSPResponse.malformedRequest; } catch (InvalidKeyException ex) { System.out.println("Signer key invalid; sending malformedRequest : " + ex.getMessage()); responseStatus = OCSPResponse.malformedRequest; } catch (SignatureException ex) { System.out.println("Signature verification error; sending malformedRequest : " + ex.getMessage()); responseStatus = OCSPResponse.malformedRequest; } catch (Exception ex) { ex.printStackTrace(); System.out .println("Some error occured during request parsing/verification; sending tryLater " + ex.getMessage()); responseStatus = OCSPResponse.tryLater; } if (responseStatus != OCSPResponse.successful) { return new OCSPResponse(responseStatus); } try { // does client understand Basic OCSP response type? ObjectID[] accepatablResponseTypes = ocspRequest.getAccepatableResponseTypes(); if ((accepatablResponseTypes != null) && (accepatablResponseTypes.length > 0)) { boolean supportsBasic = false; for (int i = 0; i < accepatablResponseTypes.length; i++) { if (accepatablResponseTypes[i].equals(BasicOCSPResponse.responseType)) { supportsBasic = true; break; } } if (!supportsBasic) { // what to do if client does not support basic OCSP response type?? // we send an basic response anyway, since there seems to be no proper status message System.out .println("Warning! Client does not support basic response type. Using it anyway..."); } } } catch (Exception ex) { // ignore this } // successfull ocspResponse = new OCSPResponse(OCSPResponse.successful); // now we build the basic ocsp response BasicOCSPResponse basicOCSPResponse = new BasicOCSPResponse(); try { // responder ID ResponderID responderID = new ResponderID((Name) responderCerts[0].getSubjectDN()); basicOCSPResponse.setResponderID(responderID); GregorianCalendar date = new GregorianCalendar(); // producedAt date Date producedAt = date.getTime(); basicOCSPResponse.setProducedAt(producedAt); // thisUpdate date Date thisUpdate = date.getTime(); // nextUpdate date date.add(Calendar.MONTH, 1); Date nextUpdate = date.getTime(); // archiveCutoff date.add(Calendar.YEAR, -3); // create the single responses for requests included Request[] requests = ocspRequest.getRequestList(); SingleResponse[] singleResponses = new SingleResponse[requests.length]; for (int i = 0; i < requests.length; i++) { Request request = requests[i]; CertStatus certStatus = null; // check the service locator ServiceLocator serviceLocator = request.getServiceLocator(); if (serviceLocator != null) { System.out.println("Request No. " + i + " contains the ServiceLocator extension:"); System.out.println(serviceLocator + "\n"); Name issuer = serviceLocator.getIssuer(); if (!issuer.equals(responderCerts[0].getSubjectDN())) { // client does not trust our responder; but we are not able to forward it // --> CertStatus unknown certStatus = new CertStatus(new UnknownInfo()); } } if (certStatus == null) { // here now the server checks the status of the cert // we only can give information about one cert // we assume "good" here certStatus = new CertStatus(); } singleResponses[i] = new SingleResponse(request.getReqCert(), certStatus, thisUpdate); singleResponses[i].setNextUpdate(nextUpdate); } // set the single responses basicOCSPResponse.setSingleResponses(singleResponses); } catch (Exception ex) { ex.printStackTrace(); System.out.println("Some error occured; sending tryLater " + ex.getMessage()); return new OCSPResponse(OCSPResponse.tryLater); } basicOCSPResponse.setCertificates(new X509Certificate[] { responderCerts[0] }); ocspResponse.setResponse(basicOCSPResponse); return ocspResponse; } }
38.161017
122
0.677215