hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
9236a3857c92c4a0b541571b3a2c679c6dee69b3
676
java
Java
play_with_data_structure/Array/src/Student.java
marchboy/data_structure
9c085a70f4d2e8b3a0a2a968753f8dbb3a3345e0
[ "Apache-2.0" ]
null
null
null
play_with_data_structure/Array/src/Student.java
marchboy/data_structure
9c085a70f4d2e8b3a0a2a968753f8dbb3a3345e0
[ "Apache-2.0" ]
null
null
null
play_with_data_structure/Array/src/Student.java
marchboy/data_structure
9c085a70f4d2e8b3a0a2a968753f8dbb3a3345e0
[ "Apache-2.0" ]
null
null
null
25.037037
74
0.62426
997,756
package play_with_data_structure.Array.src; public class Student{ public String name; private int score; public Student(String studentName, int studentScore){ name = studentName; score = studentScore; } @Override public String toString(){ return String.format("Student(name: %s, score: %s)", name, score); } public static void main(String[] args){ ArrayGeneric<Student> arr = new ArrayGeneric<>(); arr.addLast(new Student("Alice", 100)); arr.addLast(new Student("Bob", 99)); arr.addLast(new Student("Charlie", 98)); System.out.println("All Student scores: " + arr); } }
9236a457ff46492297bb73ecdc7ea3cb93cd1c4f
1,933
java
Java
graphml2sbgnml/graphml2sbgnml-cli/src/main/java/org/eisbm/graphml2sbgnml/cli/Graphml2sbgnml.java
eisbm/GraphML2SBGNML
db56aeec3b38ee9222b89773f73b39910409bb28
[ "MIT" ]
1
2019-11-15T12:48:26.000Z
2019-11-15T12:48:26.000Z
graphml2sbgnml/graphml2sbgnml-cli/src/main/java/org/eisbm/graphml2sbgnml/cli/Graphml2sbgnml.java
eisbm/GraphML2SBGNML
db56aeec3b38ee9222b89773f73b39910409bb28
[ "MIT" ]
5
2018-03-09T13:56:28.000Z
2018-04-28T00:00:25.000Z
graphml2sbgnml/graphml2sbgnml-cli/src/main/java/org/eisbm/graphml2sbgnml/cli/Graphml2sbgnml.java
eisbm/GraphML2SBGNML
db56aeec3b38ee9222b89773f73b39910409bb28
[ "MIT" ]
null
null
null
30.203125
100
0.6627
997,757
package org.eisbm.graphml2sbgnml.cli; import org.eisbm.graphmlsbfc.GraphML2SBGNML; import org.eisbm.graphmlsbfc.GraphMLModel; import org.sbfc.converter.exceptions.ConversionException; import org.sbfc.converter.exceptions.ReadModelException; import org.sbfc.converter.exceptions.WriteModelException; import org.sbfc.converter.models.SBGNModel; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.beust.jcommander.Parameter; import com.beust.jcommander.JCommander; public class Graphml2sbgnml { @Parameter(names = { "-i", "--input"}, required = true) String inputFileName; @Parameter(names = { "-o", "--output" }, required = true) String outputFileName; @Parameter(names = { "-c", "--conf", "--configuration" }, required = true) String configFileName; public static void main(String[] args) { Logger logger = LoggerFactory.getLogger(Graphml2sbgnml.class); Graphml2sbgnml app = new Graphml2sbgnml(); JCommander.newBuilder() .addObject(app) .build() .parse(args); convert(app.inputFileName, app.outputFileName, app.configFileName); } public static void convert(String inputFileName, String outputFileName, String configFileName) { GraphMLModel gModel = new GraphMLModel(); try { gModel.setModelFromFile(inputFileName); } catch (ReadModelException e) { e.printStackTrace(); } GraphML2SBGNML converter = new GraphML2SBGNML(configFileName); SBGNModel sbgnModel = new SBGNModel(); try { sbgnModel = (SBGNModel) converter.convert(gModel); } catch (ConversionException | ReadModelException e) { e.printStackTrace(); } try { sbgnModel.modelToFile(outputFileName); } catch (WriteModelException e) { e.printStackTrace(); } } }
9236a47b5995afcd6498f3c3d5c4328c3d830d49
1,953
java
Java
services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/S3CrtAsyncClient.java
cjolivier01/aws-sdk-java-v2
9050b7d6fabcdae18ad016994f4acfabf78b1780
[ "Apache-2.0" ]
1
2022-02-04T07:33:51.000Z
2022-02-04T07:33:51.000Z
services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/S3CrtAsyncClient.java
cjolivier01/aws-sdk-java-v2
9050b7d6fabcdae18ad016994f4acfabf78b1780
[ "Apache-2.0" ]
null
null
null
services-custom/s3-transfer-manager/src/main/java/software/amazon/awssdk/transfer/s3/internal/S3CrtAsyncClient.java
cjolivier01/aws-sdk-java-v2
9050b7d6fabcdae18ad016994f4acfabf78b1780
[ "Apache-2.0" ]
null
null
null
36.849057
126
0.768049
997,758
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 software.amazon.awssdk.transfer.s3.internal; import software.amazon.awssdk.annotations.SdkInternalApi; import software.amazon.awssdk.auth.credentials.AwsCredentialsProvider; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3AsyncClient; import software.amazon.awssdk.utils.builder.SdkBuilder; /** * Service client for accessing Amazon S3 asynchronously using the AWS Common Runtime S3 client. This can be created using the * static {@link #builder()} method. */ @SdkInternalApi public interface S3CrtAsyncClient extends S3AsyncClient { interface S3CrtAsyncClientBuilder extends SdkBuilder<S3CrtAsyncClientBuilder, S3CrtAsyncClient> { S3CrtAsyncClientBuilder credentialsProvider(AwsCredentialsProvider credentialsProvider); S3CrtAsyncClientBuilder region(Region region); S3CrtAsyncClientBuilder minimumPartSizeInBytes(Long uploadPartSize); S3CrtAsyncClientBuilder targetThroughputInGbps(Double targetThroughputInGbps); S3CrtAsyncClientBuilder maxConcurrency(Integer maxConcurrency); @Override S3CrtAsyncClient build(); } /** * Create a builder that can be used to configure and create a {@link S3AsyncClient}. */ static S3CrtAsyncClientBuilder builder() { return new DefaultS3CrtAsyncClient.DefaultS3CrtClientBuilder(); } }
9236a4ce74c02ce5852a6fdb33d48948a0354844
382
java
Java
xfire-core/src/test/org/codehaus/xfire/util/ServiceUtilsTest.java
eduardodaluz/xfire
e4e9723991692a0e4fab500e979bf48b8dd25caf
[ "MIT" ]
null
null
null
xfire-core/src/test/org/codehaus/xfire/util/ServiceUtilsTest.java
eduardodaluz/xfire
e4e9723991692a0e4fab500e979bf48b8dd25caf
[ "MIT" ]
3
2022-01-27T16:23:45.000Z
2022-01-27T16:24:10.000Z
xfire-core/src/test/org/codehaus/xfire/util/ServiceUtilsTest.java
eduardodaluz/xfire
e4e9723991692a0e4fab500e979bf48b8dd25caf
[ "MIT" ]
null
null
null
20.105263
78
0.696335
997,759
package org.codehaus.xfire.util; /** * @author Arjen Poutsma */ import junit.framework.TestCase; public class ServiceUtilsTest extends TestCase { public void testMakeServiceNameFromClassName() throws Exception { String result = ServiceUtils.makeServiceNameFromClassName(getClass()); assertEquals("ServiceUtilsTest", result); } }
9236a5eda60a9d0cd5e6f7bc0be732c95eb87c2d
2,682
java
Java
webapp/src/main/java/com/github/chenjianjx/srb4jfullsample/webapp/fo/rest/support/FoCorsFilter.java
chenjianjx/srb4jfullsample
ddccb7dcdcc1e508c3798d3b054a5351ed034c13
[ "Apache-2.0" ]
2
2016-01-21T05:33:55.000Z
2017-11-15T03:11:50.000Z
webapp/src/main/java/com/github/chenjianjx/srb4jfullsample/webapp/fo/rest/support/FoCorsFilter.java
chenjianjx/srb4jfullsample
ddccb7dcdcc1e508c3798d3b054a5351ed034c13
[ "Apache-2.0" ]
5
2020-03-04T22:23:06.000Z
2021-01-20T23:31:22.000Z
webapp/src/main/java/com/github/chenjianjx/srb4jfullsample/webapp/fo/rest/support/FoCorsFilter.java
chenjianjx/srb4jfullsample
ddccb7dcdcc1e508c3798d3b054a5351ed034c13
[ "Apache-2.0" ]
2
2016-01-21T13:04:03.000Z
2016-01-28T05:49:52.000Z
31.186047
139
0.752051
997,760
package com.github.chenjianjx.srb4jfullsample.webapp.fo.rest.support; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * * * */ @Provider @Component public class FoCorsFilter implements ContainerResponseFilter { /** * * Note: an element can be the wildcard (*) */ private List<String> corsAllowedOrigins; @Override public void filter(ContainerRequestContext request, ContainerResponseContext response) { String responseOriginHeader = decideResponseOriginHeader(corsAllowedOrigins, request.getHeaderString("Origin")); if (responseOriginHeader == null) { return; } MultivaluedMap<String, Object> headers = response.getHeaders(); headers.add("Access-Control-Allow-Origin", responseOriginHeader); headers.add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD"); headers.add( "Access-Control-Allow-Headers", "Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"); headers.add("Access-Control-Expose-Headers", "WWW-Authenticate"); } /** * It can return null. If null value is returned, it means there should not be cors headers in the response * * @return */ String decideResponseOriginHeader(List<String> allowed, String origin) { if (allowed == null || allowed.isEmpty()) { return null; } if (allowed.contains("*")) { return "*"; } if (allowed.contains(origin)) { return origin; } return null; } @Value("${corsAllowedOrigins}") public void setCorsAllowedOrigins(String corsAllowedOriginsStr) { List<String> corsAllowedOrigins = parseCorsAllowedOrigins(corsAllowedOriginsStr); this.corsAllowedOrigins = corsAllowedOrigins; } List<String> parseCorsAllowedOrigins(String corsAllowedOriginsStr) { List<String> resultList = new ArrayList<>(); corsAllowedOriginsStr = StringUtils.trimToNull(corsAllowedOriginsStr); String[] originArray = StringUtils.split(corsAllowedOriginsStr, ";"); if(originArray == null || originArray.length == 0){ return resultList; } resultList = Arrays.asList(originArray).stream().map(o -> StringUtils.trimToNull(o)).filter(o -> o != null).collect(Collectors.toList()); return resultList; } }
9236a72fab9d53db342e8d0ec9159294673bc2b9
1,736
java
Java
src/main/java/com/jpa/springdatajpalearning/demo1/controller/UserController.java
HCF1998/spring-data-jpa-learning
48b959d14120e73de2c93d1b720733fd4429a94e
[ "MIT" ]
null
null
null
src/main/java/com/jpa/springdatajpalearning/demo1/controller/UserController.java
HCF1998/spring-data-jpa-learning
48b959d14120e73de2c93d1b720733fd4429a94e
[ "MIT" ]
null
null
null
src/main/java/com/jpa/springdatajpalearning/demo1/controller/UserController.java
HCF1998/spring-data-jpa-learning
48b959d14120e73de2c93d1b720733fd4429a94e
[ "MIT" ]
null
null
null
31.563636
94
0.72235
997,761
package com.jpa.springdatajpalearning.demo1.controller; import com.jpa.springdatajpalearning.demo1.entity.User; import com.jpa.springdatajpalearning.demo1.repository.UserCrudRepository; import com.jpa.springdatajpalearning.demo1.repository.UserPageRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping(path = "/demo01") public class UserController { @Autowired private UserCrudRepository userCrudRepository; @Autowired private UserPageRepository userPageRepository; @GetMapping("/addUser") public void addUser(@RequestParam String name, @RequestParam String email) { User user = new User(); user.setName(name); user.setEmail(email); userCrudRepository.save(user); } @GetMapping("/all") public Iterable<User> getAllUser() { return userCrudRepository.findAll(); } @GetMapping("/info") public User getOne(@RequestParam Long id) { return userCrudRepository.findById(id).get(); } @DeleteMapping("/delete") public void delete(@RequestParam Long id) { userCrudRepository.deleteById(id); } @GetMapping("/page") public Page<User> getAllUserByPage() { Sort sort = Sort.by(Sort.Direction.ASC, "name"); return userPageRepository.findAll(PageRequest.of(1, 20, sort)); } @GetMapping("/sort") public Iterable<User> getAllUsersWithSort(){ return userPageRepository.findAll(Sort.by(new Sort.Order(Sort.Direction.ASC,"name"))); } }
9236aa2fd9e80b843ad86c17fbd3054fc1b158bb
4,521
java
Java
app/src/main/java/com/zhao/myreader/webapi/CommonApi.java
simon2077/MissZzzReader
838783ab5d7cb81934b60493e6116b76caf4aa61
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/zhao/myreader/webapi/CommonApi.java
simon2077/MissZzzReader
838783ab5d7cb81934b60493e6116b76caf4aa61
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/zhao/myreader/webapi/CommonApi.java
simon2077/MissZzzReader
838783ab5d7cb81934b60493e6116b76caf4aa61
[ "Apache-2.0" ]
null
null
null
28.25625
102
0.587038
997,763
package com.zhao.myreader.webapi; import com.zhao.myreader.callback.ResultCallback; import com.zhao.myreader.common.URLCONST; import com.zhao.myreader.greendao.entity.Book; import com.zhao.myreader.util.crawler.BiQuGeReadUtil; import com.zhao.myreader.util.crawler.DingDianReadUtil; import com.zhao.myreader.util.crawler.TianLaiReadUtil; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; /** * Created by zhao on 2017/7/24. */ public class CommonApi extends BaseApi{ /** * 获取章节列表 * @param book * @param callback */ public static void getBookChapters(Book book, final ResultCallback callback){ getCommonReturnHtmlStringApi(book.getChapterUrl(), null, "GBK", new ResultCallback() { @Override public void onFinish(Object o, int code) { callback.onFinish(TianLaiReadUtil.getChaptersFromHtml((String) o,book),0); } @Override public void onError(Exception e) { callback.onError(e); } }); } /** * 获取章节正文 * @param url * @param callback */ public static void getChapterContent(String url, final ResultCallback callback){ int tem = url.indexOf("\""); if (tem != -1){ url = url.substring(0,tem); } if (!url.contains("http")){ url = URLCONST.nameSpace_tianlai + url; } getCommonReturnHtmlStringApi(url, null, "GBK", new ResultCallback() { @Override public void onFinish(Object o, int code) { callback.onFinish(TianLaiReadUtil.getContentFormHtml((String)o),0); } @Override public void onError(Exception e) { callback.onError(e); } }); } /** * 搜索小说(天籁) * @param key * @param callback */ public static void searchTl(String key, final ResultCallback callback){ Map<String,Object> params = new HashMap<>(); try { params.put("searchkey", URLEncoder.encode(key,"GB2312")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } getCommonReturnHtmlStringApi(URLCONST.method_tl_search, params, "gbk", new ResultCallback() { @Override public void onFinish(Object o, int code) { callback.onFinish(TianLaiReadUtil.getBooksFromSearchHtml((String)o),code); } @Override public void onError(Exception e) { callback.onError(e); } }); } /** * 搜索小说(笔趣阁) * @param key * @param callback */ public static void searchBqg(String key, final ResultCallback callback){ Map<String,Object> params = new HashMap<>(); try { params.put("searchkey", URLEncoder.encode(key,"GB2312")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } getCommonReturnHtmlStringApi(URLCONST.method_bqg_search, params, "GBK", new ResultCallback() { @Override public void onFinish(Object o, int code) { callback.onFinish(BiQuGeReadUtil.getBooksFromSearchHtml((String)o),code); } @Override public void onError(Exception e) { callback.onError(e); } }); } /** * 搜索小说(顶点小说) * @param key * @param callback */ public static void searchDdxs(String key, final ResultCallback callback){ Map<String,Object> params = new HashMap<>(); try { params.put("searchkey", URLEncoder.encode(key,"GB2312")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } params.put("searchtype", "articlename"); getCommonReturnHtmlStringApi(URLCONST.method_dd_search, params, "GBK", new ResultCallback() { @Override public void onFinish(Object o, int code) { callback.onFinish(DingDianReadUtil.getBooksFromSearchHtml((String)o),code); } @Override public void onError(Exception e) { callback.onError(e); } }); } public static void getNewestAppVersion(final ResultCallback callback){ getCommonReturnStringApi(URLCONST.method_getCurAppVersion,null,callback); } }
9236aab5c0495962bf48b6efa514cd9d722a1acc
10,403
java
Java
yawp-core/src/main/java/io/yawp/repository/query/QueryBuilder.java
feroult/yawp
a415710efce1aa25ad3bade754b8b57ed398f36e
[ "MIT" ]
138
2015-06-11T16:41:59.000Z
2021-11-12T12:26:11.000Z
yawp-core/src/main/java/io/yawp/repository/query/QueryBuilder.java
feroult/yawp
a415710efce1aa25ad3bade754b8b57ed398f36e
[ "MIT" ]
124
2015-04-23T12:39:38.000Z
2022-01-22T02:50:40.000Z
yawp-core/src/main/java/io/yawp/repository/query/QueryBuilder.java
feroult/yawp
a415710efce1aa25ad3bade754b8b57ed398f36e
[ "MIT" ]
32
2015-08-04T14:44:19.000Z
2022-02-21T20:14:29.000Z
21.809224
140
0.68884
997,764
package io.yawp.repository.query; import io.yawp.repository.IdRef; import io.yawp.repository.Repository; import io.yawp.repository.hooks.RepositoryHooks; import io.yawp.repository.models.ObjectModel; import io.yawp.repository.query.condition.BaseCondition; import io.yawp.repository.query.condition.Condition; import io.yawp.repository.query.condition.SimpleCondition; import java.util.*; import java.util.stream.Collectors; import static java.util.stream.Collectors.toList; public class QueryBuilder<T> { private Class<T> clazz; private ObjectModel model; private Repository r; private IdRef<?> parentId; private BaseCondition condition; private List<QueryOrder> preOrders = new ArrayList<>(); private List<QueryOrder> postOrders = new ArrayList<>(); private Integer limit; private String cursor; private Map<QueryType, Object> forcedResults = new HashMap<>(); // results private QueryType executedQueryType; private Object executedResponse; private QueryBuilder(Class<T> clazz, Repository r) { this.clazz = clazz; this.r = r; this.model = new ObjectModel(clazz); } public static <T> QueryBuilder<T> q(Class<T> clazz, Repository r) { return new QueryBuilder<>(clazz, r); } public <N> QueryTransformer<T, N> transform(String transformName) { return new QueryTransformer<>(this, transformName); } public QueryBuilder<T> and(String field, String operator, Object value) { return where(field, operator, value); } public QueryBuilder<T> where(String field, String operator, Object value) { return where(Condition.c(field, operator, value)); } public QueryBuilder<T> where(BaseCondition c) { if (condition == null) { condition = c; } else { condition = Condition.and(condition, c); } condition.init(r, clazz); return this; } public QueryBuilder<T> and(BaseCondition c) { return where(c); } public QueryBuilder<T> from(IdRef<?> parentId) { if (parentId == null) { this.parentId = null; return this; } this.parentId = parentId; return this; } public QueryBuilder<T> order(String property) { order(property, null); return this; } public QueryBuilder<T> order(String property, String direction) { preOrders.add(new QueryOrder(null, property, direction)); return this; } public QueryBuilder<T> sort(String property) { sort(property, null); return this; } public QueryBuilder<T> sort(String property, String direction) { sort(null, property, direction); return this; } public QueryBuilder<T> sort(String entity, String property, String direction) { postOrders.add(new QueryOrder(entity, property, direction)); return this; } public QueryBuilder<T> limit(int limit) { this.limit = limit; return this; } public QueryBuilder<T> cursor(String cursor) { this.cursor = cursor; return this; } public IdRef<?> getParentId() { return parentId; } public String getCursor() { return this.cursor; } public void setCursor(String cursor) { this.cursor = cursor; } public QueryType getExecutedQueryType() { return executedQueryType; } public Object getExecutedResponse() { return executedResponse; } public QueryBuilder<T> options(QueryOptions options) { if (options.getCondition() != null) { where(options.getCondition()); } if (options.getPreOrders() != null) { preOrders.addAll(options.getPreOrders()); } if (options.getPostOrders() != null) { postOrders.addAll(options.getPostOrders()); } if (options.getLimit() != null) { limit(options.getLimit()); } if (options.getCursor() != null) { cursor(options.getCursor()); } return this; } public Integer getLimit() { return limit; } public List<QueryOrder> getPreOrders() { return preOrders; } public BaseCondition getCondition() { return condition; } public Repository getRepository() { return this.r; } public ObjectModel getModel() { return model; } public QueryBuilder<T> forceResult(QueryType type, Object object) { forcedResults.put(type, object); return this; } public Object getForcedResult(QueryType type) { return forcedResults.get(type); } @SuppressWarnings("unchecked") private List<T> getForcedResultList() { return (List<T>) getForcedResult(QueryType.LIST); } @SuppressWarnings("unchecked") private List<IdRef<T>> getForcedResultIds() { return (List<IdRef<T>>) getForcedResult(QueryType.IDS); } @SuppressWarnings("unchecked") private T getForcedResultFetch() { return (T) getForcedResult(QueryType.FETCH); } public QueryBuilder<T> clearForcedResult(QueryType type) { forcedResults.remove(type); return this; } public QueryBuilder<T> clearForcedResults() { forcedResults.clear(); return this; } public boolean hasForcedResponse(QueryType type) { return forcedResults.containsKey(type); } public boolean hasForcedResponse() { return forcedResults.size() > 0; } public List<T> executeQueryList() { r.namespace().set(getClazz()); try { return executeQuery(); } finally { r.namespace().reset(); } } public List<T> list() { List<T> list = executeQueryList(); sortList(list); return list; } public T first() { r.namespace().set(getClazz()); try { if (isQueryById()) { return executeQueryById(); } return executeQueryFirst(); } finally { r.namespace().reset(); } } private T executeQueryFirst() { limit(1); List<T> list = executeQuery(); if (list.size() == 0) { return null; } return list.get(0); } public T only() throws NoResultException, MoreThanOneResultException { r.namespace().set(getClazz()); try { T object; if (isQueryById()) { object = executeQueryById(); } else { object = executeQueryOnly(); } if (object == null) { throw new NoResultException(); } return object; } finally { r.namespace().reset(); } } private T executeQueryOnly() throws MoreThanOneResultException { List<T> list = executeQuery(); if (list.size() == 0) { throw new NoResultException(); } if (list.size() == 1) { return list.get(0); } throw new MoreThanOneResultException(); } private List<T> executeQuery() { executedQueryType = QueryType.LIST; RepositoryHooks.beforeQuery(this); List<T> list = hasForcedResponse(executedQueryType) ? getForcedResultList() : doExecuteQuery(); executedResponse = list; RepositoryHooks.afterQuery(this); return postFilter(list); } private List<T> doExecuteQuery() { return r.driver().query().objects(this); } private List<T> postFilter(List<T> objects) { if (!hasPostFilter()) { return objects; } return condition.applyPostFilter(objects); } private boolean hasPostFilter() { return condition != null && condition.hasPostFilter(); } @SuppressWarnings("unchecked") private T executeQueryById() { SimpleCondition c = (SimpleCondition) condition; IdRef<T> id = (IdRef<T>) c.getWhereValue(); executedQueryType = QueryType.FETCH; RepositoryHooks.beforeQuery(this); T retrieved = hasForcedResponse(executedQueryType) ? getForcedResultFetch() : doExecuteQueryById(id); executedResponse = retrieved; RepositoryHooks.afterQuery(this); return retrieved; } private T doExecuteQueryById(IdRef<T> id) { return r.driver().query().fetch(id); } private boolean isQueryById() { if (condition == null || !(condition instanceof SimpleCondition)) { return false; } SimpleCondition c = (SimpleCondition) condition; return c.isIdField() && c.isEqualOperator(); } public void sortList(List<?> objects) { if (!hasPostOrder()) { return; } objects.sort((o1, o2) -> { for (QueryOrder order : postOrders) { int compare = order.compare(o1, o2); if (compare == 0) { continue; } return compare; } return 0; }); } public boolean hasPreOrder() { return preOrders.size() != 0; } private boolean hasPostOrder() { return postOrders.size() != 0; } public Class<T> getClazz() { return clazz; } public QueryBuilder<T> whereById(String operator, IdRef<?> id) { return from(id.getParentId()).where(model.getIdField().getName(), operator, id); } public T fetch(IdRef<?> idRef) { return whereById("=", idRef).only(); } public T fetch(Long id) { IdRef<?> idRef = IdRef.create(r, clazz, id); return fetch(idRef); } public T fetch(String name) { IdRef<?> idRef = IdRef.create(r, clazz, name); return fetch(idRef); } public List<IdRef<T>> ids() { if (hasPostFilter() || hasPostOrder()) { throw new RuntimeException("ids() cannot be used with post query filter or order. You may need to add @Index to your model attributes."); } return idsIgnoringPost(); } public List<IdRef<T>> idsIgnoringPost() { r.namespace().set(getClazz()); try { executedQueryType = QueryType.IDS; RepositoryHooks.beforeQuery(this); List<IdRef<T>> ids = hasForcedResponse(executedQueryType) ? getForcedResultIds() : doFetchIds(); executedResponse = ids; RepositoryHooks.afterQuery(this); return ids; } finally { r.namespace().reset(); } } private List<IdRef<T>> doFetchIds() { return r.driver().query().ids(this); } public IdRef<T> onlyId() throws NoResultException, MoreThanOneResultException { List<IdRef<T>> ids = ids(); if (ids.size() == 0) { throw new NoResultException(); } if (ids.size() > 1) { throw new MoreThanOneResultException(); } return ids.get(0); } public boolean hasCursor() { return cursor != null; } public QueryBuilder<T> clone() { QueryBuilder<T> q = new QueryBuilder<>(clazz, r); if (condition != null) { q.condition = condition.clone(); q.condition.init(r, clazz); } if (preOrders != null) { q.preOrders = preOrders.stream().map(QueryOrder::clone).collect(toList()); } if (postOrders != null) { q.postOrders = postOrders.stream().map(QueryOrder::clone).collect(toList()); } q.parentId = parentId; q.limit = limit; return q; } public Map<String, Object> toMap() { Map<String, Object> result = new HashMap<>(); result.put("clazz", clazz.getCanonicalName()); result.put("executedQueryType", executedQueryType); result.put("parentId", parentId == null ? null : parentId.toString()); result.put("condition", condition == null ? null : condition.toMap()); result.put("preOrders", preOrders); result.put("postOrders", postOrders); result.put("limit", limit); return result; } }
9236ab8855ef94ba2d79a149cc84bc6ed3f4d800
2,387
java
Java
LeetCode/Dynamic Programming/Medium/(673) Number of Longest Increasing Subsequence.java
kaustubh0402/problem-solving
bf18af8165bd632109e2e88837eab816542ac6a3
[ "MIT" ]
8
2020-09-17T10:17:33.000Z
2022-01-19T08:57:04.000Z
LeetCode/Dynamic Programming/Medium/(673) Number of Longest Increasing Subsequence.java
kaustubh0402/problem-solving
bf18af8165bd632109e2e88837eab816542ac6a3
[ "MIT" ]
null
null
null
LeetCode/Dynamic Programming/Medium/(673) Number of Longest Increasing Subsequence.java
kaustubh0402/problem-solving
bf18af8165bd632109e2e88837eab816542ac6a3
[ "MIT" ]
2
2021-03-28T10:07:02.000Z
2021-07-12T03:25:38.000Z
24.608247
72
0.33473
997,765
https://leetcode.com/problems/number-of-longest-increasing-subsequence/ //Problem no : 673 //Following solution is same as Printing all LIS //But it will give MLE error class Solution { class node { int i; int l; node(int index,int len) { i=index; l=len; } } public int findNumberOfLIS(int[] nums) { int n=nums.length; int dp[]=new int[n]; Arrays.fill(dp,1); int mx=1; for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(nums[i]>nums[j]) { dp[i]=Math.max(dp[i],dp[j]+1); mx=Math.max(mx,dp[i]); } } } ArrayDeque<node> q=new ArrayDeque<>(); for(int i=0;i<n;i++) { if(dp[i]==mx) q.add(new node(i,mx)); } int ans=0; while(!q.isEmpty()) { node curr=q.removeFirst(); if(curr.l==1) { ans++; continue; } for(int in=0;in<curr.i;in++) { if(dp[in]==curr.l-1 && nums[in]<nums[curr.i]) { q.add(new node(in,curr.l-1)); } } } return ans; } } //(n^2) dp solution class Solution { public int findNumberOfLIS(int[] nums) { int n=nums.length; int dp[]=new int[n]; int count[]=new int[n]; Arrays.fill(dp,1); Arrays.fill(count,1); int mx=1; for(int i=0;i<n;i++) { for(int j=0;j<i;j++) { if(nums[i]>nums[j]) { if(dp[i]<dp[j]+1) { dp[i]=dp[j]+1; count[i]=count[j]; } else if(dp[i]==dp[j]+1) { count[i]+=count[j]; } mx=Math.max(mx,dp[i]); } } } int ans=0; for(int i=0;i<n;i++) if(dp[i]==mx) ans+=count[i]; return ans; } }
9236abb74676bb9bc42547c1731fc74dc9b0449b
1,178
java
Java
src/genecode/function/Length.java
iamsrp/genecode
dc24d7f828e4d086dba928b697f8e060bda9c3af
[ "Apache-2.0" ]
1
2017-06-06T03:48:13.000Z
2017-06-06T03:48:13.000Z
src/genecode/function/Length.java
iamsrp/genecode
dc24d7f828e4d086dba928b697f8e060bda9c3af
[ "Apache-2.0" ]
null
null
null
src/genecode/function/Length.java
iamsrp/genecode
dc24d7f828e4d086dba928b697f8e060bda9c3af
[ "Apache-2.0" ]
null
null
null
23.098039
67
0.549236
997,766
package genecode.function; import java.lang.reflect.Array; import java.util.Arrays; /** * A function which gets the size of a collection. */ public class Length extends Function { private static final long serialVersionUID = 2376235762708708L; /** * CTOR. * * @param argType The array or String type we take. */ public Length(final Class<?> argType) { super(Arrays.asList(argType), Long.class); if (!argType.isArray() && argType != String.class) { throw new IllegalArgumentException( argType + " is not an array type or a String" ); } } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") protected Object safeCall(final Object[] args) { final Object value = args[0]; if (value == null) { return null; } else if (value.getClass() == String.class) { return Long.valueOf(((String)value).length()); } else { return !value.getClass().isArray() ? null : Long.valueOf(Array.getLength(value)); } } }
9236ac07b2c4cac5b82cf421b1722d71cff3ab8d
1,444
java
Java
app/src/main/java/com/codepath/apps/restclienttemplate/models/User.java
Byrnorthil/TweeterClone-week2
71771d25525ba4746e1f0de27bb40e23317af6ea
[ "MIT" ]
null
null
null
app/src/main/java/com/codepath/apps/restclienttemplate/models/User.java
Byrnorthil/TweeterClone-week2
71771d25525ba4746e1f0de27bb40e23317af6ea
[ "MIT" ]
1
2020-02-11T08:50:21.000Z
2020-02-11T08:50:21.000Z
app/src/main/java/com/codepath/apps/restclienttemplate/models/User.java
Byrnorthil/TweeterClone-week2
71771d25525ba4746e1f0de27bb40e23317af6ea
[ "MIT" ]
1
2021-07-24T02:19:15.000Z
2021-07-24T02:19:15.000Z
27.245283
86
0.671745
997,767
package com.codepath.apps.restclienttemplate.models; import androidx.room.ColumnInfo; import androidx.room.Entity; import androidx.room.PrimaryKey; import org.jetbrains.annotations.NotNull; import org.json.JSONException; import org.json.JSONObject; import org.parceler.Parcel; import java.util.ArrayList; import java.util.List; @Parcel @Entity public class User { @ColumnInfo @PrimaryKey public long id; @ColumnInfo public String name; @ColumnInfo public String screenName; @ColumnInfo public String profileImageUrl; public User() {} //Parceler needs this public User (long id, String name, String screenName, String profileImageUrl) { this.name = name; this.screenName = screenName; this.profileImageUrl = profileImageUrl; this.id = id; } public static User fromJson(@NotNull JSONObject jsonObject) throws JSONException { User user = new User(jsonObject.getLong("id"), jsonObject.getString("name"), jsonObject.getString("screen_name"), jsonObject.getString("profile_image_url_https")); return user; } public static List<User> fromJsonTweetArray(List<Tweet> tweetsFromNetwork) { List<User> users = new ArrayList<>(); for (int i = 0; i < tweetsFromNetwork.size(); ++i) { users.add(tweetsFromNetwork.get(i).user); } return users; } }
9236ac6782f84dc3fc05a084256187c61e91e778
169
java
Java
src/main/java/sb/todoapp/todolist/ToDoListRepository.java
amazinglynormal/to-do-app-spring
1fb60b22c1ada607d6ab0af9dbb4f2d0795c4f65
[ "MIT" ]
null
null
null
src/main/java/sb/todoapp/todolist/ToDoListRepository.java
amazinglynormal/to-do-app-spring
1fb60b22c1ada607d6ab0af9dbb4f2d0795c4f65
[ "MIT" ]
null
null
null
src/main/java/sb/todoapp/todolist/ToDoListRepository.java
amazinglynormal/to-do-app-spring
1fb60b22c1ada607d6ab0af9dbb4f2d0795c4f65
[ "MIT" ]
null
null
null
24.142857
76
0.840237
997,768
package sb.todoapp.todolist; import org.springframework.data.repository.CrudRepository; public interface ToDoListRepository extends CrudRepository<ToDoList, Long> { }
9236ad71bbd367e251dd911bf1f54918bdc91926
4,626
java
Java
msbuild-impl/src/main/java/consulo/msbuild/editor/MSBuildOutOfProjectEditorNotificationProvider.java
consulo/incubating-consulo-msbuild
be88453652f656605448447928bc46fafc9e6912
[ "Apache-2.0" ]
null
null
null
msbuild-impl/src/main/java/consulo/msbuild/editor/MSBuildOutOfProjectEditorNotificationProvider.java
consulo/incubating-consulo-msbuild
be88453652f656605448447928bc46fafc9e6912
[ "Apache-2.0" ]
22
2020-12-13T19:19:53.000Z
2021-01-30T12:14:10.000Z
msbuild-impl/src/main/java/consulo/msbuild/editor/MSBuildOutOfProjectEditorNotificationProvider.java
consulo/incubating-consulo-msbuild
be88453652f656605448447928bc46fafc9e6912
[ "Apache-2.0" ]
null
null
null
28.036364
186
0.686122
997,769
package consulo.msbuild.editor; import com.intellij.openapi.fileEditor.FileEditor; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.EditorNotificationPanel; import consulo.annotation.access.RequiredReadAction; import consulo.editor.notifications.EditorNotificationProvider; import jakarta.inject.Inject; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * @author VISTALL * @since 2018-08-15 */ public class MSBuildOutOfProjectEditorNotificationProvider implements EditorNotificationProvider<EditorNotificationPanel> { private final Project myProject; @Inject public MSBuildOutOfProjectEditorNotificationProvider(Project project) { myProject = project; } @RequiredReadAction @Nullable @Override public EditorNotificationPanel createNotificationPanel(@Nonnull VirtualFile sourceFile, @Nonnull FileEditor fileEditor) { // if(sourceFile.getFileSystem() instanceof ArchiveFileSystem) // { // return null; // } // // Pair<WProject, SimpleItem> pair = MSBuildSynchronizeUtil.searchMappingInSolution(sourceFile, myProject); // if(pair != null) // { // return null; // } // // MSBuildSolutionManager solutionManager = MSBuildSolutionManager.getInstance(myProject); // if(!solutionManager.isEnabled()) // { // return null; // } // // if(sourceFile.equals(solutionManager.getSolutionFile())) // { // return null; // } // // for(WProject wProject : solutionManager.getSolution().getProjects()) // { // if(sourceFile.equals(wProject.getVirtualFile())) // { // return null; // } // } // // EditorNotificationPanel panel = new EditorNotificationPanel(); // panel.text("Unregistered file in solution"); // // panel.createActionLabel("Register to project...", () -> // { // ChooseElementsDialog<WProject> dialog = new ChooseElementsDialog<WProject>(myProject, solutionManager.getSolution().getProjects(), "Choose Project", "Please select project for map") // { // @Override // protected String getItemText(WProject wProject) // { // String path = "??"; // VirtualFile projectFile = wProject.getVirtualFile(); // if(projectFile != null) // { // path = FileUtil.toSystemDependentName(projectFile.getPath()); // } // return wProject.getName() + " (" + path + ")"; // } // // @Nullable // @Override // protected Image getItemIcon(WProject wProject) // { // return MSBuildIcons.Msbuild; // } // }; // // List<WProject> wProjects = dialog.showAndGetResult(); // if(wProjects.size() != 1) // { // return; // } // // WProject wProject = wProjects.get(0); // // VirtualFile projectFile = wProject.getVirtualFile(); // if(projectFile == null) // { // return; // } // // MSBuildSynchronizeQueue queue = MSBuildSynchronizeQueue.getInstance(myProject); // // queue.add(projectFile, () -> // { // PsiManager psiManager = PsiManager.getInstance(myProject); // // PsiFile file = psiManager.findFile(projectFile); // if(file == null) // { // return; // } // // DomManager domManager = DomManager.getDomManager(myProject); // DomFileElement<consulo.msbuild.dom.Project> fileElement = domManager.getFileElement((XmlFile) file, consulo.msbuild.dom.Project.class); // if(fileElement == null) // { // return; // } // // consulo.msbuild.dom.Project rootElement = fileElement.getRootElement(); // // MSBuildProjectType projectType = MSBuildProjectType.getProjectType(wProject.getTypeGUID()); // if(projectType == null) // { // return; // } // // MSBuildFileReferenceType referenceType = projectType.getFileReferenceType(sourceFile); // // ItemGroup selectedItemGroup = null; // List<ItemGroup> itemGroups = rootElement.getItemGroups(); // for(ItemGroup itemGroup : itemGroups) // { // List<? extends SimpleItem> simpleItems = referenceType.selectItems(itemGroup); // if(!simpleItems.isEmpty()) // { // selectedItemGroup = itemGroup; // } // } // // if(selectedItemGroup == null) // { // selectedItemGroup = rootElement.addItemGroup(); // } // // SimpleItem simpleItem = referenceType.addItem(selectedItemGroup); // // VirtualFile parent = projectFile.getParent(); // assert parent != null; // // String relativePath = VfsUtil.getRelativePath(sourceFile, parent, '\\'); // // simpleItem.getInclude().setStringValue(relativePath); // // SwingUtilities.invokeLater(() -> EditorNotifications.getInstance(myProject).updateNotifications(sourceFile)); // }); // }); // return panel; return null; } }
9236adaa9be8091ccabfb883b1fa553f7c827782
388
java
Java
src/solid/ocp/solucao/Conforto.java
gdfreitas/principios-solid
b036db9a5f9af6eda0f541a3094a70d687875585
[ "MIT" ]
2
2019-08-22T19:43:54.000Z
2020-01-26T18:16:21.000Z
src/solid/ocp/solucao/Conforto.java
gdfreitas/principios-solid
b036db9a5f9af6eda0f541a3094a70d687875585
[ "MIT" ]
null
null
null
src/solid/ocp/solucao/Conforto.java
gdfreitas/principios-solid
b036db9a5f9af6eda0f541a3094a70d687875585
[ "MIT" ]
2
2018-08-31T12:03:02.000Z
2020-01-26T18:16:23.000Z
15.52
50
0.634021
997,770
package solid.ocp.solucao; /** * @author gabriel.freitas */ @SuppressWarnings("all") public class Conforto implements ControleDirecao { @Override public double getRigidezSuspensao() { return 20; } @Override public double getRigidezDirecao() { return 20; } @Override public double getInjecaoCombustivel() { return 25; } }
9236addcc372b5100c85ada2e43a1a68157fe057
1,698
java
Java
backend/src/main/java/com/herostore/products/mapper/ProductMapper.java
cesar-lp/hulk-store
b8c66c6c670ee18ffad804c85ef05eb93fe43963
[ "MIT" ]
null
null
null
backend/src/main/java/com/herostore/products/mapper/ProductMapper.java
cesar-lp/hulk-store
b8c66c6c670ee18ffad804c85ef05eb93fe43963
[ "MIT" ]
7
2020-04-26T19:59:44.000Z
2022-02-26T22:42:26.000Z
backend/src/main/java/com/herostore/products/mapper/ProductMapper.java
cesar-lp/hero-store
b8c66c6c670ee18ffad804c85ef05eb93fe43963
[ "MIT" ]
null
null
null
39.488372
98
0.767373
997,771
package com.herostore.products.mapper; import com.herostore.products.domain.Product; import com.herostore.products.domain.ProductType; import com.herostore.products.dto.ProductTypeDTO; import com.herostore.products.dto.request.ProductRequest; import com.herostore.products.dto.response.ProductResponse; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import org.mapstruct.factory.Mappers; import java.util.List; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.toList; @Mapper(componentModel = "spring") public interface ProductMapper { ProductTypeMapper productTypeMapper = Mappers.getMapper(ProductTypeMapper.class); @Mapping(target = "productTypeName", source = "product.productType.name") @Mapping(source = "productType", target = "productType", qualifiedByName = "toProductTypeDTO") ProductResponse toProductResponse(Product product); @Mapping(target = "id", source = "productRequest.id") @Mapping(target = "name", source = "productRequest.name") @Mapping(target = "stock", source = "productRequest.stock") @Mapping(target = "price", source = "productRequest.price") Product toProduct(ProductRequest productRequest, ProductType productType); @Named("toProductTypeDTO") default ProductTypeDTO toProductTypeDTO(ProductType productType) { return productTypeMapper.toProductTypeDTO(productType); } default List<ProductResponse> toProductResponseList(List<Product> productList) { if (productList == null || productList.isEmpty()) return emptyList(); return productList.stream().map(this::toProductResponse).collect(toList()); } }
9236aecc4f2ab8d2d5c4c7fb1494357306b65be6
1,117
java
Java
dataflow-manager/generator/src/main/java/ch/skymarshall/dataflowmgr/generator/writers/dot/ProcessorGenerator.java
sebastiencaille/sky-lib
b8d01c5b90e1f234d1a202b9313e3241656a0275
[ "BSD-3-Clause" ]
null
null
null
dataflow-manager/generator/src/main/java/ch/skymarshall/dataflowmgr/generator/writers/dot/ProcessorGenerator.java
sebastiencaille/sky-lib
b8d01c5b90e1f234d1a202b9313e3241656a0275
[ "BSD-3-Clause" ]
2
2020-02-07T21:02:03.000Z
2020-12-17T21:30:19.000Z
dataflow-manager/generator/src/main/java/ch/skymarshall/dataflowmgr/generator/writers/dot/ProcessorGenerator.java
sebastiencaille/sky-lib
b8d01c5b90e1f234d1a202b9313e3241656a0275
[ "BSD-3-Clause" ]
null
null
null
32.852941
94
0.823635
997,772
package ch.skymarshall.dataflowmgr.generator.writers.dot; import java.util.Set; import ch.skymarshall.dataflowmgr.generator.writers.AbstractFlowVisitor.BindingContext; import ch.skymarshall.dataflowmgr.generator.writers.dot.FlowToDotVisitor.Graph; import ch.skymarshall.dataflowmgr.generator.writers.dot.FlowToDotVisitor.Link; import ch.skymarshall.dataflowmgr.model.ExternalAdapter; public class ProcessorGenerator extends AbstractDotFlowGenerator { protected ProcessorGenerator(FlowToDotVisitor visitor, Graph graph) { super(visitor, graph); } @Override public boolean matches(BindingContext context) { return true; } @Override public void generate(BaseGenContext<String> genContext, BindingContext context) { final String processorNode = visitor.addProcessor(context.binding, context.getProcessor()); Set<ExternalAdapter> missingAdapters = context.unprocessedAdapters(context.bindingAdapters); visitor.addExternalAdapters(missingAdapters, genContext.getLocalContext(), processorNode); graph.links.add(new Link(processorNode, context.outputDataPoint)); genContext.next(context); } }
9236af30447958acfc828d173eec390ce2d7fe9b
5,790
java
Java
mr/src/main/java/org/apache/mahout/classifier/df/mapreduce/partial/PartialBuilder.java
UnimibSoftEngCourse1819/laboratorio-4-esercizio-sonarqube-mahout-claudiom4sir
6267e5d8f6b13136f0c8151ea7e514b9733266ff
[ "Apache-2.0" ]
2,073
2015-01-01T15:35:21.000Z
2022-03-31T06:18:06.000Z
mr/src/main/java/org/apache/mahout/classifier/df/mapreduce/partial/PartialBuilder.java
UnimibSoftEngCourse1819/laboratorio-4-esercizio-sonarqube-mahout-claudiom4sir
6267e5d8f6b13136f0c8151ea7e514b9733266ff
[ "Apache-2.0" ]
224
2015-01-01T16:36:19.000Z
2021-01-27T23:22:45.000Z
mr/src/main/java/org/apache/mahout/classifier/df/mapreduce/partial/PartialBuilder.java
UnimibSoftEngCourse1819/laboratorio-4-esercizio-sonarqube-mahout-claudiom4sir
6267e5d8f6b13136f0c8151ea7e514b9733266ff
[ "Apache-2.0" ]
1,109
2015-01-01T23:32:26.000Z
2022-03-28T07:27:17.000Z
36.415094
108
0.690674
997,773
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.mahout.classifier.df.mapreduce.partial; import com.google.common.base.Preconditions; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.JobContext; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.SequenceFileOutputFormat; import org.apache.mahout.classifier.df.DFUtils; import org.apache.mahout.classifier.df.DecisionForest; import org.apache.mahout.classifier.df.builder.TreeBuilder; import org.apache.mahout.classifier.df.mapreduce.Builder; import org.apache.mahout.classifier.df.mapreduce.MapredOutput; import org.apache.mahout.classifier.df.node.Node; import org.apache.mahout.common.Pair; import org.apache.mahout.common.iterator.sequencefile.SequenceFileIterable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Arrays; import java.util.List; /** * Builds a random forest using partial data. Each mapper uses only the data given by its InputSplit */ @Deprecated public class PartialBuilder extends Builder { private static final Logger log = LoggerFactory.getLogger(PartialBuilder.class); public PartialBuilder(TreeBuilder treeBuilder, Path dataPath, Path datasetPath, Long seed) { this(treeBuilder, dataPath, datasetPath, seed, new Configuration()); } public PartialBuilder(TreeBuilder treeBuilder, Path dataPath, Path datasetPath, Long seed, Configuration conf) { super(treeBuilder, dataPath, datasetPath, seed, conf); } @Override protected void configureJob(Job job) throws IOException { Configuration conf = job.getConfiguration(); job.setJarByClass(PartialBuilder.class); FileInputFormat.setInputPaths(job, getDataPath()); FileOutputFormat.setOutputPath(job, getOutputPath(conf)); job.setOutputKeyClass(TreeID.class); job.setOutputValueClass(MapredOutput.class); job.setMapperClass(Step1Mapper.class); job.setNumReduceTasks(0); // no reducers job.setInputFormatClass(TextInputFormat.class); job.setOutputFormatClass(SequenceFileOutputFormat.class); // For this implementation to work, mapred.map.tasks needs to be set to the actual // number of mappers Hadoop will use: TextInputFormat inputFormat = new TextInputFormat(); List<?> splits = inputFormat.getSplits(job); if (splits == null || splits.isEmpty()) { log.warn("Unable to compute number of splits?"); } else { int numSplits = splits.size(); log.info("Setting mapred.map.tasks = {}", numSplits); conf.setInt("mapred.map.tasks", numSplits); } } @Override protected DecisionForest parseOutput(Job job) throws IOException { Configuration conf = job.getConfiguration(); int numTrees = Builder.getNbTrees(conf); Path outputPath = getOutputPath(conf); TreeID[] keys = new TreeID[numTrees]; Node[] trees = new Node[numTrees]; processOutput(job, outputPath, keys, trees); return new DecisionForest(Arrays.asList(trees)); } /** * Processes the output from the output path.<br> * * @param outputPath * directory that contains the output of the job * @param keys * can be null * @param trees * can be null * @throws java.io.IOException */ protected static void processOutput(JobContext job, Path outputPath, TreeID[] keys, Node[] trees) throws IOException { Preconditions.checkArgument(keys == null && trees == null || keys != null && trees != null, "if keys is null, trees should also be null"); Preconditions.checkArgument(keys == null || keys.length == trees.length, "keys.length != trees.length"); Configuration conf = job.getConfiguration(); FileSystem fs = outputPath.getFileSystem(conf); Path[] outfiles = DFUtils.listOutputFiles(fs, outputPath); // read all the outputs int index = 0; for (Path path : outfiles) { for (Pair<TreeID,MapredOutput> record : new SequenceFileIterable<TreeID, MapredOutput>(path, conf)) { TreeID key = record.getFirst(); MapredOutput value = record.getSecond(); if (keys != null) { keys[index] = key; } if (trees != null) { trees[index] = value.getTree(); } index++; } } // make sure we got all the keys/values if (keys != null && index != keys.length) { throw new IllegalStateException("Some key/values are missing from the output"); } } }
9236af570610cdb79eda26a4c5a6496ec414a882
590
java
Java
chatServe/admin-serve/src/main/java/com/netty/adminServe/dao/MessageMapper.java
HongZe1090/netty-chat-room
ddc2072ed06f89d23bb461d23cb9a6e2b11b9260
[ "Apache-2.0" ]
null
null
null
chatServe/admin-serve/src/main/java/com/netty/adminServe/dao/MessageMapper.java
HongZe1090/netty-chat-room
ddc2072ed06f89d23bb461d23cb9a6e2b11b9260
[ "Apache-2.0" ]
null
null
null
chatServe/admin-serve/src/main/java/com/netty/adminServe/dao/MessageMapper.java
HongZe1090/netty-chat-room
ddc2072ed06f89d23bb461d23cb9a6e2b11b9260
[ "Apache-2.0" ]
null
null
null
15.526316
89
0.652542
997,774
package com.netty.adminServe.dao; import com.netty.common.entity.LogInfo; import com.netty.common.entity.Message; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * @创建人 HongZe * @创建时间 2021/12/24 * @描述 */ @Mapper public interface MessageMapper { /** *@描述 插入单条消息记录 * @return */ public boolean insertInfo(Message insertInfo); /** *@描述 获取所有的日志消息 */ public List<Message> getAllInfo(); /** *@描述 根据用户id与获取用户 */ public List<com.netty.common.entity.Message> getMessage(Integer fromId,Integer toId); }
9236af99fc7e108b906d94119f3e44c73ba53a58
1,074
java
Java
src/carnero/cgeo/cgCacheSizeComparator.java
just-radovan/c-geo
d92c90355b43a0c12508888132bbeb3880dac89b
[ "Apache-2.0" ]
4
2016-09-26T20:09:18.000Z
2020-02-16T11:50:53.000Z
src/carnero/cgeo/cgCacheSizeComparator.java
carnero/c-geo
d92c90355b43a0c12508888132bbeb3880dac89b
[ "Apache-2.0" ]
null
null
null
src/carnero/cgeo/cgCacheSizeComparator.java
carnero/c-geo
d92c90355b43a0c12508888132bbeb3880dac89b
[ "Apache-2.0" ]
4
2016-05-14T00:07:58.000Z
2019-12-13T00:17:22.000Z
22.375
110
0.637803
997,775
package carnero.cgeo; import java.util.Comparator; import android.util.Log; import java.util.ArrayList; public class cgCacheSizeComparator implements Comparator<cgCache> { public static ArrayList<String> cacheSizes = new ArrayList<String>(); public cgCacheSizeComparator() { // list sizes cacheSizes.add("micro"); cacheSizes.add("small"); cacheSizes.add("regular"); cacheSizes.add("large"); } public int compare(cgCache cache1, cgCache cache2) { try { if (cache1.size == null || cache1.size.length() == 0 || cache2.size == null || cache2.size.length() == 0) { return 0; } int size1 = 0; int size2 = 0; int cnt = 1; for (String size : cacheSizes) { if (size.equalsIgnoreCase(cache1.size)) size1 = cnt; if (size.equalsIgnoreCase(cache2.size)) size2 = cnt; cnt ++; } if (size1 < size2) { return 1; } else if (size2 < size1) { return -1; } else { return 0; } } catch (Exception e) { Log.e(cgSettings.tag, "cgCacheSizeComparator.compare: " + e.toString()); } return 0; } }
9236afd9523db013ac3de648e86b2a02171d9f68
11,452
java
Java
app/src/main/java/com/thinkdev/audiorecorder/data/PrefsImpl.java
thinkapper/AudioRecorder-master
c3a0e951f4d233dbf191ac27feac6cbfb7d5bf12
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/thinkdev/audiorecorder/data/PrefsImpl.java
thinkapper/AudioRecorder-master
c3a0e951f4d233dbf191ac27feac6cbfb7d5bf12
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/thinkdev/audiorecorder/data/PrefsImpl.java
thinkapper/AudioRecorder-master
c3a0e951f4d233dbf191ac27feac6cbfb7d5bf12
[ "Apache-2.0" ]
null
null
null
31.988827
170
0.79628
997,776
package com.thinkdev.audiorecorder.data; import android.content.Context; import android.content.SharedPreferences; import com.thinkdev.audiorecorder.AppConstants; /** * App preferences implementation */ public class PrefsImpl implements Prefs { private static final String PREF_NAME = "com.thinkdev.audiorecorder.data.PrefsImpl"; private static final String PREF_KEY_IS_FIRST_RUN = "is_first_run"; private static final String PREF_KEY_IS_MIGRATED = "is_migrated"; private static final String PREF_KEY_IS_MIGRATED_DB3 = "is_migrated_db3"; private static final String PREF_KEY_IS_STORE_DIR_PUBLIC = "is_store_dir_public"; private static final String PREF_KEY_IS_ASK_TO_RENAME_AFTER_STOP_RECORDING = "is_ask_rename_after_stop_recording"; private static final String PREF_KEY_ACTIVE_RECORD = "active_record"; private static final String PREF_KEY_RECORD_COUNTER = "record_counter"; private static final String PREF_KEY_THEME_COLORMAP_POSITION = "theme_color"; private static final String PREF_KEY_KEEP_SCREEN_ON = "keep_screen_on"; private static final String PREF_KEY_FORMAT = "pref_format"; private static final String PREF_KEY_BITRATE = "pref_bitrate"; private static final String PREF_KEY_SAMPLE_RATE = "pref_sample_rate"; private static final String PREF_KEY_RECORDS_ORDER = "pref_records_order"; private static final String PREF_KEY_NAMING_FORMAT = "pref_naming_format"; //Recording prefs. private static final String PREF_KEY_RECORD_CHANNEL_COUNT = "record_channel_count"; private static final String PREF_KEY_SETTING_THEME_COLOR = "setting_theme_color"; private static final String PREF_KEY_SETTING_RECORDING_FORMAT = "setting_recording_format"; private static final String PREF_KEY_SETTING_BITRATE = "setting_bitrate"; private static final String PREF_KEY_SETTING_SAMPLE_RATE = "setting_sample_rate"; private static final String PREF_KEY_SETTING_NAMING_FORMAT = "setting_naming_format"; private static final String PREF_KEY_SETTING_CHANNEL_COUNT = "setting_channel_count"; private SharedPreferences sharedPreferences; private volatile static PrefsImpl instance; private PrefsImpl(Context context) { sharedPreferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); } public static PrefsImpl getInstance(Context context) { if (instance == null) { synchronized (PrefsImpl.class) { if (instance == null) { instance = new PrefsImpl(context); } } } return instance; } @Override public boolean isFirstRun() { return !sharedPreferences.contains(PREF_KEY_IS_FIRST_RUN) || sharedPreferences.getBoolean(PREF_KEY_IS_FIRST_RUN, false); } @Override public void firstRunExecuted() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(PREF_KEY_IS_FIRST_RUN, false); editor.putBoolean(PREF_KEY_IS_STORE_DIR_PUBLIC, false); editor.putBoolean(PREF_KEY_IS_MIGRATED, true); editor.apply(); // setStoreDirPublic(true); } @Override public boolean isStoreDirPublic() { return sharedPreferences.contains(PREF_KEY_IS_STORE_DIR_PUBLIC) && sharedPreferences.getBoolean(PREF_KEY_IS_STORE_DIR_PUBLIC, true); } @Override public void setStoreDirPublic(boolean b) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(PREF_KEY_IS_STORE_DIR_PUBLIC, b); editor.apply(); } @Override public boolean isAskToRenameAfterStopRecording() { return sharedPreferences.contains(PREF_KEY_IS_ASK_TO_RENAME_AFTER_STOP_RECORDING) && sharedPreferences.getBoolean(PREF_KEY_IS_ASK_TO_RENAME_AFTER_STOP_RECORDING, true); } @Override public boolean hasAskToRenameAfterStopRecordingSetting() { return sharedPreferences.contains(PREF_KEY_IS_ASK_TO_RENAME_AFTER_STOP_RECORDING); } @Override public void setAskToRenameAfterStopRecording(boolean b) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(PREF_KEY_IS_ASK_TO_RENAME_AFTER_STOP_RECORDING, b); editor.apply(); } @Override public long getActiveRecord() { return sharedPreferences.getLong(PREF_KEY_ACTIVE_RECORD, -1); } @Override public void setActiveRecord(long id) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(PREF_KEY_ACTIVE_RECORD, id); editor.apply(); } @Override public long getRecordCounter() { return sharedPreferences.getLong(PREF_KEY_RECORD_COUNTER, 0); } @Override public void incrementRecordCounter() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putLong(PREF_KEY_RECORD_COUNTER, getRecordCounter()+1); editor.apply(); } private int getThemeColor() { return sharedPreferences.getInt(PREF_KEY_THEME_COLORMAP_POSITION, 0); } public int getRecordChannelCount() { return sharedPreferences.getInt(PREF_KEY_RECORD_CHANNEL_COUNT, AppConstants.RECORD_AUDIO_STEREO); } @Override public void setKeepScreenOn(boolean on) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(PREF_KEY_KEEP_SCREEN_ON, on); editor.apply(); } @Override public boolean isKeepScreenOn() { return sharedPreferences.getBoolean(PREF_KEY_KEEP_SCREEN_ON, false); } public int getFormat() { return sharedPreferences.getInt(PREF_KEY_FORMAT, AppConstants.RECORDING_FORMAT_M4A); } private int getBitrate() { return sharedPreferences.getInt(PREF_KEY_BITRATE, AppConstants.RECORD_ENCODING_BITRATE_128000); } private int getSampleRate() { return sharedPreferences.getInt(PREF_KEY_SAMPLE_RATE, AppConstants.RECORD_SAMPLE_RATE_44100); } @Override public void setRecordOrder(int order) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(PREF_KEY_RECORDS_ORDER, order); editor.apply(); } @Override public int getRecordsOrder() { return sharedPreferences.getInt(PREF_KEY_RECORDS_ORDER, AppConstants.SORT_DATE); } public int getNamingFormat() { return sharedPreferences.getInt(PREF_KEY_NAMING_FORMAT, AppConstants.NAMING_COUNTED); } @Override public boolean isMigratedSettings() { return sharedPreferences.getBoolean(PREF_KEY_IS_MIGRATED, false); } @Override public void migrateSettings() { int color = getThemeColor(); int nameFormat = getNamingFormat(); int recordingFormat = getFormat(); int sampleRate = getSampleRate(); int bitrate = getBitrate(); if (bitrate == AppConstants.RECORD_ENCODING_BITRATE_24000) { bitrate = AppConstants.RECORD_ENCODING_BITRATE_48000; } int channelCount = getRecordChannelCount(); String colorKey; switch (color) { case 1: colorKey = AppConstants.THEME_BLACK; break; case 2: colorKey = AppConstants.THEME_TEAL; break; case 3: colorKey = AppConstants.THEME_BLUE; break; case 4: colorKey = AppConstants.THEME_PURPLE; break; case 5: colorKey = AppConstants.THEME_PINK; break; case 6: colorKey = AppConstants.THEME_ORANGE; break; case 7: colorKey = AppConstants.THEME_RED; break; case 8: colorKey = AppConstants.THEME_BROWN; break; case 0: case 9: colorKey = AppConstants.THEME_BLUE_GREY; break; default: colorKey = AppConstants.DEFAULT_THEME_COLOR; } String recordingFormatKey; switch (recordingFormat) { case AppConstants.RECORDING_FORMAT_WAV: recordingFormatKey = AppConstants.FORMAT_WAV; break; case AppConstants.RECORDING_FORMAT_M4A: recordingFormatKey = AppConstants.FORMAT_M4A; break; default: recordingFormatKey = AppConstants.DEFAULT_RECORDING_FORMAT; } String namingFormatKey; switch (nameFormat) { case AppConstants.NAMING_DATE: namingFormatKey = AppConstants.NAME_FORMAT_DATE; break; case AppConstants.NAMING_COUNTED: namingFormatKey = AppConstants.NAME_FORMAT_RECORD; break; default: namingFormatKey = AppConstants.DEFAULT_NAME_FORMAT; } SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREF_KEY_SETTING_THEME_COLOR, colorKey); editor.putString(PREF_KEY_SETTING_NAMING_FORMAT, namingFormatKey); editor.putString(PREF_KEY_SETTING_RECORDING_FORMAT, recordingFormatKey); editor.putInt(PREF_KEY_SETTING_SAMPLE_RATE, sampleRate); editor.putInt(PREF_KEY_SETTING_BITRATE, bitrate); editor.putInt(PREF_KEY_SETTING_CHANNEL_COUNT, channelCount); editor.putBoolean(PREF_KEY_IS_MIGRATED, true); editor.apply(); } @Override public boolean isMigratedDb3() { return sharedPreferences.getBoolean(PREF_KEY_IS_MIGRATED_DB3, false); } @Override public void migrateDb3Finished() { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putBoolean(PREF_KEY_IS_MIGRATED_DB3, true); editor.apply(); } @Override public void setSettingThemeColor(String colorKey) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREF_KEY_SETTING_THEME_COLOR, colorKey); editor.apply(); } @Override public String getSettingThemeColor() { return sharedPreferences.getString(PREF_KEY_SETTING_THEME_COLOR, AppConstants.DEFAULT_THEME_COLOR); } @Override public void setSettingNamingFormat(String nameKey) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREF_KEY_SETTING_NAMING_FORMAT, nameKey); editor.apply(); } @Override public String getSettingNamingFormat() { return sharedPreferences.getString(PREF_KEY_SETTING_NAMING_FORMAT, AppConstants.DEFAULT_NAME_FORMAT); } @Override public void setSettingRecordingFormat(String formatKey) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(PREF_KEY_SETTING_RECORDING_FORMAT, formatKey); editor.apply(); } @Override public String getSettingRecordingFormat() { return sharedPreferences.getString(PREF_KEY_SETTING_RECORDING_FORMAT, AppConstants.DEFAULT_RECORDING_FORMAT); } @Override public void setSettingSampleRate(int sampleRate) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(PREF_KEY_SETTING_SAMPLE_RATE, sampleRate); editor.apply(); } @Override public int getSettingSampleRate() { return sharedPreferences.getInt(PREF_KEY_SETTING_SAMPLE_RATE, AppConstants.DEFAULT_RECORD_SAMPLE_RATE); } @Override public void setSettingBitrate(int rate) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(PREF_KEY_SETTING_BITRATE, rate); editor.apply(); } @Override public int getSettingBitrate() { return sharedPreferences.getInt(PREF_KEY_SETTING_BITRATE, AppConstants.DEFAULT_RECORD_ENCODING_BITRATE); } @Override public void setSettingChannelCount(int count) { SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putInt(PREF_KEY_SETTING_CHANNEL_COUNT, count); editor.apply(); } @Override public int getSettingChannelCount() { return sharedPreferences.getInt(PREF_KEY_SETTING_CHANNEL_COUNT, AppConstants.DEFAULT_CHANNEL_COUNT); } @Override public void resetSettings() { SharedPreferences.Editor editor = sharedPreferences.edit(); // editor.putString(PREF_KEY_SETTING_THEME_COLOR, AppConstants.DEFAULT_THEME_COLOR); // editor.putString(PREF_KEY_SETTING_NAMING_FORMAT, AppConstants.DEFAULT_NAME_FORMAT); editor.putString(PREF_KEY_SETTING_RECORDING_FORMAT, AppConstants.DEFAULT_RECORDING_FORMAT); editor.putInt(PREF_KEY_SETTING_SAMPLE_RATE, AppConstants.DEFAULT_RECORD_SAMPLE_RATE); editor.putInt(PREF_KEY_SETTING_BITRATE, AppConstants.DEFAULT_RECORD_ENCODING_BITRATE); editor.putInt(PREF_KEY_SETTING_CHANNEL_COUNT, AppConstants.DEFAULT_CHANNEL_COUNT); editor.apply(); } }
9236afed42914a9496ebf7bcf68324f071fa0e05
2,613
java
Java
demo-mall-module/demo-mall-user-service/src/test/java/com/liyulin/demo/mall/user/test/integration/cases/api/RegisterApiControllerIntegrationTest.java
luckyQing/spring-cloud-demo
019dbcb3b9f6572c42eac461f2de14d301fe8011
[ "Apache-2.0" ]
4
2019-04-26T08:33:00.000Z
2020-01-15T02:19:40.000Z
demo-mall-module/demo-mall-user-service/src/test/java/com/liyulin/demo/mall/user/test/integration/cases/api/RegisterApiControllerIntegrationTest.java
luckyQing/spring-cloud-demo
019dbcb3b9f6572c42eac461f2de14d301fe8011
[ "Apache-2.0" ]
null
null
null
demo-mall-module/demo-mall-user-service/src/test/java/com/liyulin/demo/mall/user/test/integration/cases/api/RegisterApiControllerIntegrationTest.java
luckyQing/spring-cloud-demo
019dbcb3b9f6572c42eac461f2de14d301fe8011
[ "Apache-2.0" ]
1
2020-04-02T13:49:20.000Z
2020-04-02T13:49:20.000Z
43.55
109
0.82013
997,777
package com.liyulin.demo.mall.user.test.integration.cases.api; import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.Mockito; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.TypeReference; import com.liyulin.demo.common.business.dto.Resp; import com.liyulin.demo.common.business.exception.enums.ReturnCodeEnum; import com.liyulin.demo.common.business.test.AbstractIntegrationTest; import com.liyulin.demo.mall.user.service.api.LoginInfoApiService; import com.liyulin.demo.mall.user.service.api.RegisterApiService; import com.liyulin.demo.rpc.enums.user.ChannelEnum; import com.liyulin.demo.rpc.enums.user.PwdStateEnum; import com.liyulin.demo.rpc.enums.user.SexEnum; import com.liyulin.demo.rpc.user.request.api.login.LoginInfoInsertReqBody; import com.liyulin.demo.rpc.user.request.api.register.RegisterUserReqBody; import com.liyulin.demo.rpc.user.request.api.user.UserInfoInsertReqBody; import com.liyulin.demo.rpc.user.response.api.register.RegisterUserRespBody; @Rollback @Transactional public class RegisterApiControllerIntegrationTest extends AbstractIntegrationTest { @Test public void testRegister() throws Exception { // mock LoginInfoApiService loginInfoApiService = Mockito.mock(LoginInfoApiService.class); RegisterApiService registerApiService = applicationContext.getBean(RegisterApiService.class); setMockAttribute(registerApiService, loginInfoApiService); Mockito.doNothing().when(loginInfoApiService).cacheLoginAfterLoginSuccess(Mockito.any()); // 构造请求参数 UserInfoInsertReqBody userInfo = new UserInfoInsertReqBody(); userInfo.setMobile("18720912981"); userInfo.setChannel(ChannelEnum.APP.getValue()); userInfo.setSex(SexEnum.FEMALE.getValue()); LoginInfoInsertReqBody loginInfo = new LoginInfoInsertReqBody(); loginInfo.setUsername("zhangsan"); loginInfo.setPwdState(PwdStateEnum.DONE_SETTING.getValue()); loginInfo.setPassword("123456"); RegisterUserReqBody registerUserReqBody = new RegisterUserReqBody(); registerUserReqBody.setUserInfo(userInfo); registerUserReqBody.setLoginInfo(loginInfo); Resp<RegisterUserRespBody> result = super.postWithNoHeaders("/api/sign/user/register", registerUserReqBody, new TypeReference<Resp<RegisterUserRespBody>>() { }); Assertions.assertThat(result).isNotNull(); Assertions.assertThat(result.getHead()).isNotNull(); Assertions.assertThat(result.getHead().getCode()).isEqualTo(ReturnCodeEnum.SUCCESS.getCode()); Assertions.assertThat(result.getBody()).isNotNull(); } }
9236b0e2b3b43ed0b51939da58fc49bbcdbe8f21
838
java
Java
src/test/java/org/csveed/test/model/BeanWithNameMatching.java
sarahsz/CSVeed
73e5871bff14c773704af1479d89ed61fb27d637
[ "Apache-2.0" ]
81
2015-01-17T20:41:10.000Z
2021-09-05T12:22:25.000Z
src/test/java/org/csveed/test/model/BeanWithNameMatching.java
sarahsz/CSVeed
73e5871bff14c773704af1479d89ed61fb27d637
[ "Apache-2.0" ]
37
2015-01-05T00:23:33.000Z
2021-10-14T23:58:01.000Z
src/test/java/org/csveed/test/model/BeanWithNameMatching.java
42BV/CSVeed
77cb59409f8b41df23a3cf3afe6cd27446875154
[ "Apache-2.0" ]
27
2015-01-04T23:27:45.000Z
2021-05-09T17:17:43.000Z
19.488372
50
0.649165
997,778
package org.csveed.test.model; import org.csveed.annotations.CsvCell; import org.csveed.annotations.CsvFile; import org.csveed.bean.ColumnNameMapper; @CsvFile(mappingStrategy = ColumnNameMapper.class) public class BeanWithNameMatching { @CsvCell(columnName = "postal code") public String line3; @CsvCell(columnName = "street") public String line1; @CsvCell(columnName = "CITY") public String line2; public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getLine3() { return line3; } public void setLine3(String line3) { this.line3 = line3; } }
9236b13b75fc25df36555ba40a614aea88db2795
6,294
java
Java
src/mainFrame/SizeDialog.java
colutto/convexHull_calculator
0cc1a2fa32459950540df540ab084247fbea102e
[ "MIT" ]
null
null
null
src/mainFrame/SizeDialog.java
colutto/convexHull_calculator
0cc1a2fa32459950540df540ab084247fbea102e
[ "MIT" ]
null
null
null
src/mainFrame/SizeDialog.java
colutto/convexHull_calculator
0cc1a2fa32459950540df540ab084247fbea102e
[ "MIT" ]
null
null
null
41.682119
144
0.566254
997,779
package mainFrame; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Die Klasse SizeDialog fragt den Benutzer nach der Größe der Zeichenfläche, bis diese nicht eingegeben wurde können * einige Funktionen der Anwendung nicht ausgeführt werden. * @author Stefan Colutto 9513140 * */ public class SizeDialog extends JDialog { private JButton confirm; //Button zum Bestätigen der Eingabe private final int sizeX = 350; //die Länge des Fensters private final int sizeY = 150; //die Höhe des Fensters private JButton cancel; //Button zum Abbrechen des Dialogs private JLabel text; private JLabel width; private JLabel height; private JTextField inputWidth; //das Feld in dem vom Benutzer die gewünschte Länge der Zeichenfläche eingetragen wird private JTextField inputHeight; //das Feld in dem vom Benutzer die gewünschte Höhe der Zeichenfläche eingetragen wird private JPanel panelInput; //Panel zum anordnen der JLabel width und height und der JTextField inputWidth und inputHeight SizeDialog(MainFrame mainFrame, JScrollPane scrollPane, Draw draw) { super(mainFrame, "Choose Size", JDialog.DEFAULT_MODALITY_TYPE); setSize(sizeX, sizeY); setResizable(false); setLayout(null); panelInput = new JPanel(); panelInput.setLayout(new FlowLayout(FlowLayout.CENTER)); width = new JLabel("Width in Pixel:"); panelInput.add(width); inputWidth = new JTextField(); inputWidth.setPreferredSize(new Dimension(50,20)); panelInput.add(inputWidth); height = new JLabel("Height in Pixel:"); panelInput.add(height); inputHeight = new JTextField(); inputHeight.setPreferredSize(new Dimension(50,20)); panelInput.add(inputHeight); text = new JLabel("Please enter an appropriate Size except less or equal zero:"); text.setLocation(5, 15); text.setSize(350,20); add(text); panelInput.setLocation(0, 40); panelInput.setSize(340, 20); add(panelInput); confirm = new JButton("Confirm"); confirm.setSize(80, 30); confirm.setLocation(50, 80); add(confirm); cancel = new JButton("Cancel"); cancel.setSize(80, 30); cancel.setLocation(215, 80); add(cancel); setEnabled(true); confirm.addActionListener(new ActionListener() { /** * Die Methode wandelt die eingegebenen Strings in Integer Zahlen um und überprüft ob es sich wirklich * um Zahlen handelt und die Zahlen <0 sind. */ @SuppressWarnings("hiding") @Override public void actionPerformed(ActionEvent e) { String width = inputWidth.getText(); String height = inputHeight.getText(); inputWidth.setText(""); inputHeight.setText(""); boolean isExcepted = false; int x = 0; int y = 0; try { x = Integer.valueOf(width); //wandelt den String width in eine Integer Zahl um y = Integer.valueOf(height); //wandelt den String height in eine Integer Zahl um if (x<=0||y<=0) //falls die Integer Zahlen x oder y nicht <0 sind wird eine Exception ausgelöst throw new Exception(); } catch (Exception e2) { /*die Exception für die Umwandlung von String zu Integer und die Exception in der If Klausel * werden hier abgefangen*/ JOptionPane.showMessageDialog(SizeDialog.this, "Please enter a correct Integer", "Wrong Input", JOptionPane.ERROR_MESSAGE); isExcepted = true; } if(!isExcepted) { dispose(); //stellt den Dialog wieder auf nicht Sichtbar mainFrame.setEnabled(true); //nach dem Dialog kann der MainFrame wieder auf Benutzt werden mainFrame.setVisible(true); //der MainFrame wird wieder als vorderstes Fenster angezeigt draw.setPreferredSize(x, y, 0, 0); scrollPane.setViewportView(draw); //das scrollPane bekommt das panelDraw übergeben damit es wenn nötig mit Scrollbalken dargestellt werden kann }else setVisible(true); //falls die Eingabe falsch war wird der Dialog erneut angezeigt } }); cancel.addActionListener(new ActionListener() { /** * Die Methode wird verwendet um den Dialog vorzeitig zu beenden. */ @Override public void actionPerformed(ActionEvent e) { dispose(); mainFrame.setEnabled(true); //nach dem Dialog kann der MainFrame wieder auf Benutzt werden mainFrame.setVisible(true); //der MainFrame wird wieder als vorderstes Fenster angezeigt } }); addWindowListener(new WindowAdapter() { @Override public void windowDeactivated(WindowEvent e) { mainFrame.setEnabled(true); //nach dem Dialog kann der MainFrame wieder benutzt werden mainFrame.setVisible(true); //der MainFrame wird wieder als vorderstes Fenster angezeigt } }); } /** * Die Methode gibt die Breite des Dialogs zurück. * @return Eine Integer Zahl die die Breite des Dialogs darstellt. */ int getSizeX() { return sizeX; } /** * Die Methode gibt die Höhe des Dialogs zurück. * @return Eine Integer Zahl die die Höhe des Dialogs darstellt. */ int getSizeY() { return sizeY; } }
9236b1ef2ff3cab28ed86230f7bdff421b6de18f
3,325
java
Java
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/model/PersistenceMetadata.java
DenitsaKostova/cf-mta-deploy-service
6a827cdbf80e06c46d086b6daf169e0bf5be7266
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/model/PersistenceMetadata.java
DenitsaKostova/cf-mta-deploy-service
6a827cdbf80e06c46d086b6daf169e0bf5be7266
[ "Apache-2.0" ]
null
null
null
com.sap.cloud.lm.sl.cf.core/src/main/java/com/sap/cloud/lm/sl/cf/core/model/PersistenceMetadata.java
DenitsaKostova/cf-mta-deploy-service
6a827cdbf80e06c46d086b6daf169e0bf5be7266
[ "Apache-2.0" ]
null
null
null
46.830986
134
0.759699
997,780
package com.sap.cloud.lm.sl.cf.core.model; public class PersistenceMetadata { public static final String NOT_AVAILABLE = "N/A"; public static class NamedQueries { public static final String FIND_ALL_ENTRIES = "find_all_entries"; public static final String FIND_ALL_SUBSCRIPTIONS = "find_all_subscriptions"; public static final String FIND_ALL_CONTEXT_EXTENSION_ENTRIES = "find_all_context_extension_entries"; public static final String FIND_ALL_CONTEXT_EXTENSION_ENTRIES_BY_PROCESS_ID = "find_all_context_extension_entries_process_id"; } public static class QueryParameters { public static final String MTA_ID = "mtaId"; public static final String LAST_QUERY_PARAM = "last"; public static final String STATUS_QUERY_PARAM = "status"; } public static class TableNames { public static final String CONFIGURATION_ENTRY_TABLE = "configuration_registry"; public static final String CONFIGURATION_SUBSCRIPTION_TABLE = "configuration_subscription"; } public static class SequenceNames { public static final String DEPLOY_TARGET_SEQUENCE = "deploy_target_sequence"; public static final String CONFIGURATION_ENTRY_SEQUENCE = "configuration_entry_sequence"; public static final String CONFIGURATION_SUBSCRIPTION_SEQUENCE = "configuration_subscription_sequence"; } public static class TableColumnNames { public static final String CONFIGURATION_ENTRY_ID = "id"; public static final String CONFIGURATION_ENTRY_PROVIDER_NID = "provider_nid"; public static final String CONFIGURATION_ENTRY_PROVIDER_ID = "provider_id"; public static final String CONFIGURATION_ENTRY_PROVIDER_VERSION = "provider_version"; public static final String CONFIGURATION_ENTRY_TARGET_ORG = "target_org"; public static final String CONFIGURATION_ENTRY_TARGET_SPACE = "target_space"; public static final String CONFIGURATION_ENTRY_CONTENT = "content"; public static final String CONFIGURATION_CLOUD_TARGET = "visibility"; public static final String CONFIGURATION_SUBSCRIPTION_MTA_ID = "mta_id"; public static final String CONFIGURATION_SUBSCRIPTION_ID = "id"; public static final String CONFIGURATION_SUBSCRIPTION_SPACE_ID = "space_id"; public static final String CONFIGURATION_SUBSCRIPTION_APP_NAME = "app_name"; public static final String CONFIGURATION_SUBSCRIPTION_RESOURCE_PROP = "resource_properties"; public static final String CONFIGURATION_SUBSCRIPTION_RESOURCE_NAME = "resource_name"; public static final String CONFIGURATION_SUBSCRIPTION_MODULE = "module"; public static final String CONFIGURATION_SUBSCRIPTION_FILTER = "filter"; public static final String CONTEXT_EXTENSION_ID = "id"; public static final String CONTEXT_EXTENSION_VARIABLE_VALUE = "value"; public static final String CONTEXT_EXTENSION_VARIABLE_NAME = "name"; public static final String CONTEXT_EXTENSION_PROCESS_ID = "process_id"; public static final String CONTEXT_EXTENSION_CREATE_TIME = "create_time"; public static final String CONTEXT_EXTENSION_UPDATE_TIME = "last_updated_time"; public static final String DEPLOY_TARGET_NAME = "name"; } }
9236b284b1624bf63138d102f3f7058c2757e3c3
8,634
java
Java
CloudServiceDeployer/src/main/java/cy/ac/ucy/linc/cloudDeployer/connectors/openstack/OpenstackConnector.java
UCY-LINC-LAB/CloudServiceDeployer
ab9e677db36da71a8856d3ecfbf3d98e297fa894
[ "Apache-2.0" ]
null
null
null
CloudServiceDeployer/src/main/java/cy/ac/ucy/linc/cloudDeployer/connectors/openstack/OpenstackConnector.java
UCY-LINC-LAB/CloudServiceDeployer
ab9e677db36da71a8856d3ecfbf3d98e297fa894
[ "Apache-2.0" ]
null
null
null
CloudServiceDeployer/src/main/java/cy/ac/ucy/linc/cloudDeployer/connectors/openstack/OpenstackConnector.java
UCY-LINC-LAB/CloudServiceDeployer
ab9e677db36da71a8856d3ecfbf3d98e297fa894
[ "Apache-2.0" ]
null
null
null
35.097561
89
0.749942
997,781
package cy.ac.ucy.linc.cloudDeployer.connectors.openstack; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import org.jclouds.ContextBuilder; import org.jclouds.compute.ComputeService; import org.jclouds.compute.ComputeServiceContext; import org.jclouds.compute.domain.ComputeMetadata; import org.jclouds.compute.domain.Image; import org.jclouds.compute.domain.NodeMetadata; import org.jclouds.logging.slf4j.config.SLF4JLoggingModule; import org.jclouds.openstack.neutron.v2.NeutronApi; import org.jclouds.openstack.neutron.v2.NeutronApiMetadata; import org.jclouds.openstack.neutron.v2.domain.Network; import org.jclouds.openstack.nova.v2_0.NovaApi; import org.jclouds.openstack.nova.v2_0.NovaApiMetadata; import org.jclouds.openstack.nova.v2_0.domain.Flavor; import org.jclouds.openstack.nova.v2_0.domain.KeyPair; import org.jclouds.openstack.nova.v2_0.domain.SecurityGroup; import org.jclouds.openstack.nova.v2_0.domain.ServerCreated; import org.jclouds.openstack.nova.v2_0.extensions.KeyPairApi; import org.jclouds.openstack.nova.v2_0.extensions.SecurityGroupApi; import org.jclouds.openstack.nova.v2_0.features.FlavorApi; import org.jclouds.openstack.nova.v2_0.features.ServerApi; import org.jclouds.openstack.nova.v2_0.options.CreateServerOptions; import com.google.common.base.Optional; import com.google.common.collect.ImmutableSet; import com.google.inject.Module; import cy.ac.ucy.linc.cloudDeployer.beans.FlavorObj; import cy.ac.ucy.linc.cloudDeployer.beans.ImageObj; import cy.ac.ucy.linc.cloudDeployer.beans.Instance; import cy.ac.ucy.linc.cloudDeployer.beans.KeyPairsObj; import cy.ac.ucy.linc.cloudDeployer.beans.NetworkObj; import cy.ac.ucy.linc.cloudDeployer.beans.SecurityGroupsObj; import cy.ac.ucy.linc.cloudDeployer.connectors.ICloudConnector; public class OpenstackConnector implements ICloudConnector { private static final String PROVIDER = "openstack-nova"; private static final String NEUTRON_PROVIDER = "openstack-neutron"; private static final String NOVA_API_VERSION = "v2.0"; private static final String DEFAULT_REGION = "regionOne"; private NovaApi novaAPI; private ComputeService computeAPI; private NeutronApi networkAPI; private Set<String> zones; private HashMap<String, String> params; public OpenstackConnector(HashMap<String, String> params) { String tenant = params.get("tenant"); String username = params.get("username"); String password = params.get("password"); String apiEndpointURL = params.get("apiEndpointURL"); String apiEndpointPort = params.get("apiEndpointPort"); String identity = tenant + ":" + username; Iterable<Module> modules = ImmutableSet .<Module> of(new SLF4JLoggingModule()); ContextBuilder builder = ContextBuilder .newBuilder(new NovaApiMetadata()) .endpoint( apiEndpointURL + ":" + apiEndpointPort + "/" + OpenstackConnector.NOVA_API_VERSION + "/") .credentials(identity, password).modules(modules); this.computeAPI = builder.buildView(ComputeServiceContext.class) .getComputeService(); this.novaAPI = builder.buildApi(NovaApi.class); this.zones = this.novaAPI.getConfiguredZones(); this.networkAPI = ContextBuilder .newBuilder(new NeutronApiMetadata()) .endpoint( apiEndpointURL + ":" + apiEndpointPort + "/" + OpenstackConnector.NOVA_API_VERSION + "/") .credentials(identity, password).modules(modules) .buildApi(NeutronApi.class); } public String createInstance(Map<String, String> params) { String instName = params.get("name"); String imageID = params.get("imageID"); String flavorID = params.get("flavor"); String net1 = params.get("network"); String[] networks = { net1 }; String keypair = params.get("keypair"); String securityGroup = params.get("securityGroup"); CreateServerOptions serverOpts = CreateServerOptions.Builder.adminPass( "linc").networks(networks); serverOpts.keyPairName(keypair); serverOpts.securityGroupNames(securityGroup); System.out .println("OpenstackConnector>> received ADD instance request, with instance name: " + instName); ServerApi serverAPI = this.novaAPI .getServerApiForZone(OpenstackConnector.DEFAULT_REGION); ServerCreated s = serverAPI.create(instName, imageID, flavorID, serverOpts); return s.getId(); } public boolean terminateInstance(String vID) { ServerApi serverAPI = this.novaAPI.getServerApiForZone(DEFAULT_REGION); if (serverAPI.delete(vID)) { System.out.println("Successfully removed instance: " + vID); return true; } else System.out.println("Instance does not exist: " + vID); return false; } public List<FlavorObj> getFlavorList(Map<String, String> params) { List<FlavorObj> flavorlist = new ArrayList<FlavorObj>(); FlavorApi zonesapi = this.novaAPI.getFlavorApiForZone(DEFAULT_REGION); for (Flavor fl : zonesapi.listInDetail().concat()) { flavorlist.add(new FlavorObj(fl.getId(), fl.getName(), fl .getVcpus(), fl.getRam(), fl.getDisk())); } return flavorlist; } public List<ImageObj> getImageList(String scope, Map<String, String> params) { List<ImageObj> imagelist = new ArrayList<ImageObj>(); for (Image i : this.computeAPI.listImages()) imagelist.add(new ImageObj(i.getId(), i.getName(), i .getDescription())); return imagelist; } public List<String> getAdditionalServices(String serviceType) { // TODO Auto-generated method stub return null; } public List<String> getQuotas(String resourceType) { // TODO Auto-generated method stub return null; } public List<NetworkObj> getNetworks() { List<NetworkObj> networklist = new ArrayList<NetworkObj>(); for (Network n : this.networkAPI .getNetworkApi(OpenstackConnector.DEFAULT_REGION).list() .concat()) { networklist.add(new NetworkObj(n.getName(), n.getId())); // System.out.println(n.getName()+" "+n.getId()); } // // Optional<? extends FloatingIPApi> zonesapi = this.novaAPI // .getFloatingIPExtensionForZone("regionOne"); // FloatingIPApi floatingapi = zonesapi.get(); // Set<? extends FloatingIP> response = floatingapi.list().toSet(); // // for (FloatingIP ip : response) { // networklist.add(new NetworkObj(ip.getFixedIp(), ip.getIp())); // } return networklist; } public List<KeyPairsObj> getKeyPairs() { List<KeyPairsObj> keypairs = new ArrayList<KeyPairsObj>(); Optional<? extends KeyPairApi> keyPairApi = this.novaAPI .getKeyPairExtensionForZone("regionOne"); KeyPairApi keypairapi = keyPairApi.get(); Set<KeyPair> response = keypairapi.list().toSet(); for (KeyPair key : response) { keypairs.add(new KeyPairsObj(key.getName(), key.getPublicKey(), key .getPrivateKey(), key.getFingerprint())); } return keypairs; } public List<SecurityGroupsObj> getSecurityGroups() { List<SecurityGroupsObj> securitygroup = new ArrayList<SecurityGroupsObj>(); Optional<? extends SecurityGroupApi> securityGroupApi = this.novaAPI .getSecurityGroupExtensionForZone(DEFAULT_REGION); SecurityGroupApi securitygroupapi = securityGroupApi.get(); Set<SecurityGroup> response = securitygroupapi.list().toSet(); for (SecurityGroup sg : response) { securitygroup.add(new SecurityGroupsObj(sg.getName(), sg .getDescription())); } return securitygroup; } public List<Instance> getInstances() { // List<Instance> instances = null; // SimpleTenantUsage simpleTenantUsage = // this.novaAPI.getSimpleTenantUsageExtensionForZone(DEFAULT_REGION).get().get("camf"); // simpleTenantUsage.getServerUsages(); // System.out.println("23"); List<Instance> instances = new ArrayList<Instance>(); for (ComputeMetadata i : this.computeAPI.listNodes()) { // get NodeMetadata based on NodeID NodeMetadata nodeData = this.computeAPI.getNodeMetadata(i.getId()); /* * SimpleTenantUsageApi api = this.novaAPI * .getSimpleTenantUsageExtensionForZone(DEFAULT_REGION).get(); * Set<? extends SimpleTenantUsage> results = api.list().toSet(); * * SimpleTenantUsage usage = Iterables.getOnlyElement(results); * System.out.println(usage.getTotalHours()); */ instances.add(new Instance(i.getId(), i.getName(), nodeData .getPrivateAddresses().toString(), nodeData.getStatus() .toString(), i.getUri().toString())); } return instances; } public String createImageFromInstance(String imageName, String instanceID) { ServerApi serverAPI = this.novaAPI .getServerApiForZone(OpenstackConnector.DEFAULT_REGION); String imageID = serverAPI.createImageFromServer(imageName, instanceID); return imageID; } }
9236b28b3dd7ad3d1e9c1de697f9d93c7c15026c
2,391
java
Java
hawaii-core/src/main/java/org/hawaiiframework/crypto/HawaiiUrlSafeStringEncryptor.java
hawaiifw/hawaiiframework
506eb6be5a76c6203d3e2b48b82f2c25782a824d
[ "X11", "Apache-2.0", "OLDAP-2.2.1" ]
6
2016-11-15T23:00:47.000Z
2020-11-30T01:57:19.000Z
hawaii-core/src/main/java/org/hawaiiframework/crypto/HawaiiUrlSafeStringEncryptor.java
hawaiifw/hawaiiframework
506eb6be5a76c6203d3e2b48b82f2c25782a824d
[ "X11", "Apache-2.0", "OLDAP-2.2.1" ]
11
2016-04-16T07:45:05.000Z
2020-09-22T07:08:15.000Z
hawaii-core/src/main/java/org/hawaiiframework/crypto/HawaiiUrlSafeStringEncryptor.java
hawaiifw/hawaii-framework
506eb6be5a76c6203d3e2b48b82f2c25782a824d
[ "X11", "Apache-2.0", "OLDAP-2.2.1" ]
19
2016-04-13T13:17:09.000Z
2020-09-21T13:41:43.000Z
31.88
96
0.680468
997,782
package org.hawaiiframework.crypto; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.util.Strings; import org.bouncycastle.util.encoders.UrlBase64; import org.hawaiiframework.exception.HawaiiException; import javax.crypto.Cipher; import java.nio.charset.Charset; import java.security.GeneralSecurityException; import java.security.Security; /** * Hawaii String Encryptor with Url safe base64 encoding. */ public class HawaiiUrlSafeStringEncryptor extends HawaiiStringEncryptor { static { Security.addProvider(new BouncyCastleProvider()); } private final String key; private final String initVector; /** * Creates a new {@code HawaiiUrlSafeStringEncryptor} with the given key and init vector. * * @param key the key used for encryption/decryption * @param initVector the init vector used for encryption/decryption */ public HawaiiUrlSafeStringEncryptor(final String key, final String initVector) { super(key, initVector); this.key = key; this.initVector = initVector; } /** * Encrypt the input message. * * @param message the message to be encrypted * @return the result of encryption */ @Override public String encrypt(final String message) { try { final Cipher cipher = initCipher(Cipher.ENCRYPT_MODE, key, initVector); final byte[] encrypted = cipher.doFinal(message.getBytes(Charset.defaultCharset())); final byte[] encoded = UrlBase64.encode(encrypted); return Strings.fromByteArray(encoded); } catch (GeneralSecurityException e) { throw new HawaiiException("Error encrypting message", e); } } /** * Decrypt the encrypted input message. * * @param encryptedMessage the message to be decrypted * @return the result of decryption */ @Override public String decrypt(final String encryptedMessage) { try { final Cipher cipher = initCipher(Cipher.DECRYPT_MODE, key, initVector); final byte[] decrypted = cipher.doFinal(UrlBase64.decode(encryptedMessage)); return new String(decrypted, Charset.defaultCharset()); } catch (GeneralSecurityException e) { throw new HawaiiException("Error decrypting message", e); } } }
9236b34a43b17ca0823d62843a7c55965cccfc90
1,175
java
Java
gs-spring-boot/gs-spring-boot-app/src/test/java/com/tirthal/learning/JunitHemcrestAssertjDemoTest.java
akondasif/Learning-Spring
e13914a65a6fe623e88ec4a8394e6dccfe1c7c37
[ "MIT" ]
1
2018-05-28T02:42:55.000Z
2018-05-28T02:42:55.000Z
gs-spring-boot/gs-spring-boot-app/src/test/java/com/tirthal/learning/JunitHemcrestAssertjDemoTest.java
akondasif/Learning-Spring
e13914a65a6fe623e88ec4a8394e6dccfe1c7c37
[ "MIT" ]
3
2021-01-21T01:06:19.000Z
2022-01-21T23:19:30.000Z
gs-spring-boot/gs-spring-boot-app/src/test/java/com/tirthal/learning/JunitHemcrestAssertjDemoTest.java
akondasif/Learning-Spring
e13914a65a6fe623e88ec4a8394e6dccfe1c7c37
[ "MIT" ]
6
2017-12-14T08:05:29.000Z
2021-03-23T05:44:58.000Z
24.479167
99
0.716596
997,783
package com.tirthal.learning; import org.junit.Test; import org.springframework.boot.test.context.TestComponent; import static org.junit.Assert.assertEquals; import org.junit.Before; import static org.hamcrest.Matchers.*; import com.tirthal.learning.controller.HomeRestController; @TestComponent public class JunitHemcrestAssertjDemoTest { String result = null; @Before public void setup() { HomeRestController hc = new HomeRestController(); result = hc.home(); } @Test public void testHomeResultUsingJunit() { // Assert using JUnit assertEquals(result, "Welcome to the Spring Boot application!"); } @Test public void testHomeResultUsingHemcrest() { // Assert using Hemcrest - yeah, code is more readable org.hamcrest.MatcherAssert.assertThat(result, is("Welcome to the Spring Boot application!")); } @Test public void testHomeResultUsingAssertJ() { // Assert using AssertJ - a fluent assertion library org.assertj.core.api.Assertions.assertThat(result).startsWith("Welcome") .endsWith("application!") .isEqualTo("Welcome to the Spring Boot application!"); } }
9236b3d4dbed6bcf2010a33b163fe2cbcb7e80aa
3,810
java
Java
src/test/java/br/unicap/ed2/arvore/ArvoreBinariaTest.java
incogbyte/ed2-arvores
077566e8bd671fdb5764be486cfe88bfd5882994
[ "Apache-2.0" ]
1
2022-03-10T12:12:46.000Z
2022-03-10T12:12:46.000Z
src/test/java/br/unicap/ed2/arvore/ArvoreBinariaTest.java
incogbyte/ed2-arvores
077566e8bd671fdb5764be486cfe88bfd5882994
[ "Apache-2.0" ]
null
null
null
src/test/java/br/unicap/ed2/arvore/ArvoreBinariaTest.java
incogbyte/ed2-arvores
077566e8bd671fdb5764be486cfe88bfd5882994
[ "Apache-2.0" ]
8
2022-03-07T15:04:03.000Z
2022-03-14T14:24:54.000Z
22.951807
62
0.518635
997,784
package br.unicap.ed2.arvore; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import br.unicap.ed2.base.No; import br.unicap.ed2.bst.ArvoreBinariaDePesquisa; public class ArvoreBinariaTest { ArvoreBinariaDePesquisa a = new ArvoreBinariaDePesquisa(); public void clearTree(){ a.clear(); } @Test public void testaInserir() { a.inserir(10); a.inserir(1); a.inserir(15); a.inserir(12); a.inserir(20); a.inserir(25); //Testa Raiz assertTrue(a.procurar(10) != null); assertTrue(a.ehRaiz(10)); No no = a.procurar(10); assertTrue(no.getEsquerda().getChave() == 1); assertTrue(no.getDireita().getChave() == 15); //teste Meio assertTrue(a.procurar(15) != null); no = a.procurar(15); assertTrue(no.getEsquerda().getChave() == 12); assertTrue(no.getDireita().getChave() == 20); //teste Folha assertTrue(a.procurar(25) != null); no = a.procurar(25); assertTrue(no.getEsquerda() == null); assertTrue(no.getDireita() == null); // Testa existencia de outros assertTrue(a.procurar(1) != null); assertTrue(a.procurar(12) != null); assertTrue(a.procurar(20) != null); } @Test public void testaDeletarFolha() { a.inserir(10); a.inserir(1); a.inserir(15); a.inserir(12); a.inserir(20); a.inserir(25); No aux; //Deletar Folha 25 aux = a.procurar(25); assertTrue(aux != null); assertTrue(aux.getChave() == 25); a.deletar(25); aux = a.procurar(25); assertTrue(aux == null); //Deletar Folha 20 e 12 aux = a.procurar(20); assertTrue(aux != null); assertTrue(aux.getChave() == 20); aux = a.procurar(12); assertTrue(aux != null); assertTrue(aux.getChave() == 12); a.deletar(20); a.deletar(12); aux = a.procurar(20); assertTrue(aux == null); aux = a.procurar(12); assertTrue(aux == null); } @Test public void testaDeletarInesxistente() { a.inserir(10); a.inserir(1); a.inserir(15); a.inserir(12); a.inserir(20); a.inserir(25); No aux; //Deletar Inexistente a.deletar(30); aux = a.procurar(30); assertTrue(aux == null); } @Test public void testaDeletarFilhoUnico() { a.inserir(10); a.inserir(1); a.inserir(15); a.inserir(12); a.inserir(20); a.inserir(25); No aux; //Deletar Unico Filho aux = a.procurar(20); assertTrue(aux != null); assertTrue(aux.getChave() == 20); a.deletar(20); aux = a.procurar(20); assertTrue(aux == null); //Deletar Raiz a.deletar(1); aux = a.procurar(1); assertTrue(aux == null); aux = a.procurar(10); assertTrue(aux != null); assertTrue(aux.getChave() == 10); assertTrue(a.ehRaiz(10)); a.deletar(10); aux = a.procurar(10); assertTrue(aux == null); assertTrue(a.ehRaiz(15)); } @Test public void testaDeletarDoisFilhos() { a.inserir(10); a.inserir(1); a.inserir(15); a.inserir(12); a.inserir(20); a.inserir(25); No aux; //Deletar Dois Filho aux = a.procurar(20); assertTrue(aux != null); assertTrue(aux.getChave() == 20); a.deletar(20); aux = a.procurar(20); assertTrue(aux == null); } }
9236b4c894253c435512517377c9cd8ab19cdaa8
996
java
Java
src/main/java/jhi/gatekeeper/server/exception/EmailException.java
HuttonICS/gatekeeper-server
5e0d1daee698d8d453d69f03ef59d6d22b21322c
[ "Apache-2.0" ]
null
null
null
src/main/java/jhi/gatekeeper/server/exception/EmailException.java
HuttonICS/gatekeeper-server
5e0d1daee698d8d453d69f03ef59d6d22b21322c
[ "Apache-2.0" ]
1
2020-11-11T07:33:54.000Z
2020-11-12T14:45:24.000Z
src/main/java/jhi/gatekeeper/server/exception/EmailException.java
HuttonICS/gatekeeper-server
5e0d1daee698d8d453d69f03ef59d6d22b21322c
[ "Apache-2.0" ]
null
null
null
23.714286
75
0.73996
997,785
/* * Copyright 2017 Information and Computational Sciences, * The James Hutton Institute. * * 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 jhi.gatekeeper.server.exception; import java.io.Serializable; /** * @author Sebastian Raubach */ public class EmailException extends Exception implements Serializable { public EmailException() { super(); } public EmailException(String message) { super(message); } public EmailException(Exception e) { super(e); } }
9236b57d32892ed7b42e0784f9373b084023191b
531
java
Java
1.JavaSyntax/src/Test/Other/Test10.java
BelousAI/JavaRushTasks
da1fc267fbcfbc32e4e86886fcac11d10fe86ce0
[ "Apache-2.0" ]
null
null
null
1.JavaSyntax/src/Test/Other/Test10.java
BelousAI/JavaRushTasks
da1fc267fbcfbc32e4e86886fcac11d10fe86ce0
[ "Apache-2.0" ]
null
null
null
1.JavaSyntax/src/Test/Other/Test10.java
BelousAI/JavaRushTasks
da1fc267fbcfbc32e4e86886fcac11d10fe86ce0
[ "Apache-2.0" ]
null
null
null
21.24
71
0.563089
997,786
package Test.Other; import java.util.Arrays; import java.util.HashMap; import java.util.List; /** * Created by Антон on 30.03.2017. */ public class Test10 { public static void main(String[] args) { List<Integer> list = Arrays.asList(2,2,2,3,2,3,2,2,3,3,3,5,5); HashMap<Integer, Integer> hm = new HashMap<Integer, Integer>(); Integer am; for (Integer i : list) { am = hm.get(i); hm.put(i, am == null ? 1 : am + 1); } System.out.println(hm); } }
9236b62d6bcd5fc286c7cc65ea3f2b0238ae87c5
1,377
java
Java
src/main/java/ca/eve/app/tiger/domain/Season.java
dzca/eve
904c2d80862419b38b556fa95d8e467318b48f9e
[ "MIT" ]
null
null
null
src/main/java/ca/eve/app/tiger/domain/Season.java
dzca/eve
904c2d80862419b38b556fa95d8e467318b48f9e
[ "MIT" ]
null
null
null
src/main/java/ca/eve/app/tiger/domain/Season.java
dzca/eve
904c2d80862419b38b556fa95d8e467318b48f9e
[ "MIT" ]
null
null
null
16.590361
111
0.684096
997,787
package ca.eve.app.tiger.domain; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import io.swagger.annotations.ApiModel; @ApiModel(description = "All details about the club season.") @Entity @Table(name = "tiger_club_season") public class Season { @Id @GeneratedValue Long id; String name; String school; String address; Date startDate; Date endDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @Override public String toString() { return "Season [id=" + id + ", name=" + name + ", school=" + school + ", address=" + address + ", startDate=" + startDate + ", endDate=" + endDate + "]"; } }
9236b636f911bfd2fece003770e9ba017f452911
4,201
java
Java
app/src/main/java/com/example/android/popularmovies/MovieDbApiUtils.java
sakydpozrux/PopularMovies
97f4dd879bb2ffd12a35c504a0a93d8fbe5e5671
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/popularmovies/MovieDbApiUtils.java
sakydpozrux/PopularMovies
97f4dd879bb2ffd12a35c504a0a93d8fbe5e5671
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/popularmovies/MovieDbApiUtils.java
sakydpozrux/PopularMovies
97f4dd879bb2ffd12a35c504a0a93d8fbe5e5671
[ "Apache-2.0" ]
null
null
null
30.664234
102
0.597953
997,788
package com.example.android.popularmovies; import android.content.Context; import android.net.Uri; import android.widget.ImageView; import com.squareup.picasso.Picasso; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; import java.util.regex.Pattern; /** * Created by sakydpozrux on 07/03/2017. */ public class MovieDbApiUtils { private final static String API_URL = "http://api.themoviedb.org"; private final static String[] API_PATH = { "3", "movie" }; private final static String IMAGES_URL = "http://image.tmdb.org"; private final static String[] IMAGES_PATH = { "t", "p", "w185" }; private final static String VIDEOS_PATH = "videos"; private final static String REVIEWS_PATH = "reviews"; private final static String API_PATH_POPULAR = "popular"; private final static String API_PATH_TOP_RATED = "top_rated"; private final static String PARAM_KEY = "api_key"; public static boolean isApiKeyFormatValid(String key) { final String regex = "[\\p{XDigit}]{32}"; final Pattern apiKeyPattern = Pattern.compile(regex); return apiKeyPattern.matcher(key).matches(); } public enum SortOrder { POPULAR(API_PATH_POPULAR), TOP_RATED(API_PATH_TOP_RATED), FAVORITES("favorites"); private final String text; SortOrder (final String text) { this.text = text; } @Override public String toString() { return text; } } public static URL buildUrl(String apiKey, SortOrder order) { Uri uri = Uri.parse(API_URL).buildUpon() .appendPath(API_PATH[0]) .appendPath(API_PATH[1]) .appendPath(order.toString()) .appendQueryParameter(PARAM_KEY, apiKey).build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public static URL buildUrlVideos(String apiKey, String id) { Uri uri = Uri.parse(API_URL).buildUpon() .appendPath(API_PATH[0]) .appendPath(API_PATH[1]) .appendPath(id) .appendPath(VIDEOS_PATH) .appendQueryParameter(PARAM_KEY, apiKey).build(); URL url = null; try{ url = new URL(uri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public static URL buildUrlReviews(String apiKey, String id) { Uri uri = Uri.parse(API_URL).buildUpon() .appendPath(API_PATH[0]) .appendPath(API_PATH[1]) .appendPath(id) .appendPath(REVIEWS_PATH) .appendQueryParameter(PARAM_KEY, apiKey).build(); URL url = null; try{ url = new URL(uri.toString()); } catch (MalformedURLException e) { e.printStackTrace(); } return url; } public static void fillImageView(Context context, ImageView imageView, String imageRelativePath) { Uri uri = Uri.parse(IMAGES_URL).buildUpon() .appendPath(IMAGES_PATH[0]) .appendPath(IMAGES_PATH[1]) .appendPath(IMAGES_PATH[2]) .appendPath(imageRelativePath.substring(1)).build(); Picasso.with(context).load(uri.toString()).into(imageView); } public static String getResponseFromHttpUrl(URL url) throws IOException { HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); try { InputStream in = urlConnection.getInputStream(); Scanner scanner = new Scanner(in); scanner.useDelimiter("\\A"); boolean hasInput = scanner.hasNext(); if (hasInput) { return scanner.next(); } else { return null; } } finally { urlConnection.disconnect(); } } }
9236b6995ae0d341c4cc753a2df36d12dde8bcc5
206
java
Java
limbus-staging/src/main/java/com/remondis/limbus/staging/staging/package-info.java
remondis-it/limbus-engine
3e1c5762c928ea98881a826c0e449b5ab6490ce4
[ "Apache-2.0" ]
3
2018-05-21T13:34:36.000Z
2018-09-20T06:09:09.000Z
limbus-staging/src/main/java/com/remondis/limbus/staging/staging/package-info.java
remondis-it/limbus-engine
3e1c5762c928ea98881a826c0e449b5ab6490ce4
[ "Apache-2.0" ]
2
2020-05-07T13:14:56.000Z
2020-05-07T13:20:22.000Z
limbus-staging/src/main/java/com/remondis/limbus/staging/staging/package-info.java
remondis-it/limbus-engine
3e1c5762c928ea98881a826c0e449b5ab6490ce4
[ "Apache-2.0" ]
1
2020-08-09T03:22:35.000Z
2020-08-09T03:22:35.000Z
34.333333
117
0.76699
997,789
package com.remondis.limbus.staging.staging; /** * This package is needed to specify the URL protocol name for the handler implementation that is defined within this * package. Do not move or rename! */
9236b76f64b629051b7aad2f2ad58ce8e47a7663
352
java
Java
quickprotocol-core/src/main/java/Quick/Protocol/Listeners/CommandResponsePackageReceivedListener.java
QuickProtocol/QuickProtocol_Java
c3415e18b3b3e81dbc897a05e1f32c313c4602b7
[ "Apache-2.0" ]
null
null
null
quickprotocol-core/src/main/java/Quick/Protocol/Listeners/CommandResponsePackageReceivedListener.java
QuickProtocol/QuickProtocol_Java
c3415e18b3b3e81dbc897a05e1f32c313c4602b7
[ "Apache-2.0" ]
null
null
null
quickprotocol-core/src/main/java/Quick/Protocol/Listeners/CommandResponsePackageReceivedListener.java
QuickProtocol/QuickProtocol_Java
c3415e18b3b3e81dbc897a05e1f32c313c4602b7
[ "Apache-2.0" ]
null
null
null
23.466667
107
0.704545
997,790
package Quick.Protocol.Listeners; public interface CommandResponsePackageReceivedListener { /** * 执行 * * @param commandId 命令编号 * @param code 响应码 * @param message 错误消息 * @param typeName 类型名称 * @param content 内容 */ public abstract void Invoke(String commandId, byte code, String message, String typeName, String content); }
9236b7a4667ecd36dae2d5a88bc23cddbd999b86
3,565
java
Java
src/main/java/maxhyper/dynamictreessugiforest/genfeatures/FeatureGenFallenLeaves.java
DynamicTreesTeam/DynamicTrees-SugiForest
d24ff220ca7f9cbc64042b56dd026a7af20984ad
[ "MIT" ]
null
null
null
src/main/java/maxhyper/dynamictreessugiforest/genfeatures/FeatureGenFallenLeaves.java
DynamicTreesTeam/DynamicTrees-SugiForest
d24ff220ca7f9cbc64042b56dd026a7af20984ad
[ "MIT" ]
null
null
null
src/main/java/maxhyper/dynamictreessugiforest/genfeatures/FeatureGenFallenLeaves.java
DynamicTreesTeam/DynamicTrees-SugiForest
d24ff220ca7f9cbc64042b56dd026a7af20984ad
[ "MIT" ]
null
null
null
40.511364
192
0.671248
997,791
package maxhyper.dynamictreessugiforest.genfeatures; import com.ferreusveritas.dynamictrees.api.IPostGenFeature; import com.ferreusveritas.dynamictrees.api.IPostGrowFeature; import com.ferreusveritas.dynamictrees.blocks.BlockDynamicLeaves; import com.ferreusveritas.dynamictrees.trees.Species; import com.ferreusveritas.dynamictrees.util.SafeChunkBounds; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import net.minecraft.world.biome.Biome; import sugiforest.block.BlockSugiFallenLeaves; import sugiforest.core.Config; import java.util.List; public class FeatureGenFallenLeaves implements IPostGenFeature, IPostGrowFeature { protected final Block leafPileBlock; public FeatureGenFallenLeaves(Block leafPile){ leafPileBlock = leafPile; } private static final int maxLayer = 6; @Override public boolean postGrow(World world, BlockPos rootPos, BlockPos treePos, Species species, int soilLife, boolean natural) { if(world.rand.nextInt() % 64 == 0) { addFallenLeaves(world, rootPos,1, false); } return false; } @Override public boolean postGeneration(World world, BlockPos rootPos, Species species, Biome biome, int radius, List<BlockPos> endPoints, SafeChunkBounds safeBounds, IBlockState initialDirtState) { addFallenLeaves(world, rootPos,6, true); return true; } private boolean addFallenLeaf(World world, BlockPos pos){ BlockPos blockpos = pos.up(); while (!(world.getBlockState(blockpos).getProperties().containsKey(BlockDynamicLeaves.HYDRO))) { blockpos = blockpos.up(); if (blockpos.getY() > pos.getY() + 20){ return false; } } blockpos = blockpos.down(); while (blockpos.getY() > 0 && world.isAirBlock(blockpos)) { blockpos = blockpos.down(); } if (blockpos.getY() == 0){ return false; } blockpos = blockpos.up(); if (leafPileBlock.canPlaceBlockAt(world, blockpos) && world.getBlockState(blockpos.down()).getBlock() != leafPileBlock) { world.setBlockState(blockpos, leafPileBlock.getDefaultState().withProperty(BlockSugiFallenLeaves.CHANCE, Boolean.TRUE)); return true; } else { blockpos = blockpos.down(); IBlockState state = world.getBlockState(blockpos); if (state.getBlock() instanceof BlockSugiFallenLeaves) { int layers = state.getValue(BlockSugiFallenLeaves.LAYERS); if (layers > maxLayer) return false; world.setBlockState(blockpos, leafPileBlock.getDefaultState().withProperty(BlockSugiFallenLeaves.LAYERS, layers + 1).withProperty(BlockSugiFallenLeaves.CHANCE, Boolean.TRUE)); return true; } } return false; } private void addFallenLeaves(World world, BlockPos rootPos, int amount, boolean worldGen) { if (!Config.fallenSugiLeaves) return; int leaveRange = 4; for (int attempts = amount*10; attempts > 0; attempts--){ int randX = world.rand.nextInt((2*leaveRange)+1)-leaveRange; int randZ = world.rand.nextInt((2*leaveRange)+1)-leaveRange; BlockPos selectedPos = new BlockPos(rootPos.getX() + randX, rootPos.getY(), rootPos.getZ() + randZ); if (addFallenLeaf(world, selectedPos)){ amount--; } } } }
9236b7bd2a348addb114d5a3b78892387a40e836
4,083
java
Java
tracker-agent/src/main/java/c8y/trackeragent/devicebootstrap/DeviceBootstrapProcessor.java
reschrei1/cumulocity
bd29d1d05405e0ddbc14424da9391ff9381872e8
[ "MIT" ]
1
2019-02-22T20:58:09.000Z
2019-02-22T20:58:09.000Z
tracker-agent/src/main/java/c8y/trackeragent/devicebootstrap/DeviceBootstrapProcessor.java
reschrei1/cumulocity
bd29d1d05405e0ddbc14424da9391ff9381872e8
[ "MIT" ]
null
null
null
tracker-agent/src/main/java/c8y/trackeragent/devicebootstrap/DeviceBootstrapProcessor.java
reschrei1/cumulocity
bd29d1d05405e0ddbc14424da9391ff9381872e8
[ "MIT" ]
null
null
null
44.868132
151
0.768553
997,792
package c8y.trackeragent.devicebootstrap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Component; import com.cumulocity.rest.representation.devicebootstrap.DeviceCredentialsRepresentation; import com.cumulocity.sdk.client.SDKException; import com.cumulocity.sdk.client.devicecontrol.DeviceCredentialsApi; import c8y.trackeragent.TrackerAgent; import c8y.trackeragent.utils.TrackerPlatformProvider; @Component public class DeviceBootstrapProcessor { protected static Logger logger = LoggerFactory.getLogger(DeviceBootstrapProcessor.class); private final DeviceCredentialsApi deviceCredentialsApi; private final DeviceCredentialsRepository credentialsRepository; private final TrackerPlatformProvider platformProvider; private final TenantBinder tenantBinder; @Autowired public DeviceBootstrapProcessor(TrackerAgent trackerAgent, TrackerPlatformProvider trackerPlatformProvider, DeviceCredentialsRepository deviceCredentialsRepository, TenantBinder tenantBinder) { this.credentialsRepository = deviceCredentialsRepository; this.tenantBinder = tenantBinder; this.platformProvider = trackerPlatformProvider; this.deviceCredentialsApi = platformProvider.getBootstrapPlatform().getDeviceCredentialsApi(); } public DeviceCredentials tryAccessDeviceCredentials(String imei) { logger.info("Start bootstrapping: {}", imei); DeviceCredentialsRepresentation credentialsRepresentation = pollCredentials(imei); if (credentialsRepresentation == null) { return null; } else { return onNewDeviceCredentials(credentialsRepresentation); } } public DeviceCredentials tryAccessAgentCredentials(String tenant) { logger.info("Start bootstrapping agent for tenant: {}", tenant); String newDeviceRequestId = "tracker-agent-" + tenant; DeviceCredentialsRepresentation credentialsRepresentation = pollCredentials(newDeviceRequestId); if (credentialsRepresentation == null) { return null; } else { return onNewAgentCredentials(credentialsRepresentation); } } private DeviceCredentials onNewAgentCredentials(DeviceCredentialsRepresentation credentialsRep) { DeviceCredentials credentials = DeviceCredentials.forAgent(credentialsRep.getTenantId(), credentialsRep.getUsername(), credentialsRep.getPassword()); credentialsRepository.saveAgentCredentials(credentials); //platformProvider.initTenantPlatform(credentials.getTenant()); tenantBinder.bind(credentials.getTenant()); logger.info("Agent for tenant {} bootstraped. Following devices start working: {}", credentials.getTenant(), credentialsRepository.getAllDeviceCredentials(credentials.getTenant())); return credentials; } private DeviceCredentials onNewDeviceCredentials(DeviceCredentialsRepresentation credentialsRep) { boolean hasAgentCredentials = credentialsRepository.hasAgentCredentials(credentialsRep.getTenantId()); DeviceCredentials credentials = DeviceCredentials.forDevice(credentialsRep.getId(), credentialsRep.getTenantId()); logger.info("Credentials for imei {} accessed: {}.", credentials.getImei(), credentials); credentialsRepository.saveDeviceCredentials(credentials); if (!hasAgentCredentials) { tryAccessAgentCredentials(credentials.getTenant()); } return credentials; } private DeviceCredentialsRepresentation pollCredentials(final String newDeviceRequestId) { try { return deviceCredentialsApi.pollCredentials(newDeviceRequestId); } catch (SDKException e) { if (e.getHttpStatus() == HttpStatus.NOT_FOUND.value()) { logger.debug("Credentials not yet available for device: " + newDeviceRequestId); } else { logger.error("Failed to retrieve credentials from cumulocity.", e); } } return null; } }
9236b9559328c7a46a6cf9d63b674265331b358a
1,280
java
Java
dubbo-plugin/dubbo-qos/src/main/java/com/alibaba/dubbo/qos/command/impl/Quit.java
extrend-xuxw/dubbo
c5db1c39e686e79f3ce9e9ea0876ee6dd089b4a4
[ "Apache-2.0" ]
429
2018-01-21T13:38:16.000Z
2022-03-31T02:50:40.000Z
dubbo-plugin/dubbo-qos/src/main/java/com/alibaba/dubbo/qos/command/impl/Quit.java
extrend-xuxw/dubbo
c5db1c39e686e79f3ce9e9ea0876ee6dd089b4a4
[ "Apache-2.0" ]
14
2019-12-24T06:48:41.000Z
2021-12-25T02:14:23.000Z
dubbo-plugin/dubbo-qos/src/main/java/com/alibaba/dubbo/qos/command/impl/Quit.java
extrend-xuxw/dubbo
c5db1c39e686e79f3ce9e9ea0876ee6dd089b4a4
[ "Apache-2.0" ]
354
2018-03-12T01:29:47.000Z
2022-03-03T03:25:09.000Z
41.290323
75
0.761719
997,793
/* * 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.alibaba.dubbo.qos.command.impl; import com.alibaba.dubbo.qos.command.BaseCommand; import com.alibaba.dubbo.qos.command.CommandContext; import com.alibaba.dubbo.qos.command.annotation.Cmd; import com.alibaba.dubbo.qos.common.QosConstants; @Cmd(name = "quit",summary = "quit telnet console") public class Quit implements BaseCommand { @Override public String execute(CommandContext commandContext, String[] args) { return QosConstants.CLOSE; } }
9236b9cdbfbc7039a9cf0ca23b8ef193e2a8bd09
2,450
java
Java
src/cmps252/HW4_2/UnitTesting/record_4425.java
issasaidi/cmps252_hw4.2
f8e96065e2a4f172c8b685f03f954694f4810c14
[ "MIT" ]
1
2020-10-27T22:16:21.000Z
2020-10-27T22:16:21.000Z
src/cmps252/HW4_2/UnitTesting/record_4425.java
issasaidi/cmps252_hw4.2
f8e96065e2a4f172c8b685f03f954694f4810c14
[ "MIT" ]
2
2020-10-27T17:31:16.000Z
2020-10-28T02:16:49.000Z
src/cmps252/HW4_2/UnitTesting/record_4425.java
issasaidi/cmps252_hw4.2
f8e96065e2a4f172c8b685f03f954694f4810c14
[ "MIT" ]
108
2020-10-26T11:54:05.000Z
2021-01-16T20:00:17.000Z
25.541667
77
0.734095
997,794
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("40") class Record_4425 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 4425: FirstName is Luciano") void FirstNameOfRecord4425() { assertEquals("Luciano", customers.get(4424).getFirstName()); } @Test @DisplayName("Record 4425: LastName is Legath") void LastNameOfRecord4425() { assertEquals("Legath", customers.get(4424).getLastName()); } @Test @DisplayName("Record 4425: Company is Image Maker") void CompanyOfRecord4425() { assertEquals("Image Maker", customers.get(4424).getCompany()); } @Test @DisplayName("Record 4425: Address is 525 Commerce Dr") void AddressOfRecord4425() { assertEquals("525 Commerce Dr", customers.get(4424).getAddress()); } @Test @DisplayName("Record 4425: City is Upper Marlboro") void CityOfRecord4425() { assertEquals("Upper Marlboro", customers.get(4424).getCity()); } @Test @DisplayName("Record 4425: County is Prince Georges") void CountyOfRecord4425() { assertEquals("Prince Georges", customers.get(4424).getCounty()); } @Test @DisplayName("Record 4425: State is MD") void StateOfRecord4425() { assertEquals("MD", customers.get(4424).getState()); } @Test @DisplayName("Record 4425: ZIP is 20772") void ZIPOfRecord4425() { assertEquals("20772", customers.get(4424).getZIP()); } @Test @DisplayName("Record 4425: Phone is 301-736-1622") void PhoneOfRecord4425() { assertEquals("301-736-1622", customers.get(4424).getPhone()); } @Test @DisplayName("Record 4425: Fax is 301-736-4136") void FaxOfRecord4425() { assertEquals("301-736-4136", customers.get(4424).getFax()); } @Test @DisplayName("Record 4425: Email is nnheo@example.com") void EmailOfRecord4425() { assertEquals("nnheo@example.com", customers.get(4424).getEmail()); } @Test @DisplayName("Record 4425: Web is http://www.lucianolegath.com") void WebOfRecord4425() { assertEquals("http://www.lucianolegath.com", customers.get(4424).getWeb()); } }
9236ba07b044be94c72fc269835735c3dd1054a1
622
java
Java
src/main/java/com/rafaelcostab/delivery/api/exceptionhandler/Mistake.java
rafaelcostab/delivery-api
eb2a3c4cbf268fe18d23d1f00eac60c79e6fe63d
[ "MIT" ]
null
null
null
src/main/java/com/rafaelcostab/delivery/api/exceptionhandler/Mistake.java
rafaelcostab/delivery-api
eb2a3c4cbf268fe18d23d1f00eac60c79e6fe63d
[ "MIT" ]
null
null
null
src/main/java/com/rafaelcostab/delivery/api/exceptionhandler/Mistake.java
rafaelcostab/delivery-api
eb2a3c4cbf268fe18d23d1f00eac60c79e6fe63d
[ "MIT" ]
1
2021-06-16T16:27:04.000Z
2021-06-16T16:27:04.000Z
19.4375
60
0.800643
997,795
package com.rafaelcostab.delivery.api.exceptionhandler; import java.time.OffsetDateTime; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; @JsonInclude(Include.NON_NULL) @Getter @Setter public class Mistake { private Integer status; private OffsetDateTime whenOccurred; private String description; private List<field> fields; @AllArgsConstructor @Getter public static class field { private String name; private String message; } }
9236bb1726f985edd76ee82388b970c4152ad36d
10,649
java
Java
src/main/java/com/tencentcloudapi/cloudaudit/v20190319/models/DescribeAuditResponse.java
githubWangbo/tencentcloud-sdk-java
c490a478c4cd6d0a262c7b72c2e65af7578377cf
[ "Apache-2.0" ]
416
2018-05-16T03:36:25.000Z
2022-03-31T03:48:52.000Z
src/main/java/com/tencentcloudapi/cloudaudit/v20190319/models/DescribeAuditResponse.java
githubWangbo/tencentcloud-sdk-java
c490a478c4cd6d0a262c7b72c2e65af7578377cf
[ "Apache-2.0" ]
117
2018-05-03T07:11:06.000Z
2022-03-09T11:07:55.000Z
src/main/java/com/tencentcloudapi/cloudaudit/v20190319/models/DescribeAuditResponse.java
githubWangbo/tencentcloud-sdk-java
c490a478c4cd6d0a262c7b72c2e65af7578377cf
[ "Apache-2.0" ]
236
2018-05-10T03:15:09.000Z
2022-03-05T02:17:51.000Z
25.234597
89
0.607663
997,796
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cloudaudit.v20190319.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DescribeAuditResponse extends AbstractModel{ /** * 是否开启cmq消息通知。1:是,0:否。 */ @SerializedName("IsEnableCmqNotify") @Expose private Long IsEnableCmqNotify; /** * 管理事件读写属性,1:只读,2:只写,3:全部 */ @SerializedName("ReadWriteAttribute") @Expose private Long ReadWriteAttribute; /** * CMK的全局唯一标识符。 */ @SerializedName("KeyId") @Expose private String KeyId; /** * 跟踪集状态,1:开启,0:停止。 */ @SerializedName("AuditStatus") @Expose private Long AuditStatus; /** * 跟踪集名称。 */ @SerializedName("AuditName") @Expose private String AuditName; /** * cos存储桶所在地域。 */ @SerializedName("CosRegion") @Expose private String CosRegion; /** * 队列名称。 */ @SerializedName("CmqQueueName") @Expose private String CmqQueueName; /** * CMK别名。 */ @SerializedName("KmsAlias") @Expose private String KmsAlias; /** * kms地域。 */ @SerializedName("KmsRegion") @Expose private String KmsRegion; /** * 是否开启kms加密。1:是,0:否。如果开启KMS加密,数据在投递到cos时,会将数据加密。 */ @SerializedName("IsEnableKmsEncry") @Expose private Long IsEnableKmsEncry; /** * cos存储桶名称。 */ @SerializedName("CosBucketName") @Expose private String CosBucketName; /** * 队列所在地域。 */ @SerializedName("CmqRegion") @Expose private String CmqRegion; /** * 日志前缀。 */ @SerializedName("LogFilePrefix") @Expose private String LogFilePrefix; /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get 是否开启cmq消息通知。1:是,0:否。 * @return IsEnableCmqNotify 是否开启cmq消息通知。1:是,0:否。 */ public Long getIsEnableCmqNotify() { return this.IsEnableCmqNotify; } /** * Set 是否开启cmq消息通知。1:是,0:否。 * @param IsEnableCmqNotify 是否开启cmq消息通知。1:是,0:否。 */ public void setIsEnableCmqNotify(Long IsEnableCmqNotify) { this.IsEnableCmqNotify = IsEnableCmqNotify; } /** * Get 管理事件读写属性,1:只读,2:只写,3:全部 * @return ReadWriteAttribute 管理事件读写属性,1:只读,2:只写,3:全部 */ public Long getReadWriteAttribute() { return this.ReadWriteAttribute; } /** * Set 管理事件读写属性,1:只读,2:只写,3:全部 * @param ReadWriteAttribute 管理事件读写属性,1:只读,2:只写,3:全部 */ public void setReadWriteAttribute(Long ReadWriteAttribute) { this.ReadWriteAttribute = ReadWriteAttribute; } /** * Get CMK的全局唯一标识符。 * @return KeyId CMK的全局唯一标识符。 */ public String getKeyId() { return this.KeyId; } /** * Set CMK的全局唯一标识符。 * @param KeyId CMK的全局唯一标识符。 */ public void setKeyId(String KeyId) { this.KeyId = KeyId; } /** * Get 跟踪集状态,1:开启,0:停止。 * @return AuditStatus 跟踪集状态,1:开启,0:停止。 */ public Long getAuditStatus() { return this.AuditStatus; } /** * Set 跟踪集状态,1:开启,0:停止。 * @param AuditStatus 跟踪集状态,1:开启,0:停止。 */ public void setAuditStatus(Long AuditStatus) { this.AuditStatus = AuditStatus; } /** * Get 跟踪集名称。 * @return AuditName 跟踪集名称。 */ public String getAuditName() { return this.AuditName; } /** * Set 跟踪集名称。 * @param AuditName 跟踪集名称。 */ public void setAuditName(String AuditName) { this.AuditName = AuditName; } /** * Get cos存储桶所在地域。 * @return CosRegion cos存储桶所在地域。 */ public String getCosRegion() { return this.CosRegion; } /** * Set cos存储桶所在地域。 * @param CosRegion cos存储桶所在地域。 */ public void setCosRegion(String CosRegion) { this.CosRegion = CosRegion; } /** * Get 队列名称。 * @return CmqQueueName 队列名称。 */ public String getCmqQueueName() { return this.CmqQueueName; } /** * Set 队列名称。 * @param CmqQueueName 队列名称。 */ public void setCmqQueueName(String CmqQueueName) { this.CmqQueueName = CmqQueueName; } /** * Get CMK别名。 * @return KmsAlias CMK别名。 */ public String getKmsAlias() { return this.KmsAlias; } /** * Set CMK别名。 * @param KmsAlias CMK别名。 */ public void setKmsAlias(String KmsAlias) { this.KmsAlias = KmsAlias; } /** * Get kms地域。 * @return KmsRegion kms地域。 */ public String getKmsRegion() { return this.KmsRegion; } /** * Set kms地域。 * @param KmsRegion kms地域。 */ public void setKmsRegion(String KmsRegion) { this.KmsRegion = KmsRegion; } /** * Get 是否开启kms加密。1:是,0:否。如果开启KMS加密,数据在投递到cos时,会将数据加密。 * @return IsEnableKmsEncry 是否开启kms加密。1:是,0:否。如果开启KMS加密,数据在投递到cos时,会将数据加密。 */ public Long getIsEnableKmsEncry() { return this.IsEnableKmsEncry; } /** * Set 是否开启kms加密。1:是,0:否。如果开启KMS加密,数据在投递到cos时,会将数据加密。 * @param IsEnableKmsEncry 是否开启kms加密。1:是,0:否。如果开启KMS加密,数据在投递到cos时,会将数据加密。 */ public void setIsEnableKmsEncry(Long IsEnableKmsEncry) { this.IsEnableKmsEncry = IsEnableKmsEncry; } /** * Get cos存储桶名称。 * @return CosBucketName cos存储桶名称。 */ public String getCosBucketName() { return this.CosBucketName; } /** * Set cos存储桶名称。 * @param CosBucketName cos存储桶名称。 */ public void setCosBucketName(String CosBucketName) { this.CosBucketName = CosBucketName; } /** * Get 队列所在地域。 * @return CmqRegion 队列所在地域。 */ public String getCmqRegion() { return this.CmqRegion; } /** * Set 队列所在地域。 * @param CmqRegion 队列所在地域。 */ public void setCmqRegion(String CmqRegion) { this.CmqRegion = CmqRegion; } /** * Get 日志前缀。 * @return LogFilePrefix 日志前缀。 */ public String getLogFilePrefix() { return this.LogFilePrefix; } /** * Set 日志前缀。 * @param LogFilePrefix 日志前缀。 */ public void setLogFilePrefix(String LogFilePrefix) { this.LogFilePrefix = LogFilePrefix; } /** * Get 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @return RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public String getRequestId() { return this.RequestId; } /** * Set 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 * @param RequestId 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DescribeAuditResponse() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public DescribeAuditResponse(DescribeAuditResponse source) { if (source.IsEnableCmqNotify != null) { this.IsEnableCmqNotify = new Long(source.IsEnableCmqNotify); } if (source.ReadWriteAttribute != null) { this.ReadWriteAttribute = new Long(source.ReadWriteAttribute); } if (source.KeyId != null) { this.KeyId = new String(source.KeyId); } if (source.AuditStatus != null) { this.AuditStatus = new Long(source.AuditStatus); } if (source.AuditName != null) { this.AuditName = new String(source.AuditName); } if (source.CosRegion != null) { this.CosRegion = new String(source.CosRegion); } if (source.CmqQueueName != null) { this.CmqQueueName = new String(source.CmqQueueName); } if (source.KmsAlias != null) { this.KmsAlias = new String(source.KmsAlias); } if (source.KmsRegion != null) { this.KmsRegion = new String(source.KmsRegion); } if (source.IsEnableKmsEncry != null) { this.IsEnableKmsEncry = new Long(source.IsEnableKmsEncry); } if (source.CosBucketName != null) { this.CosBucketName = new String(source.CosBucketName); } if (source.CmqRegion != null) { this.CmqRegion = new String(source.CmqRegion); } if (source.LogFilePrefix != null) { this.LogFilePrefix = new String(source.LogFilePrefix); } if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "IsEnableCmqNotify", this.IsEnableCmqNotify); this.setParamSimple(map, prefix + "ReadWriteAttribute", this.ReadWriteAttribute); this.setParamSimple(map, prefix + "KeyId", this.KeyId); this.setParamSimple(map, prefix + "AuditStatus", this.AuditStatus); this.setParamSimple(map, prefix + "AuditName", this.AuditName); this.setParamSimple(map, prefix + "CosRegion", this.CosRegion); this.setParamSimple(map, prefix + "CmqQueueName", this.CmqQueueName); this.setParamSimple(map, prefix + "KmsAlias", this.KmsAlias); this.setParamSimple(map, prefix + "KmsRegion", this.KmsRegion); this.setParamSimple(map, prefix + "IsEnableKmsEncry", this.IsEnableKmsEncry); this.setParamSimple(map, prefix + "CosBucketName", this.CosBucketName); this.setParamSimple(map, prefix + "CmqRegion", this.CmqRegion); this.setParamSimple(map, prefix + "LogFilePrefix", this.LogFilePrefix); this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
9236bb2c620db3452691fe71c7b1dad55dc51c42
3,048
java
Java
r2dbc-migrate-core/src/test/java/name/nkonev/r2dbc/migrate/core/MariadbTestcontainersTest.java
ShaneLee/r2dbc-migrate
6eab4e273777e8bdc1deabf64ebc8f053d296883
[ "Apache-2.0" ]
70
2020-04-10T18:38:11.000Z
2022-03-30T22:26:09.000Z
r2dbc-migrate-core/src/test/java/name/nkonev/r2dbc/migrate/core/MariadbTestcontainersTest.java
ShaneLee/r2dbc-migrate
6eab4e273777e8bdc1deabf64ebc8f053d296883
[ "Apache-2.0" ]
15
2020-04-05T16:41:50.000Z
2022-03-17T21:12:58.000Z
r2dbc-migrate-core/src/test/java/name/nkonev/r2dbc/migrate/core/MariadbTestcontainersTest.java
ShaneLee/r2dbc-migrate
6eab4e273777e8bdc1deabf64ebc8f053d296883
[ "Apache-2.0" ]
8
2020-04-05T13:21:54.000Z
2021-12-13T20:01:14.000Z
34.247191
136
0.729987
997,797
package name.nkonev.r2dbc.migrate.core; import static io.r2dbc.spi.ConnectionFactoryOptions.DATABASE; import static io.r2dbc.spi.ConnectionFactoryOptions.DRIVER; import static io.r2dbc.spi.ConnectionFactoryOptions.HOST; import static io.r2dbc.spi.ConnectionFactoryOptions.PASSWORD; import static io.r2dbc.spi.ConnectionFactoryOptions.PORT; import static io.r2dbc.spi.ConnectionFactoryOptions.USER; import static name.nkonev.r2dbc.migrate.core.TestConstants.waitTestcontainersSeconds; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.Logger; import io.r2dbc.spi.ConnectionFactories; import io.r2dbc.spi.ConnectionFactory; import io.r2dbc.spi.ConnectionFactoryOptions; import java.time.Duration; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.slf4j.LoggerFactory; import org.testcontainers.containers.BindMode; import org.testcontainers.containers.GenericContainer; public class MariadbTestcontainersTest extends AbstractMysqlLikeTestcontainersTest { final static int MYSQL_PORT = 3306; private GenericContainer container; final static String user = "mysql-user"; final static String password = "mysql-password"; static Logger statementsLogger; static Level statementsPreviousLevel; @Override protected GenericContainer getContainer() { return container; } @BeforeEach public void beforeEach() { container = new GenericContainer("mariadb:10.5.8-focal") .withClasspathResourceMapping("/docker/mysql/etc/mysql/conf.d", "/etc/mysql/conf.d", BindMode.READ_ONLY) .withClasspathResourceMapping("/docker/mysql/docker-entrypoint-initdb.d", "/docker-entrypoint-initdb.d", BindMode.READ_ONLY) .withEnv("MYSQL_ALLOW_EMPTY_PASSWORD", "true") .withExposedPorts(MYSQL_PORT) .withStartupTimeout(Duration.ofSeconds(waitTestcontainersSeconds)); container.start(); statementsLogger = (Logger) LoggerFactory.getLogger("name.nkonev.r2dbc.migrate.core.R2dbcMigrate"); statementsPreviousLevel = statementsLogger.getEffectiveLevel(); } @AfterEach public void afterEach() { container.stop(); statementsLogger.setLevel(statementsPreviousLevel); } protected ConnectionFactory makeConnectionMono(int port) { ConnectionFactory connectionFactory = ConnectionFactories.get(ConnectionFactoryOptions.builder() .option(DRIVER, "mariadb") .option(HOST, "127.0.0.1") .option(PORT, port) .option(USER, user) .option(PASSWORD, password) .option(DATABASE, "r2dbc") .build()); return connectionFactory; } @Override protected int getMappedPort() { return container.getMappedPort(MYSQL_PORT); } @Override protected Level getStatementsPreviousLevel() { return statementsPreviousLevel; } @Override protected Logger getStatementsLogger() { return statementsLogger; } }
9236bb3bd12e84d4eeb2340492be285de9d25691
1,055
java
Java
dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/structure/CustomBlobModel.java
wiyarmir/DBFlow
f8106ffc8a389bf7a771c18d82669ad1dc4af0cd
[ "MIT" ]
2
2019-12-12T07:28:19.000Z
2020-04-01T10:36:15.000Z
dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/structure/CustomBlobModel.java
skyuning/DBFlow
f8106ffc8a389bf7a771c18d82669ad1dc4af0cd
[ "MIT" ]
null
null
null
dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/structure/CustomBlobModel.java
skyuning/DBFlow
f8106ffc8a389bf7a771c18d82669ad1dc4af0cd
[ "MIT" ]
1
2020-04-01T10:36:16.000Z
2020-04-01T10:36:16.000Z
28.513514
77
0.70237
997,798
package com.raizlabs.android.dbflow.test.structure; import com.raizlabs.android.dbflow.annotation.Column; import com.raizlabs.android.dbflow.annotation.QueryModel; import com.raizlabs.android.dbflow.converter.TypeConverter; import com.raizlabs.android.dbflow.data.Blob; import com.raizlabs.android.dbflow.structure.BaseQueryModel; import com.raizlabs.android.dbflow.test.TestDatabase; @QueryModel(database = TestDatabase.class) public class CustomBlobModel extends BaseQueryModel { public static class MyBlob { private final byte[] blob; public MyBlob(byte[] blob) { this.blob = blob; } } @com.raizlabs.android.dbflow.annotation.TypeConverter public static class MyTypeConverter extends TypeConverter<Blob, MyBlob> { @Override public Blob getDBValue(MyBlob model) { return new Blob(model.blob); } @Override public MyBlob getModelValue(Blob data) { return new MyBlob(data.getBlob()); } } @Column MyBlob myBlob; }
9236bb4b4397c1845b766bb9c4bb5e07259c47ca
1,496
java
Java
src/main/java/com/meli/job/JobCollection.java
juanromerameli/meli-jobs
e7b1516a3ef289196650e937df123b1cfe527d53
[ "MIT" ]
null
null
null
src/main/java/com/meli/job/JobCollection.java
juanromerameli/meli-jobs
e7b1516a3ef289196650e937df123b1cfe527d53
[ "MIT" ]
null
null
null
src/main/java/com/meli/job/JobCollection.java
juanromerameli/meli-jobs
e7b1516a3ef289196650e937df123b1cfe527d53
[ "MIT" ]
null
null
null
18.243902
64
0.574866
997,799
package com.meli.job; import java.util.*; /** * A {@link Map} that stores {@link Job} * * @author Juan Manuel Romera Ferrrio */ public class JobCollection implements Map<String, Job> { private Map<String, Job> jobs; public JobCollection() { this.jobs = new HashMap<>(); } @Override public int size() { return this.jobs.size(); } @Override public boolean isEmpty() { return this.jobs.isEmpty(); } @Override public boolean containsKey(Object key) { return jobs.containsKey(key); } @Override public boolean containsValue(Object value) { return jobs.containsValue(value); } @Override public Job get(Object key) { return jobs.get(key); } @Override public Job put(String key, Job value) { return jobs.put(key, value); } @Override public Job remove(Object key) { return jobs.remove(key); } @Override public void putAll(Map<? extends String, ? extends Job> m) { jobs.putAll(m); } @Override public void clear() { this.jobs.clear(); } @Override public Set<String> keySet() { return jobs.keySet(); } @Override public Collection<Job> values() { return jobs.values(); } @Override public Set<Entry<String, Job>> entrySet() { return jobs.entrySet(); } public Job add(Job job) { return put(job.getName(), job); } }
9236bc77fc5f17d34b15a5b7f756b784832402c3
1,485
java
Java
medium/java/c0322_688_knight-probability-in-chessboard/00_leetcode_0322.java
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
medium/java/c0322_688_knight-probability-in-chessboard/00_leetcode_0322.java
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
null
null
null
medium/java/c0322_688_knight-probability-in-chessboard/00_leetcode_0322.java
drunkwater/leetcode
8cc4a07763e71efbaedb523015f0c1eff2927f60
[ "Ruby" ]
3
2018-02-09T02:46:48.000Z
2021-02-20T08:32:03.000Z
57.115385
222
0.746128
997,800
// DRUNKWATER TEMPLATE(add description and prototypes) // Question Title and Description on leetcode.com // Function Declaration and Function Prototypes on leetcode.com //688. Knight Probability in Chessboard //On an NxN chessboard, a knight starts at the r-th row and c-th column and attempts to make exactly K moves. The rows and columns are 0 indexed, so the top-left square is (0, 0), and the bottom-right square is (N-1, N-1). //A chess knight has 8 possible moves it can make, as illustrated below. Each move is two squares in a cardinal direction, then one square in an orthogonal direction. //Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. //The knight continues moving until it has made exactly K moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving. //Example: //Input: 3, 2, 0, 0 //Output: 0.0625 //Explanation: There are two moves (to (1,2), (2,1)) that will keep the knight on the board. //From each of those positions, there are also two moves that will keep the knight on the board. //The total probability the knight stays on the board is 0.0625. //Note: //N will be between 1 and 25. //K will be between 0 and 100. //The knight always initially starts on the board. //class Solution { // public double knightProbability(int N, int K, int r, int c) { // } //} // Time Is Money
9236bd4622bf8767d6f70705033152a9291607d9
4,572
java
Java
spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/UnackedRawIntegrationTests.java
jonatan-ivanov/spring-amqp
e8e1b8638e4668f9f918157ac7931409b60b0984
[ "Apache-2.0" ]
648
2015-01-01T15:28:53.000Z
2022-03-29T08:10:00.000Z
spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/UnackedRawIntegrationTests.java
jonatan-ivanov/spring-amqp
e8e1b8638e4668f9f918157ac7931409b60b0984
[ "Apache-2.0" ]
946
2015-01-05T12:33:42.000Z
2022-03-31T15:25:47.000Z
spring-rabbit/src/test/java/org/springframework/amqp/rabbit/listener/UnackedRawIntegrationTests.java
jonatan-ivanov/spring-amqp
e8e1b8638e4668f9f918157ac7931409b60b0984
[ "Apache-2.0" ]
539
2015-01-10T00:52:19.000Z
2022-03-30T01:37:54.000Z
28.222222
108
0.740595
997,801
/* * Copyright 2002-2019 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.amqp.rabbit.listener; import static org.assertj.core.api.Assertions.assertThat; import java.io.IOException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import org.springframework.amqp.rabbit.junit.BrokerTestUtils; import org.springframework.amqp.rabbit.support.Delivery; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.GetResponse; /** * Used to verify raw Rabbit Java Client behaviour for corner cases. * * @author Dave Syer * */ @Disabled public class UnackedRawIntegrationTests { private final ConnectionFactory factory = new ConnectionFactory(); private Connection conn; private Channel noTxChannel; private Channel txChannel; @BeforeEach public void init() throws Exception { factory.setHost("localhost"); factory.setPort(BrokerTestUtils.getPort()); conn = factory.newConnection(); noTxChannel = conn.createChannel(); txChannel = conn.createChannel(); txChannel.basicQos(1); txChannel.txSelect(); try { noTxChannel.queueDelete("test.queue"); } catch (IOException e) { noTxChannel = conn.createChannel(); } noTxChannel.queueDeclare("test.queue", true, false, false, null); } @AfterEach public void clear() throws Exception { if (txChannel != null) { try { txChannel.close(); } catch (Exception e) { e.printStackTrace(); } } if (noTxChannel != null) { try { noTxChannel.close(); } catch (Exception e) { e.printStackTrace(); } } conn.close(); } @Test public void testOnePublishUnackedRequeued() throws Exception { noTxChannel.basicPublish("", "test.queue", null, "foo".getBytes()); BlockingConsumer callback = new BlockingConsumer(txChannel); txChannel.basicConsume("test.queue", callback); Delivery next = callback.nextDelivery(10_000L); assertThat(next).isNotNull(); txChannel.basicReject(next.getEnvelope().getDeliveryTag(), true); txChannel.txRollback(); GetResponse get = noTxChannel.basicGet("test.queue", true); assertThat(get).isNotNull(); } @Test public void testFourPublishUnackedRequeued() throws Exception { noTxChannel.basicPublish("", "test.queue", null, "foo".getBytes()); noTxChannel.basicPublish("", "test.queue", null, "bar".getBytes()); noTxChannel.basicPublish("", "test.queue", null, "one".getBytes()); noTxChannel.basicPublish("", "test.queue", null, "two".getBytes()); BlockingConsumer callback = new BlockingConsumer(txChannel); txChannel.basicConsume("test.queue", callback); Delivery next = callback.nextDelivery(10_000L); assertThat(next).isNotNull(); txChannel.basicReject(next.getEnvelope().getDeliveryTag(), true); txChannel.txRollback(); GetResponse get = noTxChannel.basicGet("test.queue", true); assertThat(get).isNotNull(); } public static class BlockingConsumer extends DefaultConsumer { private final BlockingQueue<Delivery> queue = new LinkedBlockingQueue<>(); public BlockingConsumer(Channel channel) { super(channel); } public Delivery nextDelivery(long timeout) throws InterruptedException { return this.queue.poll(timeout, TimeUnit.MILLISECONDS); } @Override public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException { try { this.queue.put(new Delivery(consumerTag, envelope, properties, body, "test.queue")); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } } }
9236bd4f34aaa647ad747441a093d052af6259ae
7,387
java
Java
aws-java-sdk-greengrassv2/src/main/java/com/amazonaws/services/greengrassv2/model/ListComponentVersionsRequest.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
3,372
2015-01-03T00:35:43.000Z
2022-03-31T15:56:24.000Z
aws-java-sdk-greengrassv2/src/main/java/com/amazonaws/services/greengrassv2/model/ListComponentVersionsRequest.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
2,391
2015-01-01T12:55:24.000Z
2022-03-31T08:01:50.000Z
aws-java-sdk-greengrassv2/src/main/java/com/amazonaws/services/greengrassv2/model/ListComponentVersionsRequest.java
ericvincent83/aws-sdk-java
c491416f3ea9411a04d9bafedee6c6874a79e48d
[ "Apache-2.0" ]
2,876
2015-01-01T14:38:37.000Z
2022-03-29T19:53:10.000Z
31.037815
124
0.607148
997,802
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.greengrassv2.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.AmazonWebServiceRequest; /** * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/greengrassv2-2020-11-30/ListComponentVersions" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class ListComponentVersionsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable { /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> */ private String arn; /** * <p> * The maximum number of results to be returned per paginated request. * </p> */ private Integer maxResults; /** * <p> * The token to be used for the next set of paginated results. * </p> */ private String nextToken; /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> * * @param arn * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the * component version. */ public void setArn(String arn) { this.arn = arn; } /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> * * @return The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the * component version. */ public String getArn() { return this.arn; } /** * <p> * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the component * version. * </p> * * @param arn * The <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">ARN</a> of the * component version. * @return Returns a reference to this object so that method calls can be chained together. */ public ListComponentVersionsRequest withArn(String arn) { setArn(arn); return this; } /** * <p> * The maximum number of results to be returned per paginated request. * </p> * * @param maxResults * The maximum number of results to be returned per paginated request. */ public void setMaxResults(Integer maxResults) { this.maxResults = maxResults; } /** * <p> * The maximum number of results to be returned per paginated request. * </p> * * @return The maximum number of results to be returned per paginated request. */ public Integer getMaxResults() { return this.maxResults; } /** * <p> * The maximum number of results to be returned per paginated request. * </p> * * @param maxResults * The maximum number of results to be returned per paginated request. * @return Returns a reference to this object so that method calls can be chained together. */ public ListComponentVersionsRequest withMaxResults(Integer maxResults) { setMaxResults(maxResults); return this; } /** * <p> * The token to be used for the next set of paginated results. * </p> * * @param nextToken * The token to be used for the next set of paginated results. */ public void setNextToken(String nextToken) { this.nextToken = nextToken; } /** * <p> * The token to be used for the next set of paginated results. * </p> * * @return The token to be used for the next set of paginated results. */ public String getNextToken() { return this.nextToken; } /** * <p> * The token to be used for the next set of paginated results. * </p> * * @param nextToken * The token to be used for the next set of paginated results. * @return Returns a reference to this object so that method calls can be chained together. */ public ListComponentVersionsRequest withNextToken(String nextToken) { setNextToken(nextToken); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getArn() != null) sb.append("Arn: ").append(getArn()).append(","); if (getMaxResults() != null) sb.append("MaxResults: ").append(getMaxResults()).append(","); if (getNextToken() != null) sb.append("NextToken: ").append(getNextToken()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof ListComponentVersionsRequest == false) return false; ListComponentVersionsRequest other = (ListComponentVersionsRequest) obj; if (other.getArn() == null ^ this.getArn() == null) return false; if (other.getArn() != null && other.getArn().equals(this.getArn()) == false) return false; if (other.getMaxResults() == null ^ this.getMaxResults() == null) return false; if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false) return false; if (other.getNextToken() == null ^ this.getNextToken() == null) return false; if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getArn() == null) ? 0 : getArn().hashCode()); hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode()); hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode()); return hashCode; } @Override public ListComponentVersionsRequest clone() { return (ListComponentVersionsRequest) super.clone(); } }
9236bd72b6d06c077ef96038bbd1c955efa6599f
1,198
java
Java
src/main/java/com/rapiddweller/format/xml/XMLElementParser.java
rapiddweller/rd-lib-format
1bc2bcb59caecc62c57694a7a75b74cecfaab184
[ "Apache-2.0" ]
1
2021-01-25T08:30:55.000Z
2021-01-25T08:30:55.000Z
src/main/java/com/rapiddweller/format/xml/XMLElementParser.java
rapiddweller/rd-lib-format
1bc2bcb59caecc62c57694a7a75b74cecfaab184
[ "Apache-2.0" ]
1
2021-02-09T18:47:39.000Z
2021-02-09T18:47:39.000Z
src/main/java/com/rapiddweller/format/xml/XMLElementParser.java
rapiddweller/rd-lib-format
1bc2bcb59caecc62c57694a7a75b74cecfaab184
[ "Apache-2.0" ]
null
null
null
37.84375
102
0.751445
997,803
/* * Copyright (C) 2011-2015 Volker Bergmann (envkt@example.com). * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rapiddweller.format.xml; import org.w3c.dom.Element; /** * Parent interface for classes that parse XML structures into Java objects. * Created: 05.12.2010 10:42:56 * @param <E> the type of element to provide * @author Volker Bergmann * @since 0.5.4 */ public interface XMLElementParser<E> { boolean supportsElementName(String elementName); boolean supports(Element element, Element[] parentXmlPath, E[] parentComponentPath); E parse(Element element, Element[] parentXmlPath, E[] parentComponentPath, ParseContext<E> context); }
9236bf6a32fa9f3214db6e463834f4d1448df992
807
java
Java
src/main/java/com/wrongme/daily/w20211001/ToHexSolution.java
wrongvest/leetcode
bc10f7cd289f73cee29b855f038511a7e50ac9f0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wrongme/daily/w20211001/ToHexSolution.java
wrongvest/leetcode
bc10f7cd289f73cee29b855f038511a7e50ac9f0
[ "Apache-2.0" ]
null
null
null
src/main/java/com/wrongme/daily/w20211001/ToHexSolution.java
wrongvest/leetcode
bc10f7cd289f73cee29b855f038511a7e50ac9f0
[ "Apache-2.0" ]
null
null
null
22.416667
53
0.451053
997,804
package com.wrongme.daily.w20211001; /** * 405. 数字转换为十六进制数 */ public class ToHexSolution { public String toHex(int _num) { String ans = ""; long num = _num; if (num<0){ num = (long) (Math.pow(2,32)+_num); }else if (num==0){ return 0+""; } while (num !=0) { long mod = num % 16; if (mod>=10){ char m = (char) (mod -10 +'a'); ans = m +ans; }else { ans = mod +ans; } num = num/16; } return ans; } public static void main(String[] args) { ToHexSolution solution = new ToHexSolution(); System.out.println(solution.toHex(26)); System.out.println(solution.toHex(-1)); } }
9236bf91ff231710b7e1a809438710ea627fbe6a
775
java
Java
src/main/java/be/albatroz/javacase/entity/CompanyAddress.java
Stefaan-Moreels/finTst
94bd32c93e8b4c3b7a5b3f94bcfa3166c1337c05
[ "CC0-1.0" ]
null
null
null
src/main/java/be/albatroz/javacase/entity/CompanyAddress.java
Stefaan-Moreels/finTst
94bd32c93e8b4c3b7a5b3f94bcfa3166c1337c05
[ "CC0-1.0" ]
null
null
null
src/main/java/be/albatroz/javacase/entity/CompanyAddress.java
Stefaan-Moreels/finTst
94bd32c93e8b4c3b7a5b3f94bcfa3166c1337c05
[ "CC0-1.0" ]
null
null
null
25
91
0.776774
997,805
package be.albatroz.javacase.entity; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.*; import java.io.Serializable; @Getter @Setter @Entity @DynamicInsert @DynamicUpdate @ToString(callSuper = true, exclude = {"company"}) @EqualsAndHashCode(callSuper = true, exclude = {"company"}) @DiscriminatorValue("COMPANY") public class CompanyAddress extends Address implements Serializable { @ManyToOne(targetEntity = Company.class) @JoinColumn(name = "company_id", foreignKey = @ForeignKey(name = "FK_address_company")) private Company company; @Column private boolean hq = false; }
9236c093b287ae1859b3ad09a009f418f870c0a5
30,666
java
Java
src/states/SimSettingsState.java
PavlosTserevelakis/HackTraficCERN
2b2e9e98ff7c011d6e4b2d7f521d7856ace16123
[ "MIT" ]
1
2019-03-23T11:32:05.000Z
2019-03-23T11:32:05.000Z
src/states/SimSettingsState.java
PavlosTserevelakis/HackTraficCERN
2b2e9e98ff7c011d6e4b2d7f521d7856ace16123
[ "MIT" ]
null
null
null
src/states/SimSettingsState.java
PavlosTserevelakis/HackTraficCERN
2b2e9e98ff7c011d6e4b2d7f521d7856ace16123
[ "MIT" ]
1
2019-03-23T18:22:51.000Z
2019-03-23T18:22:51.000Z
37.261239
353
0.638199
997,806
package states; import java.awt.Graphics; import data.DataManager; import elements.Ride; import elements.Road; import graphics.Assets; import graphics.Text; import main.Simulation; import network.AllNetworkRides; import network.Network; import ui.ClickListener; import ui.UIImageButton; import ui.UIManager; import ui.UISlider; import ui.UISliderDouble; import ui.UISliderTriple; import ui.UITextButton; import utils.Utils; public class SimSettingsState extends State { private UIManager uiManagerTransit; private UIManager uiManagerTransitFrance; private UIManager uiManagerE; private UIManager uiManagerA; private UIManager uiManagerB; private UIManager uiManagerGeneral; private int activePage = 1; private int nPages = 5; private long counter = 0; private int xStart = 320; private int yStart = 150; private int buttonYMargin = 5; private int buttonXMargin = 15; private int buttonWidth = 140; private int buttonHeight = 30; private int sliderWidth = 500; private int sliderHeight = 30; //private int descriptionMargin = 20; private boolean isLeftPressed = false; private UISlider timePerVhcEntrance; private UISlider fromFrToGe,fromFrToGeDuringRH; private UISliderDouble fromFrToGeRepartitionRH; private UISliderTriple fromFrToGeRepartition; private UISlider fromGeToFr,fromGeToFrDuringRH2; private UISliderDouble fromGeToFrRepartitionRH2; private UISliderTriple fromGeToFrRepartition; private UISlider fromFrToFr; private UISlider toEntranceE; private UISliderDouble toEntranceERepartition, toEntranceERepartitionRH; private UISlider fromEntranceE; private UISliderDouble fromEntranceERepartition, fromEntranceERepartitionRH2; private UISlider toEntranceA, toEntranceARepartition; private UISliderDouble toEntranceARepartitionRH; private UISlider fromEntranceA, fromEntranceARepartition; private UISliderDouble fromEntranceARepartitionRH2; private UISlider toEntranceB, toEntranceBRepartition; private UISliderDouble toEntranceBRepartitionRH; private UISlider fromEntranceB, fromEntranceBRepartition; private UISliderDouble fromEntranceBRepartitionRH2; private UISliderDouble crEntreeB_phase1; private UISliderDouble crEntreeB_phase2; private UISliderDouble crEntreeB_phase3; private UISliderDouble crEntreeB_phase4; private UIImageButton previous, next; private UITextButton run, back; public SimSettingsState(Simulation simulation) { super(simulation); this.uiManagerTransit = new UIManager(simulation); this.uiManagerTransitFrance = new UIManager(simulation); this.uiManagerE = new UIManager(simulation); this.uiManagerA = new UIManager(simulation); this.uiManagerB = new UIManager(simulation); this.uiManagerGeneral = new UIManager(simulation); // ################################################################################################## // PAGE 1 ########################################################################################### // ################################################################################################## // From France to Geneva fromFrToGe = new UISlider(simulation, xStart, yStart+1*(sliderHeight+buttonYMargin), sliderWidth, "Flow from France to Geneva (vhc/day)", 25000, DataManager.nFrGe, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromFrToGe); fromFrToGeRepartition = new UISliderTriple(simulation, xStart, yStart+2*(sliderHeight+buttonYMargin), sliderWidth, "Coming from Thoiry, St-Genis, Ferney and Europe", 100, DataManager.nFrGe_fromSW, DataManager.nFrGe_fromSW+DataManager.nFrGe_fromNW, DataManager.nFrGe_fromSW+DataManager.nFrGe_fromNW+DataManager.nFrGe_fromTun, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromFrToGeRepartition); fromFrToGeDuringRH = new UISlider(simulation, xStart, yStart+3*(sliderHeight+buttonYMargin), sliderWidth, "Quantity during rush-hours (morning)", 100, 24, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromFrToGeDuringRH); fromFrToGeRepartitionRH = new UISliderDouble(simulation, xStart, yStart+4*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 7am, 8am, 9am", 100, DataManager.nFrGe_7, DataManager.nFrGe_7+DataManager.nFrGe_8, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromFrToGeRepartitionRH); // From Geneva to France ============================================================================ fromGeToFr = new UISlider(simulation, xStart, yStart+6*(sliderHeight+buttonYMargin), sliderWidth, "Flow from Geneva to France (vhc/day)", 25000, DataManager.nGeFr, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromGeToFr); fromGeToFrRepartition = new UISliderTriple(simulation, xStart, yStart+7*(sliderHeight+buttonYMargin), sliderWidth, "Going to Thoiry, St-Genis, Ferney and Europe", 100, DataManager.nGeFr_toSW, DataManager.nGeFr_toSW+DataManager.nGeFr_toNW, DataManager.nGeFr_toSW+DataManager.nGeFr_toNW+DataManager.nGeFr_toTun, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromGeToFrRepartition); fromGeToFrDuringRH2 = new UISlider(simulation, xStart, yStart+8*(sliderHeight+buttonYMargin), sliderWidth, "Quantity during rush-hours (evening)", 100, 24, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromGeToFrDuringRH2); fromGeToFrRepartitionRH2 = new UISliderDouble(simulation, xStart, yStart+9*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 5pm, 6pm, 7pm", 100, DataManager.nGeFr_17, DataManager.nGeFr_17+DataManager.nGeFr_18, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromGeToFrRepartitionRH2); // From France to Geneva fromFrToFr = new UISlider(simulation, xStart, yStart+11*(sliderHeight+buttonYMargin), sliderWidth, "Flow from France to France", 25000, DataManager.nFrFr, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransit.addObject(fromFrToFr); // ################################################################################################## // PAGE 2 ########################################################################################### // ################################################################################################## // From France to Geneva /*fromFrToFr = new UISlider(simulation, xStart, yStart+1*(sliderHeight+buttonYMargin), sliderWidth, "Flow from France to Geneva (vhc/day)", 25000, DataManager.nFrGe, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerTransitFrance.addObject(fromFrToGe);*/ // ################################################################################################## // PAGE 3 ########################################################################################### // ################################################################################################## // To entrance E ==================================================================================== toEntranceE = new UISlider(simulation, xStart, yStart+1*(sliderHeight+buttonYMargin), sliderWidth, "Flow to Entrance E during rush-hours", 4000, DataManager.nToE, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerE.addObject(toEntranceE); toEntranceERepartition = new UISliderDouble(simulation, xStart, yStart+2*(sliderHeight+buttonYMargin), sliderWidth, "Coming from Thoiry, St-Genis and Ferney", 100, DataManager.nToE_fromSW, DataManager.nToE_fromSW+DataManager.nToE_fromNW, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerE.addObject(toEntranceERepartition); toEntranceERepartitionRH = new UISliderDouble(simulation, xStart, yStart+3*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 7am, 8am, 9am", 100, DataManager.nToE_7, DataManager.nToE_7+DataManager.nToE_8, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerE.addObject(toEntranceERepartitionRH); // From entrance E ==================================================================================== fromEntranceE = new UISlider(simulation, xStart, yStart+5*(sliderHeight+buttonYMargin), sliderWidth, "Flow from Entrance E during rush-hours", 4000, DataManager.nFromE, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerE.addObject(fromEntranceE); fromEntranceERepartition = new UISliderDouble(simulation, xStart, yStart+6*(sliderHeight+buttonYMargin), sliderWidth, "Going to Thoiry, St-Genis and Ferney", 100, DataManager.nFromE_toSW, DataManager.nFromE_toSW+DataManager.nFromE_toNW, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerE.addObject(fromEntranceERepartition); fromEntranceERepartitionRH2 = new UISliderDouble(simulation, xStart, yStart+7*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 5pm, 6pm, 7pm", 100, DataManager.nFromE_17, DataManager.nFromE_17+DataManager.nFromE_18, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerE.addObject(fromEntranceERepartitionRH2); // ################################################################################################## // PAGE 4 ########################################################################################### // ################################################################################################## // To entrance A ==================================================================================== toEntranceA = new UISlider(simulation, xStart, yStart+1*(sliderHeight+buttonYMargin), sliderWidth, "Flow to Entrance A during rush-hours", 4000, DataManager.nToA, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerA.addObject(toEntranceA); toEntranceARepartition = new UISlider(simulation, xStart, yStart+2*(sliderHeight+buttonYMargin), sliderWidth, "Coming from Geneva, France", 100, DataManager.nToA_fromGe, true, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerA.addObject(toEntranceARepartition); toEntranceARepartitionRH = new UISliderDouble(simulation, xStart, yStart+3*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 7am, 8am, 9am", 100, DataManager.nToA_7, DataManager.nToA_7+DataManager.nToA_8, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerA.addObject(toEntranceARepartitionRH); // From entrance A ==================================================================================== fromEntranceA = new UISlider(simulation, xStart, yStart+5*(sliderHeight+buttonYMargin), sliderWidth, "Flow from Entrance A during rush-hours", 4000, DataManager.nFromA, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerA.addObject(fromEntranceA); fromEntranceARepartition = new UISlider(simulation, xStart, yStart+6*(sliderHeight+buttonYMargin), sliderWidth, "Going to Geneva, France", 100, DataManager.nFromA_toGe, true, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerA.addObject(fromEntranceARepartition); fromEntranceARepartitionRH2 = new UISliderDouble(simulation, xStart, yStart+7*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 5pm, 6pm, 7pm", 100, DataManager.nFromA_17, DataManager.nFromA_17+DataManager.nFromA_18, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerA.addObject(fromEntranceARepartitionRH2); // ################################################################################################## // PAGE 5 ########################################################################################### // ################################################################################################## // To entrance B ==================================================================================== toEntranceB = new UISlider(simulation, xStart, yStart+1*(sliderHeight+buttonYMargin), sliderWidth, "Flow to Entrance B during rush-hours", 4000, DataManager.nToB, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerB.addObject(toEntranceB); toEntranceBRepartition = new UISlider(simulation, xStart, yStart+2*(sliderHeight+buttonYMargin), sliderWidth, "Coming from Geneva, France", 100, DataManager.nToB_fromGe, true, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerB.addObject(toEntranceBRepartition); toEntranceBRepartitionRH = new UISliderDouble(simulation, xStart, yStart+3*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 7am, 8am, 9am", 100, DataManager.nToB_7, DataManager.nToB_7+DataManager.nToB_8, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerB.addObject(toEntranceBRepartitionRH); // From entrance B ==================================================================================== fromEntranceB = new UISlider(simulation, xStart, yStart+5*(sliderHeight+buttonYMargin), sliderWidth, "Flow from Entrance B during rush-hours", 4000, DataManager.nFromB, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerB.addObject(fromEntranceB); fromEntranceBRepartition = new UISlider(simulation, xStart, yStart+6*(sliderHeight+buttonYMargin), sliderWidth, "Going to Geneva, France", 100, DataManager.nFromB_toGe, true, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerB.addObject(fromEntranceBRepartition); fromEntranceBRepartitionRH2 = new UISliderDouble(simulation, xStart, yStart+7*(sliderHeight+buttonYMargin), sliderWidth, "Distribution between 5pm, 6pm, 7pm", 100, DataManager.nFromB_17, DataManager.nFromB_17+DataManager.nFromB_18, true, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerB.addObject(fromEntranceBRepartitionRH2); // ################################################################################################## // PAGE 6 ########################################################################################### // ################################################################################################## timePerVhcEntrance = new UISlider(simulation, xStart, yStart+1*(sliderHeight+buttonYMargin), sliderWidth, "Control duration of 1 vehicle at entrances", 30, 8, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerGeneral.addObject(timePerVhcEntrance); crEntreeB_phase1 = new UISliderDouble(simulation, xStart, yStart+3*(sliderHeight+buttonYMargin), sliderWidth, "Duration phase 1", 60, DataManager.cycle1LTSmin, DataManager.cycle1LTSmax, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerGeneral.addObject(crEntreeB_phase1); crEntreeB_phase2 = new UISliderDouble(simulation, xStart, yStart+4*(sliderHeight+buttonYMargin), sliderWidth, "Duration phase 2", 60, DataManager.cycle2LTSmin, DataManager.cycle2LTSmax, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerGeneral.addObject(crEntreeB_phase2); crEntreeB_phase3 = new UISliderDouble(simulation, xStart, yStart+5*(sliderHeight+buttonYMargin), sliderWidth, "Duration phase 3", 60, DataManager.cycle3LTSmin, DataManager.cycle3LTSmax, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerGeneral.addObject(crEntreeB_phase3); crEntreeB_phase4 = new UISliderDouble(simulation, xStart, yStart+6*(sliderHeight+buttonYMargin), sliderWidth, "Duration phase 4", 60, DataManager.cycle4LTSmin, DataManager.cycle4LTSmax, false, new ClickListener(){ @Override public void onClick() { } }); this.uiManagerGeneral.addObject(crEntreeB_phase4); // ################################################################################################## // BUTTONS ########################################################################################## // ################################################################################################## previous = new UIImageButton(325, 593, 50, buttonHeight, Assets.previousIdle, Assets.previousActive, new ClickListener(){ @Override public void onClick() { previousPage(); } }); this.uiManagerTransit.addObject(previous); this.uiManagerTransitFrance.addObject(previous); this.uiManagerE.addObject(previous); this.uiManagerA.addObject(previous); this.uiManagerB.addObject(previous); this.uiManagerGeneral.addObject(previous); next = new UIImageButton(625, 593, 50, buttonHeight, Assets.nextIdle, Assets.nextActive, new ClickListener(){ @Override public void onClick() { nextPage(); } }); this.uiManagerTransit.addObject(next); this.uiManagerTransitFrance.addObject(next); this.uiManagerE.addObject(next); this.uiManagerA.addObject(next); this.uiManagerB.addObject(next); this.uiManagerGeneral.addObject(next); run = new UITextButton((simulation.getWidth()-0*buttonWidth)/2 + buttonXMargin/2, simulation.getHeight()-60, buttonWidth, buttonHeight, "Run", new ClickListener(){ @Override public void onClick() { // prevents user to continue clicking after state change disableUIManager(); Utils.initAllData(); if (DataManager.useProbabilities) { DataManager.applyDataProba(simulation); } else { DataManager.applyDataNumerical(simulation); } simulation.getSimState().enableUIManager(); State.setState(simulation.getSimState()); Utils.log("Simulation starts\n"); } }); this.uiManagerTransit.addObject(run); this.uiManagerTransitFrance.addObject(run); this.uiManagerE.addObject(run); this.uiManagerA.addObject(run); this.uiManagerB.addObject(run); this.uiManagerGeneral.addObject(run); back = new UITextButton((simulation.getWidth()-2*buttonWidth)/2 - buttonXMargin/2, simulation.getHeight()-60, buttonWidth, buttonHeight, "Back", new ClickListener(){ @Override public void onClick() { // prevents user to continue clicking after state change disableUIManager(); simulation.getMenuState().enableUIManager(); State.setState(simulation.getMenuState()); } }); this.uiManagerTransit.addObject(back); this.uiManagerTransitFrance.addObject(back); this.uiManagerE.addObject(back); this.uiManagerA.addObject(back); this.uiManagerB.addObject(back); this.uiManagerGeneral.addObject(back); } public void tick(int n) { if (activePage == 1) { this.uiManagerTransit.tick(); } else if (activePage == -1) { this.uiManagerTransitFrance.tick(); } else if (activePage == 2) { this.uiManagerA.tick(); } else if (activePage == 3) { this.uiManagerB.tick(); } else if (activePage == 4) { this.uiManagerE.tick(); } else if (activePage == 5) { this.uiManagerGeneral.tick(); } if (simulation.getMouseManager().isLeftPressed()) { isLeftPressed = true; } else { if (isLeftPressed) { //simulation.setEntranceERate(test.getCurrentValue()); isLeftPressed = false; } } if (counter % 10 == 0) { if (!DataManager.useProbabilities) { DataManager.applyDataNumerical(simulation); } } counter++; } public void tick() { } public void nextPage() { if (activePage+1 > nPages) { activePage = 1; } else { activePage++; } if (activePage == 1) { enableUIManager(uiManagerTransit); } else if (activePage == -1) { enableUIManager(uiManagerTransitFrance); } else if (activePage == 2) { enableUIManager(uiManagerA); } else if (activePage == 3) { enableUIManager(uiManagerB); } else if (activePage == 4) { enableUIManager(uiManagerE); } else if (activePage == 5) { enableUIManager(uiManagerGeneral); } } public void previousPage() { if (activePage-1 < 1) { activePage = nPages; } else { activePage--; } if (activePage == 1) { enableUIManager(uiManagerTransit); } else if (activePage == -1) { enableUIManager(uiManagerTransitFrance); } else if (activePage == 2) { enableUIManager(uiManagerA); } else if (activePage == 3) { enableUIManager(uiManagerB); } else if (activePage == 4) { enableUIManager(uiManagerE); } else if (activePage == 5) { enableUIManager(uiManagerGeneral); } } public void renderPageIndication(Graphics g) { int smallR = 4; int bigR = 6; int spacing = 30; double x = (simulation.getWidth() - 2*(nPages)*smallR - Math.max(0, nPages-1)*spacing ) /2.0; int y = 600; int r = 0; for (int i=1; i<=nPages ; i++) { if (activePage == i) { g.setColor(Assets.textCol); } else { g.setColor(Assets.idleCol); } if (activePage == i) { x -= (bigR-smallR); y -= (bigR-smallR); r = bigR; } else { r = smallR; } g.fillRect((int) (x), y, 2*r, 2*r); if (activePage == i) { x += (bigR-smallR); y += (bigR-smallR); r = smallR; } if (activePage == i) { g.setColor(Assets.idleCol); } x += 2*r + spacing; } } public void renderNumbers(Graphics g) { Network n = simulation.getSimState().getNetwork(); Road r = n.getRoad("rD884NE"); int totalFlow = computeTotalFlow(r); Text.drawString(g, "A - Thoiry : " + totalFlow, Assets.idleCol, 10, 20, false, Assets.normalFont); r = n.getRoad("rRueDeGeneveSE"); totalFlow = computeTotalFlow(r); Text.drawString(g, "B - St-Genis : " + totalFlow, Assets.idleCol, 10, 40, false, Assets.normalFont); r = n.getRoad("rRueGermaineTillionSW"); totalFlow = computeTotalFlow(r); Text.drawString(g, "C - Ferney : " + totalFlow, Assets.idleCol, 10, 60, false, Assets.normalFont); r = n.getRoad("rC5SW"); totalFlow = computeTotalFlow(r); Text.drawString(g, "D - Europe : " + totalFlow, Assets.idleCol, 10, 80, false, Assets.normalFont); r = n.getRoad("rRoutePauliSouthNELeft"); Road r2 = n.getRoad("rRoutePauliSouthNERight"); totalFlow = computeTotalFlow(r); int totalFlow2 = computeTotalFlow(r2); totalFlow += totalFlow2; r2 = n.getRoad("rRouteDeMeyrinSouthNW"); totalFlow2 = computeTotalFlow(r2); totalFlow += totalFlow2; Text.drawString(g, "E - Geneva : " + totalFlow, Assets.idleCol, 10, 100, false, Assets.normalFont); r = n.getRoad("rSortieCERNNW"); totalFlow = computeTotalFlow(r); Text.drawString(g, "F - Entrance E : " + totalFlow, Assets.idleCol, 10, 120, false, Assets.normalFont); // --------------------------------------------- totalFlow = computeOutFlow(n, "rD884SW"); Text.drawString(g, "G - Thoiry : " + totalFlow, Assets.idleCol, 200, 20, false, Assets.normalFont); totalFlow = computeOutFlow(n, "rRueDeGeneveNW"); Text.drawString(g, "H - St-Genis : " + totalFlow, Assets.idleCol, 200, 40, false, Assets.normalFont); totalFlow = computeOutFlow(n, "rRueGermaineTillionNE"); Text.drawString(g, "I - Ferney : " + totalFlow, Assets.idleCol, 200, 60, false, Assets.normalFont); totalFlow = computeOutFlow(n, "rSortieCERNSE"); totalFlow2 = computeOutFlow(n, "rD884CERN"); totalFlow += totalFlow2; Text.drawString(g, "J - Entrance E : " + totalFlow, Assets.idleCol, 200, 80, false, Assets.normalFont); totalFlow = computeOutFlow(n, "rC5NE"); Text.drawString(g, "K - Europe : " + totalFlow, Assets.idleCol, 200, 100, false, Assets.normalFont); totalFlow = computeOutFlow(n, "rRoutePauliSouthSW"); totalFlow2 = computeOutFlow(n, "rRouteDeMeyrinSouthSE"); totalFlow += totalFlow2; Text.drawString(g, "L - Geneva : " + totalFlow, Assets.idleCol, 200, 120, false, Assets.normalFont); } public int computeTotalFlow(Road r) { int totalFlow = -1; for (int i=0 ; i<r.getFlow().size() ; i++) { totalFlow += r.getFlow().get(i); } if (totalFlow != -1) { totalFlow++; } return totalFlow; } public int computeOutFlow(Network n, String roadName) { int totalFlow = -1; for (AllNetworkRides anr : n.getAllNetworkRides()) { for (Ride ride: anr.getNetworkRides()) { if (ride.getNextConnections().size() > 0 && ride.getNextConnections().get(ride.getNextConnections().size()-1).getName().equals(roadName)) { for (int i=0 ; i<ride.getFlow().size() ; i++) { totalFlow += ride.getFlow().get(i); } } } } if (totalFlow != -1) { totalFlow++; } return totalFlow; } public void render(Graphics g) { g.setColor(Assets.bgCol); g.fillRect(0, 0, simulation.getWidth(), simulation.getHeight()); Text.drawString(g, simulation.getVersionID(), Assets.idleCol, 10, simulation.getHeight()-10, false, Assets.normalFont); Text.drawString(g, "Simulation settings", Assets.idleCol, simulation.getWidth()/2+150, 50, true, Assets.largeFont); if (activePage == 1) { Text.drawString(g, "transit between France and Geneva", Assets.idleCol, simulation.getWidth()/2+150, 85, true, Assets.largeFont); this.uiManagerTransit.render(g); } else if (activePage == -1) { Text.drawString(g, "transit from France to France", Assets.idleCol, simulation.getWidth()/2+150, 85, true, Assets.largeFont); this.uiManagerTransitFrance.render(g); } else if (activePage == 2) { Text.drawString(g, "entrance A", Assets.idleCol, simulation.getWidth()/2+150, 85, true, Assets.largeFont); this.uiManagerA.render(g); } else if (activePage == 3) { Text.drawString(g, "entrance B", Assets.idleCol, simulation.getWidth()/2+150, 85, true, Assets.largeFont); this.uiManagerB.render(g); } else if (activePage == 4) { Text.drawString(g, "entrance E", Assets.idleCol, simulation.getWidth()/2+150, 85, true, Assets.largeFont); this.uiManagerE.render(g); } else if (activePage == 5) { Text.drawString(g, "general settings", Assets.idleCol, simulation.getWidth()/2+150, 85, true, Assets.largeFont); this.uiManagerGeneral.render(g); } renderPageIndication(g); renderNumbers(g); } // Getters & setters ==================================================================================== public UISliderDouble crEntreeB_phase1() { return crEntreeB_phase1; } public UISliderDouble crEntreeB_phase2() { return crEntreeB_phase2; } public UISliderDouble crEntreeB_phase3() { return crEntreeB_phase3; } public UISliderDouble crEntreeB_phase4() { return crEntreeB_phase4; } // FR to GE --------------------------------------------------------------------------------------------- public UISlider fromFrToGe() { return fromFrToGe; } public UISliderTriple fromFrToGeRepartition() { return fromFrToGeRepartition; } public UISliderDouble fromFrToGeRepartitionRH() { return fromFrToGeRepartitionRH; } public UISlider fromFrToGeDuringRH() { return fromFrToGeDuringRH; } // GE to FR --------------------------------------------------------------------------------------------- public UISlider fromGeToFr() { return fromGeToFr; } public UISliderTriple fromGeToFrRepartition() { return fromGeToFrRepartition; } public UISlider fromGeToFrDuringRH2() { return fromGeToFrDuringRH2; } public UISliderDouble fromGeToFrRepartitionRH2() { return fromGeToFrRepartitionRH2; } public UISlider fromFrToFr() { return fromFrToFr; } // Entrance flow ---------------------------------------------------------------------------------------- public UISlider timePerVhcEntrance() { return timePerVhcEntrance; } // To entrance E ---------------------------------------------------------------------------------------- public UISlider toEntranceE() { return toEntranceE; } public UISliderDouble toEntranceERepartition() { return toEntranceERepartition; } public UISliderDouble toEntranceERepartitionRH() { return toEntranceERepartitionRH; } // From entrance E -------------------------------------------------------------------------------------- public UISlider fromEntranceE() { return fromEntranceE; } public UISliderDouble fromEntranceERepartition() { return fromEntranceERepartition; } public UISliderDouble fromEntranceERepartitionRH2() { return fromEntranceERepartitionRH2; } // To entrance A ---------------------------------------------------------------------------------------- public UISlider toEntranceA() { return toEntranceA; } public UISlider toEntranceARepartition() { return toEntranceARepartition; } public UISliderDouble toEntranceARepartitionRH() { return toEntranceARepartitionRH; } // From entrance A ---------------------------------------------------------------------------------------- public UISlider fromEntranceA() { return fromEntranceA; } public UISlider fromEntranceARepartition() { return fromEntranceARepartition; } public UISliderDouble fromEntranceARepartitionRH2() { return fromEntranceARepartitionRH2; } // To entrance B ---------------------------------------------------------------------------------------- public UISlider toEntranceB() { return toEntranceB; } public UISlider toEntranceBRepartition() { return toEntranceBRepartition; } public UISliderDouble toEntranceBRepartitionRH() { return toEntranceBRepartitionRH; } // From entrance A ---------------------------------------------------------------------------------------- public UISlider fromEntranceB() { return fromEntranceB; } public UISlider fromEntranceBRepartition() { return fromEntranceBRepartition; } public UISliderDouble fromEntranceBRepartitionRH2() { return fromEntranceBRepartitionRH2; } // ------------------------------------------------------------------------------------------------------ public UIManager getUIManager() { return this.uiManagerTransit; } public void disableUIManager() { simulation.getMouseManager().setUIManager(null); } public void enableUIManager() { simulation.getMouseManager().setUIManager(this.uiManagerTransit); } public void enableUIManager(UIManager uiManager) { simulation.getMouseManager().setUIManager(uiManager); } }
9236c0ca9363aa6cb236102174029b849d33b7b3
1,403
java
Java
src/com/theaigames/game/warlight2/move/MoveResult.java
Norman1/testSystem
d377d0d3e29b49f9eef7e7df8976e623bea1ef2d
[ "Apache-2.0" ]
null
null
null
src/com/theaigames/game/warlight2/move/MoveResult.java
Norman1/testSystem
d377d0d3e29b49f9eef7e7df8976e623bea1ef2d
[ "Apache-2.0" ]
null
null
null
src/com/theaigames/game/warlight2/move/MoveResult.java
Norman1/testSystem
d377d0d3e29b49f9eef7e7df8976e623bea1ef2d
[ "Apache-2.0" ]
null
null
null
24.310345
78
0.700709
997,807
// Copyright 2015 theaigames.com (hzdkv@example.com) // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. package com.theaigames.game.warlight2.move; import com.theaigames.game.warlight2.map.Map; /** * MoveResult class * * Used for storing the game so the visualizer can replay it * * @author Jim van Eeden <upchh@example.com> */ public class MoveResult { private final Move move; private final Map map; public MoveResult(Move move, Map resultingMap) { this.move = move; this.map = resultingMap; } /** * @return : the move in the MoveResult object */ public Move getMove() { return this.move; } /** * @return : the map in the MoveResult object */ public Map getMap() { return this.map; } }
9236c0d8f2681408938d0168b241dde71c888116
7,033
java
Java
src/test/java/com/univocity/parsers/issues/github/Github_143.java
francogp/univocity-parsers
386c526f7337799fd63adda27f5b7bf3383c3bb4
[ "Apache-2.0" ]
861
2015-01-09T03:51:47.000Z
2022-03-23T08:30:38.000Z
src/test/java/com/univocity/parsers/issues/github/Github_143.java
francogp/univocity-parsers
386c526f7337799fd63adda27f5b7bf3383c3bb4
[ "Apache-2.0" ]
484
2015-02-19T05:00:41.000Z
2022-03-17T19:41:42.000Z
src/test/java/com/univocity/parsers/issues/github/Github_143.java
francogp/univocity-parsers
386c526f7337799fd63adda27f5b7bf3383c3bb4
[ "Apache-2.0" ]
272
2015-01-12T04:20:18.000Z
2022-03-14T21:48:06.000Z
36.82199
100
0.642684
997,808
/******************************************************************************* * Copyright 2017 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.issues.github; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.util.*; import static org.testng.Assert.*; /** * From: https://github.com/univocity/univocity-parsers/issues/143 * * @author Univocity Software Pty Ltd - <a href="mailto:dycjh@example.com">dev@univocity.com</a> */ public class Github_143 { @DataProvider Object[][] data() { return new Object[][]{ {"AA'BB"}, // 1 quote char (OK without escapeEscape option) {"AA|'BB"}, // 1 escape char and 1 quote char {"AA||'BB"}, // 2 escape char and 1 quote char {"AA''BB"}, // 2 quote char (OK without escapeEscape option) {"AA|'|'BB"}, // (1 escape char anc 1 quote char) * 2 {"AA||'||'BB"}, // (2 escape char and 1 quote char) * 2 }; } @Test public void testParseOfUnescapedSequence() { CsvParserSettings settings = new CsvParserSettings(); settings.setEscapeUnquotedValues(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape('|'); String result; result = new CsvParser(settings).parseLine("AA||'||'BB")[0]; assertEquals(result, "AA|'|'BB"); result = new CsvParser(settings).parseLine("AA||'||'||'BB")[0]; assertEquals(result, "AA|'|'|'BB"); result = new CsvParser(settings).parseLine("AA||'z||'BB")[0]; assertEquals(result, "AA|'z|'BB"); result = new CsvParser(settings).parseLine("AA|||'z||'BB")[0]; assertEquals(result, "AA|'z|'BB"); result = new CsvParser(settings).parseLine("AA|||'||'BB")[0]; assertEquals(result, "AA|'|'BB"); result = new CsvParser(settings).parseLine("AA|||'z|||'BB")[0]; assertEquals(result, "AA|'z|'BB"); } @Test(dataProvider = "data") public void testEscapeParsing(String input) { System.out.println("\n--------------[ " + input + " ]---------"); int i = 0; for (char escape : new char[]{'\'', '|'}) { CsvParserSettings settings = new CsvParserSettings(); settings.setEscapeUnquotedValues(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); System.out.print(++i + ") Escape: " + escape + ": "); System.out.print(new CsvParser(settings).parseLine(input)[0]); try { settings.setUnescapedQuoteHandling(UnescapedQuoteHandling.RAISE_ERROR); new CsvParser(settings).parseLine(input); } catch (Exception e) { System.out.print(" << error"); } System.out.println(); } } @Test(dataProvider = "data") public void testEscapeWriting(String input) { System.out.println("\n--------------[ " + input + " ]---------"); int i = 0; List<String> expected = new ArrayList<String>(); for (char escape : new char[]{'\'', '|'}) { CsvWriterSettings settings = new CsvWriterSettings(); settings.setQuoteAllFields(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); System.out.print(++i + ") Escape: " + escape + ": "); String result = new CsvWriter(settings).writeRowToString(input); CsvParserSettings parserSettings = new CsvParserSettings(); settings.setEscapeUnquotedValues(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); String parsed = new CsvParser(parserSettings).parseLine(input)[0]; System.out.println(result + (parsed.equals(input) ? "" : " << BUG!")); assertEquals(parsed, input); expected.add(result); } } @DataProvider Object[][] dataToWrite() { return new Object[][]{ {"AA'BB", '\'', "'AA''BB'"}, // 1 quote char (OK without escapeEscape option) {"AA'BB", '|', "'AA|'BB'"}, // 1 quote char (OK without escapeEscape option) {"AA|'BB", '\'', "'AA|''BB'"}, // 1 escape char and 1 quote char {"AA|'BB", '|', "'AA|||'BB'"}, // 1 escape char and 1 quote char {"AA||'BB", '\'', "'AA||''BB'"}, // 2 escape char and 1 quote char {"AA||'BB", '|', "'AA|||||'BB'"}, // 2 escape char and 1 quote char {"AA''BB", '\'', "'AA''''BB'"}, // 2 quote char (OK without escapeEscape option) {"AA''BB", '|', "'AA|'|'BB'"}, // 2 quote char (OK without escapeEscape option) {"AA|'|'BB", '\'', "'AA|''|''BB'"}, // (1 escape char anc 1 quote char) * 2 {"AA|'|'BB", '|', "'AA|||'|||'BB'"}, // (1 escape char anc 1 quote char) * 2 {"AA||'||'BB", '\'', "'AA||''||''BB'"}, // (2 escape char and 1 quote char) * 2 {"AA||'||'BB", '|', "'AA|||||'|||||'BB'"}, // (2 escape char and 1 quote char) * 2 }; } @Test(dataProvider = "dataToWrite") public void testEscapeWritingQuoteEscapeEnabled(String input, char escape, String expected) { CsvWriterSettings settings = new CsvWriterSettings(); settings.setQuoteEscapingEnabled(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); String result = new CsvWriter(settings).writeRowToString(input); assertEquals(result, expected); } @Test(dataProvider = "dataToWrite") public void testEscapeWritingQuotationTriggers(String input, char escape, String expected) { CsvWriterSettings settings = new CsvWriterSettings(); settings.setQuotationTriggers('\''); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); String result = new CsvWriter(settings).writeRowToString(input); assertEquals(result, expected); } @Test(dataProvider = "dataToWrite") public void testEscapeWritingNoQuotesButEscapeEnabled(String input, char escape, String expected) { expected = expected.substring(1, expected.length() - 1); //no quotes CsvWriterSettings settings = new CsvWriterSettings(); settings.setEscapeUnquotedValues(true); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); String result = new CsvWriter(settings).writeRowToString(input); assertEquals(result, expected); } @Test(dataProvider = "dataToWrite") public void testEscapeWritingEscapeEnabledTriggers(String input, char escape, String expected) { CsvWriterSettings settings = new CsvWriterSettings(); settings.setEscapeUnquotedValues(true); settings.setQuotationTriggers('\''); settings.getFormat().setQuote('\''); settings.getFormat().setQuoteEscape(escape); String result = new CsvWriter(settings).writeRowToString(input); assertEquals(result, expected); } }
9236c3bb9407e379de120f532f13859d16d97fef
1,811
java
Java
raml-plugin/src/main/java/org/mule/tooling/lang/raml/codestyle/RamlCodeStyleSettingsProvider.java
javaduke/data-weave-intellij-plugin
011333c125309089b553f70ed23dd72e41878c8c
[ "Apache-2.0" ]
null
null
null
raml-plugin/src/main/java/org/mule/tooling/lang/raml/codestyle/RamlCodeStyleSettingsProvider.java
javaduke/data-weave-intellij-plugin
011333c125309089b553f70ed23dd72e41878c8c
[ "Apache-2.0" ]
null
null
null
raml-plugin/src/main/java/org/mule/tooling/lang/raml/codestyle/RamlCodeStyleSettingsProvider.java
javaduke/data-weave-intellij-plugin
011333c125309089b553f70ed23dd72e41878c8c
[ "Apache-2.0" ]
null
null
null
40.244444
120
0.710657
997,809
package org.mule.tooling.lang.raml.codestyle; import com.intellij.application.options.CodeStyleAbstractConfigurable; import com.intellij.application.options.CodeStyleAbstractPanel; import com.intellij.application.options.TabbedLanguageCodeStylePanel; import com.intellij.openapi.options.Configurable; import com.intellij.psi.codeStyle.CodeStyleSettings; import org.jetbrains.annotations.NotNull; import org.jetbrains.yaml.YAMLCodeStyleSettingsProvider; import org.jetbrains.yaml.YAMLLanguage; import org.mule.tooling.lang.raml.RamlLanguage; /** * Created by eberman on 4/18/17. */ public class RamlCodeStyleSettingsProvider extends YAMLCodeStyleSettingsProvider { @NotNull @Override public Configurable createSettingsPage(final CodeStyleSettings settings, final CodeStyleSettings originalSettings) { return new CodeStyleAbstractConfigurable(settings, originalSettings, RamlLanguage.INSTANCE.getDisplayName()) { @Override protected CodeStyleAbstractPanel createPanel(final CodeStyleSettings settings) { final CodeStyleSettings currentSettings = getCurrentSettings(); final CodeStyleSettings settings1 = settings; return new TabbedLanguageCodeStylePanel(RamlLanguage.INSTANCE, currentSettings, settings1) { @Override protected void initTabs(final CodeStyleSettings settings) { addIndentOptionsTab(settings); } }; } @Override public String getHelpTopic() { return "reference.settingsdialog.codestyle.yaml"; } }; } @Override public String getConfigurableDisplayName() { return RamlLanguage.INSTANCE.getDisplayName(); } }
9236c3cc4f18dc75a099a32b91faf6319fa1324d
3,087
java
Java
app/src/main/java/com/example/passwordsaver/updatepassword.java
nikhilbhatt/PasswordSaver
660c8a6ce3730b435411e47c8557833668cc10c9
[ "MIT" ]
3
2019-07-21T09:02:32.000Z
2019-09-04T11:05:57.000Z
app/src/main/java/com/example/passwordsaver/updatepassword.java
nikhilbhatt/PasswordSaver
660c8a6ce3730b435411e47c8557833668cc10c9
[ "MIT" ]
null
null
null
app/src/main/java/com/example/passwordsaver/updatepassword.java
nikhilbhatt/PasswordSaver
660c8a6ce3730b435411e47c8557833668cc10c9
[ "MIT" ]
1
2020-10-22T13:00:40.000Z
2020-10-22T13:00:40.000Z
42.287671
113
0.597344
997,810
package com.example.passwordsaver; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; public class updatepassword extends AppCompatActivity { private EditText mcurrentpassword; private EditText mnewpassword; private EditText mconfirmnewpassword; private Button button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_updatepassword); Toolbar toolbar=findViewById(R.id.toolbarupdate); setSupportActionBar(toolbar); getSupportActionBar().setTitle("Update Password"); getSupportActionBar().setDisplayHomeAsUpEnabled(true); mcurrentpassword=findViewById(R.id.current); mnewpassword=findViewById(R.id.newpassword); mconfirmnewpassword=findViewById(R.id.confirmnewpassword); button=findViewById(R.id.updatebutton); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String textpassword=mcurrentpassword.getText().toString(); String textnewpassword=mnewpassword.getText().toString(); String textconfirmpassword=mconfirmnewpassword.getText().toString(); if(textpassword.isEmpty()) { mcurrentpassword.setError("Field is empty!"); return; } if(textnewpassword.isEmpty()) { mnewpassword.setError("Field is Empty!"); return; } SharedPreferences sharedPreferences=getSharedPreferences("PREFS",0); String currentpassword=sharedPreferences.getString("password",""); if(textpassword.equals(currentpassword)) { if(textnewpassword.equals(textconfirmpassword)) { SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putString("password",textnewpassword); editor.apply(); Toast.makeText(updatepassword.this,"Password updated",Toast.LENGTH_SHORT).show(); Intent intnt=new Intent(updatepassword.this,MainActivity.class); startActivity(intnt); finish(); } else { Toast.makeText(updatepassword.this,"Password doesn't matches",Toast.LENGTH_SHORT).show(); } } else { Toast.makeText(updatepassword.this,"Currrent password is wrong",Toast.LENGTH_SHORT).show(); } } }); } }
9236c42165fabe09f18b1b3c1167276406fa1819
3,397
java
Java
src/in/ac/iitm/smscompression/Wrapper.java
sridharkrishna/Sms-Compression
920fb30396437a73ab9ee3077f274f57758e8c52
[ "MIT" ]
null
null
null
src/in/ac/iitm/smscompression/Wrapper.java
sridharkrishna/Sms-Compression
920fb30396437a73ab9ee3077f274f57758e8c52
[ "MIT" ]
null
null
null
src/in/ac/iitm/smscompression/Wrapper.java
sridharkrishna/Sms-Compression
920fb30396437a73ab9ee3077f274f57758e8c52
[ "MIT" ]
null
null
null
24.264286
66
0.65499
997,811
package in.ac.iitm.smscompression; public class Wrapper { private EncodeMessage em = new EncodeMessage(); //private CalculateMessage cm = new CalculateMessage(); private DecodeMessage dm = new DecodeMessage(); public static String mMessage = ""; public Wrapper() { // TODO Auto-generated constructor stub } /** * Encode the message using 8bit/16bit stream for SMS * @param strMessage * @return */ public String encodeString(String strMessage) { char ch[] = strMessage.toCharArray(); int languageFlag = 0; for(int i = 0; i < ch.length; i++) { if(isTamil(ch[i]) != -1) { languageFlag = 0; //System.out.println("Tamil"); break; } else if(isHindi(ch[i]) != -1) { languageFlag = 1; //System.out.println("Hindi"); break; } else if(isGujarati(ch[i]) != -1) { languageFlag = 2; //System.out.println("Gujarati"); break; } } mMessage = em.encodeData(strMessage, languageFlag); return mMessage; } /** * Calculate the message length based on the Unicode * @param strMessage * @return */ public int[] calculateMessageLength(String strMessage) { int[] messageLength = new int[7]; int noOfChars = strMessage.length(); int noOfSms = 0; int noOfRemainingChars = 0; int totalNoOfBits = 0; int paddingBitsSz = 0; int otherBits = 0; int avgBitLen = 0; //Encoded msg length int encodedMessageLength = mMessage.length() * 16; // No. of SMS generated if(encodedMessageLength < 1120) { noOfSms = 1; } else if(encodedMessageLength > 1120) { float val = encodedMessageLength / 1120; noOfSms = ((int) val + 1); } // Total no. of bits in the encoding String //totalNoOfBits = EncodeMessage.msg.length()-24; totalNoOfBits = encodedMessageLength; // Remaining No. of Bits calculation double temp = (double) totalNoOfBits/noOfChars; //commented by vinodp date:22-03-2016 /*int remaingBitsInOneSMS = (noOfSms * 1120) - totalNoOfBits; double avg = (double) (remaingBitsInOneSMS / temp); noOfRemainingChars = (int) avg;*/ //updated by vinod on date:22-03-2016 avgBitLen = (int)Math.ceil(temp); // Average Bit length noOfRemainingChars = ((noOfSms * 1120)-totalNoOfBits)/avgBitLen; //end of updated by vinod // No. of padding bits used //paddingBitsSz = encodedMessageLength - totalNoOfBits; paddingBitsSz = EncodeMessage.msg.length() % 16; // Header Bits otherBits = 24; messageLength[0] = noOfSms; messageLength[1] = noOfChars; messageLength[2] = noOfRemainingChars; messageLength[3] = totalNoOfBits; messageLength[4] = paddingBitsSz; messageLength[5] = otherBits; messageLength[6] = avgBitLen; return messageLength; } /** * Decode the encoded string based on the decoding table * @param strEncodedString * @return */ public String decodeString(String strEncodedString) { return dm.decodeData(strEncodedString); } private int isTamil(char ch) { for(int i = 0; i < Config.Tamil.length; i++) { if(Config.Tamil[i] == ch) return i; } return -1; } private int isHindi(char ch) { for(int i = 0; i < Config.Hindi.length; i++) { if(Config.Hindi[i] == ch) return i; } return -1; } private int isGujarati(char ch) { for(int i = 0; i < Config.Gujarati.length; i++) { if(Config.Gujarati[i] == ch) return i; } return -1; } }
9236c46a342928754d79a8068269ffd7369e27b1
943
java
Java
src/main/java/fr/insee/sabianedata/ws/model/ReportingModel.java
InseeFrLab/Sabiane-Data
dd174487f40867a9c6eb2b5cde809bcc5c8b31c6
[ "MIT" ]
null
null
null
src/main/java/fr/insee/sabianedata/ws/model/ReportingModel.java
InseeFrLab/Sabiane-Data
dd174487f40867a9c6eb2b5cde809bcc5c8b31c6
[ "MIT" ]
2
2022-01-04T16:55:16.000Z
2022-01-04T16:58:20.000Z
src/main/java/fr/insee/sabianedata/ws/model/ReportingModel.java
InseeFr/Massive-Attack-Back-Office
4188c67681cdeec49060d8ad21084f5df936e5d8
[ "MIT" ]
5
2021-07-05T15:21:46.000Z
2021-09-09T13:49:03.000Z
21.431818
52
0.66596
997,812
package fr.insee.sabianedata.ws.model; import com.fasterxml.jackson.annotation.JsonInclude; import java.util.ArrayList; import java.util.List; @JsonInclude(JsonInclude.Include.NON_NULL) public class ReportingModel { private List<String> success; private List<String> failures; public ReportingModel() { this.success = new ArrayList<String>(); this.failures = new ArrayList<String>(); } public void addSuccess(String successUeId) { this.success.add(successUeId); } public void addFailure(String failureUeId) { this.failures.add(failureUeId); } public List<String> getSuccess() { return success; } public void setSuccess(List<String> success) { this.success = success; } public List<String> getFailures() { return failures; } public void setFailures(List<String> failures) { this.failures = failures; } }
9236c4c8efad718c1c8863b850f21dde8c276067
297
java
Java
VIII semester/advanced-web-technologies/2019-2020/notification-service/src/test/java/com/event4u/notificationservice/NotificationServiceApplicationTests.java
ksaracevic1/etf-alles-1
0ab1ad83d00fafc69b38266edd875bce08c1fc9e
[ "Unlicense" ]
14
2019-02-11T18:35:19.000Z
2022-03-26T09:54:47.000Z
VIII semester/advanced-web-technologies/2019-2020/notification-service/src/test/java/com/event4u/notificationservice/NotificationServiceApplicationTests.java
NailaZukanovic/etf-alles
0ab1ad83d00fafc69b38266edd875bce08c1fc9e
[ "Unlicense" ]
4
2021-12-22T12:01:34.000Z
2021-12-22T12:01:35.000Z
VIII semester/advanced-web-technologies/2019-2020/notification-service/src/test/java/com/event4u/notificationservice/NotificationServiceApplicationTests.java
NailaZukanovic/etf-alles
0ab1ad83d00fafc69b38266edd875bce08c1fc9e
[ "Unlicense" ]
18
2019-06-09T22:06:09.000Z
2022-02-15T07:17:15.000Z
19.8
60
0.818182
997,813
package com.event4u.notificationservice; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertEquals; @SpringBootTest class NotificationServiceApplicationTests { @Test void contextLoads() { } }
9236c4d1c075f8b7b56a068edd5b5ed476a15c9c
1,762
java
Java
app/src/main/java/hungry/ex_frag/numSample/GridViewAdapter.java
sunpark20/mplace
d1a94966e3f26f99bcec99ba0df1c7c454c93cfa
[ "MIT" ]
null
null
null
app/src/main/java/hungry/ex_frag/numSample/GridViewAdapter.java
sunpark20/mplace
d1a94966e3f26f99bcec99ba0df1c7c454c93cfa
[ "MIT" ]
null
null
null
app/src/main/java/hungry/ex_frag/numSample/GridViewAdapter.java
sunpark20/mplace
d1a94966e3f26f99bcec99ba0df1c7c454c93cfa
[ "MIT" ]
null
null
null
26.298507
79
0.64756
997,814
package hungry.ex_frag.numSample; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.ArrayList; import hungry.ex_frag.R; class GridViewAdapter extends BaseAdapter { private Context context; private ArrayList<String> al; public GridViewAdapter(Context context, ArrayList<String> al) { this.context = context; this.al = al; } public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); View gridView; TextView tv=null; //틀만 재사용한다. if (convertView == null) { gridView = new View(context); // get layout from mobile.xml gridView = inflater.inflate(R.layout.item_numprac_mem_score, null); } else { gridView = (View) convertView; } // set value into textview tv = (TextView) gridView .findViewById(R.id.num); tv.setText(al.get(position)); tv.setTextAppearance(context, android.R.style.TextAppearance_Large); return gridView; } private void setDefault(TextView tv){ tv.setTextColor(context.getResources().getColor(R.color.black)); tv.setBackgroundColor(context.getResources().getColor(R.color.white)); } @Override public int getCount() { return al.size(); } @Override public Object getItem(int position) { return null; } @Override public long getItemId(int position) { return 0; } }
9236c4eded9826b51ef27bec9ee7d0b94296616b
1,359
java
Java
11_Exam_Preparation/01_sboj_gb/src/main/java/org/softuni/exam/web/beans/DeleteJobBean.java
IvoIvanov77/JavaWebDevelopmentBasics
0a7aa468bedd72d4d8ebd640f47de9f65bbe3318
[ "MIT" ]
null
null
null
11_Exam_Preparation/01_sboj_gb/src/main/java/org/softuni/exam/web/beans/DeleteJobBean.java
IvoIvanov77/JavaWebDevelopmentBasics
0a7aa468bedd72d4d8ebd640f47de9f65bbe3318
[ "MIT" ]
null
null
null
11_Exam_Preparation/01_sboj_gb/src/main/java/org/softuni/exam/web/beans/DeleteJobBean.java
IvoIvanov77/JavaWebDevelopmentBasics
0a7aa468bedd72d4d8ebd640f47de9f65bbe3318
[ "MIT" ]
null
null
null
27.18
88
0.734364
997,815
package org.softuni.exam.web.beans; import org.modelmapper.ModelMapper; import org.softuni.exam.domain.models.binding.JobCreateBindingModel; import org.softuni.exam.domain.models.service.JobServiceModel; import org.softuni.exam.domain.models.view.JobsDetailsViewModel; import org.softuni.exam.service.JobService; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; @Named(value = "deleteJob") @RequestScoped public class DeleteJobBean extends BaseBean { private JobService jobService; private ModelMapper modelMapper; private JobsDetailsViewModel viewModel; private String id; public DeleteJobBean() { } @Inject public DeleteJobBean(JobService jobService, ModelMapper modelMapper) { this.jobService = jobService; this.modelMapper = modelMapper; } @PostConstruct private void init(){ this.id = this.getRequest().getParameter("id"); JobServiceModel serviceModel = this.jobService.getOneById(this.id); this.viewModel = this.modelMapper.map(serviceModel, JobsDetailsViewModel.class); } public JobsDetailsViewModel getViewModel() { return viewModel; } public void delete(){ this.jobService.deleteJob(this.id); this.redirect("/"); } }
9236c5855eff58fc04844dd9874909386879e6bd
1,193
java
Java
managed/src/main/java/com/yugabyte/yw/forms/UserRegisterFormData.java
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
1
2021-06-11T10:23:00.000Z
2021-06-11T10:23:00.000Z
managed/src/main/java/com/yugabyte/yw/forms/UserRegisterFormData.java
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
managed/src/main/java/com/yugabyte/yw/forms/UserRegisterFormData.java
adil246/yugabyte-db
dc886cdd43497543e8ad2ad07bb77ad02e4cd4b1
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
19.241935
94
0.70746
997,816
// Copyright (c) Yugabyte, Inc. package com.yugabyte.yw.forms; import play.data.validation.Constraints; import java.util.Map; import static com.yugabyte.yw.models.Users.Role; /** This class will be used by the API and UI Form Elements to validate constraints are met */ public class UserRegisterFormData { @Constraints.Required() @Constraints.Email private String email; private String password; private String confirmPassword; private Map features; @Constraints.Required() private Role role; public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getConfirmPassword() { return confirmPassword; } public void setConfirmPassword(String confirmPassword) { this.confirmPassword = confirmPassword; } public Map getFeatures() { return features; } public void setFeatures(Map features) { this.features = features; } public Role getRole() { return role; } public void setRole(Role role) { this.role = role; } }
9236c5e2f0f1775caf73de4f11e53581ce6a255f
721
java
Java
src/main/java/com/letv/core/bean/WatchAndBuyGoodsBean.java
tiwer/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
39
2017-08-07T09:03:54.000Z
2021-09-29T09:31:39.000Z
src/main/java/com/letv/core/bean/WatchAndBuyGoodsBean.java
JackChan1999/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
null
null
null
src/main/java/com/letv/core/bean/WatchAndBuyGoodsBean.java
JackChan1999/letv
1eeb7079be8bad4ffb61fdb06ff8d49760f9e120
[ "Apache-2.0" ]
39
2017-05-08T13:11:39.000Z
2021-12-26T12:42:14.000Z
24.862069
59
0.711512
997,817
package com.letv.core.bean; public class WatchAndBuyGoodsBean implements LetvBaseBean { public String attention; public String btn_txt; public String btn_url; public String desc; public String endTime; public String id; public String name; public String oldPrice; public String pic; public String pic1; public String pic2; public String pic3; public String pic_text1; public String pic_text2; public String pic_text3; public String pic_text4; public String pic_text5; public String praise; public String price; public String shortId; public String startTime; public String streamId; public String type; public String url; }
9236c7050a02bcb17ba4e47730fd81dab98e7a99
1,544
java
Java
loser-tests/src/test/java/com/loserico/netty/echo/EchoServerHandler.java
ricoyu/loser
5c26c15a95042a5e3e364e58f92a405873bb10e3
[ "MIT" ]
5
2019-06-09T13:27:49.000Z
2019-12-13T03:55:03.000Z
loser-tests/src/test/java/com/loserico/netty/echo/EchoServerHandler.java
wenxuejiang610/Loser
acbafd262961e1eba483b55215305af459502e43
[ "MIT" ]
9
2020-01-15T00:48:17.000Z
2021-08-09T20:57:38.000Z
loser-tests/src/test/java/com/loserico/netty/echo/EchoServerHandler.java
wenxuejiang610/Loser
acbafd262961e1eba483b55215305af459502e43
[ "MIT" ]
2
2019-06-09T13:43:33.000Z
2019-06-10T02:46:30.000Z
32.166667
92
0.755829
997,818
package com.loserico.netty.echo; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelHandler.Sharable; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.util.CharsetUtil; // Indicates that a ChannelHandler can be safely shared by multiple channels @Sharable public class EchoServerHandler extends ChannelInboundHandlerAdapter { /** * Called for each incoming message */ @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { ByteBuf in = (ByteBuf) msg; //Logs the message to the console System.out.println("Server received: " + in.toString(CharsetUtil.UTF_8)); //Writes the received message to the sender without flushing the outbound messages ctx.write(in); } /** * Notifies the handler that the last call made to channelRead() was the last * message in the current batch */ @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { //Flushes pending messages to the remote peer and closes the channel ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE); } /** * Called if an exception is thrown during the read operation */ @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); //Closes the channel ctx.close(); } }
9236c7ab4484afbf6f3b7e6ae7ab6ca62949e076
808
java
Java
grape-domain/src/main/java/com/mzh/grape/domain/model/IAction.java
zhdotm/grape-machine
caea0bb33436b875dcfbd2236561455ecd506811
[ "Apache-2.0" ]
null
null
null
grape-domain/src/main/java/com/mzh/grape/domain/model/IAction.java
zhdotm/grape-machine
caea0bb33436b875dcfbd2236561455ecd506811
[ "Apache-2.0" ]
null
null
null
grape-domain/src/main/java/com/mzh/grape/domain/model/IAction.java
zhdotm/grape-machine
caea0bb33436b875dcfbd2236561455ecd506811
[ "Apache-2.0" ]
null
null
null
18.363636
87
0.613861
997,819
package com.mzh.grape.domain.model; import cn.hutool.core.annotation.AnnotationUtil; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.mzh.grape.domain.annotation.Action; /** * 动作 * * @author zhihao.mao */ public interface IAction { /** * 获取动作ID * * @return 动作ID */ String getActionId(); /** * 获取状态机ID * * @return 状态机ID */ default String getStateMachineId() { Class<? extends IAction> clazz = this.getClass(); Action action = AnnotationUtil.getAnnotation(clazz, Action.class); return ObjectUtil.isNotEmpty(action) ? action.stateMachineId() : StrUtil.EMPTY; } /** * 执行动作 * * @param args 参数 * @return 是否执行成功 */ Boolean invoke(Object... args); }
9236c7d4726b40633c627ec8f80ca12d59e98e5b
287
java
Java
sandbox/src/main/java/ru/ql/basynya/homework/Point.java
Andarkis/java_a.basynya
b3a22e10bd445fbc61dbb708dd365436358aa4b4
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/ru/ql/basynya/homework/Point.java
Andarkis/java_a.basynya
b3a22e10bd445fbc61dbb708dd365436358aa4b4
[ "Apache-2.0" ]
null
null
null
sandbox/src/main/java/ru/ql/basynya/homework/Point.java
Andarkis/java_a.basynya
b3a22e10bd445fbc61dbb708dd365436358aa4b4
[ "Apache-2.0" ]
null
null
null
16.882353
76
0.609756
997,820
package ru.ql.basynya.homework; public class Point { public double x; public double y; public Point(double x, double y) { this.x = x; this.y = y; } public double distance(Point p) { return Math.sqrt(Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2)); } }
9236c8e7ac07152c41239b7380c009dc2733a87e
307
java
Java
yu-api/yu-serve/serve-system/src/main/java/org/yu/serve/system/module/dept/service/DeptTypeRoleService.java
wangxd-yu/yu-platform
7e535eb4e71dd1f137954ac8bfdd41a94e4db1d3
[ "Apache-2.0" ]
5
2021-04-17T04:29:29.000Z
2022-01-13T02:41:33.000Z
yu-api/yu-serve/serve-system/src/main/java/org/yu/serve/system/module/dept/service/DeptTypeRoleService.java
wangxd-yu/yu-platform
7e535eb4e71dd1f137954ac8bfdd41a94e4db1d3
[ "Apache-2.0" ]
null
null
null
yu-api/yu-serve/serve-system/src/main/java/org/yu/serve/system/module/dept/service/DeptTypeRoleService.java
wangxd-yu/yu-platform
7e535eb4e71dd1f137954ac8bfdd41a94e4db1d3
[ "Apache-2.0" ]
2
2022-01-04T02:38:22.000Z
2022-01-27T19:06:39.000Z
25.583333
85
0.785016
997,821
package org.yu.serve.system.module.dept.service; import org.yu.common.querydsl.service.DslBaseService; import org.yu.serve.system.module.dept.domain.DeptTypeRoleDO; /** * @author wangxd * @date 2020-11-30 14:36 */ public interface DeptTypeRoleService extends DslBaseService<DeptTypeRoleDO, String> { }
9236c9f049a53df12567f5f6bb95b68aac529588
322
java
Java
tps-forvalteren-domain/tps-forvalteren-domain-rs/src/main/java/no/nav/tps/forvalteren/domain/rs/TypeOgAntall.java
navikt/tps-forvalteren
864fa1e19d8fcea53b8acb976b517670d10768eb
[ "MIT" ]
null
null
null
tps-forvalteren-domain/tps-forvalteren-domain-rs/src/main/java/no/nav/tps/forvalteren/domain/rs/TypeOgAntall.java
navikt/tps-forvalteren
864fa1e19d8fcea53b8acb976b517670d10768eb
[ "MIT" ]
37
2020-09-23T14:00:49.000Z
2021-11-17T12:19:57.000Z
tps-forvalteren-domain/tps-forvalteren-domain-rs/src/main/java/no/nav/tps/forvalteren/domain/rs/TypeOgAntall.java
navikt/tps-forvalteren
864fa1e19d8fcea53b8acb976b517670d10768eb
[ "MIT" ]
1
2022-02-16T13:52:48.000Z
2022-02-16T13:52:48.000Z
17.888889
41
0.804348
997,822
package no.nav.tps.forvalteren.domain.rs; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; @Getter @Setter @Builder @AllArgsConstructor @NoArgsConstructor public class TypeOgAntall { private String type; private Long antall; }
9236caa6aecbd8099af2e155bb172bec5798c87b
983
java
Java
c-xml-client/src/test/java/com/webcohesion/enunciate/modules/c_client/TestCDeploymentModule.java
octetnest/enunciate
e571c6a7aa50a18c60a529be28d14619342940eb
[ "Apache-2.0" ]
431
2015-01-05T06:27:54.000Z
2022-03-29T22:01:03.000Z
c-xml-client/src/test/java/com/webcohesion/enunciate/modules/c_client/TestCDeploymentModule.java
octetnest/enunciate
e571c6a7aa50a18c60a529be28d14619342940eb
[ "Apache-2.0" ]
1,020
2015-01-17T17:44:54.000Z
2022-03-30T14:11:06.000Z
c-xml-client/src/test/java/com/webcohesion/enunciate/modules/c_client/TestCDeploymentModule.java
octetnest/enunciate
e571c6a7aa50a18c60a529be28d14619342940eb
[ "Apache-2.0" ]
180
2015-02-02T17:12:44.000Z
2022-03-05T10:51:47.000Z
29.878788
75
0.735294
997,823
/** * Copyright © 2006-2016 Web Cohesion (efpyi@example.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.webcohesion.enunciate.modules.c_client; import junit.framework.TestCase; /** * @author Ryan Heaton */ public class TestCDeploymentModule extends TestCase { /** * tests scrubbing a c identifie. */ public void testScrubIdentifier() throws Exception { assertEquals("hello_me", CXMLClientModule.scrubIdentifier("hello-me")); } }
9236cad8f00bc438251840184831a022da8c45d6
718
java
Java
src/dziedziczenie/Dziedziczenie.java
Konrad-code/Dziedziczenie
f15befa1288ab8b1ed612379fab0dceb53810bbc
[ "Unlicense" ]
null
null
null
src/dziedziczenie/Dziedziczenie.java
Konrad-code/Dziedziczenie
f15befa1288ab8b1ed612379fab0dceb53810bbc
[ "Unlicense" ]
null
null
null
src/dziedziczenie/Dziedziczenie.java
Konrad-code/Dziedziczenie
f15befa1288ab8b1ed612379fab0dceb53810bbc
[ "Unlicense" ]
null
null
null
29.916667
69
0.683844
997,824
package dziedziczenie; import dziedziczenie.potwory.Potwor; import dziedziczenie.potwory.Szkielet; import dziedziczenie.potwory.Zombie; public class Dziedziczenie { public static void main(String[] args) { Potwor pierwszySzkielet = new Szkielet(15, 100); System.out.println(pierwszySzkielet.getPredkoscPoruszania()); Szkielet drugiSzkielet = new Szkielet(20, 50, "Luk"); System.out.println(drugiSzkielet.getPredkoscPoruszania()); Zombie pierwszyZombie = new Zombie(); drugiSzkielet.atakuj(); Szkielet trzeciSzkielet = new Szkielet(); Potwor czwartySzkielet = new Szkielet(10, 100); czwartySzkielet.atakuj(); } }
9236cb6160246165646a4ccd82b0888dac8319ce
7,501
java
Java
TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/connection/AliasedConnection.java
RUB-NDS/TLS-Attacker
74c7dd7552bc47459d3111cec6029d2750abe8fc
[ "Apache-2.0" ]
593
2016-04-20T16:19:52.000Z
2020-11-05T01:22:01.000Z
TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/connection/AliasedConnection.java
RUB-NDS/TLS-Attacker
74c7dd7552bc47459d3111cec6029d2750abe8fc
[ "Apache-2.0" ]
75
2016-05-02T22:34:02.000Z
2020-11-06T11:02:36.000Z
TLS-Core/src/main/java/de/rub/nds/tlsattacker/core/connection/AliasedConnection.java
RUB-NDS/TLS-Attacker
74c7dd7552bc47459d3111cec6029d2750abe8fc
[ "Apache-2.0" ]
130
2016-04-21T05:16:09.000Z
2020-10-26T01:09:52.000Z
31.649789
115
0.610985
997,825
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2022 Ruhr University Bochum, Paderborn University, Hackmanit GmbH * * Licensed under Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0.txt */ package de.rub.nds.tlsattacker.core.connection; import de.rub.nds.tlsattacker.core.exceptions.ConfigurationException; import de.rub.nds.tlsattacker.transport.Connection; import de.rub.nds.tlsattacker.transport.ConnectionEndType; import de.rub.nds.tlsattacker.transport.TransportHandlerType; import java.util.Collection; import java.util.HashSet; import java.util.Objects; import java.util.Set; import javax.xml.bind.annotation.XmlType; @XmlType(propOrder = { "alias", "ip", "port", "hostname", "proxyDataPort", "proxyDataHostname", "proxyControlPort", "proxyControlHostname", "timeout", "firstTimeout", "connectionTimeout", "transportHandlerType", "sourcePort" }) public abstract class AliasedConnection extends Connection implements Aliasable { public static final String DEFAULT_CONNECTION_ALIAS = "defaultConnection"; public static final TransportHandlerType DEFAULT_TRANSPORT_HANDLER_TYPE = TransportHandlerType.TCP; public static final Integer DEFAULT_TIMEOUT = 1000; public static final Integer DEFAULT_CONNECTION_TIMEOUT = 8000; public static final Integer DEFAULT_FIRST_TIMEOUT = DEFAULT_TIMEOUT; public static final String DEFAULT_HOSTNAME = "localhost"; public static final String DEFAULT_IP = "127.0.0.1"; public static final Integer DEFAULT_PORT = 443; protected String alias = null; public AliasedConnection() { } public AliasedConnection(Integer port) { super(port); } public AliasedConnection(Integer port, String hostname) { super(port, hostname); } public AliasedConnection(String alias) { this.alias = alias; } public AliasedConnection(String alias, Integer port) { super(port); this.alias = alias; } public AliasedConnection(String alias, Integer port, String hostname) { super(port, hostname); this.alias = alias; } public AliasedConnection(AliasedConnection other) { super(other); alias = other.alias; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } @Override public void assertAliasesSetProperly() throws ConfigurationException { if ((alias == null) || (alias.isEmpty())) { throw new ConfigurationException("Empty or null alias in " + this.getClass().getSimpleName()); } } public abstract String toCompactString(); @Override public String aliasesToString() { return alias; } @Override public String getFirstAlias() { return alias; } @Override public Set<String> getAllAliases() { Set<String> set = new HashSet<>(); set.add(alias); return set; } @Override public boolean containsAlias(String alias) { return this.alias.equals(alias); } @Override public boolean containsAllAliases(Collection<String> aliases) { if (aliases == null || aliases.isEmpty()) { return false; } if (aliases.size() == 1) { return this.alias.equals(aliases.iterator().next()); } return false; } public String getDefaultConnectionAlias() { return DEFAULT_CONNECTION_ALIAS; } @Override public abstract ConnectionEndType getLocalConnectionEndType(); @Override public int hashCode() { int hash = super.hashCode(); hash = 41 * hash + Objects.hashCode(this.alias); return hash; } @Override public boolean equals(Object obj) { if (!super.equals(obj)) { return false; } final AliasedConnection other = (AliasedConnection) obj; return Objects.equals(this.alias, other.alias); } public void normalize(AliasedConnection defaultCon) { if ((alias == null) || alias.isEmpty()) { alias = defaultCon.getAlias(); if (alias == null || alias.isEmpty()) { alias = getDefaultConnectionAlias(); } } if (transportHandlerType == null) { transportHandlerType = defaultCon.getTransportHandlerType(); if (transportHandlerType == null) { transportHandlerType = DEFAULT_TRANSPORT_HANDLER_TYPE; } } if (timeout == null) { timeout = defaultCon.getTimeout(); if (timeout == null) { timeout = DEFAULT_TIMEOUT; } } if (firstTimeout == null) { firstTimeout = defaultCon.getFirstTimeout(); if (firstTimeout == null) { firstTimeout = DEFAULT_FIRST_TIMEOUT; } } if (connectionTimeout == null) { connectionTimeout = defaultCon.getConnectionTimeout(); if (connectionTimeout == null) { connectionTimeout = DEFAULT_CONNECTION_TIMEOUT; } } if (hostname == null || hostname.isEmpty()) { hostname = defaultCon.getHostname(); if (hostname == null || hostname.isEmpty()) { hostname = DEFAULT_HOSTNAME; } } if (ip == null || ip.isEmpty()) { ip = defaultCon.getHostname(); if (ip == null || ip.isEmpty()) { ip = DEFAULT_IP; } } if (port == null) { port = defaultCon.getPort(); if (port == null) { port = DEFAULT_PORT; } if (port < 0 || port > 65535) { throw new ConfigurationException( "Attempt to set default port " + "failed. Port must be in interval [0,65535], but is " + port); } } } public void filter(AliasedConnection defaultCon) { if (alias.equals(defaultCon.getAlias()) || alias.equals(getDefaultConnectionAlias())) { alias = null; } if (transportHandlerType == defaultCon.getTransportHandlerType() || transportHandlerType == DEFAULT_TRANSPORT_HANDLER_TYPE) { transportHandlerType = null; } if (Objects.equals(timeout, defaultCon.getTimeout()) || Objects.equals(timeout, DEFAULT_TIMEOUT)) { timeout = null; } if (Objects.equals(firstTimeout, defaultCon.getTimeout()) || Objects.equals(firstTimeout, DEFAULT_FIRST_TIMEOUT)) { firstTimeout = null; } if (hostname.equals(defaultCon.getHostname()) || Objects.equals(hostname, DEFAULT_HOSTNAME)) { hostname = null; } if (ip.equals(defaultCon.getHostname()) || Objects.equals(ip, DEFAULT_IP)) { ip = null; } if (Objects.equals(port, defaultCon.getPort()) || Objects.equals(port, DEFAULT_PORT)) { port = null; } } @Override protected void addProperties(StringBuilder sb) { sb.append("alias=").append(alias).append(" "); super.addProperties(sb); } @Override protected void addCompactProperties(StringBuilder sb) { sb.append(alias).append(":"); super.addCompactProperties(sb); } public abstract AliasedConnection getCopy(); }
9236cbac5033407005c6d77d810ce0e0bd638f65
621
java
Java
gradleSpring/src/main/java/fr/friquerette/myweebapp2/proxy/system_b/ServerProxyImage.java
friquerette/main_repo
007cf190f585f71e163ff0c5ad4ee7e670ec1e10
[ "Apache-2.0" ]
null
null
null
gradleSpring/src/main/java/fr/friquerette/myweebapp2/proxy/system_b/ServerProxyImage.java
friquerette/main_repo
007cf190f585f71e163ff0c5ad4ee7e670ec1e10
[ "Apache-2.0" ]
null
null
null
gradleSpring/src/main/java/fr/friquerette/myweebapp2/proxy/system_b/ServerProxyImage.java
friquerette/main_repo
007cf190f585f71e163ff0c5ad4ee7e670ec1e10
[ "Apache-2.0" ]
null
null
null
23.884615
65
0.716586
997,826
package fr.friquerette.myweebapp2.proxy.system_b; import fr.friquerette.myweebapp2.proxy.Image; import fr.friquerette.myweebapp2.proxy.system_a.ServerRealImage; //on System B public class ServerProxyImage implements Image { private ServerRealImage image = null; private String filename = null; public ServerProxyImage(final String filename) { this.filename = filename; } @Override public String displayImage() { if (image == null) { image = new ServerRealImage(filename); } String msg = image.displayImage(); System.out.println("Proxy doing :" + msg); return msg; } }
9236cc126b0863522fceb21e02a67a9d3c616bb3
27,128
java
Java
Source_code_of_online_tool/src/simbio/main/SimController.java
fusion-jena/SimBio
d95ad5cb366dfde0c090f7b27d3d847a2f937367
[ "Apache-2.0" ]
null
null
null
Source_code_of_online_tool/src/simbio/main/SimController.java
fusion-jena/SimBio
d95ad5cb366dfde0c090f7b27d3d847a2f937367
[ "Apache-2.0" ]
null
null
null
Source_code_of_online_tool/src/simbio/main/SimController.java
fusion-jena/SimBio
d95ad5cb366dfde0c090f7b27d3d847a2f937367
[ "Apache-2.0" ]
1
2019-07-26T09:56:40.000Z
2019-07-26T09:56:40.000Z
38.424929
121
0.63945
997,827
package simbio.main; /** * Similarity Controller * @author Samira Babalou (samira[dot]babalou[at]uni_jean[dot]de) */ import java.net.URISyntaxException; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.openrdf.model.URI; import slib.graph.algo.utils.GAction; import slib.graph.algo.utils.GActionType; import slib.graph.algo.validator.dag.ValidatorDAG; import slib.graph.io.conf.GDataConf; import slib.graph.io.conf.GraphConf; import slib.graph.io.loader.GraphLoaderGeneric; import slib.graph.io.util.GFormat; import slib.graph.model.graph.G; import slib.graph.model.impl.graph.memory.GraphMemory; import slib.graph.model.impl.repo.URIFactoryMemory; import slib.graph.model.repo.URIFactory; import slib.sml.sm.core.engine.SM_Engine; import slib.sml.sm.core.metrics.ic.dspo.findShareP; import slib.sml.sm.core.metrics.ic.utils.IC_Conf_Topo; import slib.sml.sm.core.metrics.ic.utils.ICconf; import slib.sml.sm.core.utils.SMConstants; import slib.sml.sm.core.utils.SMconf; import slib.utils.ex.SLIB_Exception; public class SimController { public static String SimBioFunc(String Term1, String Term2, String OntFlag, String Term1OntPath, String Term2OntPath, String Simflag) throws URISyntaxException { String MergedOnt = null; double sim = 0.0; String res = null; try { ICconf icConf = new IC_Conf_Topo(SMConstants.FLAG_ICI_SANCHEZ_2011_b_adapted); SMconf measureConf = new SMconf(SMConstants.FLAG_SIM_PAIRWISE_DAG_NODE_LIN_1998, icConf); URIFactory factory = URIFactoryMemory.getSingleton(); URI c1 = factory.getURI("http://www.nlm.nih.gov/thing"), c2 = factory.getURI("http://www.nlm.nih.gov/thing"); icConf = new IC_Conf_Topo(SMConstants.FLAG_ICI_SANCHEZ_2011_b_adapted); switch (Simflag) { case "Lin": measureConf = new SMconf(SMConstants.FLAG_SIM_PAIRWISE_DAG_NODE_LIN_1998, icConf); break; case "Resnik": measureConf = new SMconf(SMConstants.FLAG_SIM_PAIRWISE_DAG_NODE_RESNIK_1995, icConf); break; case "J&C": measureConf = new SMconf(SMConstants.FLAG_DIST_PAIRWISE_DAG_NODE_JIANG_CONRATH_1997, icConf); break; } String[] SetTerm1 = Term1.split(","); String[] SetTerm2 = Term2.split(","); switch (OntFlag) { case "MeSH": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; c1 = factory.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm1[i].trim()); c2 = factory.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm2[i].trim()); if (Coordinator.engineMeSH == null) { Coordinator.meshLoader(); } sim = Coordinator.engineMeSH.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); c1 = null; c2 = null; } break; case "SNOMEDCT": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineSNOMED == null) { Coordinator.snomedLoader(); } URI snomedctURI = factory.getURI("http://snomedct/"); c1 = factory.getURI(snomedctURI.stringValue() + SetTerm1[i].trim()); c2 = factory.getURI(snomedctURI.stringValue() + SetTerm2[i].trim()); sim = Coordinator.engineSNOMED.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); snomedctURI = null; c1 = null; c2 = null; } break; case "WordNet": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineWordNet == null) { Coordinator.wordnetLoader(); } Set<URI> uris_Term1 = Coordinator.indexWordnetNoun.get(SetTerm1[i].trim()); Set<URI> uris_Term2 = Coordinator.indexWordnetNoun.get(SetTerm2[i].trim()); c1 = uris_Term1.iterator().next(); c2 = uris_Term2.iterator().next(); sim = Coordinator.engineWordNet.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); c1 = null; c2 = null; factory = null; } break; case "MeSH-SNOMEDCT": MergedOnt = "MeshSnomedCT"; res = ""; SM_Engine.firstPriority = false; findShareP.CSVtoArray(MergedOnt); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineMeSH == null) Coordinator.meshLoader(); if (Coordinator.engineSNOMED == null) Coordinator.snomedLoader(); // ***********call combine engine URIFactory factoryMesh = URIFactoryMemory.getSingleton(); URIFactory factorySnomed = URIFactoryMemory.getSingleton(); URI snomedctURI = factorySnomed.getURI("http://snomedct/"); c1 = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm1[i].trim()); c2 = factorySnomed.getURI(snomedctURI.stringValue() + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.meshGraph, Coordinator.snomedGraph, MergedOnt); // MergingGraph sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); engine = null; c1 = null; c2 = null; factorySnomed = null; factoryMesh = null; snomedctURI = null; } break; case "MeSH-WordNet": res = ""; MergedOnt = "MeshWordNet"; SM_Engine.firstPriority = false; findShareP.CSVtoArray(MergedOnt); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineMeSH == null) Coordinator.meshLoader(); if (Coordinator.engineWordNet == null) Coordinator.wordnetLoader(); // ***********call combine engine URIFactory factoryMesh = URIFactoryMemory.getSingleton(); c1 = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm1[i]); Set<URI> uris_Term2 = Coordinator.indexWordnetNoun.get(SetTerm2[i]); c2 = uris_Term2.iterator().next(); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.meshGraph, Coordinator.wordnetGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; engine = null; c1 = null; c2 = null; factoryMesh = null; } break; case "SNOMEDCT-MeSH": MergedOnt = "MeshSnomedCT"; SM_Engine.firstPriority = true; findShareP.CSVtoArray(MergedOnt); res = ""; findShareP.CSVtoArray(MergedOnt); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineSNOMED == null) Coordinator.snomedLoader(); if (Coordinator.engineMeSH == null) Coordinator.meshLoader(); // ***********call combine engine URIFactory factorySnomed = URIFactoryMemory.getSingleton(); URIFactory factoryMesh = URIFactoryMemory.getSingleton(); URI snomedctURI = factorySnomed.getURI("http://snomedct/"); c1 = factorySnomed.getURI(snomedctURI.stringValue() + SetTerm1[i].trim()); c2 = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.meshGraph, Coordinator.snomedGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); snomedctURI = null; engine = null; c1 = null; c2 = null; factoryMesh = null; } break; case "SNOMEDCT-WordNet": res = ""; MergedOnt = "SnomedCTWordNet"; SM_Engine.firstPriority = false; findShareP.CSVtoArray(MergedOnt); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineSNOMED == null) Coordinator.snomedLoader(); if (Coordinator.engineWordNet == null) Coordinator.wordnetLoader(); // ***********call combine engine URIFactory factorySnomed = URIFactoryMemory.getSingleton(); URI snomedctURI = factorySnomed.getURI("http://snomedct/"); c1 = factorySnomed.getURI(snomedctURI.stringValue() + SetTerm1[i]); Set<URI> uris_Term2 = Coordinator.indexWordnetNoun.get(SetTerm2[i]); c2 = uris_Term2.iterator().next(); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.snomedGraph, Coordinator.wordnetGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); snomedctURI = null; engine = null; c1 = null; c2 = null; factory = null; } break; case "WordNet-MeSH": res = ""; MergedOnt = "MeshWordNet"; SM_Engine.firstPriority = false; findShareP.CSVtoArray(MergedOnt); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineWordNet == null) Coordinator.wordnetLoader(); if (Coordinator.engineMeSH == null) Coordinator.meshLoader(); // ***********call combine engine URIFactory factoryMesh = URIFactoryMemory.getSingleton(); Set<URI> uris_Term1 = Coordinator.indexWordnetNoun.get(SetTerm1[i]); c1 = uris_Term1.iterator().next(); c2 = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm2[i]); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.meshGraph, Coordinator.wordnetGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; engine = null; c1 = null; c2 = null; factoryMesh = null; } break; case "WordNet-SNOMEDCT": res = ""; MergedOnt = "SnomedCTWordNet"; SM_Engine.firstPriority = false; findShareP.CSVtoArray(MergedOnt); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineWordNet == null) Coordinator.wordnetLoader(); if (Coordinator.engineSNOMED == null) Coordinator.snomedLoader(); // ***********call combine engine URIFactory factorySnomed = URIFactoryMemory.getSingleton(); URI snomedctURI = factorySnomed.getURI("http://snomedct/"); Set<URI> uris_Term1 = Coordinator.indexWordnetNoun.get(SetTerm1[i]); c1 = uris_Term1.iterator().next(); c2 = factorySnomed.getURI(snomedctURI.stringValue() + SetTerm2[i]); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.snomedGraph, Coordinator.wordnetGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; snomedctURI = null; engine = null; c1 = null; c2 = null; factorySnomed = null; } break; case "Other": res = ""; MergedOnt = null; String ontname = ""; int a = Term1OntPath.indexOf("uploads"); ontname = Term1OntPath.substring(a + 8, Term1OntPath.length() - 4); String uriOnt = "http://" + ontname.toLowerCase(); for (int i = 0; i < SetTerm1.length; i++) { sim = 0; factory = URIFactoryMemory.getSingleton(); URI graphURI = factory.getURI(uriOnt + "/"); factory.loadNamespacePrefix("ONT", graphURI.toString()); G ontGraph = new GraphMemory(graphURI); GDataConf dataConf = new GDataConf(GFormat.RDF_XML, Term1OntPath); GAction actionRerootConf = new GAction(GActionType.REROOTING); GraphConf gConf = new GraphConf(); gConf.addGDataConf(dataConf); gConf.addGAction(actionRerootConf); GraphLoaderGeneric.load(gConf, ontGraph); Set<URI> roots = new ValidatorDAG().getTaxonomicRoots(ontGraph); // OntPath c1 = factory.getURI(uriOnt + "#" + SetTerm1[i].trim()); c2 = factory.getURI(uriOnt + "#" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(ontGraph); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); engine = null; factory = null; c1 = null; c2 = null; factory = null; ontGraph = null; } break; case "Other1-Other2": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; // *********** Other1********************************** String ontname1 = ""; int a1 = Term1OntPath.indexOf("uploads"); ontname1 = Term1OntPath.substring(a1 + 8, Term1OntPath.length() - 4); String uriOnt1 = "http://" + ontname1.toLowerCase(); URIFactory factoryont1 = URIFactoryMemory.getSingleton(); URI graphURI1 = factoryont1.getURI(uriOnt1 + "/"); factoryont1.loadNamespacePrefix("ONTA", graphURI1.toString()); G ont1Graph = new GraphMemory(graphURI1); GDataConf dataConf1 = new GDataConf(GFormat.RDF_XML, Term1OntPath); GAction actionRerootConf1 = new GAction(GActionType.REROOTING); GraphConf gConf1 = new GraphConf(); gConf1.addGDataConf(dataConf1); gConf1.addGAction(actionRerootConf1); GraphLoaderGeneric.load(gConf1, ont1Graph); Set<URI> roots1 = new ValidatorDAG().getTaxonomicRoots(ont1Graph); // **********Other2**************************************** String ontname2 = ""; int a2 = Term2OntPath.indexOf("uploads"); ontname2 = Term2OntPath.substring(a2 + 8, Term2OntPath.length() - 4); String uriOnt2 = "http://" + ontname2.toLowerCase(); URIFactory factoryont2 = URIFactoryMemory.getSingleton(); URI graphURI2 = factoryont2.getURI(uriOnt2 + "/"); factoryont2.loadNamespacePrefix("ONTB", graphURI2.toString()); G ont2Graph = new GraphMemory(graphURI2); GDataConf dataConf2 = new GDataConf(GFormat.RDF_XML, Term2OntPath); GAction actionRerootConf2 = new GAction(GActionType.REROOTING); GraphConf gConf2 = new GraphConf(); gConf2.addGDataConf(dataConf2); gConf2.addGAction(actionRerootConf2); GraphLoaderGeneric.load(gConf2, ont2Graph); Set<URI> roots2 = new ValidatorDAG().getTaxonomicRoots(ont2Graph); // **********combine**************************************** c1 = factoryont1.getURI(uriOnt1 + "#" + SetTerm1[i].trim()); c2 = factoryont2.getURI(uriOnt2 + "#" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, ont1Graph, ont2Graph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); ont1Graph = null; factoryont2 = null; ont2Graph = null; graphURI1 = null; graphURI2 = null; engine = null; c1 = null; c2 = null; factoryont1 = null; } break; case "MeSH-Other": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineMeSH == null) Coordinator.meshLoader(); // **********Other2**************************************** String ontname2 = ""; int a2 = Term2OntPath.indexOf("uploads"); ontname2 = Term2OntPath.substring(a2 + 8, Term2OntPath.length() - 4); String uriOnt2 = "http://" + ontname2.toLowerCase(); factory = URIFactoryMemory.getSingleton(); URI graphURI2 = factory.getURI(uriOnt2 + "/"); factory.loadNamespacePrefix("ONT", graphURI2.toString()); G ont2Graph = new GraphMemory(graphURI2); GDataConf dataConf2 = new GDataConf(GFormat.RDF_XML, Term2OntPath); GAction actionRerootConf2 = new GAction(GActionType.REROOTING); GraphConf gConf2 = new GraphConf(); gConf2.addGDataConf(dataConf2); gConf2.addGAction(actionRerootConf2); GraphLoaderGeneric.load(gConf2, ont2Graph); Set<URI> roots2 = new ValidatorDAG().getTaxonomicRoots(ont2Graph); // ***********call combine // engine********************************* URIFactory factoryMesh = URIFactoryMemory.getSingleton(); c1 = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm1[i].trim()); c2 = factory.getURI(uriOnt2 + "#" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.meshGraph, ont2Graph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); graphURI2 = null; factory = null; ont2Graph = null; engine = null; c1 = null; c2 = null; factoryMesh = null; } break; case "SNOMEDCT-Other": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineSNOMED == null) Coordinator.snomedLoader(); // **********Other2********************************* String ontname2 = ""; int a2 = Term2OntPath.indexOf("uploads"); ontname2 = Term2OntPath.substring(a2 + 8, Term2OntPath.length() - 4); String uriOnt2 = "http://" + ontname2.toLowerCase(); factory = URIFactoryMemory.getSingleton(); URI graphURI2 = factory.getURI(uriOnt2 + "/"); factory.loadNamespacePrefix("ONT", graphURI2.toString()); G ont2Graph = new GraphMemory(graphURI2); GDataConf dataConf2 = new GDataConf(GFormat.RDF_XML, Term2OntPath); GAction actionRerootConf2 = new GAction(GActionType.REROOTING); GraphConf gConf2 = new GraphConf(); gConf2.addGDataConf(dataConf2); gConf2.addGAction(actionRerootConf2); GraphLoaderGeneric.load(gConf2, ont2Graph); Set<URI> roots2 = new ValidatorDAG().getTaxonomicRoots(ont2Graph); // ***********call combine // engine********************************* URIFactory factorySnomed = URIFactoryMemory.getSingleton(); URI snomedctURI = factorySnomed.getURI("http://snomedct/"); c1 = factory.getURI(snomedctURI.stringValue() + SetTerm1[i].trim()); c2 = factory.getURI(uriOnt2 + "#" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.snomedGraph, ont2Graph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; graphURI2 = null; ont2Graph = null; snomedctURI = null; engine = null; c1 = null; c2 = null; factorySnomed = null; } break; case "WordNet-Other": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineWordNet == null) Coordinator.wordnetLoader(); // **********Other2********************************* String ontname2 = ""; int a2 = Term2OntPath.indexOf("uploads"); ontname2 = Term2OntPath.substring(a2 + 8, Term2OntPath.length() - 4); String uriOnt2 = "http://" + ontname2.toLowerCase(); factory = URIFactoryMemory.getSingleton(); URI graphURI2 = factory.getURI(uriOnt2 + "/"); factory.loadNamespacePrefix("ONT", graphURI2.toString()); G ont2Graph = new GraphMemory(graphURI2); GDataConf dataConf2 = new GDataConf(GFormat.RDF_XML, Term2OntPath); GAction actionRerootConf2 = new GAction(GActionType.REROOTING); GraphConf gConf2 = new GraphConf(); gConf2.addGDataConf(dataConf2); gConf2.addGAction(actionRerootConf2); GraphLoaderGeneric.load(gConf2, ont2Graph); Set<URI> roots2 = new ValidatorDAG().getTaxonomicRoots(ont2Graph); // ********Combine********************************* Set<URI> uris_Term1 = Coordinator.indexWordnetNoun.get(SetTerm2[i].trim()); c1 = uris_Term1.iterator().next(); c2 = factory.getURI(uriOnt2 + "#" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, Coordinator.wordnetGraph, ont2Graph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); graphURI2 = null; ont2Graph = null; engine = null; c1 = null; c2 = null; factory = null; } break; case "Other-MeSH": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineMeSH == null) Coordinator.meshLoader(); // *********** Other1********************************* String ontname1 = ""; int a1 = Term1OntPath.indexOf("uploads"); ontname1 = Term1OntPath.substring(a1 + 8, Term1OntPath.length() - 4); String uriOnt1 = "http://" + ontname1.toLowerCase(); factory = URIFactoryMemory.getSingleton(); URI graphURI1 = factory.getURI(uriOnt1 + "/"); factory.loadNamespacePrefix("ONT", graphURI1.toString()); G ont1Graph = new GraphMemory(graphURI1); GDataConf dataConf1 = new GDataConf(GFormat.RDF_XML, Term1OntPath); GAction actionRerootConf1 = new GAction(GActionType.REROOTING); GraphConf gConf1 = new GraphConf(); gConf1.addGDataConf(dataConf1); gConf1.addGAction(actionRerootConf1); GraphLoaderGeneric.load(gConf1, ont1Graph); Set<URI> roots1 = new ValidatorDAG().getTaxonomicRoots(ont1Graph); // ************MeSH*************************************** URIFactory factoryMesh = URIFactoryMemory.getSingleton(); URI meshURI = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/"); // ***********call combine engine********************* c1 = factory.getURI(uriOnt1 + "#" + SetTerm1[i].trim()); c2 = factoryMesh.getURI("http://www.nlm.nih.gov/mesh/" + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, ont1Graph, Coordinator.meshGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; graphURI1 = null; ont1Graph = null; meshURI = null; engine = null; c1 = null; c2 = null; factoryMesh = null; } break; case "Other-SNOMEDCT": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineSNOMED == null) Coordinator.snomedLoader(); // *********** Other1********************************* String ontname1 = ""; int a1 = Term1OntPath.indexOf("uploads"); ontname1 = Term1OntPath.substring(a1 + 8, Term1OntPath.length() - 4); String uriOnt1 = "http://" + ontname1.toLowerCase(); factory = URIFactoryMemory.getSingleton(); URI graphURI1 = factory.getURI(uriOnt1 + "/"); factory.loadNamespacePrefix("ONT", graphURI1.toString()); G ont1Graph = new GraphMemory(graphURI1); GDataConf dataConf1 = new GDataConf(GFormat.RDF_XML, Term1OntPath); GAction actionRerootConf1 = new GAction(GActionType.REROOTING); GraphConf gConf1 = new GraphConf(); gConf1.addGDataConf(dataConf1); gConf1.addGAction(actionRerootConf1); GraphLoaderGeneric.load(gConf1, ont1Graph); Set<URI> roots1 = new ValidatorDAG().getTaxonomicRoots(ont1Graph); // ***********SNOMED****************************************** URIFactory factorySnomed = URIFactoryMemory.getSingleton(); URI snomedctURI = factorySnomed.getURI("http://snomedct/"); // ***********call combine engine********************* c1 = factory.getURI(uriOnt1 + "#" + SetTerm1[i].trim()); c2 = factory.getURI(snomedctURI.stringValue() + SetTerm2[i].trim()); SM_Engine engine = new SM_Engine(c1, c2, ont1Graph, Coordinator.snomedGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; ont1Graph = null; graphURI1 = null; snomedctURI = null; engine = null; c1 = null; c2 = null; factorySnomed = null; } break; case "Other-WordNet": res = ""; MergedOnt = null; for (int i = 0; i < SetTerm1.length; i++) { sim = 0; if (Coordinator.engineWordNet == null) Coordinator.wordnetLoader(); // *********** Other1********************************* String ontname1 = ""; int a1 = Term1OntPath.indexOf("uploads"); ontname1 = Term1OntPath.substring(a1 + 8, Term1OntPath.length() - 4); String uriOnt1 = "http://" + ontname1.toLowerCase(); factory = URIFactoryMemory.getSingleton(); URI graphURI1 = factory.getURI(uriOnt1 + "/"); factory.loadNamespacePrefix("ONT", graphURI1.toString()); G ont1Graph = new GraphMemory(graphURI1); GDataConf dataConf1 = new GDataConf(GFormat.RDF_XML, Term1OntPath); GAction actionRerootConf1 = new GAction(GActionType.REROOTING); GraphConf gConf1 = new GraphConf(); gConf1.addGDataConf(dataConf1); gConf1.addGAction(actionRerootConf1); GraphLoaderGeneric.load(gConf1, ont1Graph); Set<URI> roots1 = new ValidatorDAG().getTaxonomicRoots(ont1Graph); // ****************Combine******************************* c1 = factory.getURI(uriOnt1 + "#" + SetTerm1[i].trim()); Set<URI> uris_Term2 = Coordinator.indexWordnetNoun.get(SetTerm2[i].trim()); c2 = uris_Term2.iterator().next(); SM_Engine engine = new SM_Engine(c1, c2, ont1Graph, Coordinator.wordnetGraph, MergedOnt); sim = engine.compare(measureConf, c1, c2, MergedOnt); res = String.valueOf(Math.round(sim * 10000.0) / 10000.0); factory = null; graphURI1 = null; ont1Graph = null; engine = null; c1 = null; c2 = null; } break; } SetTerm1 = null; SetTerm2 = null; icConf = null; measureConf = null; factory = null; icConf = null; } catch (SLIB_Exception ex) { Logger.getLogger(SimController.class.getName()).log(Level.SEVERE, null, ex); } return res; } public static String DetermineCase(String term1Source, String term2Source, String Term1OntPath, String Term2OntPath) { String state = "MeSH"; // default if (term1Source.equals("MeSH") && term2Source.equals("MeSH")) state = "MeSH"; else if (term1Source.equals("SNOMEDCT") && term2Source.equals("SNOMEDCT")) state = "SNOMEDCT"; else if (term1Source.equals("WordNet") && term2Source.equals("WordNet")) state = "WordNet"; else if (term1Source.equals("MeSH") && term2Source.equals("SNOMEDCT")) state = "MeSH-SNOMEDCT"; else if (term1Source.equals("MeSH") && term2Source.equals("WordNet")) state = "MeSH-WordNet"; else if (term1Source.equals("SNOMEDCT") && term2Source.equals("MeSH")) state = "SNOMEDCT-MeSH"; else if (term1Source.equals("SNOMEDCT") && term2Source.equals("WordNet")) state = "SNOMEDCT-WordNet"; else if (term1Source.equals("WordNet") && term2Source.equals("MeSH")) state = "WordNet-MeSH"; else if (term1Source.equals("WordNet") && term2Source.equals("SNOMEDCT")) state = "WordNet-SNOMEDCT"; else if (term1Source.equals("YourFile") && term2Source.equals("YourFile")) { if (Term1OntPath.equals(Term2OntPath)) state = "Other"; else state = "Other1-Other2"; } else if (term1Source.equals("MeSH") && term2Source.equals("YourFile")) state = "MeSH-Other"; else if (term1Source.equals("SNOMEDCT") && term2Source.equals("YourFile")) state = "SNOMEDCT-Other"; else if (term1Source.equals("WordNet") && term2Source.equals("YourFile")) state = "WordNet-Other"; else if (term1Source.equals("YourFile") && term2Source.equals("MeSH")) state = "Other-MeSH"; else if (term1Source.equals("YourFile") && term2Source.equals("SNOMEDCT")) state = "Other-SNOMEDCT"; else if (term1Source.equals("YourFile") && term2Source.equals("WordNet")) state = "Other-WordNet"; return state; } }
9236cc32c05da0a90c739b98cc25eaba301cf306
674
java
Java
src/test/java/com/litle/sdk/TestLitleRFRResponse.java
rezangit/litle-sdk-for-java
5a80be13eff13671b2a3638bc2db998193c2a740
[ "MIT" ]
9
2015-03-19T21:57:33.000Z
2017-03-20T11:17:22.000Z
src/test/java/com/litle/sdk/TestLitleRFRResponse.java
rezangit/litle-sdk-for-java
5a80be13eff13671b2a3638bc2db998193c2a740
[ "MIT" ]
13
2017-07-11T20:21:13.000Z
2022-01-13T19:52:33.000Z
src/test/java/com/litle/sdk/TestLitleRFRResponse.java
rezangit/litle-sdk-for-java
5a80be13eff13671b2a3638bc2db998193c2a740
[ "MIT" ]
19
2015-01-16T19:50:08.000Z
2017-01-17T16:31:58.000Z
24.962963
77
0.775964
997,828
package com.litle.sdk; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import com.litle.sdk.generate.RFRResponse; public class TestLitleRFRResponse { @Before public void before() throws Exception { } @Test public void testSetRFRResponse() throws Exception { RFRResponse rfrResponse = new RFRResponse(); rfrResponse.setMessage("Hurrdurrburrrrrr"); rfrResponse.setResponse("Nuh uh. :("); LitleRFRResponse litleRFRResponse = new LitleRFRResponse(rfrResponse); assertEquals("Nuh uh. :(", litleRFRResponse.getRFRResponseCode()); assertEquals("Hurrdurrburrrrrr", litleRFRResponse.getRFRResponseMessage()); } }
9236cc7a17a1e2750007eb3bb0d97450f42dd28e
338
java
Java
src/main/java/uk/gov/dvla/osl/eventsourcing/api/EventStoreWriter.java
dvla/eventstore-client
5c920f261d8a2ff787f68e87d7ebed4abd9464ee
[ "MIT" ]
1
2016-09-15T08:23:55.000Z
2016-09-15T08:23:55.000Z
src/main/java/uk/gov/dvla/osl/eventsourcing/api/EventStoreWriter.java
dvla/eventstore-client
5c920f261d8a2ff787f68e87d7ebed4abd9464ee
[ "MIT" ]
null
null
null
src/main/java/uk/gov/dvla/osl/eventsourcing/api/EventStoreWriter.java
dvla/eventstore-client
5c920f261d8a2ff787f68e87d7ebed4abd9464ee
[ "MIT" ]
1
2021-04-10T22:03:03.000Z
2021-04-10T22:03:03.000Z
30.727273
94
0.786982
997,829
package uk.gov.dvla.osl.eventsourcing.api; import java.util.List; import uk.gov.dvla.osl.eventsourcing.api.Event; public interface EventStoreWriter { void store(final String streamName, final long expectedVersion, final List<Event> events); void store(final String streamName, final long expectedVersion, final Event event); }
9236cd4d68b8c711bd36f9e731bc585c2b3db86b
321
java
Java
src/main/java/ch/uzh/ifi/seal/soprafs20/exceptions/api/put/PutException.java
Marinolino/sopra-fs20-group11-justone-server
c88673d0aba4223126dddc53b8848994f4e93bb7
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/uzh/ifi/seal/soprafs20/exceptions/api/put/PutException.java
Marinolino/sopra-fs20-group11-justone-server
c88673d0aba4223126dddc53b8848994f4e93bb7
[ "Apache-2.0" ]
null
null
null
src/main/java/ch/uzh/ifi/seal/soprafs20/exceptions/api/put/PutException.java
Marinolino/sopra-fs20-group11-justone-server
c88673d0aba4223126dddc53b8848994f4e93bb7
[ "Apache-2.0" ]
null
null
null
24.692308
63
0.775701
997,830
package ch.uzh.ifi.seal.soprafs20.exceptions.api.put; import ch.uzh.ifi.seal.soprafs20.exceptions.api.ApiException; import org.springframework.http.HttpStatus; public class PutException extends ApiException { public PutException(String message, HttpStatus statusCode){ super(message, statusCode); } }
9236cec88145df1ca779388648cd242809d0e931
17,895
java
Java
hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AttributesHelper.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
1
2021-11-11T01:36:23.000Z
2021-11-11T01:36:23.000Z
hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AttributesHelper.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
null
null
null
hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/boot/model/source/internal/hbm/AttributesHelper.java
lauracristinaes/aula-java
cb8d5b314b65a9914b93f3b5792bc98b548fe260
[ "Apache-2.0" ]
null
null
null
28.862903
109
0.758759
997,831
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.boot.model.source.internal.hbm; import java.util.Collections; import java.util.List; import javax.xml.bind.JAXBElement; import org.hibernate.boot.MappingException; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmAnyAssociationType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmArrayType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmBagCollectionType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmBasicAttributeType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmCompositeAttributeType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmCompositeKeyBasicAttributeType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmCompositeKeyManyToOneType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmDynamicComponentType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmIdBagCollectionType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmListType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmManyToOneType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmMapType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmNestedCompositeElementType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmOneToOneType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmPrimitiveArrayType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmPropertiesType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmSetType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmToolingHintType; import org.hibernate.boot.jaxb.hbm.spi.JaxbHbmTuplizerType; import org.hibernate.boot.model.source.spi.AttributePath; import org.hibernate.boot.model.source.spi.AttributeRole; import org.hibernate.boot.model.source.spi.AttributeSource; import org.hibernate.boot.model.source.spi.AttributeSourceContainer; import org.hibernate.boot.model.source.spi.EmbeddableMapping; import org.hibernate.boot.model.source.spi.EmbeddedAttributeMapping; import org.hibernate.boot.model.source.spi.NaturalIdMutability; import org.hibernate.boot.model.source.spi.SingularAttributeSourceEmbedded; import org.hibernate.boot.model.source.spi.ToolingHintContext; /** * @author Steve Ebersole */ public class AttributesHelper { public interface Callback { AttributeSourceContainer getAttributeSourceContainer(); void addAttributeSource(AttributeSource attributeSource); } public static void processAttributes( MappingDocument mappingDocument, Callback callback, List attributeMappings, String logicalTableName, NaturalIdMutability naturalIdMutability) { for ( Object rawAttributeMapping : attributeMappings ) { processAttribute( mappingDocument, callback, rawAttributeMapping, logicalTableName, naturalIdMutability ); } } private static void processAttribute( MappingDocument mappingDocument, Callback callback, Object attributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { if ( JAXBElement.class.isInstance( attributeJaxbMapping ) ) { processAttribute( mappingDocument, callback, ( (JAXBElement) attributeJaxbMapping ).getValue(), logicalTableName, naturalIdMutability ); } else if ( JaxbHbmCompositeKeyBasicAttributeType.class.isInstance( attributeJaxbMapping ) ) { callback.addAttributeSource( new CompositeIdentifierSingularAttributeSourceBasicImpl( mappingDocument, callback.getAttributeSourceContainer(), (JaxbHbmCompositeKeyBasicAttributeType) attributeJaxbMapping ) ); } else if ( JaxbHbmCompositeKeyManyToOneType.class.isInstance( attributeJaxbMapping ) ) { callback.addAttributeSource( new CompositeIdentifierSingularAttributeSourceManyToOneImpl( mappingDocument, callback.getAttributeSourceContainer(), (JaxbHbmCompositeKeyManyToOneType) attributeJaxbMapping ) ); } else if ( JaxbHbmPropertiesType.class.isInstance( attributeJaxbMapping ) ) { processPropertiesGroup( mappingDocument, callback, (JaxbHbmPropertiesType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmBasicAttributeType.class.isInstance( attributeJaxbMapping ) ) { processBasicAttribute( mappingDocument, callback, (JaxbHbmBasicAttributeType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmCompositeAttributeType.class.isInstance( attributeJaxbMapping ) ) { processEmbeddedAttribute( mappingDocument, callback, (JaxbHbmCompositeAttributeType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmDynamicComponentType.class.isInstance( attributeJaxbMapping ) ) { processDynamicComponentAttribute( mappingDocument, callback, (JaxbHbmDynamicComponentType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmManyToOneType.class.isInstance( attributeJaxbMapping ) ) { processManyToOneAttribute( mappingDocument, callback, (JaxbHbmManyToOneType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmOneToOneType.class.isInstance( attributeJaxbMapping ) ) { processOneToOneAttribute( mappingDocument, callback, (JaxbHbmOneToOneType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmAnyAssociationType.class.isInstance( attributeJaxbMapping ) ) { processAnyAttribute( mappingDocument, callback, (JaxbHbmAnyAssociationType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else if ( JaxbHbmMapType.class.isInstance( attributeJaxbMapping ) ) { processMapAttribute( mappingDocument, callback, (JaxbHbmMapType) attributeJaxbMapping ); } else if ( JaxbHbmListType.class.isInstance( attributeJaxbMapping ) ) { processListAttribute( mappingDocument, callback, (JaxbHbmListType) attributeJaxbMapping ); } else if ( JaxbHbmArrayType.class.isInstance( attributeJaxbMapping ) ) { processArrayAttribute( mappingDocument, callback, (JaxbHbmArrayType) attributeJaxbMapping ); } else if ( JaxbHbmPrimitiveArrayType.class.isInstance( attributeJaxbMapping ) ) { processPrimitiveArrayAttribute( mappingDocument, callback, (JaxbHbmPrimitiveArrayType) attributeJaxbMapping ); } else if ( JaxbHbmSetType.class.isInstance( attributeJaxbMapping ) ) { processSetAttribute( mappingDocument, callback, (JaxbHbmSetType) attributeJaxbMapping ); } else if ( JaxbHbmBagCollectionType.class.isInstance( attributeJaxbMapping ) ) { processBagAttribute( mappingDocument, callback, (JaxbHbmBagCollectionType) attributeJaxbMapping ); } else if ( JaxbHbmIdBagCollectionType.class.isInstance( attributeJaxbMapping ) ) { processIdBagAttribute( mappingDocument, callback, (JaxbHbmIdBagCollectionType) attributeJaxbMapping ); } else if ( JaxbHbmNestedCompositeElementType.class.isInstance( attributeJaxbMapping ) ) { processNestedEmbeddedElement( mappingDocument, callback, (JaxbHbmNestedCompositeElementType) attributeJaxbMapping, logicalTableName, naturalIdMutability ); } else { throw new MappingException( "Encountered unexpected JAXB mapping type for attribute : " + attributeJaxbMapping.getClass().getName(), mappingDocument.getOrigin() ); } } public static void processCompositeKeySubAttributes( MappingDocument mappingDocument, Callback callback, List<?> jaxbAttributeMappings) { for ( Object jaxbAttributeMapping : jaxbAttributeMappings ) { if ( JaxbHbmCompositeKeyBasicAttributeType.class.isInstance( jaxbAttributeMapping ) ) { callback.addAttributeSource( new CompositeIdentifierSingularAttributeSourceBasicImpl( mappingDocument, callback.getAttributeSourceContainer(), (JaxbHbmCompositeKeyBasicAttributeType) jaxbAttributeMapping ) ); } else if ( JaxbHbmCompositeKeyManyToOneType.class.isInstance( jaxbAttributeMapping ) ) { callback.addAttributeSource( new CompositeIdentifierSingularAttributeSourceManyToOneImpl( mappingDocument, callback.getAttributeSourceContainer(), (JaxbHbmCompositeKeyManyToOneType) jaxbAttributeMapping ) ); } else { throw new MappingException( "Unexpected composite-key sub-attribute type : " + jaxbAttributeMapping.getClass().getName(), mappingDocument.getOrigin() ); } } } private static void processPropertiesGroup( final MappingDocument mappingDocument, final Callback callback, final JaxbHbmPropertiesType propertiesGroupJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { final String name = propertiesGroupJaxbMapping.getName(); final AttributeRole attributeRole = callback.getAttributeSourceContainer() .getAttributeRoleBase() .append( name ); final AttributePath attributePath = callback.getAttributeSourceContainer() .getAttributePathBase() .append( name ); final EmbeddableSourceVirtualImpl embeddable = new EmbeddableSourceVirtualImpl( mappingDocument, callback, new EmbeddableSourceContainer() { @Override public AttributeRole getAttributeRoleBase() { return attributeRole; } @Override public AttributePath getAttributePathBase() { return attributePath; } @Override public ToolingHintContext getToolingHintContextBaselineForEmbeddable() { return callback.getAttributeSourceContainer().getToolingHintContext(); } }, propertiesGroupJaxbMapping.getAttributes(), logicalTableName, naturalIdMutability, propertiesGroupJaxbMapping ); // fake the JAXB mapping... final EmbeddableMapping embeddableMapping = new EmbeddableMapping() { @Override public String getClazz() { return null; } @Override public List<JaxbHbmTuplizerType> getTuplizer() { return Collections.emptyList(); } @Override public String getParent() { return null; } }; final EmbeddedAttributeMapping attributeMapping = new EmbeddedAttributeMapping() { @Override public boolean isUnique() { return propertiesGroupJaxbMapping.isUnique(); } @Override public EmbeddableMapping getEmbeddableMapping() { return embeddableMapping; } @Override public String getName() { return propertiesGroupJaxbMapping.getName(); } @Override public String getAccess() { return null; } @Override public List<JaxbHbmToolingHintType> getToolingHints() { return Collections.emptyList(); } }; // todo : make the virtual embedded attribute final SingularAttributeSourceEmbedded virtualAttribute = new AbstractSingularAttributeSourceEmbeddedImpl( mappingDocument, attributeMapping, embeddable, naturalIdMutability ) { @Override public boolean isVirtualAttribute() { return true; } @Override public Boolean isInsertable() { return propertiesGroupJaxbMapping.isInsert(); } @Override public Boolean isUpdatable() { return propertiesGroupJaxbMapping.isUpdate(); } @Override public boolean isBytecodeLazy() { return false; } @Override public XmlElementMetadata getSourceType() { return XmlElementMetadata.PROPERTIES; } @Override public String getXmlNodeName() { return null; } @Override public AttributePath getAttributePath() { return attributePath; } @Override public AttributeRole getAttributeRole() { return attributeRole; } @Override public boolean isIncludedInOptimisticLocking() { return false; } @Override public ToolingHintContext getToolingHintContext() { return mappingDocument.getToolingHintContext(); } }; callback.addAttributeSource( virtualAttribute ); } public static void processBasicAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmBasicAttributeType basicAttributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceBasicImpl( mappingDocument, callback.getAttributeSourceContainer(), basicAttributeJaxbMapping, logicalTableName, naturalIdMutability ) ); } public static void processEmbeddedAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmCompositeAttributeType embeddedAttributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceEmbeddedImpl( mappingDocument, callback.getAttributeSourceContainer(), embeddedAttributeJaxbMapping, naturalIdMutability, logicalTableName ) ); } private static void processNestedEmbeddedElement( MappingDocument mappingDocument, Callback callback, JaxbHbmNestedCompositeElementType attributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceEmbeddedImpl( mappingDocument, callback.getAttributeSourceContainer(), attributeJaxbMapping, naturalIdMutability, logicalTableName ) ); } public static void processDynamicComponentAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmDynamicComponentType dynamicComponentJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceEmbeddedImpl( mappingDocument, callback.getAttributeSourceContainer(), dynamicComponentJaxbMapping, naturalIdMutability, logicalTableName ) ); } public static void processManyToOneAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmManyToOneType manyToOneAttributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceManyToOneImpl( mappingDocument, callback.getAttributeSourceContainer(), manyToOneAttributeJaxbMapping, logicalTableName, naturalIdMutability ) ); } public static void processOneToOneAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmOneToOneType oneToOneAttributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceOneToOneImpl( mappingDocument, callback.getAttributeSourceContainer(), oneToOneAttributeJaxbMapping, logicalTableName, naturalIdMutability ) ); } public static void processAnyAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmAnyAssociationType anyAttributeJaxbMapping, String logicalTableName, NaturalIdMutability naturalIdMutability) { callback.addAttributeSource( new SingularAttributeSourceAnyImpl( mappingDocument, callback.getAttributeSourceContainer(), anyAttributeJaxbMapping, logicalTableName, naturalIdMutability ) ); } public static void processMapAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmMapType mapAttributesJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourceMapImpl( mappingDocument, mapAttributesJaxbMapping, callback.getAttributeSourceContainer() ) ); } public static void processListAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmListType listAttributeJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourceListImpl( mappingDocument, listAttributeJaxbMapping, callback.getAttributeSourceContainer() ) ); } public static void processArrayAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmArrayType arrayAttributeJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourceArrayImpl( mappingDocument, arrayAttributeJaxbMapping, callback.getAttributeSourceContainer() ) ); } public static void processPrimitiveArrayAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmPrimitiveArrayType primitiveArrayAttributeJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourcePrimitiveArrayImpl( mappingDocument, primitiveArrayAttributeJaxbMapping, callback.getAttributeSourceContainer() ) ); } public static void processSetAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmSetType setAttributeJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourceSetImpl( mappingDocument, setAttributeJaxbMapping, callback.getAttributeSourceContainer() ) ); } public static void processBagAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmBagCollectionType bagAttributeJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourceBagImpl( mappingDocument, bagAttributeJaxbMapping, callback.getAttributeSourceContainer() ) ); } public static void processIdBagAttribute( MappingDocument mappingDocument, Callback callback, JaxbHbmIdBagCollectionType idBagAttributeJaxbMapping) { callback.addAttributeSource( new PluralAttributeSourceIdBagImpl( mappingDocument, idBagAttributeJaxbMapping, callback.getAttributeSourceContainer() ) ); } }
9236cf30bce6e05162ae3e0ca3177837c5714a6a
7,901
java
Java
azure-samples/src/main/java/com/microsoft/azure/management/appservice/samples/ManageLinuxFunctionAppSourceControl.java
majacQ/azure-libraries-for-java
dadaa830231c75bf294657ba7dce49c22d29a966
[ "MIT" ]
100
2017-11-10T02:19:58.000Z
2022-03-27T10:24:07.000Z
azure-samples/src/main/java/com/microsoft/azure/management/appservice/samples/ManageLinuxFunctionAppSourceControl.java
majacQ/azure-libraries-for-java
dadaa830231c75bf294657ba7dce49c22d29a966
[ "MIT" ]
657
2017-10-24T16:39:52.000Z
2022-03-31T03:12:57.000Z
azure-samples/src/main/java/com/microsoft/azure/management/appservice/samples/ManageLinuxFunctionAppSourceControl.java
majacQ/azure-libraries-for-java
dadaa830231c75bf294657ba7dce49c22d29a966
[ "MIT" ]
122
2017-10-23T23:14:15.000Z
2021-12-22T08:27:13.000Z
42.251337
182
0.594482
997,832
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. */ package com.microsoft.azure.management.appservice.samples; import com.microsoft.azure.management.Azure; import com.microsoft.azure.management.appservice.FunctionApp; import com.microsoft.azure.management.appservice.FunctionRuntimeStack; import com.microsoft.azure.management.appservice.PricingTier; import com.microsoft.azure.management.resources.fluentcore.arm.Region; import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext; import com.microsoft.azure.management.samples.Utils; import com.microsoft.azure.management.storage.StorageAccountSkuType; import com.microsoft.rest.LogLevel; import okhttp3.OkHttpClient; import okhttp3.Request; import org.apache.commons.lang3.time.StopWatch; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * Azure App Service basic sample for managing function apps. * - Create 2 linux function apps. * - Deploy 1 under new dedicated app service plan, run from a package. * - Deploy 1 under new consumption plan, run from a package. */ public class ManageLinuxFunctionAppSourceControl { private static OkHttpClient httpClient; private static final String FUNCTION_APP_PACKAGE_URL = "https://raw.github.com/Azure/azure-libraries-for-java/master/azure-mgmt-appservice/src/test/resources/java-functions.zip"; private static final long TIMEOUT_IN_SECONDS = 5 * 60; /** * Main function which runs the actual sample. * @param azure instance of the azure client * @return true if sample runs successfully */ public static boolean runSample(Azure azure) { final String suffix = ".azurewebsites.net"; final String app1Name = SdkContext.randomResourceName("webapp1-", 20); final String app2Name = SdkContext.randomResourceName("webapp2-", 20); final String app1Url = app1Name + suffix; final String app2Url = app2Name + suffix; final String plan1Name = SdkContext.randomResourceName("plan1-", 20); final String plan2Name = SdkContext.randomResourceName("plan2-", 20); final String storage1Name = SdkContext.randomResourceName("storage1", 20); final String rgName = SdkContext.randomResourceName("rg1NEMV_", 24); try { //============================================================ // Create a function app with a new dedicated app service plan, configure as run from a package System.out.println("Creating function app " + app1Name + " in resource group " + rgName + "..."); FunctionApp app1 = azure.appServices().functionApps().define(app1Name) .withRegion(Region.US_WEST) .withNewResourceGroup(rgName) .withNewLinuxAppServicePlan(plan1Name, PricingTier.STANDARD_S1) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withNewStorageAccount(storage1Name, StorageAccountSkuType.STANDARD_LRS) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); System.out.println("Created function app " + app1.name()); Utils.print(app1); // warm up String app1UrlFunction = app1Url + "/api/HttpTrigger-Java?name=linux_function_app1"; System.out.println("Warming up " + app1UrlFunction + "..."); StopWatch stopWatch = StopWatch.createStarted(); while (stopWatch.getTime() < TIMEOUT_IN_SECONDS * 1000) { String response = get("https://" + app1UrlFunction); if (response != null && response.contains("Hello")) { break; } SdkContext.sleep(10 * 1000); } // call function System.out.println("CURLing " + app1UrlFunction + "..."); System.out.println("Response is " + get("https://" + app1UrlFunction)); // response would be "Hello, ..." //============================================================ // Create a function app with a new consumption plan, configure as run from a package System.out.println("Creating function app " + app2Name + " in resource group " + rgName + "..."); FunctionApp app2 = azure.appServices().functionApps().define(app2Name) .withRegion(Region.US_EAST) .withExistingResourceGroup(rgName) .withNewLinuxConsumptionPlan(plan2Name) .withBuiltInImage(FunctionRuntimeStack.JAVA_8) .withExistingStorageAccount(azure.storageAccounts().getByResourceGroup(rgName, storage1Name)) .withHttpsOnly(true) .withAppSetting("WEBSITE_RUN_FROM_PACKAGE", FUNCTION_APP_PACKAGE_URL) .create(); System.out.println("Created function app " + app2.name()); Utils.print(app2); // warm up String app2UrlFunction = app2Url + "/api/HttpTrigger-Java?name=linux_function_app2"; System.out.println("Warming up " + app2UrlFunction + "..."); stopWatch = StopWatch.createStarted(); while (stopWatch.getTime() < TIMEOUT_IN_SECONDS * 1000) { String response = get("https://" + app2UrlFunction); if (response != null && response.contains("Hello")) { break; } SdkContext.sleep(10 * 1000); } // call function System.out.println("CURLing " + app2UrlFunction + "..."); System.out.println("Response is " + get("https://" + app2UrlFunction)); // response would be "Hello, ..." return true; } catch (Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } finally { try { System.out.println("Deleting Resource Group: " + rgName); azure.resourceGroups().beginDeleteByName(rgName); System.out.println("Deleted Resource Group: " + rgName); } catch (NullPointerException npe) { System.out.println("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception g) { g.printStackTrace(); } } return false; } /** * Main entry point. * @param args the parameters */ public static void main(String[] args) { try { //============================================================= // Authenticate final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION")); Azure azure = Azure .configure() .withLogLevel(LogLevel.BODY_AND_HEADERS) .authenticate(credFile) .withDefaultSubscription(); // Print selected subscription System.out.println("Selected subscription: " + azure.subscriptionId()); runSample(azure); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } } private static String get(String url) { Request request = new Request.Builder().url(url).get().build(); try { return httpClient.newCall(request).execute().body().string(); } catch (IOException e) { return null; } } static { httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build(); } }
9236cf9478023be46ad7456f15ad98234e2f69b6
2,137
java
Java
org/apache/commons/collections/bag/TransformedSortedBag.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
2
2021-07-16T10:43:25.000Z
2021-12-15T13:54:10.000Z
org/apache/commons/collections/bag/TransformedSortedBag.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
1
2021-10-12T22:24:55.000Z
2021-10-12T22:24:55.000Z
org/apache/commons/collections/bag/TransformedSortedBag.java
MewX/contendo-viewer-v1.6.3
69fba3cea4f9a43e48f43148774cfa61b388e7de
[ "Apache-2.0" ]
null
null
null
21.158416
114
0.43285
997,833
/* */ package org.apache.commons.collections.bag; /* */ /* */ import java.util.Comparator; /* */ import org.apache.commons.collections.Bag; /* */ import org.apache.commons.collections.SortedBag; /* */ import org.apache.commons.collections.Transformer; /* */ import org.apache.commons.collections.collection.AbstractCollectionDecorator; /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ public class TransformedSortedBag /* */ extends TransformedBag /* */ implements SortedBag /* */ { /* */ private static final long serialVersionUID = -251737742649401930L; /* */ /* */ public static SortedBag decorate(SortedBag bag, Transformer transformer) { /* 56 */ return new TransformedSortedBag(bag, transformer); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected TransformedSortedBag(SortedBag bag, Transformer transformer) { /* 71 */ super((Bag)bag, transformer); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ /* */ protected SortedBag getSortedBag() { /* 80 */ return (SortedBag)((AbstractCollectionDecorator)this).collection; /* */ } /* */ /* */ /* */ public Object first() { /* 85 */ return getSortedBag().first(); /* */ } /* */ /* */ public Object last() { /* 89 */ return getSortedBag().last(); /* */ } /* */ /* */ public Comparator comparator() { /* 93 */ return getSortedBag().comparator(); /* */ } /* */ } /* Location: /mnt/r/ConTenDoViewer.jar!/org/apache/commons/collections/bag/TransformedSortedBag.class * Java compiler version: 1 (45.3) * JD-Core Version: 1.1.3 */
9236cfbebca54068452f66b0c10541108e4e7216
653
java
Java
src/main/java/br/com/supera/game/store/repository/ProdutoRepository.java
Matheusrp08/testesupera
6d5b61f4dd34e955adda7b6a17c2e150a219ae82
[ "MIT" ]
null
null
null
src/main/java/br/com/supera/game/store/repository/ProdutoRepository.java
Matheusrp08/testesupera
6d5b61f4dd34e955adda7b6a17c2e150a219ae82
[ "MIT" ]
null
null
null
src/main/java/br/com/supera/game/store/repository/ProdutoRepository.java
Matheusrp08/testesupera
6d5b61f4dd34e955adda7b6a17c2e150a219ae82
[ "MIT" ]
null
null
null
29.681818
81
0.770291
997,834
package br.com.supera.game.store.repository; import br.com.supera.game.store.model.Produto; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import java.util.List; import java.util.Optional; public interface ProdutoRepository extends CrudRepository<Produto, Long> { @Override @Query("SELECT p FROM Produto p WHERE p.dataExclusao IS NULL AND p.id = :id") Optional<Produto> findById(@Param("id") Long id); @Query("SELECT p FROM Produto p WHERE p.dataExclusao IS NULL") List<Produto> buscarTodosProdutos(); }
9236d025bd7cb9ab8e7f0648c6790cdcddfb3bf3
12,202
java
Java
plugins/au.gov.ga.earthsci.worldwind/src/au/gov/ga/earthsci/worldwind/common/layers/curtain/Path.java
rooby/earthsci
e134d08d4501006cb8c6b8f47f1016510d0f52be
[ "Apache-2.0" ]
45
2015-01-28T17:20:47.000Z
2022-02-03T13:08:14.000Z
plugins/au.gov.ga.earthsci.worldwind/src/au/gov/ga/earthsci/worldwind/common/layers/curtain/Path.java
rooby/earthsci
e134d08d4501006cb8c6b8f47f1016510d0f52be
[ "Apache-2.0" ]
28
2015-01-08T23:52:21.000Z
2018-10-24T02:04:48.000Z
plugins/au.gov.ga.earthsci.worldwind/src/au/gov/ga/earthsci/worldwind/common/layers/curtain/Path.java
rooby/earthsci
e134d08d4501006cb8c6b8f47f1016510d0f52be
[ "Apache-2.0" ]
29
2015-01-28T17:21:05.000Z
2022-03-30T06:23:38.000Z
31.466495
131
0.709722
997,835
/******************************************************************************* * Copyright 2012 Geoscience Australia * * 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 au.gov.ga.earthsci.worldwind.common.layers.curtain; import static au.gov.ga.earthsci.worldwind.common.util.Util.isEmpty; import gov.nasa.worldwind.Configuration; import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.cache.BasicMemoryCache; import gov.nasa.worldwind.cache.MemoryCache; import gov.nasa.worldwind.geom.Angle; import gov.nasa.worldwind.geom.Box; import gov.nasa.worldwind.geom.Extent; import gov.nasa.worldwind.geom.LatLon; import gov.nasa.worldwind.geom.Sector; import gov.nasa.worldwind.geom.Vec4; import gov.nasa.worldwind.globes.Globe; import gov.nasa.worldwind.render.DrawContext; import gov.nasa.worldwind.util.TileKey; import java.nio.FloatBuffer; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.TreeMap; import com.jogamp.common.nio.Buffers; /** * Defines a path consisting of lat/lon coordinates. Contains functionality for * generating vertex geometry for segments within the path. * * @author Michael de Hoog (lyhxr@example.com) */ public class Path { protected final NavigableMap<Double, LatLon> positions = new TreeMap<Double, LatLon>(); protected Angle length; protected static final String CACHE_NAME = "CurtainPath"; protected static final String CACHE_ID = Path.class.getName(); protected long updateFrequency = 2000; // milliseconds protected long exaggerationChangeTime = -1; protected double lastVerticalExaggeration = -Double.MAX_VALUE; public Path(List<LatLon> positions) { if (!WorldWind.getMemoryCacheSet().containsCache(CACHE_ID)) { long size = Configuration.getLongValue(AVKey.SECTOR_GEOMETRY_CACHE_SIZE, 10000000L); MemoryCache cache = new BasicMemoryCache((long) (0.85 * size), size); cache.setName(CACHE_NAME); WorldWind.getMemoryCacheSet().addCache(CACHE_ID, cache); } setPositions(positions); } /* * Private; should only be called by constructor, as vertices are cached. */ private synchronized void setPositions(List<LatLon> positions) { this.positions.clear(); double[] distances = new double[positions.size()]; //last array value is unused, but required for simple second loop //calculate total distance double total = 0d; //in radians for (int i = 0; i < positions.size() - 1; i++) { Angle distance = LatLon.greatCircleDistance(positions.get(i), positions.get(i + 1)); distances[i] = distance.radians; total += distance.radians; } this.length = Angle.fromRadians(total); //calculate percent positions double sum = 0d; for (int i = 0; i < positions.size(); i++) { this.positions.put(sum / total, positions.get(i)); sum += distances[i]; } } /** * @return The length of the path, expressed as an angle. */ public synchronized Angle getLength() { return length; } /** * @return Time between updates to vertices, in milliseconds */ public long getUpdateFrequency() { return updateFrequency; } /** * Set the amount of time between vertex updates, in milliseconds * * @param updateFrequency */ public void setUpdateFrequency(long updateFrequency) { this.updateFrequency = updateFrequency; } /** * @param percent * The percentage expressed as a decimal (e.g. 50% == 0.5) * * @return The {@link LatLon} location that lies <code>percent</code>% of * the way along the path */ public synchronized LatLon getPercentLatLon(double percent) { if (percent <= 0) { return positions.firstEntry().getValue(); } if (percent >= 1) { return positions.lastEntry().getValue(); } if (positions.containsKey(percent)) { return positions.get(percent); } Entry<Double, LatLon> lower = positions.lowerEntry(percent); Entry<Double, LatLon> higher = positions.higherEntry(percent); double p = (percent - lower.getKey()) / (higher.getKey() - lower.getKey()); //TODO add different interpolation methods return LatLon.interpolateGreatCircle(p, lower.getValue(), higher.getValue()); } public synchronized Vec4 getSegmentCenterPoint(DrawContext dc, Segment segment, double top, double bottom, boolean followTerrain) { top *= dc.getVerticalExaggeration(); bottom *= dc.getVerticalExaggeration(); double height = top - bottom; double e = top - segment.getVerticalCenter() * height; LatLon ll = getPercentLatLon(segment.getHorizontalCenter()); if (followTerrain) { e += dc.getGlobe().getElevation(ll.latitude, ll.longitude) * dc.getVerticalExaggeration(); } return dc.getGlobe().computePointFromPosition(ll, e); } public synchronized SegmentGeometry getGeometry(DrawContext dc, CurtainTile tile, double top, double bottom, int subsegments, boolean followTerrain) { if (lastVerticalExaggeration != dc.getVerticalExaggeration()) { exaggerationChangeTime = System.currentTimeMillis(); lastVerticalExaggeration = dc.getVerticalExaggeration(); } MemoryCache cache = WorldWind.getMemoryCache(CACHE_ID); TileKey tileKey = tile.getTileKey(); SegmentGeometry geometry = (SegmentGeometry) cache.getObject(tileKey); if (geometry != null && geometry.getTime() >= System.currentTimeMillis() - this.getUpdateFrequency() && geometry.getTime() >= exaggerationChangeTime) { return geometry; } Segment segment = tile.getSegment(); NavigableMap<Double, LatLon> betweenMap = segmentMap(segment, subsegments); int numVertices = betweenMap.size() * 2; Globe globe = dc.getGlobe(); FloatBuffer verts, texCoords; if (geometry != null) { verts = geometry.getVertices(); texCoords = geometry.getTexCoords(); } else if (dc.getGLRuntimeCapabilities().isUseVertexBufferObject()) { verts = FloatBuffer.allocate(numVertices * 3); texCoords = FloatBuffer.allocate(numVertices * 2); } else { verts = Buffers.newDirectFloatBuffer(numVertices * 3); texCoords = Buffers.newDirectFloatBuffer(numVertices * 2); } Vec4 refCenter = getSegmentCenterPoint(dc, segment, top, bottom, followTerrain); //calculate exaggerated segment top/bottom elevations top *= dc.getVerticalExaggeration(); bottom *= dc.getVerticalExaggeration(); double height = top - bottom; double t = top - segment.getTop() * height; double b = top - segment.getBottom() * height; //ensure t is greater than b (this can occur if exaggeration is 0) if (t <= b) { t = b + 1; } double percentDistance = segment.getHorizontalDelta(); for (Entry<Double, LatLon> entry : betweenMap.entrySet()) { LatLon ll = entry.getValue(); double e = 0; if (followTerrain) { e = globe.getElevation(ll.latitude, ll.longitude) * dc.getVerticalExaggeration(); } Vec4 point1 = globe.computePointFromPosition(ll, t + e); Vec4 point2 = globe.computePointFromPosition(ll, b + e); double percent = (entry.getKey() - segment.getStart()) / percentDistance; verts.put((float) (point1.x - refCenter.x)).put((float) (point1.y - refCenter.y)) .put((float) (point1.z - refCenter.z)); verts.put((float) (point2.x - refCenter.x)).put((float) (point2.y - refCenter.y)) .put((float) (point2.z - refCenter.z)); texCoords.put((float) percent).put(1f); texCoords.put((float) percent).put(0f); } if (geometry == null) { geometry = new SegmentGeometry(dc, verts, texCoords, refCenter); cache.add(tileKey, geometry, geometry.getSizeInBytes()); } else { geometry.update(dc, refCenter); } return geometry; } public synchronized Vec4[] getPointsInSegment(DrawContext dc, Segment segment, double top, double bottom, int subsegments, boolean followTerrain) { //TODO ?? cache value returned from this method, and if called twice with same input parameters, return cached value ?? //TODO create a new function to return some object with a vertex buffer and texture buffer instead of just a Vec4[] array NavigableMap<Double, LatLon> betweenMap = segmentMap(segment, subsegments); Globe globe = dc.getGlobe(); Vec4[] points = new Vec4[betweenMap.size() * 2]; //calculate exaggerated segment top/bottom elevations top *= dc.getVerticalExaggeration(); bottom *= dc.getVerticalExaggeration(); double height = top - bottom; double t = top - segment.getTop() * height; double b = top - segment.getBottom() * height; //add top points, and add bottom points (add them backwards, so it's a loop) int j = 0, k = betweenMap.size() * 2; for (LatLon ll : betweenMap.values()) { double e = 0; if (followTerrain) { // Note: The elevation model has already applied vertical exaggeration in the case of the VerticalExaggerationElevationModel... e = globe.getElevation(ll.latitude, ll.longitude) * dc.getVerticalExaggeration(); } points[j++] = globe.computePointFromPosition(ll, t + e); points[--k] = globe.computePointFromPosition(ll, b + e); } return points; } protected NavigableMap<Double, LatLon> segmentMap(Segment segment, int subsegments) { LatLon start = getPercentLatLon(segment.getStart()); LatLon end = getPercentLatLon(segment.getEnd()); NavigableMap<Double, LatLon> betweenMap = new TreeMap<Double, LatLon>(); //get a sublist of all the points between start and end (non-inclusive) betweenMap.putAll(positions.subMap(segment.getStart(), false, segment.getEnd(), false)); //add the start and end points betweenMap.put(segment.getStart(), start); betweenMap.put(segment.getEnd(), end); //insert any subsegment points for (int i = 0; i < subsegments - 1; i++) { double subsegment = (i + 1) / (double) subsegments; double percent = segment.getStart() + subsegment * segment.getHorizontalDelta(); LatLon pos = getPercentLatLon(percent); betweenMap.put(percent, pos); } return betweenMap; } public synchronized Extent getSegmentExtent(DrawContext dc, Segment segment, double top, double bottom, int subsegments, boolean followTerrain) { Vec4[] points = getPointsInSegment(dc, segment, top, bottom, subsegments, followTerrain); return Box.computeBoundingBox(Arrays.asList(points)); } public synchronized Angle getSegmentLength(Segment segment) { return Angle.fromRadians(getSegmentLengthInRadians(segment)); } public synchronized double getSegmentLengthInRadians(Segment segment) { return segment.getHorizontalDelta() * length.radians; } public synchronized Angle getPercentLength(double percent) { return Angle.fromRadians(getPercentLengthInRadians(percent)); } public synchronized double getPercentLengthInRadians(double percent) { return length.radians * percent; } /** * @return The sector that bounds the path */ public synchronized Sector getBoundingSector() { if (isEmpty(positions)) { return null; } Angle minLat = Angle.fromDegrees(360); Angle minLon = Angle.fromDegrees(360); Angle maxLat = Angle.fromDegrees(-360); Angle maxLon = Angle.fromDegrees(-360); for (LatLon pathPosition : positions.values()) { if (pathPosition.getLatitude().compareTo(minLat) < 0) { minLat = pathPosition.getLatitude(); } if (pathPosition.getLatitude().compareTo(maxLat) > 0) { maxLat = pathPosition.getLatitude(); } if (pathPosition.getLongitude().compareTo(minLon) < 0) { minLon = pathPosition.getLongitude(); } if (pathPosition.getLongitude().compareTo(maxLon) > 0) { maxLon = pathPosition.getLongitude(); } } return new Sector(minLat, maxLat, minLon, maxLon); } }
9236d089b52506065d919d0ddbaabb3ba25468bc
4,143
java
Java
src/main/java/com/vtapadia/fifa/config/DatabaseConfig.java
vtapadia/eFifa
666762f6dfe2fdaae503f4bfc33564c6a526d6c4
[ "MIT" ]
1
2018-08-12T10:42:48.000Z
2018-08-12T10:42:48.000Z
src/main/java/com/vtapadia/fifa/config/DatabaseConfig.java
vtapadia/eFifa
666762f6dfe2fdaae503f4bfc33564c6a526d6c4
[ "MIT" ]
null
null
null
src/main/java/com/vtapadia/fifa/config/DatabaseConfig.java
vtapadia/eFifa
666762f6dfe2fdaae503f4bfc33564c6a526d6c4
[ "MIT" ]
null
null
null
35.715517
130
0.695873
997,836
package com.vtapadia.fifa.config; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.hibernate4.HibernateTransactionManager; import org.springframework.orm.hibernate4.LocalSessionFactoryBean; import org.springframework.orm.jpa.JpaVendorAdapter; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.Database; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; import javax.persistence.EntityManager; import javax.sql.DataSource; import java.util.Properties; @Configuration @EnableTransactionManagement public class DatabaseConfig { @Value("${eFifa.db:postgresql}") String database; @Value("${eFifa.db.url}") String databaseUrl; @Value("${eFifa.db.username}") String databaseUsername; @Value("${eFifa.db.password}") String databasePassword; @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); switch (database) { case "oracle": dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver"); break; case "postgresql": default: dataSource.setDriverClassName("org.postgresql.Driver"); break; } dataSource.setUrl(databaseUrl); dataSource.setUsername(databaseUsername); dataSource.setPassword(databasePassword); return dataSource; } @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setPackagesToScan("com.vtapadia.fifa.domain"); sessionFactoryBean.setHibernateProperties(hibernateProperties()); return sessionFactoryBean; } @Bean public JpaVendorAdapter jpaVendorAdapter() { HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter(); switch (database) { case "oracle": adapter.setDatabase(Database.ORACLE); break; case "postgresql": default: adapter.setDatabase(Database.POSTGRESQL); //break; } adapter.setShowSql(false); adapter.setGenerateDdl(false); return adapter; } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, JpaVendorAdapter jpaVendorAdapter) { LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean(); lef.setDataSource(dataSource); lef.setJpaVendorAdapter(jpaVendorAdapter); lef.setPackagesToScan("com.vtapadia.fifa.domain"); return lef; } @Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; } @Bean public EntityManager entityManager() { return entityManagerFactory(dataSource(),jpaVendorAdapter()).getObject().createEntityManager(); } public Properties hibernateProperties() { Properties prop = new Properties(); switch (database) { case "oracle": prop.setProperty("hibernate.dialect","org.hibernate.dialect.Oracle10gDialect"); break; case "postgresql": default: prop.setProperty("hibernate.dialect","org.hibernate.dialect.PostgreSQL9Dialect"); break; } prop.setProperty("hibernate.show_sql","false"); prop.setProperty("hibernate.hbm2ddl.auto","validate"); return prop; } }
9236d141bcfcc28c7801a0a95401a7f92cbf8a90
11,554
java
Java
test/javasource/testmodule/proxies/Item.java
Itvisors/mendix-TaskBoard
c5b5612a2ff68aff286346204b24ebf67d53efd9
[ "Apache-2.0" ]
null
null
null
test/javasource/testmodule/proxies/Item.java
Itvisors/mendix-TaskBoard
c5b5612a2ff68aff286346204b24ebf67d53efd9
[ "Apache-2.0" ]
null
null
null
test/javasource/testmodule/proxies/Item.java
Itvisors/mendix-TaskBoard
c5b5612a2ff68aff286346204b24ebf67d53efd9
[ "Apache-2.0" ]
null
null
null
28.388206
214
0.743639
997,837
// This file was generated by Mendix Studio Pro. // // WARNING: Code you write here will be lost the next time you deploy the project. package testmodule.proxies; public class Item { private final com.mendix.systemwideinterfaces.core.IMendixObject itemMendixObject; private final com.mendix.systemwideinterfaces.core.IContext context; /** * Internal name of this entity */ public static final java.lang.String entityName = "TestModule.Item"; /** * Enum describing members of this entity */ public enum MemberNames { ItemId("ItemId"), SeqNbr("SeqNbr"), Name("Name"), IsDragDisabled("IsDragDisabled"), Item_TaskBoard("TestModule.Item_TaskBoard"), Item_Column("TestModule.Item_Column"); private java.lang.String metaName; MemberNames(java.lang.String s) { metaName = s; } @java.lang.Override public java.lang.String toString() { return metaName; } } public Item(com.mendix.systemwideinterfaces.core.IContext context) { this(context, com.mendix.core.Core.instantiate(context, "TestModule.Item")); } protected Item(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject itemMendixObject) { if (itemMendixObject == null) throw new java.lang.IllegalArgumentException("The given object cannot be null."); if (!com.mendix.core.Core.isSubClassOf("TestModule.Item", itemMendixObject.getType())) throw new java.lang.IllegalArgumentException("The given object is not a TestModule.Item"); this.itemMendixObject = itemMendixObject; this.context = context; } /** * @deprecated Use 'Item.load(IContext, IMendixIdentifier)' instead. */ @java.lang.Deprecated public static testmodule.proxies.Item initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException { return testmodule.proxies.Item.load(context, mendixIdentifier); } /** * Initialize a proxy using context (recommended). This context will be used for security checking when the get- and set-methods without context parameters are called. * The get- and set-methods with context parameter should be used when for instance sudo access is necessary (IContext.createSudoClone() can be used to obtain sudo access). */ public static testmodule.proxies.Item initialize(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixObject mendixObject) { return new testmodule.proxies.Item(context, mendixObject); } public static testmodule.proxies.Item load(com.mendix.systemwideinterfaces.core.IContext context, com.mendix.systemwideinterfaces.core.IMendixIdentifier mendixIdentifier) throws com.mendix.core.CoreException { com.mendix.systemwideinterfaces.core.IMendixObject mendixObject = com.mendix.core.Core.retrieveId(context, mendixIdentifier); return testmodule.proxies.Item.initialize(context, mendixObject); } public static java.util.List<testmodule.proxies.Item> load(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String xpathConstraint) throws com.mendix.core.CoreException { java.util.List<testmodule.proxies.Item> result = new java.util.ArrayList<testmodule.proxies.Item>(); for (com.mendix.systemwideinterfaces.core.IMendixObject obj : com.mendix.core.Core.retrieveXPathQuery(context, "//TestModule.Item" + xpathConstraint)) result.add(testmodule.proxies.Item.initialize(context, obj)); return result; } /** * Commit the changes made on this proxy object. */ public final void commit() throws com.mendix.core.CoreException { com.mendix.core.Core.commit(context, getMendixObject()); } /** * Commit the changes made on this proxy object using the specified context. */ public final void commit(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException { com.mendix.core.Core.commit(context, getMendixObject()); } /** * Delete the object. */ public final void delete() { com.mendix.core.Core.delete(context, getMendixObject()); } /** * Delete the object using the specified context. */ public final void delete(com.mendix.systemwideinterfaces.core.IContext context) { com.mendix.core.Core.delete(context, getMendixObject()); } /** * @return value of ItemId */ public final java.lang.Long getItemId() { return getItemId(getContext()); } /** * @param context * @return value of ItemId */ public final java.lang.Long getItemId(com.mendix.systemwideinterfaces.core.IContext context) { return (java.lang.Long) getMendixObject().getValue(context, MemberNames.ItemId.toString()); } /** * Set value of ItemId * @param itemid */ public final void setItemId(java.lang.Long itemid) { setItemId(getContext(), itemid); } /** * Set value of ItemId * @param context * @param itemid */ public final void setItemId(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Long itemid) { getMendixObject().setValue(context, MemberNames.ItemId.toString(), itemid); } /** * @return value of SeqNbr */ public final java.lang.Integer getSeqNbr() { return getSeqNbr(getContext()); } /** * @param context * @return value of SeqNbr */ public final java.lang.Integer getSeqNbr(com.mendix.systemwideinterfaces.core.IContext context) { return (java.lang.Integer) getMendixObject().getValue(context, MemberNames.SeqNbr.toString()); } /** * Set value of SeqNbr * @param seqnbr */ public final void setSeqNbr(java.lang.Integer seqnbr) { setSeqNbr(getContext(), seqnbr); } /** * Set value of SeqNbr * @param context * @param seqnbr */ public final void setSeqNbr(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Integer seqnbr) { getMendixObject().setValue(context, MemberNames.SeqNbr.toString(), seqnbr); } /** * @return value of Name */ public final java.lang.String getName() { return getName(getContext()); } /** * @param context * @return value of Name */ public final java.lang.String getName(com.mendix.systemwideinterfaces.core.IContext context) { return (java.lang.String) getMendixObject().getValue(context, MemberNames.Name.toString()); } /** * Set value of Name * @param name */ public final void setName(java.lang.String name) { setName(getContext(), name); } /** * Set value of Name * @param context * @param name */ public final void setName(com.mendix.systemwideinterfaces.core.IContext context, java.lang.String name) { getMendixObject().setValue(context, MemberNames.Name.toString(), name); } /** * @return value of IsDragDisabled */ public final java.lang.Boolean getIsDragDisabled() { return getIsDragDisabled(getContext()); } /** * @param context * @return value of IsDragDisabled */ public final java.lang.Boolean getIsDragDisabled(com.mendix.systemwideinterfaces.core.IContext context) { return (java.lang.Boolean) getMendixObject().getValue(context, MemberNames.IsDragDisabled.toString()); } /** * Set value of IsDragDisabled * @param isdragdisabled */ public final void setIsDragDisabled(java.lang.Boolean isdragdisabled) { setIsDragDisabled(getContext(), isdragdisabled); } /** * Set value of IsDragDisabled * @param context * @param isdragdisabled */ public final void setIsDragDisabled(com.mendix.systemwideinterfaces.core.IContext context, java.lang.Boolean isdragdisabled) { getMendixObject().setValue(context, MemberNames.IsDragDisabled.toString(), isdragdisabled); } /** * @return value of Item_TaskBoard */ public final testmodule.proxies.TaskBoard getItem_TaskBoard() throws com.mendix.core.CoreException { return getItem_TaskBoard(getContext()); } /** * @param context * @return value of Item_TaskBoard */ public final testmodule.proxies.TaskBoard getItem_TaskBoard(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException { testmodule.proxies.TaskBoard result = null; com.mendix.systemwideinterfaces.core.IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.Item_TaskBoard.toString()); if (identifier != null) result = testmodule.proxies.TaskBoard.load(context, identifier); return result; } /** * Set value of Item_TaskBoard * @param item_taskboard */ public final void setItem_TaskBoard(testmodule.proxies.TaskBoard item_taskboard) { setItem_TaskBoard(getContext(), item_taskboard); } /** * Set value of Item_TaskBoard * @param context * @param item_taskboard */ public final void setItem_TaskBoard(com.mendix.systemwideinterfaces.core.IContext context, testmodule.proxies.TaskBoard item_taskboard) { if (item_taskboard == null) getMendixObject().setValue(context, MemberNames.Item_TaskBoard.toString(), null); else getMendixObject().setValue(context, MemberNames.Item_TaskBoard.toString(), item_taskboard.getMendixObject().getId()); } /** * @return value of Item_Column */ public final testmodule.proxies.Column getItem_Column() throws com.mendix.core.CoreException { return getItem_Column(getContext()); } /** * @param context * @return value of Item_Column */ public final testmodule.proxies.Column getItem_Column(com.mendix.systemwideinterfaces.core.IContext context) throws com.mendix.core.CoreException { testmodule.proxies.Column result = null; com.mendix.systemwideinterfaces.core.IMendixIdentifier identifier = getMendixObject().getValue(context, MemberNames.Item_Column.toString()); if (identifier != null) result = testmodule.proxies.Column.load(context, identifier); return result; } /** * Set value of Item_Column * @param item_column */ public final void setItem_Column(testmodule.proxies.Column item_column) { setItem_Column(getContext(), item_column); } /** * Set value of Item_Column * @param context * @param item_column */ public final void setItem_Column(com.mendix.systemwideinterfaces.core.IContext context, testmodule.proxies.Column item_column) { if (item_column == null) getMendixObject().setValue(context, MemberNames.Item_Column.toString(), null); else getMendixObject().setValue(context, MemberNames.Item_Column.toString(), item_column.getMendixObject().getId()); } /** * @return the IMendixObject instance of this proxy for use in the Core interface. */ public final com.mendix.systemwideinterfaces.core.IMendixObject getMendixObject() { return itemMendixObject; } /** * @return the IContext instance of this proxy, or null if no IContext instance was specified at initialization. */ public final com.mendix.systemwideinterfaces.core.IContext getContext() { return context; } @java.lang.Override public boolean equals(Object obj) { if (obj == this) return true; if (obj != null && getClass().equals(obj.getClass())) { final testmodule.proxies.Item that = (testmodule.proxies.Item) obj; return getMendixObject().equals(that.getMendixObject()); } return false; } @java.lang.Override public int hashCode() { return getMendixObject().hashCode(); } /** * @return String name of this class */ public static java.lang.String getType() { return "TestModule.Item"; } /** * @return String GUID from this object, format: ID_0000000000 * @deprecated Use getMendixObject().getId().toLong() to get a unique identifier for this object. */ @java.lang.Deprecated public java.lang.String getGUID() { return "ID_" + getMendixObject().getId().toLong(); } }
9236d1b5d19f3f351bbf029571fc7fb8e871392c
1,482
java
Java
src/main/java/com/bbn/openmap/omGraphics/editable/PointStateMachine.java
d2fn/passage
2085183f1b085ac344198bd674024fe715bd4fca
[ "MIT" ]
1
2020-04-10T09:43:49.000Z
2020-04-10T09:43:49.000Z
src/main/java/com/bbn/openmap/omGraphics/editable/PointStateMachine.java
d2fn/passage
2085183f1b085ac344198bd674024fe715bd4fca
[ "MIT" ]
null
null
null
src/main/java/com/bbn/openmap/omGraphics/editable/PointStateMachine.java
d2fn/passage
2085183f1b085ac344198bd674024fe715bd4fca
[ "MIT" ]
3
2015-05-01T20:36:49.000Z
2022-03-09T22:47:04.000Z
31.531915
97
0.582321
997,838
// ********************************************************************** // // <copyright> // // BBN Technologies // 10 Moulton Street // Cambridge, MA 02138 // (617) 873-8000 // // Copyright (C) BBNT Solutions LLC. All rights reserved. // // </copyright> // ********************************************************************** // // $Source: // /cvs/distapps/openmap/src/openmap/com/bbn/openmap/omGraphics/editable/PointStateMachine.java,v // $ // $RCSfile: PointStateMachine.java,v $ // $Revision: 1.4 $ // $Date: 2004/10/14 18:06:16 $ // $Author: dietrick $ // // ********************************************************************** package com.bbn.openmap.omGraphics.editable; import com.bbn.openmap.omGraphics.EditableOMPoint; import com.bbn.openmap.util.Debug; import com.bbn.openmap.util.stateMachine.State; public class PointStateMachine extends EOMGStateMachine { public PointStateMachine(EditableOMPoint point) { super(point); } protected State[] init() { State[] states = super.init(); Debug.message("eomg", "PointStateMachine.init()"); // These are the only two states that need something special // to happen. states[GRAPHIC_EDIT] = new PointEditState((EditableOMPoint) graphic); states[GRAPHIC_UNDEFINED] = new PointUndefinedState((EditableOMPoint) graphic); states[GRAPHIC_SETOFFSET] = new PointSetOffsetState((EditableOMPoint) graphic); return states; } }
9236d331166f5ff3237022ed2e9859164179a8c3
5,959
java
Java
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcCompletenessTargetTableManager.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcCompletenessTargetTableManager.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
dhis-2/dhis-services/dhis-service-analytics/src/main/java/org/hisp/dhis/analytics/table/JdbcCompletenessTargetTableManager.java
hispindia/MAHARASHTRA-2.13
f50ec5b3ca2c5fabb43058166fd0c0fbbaa946a9
[ "BSD-3-Clause" ]
null
null
null
33.477528
146
0.626951
997,839
package org.hisp.dhis.analytics.table; /* * Copyright (c) 2004-2013, University of Oslo * 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 the HISP project 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. */ import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; import org.hisp.dhis.analytics.AnalyticsTable; import org.hisp.dhis.organisationunit.OrganisationUnitGroupSet; import org.hisp.dhis.organisationunit.OrganisationUnitLevel; import org.springframework.scheduling.annotation.Async; import org.springframework.transaction.annotation.Transactional; /** * @author Lars Helge Overland */ public class JdbcCompletenessTargetTableManager extends AbstractJdbcTableManager { @Override @Transactional public List<AnalyticsTable> getTables( boolean last3YearsOnly ) { List<AnalyticsTable> tables = new ArrayList<AnalyticsTable>(); tables.add( new AnalyticsTable( getTableName(), getDimensionColumns( null ) ) ); return tables; } public boolean validState() { return true; } public String getTableName() { return "completenesstarget"; } public void createTable( AnalyticsTable table ) { final String tableName = table.getTempTableName(); final String sqlDrop = "drop table " + tableName; executeSilently( sqlDrop ); String sqlCreate = "create table " + tableName + " ("; for ( String[] col : getDimensionColumns( table ) ) { sqlCreate += col[0] + " " + col[1] + ","; } sqlCreate += "value double precision)"; log.info( "Create SQL: " + sqlCreate ); executeSilently( sqlCreate ); } @Async public Future<?> populateTableAsync( ConcurrentLinkedQueue<AnalyticsTable> tables ) { taskLoop : while ( true ) { AnalyticsTable table = tables.poll(); if ( table == null ) { break taskLoop; } String sql = "insert into " + table.getTempTableName() + " ("; for ( String[] col : getDimensionColumns( table ) ) { sql += col[0] + ","; } sql += "value) select "; for ( String[] col : getDimensionColumns( table ) ) { sql += col[2] + ","; } sql += "1 as value " + "from datasetsource dss " + "left join dataset ds on dss.datasetid=ds.datasetid " + "left join _orgunitstructure ous on dss.sourceid=ous.organisationunitid " + "left join _organisationunitgroupsetstructure ougs on dss.sourceid=ougs.organisationunitid"; log.info( "Populate SQL: "+ sql ); jdbcTemplate.execute( sql ); } return null; } public List<String[]> getDimensionColumns( AnalyticsTable table ) { List<String[]> columns = new ArrayList<String[]>(); Collection<OrganisationUnitGroupSet> orgUnitGroupSets = organisationUnitGroupService.getAllOrganisationUnitGroupSets(); Collection<OrganisationUnitLevel> levels = organisationUnitService.getOrganisationUnitLevels(); for ( OrganisationUnitGroupSet groupSet : orgUnitGroupSets ) { String[] col = { quote( groupSet.getUid() ), "character(11)", "ougs." + quote( groupSet.getUid() ) }; columns.add( col ); } for ( OrganisationUnitLevel level : levels ) { String column = quote( PREFIX_ORGUNITLEVEL + level.getLevel() ); String[] col = { column, "character(11)", "ous." + column }; columns.add( col ); } String[] ds = { "ds", "character(11) not null", "ds.uid" }; columns.add( ds ); return columns; } public Date getEarliestData() { return null; // Not relevant } public Date getLatestData() { return null; // Not relevant } @Async public Future<?> applyAggregationLevels( ConcurrentLinkedQueue<AnalyticsTable> tables, Collection<String> dataElements, int aggregationLevel ) { return null; // Not relevant } }
9236d3427f4291c3439a226899d3bb6d53bb8e93
617
java
Java
qstool-common/src/main/java/com/qs/libs/qstoolcommon/enums/base/AndSpecification.java
qiansheng1987/springboot-family
0bfda659072ca1ed35f6a30ff80a4a92c28ab60b
[ "Apache-2.0" ]
null
null
null
qstool-common/src/main/java/com/qs/libs/qstoolcommon/enums/base/AndSpecification.java
qiansheng1987/springboot-family
0bfda659072ca1ed35f6a30ff80a4a92c28ab60b
[ "Apache-2.0" ]
null
null
null
qstool-common/src/main/java/com/qs/libs/qstoolcommon/enums/base/AndSpecification.java
qiansheng1987/springboot-family
0bfda659072ca1ed35f6a30ff80a4a92c28ab60b
[ "Apache-2.0" ]
null
null
null
24.68
95
0.719611
997,840
package com.qs.libs.qstoolcommon.enums.base; /** * 具有并关系的规格 * * @author qiansheng * @date 2021/8/25 上午10:00 */ public class AndSpecification<T> extends AbstractSpecification<T> { private Specification<T> specificationA; private Specification<T> specificationB; public AndSpecification(Specification<T> specificationA, Specification<T> specificationB) { this.specificationA = specificationA; this.specificationB = specificationB; } @Override public boolean isSatisfiedBy(T t) { return specificationA.isSatisfiedBy(t) & specificationB.isSatisfiedBy(t); } }
9236d352d17d0fd8b01128fef7d980947d043f9c
879
java
Java
demo-model/src/main/java/com/ljq/demo/springboot/entity/ReceiveAddressEntity.java
Flying9001/springBootDemo
d5af5aa874f5d0fa7fd125f50455b1f30c965dfb
[ "Apache-2.0" ]
144
2019-01-25T14:40:57.000Z
2022-03-24T10:09:17.000Z
demo-model/src/main/java/com/ljq/demo/springboot/entity/ReceiveAddressEntity.java
Flying9001/springBootDemo
d5af5aa874f5d0fa7fd125f50455b1f30c965dfb
[ "Apache-2.0" ]
9
2020-02-24T09:36:27.000Z
2021-08-08T14:16:34.000Z
demo-model/src/main/java/com/ljq/demo/springboot/entity/ReceiveAddressEntity.java
Flying9001/springBootDemo
d5af5aa874f5d0fa7fd125f50455b1f30c965dfb
[ "Apache-2.0" ]
72
2019-03-26T08:56:33.000Z
2022-03-31T10:19:22.000Z
15.421053
55
0.575654
997,841
package com.ljq.demo.springboot.entity; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; /** * 收货地址实体类 * * @author junqiang.lu * @date 2019-06-16 16:09:06 */ @Data @JsonInclude(JsonInclude.Include.NON_NULL) public class ReceiveAddressEntity extends BaseEntity { private static final long serialVersionUID = 1L; /** * id,主键 * */ private Long id; /** * 用户 id * */ private Long userId; /** * 收货人姓名 * */ private String receiverName; /** * 收货人电话,支持手机号和座机 * */ private String telephone; /** * 省份 * */ private String province; /** * 城市 * */ private String city; /** * 城市地区,县 * */ private String area; /** * 详细地址 * */ private String address; /** * 是否为默认地址,true是;false不是(默认值) * */ private Integer defaultAddress; }
9236d5ad97517cb67ce92c3cc1f936cb5154af0c
47
java
Java
src/main/java/dev/sebastianb/icbm4fabric/client/init/package-info.java
SebaSphere/ICBM4Fabric
b0008a1d8b8aa1488ebf4ac4738f5945c13016a4
[ "MIT" ]
11
2021-04-01T07:57:09.000Z
2022-02-06T17:08:04.000Z
src/main/java/dev/sebastianb/icbm4fabric/client/init/package-info.java
Terra-Studios/ICBM4Fabric
b0008a1d8b8aa1488ebf4ac4738f5945c13016a4
[ "MIT" ]
null
null
null
src/main/java/dev/sebastianb/icbm4fabric/client/init/package-info.java
Terra-Studios/ICBM4Fabric
b0008a1d8b8aa1488ebf4ac4738f5945c13016a4
[ "MIT" ]
2
2021-06-03T18:02:30.000Z
2022-02-05T17:08:37.000Z
47
47
0.87234
997,842
package dev.sebastianb.icbm4fabric.client.init;
9236d649848aa5d07fe564927e2967ca3ca0e8f4
5,781
java
Java
JOGL/jogl-java-src/com/jogamp/oculusvr/ovrSensorData.java
MrLaki5/Shadow-mapping
e9a901429f14d30907219cbee517a07b02da2d2c
[ "MIT" ]
null
null
null
JOGL/jogl-java-src/com/jogamp/oculusvr/ovrSensorData.java
MrLaki5/Shadow-mapping
e9a901429f14d30907219cbee517a07b02da2d2c
[ "MIT" ]
null
null
null
JOGL/jogl-java-src/com/jogamp/oculusvr/ovrSensorData.java
MrLaki5/Shadow-mapping
e9a901429f14d30907219cbee517a07b02da2d2c
[ "MIT" ]
null
null
null
61.5
249
0.676873
997,843
/* !---- DO NOT EDIT: This file autogenerated by com/jogamp/gluegen/JavaEmitter.java on Sat Oct 10 03:31:13 CEST 2015 ----! */ package com.jogamp.oculusvr; import java.nio.*; import com.jogamp.gluegen.runtime.*; import com.jogamp.common.os.*; import com.jogamp.common.nio.*; import jogamp.common.os.MachineDataInfoRuntime; import com.jogamp.oculusvr.*; import java.security.AccessController; import java.security.PrivilegedAction; public class ovrSensorData { StructAccessor accessor; private static final int mdIdx = MachineDataInfoRuntime.getStatic().ordinal(); private final MachineDataInfo md; private static final int[] ovrSensorData_size = new int[] { 44 /* ARM_MIPS_32 */, 44 /* X86_32_UNIX */, 44 /* X86_32_MACOS */, 44 /* PPC_32_UNIX */, 44 /* SPARC_32_SUNOS */, 44 /* X86_32_WINDOWS */, 44 /* LP64_UNIX */, 44 /* X86_64_WINDOWS */ }; private static final int[] Accelerometer_offset = new int[] { 0 /* ARM_MIPS_32 */, 0 /* X86_32_UNIX */, 0 /* X86_32_MACOS */, 0 /* PPC_32_UNIX */, 0 /* SPARC_32_SUNOS */, 0 /* X86_32_WINDOWS */, 0 /* LP64_UNIX */, 0 /* X86_64_WINDOWS */ }; private static final int[] Accelerometer_size = new int[] { 12 /* ARM_MIPS_32 */, 12 /* X86_32_UNIX */, 12 /* X86_32_MACOS */, 12 /* PPC_32_UNIX */, 12 /* SPARC_32_SUNOS */, 12 /* X86_32_WINDOWS */, 12 /* LP64_UNIX */, 12 /* X86_64_WINDOWS */ }; private static final int[] Gyro_offset = new int[] { 12 /* ARM_MIPS_32 */, 12 /* X86_32_UNIX */, 12 /* X86_32_MACOS */, 12 /* PPC_32_UNIX */, 12 /* SPARC_32_SUNOS */, 12 /* X86_32_WINDOWS */, 12 /* LP64_UNIX */, 12 /* X86_64_WINDOWS */ }; private static final int[] Gyro_size = new int[] { 12 /* ARM_MIPS_32 */, 12 /* X86_32_UNIX */, 12 /* X86_32_MACOS */, 12 /* PPC_32_UNIX */, 12 /* SPARC_32_SUNOS */, 12 /* X86_32_WINDOWS */, 12 /* LP64_UNIX */, 12 /* X86_64_WINDOWS */ }; private static final int[] Magnetometer_offset = new int[] { 24 /* ARM_MIPS_32 */, 24 /* X86_32_UNIX */, 24 /* X86_32_MACOS */, 24 /* PPC_32_UNIX */, 24 /* SPARC_32_SUNOS */, 24 /* X86_32_WINDOWS */, 24 /* LP64_UNIX */, 24 /* X86_64_WINDOWS */ }; private static final int[] Magnetometer_size = new int[] { 12 /* ARM_MIPS_32 */, 12 /* X86_32_UNIX */, 12 /* X86_32_MACOS */, 12 /* PPC_32_UNIX */, 12 /* SPARC_32_SUNOS */, 12 /* X86_32_WINDOWS */, 12 /* LP64_UNIX */, 12 /* X86_64_WINDOWS */ }; private static final int[] Temperature_offset = new int[] { 36 /* ARM_MIPS_32 */, 36 /* X86_32_UNIX */, 36 /* X86_32_MACOS */, 36 /* PPC_32_UNIX */, 36 /* SPARC_32_SUNOS */, 36 /* X86_32_WINDOWS */, 36 /* LP64_UNIX */, 36 /* X86_64_WINDOWS */ }; //private static final int[] Temperature_size = new int[] { 4 /* ARM_MIPS_32 */, 4 /* X86_32_UNIX */, 4 /* X86_32_MACOS */, 4 /* PPC_32_UNIX */, 4 /* SPARC_32_SUNOS */, 4 /* X86_32_WINDOWS */, 4 /* LP64_UNIX */, 4 /* X86_64_WINDOWS */ }; private static final int[] TimeInSeconds_offset = new int[] { 40 /* ARM_MIPS_32 */, 40 /* X86_32_UNIX */, 40 /* X86_32_MACOS */, 40 /* PPC_32_UNIX */, 40 /* SPARC_32_SUNOS */, 40 /* X86_32_WINDOWS */, 40 /* LP64_UNIX */, 40 /* X86_64_WINDOWS */ }; //private static final int[] TimeInSeconds_size = new int[] { 4 /* ARM_MIPS_32 */, 4 /* X86_32_UNIX */, 4 /* X86_32_MACOS */, 4 /* PPC_32_UNIX */, 4 /* SPARC_32_SUNOS */, 4 /* X86_32_WINDOWS */, 4 /* LP64_UNIX */, 4 /* X86_64_WINDOWS */ }; public static int size() { return ovrSensorData_size[mdIdx]; } public static ovrSensorData create() { return create(Buffers.newDirectByteBuffer(size())); } public static ovrSensorData create(java.nio.ByteBuffer buf) { return new ovrSensorData(buf); } ovrSensorData(java.nio.ByteBuffer buf) { md = MachineDataInfo.StaticConfig.values()[mdIdx].md; accessor = new StructAccessor(buf); } public java.nio.ByteBuffer getBuffer() { return accessor.getBuffer(); } /** Getter for native field <code>Accelerometer</code>: CType[(StructType) typedef 'ovrVector3f', size [fixed false, lnx64 12], [const[false], struct{ovrVector3f_: 3, }]] */ public ovrVector3f getAccelerometer() { return ovrVector3f.create( accessor.slice( Accelerometer_offset[mdIdx], Accelerometer_size[mdIdx] ) ); } /** Getter for native field <code>Gyro</code>: CType[(StructType) typedef 'ovrVector3f', size [fixed false, lnx64 12], [const[false], struct{ovrVector3f_: 3, }]] */ public ovrVector3f getGyro() { return ovrVector3f.create( accessor.slice( Gyro_offset[mdIdx], Gyro_size[mdIdx] ) ); } /** Getter for native field <code>Magnetometer</code>: CType[(StructType) typedef 'ovrVector3f', size [fixed false, lnx64 12], [const[false], struct{ovrVector3f_: 3, }]] */ public ovrVector3f getMagnetometer() { return ovrVector3f.create( accessor.slice( Magnetometer_offset[mdIdx], Magnetometer_size[mdIdx] ) ); } /** Setter for native field <code>Temperature</code>: CType[(FloatType) 'float', size [fixed true, lnx64 4], [const[false], float]] */ public ovrSensorData setTemperature(float val) { accessor.setFloatAt(Temperature_offset[mdIdx], val); return this; } /** Getter for native field <code>Temperature</code>: CType[(FloatType) 'float', size [fixed true, lnx64 4], [const[false], float]] */ public float getTemperature() { return accessor.getFloatAt(Temperature_offset[mdIdx]); } /** Setter for native field <code>TimeInSeconds</code>: CType[(FloatType) 'float', size [fixed true, lnx64 4], [const[false], float]] */ public ovrSensorData setTimeInSeconds(float val) { accessor.setFloatAt(TimeInSeconds_offset[mdIdx], val); return this; } /** Getter for native field <code>TimeInSeconds</code>: CType[(FloatType) 'float', size [fixed true, lnx64 4], [const[false], float]] */ public float getTimeInSeconds() { return accessor.getFloatAt(TimeInSeconds_offset[mdIdx]); } }
9236d6e6f7e6562f9ccdc0f2db82fbaf763d2b81
1,882
java
Java
api/src/main/java/io/github/lbandc/cv19api/DeathRecordByAge.java
lbandc/cv19api
8c410be8d695db23b4fa27598323e1f05f387362
[ "MIT" ]
2
2020-04-16T20:12:36.000Z
2020-04-17T20:34:37.000Z
api/src/main/java/io/github/lbandc/cv19api/DeathRecordByAge.java
lbandc/cv19api
8c410be8d695db23b4fa27598323e1f05f387362
[ "MIT" ]
8
2020-04-12T13:54:59.000Z
2022-02-16T01:07:33.000Z
api/src/main/java/io/github/lbandc/cv19api/DeathRecordByAge.java
lbandc/cv19api
8c410be8d695db23b4fa27598323e1f05f387362
[ "MIT" ]
1
2020-04-14T19:34:00.000Z
2020-04-14T19:34:00.000Z
24.128205
84
0.792242
997,844
package io.github.lbandc.cv19api; import java.time.Instant; import java.time.LocalDate; import java.util.UUID; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityListeners; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.PrePersist; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import org.springframework.data.annotation.CreatedDate; import org.springframework.data.jpa.domain.support.AuditingEntityListener; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; @Entity @EntityListeners(AuditingEntityListener.class) @Table(name = "death_records_by_age", uniqueConstraints = { @UniqueConstraint(columnNames = { "age_range", "recorded_on", "day_of_death" }) }) @Getter @Setter @Data @Builder @AllArgsConstructor(access = AccessLevel.PRIVATE) @NoArgsConstructor(access = AccessLevel.PRIVATE) public class DeathRecordByAge { @Id private String id; @CreatedDate @Column(name = "created_at", updatable = false) private Instant createdAt; @Enumerated(EnumType.STRING) @Column(name = "age_range") private AgeRange ageRange; @Column(name = "recorded_on", updatable = false) @NonNull private LocalDate recordedOn; @Column(name = "day_of_death", updatable = false) @NonNull private LocalDate dayOfDeath; @Column(name = "deaths") @NonNull private Integer deaths; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "source_id") @NonNull private Ingest source; @PrePersist void createId() { this.id = UUID.randomUUID().toString(); } }
9236d937ba36369746dac3c6157664121eb0e2d7
811
java
Java
Zipc_Model/src/com/zipc/garden/model/arc/validation/ARCLineValidator.java
open-garden/garden
588fc9d254b913548159bcd01c5b34bd1c5cbc73
[ "BSD-3-Clause" ]
9
2021-06-22T08:05:59.000Z
2021-09-10T05:12:02.000Z
Zipc_Model/src/com/zipc/garden/model/arc/validation/ARCLineValidator.java
open-garden/garden
588fc9d254b913548159bcd01c5b34bd1c5cbc73
[ "BSD-3-Clause" ]
1
2021-04-14T05:15:10.000Z
2021-07-02T07:23:33.000Z
Zipc_Model/src/com/zipc/garden/model/arc/validation/ARCLineValidator.java
open-garden/garden
588fc9d254b913548159bcd01c5b34bd1c5cbc73
[ "BSD-3-Clause" ]
1
2021-04-14T05:31:49.000Z
2021-04-14T05:31:49.000Z
27.965517
127
0.745993
997,845
/** * * $Id$ */ package com.zipc.garden.model.arc.validation; import com.zipc.garden.model.arc.ARCState; /** * A sample validator interface for {@link com.zipc.garden.model.arc.ARCLine}. This doesn't really do anything, and it's not a * real EMF artifact. It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code * generator can be extended. This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface ARCLineValidator { boolean validate(); boolean validateVariableName(String value); boolean validateVariableType(String value); boolean validateX(int value); boolean validateTarget(ARCState value); boolean validateSource(ARCState value); boolean validateY(int value); }
9236dabba8c548bbfaaf9760cf4e7a9aa6abd77a
13,857
java
Java
avek-gui/src/main/java/fr/axonic/avek/bus/Orchestrator.java
JustificationFactory/JustificationFactory-ClinicalStudies
8da551ab1b44e915f48279893645c1a1572b8cc1
[ "Apache-2.0" ]
null
null
null
avek-gui/src/main/java/fr/axonic/avek/bus/Orchestrator.java
JustificationFactory/JustificationFactory-ClinicalStudies
8da551ab1b44e915f48279893645c1a1572b8cc1
[ "Apache-2.0" ]
null
null
null
avek-gui/src/main/java/fr/axonic/avek/bus/Orchestrator.java
JustificationFactory/JustificationFactory-ClinicalStudies
8da551ab1b44e915f48279893645c1a1572b8cc1
[ "Apache-2.0" ]
null
null
null
38.385042
141
0.581944
997,846
package fr.axonic.avek.bus; import fr.axonic.avek.bus.translator.DataTranslator; import fr.axonic.avek.engine.*; import fr.axonic.avek.engine.exception.StepBuildingException; import fr.axonic.avek.engine.exception.StrategyException; import fr.axonic.avek.engine.exception.WrongEvidenceException; import fr.axonic.avek.engine.support.Support; import fr.axonic.avek.instance.clinical.conclusion.*; import fr.axonic.avek.instance.clinical.evidence.Stimulation; import fr.axonic.avek.instance.clinical.evidence.Subject; import fr.axonic.avek.engine.pattern.Pattern; import fr.axonic.avek.gui.api.ComponentType; import fr.axonic.avek.gui.api.GUIAPI; import fr.axonic.avek.gui.api.GUIException; import fr.axonic.avek.gui.api.ViewType; import fr.axonic.avek.gui.model.GUIExperimentParameter; import fr.axonic.avek.model.MonitoredSystem; import fr.axonic.base.engine.AEntity; import fr.axonic.base.engine.AList; import fr.axonic.base.engine.AStructure; import fr.axonic.base.engine.AVarHelper; import fr.axonic.validation.exception.VerificationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.stream.Collectors; /** * Created by Nathaël N on 04/08/16. */ public class Orchestrator implements Observer { private static final Logger LOGGER = LoggerFactory.getLogger(Orchestrator.class); private static final String SUBJECT_STR = "subject"; private static final String STIM_STR = "stimulation"; private static final String PATTERN_TREAT = "Treat"; private static final String PATTERN_ES_EF = "Establish Effect"; private static final String PATTERN_GEN = "Generalize"; private Pattern currentPattern; private Subject currentSubject; private AList<Effect> currentEffects; private Stimulation currentStimulation; private final List<Pattern> patternList; private List<Support> evidences; private final JustificationSystemAPI engineAPI; private final GUIAPI guiAPI; public Orchestrator(GUIAPI guiapi, JustificationSystemAPI engineAPI) throws VerificationException, WrongEvidenceException, GUIException { patternList = new ArrayList<>(); this.engineAPI = engineAPI; guiAPI = guiapi; guiapi.addObserver(this); this.orchestrate(); } /** * Compute for the next pattern to apply and show right view depending on * applicable patterns * * @throws GUIException * @throws VerificationException * @throws WrongEvidenceException */ private void orchestrate() throws GUIException, VerificationException, WrongEvidenceException { computeNextPattern(); // If there is only one pattern available, setting the view to it if (patternList.size() == 1) { showViewFromPattern(patternList.get(0)); } else { Map<ComponentType, Object> content = new HashMap<>(); content.put(ComponentType.SELECTION, (List)(patternList.stream() .map(Pattern::getName) .collect(Collectors.toList()))); guiAPI.show("Selection", ViewType.STRATEGY_SELECTION_VIEW, content); } } /** * Request engineAPI to get applicable patterns list */ private void computeNextPattern() { // Preparing for following view evidences = engineAPI.getUnusedAssertions(evidences); patternList.clear(); patternList.addAll( engineAPI.getPatternsBase().getPossiblePatterns(evidences) .stream() .map(engineAPI.getPatternsBase()::getPattern) .collect(Collectors.toList())); } /** * Call GUI API to show the right view corresponding to a Pattern * @param pattern Will showing view corresponding to this pattern * @throws GUIException */ private void showViewFromPattern(Pattern pattern) throws GUIException { ViewType viewType; Map<ComponentType, Object> content = getDataFromEvidence(); Map<ComponentType, Object> newContent = new HashMap<>(); content.forEach((k, v) -> newContent.put(k, DataTranslator.translateForGUI(v))); // Selecting the right view depending on pattern switch (pattern.getName()) { case PATTERN_TREAT: viewType = ViewType.TREAT_VIEW; break; case PATTERN_ES_EF: viewType = ViewType.ESTABLISH_EFFECT_VIEW; break; case PATTERN_GEN: viewType = ViewType.GENERALIZE_VIEW; break; default: throw new RuntimeException("Pattern is unknown for ViewType conversion: " + pattern); } guiAPI.show(pattern.getName(), viewType, newContent); currentPattern = pattern; } /** * Create a AList containing all EffectEnum values as Effect * @return the AList */ private AList<Effect> generateEffectList() { try { List<Effect> list = new ArrayList<>(); for (EffectEnum effectEnum : EffectEnum.values()) { Effect effect = new Effect(); effect.setEffectValue(effectEnum); list.add(effect); } AList<Effect> alist = new AList<>(); alist.addAll(list); return alist; }catch (VerificationException e) { throw new RuntimeException("Impossible to make AList<Effect>", e); } } /** * @return Map containing data present in current evidences */ private Map<ComponentType, Object> getDataFromEvidence() { Map<ComponentType, Object> content = new HashMap<>(); // Setting default Experiment results to Data bus currentEffects = generateEffectList(); content.put(ComponentType.EFFECTS, currentEffects); // Setting others data to Data bus for (Support supportRole : evidences) { try { switch (supportRole.getName()) { case SUBJECT_STR: currentSubject = (Subject) supportRole.getElement(); MonitoredSystem ms = new MonitoredSystem(currentSubject.getId()); currentSubject.getFieldsContainer().forEach((key,val)-> { if(val instanceof AStructure) ms.addCategory(AVarHelper.transformAStructureToAList((AStructure) val)); else LOGGER.warn("Not treated: '"+key+"':"+val); }); content.put(ComponentType.MONITORED_SYSTEM, ms); break; case STIM_STR: currentStimulation = (Stimulation) supportRole.getElement(); AList<AEntity> list = new AList<>(); list.setLabel("root"); list.addAll(currentStimulation.getFieldsContainer().values()); content.put(ComponentType.EXPERIMENTATION_PARAMETERS, new GUIExperimentParameter(list)); break; default: if (supportRole instanceof EstablishEffectConclusion) { LOGGER.error("Got: " + supportRole); EstablishEffectConclusion eec = (EstablishEffectConclusion) supportRole; currentEffects = ((EstablishedEffect) eec.getElement()).getEffects(); content.put(ComponentType.EFFECTS, currentEffects); break; } LOGGER.warn("Unknown Evidence role \"" + supportRole.getName() + "\" in " + supportRole); } } catch (RuntimeException e) { LOGGER.error("Impossible to treat Evidence role: " + supportRole, e); } } return content; } /** * Call the right constructXXXStep method depending on data from evidences * @param data Data from current evidences */ private void constructStep(Map<ComponentType, Object> data) { // constructing step switch (currentPattern.getName()) { case PATTERN_TREAT: constructTreatStep(); break; case PATTERN_ES_EF: constructEstablishEffectStep(); break; case PATTERN_GEN: constructGeneralizeStep(); break; default: LOGGER.error("Constructing \"" + currentPattern + "\" not implemented"); } } private void constructTreatStep() { LOGGER.debug("Constructing Treat step"); try { engineAPI.constructStep(currentPattern, evidences, new ExperimentationConclusion( "Experimentation", currentSubject, currentStimulation)); } catch (WrongEvidenceException | StepBuildingException | StrategyException e) { LOGGER.error("Impossible to constructStep"); } } private void constructEstablishEffectStep() { LOGGER.debug("Constructing Establish effect step"); try { //AList<Effect> effects = (AList<Effect>) DataTranslator.translateForEngine(data.get(ComponentType.EFFECTS)); EstablishedEffect establishedEffect = new EstablishedEffect( new Experimentation(currentStimulation, currentSubject), currentEffects); EstablishEffectConclusion conclusion = new EstablishEffectConclusion( "Establish Effect", establishedEffect); // TODO pass UploadedFile.uploadedFolder; in establishEffectConclusion engineAPI.constructStep(currentPattern, evidences, conclusion); } catch (WrongEvidenceException | StepBuildingException | StrategyException e) { LOGGER.error("Impossible to constructStep"); } } private void constructGeneralizeStep() { LOGGER.debug("Constructing Generalize step"); try { // TODO pass UploadedFile.uploadedFolder; in GeneralizationConclusion //AList<Effect> effects = (AList<Effect>) DataTranslator.translateForEngine(data.get(ComponentType.EFFECTS)); GeneralizationConclusion conclusion = new GeneralizationConclusion( "Generalization", new EstablishedEffect( new Experimentation( currentStimulation, currentSubject), currentEffects )); engineAPI.constructStep(currentPattern, evidences, conclusion); } catch (WrongEvidenceException | StepBuildingException | StrategyException e) { LOGGER.error("Impossible to constructStep"); } } /** * * @param o Should be a GUIAPI * @param arg Should be a Map&lt;FeedbackEventEnum, Object&gt; */ @Override public void update(Observable o, Object arg) { if(!o.equals(guiAPI)) { throw new RuntimeException("Update get not from current used GUI API"); } @SuppressWarnings("unchecked") Map<FeedbackEventEnum, Object> data = (Map<FeedbackEventEnum, Object>) arg; boolean strategyFlag = false; Map<ComponentType, Object> content = null; for(Map.Entry<FeedbackEventEnum,Object> entry : data.entrySet()) { switch (entry.getKey()) { // When user selected pattern strategy he wants clicking on submit button of selection view case PATTERN: String selectedPatternName = (String) entry.getValue(); Optional<Pattern> pattern = patternList.stream() .filter(p -> p.getName().equals(selectedPatternName)) .findAny(); if(pattern.isPresent()) { try { showViewFromPattern(pattern.get()); } catch (GUIException e) { LOGGER.error("Unknown error occurred while showing view", e); } } else { LOGGER.warn("No pattern found with nameType: " + selectedPatternName); } break; // When user validate data he wrote clicking on strategy button case STRATEGY: strategyFlag = true; LOGGER.debug("Strategy flag raised"); break; case CONTENT: //noinspection unchecked content = (Map<ComponentType, Object>) data.get("Content"); LOGGER.debug("Content set to "+content); break; case VIEW_TYPE: break; default: throw new RuntimeException("No rule existing for nameType: " + entry.getKey()); } } if(strategyFlag) { try { // Constructing conclusion constructStep(content); orchestrate(); } catch (GUIException | VerificationException | WrongEvidenceException e) { LOGGER.error("Unknown error occurred while orchestrating", e); } } } }
9236db450956a35bc1a8d1125063110d660e4018
4,999
java
Java
matcher/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/matcher/service/AbstractDiffMatcher.java
AlexRogalskiy/Comparalyzer
42a03c14d639663387e7b796dca41cb1300ad36b
[ "MIT" ]
1
2019-02-27T00:28:14.000Z
2019-02-27T00:28:14.000Z
matcher/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/matcher/service/AbstractDiffMatcher.java
AlexRogalskiy/Comparalyzer
42a03c14d639663387e7b796dca41cb1300ad36b
[ "MIT" ]
8
2019-11-13T09:02:17.000Z
2021-12-09T20:49:03.000Z
matcher/src/main/java/com/wildbeeslabs/sensiblemetrics/diffy/matcher/service/AbstractDiffMatcher.java
AlexRogalskiy/Diffy
42a03c14d639663387e7b796dca41cb1300ad36b
[ "MIT" ]
1
2019-02-01T08:48:24.000Z
2019-02-01T08:48:24.000Z
36.224638
125
0.689538
997,847
/* * The MIT License * * Copyright 2019 WildBees Labs, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.wildbeeslabs.sensiblemetrics.diffy.matcher.service; import com.wildbeeslabs.sensiblemetrics.diffy.matcher.description.iface.MatchDescription; import com.wildbeeslabs.sensiblemetrics.diffy.matcher.handler.iface.MatcherHandler; import com.wildbeeslabs.sensiblemetrics.diffy.matcher.handler.impl.DefaultMatcherHandler; import com.wildbeeslabs.sensiblemetrics.diffy.matcher.interfaces.DiffMatcher; import com.wildbeeslabs.sensiblemetrics.diffy.matcher.interfaces.Matcher; import com.wildbeeslabs.sensiblemetrics.diffy.common.utils.ServiceUtils; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import java.util.*; /** * Abstract matcher implementation * * @param <T> type of input element to be matched by operation * @author Alexander Rogalskiy * @version 1.1 * @since 1.0 */ @Data @EqualsAndHashCode @ToString @SuppressWarnings("unchecked") public abstract class AbstractDiffMatcher<T, S> implements DiffMatcher<T> { /** * Default explicit serialVersionUID for interoperability */ private static final long serialVersionUID = 4127438327874076332L; /** * Default {@link List} collection of {@link Matcher}s */ private final List<Matcher<? super T>> matchers = new ArrayList<>(); /** * Default {@link MatcherHandler} implementation */ private final MatcherHandler<T, S> handler; /** * Default abstract matcher constructor */ public AbstractDiffMatcher() { this(null); } /** * Default abstract matcher constructor with input {@link MatcherHandler} * * @param handler - initial input {@link MatcherHandler} */ public AbstractDiffMatcher(final MatcherHandler<T, S> handler) { this.handler = Optional.ofNullable(handler).orElse(DefaultMatcherHandler.INSTANCE); } /** * Removes input {@link Iterable} collection of {@link Matcher}s from current {@link List} collection of {@link Matcher}s * * @param matchers - initial input {@link Iterable} collection of {@link Matcher}s */ public AbstractDiffMatcher<T, S> exclude(final Iterable<Matcher<? super T>> matchers) { ServiceUtils.listOf(matchers).forEach(this::exclude); return this; } /** * Removes input {@link Matcher} from current {@link List} collection of {@link Matcher}s * * @param matcher - initial input {@link Matcher} to remove */ public AbstractDiffMatcher<T, S> exclude(final Matcher<? super T> matcher) { if (Objects.nonNull(matcher)) { this.getMatchers().remove(matcher); } return this; } /** * Adds input {@link Iterable} collection of {@link Matcher}s to current {@link List} collection * * @param matchers - initial input {@link Iterable} collection of {@link Matcher}s */ public AbstractDiffMatcher<T, S> include(final Iterable<Matcher<? super T>> matchers) { this.getMatchers().clear(); ServiceUtils.listOf(matchers).forEach(this::include); return this; } /** * Adds input {@link Matcher} to current {@link List} collection of {@link Matcher}s * * @param matcher - initial input matcher {@link Matcher} to add */ public AbstractDiffMatcher<T, S> include(final Matcher<? super T> matcher) { if (Objects.nonNull(matcher)) { this.getMatchers().add(matcher); } return this; } public void describeBy(final T value, final MatchDescription description) { description.append("["); for (final Iterator<Matcher<? super T>> it = this.matchers.iterator(); it.hasNext(); ) { it.next().describeBy(value, description); if (it.hasNext()) { description.append(", "); } } description.append("]"); } }
9236dbd5746fc800b45635d1d8188bdb82ba7d31
1,184
java
Java
src/main/java/com/amazonaws/services/sqs/model/BatchRequestTooLongException.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
2
2015-04-09T03:30:56.000Z
2020-07-06T20:23:21.000Z
src/main/java/com/amazonaws/services/sqs/model/BatchRequestTooLongException.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazonaws/services/sqs/model/BatchRequestTooLongException.java
pbailis/aws-java-sdk-dynamodb-timestamp
33d9beb9e8b8bf6965312c2c61c621ce96d054c8
[ "Apache-2.0" ]
4
2015-02-03T19:36:40.000Z
2020-07-06T20:30:56.000Z
31.157895
79
0.706926
997,848
/* * Copyright 2010-2012 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.sqs.model; import com.amazonaws.AmazonServiceException; /** * <p> * The length of all the messages put together is more than the limit. * </p> */ public class BatchRequestTooLongException extends AmazonServiceException { private static final long serialVersionUID = 1L; /** * Constructs a new BatchRequestTooLongException with the specified error * message. * * @param message Describes the error encountered. */ public BatchRequestTooLongException(String message) { super(message); } }
9236dbdc7b6c534ef455556247ec6e9949f10004
14,404
java
Java
src/main/java/dz/minagri/stat/comp/form/ZoneForm.java
bellalDjam/minagri
4ea6ef78ba994df23910bfda7c615c477a8e0dd1
[ "Apache-2.0" ]
null
null
null
src/main/java/dz/minagri/stat/comp/form/ZoneForm.java
bellalDjam/minagri
4ea6ef78ba994df23910bfda7c615c477a8e0dd1
[ "Apache-2.0" ]
null
null
null
src/main/java/dz/minagri/stat/comp/form/ZoneForm.java
bellalDjam/minagri
4ea6ef78ba994df23910bfda7c615c477a8e0dd1
[ "Apache-2.0" ]
null
null
null
28.985944
97
0.692206
997,849
/** * */ package dz.minagri.stat.comp.form; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.vaadin.event.selection.SingleSelectionEvent; import com.vaadin.event.selection.SingleSelectionListener; import com.vaadin.navigator.View; import com.vaadin.navigator.ViewChangeListener.ViewChangeEvent; import com.vaadin.shared.ui.MarginInfo; import com.vaadin.spring.annotation.SpringComponent; import com.vaadin.spring.annotation.UIScope; import com.vaadin.ui.Alignment; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.ComboBox; import com.vaadin.ui.CssLayout; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.NativeSelect; import com.vaadin.ui.Notification; import com.vaadin.ui.TextArea; import com.vaadin.ui.TextField; import com.vaadin.ui.UI; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; import dz.minagri.stat.enumeration.TypeCommune; import dz.minagri.stat.model.Commune; import dz.minagri.stat.model.Wilaya; import dz.minagri.stat.model.Zone; import dz.minagri.stat.repositories.CommuneRepository; import dz.minagri.stat.repositories.WilayaRepository; import dz.minagri.stat.repositories.ZoneRepository; /** * @author bellal djamel * */ @SpringComponent @UIScope kenaa@example.com) //@SpringView(name = RGAView.VIEW_NAME) public class ZoneForm extends VerticalLayout implements View { /** * */ private static final long serialVersionUID = -4422515472136056523L; private final WilayaRepository wilRepo; private final CommuneRepository comRepo; private final ZoneRepository zoneRepo; public static final String VIEW_NAME = "zoneform"; //UI components Label lblTitle; // private ComboBox<Wilaya> cbWilaya; private Button btnNewWilaya; private Button btnNewCommune; private Button btnNewZone; private Button btnConfirm; private Button btnCancel; private TextField TypeCommune; private TextField codeSubdiv; private FormLayout form; private HorizontalLayout cbs; private HorizontalLayout headerW; private HorizontalLayout headerC; private HorizontalLayout headerZ ; private HorizontalLayout footer; private HorizontalLayout header; private ComboBox<Wilaya> selectW; private ComboBox<Commune> selectC; private ComboBox<Zone> selectZ; private Commune selectedC=new Commune(); /** * */ public ZoneForm(WilayaRepository wilRepo,CommuneRepository comRepo,ZoneRepository zoneRepo) { //initial setup this.wilRepo =wilRepo; this.comRepo =comRepo; this.zoneRepo=zoneRepo; setSpacing(false); setMargin(false); //UI Components // lblTitle = new Label("R-G-Admistratifs"); // lblTitle.addStyleName("h4"); // addComponent(lblTitle); //add Combobox // final ComboBox<Wilaya> selectW = new ComboBox<>(); selectW.setVisible(true); // final ComboBox<Commune> selectC = new ComboBox<>(); selectC.setVisible(false); // final ComboBox<Zone> selectZ = new ComboBox<>(); selectZ.setVisible(false); //First Populate selectW List<Wilaya> wils = wilRepo.findAll(); selectW.setPlaceholder("Wilaya"); selectW.setItemCaptionGenerator(p->p.getNomWilaya()); selectW.setItems(wils); btnNewWilaya = new Button("+ Wilaya"); btnNewWilaya.addStyleName("primary"); btnNewWilaya.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { // Create a sub-window and set the content final Window subWindow = new Window("Nouvelle Wilaya"); VerticalLayout subContent = new VerticalLayout(); subContent.setWidth("90%"); subContent.setMargin(true); subContent.setSpacing(true); subWindow.setContent(subContent); // Put some components in it // Center it in the browser window subWindow.center(); subWindow.setModal(true); HorizontalLayout h0 = new HorizontalLayout(); h0.setSpacing(true); h0.setMargin(true); HorizontalLayout h1 = new HorizontalLayout(); h1.setSpacing(true); h1.setMargin(true); final TextField nameWilaya = new TextField(); nameWilaya.setPlaceholder("Nom Wilaya"); final TextField codeWilaya= new TextField(); codeWilaya.setPlaceholder("Code Wilaya"); final Button save ; final Button cancel ; save = new Button("Sauver",new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { if (nameWilaya.getValue()!=null && codeWilaya.getValue()!=null ) { Wilaya exp= new Wilaya(); exp.setNomWilaya(nameWilaya.getValue()); exp.setCodeWilaya(Long.parseLong(codeWilaya.getValue())); //TODO Delete sysout // System.out.println(codeWilaya.getValue()+"codeWilaya.getValue()"); // System.out.println(nameWilaya.getValue()+"nameWilaya.getValue()"); // System.out.println(wilRepo+"wilRepo"); wilRepo.save(exp); subWindow.close(); } } }); cancel = new Button("Cancel",new Button.ClickListener() { /** * */ private static final long serialVersionUID = -7044268028795285553L; @Override public void buttonClick(ClickEvent event) { subWindow.close(); // refresh(); } }); //reset UI cancel.addStyleName("danger"); CssLayout actions = new CssLayout(save, cancel); h0.addComponents(nameWilaya,codeWilaya); h1.addComponent(actions); subContent.addComponents(h0,h1); UI.getCurrent().addWindow(subWindow); } }); // final ComboBox<Commune> selectC = new ComboBox<>(); selectW.addValueChangeListener(new com.vaadin.data.HasValue.ValueChangeListener<Wilaya>() { @Override public void valueChange(com.vaadin.data.HasValue.ValueChangeEvent<Wilaya> event) { if(selectW.getValue()!=null ) { List<Commune> coms = selectW.getSelectedItem().get().getCommunes(); selectC.setVisible(true); btnNewCommune.setVisible(true); Notification.show("coms = "+" commune = "+coms); selectC.setPlaceholder("Commune"); selectC.setItemCaptionGenerator(p->p.getName()); selectC.setItems(selectW.getValue().getCommunes()); } } }); selectC.addSelectionListener(new SingleSelectionListener<Commune>() { Commune selCom =selectedC; private static final long serialVersionUID = 1241443965637589435L; @Override public void selectionChange(SingleSelectionEvent<Commune> event) { if(selectC.getValue()!=null) { btnNewZone.setEnabled(true); List<Zone> zones = new ArrayList<>(); if(null!=selectC.getSelectedItem().get().getZones()) { selCom = selectC.getValue(); btnNewZone.setEnabled(true); selectZ.setVisible(true); zones = selectC.getValue().getZones(); selectZ.setPlaceholder("Commune"); selectZ.setItemCaptionGenerator(p->p.getName()); selectZ.setItems(zones); }else { } } } }); btnNewCommune = new Button("+ Commune"); btnNewCommune.addStyleName("primary"); btnNewCommune.setVisible(false); btnNewCommune.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { // Create a sub-window and set the content final Window subWindow = new Window("Nouvelle Commune"); VerticalLayout subContent = new VerticalLayout(); subContent.setWidth("90%"); subContent.setMargin(true); subContent.setSpacing(true); subWindow.setContent(subContent); // Put some components in it // Center it in the browser window subWindow.center(); subWindow.setModal(true); HorizontalLayout h0 = new HorizontalLayout(); h0.setSpacing(true); h0.setMargin(true); HorizontalLayout h01 = new HorizontalLayout(); h01.setSpacing(true); h01.setMargin(true); HorizontalLayout h = new HorizontalLayout(); h.setSpacing(true); h.setMargin(true); HorizontalLayout h1 = new HorizontalLayout(); h1.setSpacing(true); h1.setMargin(true); final TextField nameCommune = new TextField(); nameCommune.setPlaceholder("Nom Commune"); List<Wilaya> wilayas = wilRepo.findAll(); selectW.setItems(wilayas); // Use the name property for item captions selectW.setItemCaptionGenerator(p -> p.getNomWilaya() + " " + p.getCodeWilaya()); final TextField codecommune= new TextField(); codecommune.setPlaceholder("Code commune"); final NativeSelect<TypeCommune> typeCommune = new NativeSelect<TypeCommune>(); typeCommune.setItems(EnumSet.allOf(TypeCommune.class)); final TextField codeSubdiv= new TextField(); codeSubdiv.setPlaceholder("Code Subdiv"); final Button save ; final Button cancel ; save = new Button("Sauver",new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { if (nameCommune.getValue()!=null && codecommune.getValue()!=null && typeCommune.getValue()!=null && codeSubdiv.getValue()!=null &&selectW.getValue()!=null ) { Commune exp= new Commune(); exp.setWilaya(selectW.getValue()); exp.setName(nameCommune.getValue()); exp.setCodeCommune(Long.parseLong(codecommune.getValue())); exp.setTypeCommune(typeCommune.getValue()); exp.setCodeSubdiv(Long.parseLong(codeSubdiv.getValue())); comRepo.save(exp); subWindow.close(); } } }); cancel = new Button("Cancel",new Button.ClickListener() { /** * */ private static final long serialVersionUID = -7044268028795285553L; @Override public void buttonClick(ClickEvent event) { subWindow.close(); // refresh(); } }); cancel.addStyleName("danger"); // save.addStyleName(style); CssLayout actions = new CssLayout(save, cancel); h0.addComponents(selectW,codeSubdiv); h01.addComponents(nameCommune,codecommune); h.addComponent(typeCommune); h1.addComponent(actions); subContent.addComponents(h0,h01,h,h1); UI.getCurrent().addWindow(subWindow); } }); btnNewZone=new Button("+ Zone"); btnNewZone.addStyleName("primary"); btnNewZone.setEnabled(false); btnNewZone.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { // Create a sub-window and set the content final Window subWindow = new Window("Nouvelle Zone"); VerticalLayout subContent = new VerticalLayout(); subContent.setWidth("90%"); subContent.setMargin(true); subContent.setSpacing(true); subWindow.setContent(subContent); // Put some components in it // Center it in the browser window subWindow.center(); subWindow.setModal(true); HorizontalLayout h0 = new HorizontalLayout(); h0.setSpacing(true); h0.setMargin(true); HorizontalLayout h01 = new HorizontalLayout(); final TextField nameZone = new TextField(); nameZone.setPlaceholder("Nom Zone"); final TextArea remarque = new TextArea(); remarque.setPlaceholder("Remarques"); final Button save ; final Button cancel ; save = new Button("Sauver",new Button.ClickListener() { /** * */ private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { if (nameZone.getValue()!=null && selectC.getValue()!=null) { Zone expz= new Zone(); expz.setName(nameZone.getValue()); expz.setRemarque(remarque.getValue()); Commune com=comRepo.findByNameLike(selectC.getValue().getName()); expz.setCommune(com); zoneRepo.save(expz); subWindow.close(); } } }); cancel = new Button("Cancel",new Button.ClickListener() { /** * */ private static final long serialVersionUID = -7044268028795285553L; @Override public void buttonClick(ClickEvent event) { subWindow.close(); // refresh(); } }); cancel.addStyleName("danger"); // save.addStyleName(style); CssLayout actions = new CssLayout(save, cancel); h0.addComponents(nameZone,remarque); h01.addComponent(actions); subContent.addComponents(h0,h01); UI.getCurrent().addWindow(subWindow); } }); headerW = new HorizontalLayout(); headerW.setMargin(false); headerW.setSpacing(false); headerC = new HorizontalLayout(); headerC.setMargin(false); headerC.setSpacing(false); headerZ = new HorizontalLayout(); header = new HorizontalLayout(); header.addComponents(selectW,btnNewWilaya,selectC,btnNewCommune,selectZ,btnNewZone); addComponent(header); form = new FormLayout(); form.setMargin(false); form.setWidth("900"); form.addStyleName("light"); addComponent(form); // List<Wilaya> wilayas = new ArrayList<>(); // wilayas = wilRepo.findAll(); // cbWilaya= new ComboBox<Wilaya>("Wilaya"); // cbWilaya.setItems(wilayas); // cbWilaya.setItemCaptionGenerator(Wilaya::getNomWilaya); btnConfirm = new Button("Confirm"); btnConfirm.addStyleName("primary"); btnConfirm.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { } }); btnCancel = new Button("Cancel"); btnCancel.addStyleName("primary"); btnCancel.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent event) { //add class to teacher Notification.show("Class Added"); } }); // cbs.addComponents(cbWilaya,btnNewWilaya); // form.addComponent(cbs); //horizontal layout for button footer = new HorizontalLayout(); footer.setMargin(new MarginInfo(true,false,true,false)); footer.setSpacing(true); footer.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT); form.addComponent(footer); footer.addComponents(btnConfirm,btnCancel); } /* (non-Javadoc) * @see com.vaadin.navigator.View#enter(com.vaadin.navigator.ViewChangeListener.ViewChangeEvent) */ @Override public void enter(ViewChangeEvent event) { } }
9236dbebfe8972e1d98c54426f1e9564dd0fac9a
1,675
java
Java
src/test/java/com/tambapps/fft4j/fourier/fft_1d/FastFouriersTest.java
nelson888/fourier-transform-library
c41af1c73a180204c2559322d7f904230a3f3d3f
[ "MIT" ]
3
2021-03-16T01:40:35.000Z
2021-07-22T16:20:53.000Z
src/test/java/com/tambapps/fft4j/fourier/fft_1d/FastFouriersTest.java
nelson888/fourier-transform-library
c41af1c73a180204c2559322d7f904230a3f3d3f
[ "MIT" ]
2
2021-06-02T14:55:11.000Z
2021-11-19T15:48:40.000Z
src/test/java/com/tambapps/fft4j/fourier/fft_1d/FastFouriersTest.java
tambapps/fourier-transform-library
c41af1c73a180204c2559322d7f904230a3f3d3f
[ "MIT" ]
null
null
null
25.378788
82
0.699701
997,850
package com.tambapps.fft4j.fourier.fft_1d; import static org.junit.Assert.assertEquals; import com.tambapps.fft4j.complex.Complex; import com.tambapps.fft4j.complex.vector.CVector; import com.tambapps.fft4j.complex.vector.ImmutableCVector; import org.junit.Test; import java.util.Arrays; public class FastFouriersTest { private final static Complex ONE = Complex.of(1); private final CVector input = ImmutableCVector.of(ONE, ONE, ONE, ONE, Complex.ZERO, Complex.ZERO, Complex.ZERO, Complex.ZERO); private final CVector expected = ImmutableCVector.of(Complex.of(4), Complex.of(1d, -2.414214), Complex.ZERO, Complex.of(1, -0.414214), Complex.ZERO, Complex.of(1, 0.414214), Complex.ZERO, Complex.of(1, 2.414214)); private void algorithmTest(FastFourierTransform algorithm) { CVector result = input.copy(); algorithm.compute(result); assertEquals("Should be equal", expected, result); assertEquals("Should be equal", expected, algorithm.computeCopy(input)); } @Test public void basicTest() { algorithmTest(FastFouriers.BASIC); } @Test public void recursiveTest() { algorithmTest(FastFouriers.CT_RECURSIVE); } @Test public void iterativeTest() { algorithmTest(FastFouriers.CT_ITERATIVE); } @Test public void inverseTest() { for (FastFourierTransform algorithm : Arrays.asList(FastFouriers.CT_ITERATIVE, FastFouriers.BASIC, FastFouriers.CT_RECURSIVE)) { CVector result = expected.copy(); FastFouriers.inverse(algorithm).compute(result); assertEquals("Should be equal", input, result); } } }
9236dc66f3a9b15996ceeab97099f34d6de61ce0
69
java
Java
src/test/java/screenplay/config/package-info.java
ashusc/BDDScreenplay-Wikipedia
999dbcffcf3e57f0dd798aa276714eccea0a27e6
[ "MIT" ]
3
2019-09-26T01:45:59.000Z
2021-07-27T18:14:36.000Z
src/test/java/screenplay/config/package-info.java
nityanarayan44/BDD-Screenplay
45ad68ec03a12f55cbeb3319eacada88ea76508d
[ "MIT" ]
2
2018-07-01T11:03:04.000Z
2018-07-05T07:36:31.000Z
src/test/java/screenplay/config/package-info.java
nityanarayan44/BDD-Screenplay
45ad68ec03a12f55cbeb3319eacada88ea76508d
[ "MIT" ]
2
2018-06-27T17:06:47.000Z
2018-11-27T07:56:31.000Z
8.625
26
0.536232
997,851
/** * */ /** * @author ashutosh * */ package screenplay.config;
9236dd69cb26fdf0b1ce081183027624bd9d5959
1,057
java
Java
app/src/main/java/cn/imppp/knowlege/ui/activity/AboutActivity.java
immppp/KownLegeRes
fae631a1288c2f048fd48c29e4a22f1a89296281
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/imppp/knowlege/ui/activity/AboutActivity.java
immppp/KownLegeRes
fae631a1288c2f048fd48c29e4a22f1a89296281
[ "Apache-2.0" ]
null
null
null
app/src/main/java/cn/imppp/knowlege/ui/activity/AboutActivity.java
immppp/KownLegeRes
fae631a1288c2f048fd48c29e4a22f1a89296281
[ "Apache-2.0" ]
null
null
null
31.088235
101
0.756859
997,852
package cn.imppp.knowlege.ui.activity; import androidx.databinding.DataBindingUtil; import androidx.lifecycle.ViewModelProvider; import cn.imppp.knowlege.R; import cn.imppp.knowlege.base.BaseActivity; import cn.imppp.knowlege.databinding.ActivityAboutBinding; import cn.imppp.knowlege.state.NormalViewModel; import android.os.Bundle; /** * @ClassName: AboutActivity * @Author: qaq * @Description: 关于界面 * @Date: 2020/9/28 4:19 PM * @Company: 杭州达恒科技 * @Version: 1.0 */ public class AboutActivity extends BaseActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityAboutBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_about); NormalViewModel normalViewModel = new ViewModelProvider(this).get(NormalViewModel.class); titleViewModel.showMenu.set(false); titleViewModel.title.set(getString(R.string.about)); normalViewModel.titleView.setValue(titleViewModel); binding.setVm(normalViewModel); } }
9236de1a895cede8b3e561454617f5b33054ab8c
3,438
java
Java
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/google/android/exoplayer/hls/PtsTimestampAdjusterProvider.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
3
2019-05-01T09:22:08.000Z
2019-07-06T22:21:59.000Z
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/google/android/exoplayer/hls/PtsTimestampAdjusterProvider.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
null
null
null
ExtractedJars/Shopkick_com.shopkick.app/javafiles/com/google/android/exoplayer/hls/PtsTimestampAdjusterProvider.java
Andreas237/AndroidPolicyAutomation
c1ed10a2c6d4cf3dfda8b8e6291dee2c2a15ee8a
[ "MIT" ]
1
2020-11-26T12:22:02.000Z
2020-11-26T12:22:02.000Z
35.081633
98
0.575625
997,853
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.exoplayer.hls; import android.util.SparseArray; import com.google.android.exoplayer.extractor.ts.PtsTimestampAdjuster; public final class PtsTimestampAdjusterProvider { public PtsTimestampAdjusterProvider() { // 0 0:aload_0 // 1 1:invokespecial #11 <Method void Object()> // 2 4:aload_0 // 3 5:new #13 <Class SparseArray> // 4 8:dup // 5 9:invokespecial #14 <Method void SparseArray()> // 6 12:putfield #16 <Field SparseArray ptsTimestampAdjusters> // 7 15:return } public PtsTimestampAdjuster getAdjuster(boolean flag, int i, long l) { PtsTimestampAdjuster ptstimestampadjuster1 = (PtsTimestampAdjuster)ptsTimestampAdjusters.get(i); // 0 0:aload_0 // 1 1:getfield #16 <Field SparseArray ptsTimestampAdjusters> // 2 4:iload_2 // 3 5:invokevirtual #23 <Method Object SparseArray.get(int)> // 4 8:checkcast #25 <Class PtsTimestampAdjuster> // 5 11:astore 6 PtsTimestampAdjuster ptstimestampadjuster = ptstimestampadjuster1; // 6 13:aload 6 // 7 15:astore 5 if(flag) //* 8 17:iload_1 //* 9 18:ifeq 50 { ptstimestampadjuster = ptstimestampadjuster1; // 10 21:aload 6 // 11 23:astore 5 if(ptstimestampadjuster1 == null) //* 12 25:aload 6 //* 13 27:ifnonnull 50 { ptstimestampadjuster = new PtsTimestampAdjuster(l); // 14 30:new #25 <Class PtsTimestampAdjuster> // 15 33:dup // 16 34:lload_3 // 17 35:invokespecial #28 <Method void PtsTimestampAdjuster(long)> // 18 38:astore 5 ptsTimestampAdjusters.put(i, ((Object) (ptstimestampadjuster))); // 19 40:aload_0 // 20 41:getfield #16 <Field SparseArray ptsTimestampAdjusters> // 21 44:iload_2 // 22 45:aload 5 // 23 47:invokevirtual #32 <Method void SparseArray.put(int, Object)> } } ptstimestampadjuster1 = ptstimestampadjuster; // 24 50:aload 5 // 25 52:astore 6 if(!flag) //* 26 54:iload_1 //* 27 55:ifne 77 { if(ptstimestampadjuster != null && ptstimestampadjuster.isInitialized()) //* 28 58:aload 5 //* 29 60:ifnull 74 //* 30 63:aload 5 //* 31 65:invokevirtual #36 <Method boolean PtsTimestampAdjuster.isInitialized()> //* 32 68:ifeq 74 return ptstimestampadjuster; // 33 71:aload 5 // 34 73:areturn ptstimestampadjuster1 = null; // 35 74:aconst_null // 36 75:astore 6 } return ptstimestampadjuster1; // 37 77:aload 6 // 38 79:areturn } public void reset() { ptsTimestampAdjusters.clear(); // 0 0:aload_0 // 1 1:getfield #16 <Field SparseArray ptsTimestampAdjusters> // 2 4:invokevirtual #40 <Method void SparseArray.clear()> // 3 7:return } private final SparseArray ptsTimestampAdjusters = new SparseArray(); }
9236de763cf9ef21e0d5133c3020315fa2080f97
614
java
Java
spring5/MySampleApp1/src/main/java/jp/tuyano/spring/sample1/MyBean.java
gaeanet/workspace
91631029b96c186304b9d747830893831ee9dc3c
[ "Unlicense" ]
null
null
null
spring5/MySampleApp1/src/main/java/jp/tuyano/spring/sample1/MyBean.java
gaeanet/workspace
91631029b96c186304b9d747830893831ee9dc3c
[ "Unlicense" ]
null
null
null
spring5/MySampleApp1/src/main/java/jp/tuyano/spring/sample1/MyBean.java
gaeanet/workspace
91631029b96c186304b9d747830893831ee9dc3c
[ "Unlicense" ]
null
null
null
16.594595
63
0.680782
997,854
package jp.tuyano.spring.sample1; import java.util.Calendar; import java.util.Date; public class MyBean implements MyBeanInterface { private Date date; private String message; public MyBean() { super(); this.date = Calendar.getInstance().getTime(); } public MyBean(String message) { this(); this.message = message; } public Date getDate() { return date; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return "MyBean [message=" + message + ", date=" + date + "]"; } }
9236dfb84ece43d5c5c0842f733db67fa8baa8d3
3,043
java
Java
devicehive-frontend/src/main/java/com/devicehive/websockets/converters/JsonMessageBuilder.java
creatorrr/devicehive-java-server
ed70be82db9d050544cd3ca21d66905efca9ac88
[ "Apache-2.0" ]
265
2015-07-06T01:00:16.000Z
2022-03-24T14:21:52.000Z
devicehive-frontend/src/main/java/com/devicehive/websockets/converters/JsonMessageBuilder.java
sighttviewliu/devicehive-java-server
ed70be82db9d050544cd3ca21d66905efca9ac88
[ "Apache-2.0" ]
116
2015-06-24T18:34:43.000Z
2021-09-19T06:44:34.000Z
devicehive-frontend/src/main/java/com/devicehive/websockets/converters/JsonMessageBuilder.java
sighttviewliu/devicehive-java-server
ed70be82db9d050544cd3ca21d66905efca9ac88
[ "Apache-2.0" ]
124
2015-07-09T20:01:54.000Z
2022-01-13T20:43:23.000Z
30.128713
105
0.706211
997,855
package com.devicehive.websockets.converters; /* * #%L * DeviceHive Java Server Common business logic * %% * Copyright (C) 2016 DataArt * %% * 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. * #L% */ import com.devicehive.exceptions.HiveException; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import java.util.Map; public class JsonMessageBuilder { public static final String STATUS = "status"; public static final String ERROR = "error"; public static final String ERROR_CODE = "code"; public static final String ACTION = "action"; public static final String REQUEST_ID = "requestId"; private JsonObject jsonObject = new JsonObject(); public JsonMessageBuilder() { } public static JsonMessageBuilder createSuccessResponseBuilder() { return new JsonMessageBuilder().addStatus("success"); } public static JsonMessageBuilder createErrorResponseBuilder(Integer errorCode) { return new JsonMessageBuilder().addErrorCode(errorCode).addStatus("error"); } public static JsonMessageBuilder createErrorResponseBuilder(Integer errorCode, String errorMessage) { return createErrorResponseBuilder(errorCode).addErrorMessage(errorMessage); } public static JsonMessageBuilder createError(HiveException ex) { return createErrorResponseBuilder(ex.getCode(), ex.getMessage()); } public JsonObject build() { return jsonObject; } public JsonMessageBuilder addErrorCode(Integer errorCode) { jsonObject.addProperty(ERROR_CODE, errorCode); return this; } public JsonMessageBuilder addStatus(String status) { jsonObject.addProperty(STATUS, status); return this; } public JsonMessageBuilder addErrorMessage(String error) { jsonObject.addProperty(ERROR, error); return this; } public JsonMessageBuilder addAction(JsonElement action) { jsonObject.add(ACTION, action); return this; } public JsonMessageBuilder addRequestId(JsonElement requestId) { jsonObject.add(REQUEST_ID, requestId); return this; } public JsonMessageBuilder addElement(String name, JsonElement element) { jsonObject.add(name, element); return this; } public JsonMessageBuilder include(JsonObject other) { for (Map.Entry<String, JsonElement> entry : other.entrySet()) { jsonObject.add(entry.getKey(), entry.getValue()); } return this; } }
9236e0f0f9e29457a43c3f9148012d2c0b71fce3
789
java
Java
gtucscityplanning/src/main/java/com/gt/cscity/planning/ui/view/FullScreenVideoView.java
checkming/ArcGisMap
ef7dcfd8398c4f57b58406b8a77559063d26a635
[ "MIT" ]
null
null
null
gtucscityplanning/src/main/java/com/gt/cscity/planning/ui/view/FullScreenVideoView.java
checkming/ArcGisMap
ef7dcfd8398c4f57b58406b8a77559063d26a635
[ "MIT" ]
null
null
null
gtucscityplanning/src/main/java/com/gt/cscity/planning/ui/view/FullScreenVideoView.java
checkming/ArcGisMap
ef7dcfd8398c4f57b58406b8a77559063d26a635
[ "MIT" ]
null
null
null
27.206897
72
0.712294
997,856
package com.gt.cscity.planning.ui.view; import android.content.Context; import android.util.AttributeSet; import android.widget.VideoView; public class FullScreenVideoView extends VideoView { public FullScreenVideoView(Context context, AttributeSet attrs) { super(context, attrs); } /** * 设置宽高,以至于全屏播放 */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); //根据父类给我们提供的比例获取屏幕的宽高 int width = getDefaultSize(0, widthMeasureSpec); int height = getDefaultSize(0, heightMeasureSpec); System.out.println("***********************************************"); System.out.println("width:" + width); System.out.println("height:" + height); setMeasuredDimension(width, height); } }